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