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