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