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