This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Correct VMS-specific handling of $! in Perl_magic_get.
[perl5.git] / lib / unicore / mktables
CommitLineData
d73e5302 1#!/usr/bin/perl -w
99870f4d
KW
2
3# !!!!!!!!!!!!!! IF YOU MODIFY THIS FILE !!!!!!!!!!!!!!!!!!!!!!!!!
4# Any files created or read by this program should be listed in 'mktables.lst'
5# Use -makelist to regenerate it.
6
23e33b60
KW
7# Needs 'no overloading' to run faster on miniperl. Code commented out at the
8# subroutine objaddr can be used instead to work as far back (untested) as
9# 5.8: needs pack "U".
10require 5.010_001;
d73e5302 11use strict;
99870f4d 12use warnings;
cf25bb62 13use Carp;
99870f4d
KW
14use File::Find;
15use File::Path;
d07a55ed 16use File::Spec;
99870f4d
KW
17use Text::Tabs;
18
19sub DEBUG () { 0 } # Set to 0 for production; 1 for development
20
21##########################################################################
22#
23# mktables -- create the runtime Perl Unicode files (lib/unicore/.../*.pl),
24# from the Unicode database files (lib/unicore/.../*.txt), It also generates
25# a pod file and a .t file
26#
27# The structure of this file is:
28# First these introductory comments; then
29# code needed for everywhere, such as debugging stuff; then
30# code to handle input parameters; then
31# data structures likely to be of external interest (some of which depend on
32# the input parameters, so follows them; then
33# more data structures and subroutine and package (class) definitions; then
34# the small actual loop to process the input files and finish up; then
35# a __DATA__ section, for the .t tests
36#
37# This program works on all releases of Unicode through at least 5.2. The
38# outputs have been scrutinized most intently for release 5.1. The others
39# have been checked for somewhat more than just sanity. It can handle all
40# existing Unicode character properties in those releases.
41#
42# This program needs to be able to run under miniperl. Therefore, it uses a
43# minimum of other modules, and hence implements some things itself that could
44# be gotten from CPAN
45#
46# This program uses inputs published by the Unicode Consortium. These can
47# change incompatibly between releases without the Perl maintainers realizing
48# it. Therefore this program is now designed to try to flag these. It looks
49# at the directories where the inputs are, and flags any unrecognized files.
50# It keeps track of all the properties in the files it handles, and flags any
51# that it doesn't know how to handle. It also flags any input lines that
52# don't match the expected syntax, among other checks.
53# It is also designed so if a new input file matches one of the known
54# templates, one hopefully just needs to add it to a list to have it
55# processed.
56#
57# It tries to keep fatal errors to a minimum, to generate something usable for
58# testing purposes. It always looks for files that could be inputs, and will
59# warn about any that it doesn't know how to handle (the -q option suppresses
60# the warning).
61#
62# This program is mostly about Unicode character (or code point) properties.
63# A property describes some attribute or quality of a code point, like if it
64# is lowercase or not, its name, what version of Unicode it was first defined
65# in, or what its uppercase equivalent is. Unicode deals with these disparate
66# possibilities by making all properties into mappings from each code point
67# into some corresponding value. In the case of it being lowercase or not,
68# the mapping is either to 'Y' or 'N' (or various synonyms thereof). Each
69# property maps each Unicode code point to a single value, called a "property
70# value". (Hence each Unicode property is a true mathematical function with
71# exactly one value per code point.)
72#
73# When using a property in a regular expression, what is desired isn't the
74# mapping of the code point to its property's value, but the reverse (or the
75# mathematical "inverse relation"): starting with the property value, "Does a
76# code point map to it?" These are written in a "compound" form:
77# \p{property=value}, e.g., \p{category=punctuation}. This program generates
78# files containing the lists of code points that map to each such regular
79# expression property value, one file per list
80#
81# There is also a single form shortcut that Perl adds for many of the commonly
82# used properties. This happens for all binary properties, plus script,
83# general_category, and block properties.
84#
85# Thus the outputs of this program are files. There are map files, mostly in
86# the 'To' directory; and there are list files for use in regular expression
87# matching, all in subdirectories of the 'lib' directory, with each
88# subdirectory being named for the property that the lists in it are for.
89# Bookkeeping, test, and documentation files are also generated.
90
91my $matches_directory = 'lib'; # Where match (\p{}) files go.
92my $map_directory = 'To'; # Where map files go.
93
94# DATA STRUCTURES
95#
96# The major data structures of this program are Property, of course, but also
97# Table. There are two kinds of tables, very similar to each other.
98# "Match_Table" is the data structure giving the list of code points that have
99# a particular property value, mentioned above. There is also a "Map_Table"
100# data structure which gives the property's mapping from code point to value.
101# There are two structures because the match tables need to be combined in
102# various ways, such as constructing unions, intersections, complements, etc.,
103# and the map ones don't. And there would be problems, perhaps subtle, if
104# a map table were inadvertently operated on in some of those ways.
105# The use of separate classes with operations defined on one but not the other
106# prevents accidentally confusing the two.
107#
108# At the heart of each table's data structure is a "Range_List", which is just
109# an ordered list of "Ranges", plus ancillary information, and methods to
110# operate on them. A Range is a compact way to store property information.
111# Each range has a starting code point, an ending code point, and a value that
112# is meant to apply to all the code points between the two end points,
113# inclusive. For a map table, this value is the property value for those
114# code points. Two such ranges could be written like this:
115# 0x41 .. 0x5A, 'Upper',
116# 0x61 .. 0x7A, 'Lower'
117#
118# Each range also has a type used as a convenience to classify the values.
119# Most ranges in this program will be Type 0, or normal, but there are some
120# ranges that have a non-zero type. These are used only in map tables, and
121# are for mappings that don't fit into the normal scheme of things. Mappings
122# that require a hash entry to communicate with utf8.c are one example;
123# another example is mappings for charnames.pm to use which indicate a name
124# that is algorithmically determinable from its code point (and vice-versa).
125# These are used to significantly compact these tables, instead of listing
126# each one of the tens of thousands individually.
127#
128# In a match table, the value of a range is irrelevant (and hence the type as
129# well, which will always be 0), and arbitrarily set to the null string.
130# Using the example above, there would be two match tables for those two
131# entries, one named Upper would contain the 0x41..0x5A range, and the other
132# named Lower would contain 0x61..0x7A.
133#
134# Actually, there are two types of range lists, "Range_Map" is the one
135# associated with map tables, and "Range_List" with match tables.
136# Again, this is so that methods can be defined on one and not the other so as
137# to prevent operating on them in incorrect ways.
138#
139# Eventually, most tables are written out to files to be read by utf8_heavy.pl
140# in the perl core. All tables could in theory be written, but some are
141# suppressed because there is no current practical use for them. It is easy
142# to change which get written by changing various lists that are near the top
143# of the actual code in this file. The table data structures contain enough
144# ancillary information to allow them to be treated as separate entities for
145# writing, such as the path to each one's file. There is a heading in each
146# map table that gives the format of its entries, and what the map is for all
147# the code points missing from it. (This allows tables to be more compact.)
148
149# The Property data structure contains one or more tables. All properties
150# contain a map table (except the $perl property which is a
151# pseudo-property containing only match tables), and any properties that
152# are usable in regular expression matches also contain various matching
153# tables, one for each value the property can have. A binary property can
154# have two values, True and False (or Y and N, which are preferred by Unicode
155# terminology). Thus each of these properties will have a map table that
156# takes every code point and maps it to Y or N (but having ranges cuts the
157# number of entries in that table way down), and two match tables, one
158# which has a list of all the code points that map to Y, and one for all the
159# code points that map to N. (For each of these, a third table is also
160# generated for the pseudo Perl property. It contains the identical code
161# points as the Y table, but can be written, not in the compound form, but in
162# a "single" form like \p{IsUppercase}.) Many properties are binary, but some
163# properties have several possible values, some have many, and properties like
164# Name have a different value for every named code point. Those will not,
165# unless the controlling lists are changed, have their match tables written
166# out. But all the ones which can be used in regular expression \p{} and \P{}
167# constructs will. Generally a property will have either its map table or its
168# match tables written but not both. Again, what gets written is controlled
169# by lists which can easily be changed.
170
171# For information about the Unicode properties, see Unicode's UAX44 document:
172
173my $unicode_reference_url = 'http://www.unicode.org/reports/tr44/';
174
175# As stated earlier, this program will work on any release of Unicode so far.
176# Most obvious problems in earlier data have NOT been corrected except when
177# necessary to make Perl or this program work reasonably. For example, no
178# folding information was given in early releases, so this program uses the
179# substitute of lower case, just so that a regular expression with the /i
180# option will do something that actually gives the right results in many
181# cases. There are also a couple other corrections for version 1.1.5,
182# commented at the point they are made. As an example of corrections that
183# weren't made (but could be) is this statement from DerivedAge.txt: "The
184# supplementary private use code points and the non-character code points were
185# assigned in version 2.0, but not specifically listed in the UCD until
186# versions 3.0 and 3.1 respectively." (To be precise it was 3.0.1 not 3.0.0)
187# More information on Unicode version glitches is further down in these
188# introductory comments.
189#
190# This program works on all properties as of 5.2, though the files for some
191# are suppressed from apparent lack of demand for. You can change which are
192# output by changing lists in this program.
193
194# The old version of mktables emphasized the term "Fuzzy" to mean Unocde's
195# loose matchings rules (from Unicode TR18):
196#
197# The recommended names for UCD properties and property values are in
198# PropertyAliases.txt [Prop] and PropertyValueAliases.txt
199# [PropValue]. There are both abbreviated names and longer, more
200# descriptive names. It is strongly recommended that both names be
201# recognized, and that loose matching of property names be used,
202# whereby the case distinctions, whitespace, hyphens, and underbar
203# are ignored.
204# The program still allows Fuzzy to override its determination of if loose
205# matching should be used, but it isn't currently used, as it is no longer
206# needed; the calculations it makes are good enough.
207
208# SUMMARY OF HOW IT WORKS:
209#
210# Process arguments
211#
212# A list is constructed containing each input file that is to be processed
213#
214# Each file on the list is processed in a loop, using the associated handler
215# code for each:
216# The PropertyAliases.txt and PropValueAliases.txt files are processed
217# first. These files name the properties and property values.
218# Objects are created of all the property and property value names
219# that the rest of the input should expect, including all synonyms.
220# The other input files give mappings from properties to property
221# values. That is, they list code points and say what the mapping
222# is under the given property. Some files give the mappings for
223# just one property; and some for many. This program goes through
224# each file and populates the properties from them. Some properties
225# are listed in more than one file, and Unicode has set up a
226# precedence as to which has priority if there is a conflict. Thus
227# the order of processing matters, and this program handles the
228# conflict possibility by processing the overriding input files
229# last, so that if necessary they replace earlier values.
230# After this is all done, the program creates the property mappings not
231# furnished by Unicode, but derivable from what it does give.
232# The tables of code points that match each property value in each
233# property that is accessible by regular expressions are created.
234# The Perl-defined properties are created and populated. Many of these
235# require data determined from the earlier steps
236# Any Perl-defined synonyms are created, and name clashes between Perl
237# and Unicode are reconciled.
238# All the properties are written to files
239# Any other files are written, and final warnings issued.
240
241# As mentioned above, some properties are given in more than one file. In
242# particular, the files in the extracted directory are supposedly just
243# reformattings of the others. But they contain information not easily
244# derivable from the other files, including results for Unihan, which this
245# program doesn't ordinarily look at, and for unassigned code points. They
246# also have historically had errors or been incomplete. In an attempt to
247# create the best possible data, this program thus processes them first to
248# glean information missing from the other files; then processes those other
249# files to override any errors in the extracted ones.
250
251# For clarity, a number of operators have been overloaded to work on tables:
252# ~ means invert (take all characters not in the set). The more
253# conventional '!' is not used because of the possibility of confusing
254# it with the actual boolean operation.
255# + means union
256# - means subtraction
257# & means intersection
258# The precedence of these is the order listed. Parentheses should be
259# copiously used. These are not a general scheme. The operations aren't
260# defined for a number of things, deliberately, to avoid getting into trouble.
261# Operations are done on references and affect the underlying structures, so
262# that the copy constructors for them have been overloaded to not return a new
263# clone, but the input object itself.
264
265# The bool operator is deliberately not overloaded to avoid confusion with
266# "should it mean if the object merely exists, or also is non-empty?".
267
268#
269# WHY CERTAIN DESIGN DECISIONS WERE MADE
270
271# XXX These comments need more work.
272#
273# Why have files written out for binary 'N' matches?
274# For binary properties, if you know the mapping for either Y or N; the
275# other is trivial to construct, so could be done at Perl run-time instead
276# of having a file for it. That is, if someone types in \p{foo: N}, Perl
277# could translate that to \P{foo: Y} and not need a file. The problem is
278# communicating to Perl that a given property is binary. Perl can't figure
279# it out from looking at the N (or No), as some non-binary properties have
280# these as property values.
281# Why
282# There are several types of properties, based on what form their values can
283# take on. These are described in more detail below in the DATA STRUCTURES
284# section of these comments, but for now, you should know that there are
285# string properties, whose values are strings of one or more code points (such
286# as the Uppercase_mapping property); every other property maps to some other
287# form, like true or false, or a number, or a name, etc. The reason there are
288# two directories for map files is because of the way utf8.c works. It
289# expects that any files there are string properties, that is that the
290# mappings are each to one code point, with mappings in multiple code points
291# handled specially in an extra hash data structure. Digit.pl is a table that
292# is written there for historical reasons, even though it doesn't fit that
293# mold. Thus it can't currently be looked at by the Perl core.
294#
295# There are no match tables generated for matches of the null string. These
296# would like like \p{JSN=}. Perhaps something like them could be added if
297# necessary. The JSN does have a real code point U+110B that maps to the null
298# string, but it is a contributory property, and therefore not output by
299# default.
300#
23e33b60
KW
301# DEBUGGING
302#
303# XXX Add more stuff here. use perl instead of miniperl to find problems with
304# Scalar::Util
305
99870f4d
KW
306# FUTURE ISSUES
307#
308# The program would break if Unicode were to change its names so that
309# interior white space, underscores, or dashes differences were significant
310# within property and property value names.
311#
312# It might be easier to use the xml versions of the UCD if this program ever
313# would need heavy revision, and the ability to handle old versions was not
314# required.
315#
316# There is the potential for name collisions, in that Perl has chosen names
317# that Unicode could decide it also likes. There have been such collisions in
318# the past, with mostly Perl deciding to adopt the Unicode definition of the
319# name. However in the 5.2 Unicode beta testing, there were a number of such
320# collisions, which were withdrawn before the final release, because of Perl's
321# and other's protests. These all involved new properties which began with
322# 'Is'. Based on the protests, Unicode is unlikely to try that again. Also,
323# many of the Perl-defined synonyms, like Any, Word, etc, are listed in a
324# Unicode document, so they are unlikely to be used by Unicode for another
325# purpose. However, they might try something beginning with 'In', or use any
326# of the other Perl-defined properties. This program will warn you of name
327# collisions, and refuse to generate tables with them, but manual intervention
328# will be required in this event. One scheme that could be implemented, if
329# necessary, would be to have this program generate another file, or add a
330# field to mktables.lst that gives the date of first definition of a property.
331# Each new release of Unicode would use that file as a basis for the next
332# iteration. And the Perl synonym addition code could sort based on the age
333# of the property, so older properties get priority, and newer ones that clash
334# would be refused; hence existing code would not be impacted, and some other
335# synonym would have to be used for the new property. This is ugly, and
336# manual intervention would certainly be easier to do in the short run; lets
337# hope it never comes to this.
338
339# A NOTE ON UNIHAN
340#
341# This program can generate tables from the Unihan database. But it doesn't
342# by default, letting the CPAN module Unicode::Unihan handle them. Prior to
343# version 5.2, this database was in a single file, Unihan.txt. In 5.2 the
344# database was split into 8 different files, all beginning with the letters
345# 'Unihan'. This program will read those file(s) if present, but it needs to
346# know which of the many properties in the file(s) should have tables created
347# for them. It will create tables for any properties listed in
348# PropertyAliases.txt and PropValueAliases.txt, plus any listed in the
349# @cjk_properties array and the @cjk_property_values array. Thus, if a
350# property you want is not in those files of the release you are building
351# against, you must add it to those two arrays. Starting in 4.0, the
352# Unicode_Radical_Stroke was listed in those files, so if the Unihan database
353# is present in the directory, a table will be generated for that property.
354# In 5.2, several more properties were added. For your convenience, the two
355# arrays are initialized with all the 5.2 listed properties that are also in
356# earlier releases. But these are commented out. You can just uncomment the
357# ones you want, or use them as a template for adding entries for other
358# properties.
359#
360# You may need to adjust the entries to suit your purposes. setup_unihan(),
361# and filter_unihan_line() are the functions where this is done. This program
362# already does some adjusting to make the lines look more like the rest of the
363# Unicode DB; You can see what that is in filter_unihan_line()
364#
365# There is a bug in the 3.2 data file in which some values for the
366# kPrimaryNumeric property have commas and an unexpected comment. A filter
367# could be added for these; or for a particular installation, the Unihan.txt
368# file could be edited to fix them.
369# have to be
370#
371# HOW TO ADD A FILE
372
373# Unicode Versions Notes
374
375# alpha's numbers halve in 2.1.9, answer cjk block at 4E00 were removed from PropList; not changed, could add gc Letter, put back in in 3.1.0
376# Some versions of 2.1.x Jamo.txt have the wrong value for 1105, which causes
377# real problems for the algorithms for Jamo calculations, so it is changed
378# here.
379# White space vs Space. in 3.2 perl has +205F=medium math space, fixed in 4.0, and ok in 3.1.1 because not there in unicode. synonym introduced in 4.1
380# ATBL = 202. 202 changed to ATB, and all code points stayed there. So if you were useing ATBL you were out of luck.
381# Hrkt Katakana_Or_Hiragana came in 4.01, before was Unknown.
382#
383# The default for missing code points for BidiClass is complicated. Starting
384# in 3.1.1, the derived file DBidiClass.txt handles this, but this program
385# tries to do the best it can for earlier releases. It is done in
386# process_PropertyAliases()
387#
388##############################################################################
389
390my $UNDEF = ':UNDEF:'; # String to print out for undefined values in tracing
391 # and errors
392my $MAX_LINE_WIDTH = 78;
393
394# Debugging aid to skip most files so as to not be distracted by them when
395# concentrating on the ones being debugged. Add
396# non_skip => 1,
397# to the constructor for those files you want processed when you set this.
398# Files with a first version number of 0 are special: they are always
399# processed regardless of the state of this flag.
400my $debug_skip = 0;
401
402# Set to 1 to enable tracing.
403our $to_trace = 0;
404
405{ # Closure for trace: debugging aid
406 my $print_caller = 1; # ? Include calling subroutine name
407 my $main_with_colon = 'main::';
408 my $main_colon_length = length($main_with_colon);
409
410 sub trace {
411 return unless $to_trace; # Do nothing if global flag not set
412
413 my @input = @_;
414
415 local $DB::trace = 0;
416 $DB::trace = 0; # Quiet 'used only once' message
417
418 my $line_number;
419
420 # Loop looking up the stack to get the first non-trace caller
421 my $caller_line;
422 my $caller_name;
423 my $i = 0;
424 do {
425 $line_number = $caller_line;
426 (my $pkg, my $file, $caller_line, my $caller) = caller $i++;
427 $caller = $main_with_colon unless defined $caller;
428
429 $caller_name = $caller;
430
431 # get rid of pkg
432 $caller_name =~ s/.*:://;
433 if (substr($caller_name, 0, $main_colon_length)
434 eq $main_with_colon)
435 {
436 $caller_name = substr($caller_name, $main_colon_length);
437 }
438
439 } until ($caller_name ne 'trace');
440
441 # If the stack was empty, we were called from the top level
442 $caller_name = 'main' if ($caller_name eq ""
443 || $caller_name eq 'trace');
444
445 my $output = "";
446 foreach my $string (@input) {
447 #print STDERR __LINE__, ": ", join ", ", @input, "\n";
448 if (ref $string eq 'ARRAY' || ref $string eq 'HASH') {
449 $output .= simple_dumper($string);
450 }
451 else {
452 $string = "$string" if ref $string;
453 $string = $UNDEF unless defined $string;
454 chomp $string;
455 $string = '""' if $string eq "";
456 $output .= " " if $output ne ""
457 && $string ne ""
458 && substr($output, -1, 1) ne " "
459 && substr($string, 0, 1) ne " ";
460 $output .= $string;
461 }
462 }
463
99f78760
KW
464 print STDERR sprintf "%4d: ", $line_number if defined $line_number;
465 print STDERR "$caller_name: " if $print_caller;
99870f4d
KW
466 print STDERR $output, "\n";
467 return;
468 }
469}
470
471# This is for a rarely used development feature that allows you to compare two
472# versions of the Unicode standard without having to deal with changes caused
473# by the code points introduced in the later verson. Change the 0 to a SINGLE
474# dotted Unicode release number (e.g. 2.1). Only code points introduced in
475# that release and earlier will be used; later ones are thrown away. You use
476# the version number of the earliest one you want to compare; then run this
477# program on directory structures containing each release, and compare the
478# outputs. These outputs will therefore include only the code points common
479# to both releases, and you can see the changes caused just by the underlying
480# release semantic changes. For versions earlier than 3.2, you must copy a
481# version of DAge.txt into the directory.
482my $string_compare_versions = DEBUG && 0; # e.g., v2.1;
483my $compare_versions = DEBUG
484 && $string_compare_versions
485 && pack "C*", split /\./, $string_compare_versions;
486
487sub uniques {
488 # Returns non-duplicated input values. From "Perl Best Practices:
489 # Encapsulated Cleverness". p. 455 in first edition.
490
491 my %seen;
492 return grep { ! $seen{$_}++ } @_;
493}
494
495$0 = File::Spec->canonpath($0);
496
497my $make_test_script = 0; # ? Should we output a test script
498my $write_unchanged_files = 0; # ? Should we update the output files even if
499 # we don't think they have changed
500my $use_directory = ""; # ? Should we chdir somewhere.
501my $pod_directory; # input directory to store the pod file.
502my $pod_file = 'perluniprops';
503my $t_path; # Path to the .t test file
504my $file_list = 'mktables.lst'; # File to store input and output file names.
505 # This is used to speed up the build, by not
506 # executing the main body of the program if
507 # nothing on the list has changed since the
508 # previous build
509my $make_list = 1; # ? Should we write $file_list. Set to always
510 # make a list so that when the pumpking is
511 # preparing a release, s/he won't have to do
512 # special things
513my $glob_list = 0; # ? Should we try to include unknown .txt files
514 # in the input.
515my $output_range_counts = 1; # ? Should we include the number of code points
516 # in ranges in the output
517# Verbosity levels; 0 is quiet
518my $NORMAL_VERBOSITY = 1;
519my $PROGRESS = 2;
520my $VERBOSE = 3;
521
522my $verbosity = $NORMAL_VERBOSITY;
523
524# Process arguments
525while (@ARGV) {
cf25bb62
JH
526 my $arg = shift @ARGV;
527 if ($arg eq '-v') {
99870f4d
KW
528 $verbosity = $VERBOSE;
529 }
530 elsif ($arg eq '-p') {
531 $verbosity = $PROGRESS;
532 $| = 1; # Flush buffers as we go.
533 }
534 elsif ($arg eq '-q') {
535 $verbosity = 0;
536 }
537 elsif ($arg eq '-w') {
538 $write_unchanged_files = 1; # update the files even if havent changed
539 }
540 elsif ($arg eq '-check') {
6ae7e459
YO
541 my $this = shift @ARGV;
542 my $ok = shift @ARGV;
543 if ($this ne $ok) {
544 print "Skipping as check params are not the same.\n";
545 exit(0);
546 }
00a8df5c 547 }
99870f4d
KW
548 elsif ($arg eq '-P' && defined ($pod_directory = shift)) {
549 -d $pod_directory or croak "Directory '$pod_directory' doesn't exist";
550 }
3df51b85
KW
551 elsif ($arg eq '-maketest' || ($arg eq '-T' && defined ($t_path = shift)))
552 {
99870f4d 553 $make_test_script = 1;
99870f4d
KW
554 }
555 elsif ($arg eq '-makelist') {
556 $make_list = 1;
557 }
558 elsif ($arg eq '-C' && defined ($use_directory = shift)) {
559 -d $use_directory or croak "Unknown directory '$use_directory'";
560 }
561 elsif ($arg eq '-L') {
562
563 # Existence not tested until have chdir'd
564 $file_list = shift;
565 }
566 elsif ($arg eq '-globlist') {
567 $glob_list = 1;
568 }
569 elsif ($arg eq '-c') {
570 $output_range_counts = ! $output_range_counts
571 }
572 else {
573 my $with_c = 'with';
574 $with_c .= 'out' if $output_range_counts; # Complements the state
575 croak <<END;
576usage: $0 [-c|-p|-q|-v|-w] [-C dir] [-L filelist] [ -P pod_dir ]
577 [ -T test_file_path ] [-globlist] [-makelist] [-maketest]
578 [-check A B ]
579 -c : Output comments $with_c number of code points in ranges
580 -q : Quiet Mode: Only output serious warnings.
581 -p : Set verbosity level to normal plus show progress.
582 -v : Set Verbosity level high: Show progress and non-serious
583 warnings
584 -w : Write files regardless
585 -C dir : Change to this directory before proceeding. All relative paths
586 except those specified by the -P and -T options will be done
587 with respect to this directory.
588 -P dir : Output $pod_file file to directory 'dir'.
3df51b85 589 -T path : Create a test script as 'path'; overrides -maketest
99870f4d
KW
590 -L filelist : Use alternate 'filelist' instead of standard one
591 -globlist : Take as input all non-Test *.txt files in current and sub
592 directories
3df51b85
KW
593 -maketest : Make test script 'TestProp.pl' in current (or -C directory),
594 overrides -T
99870f4d
KW
595 -makelist : Rewrite the file list $file_list based on current setup
596 -check A B : Executes $0 only if A and B are the same
597END
598 }
599}
600
601# Stores the most-recently changed file. If none have changed, can skip the
602# build
603my $youngest = -M $0; # Do this before the chdir!
604
605# Change directories now, because need to read 'version' early.
606if ($use_directory) {
3df51b85 607 if ($pod_directory && ! File::Spec->file_name_is_absolute($pod_directory)) {
99870f4d
KW
608 $pod_directory = File::Spec->rel2abs($pod_directory);
609 }
3df51b85 610 if ($t_path && ! File::Spec->file_name_is_absolute($t_path)) {
99870f4d 611 $t_path = File::Spec->rel2abs($t_path);
00a8df5c 612 }
99870f4d 613 chdir $use_directory or croak "Failed to chdir to '$use_directory':$!";
3df51b85 614 if ($pod_directory && File::Spec->file_name_is_absolute($pod_directory)) {
99870f4d 615 $pod_directory = File::Spec->abs2rel($pod_directory);
02b1aeec 616 }
3df51b85 617 if ($t_path && File::Spec->file_name_is_absolute($t_path)) {
99870f4d 618 $t_path = File::Spec->abs2rel($t_path);
02b1aeec 619 }
00a8df5c
YO
620}
621
99870f4d
KW
622# Get Unicode version into regular and v-string. This is done now because
623# various tables below get populated based on it. These tables are populated
624# here to be near the top of the file, and so easily seeable by those needing
625# to modify things.
626open my $VERSION, "<", "version"
627 or croak "$0: can't open required file 'version': $!\n";
628my $string_version = <$VERSION>;
629close $VERSION;
630chomp $string_version;
631my $v_version = pack "C*", split /\./, $string_version; # v string
632
633# The following are the complete names of properties with property values that
634# are known to not match any code points in some versions of Unicode, but that
635# may change in the future so they should be matchable, hence an empty file is
636# generated for them.
637my @tables_that_may_be_empty = (
638 'Joining_Type=Left_Joining',
639 );
640push @tables_that_may_be_empty, 'Script=Common' if $v_version le v4.0.1;
641push @tables_that_may_be_empty, 'Title' if $v_version lt v2.0.0;
642push @tables_that_may_be_empty, 'Script=Katakana_Or_Hiragana'
643 if $v_version ge v4.1.0;
644
645# The lists below are hashes, so the key is the item in the list, and the
646# value is the reason why it is in the list. This makes generation of
647# documentation easier.
648
649my %why_suppressed; # No file generated for these.
650
651# Files aren't generated for empty extraneous properties. This is arguable.
652# Extraneous properties generally come about because a property is no longer
653# used in a newer version of Unicode. If we generated a file without code
654# points, programs that used to work on that property will still execute
655# without errors. It just won't ever match (or will always match, with \P{}).
656# This means that the logic is now likely wrong. I (khw) think its better to
657# find this out by getting an error message. Just move them to the table
658# above to change this behavior
659my %why_suppress_if_empty_warn_if_not = (
660
661 # It is the only property that has ever officially been removed from the
662 # Standard. The database never contained any code points for it.
663 'Special_Case_Condition' => 'Obsolete',
664
665 # Apparently never official, but there were code points in some versions of
666 # old-style PropList.txt
667 'Non_Break' => 'Obsolete',
668);
669
670# These would normally go in the warn table just above, but they were changed
671# a long time before this program was written, so warnings about them are
672# moot.
673if ($v_version gt v3.2.0) {
674 push @tables_that_may_be_empty,
675 'Canonical_Combining_Class=Attached_Below_Left'
676}
677
678# These are listed in the Property aliases file in 5.2, but Unihan is ignored
679# unless explicitly added.
680if ($v_version ge v5.2.0) {
681 my $unihan = 'Unihan; remove from list if using Unihan';
23e33b60 682 foreach my $table qw (
99870f4d
KW
683 kAccountingNumeric
684 kOtherNumeric
685 kPrimaryNumeric
686 kCompatibilityVariant
687 kIICore
688 kIRG_GSource
689 kIRG_HSource
690 kIRG_JSource
691 kIRG_KPSource
692 kIRG_MSource
693 kIRG_KSource
694 kIRG_TSource
695 kIRG_USource
696 kIRG_VSource
697 kRSUnicode
698 )
699 {
700 $why_suppress_if_empty_warn_if_not{$table} = $unihan;
701 }
ca12659b
NC
702}
703
99870f4d
KW
704# Properties that this program ignores.
705my @unimplemented_properties = (
706'Unicode_Radical_Stroke' # Remove if changing to handle this one.
707);
d73e5302 708
99870f4d
KW
709# There are several types of obsolete properties defined by Unicode. These
710# must be hand-edited for every new Unicode release.
711my %why_deprecated; # Generates a deprecated warning message if used.
712my %why_stabilized; # Documentation only
713my %why_obsolete; # Documentation only
714
715{ # Closure
716 my $simple = 'Perl uses the more complete version of this property';
717 my $unihan = 'Unihan properties are by default not enabled in the Perl core. Instead use CPAN: Unicode::Unihan';
718
719 my $other_properties = 'other properties';
720 my $contributory = "Used by Unicode internally for generating $other_properties and not intended to be used stand-alone";
721 my $why_no_expand = "Easily computed, and yet doesn't cover the common encoding forms (UTF-16/8)",
722
723 %why_deprecated = (
724 'Grapheme_Link' => 'Deprecated by Unicode. Use ccc=vr (Canonical_Combining_Class=Virama) instead',
725 'Jamo_Short_Name' => $contributory,
726 'Line_Break=Surrogate' => 'Deprecated by Unicode because surrogates should never appear in well-formed text, and therefore shouldn\'t be the basis for line breaking',
727 'Other_Alphabetic' => $contributory,
728 'Other_Default_Ignorable_Code_Point' => $contributory,
729 'Other_Grapheme_Extend' => $contributory,
730 'Other_ID_Continue' => $contributory,
731 'Other_ID_Start' => $contributory,
732 'Other_Lowercase' => $contributory,
733 'Other_Math' => $contributory,
734 'Other_Uppercase' => $contributory,
735 );
736
737 %why_suppressed = (
738 # There is a lib/unicore/Decomposition.pl (used by normalize.pm) which
739 # contains the same information, but without the algorithmically
740 # determinable Hangul syllables'. This file is not published, so it's
741 # existence is not noted in the comment.
742 'Decomposition_Mapping' => 'Accessible via Unicode::Normalize',
743
744 'ISO_Comment' => 'Apparently no demand for it, but can access it through Unicode::UCD::charinfo. Obsoleted, and code points for it removed in Unicode 5.2',
745 'Unicode_1_Name' => "$simple, and no apparent demand for it, but can access it through Unicode::UCD::charinfo. If there is no later name for a code point, then this one is used instead in charnames",
746
747 'Simple_Case_Folding' => "$simple. Can access this through Unicode::UCD::casefold",
748 'Simple_Lowercase_Mapping' => "$simple. Can access this through Unicode::UCD::charinfo",
749 'Simple_Titlecase_Mapping' => "$simple. Can access this through Unicode::UCD::charinfo",
750 'Simple_Uppercase_Mapping' => "$simple. Can access this through Unicode::UCD::charinfo",
751
752 'Name' => "Accessible via 'use charnames;'",
753 'Name_Alias' => "Accessible via 'use charnames;'",
754
755 # These are sort of jumping the gun; deprecation is proposed for
756 # Unicode version 6.0, but they have never been exposed by Perl, and
757 # likely are soon to be deprecated, so best not to expose them.
758 FC_NFKC_Closure => 'Use NFKC_Casefold instead',
759 Expands_On_NFC => $why_no_expand,
760 Expands_On_NFD => $why_no_expand,
761 Expands_On_NFKC => $why_no_expand,
762 Expands_On_NFKD => $why_no_expand,
763 );
764
765 # The following are suppressed because they were made contributory or
766 # deprecated by Unicode before Perl ever thought about supporting them.
767 foreach my $property ('Jamo_Short_Name', 'Grapheme_Link') {
768 $why_suppressed{$property} = $why_deprecated{$property};
769 }
cf25bb62 770
99870f4d
KW
771 # Customize the message for all the 'Other_' properties
772 foreach my $property (keys %why_deprecated) {
773 next if (my $main_property = $property) !~ s/^Other_//;
774 $why_deprecated{$property} =~ s/$other_properties/the $main_property property (which should be used instead)/;
775 }
776}
777
778if ($v_version ge 4.0.0) {
779 $why_stabilized{'Hyphen'} = 'Use the Line_Break property instead; see www.unicode.org/reports/tr14';
780}
781if ($v_version ge 5.2.0) {
782 $why_obsolete{'ISO_Comment'} = 'Code points for it have been removed';
783}
784
785# Probably obsolete forever
786if ($v_version ge v4.1.0) {
787 $why_suppressed{'Script=Katakana_Or_Hiragana'} = 'Obsolete. All code points previously matched by this have been moved to "Script=Common"';
788}
789
790# This program can create files for enumerated-like properties, such as
791# 'Numeric_Type'. This file would be the same format as for a string
792# property, with a mapping from code point to its value, so you could look up,
793# for example, the script a code point is in. But no one so far wants this
794# mapping, or they have found another way to get it since this is a new
795# feature. So no file is generated except if it is in this list.
796my @output_mapped_properties = split "\n", <<END;
797END
798
799# If you are using the Unihan database, you need to add the properties that
800# you want to extract from it to this table. For your convenience, the
801# properties in the 5.2 PropertyAliases.txt file are listed, commented out
802my @cjk_properties = split "\n", <<'END';
803#cjkAccountingNumeric; kAccountingNumeric
804#cjkOtherNumeric; kOtherNumeric
805#cjkPrimaryNumeric; kPrimaryNumeric
806#cjkCompatibilityVariant; kCompatibilityVariant
807#cjkIICore ; kIICore
808#cjkIRG_GSource; kIRG_GSource
809#cjkIRG_HSource; kIRG_HSource
810#cjkIRG_JSource; kIRG_JSource
811#cjkIRG_KPSource; kIRG_KPSource
812#cjkIRG_KSource; kIRG_KSource
813#cjkIRG_TSource; kIRG_TSource
814#cjkIRG_USource; kIRG_USource
815#cjkIRG_VSource; kIRG_VSource
816#cjkRSUnicode; kRSUnicode ; Unicode_Radical_Stroke; URS
817END
818
819# Similarly for the property values. For your convenience, the lines in the
820# 5.2 PropertyAliases.txt file are listed. Just remove the first BUT NOT both
821# '#' marks
822my @cjk_property_values = split "\n", <<'END';
823## @missing: 0000..10FFFF; cjkAccountingNumeric; NaN
824## @missing: 0000..10FFFF; cjkCompatibilityVariant; <code point>
825## @missing: 0000..10FFFF; cjkIICore; <none>
826## @missing: 0000..10FFFF; cjkIRG_GSource; <none>
827## @missing: 0000..10FFFF; cjkIRG_HSource; <none>
828## @missing: 0000..10FFFF; cjkIRG_JSource; <none>
829## @missing: 0000..10FFFF; cjkIRG_KPSource; <none>
830## @missing: 0000..10FFFF; cjkIRG_KSource; <none>
831## @missing: 0000..10FFFF; cjkIRG_TSource; <none>
832## @missing: 0000..10FFFF; cjkIRG_USource; <none>
833## @missing: 0000..10FFFF; cjkIRG_VSource; <none>
834## @missing: 0000..10FFFF; cjkOtherNumeric; NaN
835## @missing: 0000..10FFFF; cjkPrimaryNumeric; NaN
836## @missing: 0000..10FFFF; cjkRSUnicode; <none>
837END
838
839# The input files don't list every code point. Those not listed are to be
840# defaulted to some value. Below are hard-coded what those values are for
841# non-binary properties as of 5.1. Starting in 5.0, there are
842# machine-parsable comment lines in the files the give the defaults; so this
843# list shouldn't have to be extended. The claim is that all missing entries
844# for binary properties will default to 'N'. Unicode tried to change that in
845# 5.2, but the beta period produced enough protest that they backed off.
846#
847# The defaults for the fields that appear in UnicodeData.txt in this hash must
848# be in the form that it expects. The others may be synonyms.
849my $CODE_POINT = '<code point>';
850my %default_mapping = (
851 Age => "Unassigned",
852 # Bidi_Class => Complicated; set in code
853 Bidi_Mirroring_Glyph => "",
854 Block => 'No_Block',
855 Canonical_Combining_Class => 0,
856 Case_Folding => $CODE_POINT,
857 Decomposition_Mapping => $CODE_POINT,
858 Decomposition_Type => 'None',
859 East_Asian_Width => "Neutral",
860 FC_NFKC_Closure => $CODE_POINT,
861 General_Category => 'Cn',
862 Grapheme_Cluster_Break => 'Other',
863 Hangul_Syllable_Type => 'NA',
864 ISO_Comment => "",
865 Jamo_Short_Name => "",
866 Joining_Group => "No_Joining_Group",
867 # Joining_Type => Complicated; set in code
868 kIICore => 'N', # Is converted to binary
869 #Line_Break => Complicated; set in code
870 Lowercase_Mapping => $CODE_POINT,
871 Name => "",
872 Name_Alias => "",
873 NFC_QC => 'Yes',
874 NFD_QC => 'Yes',
875 NFKC_QC => 'Yes',
876 NFKD_QC => 'Yes',
877 Numeric_Type => 'None',
878 Numeric_Value => 'NaN',
879 Script => ($v_version le 4.1.0) ? 'Common' : 'Unknown',
880 Sentence_Break => 'Other',
881 Simple_Case_Folding => $CODE_POINT,
882 Simple_Lowercase_Mapping => $CODE_POINT,
883 Simple_Titlecase_Mapping => $CODE_POINT,
884 Simple_Uppercase_Mapping => $CODE_POINT,
885 Titlecase_Mapping => $CODE_POINT,
886 Unicode_1_Name => "",
887 Unicode_Radical_Stroke => "",
888 Uppercase_Mapping => $CODE_POINT,
889 Word_Break => 'Other',
890);
891
892# Below are files that Unicode furnishes, but this program ignores, and why
893my %ignored_files = (
894 'CJKRadicals.txt' => 'Unihan data',
895 'Index.txt' => 'An index, not actual data',
896 'NamedSqProv.txt' => 'Not officially part of the Unicode standard; Append it to NamedSequences.txt if you want to process the contents.',
897 'NamesList.txt' => 'Just adds commentary',
898 'NormalizationCorrections.txt' => 'Data is already in other files.',
899 'Props.txt' => 'Adds nothing to PropList.txt; only in very early releases',
900 'ReadMe.txt' => 'Just comments',
901 'README.TXT' => 'Just comments',
902 'StandardizedVariants.txt' => 'Only for glyph changes, not a Unicode character property. Does not fit into current scheme where one code point is mapped',
903);
904
905################ End of externally interesting definitions ###############
906
907my $HEADER=<<"EOF";
908# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
3df51b85
KW
909# This file is machine-generated by $0 from the Unicode
910# database, Version $string_version. Any changes made here will be lost!
cf25bb62
JH
911EOF
912
b6922eda 913my $INTERNAL_ONLY=<<"EOF";
99870f4d
KW
914
915# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
b6922eda 916# This file is for internal use by the Perl program only. The format and even
99870f4d
KW
917# the name or existence of this file are subject to change without notice.
918# Don't use it directly.
919EOF
920
921my $DEVELOPMENT_ONLY=<<"EOF";
922# !!!!!!! DEVELOPMENT USE ONLY !!!!!!!
923# This file contains information artificially constrained to code points
924# present in Unicode release $string_compare_versions.
925# IT CANNOT BE RELIED ON. It is for use during development only and should
23e33b60 926# not be used for production.
b6922eda
KW
927
928EOF
929
99870f4d
KW
930my $LAST_UNICODE_CODEPOINT_STRING = "10FFFF";
931my $LAST_UNICODE_CODEPOINT = hex $LAST_UNICODE_CODEPOINT_STRING;
932my $MAX_UNICODE_CODEPOINTS = $LAST_UNICODE_CODEPOINT + 1;
933
934# Matches legal code point. 4-6 hex numbers, If there are 6, the first
935# two must be 10; if there are 5, the first must not be a 0. Written this way
936# to decrease backtracking
937my $code_point_re =
938 qr/ \b (?: 10[0-9A-F]{4} | [1-9A-F][0-9A-F]{4} | [0-9A-F]{4} ) \b/x;
939
940# This matches the beginning of the line in the Unicode db files that give the
941# defaults for code points not listed (i.e., missing) in the file. The code
942# depends on this ending with a semi-colon, so it can assume it is a valid
943# field when the line is split() by semi-colons
944my $missing_defaults_prefix =
945 qr/^#\s+\@missing:\s+0000\.\.$LAST_UNICODE_CODEPOINT_STRING\s*;/;
946
947# Property types. Unicode has more types, but these are sufficient for our
948# purposes.
949my $UNKNOWN = -1; # initialized to illegal value
950my $NON_STRING = 1; # Either binary or enum
951my $BINARY = 2;
952my $ENUM = 3; # Include catalog
953my $STRING = 4; # Anything else: string or misc
954
955# Some input files have lines that give default values for code points not
956# contained in the file. Sometimes these should be ignored.
957my $NO_DEFAULTS = 0; # Must evaluate to false
958my $NOT_IGNORED = 1;
959my $IGNORED = 2;
960
961# Range types. Each range has a type. Most ranges are type 0, for normal,
962# and will appear in the main body of the tables in the output files, but
963# there are other types of ranges as well, listed below, that are specially
964# handled. There are pseudo-types as well that will never be stored as a
965# type, but will affect the calculation of the type.
966
967# 0 is for normal, non-specials
968my $MULTI_CP = 1; # Sequence of more than code point
969my $HANGUL_SYLLABLE = 2;
970my $CP_IN_NAME = 3; # The NAME contains the code point appended to it.
971my $NULL = 4; # The map is to the null string; utf8.c can't
972 # handle these, nor is there an accepted syntax
973 # for them in \p{} constructs
f86864ac 974my $COMPUTE_NO_MULTI_CP = 5; # Pseudo-type; means that ranges that would
99870f4d
KW
975 # otherwise be $MULTI_CP type are instead type 0
976
977# process_generic_property_file() can accept certain overrides in its input.
978# Each of these must begin AND end with $CMD_DELIM.
979my $CMD_DELIM = "\a";
980my $REPLACE_CMD = 'replace'; # Override the Replace
981my $MAP_TYPE_CMD = 'map_type'; # Override the Type
982
983my $NO = 0;
984my $YES = 1;
985
986# Values for the Replace argument to add_range.
987# $NO # Don't replace; add only the code points not
988 # already present.
989my $IF_NOT_EQUIVALENT = 1; # Replace only under certain conditions; details in
990 # the comments at the subroutine definition.
991my $UNCONDITIONALLY = 2; # Replace without conditions.
992my $MULTIPLE = 4; # Don't replace, but add a duplicate record if
993 # already there
994
995# Flags to give property statuses. The phrases are to remind maintainers that
996# if the flag is changed, the indefinite article referring to it in the
997# documentation may need to be as well.
998my $NORMAL = "";
999my $SUPPRESSED = 'z'; # The character should never actually be seen, since
1000 # it is suppressed
37e2e78e 1001my $PLACEHOLDER = 'P'; # Implies no pod entry generated
99870f4d
KW
1002my $DEPRECATED = 'D';
1003my $a_bold_deprecated = "a 'B<$DEPRECATED>'";
1004my $A_bold_deprecated = "A 'B<$DEPRECATED>'";
1005my $DISCOURAGED = 'X';
1006my $a_bold_discouraged = "an 'B<$DISCOURAGED>'";
1007my $A_bold_discouraged = "An 'B<$DISCOURAGED>'";
1008my $STRICTER = 'T';
1009my $a_bold_stricter = "a 'B<$STRICTER>'";
1010my $A_bold_stricter = "A 'B<$STRICTER>'";
1011my $STABILIZED = 'S';
1012my $a_bold_stabilized = "an 'B<$STABILIZED>'";
1013my $A_bold_stabilized = "An 'B<$STABILIZED>'";
1014my $OBSOLETE = 'O';
1015my $a_bold_obsolete = "an 'B<$OBSOLETE>'";
1016my $A_bold_obsolete = "An 'B<$OBSOLETE>'";
1017
1018my %status_past_participles = (
1019 $DISCOURAGED => 'discouraged',
1020 $SUPPRESSED => 'should never be generated',
1021 $STABILIZED => 'stabilized',
1022 $OBSOLETE => 'obsolete',
37e2e78e 1023 $DEPRECATED => 'deprecated',
99870f4d
KW
1024);
1025
1026# The format of the values of the map tables:
1027my $BINARY_FORMAT = 'b';
1028my $DECIMAL_FORMAT = 'd';
1029my $FLOAT_FORMAT = 'f';
1030my $INTEGER_FORMAT = 'i';
1031my $HEX_FORMAT = 'x';
1032my $RATIONAL_FORMAT = 'r';
1033my $STRING_FORMAT = 's';
1034
1035my %map_table_formats = (
1036 $BINARY_FORMAT => 'binary',
1037 $DECIMAL_FORMAT => 'single decimal digit',
1038 $FLOAT_FORMAT => 'floating point number',
1039 $INTEGER_FORMAT => 'integer',
1040 $HEX_FORMAT => 'positive hex whole number; a code point',
1041 $RATIONAL_FORMAT => 'rational: an integer or a fraction',
1042 $STRING_FORMAT => 'arbitrary string',
1043);
1044
1045# Unicode didn't put such derived files in a separate directory at first.
1046my $EXTRACTED_DIR = (-d 'extracted') ? 'extracted' : "";
1047my $EXTRACTED = ($EXTRACTED_DIR) ? "$EXTRACTED_DIR/" : "";
1048my $AUXILIARY = 'auxiliary';
1049
1050# Hashes that will eventually go into Heavy.pl for the use of utf8_heavy.pl
1051my %loose_to_file_of; # loosely maps table names to their respective
1052 # files
1053my %stricter_to_file_of; # same; but for stricter mapping.
1054my %nv_floating_to_rational; # maps numeric values floating point numbers to
1055 # their rational equivalent
1056my %loose_property_name_of; # Loosely maps property names to standard form
1057
1058# These constants names and values were taken from the Unicode standard,
1059# version 5.1, section 3.12. They are used in conjunction with Hangul
1060# syllables
1061my $SBase = 0xAC00;
1062my $LBase = 0x1100;
1063my $VBase = 0x1161;
1064my $TBase = 0x11A7;
1065my $SCount = 11172;
1066my $LCount = 19;
1067my $VCount = 21;
1068my $TCount = 28;
1069my $NCount = $VCount * $TCount;
1070
1071# For Hangul syllables; These store the numbers from Jamo.txt in conjunction
1072# with the above published constants.
1073my %Jamo;
1074my %Jamo_L; # Leading consonants
1075my %Jamo_V; # Vowels
1076my %Jamo_T; # Trailing consonants
1077
37e2e78e 1078my @backslash_X_tests; # List of tests read in for testing \X
99870f4d
KW
1079my @unhandled_properties; # Will contain a list of properties found in
1080 # the input that we didn't process.
f86864ac 1081my @match_properties; # Properties that have match tables, to be
99870f4d
KW
1082 # listed in the pod
1083my @map_properties; # Properties that get map files written
1084my @named_sequences; # NamedSequences.txt contents.
1085my %potential_files; # Generated list of all .txt files in the directory
1086 # structure so we can warn if something is being
1087 # ignored.
1088my @files_actually_output; # List of files we generated.
1089my @more_Names; # Some code point names are compound; this is used
1090 # to store the extra components of them.
1091my $MIN_FRACTION_LENGTH = 3; # How many digits of a floating point number at
1092 # the minimum before we consider it equivalent to a
1093 # candidate rational
1094my $MAX_FLOATING_SLOP = 10 ** - $MIN_FRACTION_LENGTH; # And in floating terms
1095
1096# These store references to certain commonly used property objects
1097my $gc;
1098my $perl;
1099my $block;
1100
1101# Are there conflicting names because of beginning with 'In_', or 'Is_'
1102my $has_In_conflicts = 0;
1103my $has_Is_conflicts = 0;
1104
1105sub internal_file_to_platform ($) {
1106 # Convert our file paths which have '/' separators to those of the
1107 # platform.
1108
1109 my $file = shift;
1110 return undef unless defined $file;
1111
1112 return File::Spec->join(split '/', $file);
d07a55ed 1113}
5beb625e 1114
99870f4d
KW
1115sub file_exists ($) { # platform independent '-e'. This program internally
1116 # uses slash as a path separator.
1117 my $file = shift;
1118 return 0 if ! defined $file;
1119 return -e internal_file_to_platform($file);
1120}
5beb625e 1121
99870f4d 1122sub objaddr($) {
23e33b60
KW
1123 # Returns the address of the blessed input object.
1124 # It doesn't check for blessedness because that would do a string eval
1125 # every call, and the program is structured so that this is never called
1126 # for a non-blessed object.
99870f4d 1127
23e33b60 1128 no overloading; # If overloaded, numifying below won't work.
99870f4d
KW
1129
1130 # Numifying a ref gives its address.
23e33b60 1131 return 0 + $_[0];
99870f4d
KW
1132}
1133
23e33b60
KW
1134# Commented code below should work on Perl 5.8.
1135## This 'require' doesn't necessarily work in miniperl, and even if it does,
1136## the native perl version of it (which is what would operate under miniperl)
1137## is extremely slow, as it does a string eval every call.
1138#my $has_fast_scalar_util = $\18 !~ /miniperl/
1139# && defined eval "require Scalar::Util";
1140#
1141#sub objaddr($) {
1142# # Returns the address of the blessed input object. Uses the XS version if
1143# # available. It doesn't check for blessedness because that would do a
1144# # string eval every call, and the program is structured so that this is
1145# # never called for a non-blessed object.
1146#
1147# return Scalar::Util::refaddr($_[0]) if $has_fast_scalar_util;
1148#
1149# # Check at least that is a ref.
1150# my $pkg = ref($_[0]) or return undef;
1151#
1152# # Change to a fake package to defeat any overloaded stringify
1153# bless $_[0], 'main::Fake';
1154#
1155# # Numifying a ref gives its address.
1156# my $addr = 0 + $_[0];
1157#
1158# # Return to original class
1159# bless $_[0], $pkg;
1160# return $addr;
1161#}
1162
99870f4d
KW
1163sub max ($$) {
1164 my $a = shift;
1165 my $b = shift;
1166 return $a if $a >= $b;
1167 return $b;
1168}
1169
1170sub min ($$) {
1171 my $a = shift;
1172 my $b = shift;
1173 return $a if $a <= $b;
1174 return $b;
1175}
1176
1177sub clarify_number ($) {
1178 # This returns the input number with underscores inserted every 3 digits
1179 # in large (5 digits or more) numbers. Input must be entirely digits, not
1180 # checked.
1181
1182 my $number = shift;
1183 my $pos = length($number) - 3;
1184 return $number if $pos <= 1;
1185 while ($pos > 0) {
1186 substr($number, $pos, 0) = '_';
1187 $pos -= 3;
5beb625e 1188 }
99870f4d 1189 return $number;
99598c8c
JH
1190}
1191
12ac2576 1192
99870f4d 1193package Carp;
7ebf06b3 1194
99870f4d
KW
1195# These routines give a uniform treatment of messages in this program. They
1196# are placed in the Carp package to cause the stack trace to not include them,
1197# although an alternative would be to use another package and set @CARP_NOT
1198# for it.
12ac2576 1199
99870f4d 1200our $Verbose = 1 if main::DEBUG; # Useful info when debugging
12ac2576 1201
99f78760
KW
1202# This is a work-around suggested by Nicholas Clark to fix a problem with Carp
1203# and overload trying to load Scalar:Util under miniperl. See
1204# http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/2009-11/msg01057.html
1205undef $overload::VERSION;
1206
99870f4d
KW
1207sub my_carp {
1208 my $message = shift || "";
1209 my $nofold = shift || 0;
7ebf06b3 1210
99870f4d
KW
1211 if ($message) {
1212 $message = main::join_lines($message);
1213 $message =~ s/^$0: *//; # Remove initial program name
1214 $message =~ s/[.;,]+$//; # Remove certain ending punctuation
1215 $message = "\n$0: $message;";
12ac2576 1216
99870f4d
KW
1217 # Fold the message with program name, semi-colon end punctuation
1218 # (which looks good with the message that carp appends to it), and a
1219 # hanging indent for continuation lines.
1220 $message = main::simple_fold($message, "", 4) unless $nofold;
1221 $message =~ s/\n$//; # Remove the trailing nl so what carp
1222 # appends is to the same line
1223 }
12ac2576 1224
99870f4d 1225 return $message if defined wantarray; # If a caller just wants the msg
12ac2576 1226
99870f4d
KW
1227 carp $message;
1228 return;
1229}
7ebf06b3 1230
99870f4d
KW
1231sub my_carp_bug {
1232 # This is called when it is clear that the problem is caused by a bug in
1233 # this program.
7ebf06b3 1234
99870f4d
KW
1235 my $message = shift;
1236 $message =~ s/^$0: *//;
1237 $message = my_carp("Bug in $0. Please report it by running perlbug or if that is unavailable, by sending email to perbug\@perl.org:\n$message");
1238 carp $message;
1239 return;
1240}
7ebf06b3 1241
99870f4d
KW
1242sub carp_too_few_args {
1243 if (@_ != 2) {
1244 my_carp_bug("Wrong number of arguments: to 'carp_too_few_arguments'. No action taken.");
1245 return;
12ac2576 1246 }
7ebf06b3 1247
99870f4d
KW
1248 my $args_ref = shift;
1249 my $count = shift;
7ebf06b3 1250
99870f4d
KW
1251 my_carp_bug("Need at least $count arguments to "
1252 . (caller 1)[3]
1253 . ". Instead got: '"
1254 . join ', ', @$args_ref
1255 . "'. No action taken.");
1256 return;
12ac2576
JP
1257}
1258
99870f4d
KW
1259sub carp_extra_args {
1260 my $args_ref = shift;
1261 my_carp_bug("Too many arguments to 'carp_extra_args': (" . join(', ', @_) . "); Extras ignored.") if @_;
12ac2576 1262
99870f4d
KW
1263 unless (ref $args_ref) {
1264 my_carp_bug("Argument to 'carp_extra_args' ($args_ref) must be a ref. Not checking arguments.");
1265 return;
1266 }
1267 my ($package, $file, $line) = caller;
1268 my $subroutine = (caller 1)[3];
cf25bb62 1269
99870f4d
KW
1270 my $list;
1271 if (ref $args_ref eq 'HASH') {
1272 foreach my $key (keys %$args_ref) {
1273 $args_ref->{$key} = $UNDEF unless defined $args_ref->{$key};
cf25bb62 1274 }
99870f4d 1275 $list = join ', ', each %{$args_ref};
cf25bb62 1276 }
99870f4d
KW
1277 elsif (ref $args_ref eq 'ARRAY') {
1278 foreach my $arg (@$args_ref) {
1279 $arg = $UNDEF unless defined $arg;
1280 }
1281 $list = join ', ', @$args_ref;
1282 }
1283 else {
1284 my_carp_bug("Can't cope with ref "
1285 . ref($args_ref)
1286 . " . argument to 'carp_extra_args'. Not checking arguments.");
1287 return;
1288 }
1289
1290 my_carp_bug("Unrecognized parameters in options: '$list' to $subroutine. Skipped.");
1291 return;
d73e5302
JH
1292}
1293
99870f4d
KW
1294package main;
1295
1296{ # Closure
1297
1298 # This program uses the inside-out method for objects, as recommended in
1299 # "Perl Best Practices". This closure aids in generating those. There
1300 # are two routines. setup_package() is called once per package to set
1301 # things up, and then set_access() is called for each hash representing a
1302 # field in the object. These routines arrange for the object to be
1303 # properly destroyed when no longer used, and for standard accessor
1304 # functions to be generated. If you need more complex accessors, just
1305 # write your own and leave those accesses out of the call to set_access().
1306 # More details below.
1307
1308 my %constructor_fields; # fields that are to be used in constructors; see
1309 # below
1310
1311 # The values of this hash will be the package names as keys to other
1312 # hashes containing the name of each field in the package as keys, and
1313 # references to their respective hashes as values.
1314 my %package_fields;
1315
1316 sub setup_package {
1317 # Sets up the package, creating standard DESTROY and dump methods
1318 # (unless already defined). The dump method is used in debugging by
1319 # simple_dumper().
1320 # The optional parameters are:
1321 # a) a reference to a hash, that gets populated by later
1322 # set_access() calls with one of the accesses being
1323 # 'constructor'. The caller can then refer to this, but it is
1324 # not otherwise used by these two routines.
1325 # b) a reference to a callback routine to call during destruction
1326 # of the object, before any fields are actually destroyed
1327
1328 my %args = @_;
1329 my $constructor_ref = delete $args{'Constructor_Fields'};
1330 my $destroy_callback = delete $args{'Destroy_Callback'};
1331 Carp::carp_extra_args(\@_) if main::DEBUG && %args;
1332
1333 my %fields;
1334 my $package = (caller)[0];
1335
1336 $package_fields{$package} = \%fields;
1337 $constructor_fields{$package} = $constructor_ref;
1338
1339 unless ($package->can('DESTROY')) {
1340 my $destroy_name = "${package}::DESTROY";
1341 no strict "refs";
1342
1343 # Use typeglob to give the anonymous subroutine the name we want
1344 *$destroy_name = sub {
1345 my $self = shift;
1346 my $addr = main::objaddr($self);
1347
1348 $self->$destroy_callback if $destroy_callback;
1349 foreach my $field (keys %{$package_fields{$package}}) {
1350 #print STDERR __LINE__, ": Destroying ", ref $self, " ", sprintf("%04X", $addr), ": ", $field, "\n";
1351 delete $package_fields{$package}{$field}{$addr};
1352 }
1353 return;
1354 }
1355 }
1356
1357 unless ($package->can('dump')) {
1358 my $dump_name = "${package}::dump";
1359 no strict "refs";
1360 *$dump_name = sub {
1361 my $self = shift;
1362 return dump_inside_out($self, $package_fields{$package}, @_);
1363 }
1364 }
1365 return;
1366 }
1367
1368 sub set_access {
1369 # Arrange for the input field to be garbage collected when no longer
1370 # needed. Also, creates standard accessor functions for the field
1371 # based on the optional parameters-- none if none of these parameters:
1372 # 'addable' creates an 'add_NAME()' accessor function.
1373 # 'readable' or 'readable_array' creates a 'NAME()' accessor
1374 # function.
1375 # 'settable' creates a 'set_NAME()' accessor function.
1376 # 'constructor' doesn't create an accessor function, but adds the
1377 # field to the hash that was previously passed to
1378 # setup_package();
1379 # Any of the accesses can be abbreviated down, so that 'a', 'ad',
1380 # 'add' etc. all mean 'addable'.
1381 # The read accessor function will work on both array and scalar
1382 # values. If another accessor in the parameter list is 'a', the read
1383 # access assumes an array. You can also force it to be array access
1384 # by specifying 'readable_array' instead of 'readable'
1385 #
1386 # A sort-of 'protected' access can be set-up by preceding the addable,
1387 # readable or settable with some initial portion of 'protected_' (but,
1388 # the underscore is required), like 'p_a', 'pro_set', etc. The
1389 # "protection" is only by convention. All that happens is that the
1390 # accessor functions' names begin with an underscore. So instead of
1391 # calling set_foo, the call is _set_foo. (Real protection could be
1392 # accomplished by having a new subroutine, end_package called at the
1393 # end of each package, and then storing the __LINE__ ranges and
1394 # checking them on every accessor. But that is way overkill.)
1395
1396 # We create anonymous subroutines as the accessors and then use
1397 # typeglobs to assign them to the proper package and name
1398
1399 my $name = shift; # Name of the field
1400 my $field = shift; # Reference to the inside-out hash containing the
1401 # field
1402
1403 my $package = (caller)[0];
1404
1405 if (! exists $package_fields{$package}) {
1406 croak "$0: Must call 'setup_package' before 'set_access'";
1407 }
d73e5302 1408
99870f4d
KW
1409 # Stash the field so DESTROY can get it.
1410 $package_fields{$package}{$name} = $field;
cf25bb62 1411
99870f4d
KW
1412 # Remaining arguments are the accessors. For each...
1413 foreach my $access (@_) {
1414 my $access = lc $access;
cf25bb62 1415
99870f4d 1416 my $protected = "";
cf25bb62 1417
99870f4d
KW
1418 # Match the input as far as it goes.
1419 if ($access =~ /^(p[^_]*)_/) {
1420 $protected = $1;
1421 if (substr('protected_', 0, length $protected)
1422 eq $protected)
1423 {
1424
1425 # Add 1 for the underscore not included in $protected
1426 $access = substr($access, length($protected) + 1);
1427 $protected = '_';
1428 }
1429 else {
1430 $protected = "";
1431 }
1432 }
1433
1434 if (substr('addable', 0, length $access) eq $access) {
1435 my $subname = "${package}::${protected}add_$name";
1436 no strict "refs";
1437
1438 # add_ accessor. Don't add if already there, which we
1439 # determine using 'eq' for scalars and '==' otherwise.
1440 *$subname = sub {
1441 use strict "refs";
1442 return Carp::carp_too_few_args(\@_, 2) if main::DEBUG && @_ < 2;
1443 my $self = shift;
1444 my $value = shift;
1445 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
1446 if (ref $value) {
1447 return if grep { $value == $_ }
1448 @{$field->{main::objaddr $self}};
1449 }
1450 else {
1451 return if grep { $value eq $_ }
1452 @{$field->{main::objaddr $self}};
1453 }
1454 push @{$field->{main::objaddr $self}}, $value;
1455 return;
1456 }
1457 }
1458 elsif (substr('constructor', 0, length $access) eq $access) {
1459 if ($protected) {
1460 Carp::my_carp_bug("Can't set-up 'protected' constructors")
1461 }
1462 else {
1463 $constructor_fields{$package}{$name} = $field;
1464 }
1465 }
1466 elsif (substr('readable_array', 0, length $access) eq $access) {
1467
1468 # Here has read access. If one of the other parameters for
1469 # access is array, or this one specifies array (by being more
1470 # than just 'readable_'), then create a subroutine that
1471 # assumes the data is an array. Otherwise just a scalar
1472 my $subname = "${package}::${protected}$name";
1473 if (grep { /^a/i } @_
1474 or length($access) > length('readable_'))
1475 {
1476 no strict "refs";
1477 *$subname = sub {
1478 use strict "refs";
23e33b60
KW
1479 Carp::carp_extra_args(\@_) if main::DEBUG && @_ > 1;
1480 my $addr = main::objaddr $_[0];
99870f4d
KW
1481 if (ref $field->{$addr} ne 'ARRAY') {
1482 my $type = ref $field->{$addr};
1483 $type = 'scalar' unless $type;
1484 Carp::my_carp_bug("Trying to read $name as an array when it is a $type. Big problems.");
1485 return;
1486 }
1487 return scalar @{$field->{$addr}} unless wantarray;
1488
1489 # Make a copy; had problems with caller modifying the
1490 # original otherwise
1491 my @return = @{$field->{$addr}};
1492 return @return;
1493 }
1494 }
1495 else {
1496
1497 # Here not an array value, a simpler function.
1498 no strict "refs";
1499 *$subname = sub {
1500 use strict "refs";
23e33b60
KW
1501 Carp::carp_extra_args(\@_) if main::DEBUG && @_ > 1;
1502 return $field->{main::objaddr $_[0]};
99870f4d
KW
1503 }
1504 }
1505 }
1506 elsif (substr('settable', 0, length $access) eq $access) {
1507 my $subname = "${package}::${protected}set_$name";
1508 no strict "refs";
1509 *$subname = sub {
1510 use strict "refs";
23e33b60
KW
1511 if (main::DEBUG) {
1512 return Carp::carp_too_few_args(\@_, 2) if @_ < 2;
1513 Carp::carp_extra_args(\@_) if @_ > 2;
1514 }
1515 # $self is $_[0]; $value is $_[1]
1516 $field->{main::objaddr $_[0]} = $_[1];
99870f4d
KW
1517 return;
1518 }
1519 }
1520 else {
1521 Carp::my_carp_bug("Unknown accessor type $access. No accessor set.");
1522 }
cf25bb62 1523 }
99870f4d 1524 return;
cf25bb62 1525 }
99870f4d
KW
1526}
1527
1528package Input_file;
1529
1530# All input files use this object, which stores various attributes about them,
1531# and provides for convenient, uniform handling. The run method wraps the
1532# processing. It handles all the bookkeeping of opening, reading, and closing
1533# the file, returning only significant input lines.
1534#
1535# Each object gets a handler which processes the body of the file, and is
1536# called by run(). Most should use the generic, default handler, which has
1537# code scrubbed to handle things you might not expect. A handler should
1538# basically be a while(next_line()) {...} loop.
1539#
1540# You can also set up handlers to
1541# 1) call before the first line is read for pre processing
1542# 2) call to adjust each line of the input before the main handler gets them
1543# 3) call upon EOF before the main handler exits its loop
1544# 4) call at the end for post processing
1545#
1546# $_ is used to store the input line, and is to be filtered by the
1547# each_line_handler()s. So, if the format of the line is not in the desired
1548# format for the main handler, these are used to do that adjusting. They can
1549# be stacked (by enclosing them in an [ anonymous array ] in the constructor,
1550# so the $_ output of one is used as the input to the next. None of the other
1551# handlers are stackable, but could easily be changed to be so.
1552#
1553# Most of the handlers can call insert_lines() or insert_adjusted_lines()
1554# which insert the parameters as lines to be processed before the next input
1555# file line is read. This allows the EOF handler to flush buffers, for
1556# example. The difference between the two routines is that the lines inserted
1557# by insert_lines() are subjected to the each_line_handler()s. (So if you
1558# called it from such a handler, you would get infinite recursion.) Lines
1559# inserted by insert_adjusted_lines() go directly to the main handler without
1560# any adjustments. If the post-processing handler calls any of these, there
1561# will be no effect. Some error checking for these conditions could be added,
1562# but it hasn't been done.
1563#
1564# carp_bad_line() should be called to warn of bad input lines, which clears $_
1565# to prevent further processing of the line. This routine will output the
1566# message as a warning once, and then keep a count of the lines that have the
1567# same message, and output that count at the end of the file's processing.
1568# This keeps the number of messages down to a manageable amount.
1569#
1570# get_missings() should be called to retrieve any @missing input lines.
1571# Messages will be raised if this isn't done if the options aren't to ignore
1572# missings.
1573
1574sub trace { return main::trace(@_); }
1575
99870f4d
KW
1576{ # Closure
1577 # Keep track of fields that are to be put into the constructor.
1578 my %constructor_fields;
1579
1580 main::setup_package(Constructor_Fields => \%constructor_fields);
1581
1582 my %file; # Input file name, required
1583 main::set_access('file', \%file, qw{ c r });
1584
1585 my %first_released; # Unicode version file was first released in, required
1586 main::set_access('first_released', \%first_released, qw{ c r });
1587
1588 my %handler; # Subroutine to process the input file, defaults to
1589 # 'process_generic_property_file'
1590 main::set_access('handler', \%handler, qw{ c });
1591
1592 my %property;
1593 # name of property this file is for. defaults to none, meaning not
1594 # applicable, or is otherwise determinable, for example, from each line.
1595 main::set_access('property', \%property, qw{ c });
1596
1597 my %optional;
1598 # If this is true, the file is optional. If not present, no warning is
1599 # output. If it is present, the string given by this parameter is
1600 # evaluated, and if false the file is not processed.
1601 main::set_access('optional', \%optional, 'c', 'r');
1602
1603 my %non_skip;
1604 # This is used for debugging, to skip processing of all but a few input
1605 # files. Add 'non_skip => 1' to the constructor for those files you want
1606 # processed when you set the $debug_skip global.
1607 main::set_access('non_skip', \%non_skip, 'c');
1608
37e2e78e
KW
1609 my %skip;
1610 # This is used to skip processing of this input file semi-permanently.
1611 # It is used for files that we aren't planning to process anytime soon,
1612 # but want to allow to be in the directory and not raise a message that we
1613 # are not handling. Mostly for test files. This is in contrast to the
1614 # non_skip element, which is supposed to be used very temporarily for
1615 # debugging. Sets 'optional' to 1
1616 main::set_access('skip', \%skip, 'c');
1617
99870f4d
KW
1618 my %each_line_handler;
1619 # list of subroutines to look at and filter each non-comment line in the
1620 # file. defaults to none. The subroutines are called in order, each is
1621 # to adjust $_ for the next one, and the final one adjusts it for
1622 # 'handler'
1623 main::set_access('each_line_handler', \%each_line_handler, 'c');
1624
1625 my %has_missings_defaults;
1626 # ? Are there lines in the file giving default values for code points
1627 # missing from it?. Defaults to NO_DEFAULTS. Otherwise NOT_IGNORED is
1628 # the norm, but IGNORED means it has such lines, but the handler doesn't
1629 # use them. Having these three states allows us to catch changes to the
1630 # UCD that this program should track
1631 main::set_access('has_missings_defaults',
1632 \%has_missings_defaults, qw{ c r });
1633
1634 my %pre_handler;
1635 # Subroutine to call before doing anything else in the file. If undef, no
1636 # such handler is called.
1637 main::set_access('pre_handler', \%pre_handler, qw{ c });
1638
1639 my %eof_handler;
1640 # Subroutine to call upon getting an EOF on the input file, but before
1641 # that is returned to the main handler. This is to allow buffers to be
1642 # flushed. The handler is expected to call insert_lines() or
1643 # insert_adjusted() with the buffered material
1644 main::set_access('eof_handler', \%eof_handler, qw{ c r });
1645
1646 my %post_handler;
1647 # Subroutine to call after all the lines of the file are read in and
1648 # processed. If undef, no such handler is called.
1649 main::set_access('post_handler', \%post_handler, qw{ c });
1650
1651 my %progress_message;
1652 # Message to print to display progress in lieu of the standard one
1653 main::set_access('progress_message', \%progress_message, qw{ c });
1654
1655 my %handle;
1656 # cache open file handle, internal. Is undef if file hasn't been
1657 # processed at all, empty if has;
1658 main::set_access('handle', \%handle);
1659
1660 my %added_lines;
1661 # cache of lines added virtually to the file, internal
1662 main::set_access('added_lines', \%added_lines);
1663
1664 my %errors;
1665 # cache of errors found, internal
1666 main::set_access('errors', \%errors);
1667
1668 my %missings;
1669 # storage of '@missing' defaults lines
1670 main::set_access('missings', \%missings);
1671
1672 sub new {
1673 my $class = shift;
1674
1675 my $self = bless \do{ my $anonymous_scalar }, $class;
1676 my $addr = main::objaddr($self);
1677
1678 # Set defaults
1679 $handler{$addr} = \&main::process_generic_property_file;
1680 $non_skip{$addr} = 0;
37e2e78e 1681 $skip{$addr} = 0;
99870f4d
KW
1682 $has_missings_defaults{$addr} = $NO_DEFAULTS;
1683 $handle{$addr} = undef;
1684 $added_lines{$addr} = [ ];
1685 $each_line_handler{$addr} = [ ];
1686 $errors{$addr} = { };
1687 $missings{$addr} = [ ];
1688
1689 # Two positional parameters.
99f78760 1690 return Carp::carp_too_few_args(\@_, 2) if main::DEBUG && @_ < 2;
99870f4d
KW
1691 $file{$addr} = main::internal_file_to_platform(shift);
1692 $first_released{$addr} = shift;
1693
1694 # The rest of the arguments are key => value pairs
1695 # %constructor_fields has been set up earlier to list all possible
1696 # ones. Either set or push, depending on how the default has been set
1697 # up just above.
1698 my %args = @_;
1699 foreach my $key (keys %args) {
1700 my $argument = $args{$key};
1701
1702 # Note that the fields are the lower case of the constructor keys
1703 my $hash = $constructor_fields{lc $key};
1704 if (! defined $hash) {
1705 Carp::my_carp_bug("Unrecognized parameters '$key => $argument' to new() for $self. Skipped");
1706 next;
1707 }
1708 if (ref $hash->{$addr} eq 'ARRAY') {
1709 if (ref $argument eq 'ARRAY') {
1710 foreach my $argument (@{$argument}) {
1711 next if ! defined $argument;
1712 push @{$hash->{$addr}}, $argument;
1713 }
1714 }
1715 else {
1716 push @{$hash->{$addr}}, $argument if defined $argument;
1717 }
1718 }
1719 else {
1720 $hash->{$addr} = $argument;
1721 }
1722 delete $args{$key};
1723 };
1724
1725 # If the file has a property for it, it means that the property is not
1726 # listed in the file's entries. So add a handler to the list of line
1727 # handlers to insert the property name into the lines, to provide a
1728 # uniform interface to the final processing subroutine.
1729 # the final code doesn't have to worry about that.
1730 if ($property{$addr}) {
1731 push @{$each_line_handler{$addr}}, \&_insert_property_into_line;
1732 }
1733
1734 if ($non_skip{$addr} && ! $debug_skip && $verbosity) {
1735 print "Warning: " . __PACKAGE__ . " constructor for $file{$addr} has useless 'non_skip' in it\n";
a3a8c5f0 1736 }
99870f4d 1737
37e2e78e
KW
1738 $optional{$addr} = 1 if $skip{$addr};
1739
99870f4d 1740 return $self;
d73e5302
JH
1741 }
1742
cf25bb62 1743
99870f4d
KW
1744 use overload
1745 fallback => 0,
1746 qw("") => "_operator_stringify",
1747 "." => \&main::_operator_dot,
1748 ;
cf25bb62 1749
99870f4d
KW
1750 sub _operator_stringify {
1751 my $self = shift;
cf25bb62 1752
99870f4d 1753 return __PACKAGE__ . " object for " . $self->file;
d73e5302 1754 }
d73e5302 1755
99870f4d
KW
1756 # flag to make sure extracted files are processed early
1757 my $seen_non_extracted_non_age = 0;
d73e5302 1758
99870f4d
KW
1759 sub run {
1760 # Process the input object $self. This opens and closes the file and
1761 # calls all the handlers for it. Currently, this can only be called
1762 # once per file, as it destroy's the EOF handler
d73e5302 1763
99870f4d
KW
1764 my $self = shift;
1765 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
b6922eda 1766
99870f4d 1767 my $addr = main::objaddr $self;
b6922eda 1768
99870f4d 1769 my $file = $file{$addr};
d73e5302 1770
99870f4d
KW
1771 # Don't process if not expecting this file (because released later
1772 # than this Unicode version), and isn't there. This means if someone
1773 # copies it into an earlier version's directory, we will go ahead and
1774 # process it.
1775 return if $first_released{$addr} gt $v_version && ! -e $file;
1776
1777 # If in debugging mode and this file doesn't have the non-skip
1778 # flag set, and isn't one of the critical files, skip it.
1779 if ($debug_skip
1780 && $first_released{$addr} ne v0
1781 && ! $non_skip{$addr})
1782 {
1783 print "Skipping $file in debugging\n" if $verbosity;
1784 return;
1785 }
1786
1787 # File could be optional
37e2e78e 1788 if ($optional{$addr}) {
99870f4d
KW
1789 return unless -e $file;
1790 my $result = eval $optional{$addr};
1791 if (! defined $result) {
1792 Carp::my_carp_bug("Got '$@' when tried to eval $optional{$addr}. $file Skipped.");
1793 return;
1794 }
1795 if (! $result) {
1796 if ($verbosity) {
1797 print STDERR "Skipping processing input file '$file' because '$optional{$addr}' is not true\n";
1798 }
1799 return;
1800 }
1801 }
1802
1803 if (! defined $file || ! -e $file) {
1804
1805 # If the file doesn't exist, see if have internal data for it
1806 # (based on first_released being 0).
1807 if ($first_released{$addr} eq v0) {
1808 $handle{$addr} = 'pretend_is_open';
1809 }
1810 else {
1811 if (! $optional{$addr} # File could be optional
1812 && $v_version ge $first_released{$addr})
1813 {
1814 print STDERR "Skipping processing input file '$file' because not found\n" if $v_version ge $first_released{$addr};
1815 }
1816 return;
1817 }
1818 }
1819 else {
1820
37e2e78e
KW
1821 # Here, the file exists. Some platforms may change the case of
1822 # its name
99870f4d 1823 if ($seen_non_extracted_non_age) {
517956bf 1824 if ($file =~ /$EXTRACTED/i) {
99870f4d 1825 Carp::my_carp_bug(join_lines(<<END
99f78760 1826$file should be processed just after the 'Prop...Alias' files, and before
99870f4d
KW
1827anything not in the $EXTRACTED_DIR directory. Proceeding, but the results may
1828have subtle problems
1829END
1830 ));
1831 }
1832 }
1833 elsif ($EXTRACTED_DIR
1834 && $first_released{$addr} ne v0
517956bf
CB
1835 && $file !~ /$EXTRACTED/i
1836 && lc($file) ne 'dage.txt')
99870f4d
KW
1837 {
1838 # We don't set this (by the 'if' above) if we have no
1839 # extracted directory, so if running on an early version,
1840 # this test won't work. Not worth worrying about.
1841 $seen_non_extracted_non_age = 1;
1842 }
1843
1844 # And mark the file as having being processed, and warn if it
1845 # isn't a file we are expecting. As we process the files,
1846 # they are deleted from the hash, so any that remain at the
1847 # end of the program are files that we didn't process.
517956bf
CB
1848 my $fkey = File::Spec->rel2abs($file);
1849 my $expecting = delete $potential_files{$fkey};
1850 $expecting = delete $potential_files{lc($fkey)} unless defined $expecting;
1851 Carp::my_carp("Was not expecting '$file'.") if
1852 ! $expecting
99870f4d
KW
1853 && ! defined $handle{$addr};
1854
37e2e78e
KW
1855 # Having deleted from expected files, we can quit if not to do
1856 # anything. Don't print progress unless really want verbosity
1857 if ($skip{$addr}) {
1858 print "Skipping $file.\n" if $verbosity >= $VERBOSE;
1859 return;
1860 }
1861
99870f4d
KW
1862 # Open the file, converting the slashes used in this program
1863 # into the proper form for the OS
1864 my $file_handle;
1865 if (not open $file_handle, "<", $file) {
1866 Carp::my_carp("Can't open $file. Skipping: $!");
1867 return 0;
1868 }
1869 $handle{$addr} = $file_handle; # Cache the open file handle
1870 }
1871
1872 if ($verbosity >= $PROGRESS) {
1873 if ($progress_message{$addr}) {
1874 print "$progress_message{$addr}\n";
1875 }
1876 else {
1877 # If using a virtual file, say so.
1878 print "Processing ", (-e $file)
1879 ? $file
1880 : "substitute $file",
1881 "\n";
1882 }
1883 }
1884
1885
1886 # Call any special handler for before the file.
1887 &{$pre_handler{$addr}}($self) if $pre_handler{$addr};
1888
1889 # Then the main handler
1890 &{$handler{$addr}}($self);
1891
1892 # Then any special post-file handler.
1893 &{$post_handler{$addr}}($self) if $post_handler{$addr};
1894
1895 # If any errors have been accumulated, output the counts (as the first
1896 # error message in each class was output when it was encountered).
1897 if ($errors{$addr}) {
1898 my $total = 0;
1899 my $types = 0;
1900 foreach my $error (keys %{$errors{$addr}}) {
1901 $total += $errors{$addr}->{$error};
1902 delete $errors{$addr}->{$error};
1903 $types++;
1904 }
1905 if ($total > 1) {
1906 my $message
1907 = "A total of $total lines had errors in $file. ";
1908
1909 $message .= ($types == 1)
1910 ? '(Only the first one was displayed.)'
1911 : '(Only the first of each type was displayed.)';
1912 Carp::my_carp($message);
1913 }
1914 }
1915
1916 if (@{$missings{$addr}}) {
1917 Carp::my_carp_bug("Handler for $file didn't look at all the \@missing lines. Generated tables likely are wrong");
1918 }
1919
1920 # If a real file handle, close it.
1921 close $handle{$addr} or Carp::my_carp("Can't close $file: $!") if
1922 ref $handle{$addr};
1923 $handle{$addr} = ""; # Uses empty to indicate that has already seen
1924 # the file, as opposed to undef
1925 return;
1926 }
1927
1928 sub next_line {
1929 # Sets $_ to be the next logical input line, if any. Returns non-zero
1930 # if such a line exists. 'logical' means that any lines that have
1931 # been added via insert_lines() will be returned in $_ before the file
1932 # is read again.
1933
1934 my $self = shift;
1935 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
1936
1937 my $addr = main::objaddr $self;
1938
1939 # Here the file is open (or if the handle is not a ref, is an open
1940 # 'virtual' file). Get the next line; any inserted lines get priority
1941 # over the file itself.
1942 my $adjusted;
1943
1944 LINE:
1945 while (1) { # Loop until find non-comment, non-empty line
1946 #local $to_trace = 1 if main::DEBUG;
1947 my $inserted_ref = shift @{$added_lines{$addr}};
1948 if (defined $inserted_ref) {
1949 ($adjusted, $_) = @{$inserted_ref};
1950 trace $adjusted, $_ if main::DEBUG && $to_trace;
1951 return 1 if $adjusted;
1952 }
1953 else {
1954 last if ! ref $handle{$addr}; # Don't read unless is real file
1955 last if ! defined ($_ = readline $handle{$addr});
1956 }
1957 chomp;
1958 trace $_ if main::DEBUG && $to_trace;
1959
1960 # See if this line is the comment line that defines what property
1961 # value that code points that are not listed in the file should
1962 # have. The format or existence of these lines is not guaranteed
1963 # by Unicode since they are comments, but the documentation says
1964 # that this was added for machine-readability, so probably won't
1965 # change. This works starting in Unicode Version 5.0. They look
1966 # like:
1967 #
1968 # @missing: 0000..10FFFF; Not_Reordered
1969 # @missing: 0000..10FFFF; Decomposition_Mapping; <code point>
1970 # @missing: 0000..10FFFF; ; NaN
1971 #
1972 # Save the line for a later get_missings() call.
1973 if (/$missing_defaults_prefix/) {
1974 if ($has_missings_defaults{$addr} == $NO_DEFAULTS) {
1975 $self->carp_bad_line("Unexpected \@missing line. Assuming no missing entries");
1976 }
1977 elsif ($has_missings_defaults{$addr} == $NOT_IGNORED) {
1978 my @defaults = split /\s* ; \s*/x, $_;
1979
1980 # The first field is the @missing, which ends in a
1981 # semi-colon, so can safely shift.
1982 shift @defaults;
1983
1984 # Some of these lines may have empty field placeholders
1985 # which get in the way. An example is:
1986 # @missing: 0000..10FFFF; ; NaN
1987 # Remove them. Process starting from the top so the
1988 # splice doesn't affect things still to be looked at.
1989 for (my $i = @defaults - 1; $i >= 0; $i--) {
1990 next if $defaults[$i] ne "";
1991 splice @defaults, $i, 1;
1992 }
1993
1994 # What's left should be just the property (maybe) and the
1995 # default. Having only one element means it doesn't have
1996 # the property.
1997 my $default;
1998 my $property;
1999 if (@defaults >= 1) {
2000 if (@defaults == 1) {
2001 $default = $defaults[0];
2002 }
2003 else {
2004 $property = $defaults[0];
2005 $default = $defaults[1];
2006 }
2007 }
2008
2009 if (@defaults < 1
2010 || @defaults > 2
2011 || ($default =~ /^</
2012 && $default !~ /^<code *point>$/i
2013 && $default !~ /^<none>$/i))
2014 {
2015 $self->carp_bad_line("Unrecognized \@missing line: $_. Assuming no missing entries");
2016 }
2017 else {
2018
2019 # If the property is missing from the line, it should
2020 # be the one for the whole file
2021 $property = $property{$addr} if ! defined $property;
2022
2023 # Change <none> to the null string, which is what it
2024 # really means. If the default is the code point
2025 # itself, set it to <code point>, which is what
2026 # Unicode uses (but sometimes they've forgotten the
2027 # space)
2028 if ($default =~ /^<none>$/i) {
2029 $default = "";
2030 }
2031 elsif ($default =~ /^<code *point>$/i) {
2032 $default = $CODE_POINT;
2033 }
2034
2035 # Store them as a sub-arrays with both components.
2036 push @{$missings{$addr}}, [ $default, $property ];
2037 }
2038 }
2039
2040 # There is nothing for the caller to process on this comment
2041 # line.
2042 next;
2043 }
2044
2045 # Remove comments and trailing space, and skip this line if the
2046 # result is empty
2047 s/#.*//;
2048 s/\s+$//;
2049 next if /^$/;
2050
2051 # Call any handlers for this line, and skip further processing of
2052 # the line if the handler sets the line to null.
2053 foreach my $sub_ref (@{$each_line_handler{$addr}}) {
2054 &{$sub_ref}($self);
2055 next LINE if /^$/;
2056 }
2057
2058 # Here the line is ok. return success.
2059 return 1;
2060 } # End of looping through lines.
2061
2062 # If there is an EOF handler, call it (only once) and if it generates
2063 # more lines to process go back in the loop to handle them.
2064 if ($eof_handler{$addr}) {
2065 &{$eof_handler{$addr}}($self);
2066 $eof_handler{$addr} = ""; # Currently only get one shot at it.
2067 goto LINE if $added_lines{$addr};
2068 }
2069
2070 # Return failure -- no more lines.
2071 return 0;
2072
2073 }
2074
2075# Not currently used, not fully tested.
2076# sub peek {
2077# # Non-destructive look-ahead one non-adjusted, non-comment, non-blank
2078# # record. Not callable from an each_line_handler(), nor does it call
2079# # an each_line_handler() on the line.
2080#
2081# my $self = shift;
2082# my $addr = main::objaddr $self;
2083#
2084# foreach my $inserted_ref (@{$added_lines{$addr}}) {
2085# my ($adjusted, $line) = @{$inserted_ref};
2086# next if $adjusted;
2087#
2088# # Remove comments and trailing space, and return a non-empty
2089# # resulting line
2090# $line =~ s/#.*//;
2091# $line =~ s/\s+$//;
2092# return $line if $line ne "";
2093# }
2094#
2095# return if ! ref $handle{$addr}; # Don't read unless is real file
2096# while (1) { # Loop until find non-comment, non-empty line
2097# local $to_trace = 1 if main::DEBUG;
2098# trace $_ if main::DEBUG && $to_trace;
2099# return if ! defined (my $line = readline $handle{$addr});
2100# chomp $line;
2101# push @{$added_lines{$addr}}, [ 0, $line ];
2102#
2103# $line =~ s/#.*//;
2104# $line =~ s/\s+$//;
2105# return $line if $line ne "";
2106# }
2107#
2108# return;
2109# }
2110
2111
2112 sub insert_lines {
2113 # Lines can be inserted so that it looks like they were in the input
2114 # file at the place it was when this routine is called. See also
2115 # insert_adjusted_lines(). Lines inserted via this routine go through
2116 # any each_line_handler()
2117
2118 my $self = shift;
2119
2120 # Each inserted line is an array, with the first element being 0 to
2121 # indicate that this line hasn't been adjusted, and needs to be
2122 # processed.
2123 push @{$added_lines{main::objaddr $self}}, map { [ 0, $_ ] } @_;
2124 return;
2125 }
2126
2127 sub insert_adjusted_lines {
2128 # Lines can be inserted so that it looks like they were in the input
2129 # file at the place it was when this routine is called. See also
2130 # insert_lines(). Lines inserted via this routine are already fully
2131 # adjusted, ready to be processed; each_line_handler()s handlers will
2132 # not be called. This means this is not a completely general
2133 # facility, as only the last each_line_handler on the stack should
2134 # call this. It could be made more general, by passing to each of the
2135 # line_handlers their position on the stack, which they would pass on
2136 # to this routine, and that would replace the boolean first element in
2137 # the anonymous array pushed here, so that the next_line routine could
2138 # use that to call only those handlers whose index is after it on the
2139 # stack. But this is overkill for what is needed now.
2140
2141 my $self = shift;
2142 trace $_[0] if main::DEBUG && $to_trace;
2143
2144 # Each inserted line is an array, with the first element being 1 to
2145 # indicate that this line has been adjusted
2146 push @{$added_lines{main::objaddr $self}}, map { [ 1, $_ ] } @_;
2147 return;
2148 }
2149
2150 sub get_missings {
2151 # Returns the stored up @missings lines' values, and clears the list.
2152 # The values are in an array, consisting of the default in the first
2153 # element, and the property in the 2nd. However, since these lines
2154 # can be stacked up, the return is an array of all these arrays.
2155
2156 my $self = shift;
2157 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2158
2159 my $addr = main::objaddr $self;
2160
2161 # If not accepting a list return, just return the first one.
2162 return shift @{$missings{$addr}} unless wantarray;
2163
2164 my @return = @{$missings{$addr}};
2165 undef @{$missings{$addr}};
2166 return @return;
2167 }
2168
2169 sub _insert_property_into_line {
2170 # Add a property field to $_, if this file requires it.
2171
2172 my $property = $property{main::objaddr shift};
2173 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2174
2175 $_ =~ s/(;|$)/; $property$1/;
2176 return;
2177 }
2178
2179 sub carp_bad_line {
2180 # Output consistent error messages, using either a generic one, or the
2181 # one given by the optional parameter. To avoid gazillions of the
2182 # same message in case the syntax of a file is way off, this routine
2183 # only outputs the first instance of each message, incrementing a
2184 # count so the totals can be output at the end of the file.
2185
2186 my $self = shift;
2187 my $message = shift;
2188 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2189
2190 my $addr = main::objaddr $self;
2191
2192 $message = 'Unexpected line' unless $message;
2193
2194 # No trailing punctuation so as to fit with our addenda.
2195 $message =~ s/[.:;,]$//;
2196
2197 # If haven't seen this exact message before, output it now. Otherwise
2198 # increment the count of how many times it has occurred
2199 unless ($errors{$addr}->{$message}) {
2200 Carp::my_carp("$message in '$_' in "
2201 . $file{main::objaddr $self}
2202 . " at line $.. Skipping this line;");
2203 $errors{$addr}->{$message} = 1;
2204 }
2205 else {
2206 $errors{$addr}->{$message}++;
2207 }
2208
2209 # Clear the line to prevent any further (meaningful) processing of it.
2210 $_ = "";
2211
2212 return;
2213 }
2214} # End closure
2215
2216package Multi_Default;
2217
2218# Certain properties in early versions of Unicode had more than one possible
2219# default for code points missing from the files. In these cases, one
2220# default applies to everything left over after all the others are applied,
2221# and for each of the others, there is a description of which class of code
2222# points applies to it. This object helps implement this by storing the
2223# defaults, and for all but that final default, an eval string that generates
2224# the class that it applies to.
2225
2226
2227{ # Closure
2228
2229 main::setup_package();
2230
2231 my %class_defaults;
2232 # The defaults structure for the classes
2233 main::set_access('class_defaults', \%class_defaults);
2234
2235 my %other_default;
2236 # The default that applies to everything left over.
2237 main::set_access('other_default', \%other_default, 'r');
2238
2239
2240 sub new {
2241 # The constructor is called with default => eval pairs, terminated by
2242 # the left-over default. e.g.
2243 # Multi_Default->new(
2244 # 'T' => '$gc->table("Mn") + $gc->table("Cf") - 0x200C
2245 # - 0x200D',
2246 # 'R' => 'some other expression that evaluates to code points',
2247 # .
2248 # .
2249 # .
2250 # 'U'));
2251
2252 my $class = shift;
2253
2254 my $self = bless \do{my $anonymous_scalar}, $class;
2255 my $addr = main::objaddr($self);
2256
2257 while (@_ > 1) {
2258 my $default = shift;
2259 my $eval = shift;
2260 $class_defaults{$addr}->{$default} = $eval;
2261 }
2262
2263 $other_default{$addr} = shift;
2264
2265 return $self;
2266 }
2267
2268 sub get_next_defaults {
2269 # Iterates and returns the next class of defaults.
2270 my $self = shift;
2271 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2272
2273 my $addr = main::objaddr $self;
2274
2275 return each %{$class_defaults{$addr}};
2276 }
2277}
2278
2279package Alias;
2280
2281# An alias is one of the names that a table goes by. This class defines them
2282# including some attributes. Everything is currently setup in the
2283# constructor.
2284
2285
2286{ # Closure
2287
2288 main::setup_package();
2289
2290 my %name;
2291 main::set_access('name', \%name, 'r');
2292
2293 my %loose_match;
2294 # Determined by the constructor code if this name should match loosely or
2295 # not. The constructor parameters can override this, but it isn't fully
2296 # implemented, as should have ability to override Unicode one's via
2297 # something like a set_loose_match()
2298 main::set_access('loose_match', \%loose_match, 'r');
2299
2300 my %make_pod_entry;
2301 # Some aliases should not get their own entries because they are covered
2302 # by a wild-card, and some we want to discourage use of. Binary
2303 main::set_access('make_pod_entry', \%make_pod_entry, 'r');
2304
2305 my %status;
2306 # Aliases have a status, like deprecated, or even suppressed (which means
2307 # they don't appear in documentation). Enum
2308 main::set_access('status', \%status, 'r');
2309
2310 my %externally_ok;
2311 # Similarly, some aliases should not be considered as usable ones for
2312 # external use, such as file names, or we don't want documentation to
2313 # recommend them. Boolean
2314 main::set_access('externally_ok', \%externally_ok, 'r');
2315
2316 sub new {
2317 my $class = shift;
2318
2319 my $self = bless \do { my $anonymous_scalar }, $class;
2320 my $addr = main::objaddr($self);
2321
2322 $name{$addr} = shift;
2323 $loose_match{$addr} = shift;
2324 $make_pod_entry{$addr} = shift;
2325 $externally_ok{$addr} = shift;
2326 $status{$addr} = shift;
2327
2328 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2329
2330 # Null names are never ok externally
2331 $externally_ok{$addr} = 0 if $name{$addr} eq "";
2332
2333 return $self;
2334 }
2335}
2336
2337package Range;
2338
2339# A range is the basic unit for storing code points, and is described in the
2340# comments at the beginning of the program. Each range has a starting code
2341# point; an ending code point (not less than the starting one); a value
2342# that applies to every code point in between the two end-points, inclusive;
2343# and an enum type that applies to the value. The type is for the user's
2344# convenience, and has no meaning here, except that a non-zero type is
2345# considered to not obey the normal Unicode rules for having standard forms.
2346#
2347# The same structure is used for both map and match tables, even though in the
2348# latter, the value (and hence type) is irrelevant and could be used as a
2349# comment. In map tables, the value is what all the code points in the range
2350# map to. Type 0 values have the standardized version of the value stored as
2351# well, so as to not have to recalculate it a lot.
2352
2353sub trace { return main::trace(@_); }
2354
2355{ # Closure
2356
2357 main::setup_package();
2358
2359 my %start;
2360 main::set_access('start', \%start, 'r', 's');
2361
2362 my %end;
2363 main::set_access('end', \%end, 'r', 's');
2364
2365 my %value;
2366 main::set_access('value', \%value, 'r');
2367
2368 my %type;
2369 main::set_access('type', \%type, 'r');
2370
2371 my %standard_form;
2372 # The value in internal standard form. Defined only if the type is 0.
2373 main::set_access('standard_form', \%standard_form);
2374
2375 # Note that if these fields change, the dump() method should as well
2376
2377 sub new {
2378 return Carp::carp_too_few_args(\@_, 3) if main::DEBUG && @_ < 3;
2379 my $class = shift;
2380
2381 my $self = bless \do { my $anonymous_scalar }, $class;
2382 my $addr = main::objaddr($self);
2383
2384 $start{$addr} = shift;
2385 $end{$addr} = shift;
2386
2387 my %args = @_;
2388
2389 my $value = delete $args{'Value'}; # Can be 0
2390 $value = "" unless defined $value;
2391 $value{$addr} = $value;
2392
2393 $type{$addr} = delete $args{'Type'} || 0;
2394
2395 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
2396
2397 if (! $type{$addr}) {
2398 $standard_form{$addr} = main::standardize($value);
2399 }
2400
2401 return $self;
2402 }
2403
2404 use overload
2405 fallback => 0,
2406 qw("") => "_operator_stringify",
2407 "." => \&main::_operator_dot,
2408 ;
2409
2410 sub _operator_stringify {
2411 my $self = shift;
2412 my $addr = main::objaddr $self;
2413
2414 # Output it like '0041..0065 (value)'
2415 my $return = sprintf("%04X", $start{$addr})
2416 . '..'
2417 . sprintf("%04X", $end{$addr});
2418 my $value = $value{$addr};
2419 my $type = $type{$addr};
2420 $return .= ' (';
2421 $return .= "$value";
2422 $return .= ", Type=$type" if $type != 0;
2423 $return .= ')';
2424
2425 return $return;
2426 }
2427
2428 sub standard_form {
2429 # The standard form is the value itself if the standard form is
2430 # undefined (that is if the value is special)
2431
2432 my $self = shift;
2433 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2434
2435 my $addr = main::objaddr $self;
2436
2437 return $standard_form{$addr} if defined $standard_form{$addr};
2438 return $value{$addr};
2439 }
2440
2441 sub dump {
2442 # Human, not machine readable. For machine readable, comment out this
2443 # entire routine and let the standard one take effect.
2444 my $self = shift;
2445 my $indent = shift;
2446 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2447
2448 my $addr = main::objaddr $self;
2449
2450 my $return = $indent
2451 . sprintf("%04X", $start{$addr})
2452 . '..'
2453 . sprintf("%04X", $end{$addr})
2454 . " '$value{$addr}';";
2455 if (! defined $standard_form{$addr}) {
2456 $return .= "(type=$type{$addr})";
2457 }
2458 elsif ($standard_form{$addr} ne $value{$addr}) {
2459 $return .= "(standard '$standard_form{$addr}')";
2460 }
2461 return $return;
2462 }
2463} # End closure
2464
2465package _Range_List_Base;
2466
2467# Base class for range lists. A range list is simply an ordered list of
2468# ranges, so that the ranges with the lowest starting numbers are first in it.
2469#
2470# When a new range is added that is adjacent to an existing range that has the
2471# same value and type, it merges with it to form a larger range.
2472#
2473# Ranges generally do not overlap, except that there can be multiple entries
2474# of single code point ranges. This is because of NameAliases.txt.
2475#
2476# In this program, there is a standard value such that if two different
2477# values, have the same standard value, they are considered equivalent. This
2478# value was chosen so that it gives correct results on Unicode data
2479
2480# There are a number of methods to manipulate range lists, and some operators
2481# are overloaded to handle them.
2482
2483# Because of the slowness of pure Perl objaddr() on miniperl, and measurements
2484# showing this package was using a lot of real time calculating that, the code
2485# was changed to only calculate it once per call stack. This is done by
2486# consistently using the package variable $addr in routines, and only calling
2487# objaddr() if it isn't defined, and setting that to be local, so that callees
2488# will have it already. It would be a good thing to change this. XXX
2489
2490sub trace { return main::trace(@_); }
2491
2492{ # Closure
2493
2494 our $addr;
2495
2496 main::setup_package();
2497
2498 my %ranges;
2499 # The list of ranges
2500 main::set_access('ranges', \%ranges, 'readable_array');
2501
2502 my %max;
2503 # The highest code point in the list. This was originally a method, but
2504 # actual measurements said it was used a lot.
2505 main::set_access('max', \%max, 'r');
2506
2507 my %each_range_iterator;
2508 # Iterator position for each_range()
2509 main::set_access('each_range_iterator', \%each_range_iterator);
2510
2511 my %owner_name_of;
2512 # Name of parent this is attached to, if any. Solely for better error
2513 # messages.
2514 main::set_access('owner_name_of', \%owner_name_of, 'p_r');
2515
2516 my %_search_ranges_cache;
2517 # A cache of the previous result from _search_ranges(), for better
2518 # performance
2519 main::set_access('_search_ranges_cache', \%_search_ranges_cache);
2520
2521 sub new {
2522 my $class = shift;
2523 my %args = @_;
2524
2525 # Optional initialization data for the range list.
2526 my $initialize = delete $args{'Initialize'};
2527
2528 my $self;
2529
2530 # Use _union() to initialize. _union() returns an object of this
2531 # class, which means that it will call this constructor recursively.
2532 # But it won't have this $initialize parameter so that it won't
2533 # infinitely loop on this.
2534 return _union($class, $initialize, %args) if defined $initialize;
2535
2536 $self = bless \do { my $anonymous_scalar }, $class;
2537 local $addr = main::objaddr($self);
2538
2539 # Optional parent object, only for debug info.
2540 $owner_name_of{$addr} = delete $args{'Owner'};
2541 $owner_name_of{$addr} = "" if ! defined $owner_name_of{$addr};
2542
2543 # Stringify, in case it is an object.
2544 $owner_name_of{$addr} = "$owner_name_of{$addr}";
2545
2546 # This is used only for error messages, and so a colon is added
2547 $owner_name_of{$addr} .= ": " if $owner_name_of{$addr} ne "";
2548
2549 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
2550
2551 # Max is initialized to a negative value that isn't adjacent to 0,
2552 # for simpler tests
2553 $max{$addr} = -2;
2554
2555 $_search_ranges_cache{$addr} = 0;
2556 $ranges{$addr} = [];
2557
2558 return $self;
2559 }
2560
2561 use overload
2562 fallback => 0,
2563 qw("") => "_operator_stringify",
2564 "." => \&main::_operator_dot,
2565 ;
2566
2567 sub _operator_stringify {
2568 my $self = shift;
2569 local $addr = main::objaddr($self) if !defined $addr;
2570
2571 return "Range_List attached to '$owner_name_of{$addr}'"
2572 if $owner_name_of{$addr};
2573 return "anonymous Range_List " . \$self;
2574 }
2575
2576 sub _union {
2577 # Returns the union of the input code points. It can be called as
2578 # either a constructor or a method. If called as a method, the result
2579 # will be a new() instance of the calling object, containing the union
2580 # of that object with the other parameter's code points; if called as
2581 # a constructor, the first parameter gives the class the new object
2582 # should be, and the second parameter gives the code points to go into
2583 # it.
2584 # In either case, there are two parameters looked at by this routine;
2585 # any additional parameters are passed to the new() constructor.
2586 #
2587 # The code points can come in the form of some object that contains
2588 # ranges, and has a conventionally named method to access them; or
2589 # they can be an array of individual code points (as integers); or
2590 # just a single code point.
2591 #
2592 # If they are ranges, this routine doesn't make any effort to preserve
2593 # the range values of one input over the other. Therefore this base
2594 # class should not allow _union to be called from other than
2595 # initialization code, so as to prevent two tables from being added
2596 # together where the range values matter. The general form of this
2597 # routine therefore belongs in a derived class, but it was moved here
2598 # to avoid duplication of code. The failure to overload this in this
2599 # class keeps it safe.
2600 #
2601
2602 my $self;
2603 my @args; # Arguments to pass to the constructor
2604
2605 my $class = shift;
2606
2607 # If a method call, will start the union with the object itself, and
2608 # the class of the new object will be the same as self.
2609 if (ref $class) {
2610 $self = $class;
2611 $class = ref $self;
2612 push @args, $self;
2613 }
2614
2615 # Add the other required parameter.
2616 push @args, shift;
2617 # Rest of parameters are passed on to the constructor
2618
2619 # Accumulate all records from both lists.
2620 my @records;
2621 for my $arg (@args) {
2622 #local $to_trace = 0 if main::DEBUG;
2623 trace "argument = $arg" if main::DEBUG && $to_trace;
2624 if (! defined $arg) {
2625 my $message = "";
2626 if (defined $self) {
2627 $message .= $owner_name_of{main::objaddr $self};
2628 }
2629 Carp::my_carp_bug($message .= "Undefined argument to _union. No union done.");
2630 return;
2631 }
2632 $arg = [ $arg ] if ! ref $arg;
2633 my $type = ref $arg;
2634 if ($type eq 'ARRAY') {
2635 foreach my $element (@$arg) {
2636 push @records, Range->new($element, $element);
2637 }
2638 }
2639 elsif ($arg->isa('Range')) {
2640 push @records, $arg;
2641 }
2642 elsif ($arg->can('ranges')) {
2643 push @records, $arg->ranges;
2644 }
2645 else {
2646 my $message = "";
2647 if (defined $self) {
2648 $message .= $owner_name_of{main::objaddr $self};
2649 }
2650 Carp::my_carp_bug($message . "Cannot take the union of a $type. No union done.");
2651 return;
2652 }
2653 }
2654
2655 # Sort with the range containing the lowest ordinal first, but if
2656 # two ranges start at the same code point, sort with the bigger range
2657 # of the two first, because it takes fewer cycles.
2658 @records = sort { ($a->start <=> $b->start)
2659 or
2660 # if b is shorter than a, b->end will be
2661 # less than a->end, and we want to select
2662 # a, so want to return -1
2663 ($b->end <=> $a->end)
2664 } @records;
2665
2666 my $new = $class->new(@_);
2667
2668 # Fold in records so long as they add new information.
2669 for my $set (@records) {
2670 my $start = $set->start;
2671 my $end = $set->end;
2672 my $value = $set->value;
2673 if ($start > $new->max) {
2674 $new->_add_delete('+', $start, $end, $value);
2675 }
2676 elsif ($end > $new->max) {
2677 $new->_add_delete('+', $new->max +1, $end, $value);
2678 }
2679 }
2680
2681 return $new;
2682 }
2683
2684 sub range_count { # Return the number of ranges in the range list
2685 my $self = shift;
2686 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2687
2688 local $addr = main::objaddr($self) if ! defined $addr;
2689
2690 return scalar @{$ranges{$addr}};
2691 }
2692
2693 sub min {
2694 # Returns the minimum code point currently in the range list, or if
2695 # the range list is empty, 2 beyond the max possible. This is a
2696 # method because used so rarely, that not worth saving between calls,
2697 # and having to worry about changing it as ranges are added and
2698 # deleted.
2699
2700 my $self = shift;
2701 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2702
2703 local $addr = main::objaddr($self) if ! defined $addr;
2704
2705 # If the range list is empty, return a large value that isn't adjacent
2706 # to any that could be in the range list, for simpler tests
2707 return $LAST_UNICODE_CODEPOINT + 2 unless scalar @{$ranges{$addr}};
2708 return $ranges{$addr}->[0]->start;
2709 }
2710
2711 sub contains {
2712 # Boolean: Is argument in the range list? If so returns $i such that:
2713 # range[$i]->end < $codepoint <= range[$i+1]->end
2714 # which is one beyond what you want; this is so that the 0th range
2715 # doesn't return false
2716 my $self = shift;
2717 my $codepoint = shift;
2718 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2719
2720 local $addr = main::objaddr $self if ! defined $addr;
2721
2722 my $i = $self->_search_ranges($codepoint);
2723 return 0 unless defined $i;
2724
2725 # The search returns $i, such that
2726 # range[$i-1]->end < $codepoint <= range[$i]->end
2727 # So is in the table if and only iff it is at least the start position
2728 # of range $i.
2729 return 0 if $ranges{$addr}->[$i]->start > $codepoint;
2730 return $i + 1;
2731 }
2732
2733 sub value_of {
2734 # Returns the value associated with the code point, undef if none
2735
2736 my $self = shift;
2737 my $codepoint = shift;
2738 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2739
2740 local $addr = main::objaddr $self if ! defined $addr;
2741
2742 my $i = $self->contains($codepoint);
2743 return unless $i;
2744
2745 # contains() returns 1 beyond where we should look
2746 return $ranges{$addr}->[$i-1]->value;
2747 }
2748
2749 sub _search_ranges {
2750 # Find the range in the list which contains a code point, or where it
2751 # should go if were to add it. That is, it returns $i, such that:
2752 # range[$i-1]->end < $codepoint <= range[$i]->end
2753 # Returns undef if no such $i is possible (e.g. at end of table), or
2754 # if there is an error.
2755
2756 my $self = shift;
2757 my $code_point = shift;
2758 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2759
2760 local $addr = main::objaddr $self if ! defined $addr;
2761
2762 return if $code_point > $max{$addr};
2763 my $r = $ranges{$addr}; # The current list of ranges
2764 my $range_list_size = scalar @$r;
2765 my $i;
2766
2767 use integer; # want integer division
2768
2769 # Use the cached result as the starting guess for this one, because,
2770 # an experiment on 5.1 showed that 90% of the time the cache was the
2771 # same as the result on the next call (and 7% it was one less).
2772 $i = $_search_ranges_cache{$addr};
2773 $i = 0 if $i >= $range_list_size; # Reset if no longer valid (prob.
2774 # from an intervening deletion
2775 #local $to_trace = 1 if main::DEBUG;
2776 trace "previous \$i is still valid: $i" if main::DEBUG && $to_trace && $code_point <= $r->[$i]->end && ($i == 0 || $r->[$i-1]->end < $code_point);
2777 return $i if $code_point <= $r->[$i]->end
2778 && ($i == 0 || $r->[$i-1]->end < $code_point);
2779
2780 # Here the cache doesn't yield the correct $i. Try adding 1.
2781 if ($i < $range_list_size - 1
2782 && $r->[$i]->end < $code_point &&
2783 $code_point <= $r->[$i+1]->end)
2784 {
2785 $i++;
2786 trace "next \$i is correct: $i" if main::DEBUG && $to_trace;
2787 $_search_ranges_cache{$addr} = $i;
2788 return $i;
2789 }
2790
2791 # Here, adding 1 also didn't work. We do a binary search to
2792 # find the correct position, starting with current $i
2793 my $lower = 0;
2794 my $upper = $range_list_size - 1;
2795 while (1) {
2796 trace "top of loop i=$i:", sprintf("%04X", $r->[$lower]->start), "[$lower] .. ", sprintf("%04X", $r->[$i]->start), "[$i] .. ", sprintf("%04X", $r->[$upper]->start), "[$upper]" if main::DEBUG && $to_trace;
2797
2798 if ($code_point <= $r->[$i]->end) {
2799
2800 # Here we have met the upper constraint. We can quit if we
2801 # also meet the lower one.
2802 last if $i == 0 || $r->[$i-1]->end < $code_point;
2803
2804 $upper = $i; # Still too high.
2805
2806 }
2807 else {
2808
2809 # Here, $r[$i]->end < $code_point, so look higher up.
2810 $lower = $i;
2811 }
2812
2813 # Split search domain in half to try again.
2814 my $temp = ($upper + $lower) / 2;
2815
2816 # No point in continuing unless $i changes for next time
2817 # in the loop.
2818 if ($temp == $i) {
2819
2820 # We can't reach the highest element because of the averaging.
2821 # So if one below the upper edge, force it there and try one
2822 # more time.
2823 if ($i == $range_list_size - 2) {
2824
2825 trace "Forcing to upper edge" if main::DEBUG && $to_trace;
2826 $i = $range_list_size - 1;
2827
2828 # Change $lower as well so if fails next time through,
2829 # taking the average will yield the same $i, and we will
2830 # quit with the error message just below.
2831 $lower = $i;
2832 next;
2833 }
2834 Carp::my_carp_bug("$owner_name_of{$addr}Can't find where the range ought to go. No action taken.");
2835 return;
2836 }
2837 $i = $temp;
2838 } # End of while loop
2839
2840 if (main::DEBUG && $to_trace) {
2841 trace 'i-1=[', $i-1, ']', $r->[$i-1] if $i;
2842 trace "i= [ $i ]", $r->[$i];
2843 trace 'i+1=[', $i+1, ']', $r->[$i+1] if $i < $range_list_size - 1;
2844 }
2845
2846 # Here we have found the offset. Cache it as a starting point for the
2847 # next call.
2848 $_search_ranges_cache{$addr} = $i;
2849 return $i;
2850 }
2851
2852 sub _add_delete {
2853 # Add, replace or delete ranges to or from a list. The $type
2854 # parameter gives which:
2855 # '+' => insert or replace a range, returning a list of any changed
2856 # ranges.
2857 # '-' => delete a range, returning a list of any deleted ranges.
2858 #
2859 # The next three parameters give respectively the start, end, and
2860 # value associated with the range. 'value' should be null unless the
2861 # operation is '+';
2862 #
2863 # The range list is kept sorted so that the range with the lowest
2864 # starting position is first in the list, and generally, adjacent
2865 # ranges with the same values are merged into single larger one (see
2866 # exceptions below).
2867 #
2868 # There are more parameters, all are key => value pairs:
2869 # Type gives the type of the value. It is only valid for '+'.
2870 # All ranges have types; if this parameter is omitted, 0 is
2871 # assumed. Ranges with type 0 are assumed to obey the
2872 # Unicode rules for casing, etc; ranges with other types are
2873 # not. Otherwise, the type is arbitrary, for the caller's
2874 # convenience, and looked at only by this routine to keep
2875 # adjacent ranges of different types from being merged into
2876 # a single larger range, and when Replace =>
2877 # $IF_NOT_EQUIVALENT is specified (see just below).
2878 # Replace determines what to do if the range list already contains
2879 # ranges which coincide with all or portions of the input
2880 # range. It is only valid for '+':
2881 # => $NO means that the new value is not to replace
2882 # any existing ones, but any empty gaps of the
2883 # range list coinciding with the input range
2884 # will be filled in with the new value.
2885 # => $UNCONDITIONALLY means to replace the existing values with
2886 # this one unconditionally. However, if the
2887 # new and old values are identical, the
2888 # replacement is skipped to save cycles
2889 # => $IF_NOT_EQUIVALENT means to replace the existing values
2890 # with this one if they are not equivalent.
2891 # Ranges are equivalent if their types are the
2892 # same, and they are the same string, or if
2893 # both are type 0 ranges, if their Unicode
2894 # standard forms are identical. In this last
2895 # case, the routine chooses the more "modern"
2896 # one to use. This is because some of the
2897 # older files are formatted with values that
2898 # are, for example, ALL CAPs, whereas the
2899 # derived files have a more modern style,
2900 # which looks better. By looking for this
2901 # style when the pre-existing and replacement
2902 # standard forms are the same, we can move to
2903 # the modern style
2904 # => $MULTIPLE means that if this range duplicates an
2905 # existing one, but has a different value,
2906 # don't replace the existing one, but insert
2907 # this, one so that the same range can occur
2908 # multiple times.
2909 # => anything else is the same as => $IF_NOT_EQUIVALENT
2910 #
2911 # "same value" means identical for type-0 ranges, and it means having
2912 # the same standard forms for non-type-0 ranges.
2913
2914 return Carp::carp_too_few_args(\@_, 5) if main::DEBUG && @_ < 5;
2915
2916 my $self = shift;
2917 my $operation = shift; # '+' for add/replace; '-' for delete;
2918 my $start = shift;
2919 my $end = shift;
2920 my $value = shift;
2921
2922 my %args = @_;
2923
2924 $value = "" if not defined $value; # warning: $value can be "0"
2925
2926 my $replace = delete $args{'Replace'};
2927 $replace = $IF_NOT_EQUIVALENT unless defined $replace;
2928
2929 my $type = delete $args{'Type'};
2930 $type = 0 unless defined $type;
2931
2932 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
2933
2934 local $addr = main::objaddr($self) if ! defined $addr;
2935
2936 if ($operation ne '+' && $operation ne '-') {
2937 Carp::my_carp_bug("$owner_name_of{$addr}First parameter to _add_delete must be '+' or '-'. No action taken.");
2938 return;
2939 }
2940 unless (defined $start && defined $end) {
2941 Carp::my_carp_bug("$owner_name_of{$addr}Undefined start and/or end to _add_delete. No action taken.");
2942 return;
2943 }
2944 unless ($end >= $start) {
2945 Carp::my_carp_bug("$owner_name_of{$addr}End of range (" . sprintf("%04X", $end) . ") must not be before start (" . sprintf("%04X", $start) . "). No action taken.");
2946 return;
2947 }
2948 #local $to_trace = 1 if main::DEBUG;
2949
2950 if ($operation eq '-') {
2951 if ($replace != $IF_NOT_EQUIVALENT) {
2952 Carp::my_carp_bug("$owner_name_of{$addr}Replace => \$IF_NOT_EQUIVALENT is required when deleting a range from a range list. Assuming Replace => \$IF_NOT_EQUIVALENT.");
2953 $replace = $IF_NOT_EQUIVALENT;
2954 }
2955 if ($type) {
2956 Carp::my_carp_bug("$owner_name_of{$addr}Type => 0 is required when deleting a range from a range list. Assuming Type => 0.");
2957 $type = 0;
2958 }
2959 if ($value ne "") {
2960 Carp::my_carp_bug("$owner_name_of{$addr}Value => \"\" is required when deleting a range from a range list. Assuming Value => \"\".");
2961 $value = "";
2962 }
2963 }
2964
2965 my $r = $ranges{$addr}; # The current list of ranges
2966 my $range_list_size = scalar @$r; # And its size
2967 my $max = $max{$addr}; # The current high code point in
2968 # the list of ranges
2969
2970 # Do a special case requiring fewer machine cycles when the new range
2971 # starts after the current highest point. The Unicode input data is
2972 # structured so this is common.
2973 if ($start > $max) {
2974
2975 trace "$owner_name_of{$addr} $operation", sprintf("%04X", $start) . '..' . sprintf("%04X", $end) . " ($value) type=$type" if main::DEBUG && $to_trace;
2976 return if $operation eq '-'; # Deleting a non-existing range is a
2977 # no-op
2978
2979 # If the new range doesn't logically extend the current final one
2980 # in the range list, create a new range at the end of the range
2981 # list. (max cleverly is initialized to a negative number not
2982 # adjacent to 0 if the range list is empty, so even adding a range
2983 # to an empty range list starting at 0 will have this 'if'
2984 # succeed.)
2985 if ($start > $max + 1 # non-adjacent means can't extend.
2986 || @{$r}[-1]->value ne $value # values differ, can't extend.
2987 || @{$r}[-1]->type != $type # types differ, can't extend.
2988 ) {
2989 push @$r, Range->new($start, $end,
2990 Value => $value,
2991 Type => $type);
2992 }
2993 else {
2994
2995 # Here, the new range starts just after the current highest in
2996 # the range list, and they have the same type and value.
2997 # Extend the current range to incorporate the new one.
2998 @{$r}[-1]->set_end($end);
2999 }
3000
3001 # This becomes the new maximum.
3002 $max{$addr} = $end;
3003
3004 return;
3005 }
3006 #local $to_trace = 0 if main::DEBUG;
3007
3008 trace "$owner_name_of{$addr} $operation", sprintf("%04X", $start) . '..' . sprintf("%04X", $end) . " ($value) replace=$replace" if main::DEBUG && $to_trace;
3009
3010 # Here, the input range isn't after the whole rest of the range list.
3011 # Most likely 'splice' will be needed. The rest of the routine finds
3012 # the needed splice parameters, and if necessary, does the splice.
3013 # First, find the offset parameter needed by the splice function for
3014 # the input range. Note that the input range may span multiple
3015 # existing ones, but we'll worry about that later. For now, just find
3016 # the beginning. If the input range is to be inserted starting in a
3017 # position not currently in the range list, it must (obviously) come
3018 # just after the range below it, and just before the range above it.
3019 # Slightly less obviously, it will occupy the position currently
3020 # occupied by the range that is to come after it. More formally, we
3021 # are looking for the position, $i, in the array of ranges, such that:
3022 #
3023 # r[$i-1]->start <= r[$i-1]->end < $start < r[$i]->start <= r[$i]->end
3024 #
3025 # (The ordered relationships within existing ranges are also shown in
3026 # the equation above). However, if the start of the input range is
3027 # within an existing range, the splice offset should point to that
3028 # existing range's position in the list; that is $i satisfies a
3029 # somewhat different equation, namely:
3030 #
3031 #r[$i-1]->start <= r[$i-1]->end < r[$i]->start <= $start <= r[$i]->end
3032 #
3033 # More briefly, $start can come before or after r[$i]->start, and at
3034 # this point, we don't know which it will be. However, these
3035 # two equations share these constraints:
3036 #
3037 # r[$i-1]->end < $start <= r[$i]->end
3038 #
3039 # And that is good enough to find $i.
3040
3041 my $i = $self->_search_ranges($start);
3042 if (! defined $i) {
3043 Carp::my_carp_bug("Searching $self for range beginning with $start unexpectedly returned undefined. Operation '$operation' not performed");
3044 return;
3045 }
3046
3047 # The search function returns $i such that:
3048 #
3049 # r[$i-1]->end < $start <= r[$i]->end
3050 #
3051 # That means that $i points to the first range in the range list
3052 # that could possibly be affected by this operation. We still don't
3053 # know if the start of the input range is within r[$i], or if it
3054 # points to empty space between r[$i-1] and r[$i].
3055 trace "[$i] is the beginning splice point. Existing range there is ", $r->[$i] if main::DEBUG && $to_trace;
3056
3057 # Special case the insertion of data that is not to replace any
3058 # existing data.
3059 if ($replace == $NO) { # If $NO, has to be operation '+'
3060 #local $to_trace = 1 if main::DEBUG;
3061 trace "Doesn't replace" if main::DEBUG && $to_trace;
3062
3063 # Here, the new range is to take effect only on those code points
3064 # that aren't already in an existing range. This can be done by
3065 # looking through the existing range list and finding the gaps in
3066 # the ranges that this new range affects, and then calling this
3067 # function recursively on each of those gaps, leaving untouched
3068 # anything already in the list. Gather up a list of the changed
3069 # gaps first so that changes to the internal state as new ranges
3070 # are added won't be a problem.
3071 my @gap_list;
3072
3073 # First, if the starting point of the input range is outside an
3074 # existing one, there is a gap from there to the beginning of the
3075 # existing range -- add a span to fill the part that this new
3076 # range occupies
3077 if ($start < $r->[$i]->start) {
3078 push @gap_list, Range->new($start,
3079 main::min($end,
3080 $r->[$i]->start - 1),
3081 Type => $type);
3082 trace "gap before $r->[$i] [$i], will add", $gap_list[-1] if main::DEBUG && $to_trace;
3083 }
3084
3085 # Then look through the range list for other gaps until we reach
3086 # the highest range affected by the input one.
3087 my $j;
3088 for ($j = $i+1; $j < $range_list_size; $j++) {
3089 trace "j=[$j]", $r->[$j] if main::DEBUG && $to_trace;
3090 last if $end < $r->[$j]->start;
3091
3092 # If there is a gap between when this range starts and the
3093 # previous one ends, add a span to fill it. Note that just
3094 # because there are two ranges doesn't mean there is a
3095 # non-zero gap between them. It could be that they have
3096 # different values or types
3097 if ($r->[$j-1]->end + 1 != $r->[$j]->start) {
3098 push @gap_list,
3099 Range->new($r->[$j-1]->end + 1,
3100 $r->[$j]->start - 1,
3101 Type => $type);
3102 trace "gap between $r->[$j-1] and $r->[$j] [$j], will add: $gap_list[-1]" if main::DEBUG && $to_trace;
3103 }
3104 }
3105
3106 # Here, we have either found an existing range in the range list,
3107 # beyond the area affected by the input one, or we fell off the
3108 # end of the loop because the input range affects the whole rest
3109 # of the range list. In either case, $j is 1 higher than the
3110 # highest affected range. If $j == $i, it means that there are no
3111 # affected ranges, that the entire insertion is in the gap between
3112 # r[$i-1], and r[$i], which we already have taken care of before
3113 # the loop.
3114 # On the other hand, if there are affected ranges, it might be
3115 # that there is a gap that needs filling after the final such
3116 # range to the end of the input range
3117 if ($r->[$j-1]->end < $end) {
3118 push @gap_list, Range->new(main::max($start,
3119 $r->[$j-1]->end + 1),
3120 $end,
3121 Type => $type);
3122 trace "gap after $r->[$j-1], will add $gap_list[-1]" if main::DEBUG && $to_trace;
3123 }
3124
3125 # Call recursively to fill in all the gaps.
3126 foreach my $gap (@gap_list) {
3127 $self->_add_delete($operation,
3128 $gap->start,
3129 $gap->end,
3130 $value,
3131 Type => $type);
3132 }
3133
3134 return;
3135 }
3136
3137 # Here, we have taken care of the case where $replace is $NO, which
3138 # means that whatever action we now take is done unconditionally. It
3139 # still could be that this call will result in a no-op, if duplicates
3140 # aren't allowed, and we are inserting a range that merely duplicates
3141 # data already in the range list; or also if deleting a non-existent
3142 # range.
3143 # $i still points to the first potential affected range. Now find the
3144 # highest range affected, which will determine the length parameter to
3145 # splice. (The input range can span multiple existing ones.) While
3146 # we are looking through the range list, see also if this is an
3147 # insertion that will change the values of at least one of the
3148 # affected ranges. We don't need to do this check unless this is an
3149 # insertion of non-multiples, and also since this is a boolean, we
3150 # don't need to do it if have already determined that it will make a
3151 # change; just unconditionally change them. $cdm is created to be 1
3152 # if either of these is true. (The 'c' in the name comes from below)
3153 my $cdm = ($operation eq '-' || $replace == $MULTIPLE);
3154 my $j; # This will point to the highest affected range
3155
3156 # For non-zero types, the standard form is the value itself;
3157 my $standard_form = ($type) ? $value : main::standardize($value);
3158
3159 for ($j = $i; $j < $range_list_size; $j++) {
3160 trace "Looking for highest affected range; the one at $j is ", $r->[$j] if main::DEBUG && $to_trace;
3161
3162 # If find a range that it doesn't overlap into, we can stop
3163 # searching
3164 last if $end < $r->[$j]->start;
3165
3166 # Here, overlaps the range at $j. If the value's don't match,
3167 # and this is supposedly an insertion, it becomes a change
3168 # instead. This is what the 'c' stands for in $cdm.
3169 if (! $cdm) {
3170 if ($r->[$j]->standard_form ne $standard_form) {
3171 $cdm = 1;
3172 }
3173 else {
3174
3175 # Here, the two values are essentially the same. If the
3176 # two are actually identical, replacing wouldn't change
3177 # anything so skip it.
3178 my $pre_existing = $r->[$j]->value;
3179 if ($pre_existing ne $value) {
3180
3181 # Here the new and old standardized values are the
3182 # same, but the non-standardized values aren't. If
3183 # replacing unconditionally, then replace
3184 if( $replace == $UNCONDITIONALLY) {
3185 $cdm = 1;
3186 }
3187 else {
3188
3189 # Here, are replacing conditionally. Decide to
3190 # replace or not based on which appears to look
3191 # the "nicest". If one is mixed case and the
3192 # other isn't, choose the mixed case one.
3193 my $new_mixed = $value =~ /[A-Z]/
3194 && $value =~ /[a-z]/;
3195 my $old_mixed = $pre_existing =~ /[A-Z]/
3196 && $pre_existing =~ /[a-z]/;
3197
3198 if ($old_mixed != $new_mixed) {
3199 $cdm = 1 if $new_mixed;
3200 if (main::DEBUG && $to_trace) {
3201 if ($cdm) {
3202 trace "Replacing $pre_existing with $value";
3203 }
3204 else {
3205 trace "Retaining $pre_existing over $value";
3206 }
3207 }
3208 }
3209 else {
3210
3211 # Here casing wasn't different between the two.
3212 # If one has hyphens or underscores and the
3213 # other doesn't, choose the one with the
3214 # punctuation.
3215 my $new_punct = $value =~ /[-_]/;
3216 my $old_punct = $pre_existing =~ /[-_]/;
3217
3218 if ($old_punct != $new_punct) {
3219 $cdm = 1 if $new_punct;
3220 if (main::DEBUG && $to_trace) {
3221 if ($cdm) {
3222 trace "Replacing $pre_existing with $value";
3223 }
3224 else {
3225 trace "Retaining $pre_existing over $value";
3226 }
3227 }
3228 } # else existing one is just as "good";
3229 # retain it to save cycles.
3230 }
3231 }
3232 }
3233 }
3234 }
3235 } # End of loop looking for highest affected range.
3236
3237 # Here, $j points to one beyond the highest range that this insertion
3238 # affects (hence to beyond the range list if that range is the final
3239 # one in the range list).
3240
3241 # The splice length is all the affected ranges. Get it before
3242 # subtracting, for efficiency, so we don't have to later add 1.
3243 my $length = $j - $i;
3244
3245 $j--; # $j now points to the highest affected range.
3246 trace "Final affected range is $j: $r->[$j]" if main::DEBUG && $to_trace;
3247
3248 # If inserting a multiple record, this is where it goes, after all the
3249 # existing ones for this range. This implies an insertion, and no
3250 # change to any existing ranges. Note that $j can be -1 if this new
3251 # range doesn't actually duplicate any existing, and comes at the
3252 # beginning of the list, in which case we can handle it like any other
3253 # insertion, and is easier to do so.
3254 if ($replace == $MULTIPLE && $j >= 0) {
3255
3256 # This restriction could be remedied with a little extra work, but
3257 # it won't hopefully ever be necessary
3258 if ($r->[$j]->start != $r->[$j]->end) {
3259 Carp::my_carp_bug("$owner_name_of{$addr}Can't cope with adding a multiple when the other range ($r->[$j]) contains more than one code point. No action taken.");
3260 return;
3261 }
3262
3263 # Don't add an exact duplicate, as it isn't really a multiple
3264 return if $value eq $r->[$j]->value && $type eq $r->[$j]->type;
3265
3266 trace "Adding multiple record at $j+1 with $start..$end, $value" if main::DEBUG && $to_trace;
3267 my @return = splice @$r,
3268 $j+1,
3269 0,
3270 Range->new($start,
3271 $end,
3272 Value => $value,
3273 Type => $type);
3274 if (main::DEBUG && $to_trace) {
3275 trace "After splice:";
3276 trace 'j-2=[', $j-2, ']', $r->[$j-2] if $j >= 2;
3277 trace 'j-1=[', $j-1, ']', $r->[$j-1] if $j >= 1;
3278 trace "j =[", $j, "]", $r->[$j] if $j >= 0;
3279 trace 'j+1=[', $j+1, ']', $r->[$j+1] if $j < @$r - 1;
3280 trace 'j+2=[', $j+2, ']', $r->[$j+2] if $j < @$r - 2;
3281 trace 'j+3=[', $j+3, ']', $r->[$j+3] if $j < @$r - 3;
3282 }
3283 return @return;
3284 }
3285
3286 # Here, have taken care of $NO and $MULTIPLE replaces.
3287 # $j points to the highest affected range. But it can be < $i or even
3288 # -1. These happen only if the insertion is entirely in the gap
3289 # between r[$i-1] and r[$i]. Here's why: j < i means that the j loop
3290 # above exited first time through with $end < $r->[$i]->start. (And
3291 # then we subtracted one from j) This implies also that $start <
3292 # $r->[$i]->start, but we know from above that $r->[$i-1]->end <
3293 # $start, so the entire input range is in the gap.
3294 if ($j < $i) {
3295
3296 # Here the entire input range is in the gap before $i.
3297
3298 if (main::DEBUG && $to_trace) {
3299 if ($i) {
3300 trace "Entire range is between $r->[$i-1] and $r->[$i]";
3301 }
3302 else {
3303 trace "Entire range is before $r->[$i]";
3304 }
3305 }
3306 return if $operation ne '+'; # Deletion of a non-existent range is
3307 # a no-op
3308 }
3309 else {
3310
3311 # Here the entire input range is not in the gap before $i. There
3312 # is an affected one, and $j points to the highest such one.
3313
3314 # At this point, here is the situation:
3315 # This is not an insertion of a multiple, nor of tentative ($NO)
3316 # data.
3317 # $i points to the first element in the current range list that
3318 # may be affected by this operation. In fact, we know
3319 # that the range at $i is affected because we are in
3320 # the else branch of this 'if'
3321 # $j points to the highest affected range.
3322 # In other words,
3323 # r[$i-1]->end < $start <= r[$i]->end
3324 # And:
3325 # r[$i-1]->end < $start <= $end <= r[$j]->end
3326 #
3327 # Also:
3328 # $cdm is a boolean which is set true if and only if this is a
3329 # change or deletion (multiple was handled above). In
3330 # other words, it could be renamed to be just $cd.
3331
3332 # We now have enough information to decide if this call is a no-op
3333 # or not. It is a no-op if it is a deletion of a non-existent
3334 # range, or an insertion of already existing data.
3335
3336 if (main::DEBUG && $to_trace && ! $cdm
3337 && $i == $j
3338 && $start >= $r->[$i]->start)
3339 {
3340 trace "no-op";
3341 }
3342 return if ! $cdm # change or delete => not no-op
3343 && $i == $j # more than one affected range => not no-op
3344
3345 # Here, r[$i-1]->end < $start <= $end <= r[$i]->end
3346 # Further, $start and/or $end is >= r[$i]->start
3347 # The test below hence guarantees that
3348 # r[$i]->start < $start <= $end <= r[$i]->end
3349 # This means the input range is contained entirely in
3350 # the one at $i, so is a no-op
3351 && $start >= $r->[$i]->start;
3352 }
3353
3354 # Here, we know that some action will have to be taken. We have
3355 # calculated the offset and length (though adjustments may be needed)
3356 # for the splice. Now start constructing the replacement list.
3357 my @replacement;
3358 my $splice_start = $i;
3359
3360 my $extends_below;
3361 my $extends_above;
3362
3363 # See if should extend any adjacent ranges.
3364 if ($operation eq '-') { # Don't extend deletions
3365 $extends_below = $extends_above = 0;
3366 }
3367 else { # Here, should extend any adjacent ranges. See if there are
3368 # any.
3369 $extends_below = ($i > 0
3370 # can't extend unless adjacent
3371 && $r->[$i-1]->end == $start -1
3372 # can't extend unless are same standard value
3373 && $r->[$i-1]->standard_form eq $standard_form
3374 # can't extend unless share type
3375 && $r->[$i-1]->type == $type);
3376 $extends_above = ($j+1 < $range_list_size
3377 && $r->[$j+1]->start == $end +1
3378 && $r->[$j+1]->standard_form eq $standard_form
3379 && $r->[$j-1]->type == $type);
3380 }
3381 if ($extends_below && $extends_above) { # Adds to both
3382 $splice_start--; # start replace at element below
3383 $length += 2; # will replace on both sides
3384 trace "Extends both below and above ranges" if main::DEBUG && $to_trace;
3385
3386 # The result will fill in any gap, replacing both sides, and
3387 # create one large range.
3388 @replacement = Range->new($r->[$i-1]->start,
3389 $r->[$j+1]->end,
3390 Value => $value,
3391 Type => $type);
3392 }
3393 else {
3394
3395 # Here we know that the result won't just be the conglomeration of
3396 # a new range with both its adjacent neighbors. But it could
3397 # extend one of them.
3398
3399 if ($extends_below) {
3400
3401 # Here the new element adds to the one below, but not to the
3402 # one above. If inserting, and only to that one range, can
3403 # just change its ending to include the new one.
3404 if ($length == 0 && ! $cdm) {
3405 $r->[$i-1]->set_end($end);
3406 trace "inserted range extends range to below so it is now $r->[$i-1]" if main::DEBUG && $to_trace;
3407 return;
3408 }
3409 else {
3410 trace "Changing inserted range to start at ", sprintf("%04X", $r->[$i-1]->start), " instead of ", sprintf("%04X", $start) if main::DEBUG && $to_trace;
3411 $splice_start--; # start replace at element below
3412 $length++; # will replace the element below
3413 $start = $r->[$i-1]->start;
3414 }
3415 }
3416 elsif ($extends_above) {
3417
3418 # Here the new element adds to the one above, but not below.
3419 # Mirror the code above
3420 if ($length == 0 && ! $cdm) {
3421 $r->[$j+1]->set_start($start);
3422 trace "inserted range extends range to above so it is now $r->[$j+1]" if main::DEBUG && $to_trace;
3423 return;
3424 }
3425 else {
3426 trace "Changing inserted range to end at ", sprintf("%04X", $r->[$j+1]->end), " instead of ", sprintf("%04X", $end) if main::DEBUG && $to_trace;
3427 $length++; # will replace the element above
3428 $end = $r->[$j+1]->end;
3429 }
3430 }
3431
3432 trace "Range at $i is $r->[$i]" if main::DEBUG && $to_trace;
3433
3434 # Finally, here we know there will have to be a splice.
3435 # If the change or delete affects only the highest portion of the
3436 # first affected range, the range will have to be split. The
3437 # splice will remove the whole range, but will replace it by a new
3438 # range containing just the unaffected part. So, in this case,
3439 # add to the replacement list just this unaffected portion.
3440 if (! $extends_below
3441 && $start > $r->[$i]->start && $start <= $r->[$i]->end)
3442 {
3443 push @replacement,
3444 Range->new($r->[$i]->start,
3445 $start - 1,
3446 Value => $r->[$i]->value,
3447 Type => $r->[$i]->type);
3448 }
3449
3450 # In the case of an insert or change, but not a delete, we have to
3451 # put in the new stuff; this comes next.
3452 if ($operation eq '+') {
3453 push @replacement, Range->new($start,
3454 $end,
3455 Value => $value,
3456 Type => $type);
3457 }
3458
3459 trace "Range at $j is $r->[$j]" if main::DEBUG && $to_trace && $j != $i;
3460 #trace "$end >=", $r->[$j]->start, " && $end <", $r->[$j]->end if main::DEBUG && $to_trace;
3461
3462 # And finally, if we're changing or deleting only a portion of the
3463 # highest affected range, it must be split, as the lowest one was.
3464 if (! $extends_above
3465 && $j >= 0 # Remember that j can be -1 if before first
3466 # current element
3467 && $end >= $r->[$j]->start
3468 && $end < $r->[$j]->end)
3469 {
3470 push @replacement,
3471 Range->new($end + 1,
3472 $r->[$j]->end,
3473 Value => $r->[$j]->value,
3474 Type => $r->[$j]->type);
3475 }
3476 }
3477
3478 # And do the splice, as calculated above
3479 if (main::DEBUG && $to_trace) {
3480 trace "replacing $length element(s) at $i with ";
3481 foreach my $replacement (@replacement) {
3482 trace " $replacement";
3483 }
3484 trace "Before splice:";
3485 trace 'i-2=[', $i-2, ']', $r->[$i-2] if $i >= 2;
3486 trace 'i-1=[', $i-1, ']', $r->[$i-1] if $i >= 1;
3487 trace "i =[", $i, "]", $r->[$i];
3488 trace 'i+1=[', $i+1, ']', $r->[$i+1] if $i < @$r - 1;
3489 trace 'i+2=[', $i+2, ']', $r->[$i+2] if $i < @$r - 2;
3490 }
3491
3492 my @return = splice @$r, $splice_start, $length, @replacement;
3493
3494 if (main::DEBUG && $to_trace) {
3495 trace "After splice:";
3496 trace 'i-2=[', $i-2, ']', $r->[$i-2] if $i >= 2;
3497 trace 'i-1=[', $i-1, ']', $r->[$i-1] if $i >= 1;
3498 trace "i =[", $i, "]", $r->[$i];
3499 trace 'i+1=[', $i+1, ']', $r->[$i+1] if $i < @$r - 1;
3500 trace 'i+2=[', $i+2, ']', $r->[$i+2] if $i < @$r - 2;
3501 trace "removed @return";
3502 }
3503
3504 # An actual deletion could have changed the maximum in the list.
3505 # There was no deletion if the splice didn't return something, but
3506 # otherwise recalculate it. This is done too rarely to worry about
3507 # performance.
3508 if ($operation eq '-' && @return) {
3509 $max{$addr} = $r->[-1]->end;
3510 }
3511 return @return;
3512 }
3513
3514 sub reset_each_range { # reset the iterator for each_range();
3515 my $self = shift;
3516 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3517
3518 local $addr = main::objaddr $self if ! defined $addr;
3519
3520 undef $each_range_iterator{$addr};
3521 return;
3522 }
3523
3524 sub each_range {
3525 # Iterate over each range in a range list. Results are undefined if
3526 # the range list is changed during the iteration.
3527
3528 my $self = shift;
3529 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3530
3531 local $addr = main::objaddr($self) if ! defined $addr;
3532
3533 return if $self->is_empty;
3534
3535 $each_range_iterator{$addr} = -1
3536 if ! defined $each_range_iterator{$addr};
3537 $each_range_iterator{$addr}++;
3538 return $ranges{$addr}->[$each_range_iterator{$addr}]
3539 if $each_range_iterator{$addr} < @{$ranges{$addr}};
3540 undef $each_range_iterator{$addr};
3541 return;
3542 }
3543
3544 sub count { # Returns count of code points in range list
3545 my $self = shift;
3546 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3547
3548 local $addr = main::objaddr($self) if ! defined $addr;
3549
3550 my $count = 0;
3551 foreach my $range (@{$ranges{$addr}}) {
3552 $count += $range->end - $range->start + 1;
3553 }
3554 return $count;
3555 }
3556
3557 sub delete_range { # Delete a range
3558 my $self = shift;
3559 my $start = shift;
3560 my $end = shift;
3561
3562 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3563
3564 return $self->_add_delete('-', $start, $end, "");
3565 }
3566
3567 sub is_empty { # Returns boolean as to if a range list is empty
3568 my $self = shift;
3569 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3570
3571 local $addr = main::objaddr($self) if ! defined $addr;
3572 return scalar @{$ranges{$addr}} == 0;
3573 }
3574
3575 sub hash {
3576 # Quickly returns a scalar suitable for separating tables into
3577 # buckets, i.e. it is a hash function of the contents of a table, so
3578 # there are relatively few conflicts.
3579
3580 my $self = shift;
3581 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3582
3583 local $addr = main::objaddr($self) if ! defined $addr;
3584
3585 # These are quickly computable. Return looks like 'min..max;count'
3586 return $self->min . "..$max{$addr};" . scalar @{$ranges{$addr}};
3587 }
3588} # End closure for _Range_List_Base
3589
3590package Range_List;
3591use base '_Range_List_Base';
3592
3593# A Range_List is a range list for match tables; i.e. the range values are
3594# not significant. Thus a number of operations can be safely added to it,
3595# such as inversion, intersection. Note that union is also an unsafe
3596# operation when range values are cared about, and that method is in the base
3597# class, not here. But things are set up so that that method is callable only
3598# during initialization. Only in this derived class, is there an operation
3599# that combines two tables. A Range_Map can thus be used to initialize a
3600# Range_List, and its mappings will be in the list, but are not significant to
3601# this class.
3602
3603sub trace { return main::trace(@_); }
3604
3605{ # Closure
3606
3607 use overload
3608 fallback => 0,
3609 '+' => sub { my $self = shift;
3610 my $other = shift;
3611
3612 return $self->_union($other)
3613 },
3614 '&' => sub { my $self = shift;
3615 my $other = shift;
3616
3617 return $self->_intersect($other, 0);
3618 },
3619 '~' => "_invert",
3620 '-' => "_subtract",
3621 ;
3622
3623 sub _invert {
3624 # Returns a new Range_List that gives all code points not in $self.
3625
3626 my $self = shift;
3627
3628 my $new = Range_List->new;
3629
3630 # Go through each range in the table, finding the gaps between them
3631 my $max = -1; # Set so no gap before range beginning at 0
3632 for my $range ($self->ranges) {
3633 my $start = $range->start;
3634 my $end = $range->end;
3635
3636 # If there is a gap before this range, the inverse will contain
3637 # that gap.
3638 if ($start > $max + 1) {
3639 $new->add_range($max + 1, $start - 1);
3640 }
3641 $max = $end;
3642 }
3643
3644 # And finally, add the gap from the end of the table to the max
3645 # possible code point
3646 if ($max < $LAST_UNICODE_CODEPOINT) {
3647 $new->add_range($max + 1, $LAST_UNICODE_CODEPOINT);
3648 }
3649 return $new;
3650 }
3651
3652 sub _subtract {
3653 # Returns a new Range_List with the argument deleted from it. The
3654 # argument can be a single code point, a range, or something that has
3655 # a range, with the _range_list() method on it returning them
3656
3657 my $self = shift;
3658 my $other = shift;
3659 my $reversed = shift;
3660 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3661
3662 if ($reversed) {
3663 Carp::my_carp_bug("Can't cope with a "
3664 . __PACKAGE__
3665 . " being the second parameter in a '-'. Subtraction ignored.");
3666 return $self;
3667 }
3668
3669 my $new = Range_List->new(Initialize => $self);
3670
3671 if (! ref $other) { # Single code point
3672 $new->delete_range($other, $other);
3673 }
3674 elsif ($other->isa('Range')) {
3675 $new->delete_range($other->start, $other->end);
3676 }
3677 elsif ($other->can('_range_list')) {
3678 foreach my $range ($other->_range_list->ranges) {
3679 $new->delete_range($range->start, $range->end);
3680 }
3681 }
3682 else {
3683 Carp::my_carp_bug("Can't cope with a "
3684 . ref($other)
3685 . " argument to '-'. Subtraction ignored."
3686 );
3687 return $self;
3688 }
3689
3690 return $new;
3691 }
3692
3693 sub _intersect {
3694 # Returns either a boolean giving whether the two inputs' range lists
3695 # intersect (overlap), or a new Range_List containing the intersection
3696 # of the two lists. The optional final parameter being true indicates
3697 # to do the check instead of the intersection.
3698
3699 my $a_object = shift;
3700 my $b_object = shift;
3701 my $check_if_overlapping = shift;
3702 $check_if_overlapping = 0 unless defined $check_if_overlapping;
3703 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3704
3705 if (! defined $b_object) {
3706 my $message = "";
3707 $message .= $a_object->_owner_name_of if defined $a_object;
3708 Carp::my_carp_bug($message .= "Called with undefined value. Intersection not done.");
3709 return;
3710 }
3711
3712 # a & b = !(!a | !b), or in our terminology = ~ ( ~a + -b )
3713 # Thus the intersection could be much more simply be written:
3714 # return ~(~$a_object + ~$b_object);
3715 # But, this is slower, and when taking the inverse of a large
3716 # range_size_1 table, back when such tables were always stored that
3717 # way, it became prohibitively slow, hence the code was changed to the
3718 # below
3719
3720 if ($b_object->isa('Range')) {
3721 $b_object = Range_List->new(Initialize => $b_object,
3722 Owner => $a_object->_owner_name_of);
3723 }
3724 $b_object = $b_object->_range_list if $b_object->can('_range_list');
3725
3726 my @a_ranges = $a_object->ranges;
3727 my @b_ranges = $b_object->ranges;
3728
3729 #local $to_trace = 1 if main::DEBUG;
3730 trace "intersecting $a_object with ", scalar @a_ranges, "ranges and $b_object with", scalar @b_ranges, " ranges" if main::DEBUG && $to_trace;
3731
3732 # Start with the first range in each list
3733 my $a_i = 0;
3734 my $range_a = $a_ranges[$a_i];
3735 my $b_i = 0;
3736 my $range_b = $b_ranges[$b_i];
3737
3738 my $new = __PACKAGE__->new(Owner => $a_object->_owner_name_of)
3739 if ! $check_if_overlapping;
3740
3741 # If either list is empty, there is no intersection and no overlap
3742 if (! defined $range_a || ! defined $range_b) {
3743 return $check_if_overlapping ? 0 : $new;
3744 }
3745 trace "range_a[$a_i]=$range_a; range_b[$b_i]=$range_b" if main::DEBUG && $to_trace;
3746
3747 # Otherwise, must calculate the intersection/overlap. Start with the
3748 # very first code point in each list
3749 my $a = $range_a->start;
3750 my $b = $range_b->start;
3751
3752 # Loop through all the ranges of each list; in each iteration, $a and
3753 # $b are the current code points in their respective lists
3754 while (1) {
3755
3756 # If $a and $b are the same code point, ...
3757 if ($a == $b) {
3758
3759 # it means the lists overlap. If just checking for overlap
3760 # know the answer now,
3761 return 1 if $check_if_overlapping;
3762
3763 # The intersection includes this code point plus anything else
3764 # common to both current ranges.
3765 my $start = $a;
3766 my $end = main::min($range_a->end, $range_b->end);
3767 if (! $check_if_overlapping) {
3768 trace "adding intersection range ", sprintf("%04X", $start) . ".." . sprintf("%04X", $end) if main::DEBUG && $to_trace;
3769 $new->add_range($start, $end);
3770 }
3771
3772 # Skip ahead to the end of the current intersect
3773 $a = $b = $end;
3774
3775 # If the current intersect ends at the end of either range (as
3776 # it must for at least one of them), the next possible one
3777 # will be the beginning code point in it's list's next range.
3778 if ($a == $range_a->end) {
3779 $range_a = $a_ranges[++$a_i];
3780 last unless defined $range_a;
3781 $a = $range_a->start;
3782 }
3783 if ($b == $range_b->end) {
3784 $range_b = $b_ranges[++$b_i];
3785 last unless defined $range_b;
3786 $b = $range_b->start;
3787 }
3788
3789 trace "range_a[$a_i]=$range_a; range_b[$b_i]=$range_b" if main::DEBUG && $to_trace;
3790 }
3791 elsif ($a < $b) {
3792
3793 # Not equal, but if the range containing $a encompasses $b,
3794 # change $a to be the middle of the range where it does equal
3795 # $b, so the next iteration will get the intersection
3796 if ($range_a->end >= $b) {
3797 $a = $b;
3798 }
3799 else {
3800
3801 # Here, the current range containing $a is entirely below
3802 # $b. Go try to find a range that could contain $b.
3803 $a_i = $a_object->_search_ranges($b);
3804
3805 # If no range found, quit.
3806 last unless defined $a_i;
3807
3808 # The search returns $a_i, such that
3809 # range_a[$a_i-1]->end < $b <= range_a[$a_i]->end
3810 # Set $a to the beginning of this new range, and repeat.
3811 $range_a = $a_ranges[$a_i];
3812 $a = $range_a->start;
3813 }
3814 }
3815 else { # Here, $b < $a.
3816
3817 # Mirror image code to the leg just above
3818 if ($range_b->end >= $a) {
3819 $b = $a;
3820 }
3821 else {
3822 $b_i = $b_object->_search_ranges($a);
3823 last unless defined $b_i;
3824 $range_b = $b_ranges[$b_i];
3825 $b = $range_b->start;
3826 }
3827 }
3828 } # End of looping through ranges.
3829
3830 # Intersection fully computed, or now know that there is no overlap
3831 return $check_if_overlapping ? 0 : $new;
3832 }
3833
3834 sub overlaps {
3835 # Returns boolean giving whether the two arguments overlap somewhere
3836
3837 my $self = shift;
3838 my $other = shift;
3839 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3840
3841 return $self->_intersect($other, 1);
3842 }
3843
3844 sub add_range {
3845 # Add a range to the list.
3846
3847 my $self = shift;
3848 my $start = shift;
3849 my $end = shift;
3850 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3851
3852 return $self->_add_delete('+', $start, $end, "");
3853 }
3854
99f78760 3855 my $non_ASCII = (ord('A') != 65); # Assumes test on same platform
99870f4d
KW
3856
3857 sub is_code_point_usable {
3858 # This used only for making the test script. See if the input
3859 # proposed trial code point is one that Perl will handle. If second
3860 # parameter is 0, it won't select some code points for various
3861 # reasons, noted below.
3862
3863 my $code = shift;
3864 my $try_hard = shift;
3865 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3866
3867 return 0 if $code < 0; # Never use a negative
3868
3869 # For non-ASCII, we shun the characters that don't have Perl encoding-
3870 # independent symbols for them. 'A' is such a symbol, so is "\n".
99870f4d
KW
3871 return $try_hard if $non_ASCII
3872 && $code <= 0xFF
3873 && ($code >= 0x7F
3874 || ($code >= 0x0E && $code <= 0x1F)
3875 || ($code >= 0x01 && $code <= 0x06)
37e2e78e 3876 || $code == 0x0B);
99870f4d
KW
3877
3878 # shun null. I'm (khw) not sure why this was done, but NULL would be
3879 # the character very frequently used.
3880 return $try_hard if $code == 0x0000;
3881
3882 return 0 if $try_hard; # XXX Temporary until fix utf8.c
3883
3884 # shun non-character code points.
3885 return $try_hard if $code >= 0xFDD0 && $code <= 0xFDEF;
3886 return $try_hard if ($code & 0xFFFE) == 0xFFFE; # includes FFFF
3887
3888 return $try_hard if $code > $LAST_UNICODE_CODEPOINT; # keep in range
3889 return $try_hard if $code >= 0xD800 && $code <= 0xDFFF; # no surrogate
3890
3891 return 1;
3892 }
3893
3894 sub get_valid_code_point {
3895 # Return a code point that's part of the range list. Returns nothing
3896 # if the table is empty or we can't find a suitable code point. This
3897 # used only for making the test script.
3898
3899 my $self = shift;
3900 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3901
3902 my $addr = main::objaddr($self);
3903
3904 # On first pass, don't choose less desirable code points; if no good
3905 # one is found, repeat, allowing a less desirable one to be selected.
3906 for my $try_hard (0, 1) {
3907
3908 # Look through all the ranges for a usable code point.
3909 for my $set ($self->ranges) {
3910
3911 # Try the edge cases first, starting with the end point of the
3912 # range.
3913 my $end = $set->end;
3914 return $end if is_code_point_usable($end, $try_hard);
3915
3916 # End point didn't, work. Start at the beginning and try
3917 # every one until find one that does work.
3918 for my $trial ($set->start .. $end - 1) {
3919 return $trial if is_code_point_usable($trial, $try_hard);
3920 }
3921 }
3922 }
3923 return (); # If none found, give up.
3924 }
3925
3926 sub get_invalid_code_point {
3927 # Return a code point that's not part of the table. Returns nothing
3928 # if the table covers all code points or a suitable code point can't
3929 # be found. This used only for making the test script.
3930
3931 my $self = shift;
3932 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3933
3934 # Just find a valid code point of the inverse, if any.
3935 return Range_List->new(Initialize => ~ $self)->get_valid_code_point;
3936 }
3937} # end closure for Range_List
3938
3939package Range_Map;
3940use base '_Range_List_Base';
3941
3942# A Range_Map is a range list in which the range values (called maps) are
3943# significant, and hence shouldn't be manipulated by our other code, which
3944# could be ambiguous or lose things. For example, in taking the union of two
3945# lists, which share code points, but which have differing values, which one
3946# has precedence in the union?
3947# It turns out that these operations aren't really necessary for map tables,
3948# and so this class was created to make sure they aren't accidentally
3949# applied to them.
3950
3951{ # Closure
3952
3953 sub add_map {
3954 # Add a range containing a mapping value to the list
3955
3956 my $self = shift;
3957 # Rest of parameters passed on
3958
3959 return $self->_add_delete('+', @_);
3960 }
3961
3962 sub add_duplicate {
3963 # Adds entry to a range list which can duplicate an existing entry
3964
3965 my $self = shift;
3966 my $code_point = shift;
3967 my $value = shift;
3968 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3969
3970 return $self->add_map($code_point, $code_point,
3971 $value, Replace => $MULTIPLE);
3972 }
3973} # End of closure for package Range_Map
3974
3975package _Base_Table;
3976
3977# A table is the basic data structure that gets written out into a file for
3978# use by the Perl core. This is the abstract base class implementing the
3979# common elements from the derived ones. A list of the methods to be
3980# furnished by an implementing class is just after the constructor.
3981
3982sub standardize { return main::standardize($_[0]); }
3983sub trace { return main::trace(@_); }
3984
3985{ # Closure
3986
3987 main::setup_package();
3988
3989 my %range_list;
3990 # Object containing the ranges of the table.
3991 main::set_access('range_list', \%range_list, 'p_r', 'p_s');
3992
3993 my %full_name;
3994 # The full table name.
3995 main::set_access('full_name', \%full_name, 'r');
3996
3997 my %name;
3998 # The table name, almost always shorter
3999 main::set_access('name', \%name, 'r');
4000
4001 my %short_name;
4002 # The shortest of all the aliases for this table, with underscores removed
4003 main::set_access('short_name', \%short_name);
4004
4005 my %nominal_short_name_length;
4006 # The length of short_name before removing underscores
4007 main::set_access('nominal_short_name_length',
4008 \%nominal_short_name_length);
4009
23e33b60
KW
4010 my %complete_name;
4011 # The complete name, including property.
4012 main::set_access('complete_name', \%complete_name, 'r');
4013
99870f4d
KW
4014 my %property;
4015 # Parent property this table is attached to.
4016 main::set_access('property', \%property, 'r');
4017
4018 my %aliases;
4019 # Ordered list of aliases of the table's name. The first ones in the list
4020 # are output first in comments
4021 main::set_access('aliases', \%aliases, 'readable_array');
4022
4023 my %comment;
4024 # A comment associated with the table for human readers of the files
4025 main::set_access('comment', \%comment, 's');
4026
4027 my %description;
4028 # A comment giving a short description of the table's meaning for human
4029 # readers of the files.
4030 main::set_access('description', \%description, 'readable_array');
4031
4032 my %note;
4033 # A comment giving a short note about the table for human readers of the
4034 # files.
4035 main::set_access('note', \%note, 'readable_array');
4036
4037 my %internal_only;
4038 # Boolean; if set means any file that contains this table is marked as for
4039 # internal-only use.
4040 main::set_access('internal_only', \%internal_only);
4041
4042 my %find_table_from_alias;
4043 # The parent property passes this pointer to a hash which this class adds
4044 # all its aliases to, so that the parent can quickly take an alias and
4045 # find this table.
4046 main::set_access('find_table_from_alias', \%find_table_from_alias, 'p_r');
4047
4048 my %locked;
4049 # After this table is made equivalent to another one; we shouldn't go
4050 # changing the contents because that could mean it's no longer equivalent
4051 main::set_access('locked', \%locked, 'r');
4052
4053 my %file_path;
4054 # This gives the final path to the file containing the table. Each
4055 # directory in the path is an element in the array
4056 main::set_access('file_path', \%file_path, 'readable_array');
4057
4058 my %status;
4059 # What is the table's status, normal, $OBSOLETE, etc. Enum
4060 main::set_access('status', \%status, 'r');
4061
4062 my %status_info;
4063 # A comment about its being obsolete, or whatever non normal status it has
4064 main::set_access('status_info', \%status_info, 'r');
4065
4066 my %range_size_1;
4067 # Is the table to be output with each range only a single code point?
4068 # This is done to avoid breaking existing code that may have come to rely
4069 # on this behavior in previous versions of this program.)
4070 main::set_access('range_size_1', \%range_size_1, 'r', 's');
4071
4072 my %perl_extension;
4073 # A boolean set iff this table is a Perl extension to the Unicode
4074 # standard.
4075 main::set_access('perl_extension', \%perl_extension, 'r');
4076
0c07e538
KW
4077 my %output_range_counts;
4078 # A boolean set iff this table is to have comments written in the
4079 # output file that contain the number of code points in the range.
4080 # The constructor can override the global flag of the same name.
4081 main::set_access('output_range_counts', \%output_range_counts, 'r');
4082
99870f4d
KW
4083 sub new {
4084 # All arguments are key => value pairs, which you can see below, most
4085 # of which match fields documented above. Otherwise: Pod_Entry,
4086 # Externally_Ok, and Fuzzy apply to the names of the table, and are
4087 # documented in the Alias package
4088
4089 return Carp::carp_too_few_args(\@_, 2) if main::DEBUG && @_ < 2;
4090
4091 my $class = shift;
4092
4093 my $self = bless \do { my $anonymous_scalar }, $class;
4094 my $addr = main::objaddr($self);
4095
4096 my %args = @_;
4097
4098 $name{$addr} = delete $args{'Name'};
4099 $find_table_from_alias{$addr} = delete $args{'_Alias_Hash'};
4100 $full_name{$addr} = delete $args{'Full_Name'};
23e33b60
KW
4101 my $complete_name = $complete_name{$addr}
4102 = delete $args{'Complete_Name'};
99870f4d 4103 $internal_only{$addr} = delete $args{'Internal_Only_Warning'} || 0;
0c07e538 4104 $output_range_counts{$addr} = delete $args{'Output_Range_Counts'};
99870f4d
KW
4105 $property{$addr} = delete $args{'_Property'};
4106 $range_list{$addr} = delete $args{'_Range_List'};
4107 $status{$addr} = delete $args{'Status'} || $NORMAL;
4108 $status_info{$addr} = delete $args{'_Status_Info'} || "";
4109 $range_size_1{$addr} = delete $args{'Range_Size_1'} || 0;
4110
4111 my $description = delete $args{'Description'};
4112 my $externally_ok = delete $args{'Externally_Ok'};
4113 my $loose_match = delete $args{'Fuzzy'};
4114 my $note = delete $args{'Note'};
4115 my $make_pod_entry = delete $args{'Pod_Entry'};
37e2e78e 4116 my $perl_extension = delete $args{'Perl_Extension'};
99870f4d
KW
4117
4118 # Shouldn't have any left over
4119 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
4120
4121 # Can't use || above because conceivably the name could be 0, and
4122 # can't use // operator in case this program gets used in Perl 5.8
4123 $full_name{$addr} = $name{$addr} if ! defined $full_name{$addr};
0c07e538
KW
4124 $output_range_counts{$addr} = $output_range_counts if
4125 ! defined $output_range_counts{$addr};
99870f4d
KW
4126
4127 $aliases{$addr} = [ ];
4128 $comment{$addr} = [ ];
4129 $description{$addr} = [ ];
4130 $note{$addr} = [ ];
4131 $file_path{$addr} = [ ];
4132 $locked{$addr} = "";
4133
4134 push @{$description{$addr}}, $description if $description;
4135 push @{$note{$addr}}, $note if $note;
4136
37e2e78e
KW
4137 if ($status{$addr} eq $PLACEHOLDER) {
4138
4139 # A placeholder table doesn't get documented, is a perl extension,
4140 # and quite likely will be empty
4141 $make_pod_entry = 0 if ! defined $make_pod_entry;
4142 $perl_extension = 1 if ! defined $perl_extension;
4143 push @tables_that_may_be_empty, $complete_name{$addr};
4144 }
4145 elsif (! $status{$addr}) {
4146
4147 # If hasn't set its status already, see if it is on one of the
4148 # lists of properties or tables that have particular statuses; if
4149 # not