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