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