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