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