This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Unicode::UCD: Fix to work on Unicodes without script property
[perl5.git] / lib / Unicode / UCD.pm
CommitLineData
55d7b906 1package Unicode::UCD;
561c79ed
JH
2
3use strict;
4use warnings;
36c2430c 5no warnings 'surrogate'; # surrogates can be inputs to this
98ef7649 6use charnames ();
94c91ffc 7use Unicode::Normalize qw(getCombinClass NFD);
561c79ed 8
e80c2d9d 9our $VERSION = '0.44';
561c79ed 10
741297c1
JH
11use Storable qw(dclone);
12
561c79ed
JH
13require Exporter;
14
15our @ISA = qw(Exporter);
74f8133e 16
10a6ecd2
JH
17our @EXPORT_OK = qw(charinfo
18 charblock charscript
19 charblocks charscripts
b08cd201 20 charinrange
ea508aee 21 general_categories bidi_types
b08cd201 22 compexcl
a2bd7410 23 casefold casespec
7319f91d
KW
24 namedseq
25 num
7ef25837
KW
26 prop_aliases
27 prop_value_aliases
681d705c 28 prop_invlist
62b3b855 29 prop_invmap
681d705c 30 MAX_CP
7319f91d 31 );
561c79ed
JH
32
33use Carp;
34
35=head1 NAME
36
55d7b906 37Unicode::UCD - Unicode character database
561c79ed
JH
38
39=head1 SYNOPSIS
40
55d7b906 41 use Unicode::UCD 'charinfo';
b08cd201 42 my $charinfo = charinfo($codepoint);
561c79ed 43
956cae9a
KW
44 use Unicode::UCD 'casefold';
45 my $casefold = casefold(0xFB00);
46
5d8e6e41
KW
47 use Unicode::UCD 'casespec';
48 my $casespec = casespec(0xFB00);
49
55d7b906 50 use Unicode::UCD 'charblock';
e882dd67
JH
51 my $charblock = charblock($codepoint);
52
55d7b906 53 use Unicode::UCD 'charscript';
65044554 54 my $charscript = charscript($codepoint);
561c79ed 55
55d7b906 56 use Unicode::UCD 'charblocks';
e145285f
JH
57 my $charblocks = charblocks();
58
55d7b906 59 use Unicode::UCD 'charscripts';
ea508aee 60 my $charscripts = charscripts();
e145285f 61
55d7b906 62 use Unicode::UCD qw(charscript charinrange);
e145285f
JH
63 my $range = charscript($script);
64 print "looks like $script\n" if charinrange($range, $codepoint);
65
ea508aee
JH
66 use Unicode::UCD qw(general_categories bidi_types);
67 my $categories = general_categories();
68 my $types = bidi_types();
69
7ef25837
KW
70 use Unicode::UCD 'prop_aliases';
71 my @space_names = prop_aliases("space");
72
73 use Unicode::UCD 'prop_value_aliases';
74 my @gc_punct_names = prop_value_aliases("Gc", "Punct");
75
681d705c
KW
76 use Unicode::UCD 'prop_invlist';
77 my @puncts = prop_invlist("gc=punctuation");
78
62b3b855
KW
79 use Unicode::UCD 'prop_invmap';
80 my ($list_ref, $map_ref, $format, $missing)
81 = prop_invmap("General Category");
82
55d7b906 83 use Unicode::UCD 'compexcl';
e145285f
JH
84 my $compexcl = compexcl($codepoint);
85
a2bd7410
JH
86 use Unicode::UCD 'namedseq';
87 my $namedseq = namedseq($named_sequence_name);
88
55d7b906 89 my $unicode_version = Unicode::UCD::UnicodeVersion();
e145285f 90
7319f91d 91 my $convert_to_numeric =
62a8c8c2 92 Unicode::UCD::num("\N{RUMI DIGIT ONE}\N{RUMI DIGIT TWO}");
7319f91d 93
561c79ed
JH
94=head1 DESCRIPTION
95
a452d459
KW
96The Unicode::UCD module offers a series of functions that
97provide a simple interface to the Unicode
8b731da2 98Character Database.
561c79ed 99
a452d459
KW
100=head2 code point argument
101
102Some of the functions are called with a I<code point argument>, which is either
103a decimal or a hexadecimal scalar designating a Unicode code point, or C<U+>
104followed by hexadecimals designating a Unicode code point. In other words, if
105you want a code point to be interpreted as a hexadecimal number, you must
106prefix it with either C<0x> or C<U+>, because a string like e.g. C<123> will be
f200dd12
KW
107interpreted as a decimal code point. Note that the largest code point in
108Unicode is U+10FFFF.
c3e5bc54 109
561c79ed
JH
110=cut
111
10a6ecd2 112my $BLOCKSFH;
10a6ecd2 113my $VERSIONFH;
b08cd201
JH
114my $CASEFOLDFH;
115my $CASESPECFH;
a2bd7410 116my $NAMEDSEQFH;
e80c2d9d 117my $v_unicode_version; # v-string.
561c79ed
JH
118
119sub openunicode {
120 my ($rfh, @path) = @_;
121 my $f;
122 unless (defined $$rfh) {
123 for my $d (@INC) {
124 use File::Spec;
55d7b906 125 $f = File::Spec->catfile($d, "unicore", @path);
32c16050 126 last if open($$rfh, $f);
e882dd67 127 undef $f;
561c79ed 128 }
e882dd67
JH
129 croak __PACKAGE__, ": failed to find ",
130 File::Spec->catfile(@path), " in @INC"
131 unless defined $f;
561c79ed
JH
132 }
133 return $f;
134}
135
a452d459 136=head2 B<charinfo()>
561c79ed 137
55d7b906 138 use Unicode::UCD 'charinfo';
561c79ed 139
b08cd201 140 my $charinfo = charinfo(0x41);
561c79ed 141
a452d459
KW
142This returns information about the input L</code point argument>
143as a reference to a hash of fields as defined by the Unicode
144standard. If the L</code point argument> is not assigned in the standard
145(i.e., has the general category C<Cn> meaning C<Unassigned>)
146or is a non-character (meaning it is guaranteed to never be assigned in
147the standard),
a18e976f 148C<undef> is returned.
a452d459
KW
149
150Fields that aren't applicable to the particular code point argument exist in the
151returned hash, and are empty.
152
153The keys in the hash with the meanings of their values are:
154
155=over
156
157=item B<code>
158
159the input L</code point argument> expressed in hexadecimal, with leading zeros
160added if necessary to make it contain at least four hexdigits
161
162=item B<name>
163
164name of I<code>, all IN UPPER CASE.
165Some control-type code points do not have names.
166This field will be empty for C<Surrogate> and C<Private Use> code points,
167and for the others without a name,
168it will contain a description enclosed in angle brackets, like
169C<E<lt>controlE<gt>>.
170
171
172=item B<category>
173
174The short name of the general category of I<code>.
175This will match one of the keys in the hash returned by L</general_categories()>.
176
7ef25837
KW
177The L</prop_value_aliases()> function can be used to get all the synonyms
178of the category name.
179
a452d459
KW
180=item B<combining>
181
182the combining class number for I<code> used in the Canonical Ordering Algorithm.
183For Unicode 5.1, this is described in Section 3.11 C<Canonical Ordering Behavior>
184available at
185L<http://www.unicode.org/versions/Unicode5.1.0/>
186
7ef25837
KW
187The L</prop_value_aliases()> function can be used to get all the synonyms
188of the combining class number.
189
a452d459
KW
190=item B<bidi>
191
192bidirectional type of I<code>.
193This will match one of the keys in the hash returned by L</bidi_types()>.
194
7ef25837
KW
195The L</prop_value_aliases()> function can be used to get all the synonyms
196of the bidi type name.
197
a452d459
KW
198=item B<decomposition>
199
200is empty if I<code> has no decomposition; or is one or more codes
a18e976f 201(separated by spaces) that, taken in order, represent a decomposition for
a452d459
KW
202I<code>. Each has at least four hexdigits.
203The codes may be preceded by a word enclosed in angle brackets then a space,
204like C<E<lt>compatE<gt> >, giving the type of decomposition
205
06bba7d5
KW
206This decomposition may be an intermediate one whose components are also
207decomposable. Use L<Unicode::Normalize> to get the final decomposition.
208
a452d459
KW
209=item B<decimal>
210
211if I<code> is a decimal digit this is its integer numeric value
212
213=item B<digit>
214
89e4a205
KW
215if I<code> represents some other digit-like number, this is its integer
216numeric value
a452d459
KW
217
218=item B<numeric>
219
220if I<code> represents a whole or rational number, this is its numeric value.
221Rational values are expressed as a string like C<1/4>.
222
223=item B<mirrored>
224
225C<Y> or C<N> designating if I<code> is mirrored in bidirectional text
226
227=item B<unicode10>
228
229name of I<code> in the Unicode 1.0 standard if one
230existed for this code point and is different from the current name
231
232=item B<comment>
233
89e4a205 234As of Unicode 6.0, this is always empty.
a452d459
KW
235
236=item B<upper>
237
06bba7d5 238is empty if there is no single code point uppercase mapping for I<code>
4f66642e 239(its uppercase mapping is itself);
a452d459
KW
240otherwise it is that mapping expressed as at least four hexdigits.
241(L</casespec()> should be used in addition to B<charinfo()>
242for case mappings when the calling program can cope with multiple code point
243mappings.)
244
245=item B<lower>
246
06bba7d5 247is empty if there is no single code point lowercase mapping for I<code>
4f66642e 248(its lowercase mapping is itself);
a452d459
KW
249otherwise it is that mapping expressed as at least four hexdigits.
250(L</casespec()> should be used in addition to B<charinfo()>
251for case mappings when the calling program can cope with multiple code point
252mappings.)
253
254=item B<title>
255
06bba7d5 256is empty if there is no single code point titlecase mapping for I<code>
4f66642e 257(its titlecase mapping is itself);
a452d459
KW
258otherwise it is that mapping expressed as at least four hexdigits.
259(L</casespec()> should be used in addition to B<charinfo()>
260for case mappings when the calling program can cope with multiple code point
261mappings.)
262
263=item B<block>
264
a18e976f 265the block I<code> belongs to (used in C<\p{Blk=...}>).
a452d459
KW
266See L</Blocks versus Scripts>.
267
268
269=item B<script>
270
a18e976f 271the script I<code> belongs to.
a452d459
KW
272See L</Blocks versus Scripts>.
273
274=back
32c16050
JH
275
276Note that you cannot do (de)composition and casing based solely on the
a452d459
KW
277I<decomposition>, I<combining>, I<lower>, I<upper>, and I<title> fields;
278you will need also the L</compexcl()>, and L</casespec()> functions.
561c79ed
JH
279
280=cut
281
e10d7780 282# NB: This function is nearly duplicated in charnames.pm
10a6ecd2
JH
283sub _getcode {
284 my $arg = shift;
285
dc0a4417 286 if ($arg =~ /^[1-9]\d*$/) {
10a6ecd2 287 return $arg;
dc0a4417 288 } elsif ($arg =~ /^(?:[Uu]\+|0[xX])?([[:xdigit:]]+)$/) {
10a6ecd2
JH
289 return hex($1);
290 }
291
292 return;
293}
294
05dbc6f8
KW
295# Populated by _num. Converts real number back to input rational
296my %real_to_rational;
297
298# To store the contents of files found on disk.
299my @BIDIS;
300my @CATEGORIES;
301my @DECOMPOSITIONS;
302my @NUMERIC_TYPES;
5c3b35c9
KW
303my %SIMPLE_LOWER;
304my %SIMPLE_TITLE;
305my %SIMPLE_UPPER;
306my %UNICODE_1_NAMES;
72fcb9f0 307my %ISO_COMMENT;
05dbc6f8 308
05dbc6f8 309sub charinfo {
a6fa416b 310
05dbc6f8
KW
311 # This function has traditionally mimicked what is in UnicodeData.txt,
312 # warts and all. This is a re-write that avoids UnicodeData.txt so that
313 # it can be removed to save disk space. Instead, this assembles
314 # information gotten by other methods that get data from various other
315 # files. It uses charnames to get the character name; and various
316 # mktables tables.
324f9e44 317
05dbc6f8 318 use feature 'unicode_strings';
a6fa416b 319
10a6ecd2
JH
320 my $arg = shift;
321 my $code = _getcode($arg);
05dbc6f8
KW
322 croak __PACKAGE__, "::charinfo: unknown code '$arg'" unless defined $code;
323
324 # Non-unicode implies undef.
325 return if $code > 0x10FFFF;
326
327 my %prop;
328 my $char = chr($code);
329
35a865d4 330 @CATEGORIES =_read_table("To/Gc.pl") unless @CATEGORIES;
05dbc6f8
KW
331 $prop{'category'} = _search(\@CATEGORIES, 0, $#CATEGORIES, $code)
332 // $utf8::SwashInfo{'ToGc'}{'missing'};
333
334 return if $prop{'category'} eq 'Cn'; # Unassigned code points are undef
335
336 $prop{'code'} = sprintf "%04X", $code;
337 $prop{'name'} = ($char =~ /\p{Cntrl}/) ? '<control>'
338 : (charnames::viacode($code) // "");
339
340 $prop{'combining'} = getCombinClass($code);
341
35a865d4 342 @BIDIS =_read_table("To/Bc.pl") unless @BIDIS;
05dbc6f8
KW
343 $prop{'bidi'} = _search(\@BIDIS, 0, $#BIDIS, $code)
344 // $utf8::SwashInfo{'ToBc'}{'missing'};
345
346 # For most code points, we can just read in "unicore/Decomposition.pl", as
347 # its contents are exactly what should be output. But that file doesn't
348 # contain the data for the Hangul syllable decompositions, which can be
94c91ffc
KW
349 # algorithmically computed, and NFD() does that, so we call NFD() for
350 # those. We can't use NFD() for everything, as it does a complete
05dbc6f8 351 # recursive decomposition, and what this function has always done is to
94c91ffc
KW
352 # return what's in UnicodeData.txt which doesn't show that recursiveness.
353 # Fortunately, the NFD() of the Hanguls doesn't have any recursion
354 # issues.
355 # Having no decomposition implies an empty field; otherwise, all but
356 # "Canonical" imply a compatible decomposition, and the type is prefixed
357 # to that, as it is in UnicodeData.txt
9abdc62b
KW
358 UnicodeVersion() unless defined $v_unicode_version;
359 if ($v_unicode_version ge v2.0.0 && $char =~ /\p{Block=Hangul_Syllables}/) {
05dbc6f8
KW
360 # The code points of the decomposition are output in standard Unicode
361 # hex format, separated by blanks.
362 $prop{'decomposition'} = join " ", map { sprintf("%04X", $_)}
94c91ffc 363 unpack "U*", NFD($char);
a6fa416b 364 }
05dbc6f8 365 else {
35a865d4 366 @DECOMPOSITIONS = _read_table("Decomposition.pl")
05dbc6f8
KW
367 unless @DECOMPOSITIONS;
368 $prop{'decomposition'} = _search(\@DECOMPOSITIONS, 0, $#DECOMPOSITIONS,
369 $code) // "";
561c79ed 370 }
05dbc6f8
KW
371
372 # Can use num() to get the numeric values, if any.
373 if (! defined (my $value = num($char))) {
374 $prop{'decimal'} = $prop{'digit'} = $prop{'numeric'} = "";
375 }
376 else {
377 if ($char =~ /\d/) {
378 $prop{'decimal'} = $prop{'digit'} = $prop{'numeric'} = $value;
379 }
380 else {
381
382 # For non-decimal-digits, we have to read in the Numeric type
383 # to distinguish them. It is not just a matter of integer vs.
384 # rational, as some whole number values are not considered digits,
385 # e.g., TAMIL NUMBER TEN.
386 $prop{'decimal'} = "";
387
35a865d4 388 @NUMERIC_TYPES =_read_table("To/Nt.pl") unless @NUMERIC_TYPES;
05dbc6f8
KW
389 if ((_search(\@NUMERIC_TYPES, 0, $#NUMERIC_TYPES, $code) // "")
390 eq 'Digit')
391 {
392 $prop{'digit'} = $prop{'numeric'} = $value;
393 }
394 else {
395 $prop{'digit'} = "";
396 $prop{'numeric'} = $real_to_rational{$value} // $value;
397 }
398 }
399 }
400
401 $prop{'mirrored'} = ($char =~ /\p{Bidi_Mirrored}/) ? 'Y' : 'N';
402
35a865d4 403 %UNICODE_1_NAMES =_read_table("To/Na1.pl", "use_hash") unless %UNICODE_1_NAMES;
5c3b35c9 404 $prop{'unicode10'} = $UNICODE_1_NAMES{$code} // "";
05dbc6f8 405
72fcb9f0
KW
406 UnicodeVersion() unless defined $v_unicode_version;
407 if ($v_unicode_version ge v6.0.0) {
408 $prop{'comment'} = "";
409 }
410 else {
411 %ISO_COMMENT = _read_table("To/Isc.pl", "use_hash") unless %ISO_COMMENT;
412 $prop{'comment'} = (defined $ISO_COMMENT{$code})
413 ? $ISO_COMMENT{$code}
414 : "";
415 }
05dbc6f8 416
35a865d4 417 %SIMPLE_UPPER = _read_table("To/Uc.pl", "use_hash") unless %SIMPLE_UPPER;
bf7fe2df 418 $prop{'upper'} = (defined $SIMPLE_UPPER{$code})
d11155ec 419 ? sprintf("%04X", $SIMPLE_UPPER{$code})
bf7fe2df 420 : "";
75e7c50b 421
35a865d4 422 %SIMPLE_LOWER = _read_table("To/Lc.pl", "use_hash") unless %SIMPLE_LOWER;
bf7fe2df 423 $prop{'lower'} = (defined $SIMPLE_LOWER{$code})
d11155ec 424 ? sprintf("%04X", $SIMPLE_LOWER{$code})
bf7fe2df 425 : "";
75e7c50b 426
35a865d4 427 %SIMPLE_TITLE = _read_table("To/Tc.pl", "use_hash") unless %SIMPLE_TITLE;
bf7fe2df 428 $prop{'title'} = (defined $SIMPLE_TITLE{$code})
d11155ec 429 ? sprintf("%04X", $SIMPLE_TITLE{$code})
bf7fe2df 430 : "";
05dbc6f8
KW
431
432 $prop{block} = charblock($code);
433 $prop{script} = charscript($code);
434 return \%prop;
561c79ed
JH
435}
436
e882dd67
JH
437sub _search { # Binary search in a [[lo,hi,prop],[...],...] table.
438 my ($table, $lo, $hi, $code) = @_;
439
440 return if $lo > $hi;
441
442 my $mid = int(($lo+$hi) / 2);
443
444 if ($table->[$mid]->[0] < $code) {
10a6ecd2 445 if ($table->[$mid]->[1] >= $code) {
e882dd67
JH
446 return $table->[$mid]->[2];
447 } else {
448 _search($table, $mid + 1, $hi, $code);
449 }
450 } elsif ($table->[$mid]->[0] > $code) {
451 _search($table, $lo, $mid - 1, $code);
452 } else {
453 return $table->[$mid]->[2];
454 }
455}
456
cb366075 457sub _read_table ($;$) {
3a12600d
KW
458
459 # Returns the contents of the mktables generated table file located at $1
cb366075
KW
460 # in the form of either an array of arrays or a hash, depending on if the
461 # optional second parameter is true (for hash return) or not. In the case
462 # of a hash return, each key is a code point, and its corresponding value
463 # is what the table gives as the code point's corresponding value. In the
464 # case of an array return, each outer array denotes a range with [0] the
465 # start point of that range; [1] the end point; and [2] the value that
466 # every code point in the range has. The hash return is useful for fast
467 # lookup when the table contains only single code point ranges. The array
468 # return takes much less memory when there are large ranges.
3a12600d 469 #
cb366075 470 # This function has the side effect of setting
3a12600d
KW
471 # $utf8::SwashInfo{$property}{'format'} to be the mktables format of the
472 # table; and
473 # $utf8::SwashInfo{$property}{'missing'} to be the value for all entries
474 # not listed in the table.
475 # where $property is the Unicode property name, preceded by 'To' for map
476 # properties., e.g., 'ToSc'.
477 #
478 # Table entries look like one of:
479 # 0000 0040 Common # [65]
480 # 00AA Latin
481
482 my $table = shift;
cb366075
KW
483 my $return_hash = shift;
484 $return_hash = 0 unless defined $return_hash;
3a12600d 485 my @return;
cb366075 486 my %return;
3a12600d 487 local $_;
d11155ec 488 my $list = do "unicore/$table";
3a12600d 489
d11155ec
KW
490 # Look up if this property requires adjustments, which we do below if it
491 # does.
492 require "unicore/Heavy.pl";
493 my $property = $table =~ s/\.pl//r;
494 $property = $utf8::file_to_swash_name{$property};
495 my $to_adjust = defined $property
496 && $utf8::SwashInfo{$property}{'format'} eq 'a';
497
498 for (split /^/m, $list) {
3a12600d
KW
499 my ($start, $end, $value) = / ^ (.+?) \t (.*?) \t (.+?)
500 \s* ( \# .* )? # Optional comment
501 $ /x;
83fd1222
KW
502 my $decimal_start = hex $start;
503 my $decimal_end = ($end eq "") ? $decimal_start : hex $end;
cb366075 504 if ($return_hash) {
83fd1222 505 foreach my $i ($decimal_start .. $decimal_end) {
d11155ec
KW
506 $return{$i} = ($to_adjust)
507 ? $value + $i - $decimal_start
508 : $value;
cb366075
KW
509 }
510 }
d11155ec
KW
511 elsif (! $to_adjust
512 && @return
513 && $return[-1][1] == $decimal_start - 1
9a96c106
KW
514 && $return[-1][2] eq $value)
515 {
516 # If this is merely extending the previous range, do just that.
517 $return[-1]->[1] = $decimal_end;
518 }
cb366075 519 else {
83fd1222 520 push @return, [ $decimal_start, $decimal_end, $value ];
cb366075 521 }
3a12600d 522 }
cb366075 523 return ($return_hash) ? %return : @return;
3a12600d
KW
524}
525
10a6ecd2
JH
526sub charinrange {
527 my ($range, $arg) = @_;
528 my $code = _getcode($arg);
529 croak __PACKAGE__, "::charinrange: unknown code '$arg'"
530 unless defined $code;
531 _search($range, 0, $#$range, $code);
532}
533
a452d459 534=head2 B<charblock()>
561c79ed 535
55d7b906 536 use Unicode::UCD 'charblock';
561c79ed
JH
537
538 my $charblock = charblock(0x41);
10a6ecd2 539 my $charblock = charblock(1234);
a452d459 540 my $charblock = charblock(0x263a);
10a6ecd2
JH
541 my $charblock = charblock("U+263a");
542
78bf21c2 543 my $range = charblock('Armenian');
10a6ecd2 544
a452d459 545With a L</code point argument> charblock() returns the I<block> the code point
430fe03d
KW
546belongs to, e.g. C<Basic Latin>. The old-style block name is returned (see
547L</Old-style versus new-style block names>).
a452d459 548If the code point is unassigned, this returns the block it would belong to if
a18e976f 549it were assigned.
10a6ecd2 550
78bf21c2
JH
551See also L</Blocks versus Scripts>.
552
18972f4b 553If supplied with an argument that can't be a code point, charblock() tries to
430fe03d
KW
554do the opposite and interpret the argument as an old-style block name. The
555return value
a18e976f
KW
556is a I<range set> with one range: an anonymous list with a single element that
557consists of another anonymous list whose first element is the first code point
558in the block, and whose second (and final) element is the final code point in
559the block. (The extra list consisting of just one element is so that the same
560program logic can be used to handle both this return, and the return from
561L</charscript()> which can have multiple ranges.) You can test whether a code
562point is in a range using the L</charinrange()> function. If the argument is
563not a known block, C<undef> is returned.
561c79ed 564
561c79ed
JH
565=cut
566
567my @BLOCKS;
10a6ecd2 568my %BLOCKS;
561c79ed 569
10a6ecd2 570sub _charblocks {
06bba7d5
KW
571
572 # Can't read from the mktables table because it loses the hyphens in the
573 # original.
561c79ed 574 unless (@BLOCKS) {
10a6ecd2 575 if (openunicode(\$BLOCKSFH, "Blocks.txt")) {
6c8d78fb 576 local $_;
ce066323 577 local $/ = "\n";
10a6ecd2 578 while (<$BLOCKSFH>) {
2796c109 579 if (/^([0-9A-F]+)\.\.([0-9A-F]+);\s+(.+)/) {
10a6ecd2
JH
580 my ($lo, $hi) = (hex($1), hex($2));
581 my $subrange = [ $lo, $hi, $3 ];
582 push @BLOCKS, $subrange;
583 push @{$BLOCKS{$3}}, $subrange;
561c79ed
JH
584 }
585 }
10a6ecd2 586 close($BLOCKSFH);
561c79ed
JH
587 }
588 }
10a6ecd2
JH
589}
590
591sub charblock {
592 my $arg = shift;
593
594 _charblocks() unless @BLOCKS;
595
596 my $code = _getcode($arg);
561c79ed 597
10a6ecd2 598 if (defined $code) {
c707cf8e
KW
599 my $result = _search(\@BLOCKS, 0, $#BLOCKS, $code);
600 return $result if defined $result;
601 return 'No_Block';
602 }
603 elsif (exists $BLOCKS{$arg}) {
604 return dclone $BLOCKS{$arg};
10a6ecd2 605 }
e882dd67
JH
606}
607
a452d459 608=head2 B<charscript()>
e882dd67 609
55d7b906 610 use Unicode::UCD 'charscript';
e882dd67
JH
611
612 my $charscript = charscript(0x41);
10a6ecd2
JH
613 my $charscript = charscript(1234);
614 my $charscript = charscript("U+263a");
e882dd67 615
78bf21c2 616 my $range = charscript('Thai');
10a6ecd2 617
a452d459
KW
618With a L</code point argument> charscript() returns the I<script> the
619code point belongs to, e.g. C<Latin>, C<Greek>, C<Han>.
49ea58c8
KW
620If the code point is unassigned or the Unicode version being used is so early
621that it doesn't have scripts, this function returns C<"Unknown">.
78bf21c2 622
eb0cc9e3 623If supplied with an argument that can't be a code point, charscript() tries
a18e976f
KW
624to do the opposite and interpret the argument as a script name. The
625return value is a I<range set>: an anonymous list of lists that contain
eb0cc9e3 626I<start-of-range>, I<end-of-range> code point pairs. You can test whether a
a18e976f
KW
627code point is in a range set using the L</charinrange()> function. If the
628argument is not a known script, C<undef> is returned.
a452d459
KW
629
630See also L</Blocks versus Scripts>.
e882dd67 631
e882dd67
JH
632=cut
633
634my @SCRIPTS;
10a6ecd2 635my %SCRIPTS;
e882dd67 636
10a6ecd2 637sub _charscripts {
49ea58c8
KW
638 unless (@SCRIPTS) {
639 UnicodeVersion() unless defined $v_unicode_version;
640 if ($v_unicode_version lt v3.1.0) {
641 push @SCRIPTS, [ 0, 0x10FFFF, 'Unknown' ];
642 }
643 else {
644 @SCRIPTS =_read_table("To/Sc.pl");
645 }
646 }
7bccef0b 647 foreach my $entry (@SCRIPTS) {
f3d50ac9 648 $entry->[2] =~ s/(_\w)/\L$1/g; # Preserve old-style casing
7bccef0b 649 push @{$SCRIPTS{$entry->[2]}}, $entry;
e882dd67 650 }
10a6ecd2
JH
651}
652
653sub charscript {
654 my $arg = shift;
655
656 _charscripts() unless @SCRIPTS;
e882dd67 657
10a6ecd2
JH
658 my $code = _getcode($arg);
659
660 if (defined $code) {
7bccef0b
KW
661 my $result = _search(\@SCRIPTS, 0, $#SCRIPTS, $code);
662 return $result if defined $result;
8079ad82 663 return $utf8::SwashInfo{'ToSc'}{'missing'};
7bccef0b
KW
664 } elsif (exists $SCRIPTS{$arg}) {
665 return dclone $SCRIPTS{$arg};
10a6ecd2 666 }
7bccef0b
KW
667
668 return;
10a6ecd2
JH
669}
670
a452d459 671=head2 B<charblocks()>
10a6ecd2 672
55d7b906 673 use Unicode::UCD 'charblocks';
10a6ecd2 674
b08cd201 675 my $charblocks = charblocks();
10a6ecd2 676
b08cd201 677charblocks() returns a reference to a hash with the known block names
a452d459 678as the keys, and the code point ranges (see L</charblock()>) as the values.
10a6ecd2 679
430fe03d
KW
680The names are in the old-style (see L</Old-style versus new-style block
681names>).
682
62b3b855
KW
683L<prop_invmap("block")|/prop_invmap()> can be used to get this same data in a
684different type of data structure.
685
78bf21c2
JH
686See also L</Blocks versus Scripts>.
687
10a6ecd2
JH
688=cut
689
690sub charblocks {
b08cd201 691 _charblocks() unless %BLOCKS;
741297c1 692 return dclone \%BLOCKS;
10a6ecd2
JH
693}
694
a452d459 695=head2 B<charscripts()>
10a6ecd2 696
55d7b906 697 use Unicode::UCD 'charscripts';
10a6ecd2 698
ea508aee 699 my $charscripts = charscripts();
10a6ecd2 700
ea508aee 701charscripts() returns a reference to a hash with the known script
a452d459 702names as the keys, and the code point ranges (see L</charscript()>) as
ea508aee 703the values.
10a6ecd2 704
62b3b855
KW
705L<prop_invmap("script")|/prop_invmap()> can be used to get this same data in a
706different type of data structure.
707
78bf21c2
JH
708See also L</Blocks versus Scripts>.
709
10a6ecd2
JH
710=cut
711
712sub charscripts {
b08cd201 713 _charscripts() unless %SCRIPTS;
741297c1 714 return dclone \%SCRIPTS;
561c79ed
JH
715}
716
a452d459 717=head2 B<charinrange()>
10a6ecd2 718
f200dd12 719In addition to using the C<\p{Blk=...}> and C<\P{Blk=...}> constructs, you
10a6ecd2 720can also test whether a code point is in the I<range> as returned by
a452d459
KW
721L</charblock()> and L</charscript()> or as the values of the hash returned
722by L</charblocks()> and L</charscripts()> by using charinrange():
10a6ecd2 723
55d7b906 724 use Unicode::UCD qw(charscript charinrange);
10a6ecd2
JH
725
726 $range = charscript('Hiragana');
e145285f 727 print "looks like hiragana\n" if charinrange($range, $codepoint);
10a6ecd2
JH
728
729=cut
730
ea508aee
JH
731my %GENERAL_CATEGORIES =
732 (
733 'L' => 'Letter',
734 'LC' => 'CasedLetter',
735 'Lu' => 'UppercaseLetter',
736 'Ll' => 'LowercaseLetter',
737 'Lt' => 'TitlecaseLetter',
738 'Lm' => 'ModifierLetter',
739 'Lo' => 'OtherLetter',
740 'M' => 'Mark',
741 'Mn' => 'NonspacingMark',
742 'Mc' => 'SpacingMark',
743 'Me' => 'EnclosingMark',
744 'N' => 'Number',
745 'Nd' => 'DecimalNumber',
746 'Nl' => 'LetterNumber',
747 'No' => 'OtherNumber',
748 'P' => 'Punctuation',
749 'Pc' => 'ConnectorPunctuation',
750 'Pd' => 'DashPunctuation',
751 'Ps' => 'OpenPunctuation',
752 'Pe' => 'ClosePunctuation',
753 'Pi' => 'InitialPunctuation',
754 'Pf' => 'FinalPunctuation',
755 'Po' => 'OtherPunctuation',
756 'S' => 'Symbol',
757 'Sm' => 'MathSymbol',
758 'Sc' => 'CurrencySymbol',
759 'Sk' => 'ModifierSymbol',
760 'So' => 'OtherSymbol',
761 'Z' => 'Separator',
762 'Zs' => 'SpaceSeparator',
763 'Zl' => 'LineSeparator',
764 'Zp' => 'ParagraphSeparator',
765 'C' => 'Other',
766 'Cc' => 'Control',
767 'Cf' => 'Format',
768 'Cs' => 'Surrogate',
769 'Co' => 'PrivateUse',
770 'Cn' => 'Unassigned',
771 );
772
773sub general_categories {
774 return dclone \%GENERAL_CATEGORIES;
775}
776
a452d459 777=head2 B<general_categories()>
ea508aee
JH
778
779 use Unicode::UCD 'general_categories';
780
781 my $categories = general_categories();
782
a452d459 783This returns a reference to a hash which has short
ea508aee
JH
784general category names (such as C<Lu>, C<Nd>, C<Zs>, C<S>) as keys and long
785names (such as C<UppercaseLetter>, C<DecimalNumber>, C<SpaceSeparator>,
786C<Symbol>) as values. The hash is reversible in case you need to go
787from the long names to the short names. The general category is the
a452d459
KW
788one returned from
789L</charinfo()> under the C<category> key.
ea508aee 790
7ef25837
KW
791The L</prop_value_aliases()> function can be used to get all the synonyms of
792the category name.
793
ea508aee
JH
794=cut
795
796my %BIDI_TYPES =
797 (
798 'L' => 'Left-to-Right',
799 'LRE' => 'Left-to-Right Embedding',
800 'LRO' => 'Left-to-Right Override',
801 'R' => 'Right-to-Left',
802 'AL' => 'Right-to-Left Arabic',
803 'RLE' => 'Right-to-Left Embedding',
804 'RLO' => 'Right-to-Left Override',
805 'PDF' => 'Pop Directional Format',
806 'EN' => 'European Number',
807 'ES' => 'European Number Separator',
808 'ET' => 'European Number Terminator',
809 'AN' => 'Arabic Number',
810 'CS' => 'Common Number Separator',
811 'NSM' => 'Non-Spacing Mark',
812 'BN' => 'Boundary Neutral',
813 'B' => 'Paragraph Separator',
814 'S' => 'Segment Separator',
815 'WS' => 'Whitespace',
816 'ON' => 'Other Neutrals',
817 );
818
a452d459 819=head2 B<bidi_types()>
ea508aee
JH
820
821 use Unicode::UCD 'bidi_types';
822
823 my $categories = bidi_types();
824
a452d459 825This returns a reference to a hash which has the short
ea508aee
JH
826bidi (bidirectional) type names (such as C<L>, C<R>) as keys and long
827names (such as C<Left-to-Right>, C<Right-to-Left>) as values. The
828hash is reversible in case you need to go from the long names to the
a452d459
KW
829short names. The bidi type is the one returned from
830L</charinfo()>
ea508aee
JH
831under the C<bidi> key. For the exact meaning of the various bidi classes
832the Unicode TR9 is recommended reading:
a452d459 833L<http://www.unicode.org/reports/tr9/>
ea508aee
JH
834(as of Unicode 5.0.0)
835
7ef25837
KW
836The L</prop_value_aliases()> function can be used to get all the synonyms of
837the bidi type name.
838
ea508aee
JH
839=cut
840
a452d459
KW
841sub bidi_types {
842 return dclone \%BIDI_TYPES;
843}
844
845=head2 B<compexcl()>
b08cd201 846
55d7b906 847 use Unicode::UCD 'compexcl';
b08cd201 848
a452d459 849 my $compexcl = compexcl(0x09dc);
b08cd201 850
2afba6a4
KW
851This routine returns C<undef> if the Unicode version being used is so early
852that it doesn't have this property. It is included for backwards
853compatibility, but as of Perl 5.12 and more modern Unicode versions, for
71a442a8
KW
854most purposes it is probably more convenient to use one of the following
855instead:
856
857 my $compexcl = chr(0x09dc) =~ /\p{Comp_Ex};
858 my $compexcl = chr(0x09dc) =~ /\p{Full_Composition_Exclusion};
859
860or even
861
862 my $compexcl = chr(0x09dc) =~ /\p{CE};
863 my $compexcl = chr(0x09dc) =~ /\p{Composition_Exclusion};
864
865The first two forms return B<true> if the L</code point argument> should not
76b05678
KW
866be produced by composition normalization. For the final two forms to return
867B<true>, it is additionally required that this fact not otherwise be
868determinable from the Unicode data base.
71a442a8
KW
869
870This routine behaves identically to the final two forms. That is,
871it does not return B<true> if the code point has a decomposition
a452d459
KW
872consisting of another single code point, nor if its decomposition starts
873with a code point whose combining class is non-zero. Code points that meet
874either of these conditions should also not be produced by composition
71a442a8
KW
875normalization, which is probably why you should use the
876C<Full_Composition_Exclusion> property instead, as shown above.
b08cd201 877
71a442a8 878The routine returns B<false> otherwise.
b08cd201
JH
879
880=cut
881
b08cd201
JH
882sub compexcl {
883 my $arg = shift;
884 my $code = _getcode($arg);
74f8133e
JH
885 croak __PACKAGE__, "::compexcl: unknown code '$arg'"
886 unless defined $code;
b08cd201 887
2afba6a4
KW
888 UnicodeVersion() unless defined $v_unicode_version;
889 return if $v_unicode_version lt v3.0.0;
890
36c2430c 891 no warnings "non_unicode"; # So works on non-Unicode code points
71a442a8 892 return chr($code) =~ /\p{Composition_Exclusion}/;
b08cd201
JH
893}
894
a452d459 895=head2 B<casefold()>
b08cd201 896
55d7b906 897 use Unicode::UCD 'casefold';
b08cd201 898
a452d459
KW
899 my $casefold = casefold(0xDF);
900 if (defined $casefold) {
901 my @full_fold_hex = split / /, $casefold->{'full'};
902 my $full_fold_string =
903 join "", map {chr(hex($_))} @full_fold_hex;
904 my @turkic_fold_hex =
905 split / /, ($casefold->{'turkic'} ne "")
906 ? $casefold->{'turkic'}
907 : $casefold->{'full'};
908 my $turkic_fold_string =
909 join "", map {chr(hex($_))} @turkic_fold_hex;
910 }
911 if (defined $casefold && $casefold->{'simple'} ne "") {
912 my $simple_fold_hex = $casefold->{'simple'};
913 my $simple_fold_string = chr(hex($simple_fold_hex));
914 }
b08cd201 915
a452d459 916This returns the (almost) locale-independent case folding of the
6329003c
KW
917character specified by the L</code point argument>. (Starting in Perl v5.16,
918the core function C<fc()> returns the C<full> mapping (described below)
919faster than this does, and for entire strings.)
b08cd201 920
6329003c 921If there is no case folding for the input code point, C<undef> is returned.
a452d459
KW
922
923If there is a case folding for that code point, a reference to a hash
b08cd201
JH
924with the following fields is returned:
925
a452d459
KW
926=over
927
928=item B<code>
929
930the input L</code point argument> expressed in hexadecimal, with leading zeros
931added if necessary to make it contain at least four hexdigits
932
933=item B<full>
934
a18e976f 935one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
936code points for the case folding for I<code>.
937Each has at least four hexdigits.
938
939=item B<simple>
940
941is empty, or is exactly one code with at least four hexdigits which can be used
942as an alternative case folding when the calling program cannot cope with the
943fold being a sequence of multiple code points. If I<full> is just one code
944point, then I<simple> equals I<full>. If there is no single code point folding
945defined for I<code>, then I<simple> is the empty string. Otherwise, it is an
946inferior, but still better-than-nothing alternative folding to I<full>.
947
948=item B<mapping>
949
950is the same as I<simple> if I<simple> is not empty, and it is the same as I<full>
951otherwise. It can be considered to be the simplest possible folding for
952I<code>. It is defined primarily for backwards compatibility.
953
954=item B<status>
b08cd201 955
a452d459
KW
956is C<C> (for C<common>) if the best possible fold is a single code point
957(I<simple> equals I<full> equals I<mapping>). It is C<S> if there are distinct
958folds, I<simple> and I<full> (I<mapping> equals I<simple>). And it is C<F> if
a18e976f
KW
959there is only a I<full> fold (I<mapping> equals I<full>; I<simple> is empty).
960Note that this
a452d459
KW
961describes the contents of I<mapping>. It is defined primarily for backwards
962compatibility.
b08cd201 963
6329003c 964For Unicode versions between 3.1 and 3.1.1 inclusive, I<status> can also be
a452d459
KW
965C<I> which is the same as C<C> but is a special case for dotted uppercase I and
966dotless lowercase i:
b08cd201 967
a452d459 968=over
b08cd201 969
a18e976f 970=item B<*> If you use this C<I> mapping
a452d459 971
a18e976f 972the result is case-insensitive,
a452d459
KW
973but dotless and dotted I's are not distinguished
974
a18e976f 975=item B<*> If you exclude this C<I> mapping
a452d459 976
a18e976f 977the result is not fully case-insensitive, but
a452d459
KW
978dotless and dotted I's are distinguished
979
980=back
981
982=item B<turkic>
983
984contains any special folding for Turkic languages. For versions of Unicode
985starting with 3.2, this field is empty unless I<code> has a different folding
986in Turkic languages, in which case it is one or more codes (separated by
a18e976f 987spaces) that, taken in order, give the code points for the case folding for
a452d459
KW
988I<code> in those languages.
989Each code has at least four hexdigits.
990Note that this folding does not maintain canonical equivalence without
991additional processing.
992
6329003c
KW
993For Unicode versions between 3.1 and 3.1.1 inclusive, this field is empty unless
994there is a
a452d459
KW
995special folding for Turkic languages, in which case I<status> is C<I>, and
996I<mapping>, I<full>, I<simple>, and I<turkic> are all equal.
997
998=back
999
1000Programs that want complete generality and the best folding results should use
1001the folding contained in the I<full> field. But note that the fold for some
1002code points will be a sequence of multiple code points.
1003
1004Programs that can't cope with the fold mapping being multiple code points can
1005use the folding contained in the I<simple> field, with the loss of some
1006generality. In Unicode 5.1, about 7% of the defined foldings have no single
1007code point folding.
1008
1009The I<mapping> and I<status> fields are provided for backwards compatibility for
1010existing programs. They contain the same values as in previous versions of
1011this function.
1012
1013Locale is not completely independent. The I<turkic> field contains results to
1014use when the locale is a Turkic language.
b08cd201
JH
1015
1016For more information about case mappings see
a452d459 1017L<http://www.unicode.org/unicode/reports/tr21>
b08cd201
JH
1018
1019=cut
1020
1021my %CASEFOLD;
1022
1023sub _casefold {
1024 unless (%CASEFOLD) {
551b6b6f 1025 if (openunicode(\$CASEFOLDFH, "CaseFolding.txt")) {
6c8d78fb 1026 local $_;
ce066323 1027 local $/ = "\n";
b08cd201 1028 while (<$CASEFOLDFH>) {
a452d459 1029 if (/^([0-9A-F]+); ([CFIST]); ([0-9A-F]+(?: [0-9A-F]+)*);/) {
b08cd201 1030 my $code = hex($1);
a452d459
KW
1031 $CASEFOLD{$code}{'code'} = $1;
1032 $CASEFOLD{$code}{'turkic'} = "" unless
1033 defined $CASEFOLD{$code}{'turkic'};
1034 if ($2 eq 'C' || $2 eq 'I') { # 'I' is only on 3.1 and
1035 # earlier Unicodes
1036 # Both entries there (I
1037 # only checked 3.1) are
1038 # the same as C, and
1039 # there are no other
1040 # entries for those
1041 # codepoints, so treat
1042 # as if C, but override
1043 # the turkic one for
1044 # 'I'.
1045 $CASEFOLD{$code}{'status'} = $2;
1046 $CASEFOLD{$code}{'full'} = $CASEFOLD{$code}{'simple'} =
1047 $CASEFOLD{$code}{'mapping'} = $3;
1048 $CASEFOLD{$code}{'turkic'} = $3 if $2 eq 'I';
1049 } elsif ($2 eq 'F') {
1050 $CASEFOLD{$code}{'full'} = $3;
1051 unless (defined $CASEFOLD{$code}{'simple'}) {
1052 $CASEFOLD{$code}{'simple'} = "";
1053 $CASEFOLD{$code}{'mapping'} = $3;
1054 $CASEFOLD{$code}{'status'} = $2;
1055 }
1056 } elsif ($2 eq 'S') {
1057
1058
1059 # There can't be a simple without a full, and simple
1060 # overrides all but full
1061
1062 $CASEFOLD{$code}{'simple'} = $3;
1063 $CASEFOLD{$code}{'mapping'} = $3;
1064 $CASEFOLD{$code}{'status'} = $2;
1065 } elsif ($2 eq 'T') {
1066 $CASEFOLD{$code}{'turkic'} = $3;
1067 } # else can't happen because only [CIFST] are possible
b08cd201
JH
1068 }
1069 }
1070 close($CASEFOLDFH);
1071 }
1072 }
1073}
1074
1075sub casefold {
1076 my $arg = shift;
1077 my $code = _getcode($arg);
74f8133e
JH
1078 croak __PACKAGE__, "::casefold: unknown code '$arg'"
1079 unless defined $code;
b08cd201
JH
1080
1081 _casefold() unless %CASEFOLD;
1082
1083 return $CASEFOLD{$code};
1084}
1085
a452d459 1086=head2 B<casespec()>
b08cd201 1087
55d7b906 1088 use Unicode::UCD 'casespec';
b08cd201 1089
a452d459 1090 my $casespec = casespec(0xFB00);
b08cd201 1091
a452d459
KW
1092This returns the potentially locale-dependent case mappings of the L</code point
1093argument>. The mappings may be longer than a single code point (which the basic
1094Unicode case mappings as returned by L</charinfo()> never are).
b08cd201 1095
a452d459
KW
1096If there are no case mappings for the L</code point argument>, or if all three
1097possible mappings (I<lower>, I<title> and I<upper>) result in single code
a18e976f 1098points and are locale independent and unconditional, C<undef> is returned
5d8e6e41
KW
1099(which means that the case mappings, if any, for the code point are those
1100returned by L</charinfo()>).
a452d459
KW
1101
1102Otherwise, a reference to a hash giving the mappings (or a reference to a hash
5d8e6e41
KW
1103of such hashes, explained below) is returned with the following keys and their
1104meanings:
a452d459
KW
1105
1106The keys in the bottom layer hash with the meanings of their values are:
1107
1108=over
1109
1110=item B<code>
1111
1112the input L</code point argument> expressed in hexadecimal, with leading zeros
1113added if necessary to make it contain at least four hexdigits
1114
1115=item B<lower>
1116
a18e976f 1117one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
1118code points for the lower case of I<code>.
1119Each has at least four hexdigits.
1120
1121=item B<title>
b08cd201 1122
a18e976f 1123one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
1124code points for the title case of I<code>.
1125Each has at least four hexdigits.
b08cd201 1126
d2da20e3 1127=item B<upper>
b08cd201 1128
a18e976f 1129one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
1130code points for the upper case of I<code>.
1131Each has at least four hexdigits.
1132
1133=item B<condition>
1134
1135the conditions for the mappings to be valid.
a18e976f 1136If C<undef>, the mappings are always valid.
a452d459
KW
1137When defined, this field is a list of conditions,
1138all of which must be true for the mappings to be valid.
1139The list consists of one or more
1140I<locales> (see below)
1141and/or I<contexts> (explained in the next paragraph),
1142separated by spaces.
1143(Other than as used to separate elements, spaces are to be ignored.)
1144Case distinctions in the condition list are not significant.
82c0b05b 1145Conditions preceded by "NON_" represent the negation of the condition.
b08cd201 1146
a452d459
KW
1147A I<context> is one of those defined in the Unicode standard.
1148For Unicode 5.1, they are defined in Section 3.13 C<Default Case Operations>
1149available at
5d8e6e41
KW
1150L<http://www.unicode.org/versions/Unicode5.1.0/>.
1151These are for context-sensitive casing.
f499c386 1152
a452d459
KW
1153=back
1154
5d8e6e41 1155The hash described above is returned for locale-independent casing, where
a18e976f 1156at least one of the mappings has length longer than one. If C<undef> is
5d8e6e41
KW
1157returned, the code point may have mappings, but if so, all are length one,
1158and are returned by L</charinfo()>.
1159Note that when this function does return a value, it will be for the complete
1160set of mappings for a code point, even those whose length is one.
1161
1162If there are additional casing rules that apply only in certain locales,
1163an additional key for each will be defined in the returned hash. Each such key
1164will be its locale name, defined as a 2-letter ISO 3166 country code, possibly
1165followed by a "_" and a 2-letter ISO language code (possibly followed by a "_"
1166and a variant code). You can find the lists of all possible locales, see
1167L<Locale::Country> and L<Locale::Language>.
89e4a205 1168(In Unicode 6.0, the only locales returned by this function
a452d459 1169are C<lt>, C<tr>, and C<az>.)
b08cd201 1170
5d8e6e41
KW
1171Each locale key is a reference to a hash that has the form above, and gives
1172the casing rules for that particular locale, which take precedence over the
1173locale-independent ones when in that locale.
1174
1175If the only casing for a code point is locale-dependent, then the returned
1176hash will not have any of the base keys, like C<code>, C<upper>, etc., but
1177will contain only locale keys.
1178
b08cd201 1179For more information about case mappings see
a452d459 1180L<http://www.unicode.org/unicode/reports/tr21/>
b08cd201
JH
1181
1182=cut
1183
1184my %CASESPEC;
1185
1186sub _casespec {
1187 unless (%CASESPEC) {
551b6b6f 1188 if (openunicode(\$CASESPECFH, "SpecialCasing.txt")) {
6c8d78fb 1189 local $_;
ce066323 1190 local $/ = "\n";
b08cd201
JH
1191 while (<$CASESPECFH>) {
1192 if (/^([0-9A-F]+); ([0-9A-F]+(?: [0-9A-F]+)*)?; ([0-9A-F]+(?: [0-9A-F]+)*)?; ([0-9A-F]+(?: [0-9A-F]+)*)?; (\w+(?: \w+)*)?/) {
f499c386
JH
1193 my ($hexcode, $lower, $title, $upper, $condition) =
1194 ($1, $2, $3, $4, $5);
1195 my $code = hex($hexcode);
1196 if (exists $CASESPEC{$code}) {
1197 if (exists $CASESPEC{$code}->{code}) {
1198 my ($oldlower,
1199 $oldtitle,
1200 $oldupper,
1201 $oldcondition) =
1202 @{$CASESPEC{$code}}{qw(lower
1203 title
1204 upper
1205 condition)};
822ebcc8
JH
1206 if (defined $oldcondition) {
1207 my ($oldlocale) =
f499c386 1208 ($oldcondition =~ /^([a-z][a-z](?:_\S+)?)/);
f499c386
JH
1209 delete $CASESPEC{$code};
1210 $CASESPEC{$code}->{$oldlocale} =
1211 { code => $hexcode,
1212 lower => $oldlower,
1213 title => $oldtitle,
1214 upper => $oldupper,
1215 condition => $oldcondition };
f499c386
JH
1216 }
1217 }
1218 my ($locale) =
1219 ($condition =~ /^([a-z][a-z](?:_\S+)?)/);
1220 $CASESPEC{$code}->{$locale} =
1221 { code => $hexcode,
1222 lower => $lower,
1223 title => $title,
1224 upper => $upper,
1225 condition => $condition };
1226 } else {
1227 $CASESPEC{$code} =
1228 { code => $hexcode,
1229 lower => $lower,
1230 title => $title,
1231 upper => $upper,
1232 condition => $condition };
1233 }
b08cd201
JH
1234 }
1235 }
1236 close($CASESPECFH);
1237 }
1238 }
1239}
1240
1241sub casespec {
1242 my $arg = shift;
1243 my $code = _getcode($arg);
74f8133e
JH
1244 croak __PACKAGE__, "::casespec: unknown code '$arg'"
1245 unless defined $code;
b08cd201
JH
1246
1247 _casespec() unless %CASESPEC;
1248
741297c1 1249 return ref $CASESPEC{$code} ? dclone $CASESPEC{$code} : $CASESPEC{$code};
b08cd201
JH
1250}
1251
a452d459 1252=head2 B<namedseq()>
a2bd7410
JH
1253
1254 use Unicode::UCD 'namedseq';
1255
1256 my $namedseq = namedseq("KATAKANA LETTER AINU P");
1257 my @namedseq = namedseq("KATAKANA LETTER AINU P");
1258 my %namedseq = namedseq();
1259
1260If used with a single argument in a scalar context, returns the string
a18e976f 1261consisting of the code points of the named sequence, or C<undef> if no
a2bd7410 1262named sequence by that name exists. If used with a single argument in
956cae9a
KW
1263a list context, it returns the list of the ordinals of the code points. If used
1264with no
a2bd7410
JH
1265arguments in a list context, returns a hash with the names of the
1266named sequences as the keys and the named sequences as strings as
a18e976f 1267the values. Otherwise, it returns C<undef> or an empty list depending
a2bd7410
JH
1268on the context.
1269
a452d459
KW
1270This function only operates on officially approved (not provisional) named
1271sequences.
a2bd7410 1272
27f853a0
KW
1273Note that as of Perl 5.14, C<\N{KATAKANA LETTER AINU P}> will insert the named
1274sequence into double-quoted strings, and C<charnames::string_vianame("KATAKANA
1275LETTER AINU P")> will return the same string this function does, but will also
1276operate on character names that aren't named sequences, without you having to
1277know which are which. See L<charnames>.
1278
a2bd7410
JH
1279=cut
1280
1281my %NAMEDSEQ;
1282
1283sub _namedseq {
1284 unless (%NAMEDSEQ) {
98ef7649 1285 if (openunicode(\$NAMEDSEQFH, "Name.pl")) {
a2bd7410 1286 local $_;
ce066323 1287 local $/ = "\n";
a2bd7410 1288 while (<$NAMEDSEQFH>) {
98ef7649
KW
1289 if (/^ [0-9A-F]+ \ /x) {
1290 chomp;
1291 my ($sequence, $name) = split /\t/;
1292 my @s = map { chr(hex($_)) } split(' ', $sequence);
1293 $NAMEDSEQ{$name} = join("", @s);
a2bd7410
JH
1294 }
1295 }
1296 close($NAMEDSEQFH);
1297 }
1298 }
1299}
1300
1301sub namedseq {
98ef7649
KW
1302
1303 # Use charnames::string_vianame() which now returns this information,
1304 # unless the caller wants the hash returned, in which case we read it in,
1305 # and thereafter use it instead of calling charnames, as it is faster.
1306
a2bd7410
JH
1307 my $wantarray = wantarray();
1308 if (defined $wantarray) {
1309 if ($wantarray) {
1310 if (@_ == 0) {
98ef7649 1311 _namedseq() unless %NAMEDSEQ;
a2bd7410
JH
1312 return %NAMEDSEQ;
1313 } elsif (@_ == 1) {
98ef7649
KW
1314 my $s;
1315 if (%NAMEDSEQ) {
1316 $s = $NAMEDSEQ{ $_[0] };
1317 }
1318 else {
1319 $s = charnames::string_vianame($_[0]);
1320 }
a2bd7410
JH
1321 return defined $s ? map { ord($_) } split('', $s) : ();
1322 }
1323 } elsif (@_ == 1) {
98ef7649
KW
1324 return $NAMEDSEQ{ $_[0] } if %NAMEDSEQ;
1325 return charnames::string_vianame($_[0]);
a2bd7410
JH
1326 }
1327 }
1328 return;
1329}
1330
7319f91d
KW
1331my %NUMERIC;
1332
1333sub _numeric {
35a865d4 1334 my @numbers = _read_table("To/Nv.pl");
98025745
KW
1335 foreach my $entry (@numbers) {
1336 my ($start, $end, $value) = @$entry;
1337
05dbc6f8
KW
1338 # If value contains a slash, convert to decimal, add a reverse hash
1339 # used by charinfo.
98025745
KW
1340 if ((my @rational = split /\//, $value) == 2) {
1341 my $real = $rational[0] / $rational[1];
05dbc6f8 1342 $real_to_rational{$real} = $value;
98025745 1343 $value = $real;
98025745 1344
4f143a72
KW
1345 # Should only be single element, but just in case...
1346 for my $i ($start .. $end) {
1347 $NUMERIC{$i} = $value;
1348 }
1349 }
1350 else {
1351 # The values require adjusting, as is in 'a' format
1352 for my $i ($start .. $end) {
1353 $NUMERIC{$i} = $value + $i - $start;
1354 }
7319f91d 1355 }
7319f91d 1356 }
2dc5eb26
KW
1357
1358 # Decided unsafe to use these that aren't officially part of the Unicode
1359 # standard.
1360 #use Math::Trig;
1361 #my $pi = acos(-1.0);
98025745 1362 #$NUMERIC{0x03C0} = $pi;
7319f91d
KW
1363
1364 # Euler's constant, not to be confused with Euler's number
98025745 1365 #$NUMERIC{0x2107} = 0.57721566490153286060651209008240243104215933593992;
7319f91d
KW
1366
1367 # Euler's number
98025745 1368 #$NUMERIC{0x212F} = 2.7182818284590452353602874713526624977572;
2dc5eb26 1369
7319f91d
KW
1370 return;
1371}
1372
1373=pod
1374
67592e11 1375=head2 B<num()>
7319f91d 1376
eefd7bc2
KW
1377 use Unicode::UCD 'num';
1378
1379 my $val = num("123");
1380 my $one_quarter = num("\N{VULGAR FRACTION 1/4}");
1381
7319f91d
KW
1382C<num> returns the numeric value of the input Unicode string; or C<undef> if it
1383doesn't think the entire string has a completely valid, safe numeric value.
1384
1385If the string is just one character in length, the Unicode numeric value
1386is returned if it has one, or C<undef> otherwise. Note that this need
1387not be a whole number. C<num("\N{TIBETAN DIGIT HALF ZERO}")>, for
2dc5eb26
KW
1388example returns -0.5.
1389
1390=cut
7319f91d 1391
2dc5eb26
KW
1392#A few characters to which Unicode doesn't officially
1393#assign a numeric value are considered numeric by C<num>.
1394#These are:
1395
1396# EULER CONSTANT 0.5772... (this is NOT Euler's number)
1397# SCRIPT SMALL E 2.71828... (this IS Euler's number)
1398# GREEK SMALL LETTER PI 3.14159...
1399
1400=pod
7319f91d
KW
1401
1402If the string is more than one character, C<undef> is returned unless
8bb4c8e2 1403all its characters are decimal digits (that is, they would match C<\d+>),
7319f91d
KW
1404from the same script. For example if you have an ASCII '0' and a Bengali
1405'3', mixed together, they aren't considered a valid number, and C<undef>
1406is returned. A further restriction is that the digits all have to be of
1407the same form. A half-width digit mixed with a full-width one will
1408return C<undef>. The Arabic script has two sets of digits; C<num> will
1409return C<undef> unless all the digits in the string come from the same
1410set.
1411
1412C<num> errs on the side of safety, and there may be valid strings of
1413decimal digits that it doesn't recognize. Note that Unicode defines
1414a number of "digit" characters that aren't "decimal digit" characters.
a278d14b 1415"Decimal digits" have the property that they have a positional value, i.e.,
7319f91d
KW
1416there is a units position, a 10's position, a 100's, etc, AND they are
1417arranged in Unicode in blocks of 10 contiguous code points. The Chinese
1418digits, for example, are not in such a contiguous block, and so Unicode
1419doesn't view them as decimal digits, but merely digits, and so C<\d> will not
1420match them. A single-character string containing one of these digits will
1421have its decimal value returned by C<num>, but any longer string containing
1422only these digits will return C<undef>.
1423
a278d14b
KW
1424Strings of multiple sub- and superscripts are not recognized as numbers. You
1425can use either of the compatibility decompositions in Unicode::Normalize to
7319f91d
KW
1426change these into digits, and then call C<num> on the result.
1427
1428=cut
1429
1430# To handle sub, superscripts, this could if called in list context,
1431# consider those, and return the <decomposition> type in the second
1432# array element.
1433
1434sub num {
1435 my $string = $_[0];
1436
1437 _numeric unless %NUMERIC;
1438
1439 my $length = length($string);
98025745 1440 return $NUMERIC{ord($string)} if $length == 1;
7319f91d
KW
1441 return if $string =~ /\D/;
1442 my $first_ord = ord(substr($string, 0, 1));
98025745 1443 my $value = $NUMERIC{$first_ord};
5522af1c
KW
1444
1445 # To be a valid decimal number, it should be in a block of 10 consecutive
1446 # characters, whose values are 0, 1, 2, ... 9. Therefore this digit's
1447 # value is its offset in that block from the character that means zero.
7319f91d
KW
1448 my $zero_ord = $first_ord - $value;
1449
5522af1c
KW
1450 # Unicode 6.0 instituted the rule that only digits in a consecutive
1451 # block of 10 would be considered decimal digits. If this is an earlier
1452 # release, we verify that this first character is a member of such a
1453 # block. That is, that the block of characters surrounding this one
1454 # consists of all \d characters whose numeric values are the expected
1455 # ones.
1456 UnicodeVersion() unless defined $v_unicode_version;
1457 if ($v_unicode_version lt v6.0.0) {
1458 for my $i (0 .. 9) {
1459 my $ord = $zero_ord + $i;
1460 return unless chr($ord) =~ /\d/;
1461 my $numeric = $NUMERIC{$ord};
1462 return unless defined $numeric;
1463 return unless $numeric == $i;
1464 }
1465 }
1466
7319f91d 1467 for my $i (1 .. $length -1) {
5522af1c
KW
1468
1469 # Here we know either by verifying, or by fact of the first character
1470 # being a \d in Unicode 6.0 or later, that any character between the
1471 # character that means 0, and 9 positions above it must be \d, and
1472 # must have its value correspond to its offset from the zero. Any
1473 # characters outside these 10 do not form a legal number for this
1474 # function.
7319f91d
KW
1475 my $ord = ord(substr($string, $i, 1));
1476 my $digit = $ord - $zero_ord;
1477 return unless $digit >= 0 && $digit <= 9;
1478 $value = $value * 10 + $digit;
1479 }
5522af1c 1480
7319f91d
KW
1481 return $value;
1482}
1483
7ef25837
KW
1484=pod
1485
1486=head2 B<prop_aliases()>
1487
1488 use Unicode::UCD 'prop_aliases';
1489
1490 my ($short_name, $full_name, @other_names) = prop_aliases("space");
1491 my $same_full_name = prop_aliases("Space"); # Scalar context
1492 my ($same_short_name) = prop_aliases("Space"); # gets 0th element
1493 print "The full name is $full_name\n";
1494 print "The short name is $short_name\n";
1495 print "The other aliases are: ", join(", ", @other_names), "\n";
1496
1497 prints:
1498 The full name is White_Space
1499 The short name is WSpace
1500 The other aliases are: Space
1501
1502Most Unicode properties have several synonymous names. Typically, there is at
1503least a short name, convenient to type, and a long name that more fully
1504describes the property, and hence is more easily understood.
1505
1506If you know one name for a Unicode property, you can use C<prop_aliases> to find
1507either the long name (when called in scalar context), or a list of all of the
1508names, somewhat ordered so that the short name is in the 0th element, the long
1509name in the next element, and any other synonyms are in the remaining
1510elements, in no particular order.
1511
1512The long name is returned in a form nicely capitalized, suitable for printing.
1513
1514The input parameter name is loosely matched, which means that white space,
1515hyphens, and underscores are ignored (except for the trailing underscore in
1516the old_form grandfathered-in C<"L_">, which is better written as C<"LC">, and
1517both of which mean C<General_Category=Cased Letter>).
1518
1519If the name is unknown, C<undef> is returned (or an empty list in list
1520context). Note that Perl typically recognizes property names in regular
1521expressions with an optional C<"Is_>" (with or without the underscore)
1522prefixed to them, such as C<\p{isgc=punct}>. This function does not recognize
1523those in the input, returning C<undef>. Nor are they included in the output
1524as possible synonyms.
1525
1526C<prop_aliases> does know about the Perl extensions to Unicode properties,
1527such as C<Any> and C<XPosixAlpha>, and the single form equivalents to Unicode
1528properties such as C<XDigit>, C<Greek>, C<In_Greek>, and C<Is_Greek>. The
1529final example demonstrates that the C<"Is_"> prefix is recognized for these
1530extensions; it is needed to resolve ambiguities. For example,
1531C<prop_aliases('lc')> returns the list C<(lc, Lowercase_Mapping)>, but
1532C<prop_aliases('islc')> returns C<(Is_LC, Cased_Letter)>. This is
1533because C<islc> is a Perl extension which is short for
1534C<General_Category=Cased Letter>. The lists returned for the Perl extensions
1535will not include the C<"Is_"> prefix (whether or not the input had it) unless
1536needed to resolve ambiguities, as shown in the C<"islc"> example, where the
1537returned list had one element containing C<"Is_">, and the other without.
1538
1539It is also possible for the reverse to happen: C<prop_aliases('isc')> returns
1540the list C<(isc, ISO_Comment)>; whereas C<prop_aliases('c')> returns
1541C<(C, Other)> (the latter being a Perl extension meaning
ee94c7d1
KW
1542C<General_Category=Other>.
1543L<perluniprops/Properties accessible through Unicode::UCD> lists the available
1544forms, including which ones are discouraged from use.
7ef25837
KW
1545
1546Those discouraged forms are accepted as input to C<prop_aliases>, but are not
1547returned in the lists. C<prop_aliases('isL&')> and C<prop_aliases('isL_')>,
1548which are old synonyms for C<"Is_LC"> and should not be used in new code, are
1549examples of this. These both return C<(Is_LC, Cased_Letter)>. Thus this
1550function allows you to take a discourarged form, and find its acceptable
1551alternatives. The same goes with single-form Block property equivalences.
1552Only the forms that begin with C<"In_"> are not discouraged; if you pass
1553C<prop_aliases> a discouraged form, you will get back the equivalent ones that
1554begin with C<"In_">. It will otherwise look like a new-style block name (see.
1555L</Old-style versus new-style block names>).
1556
1557C<prop_aliases> does not know about any user-defined properties, and will
1558return C<undef> if called with one of those. Likewise for Perl internal
1559properties, with the exception of "Perl_Decimal_Digit" which it does know
1560about (and which is documented below in L</prop_invmap()>).
1561
1562=cut
1563
1564# It may be that there are use cases where the discouraged forms should be
1565# returned. If that comes up, an optional boolean second parameter to the
1566# function could be created, for example.
1567
1568# These are created by mktables for this routine and stored in unicore/UCD.pl
1569# where their structures are described.
1570our %string_property_loose_to_name;
1571our %ambiguous_names;
1572our %loose_perlprop_to_name;
1573our %prop_aliases;
1574
1575sub prop_aliases ($) {
1576 my $prop = $_[0];
1577 return unless defined $prop;
1578
1579 require "unicore/UCD.pl";
1580 require "unicore/Heavy.pl";
1581 require "utf8_heavy.pl";
1582
1583 # The property name may be loosely or strictly matched; we don't know yet.
1584 # But both types use lower-case.
1585 $prop = lc $prop;
1586
1587 # It is loosely matched if its lower case isn't known to be strict.
1588 my $list_ref;
1589 if (! exists $utf8::stricter_to_file_of{$prop}) {
1590 my $loose = utf8::_loose_name($prop);
1591
1592 # There is a hash that converts from any loose name to its standard
1593 # form, mapping all synonyms for a name to one name that can be used
1594 # as a key into another hash. The whole concept is for memory
1595 # savings, as the second hash doesn't have to have all the
1596 # combinations. Actually, there are two hashes that do the
1597 # converstion. One is used in utf8_heavy.pl (stored in Heavy.pl) for
1598 # looking up properties matchable in regexes. This function needs to
1599 # access string properties, which aren't available in regexes, so a
1600 # second conversion hash is made for them (stored in UCD.pl). Look in
1601 # the string one now, as the rest can have an optional 'is' prefix,
1602 # which these don't.
1603 if (exists $string_property_loose_to_name{$loose}) {
1604
1605 # Convert to its standard loose name.
1606 $prop = $string_property_loose_to_name{$loose};
1607 }
1608 else {
1609 my $retrying = 0; # bool. ? Has an initial 'is' been stripped
1610 RETRY:
1611 if (exists $utf8::loose_property_name_of{$loose}
1612 && (! $retrying
1613 || ! exists $ambiguous_names{$loose}))
1614 {
1615 # Found an entry giving the standard form. We don't get here
1616 # (in the test above) when we've stripped off an
1617 # 'is' and the result is an ambiguous name. That is because
1618 # these are official Unicode properties (though Perl can have
1619 # an optional 'is' prefix meaning the official property), and
1620 # all ambiguous cases involve a Perl single-form extension
1621 # for the gc, script, or block properties, and the stripped
1622 # 'is' means that they mean one of those, and not one of
1623 # these
1624 $prop = $utf8::loose_property_name_of{$loose};
1625 }
1626 elsif (exists $loose_perlprop_to_name{$loose}) {
1627
1628 # This hash is specifically for this function to list Perl
1629 # extensions that aren't in the earlier hashes. If there is
1630 # only one element, the short and long names are identical.
1631 # Otherwise the form is already in the same form as
1632 # %prop_aliases, which is handled at the end of the function.
1633 $list_ref = $loose_perlprop_to_name{$loose};
1634 if (@$list_ref == 1) {
1635 my @list = ($list_ref->[0], $list_ref->[0]);
1636 $list_ref = \@list;
1637 }
1638 }
1639 elsif (! exists $utf8::loose_to_file_of{$loose}) {
1640
1641 # loose_to_file_of is a complete list of loose names. If not
1642 # there, the input is unknown.
1643 return;
1644 }
1645 else {
1646
1647 # Here we found the name but not its aliases, so it has to
1648 # exist. This means it must be one of the Perl single-form
1649 # extensions. First see if it is for a property-value
1650 # combination in one of the following properties.
1651 my @list;
1652 foreach my $property ("gc", "script") {
1653 @list = prop_value_aliases($property, $loose);
1654 last if @list;
1655 }
1656 if (@list) {
1657
1658 # Here, it is one of those property-value combination
1659 # single-form synonyms. There are ambiguities with some
1660 # of these. Check against the list for these, and adjust
1661 # if necessary.
1662 for my $i (0 .. @list -1) {
1663 if (exists $ambiguous_names
1664 {utf8::_loose_name(lc $list[$i])})
1665 {
1666 # The ambiguity is resolved by toggling whether or
1667 # not it has an 'is' prefix
1668 $list[$i] =~ s/^Is_// or $list[$i] =~ s/^/Is_/;
1669 }
1670 }
1671 return @list;
1672 }
1673
1674 # Here, it wasn't one of the gc or script single-form
1675 # extensions. It could be a block property single-form
1676 # extension. An 'in' prefix definitely means that, and should
2a4f2769
KW
1677 # be looked up without the prefix. However, starting in
1678 # Unicode 6.1, we have to special case 'indic...', as there
1679 # is a property that begins with that name. We shouldn't
1680 # strip the 'in' from that. I'm (khw) generalizing this to
1681 # 'indic' instead of the single property, because I suspect
1682 # that others of this class may come along in the future.
1683 # However, this could backfire and a block created whose name
1684 # begins with 'dic...', and we would want to strip the 'in'.
1685 # At which point this would have to be tweaked.
1686 my $began_with_in = $loose =~ s/^in(?!dic)//;
7ef25837
KW
1687 @list = prop_value_aliases("block", $loose);
1688 if (@list) {
1689 map { $_ =~ s/^/In_/ } @list;
1690 return @list;
1691 }
1692
1693 # Here still haven't found it. The last opportunity for it
1694 # being valid is only if it began with 'is'. We retry without
1695 # the 'is', setting a flag to that effect so that we don't
1696 # accept things that begin with 'isis...'
1697 if (! $retrying && ! $began_with_in && $loose =~ s/^is//) {
1698 $retrying = 1;
1699 goto RETRY;
1700 }
1701
1702 # Here, didn't find it. Since it was in %loose_to_file_of, we
1703 # should have been able to find it.
1704 carp __PACKAGE__, "::prop_aliases: Unexpectedly could not find '$prop'. Send bug report to perlbug\@perl.org";
1705 return;
1706 }
1707 }
1708 }
1709
1710 if (! $list_ref) {
1711 # Here, we have set $prop to a standard form name of the input. Look
1712 # it up in the structure created by mktables for this purpose, which
1713 # contains both strict and loosely matched properties. Avoid
1714 # autovivifying.
1715 $list_ref = $prop_aliases{$prop} if exists $prop_aliases{$prop};
1716 return unless $list_ref;
1717 }
1718
1719 # The full name is in element 1.
1720 return $list_ref->[1] unless wantarray;
1721
1722 return @{dclone $list_ref};
1723}
1724
1725=pod
1726
1727=head2 B<prop_value_aliases()>
1728
1729 use Unicode::UCD 'prop_value_aliases';
1730
1731 my ($short_name, $full_name, @other_names)
1732 = prop_value_aliases("Gc", "Punct");
1733 my $same_full_name = prop_value_aliases("Gc", "P"); # Scalar cntxt
1734 my ($same_short_name) = prop_value_aliases("Gc", "P"); # gets 0th
1735 # element
1736 print "The full name is $full_name\n";
1737 print "The short name is $short_name\n";
1738 print "The other aliases are: ", join(", ", @other_names), "\n";
1739
1740 prints:
1741 The full name is Punctuation
1742 The short name is P
1743 The other aliases are: Punct
1744
1745Some Unicode properties have a restricted set of legal values. For example,
1746all binary properties are restricted to just C<true> or C<false>; and there
1747are only a few dozen possible General Categories.
1748
1749For such properties, there are usually several synonyms for each possible
1750value. For example, in binary properties, I<truth> can be represented by any of
1751the strings "Y", "Yes", "T", or "True"; and the General Category
1752"Punctuation" by that string, or "Punct", or simply "P".
1753
1754Like property names, there is typically at least a short name for each such
1755property-value, and a long name. If you know any name of the property-value,
1756you can use C<prop_value_aliases>() to get the long name (when called in
1757scalar context), or a list of all the names, with the short name in the 0th
1758element, the long name in the next element, and any other synonyms in the
1759remaining elements, in no particular order, except that any all-numeric
1760synonyms will be last.
1761
1762The long name is returned in a form nicely capitalized, suitable for printing.
1763
1764Case, white space, hyphens, and underscores are ignored in the input parameters
1765(except for the trailing underscore in the old-form grandfathered-in general
1766category property value C<"L_">, which is better written as C<"LC">).
1767
1768If either name is unknown, C<undef> is returned. Note that Perl typically
1769recognizes property names in regular expressions with an optional C<"Is_>"
1770(with or without the underscore) prefixed to them, such as C<\p{isgc=punct}>.
1771This function does not recognize those in the property parameter, returning
1772C<undef>.
1773
1774If called with a property that doesn't have synonyms for its values, it
1775returns the input value, possibly normalized with capitalization and
1776underscores.
1777
1778For the block property, new-style block names are returned (see
1779L</Old-style versus new-style block names>).
1780
1781To find the synonyms for single-forms, such as C<\p{Any}>, use
1782L</prop_aliases()> instead.
1783
1784C<prop_value_aliases> does not know about any user-defined properties, and
1785will return C<undef> if called with one of those.
1786
1787=cut
1788
1789# These are created by mktables for this routine and stored in unicore/UCD.pl
1790# where their structures are described.
1791our %loose_to_standard_value;
1792our %prop_value_aliases;
1793
1794sub prop_value_aliases ($$) {
1795 my ($prop, $value) = @_;
1796 return unless defined $prop && defined $value;
1797
1798 require "unicore/UCD.pl";
1799 require "utf8_heavy.pl";
1800
1801 # Find the property name synonym that's used as the key in other hashes,
1802 # which is element 0 in the returned list.
1803 ($prop) = prop_aliases($prop);
1804 return if ! $prop;
1805 $prop = utf8::_loose_name(lc $prop);
1806
1807 # Here is a legal property, but the hash below (created by mktables for
1808 # this purpose) only knows about the properties that have a very finite
1809 # number of potential values, that is not ones whose value could be
1810 # anything, like most (if not all) string properties. These don't have
1811 # synonyms anyway. Simply return the input. For example, there is no
1812 # synonym for ('Uppercase_Mapping', A').
1813 return $value if ! exists $prop_value_aliases{$prop};
1814
1815 # The value name may be loosely or strictly matched; we don't know yet.
1816 # But both types use lower-case.
1817 $value = lc $value;
1818
1819 # If the name isn't found under loose matching, it certainly won't be
1820 # found under strict
1821 my $loose_value = utf8::_loose_name($value);
1822 return unless exists $loose_to_standard_value{"$prop=$loose_value"};
1823
1824 # Similarly if the combination under loose matching doesn't exist, it
1825 # won't exist under strict.
1826 my $standard_value = $loose_to_standard_value{"$prop=$loose_value"};
1827 return unless exists $prop_value_aliases{$prop}{$standard_value};
1828
1829 # Here we did find a combination under loose matching rules. But it could
1830 # be that is a strict property match that shouldn't have matched.
1831 # %prop_value_aliases is set up so that the strict matches will appear as
1832 # if they were in loose form. Thus, if the non-loose version is legal,
1833 # we're ok, can skip the further check.
1834 if (! exists $utf8::stricter_to_file_of{"$prop=$value"}
1835
1836 # We're also ok and skip the further check if value loosely matches.
1837 # mktables has verified that no strict name under loose rules maps to
1838 # an existing loose name. This code relies on the very limited
1839 # circumstances that strict names can be here. Strict name matching
1840 # happens under two conditions:
1841 # 1) when the name begins with an underscore. But this function
1842 # doesn't accept those, and %prop_value_aliases doesn't have
1843 # them.
1844 # 2) When the values are numeric, in which case we need to look
1845 # further, but their squeezed-out loose values will be in
1846 # %stricter_to_file_of
1847 && exists $utf8::stricter_to_file_of{"$prop=$loose_value"})
1848 {
1849 # The only thing that's legal loosely under strict is that can have an
1850 # underscore between digit pairs XXX
1851 while ($value =~ s/(\d)_(\d)/$1$2/g) {}
1852 return unless exists $utf8::stricter_to_file_of{"$prop=$value"};
1853 }
1854
1855 # Here, we know that the combination exists. Return it.
1856 my $list_ref = $prop_value_aliases{$prop}{$standard_value};
1857 if (@$list_ref > 1) {
1858 # The full name is in element 1.
1859 return $list_ref->[1] unless wantarray;
1860
1861 return @{dclone $list_ref};
1862 }
1863
1864 return $list_ref->[0] unless wantarray;
1865
1866 # Only 1 element means that it repeats
1867 return ( $list_ref->[0], $list_ref->[0] );
1868}
7319f91d 1869
681d705c
KW
1870# All 1 bits is the largest possible UV.
1871$Unicode::UCD::MAX_CP = ~0;
1872
1873=pod
1874
1875=head2 B<prop_invlist()>
1876
1877C<prop_invlist> returns an inversion list (described below) that defines all the
1878code points for the binary Unicode property (or "property=value" pair) given
1879by the input parameter string:
1880
1881 use feature 'say';
1882 use Unicode::UCD 'prop_invlist';
1883 say join ", ", prop_invlist("Any");
1884
1885 prints:
1886 0, 1114112
1887
1888An empty list is returned if the input is unknown; the number of elements in
1889the list is returned if called in scalar context.
1890
1891L<perluniprops|perluniprops/Properties accessible through \p{} and \P{}> gives
1892the list of properties that this function accepts, as well as all the possible
1893forms for them (including with the optional "Is_" prefixes). (Except this
1894function doesn't accept any Perl-internal properties, some of which are listed
1895there.) This function uses the same loose or tighter matching rules for
1896resolving the input property's name as is done for regular expressions. These
1897are also specified in L<perluniprops|perluniprops/Properties accessible
1898through \p{} and \P{}>. Examples of using the "property=value" form are:
1899
1900 say join ", ", prop_invlist("Script=Shavian");
1901
1902 prints:
1903 66640, 66688
1904
1905 say join ", ", prop_invlist("ASCII_Hex_Digit=No");
1906
1907 prints:
1908 0, 48, 58, 65, 71, 97, 103
1909
1910 say join ", ", prop_invlist("ASCII_Hex_Digit=Yes");
1911
1912 prints:
1913 48, 58, 65, 71, 97, 103
1914
1915Inversion lists are a compact way of specifying Unicode property-value
1916definitions. The 0th item in the list is the lowest code point that has the
1917property-value. The next item (item [1]) is the lowest code point beyond that
1918one that does NOT have the property-value. And the next item beyond that
1919([2]) is the lowest code point beyond that one that does have the
1920property-value, and so on. Put another way, each element in the list gives
1921the beginning of a range that has the property-value (for even numbered
1922elements), or doesn't have the property-value (for odd numbered elements).
1923The name for this data structure stems from the fact that each element in the
1924list toggles (or inverts) whether the corresponding range is or isn't on the
1925list.
1926
1927In the final example above, the first ASCII Hex digit is code point 48, the
1928character "0", and all code points from it through 57 (a "9") are ASCII hex
1929digits. Code points 58 through 64 aren't, but 65 (an "A") through 70 (an "F")
1930are, as are 97 ("a") through 102 ("f"). 103 starts a range of code points
1931that aren't ASCII hex digits. That range extends to infinity, which on your
1932computer can be found in the variable C<$Unicode::UCD::MAX_CP>. (This
1933variable is as close to infinity as Perl can get on your platform, and may be
1934too high for some operations to work; you may wish to use a smaller number for
1935your purposes.)
1936
1937Note that the inversion lists returned by this function can possibly include
1938non-Unicode code points, that is anything above 0x10FFFF. This is in
1939contrast to Perl regular expression matches on those code points, in which a
1940non-Unicode code point always fails to match. For example, both of these have
1941the same result:
1942
1943 chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Fails.
1944 chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Fails!
1945
1946And both raise a warning that a Unicode property is being used on a
1947non-Unicode code point. It is arguable as to which is the correct thing to do
1948here. This function has chosen the way opposite to the Perl regular
1949expression behavior. This allows you to easily flip to to the Perl regular
1950expression way (for you to go in the other direction would be far harder).
1951Simply add 0x110000 at the end of the non-empty returned list if it isn't
1952already that value; and pop that value if it is; like:
1953
1954 my @list = prop_invlist("foo");
1955 if (@list) {
1956 if ($list[-1] == 0x110000) {
1957 pop @list; # Defeat the turning on for above Unicode
1958 }
1959 else {
1960 push @list, 0x110000; # Turn off for above Unicode
1961 }
1962 }
1963
1964It is a simple matter to expand out an inversion list to a full list of all
1965code points that have the property-value:
1966
1967 my @invlist = prop_invlist($property_name);
1968 die "empty" unless @invlist;
1969 my @full_list;
1970 for (my $i = 0; $i < @invlist; $i += 2) {
1971 my $upper = ($i + 1) < @invlist
1972 ? $invlist[$i+1] - 1 # In range
1973 : $Unicode::UCD::MAX_CP; # To infinity. You may want
1974 # to stop much much earlier;
1975 # going this high may expose
1976 # perl deficiencies with very
1977 # large numbers.
1978 for my $j ($invlist[$i] .. $upper) {
1979 push @full_list, $j;
1980 }
1981 }
1982
1983C<prop_invlist> does not know about any user-defined nor Perl internal-only
1984properties, and will return C<undef> if called with one of those.
1985
1986=cut
1987
1988# User-defined properties could be handled with some changes to utf8_heavy.pl;
1989# and implementing here of dealing with EXTRAS. If done, consideration should
1990# be given to the fact that the user subroutine could return different results
1991# with each call; security issues need to be thought about.
1992
1993# These are created by mktables for this routine and stored in unicore/UCD.pl
1994# where their structures are described.
1995our %loose_defaults;
1996our $MAX_UNICODE_CODEPOINT;
1997
1998sub prop_invlist ($) {
1999 my $prop = $_[0];
2000 return if ! defined $prop;
2001
2002 require "utf8_heavy.pl";
2003
2004 # Warnings for these are only for regexes, so not applicable to us
2005 no warnings 'deprecated';
2006
2007 # Get the swash definition of the property-value.
2008 my $swash = utf8::SWASHNEW(__PACKAGE__, $prop, undef, 1, 0);
2009
2010 # Fail if not found, or isn't a boolean property-value, or is a
2011 # user-defined property, or is internal-only.
2012 return if ! $swash
2013 || ref $swash eq ""
2014 || $swash->{'BITS'} != 1
2015 || $swash->{'USER_DEFINED'}
2016 || $prop =~ /^\s*_/;
2017
2018 if ($swash->{'EXTRAS'}) {
2019 carp __PACKAGE__, "::prop_invlist: swash returned for $prop unexpectedly has EXTRAS magic";
2020 return;
2021 }
2022 if ($swash->{'SPECIALS'}) {
2023 carp __PACKAGE__, "::prop_invlist: swash returned for $prop unexpectedly has SPECIALS magic";
2024 return;
2025 }
2026
2027 my @invlist;
2028
2029 # The input lines look like:
2030 # 0041\t005A # [26]
2031 # 005F
2032
2033 # Split into lines, stripped of trailing comments
2034 foreach my $range (split "\n",
2035 $swash->{'LIST'} =~ s/ \s* (?: \# .* )? $ //xmgr)
2036 {
2037 # And find the beginning and end of the range on the line
2038 my ($hex_begin, $hex_end) = split "\t", $range;
2039 my $begin = hex $hex_begin;
2040
a39cc031
KW
2041 # If the new range merely extends the old, we remove the marker
2042 # created the last time through the loop for the old's end, which
2043 # causes the new one's end to be used instead.
2044 if (@invlist && $begin == $invlist[-1]) {
2045 pop @invlist;
2046 }
2047 else {
2f3f243e
KW
2048 # Add the beginning of the range
2049 push @invlist, $begin;
a39cc031 2050 }
681d705c
KW
2051
2052 if (defined $hex_end) { # The next item starts with the code point 1
2053 # beyond the end of the range.
2054 push @invlist, hex($hex_end) + 1;
2055 }
2056 else { # No end of range, is a single code point.
2057 push @invlist, $begin + 1;
2058 }
2059 }
2060
2061 require "unicore/UCD.pl";
2062 my $FIRST_NON_UNICODE = $MAX_UNICODE_CODEPOINT + 1;
2063
2064 # Could need to be inverted: add or subtract a 0 at the beginning of the
2065 # list. And to keep it from matching non-Unicode, add or subtract the
2066 # first non-unicode code point.
2067 if ($swash->{'INVERT_IT'}) {
2068 if (@invlist && $invlist[0] == 0) {
2069 shift @invlist;
2070 }
2071 else {
2072 unshift @invlist, 0;
2073 }
2074 if (@invlist && $invlist[-1] == $FIRST_NON_UNICODE) {
2075 pop @invlist;
2076 }
2077 else {
2078 push @invlist, $FIRST_NON_UNICODE;
2079 }
2080 }
2081
2082 # Here, the list is set up to include only Unicode code points. But, if
2083 # the table is the default one for the property, it should contain all
2084 # non-Unicode code points. First calculate the loose name for the
2085 # property. This is done even for strict-name properties, as the data
2086 # structure that mktables generates for us is set up so that we don't have
2087 # to worry about that. The property-value needs to be split if compound,
2088 # as the loose rules need to be independently calculated on each part. We
2089 # know that it is syntactically valid, or SWASHNEW would have failed.
2090
2091 $prop = lc $prop;
2092 my ($prop_only, $table) = split /\s*[:=]\s*/, $prop;
2093 if ($table) {
2094
2095 # May have optional prefixed 'is'
2096 $prop = utf8::_loose_name($prop_only) =~ s/^is//r;
2097 $prop = $utf8::loose_property_name_of{$prop};
2098 $prop .= "=" . utf8::_loose_name($table);
2099 }
2100 else {
2101 $prop = utf8::_loose_name($prop);
2102 }
2103 if (exists $loose_defaults{$prop}) {
2104
2105 # Here, is the default table. If a range ended with 10ffff, instead
2106 # continue that range to infinity, by popping the 110000; otherwise,
2107 # add the range from 11000 to infinity
2108 if (! @invlist || $invlist[-1] != $FIRST_NON_UNICODE) {
2109 push @invlist, $FIRST_NON_UNICODE;
2110 }
2111 else {
2112 pop @invlist;
2113 }
2114 }
2115
2116 return @invlist;
2117}
7319f91d 2118
62b3b855
KW
2119sub _search_invlist {
2120 # Find the range in the inversion list which contains a code point; that
2121 # is, find i such that l[i] <= code_point < l[i+1]
2122
2123 # If this is ever made public, could use to speed up .t specials. Would
2124 # need to use code point argument, as in other functions in this pm
2125
2126 my $list_ref = shift;
2127 my $code_point = shift;
2128 # Verify non-neg numeric XXX
2129
2130 my $max_element = @$list_ref - 1;
2131 return if ! $max_element < 0; # Undef if list is empty.
2132
2133 # Short cut something at the far-end of the table. This also allows us to
2134 # refer to element [$i+1] without fear of being out-of-bounds in the loop
2135 # below.
2136 return $max_element if $code_point >= $list_ref->[$max_element];
2137
2138 use integer; # want integer division
2139
2140 my $i = $max_element / 2;
2141
2142 my $lower = 0;
2143 my $upper = $max_element;
2144 while (1) {
2145
2146 if ($code_point >= $list_ref->[$i]) {
2147
2148 # Here we have met the lower constraint. We can quit if we
2149 # also meet the upper one.
2150 last if $code_point < $list_ref->[$i+1];
2151
2152 $lower = $i; # Still too low.
2153
2154 }
2155 else {
2156
2157 # Here, $code_point < $list_ref[$i], so look lower down.
2158 $upper = $i;
2159 }
2160
2161 # Split search domain in half to try again.
2162 my $temp = ($upper + $lower) / 2;
2163
2164 # No point in continuing unless $i changes for next time
2165 # in the loop.
2166 return $i if $temp == $i;
2167 $i = $temp;
2168 } # End of while loop
2169
2170 # Here we have found the offset
2171 return $i;
2172}
2173
2174=pod
2175
2176=head2 B<prop_invmap()>
2177
2178 use Unicode::UCD 'prop_invmap';
2179 my ($list_ref, $map_ref, $format, $missing)
2180 = prop_invmap("General Category");
2181
2182C<prop_invmap> is used to get the complete mapping definition for a property,
2183in the form of an inversion map. An inversion map consists of two parallel
2184arrays. One is an ordered list of code points that mark range beginnings, and
2185the other gives the value (or mapping) that all code points in the
2186corresponding range have.
2187
2188C<prop_invmap> is called with the name of the desired property. The name is
2189loosely matched, meaning that differences in case, white-space, hyphens, and
2190underscores are not meaningful (except for the trailing underscore in the
2191old-form grandfathered-in property C<"L_">, which is better written as C<"LC">,
2192or even better, C<"Gc=LC">).
2193
2194Many Unicode properties have more than one name (or alias). C<prop_invmap>
2195understands all of these, including Perl extensions to them. Ambiguities are
2196resolved as described above for L</prop_aliases()>. The Perl internal
2197property "Perl_Decimal_Digit, described below, is also accepted. C<undef> is
2198returned if the property name is unknown.
ee94c7d1
KW
2199See L<perluniprops/Properties accessible through Unicode::UCD> for the
2200properties acceptable as inputs to this function.
62b3b855
KW
2201
2202It is a fatal error to call this function except in list context.
2203
2204In addition to the the two arrays that form the inversion map, C<prop_invmap>
2205returns two other values; one is a scalar that gives some details as to the
2206format of the entries of the map array; the other is used for specialized
2207purposes, described at the end of this section.
2208
2209This means that C<prop_invmap> returns a 4 element list. For example,
2210
2211 my ($blocks_ranges_ref, $blocks_maps_ref, $format, $default)
2212 = prop_invmap("Block");
2213
2214In this call, the two arrays will be populated as shown below (for Unicode
22156.0):
2216
2217 Index @blocks_ranges @blocks_maps
2218 0 0x0000 Basic Latin
2219 1 0x0080 Latin-1 Supplement
2220 2 0x0100 Latin Extended-A
2221 3 0x0180 Latin Extended-B
2222 4 0x0250 IPA Extensions
2223 5 0x02B0 Spacing Modifier Letters
2224 6 0x0300 Combining Diacritical Marks
2225 7 0x0370 Greek and Coptic
2226 8 0x0400 Cyrillic
2227 ...
2228 233 0x2B820 No_Block
2229 234 0x2F800 CJK Compatibility Ideographs Supplement
2230 235 0x2FA20 No_Block
2231 236 0xE0000 Tags
2232 237 0xE0080 No_Block
2233 238 0xE0100 Variation Selectors Supplement
2234 239 0xE01F0 No_Block
2235 240 0xF0000 Supplementary Private Use Area-A
2236 241 0x100000 Supplementary Private Use Area-B
2237 242 0x110000 No_Block
2238
2239The first line (with Index [0]) means that the value for code point 0 is "Basic
2240Latin". The entry "0x0080" in the @blocks_ranges column in the second line
2241means that the value from the first line, "Basic Latin", extends to all code
2242points in the range from 0 up to but not including 0x0080, that is, through
647396da 2243127. In other words, the code points from 0 to 127 are all in the "Basic
62b3b855
KW
2244Latin" block. Similarly, all code points in the range from 0x0080 up to (but
2245not including) 0x0100 are in the block named "Latin-1 Supplement", etc.
2246(Notice that the return is the old-style block names; see L</Old-style versus
2247new-style block names>).
2248
2249The final line (with Index [242]) means that the value for all code points above
2250the legal Unicode maximum code point have the value "No_Block", which is the
2251term Unicode uses for a non-existing block.
2252
2253The arrays completely specify the mappings for all possible code points.
2254The final element in an inversion map returned by this function will always be
2255for the range that consists of all the code points that aren't legal Unicode,
2256but that are expressible on the platform. (That is, it starts with code point
22570x110000, the first code point above the legal Unicode maximum, and extends to
2258infinity.) The value for that range will be the same that any typical
2259unassigned code point has for the specified property. (Certain unassigned
2260code points are not "typical"; for example the non-character code points, or
2261those in blocks that are to be written right-to-left. The above-Unicode
2262range's value is not based on these atypical code points.) It could be argued
2263that, instead of treating these as unassigned Unicode code points, the value
2264for this range should be C<undef>. If you wish, you can change the returned
2265arrays accordingly.
2266
2267The maps are almost always simple scalars that should be interpreted as-is.
2268These values are those given in the Unicode-supplied data files, which may be
2269inconsistent as to capitalization and as to which synonym for a property-value
2270is given. The results may be normalized by using the L</prop_value_aliases()>
2271function.
2272
2273There are exceptions to the simple scalar maps. Some properties have some
2274elements in their map list that are themselves lists of scalars; and some
2275special strings are returned that are not to be interpreted as-is. Element
2276[2] (placed into C<$format> in the example above) of the returned four element
647396da 2277list tells you if the map has any of these special elements or not, as follows:
62b3b855
KW
2278
2279=over
2280
dc8d8ea6 2281=item B<C<s>>
62b3b855
KW
2282
2283means all the elements of the map array are simple scalars, with no special
2284elements. Almost all properties are like this, like the C<block> example
2285above.
2286
dc8d8ea6 2287=item B<C<sl>>
62b3b855 2288
647396da 2289means that some of the map array elements have the form given by C<"s">, and
62b3b855
KW
2290the rest are lists of scalars. For example, here is a portion of the output
2291of calling C<prop_invmap>() with the "Script Extensions" property:
2292
2293 @scripts_ranges @scripts_maps
2294 ...
c2ca0207
KW
2295 0x0953 Devanagari
2296 0x0964 [ Bengali, Devanagari, Gurumukhi, Oriya ]
2297 0x0966 Devanagari
62b3b855
KW
2298 0x0970 Common
2299
647396da
KW
2300Here, the code points 0x964 and 0x965 are both used in Bengali,
2301Devanagari, Gurmukhi, and Oriya, but no other scripts.
62b3b855 2302
647396da 2303The Name_Alias property is also of this form. But each scalar consists of two
58b75e36 2304components: 1) the name, and 2) the type of alias this is. They are
7620cb10
KW
2305separated by a colon and a space. In Unicode 6.1, there are several alias types:
2306
2307=over
2308
2309=item C<correction>
2310
2311indicates that the name is a corrected form for the
2312original name (which remains valid) for the same code point.
2313
2314=item C<control>
2315
2316adds a new name for a control character.
2317
2318=item C<alternate>
2319
2320is an alternate name for a character
2321
2322=item C<figment>
2323
2324is a name for a character that has been documented but was never in any
2325actual standard.
2326
2327=item C<abbreviation>
2328
2329is a common abbreviation for a character
2330
2331=back
2332
2333The lists are ordered (roughly) so the most preferred names come before less
2334preferred ones.
58b75e36
KW
2335
2336For example,
2337
7620cb10
KW
2338 @aliases_ranges @alias_maps
2339 ...
2340 0x009E [ 'PRIVACY MESSAGE: control', 'PM: abbreviation' ]
2341 0x009F [ 'APPLICATION PROGRAM COMMAND: control',
2342 'APC: abbreviation'
2343 ]
2344 0x00A0 'NBSP: abbreviation'
2345 0x00A1 ""
2346 0x00AD 'SHY: abbreviation'
2347 0x00AE ""
2348 0x01A2 'LATIN CAPITAL LETTER GHA: correction'
2349 0x01A3 'LATIN SMALL LETTER GHA: correction'
2350 0x01A4 ""
58b75e36 2351 ...
58b75e36 2352
7620cb10
KW
2353A map to the empty string means that there is no alias defined for the code
2354point.
58b75e36 2355
d11155ec 2356=item B<C<a>>
62b3b855 2357
647396da 2358is like C<"s"> in that all the map array elements are scalars, but here they are
d11155ec
KW
2359restricted to all being integers, and some have to be adjusted (hence the name
2360C<"a">) to get the correct result. For example, in:
62b3b855
KW
2361
2362 my ($uppers_ranges_ref, $uppers_maps_ref, $format)
2363 = prop_invmap("Simple_Uppercase_Mapping");
2364
2365the returned arrays look like this:
2366
2367 @$uppers_ranges_ref @$uppers_maps_ref Note
bf7fe2df 2368 0 0
d11155ec 2369 97 65 'a' maps to 'A', b => B ...
bf7fe2df 2370 123 0
d11155ec 2371 181 924 MICRO SIGN => Greek Cap MU
bf7fe2df 2372 182 0
62b3b855
KW
2373 ...
2374
d11155ec
KW
2375Let's start with the second line. It says that the uppercase of code point 97
2376is 65; or C<uc("a")> == "A". But the line is for the entire range of code
2377points 97 through 122. To get the mapping for any code point in a range, you
2378take the offset it has from the beginning code point of the range, and add
2379that to the mapping for that first code point. So, the mapping for 122 ("z")
2380is derived by taking the offset of 122 from 97 (=25) and adding that to 65,
2381yielding 90 ("z"). Likewise for everything in between.
2382
2383The first line works the same way. The first map in a range is always the
2384correct value for its code point (because the adjustment is 0). Thus the
2385C<uc(chr(0))> is just itself. Also, C<uc(chr(1))> is also itself, as the
2386adjustment is 0+1-0 .. C<uc(chr(96))> is 96.
bf7fe2df 2387
d11155ec
KW
2388Requiring this simple adjustment allows the returned arrays to be
2389significantly smaller than otherwise, up to a factor of 10, speeding up
2390searching through them.
62b3b855 2391
d11155ec 2392=item B<C<al>>
62b3b855 2393
d11155ec 2394means that some of the map array elements have the form given by C<"a">, and
62b3b855
KW
2395the rest are ordered lists of code points.
2396For example, in:
2397
2398 my ($uppers_ranges_ref, $uppers_maps_ref, $format)
2399 = prop_invmap("Uppercase_Mapping");
2400
2401the returned arrays look like this:
2402
2403 @$uppers_ranges_ref @$uppers_maps_ref
bf7fe2df 2404 0 0
d11155ec 2405 97 65
bf7fe2df 2406 123 0
d11155ec 2407 181 924
bf7fe2df 2408 182 0
62b3b855
KW
2409 ...
2410 0x0149 [ 0x02BC 0x004E ]
bf7fe2df 2411 0x014A 0
d11155ec 2412 0x014B 330
62b3b855
KW
2413 ...
2414
2415This is the full Uppercase_Mapping property (as opposed to the
d11155ec 2416Simple_Uppercase_Mapping given in the example for format C<"a">). The only
62b3b855
KW
2417difference between the two in the ranges shown is that the code point at
24180x0149 (LATIN SMALL LETTER N PRECEDED BY APOSTROPHE) maps to a string of two
2419characters, 0x02BC (MODIFIER LETTER APOSTROPHE) followed by 0x004E (LATIN
2420CAPITAL LETTER N).
2421
d11155ec
KW
2422No adjustments are needed to entries that are references to arrays; each such
2423entry will have exactly one element in its range, so the offset is always 0.
bf7fe2df 2424
d11155ec 2425=item B<C<ae>>
b0b13ada 2426
d11155ec
KW
2427This is like C<"a">, but some elements are the empty string, and should not be
2428adjusted.
b0b13ada
KW
2429The one internal Perl property accessible by C<prop_invmap> is of this type:
2430"Perl_Decimal_Digit" returns an inversion map which gives the numeric values
2431that are represented by the Unicode decimal digit characters. Characters that
2432don't represent decimal digits map to the empty string, like so:
2433
2434 @digits @values
2435 0x0000 ""
d11155ec 2436 0x0030 0
b0b13ada 2437 0x003A: ""
d11155ec 2438 0x0660: 0
b0b13ada 2439 0x066A: ""
d11155ec 2440 0x06F0: 0
b0b13ada 2441 0x06FA: ""
d11155ec 2442 0x07C0: 0
b0b13ada 2443 0x07CA: ""
d11155ec 2444 0x0966: 0
b0b13ada
KW
2445 ...
2446
2447This means that the code points from 0 to 0x2F do not represent decimal digits;
d11155ec
KW
2448the code point 0x30 (DIGIT ZERO) represents 0; code point 0x31, (DIGIT ONE),
2449represents 0+1-0 = 1; ... code point 0x39, (DIGIT NINE), represents 0+9-0 = 9;
2450... code points 0x3A through 0x65F do not represent decimal digits; 0x660
2451(ARABIC-INDIC DIGIT ZERO), represents 0; ... 0x07C1 (NKO DIGIT ONE),
2452represents 0+1-0 = 1 ...
b0b13ada 2453
d11155ec 2454=item B<C<ale>>
62b3b855 2455
d11155ec
KW
2456is a combination of the C<"al"> type and the C<"ae"> type. Some of
2457the map array elements have the forms given by C<"al">, and
62b3b855
KW
2458the rest are the empty string. The property C<NFKC_Casefold> has this form.
2459An example slice is:
2460
2461 @$ranges_ref @$maps_ref Note
2462 ...
d11155ec
KW
2463 0x00AA 97 FEMININE ORDINAL INDICATOR => 'a'
2464 0x00AB 0
62b3b855 2465 0x00AD SOFT HYPHEN => ""
d11155ec 2466 0x00AE 0
62b3b855 2467 0x00AF [ 0x0020, 0x0304 ] MACRON => SPACE . COMBINING MACRON
d11155ec 2468 0x00B0 0
62b3b855
KW
2469 ...
2470
4f143a72 2471=item B<C<ar>>
6cc45523
KW
2472
2473means that all the elements of the map array are either rational numbers or
2474the string C<"NaN">, meaning "Not a Number". A rational number is either an
2475integer, or two integers separated by a solidus (C<"/">). The second integer
2476represents the denominator of the division implied by the solidus, and is
6329003c
KW
2477actually always positive, so it is guaranteed not to be 0 and to not to be
2478signed. When the element is a plain integer (without the
4f143a72
KW
2479solidus), it may need to be adjusted to get the correct value by adding the
2480offset, just as other C<"a"> properties. No adjustment is needed for
2481fractions, as the range is guaranteed to have just a single element, and so
2482the offset is always 0.
2483
2484If you want to convert the returned map to entirely scalar numbers, you
6cc45523
KW
2485can use something like this:
2486
2487 my ($invlist_ref, $invmap_ref, $format) = prop_invmap($property);
4f143a72 2488 if ($format && $format eq "ar") {
6cc45523
KW
2489 map { $_ = eval $_ } @$invmap_ref;
2490 }
2491
2492Here's some entries from the output of the property "Nv", which has format
4f143a72 2493C<"ar">.
6cc45523 2494
4f143a72 2495 @numerics_ranges @numerics_maps Note
6cc45523 2496 0x00 "NaN"
4f143a72 2497 0x30 0 DIGIT 0 .. DIGIT 9
6cc45523 2498 0x3A "NaN"
4f143a72 2499 0xB2 2 SUPERSCRIPTs 2 and 3
6cc45523 2500 0xB4 "NaN"
4f143a72 2501 0xB9 1 SUPERSCRIPT 1
6cc45523 2502 0xBA "NaN"
4f143a72
KW
2503 0xBC 1/4 VULGAR FRACTION 1/4
2504 0xBD 1/2 VULGAR FRACTION 1/2
2505 0xBE 3/4 VULGAR FRACTION 3/4
6cc45523 2506 0xBF "NaN"
4f143a72
KW
2507 0x660 0 ARABIC-INDIC DIGIT ZERO .. NINE
2508 0x66A "NaN"
6cc45523 2509
dc8d8ea6 2510=item B<C<n>>
62b3b855
KW
2511
2512means the Name property. All the elements of the map array are simple
2513scalars, but some of them contain special strings that require more work to
2514get the actual name.
2515
2516Entries such as:
2517
2518 CJK UNIFIED IDEOGRAPH-<code point>
2519
2520mean that the name for the code point is "CJK UNIFIED IDEOGRAPH-"
2521with the code point (expressed in hexadecimal) appended to it, like "CJK
647396da
KW
2522UNIFIED IDEOGRAPH-3403" (similarly for S<C<CJK COMPATIBILITY IDEOGRAPH-E<lt>code
2523pointE<gt>>>).
62b3b855
KW
2524
2525Also, entries like
2526
2527 <hangul syllable>
2528
2529means that the name is algorithmically calculated. This is easily done by
2530the function L<charnames/charnames::viacode(code)>.
2531
2532Note that for control characters (C<Gc=cc>), Unicode's data files have the
2533string "C<E<lt>controlE<gt>>", but the real name of each of these characters is the empty
7620cb10 2534string. This function returns that real name, the empty string. (There are
647396da
KW
2535names for these characters, but they are considered aliases, not the Name
2536property name, and are contained in the C<Name_Alias> property.)
62b3b855 2537
d11155ec 2538=item B<C<ad>>
62b3b855 2539
d11155ec 2540means the Decomposition_Mapping property. This property is like C<"al">
bea2c146 2541properties, except that one of the scalar elements is of the form:
62b3b855
KW
2542
2543 <hangul syllable>
2544
bea2c146
KW
2545This signifies that this entry should be replaced by the decompositions for
2546all the code points whose decomposition is algorithmically calculated. (All
6329003c
KW
2547of them are currently in one range and no others outisde the range are likely
2548to ever be added to Unicode; the C<"n"> format
bea2c146 2549has this same entry.) These can be generated via the function
62b3b855
KW
2550L<Unicode::Normalize::NFD()|Unicode::Normalize>.
2551
62b3b855
KW
2552Note that the mapping is the one that is specified in the Unicode data files,
2553and to get the final decomposition, it may need to be applied recursively.
2554
2555=back
2556
d11155ec
KW
2557Note that a format begins with the letter "a" if and only the property it is
2558for requires adjustments by adding the offsets in multi-element ranges. For
2559all these properties, an entry should be adjusted only if the map is a scalar
2560which is an integer. That is, it must match the regular expression:
2561
2562 / ^ -? \d+ $ /xa
2563
2564Further, the first element in a range never needs adjustment, as the
2565adjustment would be just adding 0.
2566
62b3b855
KW
2567A binary search can be used to quickly find a code point in the inversion
2568list, and hence its corresponding mapping.
2569
2570The final element (index [3], assigned to C<$default> in the "block" example) in
2571the four element list returned by this function may be useful for applications
2572that wish to convert the returned inversion map data structure into some
2573other, such as a hash. It gives the mapping that most code points map to
2574under the property. If you establish the convention that any code point not
2575explicitly listed in your data structure maps to this value, you can
2576potentially make your data structure much smaller. As you construct your data
2577structure from the one returned by this function, simply ignore those ranges
2578that map to this value, generally called the "default" value. For example, to
2579convert to the data structure searchable by L</charinrange()>, you can follow
6329003c 2580this recipe for properties that don't require adjustments:
62b3b855
KW
2581
2582 my ($list_ref, $map_ref, $format, $missing) = prop_invmap($property);
2583 my @range_list;
6329003c
KW
2584
2585 # Look at each element in the list, but the -2 is needed because we
2586 # look at $i+1 in the loop, and the final element is guaranteed to map
2587 # to $missing by prop_invmap(), so we would skip it anyway.
62b3b855
KW
2588 for my $i (0 .. @$list_ref - 2) {
2589 next if $map_ref->[$i] eq $missing;
2590 push @range_list, [ $list_ref->[$i],
2591 $list_ref->[$i+1],
2592 $map_ref->[$i]
2593 ];
2594 }
2595
2596 print charinrange(\@range_list, $code_point), "\n";
2597
62b3b855
KW
2598With this, C<charinrange()> will return C<undef> if its input code point maps
2599to C<$missing>. You can avoid this by omitting the C<next> statement, and adding
2600a line after the loop to handle the final element of the inversion map.
2601
6329003c
KW
2602Similarly, this recipe can be used for properties that do require adjustments:
2603
2604 for my $i (0 .. @$list_ref - 2) {
2605 next if $map_ref->[$i] eq $missing;
2606
2607 # prop_invmap() guarantees that if the mapping is to an array, the
2608 # range has just one element, so no need to worry about adjustments.
2609 if (ref $map_ref->[$i]) {
2610 push @range_list,
2611 [ $list_ref->[$i], $list_ref->[$i], $map_ref->[$i] ];
2612 }
2613 else { # Otherwise each element is actually mapped to a separate
2614 # value, so the range has to be split into single code point
2615 # ranges.
2616
2617 my $adjustment = 0;
2618
2619 # For each code point that gets mapped to something...
2620 for my $j ($list_ref->[$i] .. $list_ref->[$i+1] -1 ) {
2621
2622 # ... add a range consisting of just it mapping to the
2623 # original plus the adjustment, which is incremented for the
2624 # next time through the loop, as the offset increases by 1
2625 # for each element in the range
2626 push @range_list,
2627 [ $j, $j, $map_ref->[$i] + $adjustment++ ];
2628 }
2629 }
2630 }
62b3b855
KW
2631
2632Note that the inversion maps returned for the C<Case_Folding> and
2633C<Simple_Case_Folding> properties do not include the Turkic-locale mappings.
2634Use L</casefold()> for these.
2635
62b3b855
KW
2636C<prop_invmap> does not know about any user-defined properties, and will
2637return C<undef> if called with one of those.
2638
2639=cut
2640
2641# User-defined properties could be handled with some changes to utf8_heavy.pl;
2642# if done, consideration should be given to the fact that the user subroutine
2643# could return different results with each call, which could lead to some
2644# security issues.
2645
2646# One could store things in memory so they don't have to be recalculated, but
2647# it is unlikely this will be called often, and some properties would take up
2648# significant memory.
2649
2650# These are created by mktables for this routine and stored in unicore/UCD.pl
2651# where their structures are described.
2652our @algorithmic_named_code_points;
2653our $HANGUL_BEGIN;
2654our $HANGUL_COUNT;
2655
2656sub prop_invmap ($) {
2657
2658 croak __PACKAGE__, "::prop_invmap: must be called in list context" unless wantarray;
2659
2660 my $prop = $_[0];
2661 return unless defined $prop;
2662
2663 # Fail internal properties
2664 return if $prop =~ /^_/;
2665
2666 # The values returned by this function.
2667 my (@invlist, @invmap, $format, $missing);
2668
2669 # The swash has two components we look at, the base list, and a hash,
2670 # named 'SPECIALS', containing any additional members whose mappings don't
2671 # fit into the the base list scheme of things. These generally 'override'
2672 # any value in the base list for the same code point.
2673 my $overrides;
2674
2675 require "utf8_heavy.pl";
2676 require "unicore/UCD.pl";
2677
2678RETRY:
2679
647396da
KW
2680 # If there are multiple entries for a single code point
2681 my $has_multiples = 0;
2682
62b3b855
KW
2683 # Try to get the map swash for the property. They have 'To' prepended to
2684 # the property name, and 32 means we will accept 32 bit return values.
647396da 2685 # The 0 means we aren't calling this from tr///.
62b3b855
KW
2686 my $swash = utf8::SWASHNEW(__PACKAGE__, "To$prop", undef, 32, 0);
2687
2688 # If didn't find it, could be because needs a proxy. And if was the
2689 # 'Block' or 'Name' property, use a proxy even if did find it. Finding it
647396da
KW
2690 # in these cases would be the result of the installation changing mktables
2691 # to output the Block or Name tables. The Block table gives block names
2692 # in the new-style, and this routine is supposed to return old-style block
2693 # names. The Name table is valid, but we need to execute the special code
2694 # below to add in the algorithmic-defined name entries.
34132297 2695 # And NFKCCF needs conversion, so handle that here too.
62b3b855 2696 if (ref $swash eq ""
34132297 2697 || $swash->{'TYPE'} =~ / ^ To (?: Blk | Na | NFKCCF ) $ /x)
62b3b855
KW
2698 {
2699
2700 # Get the short name of the input property, in standard form
2701 my ($second_try) = prop_aliases($prop);
2702 return unless $second_try;
2703 $second_try = utf8::_loose_name(lc $second_try);
2704
2705 if ($second_try eq "in") {
2706
2707 # This property is identical to age for inversion map purposes
2708 $prop = "age";
2709 goto RETRY;
2710 }
cfc5eb77 2711 elsif ($second_try =~ / ^ s ( cf | fc | [ltu] c ) $ /x) {
62b3b855 2712
75e7c50b
KW
2713 # These properties use just the LIST part of the full mapping,
2714 # which includes the simple maps that are otherwise overridden by
2715 # the SPECIALS. So all we need do is to not look at the SPECIALS;
2716 # set $overrides to indicate that
62b3b855 2717 $overrides = -1;
62b3b855 2718
75e7c50b 2719 # The full name is the simple name stripped of its initial 's'
cfc5eb77
KW
2720 $prop = $1;
2721
2722 # .. except for this case
2723 $prop = 'cf' if $prop eq 'fc';
2724
62b3b855
KW
2725 goto RETRY;
2726 }
2727 elsif ($second_try eq "blk") {
2728
2729 # We use the old block names. Just create a fake swash from its
2730 # data.
2731 _charblocks();
2732 my %blocks;
2733 $blocks{'LIST'} = "";
2734 $blocks{'TYPE'} = "ToBlk";
2735 $utf8::SwashInfo{ToBlk}{'missing'} = "No_Block";
2736 $utf8::SwashInfo{ToBlk}{'format'} = "s";
2737
2738 foreach my $block (@BLOCKS) {
2739 $blocks{'LIST'} .= sprintf "%x\t%x\t%s\n",
2740 $block->[0],
2741 $block->[1],
2742 $block->[2];
2743 }
2744 $swash = \%blocks;
2745 }
2746 elsif ($second_try eq "na") {
2747
2748 # Use the combo file that has all the Name-type properties in it,
2749 # extracting just the ones that are for the actual 'Name'
2750 # property. And create a fake swash from it.
2751 my %names;
2752 $names{'LIST'} = "";
2753 my $original = do "unicore/Name.pl";
62b3b855
KW
2754 my $algorithm_names = \@algorithmic_named_code_points;
2755
3b6a8189
KW
2756 # We need to remove the names from it that are aliases. For that
2757 # we need to also read in that table. Create a hash with the keys
2758 # being the code points, and the values being a list of the
2759 # aliases for the code point key.
2760 my ($aliases_code_points, $aliases_maps, undef, undef) =
2761 &prop_invmap('Name_Alias');
2762 my %aliases;
2763 for (my $i = 0; $i < @$aliases_code_points; $i++) {
2764 my $code_point = $aliases_code_points->[$i];
2765 $aliases{$code_point} = $aliases_maps->[$i];
2766
2767 # If not already a list, make it into one, so that later we
2768 # can treat things uniformly
2769 if (! ref $aliases{$code_point}) {
2770 $aliases{$code_point} = [ $aliases{$code_point} ];
2771 }
2772
2773 # Remove the alias type from the entry, retaining just the
2774 # name.
2775 map { s/:.*// } @{$aliases{$code_point}};
2776 }
2777
62b3b855
KW
2778 my $i = 0;
2779 foreach my $line (split "\n", $original) {
2780 my ($hex_code_point, $name) = split "\t", $line;
2781
2782 # Weeds out all comments, blank lines, and named sequences
df46a385 2783 next if $hex_code_point =~ /[^[:xdigit:]]/a;
62b3b855
KW
2784
2785 my $code_point = hex $hex_code_point;
2786
2787 # The name of all controls is the default: the empty string.
2788 # The set of controls is immutable, so these hard-coded
2789 # constants work.
2790 next if $code_point <= 0x9F
2791 && ($code_point <= 0x1F || $code_point >= 0x7F);
2792
3b6a8189
KW
2793 # If this is a name_alias, it isn't a name
2794 next if grep { $_ eq $name } @{$aliases{$code_point}};
62b3b855
KW
2795
2796 # If we are beyond where one of the special lines needs to
2797 # be inserted ...
3b6a8189 2798 while ($i < @$algorithm_names
62b3b855
KW
2799 && $code_point > $algorithm_names->[$i]->{'low'})
2800 {
2801
2802 # ... then insert it, ahead of what we were about to
2803 # output
3b6a8189 2804 $names{'LIST'} .= sprintf "%x\t%x\t%s\n",
62b3b855
KW
2805 $algorithm_names->[$i]->{'low'},
2806 $algorithm_names->[$i]->{'high'},
2807 $algorithm_names->[$i]->{'name'};
2808
62b3b855
KW
2809 # Done with this range.
2810 $i++;
2811
3b6a8189
KW
2812 # We loop until all special lines that precede the next
2813 # regular one are output.
62b3b855
KW
2814 }
2815
3b6a8189
KW
2816 # Here, is a normal name.
2817 $names{'LIST'} .= sprintf "%x\t\t%s\n", $code_point, $name;
2818 } # End of loop through all the names
62b3b855
KW
2819
2820 $names{'TYPE'} = "ToNa";
2821 $utf8::SwashInfo{ToNa}{'missing'} = "";
2822 $utf8::SwashInfo{ToNa}{'format'} = "n";
2823 $swash = \%names;
2824 }
2825 elsif ($second_try =~ / ^ ( d [mt] ) $ /x) {
2826
2827 # The file is a combination of dt and dm properties. Create a
2828 # fake swash from the portion that we want.
2829 my $original = do "unicore/Decomposition.pl";
2830 my %decomps;
2831
2832 if ($second_try eq 'dt') {
2833 $decomps{'TYPE'} = "ToDt";
2834 $utf8::SwashInfo{'ToDt'}{'missing'} = "None";
2835 $utf8::SwashInfo{'ToDt'}{'format'} = "s";
d11155ec 2836 } # 'dm' is handled below, with 'nfkccf'
62b3b855
KW
2837
2838 $decomps{'LIST'} = "";
2839
2840 # This property has one special range not in the file: for the
1a4c9760
KW
2841 # hangul syllables. But not in Unicode version 1.
2842 UnicodeVersion() unless defined $v_unicode_version;
2843 my $done_hangul = ($v_unicode_version lt v2.0.0)
2844 ? 1
2845 : 0; # Have we done the hangul range ?
62b3b855
KW
2846 foreach my $line (split "\n", $original) {
2847 my ($hex_lower, $hex_upper, $type_and_map) = split "\t", $line;
2848 my $code_point = hex $hex_lower;
2849 my $value;
bea2c146 2850 my $redo = 0;
62b3b855
KW
2851
2852 # The type, enclosed in <...>, precedes the mapping separated
2853 # by blanks
2854 if ($type_and_map =~ / ^ < ( .* ) > \s+ (.*) $ /x) {
2855 $value = ($second_try eq 'dt') ? $1 : $2
2856 }
2857 else { # If there is no type specified, it's canonical
2858 $value = ($second_try eq 'dt')
2859 ? "Canonical" :
2860 $type_and_map;
2861 }
2862
2863 # Insert the hangul range at the appropriate spot.
2864 if (! $done_hangul && $code_point > $HANGUL_BEGIN) {
2865 $done_hangul = 1;
2866 $decomps{'LIST'} .=
2867 sprintf "%x\t%x\t%s\n",
2868 $HANGUL_BEGIN,
2869 $HANGUL_BEGIN + $HANGUL_COUNT - 1,
2870 ($second_try eq 'dt')
2871 ? "Canonical"
2872 : "<hangul syllable>";
2873 }
2874
1a4c9760
KW
2875 if ($value =~ / / && $hex_upper ne "" && $hex_upper ne $hex_lower) {
2876 $line = sprintf("%04X\t%s\t%s", hex($hex_lower) + 1, $hex_upper, $value);
2877 $hex_upper = "";
2878 $redo = 1;
2879 }
2880
62b3b855
KW
2881 # And append this to our constructed LIST.
2882 $decomps{'LIST'} .= "$hex_lower\t$hex_upper\t$value\n";
bea2c146
KW
2883
2884 redo if $redo;
62b3b855
KW
2885 }
2886 $swash = \%decomps;
2887 }
d11155ec
KW
2888 elsif ($second_try ne 'nfkccf') { # Don't know this property. Fail.
2889 return;
2890 }
2891
2892 if ($second_try eq 'nfkccf' || $second_try eq 'dm') {
34132297 2893
d11155ec
KW
2894 # The 'nfkccf' property is stored in the old format for backwards
2895 # compatibility for any applications that has read its file
2896 # directly before prop_invmap() existed.
2897 # And the code above has extracted the 'dm' property from its file
2898 # yielding the same format. So here we convert them to adjusted
2899 # format for compatibility with the other properties similar to
2900 # them.
2901 my %revised_swash;
34132297 2902
d11155ec 2903 # We construct a new converted list.
34132297 2904 my $list = "";
d11155ec
KW
2905
2906 my @ranges = split "\n", $swash->{'LIST'};
2907 for (my $i = 0; $i < @ranges; $i++) {
2908 my ($hex_begin, $hex_end, $map) = split "\t", $ranges[$i];
2909
2910 # The dm property has maps that are space separated sequences
2911 # of code points, as well as the special entry "<hangul
2912 # syllable>, which also contains a blank.
2913 my @map = split " ", $map;
2914 if (@map > 1) {
2915
2916 # If it's just the special entry, append as-is.
2917 if ($map eq '<hangul syllable>') {
2918 $list .= "$ranges[$i]\n";
2919 }
2920 else {
2921
2922 # These should all single-element ranges.
1a4c9760 2923 croak __PACKAGE__, "::prop_invmap: Not expecting a mapping with multiple code points in a multi-element range, $ranges[$i]" if $hex_end ne "" && $hex_end ne $hex_begin;
d11155ec
KW
2924
2925 # Convert them to decimal, as that's what's expected.
2926 $list .= "$hex_begin\t\t"
2927 . join(" ", map { hex } @map)
2928 . "\n";
2929 }
2930 next;
2931 }
2932
2933 # Here, the mapping doesn't have a blank, is for a single code
2934 # point.
34132297
KW
2935 my $begin = hex $hex_begin;
2936 my $end = (defined $hex_end && $hex_end ne "")
2937 ? hex $hex_end
2938 : $begin;
d11155ec
KW
2939
2940 # Again, the output is to be in decimal.
34132297 2941 my $decimal_map = hex $map;
d11155ec
KW
2942
2943 # We know that multi-element ranges with the same mapping
2944 # should not be adjusted, as after the adjustment
2945 # multi-element ranges are for consecutive increasing code
2946 # points. Further, the final element in the list won't be
2947 # adjusted, as there is nothing after it to include in the
2948 # adjustment
2949 if ($begin != $end || $i == @ranges -1) {
2950
2951 # So just convert these to single-element ranges
2952 foreach my $code_point ($begin .. $end) {
2953 $list .= sprintf("%04X\t\t%d\n",
2954 $code_point, $decimal_map);
2955 }
34132297 2956 }
d11155ec 2957 else {
34132297 2958
d11155ec
KW
2959 # Here, we have a candidate for adjusting. What we do is
2960 # look through the subsequent adjacent elements in the
2961 # input. If the map to the next one differs by 1 from the
2962 # one before, then we combine into a larger range with the
2963 # initial map. Loop doing this until we find one that
2964 # can't be combined.
2965
2966 my $offset = 0; # How far away are we from the initial
2967 # map
2968 my $squished = 0; # ? Did we squish at least two
2969 # elements together into one range
2970 for ( ; $i < @ranges; $i++) {
2971 my ($next_hex_begin, $next_hex_end, $next_map)
2972 = split "\t", $ranges[$i+1];
2973
2974 # In the case of 'dm', the map may be a sequence of
2975 # multiple code points, which are never combined with
2976 # another range
2977 last if $next_map =~ / /;
2978
2979 $offset++;
2980 my $next_decimal_map = hex $next_map;
2981
2982 # If the next map is not next in sequence, it
2983 # shouldn't be combined.
2984 last if $next_decimal_map != $decimal_map + $offset;
2985
2986 my $next_begin = hex $next_hex_begin;
2987
2988 # Likewise, if the next element isn't adjacent to the
2989 # previous one, it shouldn't be combined.
2990 last if $next_begin != $begin + $offset;
2991
2992 my $next_end = (defined $next_hex_end
2993 && $next_hex_end ne "")
2994 ? hex $next_hex_end
2995 : $next_begin;
2996
2997 # And finally, if the next element is a multi-element
2998 # range, it shouldn't be combined.
2999 last if $next_end != $next_begin;
3000
3001 # Here, we will combine. Loop to see if we should
3002 # combine the next element too.
3003 $squished = 1;
3004 }
3005
3006 if ($squished) {
3007
3008 # Here, 'i' is the element number of the last element to
3009 # be combined, and the range is single-element, or we
3010 # wouldn't be combining. Get it's code point.
3011 my ($hex_end, undef, undef) = split "\t", $ranges[$i];
3012 $list .= "$hex_begin\t$hex_end\t$decimal_map\n";
3013 } else {
3014
3015 # Here, no combining done. Just appen the initial
3016 # (and current) values.
3017 $list .= "$hex_begin\t\t$decimal_map\n";
3018 }
3019 }
3020 } # End of loop constructing the converted list
3021
3022 # Finish up the data structure for our converted swash
3023 my $type = ($second_try eq 'nfkccf') ? 'ToNFKCCF' : 'ToDm';
3024 $revised_swash{'LIST'} = $list;
3025 $revised_swash{'TYPE'} = $type;
3026 $revised_swash{'SPECIALS'} = $swash->{'SPECIALS'};
3027 $swash = \%revised_swash;
3028
3029 $utf8::SwashInfo{$type}{'missing'} = 0;
3030 $utf8::SwashInfo{$type}{'format'} = 'a';
62b3b855
KW
3031 }
3032 }
3033
3034 if ($swash->{'EXTRAS'}) {
3035 carp __PACKAGE__, "::prop_invmap: swash returned for $prop unexpectedly has EXTRAS magic";
3036 return;
3037 }
3038
3039 # Here, have a valid swash return. Examine it.
34132297 3040 my $returned_prop = $swash->{'TYPE'};
62b3b855
KW
3041
3042 # All properties but binary ones should have 'missing' and 'format'
3043 # entries
3044 $missing = $utf8::SwashInfo{$returned_prop}{'missing'};
3045 $missing = 'N' unless defined $missing;
3046
3047 $format = $utf8::SwashInfo{$returned_prop}{'format'};
3048 $format = 'b' unless defined $format;
3049
d11155ec
KW
3050 my $requires_adjustment = $format =~ /^a/;
3051
62b3b855
KW
3052 # The LIST input lines look like:
3053 # ...
3054 # 0374\t\tCommon
3055 # 0375\t0377\tGreek # [3]
3056 # 037A\t037D\tGreek # [4]
3057 # 037E\t\tCommon
3058 # 0384\t\tGreek
3059 # ...
3060 #
3061 # Convert them to like
3062 # 0374 => Common
3063 # 0375 => Greek
3064 # 0378 => $missing
3065 # 037A => Greek
3066 # 037E => Common
3067 # 037F => $missing
3068 # 0384 => Greek
3069 #
3070 # For binary properties, the final non-comment column is absent, and
3071 # assumed to be 'Y'.
3072
3073 foreach my $range (split "\n", $swash->{'LIST'}) {
3074 $range =~ s/ \s* (?: \# .* )? $ //xg; # rmv trailing space, comments
3075
3076 # Find the beginning and end of the range on the line
3077 my ($hex_begin, $hex_end, $map) = split "\t", $range;
3078 my $begin = hex $hex_begin;
3079 my $end = (defined $hex_end && $hex_end ne "")
3080 ? hex $hex_end
3081 : $begin;
3082
92bcf67b
KW
3083 # Each time through the loop (after the first):
3084 # $invlist[-2] contains the beginning of the previous range processed
3085 # $invlist[-1] contains the end+1 of the previous range processed
3086 # $invmap[-2] contains the value of the previous range processed
3087 # $invmap[-1] contains the default value for missing ranges ($missing)
3088 #
3089 # Thus, things are set up for the typical case of a new non-adjacent
3090 # range of non-missings to be added. But, if the new range is
dc8d8ea6 3091 # adjacent, it needs to replace the [-1] element; and if the new
92bcf67b
KW
3092 # range is a multiple value of the previous one, it needs to be added
3093 # to the [-2] map element.
3094
3095 # The first time through, everything will be empty. If the property
3096 # doesn't have a range that begins at 0, add one that maps to $missing
62b3b855
KW
3097 if (! @invlist) {
3098 if ($begin != 0) {
3099 push @invlist, 0;
3100 push @invmap, $missing;
3101 }
3102 }
e35c6019
KW
3103 elsif (@invlist > 1 && $invlist[-2] == $begin) {
3104
3105 # Here we handle the case where the input has multiple entries for
3106 # each code point. mktables should have made sure that each such
3107 # range contains only one code point. At this point, $invlist[-1]
3108 # is the $missing that was added at the end of the last loop
3109 # iteration, and [-2] is the last real input code point, and that
3110 # code point is the same as the one we are adding now, making the
3111 # new one a multiple entry. Add it to the existing entry, either
3112 # by pushing it to the existing list of multiple entries, or
3113 # converting the single current entry into a list with both on it.
3114 # This is all we need do for this iteration.
3115
3116 if ($end != $begin) {
294705a8 3117 croak __PACKAGE__, ":prop_invmap: Multiple maps per code point in '$prop' require single-element ranges: begin=$begin, end=$end, map=$map";
e35c6019
KW
3118 }
3119 if (! ref $invmap[-2]) {
3120 $invmap[-2] = [ $invmap[-2], $map ];
3121 }
3122 else {
3123 push @{$invmap[-2]}, $map;
3124 }
3125 $has_multiples = 1;
3126 next;
3127 }
62b3b855
KW
3128 elsif ($invlist[-1] == $begin) {
3129
3130 # If the input isn't in the most compact form, so that there are
3131 # two adjacent ranges that map to the same thing, they should be
d11155ec
KW
3132 # combined (EXCEPT where the arrays require adjustments, in which
3133 # case everything is already set up correctly). This happens in
3134 # our constructed dt mapping, as Element [-2] is the map for the
3135 # latest range so far processed. Just set the beginning point of
3136 # the map to $missing (in invlist[-1]) to 1 beyond where this
3137 # range ends. For example, in
62b3b855
KW
3138 # 12\t13\tXYZ
3139 # 14\t17\tXYZ
3140 # we have set it up so that it looks like
3141 # 12 => XYZ
3142 # 14 => $missing
3143 #
3144 # We now see that it should be
3145 # 12 => XYZ
3146 # 18 => $missing
d11155ec 3147 if (! $requires_adjustment && @invlist > 1 && ( (defined $map)
c887f93f
KW
3148 ? $invmap[-2] eq $map
3149 : $invmap[-2] eq 'Y'))
3150 {
62b3b855
KW
3151 $invlist[-1] = $end + 1;
3152 next;
3153 }
3154
3155 # Here, the range started in the previous iteration that maps to
3156 # $missing starts at the same code point as this range. That
3157 # means there is no gap to fill that that range was intended for,
3158 # so we just pop it off the parallel arrays.
3159 pop @invlist;
3160 pop @invmap;
3161 }
3162
3163 # Add the range beginning, and the range's map.
3164 push @invlist, $begin;
d11155ec 3165 if ($returned_prop eq 'ToDm') {
62b3b855
KW
3166
3167 # The decomposition maps are either a line like <hangul syllable>
3168 # which are to be taken as is; or a sequence of code points in hex
3169 # and separated by blanks. Convert them to decimal, and if there
3170 # is more than one, use an anonymous array as the map.
3171 if ($map =~ /^ < /x) {
3172 push @invmap, $map;
3173 }
3174 else {
bea2c146 3175 my @map = split " ", $map;
62b3b855
KW
3176 if (@map == 1) {
3177 push @invmap, $map[0];
3178 }
3179 else {
3180 push @invmap, \@map;
3181 }
3182 }
3183 }
3184 else {
3185
3186 # Otherwise, convert hex formatted list entries to decimal; add a
3187 # 'Y' map for the missing value in binary properties, or
3188 # otherwise, use the input map unchanged.
3189 $map = ($format eq 'x')
3190 ? hex $map
3191 : $format eq 'b'
3192 ? 'Y'
3193 : $map;
3194 push @invmap, $map;
3195 }
3196
3197 # We just started a range. It ends with $end. The gap between it and
3198 # the next element in the list must be filled with a range that maps
3199 # to the default value. If there is no gap, the next iteration will
3200 # pop this, unless there is no next iteration, and we have filled all
3201 # of the Unicode code space, so check for that and skip.
3202 if ($end < $MAX_UNICODE_CODEPOINT) {
3203 push @invlist, $end + 1;
3204 push @invmap, $missing;
3205 }
3206 }
3207
3208 # If the property is empty, make all code points use the value for missing
3209 # ones.
3210 if (! @invlist) {
3211 push @invlist, 0;
3212 push @invmap, $missing;
3213 }
3214
647396da 3215 # And add in standard element that all non-Unicode code points map to:
62b3b855
KW
3216 # $missing
3217 push @invlist, $MAX_UNICODE_CODEPOINT + 1;
3218 push @invmap, $missing;
3219
3220 # The second component of the map are those values that require
3221 # non-standard specification, stored in SPECIALS. These override any
3222 # duplicate code points in LIST. If we are using a proxy, we may have
3223 # already set $overrides based on the proxy.
3224 $overrides = $swash->{'SPECIALS'} unless defined $overrides;
3225 if ($overrides) {
3226
3227 # A negative $overrides implies that the SPECIALS should be ignored,
d11155ec 3228 # and a simple 'a' list is the value.
62b3b855 3229 if ($overrides < 0) {
d11155ec 3230 $format = 'a';
62b3b855
KW
3231 }
3232 else {
3233
3234 # Currently, all overrides are for properties that normally map to
3235 # single code points, but now some will map to lists of code
3236 # points (but there is an exception case handled below).
d11155ec 3237 $format = 'al';
62b3b855
KW
3238
3239 # Look through the overrides.
3240 foreach my $cp_maybe_utf8 (keys %$overrides) {
3241 my $cp;
3242 my @map;
3243
3244 # If the overrides came from SPECIALS, the code point keys are
3245 # packed UTF-8.
3246 if ($overrides == $swash->{'SPECIALS'}) {
3247 $cp = unpack("C0U", $cp_maybe_utf8);
3248 @map = unpack "U0U*", $swash->{'SPECIALS'}{$cp_maybe_utf8};
3249
3250 # The empty string will show up unpacked as an empty
3251 # array.
d11155ec 3252 $format = 'ale' if @map == 0;
62b3b855
KW
3253 }
3254 else {
3255
3256 # But if we generated the overrides, we didn't bother to
3257 # pack them, and we, so far, do this only for properties
d11155ec 3258 # that are 'a' ones.
62b3b855
KW
3259 $cp = $cp_maybe_utf8;
3260 @map = hex $overrides->{$cp};
d11155ec 3261 $format = 'a';
62b3b855
KW
3262 }
3263
3264 # Find the range that the override applies to.
3265 my $i = _search_invlist(\@invlist, $cp);
3266 if ($cp < $invlist[$i] || $cp >= $invlist[$i + 1]) {
294705a8 3267 croak __PACKAGE__, "::prop_invmap: wrong_range, cp=$cp; i=$i, current=$invlist[$i]; next=$invlist[$i + 1]"
62b3b855
KW
3268 }
3269
3270 # And what that range currently maps to
3271 my $cur_map = $invmap[$i];
3272
3273 # If there is a gap between the next range and the code point
3274 # we are overriding, we have to add elements to both arrays to
3275 # fill that gap, using the map that applies to it, which is
3276 # $cur_map, since it is part of the current range.
3277 if ($invlist[$i + 1] > $cp + 1) {
3278 #use feature 'say';
3279 #say "Before splice:";
3280 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3281 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3282 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3283 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3284 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3285
3286 splice @invlist, $i + 1, 0, $cp + 1;
3287 splice @invmap, $i + 1, 0, $cur_map;
3288
3289 #say "After splice:";
3290 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3291 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3292 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3293 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3294 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3295 }
3296
3297 # If the remaining portion of the range is multiple code
3298 # points (ending with the one we are replacing, guaranteed by
3299 # the earlier splice). We must split it into two
3300 if ($invlist[$i] < $cp) {
3301 $i++; # Compensate for the new element
3302
3303 #use feature 'say';
3304 #say "Before splice:";
3305 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3306 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3307 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3308 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3309 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3310
3311 splice @invlist, $i, 0, $cp;
3312 splice @invmap, $i, 0, 'dummy';
3313
3314 #say "After splice:";
3315 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3316 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3317 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3318 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3319 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3320 }
3321
3322 # Here, the range we are overriding contains a single code
3323 # point. The result could be the empty string, a single
3324 # value, or a list. If the last case, we use an anonymous
3325 # array.
3326 $invmap[$i] = (scalar @map == 0)
3327 ? ""
3328 : (scalar @map > 1)
3329 ? \@map
3330 : $map[0];
3331 }
3332 }
3333 }
3334 elsif ($format eq 'x') {
3335
647396da
KW
3336 # All hex-valued properties are really to code points, and have been
3337 # converted to decimal.
5bbfa552 3338 $format = 's';
62b3b855 3339 }
d11155ec
KW
3340 elsif ($returned_prop eq 'ToDm') {
3341 $format = 'ad';
62b3b855
KW
3342 }
3343 elsif ($format eq 'sw') { # blank-separated elements to form a list.
3344 map { $_ = [ split " ", $_ ] if $_ =~ / / } @invmap;
3345 $format = 'sl';
3346 }
3347 elsif ($returned_prop eq 'ToNameAlias') {
3348
3349 # This property currently doesn't have any lists, but theoretically
3350 # could
3351 $format = 'sl';
3352 }
b0b13ada 3353 elsif ($returned_prop eq 'ToPerlDecimalDigit') {
d11155ec 3354 $format = 'ae';
b0b13ada 3355 }
4f143a72
KW
3356 elsif ($returned_prop eq 'ToNv') {
3357
3358 # The one property that has this format is stored as a delta, so needs
3359 # to indicate that need to add code point to it.
3360 $format = 'ar';
3361 }
b577d4a6 3362 elsif ($format ne 'n' && $format ne 'a') {
62b3b855
KW
3363
3364 # All others are simple scalars
3365 $format = 's';
3366 }
e35c6019 3367 if ($has_multiples && $format !~ /l/) {
294705a8 3368 croak __PACKAGE__, "::prop_invmap: Wrong format '$format' for prop_invmap('$prop'); should indicate has lists";
e35c6019 3369 }
62b3b855
KW
3370
3371 return (\@invlist, \@invmap, $format, $missing);
3372}
3373
55d7b906 3374=head2 Unicode::UCD::UnicodeVersion
10a6ecd2 3375
a452d459
KW
3376This returns the version of the Unicode Character Database, in other words, the
3377version of the Unicode standard the database implements. The version is a
3378string of numbers delimited by dots (C<'.'>).
10a6ecd2
JH
3379
3380=cut
3381
3382my $UNICODEVERSION;
3383
3384sub UnicodeVersion {
3385 unless (defined $UNICODEVERSION) {
3386 openunicode(\$VERSIONFH, "version");
ce066323 3387 local $/ = "\n";
10a6ecd2
JH
3388 chomp($UNICODEVERSION = <$VERSIONFH>);
3389 close($VERSIONFH);
3390 croak __PACKAGE__, "::VERSION: strange version '$UNICODEVERSION'"
3391 unless $UNICODEVERSION =~ /^\d+(?:\.\d+)+$/;
3392 }
e80c2d9d 3393 $v_unicode_version = pack "C*", split /\./, $UNICODEVERSION;
10a6ecd2
JH
3394 return $UNICODEVERSION;
3395}
3aa957f9 3396
a452d459
KW
3397=head2 B<Blocks versus Scripts>
3398
3399The difference between a block and a script is that scripts are closer
3400to the linguistic notion of a set of code points required to present
3401languages, while block is more of an artifact of the Unicode code point
3402numbering and separation into blocks of (mostly) 256 code points.
3403
3404For example the Latin B<script> is spread over several B<blocks>, such
3405as C<Basic Latin>, C<Latin 1 Supplement>, C<Latin Extended-A>, and
3406C<Latin Extended-B>. On the other hand, the Latin script does not
3407contain all the characters of the C<Basic Latin> block (also known as
3408ASCII): it includes only the letters, and not, for example, the digits
3409or the punctuation.
3410
3411For blocks see L<http://www.unicode.org/Public/UNIDATA/Blocks.txt>
3412
3413For scripts see UTR #24: L<http://www.unicode.org/unicode/reports/tr24/>
3414
3415=head2 B<Matching Scripts and Blocks>
3416
3417Scripts are matched with the regular-expression construct
3418C<\p{...}> (e.g. C<\p{Tibetan}> matches characters of the Tibetan script),
f200dd12 3419while C<\p{Blk=...}> is used for blocks (e.g. C<\p{Blk=Tibetan}> matches
a452d459
KW
3420any of the 256 code points in the Tibetan block).
3421
430fe03d
KW
3422=head2 Old-style versus new-style block names
3423
3424Unicode publishes the names of blocks in two different styles, though the two
3425are equivalent under Unicode's loose matching rules.
3426
3427The original style uses blanks and hyphens in the block names (except for
3428C<No_Block>), like so:
3429
3430 Miscellaneous Mathematical Symbols-B
3431
3432The newer style replaces these with underscores, like this:
3433
3434 Miscellaneous_Mathematical_Symbols_B
3435
3436This newer style is consistent with the values of other Unicode properties.
3437To preserve backward compatibility, all the functions in Unicode::UCD that
3438return block names (except one) return the old-style ones. That one function,
3439L</prop_value_aliases()> can be used to convert from old-style to new-style:
3440
3441 my $new_style = prop_values_aliases("block", $old_style);
3442
3443Perl also has single-form extensions that refer to blocks, C<In_Cyrillic>,
3444meaning C<Block=Cyrillic>. These have always been written in the new style.
3445
3446To convert from new-style to old-style, follow this recipe:
3447
3448 $old_style = charblock((prop_invlist("block=$new_style"))[0]);
3449
3450(which finds the range of code points in the block using C<prop_invlist>,
3451gets the lower end of the range (0th element) and then looks up the old name
3452for its block using C<charblock>).
3453
7620cb10
KW
3454Note that starting in Unicode 6.1, many of the block names have shorter
3455synonyms. These are always given in the new style.
3456
8b731da2
JH
3457=head1 BUGS
3458
3459Does not yet support EBCDIC platforms.
3460
561c79ed
JH
3461=head1 AUTHOR
3462
a18e976f 3463Jarkko Hietaniemi. Now maintained by perl5 porters.
561c79ed
JH
3464
3465=cut
3466
34671;