"Fossies" - the Fresh Open Source Software Archive

Member "install-tl-20200916/tlpkg/tlperl/lib/_charnames.pm" (10 Mar 2019, 33166 Bytes) of package /windows/misc/install-tl.zip:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Perl source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

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