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