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