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