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