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