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