This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Avoid loading modules for %! and %+ on meeting %{"foo::!"} and %{"foo::+"}
[perl5.git] / lib / utf8_heavy.pl
CommitLineData
a0ed51b3 1package utf8;
cf25bb62
JH
2use strict;
3use warnings;
a0ed51b3 4
15732964 5sub DEBUG () { 0 }
a0ed51b3
LW
6
7sub DESTROY {}
8
5beb625e
JH
9my %Cache;
10
86916d66
JH
11sub croak { require Carp; Carp::croak(@_) }
12
5beb625e 13##
3a2263fe
RGS
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.
5beb625e
JH
16##
17
99870f4d
KW
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
3dd10fe8
KW
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
99870f4d
KW
30 sub SWASHNEW {
31 my ($class, $type, $list, $minbits, $none) = @_;
32 local $^D = 0 if $^D;
33
3dd10fe8 34 $class = "" unless defined $class;
5bcf08c4
KW
35 print STDERR __LINE__, ": class=$class, type=$type, list=",
36 (defined $list) ? $list : ':undef:',
37 ", minbits=$minbits, none=$none\n" if DEBUG;
99870f4d
KW
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)
cf25bb62 81 {
3dd10fe8
KW
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
99870f4d
KW
91 $type =~ s/^\s+//;
92 $type =~ s/\s+$//;
93
4ff124d1
KW
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;
99870f4d
KW
99
100 GETFILE:
101 {
102 ##
a44f4b74
KW
103 ## It could be a user-defined property. Look in current
104 ## package if no package given
99870f4d
KW
105 ##
106
107 my $caller1 = $type =~ s/(.+)::// ? $1 : caller(1);
108
d658a8a8 109 if (defined $caller1 && $type =~ /^I[ns]\w+$/) {
99870f4d
KW
110 my $prop = "${caller1}::$type";
111 if (exists &{$prop}) {
112 no strict 'refs';
113
4ff124d1 114 $list = &{$prop}($caseless);
99870f4d
KW
115 last GETFILE;
116 }
117 }
118
a44f4b74
KW
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.
1363cbd0
FC
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) {
a44f4b74
KW
131 eval "require '$unicore_dir/Heavy.pl'";
132 last GETFILE if $@;
133 }
134 else {
135 require "$unicore_dir/Heavy.pl";
136 }
1363cbd0 137 BEGIN { delete $utf8::{miniperl} }
99870f4d 138
4ff124d1 139 # All property names are matched caselessly
99870f4d
KW
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;
3dd10fe8
KW
147 if (@remainder) {
148 pop @recursed if @recursed;
149 return $type;
150 }
99870f4d
KW
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};
3dd10fe8
KW
169 if (! defined $property) {
170 pop @recursed if @recursed;
171 return $type;
172 }
99870f4d
KW
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
3dd10fe8
KW
182 if ($table =~ / ^ \/ | \/ $ /x) {
183 pop @recursed if @recursed;
184 return $type;
185 }
99870f4d
KW
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
3dd10fe8
KW
192 if (@parts > 2) {
193 pop @recursed if @recursed;
194 return $type;
195 }
99870f4d
KW
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.)
3dd10fe8
KW
228 if ($part !~ / ^ -? [0-9]+ ( \. [0-9]+)? $ /x) {
229 pop @recursed if @recursed;
230 return $type;
231 }
99870f4d
KW
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.
3dd10fe8
KW
335 if (! defined $table) {
336 pop @recursed if @recursed;
337 return $type;
338 }
99870f4d
KW
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 }
4ff124d1
KW
368
369 if ($caseless
370 && exists $utf8::caseless_equivalent{$property_and_table})
371 {
372 $file = $utf8::caseless_equivalent{$property_and_table};
373 }
99870f4d
KW
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};
3a3263a0 392 warnings::warnif('deprecated', "User-defined case-mapping '$type' is deprecated");
99870f4d
KW
393 last GETFILE;
394 }
395 }
396
397 ##
398 ## Last attempt -- see if it's a standard "To" name
399 ## (e.g. "ToLower") ToTitle is used by ucfirst().
400 ## The user-level way to access ToDigit() and ToFold()
401 ## is to use Unicode::UCD.
402 ##
403 if ($type =~ /^To(Digit|Fold|Lower|Title|Upper)$/) {
404 $file = "$unicore_dir/To/$1.pl";
405 ## would like to test to see if $file actually exists....
406 last GETFILE;
407 }
408
409 ##
410 ## If we reach this line, it's because we couldn't figure
411 ## out what to do with $type. Ouch.
412 ##
413
3dd10fe8 414 pop @recursed if @recursed;
99870f4d 415 return $type;
cf25bb62
JH
416 }
417
99870f4d
KW
418 if (defined $file) {
419 print STDERR __LINE__, ": found it (file='$file')\n" if DEBUG;
420
421 ##
422 ## If we reach here, it was due to a 'last GETFILE' above
423 ## (exception: user-defined properties and mappings), so we
424 ## have a filename, so now we load it if we haven't already.
425 ## If we have, return the cached results. The cache key is the
426 ## class and file to load.
427 ##
428 my $found = $Cache{$class, $file};
429 if ($found and ref($found) eq $class) {
430 print STDERR __LINE__, ": Returning cached '$file' for \\p{$type}\n" if DEBUG;
3dd10fe8 431 pop @recursed if @recursed;
99870f4d
KW
432 return $found;
433 }
434
435 local $@;
436 local $!;
437 $list = do $file; die $@ if $@;
0a0ffbce 438 }
cf25bb62 439
99870f4d 440 $ListSorted = 1; ## we know that these lists are sorted
cf25bb62
JH
441 }
442
99870f4d
KW
443 my $extras;
444 my $bits = $minbits;
445
99870f4d
KW
446 if ($list) {
447 my @tmp = split(/^/m, $list);
448 my %seen;
449 no warnings;
450 $extras = join '', grep /^[^0-9a-fA-F]/, @tmp;
451 $list = join '',
452 map { $_->[1] }
453 sort { $a->[0] <=> $b->[0] }
454 map { /^([0-9a-fA-F]+)/; [ CORE::hex($1), $_ ] }
455 grep { /^([0-9a-fA-F]+)/ and not $seen{$1}++ } @tmp; # XXX doesn't do ranges right
456 }
a0ed51b3 457
99870f4d
KW
458 if ($none) {
459 my $hextra = sprintf "%04x", $none + 1;
460 $list =~ s/\tXXXX$/\t$hextra/mg;
461 }
a0ed51b3 462
99870f4d
KW
463 if ($minbits != 1 && $minbits < 32) { # not binary property
464 my $top = 0;
465 while ($list =~ /^([0-9a-fA-F]+)(?:[\t]([0-9a-fA-F]+)?)(?:[ \t]([0-9a-fA-F]+))?/mg) {
466 my $min = CORE::hex $1;
467 my $max = defined $2 ? CORE::hex $2 : $min;
468 my $val = defined $3 ? CORE::hex $3 : 0;
469 $val += $max - $min if defined $3;
470 $top = $val if $val > $top;
471 }
472 my $topbits =
473 $top > 0xffff ? 32 :
474 $top > 0xff ? 16 : 8;
475 $bits = $topbits if $bits < $topbits;
476 }
a0ed51b3 477
99870f4d
KW
478 my @extras;
479 if ($extras) {
480 for my $x ($extras) {
481 pos $x = 0;
482 while ($x =~ /^([^0-9a-fA-F\n])(.*)/mg) {
483 my $char = $1;
484 my $name = $2;
485 print STDERR __LINE__, ": $1 => $2\n" if DEBUG;
486 if ($char =~ /[-+!&]/) {
487 my ($c,$t) = split(/::/, $name, 2); # bogus use of ::, really
488 my $subobj;
489 if ($c eq 'utf8') {
490 $subobj = utf8->SWASHNEW($t, "", $minbits, 0);
491 }
492 elsif (exists &$name) {
493 $subobj = utf8->SWASHNEW($name, "", $minbits, 0);
494 }
495 elsif ($c =~ /^([0-9a-fA-F]+)/) {
496 $subobj = utf8->SWASHNEW("", $c, $minbits, 0);
497 }
3dd10fe8
KW
498 if (! ref $subobj) {
499 pop @recursed if @recursed && $type;
500 return $subobj;
501 }
99870f4d
KW
502 push @extras, $name => $subobj;
503 $bits = $subobj->{BITS} if $bits < $subobj->{BITS};
504 }
505 }
506 }
507 }
a0ed51b3 508
99870f4d
KW
509 if (DEBUG) {
510 print STDERR __LINE__, ": CLASS = $class, TYPE => $type, BITS => $bits, NONE => $none";
511 print STDERR "\nLIST =>\n$list" if defined $list;
512 print STDERR "\nEXTRAS =>\n$extras" if defined $extras;
513 print STDERR "\n";
514 }
a0ed51b3 515
99870f4d
KW
516 my $SWASH = bless {
517 TYPE => $type,
518 BITS => $bits,
519 EXTRAS => $extras,
520 LIST => $list,
521 NONE => $none,
522 @extras,
523 } => $class;
524
525 if ($file) {
526 $Cache{$class, $file} = $SWASH;
527 }
5beb625e 528
3dd10fe8
KW
529 pop @recursed if @recursed && $type;
530
99870f4d 531 return $SWASH;
5beb625e 532 }
a0ed51b3
LW
533}
534
979f2922 535# Now SWASHGET is recasted into a C function S_swash_get (see utf8.c).
a0ed51b3
LW
536
5371;