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