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