This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
(perl #132158) abort compilation if we see an error compiling a form
[perl5.git] / lib / utf8_heavy.pl
1 package utf8;
2 use strict;
3 use warnings;
4 use re "/aa";  # So we won't even try to look at above Latin1, potentially
5                # resulting in a recursive call
6
7 sub DEBUG () { 0 }
8 $|=1 if DEBUG;
9
10 sub DESTROY {}
11
12 my %Cache;
13
14 sub croak { require Carp; Carp::croak(@_) }
15
16 # Digits may be separated by a single underscore
17 my $digits = qr/ ( [0-9] _? )+ (?!:_) /x;
18
19 # A sign can be surrounded by white space
20 my $sign = qr/ \s* [+-]? \s* /x;
21
22 my $f_float = qr/  $sign $digits+ \. $digits*    # e.g., 5.0, 5.
23                  | $sign $digits* \. $digits+/x; # 0.7, .7
24
25 # A number may be an integer, a rational, or a float with an optional exponent
26 # We (shudder) accept a signed denominator
27 my $number = qr{  ^ $sign $digits+ $
28                 | ^ $sign $digits+ \/ $sign $digits+ $
29                 | ^ $f_float (?: [Ee] [+-]? $digits )? $}x;
30
31 sub _loose_name ($) {
32     # Given a lowercase property or property-value name, return its
33     # standardized version that is expected for look-up in the 'loose' hashes
34     # in Heavy.pl (hence, this depends on what mktables does).  This squeezes
35     # out blanks, underscores and dashes.  The complication stems from the
36     # grandfathered-in 'L_', which retains a single trailing underscore.
37
38     (my $loose = $_[0]) =~ s/[-_ \t]//g;
39
40     return $loose if $loose !~ / ^ (?: is | to )? l $/x;
41     return 'l_' if $_[0] =~ / l .* _ /x;    # If original had a trailing '_'
42     return $loose;
43 }
44
45 ##
46 ## "SWASH" == "SWATCH HASH". A "swatch" is a swatch of the Unicode landscape.
47 ## It's a data structure that encodes a set of Unicode characters.
48 ##
49
50 {
51     # If a floating point number is within this distance from the value of a
52     # fraction, it is considered to be that fraction, even if many more digits
53     # are specified that don't exactly match.
54     my $min_floating_slop;
55
56     # To guard against this program calling something that in turn ends up
57     # calling this program with the same inputs, and hence infinitely
58     # recursing, we keep a stack of the properties that are currently in
59     # progress, pushed upon entry, popped upon return.
60     my @recursed;
61
62     sub SWASHNEW {
63         my ($class, $type, $list, $minbits, $none) = @_;
64         my $user_defined = 0;
65         local $^D = 0 if $^D;
66
67         $class = "" unless defined $class;
68         print STDERR __LINE__, ": class=$class, type=$type, list=",
69                                 (defined $list) ? $list : ':undef:',
70                                 ", minbits=$minbits, none=$none\n" if DEBUG;
71
72         ##
73         ## Get the list of codepoints for the type.
74         ## Called from swash_init (see utf8.c) or SWASHNEW itself.
75         ##
76         ## Callers of swash_init:
77         ##     op.c:pmtrans             -- for tr/// and y///
78         ##     regexec.c:regclass_swash -- for /[]/, \p, and \P
79         ##     utf8.c:is_utf8_common    -- for common Unicode properties
80         ##     utf8.c:S__to_utf8_case   -- for lc, uc, ucfirst, etc. and //i
81         ##     Unicode::UCD::prop_invlist
82         ##     Unicode::UCD::prop_invmap
83         ##
84         ## Given a $type, our goal is to fill $list with the set of codepoint
85         ## ranges. If $type is false, $list passed is used.
86         ##
87         ## $minbits:
88         ##     For binary properties, $minbits must be 1.
89         ##     For character mappings (case and transliteration), $minbits must
90         ##     be a number except 1.
91         ##
92         ## $list (or that filled according to $type):
93         ##     Refer to perlunicode.pod, "User-Defined Character Properties."
94         ##     
95         ##     For binary properties, only characters with the property value
96         ##     of True should be listed. The 3rd column, if any, will be ignored
97         ##
98         ## $none is undocumented, so I'm (khw) trying to do some documentation
99         ## of it now.  It appears to be if there is a mapping in an input file
100         ## that maps to 'XXXX', then that is replaced by $none+1, expressed in
101         ## hexadecimal.  It is used somehow in tr///.
102         ##
103         ## To make the parsing of $type clear, this code takes the a rather
104         ## unorthodox approach of last'ing out of the block once we have the
105         ## info we need. Were this to be a subroutine, the 'last' would just
106         ## be a 'return'.
107         ##
108         #   If a problem is found $type is returned;
109         #   Upon success, a new (or cached) blessed object is returned with
110         #   keys TYPE, BITS, EXTRAS, LIST, and NONE with values having the
111         #   same meanings as the input parameters.
112         #   SPECIALS contains a reference to any special-treatment hash in the
113         #       property.
114         #   INVERT_IT is non-zero if the result should be inverted before use
115         #   USER_DEFINED is non-zero if the result came from a user-defined
116         my $file; ## file to load data from, and also part of the %Cache key.
117
118         # Change this to get a different set of Unicode tables
119         my $unicore_dir = 'unicore';
120         my $invert_it = 0;
121         my $list_is_from_mktables = 0;  # Is $list returned from a mktables
122                                         # generated file?  If so, we know it's
123                                         # well behaved.
124
125         if ($type)
126         {
127             # Verify that this isn't a recursive call for this property.
128             # Can't use croak, as it may try to recurse to here itself.
129             my $class_type = $class . "::$type";
130             if (grep { $_ eq $class_type } @recursed) {
131                 CORE::die "panic: Infinite recursion in SWASHNEW for '$type'\n";
132             }
133             push @recursed, $class_type;
134
135             $type =~ s/^\s+//;
136             $type =~ s/\s+$//;
137
138             # regcomp.c surrounds the property name with '__" and '_i' if this
139             # is to be caseless matching.
140             my $caseless = $type =~ s/^(.*)__(.*)_i$/$1$2/;
141
142             print STDERR __LINE__, ": type=$type, caseless=$caseless\n" if DEBUG;
143
144         GETFILE:
145             {
146                 ##
147                 ## It could be a user-defined property.  Look in current
148                 ## package if no package given
149                 ##
150
151
152                 my $caller0 = caller(0);
153                 my $caller1 = $type =~ s/(.+):://
154                               ? $1
155                               : $caller0 eq 'main'
156                                 ? 'main'
157                                 : caller(1);
158
159                 if (defined $caller1 && $type =~ /^I[ns]\w+$/) {
160                     my $prop = "${caller1}::$type";
161                     if (exists &{$prop}) {
162                         # stolen from Scalar::Util::PP::tainted()
163                         my $tainted;
164                         {
165                             local($@, $SIG{__DIE__}, $SIG{__WARN__});
166                             local $^W = 0;
167                             no warnings;
168                             eval { kill 0 * $prop };
169                             $tainted = 1 if $@ =~ /^Insecure/;
170                         }
171                         die "Insecure user-defined property \\p{$prop}\n"
172                             if $tainted;
173                         no strict 'refs';
174                         $list = &{$prop}($caseless);
175                         $user_defined = 1;
176                         last GETFILE;
177                     }
178                 }
179
180                 # During Perl's compilation, this routine may be called before
181                 # the tables are constructed.  If so, we have a chicken/egg
182                 # problem.  If we die, the tables never get constructed, so
183                 # keep going, but return an empty table so only what the code
184                 # has compiled in internally (currently ASCII/Latin1 range
185                 # matching) will work.
186                 BEGIN {
187                     # Poor man's constant, to avoid a run-time check.
188                     $utf8::{miniperl}
189                         = \! defined &DynaLoader::boot_DynaLoader;
190                 }
191                 if (miniperl) {
192                     eval "require '$unicore_dir/Heavy.pl'";
193                     if ($@) {
194                         print STDERR __LINE__, ": '$@'\n" if DEBUG;
195                         pop @recursed if @recursed;
196                         return $type;
197                     }
198                 }
199                 else {
200                     require "$unicore_dir/Heavy.pl";
201                 }
202                 BEGIN { delete $utf8::{miniperl} }
203
204                 # All property names are matched caselessly
205                 my $property_and_table = CORE::lc $type;
206                 print STDERR __LINE__, ": $property_and_table\n" if DEBUG;
207
208                 # See if is of the compound form 'property=value', where the
209                 # value indicates the table we should use.
210                 my ($property, $table, @remainder) =
211                                     split /\s*[:=]\s*/, $property_and_table, -1;
212                 if (@remainder) {
213                     pop @recursed if @recursed;
214                     return $type;
215                 }
216
217                 my $prefix;
218                 if (! defined $table) {
219                         
220                     # Here, is the single form.  The property becomes empty, and
221                     # the whole value is the table.
222                     $table = $property;
223                     $prefix = $property = "";
224                 } else {
225                     print STDERR __LINE__, ": $property\n" if DEBUG;
226
227                     # Here it is the compound property=table form.  The property
228                     # name is always loosely matched, and always can have an
229                     # optional 'is' prefix (which isn't true in the single
230                     # form).
231                     $property = _loose_name($property) =~ s/^is//r;
232
233                     # And convert to canonical form.  Quit if not valid.
234                     $property = $utf8::loose_property_name_of{$property};
235                     if (! defined $property) {
236                         pop @recursed if @recursed;
237                         return $type;
238                     }
239
240                     $prefix = "$property=";
241
242                     # If the rhs looks like it is a number...
243                     print STDERR __LINE__, ": table=$table\n" if DEBUG;
244
245                     if ($table =~ $number) {
246                         print STDERR __LINE__, ": table=$table\n" if DEBUG;
247
248                         # Split on slash, in case it is a rational, like \p{1/5}
249                         my @parts = split m{ \s* / \s* }x, $table, -1;
250                         print __LINE__, ": $type\n" if @parts > 2 && DEBUG;
251
252                         foreach my $part (@parts) {
253                             print __LINE__, ": part=$part\n" if DEBUG;
254
255                             $part =~ s/^\+\s*//;    # Remove leading plus
256                             $part =~ s/^-\s*/-/;    # Remove blanks after unary
257                                                     # minus
258
259                             # Remove underscores between digits.
260                             $part =~ s/(?<= [0-9] ) _ (?= [0-9] ) //xg;
261
262                             # No leading zeros (but don't make a single '0'
263                             # into a null string)
264                             $part =~ s/ ^ ( -? ) 0+ /$1/x;
265                             $part .= '0' if $part eq '-' || $part eq "";
266
267                             # No trailing zeros after a decimal point
268                             $part =~ s/ ( \. [0-9]*? ) 0+ $ /$1/x;
269
270                             # Begin with a 0 if a leading decimal point
271                             $part =~ s/ ^ ( -? ) \. /${1}0./x;
272
273                             # Ensure not a trailing decimal point: turn into an
274                             # integer
275                             $part =~ s/ \. $ //x;
276
277                             print STDERR __LINE__, ": part=$part\n" if DEBUG;
278                             #return $type if $part eq "";
279                         }
280
281                         #  If a rational...
282                         if (@parts == 2) {
283
284                             # If denominator is negative, get rid of it, and ...
285                             if ($parts[1] =~ s/^-//) {
286
287                                 # If numerator is also negative, convert the
288                                 # whole thing to positive, else move the minus
289                                 # to the numerator
290                                 if ($parts[0] !~ s/^-//) {
291                                     $parts[0] = '-' . $parts[0];
292                                 }
293                             }
294                             $table = join '/', @parts;
295                         }
296                         elsif ($property ne 'nv' || $parts[0] !~ /\./) {
297
298                             # Here is not numeric value, or doesn't have a
299                             # decimal point.  No further manipulation is
300                             # necessary.  (Note the hard-coded property name.
301                             # This could fail if other properties eventually
302                             # had fractions as well; perhaps the cjk ones
303                             # could evolve to do that.  This hard-coding could
304                             # be fixed by mktables generating a list of
305                             # properties that could have fractions.)
306                             $table = $parts[0];
307                         } else {
308
309                             # Here is a floating point numeric_value.  Convert
310                             # to rational.  Get a normalized form, like
311                             # 5.00E-01, and look that up in the hash
312
313                             my $float = sprintf "%.*e",
314                                                 $utf8::e_precision,
315                                                 0 + $parts[0];
316
317                             if (exists $utf8::nv_floating_to_rational{$float}) {
318                                 $table = $utf8::nv_floating_to_rational{$float};
319                             } else {
320                                 pop @recursed if @recursed;
321                                 return $type;
322                             }
323                         }
324                         print STDERR __LINE__, ": $property=$table\n" if DEBUG;
325                     }
326                 }
327
328                 # Combine lhs (if any) and rhs to get something that matches
329                 # the syntax of the lookups.
330                 $property_and_table = "$prefix$table";
331                 print STDERR __LINE__, ": $property_and_table\n" if DEBUG;
332
333                 # First try stricter matching.
334                 $file = $utf8::stricter_to_file_of{$property_and_table};
335
336                 # If didn't find it, try again with looser matching by editing
337                 # out the applicable characters on the rhs and looking up
338                 # again.
339                 my $strict_property_and_table;
340                 if (! defined $file) {
341
342                     # This isn't used unless the name begins with 'to'
343                     $strict_property_and_table = $property_and_table =~  s/^to//r;
344                     $table = _loose_name($table);
345                     $property_and_table = "$prefix$table";
346                     print STDERR __LINE__, ": $property_and_table\n" if DEBUG;
347                     $file = $utf8::loose_to_file_of{$property_and_table};
348                 }
349
350                 # Add the constant and go fetch it in.
351                 if (defined $file) {
352
353                     # If the file name contains a !, it means to invert.  The
354                     # 0+ makes sure result is numeric
355                     $invert_it = 0 + $file =~ s/!//;
356
357                     if ($utf8::why_deprecated{$file}) {
358                         warnings::warnif('deprecated', "Use of '$type' in \\p{} or \\P{} is deprecated because: $utf8::why_deprecated{$file};");
359                     }
360
361                     if ($caseless
362                         && exists $utf8::caseless_equivalent{$property_and_table})
363                     {
364                         $file = $utf8::caseless_equivalent{$property_and_table};
365                     }
366
367                     # The pseudo-directory '#' means that there really isn't a
368                     # file to read, the data is in-line as part of the string;
369                     # we extract it below.
370                     $file = "$unicore_dir/lib/$file.pl" unless $file =~ m!^#/!;
371                     last GETFILE;
372                 }
373                 print STDERR __LINE__, ": didn't find $property_and_table\n" if DEBUG;
374
375                 ##
376                 ## Last attempt -- see if it's a standard "To" name
377                 ## (e.g. "ToLower")  ToTitle is used by ucfirst().
378                 ## The user-level way to access ToDigit() and ToFold()
379                 ## is to use Unicode::UCD.
380                 ##
381                 # Only check if caller wants non-binary
382                 if ($minbits != 1) {
383                     if ($property_and_table =~ s/^to//) {
384                     # Look input up in list of properties for which we have
385                     # mapping files.  First do it with the strict approach
386                         if (defined ($file = $utf8::strict_property_to_file_of{
387                                                     $strict_property_and_table}))
388                         {
389                             $type = $utf8::file_to_swash_name{$file};
390                             print STDERR __LINE__, ": type set to $type\n"
391                                                                         if DEBUG;
392                             $file = "$unicore_dir/$file.pl";
393                             last GETFILE;
394                         }
395                         elsif (defined ($file =
396                           $utf8::loose_property_to_file_of{$property_and_table}))
397                         {
398                             $type = $utf8::file_to_swash_name{$file};
399                             print STDERR __LINE__, ": type set to $type\n"
400                                                                         if DEBUG;
401                             $file = "$unicore_dir/$file.pl";
402                             last GETFILE;
403                         }   # If that fails see if there is a corresponding binary
404                             # property file
405                         elsif (defined ($file =
406                                     $utf8::loose_to_file_of{$property_and_table}))
407                         {
408
409                             # Here, there is no map file for the property we
410                             # are trying to get the map of, but this is a
411                             # binary property, and there is a file for it that
412                             # can easily be translated to a mapping, so use
413                             # that, treating this as a binary property.
414                             # Setting 'minbits' here causes it to be stored as
415                             # such in the cache, so if someone comes along
416                             # later looking for just a binary, they get it.
417                             $minbits = 1;
418
419                             # The 0+ makes sure is numeric
420                             $invert_it = 0 + $file =~ s/!//;
421                             $file = "$unicore_dir/lib/$file.pl"
422                                                          unless $file =~ m!^#/!;
423                             last GETFILE;
424                         }
425                     }
426                 }
427
428                 ##
429                 ## If we reach this line, it's because we couldn't figure
430                 ## out what to do with $type. Ouch.
431                 ##
432
433                 pop @recursed if @recursed;
434                 return $type;
435             } # end of GETFILE block
436
437             if (defined $file) {
438                 print STDERR __LINE__, ": found it (file='$file')\n" if DEBUG;
439
440                 ##
441                 ## If we reach here, it was due to a 'last GETFILE' above
442                 ## (exception: user-defined properties and mappings), so we
443                 ## have a filename, so now we load it if we haven't already.
444
445                 # The pseudo-directory '#' means the result isn't really a
446                 # file, but is in-line, with semi-colons to be turned into
447                 # new-lines.  Since it is in-line there is no advantage to
448                 # caching the result
449                 if ($file =~ s!^#/!!) {
450                     $list = $utf8::inline_definitions[$file];
451                 }
452                 else {
453                     # Here, we have an actual file to read in and load, but it
454                     # may already have been read-in and cached.  The cache key
455                     # is the class and file to load, and whether the results
456                     # need to be inverted.
457                     my $found = $Cache{$class, $file, $invert_it};
458                     if ($found and ref($found) eq $class) {
459                         print STDERR __LINE__, ": Returning cached swash for '$class,$file,$invert_it' for \\p{$type}\n" if DEBUG;
460                         pop @recursed if @recursed;
461                         return $found;
462                     }
463
464                     local $@;
465                     local $!;
466                     $list = do $file; die $@ if $@;
467                 }
468
469                 $list_is_from_mktables = 1;
470             }
471         } # End of $type is non-null
472
473         # Here, either $type was null, or we found the requested property and
474         # read it into $list
475
476         my $extras = "";
477
478         my $bits = $minbits;
479
480         # mktables lists don't have extras, like '&utf8::prop', so don't need
481         # to separate them; also lists are already sorted, so don't need to do
482         # that.
483         if ($list && ! $list_is_from_mktables) {
484             my $taint = substr($list,0,0); # maintain taint
485
486             # Separate the extras from the code point list, and make sure
487             # user-defined properties and tr/// are well-behaved for
488             # downstream code.
489             if ($user_defined || $none) {
490                 my @tmp = split(/^/m, $list);
491                 my %seen;
492                 no warnings;
493
494                 # The extras are anything that doesn't begin with a hex digit.
495                 $extras = join '', $taint, grep /^[^0-9a-fA-F]/, @tmp;
496
497                 # Remove the extras, and sort the remaining entries by the
498                 # numeric value of their beginning hex digits, removing any
499                 # duplicates.
500                 $list = join '', $taint,
501                         map  { $_->[1] }
502                         sort { $a->[0] <=> $b->[0] }
503                         map  { /^([0-9a-fA-F]+)/ && !$seen{$1}++ ? [ CORE::hex($1), $_ ] : () }
504                         @tmp; # XXX doesn't do ranges right
505             }
506             else {
507                 # mktables has gone to some trouble to make non-user defined
508                 # properties well-behaved, so we can skip the effort we do for
509                 # user-defined ones.  Any extras are at the very beginning of
510                 # the string.
511
512                 # This regex splits out the first lines of $list into $1 and
513                 # strips them off from $list, until we get one that begins
514                 # with a hex number, alone on the line, or followed by a tab.
515                 # Either portion may be empty.
516                 $list =~ s/ \A ( .*? )
517                             (?: \z | (?= ^ [0-9a-fA-F]+ (?: \t | $) ) )
518                           //msx;
519
520                 $extras = "$taint$1";
521             }
522         }
523
524         if ($none) {
525             my $hextra = sprintf "%04x", $none + 1;
526             $list =~ s/\tXXXX$/\t$hextra/mg;
527         }
528
529         if ($minbits != 1 && $minbits < 32) { # not binary property
530             my $top = 0;
531             while ($list =~ /^([0-9a-fA-F]+)(?:[\t]([0-9a-fA-F]+)?)(?:[ \t]([0-9a-fA-F]+))?/mg) {
532                 my $min = CORE::hex $1;
533                 my $max = defined $2 ? CORE::hex $2 : $min;
534                 my $val = defined $3 ? CORE::hex $3 : 0;
535                 $val += $max - $min if defined $3;
536                 $top = $val if $val > $top;
537             }
538             my $topbits =
539                 $top > 0xffff ? 32 :
540                 $top > 0xff ? 16 : 8;
541             $bits = $topbits if $bits < $topbits;
542         }
543
544         my @extras;
545         if ($extras) {
546             for my $x ($extras) {
547                 my $taint = substr($x,0,0); # maintain taint
548                 pos $x = 0;
549                 while ($x =~ /^([^0-9a-fA-F\n])(.*)/mg) {
550                     my $char = "$1$taint";
551                     my $name = "$2$taint";
552                     print STDERR __LINE__, ": char [$char] => name [$name]\n"
553                         if DEBUG;
554                     if ($char =~ /[-+!&]/) {
555                         my ($c,$t) = split(/::/, $name, 2);     # bogus use of ::, really
556                         my $subobj;
557                         if ($c eq 'utf8') {
558                             $subobj = utf8->SWASHNEW($t, "", $minbits, 0);
559                         }
560                         elsif (exists &$name) {
561                             $subobj = utf8->SWASHNEW($name, "", $minbits, 0);
562                         }
563                         elsif ($c =~ /^([0-9a-fA-F]+)/) {
564                             $subobj = utf8->SWASHNEW("", $c, $minbits, 0);
565                         }
566                         print STDERR __LINE__, ": returned from getting sub object for $name\n" if DEBUG;
567                         if (! ref $subobj) {
568                             pop @recursed if @recursed && $type;
569                             return $subobj;
570                         }
571                         push @extras, $name => $subobj;
572                         $bits = $subobj->{BITS} if $bits < $subobj->{BITS};
573                         $user_defined = $subobj->{USER_DEFINED}
574                                               if $subobj->{USER_DEFINED};
575                     }
576                 }
577             }
578         }
579
580         if (DEBUG) {
581             print STDERR __LINE__, ": CLASS = $class, TYPE => $type, BITS => $bits, NONE => $none, INVERT_IT => $invert_it, USER_DEFINED => $user_defined";
582             print STDERR "\nLIST =>\n$list" if defined $list;
583             print STDERR "\nEXTRAS =>\n$extras" if defined $extras;
584             print STDERR "\n";
585         }
586
587         my $SWASH = bless {
588             TYPE => $type,
589             BITS => $bits,
590             EXTRAS => $extras,
591             LIST => $list,
592             NONE => $none,
593             USER_DEFINED => $user_defined,
594             @extras,
595         } => $class;
596
597         if ($file) {
598             $Cache{$class, $file, $invert_it} = $SWASH;
599             if ($type
600                 && exists $utf8::SwashInfo{$type}
601                 && exists $utf8::SwashInfo{$type}{'specials_name'})
602             {
603                 my $specials_name = $utf8::SwashInfo{$type}{'specials_name'};
604                 no strict "refs";
605                 print STDERR "\nspecials_name => $specials_name\n" if DEBUG;
606                 $SWASH->{'SPECIALS'} = \%$specials_name;
607             }
608             $SWASH->{'INVERT_IT'} = $invert_it;
609         }
610
611         pop @recursed if @recursed && $type;
612
613         return $SWASH;
614     }
615 }
616
617 # Now SWASHGET is recasted into a C function S_swatch_get (see utf8.c).
618
619 1;