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