1 ## !!!!!!!!!!!!!! IF YOU MODIFY THIS FILE !!!!!!!!!!!!!!!!!!!!!!!!!
2 ## Any files created or read by this program should be listed in 'mktables.lst'
5 require 5.008; # Needs pack "U". Probably safest to run on 5.8.x
11 ## mktables -- create the runtime Perl Unicode files (lib/unicore/**/*.pl)
12 ## from the Unicode database files (lib/unicore/*.txt).
15 ## "Fuzzy" means this section in Unicode TR18:
17 ## The recommended names for UCD properties and property values are in
18 ## PropertyAliases.txt [Prop] and PropertyValueAliases.txt
19 ## [PropValue]. There are both abbreviated names and longer, more
20 ## descriptive names. It is strongly recommended that both names be
21 ## recognized, and that loose matching of property names be used,
22 ## whereby the case distinctions, whitespace, hyphens, and underbar
25 ## Base names already used in lib/gc_sc (for avoiding 8.3 conflicts)
32 my $MakeTestScript = 0;
35 my $FileList = "$0.lst";
40 my $arg = shift @ARGV;
43 } elsif ($arg eq '-q') {
45 } elsif ($arg eq '-w') {
46 $AlwaysWrite = 1; # update the files even if they havent changed
48 } elsif ($arg eq '-check') {
49 my $this = shift @ARGV;
52 print "Skipping as check params are not the same.\n";
55 } elsif ($arg eq '-maketest') {
57 } elsif ($arg eq '-makelist') {
59 } elsif ($arg eq '-C' && defined ($UseDir = shift)) {
60 -d $UseDir or die "Unknown directory '$UseDir'";
61 } elsif ($arg eq '-L' && defined ($FileList = shift)) {
62 -e $FileList or die "Filelist '$FileList' doesn't appear to exist!";
64 die "usage: $0 [-v|-q|-w|-C dir|-L filelist] [-maketest] [-makelist]\n",
65 " -v : Verbose Mode\n",
67 " -w : Write files regardless\n",
68 " -maketest : Make test script\n",
69 " -makelist : Rewrite the file list based on current setup\n",
70 " -L filelist : Use this file list, (defaults to $0.lst)\n",
71 " -C dir : Change to this directory before proceeding\n",
72 " -check A B : Executes only if A and B are the same\n";
77 print "Reading file list '$FileList'\n"
79 open my $fh,"<",$FileList or die "Failed to read '$FileList':$!";
82 for my $list ( \@input, \@output ) {
85 next if /^ \s* (?: \# .* )? $/x;
87 my ( $file ) = split /\t/, $_;
91 @$list = grep !$dupe{ $_ }++, @$list;
94 die "No input or output files in '$FileList'!"
95 if !@input or !@output;
97 foreach my $file (@output) {
102 print "Expecting ".scalar( @input )." input files. ",
103 "Checking ".scalar( @output )." output files.\n";
105 # we set maxtime to be the youngest input file, including $0 itself.
106 my $maxtime = -M $0; # do this before the chdir!
108 chdir $UseDir or die "Failed to chdir to '$UseDir':$!";
110 foreach my $in (@input) {
112 die "Missing input file '$in'" unless defined $time;
113 $maxtime = $time if $maxtime < $time;
116 # now we check to see if any output files are older than maxtime, if
117 # they are we need to continue on, otherwise we can presumably bail.
119 foreach my $out (@output) {
121 print "'$out' is missing.\n"
126 if ( -M $out > $maxtime ) {
127 print "'$out' is too old.\n"
134 print "Files seem to be ok, not bothering to rebuild.\n";
137 print "Must rebuild tables.\n"
141 print "Not checking filelist.\n";
144 chdir $UseDir or die "Failed to chdir to '$UseDir':$!";
148 foreach my $lib ('To', 'lib',
149 map {File::Spec->catdir("lib",$_)}
150 qw(gc_sc dt bc hst ea jt lb nt ccc)) {
152 mkdir $lib, 0755 or die "mkdir '$lib': $!";
155 my $LastUnicodeCodepoint = 0x10FFFF; # As of Unicode 5.1.
158 # !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
159 # This file is built by $0 from e.g. UnicodeData.txt.
160 # Any changes made here will be lost!
164 my $INTERNAL_ONLY=<<"EOF";
165 # This file is for internal use by the Perl program only. The format and even
166 # name or existence of this file are subject to change without notice. Don't
172 my $filename = shift;
173 return unless -e $filename;
174 return if CORE::unlink($filename);
175 # We might need write permission
176 chmod 0777, $filename;
177 CORE::unlink($filename) or die "Couldn't unlink $filename: $!\n";
181 ## Given a filename and a reference to an array of lines,
182 ## write the lines to the file only if the contents have not changed.
183 ## Filename can be given as an arrayref of directory names
185 sub WriteIfChanged($\@)
190 $file = File::Spec->catfile(@$file) if ref $file;
192 my $TextToWrite = join '', @$lines;
193 if (open IN, $file) {
195 my $PreviousText = <IN>;
197 if ($PreviousText eq $TextToWrite) {
198 print "$file unchanged.\n" if $Verbose;
199 return unless $AlwaysWrite;
202 force_unlink ($file);
203 if (not open OUT, ">$file") {
204 die "$0: can't open $file for output: $!\n";
206 print "$file written.\n" if $Verbose;
208 print OUT $TextToWrite;
213 ## The main datastructure (a "Table") represents a set of code points that
214 ## are part of a particular quality (that are part of \pL, \p{InGreek},
215 ## etc.). They are kept as ranges of code points (starting and ending of
218 ## For example, a range ASCII LETTERS would be represented as:
219 ## [ [ 0x41 => 0x5A, 'UPPER' ],
220 ## [ 0x61 => 0x7A, 'LOWER, ] ]
222 sub RANGE_START() { 0 } ## index into range element
223 sub RANGE_END() { 1 } ## index into range element
224 sub RANGE_NAME() { 2 } ## index into range element
226 ## Conceptually, these should really be folded into the 'Table' objects
234 ## Turn something like
243 $name =~ s/(?<![a-z])(\w)/\u$1/g;
244 $name =~ s/[-_\s]+//g;
246 $CanonicalToOrig{$name} = $orig if not $CanonicalToOrig{$name};
252 ## Store the alias definitions for later use.
263 ## Most of the work with aliases doesn't occur here,
264 ## but rather in utf8_heavy.pl, which uses PVA.pl,
266 # Placate the warnings about used only once. (They are used again, but
267 # via a typeglob lookup)
268 %utf8::PropertyAlias = ();
269 %utf8::PA_reverse = ();
270 %utf8::PropValueAlias = ();
271 %utf8::PVA_reverse = ();
272 %utf8::PVA_abbr_map = ();
274 open PA, "< PropertyAliases.txt"
275 or confess "Can't open PropertyAliases.txt: $!";
281 my ($abbrev, $name) = split /\s*;\s*/;
282 next if $abbrev eq "n/a";
283 $PropertyAlias{$abbrev} = $name;
284 $PA_reverse{$name} = $abbrev;
286 # The %utf8::... versions use japhy's code originally from utf8_pva.pl
287 # However, it's moved here so that we build the tables at runtime.
288 tr/ _-//d for $abbrev, $name;
289 $utf8::PropertyAlias{lc $abbrev} = $name;
290 $utf8::PA_reverse{lc $name} = $abbrev;
294 open PVA, "< PropValueAliases.txt"
295 or confess "Can't open PropValueAliases.txt: $!";
301 my ($prop, @data) = split /\s*;\s*/;
303 if ($prop eq 'ccc') {
304 $PropValueAlias{$prop}{$data[1]} = [ @data[0,2] ];
305 $PVA_reverse{$prop}{$data[2]} = [ @data[0,1] ];
308 next if $data[0] eq "n/a";
309 $PropValueAlias{$prop}{$data[0]} = $data[1];
310 $PVA_reverse{$prop}{$data[1]} = $data[0];
313 shift @data if $prop eq 'ccc';
314 next if $data[0] eq "n/a";
316 $data[1] =~ tr/ _-//d;
317 $utf8::PropValueAlias{$prop}{lc $data[0]} = $data[1];
318 $utf8::PVA_reverse{$prop}{lc $data[1]} = $data[0];
320 my $abbr_class = ($prop eq 'gc' or $prop eq 'sc') ? 'gc_sc' : $prop;
321 $utf8::PVA_abbr_map{$abbr_class}{lc $data[0]} = $data[0];
325 # backwards compatibility for L& -> LC
326 $utf8::PropValueAlias{gc}{'l&'} = $utf8::PropValueAlias{gc}{lc};
327 $utf8::PVA_abbr_map{gc_sc}{'l&'} = $utf8::PVA_abbr_map{gc_sc}{lc};
333 ## Associates a property ("Greek", "Lu", "Assigned",...) with a Table.
336 ## New_Prop(In => 'Greek', $Table, Desc => 'Greek Block', Fuzzy => 1);
338 ## Normally, these parameters are set when the Table is created (when the
339 ## Table->New constructor is called), but there are times when it needs to
340 ## be done after-the-fact...)
344 my $Type = shift; ## "Is" or "In";
348 ## remaining args are optional key/val
351 my $Fuzzy = delete $Args{Fuzzy};
352 my $Desc = delete $Args{Desc}; # description
354 $Name = CanonicalName($Name) if $Fuzzy;
356 ## sanity check a few args
357 if (%Args or ($Type ne 'Is' and $Type ne 'In') or not ref $Table) {
358 confess "$0: bad args to New_Prop"
361 if (not $TableInfo{$Type}->{$Name})
363 $TableInfo{$Type}->{$Name} = $Table;
364 $TableDesc{$Type}->{$Name} = $Desc;
366 $FuzzyNames{$Type}->{$Name} = $Name;
373 ## Creates a new Table object.
375 ## Args are key/value pairs:
376 ## In => Name -- Name of "In" property to be associated with
377 ## Is => Name -- Name of "Is" property to be associated with
378 ## Fuzzy => Boolean -- True if name can be accessed "fuzzily"
379 ## Desc => String -- Description of the property
381 ## No args are required.
388 my $Table = bless [], $class;
390 my $Fuzzy = delete $Args{Fuzzy};
391 my $Desc = delete $Args{Desc};
393 for my $Type ('Is', 'In')
395 if (my $Name = delete $Args{$Type}) {
396 New_Prop($Type => $Name, $Table, Desc => $Desc, Fuzzy => $Fuzzy);
400 ## shouldn't have any left over
402 confess "$0: bad args to Table->New"
410 ## Returns the maximum code point currently in the table.
414 my $last = $_[0]->[-1]; ## last code point
415 confess "oops" unless $last; ## must have code points to have a max
416 return $last->[RANGE_END];
420 ## Replaces the codepoints in the Table with those in the Table given
421 ## as an arg. (NOTE: this is not a "deep copy").
423 sub Table::Replace($$)
425 my $Table = shift; #self
432 ## Given a new code point, make the last range of the Table extend to
433 ## include the new (and all intervening) code points.
435 ## Takes the time to make sure that the extension is valid.
439 my $Table = shift; #self
440 my $codepoint = shift;
442 my $PrevMax = $Table->Max;
444 confess "oops ($codepoint <= $PrevMax)" if $codepoint <= $PrevMax;
446 $Table->ExtendNoCheck($codepoint);
451 ## Given a new code point, make the last range of the Table extend to
452 ## include the new (and all intervening) code points.
454 ## Does NOT check that the extension is valid. Assumes that the caller
455 ## has already made this check.
457 sub Table::ExtendNoCheck
459 ## Optmized adding: Assumes $Table and $codepoint as parms
460 $_[0]->[-1]->[RANGE_END] = $_[1];
464 ## Given a code point range start and end (and optional name), blindly
465 ## append them to the list of ranges for the Table.
467 ## NOTE: Code points must be added in strictly ascending numeric order.
469 sub Table::RawAppendRange
471 my $Table = shift; #self
475 $name = "" if not defined $name; ## warning: $name can be "0"
477 push @$Table, [ $start, # RANGE_START
479 $name ]; # RANGE_NAME
483 ## Given a code point (and optional name), add it to the Table.
485 ## NOTE: Code points must be added in strictly ascending numeric order.
489 my $Table = shift; #self
490 my $codepoint = shift;
492 $name = "" if not defined $name; ## warning: $name can be "0"
495 ## If we've already got a range working, and this code point is the next
496 ## one in line, and if the name is the same, just extend the current range.
498 my $last = $Table->[-1];
501 $last->[RANGE_END] == $codepoint - 1
503 $last->[RANGE_NAME] eq $name)
505 $Table->ExtendNoCheck($codepoint);
509 $Table->RawAppendRange($codepoint, $codepoint, $name);
514 ## Given a code point range starting value and ending value (and name),
515 ## Add the range to the Table.
517 ## NOTE: Code points must be added in strictly ascending numeric order.
519 sub Table::AppendRange
521 my $Table = shift; #self
525 $name = "" if not defined $name; ## warning: $name can be "0"
527 $Table->Append($start, $name);
528 $Table->Extend($end) if $end > $start;
532 ## Return a new Table that represents all code points not in the Table.
536 my $Table = shift; #self
538 my $New = Table->New();
540 for my $range (@$Table)
542 my $start = $range->[RANGE_START];
543 my $end = $range->[RANGE_END];
544 if ($start-1 >= $max+1) {
545 $New->AppendRange($max+1, $start-1, "");
549 if ($max+1 < $LastUnicodeCodepoint) {
550 $New->AppendRange($max+1, $LastUnicodeCodepoint);
556 ## Merges any number of other tables with $self, returning the new table.
557 ## (existing tables are not modified)
560 ## Args may be Tables, or individual code points (as integers).
562 ## Can be called as either a constructor or a method.
566 shift(@_) if not ref $_[0]; ## if called as a constructor, lose the class
569 ## Accumulate all records from all tables
571 for my $Arg (@Tables)
574 ## arg is a table -- get its ranges
575 push @Records, @$Arg;
577 ## arg is a codepoint, make a range
578 push @Records, [ $Arg, $Arg ]
582 ## sort by range start, with longer ranges coming first.
583 my ($first, @Rest) = sort {
584 ($a->[RANGE_START] <=> $b->[RANGE_START])
586 ($b->[RANGE_END] <=> $b->[RANGE_END])
589 my $New = Table->New();
591 ## Ensuring the first range is there makes the subsequent loop easier
592 $New->AppendRange($first->[RANGE_START],
593 $first->[RANGE_END]);
595 ## Fold in records so long as they add new information.
598 my $start = $set->[RANGE_START];
599 my $end = $set->[RANGE_END];
600 if ($start > $New->Max) {
601 $New->AppendRange($start, $end);
602 } elsif ($end > $New->Max) {
603 $New->ExtendNoCheck($end);
611 ## Given a filename, write a representation of the Table to a file.
612 ## May have an optional comment as a 2nd arg.
613 ## Filename may actually be an arrayref of directories
617 my $Table = shift; #self
618 my $filename = shift;
623 # files in subdirectories are internal-use-only
624 push @OUT, $INTERNAL_ONLY if ref $filename;
626 if (defined $comment) {
627 $comment =~ s/\s+\Z//;
628 $comment =~ s/^/# /gm;
629 push @OUT, "#\n$comment\n#\n";
631 push @OUT, "return <<'END';\n";
633 for my $set (@$Table)
635 my $start = $set->[RANGE_START];
636 my $end = $set->[RANGE_END];
637 my $name = $set->[RANGE_NAME];
639 if ($start == $end) {
640 push @OUT, sprintf "%04X\t\t%s\n", $start, $name;
642 push @OUT, sprintf "%04X\t%04X\t%s\n", $start, $end, $name;
648 WriteIfChanged($filename, @OUT);
651 ## This used only for making the test script.
656 return 0 if $code <= 0x0000; ## don't use null
657 return 0 if $code >= $LastUnicodeCodepoint; ## keep in range
658 return 0 if ($code >= 0xD800 and $code <= 0xDFFF); ## no surrogates
659 return 0 if ($code >= 0xFDD0 and $code <= 0xFDEF); ## utf8.c says no good
660 return 0 if (($code & 0xFFFF) == 0xFFFE); ## utf8.c says no good
661 return 0 if (($code & 0xFFFF) == 0xFFFF); ## utf8.c says no good
665 ## Return a code point that's part of the table.
666 ## Returns nothing if the table is empty (or covers only surrogates).
667 ## This used only for making the test script.
670 my $Table = shift; #self
671 for my $set (@$Table) {
672 return $set->[RANGE_END] if IsUsable($set->[RANGE_END]);
677 ## Return a code point that's not part of the table
678 ## Returns nothing if the table covers all code points.
679 ## This used only for making the test script.
680 sub Table::InvalidCode
682 my $Table = shift; #self
684 return 0x1234 if not @$Table;
686 for my $set (@$Table)
688 if (IsUsable($set->[RANGE_END] + 1))
690 return $set->[RANGE_END] + 1;
693 if (IsUsable($set->[RANGE_START] - 1))
695 return $set->[RANGE_START] - 1;
701 ###########################################################################
702 ###########################################################################
703 ###########################################################################
708 ## New_Alias(Is => 'All', SameAs => 'Any', Fuzzy => 1);
710 ## The args must be in that order, although the Fuzzy pair may be omitted.
712 ## This creates 'IsAll' as an alias for 'IsAny'
716 my $Type = shift; ## "Is" or "In"
718 my $SameAs = shift; # expecting "SameAs" -- just ignored
721 ## remaining args are optional key/val
724 my $Fuzzy = delete $Args{Fuzzy};
726 ## sanity check a few args
727 if (%Args or ($Type ne 'Is' and $Type ne 'In') or $SameAs ne 'SameAs') {
728 confess "$0: bad args to New_Alias"
731 $Alias = CanonicalName($Alias) if $Fuzzy;
733 if (not $TableInfo{$Type}->{$Name})
735 my $CName = CanonicalName($Name);
736 if ($TableInfo{$Type}->{$CName}) {
737 confess "$0: Use canonical form '$CName' instead of '$Name' for alias.";
739 confess "$0: don't have original $Type => $Name to make alias\n";
742 if ($TableInfo{$Alias}) {
743 confess "$0: already have original $Type => $Alias; can't make alias";
745 $AliasInfo{$Type}->{$Name} = $Alias;
747 $FuzzyNames{$Type}->{$Alias} = $Name;
753 ## All assigned code points
754 my $Assigned = Table->New(Is => 'Assigned',
755 Desc => "All assigned code points",
758 my $Name = Table->New(); ## all characters, individually by name
759 my $General = Table->New(); ## all characters, grouped by category
763 ## Simple Data::Dumper like. Good enough for our needs. We can't use the real
764 ## thing as we have to run under miniperl
770 if (ref $item eq 'ARRAY') {
771 push @lines, "[\n", simple_dumper (@$item), "],\n";
772 } elsif (ref $item eq 'HASH') {
773 push @lines, "{\n", simple_dumper (%$item), "},\n";
775 die "Can't cope with $item";
780 $copy =~ s/([\'\\])/\\$1/gs;
781 push @lines, "'$copy',\n";
783 push @lines, "undef,\n";
791 ## Process UnicodeData.txt (Categories, etc.)
793 # These are the character mappings as defined in the POSIX standard
794 # and in the case of PerlSpace and PerlWord as is defined in the test macros
795 # for binary strings. IOW, PerlWord is [A-Za-z_] and PerlSpace is [\f\r\n\t ]
796 # This differs from Word and the existing SpacePerl (note the prefix/suffix difference)
797 # which is basically the Unicode WhiteSpace without the vertical tab included
799 my %TRUE_POSIX_PERL_CC= (
800 PosixAlnum => { map { $_ => 1 } ( 0x0030..0x0039, 0x0041..0x005a, 0x0061..0x007a )},
801 PosixAlpha => { map { $_ => 1 } ( 0x0041..0x005a, 0x0061..0x007a )},
802 # Not Needed: Ascii => { map { $_ => 1 } ( 0x0000..0x007f )},
803 PosixBlank => { map { $_ => 1 } ( 0x0009, 0x0020 )},
804 PosixCntrl => { map { $_ => 1 } ( 0x0000..0x001f, 0x007f )},
805 PosixGraph => { map { $_ => 1 } ( 0x0021..0x007e )},
806 PosixLower => { map { $_ => 1 } ( 0x0061..0x007a )},
807 PosixPrint => { map { $_ => 1 } ( 0x0020..0x007e )},
808 PosixPunct => { map { $_ => 1 } ( 0x0021..0x002f, 0x003a..0x0040, 0x005b..0x0060, 0x007b..0x007e )},
809 PosixSpace => { map { $_ => 1 } ( 0x0009..0x000d, 0x0020 )},
810 PosixUpper => { map { $_ => 1 } ( 0x0041..0x005a )},
811 # Not needed: PosixXdigit => { map { $_ => 1 } ( 0x0030..0x0039, 0x0041..0x0046, 0x0061..0x0066 )},
812 PosixDigit => { map { $_ => 1 } ( 0x0030..0x0039 )},
814 PerlSpace => { map { $_ => 1 } ( 0x0009..0x000a, 0x000c..0x000d, 0x0020 )},
815 PerlWord => { map { $_ => 1 } ( 0x0030..0x0039, 0x0041..0x005a, 0x005f, 0x0061..0x007a )},
818 sub UnicodeData_Txt()
820 my $Bidi = Table->New();
821 my $Deco = Table->New();
822 my $Comb = Table->New();
823 my $Number = Table->New();
824 my $Mirrored = Table->New();#Is => 'Mirrored',
825 #Desc => "Mirrored in bidirectional text",
831 $DC{Can} = Table->New();
832 $DC{Com} = Table->New();
834 ## Initialize Broken Perl-generated categories
835 ## (Categories from UnicodeData.txt are auto-initialized in gencat)
837 Table->New(Is => 'Alnum', Desc => "[[:Alnum:]]", Fuzzy => 0);
839 Table->New(Is => 'Alpha', Desc => "[[:Alpha:]]", Fuzzy => 0);
841 Table->New(Is => 'ASCII', Desc => "[[:ASCII:]]", Fuzzy => 0);
843 Table->New(Is => 'Blank', Desc => "[[:Blank:]]", Fuzzy => 0);
845 Table->New(Is => 'Cntrl', Desc => "[[:Cntrl:]]", Fuzzy => 0);
847 Table->New(Is => 'Digit', Desc => "[[:Digit:]]", Fuzzy => 0);
849 Table->New(Is => 'Graph', Desc => "[[:Graph:]]", Fuzzy => 0);
851 Table->New(Is => 'Lower', Desc => "[[:Lower:]]", Fuzzy => 0);
853 Table->New(Is => 'Print', Desc => "[[:Print:]]", Fuzzy => 0);
855 Table->New(Is => 'Punct', Desc => "[[:Punct:]]", Fuzzy => 0);
857 Table->New(Is => 'Space', Desc => "[[:Space:]]", Fuzzy => 0);
859 Table->New(Is => 'Title', Desc => "[[:Title:]]", Fuzzy => 0);
861 Table->New(Is => 'Upper', Desc => "[[:Upper:]]", Fuzzy => 0);
863 Table->New(Is => 'XDigit', Desc => "[[:XDigit:]]", Fuzzy => 0);
865 Table->New(Is => 'Word', Desc => "[[:Word:]]", Fuzzy => 0);
867 Table->New(Is => 'SpacePerl', Desc => '\s', Fuzzy => 0);
869 Table->New(Is => 'VertSpace', Desc => '\v', Fuzzy => 0);
871 Table->New(Is => 'HorizSpace', Desc => '\h', Fuzzy => 0);
873 $To{Upper} = Table->New();
874 $To{Lower} = Table->New();
875 $To{Title} = Table->New();
876 $To{Digit} = Table->New();
878 foreach my $cat (keys %TRUE_POSIX_PERL_CC) {
879 $Cat{$cat} = Table->New(Is=>$cat, Fuzzy => 0);
884 my ($name, ## Name ("LATIN CAPITAL LETTER A")
885 $cat, ## Category ("Lu", "Zp", "Nd", etc.)
886 $code, ## Code point (as an integer)
889 my $MajorCat = substr($cat, 0, 1); ## L, M, Z, S, etc
891 $Assigned->$op($code);
892 $Name->$op($code, $name);
893 $General->$op($code, $cat);
895 ## add to the sub category (e.g. "Lu", "Nd", "Cf", ..)
896 $Cat{$cat} ||= Table->New(Is => $cat,
897 Desc => "General Category '$cat'",
899 $Cat{$cat}->$op($code);
901 ## add to the major category (e.g. "L", "N", "C", ...)
902 $Cat{$MajorCat} ||= Table->New(Is => $MajorCat,
903 Desc => "Major Category '$MajorCat'",
905 $Cat{$MajorCat}->$op($code);
907 ($General{$name} ||= Table->New)->$op($code, $name);
909 # 005F: SPACING UNDERSCORE
910 $Cat{Word}->$op($code) if $cat =~ /^[LMN]|Pc/;
911 $Cat{Alnum}->$op($code) if $cat =~ /^[LM]|Nd/;
912 $Cat{Alpha}->$op($code) if $cat =~ /^[LM]/;
915 ($cat =~ /Zs|Zl|Zp/ &&
916 $code != 0x200B) # 200B is ZWSP which is for line break control
917 # and therefore it is not part of "space" even
918 # while it is "Zs" in some versions of Unicode.
919 # In 5.1 it is Cf, so this line is no longer
921 || $code == 0x0009 # 0009: HORIZONTAL TAB
922 || $code == 0x000A # 000A: LINE FEED
923 || $code == 0x000B # 000B: VERTICAL TAB
924 || $code == 0x000C # 000C: FORM FEED
925 || $code == 0x000D # 000D: CARRIAGE RETURN
926 || $code == 0x0085 # 0085: NEL
930 $Cat{Space}->$op($code) if $isspace;
932 $Cat{SpacePerl}->$op($code) if $isspace
933 && $code != 0x000B; # Backward compat.
935 $Cat{VertSpace}->$op($code) if grep {$code == $_}
936 ( 0x0A..0x0D,0x85,0x2028,0x2029 );
938 $Cat{HorizSpace}->$op($code) if grep {$code == $_} (
939 0x09, 0x20, 0xa0, 0x1680, 0x180e, 0x2000, 0x2001, 0x2002,
940 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a,
941 0x202f, 0x205f, 0x3000
944 $Cat{Blank}->$op($code) if $isspace
945 && !($code == 0x000A ||
952 $Cat{Digit}->$op($code) if $cat eq "Nd";
953 $Cat{Upper}->$op($code) if $cat eq "Lu";
954 $Cat{Lower}->$op($code) if $cat eq "Ll";
955 $Cat{Title}->$op($code) if $cat eq "Lt";
956 $Cat{ASCII}->$op($code) if $code <= 0x007F;
957 $Cat{Cntrl}->$op($code) if $cat =~ /^C/;
958 my $isgraph = !$isspace && $cat !~ /Cc|Cs|Cn/;
959 $Cat{Graph}->$op($code) if $isgraph;
960 $Cat{Print}->$op($code) if $isgraph || $isspace;
961 $Cat{Punct}->$op($code) if $cat =~ /^P/;
963 $Cat{XDigit}->$op($code) if ($code >= 0x30 && $code <= 0x39) ## 0..9
964 || ($code >= 0x41 && $code <= 0x46) ## A..F
965 || ($code >= 0x61 && $code <= 0x66); ## a..f
967 foreach my $cat (keys %TRUE_POSIX_PERL_CC) {
968 if ($TRUE_POSIX_PERL_CC{$cat}{$code}) {
969 $Cat{$cat}->$op($code);
975 ## open and read file.....
976 if (not open IN, "UnicodeData.txt") {
977 die "$0: UnicodeData.txt: $!\n";
981 ## For building \p{_CombAbove} and \p{_CanonDCIJ}
983 my %_Above_HexCodes; ## Hexcodes for chars with $comb == 230 ("ABOVE")
985 my %CodeToDeco; ## Maps code to decomp. list for chars with first
986 ## decomp. char an "i" or "j" (for \p{_CanonDCIJ})
988 ## This is filled in as we go....
989 my $CombAbove = Table->New(Is => '_CombAbove',
990 Desc => '(for internal casefolding use)',
995 next unless /^[0-9A-Fa-f]+;/;
998 my ($hexcode, ## code point in hex (e.g. "0041")
999 $name, ## character name (e.g. "LATIN CAPITAL LETTER A")
1000 $cat, ## category (e.g. "Lu")
1001 $comb, ## Canonical combining class (e.g. "230")
1002 $bidi, ## directional category (e.g. "L")
1003 $deco, ## decomposition mapping
1004 $decimal, ## decimal digit value
1005 $digit, ## digit value
1006 $number, ## numeric value
1007 $mirrored, ## mirrored
1008 $unicode10, ## name in Unicode 1.0
1009 $comment, ## comment field
1010 $upper, ## uppercase mapping
1011 $lower, ## lowercase mapping
1012 $title, ## titlecase mapping
1013 ) = split(/\s*;\s*/);
1015 # Note that in Unicode 3.2 there will be names like
1016 # LINE FEED (LF), which probably means that \N{} needs
1017 # to cope also with LINE FEED and LF.
1018 $name = $unicode10 if $name eq '<control>' && $unicode10 ne '';
1020 my $code = hex($hexcode);
1022 if ($comb and $comb == 230) {
1023 $CombAbove->Append($code);
1024 $_Above_HexCodes{$hexcode} = 1;
1027 ## Used in building \p{_CanonDCIJ}
1028 if ($deco and $deco =~ m/^006[9A]\b/) {
1029 $CodeToDeco{$code} = $deco;
1033 ## There are a few pairs of lines like:
1034 ## AC00;<Hangul Syllable, First>;Lo;0;L;;;;;N;;;;;
1035 ## D7A3;<Hangul Syllable, Last>;Lo;0;L;;;;;N;;;;;
1036 ## that define ranges.
1038 if ($name =~ /^<(.+), (First|Last)>$/)
1041 gencat($name, $cat, $code, $2 eq 'First' ? 'Append' : 'Extend');
1042 #New_Prop(In => $name, $General{$name}, Fuzzy => 1);
1046 ## normal (single-character) lines
1047 gencat($name, $cat, $code, 'Append');
1049 # No Append() here since since several codes may map into one.
1050 $To{Upper}->RawAppendRange($code, $code, $upper) if $upper;
1051 $To{Lower}->RawAppendRange($code, $code, $lower) if $lower;
1052 $To{Title}->RawAppendRange($code, $code, $title) if $title;
1053 $To{Digit}->Append($code, $decimal) if length $decimal;
1055 $Bidi->Append($code, $bidi);
1056 $Comb->Append($code, $comb) if $comb;
1057 $Number->Append($code, $number) if length $number;
1059 length($decimal) and ($Number{De} ||= Table->New())->Append($code)
1061 length($digit) and ($Number{Di} ||= Table->New())->Append($code)
1063 length($number) and ($Number{Nu} ||= Table->New())->Append($code);
1065 $Mirrored->Append($code) if $mirrored eq "Y";
1067 $Bidi{$bidi} ||= Table->New();#Is => "bt/$bidi",
1068 #Desc => "Bi-directional category '$bidi'",
1070 $Bidi{$bidi}->Append($code);
1074 $Deco->Append($code, $deco);
1075 if ($deco =~/^<(\w+)>/)
1077 my $dshort = $PVA_reverse{dt}{ucfirst lc $1};
1078 $DC{Com}->Append($code);
1079 $dshort = $PVA_reverse{dt}{lc $1} unless $dshort ne "";
1080 die "No reverse for $1'" unless $dshort ne "";
1081 #$dshort = lc $dshort; # use lower case only
1082 $DC{$dshort} ||= Table->New();
1083 $DC{$dshort}->Append($code);
1087 $DC{Can}->Append($code);
1094 ## Read in the NameAliases.txt. It contains other normative names of code
1095 ## points not listed in UnicodeData.txt. This happens when there is an
1096 ## error in the name found after the data base was published, but instead of
1097 ## changing it, to avoid breaking any code that came to rely on the
1098 ## erroneous version, the correct name is added as an alias.
1100 my $NameAliases = Table->New();
1102 if (not open IN, "NameAliases.txt") {
1103 die "$0: NameAliases.txt: $!\n";
1108 next unless /^[0-9A-Fa-f]+;/;
1111 my ($hexcode, ## code point in hex (e.g. "0041")
1112 $name, ## character name (e.g. "LATIN CAPITAL LETTER A")
1113 ) = split(/\s*;\s*/);
1115 my $code = hex($hexcode);
1117 ## One is supposed to enter elements into tables in strictly increasing
1118 ## order, but this in fact works to append duplicate code points at
1119 ## the end of the table. The table is intended to be indexed by name
1122 $Name->RawAppendRange($code, $code, $name);
1128 ## Tidy up a few special cases....
1131 $Cat{Cn} = $Assigned->Invert; ## Cn is everything that doesn't exist
1132 New_Prop(Is => 'Cn',
1134 Desc => "General Category 'Cn' [not functional in Perl]",
1137 ## Unassigned is the same as 'Cn'
1138 New_Alias(Is => 'Unassigned', SameAs => 'Cn', Fuzzy => 0);
1140 $Cat{C}->Replace($Cat{C}->Merge($Cat{Cn})); ## Now merge in Cn into C
1143 # LC is Ll, Lu, and Lt.
1144 # (used to be L& or L_, but PropValueAliases.txt defines it as LC)
1145 New_Prop(Is => 'LC',
1146 Table->Merge(@Cat{qw[Ll Lu Lt]}),
1147 Desc => '[\p{Ll}\p{Lu}\p{Lt}]',
1150 ## Any and All are all code points.
1151 my $Any = Table->New(Is => 'Any',
1152 Desc => sprintf("[\\x{0000}-\\x{%X}]",
1153 $LastUnicodeCodepoint),
1155 $Any->RawAppendRange(0, $LastUnicodeCodepoint);
1157 New_Alias(Is => 'All', SameAs => 'Any', Fuzzy => 0);
1160 ## Build special properties for Perl's internal case-folding needs:
1161 ## \p{_CaseIgnorable}
1164 ## _CombAbove was built above. Others are built here....
1167 ## \p{_CaseIgnorable} is [\p{Mn}\0x00AD\x2010]
1168 New_Prop(Is => '_CaseIgnorable',
1169 Table->Merge($Cat{Mn},
1170 0x00AD, #SOFT HYPHEN
1172 Desc => '(for internal casefolding use)',
1176 ## \p{_CanonDCIJ} is fairly complex...
1177 my $CanonCDIJ = Table->New(Is => '_CanonDCIJ',
1178 Desc => '(for internal casefolding use)',
1180 ## It contains the ASCII 'i' and 'j'....
1181 $CanonCDIJ->Append(0x0069); # ASCII ord("i")
1182 $CanonCDIJ->Append(0x006A); # ASCII ord("j")
1183 ## ...and any character with a decomposition that starts with either of
1184 ## those code points, but only if the decomposition does not have any
1185 ## combining character with the "ABOVE" canonical combining class.
1186 for my $code (sort { $a <=> $b} keys %CodeToDeco)
1188 ## Need to ensure that all decomposition characters do not have
1189 ## a %HexCodeToComb in %AboveCombClasses.
1191 for my $deco_hexcode (split / /, $CodeToDeco{$code})
1193 if (exists $_Above_HexCodes{$deco_hexcode}) {
1194 ## one of the decmposition chars has an ABOVE combination
1195 ## class, so we're not interested in this one
1201 $CanonCDIJ->Append($code);
1208 ## Now dump the files.
1210 $Name->Write("Name.pl");
1214 foreach my $name (qw (PropertyAlias PA_reverse PropValueAlias
1215 PVA_reverse PVA_abbr_map)) {
1216 # Should I really jump through typeglob hoops just to avoid a
1217 # symbolic reference? (%{"utf8::$name})
1218 push @PVA, "\n", "\%utf8::$name = (\n",
1219 simple_dumper (%{$utf8::{$name}}), ");\n";
1222 WriteIfChanged("PVA.pl", @PVA);
1225 # $Bidi->Write("Bidirectional.pl");
1228 ["lib","bc","$_.pl"],
1229 "BidiClass category '$PropValueAlias{bc}{$_}'"
1233 $Comb->Write("CombiningClass.pl");
1234 for (keys %{ $PropValueAlias{ccc} }) {
1235 my ($code, $name) = @{ $PropValueAlias{ccc}{$_} };
1236 (my $c = Table->New())->Append($code);
1238 ["lib","ccc","$_.pl"],
1239 "CombiningClass category '$name'"
1243 $Deco->Write("Decomposition.pl");
1246 ["lib","dt","$_.pl"],
1247 "DecompositionType category '$PropValueAlias{dt}{$_}'"
1251 # $Number->Write("Number.pl");
1252 for (keys %Number) {
1254 ["lib","nt","$_.pl"],
1255 "NumericType category '$PropValueAlias{nt}{$_}'"
1259 # $General->Write("Category.pl");
1261 for my $to (sort keys %To) {
1262 $To{$to}->Write(["To","$to.pl"]);
1265 for (keys %{ $PropValueAlias{gc} }) {
1266 New_Alias(Is => $PropValueAlias{gc}{$_}, SameAs => $_, Fuzzy => 1);
1271 ## Process LineBreak.txt
1275 if (not open IN, "LineBreak.txt") {
1276 die "$0: LineBreak.txt: $!\n";
1279 my $Lbrk = Table->New();
1284 next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(\w+)/;
1286 my ($first, $last, $lbrk) = (hex($1), hex($2||""), $3);
1288 $Lbrk->Append($first, $lbrk);
1290 $Lbrk{$lbrk} ||= Table->New();
1291 $Lbrk{$lbrk}->Append($first);
1294 $Lbrk->Extend($last);
1295 $Lbrk{$lbrk}->Extend($last);
1300 # $Lbrk->Write("Lbrk.pl");
1305 ["lib","lb","$_.pl"],
1306 "Linebreak category '$PropValueAlias{lb}{$_}'"
1312 ## Process ArabicShaping.txt.
1314 sub ArabicShaping_txt()
1316 if (not open IN, "ArabicShaping.txt") {
1317 die "$0: ArabicShaping.txt: $!\n";
1320 my $ArabLink = Table->New();
1321 my $ArabLinkGroup = Table->New();
1327 next unless /^[0-9A-Fa-f]+;/;
1330 my ($hexcode, $name, $link, $linkgroup) = split(/\s*;\s*/);
1331 my $code = hex($hexcode);
1332 $ArabLink->Append($code, $link);
1333 $ArabLinkGroup->Append($code, $linkgroup);
1335 $JoinType{$link} ||= Table->New(Is => "JoinType$link");
1336 $JoinType{$link}->Append($code);
1340 # $ArabLink->Write("ArabLink.pl");
1341 # $ArabLinkGroup->Write("ArabLnkGrp.pl");
1344 for (keys %JoinType) {
1345 $JoinType{$_}->Write(
1346 ["lib","jt","$_.pl"],
1347 "JoiningType category '$PropValueAlias{jt}{$_}'"
1353 ## Process EastAsianWidth.txt.
1355 sub EastAsianWidth_txt()
1357 if (not open IN, "EastAsianWidth.txt") {
1358 die "$0: EastAsianWidth.txt: $!\n";
1365 next unless /^[0-9A-Fa-f]+(\.\.[0-9A-Fa-f]+)?;/;
1369 my ($hexcodes, $pv) = split(/\s*;\s*/);
1370 $EAW{$pv} ||= Table->New(Is => "EastAsianWidth$pv");
1371 my ($start, $end) = split(/\.\./, $hexcodes);
1373 $EAW{$pv}->AppendRange(hex($start), hex($end));
1375 $EAW{$pv}->Append(hex($start));
1383 ["lib","ea","$_.pl"],
1384 "EastAsianWidth category '$PropValueAlias{ea}{$_}'"
1390 ## Process HangulSyllableType.txt.
1392 sub HangulSyllableType_txt()
1394 if (not open IN, "HangulSyllableType.txt") {
1395 die "$0: HangulSyllableType.txt: $!\n";
1402 next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(\w+)/;
1403 my ($first, $last, $pv) = (hex($1), hex($2||""), $3);
1405 $HST{$pv} ||= Table->New(Is => "HangulSyllableType$pv");
1406 $HST{$pv}->Append($first);
1408 if ($last) { $HST{$pv}->Extend($last) }
1414 ["lib","hst","$_.pl"],
1415 "HangulSyllableType category '$PropValueAlias{hst}{$_}'"
1421 ## Process Jamo.txt.
1425 if (not open IN, "Jamo.txt") {
1426 die "$0: Jamo.txt: $!\n";
1428 my $Short = Table->New();
1432 next unless /^([0-9A-Fa-f]+)\s*;\s*(\w*)/;
1433 my ($code, $short) = (hex($1), $2);
1435 $Short->Append($code, $short);
1438 # $Short->Write("JamoShort.pl");
1442 ## Process Scripts.txt.
1448 if (not open(IN, "Scripts.txt")) {
1449 die "$0: Scripts.txt: $!\n";
1452 next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(.+?)\s*\#/;
1454 # Wait until all the scripts have been read since
1455 # they are not listed in numeric order.
1456 push @ScriptInfo, [ hex($1), hex($2||""), $3 ];
1460 # Now append the scripts properties in their code point order.
1463 my $Scripts = Table->New();
1465 for my $script (sort { $a->[0] <=> $b->[0] } @ScriptInfo)
1467 my ($first, $last, $name) = @$script;
1468 $Scripts->Append($first, $name);
1470 $Script{$name} ||= Table->New(Is => $name,
1471 Desc => "Script '$name'",
1473 $Script{$name}->Append($first, $name);
1476 $Scripts->Extend($last);
1477 $Script{$name}->Extend($last);
1481 # $Scripts->Write("Scripts.pl");
1483 ## Common is everything not explicitly assigned to a Script
1485 ## ***shouldn't this be intersected with \p{Assigned}? ******
1487 New_Prop(Is => 'Common',
1489 Desc => 'Pseudo-Script of codepoints not in other Unicode scripts',
1494 ## Given a name like "Close Punctuation", return a regex (that when applied
1495 ## with /i) matches any valid form of that name (e.g. "ClosePunctuation",
1496 ## "Close-Punctuation", etc.)
1498 ## Accept any space, dash, or underbar where in the official name there is
1499 ## space or a dash (or underbar, but there never is).
1505 $Name =~ s/[- _]/(?:[-_]|\\s+)?/g;
1510 ## Process Blocks.txt.
1514 my $Blocks = Table->New();
1517 if (not open IN, "Blocks.txt") {
1518 die "$0: Blocks.txt: $!\n";
1523 #next if not /Private Use$/;
1524 next if not /^([0-9A-Fa-f]+)\.\.([0-9A-Fa-f]+)\s*;\s*(.+?)\s*$/;
1526 my ($first, $last, $name) = (hex($1), hex($2), $3);
1528 $Blocks->Append($first, $name);
1530 $Blocks{$name} ||= Table->New(In => $name,
1531 Desc => "Block '$name'",
1533 $Blocks{$name}->Append($first, $name);
1535 if ($last and $last != $first) {
1536 $Blocks->Extend($last);
1537 $Blocks{$name}->Extend($last);
1542 # $Blocks->Write("Blocks.pl");
1546 ## Read in the PropList.txt. It contains extended properties not
1547 ## listed in the UnicodeData.txt, such as 'Other_Alphabetic':
1548 ## alphabetic but not of the general category L; many modifiers
1549 ## belong to this extended property category: while they are not
1550 ## alphabets, they are alphabetic in nature.
1556 if (not open IN, "PropList.txt") {
1557 die "$0: PropList.txt: $!\n";
1562 next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(.+?)\s*\#/;
1564 # Wait until all the extended properties have been read since
1565 # they are not listed in numeric order.
1566 push @PropInfo, [ hex($1), hex($2||""), $3 ];
1570 # Now append the extended properties in their code point order.
1571 my $Props = Table->New();
1574 for my $prop (sort { $a->[0] <=> $b->[0] } @PropInfo)
1576 my ($first, $last, $name) = @$prop;
1577 $Props->Append($first, $name);
1579 $Prop{$name} ||= Table->New(Is => $name,
1580 Desc => "Extended property '$name'",
1582 $Prop{$name}->Append($first, $name);
1585 $Props->Extend($last);
1586 $Prop{$name}->Extend($last);
1591 (my $file = $PA_reverse{$_}) =~ tr/_//d;
1592 # XXX I'm assuming that the names from %Prop don't suffer 8.3 clashes.
1593 $BaseNames{lc $file}++;
1595 ["lib","gc_sc","$file.pl"],
1596 "Binary property '$_'"
1600 # Alphabetic is L, Nl, and Other_Alphabetic.
1601 New_Prop(Is => 'Alphabetic',
1602 Table->Merge($Cat{L}, $Cat{Nl}, $Prop{Other_Alphabetic}),
1603 Desc => '[\p{L}\p{Nl}\p{OtherAlphabetic}]', # canonical names
1606 # Lowercase is Ll and Other_Lowercase.
1607 New_Prop(Is => 'Lowercase',
1608 Table->Merge($Cat{Ll}, $Prop{Other_Lowercase}),
1609 Desc => '[\p{Ll}\p{OtherLowercase}]', # canonical names
1612 # Uppercase is Lu and Other_Uppercase.
1613 New_Prop(Is => 'Uppercase',
1614 Table->Merge($Cat{Lu}, $Prop{Other_Uppercase}),
1615 Desc => '[\p{Lu}\p{OtherUppercase}]', # canonical names
1618 # Math is Sm and Other_Math.
1619 New_Prop(Is => 'Math',
1620 Table->Merge($Cat{Sm}, $Prop{Other_Math}),
1621 Desc => '[\p{Sm}\p{OtherMath}]', # canonical names
1624 # ID_Start is Ll, Lu, Lt, Lm, Lo, Nl, and Other_ID_Start.
1625 New_Prop(Is => 'ID_Start',
1626 Table->Merge(@Cat{qw[Ll Lu Lt Lm Lo Nl]}, $Prop{Other_ID_Start}),
1627 Desc => '[\p{Ll}\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{OtherIDStart}]',
1630 # ID_Continue is ID_Start, Mn, Mc, Nd, Pc, and Other_ID_Continue.
1631 New_Prop(Is => 'ID_Continue',
1632 Table->Merge(@Cat{qw[Ll Lu Lt Lm Lo Nl Mn Mc Nd Pc ]},
1633 @Prop{qw[Other_ID_Start Other_ID_Continue]}),
1634 Desc => '[\p{ID_Start}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{OtherIDContinue}]',
1637 # Default_Ignorable_Code_Point = Other_Default_Ignorable_Code_Point
1638 # + Cf + Cc + Cs + Noncharacter + Variation_Selector
1639 # - WhiteSpace - FFF9..FFFB (Annotation Characters)
1641 my $Annotation = Table->New();
1642 $Annotation->RawAppendRange(0xFFF9, 0xFFFB);
1644 New_Prop(Is => 'Default_Ignorable_Code_Point',
1645 Table->Merge(@Cat{qw[Cf Cc Cs]},
1646 $Prop{Noncharacter_Code_Point},
1647 $Prop{Variation_Selector},
1648 $Prop{Other_Default_Ignorable_Code_Point})
1650 ->Merge($Prop{White_Space}, $Annotation)
1652 Desc => '(?![\p{WhiteSpace}\x{FFF9}-\x{FFFB}])[\p{Cf}\p{Cc}'.
1653 '\p{Cs}\p{NoncharacterCodePoint}\p{VariationSelector}'.
1654 '\p{OtherDefaultIgnorableCodePoint}]',
1661 ## These are used in:
1662 ## MakePropTestScript()
1663 ## WriteAllMappings()
1664 ## for making the test script.
1666 my %FuzzyNameToTest;
1667 my %ExactNameToTest;
1670 ## This used only for making the test script
1675 my $MatchCode = shift;
1676 my $FailCode = shift;
1678 if (defined $MatchCode) {
1679 printf $FH qq/Expect(1, "\\x{%04X}", '\\p{$Prop}' );\n/, $MatchCode;
1680 printf $FH qq/Expect(0, "\\x{%04X}", '\\p{^$Prop}');\n/, $MatchCode;
1681 printf $FH qq/Expect(0, "\\x{%04X}", '\\P{$Prop}' );\n/, $MatchCode;
1682 printf $FH qq/Expect(1, "\\x{%04X}", '\\P{^$Prop}');\n/, $MatchCode;
1684 if (defined $FailCode) {
1685 printf $FH qq/Expect(0, "\\x{%04X}", '\\p{$Prop}' );\n/, $FailCode;
1686 printf $FH qq/Expect(1, "\\x{%04X}", '\\p{^$Prop}');\n/, $FailCode;
1687 printf $FH qq/Expect(1, "\\x{%04X}", '\\P{$Prop}' );\n/, $FailCode;
1688 printf $FH qq/Expect(0, "\\x{%04X}", '\\P{^$Prop}');\n/, $FailCode;
1692 ## This used only for making the test script
1698 print $FH qq/Error('\\p{$prop}');\n/;
1699 print $FH qq/Error('\\P{$prop}');\n/;
1702 ## This used only for making the test script
1718 ## This used only for making the test script
1719 sub RandomlyFuzzifyName($;$)
1722 my $WantError = shift; ## if true, make an error
1725 for my $part (split /[-\s_]+/, $Name)
1728 if ($WantError and rand() < 0.3) {
1729 push @parts, $BadSeps[rand(@BadSeps)];
1732 push @parts, $GoodSeps[rand(@GoodSeps)];
1735 my $switch = int rand(4);
1737 push @parts, uc $part;
1738 } elsif ($switch == 1) {
1739 push @parts, lc $part;
1740 } elsif ($switch == 2) {
1741 push @parts, ucfirst $part;
1746 my $new = join('', @parts);
1749 if (rand() >= 0.5) {
1750 $new .= $BadSeps[rand(@BadSeps)];
1752 $new = $BadSeps[rand(@BadSeps)] . $new;
1758 ## This used only for making the test script
1759 sub MakePropTestScript()
1761 ## this written directly -- it's huge.
1762 force_unlink ("TestProp.pl");
1763 if (not open OUT, ">TestProp.pl") {
1764 die "$0: TestProp.pl: $!\n";
1768 while (my ($Name, $Table) = each %ExactNameToTest)
1770 GenTests(*OUT, $Name, $Table->ValidCode, $Table->InvalidCode);
1771 ExpectError(*OUT, uc $Name) if uc $Name ne $Name;
1772 ExpectError(*OUT, lc $Name) if lc $Name ne $Name;
1776 while (my ($Name, $Table) = each %FuzzyNameToTest)
1778 my $Orig = $CanonicalToOrig{$Name};
1782 RandomlyFuzzifyName($Orig) => 1
1785 for my $N (keys %Names) {
1786 GenTests(*OUT, $N, $Table->ValidCode, $Table->InvalidCode);
1789 ExpectError(*OUT, RandomlyFuzzifyName($Orig, 'ERROR'));
1792 print OUT "Finished();\n";
1798 ## These are used only in:
1799 ## RegisterFileForName()
1800 ## WriteAllMappings()
1802 my %Exact; ## will become %utf8::Exact;
1803 my %Canonical; ## will become %utf8::Canonical;
1804 my %CaComment; ## Comment for %Canonical entry of same key
1807 ## Given info about a name and a datafile that it should be associated with,
1808 ## register that assocation in %Exact and %Canonical.
1809 sub RegisterFileForName($$$$)
1813 my $IsFuzzy = shift;
1814 my $filename = shift;
1817 ## Now in details for the mapping. $Type eq 'Is' has the
1818 ## Is removed, as it will be removed in utf8_heavy when this
1819 ## data is being checked. In keeps its "In", but a second
1820 ## sans-In record is written if it doesn't conflict with
1821 ## anything already there.
1825 if ($Type eq 'Is') {
1826 die "oops[$Name]" if $Exact{$Name};
1827 $Exact{$Name} = $filename;
1829 die "oops[$Type$Name]" if $Exact{"$Type$Name"};
1830 $Exact{"$Type$Name"} = $filename;
1831 $Exact{$Name} = $filename if not $Exact{$Name};
1836 my $CName = lc $Name;
1837 if ($Type eq 'Is') {
1838 die "oops[$CName]" if $Canonical{$CName};
1839 $Canonical{$CName} = $filename;
1840 $CaComment{$CName} = $Name if $Name =~ tr/A-Z// >= 2;
1842 die "oops[$Type$CName]" if $Canonical{lc "$Type$CName"};
1843 $Canonical{lc "$Type$CName"} = $filename;
1844 $CaComment{lc "$Type$CName"} = "$Type$Name";
1845 if (not $Canonical{$CName}) {
1846 $Canonical{$CName} = $filename;
1847 $CaComment{$CName} = "$Type$Name";
1854 ## Writes the info accumulated in
1861 sub WriteAllMappings()
1865 ## 'Is' *MUST* come first, so its names have precidence over 'In's
1866 for my $Type ('Is', 'In')
1868 my %RawNameToFile; ## a per-$Type cache
1870 for my $Name (sort {length $a <=> length $b} keys %{$TableInfo{$Type}})
1872 ## Note: $Name is already canonical
1873 my $Table = $TableInfo{$Type}->{$Name};
1874 my $IsFuzzy = $FuzzyNames{$Type}->{$Name};
1876 ## Need an 8.3 safe filename (which means "an 8 safe" $filename)
1879 ## 'Is' items lose 'Is' from the basename.
1880 $filename = $Type eq 'Is' ?
1881 ($PVA_reverse{sc}{$Name} || $Name) :
1884 $filename =~ s/[^\w_]+/_/g; # "L&" -> "L_"
1885 substr($filename, 8) = '' if length($filename) > 8;
1888 ## Make sure the basename doesn't conflict with something we
1889 ## might have already written. If we have, say,
1896 while (my $num = $BaseNames{lc $filename}++)
1898 $num++; ## so basenames with numbers start with '2', which
1899 ## just looks more natural.
1900 ## Want to append $num, but if it'll make the basename longer
1901 ## than 8 characters, pre-truncate $filename so that the result
1903 my $delta = length($filename) + length($num) - 8;
1905 substr($filename, -$delta) = $num;
1913 ## Construct a nice comment to add to the file, and build data
1914 ## for the "./Properties" file along the way.
1918 my $Desc = $TableDesc{$Type}->{$Name} || "";
1919 ## get list of names this table is reference by
1920 my @Supported = $Name;
1921 while (my ($Orig, $Alias) = each %{ $AliasInfo{$Type} })
1923 if ($Orig eq $Name) {
1924 push @Supported, $Alias;
1928 my $TypeToShow = $Type eq 'Is' ? "" : $Type;
1931 $Comment = "This file supports:\n";
1932 for my $N (@Supported)
1934 my $IsFuzzy = $FuzzyNames{$Type}->{$N};
1935 my $Prop = "\\p{$TypeToShow$Name}";
1936 $OrigProp = $Prop if not $OrigProp; #cache for aliases
1938 $Comment .= "\t$Prop (and fuzzy permutations)\n";
1940 $Comment .= "\t$Prop\n";
1942 my $MyDesc = ($N eq $Name) ? $Desc : "Alias for $OrigProp ($Desc)";
1944 push @MAP, sprintf("%s %-42s %s\n",
1945 $IsFuzzy ? '*' : ' ', $Prop, $MyDesc);
1948 $Comment .= "\nMeaning: $Desc\n";
1953 ## Okay, write the file...
1955 $Table->Write(["lib","gc_sc","$filename.pl"], $Comment);
1958 $RawNameToFile{$Name} = $filename;
1959 RegisterFileForName($Type => $Name, $IsFuzzy, $filename);
1963 my $CName = CanonicalName($Type . '_'. $Name);
1964 $FuzzyNameToTest{$Name} = $Table if !$FuzzyNameToTest{$Name};
1965 $FuzzyNameToTest{$CName} = $Table if !$FuzzyNameToTest{$CName};
1967 $ExactNameToTest{$Name} = $Table;
1972 ## Register aliase info
1973 for my $Name (sort {length $a <=> length $b} keys %{$AliasInfo{$Type}})
1975 my $Alias = $AliasInfo{$Type}->{$Name};
1976 my $IsFuzzy = $FuzzyNames{$Type}->{$Alias};
1977 my $filename = $RawNameToFile{$Name};
1978 die "oops [$Alias]->[$Name]" if not $filename;
1979 RegisterFileForName($Type => $Alias, $IsFuzzy, $filename);
1981 my $Table = $TableInfo{$Type}->{$Name};
1982 die "oops" if not $Table;
1985 my $CName = CanonicalName($Type .'_'. $Alias);
1986 $FuzzyNameToTest{$Alias} = $Table if !$FuzzyNameToTest{$Alias};
1987 $FuzzyNameToTest{$CName} = $Table if !$FuzzyNameToTest{$CName};
1989 $ExactNameToTest{$Alias} = $Table;
1995 ## Write out the property list
2000 "## This file created by $0\n",
2001 "## List of built-in \\p{...}/\\P{...} properties.\n",
2003 "## '*' means name may be 'fuzzy'\n",
2005 sort { substr($a,2) cmp substr($b, 2) } @MAP,
2007 WriteIfChanged('Properties', @OUT);
2010 use Text::Tabs (); ## using this makes the files about half the size
2017 "## Data in this file used by ../utf8_heavy.pl\n",
2019 "## Mapping from name to filename in ./lib/gc_sc\n",
2020 "%utf8::Exact = (\n",
2023 $Exact{InGreek} = 'InGreekA'; # this is evil kludge
2024 for my $Name (sort keys %Exact)
2026 my $File = $Exact{$Name};
2027 $Name = $Name =~ m/\W/ ? qq/'$Name'/ : " $Name ";
2028 my $Text = sprintf("%-15s => %s,\n", $Name, qq/'$File'/);
2029 push @OUT, Text::Tabs::unexpand($Text);
2031 push @OUT, ");\n1;\n";
2033 WriteIfChanged('Exact.pl', @OUT);
2036 ## Write Canonical.pl
2041 "## Data in this file used by ../utf8_heavy.pl\n",
2043 "## Mapping from lc(canonical name) to filename in ./lib\n",
2044 "%utf8::Canonical = (\n",
2046 my $Trail = ""; ## used just to keep the spacing pretty
2047 for my $Name (sort keys %Canonical)
2049 my $File = $Canonical{$Name};
2050 if ($CaComment{$Name}) {
2051 push @OUT, "\n" if not $Trail;
2052 push @OUT, " # $CaComment{$Name}\n";
2057 $Name = $Name =~ m/\W/ ? qq/'$Name'/ : " $Name ";
2058 my $Text = sprintf(" %-41s => %s,\n$Trail", $Name, qq/'$File'/);
2059 push @OUT, Text::Tabs::unexpand($Text);
2061 push @OUT, ");\n1\n";
2062 WriteIfChanged('Canonical.pl', @OUT);
2065 MakePropTestScript() if $MakeTestScript;
2069 sub SpecialCasing_txt()
2072 # Read in the special cases.
2077 if (not open IN, "SpecialCasing.txt") {
2078 die "$0: SpecialCasing.txt: $!\n";
2081 next unless /^[0-9A-Fa-f]+;/;
2085 my ($code, $lower, $title, $upper, $condition) = split(/\s*;\s*/);
2087 if ($condition) { # not implemented yet
2088 print "# SKIPPING $_\n" if $Verbose;
2092 # Wait until all the special cases have been read since
2093 # they are not listed in numeric order.
2094 my $ix = hex($code);
2095 push @{$CaseInfo{Lower}}, [ $ix, $code, $lower ]
2096 unless $code eq $lower;
2097 push @{$CaseInfo{Title}}, [ $ix, $code, $title ]
2098 unless $code eq $title;
2099 push @{$CaseInfo{Upper}}, [ $ix, $code, $upper ]
2100 unless $code eq $upper;
2104 # Now write out the special cases properties in their code point order.
2105 # Prepend them to the To/{Upper,Lower,Title}.pl.
2107 for my $case (qw(Lower Title Upper))
2109 my $NormalCase = do "To/$case.pl" || die "$0: $@\n";
2113 $HEADER, $INTERNAL_ONLY, "\n",
2114 "# The key: UTF-8 _bytes_, the value: UTF-8 (speed hack)\n",
2115 "%utf8::ToSpec$case =\n(\n",
2118 for my $prop (sort { $a->[0] <=> $b->[0] } @{$CaseInfo{$case}}) {
2119 my ($ix, $code, $to) = @$prop;
2121 join "", map { sprintf "\\x{%s}", $_ } split ' ', $to;
2122 push @OUT, sprintf qq["%s" => "$tostr",\n], join("", map { sprintf "\\x%02X", $_ } unpack("U0C*", pack("U", $ix)));
2123 # Remove any single-character mappings for
2124 # the same character since we are going for
2125 # the special casing rules.
2126 $NormalCase =~ s/^$code\t\t\w+\n//m;
2130 "return <<'END';\n",
2134 WriteIfChanged(["To","$case.pl"], @OUT);
2139 # Read in the case foldings.
2141 # We will do full case folding, C + F + I (see CaseFolding.txt). Note that
2142 # there are no I entries starting with Unicode 3.2, but leaving it in allows
2143 # for backward compatibility.
2145 sub CaseFolding_txt()
2147 if (not open IN, "CaseFolding.txt") {
2148 die "$0: CaseFolding.txt: $!\n";
2151 my $Fold = Table->New();
2155 # Skip status 'S', simple case folding
2156 next unless /^([0-9A-Fa-f]+)\s*;\s*([CFI])\s*;\s*([0-9A-Fa-f]+(?: [0-9A-Fa-f]+)*)\s*;/;
2158 my ($code, $status, $fold) = (hex($1), $2, $3);
2160 if ($status eq 'C') { # Common: one-to-one folding
2161 # No append() since several codes may fold into one.
2162 $Fold->RawAppendRange($code, $code, $fold);
2163 } else { # F: full, or I: dotted uppercase I -> dotless lowercase I
2164 $Fold{$code} = $fold;
2169 $Fold->Write("To/Fold.pl");
2172 # Prepend the special foldings to the common foldings.
2174 my $CommonFold = do "To/Fold.pl" || die "$0: To/Fold.pl: $!\n";
2178 $HEADER, $INTERNAL_ONLY, "\n",
2179 "# The key: UTF-8 _bytes_, the value: UTF-8 (speed hack)\n",
2180 "%utf8::ToSpecFold =\n(\n",
2182 for my $code (sort { $a <=> $b } keys %Fold) {
2184 join "", map { sprintf "\\x{%s}", $_ } split ' ', $Fold{$code};
2185 push @OUT, sprintf qq["%s" => "$foldstr",\n], join("", map { sprintf "\\x%02X", $_ } unpack("U0C*", pack("U", $code)));
2189 "return <<'END';\n",
2194 WriteIfChanged(["To","Fold.pl"], @OUT);
2209 ArabicShaping_txt();
2210 EastAsianWidth_txt();
2211 HangulSyllableType_txt();
2213 SpecialCasing_txt();
2216 if ( $FileList and $MakeList ) {
2218 print "Updating '$FileList'\n"
2221 open my $ofh,">",$FileList
2222 or die "Can't write to '$FileList':$!";
2223 print $ofh <<"EOFHEADER";
2225 # mktables.lst -- File list for mktables.
2227 # Autogenerated on @{[scalar localtime]}
2229 # - First section is input files
2230 # (mktables itself is automatically included)
2231 # - Section seperator is /^=+\$/
2232 # - Second section is a list of output files.
2233 # - Lines matching /^\\s*#/ are treated as comments
2234 # which along with blank lines are ignored.
2240 my @input=("version",glob('*.txt'));
2241 print $ofh "$_\n" for
2243 "\n=================================\n",
2244 "# Output files:\n",
2256 push @output_files, "$_\n";
2261 print $ofh sort @output_files;
2262 print $ofh "\n# ",scalar(@input)," input files\n",
2263 "# ",scalar(@output_files)+1," output files\n\n",
2266 or warn "Failed to close $ofh: $!";
2268 print "Filelist has ",scalar(@input)," input files and ",
2269 scalar(@output_files)+1," output files\n"
2272 print "All done\n" if $Verbose;
2275 ## TRAILING CODE IS USED BY MakePropTestScript()
2288 my $Line = (caller)[2];
2293 $RegObj = qr/$Regex/;
2294 $String =~ $RegObj ? 1 : 0
2297 if (not defined $result) {
2298 print "couldn't compile /$Regex/ on $0 line $Line: $@\n";
2300 } elsif ($result ^ $Expect) {
2301 print "bad result (expected $Expect) on $0 line $Line: $@\n";
2310 if (eval { 'x' =~ qr/$Regex/; 1 }) {
2312 my $Line = (caller)[2];
2313 print "expected error for /$Regex/ on $0 line $Line: $@\n";
2320 print "All $Tests tests passed.\n";
2323 print "$Tests tests, $Fails failed!\n";