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