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