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