This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perluniprops: display 2 synonyms as being discouraged
[perl5.git] / lib / utf8_heavy.pl
CommitLineData
a0ed51b3 1package utf8;
cf25bb62
JH
2use strict;
3use warnings;
a0ed51b3 4
15732964 5sub DEBUG () { 0 }
a0ed51b3
LW
6
7sub DESTROY {}
8
5beb625e
JH
9my %Cache;
10
86916d66
JH
11sub croak { require Carp; Carp::croak(@_) }
12
5beb625e 13##
3a2263fe
RGS
14## "SWASH" == "SWATCH HASH". A "swatch" is a swatch of the Unicode landscape.
15## It's a data structure that encodes a set of Unicode characters.
5beb625e
JH
16##
17
99870f4d
KW
18{
19 # If a floating point number is within this distance from the value of a
20 # fraction, it is considered to be that fraction, even if many more digits
21 # are specified that don't exactly match.
22 my $min_floating_slop;
23
3dd10fe8
KW
24 # To guard against this program calling something that in turn ends up
25 # calling this program with the same inputs, and hence infinitely
26 # recursing, we keep a stack of the properties that are currently in
27 # progress, pushed upon entry, popped upon return.
28 my @recursed;
29
99870f4d
KW
30 sub SWASHNEW {
31 my ($class, $type, $list, $minbits, $none) = @_;
32 local $^D = 0 if $^D;
33
3dd10fe8 34 $class = "" unless defined $class;
5bcf08c4
KW
35 print STDERR __LINE__, ": class=$class, type=$type, list=",
36 (defined $list) ? $list : ':undef:',
37 ", minbits=$minbits, none=$none\n" if DEBUG;
99870f4d
KW
38
39 ##
40 ## Get the list of codepoints for the type.
41 ## Called from swash_init (see utf8.c) or SWASHNEW itself.
42 ##
43 ## Callers of swash_init:
44 ## op.c:pmtrans -- for tr/// and y///
45 ## regexec.c:regclass_swash -- for /[]/, \p, and \P
46 ## utf8.c:is_utf8_common -- for common Unicode properties
47 ## utf8.c:to_utf8_case -- for lc, uc, ucfirst, etc. and //i
48 ##
49 ## Given a $type, our goal is to fill $list with the set of codepoint
50 ## ranges. If $type is false, $list passed is used.
51 ##
52 ## $minbits:
53 ## For binary properties, $minbits must be 1.
54 ## For character mappings (case and transliteration), $minbits must
55 ## be a number except 1.
56 ##
57 ## $list (or that filled according to $type):
58 ## Refer to perlunicode.pod, "User-Defined Character Properties."
59 ##
60 ## For binary properties, only characters with the property value
61 ## of True should be listed. The 3rd column, if any, will be ignored
62 ##
63 ## $none is undocumented, so I'm (khw) trying to do some documentation
64 ## of it now. It appears to be if there is a mapping in an input file
65 ## that maps to 'XXXX', then that is replaced by $none+1, expressed in
83fe8199 66 ## hexadecimal. It is used somehow in tr///.
99870f4d
KW
67 ##
68 ## To make the parsing of $type clear, this code takes the a rather
69 ## unorthodox approach of last'ing out of the block once we have the
70 ## info we need. Were this to be a subroutine, the 'last' would just
71 ## be a 'return'.
72 ##
fbe6f3cf
KW
73 # If a problem is found $type is returned;
74 # Upon success, a new (or cached) blessed object is returned with
75 # keys TYPE, BITS, EXTRAS, LIST, and NONE with values having the
76 # same meanings as the input parameters.
a6517ebf
KW
77 # SPECIALS contains a reference to any special-treatment hash in the
78 # INVERT_IT is non-zero if the result should be inverted before use
99870f4d
KW
79 my $file; ## file to load data from, and also part of the %Cache key.
80 my $ListSorted = 0;
81
82 # Change this to get a different set of Unicode tables
83 my $unicore_dir = 'unicore';
a6517ebf 84 my $invert_it = 0;
99870f4d
KW
85
86 if ($type)
cf25bb62 87 {
3dd10fe8
KW
88
89 # Verify that this isn't a recursive call for this property.
90 # Can't use croak, as it may try to recurse here itself.
91 my $class_type = $class . "::$type";
92 if (grep { $_ eq $class_type } @recursed) {
93 CORE::die "panic: Infinite recursion in SWASHNEW for '$type'\n";
94 }
95 push @recursed, $class_type;
96
99870f4d
KW
97 $type =~ s/^\s+//;
98 $type =~ s/\s+$//;
99
4ff124d1
KW
100 # regcomp.c surrounds the property name with '__" and '_i' if this
101 # is to be caseless matching.
102 my $caseless = $type =~ s/^__(.*)_i$/$1/;
103
104 print STDERR __LINE__, ": type=$type, caseless=$caseless\n" if DEBUG;
99870f4d
KW
105
106 GETFILE:
107 {
108 ##
a44f4b74
KW
109 ## It could be a user-defined property. Look in current
110 ## package if no package given
99870f4d
KW
111 ##
112
113 my $caller1 = $type =~ s/(.+)::// ? $1 : caller(1);
114
d658a8a8 115 if (defined $caller1 && $type =~ /^I[ns]\w+$/) {
99870f4d
KW
116 my $prop = "${caller1}::$type";
117 if (exists &{$prop}) {
0e9be77f
DM
118 # stolen from Scalar::Util::PP::tainted()
119 my $tainted;
120 {
121 local($@, $SIG{__DIE__}, $SIG{__WARN__});
122 local $^W = 0;
123 no warnings;
124 eval { kill 0 * $prop };
125 $tainted = 1 if $@ =~ /^Insecure/;
126 }
127 die "Insecure user-defined property \\p{$prop}\n"
128 if $tainted;
99870f4d 129 no strict 'refs';
4ff124d1 130 $list = &{$prop}($caseless);
99870f4d
KW
131 last GETFILE;
132 }
133 }
134
a44f4b74
KW
135 # During Perl's compilation, this routine may be called before
136 # the tables are constructed. If so, we have a chicken/egg
137 # problem. If we die, the tables never get constructed, so
138 # keep going, but return an empty table so only what the code
139 # has compiled in internally (currently ASCII/Latin1 range
140 # matching) will work.
1363cbd0
FC
141 BEGIN {
142 # Poor man's constant, to avoid a run-time check.
143 $utf8::{miniperl}
144 = \! defined &DynaLoader::boot_DynaLoader;
145 }
146 if (miniperl) {
a44f4b74
KW
147 eval "require '$unicore_dir/Heavy.pl'";
148 last GETFILE if $@;
149 }
150 else {
151 require "$unicore_dir/Heavy.pl";
152 }
1363cbd0 153 BEGIN { delete $utf8::{miniperl} }
99870f4d 154
4ff124d1 155 # All property names are matched caselessly
49801ec2 156 my $property_and_table = CORE::lc $type;
99870f4d
KW
157 print STDERR __LINE__, ": $property_and_table\n" if DEBUG;
158
159 # See if is of the compound form 'property=value', where the
160 # value indicates the table we should use.
161 my ($property, $table, @remainder) =
162 split /\s*[:=]\s*/, $property_and_table, -1;
3dd10fe8
KW
163 if (@remainder) {
164 pop @recursed if @recursed;
165 return $type;
166 }
99870f4d
KW
167
168 my $prefix;
169 if (! defined $table) {
170
171 # Here, is the single form. The property becomes empty, and
172 # the whole value is the table.
173 $table = $property;
174 $prefix = $property = "";
175 } else {
176 print STDERR __LINE__, ": $property\n" if DEBUG;
177
178 # Here it is the compound property=table form. The property
179 # name is always loosely matched, which means remove any of
180 # these:
181 $property =~ s/[_\s-]//g;
182
183 # And convert to canonical form. Quit if not valid.
184 $property = $utf8::loose_property_name_of{$property};
3dd10fe8
KW
185 if (! defined $property) {
186 pop @recursed if @recursed;
187 return $type;
188 }
99870f4d
KW
189
190 $prefix = "$property=";
191
192 # If the rhs looks like it is a number...
193 print STDERR __LINE__, ": table=$table\n" if DEBUG;
194 if ($table =~ qr{ ^ [ \s 0-9 _ + / . -]+ $ }x) {
195 print STDERR __LINE__, ": table=$table\n" if DEBUG;
196
197 # Don't allow leading nor trailing slashes
3dd10fe8
KW
198 if ($table =~ / ^ \/ | \/ $ /x) {
199 pop @recursed if @recursed;
200 return $type;
201 }
99870f4d
KW
202
203 # Split on slash, in case it is a rational, like \p{1/5}
204 my @parts = split qr{ \s* / \s* }x, $table, -1;
205 print __LINE__, ": $type\n" if @parts > 2 && DEBUG;
206
207 # Can have maximum of one slash
3dd10fe8
KW
208 if (@parts > 2) {
209 pop @recursed if @recursed;
210 return $type;
211 }
99870f4d
KW
212
213 foreach my $part (@parts) {
214 print __LINE__, ": part=$part\n" if DEBUG;
215
216 $part =~ s/^\+\s*//; # Remove leading plus
217 $part =~ s/^-\s*/-/; # Remove blanks after unary
218 # minus
219
220 # Remove underscores between digits.
221 $part =~ s/( ?<= [0-9] ) _ (?= [0-9] ) //xg;
222
223 # No leading zeros (but don't make a single '0'
224 # into a null string)
225 $part =~ s/ ^ ( -? ) 0+ /$1/x;
226 $part .= '0' if $part eq '-' || $part eq "";
227
228 # No trailing zeros after a decimal point
229 $part =~ s/ ( \. .*? ) 0+ $ /$1/x;
230
231 # Begin with a 0 if a leading decimal point
232 $part =~ s/ ^ ( -? ) \. /${1}0./x;
233
234 # Ensure not a trailing decimal point: turn into an
235 # integer
236 $part =~ s/ \. $ //x;
237
238 print STDERR __LINE__, ": part=$part\n" if DEBUG;
239 #return $type if $part eq "";
240
241 # Result better look like a number. (This test is
242 # needed because, for example could have a plus in
243 # the middle.)
3dd10fe8
KW
244 if ($part !~ / ^ -? [0-9]+ ( \. [0-9]+)? $ /x) {
245 pop @recursed if @recursed;
246 return $type;
247 }
99870f4d
KW
248 }
249
250 # If a rational...
251 if (@parts == 2) {
252
253 # If denominator is negative, get rid of it, and ...
254 if ($parts[1] =~ s/^-//) {
255
256 # If numerator is also negative, convert the
257 # whole thing to positive, or move the minus to
258 # the numerator
259 if ($parts[0] !~ s/^-//) {
260 $parts[0] = '-' . $parts[0];
261 }
262 }
263 $table = join '/', @parts;
264 }
265 elsif ($property ne 'nv' || $parts[0] !~ /\./) {
266
267 # Here is not numeric value, or doesn't have a
268 # decimal point. No further manipulation is
269 # necessary. (Note the hard-coded property name.
270 # This could fail if other properties eventually
271 # had fractions as well; perhaps the cjk ones
272 # could evolve to do that. This hard-coding could
273 # be fixed by mktables generating a list of
274 # properties that could have fractions.)
275 $table = $parts[0];
276 } else {
277
278 # Here is a floating point numeric_value. Try to
279 # convert to rational. First see if is in the list
280 # of known ones.
281 if (exists $utf8::nv_floating_to_rational{$parts[0]}) {
282 $table = $utf8::nv_floating_to_rational{$parts[0]};
283 } else {
284
285 # Here not in the list. See if is close
286 # enough to something in the list. First
287 # determine what 'close enough' means. It has
288 # to be as tight as what mktables says is the
289 # maximum slop, and as tight as how many
290 # digits we were passed. That is, if the user
291 # said .667, .6667, .66667, etc. we match as
292 # many digits as they passed until get to
293 # where it doesn't matter any more due to the
294 # machine's precision. If they said .6666668,
295 # we fail.
296 (my $fraction = $parts[0]) =~ s/^.*\.//;
297 my $epsilon = 10 ** - (length($fraction));
298 if ($epsilon > $utf8::max_floating_slop) {
299 $epsilon = $utf8::max_floating_slop;
300 }
301
302 # But it can't be tighter than the minimum
303 # precision for this machine. If haven't
304 # already calculated that minimum, do so now.
305 if (! defined $min_floating_slop) {
306
307 # Keep going down an order of magnitude
308 # until find that adding this quantity to
309 # 1 remains 1; but put an upper limit on
310 # this so in case this algorithm doesn't
311 # work properly on some platform, that we
312 # won't loop forever.
313 my $count = 0;
314 $min_floating_slop = 1;
315 while (1+ $min_floating_slop != 1
316 && $count++ < 50)
317 {
318 my $next = $min_floating_slop / 10;
319 last if $next == 0; # If underflows,
320 # use previous one
321 $min_floating_slop = $next;
322 print STDERR __LINE__, ": min_float_slop=$min_floating_slop\n" if DEBUG;
323 }
324
325 # Back off a couple orders of magnitude,
326 # just to be safe.
327 $min_floating_slop *= 100;
328 }
329
330 if ($epsilon < $min_floating_slop) {
331 $epsilon = $min_floating_slop;
332 }
333 print STDERR __LINE__, ": fraction=.$fraction; epsilon=$epsilon\n" if DEBUG;
334
335 undef $table;
336
337 # And for each possible rational in the table,
338 # see if it is within epsilon of the input.
339 foreach my $official
340 (keys %utf8::nv_floating_to_rational)
341 {
342 print STDERR __LINE__, ": epsilon=$epsilon, official=$official, diff=", abs($parts[0] - $official), "\n" if DEBUG;
343 if (abs($parts[0] - $official) < $epsilon) {
344 $table =
345 $utf8::nv_floating_to_rational{$official};
346 last;
347 }
348 }
349
350 # Quit if didn't find one.
3dd10fe8
KW
351 if (! defined $table) {
352 pop @recursed if @recursed;
353 return $type;
354 }
99870f4d
KW
355 }
356 }
357 print STDERR __LINE__, ": $property=$table\n" if DEBUG;
358 }
359 }
360
361 # Combine lhs (if any) and rhs to get something that matches
362 # the syntax of the lookups.
363 $property_and_table = "$prefix$table";
364 print STDERR __LINE__, ": $property_and_table\n" if DEBUG;
365
366 # First try stricter matching.
367 $file = $utf8::stricter_to_file_of{$property_and_table};
368
369 # If didn't find it, try again with looser matching by editing
370 # out the applicable characters on the rhs and looking up
371 # again.
372 if (! defined $file) {
373 $table =~ s/ [_\s-] //xg;
374 $property_and_table = "$prefix$table";
375 print STDERR __LINE__, ": $property_and_table\n" if DEBUG;
376 $file = $utf8::loose_to_file_of{$property_and_table};
377 }
378
379 # Add the constant and go fetch it in.
380 if (defined $file) {
a6517ebf
KW
381
382 # A beginning ! means to invert
383 $invert_it = $file =~ s/^!//;
384
99870f4d
KW
385 if ($utf8::why_deprecated{$file}) {
386 warnings::warnif('deprecated', "Use of '$type' in \\p{} or \\P{} is deprecated because: $utf8::why_deprecated{$file};");
387 }
4ff124d1
KW
388
389 if ($caseless
390 && exists $utf8::caseless_equivalent{$property_and_table})
391 {
392 $file = $utf8::caseless_equivalent{$property_and_table};
393 }
99870f4d
KW
394 $file= "$unicore_dir/lib/$file.pl";
395 last GETFILE;
396 }
397 print STDERR __LINE__, ": didn't find $property_and_table\n" if DEBUG;
398
399 ##
99870f4d
KW
400 ## Last attempt -- see if it's a standard "To" name
401 ## (e.g. "ToLower") ToTitle is used by ucfirst().
402 ## The user-level way to access ToDigit() and ToFold()
403 ## is to use Unicode::UCD.
404 ##
405 if ($type =~ /^To(Digit|Fold|Lower|Title|Upper)$/) {
08432a98
KW
406
407 # Fail if wanting a binary property, as these aren't.
408 if ($minbits == 1) {
409 pop @recursed if @recursed;
410 return $type;
411 }
99870f4d
KW
412 $file = "$unicore_dir/To/$1.pl";
413 ## would like to test to see if $file actually exists....
414 last GETFILE;
415 }
416
417 ##
418 ## If we reach this line, it's because we couldn't figure
419 ## out what to do with $type. Ouch.
420 ##
421
3dd10fe8 422 pop @recursed if @recursed;
99870f4d 423 return $type;
cf25bb62
JH
424 }
425
99870f4d
KW
426 if (defined $file) {
427 print STDERR __LINE__, ": found it (file='$file')\n" if DEBUG;
428
429 ##
430 ## If we reach here, it was due to a 'last GETFILE' above
431 ## (exception: user-defined properties and mappings), so we
432 ## have a filename, so now we load it if we haven't already.
433 ## If we have, return the cached results. The cache key is the
434 ## class and file to load.
435 ##
436 my $found = $Cache{$class, $file};
437 if ($found and ref($found) eq $class) {
a6517ebf 438 print STDERR __LINE__, ": Returning cached '$file' for \\p{$type}; invert_it=$invert_it\n" if DEBUG;
3dd10fe8 439 pop @recursed if @recursed;
a6517ebf 440 $found->{'INVERT_IT'} = $invert_it;
99870f4d
KW
441 return $found;
442 }
443
444 local $@;
445 local $!;
446 $list = do $file; die $@ if $@;
0a0ffbce 447 }
cf25bb62 448
99870f4d 449 $ListSorted = 1; ## we know that these lists are sorted
cf25bb62
JH
450 }
451
99870f4d
KW
452 my $extras;
453 my $bits = $minbits;
454
99870f4d 455 if ($list) {
0e9be77f 456 my $taint = substr($list,0,0); # maintain taint
99870f4d
KW
457 my @tmp = split(/^/m, $list);
458 my %seen;
459 no warnings;
0e9be77f
DM
460 $extras = join '', $taint, grep /^[^0-9a-fA-F]/, @tmp;
461 $list = join '', $taint,
99870f4d
KW
462 map { $_->[1] }
463 sort { $a->[0] <=> $b->[0] }
464 map { /^([0-9a-fA-F]+)/; [ CORE::hex($1), $_ ] }
465 grep { /^([0-9a-fA-F]+)/ and not $seen{$1}++ } @tmp; # XXX doesn't do ranges right
466 }
a0ed51b3 467
99870f4d
KW
468 if ($none) {
469 my $hextra = sprintf "%04x", $none + 1;
470 $list =~ s/\tXXXX$/\t$hextra/mg;
471 }
a0ed51b3 472
99870f4d
KW
473 if ($minbits != 1 && $minbits < 32) { # not binary property
474 my $top = 0;
475 while ($list =~ /^([0-9a-fA-F]+)(?:[\t]([0-9a-fA-F]+)?)(?:[ \t]([0-9a-fA-F]+))?/mg) {
476 my $min = CORE::hex $1;
477 my $max = defined $2 ? CORE::hex $2 : $min;
478 my $val = defined $3 ? CORE::hex $3 : 0;
479 $val += $max - $min if defined $3;
480 $top = $val if $val > $top;
481 }
482 my $topbits =
483 $top > 0xffff ? 32 :
484 $top > 0xff ? 16 : 8;
485 $bits = $topbits if $bits < $topbits;
486 }
a0ed51b3 487
99870f4d
KW
488 my @extras;
489 if ($extras) {
490 for my $x ($extras) {
0e9be77f 491 my $taint = substr($x,0,0); # maintain taint
99870f4d
KW
492 pos $x = 0;
493 while ($x =~ /^([^0-9a-fA-F\n])(.*)/mg) {
0e9be77f
DM
494 my $char = "$1$taint";
495 my $name = "$2$taint";
496 print STDERR __LINE__, ": char [$char] => name [$name]\n"
497 if DEBUG;
99870f4d
KW
498 if ($char =~ /[-+!&]/) {
499 my ($c,$t) = split(/::/, $name, 2); # bogus use of ::, really
500 my $subobj;
501 if ($c eq 'utf8') {
502 $subobj = utf8->SWASHNEW($t, "", $minbits, 0);
503 }
504 elsif (exists &$name) {
505 $subobj = utf8->SWASHNEW($name, "", $minbits, 0);
506 }
507 elsif ($c =~ /^([0-9a-fA-F]+)/) {
508 $subobj = utf8->SWASHNEW("", $c, $minbits, 0);
509 }
3dd10fe8
KW
510 if (! ref $subobj) {
511 pop @recursed if @recursed && $type;
512 return $subobj;
513 }
99870f4d
KW
514 push @extras, $name => $subobj;
515 $bits = $subobj->{BITS} if $bits < $subobj->{BITS};
516 }
517 }
518 }
519 }
a0ed51b3 520
99870f4d 521 if (DEBUG) {
a6517ebf 522 print STDERR __LINE__, ": CLASS = $class, TYPE => $type, BITS => $bits, NONE => $none, INVERT_IT => $invert_it";
99870f4d
KW
523 print STDERR "\nLIST =>\n$list" if defined $list;
524 print STDERR "\nEXTRAS =>\n$extras" if defined $extras;
525 print STDERR "\n";
526 }
a0ed51b3 527
99870f4d
KW
528 my $SWASH = bless {
529 TYPE => $type,
530 BITS => $bits,
531 EXTRAS => $extras,
532 LIST => $list,
533 NONE => $none,
534 @extras,
535 } => $class;
536
537 if ($file) {
538 $Cache{$class, $file} = $SWASH;
64870e05
KW
539 if ($type
540 && exists $utf8::SwashInfo{$type}
541 && exists $utf8::SwashInfo{$type}{'specials_name'})
542 {
543 my $specials_name = $utf8::SwashInfo{$type}{'specials_name'};
544 no strict "refs";
545 print STDERR "\nspecials_name => $SWASH->{'SPECIALS'}\n" if DEBUG;
546 $SWASH->{'SPECIALS'} = \%$specials_name;
547 }
a6517ebf 548 $SWASH->{'INVERT_IT'} = $invert_it;
99870f4d 549 }
5beb625e 550
3dd10fe8
KW
551 pop @recursed if @recursed && $type;
552
99870f4d 553 return $SWASH;
5beb625e 554 }
a0ed51b3
LW
555}
556
979f2922 557# Now SWASHGET is recasted into a C function S_swash_get (see utf8.c).
a0ed51b3
LW
558
5591;