home *** CD-ROM | disk | FTP | other *** search
/ PC World 2005 December (Special) / PCWorld_2005-12_Special_cd.bin / Bezpecnost / lsti / lsti.exe / framework-2.5.exe / mktables < prev    next >
Text File  |  2005-01-27  |  57KB  |  2,047 lines

  1. #!/usr/bin/perl -w
  2. require 5.008;    # Needs pack "U". Probably safest to run on 5.8.x
  3. use strict;
  4. use Carp;
  5. use File::Spec;
  6.  
  7. ##
  8. ## mktables -- create the runtime Perl Unicode files (lib/unicore/**/*.pl)
  9. ## from the Unicode database files (lib/unicore/*.txt).
  10. ##
  11.  
  12. ## "Fuzzy" means this section in Unicode TR18:
  13. ##
  14. ##    The recommended names for UCD properties and property values are in
  15. ##    PropertyAliases.txt [Prop] and PropertyValueAliases.txt
  16. ##    [PropValue]. There are both abbreviated names and longer, more
  17. ##    descriptive names. It is strongly recommended that both names be
  18. ##    recognized, and that loose matching of property names be used,
  19. ##    whereby the case distinctions, whitespace, hyphens, and underbar
  20. ##    are ignored.
  21.  
  22. ## Base names already used in lib/gc_sc (for avoiding 8.3 conflicts)
  23. my %BaseNames;
  24.  
  25. ##
  26. ## Process any args.
  27. ##
  28. my $Verbose        = 0;
  29. my $MakeTestScript = 0;
  30. my $AlwaysWrite    = 0;
  31.  
  32. while (@ARGV)
  33. {
  34.     my $arg = shift @ARGV;
  35.     if ($arg eq '-v') {
  36.         $Verbose = 1;
  37.     } elsif ($arg eq '-q') {
  38.         $Verbose = 0;
  39.     } elsif ($arg eq '-w') {
  40.         $AlwaysWrite = 1;    # update the files even if they havent changed
  41.     } elsif ($arg eq '-maketest') {
  42.         $MakeTestScript = 1;
  43.     } elsif ($arg eq '-C' && defined (my $dir = shift)) {
  44.     chdir $dir or die "chdir $_: $!";
  45.     } else {
  46.         die "usage: $0 [-v|-q|-C dir] [-maketest]";
  47.     }
  48. }
  49.  
  50. foreach my $lib ('To', 'lib',
  51.          map {File::Spec->catdir("lib",$_)}
  52.          qw(gc_sc dt bc hst ea jt lb nt ccc)) {
  53.   next if -d $lib;
  54.   mkdir $lib, 0755 or die "mkdir '$lib': $!";
  55. }
  56.  
  57. my $LastUnicodeCodepoint = 0x10FFFF; # As of Unicode 3.1.1.
  58.  
  59. my $HEADER=<<"EOF";
  60. # !!!!!!!   DO NOT EDIT THIS FILE   !!!!!!! 
  61. # This file is built by $0 from e.g. UnicodeData.txt.
  62. # Any changes made here will be lost!
  63.  
  64. EOF
  65.  
  66. sub force_unlink {
  67.     my $filename = shift;
  68.     return unless -e $filename;
  69.     return if CORE::unlink($filename);
  70.     # We might need write permission
  71.     chmod 0777, $filename;
  72.     CORE::unlink($filename) or die "Couldn't unlink $filename: $!\n";
  73. }
  74.  
  75. ##
  76. ## Given a filename and a reference to an array of lines,
  77. ## write the lines to the file only if the contents have not changed.
  78. ## Filename can be given as an arrayref of directory names
  79. ##
  80. sub WriteIfChanged($\@)
  81. {
  82.     my $file  = shift;
  83.     my $lines = shift;
  84.  
  85.     $file = File::Spec->catfile(@$file) if ref $file;
  86.  
  87.     my $TextToWrite = join '', @$lines;
  88.     if (open IN, $file) {
  89.         local($/) = undef;
  90.         my $PreviousText = <IN>;
  91.         close IN;
  92.         if ($PreviousText eq $TextToWrite) {
  93.             print "$file unchanged.\n" if $Verbose;
  94.             return unless $AlwaysWrite;
  95.         }
  96.     }
  97.     force_unlink ($file);
  98.     if (not open OUT, ">$file") {
  99.         die "$0: can't open $file for output: $!\n";
  100.     }
  101.     print "$file written.\n" if $Verbose;
  102.  
  103.     print OUT $TextToWrite;
  104.     close OUT;
  105. }
  106.  
  107. ##
  108. ## The main datastructure (a "Table") represents a set of code points that
  109. ## are part of a particular quality (that are part of \pL, \p{InGreek},
  110. ## etc.). They are kept as ranges of code points (starting and ending of
  111. ## each range).
  112. ##
  113. ## For example, a range ASCII LETTERS would be represented as:
  114. ##   [ [ 0x41 => 0x5A, 'UPPER' ],
  115. ##     [ 0x61 => 0x7A, 'LOWER, ] ]
  116. ##
  117. sub RANGE_START() { 0 } ## index into range element
  118. sub RANGE_END()   { 1 } ## index into range element
  119. sub RANGE_NAME()  { 2 } ## index into range element
  120.  
  121. ## Conceptually, these should really be folded into the 'Table' objects
  122. my %TableInfo;
  123. my %TableDesc;
  124. my %FuzzyNames;
  125. my %AliasInfo;
  126. my %CanonicalToOrig;
  127.  
  128. ##
  129. ## Turn something like
  130. ##    OLD-ITALIC
  131. ## into
  132. ##    OldItalic
  133. ##
  134. sub CanonicalName($)
  135. {
  136.     my $orig = shift;
  137.     my $name = lc $orig;
  138.     $name =~ s/(?<![a-z])(\w)/\u$1/g;
  139.     $name =~ s/[-_\s]+//g;
  140.  
  141.     $CanonicalToOrig{$name} = $orig if not $CanonicalToOrig{$name};
  142.     return $name;
  143. }
  144.  
  145.  
  146. ##
  147. ## Store the alias definitions for later use.
  148. ##
  149. my %PropertyAlias;
  150. my %PropValueAlias;
  151.  
  152. my %PA_reverse;
  153. my %PVA_reverse;
  154.  
  155. sub Build_Aliases()
  156. {
  157.     ##
  158.     ## Most of the work with aliases doesn't occur here,
  159.     ## but rather in utf8_heavy.pl, which uses PVA.pl,
  160.  
  161.     # Placate the warnings about used only once. (They are used again, but
  162.     # via a typeglob lookup)
  163.     %utf8::PropertyAlias = ();
  164.     %utf8::PA_reverse = ();
  165.     %utf8::PropValueAlias = ();
  166.     %utf8::PVA_reverse = ();
  167.     %utf8::PVA_abbr_map = ();
  168.  
  169.     open PA, "< PropertyAliases.txt"
  170.     or confess "Can't open PropertyAliases.txt: $!";
  171.     while (<PA>) {
  172.     s/#.*//;
  173.     s/\s+$//;
  174.     next if /^$/;
  175.  
  176.     my ($abbrev, $name) = split /\s*;\s*/;
  177.         next if $abbrev eq "n/a";
  178.     $PropertyAlias{$abbrev} = $name;
  179.         $PA_reverse{$name} = $abbrev;
  180.  
  181.     # The %utf8::... versions use japhy's code originally from utf8_pva.pl
  182.     # However, it's moved here so that we build the tables at runtime.
  183.     tr/ _-//d for $abbrev, $name;
  184.     $utf8::PropertyAlias{lc $abbrev} = $name;
  185.     $utf8::PA_reverse{lc $name} = $abbrev;
  186.     }
  187.     close PA;
  188.  
  189.     open PVA, "< PropValueAliases.txt"
  190.     or confess "Can't open PropValueAliases.txt: $!";
  191.     while (<PVA>) {
  192.     s/#.*//;
  193.     s/\s+$//;
  194.     next if /^$/;
  195.  
  196.     my ($prop, @data) = split /\s*;\s*/;
  197.  
  198.     if ($prop eq 'ccc') {
  199.         $PropValueAlias{$prop}{$data[1]} = [ @data[0,2] ];
  200.         $PVA_reverse{$prop}{$data[2]} = [ @data[0,1] ];
  201.     }
  202.     else {
  203.             next if $data[0] eq "n/a";
  204.         $PropValueAlias{$prop}{$data[0]} = $data[1];
  205.             $PVA_reverse{$prop}{$data[1]} = $data[0];
  206.     }
  207.  
  208.     shift @data if $prop eq 'ccc';
  209.     next if $data[0] eq "n/a";
  210.  
  211.     $data[1] =~ tr/ _-//d;
  212.     $utf8::PropValueAlias{$prop}{lc $data[0]} = $data[1];
  213.     $utf8::PVA_reverse{$prop}{lc $data[1]} = $data[0];
  214.  
  215.     my $abbr_class = ($prop eq 'gc' or $prop eq 'sc') ? 'gc_sc' : $prop;
  216.     $utf8::PVA_abbr_map{$abbr_class}{lc $data[0]} = $data[0];
  217.     }
  218.     close PVA;
  219.  
  220.     # backwards compatibility for L& -> LC
  221.     $utf8::PropValueAlias{gc}{'l&'} = $utf8::PropValueAlias{gc}{lc};
  222.     $utf8::PVA_abbr_map{gc_sc}{'l&'} = $utf8::PVA_abbr_map{gc_sc}{lc};
  223.  
  224. }
  225.  
  226.  
  227. ##
  228. ## Associates a property ("Greek", "Lu", "Assigned",...) with a Table.
  229. ##
  230. ## Called like:
  231. ##       New_Prop(In => 'Greek', $Table, Desc => 'Greek Block', Fuzzy => 1);
  232. ##
  233. ## Normally, these parameters are set when the Table is created (when the
  234. ## Table->New constructor is called), but there are times when it needs to
  235. ## be done after-the-fact...)
  236. ##
  237. sub New_Prop($$$@)
  238. {
  239.     my $Type = shift; ## "Is" or "In";
  240.     my $Name = shift;
  241.     my $Table = shift;
  242.  
  243.     ## remaining args are optional key/val
  244.     my %Args = @_;
  245.  
  246.     my $Fuzzy = delete $Args{Fuzzy};
  247.     my $Desc  = delete $Args{Desc}; # description
  248.  
  249.     $Name = CanonicalName($Name) if $Fuzzy;
  250.  
  251.     ## sanity check a few args
  252.     if (%Args or ($Type ne 'Is' and $Type ne 'In') or not ref $Table) {
  253.         confess "$0: bad args to New_Prop"
  254.     }
  255.  
  256.     if (not $TableInfo{$Type}->{$Name})
  257.     {
  258.         $TableInfo{$Type}->{$Name} = $Table;
  259.         $TableDesc{$Type}->{$Name} = $Desc;
  260.         if ($Fuzzy) {
  261.             $FuzzyNames{$Type}->{$Name} = $Name;
  262.         }
  263.     }
  264. }
  265.  
  266.  
  267. ##
  268. ## Creates a new Table object.
  269. ##
  270. ## Args are key/value pairs:
  271. ##    In => Name         -- Name of "In" property to be associated with
  272. ##    Is => Name         -- Name of "Is" property to be associated with
  273. ##    Fuzzy => Boolean   -- True if name can be accessed "fuzzily"
  274. ##    Desc  => String    -- Description of the property
  275. ##
  276. ## No args are required.
  277. ##
  278. sub Table::New
  279. {
  280.     my $class = shift;
  281.     my %Args = @_;
  282.  
  283.     my $Table = bless [], $class;
  284.  
  285.     my $Fuzzy = delete $Args{Fuzzy};
  286.     my $Desc  = delete $Args{Desc};
  287.  
  288.     for my $Type ('Is', 'In')
  289.     {
  290.         if (my $Name = delete $Args{$Type}) {
  291.             New_Prop($Type => $Name, $Table, Desc => $Desc, Fuzzy => $Fuzzy);
  292.         }
  293.     }
  294.  
  295.     ## shouldn't have any left over
  296.     if (%Args) {
  297.         confess "$0: bad args to Table->New"
  298.     }
  299.  
  300.     return $Table;
  301. }
  302.  
  303. ##
  304. ## Returns true if the Table has no code points
  305. ##
  306. sub Table::IsEmpty
  307. {
  308.     my $Table = shift; #self
  309.     return not @$Table;
  310. }
  311.  
  312. ##
  313. ## Returns true if the Table has code points
  314. ##
  315. sub Table::NotEmpty
  316. {
  317.     my $Table = shift; #self
  318.     return @$Table;
  319. }
  320.  
  321. ##
  322. ## Returns the maximum code point currently in the table.
  323. ##
  324. sub Table::Max
  325. {
  326.     my $Table = shift; #self
  327.     confess "oops" if $Table->IsEmpty; ## must have code points to have a max
  328.     return $Table->[-1]->[RANGE_END];
  329. }
  330.  
  331. ##
  332. ## Replaces the codepoints in the Table with those in the Table given
  333. ## as an arg. (NOTE: this is not a "deep copy").
  334. ##
  335. sub Table::Replace($$)
  336. {
  337.     my $Table = shift; #self
  338.     my $New   = shift;
  339.  
  340.     @$Table = @$New;
  341. }
  342.  
  343. ##
  344. ## Given a new code point, make the last range of the Table extend to
  345. ## include the new (and all intervening) code points.
  346. ##
  347. sub Table::Extend
  348. {
  349.     my $Table = shift; #self
  350.     my $codepoint = shift;
  351.  
  352.     my $PrevMax = $Table->Max;
  353.  
  354.     confess "oops ($codepoint <= $PrevMax)" if $codepoint <= $PrevMax;
  355.  
  356.     $Table->[-1]->[RANGE_END] = $codepoint;
  357. }
  358.  
  359. ##
  360. ## Given a code point range start and end (and optional name), blindly
  361. ## append them to the list of ranges for the Table.
  362. ##
  363. ## NOTE: Code points must be added in strictly ascending numeric order.
  364. ##
  365. sub Table::RawAppendRange
  366. {
  367.     my $Table = shift; #self
  368.     my $start = shift;
  369.     my $end   = shift;
  370.     my $name  = shift;
  371.     $name = "" if not defined $name; ## warning: $name can be "0"
  372.  
  373.     push @$Table, [ $start,    # RANGE_START
  374.                     $end,      # RANGE_END
  375.                     $name   ]; # RANGE_NAME
  376. }
  377.  
  378. ##
  379. ## Given a code point (and optional name), add it to the Table.
  380. ##
  381. ## NOTE: Code points must be added in strictly ascending numeric order.
  382. ##
  383. sub Table::Append
  384. {
  385.     my $Table     = shift; #self
  386.     my $codepoint = shift;
  387.     my $name      = shift;
  388.     $name = "" if not defined $name; ## warning: $name can be "0"
  389.  
  390.     ##
  391.     ## If we've already got a range working, and this code point is the next
  392.     ## one in line, and if the name is the same, just extend the current range.
  393.     ##
  394.     if ($Table->NotEmpty
  395.         and
  396.         $Table->Max == $codepoint - 1
  397.         and
  398.         $Table->[-1]->[RANGE_NAME] eq $name)
  399.     {
  400.         $Table->Extend($codepoint);
  401.     }
  402.     else
  403.     {
  404.         $Table->RawAppendRange($codepoint, $codepoint, $name);
  405.     }
  406. }
  407.  
  408. ##
  409. ## Given a code point range starting value and ending value (and name),
  410. ## Add the range to teh Table.
  411. ##
  412. ## NOTE: Code points must be added in strictly ascending numeric order.
  413. ##
  414. sub Table::AppendRange
  415. {
  416.     my $Table = shift; #self
  417.     my $start = shift;
  418.     my $end   = shift;
  419.     my $name  = shift;
  420.     $name = "" if not defined $name; ## warning: $name can be "0"
  421.  
  422.     $Table->Append($start, $name);
  423.     $Table->Extend($end) if $end > $start;
  424. }
  425.  
  426. ##
  427. ## Return a new Table that represents all code points not in the Table.
  428. ##
  429. sub Table::Invert
  430. {
  431.     my $Table = shift; #self
  432.  
  433.     my $New = Table->New();
  434.     my $max = -1;
  435.     for my $range (@$Table)
  436.     {
  437.         my $start = $range->[RANGE_START];
  438.         my $end   = $range->[RANGE_END];
  439.         if ($start-1 >= $max+1) {
  440.             $New->AppendRange($max+1, $start-1, "");
  441.         }
  442.         $max = $end;
  443.     }
  444.     if ($max+1 < $LastUnicodeCodepoint) {
  445.         $New->AppendRange($max+1, $LastUnicodeCodepoint);
  446.     }
  447.     return $New;
  448. }
  449.  
  450. ##
  451. ## Merges any number of other tables with $self, returning the new table.
  452. ## (existing tables are not modified)
  453. ##
  454. ##
  455. ## Args may be Tables, or individual code points (as integers).
  456. ##
  457. ## Can be called as either a constructor or a method.
  458. ##
  459. sub Table::Merge
  460. {
  461.     shift(@_) if not ref $_[0]; ## if called as a constructor, lose the class
  462.     my @Tables = @_;
  463.  
  464.     ## Accumulate all records from all tables
  465.     my @Records;
  466.     for my $Arg (@Tables)
  467.     {
  468.         if (ref $Arg) {
  469.             ## arg is a table -- get its ranges
  470.             push @Records, @$Arg;
  471.         } else {
  472.             ## arg is a codepoint, make a range
  473.             push @Records, [ $Arg, $Arg ]
  474.         }
  475.     }
  476.  
  477.     ## sort by range start, with longer ranges coming first.
  478.     my ($first, @Rest) = sort {
  479.         ($a->[RANGE_START] <=> $b->[RANGE_START])
  480.           or
  481.         ($b->[RANGE_END]   <=> $b->[RANGE_END])
  482.     } @Records;
  483.  
  484.     my $New = Table->New();
  485.  
  486.     ## Ensuring the first range is there makes the subsequent loop easier
  487.     $New->AppendRange($first->[RANGE_START],
  488.                       $first->[RANGE_END]);
  489.  
  490.     ## Fold in records so long as they add new information.
  491.     for my $set (@Rest)
  492.     {
  493.         my $start = $set->[RANGE_START];
  494.         my $end   = $set->[RANGE_END];
  495.         if ($start > $New->Max) {
  496.             $New->AppendRange($start, $end);
  497.         } elsif ($end > $New->Max) {
  498.             $New->Extend($end);
  499.         }
  500.     }
  501.  
  502.     return $New;
  503. }
  504.  
  505. ##
  506. ## Given a filename, write a representation of the Table to a file.
  507. ## May have an optional comment as a 2nd arg.
  508. ## Filename may actually be an arrayref of directories
  509. ##
  510. sub Table::Write
  511. {
  512.     my $Table    = shift; #self
  513.     my $filename = shift;
  514.     my $comment  = shift;
  515.  
  516.     my @OUT = $HEADER;
  517.     if (defined $comment) {
  518.         $comment =~ s/\s+\Z//;
  519.         $comment =~ s/^/# /gm;
  520.         push @OUT, "#\n$comment\n#\n";
  521.     }
  522.     push @OUT, "return <<'END';\n";
  523.  
  524.     for my $set (@$Table)
  525.     {
  526.         my $start = $set->[RANGE_START];
  527.         my $end   = $set->[RANGE_END];
  528.         my $name  = $set->[RANGE_NAME];
  529.  
  530.         if ($start == $end) {
  531.             push @OUT, sprintf "%04X\t\t%s\n", $start, $name;
  532.         } else {
  533.             push @OUT, sprintf "%04X\t%04X\t%s\n", $start, $end, $name;
  534.         }
  535.     }
  536.  
  537.     push @OUT, "END\n";
  538.  
  539.     WriteIfChanged($filename, @OUT);
  540. }
  541.  
  542. ## This used only for making the test script.
  543. ## helper function
  544. sub IsUsable($)
  545. {
  546.     my $code = shift;
  547.     return 0 if $code <= 0x0000;                       ## don't use null
  548.     return 0 if $code >= $LastUnicodeCodepoint;        ## keep in range
  549.     return 0 if ($code >= 0xD800 and $code <= 0xDFFF); ## no surrogates
  550.     return 0 if ($code >= 0xFDD0 and $code <= 0xFDEF); ## utf8.c says no good
  551.     return 0 if (($code & 0xFFFF) == 0xFFFE);          ## utf8.c says no good
  552.     return 0 if (($code & 0xFFFF) == 0xFFFF);          ## utf8.c says no good
  553.     return 1;
  554. }
  555.  
  556. ## Return a code point that's part of the table.
  557. ## Returns nothing if the table is empty (or covers only surrogates).
  558. ## This used only for making the test script.
  559. sub Table::ValidCode
  560. {
  561.     my $Table = shift; #self
  562.     for my $set (@$Table) {
  563.         return $set->[RANGE_END] if IsUsable($set->[RANGE_END]);
  564.     }
  565.     return ();
  566. }
  567.  
  568. ## Return a code point that's not part of the table
  569. ## Returns nothing if the table covers all code points.
  570. ## This used only for making the test script.
  571. sub Table::InvalidCode
  572. {
  573.     my $Table = shift; #self
  574.  
  575.     return 0x1234 if $Table->IsEmpty();
  576.  
  577.     for my $set (@$Table)
  578.     {
  579.         if (IsUsable($set->[RANGE_END] + 1))
  580.         {
  581.             return $set->[RANGE_END] + 1;
  582.         }
  583.  
  584.         if (IsUsable($set->[RANGE_START] - 1))
  585.         {
  586.             return $set->[RANGE_START] - 1;
  587.         }
  588.     }
  589.     return ();
  590. }
  591.  
  592. ###########################################################################
  593. ###########################################################################
  594. ###########################################################################
  595.  
  596.  
  597. ##
  598. ## Called like:
  599. ##     New_Alias(Is => 'All', SameAs => 'Any', Fuzzy => 1);
  600. ##
  601. ## The args must be in that order, although the Fuzzy pair may be omitted.
  602. ##
  603. ## This creates 'IsAll' as an alias for 'IsAny'
  604. ##
  605. sub New_Alias($$$@)
  606. {
  607.     my $Type   = shift; ## "Is" or "In"
  608.     my $Alias  = shift;
  609.     my $SameAs = shift; # expecting "SameAs" -- just ignored
  610.     my $Name   = shift;
  611.  
  612.     ## remaining args are optional key/val
  613.     my %Args = @_;
  614.  
  615.     my $Fuzzy = delete $Args{Fuzzy};
  616.  
  617.     ## sanity check a few args
  618.     if (%Args or ($Type ne 'Is' and $Type ne 'In') or $SameAs ne 'SameAs') {
  619.         confess "$0: bad args to New_Alias"
  620.     }
  621.  
  622.     $Alias = CanonicalName($Alias) if $Fuzzy;
  623.  
  624.     if (not $TableInfo{$Type}->{$Name})
  625.     {
  626.         my $CName = CanonicalName($Name);
  627.         if ($TableInfo{$Type}->{$CName}) {
  628.             confess "$0: Use canonical form '$CName' instead of '$Name' for alias.";
  629.         } else {
  630.             confess "$0: don't have original $Type => $Name to make alias\n";
  631.         }
  632.     }
  633.     if ($TableInfo{$Alias}) {
  634.         confess "$0: already have original $Type => $Alias; can't make alias";
  635.     }
  636.     $AliasInfo{$Type}->{$Name} = $Alias;
  637.     if ($Fuzzy) {
  638.         $FuzzyNames{$Type}->{$Alias} = $Name;
  639.     }
  640.  
  641. }
  642.  
  643.  
  644. ## All assigned code points
  645. my $Assigned = Table->New(Is    => 'Assigned',
  646.                           Desc  => "All assigned code points",
  647.                           Fuzzy => 0);
  648.  
  649. my $Name     = Table->New(); ## all characters, individually by name
  650. my $General  = Table->New(); ## all characters, grouped by category
  651. my %General;
  652. my %Cat;
  653.  
  654. ## Simple Data::Dumper alike. Good enough for our needs. We can't use the real
  655. ## thing as we have to run under miniperl
  656. sub simple_dumper {
  657.     my @lines;
  658.     my $item;
  659.     foreach $item (@_) {
  660.     if (ref $item) {
  661.         if (ref $item eq 'ARRAY') {
  662.         push @lines, "[\n", simple_dumper (@$item), "],\n";
  663.         } elsif (ref $item eq 'HASH') {
  664.         push @lines, "{\n", simple_dumper (%$item), "},\n";
  665.         } else {
  666.         die "Can't cope with $item";
  667.         }
  668.     } else {
  669.         if (defined $item) {
  670.         my $copy = $item;
  671.         $copy =~ s/([\'\\])/\\$1/gs;
  672.         push @lines, "'$copy',\n";
  673.         } else {
  674.         push @lines, "undef,\n";
  675.         }
  676.     }
  677.     }
  678.     @lines;
  679. }
  680.  
  681. ##
  682. ## Process UnicodeData.txt (Categories, etc.)
  683. ##
  684. sub UnicodeData_Txt()
  685. {
  686.     my $Bidi     = Table->New();
  687.     my $Deco     = Table->New();
  688.     my $Comb     = Table->New();
  689.     my $Number   = Table->New();
  690.     my $Mirrored = Table->New();#Is    => 'Mirrored',
  691.                               #Desc  => "Mirrored in bidirectional text",
  692.                               #Fuzzy => 0);
  693.  
  694.     my %DC;
  695.     my %Bidi;
  696.     my %Number;
  697.     $DC{can} = Table->New();
  698.     $DC{com} = Table->New();
  699.  
  700.     ## Initialize Perl-generated categories
  701.     ## (Categories from UnicodeData.txt are auto-initialized in gencat)
  702.     $Cat{Alnum}  =
  703.     Table->New(Is => 'Alnum',  Desc => "[[:Alnum:]]",  Fuzzy => 0);
  704.     $Cat{Alpha}  =
  705.     Table->New(Is => 'Alpha',  Desc => "[[:Alpha:]]",  Fuzzy => 0);
  706.     $Cat{ASCII}  =
  707.     Table->New(Is => 'ASCII',  Desc => "[[:ASCII:]]",  Fuzzy => 0);
  708.     $Cat{Blank}  =
  709.     Table->New(Is => 'Blank',  Desc => "[[:Blank:]]",  Fuzzy => 0);
  710.     $Cat{Cntrl}  =
  711.     Table->New(Is => 'Cntrl',  Desc => "[[:Cntrl:]]",  Fuzzy => 0);
  712.     $Cat{Digit}  =
  713.     Table->New(Is => 'Digit',  Desc => "[[:Digit:]]",  Fuzzy => 0);
  714.     $Cat{Graph}  =
  715.     Table->New(Is => 'Graph',  Desc => "[[:Graph:]]",  Fuzzy => 0);
  716.     $Cat{Lower}  =
  717.     Table->New(Is => 'Lower',  Desc => "[[:Lower:]]",  Fuzzy => 0);
  718.     $Cat{Print}  =
  719.     Table->New(Is => 'Print',  Desc => "[[:Print:]]",  Fuzzy => 0);
  720.     $Cat{Punct}  =
  721.     Table->New(Is => 'Punct',  Desc => "[[:Punct:]]",  Fuzzy => 0);
  722.     $Cat{Space}  =
  723.     Table->New(Is => 'Space',  Desc => "[[:Space:]]",  Fuzzy => 0);
  724.     $Cat{Title}  =
  725.     Table->New(Is => 'Title',  Desc => "[[:Title:]]",  Fuzzy => 0);
  726.     $Cat{Upper}  =
  727.     Table->New(Is => 'Upper',  Desc => "[[:Upper:]]",  Fuzzy => 0);
  728.     $Cat{XDigit} =
  729.     Table->New(Is => 'XDigit', Desc => "[[:XDigit:]]", Fuzzy => 0);
  730.     $Cat{Word}   =
  731.     Table->New(Is => 'Word',   Desc => "[[:Word:]]",   Fuzzy => 0);
  732.     $Cat{SpacePerl} =
  733.     Table->New(Is => 'SpacePerl', Desc => '\s', Fuzzy => 0);
  734.  
  735.     my %To;
  736.     $To{Upper} = Table->New();
  737.     $To{Lower} = Table->New();
  738.     $To{Title} = Table->New();
  739.     $To{Digit} = Table->New();
  740.  
  741.     sub gencat($$$$)
  742.     {
  743.         my ($name, ## Name ("LATIN CAPITAL LETTER A")
  744.             $cat,  ## Category ("Lu", "Zp", "Nd", etc.)
  745.             $code, ## Code point (as an integer)
  746.             $op) = @_;
  747.  
  748.         my $MajorCat = substr($cat, 0, 1); ## L, M, Z, S, etc
  749.  
  750.         $Assigned->$op($code);
  751.         $Name->$op($code, $name);
  752.         $General->$op($code, $cat);
  753.  
  754.         ## add to the sub category (e.g. "Lu", "Nd", "Cf", ..)
  755.         $Cat{$cat}      ||= Table->New(Is   => $cat,
  756.                                        Desc => "General Category '$cat'",
  757.                                        Fuzzy => 0);
  758.         $Cat{$cat}->$op($code);
  759.  
  760.         ## add to the major category (e.g. "L", "N", "C", ...)
  761.         $Cat{$MajorCat} ||= Table->New(Is => $MajorCat,
  762.                                        Desc => "Major Category '$MajorCat'",
  763.                                        Fuzzy => 0);
  764.         $Cat{$MajorCat}->$op($code);
  765.  
  766.         ($General{$name} ||= Table->New)->$op($code, $name);
  767.  
  768.         # 005F: SPACING UNDERSCORE
  769.         $Cat{Word}->$op($code)  if $cat =~ /^[LMN]|Pc/;
  770.         $Cat{Alnum}->$op($code) if $cat =~ /^[LM]|Nd/;
  771.         $Cat{Alpha}->$op($code) if $cat =~ /^[LM]/;
  772.  
  773.     my $isspace = 
  774.         ($cat =~ /Zs|Zl|Zp/ &&
  775.          $code != 0x200B) # 200B is ZWSP which is for line break control
  776.          # and therefore it is not part of "space" even while it is "Zs".
  777.                                 || $code == 0x0009  # 0009: HORIZONTAL TAB
  778.                                 || $code == 0x000A  # 000A: LINE FEED
  779.                                 || $code == 0x000B  # 000B: VERTICAL TAB
  780.                                 || $code == 0x000C  # 000C: FORM FEED
  781.                                 || $code == 0x000D  # 000D: CARRIAGE RETURN
  782.                                 || $code == 0x0085  # 0085: NEL
  783.  
  784.         ;
  785.  
  786.         $Cat{Space}->$op($code) if $isspace;
  787.  
  788.         $Cat{SpacePerl}->$op($code) if $isspace
  789.                                    && $code != 0x000B; # Backward compat.
  790.  
  791.         $Cat{Blank}->$op($code) if $isspace
  792.                                 && !($code == 0x000A ||
  793.                      $code == 0x000B ||
  794.                      $code == 0x000C ||
  795.                      $code == 0x000D ||
  796.                      $code == 0x0085 ||
  797.                      $cat =~ /^Z[lp]/);
  798.  
  799.         $Cat{Digit}->$op($code) if $cat eq "Nd";
  800.         $Cat{Upper}->$op($code) if $cat eq "Lu";
  801.         $Cat{Lower}->$op($code) if $cat eq "Ll";
  802.         $Cat{Title}->$op($code) if $cat eq "Lt";
  803.         $Cat{ASCII}->$op($code) if $code <= 0x007F;
  804.         $Cat{Cntrl}->$op($code) if $cat =~ /^C/;
  805.     my $isgraph = !$isspace && $cat !~ /Cc|Cs|Cn/;
  806.         $Cat{Graph}->$op($code) if $isgraph;
  807.         $Cat{Print}->$op($code) if $isgraph || $isspace;
  808.         $Cat{Punct}->$op($code) if $cat =~ /^P/;
  809.  
  810.         $Cat{XDigit}->$op($code) if ($code >= 0x30 && $code <= 0x39)  ## 0..9
  811.                                  || ($code >= 0x41 && $code <= 0x46)  ## A..F
  812.                                  || ($code >= 0x61 && $code <= 0x66); ## a..f
  813.     }
  814.  
  815.     ## open ane read file.....
  816.     if (not open IN, "UnicodeData.txt") {
  817.         die "$0: UnicodeData.txt: $!\n";
  818.     }
  819.  
  820.     ##
  821.     ## For building \p{_CombAbove} and \p{_CanonDCIJ}
  822.     ##
  823.     my %_Above_HexCodes; ## Hexcodes for chars with $comb == 230 ("ABOVE")
  824.  
  825.     my %CodeToDeco;      ## Maps code to decomp. list for chars with first
  826.                          ## decomp. char an "i" or "j" (for \p{_CanonDCIJ})
  827.  
  828.     ## This is filled in as we go....
  829.     my $CombAbove = Table->New(Is   => '_CombAbove',
  830.                                Desc  => '(for internal casefolding use)',
  831.                                Fuzzy => 0);
  832.  
  833.     while (<IN>)
  834.     {
  835.         next unless /^[0-9A-Fa-f]+;/;
  836.         s/\s+$//;
  837.  
  838.         my ($hexcode,   ## code point in hex (e.g. "0041")
  839.             $name,      ## character name (e.g. "LATIN CAPITAL LETTER A")
  840.             $cat,       ## category (e.g. "Lu")
  841.             $comb,      ## Canonical combining class (e.t. "230")
  842.             $bidi,      ## directional category (e.g. "L")
  843.             $deco,      ## decomposition mapping
  844.             $decimal,   ## decimal digit value
  845.             $digit,     ## digit value
  846.             $number,    ## numeric value
  847.             $mirrored,  ## mirrored
  848.             $unicode10, ## name in Unicode 1.0
  849.             $comment,   ## comment field
  850.             $upper,     ## uppercase mapping
  851.             $lower,     ## lowercase mapping
  852.             $title,     ## titlecase mapping
  853.               ) = split(/\s*;\s*/);
  854.  
  855.     # Note that in Unicode 3.2 there will be names like
  856.     # LINE FEED (LF), which probably means that \N{} needs
  857.     # to cope also with LINE FEED and LF.
  858.     $name = $unicode10 if $name eq '<control>' && $unicode10 ne '';
  859.  
  860.         my $code = hex($hexcode);
  861.  
  862.         if ($comb and $comb == 230) {
  863.             $CombAbove->Append($code);
  864.             $_Above_HexCodes{$hexcode} = 1;
  865.         }
  866.  
  867.         ## Used in building \p{_CanonDCIJ}
  868.         if ($deco and $deco =~ m/^006[9A]\b/) {
  869.             $CodeToDeco{$code} = $deco;
  870.         }
  871.  
  872.         ##
  873.         ## There are a few pairs of lines like:
  874.         ##   AC00;<Hangul Syllable, First>;Lo;0;L;;;;;N;;;;;
  875.         ##   D7A3;<Hangul Syllable, Last>;Lo;0;L;;;;;N;;;;;
  876.         ## that define ranges.
  877.         ##
  878.         if ($name =~ /^<(.+), (First|Last)>$/)
  879.         {
  880.             $name = $1;
  881.             gencat($name, $cat, $code, $2 eq 'First' ? 'Append' : 'Extend');
  882.             #New_Prop(In => $name, $General{$name}, Fuzzy => 1);
  883.         }
  884.         else
  885.         {
  886.             ## normal (single-character) lines
  887.             gencat($name, $cat, $code, 'Append');
  888.  
  889.             # No Append() here since since several codes may map into one.
  890.             $To{Upper}->RawAppendRange($code, $code, $upper) if $upper;
  891.             $To{Lower}->RawAppendRange($code, $code, $lower) if $lower;
  892.             $To{Title}->RawAppendRange($code, $code, $title) if $title;
  893.             $To{Digit}->Append($code, $decimal) if length $decimal;
  894.  
  895.             $Bidi->Append($code, $bidi);
  896.             $Comb->Append($code, $comb) if $comb;
  897.             $Number->Append($code, $number) if length $number;
  898.  
  899.         length($decimal) and ($Number{De} ||= Table->New())->Append($code)
  900.           or
  901.         length($digit)   and ($Number{Di} ||= Table->New())->Append($code)
  902.           or
  903.         length($number)  and ($Number{Nu} ||= Table->New())->Append($code);
  904.  
  905.             $Mirrored->Append($code) if $mirrored eq "Y";
  906.  
  907.             $Bidi{$bidi} ||= Table->New();#Is    => "bt/$bidi",
  908.                                         #Desc  => "Bi-directional category '$bidi'",
  909.                                         #Fuzzy => 0);
  910.             $Bidi{$bidi}->Append($code);
  911.  
  912.             if ($deco)
  913.             {
  914.                 $Deco->Append($code, $deco);
  915.                 if ($deco =~/^<(\w+)>/)
  916.                 {
  917.             my $dshort = $PVA_reverse{dt}{ucfirst lc $1};
  918.                     $DC{com}->Append($code);
  919.  
  920.                     $DC{$dshort} ||= Table->New();
  921.                     $DC{$dshort}->Append($code);
  922.                 }
  923.                 else
  924.                 {
  925.                     $DC{can}->Append($code);
  926.                 }
  927.             }
  928.         }
  929.     }
  930.     close IN;
  931.  
  932.     ##
  933.     ## Tidy up a few special cases....
  934.     ##
  935.  
  936.     $Cat{Cn} = $Assigned->Invert; ## Cn is everything that doesn't exist
  937.     New_Prop(Is => 'Cn',
  938.              $Cat{Cn},
  939.              Desc => "General Category 'Cn' [not functional in Perl]",
  940.              Fuzzy => 0);
  941.  
  942.     ## Unassigned is the same as 'Cn'
  943.     New_Alias(Is => 'Unassigned', SameAs => 'Cn', Fuzzy => 0);
  944.  
  945.     $Cat{C}->Replace($Cat{C}->Merge($Cat{Cn}));  ## Now merge in Cn into C
  946.  
  947.  
  948.     # LC is Ll, Lu, and Lt.
  949.     # (used to be L& or L_, but PropValueAliases.txt defines it as LC)
  950.     New_Prop(Is => 'LC',
  951.              Table->Merge(@Cat{qw[Ll Lu Lt]}),
  952.              Desc  => '[\p{Ll}\p{Lu}\p{Lt}]',
  953.              Fuzzy => 0);
  954.  
  955.     ## Any and All are all code points.
  956.     my $Any = Table->New(Is    => 'Any',
  957.                          Desc  => sprintf("[\\x{0000}-\\x{%X}]",
  958.                                           $LastUnicodeCodepoint),
  959.                          Fuzzy => 0);
  960.     $Any->RawAppendRange(0, $LastUnicodeCodepoint);
  961.  
  962.     New_Alias(Is => 'All', SameAs => 'Any', Fuzzy => 0);
  963.  
  964.     ##
  965.     ## Build special properties for Perl's internal case-folding needs:
  966.     ##    \p{_CaseIgnorable}
  967.     ##    \p{_CanonDCIJ}
  968.     ##    \p{_CombAbove}
  969.     ## _CombAbove was built above. Others are built here....
  970.     ##
  971.  
  972.     ## \p{_CaseIgnorable} is [\p{Mn}\0x00AD\x2010]
  973.     New_Prop(Is => '_CaseIgnorable',
  974.              Table->Merge($Cat{Mn},
  975.                           0x00AD,    #SOFT HYPHEN
  976.                           0x2010),   #HYPHEN
  977.              Desc  => '(for internal casefolding use)',
  978.              Fuzzy => 0);
  979.  
  980.  
  981.     ## \p{_CanonDCIJ} is fairly complex...
  982.     my $CanonCDIJ = Table->New(Is    => '_CanonDCIJ',
  983.                                Desc  => '(for internal casefolding use)',
  984.                                Fuzzy => 0);
  985.     ## It contains the ASCII 'i' and 'j'....
  986.     $CanonCDIJ->Append(0x0069); # ASCII ord("i")
  987.     $CanonCDIJ->Append(0x006A); # ASCII ord("j")
  988.     ## ...and any character with a decomposition that starts with either of
  989.     ## those code points, but only if the decomposition does not have any
  990.     ## combining character with the "ABOVE" canonical combining class.
  991.     for my $code (sort { $a <=> $b} keys %CodeToDeco)
  992.     {
  993.         ## Need to ensure that all decomposition characters do not have
  994.         ## a %HexCodeToComb in %AboveCombClasses.
  995.         my $want = 1;
  996.         for my $deco_hexcode (split / /, $CodeToDeco{$code})
  997.         {
  998.             if (exists $_Above_HexCodes{$deco_hexcode}) {
  999.                 ## one of the decmposition chars has an ABOVE combination
  1000.                 ## class, so we're not interested in this one
  1001.                 $want = 0;
  1002.                 last;
  1003.             }
  1004.         }
  1005.         if ($want) {
  1006.             $CanonCDIJ->Append($code);
  1007.         }
  1008.     }
  1009.  
  1010.  
  1011.  
  1012.     ##
  1013.     ## Now dump the files.
  1014.     ##
  1015.     $Name->Write("Name.pl");
  1016.  
  1017.     {
  1018.     my @PVA = $HEADER;
  1019.     foreach my $name (qw (PropertyAlias PA_reverse PropValueAlias
  1020.                   PVA_reverse PVA_abbr_map)) {
  1021.         # Should I really jump through typeglob hoops just to avoid a
  1022.         # symbolic reference? (%{"utf8::$name})
  1023.         push @PVA, "\n", "\%utf8::$name = (\n",
  1024.         simple_dumper (%{$utf8::{$name}}), ");\n";
  1025.     }
  1026.     push @PVA, "1;\n";
  1027.     WriteIfChanged("PVA.pl", @PVA);
  1028.     }
  1029.  
  1030.     # $Bidi->Write("Bidirectional.pl");
  1031.     for (keys %Bidi) {
  1032.     $Bidi{$_}->Write(
  1033.         ["lib","bc","$_.pl"],
  1034.         "BidiClass category '$PropValueAlias{bc}{$_}'"
  1035.     );
  1036.     }
  1037.  
  1038.     $Comb->Write("CombiningClass.pl");
  1039.     for (keys %{ $PropValueAlias{ccc} }) {
  1040.     my ($code, $name) = @{ $PropValueAlias{ccc}{$_} };
  1041.     (my $c = Table->New())->Append($code);
  1042.     $c->Write(
  1043.         ["lib","ccc","$_.pl"],
  1044.         "CombiningClass category '$name'"
  1045.     );
  1046.     }
  1047.  
  1048.     $Deco->Write("Decomposition.pl");
  1049.     for (keys %DC) {
  1050.     $DC{$_}->Write(
  1051.         ["lib","dt","$_.pl"],
  1052.         "DecompositionType category '$PropValueAlias{dt}{$_}'"
  1053.     );
  1054.     }
  1055.  
  1056.     # $Number->Write("Number.pl");
  1057.     for (keys %Number) {
  1058.     $Number{$_}->Write(
  1059.         ["lib","nt","$_.pl"],
  1060.         "NumericType category '$PropValueAlias{nt}{$_}'"
  1061.     );
  1062.     }
  1063.  
  1064.     # $General->Write("Category.pl");
  1065.  
  1066.     for my $to (sort keys %To) {
  1067.         $To{$to}->Write(["To","$to.pl"]);
  1068.     }
  1069.  
  1070.     for (keys %{ $PropValueAlias{gc} }) {
  1071.     New_Alias(Is => $PropValueAlias{gc}{$_}, SameAs => $_, Fuzzy => 1);
  1072.     }
  1073. }
  1074.  
  1075. ##
  1076. ## Process LineBreak.txt
  1077. ##
  1078. sub LineBreak_Txt()
  1079. {
  1080.     if (not open IN, "LineBreak.txt") {
  1081.         die "$0: LineBreak.txt: $!\n";
  1082.     }
  1083.  
  1084.     my $Lbrk = Table->New();
  1085.     my %Lbrk;
  1086.  
  1087.     while (<IN>)
  1088.     {
  1089.         next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(\w+)/;
  1090.  
  1091.     my ($first, $last, $lbrk) = (hex($1), hex($2||""), $3);
  1092.  
  1093.     $Lbrk->Append($first, $lbrk);
  1094.  
  1095.         $Lbrk{$lbrk} ||= Table->New();
  1096.         $Lbrk{$lbrk}->Append($first);
  1097.  
  1098.     if ($last) {
  1099.         $Lbrk->Extend($last);
  1100.         $Lbrk{$lbrk}->Extend($last);
  1101.     }
  1102.     }
  1103.     close IN;
  1104.  
  1105.     # $Lbrk->Write("Lbrk.pl");
  1106.  
  1107.  
  1108.     for (keys %Lbrk) {
  1109.     $Lbrk{$_}->Write(
  1110.         ["lib","lb","$_.pl"],
  1111.         "Linebreak category '$PropValueAlias{lb}{$_}'"
  1112.     );
  1113.     }
  1114. }
  1115.  
  1116. ##
  1117. ## Process ArabicShaping.txt.
  1118. ##
  1119. sub ArabicShaping_txt()
  1120. {
  1121.     if (not open IN, "ArabicShaping.txt") {
  1122.         die "$0: ArabicShaping.txt: $!\n";
  1123.     }
  1124.  
  1125.     my $ArabLink      = Table->New();
  1126.     my $ArabLinkGroup = Table->New();
  1127.  
  1128.     my %JoinType;
  1129.  
  1130.     while (<IN>)
  1131.     {
  1132.     next unless /^[0-9A-Fa-f]+;/;
  1133.     s/\s+$//;
  1134.  
  1135.     my ($hexcode, $name, $link, $linkgroup) = split(/\s*;\s*/);
  1136.         my $code = hex($hexcode);
  1137.     $ArabLink->Append($code, $link);
  1138.     $ArabLinkGroup->Append($code, $linkgroup);
  1139.  
  1140.         $JoinType{$link} ||= Table->New(Is => "JoinType$link");
  1141.         $JoinType{$link}->Append($code);
  1142.     }
  1143.     close IN;
  1144.  
  1145.     # $ArabLink->Write("ArabLink.pl");
  1146.     # $ArabLinkGroup->Write("ArabLnkGrp.pl");
  1147.  
  1148.  
  1149.     for (keys %JoinType) {
  1150.     $JoinType{$_}->Write(
  1151.         ["lib","jt","$_.pl"],
  1152.         "JoiningType category '$PropValueAlias{jt}{$_}'"
  1153.     );
  1154.     }
  1155. }
  1156.  
  1157. ##
  1158. ## Process EastAsianWidth.txt.
  1159. ##
  1160. sub EastAsianWidth_txt()
  1161. {
  1162.     if (not open IN, "EastAsianWidth.txt") {
  1163.         die "$0: EastAsianWidth.txt: $!\n";
  1164.     }
  1165.  
  1166.     my %EAW;
  1167.  
  1168.     while (<IN>)
  1169.     {
  1170.     next unless /^[0-9A-Fa-f]+;/;
  1171.     s/#.*//;
  1172.     s/\s+$//;
  1173.  
  1174.     my ($hexcode, $pv) = split(/\s*;\s*/);
  1175.         my $code = hex($hexcode);
  1176.         $EAW{$pv} ||= Table->New(Is => "EastAsianWidth$pv");
  1177.         $EAW{$pv}->Append($code);
  1178.     }
  1179.     close IN;
  1180.  
  1181.  
  1182.     for (keys %EAW) {
  1183.     $EAW{$_}->Write(
  1184.         ["lib","ea","$_.pl"],
  1185.         "EastAsianWidth category '$PropValueAlias{ea}{$_}'"
  1186.     );
  1187.     }
  1188. }
  1189.  
  1190. ##
  1191. ## Process HangulSyllableType.txt.
  1192. ##
  1193. sub HangulSyllableType_txt()
  1194. {
  1195.     if (not open IN, "HangulSyllableType.txt") {
  1196.         die "$0: HangulSyllableType.txt: $!\n";
  1197.     }
  1198.  
  1199.     my %HST;
  1200.  
  1201.     while (<IN>)
  1202.     {
  1203.         next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(\w+)/;
  1204.     my ($first, $last, $pv) = (hex($1), hex($2||""), $3);
  1205.  
  1206.         $HST{$pv} ||= Table->New(Is => "HangulSyllableType$pv");
  1207.         $HST{$pv}->Append($first);
  1208.  
  1209.     if ($last) { $HST{$pv}->Extend($last) }
  1210.     }
  1211.     close IN;
  1212.  
  1213.     for (keys %HST) {
  1214.     $HST{$_}->Write(
  1215.         ["lib","hst","$_.pl"],
  1216.         "HangulSyllableType category '$PropValueAlias{hst}{$_}'"
  1217.     );
  1218.     }
  1219. }
  1220.  
  1221. ##
  1222. ## Process Jamo.txt.
  1223. ##
  1224. sub Jamo_txt()
  1225. {
  1226.     if (not open IN, "Jamo.txt") {
  1227.         die "$0: Jamo.txt: $!\n";
  1228.     }
  1229.     my $Short = Table->New();
  1230.  
  1231.     while (<IN>)
  1232.     {
  1233.     next unless /^([0-9A-Fa-f]+)\s*;\s*(\w*)/;
  1234.     my ($code, $short) = (hex($1), $2);
  1235.  
  1236.     $Short->Append($code, $short);
  1237.     }
  1238.     close IN;
  1239.     # $Short->Write("JamoShort.pl");
  1240. }
  1241.  
  1242. ##
  1243. ## Process Scripts.txt.
  1244. ##
  1245. sub Scripts_txt()
  1246. {
  1247.     my @ScriptInfo;
  1248.  
  1249.     if (not open(IN, "Scripts.txt")) {
  1250.         die "$0: Scripts.txt: $!\n";
  1251.     }
  1252.     while (<IN>) {
  1253.         next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(.+?)\s*\#/;
  1254.  
  1255.         # Wait until all the scripts have been read since
  1256.         # they are not listed in numeric order.
  1257.         push @ScriptInfo, [ hex($1), hex($2||""), $3 ];
  1258.     }
  1259.     close IN;
  1260.  
  1261.     # Now append the scripts properties in their code point order.
  1262.  
  1263.     my %Script;
  1264.     my $Scripts = Table->New();
  1265.  
  1266.     for my $script (sort { $a->[0] <=> $b->[0] } @ScriptInfo)
  1267.     {
  1268.         my ($first, $last, $name) = @$script;
  1269.         $Scripts->Append($first, $name);
  1270.  
  1271.         $Script{$name} ||= Table->New(Is    => $name,
  1272.                                       Desc  => "Script '$name'",
  1273.                                       Fuzzy => 1);
  1274.         $Script{$name}->Append($first, $name);
  1275.  
  1276.         if ($last) {
  1277.             $Scripts->Extend($last);
  1278.             $Script{$name}->Extend($last);
  1279.         }
  1280.     }
  1281.  
  1282.     # $Scripts->Write("Scripts.pl");
  1283.  
  1284.     ## Common is everything not explicitly assigned to a Script
  1285.     ##
  1286.     ##    ***shouldn't this be intersected with \p{Assigned}? ******
  1287.     ##
  1288.     New_Prop(Is => 'Common',
  1289.              $Scripts->Invert,
  1290.              Desc  => 'Pseudo-Script of codepoints not in other Unicode scripts',
  1291.              Fuzzy => 1);
  1292. }
  1293.  
  1294. ##
  1295. ## Given a name like "Close Punctuation", return a regex (that when applied
  1296. ## with /i) matches any valid form of that name (e.g. "ClosePunctuation",
  1297. ## "Close-Punctuation", etc.)
  1298. ##
  1299. ## Accept any space, dash, or underbar where in the official name there is
  1300. ## space or a dash (or underbar, but there never is).
  1301. ##
  1302. ##
  1303. sub NameToRegex($)
  1304. {
  1305.     my $Name = shift;
  1306.     $Name =~ s/[- _]/(?:[-_]|\\s+)?/g;
  1307.     return $Name;
  1308. }
  1309.  
  1310. ##
  1311. ## Process Blocks.txt.
  1312. ##
  1313. sub Blocks_txt()
  1314. {
  1315.     my $Blocks = Table->New();
  1316.     my %Blocks;
  1317.  
  1318.     if (not open IN, "Blocks.txt") {
  1319.         die "$0: Blocks.txt: $!\n";
  1320.     }
  1321.  
  1322.     while (<IN>)
  1323.     {
  1324.         #next if not /Private Use$/;
  1325.     next if not /^([0-9A-Fa-f]+)\.\.([0-9A-Fa-f]+)\s*;\s*(.+?)\s*$/;
  1326.  
  1327.     my ($first, $last, $name) = (hex($1), hex($2), $3);
  1328.  
  1329.     $Blocks->Append($first, $name);
  1330.  
  1331.         $Blocks{$name} ||= Table->New(In    => $name,
  1332.                                       Desc  => "Block '$name'",
  1333.                                       Fuzzy => 1);
  1334.         $Blocks{$name}->Append($first, $name);
  1335.  
  1336.     if ($last and $last != $first) {
  1337.         $Blocks->Extend($last);
  1338.         $Blocks{$name}->Extend($last);
  1339.     }
  1340.     }
  1341.     close IN;
  1342.  
  1343.     # $Blocks->Write("Blocks.pl");
  1344. }
  1345.  
  1346. ##
  1347. ## Read in the PropList.txt.  It contains extended properties not
  1348. ## listed in the UnicodeData.txt, such as 'Other_Alphabetic':
  1349. ## alphabetic but not of the general category L; many modifiers
  1350. ## belong to this extended property category: while they are not
  1351. ## alphabets, they are alphabetic in nature.
  1352. ##
  1353. sub PropList_txt()
  1354. {
  1355.     my @PropInfo;
  1356.  
  1357.     if (not open IN, "PropList.txt") {
  1358.         die "$0: PropList.txt: $!\n";
  1359.     }
  1360.  
  1361.     while (<IN>)
  1362.     {
  1363.     next unless /^([0-9A-Fa-f]+)(?:\.\.([0-9A-Fa-f]+))?\s*;\s*(.+?)\s*\#/;
  1364.  
  1365.     # Wait until all the extended properties have been read since
  1366.     # they are not listed in numeric order.
  1367.     push @PropInfo, [ hex($1), hex($2||""), $3 ];
  1368.     }
  1369.     close IN;
  1370.  
  1371.     # Now append the extended properties in their code point order.
  1372.     my $Props = Table->New();
  1373.     my %Prop;
  1374.  
  1375.     for my $prop (sort { $a->[0] <=> $b->[0] } @PropInfo)
  1376.     {
  1377.         my ($first, $last, $name) = @$prop;
  1378.         $Props->Append($first, $name);
  1379.  
  1380.         $Prop{$name} ||= Table->New(Is    => $name,
  1381.                                     Desc  => "Extended property '$name'",
  1382.                                     Fuzzy => 1);
  1383.         $Prop{$name}->Append($first, $name);
  1384.  
  1385.         if ($last) {
  1386.             $Props->Extend($last);
  1387.             $Prop{$name}->Extend($last);
  1388.         }
  1389.     }
  1390.  
  1391.     for (keys %Prop) {
  1392.     (my $file = $PA_reverse{$_}) =~ tr/_//d;
  1393.     # XXX I'm assuming that the names from %Prop don't suffer 8.3 clashes.
  1394.     $BaseNames{lc $file}++;
  1395.     $Prop{$_}->Write(
  1396.         ["lib","gc_sc","$file.pl"],
  1397.         "Binary property '$_'"
  1398.     );
  1399.     }
  1400.  
  1401.     # Alphabetic is L and Other_Alphabetic.
  1402.     New_Prop(Is    => 'Alphabetic',
  1403.              Table->Merge($Cat{L}, $Prop{Other_Alphabetic}),
  1404.              Desc  => '[\p{L}\p{OtherAlphabetic}]', # use canonical names here
  1405.              Fuzzy => 1);
  1406.  
  1407.     # Lowercase is Ll and Other_Lowercase.
  1408.     New_Prop(Is    => 'Lowercase',
  1409.              Table->Merge($Cat{Ll}, $Prop{Other_Lowercase}),
  1410.              Desc  => '[\p{Ll}\p{OtherLowercase}]', # use canonical names here
  1411.              Fuzzy => 1);
  1412.  
  1413.     # Uppercase is Lu and Other_Uppercase.
  1414.     New_Prop(Is => 'Uppercase',
  1415.              Table->Merge($Cat{Lu}, $Prop{Other_Uppercase}),
  1416.              Desc  => '[\p{Lu}\p{Other_Uppercase}]', # use canonical names here
  1417.              Fuzzy => 1);
  1418.  
  1419.     # Math is Sm and Other_Math.
  1420.     New_Prop(Is => 'Math',
  1421.              Table->Merge($Cat{Sm}, $Prop{Other_Math}),
  1422.              Desc  => '[\p{Sm}\p{OtherMath}]', # use canonical names here
  1423.              Fuzzy => 1);
  1424.  
  1425.     # ID_Start is Ll, Lu, Lt, Lm, Lo, and Nl.
  1426.     New_Prop(Is => 'ID_Start',
  1427.              Table->Merge(@Cat{qw[Ll Lu Lt Lm Lo Nl]}),
  1428.              Desc  => '[\p{Ll}\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{Nl}]',
  1429.              Fuzzy => 1);
  1430.  
  1431.     # ID_Continue is ID_Start, Mn, Mc, Nd, and Pc.
  1432.     New_Prop(Is => 'ID_Continue',
  1433.              Table->Merge(@Cat{qw[Ll Lu Lt Lm Lo Nl Mn Mc Nd Pc ]}),
  1434.              Desc  => '[\p{ID_Start}\p{Mn}\p{Mc}\p{Nd}\p{Pc}]',
  1435.              Fuzzy => 1);
  1436. }
  1437.  
  1438.  
  1439. ##
  1440. ## These are used in:
  1441. ##   MakePropTestScript()
  1442. ##   WriteAllMappings()
  1443. ## for making the test script.
  1444. ##
  1445. my %FuzzyNameToTest;
  1446. my %ExactNameToTest;
  1447.  
  1448.  
  1449. ## This used only for making the test script
  1450. sub GenTests($$$$)
  1451. {
  1452.     my $FH = shift;
  1453.     my $Prop = shift;
  1454.     my $MatchCode = shift;
  1455.     my $FailCode = shift;
  1456.  
  1457.     if (defined $MatchCode) {
  1458.         printf $FH qq/Expect(1, "\\x{%04X}", '\\p{$Prop}' );\n/, $MatchCode;
  1459.         printf $FH qq/Expect(0, "\\x{%04X}", '\\p{^$Prop}');\n/, $MatchCode;
  1460.         printf $FH qq/Expect(0, "\\x{%04X}", '\\P{$Prop}' );\n/, $MatchCode;
  1461.         printf $FH qq/Expect(1, "\\x{%04X}", '\\P{^$Prop}');\n/, $MatchCode;
  1462.     }
  1463.     if (defined $FailCode) {
  1464.         printf $FH qq/Expect(0, "\\x{%04X}", '\\p{$Prop}' );\n/, $FailCode;
  1465.         printf $FH qq/Expect(1, "\\x{%04X}", '\\p{^$Prop}');\n/, $FailCode;
  1466.         printf $FH qq/Expect(1, "\\x{%04X}", '\\P{$Prop}' );\n/, $FailCode;
  1467.         printf $FH qq/Expect(0, "\\x{%04X}", '\\P{^$Prop}');\n/, $FailCode;
  1468.     }
  1469. }
  1470.  
  1471. ## This used only for making the test script
  1472. sub ExpectError($$)
  1473. {
  1474.     my $FH = shift;
  1475.     my $prop = shift;
  1476.  
  1477.     print $FH qq/Error('\\p{$prop}');\n/;
  1478.     print $FH qq/Error('\\P{$prop}');\n/;
  1479. }
  1480.  
  1481. ## This used only for making the test script
  1482. my @GoodSeps = (
  1483.                 " ",
  1484.                 "-",
  1485.                 " \t ",
  1486.                 "",
  1487.                 "",
  1488.                 "_",
  1489.                );
  1490. my @BadSeps = (
  1491.                "--",
  1492.                "__",
  1493.                " _",
  1494.                "/"
  1495.               );
  1496.  
  1497. ## This used only for making the test script
  1498. sub RandomlyFuzzifyName($;$)
  1499. {
  1500.     my $Name = shift;
  1501.     my $WantError = shift;  ## if true, make an error
  1502.  
  1503.     my @parts;
  1504.     for my $part (split /[-\s_]+/, $Name)
  1505.     {
  1506.         if (@parts) {
  1507.             if ($WantError and rand() < 0.3) {
  1508.                 push @parts, $BadSeps[rand(@BadSeps)];
  1509.                 $WantError = 0;
  1510.             } else {
  1511.                 push @parts, $GoodSeps[rand(@GoodSeps)];
  1512.             }
  1513.         }
  1514.         my $switch = int rand(4);
  1515.         if ($switch == 0) {
  1516.             push @parts, uc $part;
  1517.         } elsif ($switch == 1) {
  1518.             push @parts, lc $part;
  1519.         } elsif ($switch == 2) {
  1520.             push @parts, ucfirst $part;
  1521.         } else {
  1522.             push @parts, $part;
  1523.         }
  1524.     }
  1525.     my $new = join('', @parts);
  1526.  
  1527.     if ($WantError) {
  1528.         if (rand() >= 0.5) {
  1529.             $new .= $BadSeps[rand(@BadSeps)];
  1530.         } else {
  1531.             $new = $BadSeps[rand(@BadSeps)] . $new;
  1532.         }
  1533.     }
  1534.     return $new;
  1535. }
  1536.  
  1537. ## This used only for making the test script
  1538. sub MakePropTestScript()
  1539. {
  1540.     ## this written directly -- it's huge.
  1541.     force_unlink ("TestProp.pl");
  1542.     if (not open OUT, ">TestProp.pl") {
  1543.         die "$0: TestProp.pl: $!\n";
  1544.     }
  1545.     print OUT <DATA>;
  1546.  
  1547.     while (my ($Name, $Table) = each %ExactNameToTest)
  1548.     {
  1549.         GenTests(*OUT, $Name, $Table->ValidCode, $Table->InvalidCode);
  1550.         ExpectError(*OUT, uc $Name) if uc $Name ne $Name;
  1551.         ExpectError(*OUT, lc $Name) if lc $Name ne $Name;
  1552.     }
  1553.  
  1554.  
  1555.     while (my ($Name, $Table) = each %FuzzyNameToTest)
  1556.     {
  1557.         my $Orig  = $CanonicalToOrig{$Name};
  1558.         my %Names = (
  1559.                      $Name => 1,
  1560.                      $Orig => 1,
  1561.                      RandomlyFuzzifyName($Orig) => 1
  1562.                     );
  1563.  
  1564.         for my $N (keys %Names) {
  1565.             GenTests(*OUT, $N, $Table->ValidCode, $Table->InvalidCode);
  1566.         }
  1567.  
  1568.         ExpectError(*OUT, RandomlyFuzzifyName($Orig, 'ERROR'));
  1569.     }
  1570.  
  1571.     print OUT "Finished();\n";
  1572.     close OUT;
  1573. }
  1574.  
  1575.  
  1576. ##
  1577. ## These are used only in:
  1578. ##   RegisterFileForName()
  1579. ##   WriteAllMappings()
  1580. ##
  1581. my %Exact;      ## will become %utf8::Exact;
  1582. my %Canonical;  ## will become %utf8::Canonical;
  1583. my %CaComment;  ## Comment for %Canonical entry of same key
  1584.  
  1585. ##
  1586. ## Given info about a name and a datafile that it should be associated with,
  1587. ## register that assocation in %Exact and %Canonical.
  1588. sub RegisterFileForName($$$$)
  1589. {
  1590.     my $Type     = shift;
  1591.     my $Name     = shift;
  1592.     my $IsFuzzy  = shift;
  1593.     my $filename = shift;
  1594.  
  1595.     ##
  1596.     ## Now in details for the mapping. $Type eq 'Is' has the
  1597.     ## Is removed, as it will be removed in utf8_heavy when this
  1598.     ## data is being checked. In keeps its "In", but a second
  1599.     ## sans-In record is written if it doesn't conflict with
  1600.     ## anything already there.
  1601.     ##
  1602.     if (not $IsFuzzy)
  1603.     {
  1604.         if ($Type eq 'Is') {
  1605.             die "oops[$Name]" if $Exact{$Name};
  1606.             $Exact{$Name} = $filename;
  1607.         } else {
  1608.             die "oops[$Type$Name]" if $Exact{"$Type$Name"};
  1609.             $Exact{"$Type$Name"} = $filename;
  1610.             $Exact{$Name} = $filename if not $Exact{$Name};
  1611.         }
  1612.     }
  1613.     else
  1614.     {
  1615.         my $CName = lc $Name;
  1616.         if ($Type eq 'Is') {
  1617.             die "oops[$CName]" if $Canonical{$CName};
  1618.             $Canonical{$CName} = $filename;
  1619.             $CaComment{$CName} = $Name if $Name =~ tr/A-Z// >= 2;
  1620.         } else {
  1621.             die "oops[$Type$CName]" if $Canonical{lc "$Type$CName"};
  1622.             $Canonical{lc "$Type$CName"} = $filename;
  1623.             $CaComment{lc "$Type$CName"} = "$Type$Name";
  1624.             if (not $Canonical{$CName}) {
  1625.                 $Canonical{$CName} = $filename;
  1626.                 $CaComment{$CName} = "$Type$Name";
  1627.             }
  1628.         }
  1629.     }
  1630. }
  1631.  
  1632. ##
  1633. ## Writes the info accumulated in
  1634. ##
  1635. ##       %TableInfo;
  1636. ##       %FuzzyNames;
  1637. ##       %AliasInfo;
  1638. ##
  1639. ##
  1640. sub WriteAllMappings()
  1641. {
  1642.     my @MAP;
  1643.  
  1644.     ## 'Is' *MUST* come first, so its names have precidence over 'In's
  1645.     for my $Type ('Is', 'In')
  1646.     {
  1647.         my %RawNameToFile; ## a per-$Type cache
  1648.  
  1649.         for my $Name (sort {length $a <=> length $b} keys %{$TableInfo{$Type}})
  1650.         {
  1651.             ## Note: $Name is already canonical
  1652.             my $Table   = $TableInfo{$Type}->{$Name};
  1653.             my $IsFuzzy = $FuzzyNames{$Type}->{$Name};
  1654.  
  1655.             ## Need an 8.3 safe filename (which means "an 8 safe" $filename)
  1656.             my $filename;
  1657.             {
  1658.                 ## 'Is' items lose 'Is' from the basename.
  1659.                 $filename = $Type eq 'Is' ?
  1660.             ($PVA_reverse{sc}{$Name} || $Name) :
  1661.             "$Type$Name";
  1662.  
  1663.                 $filename =~ s/[^\w_]+/_/g; # "L&" -> "L_"
  1664.                 substr($filename, 8) = '' if length($filename) > 8;
  1665.  
  1666.                 ##
  1667.                 ## Make sure the basename doesn't conflict with something we
  1668.                 ## might have already written. If we have, say,
  1669.                 ##     InGreekExtended1
  1670.                 ##     InGreekExtended2
  1671.                 ## they become
  1672.                 ##     InGreekE
  1673.                 ##     InGreek2
  1674.                 ##
  1675.                 while (my $num = $BaseNames{lc $filename}++)
  1676.                 {
  1677.                     $num++; ## so basenames with numbers start with '2', which
  1678.                             ## just looks more natural.
  1679.                     ## Want to append $num, but if it'll make the basename longer
  1680.                     ## than 8 characters, pre-truncate $filename so that the result
  1681.                     ## is acceptable.
  1682.                     my $delta = length($filename) + length($num) - 8;
  1683.                     if ($delta > 0) {
  1684.                         substr($filename, -$delta) = $num;
  1685.                     } else {
  1686.                         $filename .= $num;
  1687.                     }
  1688.                 }
  1689.             };
  1690.  
  1691.             ##
  1692.             ## Construct a nice comment to add to the file, and build data
  1693.             ## for the "./Properties" file along the way.
  1694.             ##
  1695.             my $Comment;
  1696.             {
  1697.                 my $Desc = $TableDesc{$Type}->{$Name} || "";
  1698.                 ## get list of names this table is reference by
  1699.                 my @Supported = $Name;
  1700.                 while (my ($Orig, $Alias) = each %{ $AliasInfo{$Type} })
  1701.                 {
  1702.                     if ($Orig eq $Name) {
  1703.                         push @Supported, $Alias;
  1704.                     }
  1705.                 }
  1706.  
  1707.                 my $TypeToShow = $Type eq 'Is' ? "" : $Type;
  1708.                 my $OrigProp;
  1709.  
  1710.                 $Comment = "This file supports:\n";
  1711.                 for my $N (@Supported)
  1712.                 {
  1713.                     my $IsFuzzy = $FuzzyNames{$Type}->{$N};
  1714.                     my $Prop    = "\\p{$TypeToShow$Name}";
  1715.                     $OrigProp = $Prop if not $OrigProp; #cache for aliases
  1716.                     if ($IsFuzzy) {
  1717.                         $Comment .= "\t$Prop (and fuzzy permutations)\n";
  1718.                     } else {
  1719.                         $Comment .= "\t$Prop\n";
  1720.                     }
  1721.                     my $MyDesc = ($N eq $Name) ? $Desc : "Alias for $OrigProp ($Desc)";
  1722.  
  1723.                     push @MAP, sprintf("%s %-42s %s\n",
  1724.                                        $IsFuzzy ? '*' : ' ', $Prop, $MyDesc);
  1725.                 }
  1726.                 if ($Desc) {
  1727.                     $Comment .= "\nMeaning: $Desc\n";
  1728.                 }
  1729.  
  1730.             }
  1731.             ##
  1732.             ## Okay, write the file...
  1733.             ##
  1734.             $Table->Write(["lib","gc_sc","$filename.pl"], $Comment);
  1735.  
  1736.             ## and register it
  1737.             $RawNameToFile{$Name} = $filename;
  1738.             RegisterFileForName($Type => $Name, $IsFuzzy, $filename);
  1739.  
  1740.             if ($IsFuzzy)
  1741.             {
  1742.                 my $CName = CanonicalName($Type . '_'. $Name);
  1743.                 $FuzzyNameToTest{$Name}  = $Table if !$FuzzyNameToTest{$Name};
  1744.                 $FuzzyNameToTest{$CName} = $Table if !$FuzzyNameToTest{$CName};
  1745.             } else {
  1746.                 $ExactNameToTest{$Name} = $Table;
  1747.             }
  1748.  
  1749.         }
  1750.  
  1751.         ## Register aliase info
  1752.         for my $Name (sort {length $a <=> length $b} keys %{$AliasInfo{$Type}})
  1753.         {
  1754.             my $Alias    = $AliasInfo{$Type}->{$Name};
  1755.             my $IsFuzzy  = $FuzzyNames{$Type}->{$Alias};
  1756.             my $filename = $RawNameToFile{$Name};
  1757.             die "oops [$Alias]->[$Name]" if not $filename;
  1758.             RegisterFileForName($Type => $Alias, $IsFuzzy, $filename);
  1759.  
  1760.             my $Table = $TableInfo{$Type}->{$Name};
  1761.             die "oops" if not $Table;
  1762.             if ($IsFuzzy)
  1763.             {
  1764.                 my $CName = CanonicalName($Type .'_'. $Alias);
  1765.                 $FuzzyNameToTest{$Alias} = $Table if !$FuzzyNameToTest{$Alias};
  1766.                 $FuzzyNameToTest{$CName} = $Table if !$FuzzyNameToTest{$CName};
  1767.             } else {
  1768.                 $ExactNameToTest{$Alias} = $Table;
  1769.             }
  1770.         }
  1771.     }
  1772.  
  1773.     ##
  1774.     ## Write out the property list
  1775.     ##
  1776.     {
  1777.         my @OUT = (
  1778.                    "##\n",
  1779.                    "## This file created by $0\n",
  1780.                    "## List of built-in \\p{...}/\\P{...} properties.\n",
  1781.                    "##\n",
  1782.                    "## '*' means name may be 'fuzzy'\n",
  1783.                    "##\n\n",
  1784.                    sort { substr($a,2) cmp substr($b, 2) } @MAP,
  1785.                   );
  1786.         WriteIfChanged('Properties', @OUT);
  1787.     }
  1788.  
  1789.     use Text::Tabs ();  ## using this makes the files about half the size
  1790.  
  1791.     ## Write Exact.pl
  1792.     {
  1793.         my @OUT = (
  1794.                    $HEADER,
  1795.                    "##\n",
  1796.                    "## Data in this file used by ../utf8_heavy.pl\n",
  1797.                    "##\n\n",
  1798.                    "## Mapping from name to filename in ./lib/gc_sc\n",
  1799.                    "%utf8::Exact = (\n",
  1800.                   );
  1801.  
  1802.     $Exact{InGreek} = 'InGreekA';  # this is evil kludge
  1803.         for my $Name (sort keys %Exact)
  1804.         {
  1805.             my $File = $Exact{$Name};
  1806.             $Name = $Name =~ m/\W/ ? qq/'$Name'/ : " $Name ";
  1807.             my $Text = sprintf("%-15s => %s,\n", $Name, qq/'$File'/);
  1808.             push @OUT, Text::Tabs::unexpand($Text);
  1809.         }
  1810.         push @OUT, ");\n1;\n";
  1811.  
  1812.         WriteIfChanged('Exact.pl', @OUT);
  1813.     }
  1814.  
  1815.     ## Write Canonical.pl
  1816.     {
  1817.         my @OUT = (
  1818.                    $HEADER,
  1819.                    "##\n",
  1820.                    "## Data in this file used by ../utf8_heavy.pl\n",
  1821.                    "##\n\n",
  1822.                    "## Mapping from lc(canonical name) to filename in ./lib\n",
  1823.                    "%utf8::Canonical = (\n",
  1824.                   );
  1825.         my $Trail = ""; ## used just to keep the spacing pretty
  1826.         for my $Name (sort keys %Canonical)
  1827.         {
  1828.             my $File = $Canonical{$Name};
  1829.             if ($CaComment{$Name}) {
  1830.                 push @OUT, "\n" if not $Trail;
  1831.                 push @OUT, " # $CaComment{$Name}\n";
  1832.                 $Trail = "\n";
  1833.             } else {
  1834.                 $Trail = "";
  1835.             }
  1836.             $Name = $Name =~ m/\W/ ? qq/'$Name'/ : " $Name ";
  1837.             my $Text = sprintf("  %-41s => %s,\n$Trail", $Name, qq/'$File'/);
  1838.             push @OUT, Text::Tabs::unexpand($Text);
  1839.         }
  1840.         push @OUT, ");\n1\n";
  1841.         WriteIfChanged('Canonical.pl', @OUT);
  1842.     }
  1843.  
  1844.     MakePropTestScript() if $MakeTestScript;
  1845. }
  1846.  
  1847.  
  1848. sub SpecialCasing_txt()
  1849. {
  1850.     #
  1851.     # Read in the special cases.
  1852.     #
  1853.  
  1854.     my %CaseInfo;
  1855.  
  1856.     if (not open IN, "SpecialCasing.txt") {
  1857.         die "$0: SpecialCasing.txt: $!\n";
  1858.     }
  1859.     while (<IN>) {
  1860.         next unless /^[0-9A-Fa-f]+;/;
  1861.         s/\#.*//;
  1862.         s/\s+$//;
  1863.  
  1864.         my ($code, $lower, $title, $upper, $condition) = split(/\s*;\s*/);
  1865.  
  1866.         if ($condition) { # not implemented yet
  1867.             print "# SKIPPING $_\n" if $Verbose;
  1868.             next;
  1869.         }
  1870.  
  1871.         # Wait until all the special cases have been read since
  1872.         # they are not listed in numeric order.
  1873.         my $ix = hex($code);
  1874.         push @{$CaseInfo{Lower}}, [ $ix, $code, $lower ]
  1875.         unless $code eq $lower;
  1876.         push @{$CaseInfo{Title}}, [ $ix, $code, $title ]
  1877.         unless $code eq $title;
  1878.         push @{$CaseInfo{Upper}}, [ $ix, $code, $upper ]
  1879.         unless $code eq $upper;
  1880.     }
  1881.     close IN;
  1882.  
  1883.     # Now write out the special cases properties in their code point order.
  1884.     # Prepend them to the To/{Upper,Lower,Title}.pl.
  1885.  
  1886.     for my $case (qw(Lower Title Upper))
  1887.     {
  1888.         my $NormalCase = do "To/$case.pl" || die "$0: $@\n";
  1889.  
  1890.         my @OUT =
  1891.         (
  1892.          $HEADER, "\n",
  1893.          "# The key UTF-8 _bytes_, the value UTF-8 (speed hack)\n",
  1894.          "%utf8::ToSpec$case =\n(\n",
  1895.         );
  1896.  
  1897.         for my $prop (sort { $a->[0] <=> $b->[0] } @{$CaseInfo{$case}}) {
  1898.             my ($ix, $code, $to) = @$prop;
  1899.             my $tostr =
  1900.               join "", map { sprintf "\\x{%s}", $_ } split ' ', $to;
  1901.             push @OUT, sprintf qq["%s" => "$tostr",\n], join("", map { sprintf "\\x%02X", $_ } unpack("U0C*", pack("U", $ix)));
  1902.         # Remove any single-character mappings for
  1903.         # the same character since we are going for
  1904.         # the special casing rules.
  1905.         $NormalCase =~ s/^$code\t\t\w+\n//m;
  1906.         }
  1907.         push @OUT, (
  1908.                     ");\n\n",
  1909.                     "return <<'END';\n",
  1910.                     $NormalCase,
  1911.                     "END\n"
  1912.                     );
  1913.         WriteIfChanged(["To","$case.pl"], @OUT);
  1914.     }
  1915. }
  1916.  
  1917. #
  1918. # Read in the case foldings.
  1919. #
  1920. # We will do full case folding, C + F + I (see CaseFolding.txt).
  1921. #
  1922. sub CaseFolding_txt()
  1923. {
  1924.     if (not open IN, "CaseFolding.txt") {
  1925.     die "$0: CaseFolding.txt: $!\n";
  1926.     }
  1927.  
  1928.     my $Fold = Table->New();
  1929.     my %Fold;
  1930.  
  1931.     while (<IN>) {
  1932.     # Skip status 'S', simple case folding
  1933.     next unless /^([0-9A-Fa-f]+)\s*;\s*([CFI])\s*;\s*([0-9A-Fa-f]+(?: [0-9A-Fa-f]+)*)\s*;/;
  1934.  
  1935.     my ($code, $status, $fold) = (hex($1), $2, $3);
  1936.  
  1937.     if ($status eq 'C') { # Common: one-to-one folding
  1938.         # No append() since several codes may fold into one.
  1939.         $Fold->RawAppendRange($code, $code, $fold);
  1940.     } else { # F: full, or I: dotted uppercase I -> dotless lowercase I
  1941.         $Fold{$code} = $fold;
  1942.     }
  1943.     }
  1944.     close IN;
  1945.  
  1946.     $Fold->Write("To/Fold.pl");
  1947.  
  1948.     #
  1949.     # Prepend the special foldings to the common foldings.
  1950.     #
  1951.     my $CommonFold = do "To/Fold.pl" || die "$0: To/Fold.pl: $!\n";
  1952.  
  1953.     my @OUT =
  1954.     (
  1955.      $HEADER, "\n",
  1956.      "#  The ke UTF-8 _bytes_, the value UTF-8 (speed hack)\n",
  1957.      "%utf8::ToSpecFold =\n(\n",
  1958.     );
  1959.     for my $code (sort { $a <=> $b } keys %Fold) {
  1960.         my $foldstr =
  1961.           join "", map { sprintf "\\x{%s}", $_ } split ' ', $Fold{$code};
  1962.         push @OUT, sprintf qq["%s" => "$foldstr",\n], join("", map { sprintf "\\x%02X", $_ } unpack("U0C*", pack("U", $code)));
  1963.     }
  1964.     push @OUT, (
  1965.                 ");\n\n",
  1966.                 "return <<'END';\n",
  1967.                 $CommonFold,
  1968.                 "END\n",
  1969.                );
  1970.  
  1971.     WriteIfChanged(["To","Fold.pl"], @OUT);
  1972. }
  1973.  
  1974. ## Do it....
  1975.  
  1976. Build_Aliases();
  1977. UnicodeData_Txt();
  1978. PropList_txt();
  1979.  
  1980. Scripts_txt();
  1981. Blocks_txt();
  1982.  
  1983. WriteAllMappings();
  1984.  
  1985. LineBreak_Txt();
  1986. ArabicShaping_txt();
  1987. EastAsianWidth_txt();
  1988. HangulSyllableType_txt();
  1989. Jamo_txt();
  1990. SpecialCasing_txt();
  1991. CaseFolding_txt();
  1992.  
  1993. exit(0);
  1994.  
  1995. ## TRAILING CODE IS USED BY MakePropTestScript()
  1996. __DATA__
  1997. use strict;
  1998. use warnings;
  1999.  
  2000. my $Tests = 0;
  2001. my $Fails = 0;
  2002.  
  2003. sub Expect($$$)
  2004. {
  2005.     my $Expect = shift;
  2006.     my $String = shift;
  2007.     my $Regex  = shift;
  2008.     my $Line   = (caller)[2];
  2009.  
  2010.     $Tests++;
  2011.     my $RegObj;
  2012.     my $result = eval {
  2013.         $RegObj = qr/$Regex/;
  2014.         $String =~ $RegObj ? 1 : 0
  2015.     };
  2016.     
  2017.     if (not defined $result) {
  2018.         print "couldn't compile /$Regex/ on $0 line $Line: $@\n";
  2019.         $Fails++;
  2020.     } elsif ($result ^ $Expect) {
  2021.         print "bad result (expected $Expect) on $0 line $Line: $@\n";
  2022.         $Fails++;
  2023.     }
  2024. }
  2025.  
  2026. sub Error($)
  2027. {
  2028.     my $Regex  = shift;
  2029.     $Tests++;
  2030.     if (eval { 'x' =~ qr/$Regex/; 1 }) {
  2031.         $Fails++;
  2032.         my $Line = (caller)[2];
  2033.         print "expected error for /$Regex/ on $0 line $Line: $@\n";
  2034.     }
  2035. }
  2036.  
  2037. sub Finished()
  2038. {
  2039.    if ($Fails == 0) {
  2040.       print "All $Tests tests passed.\n";
  2041.       exit(0);
  2042.    } else {
  2043.       print "$Tests tests, $Fails failed!\n";
  2044.       exit(-1);
  2045.    }
  2046. }
  2047.