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