This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
mktables: Set caseless equivalent tables
[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;
a44f4b74 35 print STDERR __LINE__, ": class=$class, type=$type, list=$list, minbits=$minbits, none=$none\n" if DEBUG;
99870f4d
KW
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)
cf25bb62 79 {
3dd10fe8
KW
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
99870f4d
KW
89 $type =~ s/^\s+//;
90 $type =~ s/\s+$//;
91
92 print STDERR __LINE__, ": type = $type\n" if DEBUG;
93
94 GETFILE:
95 {
96 ##
a44f4b74
KW
97 ## It could be a user-defined property. Look in current
98 ## package if no package given
99870f4d
KW
99 ##
100
101 my $caller1 = $type =~ s/(.+)::// ? $1 : caller(1);
102
d658a8a8 103 if (defined $caller1 && $type =~ /^I[ns]\w+$/) {
99870f4d
KW
104 my $prop = "${caller1}::$type";
105 if (exists &{$prop}) {
106 no strict 'refs';
107
108 $list = &{$prop};
109 last GETFILE;
110 }
111 }
112
a44f4b74
KW
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.
1363cbd0
FC
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) {
a44f4b74
KW
125 eval "require '$unicore_dir/Heavy.pl'";
126 last GETFILE if $@;
127 }
128 else {
129 require "$unicore_dir/Heavy.pl";
130 }
1363cbd0 131 BEGIN { delete $utf8::{miniperl} }
99870f4d
KW
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;
3dd10fe8
KW
141 if (@remainder) {
142 pop @recursed if @recursed;
143 return $type;
144 }
99870f4d
KW
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};
3dd10fe8
KW
163 if (! defined $property) {
164 pop @recursed if @recursed;
165 return $type;
166 }
99870f4d
KW
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
3dd10fe8
KW
176 if ($table =~ / ^ \/ | \/ $ /x) {
177 pop @recursed if @recursed;
178 return $type;
179 }
99870f4d
KW
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
3dd10fe8
KW
186 if (@parts > 2) {
187 pop @recursed if @recursed;
188 return $type;
189 }
99870f4d
KW
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.)
3dd10fe8
KW
222 if ($part !~ / ^ -? [0-9]+ ( \. [0-9]+)? $ /x) {
223 pop @recursed if @recursed;
224 return $type;
225 }
99870f4d
KW
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.
3dd10fe8
KW
329 if (! defined $table) {
330 pop @recursed if @recursed;
331 return $type;
332 }
99870f4d
KW
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
3dd10fe8 401 pop @recursed if @recursed;
99870f4d 402 return $type;
cf25bb62
JH
403 }
404
99870f4d
KW
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;
3dd10fe8 418 pop @recursed if @recursed;
99870f4d
KW
419 return $found;
420 }
421
422 local $@;
423 local $!;
424 $list = do $file; die $@ if $@;
0a0ffbce 425 }
cf25bb62 426
99870f4d 427 $ListSorted = 1; ## we know that these lists are sorted
cf25bb62
JH
428 }
429
99870f4d
KW
430 my $extras;
431 my $bits = $minbits;
432
99870f4d
KW
433 if ($list) {
434 my @tmp = split(/^/m, $list);
435 my %seen;
436 no warnings;
437 $extras = join '', grep /^[^0-9a-fA-F]/, @tmp;
438 $list = join '',
439 map { $_->[1] }
440 sort { $a->[0] <=> $b->[0] }
441 map { /^([0-9a-fA-F]+)/; [ CORE::hex($1), $_ ] }
442 grep { /^([0-9a-fA-F]+)/ and not $seen{$1}++ } @tmp; # XXX doesn't do ranges right
443 }
a0ed51b3 444
99870f4d
KW
445 if ($none) {
446 my $hextra = sprintf "%04x", $none + 1;
447 $list =~ s/\tXXXX$/\t$hextra/mg;
448 }
a0ed51b3 449
99870f4d
KW
450 if ($minbits != 1 && $minbits < 32) { # not binary property
451 my $top = 0;
452 while ($list =~ /^([0-9a-fA-F]+)(?:[\t]([0-9a-fA-F]+)?)(?:[ \t]([0-9a-fA-F]+))?/mg) {
453 my $min = CORE::hex $1;
454 my $max = defined $2 ? CORE::hex $2 : $min;
455 my $val = defined $3 ? CORE::hex $3 : 0;
456 $val += $max - $min if defined $3;
457 $top = $val if $val > $top;
458 }
459 my $topbits =
460 $top > 0xffff ? 32 :
461 $top > 0xff ? 16 : 8;
462 $bits = $topbits if $bits < $topbits;
463 }
a0ed51b3 464
99870f4d
KW
465 my @extras;
466 if ($extras) {
467 for my $x ($extras) {
468 pos $x = 0;
469 while ($x =~ /^([^0-9a-fA-F\n])(.*)/mg) {
470 my $char = $1;
471 my $name = $2;
472 print STDERR __LINE__, ": $1 => $2\n" if DEBUG;
473 if ($char =~ /[-+!&]/) {
474 my ($c,$t) = split(/::/, $name, 2); # bogus use of ::, really
475 my $subobj;
476 if ($c eq 'utf8') {
477 $subobj = utf8->SWASHNEW($t, "", $minbits, 0);
478 }
479 elsif (exists &$name) {
480 $subobj = utf8->SWASHNEW($name, "", $minbits, 0);
481 }
482 elsif ($c =~ /^([0-9a-fA-F]+)/) {
483 $subobj = utf8->SWASHNEW("", $c, $minbits, 0);
484 }
3dd10fe8
KW
485 if (! ref $subobj) {
486 pop @recursed if @recursed && $type;
487 return $subobj;
488 }
99870f4d
KW
489 push @extras, $name => $subobj;
490 $bits = $subobj->{BITS} if $bits < $subobj->{BITS};
491 }
492 }
493 }
494 }
a0ed51b3 495
99870f4d
KW
496 if (DEBUG) {
497 print STDERR __LINE__, ": CLASS = $class, TYPE => $type, BITS => $bits, NONE => $none";
498 print STDERR "\nLIST =>\n$list" if defined $list;
499 print STDERR "\nEXTRAS =>\n$extras" if defined $extras;
500 print STDERR "\n";
501 }
a0ed51b3 502
99870f4d
KW
503 my $SWASH = bless {
504 TYPE => $type,
505 BITS => $bits,
506 EXTRAS => $extras,
507 LIST => $list,
508 NONE => $none,
509 @extras,
510 } => $class;
511
512 if ($file) {
513 $Cache{$class, $file} = $SWASH;
514 }
5beb625e 515
3dd10fe8
KW
516 pop @recursed if @recursed && $type;
517
99870f4d 518 return $SWASH;
5beb625e 519 }
a0ed51b3
LW
520}
521
979f2922 522# Now SWASHGET is recasted into a C function S_swash_get (see utf8.c).
a0ed51b3
LW
523
5241;