This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
mktables: Fix-up for Unicode version 1
[perl5.git] / lib / _charnames.pm
CommitLineData
e7a078a0
KW
1# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
2# This helper module is for internal use by core Perl only. This module is
3# subject to change or removal at any time without notice. Don't use it
4# directly. Use the public <charnames> module instead.
5
6package _charnames;
7use strict;
8use warnings;
9use File::Spec;
654dfe52 10our $VERSION = '1.31';
e7a078a0
KW
11use unicore::Name; # mktables-generated algorithmically-defined names
12
13use bytes (); # for $bytes::hint_bits
14use re "/aa"; # Everything in here should be ASCII
15
16$Carp::Internal{ (__PACKAGE__) } = 1;
17
18# Translate between Unicode character names and their code points. This is a
19# submodule of package <charnames>, used to allow \N{...} to be autoloaded,
20# but it was decided not to autoload the various functions in charnames; the
21# splitting allows this behavior.
22#
23# The official names with their code points are stored in a table in
24# lib/unicore/Name.pl which is read in as a large string (almost 3/4 Mb in
25# Unicode 6.0). Each code point/name combination is separated by a \n in the
26# string. (Some of the CJK and the Hangul syllable names are determined
27# instead algorithmically via subroutines stored instead in
28# lib/unicore/Name.pm). Because of the large size of this table, it isn't
29# converted into hashes for faster lookup.
30#
31# But, user defined aliases are stored in their own hashes, as are Perl
32# extensions to the official names. These are checked first before looking at
33# the official table.
34#
35# Basically, the table is grepped for the input code point (viacode()) or
36# name (the other functions), and the corresponding value on the same line is
37# returned. The grepping is done by turning the input into a regular
38# expression. Thus, the same table does double duty, used by both name and
39# code point lookup. (If we were to have hashes, we would need two, one for
40# each lookup direction.)
41#
42# For loose name matching, the logical thing would be to have a table
43# with all the ignorable characters squeezed out, and then grep it with the
44# similiarly-squeezed input name. (And this is in fact how the lookups are
45# done with the small Perl extension hashes.) But since we need to be able to
46# go from code point to official name, the original table would still need to
47# exist. Due to the large size of the table, it was decided to not read
48# another very large string into memory for a second table. Instead, the
49# regular expression of the input name is modified to have optional spaces and
50# dashes between characters. For example, in strict matching, the regular
51# expression would be:
52# qr/\tDIGIT ONE$/m
53# Under loose matching, the blank would be squeezed out, and the re would be:
54# qr/\tD[- ]?I[- ]?G[- ]?I[- ]?T[- ]?O[- ]?N[- ]?E$/m
55# which matches a blank or dash between any characters in the official table.
56#
57# This is also how script lookup is done. Basically the re looks like
58# qr/ (?:LATIN|GREEK|CYRILLIC) (?:SMALL )?LETTER $name/
59# where $name is the loose or strict regex for the remainder of the name.
60
61# The hashes are stored as utf8 strings. This makes it easier to deal with
62# sequences. I (khw) also tried making Name.pl utf8, but it slowed things
63# down by a factor of 7. I then tried making Name.pl store the ut8
64# equivalents but not calling them utf8. That led to similar speed as leaving
65# it alone, but since that is harder for a human to parse, I left it as-is.
66
67my %system_aliases = (
e7a078a0 68
e7a078a0
KW
69 'SINGLE-SHIFT 2' => pack("U", 0x8E),
70 'SINGLE-SHIFT 3' => pack("U", 0x8F),
71 'PRIVATE USE 1' => pack("U", 0x91),
72 'PRIVATE USE 2' => pack("U", 0x92),
e7a078a0
KW
73);
74
75# These are the aliases above that differ under :loose and :full matching
76# because the :full versions have blanks or hyphens in them.
7620cb10
KW
77#my %loose_system_aliases = (
78#);
e7a078a0
KW
79
80my %deprecated_aliases = (
e7a078a0 81 # Use of these gives deprecated message.
e7a078a0
KW
82 # Unicode 6.0 co-opted this for U+1F514, so deprecate it for now.
83 'BELL' => pack("U", 0x07),
84);
85
7620cb10
KW
86#my %loose_deprecated_aliases = (
87#);
e7a078a0
KW
88
89# These are special cased in :loose matching, differing only in a medial
90# hyphen
91my $HANGUL_JUNGSEONG_O_E_utf8 = pack("U", 0x1180);
92my $HANGUL_JUNGSEONG_OE_utf8 = pack("U", 0x116C);
93
94
95my $txt; # The table of official character names
96
97my %full_names_cache; # Holds already-looked-up names, so don't have to
98# re-look them up again. The previous versions of charnames had scoping
99# bugs. For example if we use script A in one scope and find and cache
100# what Z resolves to, we can't use that cache in a different scope that
101# uses script B instead of A, as Z might be an entirely different letter
102# there; or there might be different aliases in effect in different
103# scopes, or :short may be in effect or not effect in different scopes,
104# or various combinations thereof. This was solved in this version
105# mostly by moving things to %^H. But some things couldn't be moved
106# there. One of them was the cache of runtime looked-up names, in part
107# because %^H is read-only at runtime. I (khw) don't know why the cache
108# was run-time only in the previous versions: perhaps oversight; perhaps
109# that compile time looking doesn't happen in a loop so didn't think it
110# was worthwhile; perhaps not wanting to make the cache too large. But
111# I decided to make it compile time as well; this could easily be
112# changed.
113# Anyway, this hash is not scoped, and is added to at runtime. It
114# doesn't have scoping problems because the data in it is restricted to
115# official names, which are always invariant, and we only set it and
116# look at it at during :full lookups, so is unaffected by any other
117# scoped options. I put this in to maintain parity with the older
118# version. If desired, a %short_names cache could also be made, as well
119# as one for each script, say in %script_names_cache, with each key
120# being a hash for a script named in a 'use charnames' statement. I
121# decided not to do that for now, just because it's added complication,
122# and because I'm just trying to maintain parity, not extend it.
123
124# Like %full_names_cache, but for use when :loose is in effect. There needs
125# to be two caches because :loose may not be in effect for a scope, and a
126# loose name could inappropriately be returned when only exact matching is
127# called for.
128my %loose_names_cache;
129
130# Designed so that test decimal first, and then hex. Leading zeros
131# imply non-decimal, as do non-[0-9]
132my $decimal_qr = qr/^[1-9]\d*$/;
133
134# Returns the hex number in $1.
135my $hex_qr = qr/^(?:[Uu]\+|0[xX])?([[:xdigit:]]+)$/;
136
137sub croak
138{
139 require Carp; goto &Carp::croak;
140} # croak
141
142sub carp
143{
144 require Carp; goto &Carp::carp;
145} # carp
146
147sub alias (@) # Set up a single alias
148{
149 my $alias = ref $_[0] ? $_[0] : { @_ };
150 foreach my $name (keys %$alias) {
151 my $value = $alias->{$name};
152 next unless defined $value; # Omit if screwed up.
153
154 # Is slightly slower to just after this statement see if it is
155 # decimal, since we already know it is after having converted from
156 # hex, but makes the code easier to maintain, and is called
157 # infrequently, only at compile-time
158 if ($value !~ $decimal_qr && $value =~ $hex_qr) {
159 $value = CORE::hex $1;
160 }
161 if ($value =~ $decimal_qr) {
162 no warnings qw(non_unicode surrogate nonchar); # Allow any non-malformed
163 $^H{charnames_ord_aliases}{$name} = pack("U", $value);
164
165 # Use a canonical form.
166 $^H{charnames_inverse_ords}{sprintf("%05X", $value)} = $name;
167 }
168 else {
169 # XXX validate syntax when deprecation cycle complete. ie. start
170 # with an alpha only, etc.
171 $^H{charnames_name_aliases}{$name} = $value;
172 }
173 }
174} # alias
175
176sub not_legal_use_bytes_msg {
177 my ($name, $utf8) = @_;
178 my $return;
179
180 if (length($utf8) == 1) {
181 $return = sprintf("Character 0x%04x with name '%s' is", ord $utf8, $name);
182 } else {
183 $return = sprintf("String with name '%s' (and ordinals %s) contains character(s)", $name, join(" ", map { sprintf "0x%04X", ord $_ } split(//, $utf8)));
184 }
185 return $return . " above 0xFF with 'use bytes' in effect";
186}
187
188sub alias_file ($) # Reads a file containing alias definitions
189{
190 my ($arg, $file) = @_;
191 if (-f $arg && File::Spec->file_name_is_absolute ($arg)) {
192 $file = $arg;
193 }
194 elsif ($arg =~ m/^\w+$/) {
195 $file = "unicore/${arg}_alias.pl";
196 }
197 else {
198 croak "Charnames alias files can only have identifier characters";
199 }
200 if (my @alias = do $file) {
201 @alias == 1 && !defined $alias[0] and
202 croak "$file cannot be used as alias file for charnames";
203 @alias % 2 and
204 croak "$file did not return a (valid) list of alias pairs";
205 alias (@alias);
206 return (1);
207 }
208 0;
209} # alias_file
210
211# For use when don't import anything. This structure must be kept in
212# sync with the one that import() fills up.
213my %dummy_H = (
214 charnames_stringified_names => "",
215 charnames_stringified_ords => "",
216 charnames_scripts => "",
217 charnames_full => 1,
218 charnames_loose => 0,
219 charnames_short => 0,
220 );
221
222
223sub lookup_name ($$$) {
224 my ($name, $wants_ord, $runtime) = @_;
225
226 # Lookup the name or sequence $name in the tables. If $wants_ord is false,
227 # returns the string equivalent of $name; if true, returns the ordinal value
228 # instead, but in this case $name must not be a sequence; otherwise undef is
229 # returned and a warning raised. $runtime is 0 if compiletime, otherwise
230 # gives the number of stack frames to go back to get the application caller
231 # info.
232 # If $name is not found, returns undef in runtime with no warning; and in
233 # compiletime, the Unicode replacement character, with a warning.
234
235 # It looks first in the aliases, then in the large table of official Unicode
236 # names.
237
238 my $utf8; # The string result
239 my $save_input;
240
241 if ($runtime) {
242
243 my $hints_ref = (caller($runtime))[10];
244
245 # If we didn't import anything (which happens with 'use charnames ()',
246 # substitute a dummy structure.
247 $hints_ref = \%dummy_H if ! defined $hints_ref
248 || (! defined $hints_ref->{charnames_full}
249 && ! defined $hints_ref->{charnames_loose});
250
251 # At runtime, but currently not at compile time, $^H gets
252 # stringified, so un-stringify back to the original data structures.
253 # These get thrown away by perl before the next invocation
254 # Also fill in the hash with the non-stringified data.
255 # N.B. New fields must be also added to %dummy_H
256
257 %{$^H{charnames_name_aliases}} = split ',',
258 $hints_ref->{charnames_stringified_names};
259 %{$^H{charnames_ord_aliases}} = split ',',
260 $hints_ref->{charnames_stringified_ords};
261 $^H{charnames_scripts} = $hints_ref->{charnames_scripts};
262 $^H{charnames_full} = $hints_ref->{charnames_full};
263 $^H{charnames_loose} = $hints_ref->{charnames_loose};
264 $^H{charnames_short} = $hints_ref->{charnames_short};
265 }
266
267 my $loose = $^H{charnames_loose};
268 my $lookup_name; # Input name suitably modified for grepping for in the
269 # table
270
271 # User alias should be checked first or else can't override ours, and if we
272 # were to add any, could conflict with theirs.
273 if (exists $^H{charnames_ord_aliases}{$name}) {
274 $utf8 = $^H{charnames_ord_aliases}{$name};
275 }
276 elsif (exists $^H{charnames_name_aliases}{$name}) {
277 $name = $^H{charnames_name_aliases}{$name};
278 $save_input = $lookup_name = $name; # Cache the result for any error
279 # message
280 # The aliases are documented to not match loosely, so change loose match
281 # into full.
282 if ($loose) {
283 $loose = 0;
284 $^H{charnames_full} = 1;
285 }
286 }
287 else {
288
289 # Here, not a user alias. That means that loose matching may be in
290 # effect; will have to modify the input name.
291 $lookup_name = $name;
292 if ($loose) {
293 $lookup_name = uc $lookup_name;
294
295 # Squeeze out all underscores
296 $lookup_name =~ s/_//g;
297
298 # Remove all medial hyphens
299 $lookup_name =~ s/ (?<= \S ) - (?= \S )//gx;
300
301 # Squeeze out all spaces
302 $lookup_name =~ s/\s//g;
303 }
304
305 # Here, $lookup_name has been modified as necessary for looking in the
306 # hashes. Check the system alias files next. Most of these aliases are
307 # the same for both strict and loose matching. To save space, the ones
308 # which differ are in their own separate hash, which is checked if loose
309 # matching is selected and the regular match fails. To save time, the
310 # loose hashes could be expanded to include all aliases, and there would
311 # only have to be one check. But if someone specifies :loose, they are
312 # interested in convenience over speed, and the time for this second check
313 # is miniscule compared to the rest of the routine.
314 if (exists $system_aliases{$lookup_name}) {
315 $utf8 = $system_aliases{$lookup_name};
316 }
7620cb10
KW
317 # There are currently no entries in this hash, so don't waste time looking
318 # for them. But the code is retained for the unlikely possibility that
319 # some will be added in the future.
320# elsif ($loose && exists $loose_system_aliases{$lookup_name}) {
321# $utf8 = $loose_system_aliases{$lookup_name};
322# }
323 if (exists $deprecated_aliases{$lookup_name}) {
e7a078a0
KW
324 require warnings;
325 warnings::warnif('deprecated',
326 "Unicode character name \"$name\" is deprecated, use \""
327 . viacode(ord $deprecated_aliases{$lookup_name})
328 . "\" instead");
329 $utf8 = $deprecated_aliases{$lookup_name};
330 }
7620cb10
KW
331 # There are currently no entries in this hash, so don't waste time looking
332 # for them. But the code is retained for the unlikely possibility that
333 # some will be added in the future.
334# elsif ($loose && exists $loose_deprecated_aliases{$lookup_name}) {
335# require warnings;
336# warnings::warnif('deprecated',
337# "Unicode character name \"$name\" is deprecated, use \""
338# . viacode(ord $loose_deprecated_aliases{$lookup_name})
339# . "\" instead");
340# $utf8 = $loose_deprecated_aliases{$lookup_name};
341# }
e7a078a0
KW
342 }
343
344 my @off; # Offsets into table of pattern match begin and end
345
346 # If haven't found it yet...
347 if (! defined $utf8) {
348
349 # See if has looked this input up earlier.
350 if (! $loose && $^H{charnames_full} && exists $full_names_cache{$name}) {
351 $utf8 = $full_names_cache{$name};
352 }
353 elsif ($loose && exists $loose_names_cache{$name}) {
354 $utf8 = $loose_names_cache{$name};
355 }
356 else { # Here, must do a look-up
357
358 # If full or loose matching succeeded, points to where to cache the
359 # result
360 my $cache_ref;
361
362 ## Suck in the code/name list as a big string.
363 ## Lines look like:
364 ## "00052\tLATIN CAPITAL LETTER R\n"
365 # or
366 # "0052 0303\tLATIN CAPITAL LETTER R WITH TILDE\n"
367 $txt = do "unicore/Name.pl" unless $txt;
368
369 ## @off will hold the index into the code/name string of the start and
370 ## end of the name as we find it.
371
372 ## If :loose, look for a loose match; if :full, look for the name
373 ## exactly
374 # First, see if the name is one which is algorithmically determinable.
375 # The subroutine is included in Name.pl. The table contained in
376 # $txt doesn't contain these. Experiments show that checking
377 # for these before checking for the regular names has no
378 # noticeable impact on performance for the regular names, but
379 # the other way around slows down finding these immensely.
380 # Algorithmically determinables are not placed in the cache because
381 # that uses up memory, and finding these again is fast.
382 if (($loose || $^H{charnames_full})
383 && (defined (my $ord = charnames::name_to_code_point_special($lookup_name, $loose))))
384 {
385 $utf8 = pack("U", $ord);
386 }
387 else {
388
389 # Not algorithmically determinable; look up in the table. The name
390 # will be turned into a regex, so quote any meta characters.
391 $lookup_name = quotemeta $lookup_name;
392
393 if ($loose) {
394
395 # For loose matches, $lookup_name has already squeezed out the
396 # non-essential characters. We have to add in code to make the
397 # squeezed version match the non-squeezed equivalent in the table.
398 # The only remaining hyphens are ones that start or end a word in
399 # the original. They have been quoted in $lookup_name so they look
400 # like "\-". Change all other characters except the backslash
401 # quotes for any metacharacters, and the final character, so that
402 # e.g., COLON gets transformed into: /C[- ]?O[- ]?L[- ]?O[- ]?N/
403 $lookup_name =~ s/ (?! \\ -) # Don't do this to the \- sequence
404 ( [^-\\] ) # Nor the "-" within that sequence,
405 # nor the "\" that quotes metachars,
406 # but otherwise put the char into $1
407 (?=.) # And don't do it for the final char
408 /$1\[- \]?/gx; # And add an optional blank or
409 # '-' after each $1 char
410
411 # Those remaining hyphens were originally at the beginning or end of
412 # a word, so they can match either a blank before or after, but not
413 # both. (Keep in mind that they have been quoted, so are a '\-'
414 # sequence)
415 $lookup_name =~ s/\\ -/(?:- | -)/xg;
416 }
417
418 # Do the lookup in the full table if asked for, and if succeeds
419 # save the offsets and set where to cache the result.
420 if (($loose || $^H{charnames_full}) && $txt =~ /\t$lookup_name$/m) {
421 @off = ($-[0] + 1, $+[0]); # The 1 is for the tab
422 $cache_ref = ($loose) ? \%loose_names_cache : \%full_names_cache;
423 }
424 else {
425
426 # Here, didn't look for, or didn't find the name.
427 # If :short is allowed, see if input is like "greek:Sigma".
428 # Keep in mind that $lookup_name has had the metas quoted.
429 my $scripts_trie = "";
430 my $name_has_uppercase;
431 if (($^H{charnames_short})
432 && $lookup_name =~ /^ (?: \\ \s)* # Quoted space
433 (.+?) # $1 = the script
434 (?: \\ \s)*
435 \\ : # Quoted colon
436 (?: \\ \s)*
437 (.+?) # $2 = the name
438 (?: \\ \s)* $
439 /xs)
440 {
441 # Even in non-loose matching, the script traditionally has been
442 # case insensitve
443 $scripts_trie = "\U$1";
444 $lookup_name = $2;
445
446 # Use original name to find its input casing, but ignore the
447 # script part of that to make the determination.
448 $save_input = $name if ! defined $save_input;
449 $name =~ s/.*?://;
450 $name_has_uppercase = $name =~ /[[:upper:]]/;
451 }
452 else { # Otherwise look in allowed scripts
453 $scripts_trie = $^H{charnames_scripts};
454
455 # Use original name to find its input casing
456 $name_has_uppercase = $name =~ /[[:upper:]]/;
457 }
458
459 my $case = $name_has_uppercase ? "CAPITAL" : "SMALL";
460 if (! $scripts_trie
461 || $txt !~
462 /\t (?: $scripts_trie ) \ (?:$case\ )? LETTER \ \U$lookup_name $/xm)
463 {
464 # Here we still don't have it, give up.
465 return if $runtime;
466
467 # May have zapped input name, get it again.
468 $name = (defined $save_input) ? $save_input : $_[0];
469 carp "Unknown charname '$name'";
470 return ($wants_ord) ? 0xFFFD : pack("U", 0xFFFD);
471 }
472
473 # Here have found the input name in the table.
474 @off = ($-[0] + 1, $+[0]); # The 1 is for the tab
475 }
476
477 # Here, the input name has been found; we haven't set up the output,
478 # but we know where in the string
479 # the name starts. The string is set up so that for single characters
480 # (and not named sequences), the name is preceded immediately by a
481 # tab and 5 hex digits for its code, with a \n before those. Named
482 # sequences won't have the 7th preceding character be a \n.
483 # (Actually, for the very first entry in the table this isn't strictly
484 # true: subtracting 7 will yield -1, and the substr below will
485 # therefore yield the very last character in the table, which should
486 # also be a \n, so the statement works anyway.)
487 if (substr($txt, $off[0] - 7, 1) eq "\n") {
488 $utf8 = pack("U", CORE::hex substr($txt, $off[0] - 6, 5));
489
490 # Handle the single loose matching special case, in which two names
491 # differ only by a single medial hyphen. If the original had a
492 # hyphen (or more) in the right place, then it is that one.
493 $utf8 = $HANGUL_JUNGSEONG_O_E_utf8
494 if $loose
495 && $utf8 eq $HANGUL_JUNGSEONG_OE_utf8
496 && $name =~ m/O \s* - [-\s]* E/ix;
497 # Note that this wouldn't work if there were a 2nd
498 # OE in the name
499 }
500 else {
501
502 # Here, is a named sequence. Need to go looking for the beginning,
503 # which is just after the \n from the previous entry in the table.
504 # The +1 skips past that newline, or, if the rindex() fails, to put
505 # us to an offset of zero.
506 my $charstart = rindex($txt, "\n", $off[0] - 7) + 1;
507 $utf8 = pack("U*", map { CORE::hex }
508 split " ", substr($txt, $charstart, $off[0] - $charstart - 1));
509 }
510 }
511
512 # Cache the input so as to not have to search the large table
513 # again, but only if it came from the one search that we cache.
514 # (Haven't bothered with the pain of sorting out scoping issues for the
515 # scripts searches.)
516 $cache_ref->{$name} = $utf8 if defined $cache_ref;
517 }
518 }
519
520
521 # Here, have the utf8. If the return is to be an ord, must be any single
522 # character.
523 if ($wants_ord) {
524 return ord($utf8) if length $utf8 == 1;
525 }
526 else {
527
528 # Here, wants string output. If utf8 is acceptable, just return what
529 # we've got; otherwise attempt to convert it to non-utf8 and return that.
530 my $in_bytes = ($runtime)
531 ? (caller $runtime)[8] & $bytes::hint_bits
532 : $^H & $bytes::hint_bits;
533 return $utf8 if (! $in_bytes || utf8::downgrade($utf8, 1)) # The 1 arg
534 # means don't die on failure
535 }
536
537 # Here, there is an error: either there are too many characters, or the
538 # result string needs to be non-utf8, and at least one character requires
539 # utf8. Prefer any official name over the input one for the error message.
540 if (@off) {
541 $name = substr($txt, $off[0], $off[1] - $off[0]) if @off;
542 }
543 else {
544 $name = (defined $save_input) ? $save_input : $_[0];
545 }
546
547 if ($wants_ord) {
548 # Only way to get here in this case is if result too long. Message
549 # assumes that our only caller that requires single char result is
550 # vianame.
551 carp "charnames::vianame() doesn't handle named sequences ($name). Use charnames::string_vianame() instead";
552 return;
553 }
554
555 # Only other possible failure here is from use bytes.
556 if ($runtime) {
557 carp not_legal_use_bytes_msg($name, $utf8);
558 return;
559 } else {
560 croak not_legal_use_bytes_msg($name, $utf8);
561 }
562
563} # lookup_name
564
565sub charnames {
566
567 # For \N{...}. Looks up the character name and returns the string
568 # representation of it.
569
570 # The first 0 arg means wants a string returned; the second that we are in
571 # compile time
572 return lookup_name($_[0], 0, 0);
573}
574
575sub import
576{
577 shift; ## ignore class name
578
579 if (not @_) {
580 carp("'use charnames' needs explicit imports list");
581 }
582 $^H{charnames} = \&charnames ;
583 $^H{charnames_ord_aliases} = {};
584 $^H{charnames_name_aliases} = {};
585 $^H{charnames_inverse_ords} = {};
586 # New fields must be added to %dummy_H, and the code in lookup_name()
587 # that copies fields from the runtime structure
588
589 ##
590 ## fill %h keys with our @_ args.
591 ##
592 my ($promote, %h, @args) = (0);
593 while (my $arg = shift) {
594 if ($arg eq ":alias") {
595 @_ or
596 croak ":alias needs an argument in charnames";
597 my $alias = shift;
598 if (ref $alias) {
599 ref $alias eq "HASH" or
600 croak "Only HASH reference supported as argument to :alias";
601 alias ($alias);
602 next;
603 }
604 if ($alias =~ m{:(\w+)$}) {
605 $1 eq "full" || $1 eq "loose" || $1 eq "short" and
606 croak ":alias cannot use existing pragma :$1 (reversed order?)";
607 alias_file ($1) and $promote = 1;
608 next;
609 }
610 alias_file ($alias);
611 next;
612 }
613 if (substr($arg, 0, 1) eq ':'
614 and ! ($arg eq ":full" || $arg eq ":short" || $arg eq ":loose"))
615 {
616 warn "unsupported special '$arg' in charnames";
617 next;
618 }
619 push @args, $arg;
620 }
621
622 @args == 0 && $promote and @args = (":full");
623 @h{@args} = (1) x @args;
624
625 # Don't leave these undefined as are tested for in lookup_names
626 $^H{charnames_full} = delete $h{':full'} || 0;
627 $^H{charnames_loose} = delete $h{':loose'} || 0;
628 $^H{charnames_short} = delete $h{':short'} || 0;
629 my @scripts = map { uc quotemeta } keys %h;
630
631 ##
632 ## If utf8? warnings are enabled, and some scripts were given,
633 ## see if at least we can find one letter from each script.
634 ##
635 if (warnings::enabled('utf8') && @scripts) {
636 $txt = do "unicore/Name.pl" unless $txt;
637
638 for my $script (@scripts) {
639 if (not $txt =~ m/\t$script (?:CAPITAL |SMALL )?LETTER /) {
640 warnings::warn('utf8', "No such script: '$script'");
641 $script = quotemeta $script; # Escape it, for use in the re.
642 }
643 }
644 }
645
646 # %^H gets stringified, so serialize it ourselves so can extract the
647 # real data back later.
648 $^H{charnames_stringified_ords} = join ",", %{$^H{charnames_ord_aliases}};
649 $^H{charnames_stringified_names} = join ",", %{$^H{charnames_name_aliases}};
650 $^H{charnames_stringified_inverse_ords} = join ",", %{$^H{charnames_inverse_ords}};
651
652 # Modify the input script names for loose name matching if that is also
653 # specified, similar to the way the base character name is prepared. They
654 # don't (currently, and hopefully never will) have dashes. These go into a
655 # regex, and have already been uppercased and quotemeta'd. Squeeze out all
656 # input underscores, blanks, and dashes. Then convert so will match a blank
657 # between any characters.
658 if ($^H{charnames_loose}) {
659 for (my $i = 0; $i < @scripts; $i++) {
660 $scripts[$i] =~ s/[_ -]//g;
661 $scripts[$i] =~ s/ ( [^\\] ) (?= . ) /$1\\ ?/gx;
662 }
663 }
664
665 $^H{charnames_scripts} = join "|", @scripts; # Stringifiy them as a trie
666} # import
667
668# Cache of already looked-up values. This is set to only contain
669# official values, and user aliases can't override them, so scoping is
670# not an issue.
671my %viacode;
672
673sub viacode {
674
675 # Returns the name of the code point argument
676
677 if (@_ != 1) {
678 carp "charnames::viacode() expects one argument";
679 return;
680 }
681
682 my $arg = shift;
683
684 # This is derived from Unicode::UCD, where it is nearly the same as the
685 # function _getcode(), but here it makes sure that even a hex argument
686 # has the proper number of leading zeros, which is critical in
687 # matching against $txt below
688 # Must check if decimal first; see comments at that definition
689 my $hex;
690 if ($arg =~ $decimal_qr) {
691 $hex = sprintf "%05X", $arg;
692 } elsif ($arg =~ $hex_qr) {
693 # Below is the line that differs from the _getcode() source
694 $hex = sprintf "%05X", hex $1;
695 } else {
696 carp("unexpected arg \"$arg\" to charnames::viacode()");
697 return;
698 }
699
700 return $viacode{$hex} if exists $viacode{$hex};
701
7620cb10
KW
702 my $return;
703
e7a078a0
KW
704 # If the code point is above the max in the table, there's no point
705 # looking through it. Checking the length first is slightly faster
706 if (length($hex) <= 5 || CORE::hex($hex) <= 0x10FFFF) {
707 $txt = do "unicore/Name.pl" unless $txt;
708
709 # See if the name is algorithmically determinable.
710 my $algorithmic = charnames::code_point_to_name_special(CORE::hex $hex);
711 if (defined $algorithmic) {
712 $viacode{$hex} = $algorithmic;
713 return $algorithmic;
714 }
715
716 # Return the official name, if exists. It's unclear to me (khw) at
717 # this juncture if it is better to return a user-defined override, so
718 # leaving it as is for now.
719 if ($txt =~ m/^$hex\t/m) {
720
721 # The name starts with the next character and goes up to the
722 # next new-line. Using capturing parentheses above instead of
723 # @+ more than doubles the execution time in Perl 5.13
7620cb10
KW
724 $return = substr($txt, $+[0], index($txt, "\n", $+[0]) - $+[0]);
725
726 # If not one of these 4 code points, return what we've found.
727 if ($hex !~ / ^ 000 (?: 8[014] | 99 ) $ /x) {
728 $viacode{$hex} = $return;
729 return $return;
730 }
731
732 # For backwards compatibility, we don't return the official name of
733 # the 4 code points if there are user-defined aliases for them -- so
734 # continue looking.
e7a078a0
KW
735 }
736 }
737
738 # See if there is a user name for it, before giving up completely.
739 # First get the scoped aliases, give up if have none.
740 my $H_ref = (caller(1))[10];
7620cb10
KW
741 return if ! defined $return
742 && (! defined $H_ref
743 || ! exists $H_ref->{charnames_stringified_inverse_ords});
e7a078a0 744
424313d4
KW
745 my %code_point_aliases;
746 if (defined $H_ref->{charnames_stringified_inverse_ords}) {
747 %code_point_aliases = split ',',
e7a078a0 748 $H_ref->{charnames_stringified_inverse_ords};
424313d4
KW
749 return $code_point_aliases{$hex} if exists $code_point_aliases{$hex};
750 }
7620cb10 751
de72f72f
KW
752 # Here there is no user-defined alias, return any official one.
753 return $return if defined $return;
7620cb10 754
de72f72f
KW
755 if (CORE::hex($hex) > 0x10FFFF) {
756 carp "Unicode characters only allocated up to U+10FFFF (you asked for U+$hex)";
757 }
758 return;
e7a078a0 759
e7a078a0
KW
760} # _viacode
761
7621;
763
764# ex: set ts=8 sts=2 sw=2 et: