This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Unicode::UCD: move common directory to subroutine
[perl5.git] / lib / unicore / mktables
CommitLineData
d73e5302 1#!/usr/bin/perl -w
99870f4d
KW
2
3# !!!!!!!!!!!!!! IF YOU MODIFY THIS FILE !!!!!!!!!!!!!!!!!!!!!!!!!
4# Any files created or read by this program should be listed in 'mktables.lst'
5# Use -makelist to regenerate it.
6
23e33b60
KW
7# Needs 'no overloading' to run faster on miniperl. Code commented out at the
8# subroutine objaddr can be used instead to work as far back (untested) as
f998e60c
KW
9# 5.8: needs pack "U". But almost all occurrences of objaddr have been
10# removed in favor of using 'no overloading'. You also would have to go
11# through and replace occurrences like:
ffe43484 12# my $addr = do { no overloading; pack 'J', $self; }
f998e60c
KW
13# with
14# my $addr = main::objaddr $self;
6c68572b 15# (or reverse commit 9b01bafde4b022706c3d6f947a0963f821b2e50b
051df77b
NC
16# that instituted the change to main::objaddr, and subsequent commits that
17# changed 0+$self to pack 'J', $self.)
6c68572b 18
cdcef19a 19my $start_time;
98dc9551 20BEGIN { # Get the time the script started running; do it at compilation to
cdcef19a
KW
21 # get it as close as possible
22 $start_time= time;
23}
24
23e33b60 25require 5.010_001;
d73e5302 26use strict;
99870f4d 27use warnings;
cf25bb62 28use Carp;
bd9ebcfd 29use Config;
99870f4d
KW
30use File::Find;
31use File::Path;
d07a55ed 32use File::Spec;
99870f4d 33use Text::Tabs;
6b64c11c 34use re "/aa";
99870f4d
KW
35
36sub DEBUG () { 0 } # Set to 0 for production; 1 for development
bd9ebcfd 37my $debugging_build = $Config{"ccflags"} =~ /-DDEBUGGING/;
99870f4d
KW
38
39##########################################################################
40#
41# mktables -- create the runtime Perl Unicode files (lib/unicore/.../*.pl),
42# from the Unicode database files (lib/unicore/.../*.txt), It also generates
43# a pod file and a .t file
44#
45# The structure of this file is:
46# First these introductory comments; then
47# code needed for everywhere, such as debugging stuff; then
48# code to handle input parameters; then
49# data structures likely to be of external interest (some of which depend on
50# the input parameters, so follows them; then
51# more data structures and subroutine and package (class) definitions; then
52# the small actual loop to process the input files and finish up; then
53# a __DATA__ section, for the .t tests
54#
5f7264c7 55# This program works on all releases of Unicode through at least 6.0. The
99870f4d
KW
56# outputs have been scrutinized most intently for release 5.1. The others
57# have been checked for somewhat more than just sanity. It can handle all
58# existing Unicode character properties in those releases.
59#
99870f4d
KW
60# This program is mostly about Unicode character (or code point) properties.
61# A property describes some attribute or quality of a code point, like if it
62# is lowercase or not, its name, what version of Unicode it was first defined
63# in, or what its uppercase equivalent is. Unicode deals with these disparate
64# possibilities by making all properties into mappings from each code point
65# into some corresponding value. In the case of it being lowercase or not,
66# the mapping is either to 'Y' or 'N' (or various synonyms thereof). Each
67# property maps each Unicode code point to a single value, called a "property
68# value". (Hence each Unicode property is a true mathematical function with
69# exactly one value per code point.)
70#
71# When using a property in a regular expression, what is desired isn't the
72# mapping of the code point to its property's value, but the reverse (or the
73# mathematical "inverse relation"): starting with the property value, "Does a
74# code point map to it?" These are written in a "compound" form:
75# \p{property=value}, e.g., \p{category=punctuation}. This program generates
76# files containing the lists of code points that map to each such regular
77# expression property value, one file per list
78#
79# There is also a single form shortcut that Perl adds for many of the commonly
80# used properties. This happens for all binary properties, plus script,
81# general_category, and block properties.
82#
83# Thus the outputs of this program are files. There are map files, mostly in
84# the 'To' directory; and there are list files for use in regular expression
85# matching, all in subdirectories of the 'lib' directory, with each
86# subdirectory being named for the property that the lists in it are for.
87# Bookkeeping, test, and documentation files are also generated.
88
89my $matches_directory = 'lib'; # Where match (\p{}) files go.
90my $map_directory = 'To'; # Where map files go.
91
92# DATA STRUCTURES
93#
94# The major data structures of this program are Property, of course, but also
95# Table. There are two kinds of tables, very similar to each other.
96# "Match_Table" is the data structure giving the list of code points that have
97# a particular property value, mentioned above. There is also a "Map_Table"
98# data structure which gives the property's mapping from code point to value.
99# There are two structures because the match tables need to be combined in
100# various ways, such as constructing unions, intersections, complements, etc.,
101# and the map ones don't. And there would be problems, perhaps subtle, if
102# a map table were inadvertently operated on in some of those ways.
103# The use of separate classes with operations defined on one but not the other
104# prevents accidentally confusing the two.
105#
106# At the heart of each table's data structure is a "Range_List", which is just
107# an ordered list of "Ranges", plus ancillary information, and methods to
108# operate on them. A Range is a compact way to store property information.
109# Each range has a starting code point, an ending code point, and a value that
110# is meant to apply to all the code points between the two end points,
111# inclusive. For a map table, this value is the property value for those
112# code points. Two such ranges could be written like this:
113# 0x41 .. 0x5A, 'Upper',
114# 0x61 .. 0x7A, 'Lower'
115#
116# Each range also has a type used as a convenience to classify the values.
117# Most ranges in this program will be Type 0, or normal, but there are some
118# ranges that have a non-zero type. These are used only in map tables, and
119# are for mappings that don't fit into the normal scheme of things. Mappings
120# that require a hash entry to communicate with utf8.c are one example;
121# another example is mappings for charnames.pm to use which indicate a name
122# that is algorithmically determinable from its code point (and vice-versa).
123# These are used to significantly compact these tables, instead of listing
124# each one of the tens of thousands individually.
125#
126# In a match table, the value of a range is irrelevant (and hence the type as
127# well, which will always be 0), and arbitrarily set to the null string.
128# Using the example above, there would be two match tables for those two
129# entries, one named Upper would contain the 0x41..0x5A range, and the other
130# named Lower would contain 0x61..0x7A.
131#
132# Actually, there are two types of range lists, "Range_Map" is the one
133# associated with map tables, and "Range_List" with match tables.
134# Again, this is so that methods can be defined on one and not the other so as
135# to prevent operating on them in incorrect ways.
136#
137# Eventually, most tables are written out to files to be read by utf8_heavy.pl
138# in the perl core. All tables could in theory be written, but some are
139# suppressed because there is no current practical use for them. It is easy
140# to change which get written by changing various lists that are near the top
141# of the actual code in this file. The table data structures contain enough
142# ancillary information to allow them to be treated as separate entities for
143# writing, such as the path to each one's file. There is a heading in each
144# map table that gives the format of its entries, and what the map is for all
145# the code points missing from it. (This allows tables to be more compact.)
678f13d5 146#
99870f4d
KW
147# The Property data structure contains one or more tables. All properties
148# contain a map table (except the $perl property which is a
149# pseudo-property containing only match tables), and any properties that
150# are usable in regular expression matches also contain various matching
151# tables, one for each value the property can have. A binary property can
152# have two values, True and False (or Y and N, which are preferred by Unicode
153# terminology). Thus each of these properties will have a map table that
154# takes every code point and maps it to Y or N (but having ranges cuts the
155# number of entries in that table way down), and two match tables, one
156# which has a list of all the code points that map to Y, and one for all the
157# code points that map to N. (For each of these, a third table is also
158# generated for the pseudo Perl property. It contains the identical code
159# points as the Y table, but can be written, not in the compound form, but in
160# a "single" form like \p{IsUppercase}.) Many properties are binary, but some
161# properties have several possible values, some have many, and properties like
162# Name have a different value for every named code point. Those will not,
163# unless the controlling lists are changed, have their match tables written
164# out. But all the ones which can be used in regular expression \p{} and \P{}
c12f2655
KW
165# constructs will. Prior to 5.14, generally a property would have either its
166# map table or its match tables written but not both. Again, what gets
167# written is controlled by lists which can easily be changed. Starting in
168# 5.14, advantage was taken of this, and all the map tables needed to
169# reconstruct the Unicode db are now written out, while suppressing the
170# Unicode .txt files that contain the data. Our tables are much more compact
171# than the .txt files, so a significant space savings was achieved.
172
173# Properties have a 'Type', like binary, or string, or enum depending on how
174# many match tables there are and the content of the maps. This 'Type' is
175# different than a range 'Type', so don't get confused by the two concepts
176# having the same name.
678f13d5 177#
99870f4d
KW
178# For information about the Unicode properties, see Unicode's UAX44 document:
179
180my $unicode_reference_url = 'http://www.unicode.org/reports/tr44/';
181
182# As stated earlier, this program will work on any release of Unicode so far.
183# Most obvious problems in earlier data have NOT been corrected except when
184# necessary to make Perl or this program work reasonably. For example, no
c12f2655
KW
185# folding information was given in early releases, so this program substitutes
186# lower case instead, just so that a regular expression with the /i option
187# will do something that actually gives the right results in many cases.
188# There are also a couple other corrections for version 1.1.5, commented at
189# the point they are made. As an example of corrections that weren't made
190# (but could be) is this statement from DerivedAge.txt: "The supplementary
191# private use code points and the non-character code points were assigned in
192# version 2.0, but not specifically listed in the UCD until versions 3.0 and
193# 3.1 respectively." (To be precise it was 3.0.1 not 3.0.0) More information
194# on Unicode version glitches is further down in these introductory comments.
99870f4d 195#
5f7264c7
KW
196# This program works on all non-provisional properties as of 6.0, though the
197# files for some are suppressed from apparent lack of demand for them. You
198# can change which are output by changing lists in this program.
678f13d5 199#
dc85bd38 200# The old version of mktables emphasized the term "Fuzzy" to mean Unicode's
99870f4d
KW
201# loose matchings rules (from Unicode TR18):
202#
203# The recommended names for UCD properties and property values are in
204# PropertyAliases.txt [Prop] and PropertyValueAliases.txt
205# [PropValue]. There are both abbreviated names and longer, more
206# descriptive names. It is strongly recommended that both names be
207# recognized, and that loose matching of property names be used,
208# whereby the case distinctions, whitespace, hyphens, and underbar
209# are ignored.
210# The program still allows Fuzzy to override its determination of if loose
211# matching should be used, but it isn't currently used, as it is no longer
212# needed; the calculations it makes are good enough.
678f13d5 213#
99870f4d
KW
214# SUMMARY OF HOW IT WORKS:
215#
216# Process arguments
217#
218# A list is constructed containing each input file that is to be processed
219#
220# Each file on the list is processed in a loop, using the associated handler
221# code for each:
222# The PropertyAliases.txt and PropValueAliases.txt files are processed
223# first. These files name the properties and property values.
224# Objects are created of all the property and property value names
225# that the rest of the input should expect, including all synonyms.
226# The other input files give mappings from properties to property
227# values. That is, they list code points and say what the mapping
228# is under the given property. Some files give the mappings for
229# just one property; and some for many. This program goes through
230# each file and populates the properties from them. Some properties
231# are listed in more than one file, and Unicode has set up a
232# precedence as to which has priority if there is a conflict. Thus
233# the order of processing matters, and this program handles the
234# conflict possibility by processing the overriding input files
235# last, so that if necessary they replace earlier values.
236# After this is all done, the program creates the property mappings not
237# furnished by Unicode, but derivable from what it does give.
238# The tables of code points that match each property value in each
239# property that is accessible by regular expressions are created.
240# The Perl-defined properties are created and populated. Many of these
241# require data determined from the earlier steps
242# Any Perl-defined synonyms are created, and name clashes between Perl
678f13d5 243# and Unicode are reconciled and warned about.
99870f4d
KW
244# All the properties are written to files
245# Any other files are written, and final warnings issued.
678f13d5 246#
99870f4d
KW
247# For clarity, a number of operators have been overloaded to work on tables:
248# ~ means invert (take all characters not in the set). The more
249# conventional '!' is not used because of the possibility of confusing
250# it with the actual boolean operation.
251# + means union
252# - means subtraction
253# & means intersection
254# The precedence of these is the order listed. Parentheses should be
255# copiously used. These are not a general scheme. The operations aren't
256# defined for a number of things, deliberately, to avoid getting into trouble.
257# Operations are done on references and affect the underlying structures, so
258# that the copy constructors for them have been overloaded to not return a new
259# clone, but the input object itself.
678f13d5 260#
99870f4d
KW
261# The bool operator is deliberately not overloaded to avoid confusion with
262# "should it mean if the object merely exists, or also is non-empty?".
99870f4d
KW
263#
264# WHY CERTAIN DESIGN DECISIONS WERE MADE
678f13d5
KW
265#
266# This program needs to be able to run under miniperl. Therefore, it uses a
267# minimum of other modules, and hence implements some things itself that could
268# be gotten from CPAN
269#
270# This program uses inputs published by the Unicode Consortium. These can
271# change incompatibly between releases without the Perl maintainers realizing
272# it. Therefore this program is now designed to try to flag these. It looks
273# at the directories where the inputs are, and flags any unrecognized files.
274# It keeps track of all the properties in the files it handles, and flags any
275# that it doesn't know how to handle. It also flags any input lines that
276# don't match the expected syntax, among other checks.
277#
278# It is also designed so if a new input file matches one of the known
279# templates, one hopefully just needs to add it to a list to have it
280# processed.
281#
282# As mentioned earlier, some properties are given in more than one file. In
283# particular, the files in the extracted directory are supposedly just
284# reformattings of the others. But they contain information not easily
285# derivable from the other files, including results for Unihan, which this
286# program doesn't ordinarily look at, and for unassigned code points. They
287# also have historically had errors or been incomplete. In an attempt to
288# create the best possible data, this program thus processes them first to
289# glean information missing from the other files; then processes those other
290# files to override any errors in the extracted ones. Much of the design was
291# driven by this need to store things and then possibly override them.
292#
293# It tries to keep fatal errors to a minimum, to generate something usable for
294# testing purposes. It always looks for files that could be inputs, and will
295# warn about any that it doesn't know how to handle (the -q option suppresses
296# the warning).
99870f4d 297#
678f13d5
KW
298# Why is there more than one type of range?
299# This simplified things. There are some very specialized code points that
300# have to be handled specially for output, such as Hangul syllable names.
301# By creating a range type (done late in the development process), it
302# allowed this to be stored with the range, and overridden by other input.
303# Originally these were stored in another data structure, and it became a
304# mess trying to decide if a second file that was for the same property was
305# overriding the earlier one or not.
306#
307# Why are there two kinds of tables, match and map?
308# (And there is a base class shared by the two as well.) As stated above,
309# they actually are for different things. Development proceeded much more
310# smoothly when I (khw) realized the distinction. Map tables are used to
311# give the property value for every code point (actually every code point
312# that doesn't map to a default value). Match tables are used for regular
313# expression matches, and are essentially the inverse mapping. Separating
314# the two allows more specialized methods, and error checks so that one
315# can't just take the intersection of two map tables, for example, as that
316# is nonsensical.
99870f4d 317#
23e33b60
KW
318# DEBUGGING
319#
678f13d5
KW
320# This program is written so it will run under miniperl. Occasionally changes
321# will cause an error where the backtrace doesn't work well under miniperl.
322# To diagnose the problem, you can instead run it under regular perl, if you
323# have one compiled.
324#
325# There is a good trace facility. To enable it, first sub DEBUG must be set
326# to return true. Then a line like
327#
328# local $to_trace = 1 if main::DEBUG;
329#
330# can be added to enable tracing in its lexical scope or until you insert
331# another line:
332#
333# local $to_trace = 0 if main::DEBUG;
334#
335# then use a line like "trace $a, @b, %c, ...;
336#
337# Some of the more complex subroutines already have trace statements in them.
338# Permanent trace statements should be like:
339#
340# trace ... if main::DEBUG && $to_trace;
341#
342# If there is just one or a few files that you're debugging, you can easily
343# cause most everything else to be skipped. Change the line
344#
345# my $debug_skip = 0;
346#
347# to 1, and every file whose object is in @input_file_objects and doesn't have
348# a, 'non_skip => 1,' in its constructor will be skipped.
349#
b4a0206c 350# To compare the output tables, it may be useful to specify the -annotate
c4019d52
KW
351# flag. This causes the tables to expand so there is one entry for each
352# non-algorithmically named code point giving, currently its name, and its
353# graphic representation if printable (and you have a font that knows about
354# it). This makes it easier to see what the particular code points are in
355# each output table. The tables are usable, but because they don't have
356# ranges (for the most part), a Perl using them will run slower. Non-named
357# code points are annotated with a description of their status, and contiguous
358# ones with the same description will be output as a range rather than
359# individually. Algorithmically named characters are also output as ranges,
360# except when there are just a few contiguous ones.
361#
99870f4d
KW
362# FUTURE ISSUES
363#
364# The program would break if Unicode were to change its names so that
365# interior white space, underscores, or dashes differences were significant
366# within property and property value names.
367#
368# It might be easier to use the xml versions of the UCD if this program ever
369# would need heavy revision, and the ability to handle old versions was not
370# required.
371#
372# There is the potential for name collisions, in that Perl has chosen names
373# that Unicode could decide it also likes. There have been such collisions in
374# the past, with mostly Perl deciding to adopt the Unicode definition of the
375# name. However in the 5.2 Unicode beta testing, there were a number of such
376# collisions, which were withdrawn before the final release, because of Perl's
377# and other's protests. These all involved new properties which began with
378# 'Is'. Based on the protests, Unicode is unlikely to try that again. Also,
379# many of the Perl-defined synonyms, like Any, Word, etc, are listed in a
380# Unicode document, so they are unlikely to be used by Unicode for another
381# purpose. However, they might try something beginning with 'In', or use any
382# of the other Perl-defined properties. This program will warn you of name
383# collisions, and refuse to generate tables with them, but manual intervention
384# will be required in this event. One scheme that could be implemented, if
385# necessary, would be to have this program generate another file, or add a
386# field to mktables.lst that gives the date of first definition of a property.
387# Each new release of Unicode would use that file as a basis for the next
388# iteration. And the Perl synonym addition code could sort based on the age
389# of the property, so older properties get priority, and newer ones that clash
390# would be refused; hence existing code would not be impacted, and some other
391# synonym would have to be used for the new property. This is ugly, and
392# manual intervention would certainly be easier to do in the short run; lets
393# hope it never comes to this.
678f13d5 394#
99870f4d
KW
395# A NOTE ON UNIHAN
396#
397# This program can generate tables from the Unihan database. But it doesn't
398# by default, letting the CPAN module Unicode::Unihan handle them. Prior to
399# version 5.2, this database was in a single file, Unihan.txt. In 5.2 the
400# database was split into 8 different files, all beginning with the letters
401# 'Unihan'. This program will read those file(s) if present, but it needs to
402# know which of the many properties in the file(s) should have tables created
403# for them. It will create tables for any properties listed in
404# PropertyAliases.txt and PropValueAliases.txt, plus any listed in the
405# @cjk_properties array and the @cjk_property_values array. Thus, if a
406# property you want is not in those files of the release you are building
407# against, you must add it to those two arrays. Starting in 4.0, the
408# Unicode_Radical_Stroke was listed in those files, so if the Unihan database
409# is present in the directory, a table will be generated for that property.
410# In 5.2, several more properties were added. For your convenience, the two
5f7264c7 411# arrays are initialized with all the 6.0 listed properties that are also in
99870f4d
KW
412# earlier releases. But these are commented out. You can just uncomment the
413# ones you want, or use them as a template for adding entries for other
414# properties.
415#
416# You may need to adjust the entries to suit your purposes. setup_unihan(),
417# and filter_unihan_line() are the functions where this is done. This program
418# already does some adjusting to make the lines look more like the rest of the
419# Unicode DB; You can see what that is in filter_unihan_line()
420#
421# There is a bug in the 3.2 data file in which some values for the
422# kPrimaryNumeric property have commas and an unexpected comment. A filter
423# could be added for these; or for a particular installation, the Unihan.txt
424# file could be edited to fix them.
99870f4d 425#
678f13d5
KW
426# HOW TO ADD A FILE TO BE PROCESSED
427#
428# A new file from Unicode needs to have an object constructed for it in
429# @input_file_objects, probably at the end or at the end of the extracted
430# ones. The program should warn you if its name will clash with others on
431# restrictive file systems, like DOS. If so, figure out a better name, and
432# add lines to the README.perl file giving that. If the file is a character
433# property, it should be in the format that Unicode has by default
434# standardized for such files for the more recently introduced ones.
435# If so, the Input_file constructor for @input_file_objects can just be the
436# file name and release it first appeared in. If not, then it should be
437# possible to construct an each_line_handler() to massage the line into the
438# standardized form.
439#
440# For non-character properties, more code will be needed. You can look at
441# the existing entries for clues.
442#
443# UNICODE VERSIONS NOTES
444#
445# The Unicode UCD has had a number of errors in it over the versions. And
446# these remain, by policy, in the standard for that version. Therefore it is
447# risky to correct them, because code may be expecting the error. So this
448# program doesn't generally make changes, unless the error breaks the Perl
449# core. As an example, some versions of 2.1.x Jamo.txt have the wrong value
450# for U+1105, which causes real problems for the algorithms for Jamo
451# calculations, so it is changed here.
452#
453# But it isn't so clear cut as to what to do about concepts that are
454# introduced in a later release; should they extend back to earlier releases
455# where the concept just didn't exist? It was easier to do this than to not,
456# so that's what was done. For example, the default value for code points not
457# in the files for various properties was probably undefined until changed by
458# some version. No_Block for blocks is such an example. This program will
459# assign No_Block even in Unicode versions that didn't have it. This has the
460# benefit that code being written doesn't have to special case earlier
461# versions; and the detriment that it doesn't match the Standard precisely for
462# the affected versions.
463#
464# Here are some observations about some of the issues in early versions:
465#
6426c51b 466# The number of code points in \p{alpha} halved in 2.1.9. It turns out that
678f13d5
KW
467# the reason is that the CJK block starting at 4E00 was removed from PropList,
468# and was not put back in until 3.1.0
469#
470# Unicode introduced the synonym Space for White_Space in 4.1. Perl has
471# always had a \p{Space}. In release 3.2 only, they are not synonymous. The
472# reason is that 3.2 introduced U+205F=medium math space, which was not
473# classed as white space, but Perl figured out that it should have been. 4.0
474# reclassified it correctly.
475#
476# Another change between 3.2 and 4.0 is the CCC property value ATBL. In 3.2
477# this was erroneously a synonym for 202. In 4.0, ATB became 202, and ATBL
478# was left with no code points, as all the ones that mapped to 202 stayed
479# mapped to 202. Thus if your program used the numeric name for the class,
480# it would not have been affected, but if it used the mnemonic, it would have
481# been.
482#
483# \p{Script=Hrkt} (Katakana_Or_Hiragana) came in 4.0.1. Before that code
484# points which eventually came to have this script property value, instead
485# mapped to "Unknown". But in the next release all these code points were
486# moved to \p{sc=common} instead.
99870f4d
KW
487#
488# The default for missing code points for BidiClass is complicated. Starting
489# in 3.1.1, the derived file DBidiClass.txt handles this, but this program
490# tries to do the best it can for earlier releases. It is done in
491# process_PropertyAliases()
492#
493##############################################################################
494
495my $UNDEF = ':UNDEF:'; # String to print out for undefined values in tracing
496 # and errors
497my $MAX_LINE_WIDTH = 78;
498
499# Debugging aid to skip most files so as to not be distracted by them when
500# concentrating on the ones being debugged. Add
501# non_skip => 1,
502# to the constructor for those files you want processed when you set this.
503# Files with a first version number of 0 are special: they are always
c12f2655
KW
504# processed regardless of the state of this flag. Generally, Jamo.txt and
505# UnicodeData.txt must not be skipped if you want this program to not die
506# before normal completion.
99870f4d
KW
507my $debug_skip = 0;
508
509# Set to 1 to enable tracing.
510our $to_trace = 0;
511
512{ # Closure for trace: debugging aid
513 my $print_caller = 1; # ? Include calling subroutine name
514 my $main_with_colon = 'main::';
515 my $main_colon_length = length($main_with_colon);
516
517 sub trace {
518 return unless $to_trace; # Do nothing if global flag not set
519
520 my @input = @_;
521
522 local $DB::trace = 0;
523 $DB::trace = 0; # Quiet 'used only once' message
524
525 my $line_number;
526
527 # Loop looking up the stack to get the first non-trace caller
528 my $caller_line;
529 my $caller_name;
530 my $i = 0;
531 do {
532 $line_number = $caller_line;
533 (my $pkg, my $file, $caller_line, my $caller) = caller $i++;
534 $caller = $main_with_colon unless defined $caller;
535
536 $caller_name = $caller;
537
538 # get rid of pkg
539 $caller_name =~ s/.*:://;
540 if (substr($caller_name, 0, $main_colon_length)
541 eq $main_with_colon)
542 {
543 $caller_name = substr($caller_name, $main_colon_length);
544 }
545
546 } until ($caller_name ne 'trace');
547
548 # If the stack was empty, we were called from the top level
549 $caller_name = 'main' if ($caller_name eq ""
550 || $caller_name eq 'trace');
551
552 my $output = "";
553 foreach my $string (@input) {
554 #print STDERR __LINE__, ": ", join ", ", @input, "\n";
555 if (ref $string eq 'ARRAY' || ref $string eq 'HASH') {
556 $output .= simple_dumper($string);
557 }
558 else {
559 $string = "$string" if ref $string;
560 $string = $UNDEF unless defined $string;
561 chomp $string;
562 $string = '""' if $string eq "";
563 $output .= " " if $output ne ""
564 && $string ne ""
565 && substr($output, -1, 1) ne " "
566 && substr($string, 0, 1) ne " ";
567 $output .= $string;
568 }
569 }
570
99f78760
KW
571 print STDERR sprintf "%4d: ", $line_number if defined $line_number;
572 print STDERR "$caller_name: " if $print_caller;
99870f4d
KW
573 print STDERR $output, "\n";
574 return;
575 }
576}
577
578# This is for a rarely used development feature that allows you to compare two
579# versions of the Unicode standard without having to deal with changes caused
c12f2655
KW
580# by the code points introduced in the later version. Change the 0 to a
581# string containing a SINGLE dotted Unicode release number (e.g. "2.1"). Only
582# code points introduced in that release and earlier will be used; later ones
583# are thrown away. You use the version number of the earliest one you want to
584# compare; then run this program on directory structures containing each
585# release, and compare the outputs. These outputs will therefore include only
586# the code points common to both releases, and you can see the changes caused
587# just by the underlying release semantic changes. For versions earlier than
588# 3.2, you must copy a version of DAge.txt into the directory.
589my $string_compare_versions = DEBUG && 0; # e.g., "2.1";
99870f4d
KW
590my $compare_versions = DEBUG
591 && $string_compare_versions
592 && pack "C*", split /\./, $string_compare_versions;
593
594sub uniques {
595 # Returns non-duplicated input values. From "Perl Best Practices:
596 # Encapsulated Cleverness". p. 455 in first edition.
597
598 my %seen;
0e407844
NC
599 # Arguably this breaks encapsulation, if the goal is to permit multiple
600 # distinct objects to stringify to the same value, and be interchangeable.
601 # However, for this program, no two objects stringify identically, and all
602 # lists passed to this function are either objects or strings. So this
603 # doesn't affect correctness, but it does give a couple of percent speedup.
604 no overloading;
99870f4d
KW
605 return grep { ! $seen{$_}++ } @_;
606}
607
608$0 = File::Spec->canonpath($0);
609
610my $make_test_script = 0; # ? Should we output a test script
611my $write_unchanged_files = 0; # ? Should we update the output files even if
612 # we don't think they have changed
613my $use_directory = ""; # ? Should we chdir somewhere.
614my $pod_directory; # input directory to store the pod file.
615my $pod_file = 'perluniprops';
616my $t_path; # Path to the .t test file
617my $file_list = 'mktables.lst'; # File to store input and output file names.
618 # This is used to speed up the build, by not
619 # executing the main body of the program if
620 # nothing on the list has changed since the
621 # previous build
622my $make_list = 1; # ? Should we write $file_list. Set to always
623 # make a list so that when the pumpking is
624 # preparing a release, s/he won't have to do
625 # special things
626my $glob_list = 0; # ? Should we try to include unknown .txt files
627 # in the input.
bd9ebcfd
KW
628my $output_range_counts = $debugging_build; # ? Should we include the number
629 # of code points in ranges in
630 # the output
558712cf 631my $annotate = 0; # ? Should character names be in the output
9ef2b94f 632
99870f4d
KW
633# Verbosity levels; 0 is quiet
634my $NORMAL_VERBOSITY = 1;
635my $PROGRESS = 2;
636my $VERBOSE = 3;
637
638my $verbosity = $NORMAL_VERBOSITY;
639
640# Process arguments
641while (@ARGV) {
cf25bb62
JH
642 my $arg = shift @ARGV;
643 if ($arg eq '-v') {
99870f4d
KW
644 $verbosity = $VERBOSE;
645 }
646 elsif ($arg eq '-p') {
647 $verbosity = $PROGRESS;
648 $| = 1; # Flush buffers as we go.
649 }
650 elsif ($arg eq '-q') {
651 $verbosity = 0;
652 }
653 elsif ($arg eq '-w') {
654 $write_unchanged_files = 1; # update the files even if havent changed
655 }
656 elsif ($arg eq '-check') {
6ae7e459
YO
657 my $this = shift @ARGV;
658 my $ok = shift @ARGV;
659 if ($this ne $ok) {
660 print "Skipping as check params are not the same.\n";
661 exit(0);
662 }
00a8df5c 663 }
99870f4d
KW
664 elsif ($arg eq '-P' && defined ($pod_directory = shift)) {
665 -d $pod_directory or croak "Directory '$pod_directory' doesn't exist";
666 }
3df51b85
KW
667 elsif ($arg eq '-maketest' || ($arg eq '-T' && defined ($t_path = shift)))
668 {
99870f4d 669 $make_test_script = 1;
99870f4d
KW
670 }
671 elsif ($arg eq '-makelist') {
672 $make_list = 1;
673 }
674 elsif ($arg eq '-C' && defined ($use_directory = shift)) {
675 -d $use_directory or croak "Unknown directory '$use_directory'";
676 }
677 elsif ($arg eq '-L') {
678
679 # Existence not tested until have chdir'd
680 $file_list = shift;
681 }
682 elsif ($arg eq '-globlist') {
683 $glob_list = 1;
684 }
685 elsif ($arg eq '-c') {
686 $output_range_counts = ! $output_range_counts
687 }
b4a0206c 688 elsif ($arg eq '-annotate') {
558712cf 689 $annotate = 1;
bd9ebcfd
KW
690 $debugging_build = 1;
691 $output_range_counts = 1;
9ef2b94f 692 }
99870f4d
KW
693 else {
694 my $with_c = 'with';
695 $with_c .= 'out' if $output_range_counts; # Complements the state
696 croak <<END;
697usage: $0 [-c|-p|-q|-v|-w] [-C dir] [-L filelist] [ -P pod_dir ]
698 [ -T test_file_path ] [-globlist] [-makelist] [-maketest]
699 [-check A B ]
700 -c : Output comments $with_c number of code points in ranges
701 -q : Quiet Mode: Only output serious warnings.
702 -p : Set verbosity level to normal plus show progress.
703 -v : Set Verbosity level high: Show progress and non-serious
704 warnings
705 -w : Write files regardless
706 -C dir : Change to this directory before proceeding. All relative paths
707 except those specified by the -P and -T options will be done
708 with respect to this directory.
709 -P dir : Output $pod_file file to directory 'dir'.
3df51b85 710 -T path : Create a test script as 'path'; overrides -maketest
99870f4d
KW
711 -L filelist : Use alternate 'filelist' instead of standard one
712 -globlist : Take as input all non-Test *.txt files in current and sub
713 directories
3df51b85
KW
714 -maketest : Make test script 'TestProp.pl' in current (or -C directory),
715 overrides -T
99870f4d 716 -makelist : Rewrite the file list $file_list based on current setup
b4a0206c 717 -annotate : Output an annotation for each character in the table files;
c4019d52 718 useful for debugging mktables, looking at diffs; but is slow,
b318e5e5
KW
719 memory intensive; resulting tables are usable but are slow and
720 very large (and currently fail the Unicode::UCD.t tests).
99870f4d
KW
721 -check A B : Executes $0 only if A and B are the same
722END
723 }
724}
725
726# Stores the most-recently changed file. If none have changed, can skip the
727# build
aeab6150 728my $most_recent = (stat $0)[9]; # Do this before the chdir!
99870f4d
KW
729
730# Change directories now, because need to read 'version' early.
731if ($use_directory) {
3df51b85 732 if ($pod_directory && ! File::Spec->file_name_is_absolute($pod_directory)) {
99870f4d
KW
733 $pod_directory = File::Spec->rel2abs($pod_directory);
734 }
3df51b85 735 if ($t_path && ! File::Spec->file_name_is_absolute($t_path)) {
99870f4d 736 $t_path = File::Spec->rel2abs($t_path);
00a8df5c 737 }
99870f4d 738 chdir $use_directory or croak "Failed to chdir to '$use_directory':$!";
3df51b85 739 if ($pod_directory && File::Spec->file_name_is_absolute($pod_directory)) {
99870f4d 740 $pod_directory = File::Spec->abs2rel($pod_directory);
02b1aeec 741 }
3df51b85 742 if ($t_path && File::Spec->file_name_is_absolute($t_path)) {
99870f4d 743 $t_path = File::Spec->abs2rel($t_path);
02b1aeec 744 }
00a8df5c
YO
745}
746
99870f4d
KW
747# Get Unicode version into regular and v-string. This is done now because
748# various tables below get populated based on it. These tables are populated
749# here to be near the top of the file, and so easily seeable by those needing
750# to modify things.
751open my $VERSION, "<", "version"
752 or croak "$0: can't open required file 'version': $!\n";
753my $string_version = <$VERSION>;
754close $VERSION;
755chomp $string_version;
756my $v_version = pack "C*", split /\./, $string_version; # v string
757
758# The following are the complete names of properties with property values that
759# are known to not match any code points in some versions of Unicode, but that
760# may change in the future so they should be matchable, hence an empty file is
761# generated for them.
762my @tables_that_may_be_empty = (
763 'Joining_Type=Left_Joining',
764 );
765push @tables_that_may_be_empty, 'Script=Common' if $v_version le v4.0.1;
766push @tables_that_may_be_empty, 'Title' if $v_version lt v2.0.0;
767push @tables_that_may_be_empty, 'Script=Katakana_Or_Hiragana'
768 if $v_version ge v4.1.0;
82aed44a
KW
769push @tables_that_may_be_empty, 'Script_Extensions=Katakana_Or_Hiragana'
770 if $v_version ge v6.0.0;
f583b44c
KW
771push @tables_that_may_be_empty, 'Grapheme_Cluster_Break=Prepend'
772 if $v_version ge v6.1.0;
99870f4d
KW
773
774# The lists below are hashes, so the key is the item in the list, and the
775# value is the reason why it is in the list. This makes generation of
776# documentation easier.
777
778my %why_suppressed; # No file generated for these.
779
780# Files aren't generated for empty extraneous properties. This is arguable.
781# Extraneous properties generally come about because a property is no longer
782# used in a newer version of Unicode. If we generated a file without code
783# points, programs that used to work on that property will still execute
784# without errors. It just won't ever match (or will always match, with \P{}).
785# This means that the logic is now likely wrong. I (khw) think its better to
786# find this out by getting an error message. Just move them to the table
787# above to change this behavior
788my %why_suppress_if_empty_warn_if_not = (
789
790 # It is the only property that has ever officially been removed from the
791 # Standard. The database never contained any code points for it.
792 'Special_Case_Condition' => 'Obsolete',
793
794 # Apparently never official, but there were code points in some versions of
795 # old-style PropList.txt
796 'Non_Break' => 'Obsolete',
797);
798
799# These would normally go in the warn table just above, but they were changed
800# a long time before this program was written, so warnings about them are
801# moot.
802if ($v_version gt v3.2.0) {
803 push @tables_that_may_be_empty,
804 'Canonical_Combining_Class=Attached_Below_Left'
805}
806
5f7264c7 807# These are listed in the Property aliases file in 6.0, but Unihan is ignored
99870f4d
KW
808# unless explicitly added.
809if ($v_version ge v5.2.0) {
810 my $unihan = 'Unihan; remove from list if using Unihan';
ea25a9b2 811 foreach my $table (qw (
99870f4d
KW
812 kAccountingNumeric
813 kOtherNumeric
814 kPrimaryNumeric
815 kCompatibilityVariant
816 kIICore
817 kIRG_GSource
818 kIRG_HSource
819 kIRG_JSource
820 kIRG_KPSource
821 kIRG_MSource
822 kIRG_KSource
823 kIRG_TSource
824 kIRG_USource
825 kIRG_VSource
826 kRSUnicode
ea25a9b2 827 ))
99870f4d
KW
828 {
829 $why_suppress_if_empty_warn_if_not{$table} = $unihan;
830 }
ca12659b
NC
831}
832
272501f6
KW
833# Enum values for to_output_map() method in the Map_Table package.
834my $EXTERNAL_MAP = 1;
835my $INTERNAL_MAP = 2;
bbed833a 836my $OUTPUT_DELTAS = 3;
272501f6 837
fcf1973c
KW
838# To override computed values for writing the map tables for these properties.
839# The default for enum map tables is to write them out, so that the Unicode
840# .txt files can be removed, but all the data to compute any property value
841# for any code point is available in a more compact form.
842my %global_to_output_map = (
843 # Needed by UCD.pm, but don't want to publicize that it exists, so won't
c12f2655
KW
844 # get stuck supporting it if things change. Since it is a STRING
845 # property, it normally would be listed in the pod, but INTERNAL_MAP
846 # suppresses that.
fcf1973c
KW
847 Unicode_1_Name => $INTERNAL_MAP,
848
849 Present_In => 0, # Suppress, as easily computed from Age
fcf1973c 850 Block => 0, # Suppress, as Blocks.txt is retained.
53d34b6c
KW
851
852 # Suppress, as mapping can be found instead from the
853 # Perl_Decomposition_Mapping file
854 Decomposition_Type => 0,
fcf1973c
KW
855);
856
99870f4d 857# Properties that this program ignores.
230e0c16
KW
858my @unimplemented_properties;
859
860# With this release, it is automatically handled if the Unihan db is
861# downloaded
862push @unimplemented_properties, 'Unicode_Radical_Stroke' if $v_version le v5.2.0;
d73e5302 863
99870f4d
KW
864# There are several types of obsolete properties defined by Unicode. These
865# must be hand-edited for every new Unicode release.
866my %why_deprecated; # Generates a deprecated warning message if used.
867my %why_stabilized; # Documentation only
868my %why_obsolete; # Documentation only
869
870{ # Closure
871 my $simple = 'Perl uses the more complete version of this property';
872 my $unihan = 'Unihan properties are by default not enabled in the Perl core. Instead use CPAN: Unicode::Unihan';
873
874 my $other_properties = 'other properties';
875 my $contributory = "Used by Unicode internally for generating $other_properties and not intended to be used stand-alone";
5d294d41 876 my $why_no_expand = "Deprecated by Unicode. These are characters that expand to more than one character in the specified normalization form, but whether they actually take up more bytes or not depends on the encoding being used. For example, a UTF-8 encoded character may expand to a different number of bytes than a UTF-32 encoded character.";
99870f4d
KW
877
878 %why_deprecated = (
5f7264c7 879 'Grapheme_Link' => 'Deprecated by Unicode: Duplicates ccc=vr (Canonical_Combining_Class=Virama)',
99870f4d
KW
880 'Jamo_Short_Name' => $contributory,
881 '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',
882 'Other_Alphabetic' => $contributory,
883 'Other_Default_Ignorable_Code_Point' => $contributory,
884 'Other_Grapheme_Extend' => $contributory,
885 'Other_ID_Continue' => $contributory,
886 'Other_ID_Start' => $contributory,
887 'Other_Lowercase' => $contributory,
888 'Other_Math' => $contributory,
889 'Other_Uppercase' => $contributory,
e22aaf5c
KW
890 'Expands_On_NFC' => $why_no_expand,
891 'Expands_On_NFD' => $why_no_expand,
892 'Expands_On_NFKC' => $why_no_expand,
893 'Expands_On_NFKD' => $why_no_expand,
99870f4d
KW
894 );
895
896 %why_suppressed = (
5f7264c7 897 # There is a lib/unicore/Decomposition.pl (used by Normalize.pm) which
99870f4d
KW
898 # contains the same information, but without the algorithmically
899 # determinable Hangul syllables'. This file is not published, so it's
900 # existence is not noted in the comment.
e0b29447 901 'Decomposition_Mapping' => 'Accessible via Unicode::Normalize or Unicode::UCD::prop_invmap()',
99870f4d 902
3111abc0
KW
903 'Indic_Matra_Category' => "Provisional",
904 'Indic_Syllabic_Category' => "Provisional",
905
5f8d1a89
KW
906 # Don't suppress ISO_Comment, as otherwise special handling is needed
907 # to differentiate between it and gc=c, which can be written as 'isc',
908 # which is the same characters as ISO_Comment's short name.
99870f4d 909
fbb93542 910 'Name' => "Accessible via \\N{...} or 'use charnames;' or Unicode::UCD::prop_invmap()",
e0b29447
KW
911
912 'Simple_Case_Folding' => "$simple. Can access this through Unicode::UCD::casefold or Unicode::UCD::prop_invmap()",
913 'Simple_Lowercase_Mapping' => "$simple. Can access this through Unicode::UCD::charinfo or Unicode::UCD::prop_invmap()",
914 'Simple_Titlecase_Mapping' => "$simple. Can access this through Unicode::UCD::charinfo or Unicode::UCD::prop_invmap()",
915 'Simple_Uppercase_Mapping' => "$simple. Can access this through Unicode::UCD::charinfo or Unicode::UCD::prop_invmap()",
99870f4d 916
5f7264c7 917 FC_NFKC_Closure => 'Supplanted in usage by NFKC_Casefold; otherwise not useful',
99870f4d
KW
918 );
919
1704a0ea
KW
920 foreach my $property (
921
922 # The following are suppressed because they were made contributory
923 # or deprecated by Unicode before Perl ever thought about
924 # supporting them.
925 'Jamo_Short_Name',
926 'Grapheme_Link',
927 'Expands_On_NFC',
928 'Expands_On_NFD',
929 'Expands_On_NFKC',
930 'Expands_On_NFKD',
931
932 # The following are suppressed because they have been marked
933 # as deprecated for a sufficient amount of time
934 'Other_Alphabetic',
935 'Other_Default_Ignorable_Code_Point',
936 'Other_Grapheme_Extend',
937 'Other_ID_Continue',
938 'Other_ID_Start',
939 'Other_Lowercase',
940 'Other_Math',
941 'Other_Uppercase',
e22aaf5c 942 ) {
99870f4d
KW
943 $why_suppressed{$property} = $why_deprecated{$property};
944 }
cf25bb62 945
99870f4d
KW
946 # Customize the message for all the 'Other_' properties
947 foreach my $property (keys %why_deprecated) {
948 next if (my $main_property = $property) !~ s/^Other_//;
949 $why_deprecated{$property} =~ s/$other_properties/the $main_property property (which should be used instead)/;
950 }
951}
952
953if ($v_version ge 4.0.0) {
954 $why_stabilized{'Hyphen'} = 'Use the Line_Break property instead; see www.unicode.org/reports/tr14';
5f7264c7
KW
955 if ($v_version ge 6.0.0) {
956 $why_deprecated{'Hyphen'} = 'Supplanted by Line_Break property values; see www.unicode.org/reports/tr14';
957 }
99870f4d 958}
5f7264c7 959if ($v_version ge 5.2.0 && $v_version lt 6.0.0) {
99870f4d 960 $why_obsolete{'ISO_Comment'} = 'Code points for it have been removed';
5f7264c7 961 if ($v_version ge 6.0.0) {
63f74647 962 $why_deprecated{'ISO_Comment'} = 'No longer needed for Unicode\'s internal chart generation; otherwise not useful, and code points for it have been removed';
5f7264c7 963 }
99870f4d
KW
964}
965
966# Probably obsolete forever
967if ($v_version ge v4.1.0) {
82aed44a
KW
968 $why_suppressed{'Script=Katakana_Or_Hiragana'} = 'Obsolete. All code points previously matched by this have been moved to "Script=Common".';
969}
970if ($v_version ge v6.0.0) {
2b352efd
KW
971 $why_suppressed{'Script=Katakana_Or_Hiragana'} .= ' Consider instead using "Script_Extensions=Katakana" or "Script_Extensions=Hiragana (or both)"';
972 $why_suppressed{'Script_Extensions=Katakana_Or_Hiragana'} = 'All code points that would be matched by this are matched by either "Script_Extensions=Katakana" or "Script_Extensions=Hiragana"';
99870f4d
KW
973}
974
975# This program can create files for enumerated-like properties, such as
976# 'Numeric_Type'. This file would be the same format as for a string
977# property, with a mapping from code point to its value, so you could look up,
978# for example, the script a code point is in. But no one so far wants this
979# mapping, or they have found another way to get it since this is a new
980# feature. So no file is generated except if it is in this list.
981my @output_mapped_properties = split "\n", <<END;
982END
983
c12f2655
KW
984# If you are using the Unihan database in a Unicode version before 5.2, you
985# need to add the properties that you want to extract from it to this table.
986# For your convenience, the properties in the 6.0 PropertyAliases.txt file are
987# listed, commented out
99870f4d
KW
988my @cjk_properties = split "\n", <<'END';
989#cjkAccountingNumeric; kAccountingNumeric
990#cjkOtherNumeric; kOtherNumeric
991#cjkPrimaryNumeric; kPrimaryNumeric
992#cjkCompatibilityVariant; kCompatibilityVariant
993#cjkIICore ; kIICore
994#cjkIRG_GSource; kIRG_GSource
995#cjkIRG_HSource; kIRG_HSource
996#cjkIRG_JSource; kIRG_JSource
997#cjkIRG_KPSource; kIRG_KPSource
998#cjkIRG_KSource; kIRG_KSource
999#cjkIRG_TSource; kIRG_TSource
1000#cjkIRG_USource; kIRG_USource
1001#cjkIRG_VSource; kIRG_VSource
1002#cjkRSUnicode; kRSUnicode ; Unicode_Radical_Stroke; URS
1003END
1004
1005# Similarly for the property values. For your convenience, the lines in the
5f7264c7 1006# 6.0 PropertyAliases.txt file are listed. Just remove the first BUT NOT both
c12f2655 1007# '#' marks (for Unicode versions before 5.2)
99870f4d
KW
1008my @cjk_property_values = split "\n", <<'END';
1009## @missing: 0000..10FFFF; cjkAccountingNumeric; NaN
1010## @missing: 0000..10FFFF; cjkCompatibilityVariant; <code point>
1011## @missing: 0000..10FFFF; cjkIICore; <none>
1012## @missing: 0000..10FFFF; cjkIRG_GSource; <none>
1013## @missing: 0000..10FFFF; cjkIRG_HSource; <none>
1014## @missing: 0000..10FFFF; cjkIRG_JSource; <none>
1015## @missing: 0000..10FFFF; cjkIRG_KPSource; <none>
1016## @missing: 0000..10FFFF; cjkIRG_KSource; <none>
1017## @missing: 0000..10FFFF; cjkIRG_TSource; <none>
1018## @missing: 0000..10FFFF; cjkIRG_USource; <none>
1019## @missing: 0000..10FFFF; cjkIRG_VSource; <none>
1020## @missing: 0000..10FFFF; cjkOtherNumeric; NaN
1021## @missing: 0000..10FFFF; cjkPrimaryNumeric; NaN
1022## @missing: 0000..10FFFF; cjkRSUnicode; <none>
1023END
1024
1025# The input files don't list every code point. Those not listed are to be
1026# defaulted to some value. Below are hard-coded what those values are for
1027# non-binary properties as of 5.1. Starting in 5.0, there are
1028# machine-parsable comment lines in the files the give the defaults; so this
1029# list shouldn't have to be extended. The claim is that all missing entries
1030# for binary properties will default to 'N'. Unicode tried to change that in
1031# 5.2, but the beta period produced enough protest that they backed off.
1032#
1033# The defaults for the fields that appear in UnicodeData.txt in this hash must
1034# be in the form that it expects. The others may be synonyms.
1035my $CODE_POINT = '<code point>';
1036my %default_mapping = (
1037 Age => "Unassigned",
1038 # Bidi_Class => Complicated; set in code
1039 Bidi_Mirroring_Glyph => "",
1040 Block => 'No_Block',
1041 Canonical_Combining_Class => 0,
1042 Case_Folding => $CODE_POINT,
1043 Decomposition_Mapping => $CODE_POINT,
1044 Decomposition_Type => 'None',
1045 East_Asian_Width => "Neutral",
1046 FC_NFKC_Closure => $CODE_POINT,
1047 General_Category => 'Cn',
1048 Grapheme_Cluster_Break => 'Other',
1049 Hangul_Syllable_Type => 'NA',
1050 ISO_Comment => "",
1051 Jamo_Short_Name => "",
1052 Joining_Group => "No_Joining_Group",
1053 # Joining_Type => Complicated; set in code
1054 kIICore => 'N', # Is converted to binary
1055 #Line_Break => Complicated; set in code
1056 Lowercase_Mapping => $CODE_POINT,
1057 Name => "",
1058 Name_Alias => "",
1059 NFC_QC => 'Yes',
1060 NFD_QC => 'Yes',
1061 NFKC_QC => 'Yes',
1062 NFKD_QC => 'Yes',
1063 Numeric_Type => 'None',
1064 Numeric_Value => 'NaN',
1065 Script => ($v_version le 4.1.0) ? 'Common' : 'Unknown',
1066 Sentence_Break => 'Other',
1067 Simple_Case_Folding => $CODE_POINT,
1068 Simple_Lowercase_Mapping => $CODE_POINT,
1069 Simple_Titlecase_Mapping => $CODE_POINT,
1070 Simple_Uppercase_Mapping => $CODE_POINT,
1071 Titlecase_Mapping => $CODE_POINT,
1072 Unicode_1_Name => "",
1073 Unicode_Radical_Stroke => "",
1074 Uppercase_Mapping => $CODE_POINT,
1075 Word_Break => 'Other',
1076);
1077
1078# Below are files that Unicode furnishes, but this program ignores, and why
1079my %ignored_files = (
73ba1144
KW
1080 'CJKRadicals.txt' => 'Maps the kRSUnicode property values to corresponding code points',
1081 'Index.txt' => 'Alphabetical index of Unicode characters',
1082 'NamedSqProv.txt' => 'Named sequences proposed for inclusion in a later version of the Unicode Standard; if you need them now, you can append this file to F<NamedSequences.txt> and recompile perl',
1083 'NamesList.txt' => 'Annotated list of characters',
1084 'NormalizationCorrections.txt' => 'Documentation of corrections already incorporated into the Unicode data base',
1085 'Props.txt' => 'Only in very early releases; is a subset of F<PropList.txt> (which is used instead)',
1086 'ReadMe.txt' => 'Documentation',
1087 'StandardizedVariants.txt' => 'Certain glyph variations for character display are standardized. This lists the non-Unihan ones; the Unihan ones are also not used by Perl, and are in a separate Unicode data base L<http://www.unicode.org/ivd>',
1088 'EmojiSources.txt' => 'Maps certain Unicode code points to their legacy Japanese cell-phone values',
73ba1144
KW
1089 'auxiliary/WordBreakTest.html' => 'Documentation of validation tests',
1090 'auxiliary/SentenceBreakTest.html' => 'Documentation of validation tests',
1091 'auxiliary/GraphemeBreakTest.html' => 'Documentation of validation tests',
1092 'auxiliary/LineBreakTest.html' => 'Documentation of validation tests',
99870f4d
KW
1093);
1094
1fec9f60
KW
1095my %skipped_files; # List of files that we skip
1096
678f13d5 1097### End of externally interesting definitions, except for @input_file_objects
99870f4d
KW
1098
1099my $HEADER=<<"EOF";
1100# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
3df51b85
KW
1101# This file is machine-generated by $0 from the Unicode
1102# database, Version $string_version. Any changes made here will be lost!
cf25bb62
JH
1103EOF
1104
126c3d4e 1105my $INTERNAL_ONLY_HEADER = <<"EOF";
99870f4d
KW
1106
1107# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
fac53429
KW
1108# This file is for internal use by core Perl only. The format and even the
1109# name or existence of this file are subject to change without notice. Don't
1110# use it directly.
99870f4d
KW
1111EOF
1112
1113my $DEVELOPMENT_ONLY=<<"EOF";
1114# !!!!!!! DEVELOPMENT USE ONLY !!!!!!!
1115# This file contains information artificially constrained to code points
1116# present in Unicode release $string_compare_versions.
1117# IT CANNOT BE RELIED ON. It is for use during development only and should
23e33b60 1118# not be used for production.
b6922eda
KW
1119
1120EOF
1121
6189eadc
KW
1122my $MAX_UNICODE_CODEPOINT_STRING = "10FFFF";
1123my $MAX_UNICODE_CODEPOINT = hex $MAX_UNICODE_CODEPOINT_STRING;
1124my $MAX_UNICODE_CODEPOINTS = $MAX_UNICODE_CODEPOINT + 1;
99870f4d
KW
1125
1126# Matches legal code point. 4-6 hex numbers, If there are 6, the first
1127# two must be 10; if there are 5, the first must not be a 0. Written this way
92199589
KW
1128# to decrease backtracking. The first regex allows the code point to be at
1129# the end of a word, but to work properly, the word shouldn't end with a valid
1130# hex character. The second one won't match a code point at the end of a
1131# word, and doesn't have the run-on issue
8c32d378
KW
1132my $run_on_code_point_re =
1133 qr/ (?: 10[0-9A-F]{4} | [1-9A-F][0-9A-F]{4} | [0-9A-F]{4} ) \b/x;
1134my $code_point_re = qr/\b$run_on_code_point_re/;
99870f4d
KW
1135
1136# This matches the beginning of the line in the Unicode db files that give the
1137# defaults for code points not listed (i.e., missing) in the file. The code
1138# depends on this ending with a semi-colon, so it can assume it is a valid
1139# field when the line is split() by semi-colons
1140my $missing_defaults_prefix =
6189eadc 1141 qr/^#\s+\@missing:\s+0000\.\.$MAX_UNICODE_CODEPOINT_STRING\s*;/;
99870f4d
KW
1142
1143# Property types. Unicode has more types, but these are sufficient for our
1144# purposes.
1145my $UNKNOWN = -1; # initialized to illegal value
1146my $NON_STRING = 1; # Either binary or enum
1147my $BINARY = 2;
06f26c45
KW
1148my $FORCED_BINARY = 3; # Not a binary property, but, besides its normal
1149 # tables, additional true and false tables are
1150 # generated so that false is anything matching the
1151 # default value, and true is everything else.
1152my $ENUM = 4; # Include catalog
1153my $STRING = 5; # Anything else: string or misc
99870f4d
KW
1154
1155# Some input files have lines that give default values for code points not
1156# contained in the file. Sometimes these should be ignored.
1157my $NO_DEFAULTS = 0; # Must evaluate to false
1158my $NOT_IGNORED = 1;
1159my $IGNORED = 2;
1160
1161# Range types. Each range has a type. Most ranges are type 0, for normal,
1162# and will appear in the main body of the tables in the output files, but
1163# there are other types of ranges as well, listed below, that are specially
1164# handled. There are pseudo-types as well that will never be stored as a
1165# type, but will affect the calculation of the type.
1166
1167# 0 is for normal, non-specials
1168my $MULTI_CP = 1; # Sequence of more than code point
1169my $HANGUL_SYLLABLE = 2;
1170my $CP_IN_NAME = 3; # The NAME contains the code point appended to it.
1171my $NULL = 4; # The map is to the null string; utf8.c can't
1172 # handle these, nor is there an accepted syntax
1173 # for them in \p{} constructs
f86864ac 1174my $COMPUTE_NO_MULTI_CP = 5; # Pseudo-type; means that ranges that would
99870f4d
KW
1175 # otherwise be $MULTI_CP type are instead type 0
1176
1177# process_generic_property_file() can accept certain overrides in its input.
1178# Each of these must begin AND end with $CMD_DELIM.
1179my $CMD_DELIM = "\a";
1180my $REPLACE_CMD = 'replace'; # Override the Replace
1181my $MAP_TYPE_CMD = 'map_type'; # Override the Type
1182
1183my $NO = 0;
1184my $YES = 1;
1185
1186# Values for the Replace argument to add_range.
1187# $NO # Don't replace; add only the code points not
1188 # already present.
1189my $IF_NOT_EQUIVALENT = 1; # Replace only under certain conditions; details in
1190 # the comments at the subroutine definition.
1191my $UNCONDITIONALLY = 2; # Replace without conditions.
9470941f 1192my $MULTIPLE_BEFORE = 4; # Don't replace, but add a duplicate record if
99870f4d 1193 # already there
7f4b1e25
KW
1194my $MULTIPLE_AFTER = 5; # Don't replace, but add a duplicate record if
1195 # already there
1196my $CROAK = 6; # Die with an error if is already there
99870f4d
KW
1197
1198# Flags to give property statuses. The phrases are to remind maintainers that
1199# if the flag is changed, the indefinite article referring to it in the
1200# documentation may need to be as well.
1201my $NORMAL = "";
99870f4d
KW
1202my $DEPRECATED = 'D';
1203my $a_bold_deprecated = "a 'B<$DEPRECATED>'";
1204my $A_bold_deprecated = "A 'B<$DEPRECATED>'";
1205my $DISCOURAGED = 'X';
1206my $a_bold_discouraged = "an 'B<$DISCOURAGED>'";
1207my $A_bold_discouraged = "An 'B<$DISCOURAGED>'";
1208my $STRICTER = 'T';
1209my $a_bold_stricter = "a 'B<$STRICTER>'";
1210my $A_bold_stricter = "A 'B<$STRICTER>'";
1211my $STABILIZED = 'S';
1212my $a_bold_stabilized = "an 'B<$STABILIZED>'";
1213my $A_bold_stabilized = "An 'B<$STABILIZED>'";
1214my $OBSOLETE = 'O';
1215my $a_bold_obsolete = "an 'B<$OBSOLETE>'";
1216my $A_bold_obsolete = "An 'B<$OBSOLETE>'";
1217
1218my %status_past_participles = (
1219 $DISCOURAGED => 'discouraged',
99870f4d
KW
1220 $STABILIZED => 'stabilized',
1221 $OBSOLETE => 'obsolete',
37e2e78e 1222 $DEPRECATED => 'deprecated',
99870f4d
KW
1223);
1224
395dfc19
KW
1225# Table fates. These are somewhat ordered, so that fates < $MAP_PROXIED should be
1226# externally documented.
301ba948 1227my $ORDINARY = 0; # The normal fate.
395dfc19
KW
1228my $MAP_PROXIED = 1; # The map table for the property isn't written out,
1229 # but there is a file written that can be used to
1230 # reconstruct this table
301ba948
KW
1231my $SUPPRESSED = 3; # The file for this table is not written out.
1232my $INTERNAL_ONLY = 4; # The file for this table is written out, but it is
1233 # for Perl's internal use only
1234my $PLACEHOLDER = 5; # A property that is defined as a placeholder in a
1235 # Unicode version that doesn't have it, but we need it
1236 # to be defined, if empty, to have things work.
1237 # Implies no pod entry generated
1238
f5817e0a
KW
1239# The format of the values of the tables:
1240my $EMPTY_FORMAT = "";
99870f4d
KW
1241my $BINARY_FORMAT = 'b';
1242my $DECIMAL_FORMAT = 'd';
1243my $FLOAT_FORMAT = 'f';
1244my $INTEGER_FORMAT = 'i';
1245my $HEX_FORMAT = 'x';
1246my $RATIONAL_FORMAT = 'r';
1247my $STRING_FORMAT = 's';
a14f3cb1 1248my $DECOMP_STRING_FORMAT = 'c';
c3ff2976 1249my $STRING_WHITE_SPACE_LIST = 'sw';
99870f4d
KW
1250
1251my %map_table_formats = (
1252 $BINARY_FORMAT => 'binary',
1253 $DECIMAL_FORMAT => 'single decimal digit',
1254 $FLOAT_FORMAT => 'floating point number',
1255 $INTEGER_FORMAT => 'integer',
add63c13 1256 $HEX_FORMAT => 'non-negative hex whole number; a code point',
99870f4d 1257 $RATIONAL_FORMAT => 'rational: an integer or a fraction',
1a9d544b 1258 $STRING_FORMAT => 'string',
92f9d56c 1259 $DECOMP_STRING_FORMAT => 'Perl\'s internal (Normalize.pm) decomposition mapping',
c3ff2976 1260 $STRING_WHITE_SPACE_LIST => 'string, but some elements are interpreted as a list; white space occurs only as list item separators'
99870f4d
KW
1261);
1262
1263# Unicode didn't put such derived files in a separate directory at first.
1264my $EXTRACTED_DIR = (-d 'extracted') ? 'extracted' : "";
1265my $EXTRACTED = ($EXTRACTED_DIR) ? "$EXTRACTED_DIR/" : "";
1266my $AUXILIARY = 'auxiliary';
1267
1268# Hashes that will eventually go into Heavy.pl for the use of utf8_heavy.pl
9e4a1e86 1269# and into UCD.pl for the use of UCD.pm
99870f4d
KW
1270my %loose_to_file_of; # loosely maps table names to their respective
1271 # files
1272my %stricter_to_file_of; # same; but for stricter mapping.
315bfd4e 1273my %loose_property_to_file_of; # Maps a loose property name to its map file
89cf10cc
KW
1274my %file_to_swash_name; # Maps the file name to its corresponding key name
1275 # in the hash %utf8::SwashInfo
99870f4d
KW
1276my %nv_floating_to_rational; # maps numeric values floating point numbers to
1277 # their rational equivalent
c12f2655
KW
1278my %loose_property_name_of; # Loosely maps (non_string) property names to
1279 # standard form
86a52d1e 1280my %string_property_loose_to_name; # Same, for string properties.
c15fda25
KW
1281my %loose_defaults; # keys are of form "prop=value", where 'prop' is
1282 # the property name in standard loose form, and
1283 # 'value' is the default value for that property,
1284 # also in standard loose form.
9e4a1e86
KW
1285my %loose_to_standard_value; # loosely maps table names to the canonical
1286 # alias for them
2df7880f
KW
1287my %ambiguous_names; # keys are alias names (in standard form) that
1288 # have more than one possible meaning.
5d1df013
KW
1289my %prop_aliases; # Keys are standard property name; values are each
1290 # one's aliases
1e863613
KW
1291my %prop_value_aliases; # Keys of top level are standard property name;
1292 # values are keys to another hash, Each one is
1293 # one of the property's values, in standard form.
1294 # The values are that prop-val's aliases.
2df7880f 1295my %ucd_pod; # Holds entries that will go into the UCD section of the pod
99870f4d 1296
d867ccfb
KW
1297# Most properties are immune to caseless matching, otherwise you would get
1298# nonsensical results, as properties are a function of a code point, not
1299# everything that is caselessly equivalent to that code point. For example,
1300# Changes_When_Case_Folded('s') should be false, whereas caselessly it would
1301# be true because 's' and 'S' are equivalent caselessly. However,
1302# traditionally, [:upper:] and [:lower:] are equivalent caselessly, so we
1303# extend that concept to those very few properties that are like this. Each
1304# such property will match the full range caselessly. They are hard-coded in
1305# the program; it's not worth trying to make it general as it's extremely
1306# unlikely that they will ever change.
1307my %caseless_equivalent_to;
1308
99870f4d
KW
1309# These constants names and values were taken from the Unicode standard,
1310# version 5.1, section 3.12. They are used in conjunction with Hangul
6e5a209b
KW
1311# syllables. The '_string' versions are so generated tables can retain the
1312# hex format, which is the more familiar value
1313my $SBase_string = "0xAC00";
1314my $SBase = CORE::hex $SBase_string;
1315my $LBase_string = "0x1100";
1316my $LBase = CORE::hex $LBase_string;
1317my $VBase_string = "0x1161";
1318my $VBase = CORE::hex $VBase_string;
1319my $TBase_string = "0x11A7";
1320my $TBase = CORE::hex $TBase_string;
99870f4d
KW
1321my $SCount = 11172;
1322my $LCount = 19;
1323my $VCount = 21;
1324my $TCount = 28;
1325my $NCount = $VCount * $TCount;
1326
1327# For Hangul syllables; These store the numbers from Jamo.txt in conjunction
1328# with the above published constants.
1329my %Jamo;
1330my %Jamo_L; # Leading consonants
1331my %Jamo_V; # Vowels
1332my %Jamo_T; # Trailing consonants
1333
bb1dd3da
KW
1334# For code points whose name contains its ordinal as a '-ABCD' suffix.
1335# The key is the base name of the code point, and the value is an
1336# array giving all the ranges that use this base name. Each range
1337# is actually a hash giving the 'low' and 'high' values of it.
1338my %names_ending_in_code_point;
1339my %loose_names_ending_in_code_point; # Same as above, but has blanks, dashes
1340 # removed from the names
1341# Inverse mapping. The list of ranges that have these kinds of
1342# names. Each element contains the low, high, and base names in an
1343# anonymous hash.
1344my @code_points_ending_in_code_point;
1345
1346# Boolean: does this Unicode version have the hangul syllables, and are we
1347# writing out a table for them?
1348my $has_hangul_syllables = 0;
1349
1350# Does this Unicode version have code points whose names end in their
1351# respective code points, and are we writing out a table for them? 0 for no;
1352# otherwise points to first property that a table is needed for them, so that
1353# if multiple tables are needed, we don't create duplicates
1354my $needing_code_points_ending_in_code_point = 0;
1355
37e2e78e 1356my @backslash_X_tests; # List of tests read in for testing \X
99870f4d
KW
1357my @unhandled_properties; # Will contain a list of properties found in
1358 # the input that we didn't process.
f86864ac 1359my @match_properties; # Properties that have match tables, to be
99870f4d
KW
1360 # listed in the pod
1361my @map_properties; # Properties that get map files written
1362my @named_sequences; # NamedSequences.txt contents.
1363my %potential_files; # Generated list of all .txt files in the directory
1364 # structure so we can warn if something is being
1365 # ignored.
1366my @files_actually_output; # List of files we generated.
1367my @more_Names; # Some code point names are compound; this is used
1368 # to store the extra components of them.
1369my $MIN_FRACTION_LENGTH = 3; # How many digits of a floating point number at
1370 # the minimum before we consider it equivalent to a
1371 # candidate rational
1372my $MAX_FLOATING_SLOP = 10 ** - $MIN_FRACTION_LENGTH; # And in floating terms
1373
1374# These store references to certain commonly used property objects
1375my $gc;
1376my $perl;
1377my $block;
3e20195b
KW
1378my $perl_charname;
1379my $print;
7fc6cb55 1380my $Any;
359523e2 1381my $script;
99870f4d
KW
1382
1383# Are there conflicting names because of beginning with 'In_', or 'Is_'
1384my $has_In_conflicts = 0;
1385my $has_Is_conflicts = 0;
1386
1387sub internal_file_to_platform ($) {
1388 # Convert our file paths which have '/' separators to those of the
1389 # platform.
1390
1391 my $file = shift;
1392 return undef unless defined $file;
1393
1394 return File::Spec->join(split '/', $file);
d07a55ed 1395}
5beb625e 1396
99870f4d
KW
1397sub file_exists ($) { # platform independent '-e'. This program internally
1398 # uses slash as a path separator.
1399 my $file = shift;
1400 return 0 if ! defined $file;
1401 return -e internal_file_to_platform($file);
1402}
5beb625e 1403
99870f4d 1404sub objaddr($) {
23e33b60
KW
1405 # Returns the address of the blessed input object.
1406 # It doesn't check for blessedness because that would do a string eval
1407 # every call, and the program is structured so that this is never called
1408 # for a non-blessed object.
99870f4d 1409
23e33b60 1410 no overloading; # If overloaded, numifying below won't work.
99870f4d
KW
1411
1412 # Numifying a ref gives its address.
051df77b 1413 return pack 'J', $_[0];
99870f4d
KW
1414}
1415
558712cf 1416# These are used only if $annotate is true.
c4019d52
KW
1417# The entire range of Unicode characters is examined to populate these
1418# after all the input has been processed. But most can be skipped, as they
1419# have the same descriptive phrases, such as being unassigned
1420my @viacode; # Contains the 1 million character names
1421my @printable; # boolean: And are those characters printable?
1422my @annotate_char_type; # Contains a type of those characters, specifically
1423 # for the purposes of annotation.
1424my $annotate_ranges; # A map of ranges of code points that have the same
98dc9551 1425 # name for the purposes of annotation. They map to the
c4019d52
KW
1426 # upper edge of the range, so that the end point can
1427 # be immediately found. This is used to skip ahead to
1428 # the end of a range, and avoid processing each
1429 # individual code point in it.
1430my $unassigned_sans_noncharacters; # A Range_List of the unassigned
1431 # characters, but excluding those which are
1432 # also noncharacter code points
1433
1434# The annotation types are an extension of the regular range types, though
1435# some of the latter are folded into one. Make the new types negative to
1436# avoid conflicting with the regular types
1437my $SURROGATE_TYPE = -1;
1438my $UNASSIGNED_TYPE = -2;
1439my $PRIVATE_USE_TYPE = -3;
1440my $NONCHARACTER_TYPE = -4;
1441my $CONTROL_TYPE = -5;
1442my $UNKNOWN_TYPE = -6; # Used only if there is a bug in this program
1443
1444sub populate_char_info ($) {
558712cf 1445 # Used only with the $annotate option. Populates the arrays with the
c4019d52
KW
1446 # input code point's info that are needed for outputting more detailed
1447 # comments. If calling context wants a return, it is the end point of
1448 # any contiguous range of characters that share essentially the same info
1449
1450 my $i = shift;
1451 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
1452
1453 $viacode[$i] = $perl_charname->value_of($i) || "";
1454
1455 # A character is generally printable if Unicode says it is,
1456 # but below we make sure that most Unicode general category 'C' types
1457 # aren't.
1458 $printable[$i] = $print->contains($i);
1459
1460 $annotate_char_type[$i] = $perl_charname->type_of($i) || 0;
1461
1462 # Only these two regular types are treated specially for annotations
1463 # purposes
1464 $annotate_char_type[$i] = 0 if $annotate_char_type[$i] != $CP_IN_NAME
1465 && $annotate_char_type[$i] != $HANGUL_SYLLABLE;
1466
1467 # Give a generic name to all code points that don't have a real name.
1468 # We output ranges, if applicable, for these. Also calculate the end
1469 # point of the range.
1470 my $end;
1471 if (! $viacode[$i]) {
1472 if ($gc-> table('Surrogate')->contains($i)) {
1473 $viacode[$i] = 'Surrogate';
1474 $annotate_char_type[$i] = $SURROGATE_TYPE;
1475 $printable[$i] = 0;
1476 $end = $gc->table('Surrogate')->containing_range($i)->end;
1477 }
1478 elsif ($gc-> table('Private_use')->contains($i)) {
1479 $viacode[$i] = 'Private Use';
1480 $annotate_char_type[$i] = $PRIVATE_USE_TYPE;
1481 $printable[$i] = 0;
1482 $end = $gc->table('Private_Use')->containing_range($i)->end;
1483 }
1484 elsif (Property::property_ref('Noncharacter_Code_Point')-> table('Y')->
1485 contains($i))
1486 {
1487 $viacode[$i] = 'Noncharacter';
1488 $annotate_char_type[$i] = $NONCHARACTER_TYPE;
1489 $printable[$i] = 0;
1490 $end = property_ref('Noncharacter_Code_Point')->table('Y')->
1491 containing_range($i)->end;
1492 }
1493 elsif ($gc-> table('Control')->contains($i)) {
1494 $viacode[$i] = 'Control';
1495 $annotate_char_type[$i] = $CONTROL_TYPE;
1496 $printable[$i] = 0;
1497 $end = 0x81 if $i == 0x80; # Hard-code this one known case
1498 }
1499 elsif ($gc-> table('Unassigned')->contains($i)) {
1500 $viacode[$i] = 'Unassigned, block=' . $block-> value_of($i);
1501 $annotate_char_type[$i] = $UNASSIGNED_TYPE;
1502 $printable[$i] = 0;
1503
1504 # Because we name the unassigned by the blocks they are in, it
1505 # can't go past the end of that block, and it also can't go past
1506 # the unassigned range it is in. The special table makes sure
1507 # that the non-characters, which are unassigned, are separated
1508 # out.
1509 $end = min($block->containing_range($i)->end,
1510 $unassigned_sans_noncharacters-> containing_range($i)->
1511 end);
13ca76ff
KW
1512 }
1513 else {
1514 Carp::my_carp_bug("Can't figure out how to annotate "
1515 . sprintf("U+%04X", $i)
1516 . ". Proceeding anyway.");
c4019d52
KW
1517 $viacode[$i] = 'UNKNOWN';
1518 $annotate_char_type[$i] = $UNKNOWN_TYPE;
1519 $printable[$i] = 0;
1520 }
1521 }
1522
1523 # Here, has a name, but if it's one in which the code point number is
1524 # appended to the name, do that.
1525 elsif ($annotate_char_type[$i] == $CP_IN_NAME) {
1526 $viacode[$i] .= sprintf("-%04X", $i);
1527 $end = $perl_charname->containing_range($i)->end;
1528 }
1529
1530 # And here, has a name, but if it's a hangul syllable one, replace it with
1531 # the correct name from the Unicode algorithm
1532 elsif ($annotate_char_type[$i] == $HANGUL_SYLLABLE) {
1533 use integer;
1534 my $SIndex = $i - $SBase;
1535 my $L = $LBase + $SIndex / $NCount;
1536 my $V = $VBase + ($SIndex % $NCount) / $TCount;
1537 my $T = $TBase + $SIndex % $TCount;
1538 $viacode[$i] = "HANGUL SYLLABLE $Jamo{$L}$Jamo{$V}";
1539 $viacode[$i] .= $Jamo{$T} if $T != $TBase;
1540 $end = $perl_charname->containing_range($i)->end;
1541 }
1542
1543 return if ! defined wantarray;
1544 return $i if ! defined $end; # If not a range, return the input
1545
1546 # Save this whole range so can find the end point quickly
1547 $annotate_ranges->add_map($i, $end, $end);
1548
1549 return $end;
1550}
1551
23e33b60
KW
1552# Commented code below should work on Perl 5.8.
1553## This 'require' doesn't necessarily work in miniperl, and even if it does,
1554## the native perl version of it (which is what would operate under miniperl)
1555## is extremely slow, as it does a string eval every call.
1556#my $has_fast_scalar_util = $\18 !~ /miniperl/
1557# && defined eval "require Scalar::Util";
1558#
1559#sub objaddr($) {
1560# # Returns the address of the blessed input object. Uses the XS version if
1561# # available. It doesn't check for blessedness because that would do a
1562# # string eval every call, and the program is structured so that this is
1563# # never called for a non-blessed object.
1564#
1565# return Scalar::Util::refaddr($_[0]) if $has_fast_scalar_util;
1566#
1567# # Check at least that is a ref.
1568# my $pkg = ref($_[0]) or return undef;
1569#
1570# # Change to a fake package to defeat any overloaded stringify
1571# bless $_[0], 'main::Fake';
1572#
1573# # Numifying a ref gives its address.
051df77b 1574# my $addr = pack 'J', $_[0];
23e33b60
KW
1575#
1576# # Return to original class
1577# bless $_[0], $pkg;
1578# return $addr;
1579#}
1580
99870f4d
KW
1581sub max ($$) {
1582 my $a = shift;
1583 my $b = shift;
1584 return $a if $a >= $b;
1585 return $b;
1586}
1587
1588sub min ($$) {
1589 my $a = shift;
1590 my $b = shift;
1591 return $a if $a <= $b;
1592 return $b;
1593}
1594
1595sub clarify_number ($) {
1596 # This returns the input number with underscores inserted every 3 digits
1597 # in large (5 digits or more) numbers. Input must be entirely digits, not
1598 # checked.
1599
1600 my $number = shift;
1601 my $pos = length($number) - 3;
1602 return $number if $pos <= 1;
1603 while ($pos > 0) {
1604 substr($number, $pos, 0) = '_';
1605 $pos -= 3;
5beb625e 1606 }
99870f4d 1607 return $number;
99598c8c
JH
1608}
1609
12ac2576 1610
99870f4d 1611package Carp;
7ebf06b3 1612
99870f4d
KW
1613# These routines give a uniform treatment of messages in this program. They
1614# are placed in the Carp package to cause the stack trace to not include them,
1615# although an alternative would be to use another package and set @CARP_NOT
1616# for it.
12ac2576 1617
99870f4d 1618our $Verbose = 1 if main::DEBUG; # Useful info when debugging
12ac2576 1619
99f78760
KW
1620# This is a work-around suggested by Nicholas Clark to fix a problem with Carp
1621# and overload trying to load Scalar:Util under miniperl. See
1622# http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/2009-11/msg01057.html
1623undef $overload::VERSION;
1624
99870f4d
KW
1625sub my_carp {
1626 my $message = shift || "";
1627 my $nofold = shift || 0;
7ebf06b3 1628
99870f4d
KW
1629 if ($message) {
1630 $message = main::join_lines($message);
1631 $message =~ s/^$0: *//; # Remove initial program name
1632 $message =~ s/[.;,]+$//; # Remove certain ending punctuation
1633 $message = "\n$0: $message;";
12ac2576 1634
99870f4d
KW
1635 # Fold the message with program name, semi-colon end punctuation
1636 # (which looks good with the message that carp appends to it), and a
1637 # hanging indent for continuation lines.
1638 $message = main::simple_fold($message, "", 4) unless $nofold;
1639 $message =~ s/\n$//; # Remove the trailing nl so what carp
1640 # appends is to the same line
1641 }
12ac2576 1642
99870f4d 1643 return $message if defined wantarray; # If a caller just wants the msg
12ac2576 1644
99870f4d
KW
1645 carp $message;
1646 return;
1647}
7ebf06b3 1648
99870f4d
KW
1649sub my_carp_bug {
1650 # This is called when it is clear that the problem is caused by a bug in
1651 # this program.
7ebf06b3 1652
99870f4d
KW
1653 my $message = shift;
1654 $message =~ s/^$0: *//;
1655 $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");
1656 carp $message;
1657 return;
1658}
7ebf06b3 1659
99870f4d
KW
1660sub carp_too_few_args {
1661 if (@_ != 2) {
1662 my_carp_bug("Wrong number of arguments: to 'carp_too_few_arguments'. No action taken.");
1663 return;
12ac2576 1664 }
7ebf06b3 1665
99870f4d
KW
1666 my $args_ref = shift;
1667 my $count = shift;
7ebf06b3 1668
99870f4d
KW
1669 my_carp_bug("Need at least $count arguments to "
1670 . (caller 1)[3]
1671 . ". Instead got: '"
1672 . join ', ', @$args_ref
1673 . "'. No action taken.");
1674 return;
12ac2576
JP
1675}
1676
99870f4d
KW
1677sub carp_extra_args {
1678 my $args_ref = shift;
1679 my_carp_bug("Too many arguments to 'carp_extra_args': (" . join(', ', @_) . "); Extras ignored.") if @_;
12ac2576 1680
99870f4d
KW
1681 unless (ref $args_ref) {
1682 my_carp_bug("Argument to 'carp_extra_args' ($args_ref) must be a ref. Not checking arguments.");
1683 return;
1684 }
1685 my ($package, $file, $line) = caller;
1686 my $subroutine = (caller 1)[3];
cf25bb62 1687
99870f4d
KW
1688 my $list;
1689 if (ref $args_ref eq 'HASH') {
1690 foreach my $key (keys %$args_ref) {
1691 $args_ref->{$key} = $UNDEF unless defined $args_ref->{$key};
cf25bb62 1692 }
99870f4d 1693 $list = join ', ', each %{$args_ref};
cf25bb62 1694 }
99870f4d
KW
1695 elsif (ref $args_ref eq 'ARRAY') {
1696 foreach my $arg (@$args_ref) {
1697 $arg = $UNDEF unless defined $arg;
1698 }
1699 $list = join ', ', @$args_ref;
1700 }
1701 else {
1702 my_carp_bug("Can't cope with ref "
1703 . ref($args_ref)
1704 . " . argument to 'carp_extra_args'. Not checking arguments.");
1705 return;
1706 }
1707
1708 my_carp_bug("Unrecognized parameters in options: '$list' to $subroutine. Skipped.");
1709 return;
d73e5302
JH
1710}
1711
99870f4d
KW
1712package main;
1713
1714{ # Closure
1715
1716 # This program uses the inside-out method for objects, as recommended in
1717 # "Perl Best Practices". This closure aids in generating those. There
1718 # are two routines. setup_package() is called once per package to set
1719 # things up, and then set_access() is called for each hash representing a
1720 # field in the object. These routines arrange for the object to be
1721 # properly destroyed when no longer used, and for standard accessor
1722 # functions to be generated. If you need more complex accessors, just
1723 # write your own and leave those accesses out of the call to set_access().
1724 # More details below.
1725
1726 my %constructor_fields; # fields that are to be used in constructors; see
1727 # below
1728
1729 # The values of this hash will be the package names as keys to other
1730 # hashes containing the name of each field in the package as keys, and
1731 # references to their respective hashes as values.
1732 my %package_fields;
1733
1734 sub setup_package {
1735 # Sets up the package, creating standard DESTROY and dump methods
1736 # (unless already defined). The dump method is used in debugging by
1737 # simple_dumper().
1738 # The optional parameters are:
1739 # a) a reference to a hash, that gets populated by later
1740 # set_access() calls with one of the accesses being
1741 # 'constructor'. The caller can then refer to this, but it is
1742 # not otherwise used by these two routines.
1743 # b) a reference to a callback routine to call during destruction
1744 # of the object, before any fields are actually destroyed
1745
1746 my %args = @_;
1747 my $constructor_ref = delete $args{'Constructor_Fields'};
1748 my $destroy_callback = delete $args{'Destroy_Callback'};
1749 Carp::carp_extra_args(\@_) if main::DEBUG && %args;
1750
1751 my %fields;
1752 my $package = (caller)[0];
1753
1754 $package_fields{$package} = \%fields;
1755 $constructor_fields{$package} = $constructor_ref;
1756
1757 unless ($package->can('DESTROY')) {
1758 my $destroy_name = "${package}::DESTROY";
1759 no strict "refs";
1760
1761 # Use typeglob to give the anonymous subroutine the name we want
1762 *$destroy_name = sub {
1763 my $self = shift;
ffe43484 1764 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
1765
1766 $self->$destroy_callback if $destroy_callback;
1767 foreach my $field (keys %{$package_fields{$package}}) {
1768 #print STDERR __LINE__, ": Destroying ", ref $self, " ", sprintf("%04X", $addr), ": ", $field, "\n";
1769 delete $package_fields{$package}{$field}{$addr};
1770 }
1771 return;
1772 }
1773 }
1774
1775 unless ($package->can('dump')) {
1776 my $dump_name = "${package}::dump";
1777 no strict "refs";
1778 *$dump_name = sub {
1779 my $self = shift;
1780 return dump_inside_out($self, $package_fields{$package}, @_);
1781 }
1782 }
1783 return;
1784 }
1785
1786 sub set_access {
1787 # Arrange for the input field to be garbage collected when no longer
1788 # needed. Also, creates standard accessor functions for the field
1789 # based on the optional parameters-- none if none of these parameters:
1790 # 'addable' creates an 'add_NAME()' accessor function.
1791 # 'readable' or 'readable_array' creates a 'NAME()' accessor
1792 # function.
1793 # 'settable' creates a 'set_NAME()' accessor function.
1794 # 'constructor' doesn't create an accessor function, but adds the
1795 # field to the hash that was previously passed to
1796 # setup_package();
1797 # Any of the accesses can be abbreviated down, so that 'a', 'ad',
1798 # 'add' etc. all mean 'addable'.
1799 # The read accessor function will work on both array and scalar
1800 # values. If another accessor in the parameter list is 'a', the read
1801 # access assumes an array. You can also force it to be array access
1802 # by specifying 'readable_array' instead of 'readable'
1803 #
1804 # A sort-of 'protected' access can be set-up by preceding the addable,
1805 # readable or settable with some initial portion of 'protected_' (but,
1806 # the underscore is required), like 'p_a', 'pro_set', etc. The
1807 # "protection" is only by convention. All that happens is that the
1808 # accessor functions' names begin with an underscore. So instead of
1809 # calling set_foo, the call is _set_foo. (Real protection could be
c1739a4a 1810 # accomplished by having a new subroutine, end_package, called at the
99870f4d
KW
1811 # end of each package, and then storing the __LINE__ ranges and
1812 # checking them on every accessor. But that is way overkill.)
1813
1814 # We create anonymous subroutines as the accessors and then use
1815 # typeglobs to assign them to the proper package and name
1816
1817 my $name = shift; # Name of the field
1818 my $field = shift; # Reference to the inside-out hash containing the
1819 # field
1820
1821 my $package = (caller)[0];
1822
1823 if (! exists $package_fields{$package}) {
1824 croak "$0: Must call 'setup_package' before 'set_access'";
1825 }
d73e5302 1826
99870f4d
KW
1827 # Stash the field so DESTROY can get it.
1828 $package_fields{$package}{$name} = $field;
cf25bb62 1829
99870f4d
KW
1830 # Remaining arguments are the accessors. For each...
1831 foreach my $access (@_) {
1832 my $access = lc $access;
cf25bb62 1833
99870f4d 1834 my $protected = "";
cf25bb62 1835
99870f4d
KW
1836 # Match the input as far as it goes.
1837 if ($access =~ /^(p[^_]*)_/) {
1838 $protected = $1;
1839 if (substr('protected_', 0, length $protected)
1840 eq $protected)
1841 {
1842
1843 # Add 1 for the underscore not included in $protected
1844 $access = substr($access, length($protected) + 1);
1845 $protected = '_';
1846 }
1847 else {
1848 $protected = "";
1849 }
1850 }
1851
1852 if (substr('addable', 0, length $access) eq $access) {
1853 my $subname = "${package}::${protected}add_$name";
1854 no strict "refs";
1855
1856 # add_ accessor. Don't add if already there, which we
1857 # determine using 'eq' for scalars and '==' otherwise.
1858 *$subname = sub {
1859 use strict "refs";
1860 return Carp::carp_too_few_args(\@_, 2) if main::DEBUG && @_ < 2;
1861 my $self = shift;
1862 my $value = shift;
ffe43484 1863 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
1864 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
1865 if (ref $value) {
f998e60c 1866 return if grep { $value == $_ } @{$field->{$addr}};
99870f4d
KW
1867 }
1868 else {
f998e60c 1869 return if grep { $value eq $_ } @{$field->{$addr}};
99870f4d 1870 }
f998e60c 1871 push @{$field->{$addr}}, $value;
99870f4d
KW
1872 return;
1873 }
1874 }
1875 elsif (substr('constructor', 0, length $access) eq $access) {
1876 if ($protected) {
1877 Carp::my_carp_bug("Can't set-up 'protected' constructors")
1878 }
1879 else {
1880 $constructor_fields{$package}{$name} = $field;
1881 }
1882 }
1883 elsif (substr('readable_array', 0, length $access) eq $access) {
1884
1885 # Here has read access. If one of the other parameters for
1886 # access is array, or this one specifies array (by being more
1887 # than just 'readable_'), then create a subroutine that
1888 # assumes the data is an array. Otherwise just a scalar
1889 my $subname = "${package}::${protected}$name";
1890 if (grep { /^a/i } @_
1891 or length($access) > length('readable_'))
1892 {
1893 no strict "refs";
1894 *$subname = sub {
1895 use strict "refs";
23e33b60 1896 Carp::carp_extra_args(\@_) if main::DEBUG && @_ > 1;
ffe43484 1897 my $addr = do { no overloading; pack 'J', $_[0]; };
99870f4d
KW
1898 if (ref $field->{$addr} ne 'ARRAY') {
1899 my $type = ref $field->{$addr};
1900 $type = 'scalar' unless $type;
1901 Carp::my_carp_bug("Trying to read $name as an array when it is a $type. Big problems.");
1902 return;
1903 }
1904 return scalar @{$field->{$addr}} unless wantarray;
1905
1906 # Make a copy; had problems with caller modifying the
1907 # original otherwise
1908 my @return = @{$field->{$addr}};
1909 return @return;
1910 }
1911 }
1912 else {
1913
1914 # Here not an array value, a simpler function.
1915 no strict "refs";
1916 *$subname = sub {
1917 use strict "refs";
23e33b60 1918 Carp::carp_extra_args(\@_) if main::DEBUG && @_ > 1;
f998e60c 1919 no overloading;
051df77b 1920 return $field->{pack 'J', $_[0]};
99870f4d
KW
1921 }
1922 }
1923 }
1924 elsif (substr('settable', 0, length $access) eq $access) {
1925 my $subname = "${package}::${protected}set_$name";
1926 no strict "refs";
1927 *$subname = sub {
1928 use strict "refs";
23e33b60
KW
1929 if (main::DEBUG) {
1930 return Carp::carp_too_few_args(\@_, 2) if @_ < 2;
1931 Carp::carp_extra_args(\@_) if @_ > 2;
1932 }
1933 # $self is $_[0]; $value is $_[1]
f998e60c 1934 no overloading;
051df77b 1935 $field->{pack 'J', $_[0]} = $_[1];
99870f4d
KW
1936 return;
1937 }
1938 }
1939 else {
1940 Carp::my_carp_bug("Unknown accessor type $access. No accessor set.");
1941 }
cf25bb62 1942 }
99870f4d 1943 return;
cf25bb62 1944 }
99870f4d
KW
1945}
1946
1947package Input_file;
1948
1949# All input files use this object, which stores various attributes about them,
1950# and provides for convenient, uniform handling. The run method wraps the
1951# processing. It handles all the bookkeeping of opening, reading, and closing
1952# the file, returning only significant input lines.
1953#
1954# Each object gets a handler which processes the body of the file, and is
1955# called by run(). Most should use the generic, default handler, which has
1956# code scrubbed to handle things you might not expect. A handler should
1957# basically be a while(next_line()) {...} loop.
1958#
1959# You can also set up handlers to
1960# 1) call before the first line is read for pre processing
1961# 2) call to adjust each line of the input before the main handler gets them
1962# 3) call upon EOF before the main handler exits its loop
1963# 4) call at the end for post processing
1964#
1965# $_ is used to store the input line, and is to be filtered by the
1966# each_line_handler()s. So, if the format of the line is not in the desired
1967# format for the main handler, these are used to do that adjusting. They can
1968# be stacked (by enclosing them in an [ anonymous array ] in the constructor,
1969# so the $_ output of one is used as the input to the next. None of the other
1970# handlers are stackable, but could easily be changed to be so.
1971#
1972# Most of the handlers can call insert_lines() or insert_adjusted_lines()
1973# which insert the parameters as lines to be processed before the next input
1974# file line is read. This allows the EOF handler to flush buffers, for
1975# example. The difference between the two routines is that the lines inserted
1976# by insert_lines() are subjected to the each_line_handler()s. (So if you
1977# called it from such a handler, you would get infinite recursion.) Lines
1978# inserted by insert_adjusted_lines() go directly to the main handler without
1979# any adjustments. If the post-processing handler calls any of these, there
1980# will be no effect. Some error checking for these conditions could be added,
1981# but it hasn't been done.
1982#
1983# carp_bad_line() should be called to warn of bad input lines, which clears $_
1984# to prevent further processing of the line. This routine will output the
1985# message as a warning once, and then keep a count of the lines that have the
1986# same message, and output that count at the end of the file's processing.
1987# This keeps the number of messages down to a manageable amount.
1988#
1989# get_missings() should be called to retrieve any @missing input lines.
1990# Messages will be raised if this isn't done if the options aren't to ignore
1991# missings.
1992
1993sub trace { return main::trace(@_); }
1994
99870f4d
KW
1995{ # Closure
1996 # Keep track of fields that are to be put into the constructor.
1997 my %constructor_fields;
1998
1999 main::setup_package(Constructor_Fields => \%constructor_fields);
2000
2001 my %file; # Input file name, required
2002 main::set_access('file', \%file, qw{ c r });
2003
2004 my %first_released; # Unicode version file was first released in, required
2005 main::set_access('first_released', \%first_released, qw{ c r });
2006
2007 my %handler; # Subroutine to process the input file, defaults to
2008 # 'process_generic_property_file'
2009 main::set_access('handler', \%handler, qw{ c });
2010
2011 my %property;
2012 # name of property this file is for. defaults to none, meaning not
2013 # applicable, or is otherwise determinable, for example, from each line.
2014 main::set_access('property', \%property, qw{ c });
2015
2016 my %optional;
2017 # If this is true, the file is optional. If not present, no warning is
2018 # output. If it is present, the string given by this parameter is
2019 # evaluated, and if false the file is not processed.
2020 main::set_access('optional', \%optional, 'c', 'r');
2021
2022 my %non_skip;
2023 # This is used for debugging, to skip processing of all but a few input
2024 # files. Add 'non_skip => 1' to the constructor for those files you want
2025 # processed when you set the $debug_skip global.
2026 main::set_access('non_skip', \%non_skip, 'c');
2027
37e2e78e 2028 my %skip;
09ca89ce
KW
2029 # This is used to skip processing of this input file semi-permanently,
2030 # when it evaluates to true. The value should be the reason the file is
2031 # being skipped. It is used for files that we aren't planning to process
2032 # anytime soon, but want to allow to be in the directory and not raise a
2033 # message that we are not handling. Mostly for test files. This is in
2034 # contrast to the non_skip element, which is supposed to be used very
2035 # temporarily for debugging. Sets 'optional' to 1. Also, files that we
2036 # pretty much will never look at can be placed in the global
1fec9f60 2037 # %ignored_files instead. Ones used here will be added to %skipped files
37e2e78e
KW
2038 main::set_access('skip', \%skip, 'c');
2039
99870f4d
KW
2040 my %each_line_handler;
2041 # list of subroutines to look at and filter each non-comment line in the
2042 # file. defaults to none. The subroutines are called in order, each is
2043 # to adjust $_ for the next one, and the final one adjusts it for
2044 # 'handler'
2045 main::set_access('each_line_handler', \%each_line_handler, 'c');
2046
2047 my %has_missings_defaults;
2048 # ? Are there lines in the file giving default values for code points
2049 # missing from it?. Defaults to NO_DEFAULTS. Otherwise NOT_IGNORED is
2050 # the norm, but IGNORED means it has such lines, but the handler doesn't
2051 # use them. Having these three states allows us to catch changes to the
2052 # UCD that this program should track
2053 main::set_access('has_missings_defaults',
2054 \%has_missings_defaults, qw{ c r });
2055
2056 my %pre_handler;
2057 # Subroutine to call before doing anything else in the file. If undef, no
2058 # such handler is called.
2059 main::set_access('pre_handler', \%pre_handler, qw{ c });
2060
2061 my %eof_handler;
2062 # Subroutine to call upon getting an EOF on the input file, but before
2063 # that is returned to the main handler. This is to allow buffers to be
2064 # flushed. The handler is expected to call insert_lines() or
2065 # insert_adjusted() with the buffered material
2066 main::set_access('eof_handler', \%eof_handler, qw{ c r });
2067
2068 my %post_handler;
2069 # Subroutine to call after all the lines of the file are read in and
2070 # processed. If undef, no such handler is called.
2071 main::set_access('post_handler', \%post_handler, qw{ c });
2072
2073 my %progress_message;
2074 # Message to print to display progress in lieu of the standard one
2075 main::set_access('progress_message', \%progress_message, qw{ c });
2076
2077 my %handle;
2078 # cache open file handle, internal. Is undef if file hasn't been
2079 # processed at all, empty if has;
2080 main::set_access('handle', \%handle);
2081
2082 my %added_lines;
2083 # cache of lines added virtually to the file, internal
2084 main::set_access('added_lines', \%added_lines);
2085
2086 my %errors;
2087 # cache of errors found, internal
2088 main::set_access('errors', \%errors);
2089
2090 my %missings;
2091 # storage of '@missing' defaults lines
2092 main::set_access('missings', \%missings);
2093
2094 sub new {
2095 my $class = shift;
2096
2097 my $self = bless \do{ my $anonymous_scalar }, $class;
ffe43484 2098 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2099
2100 # Set defaults
2101 $handler{$addr} = \&main::process_generic_property_file;
2102 $non_skip{$addr} = 0;
37e2e78e 2103 $skip{$addr} = 0;
99870f4d
KW
2104 $has_missings_defaults{$addr} = $NO_DEFAULTS;
2105 $handle{$addr} = undef;
2106 $added_lines{$addr} = [ ];
2107 $each_line_handler{$addr} = [ ];
2108 $errors{$addr} = { };
2109 $missings{$addr} = [ ];
2110
2111 # Two positional parameters.
99f78760 2112 return Carp::carp_too_few_args(\@_, 2) if main::DEBUG && @_ < 2;
99870f4d
KW
2113 $file{$addr} = main::internal_file_to_platform(shift);
2114 $first_released{$addr} = shift;
2115
2116 # The rest of the arguments are key => value pairs
2117 # %constructor_fields has been set up earlier to list all possible
2118 # ones. Either set or push, depending on how the default has been set
2119 # up just above.
2120 my %args = @_;
2121 foreach my $key (keys %args) {
2122 my $argument = $args{$key};
2123
2124 # Note that the fields are the lower case of the constructor keys
2125 my $hash = $constructor_fields{lc $key};
2126 if (! defined $hash) {
2127 Carp::my_carp_bug("Unrecognized parameters '$key => $argument' to new() for $self. Skipped");
2128 next;
2129 }
2130 if (ref $hash->{$addr} eq 'ARRAY') {
2131 if (ref $argument eq 'ARRAY') {
2132 foreach my $argument (@{$argument}) {
2133 next if ! defined $argument;
2134 push @{$hash->{$addr}}, $argument;
2135 }
2136 }
2137 else {
2138 push @{$hash->{$addr}}, $argument if defined $argument;
2139 }
2140 }
2141 else {
2142 $hash->{$addr} = $argument;
2143 }
2144 delete $args{$key};
2145 };
2146
2147 # If the file has a property for it, it means that the property is not
2148 # listed in the file's entries. So add a handler to the list of line
2149 # handlers to insert the property name into the lines, to provide a
2150 # uniform interface to the final processing subroutine.
2151 # the final code doesn't have to worry about that.
2152 if ($property{$addr}) {
2153 push @{$each_line_handler{$addr}}, \&_insert_property_into_line;
2154 }
2155
2156 if ($non_skip{$addr} && ! $debug_skip && $verbosity) {
2157 print "Warning: " . __PACKAGE__ . " constructor for $file{$addr} has useless 'non_skip' in it\n";
a3a8c5f0 2158 }
99870f4d 2159
09ca89ce
KW
2160 # If skipping, set to optional, and add to list of ignored files,
2161 # including its reason
2162 if ($skip{$addr}) {
2163 $optional{$addr} = 1;
1fec9f60 2164 $skipped_files{$file{$addr}} = $skip{$addr}
09ca89ce 2165 }
37e2e78e 2166
99870f4d 2167 return $self;
d73e5302
JH
2168 }
2169
cf25bb62 2170
99870f4d
KW
2171 use overload
2172 fallback => 0,
2173 qw("") => "_operator_stringify",
2174 "." => \&main::_operator_dot,
2175 ;
cf25bb62 2176
99870f4d
KW
2177 sub _operator_stringify {
2178 my $self = shift;
cf25bb62 2179
99870f4d 2180 return __PACKAGE__ . " object for " . $self->file;
d73e5302 2181 }
d73e5302 2182
99870f4d
KW
2183 # flag to make sure extracted files are processed early
2184 my $seen_non_extracted_non_age = 0;
d73e5302 2185
99870f4d
KW
2186 sub run {
2187 # Process the input object $self. This opens and closes the file and
2188 # calls all the handlers for it. Currently, this can only be called
2189 # once per file, as it destroy's the EOF handler
d73e5302 2190
99870f4d
KW
2191 my $self = shift;
2192 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
b6922eda 2193
ffe43484 2194 my $addr = do { no overloading; pack 'J', $self; };
b6922eda 2195
99870f4d 2196 my $file = $file{$addr};
d73e5302 2197
99870f4d
KW
2198 # Don't process if not expecting this file (because released later
2199 # than this Unicode version), and isn't there. This means if someone
2200 # copies it into an earlier version's directory, we will go ahead and
2201 # process it.
2202 return if $first_released{$addr} gt $v_version && ! -e $file;
2203
2204 # If in debugging mode and this file doesn't have the non-skip
2205 # flag set, and isn't one of the critical files, skip it.
2206 if ($debug_skip
2207 && $first_released{$addr} ne v0
2208 && ! $non_skip{$addr})
2209 {
2210 print "Skipping $file in debugging\n" if $verbosity;
2211 return;
2212 }
2213
2214 # File could be optional
37e2e78e 2215 if ($optional{$addr}) {
99870f4d
KW
2216 return unless -e $file;
2217 my $result = eval $optional{$addr};
2218 if (! defined $result) {
2219 Carp::my_carp_bug("Got '$@' when tried to eval $optional{$addr}. $file Skipped.");
2220 return;
2221 }
2222 if (! $result) {
2223 if ($verbosity) {
2224 print STDERR "Skipping processing input file '$file' because '$optional{$addr}' is not true\n";
2225 }
2226 return;
2227 }
2228 }
2229
2230 if (! defined $file || ! -e $file) {
2231
2232 # If the file doesn't exist, see if have internal data for it
2233 # (based on first_released being 0).
2234 if ($first_released{$addr} eq v0) {
2235 $handle{$addr} = 'pretend_is_open';
2236 }
2237 else {
2238 if (! $optional{$addr} # File could be optional
2239 && $v_version ge $first_released{$addr})
2240 {
2241 print STDERR "Skipping processing input file '$file' because not found\n" if $v_version ge $first_released{$addr};
2242 }
2243 return;
2244 }
2245 }
2246 else {
2247
37e2e78e
KW
2248 # Here, the file exists. Some platforms may change the case of
2249 # its name
99870f4d 2250 if ($seen_non_extracted_non_age) {
517956bf 2251 if ($file =~ /$EXTRACTED/i) {
1675ea0d 2252 Carp::my_carp_bug(main::join_lines(<<END
99f78760 2253$file should be processed just after the 'Prop...Alias' files, and before
99870f4d
KW
2254anything not in the $EXTRACTED_DIR directory. Proceeding, but the results may
2255have subtle problems
2256END
2257 ));
2258 }
2259 }
2260 elsif ($EXTRACTED_DIR
2261 && $first_released{$addr} ne v0
517956bf
CB
2262 && $file !~ /$EXTRACTED/i
2263 && lc($file) ne 'dage.txt')
99870f4d
KW
2264 {
2265 # We don't set this (by the 'if' above) if we have no
2266 # extracted directory, so if running on an early version,
2267 # this test won't work. Not worth worrying about.
2268 $seen_non_extracted_non_age = 1;
2269 }
2270
2271 # And mark the file as having being processed, and warn if it
2272 # isn't a file we are expecting. As we process the files,
2273 # they are deleted from the hash, so any that remain at the
2274 # end of the program are files that we didn't process.
517956bf 2275 my $fkey = File::Spec->rel2abs($file);
faf3cf6b
KW
2276 my $expecting = delete $potential_files{lc($fkey)};
2277
678f13d5
KW
2278 Carp::my_carp("Was not expecting '$file'.") if
2279 ! $expecting
99870f4d
KW
2280 && ! defined $handle{$addr};
2281
37e2e78e
KW
2282 # Having deleted from expected files, we can quit if not to do
2283 # anything. Don't print progress unless really want verbosity
2284 if ($skip{$addr}) {
2285 print "Skipping $file.\n" if $verbosity >= $VERBOSE;
2286 return;
2287 }
2288
99870f4d
KW
2289 # Open the file, converting the slashes used in this program
2290 # into the proper form for the OS
2291 my $file_handle;
2292 if (not open $file_handle, "<", $file) {
2293 Carp::my_carp("Can't open $file. Skipping: $!");
2294 return 0;
2295 }
2296 $handle{$addr} = $file_handle; # Cache the open file handle
2297 }
2298
2299 if ($verbosity >= $PROGRESS) {
2300 if ($progress_message{$addr}) {
2301 print "$progress_message{$addr}\n";
2302 }
2303 else {
2304 # If using a virtual file, say so.
2305 print "Processing ", (-e $file)
2306 ? $file
2307 : "substitute $file",
2308 "\n";
2309 }
2310 }
2311
2312
2313 # Call any special handler for before the file.
2314 &{$pre_handler{$addr}}($self) if $pre_handler{$addr};
2315
2316 # Then the main handler
2317 &{$handler{$addr}}($self);
2318
2319 # Then any special post-file handler.
2320 &{$post_handler{$addr}}($self) if $post_handler{$addr};
2321
2322 # If any errors have been accumulated, output the counts (as the first
2323 # error message in each class was output when it was encountered).
2324 if ($errors{$addr}) {
2325 my $total = 0;
2326 my $types = 0;
2327 foreach my $error (keys %{$errors{$addr}}) {
2328 $total += $errors{$addr}->{$error};
2329 delete $errors{$addr}->{$error};
2330 $types++;
2331 }
2332 if ($total > 1) {
2333 my $message
2334 = "A total of $total lines had errors in $file. ";
2335
2336 $message .= ($types == 1)
2337 ? '(Only the first one was displayed.)'
2338 : '(Only the first of each type was displayed.)';
2339 Carp::my_carp($message);
2340 }
2341 }
2342
2343 if (@{$missings{$addr}}) {
2344 Carp::my_carp_bug("Handler for $file didn't look at all the \@missing lines. Generated tables likely are wrong");
2345 }
2346
2347 # If a real file handle, close it.
2348 close $handle{$addr} or Carp::my_carp("Can't close $file: $!") if
2349 ref $handle{$addr};
2350 $handle{$addr} = ""; # Uses empty to indicate that has already seen
2351 # the file, as opposed to undef
2352 return;
2353 }
2354
2355 sub next_line {
2356 # Sets $_ to be the next logical input line, if any. Returns non-zero
2357 # if such a line exists. 'logical' means that any lines that have
2358 # been added via insert_lines() will be returned in $_ before the file
2359 # is read again.
2360
2361 my $self = shift;
2362 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2363
ffe43484 2364 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2365
2366 # Here the file is open (or if the handle is not a ref, is an open
2367 # 'virtual' file). Get the next line; any inserted lines get priority
2368 # over the file itself.
2369 my $adjusted;
2370
2371 LINE:
2372 while (1) { # Loop until find non-comment, non-empty line
2373 #local $to_trace = 1 if main::DEBUG;
2374 my $inserted_ref = shift @{$added_lines{$addr}};
2375 if (defined $inserted_ref) {
2376 ($adjusted, $_) = @{$inserted_ref};
2377 trace $adjusted, $_ if main::DEBUG && $to_trace;
2378 return 1 if $adjusted;
2379 }
2380 else {
2381 last if ! ref $handle{$addr}; # Don't read unless is real file
2382 last if ! defined ($_ = readline $handle{$addr});
2383 }
2384 chomp;
2385 trace $_ if main::DEBUG && $to_trace;
2386
2387 # See if this line is the comment line that defines what property
2388 # value that code points that are not listed in the file should
2389 # have. The format or existence of these lines is not guaranteed
2390 # by Unicode since they are comments, but the documentation says
2391 # that this was added for machine-readability, so probably won't
2392 # change. This works starting in Unicode Version 5.0. They look
2393 # like:
2394 #
2395 # @missing: 0000..10FFFF; Not_Reordered
2396 # @missing: 0000..10FFFF; Decomposition_Mapping; <code point>
2397 # @missing: 0000..10FFFF; ; NaN
2398 #
2399 # Save the line for a later get_missings() call.
2400 if (/$missing_defaults_prefix/) {
2401 if ($has_missings_defaults{$addr} == $NO_DEFAULTS) {
2402 $self->carp_bad_line("Unexpected \@missing line. Assuming no missing entries");
2403 }
2404 elsif ($has_missings_defaults{$addr} == $NOT_IGNORED) {
2405 my @defaults = split /\s* ; \s*/x, $_;
2406
2407 # The first field is the @missing, which ends in a
2408 # semi-colon, so can safely shift.
2409 shift @defaults;
2410
2411 # Some of these lines may have empty field placeholders
2412 # which get in the way. An example is:
2413 # @missing: 0000..10FFFF; ; NaN
2414 # Remove them. Process starting from the top so the
2415 # splice doesn't affect things still to be looked at.
2416 for (my $i = @defaults - 1; $i >= 0; $i--) {
2417 next if $defaults[$i] ne "";
2418 splice @defaults, $i, 1;
2419 }
2420
2421 # What's left should be just the property (maybe) and the
2422 # default. Having only one element means it doesn't have
2423 # the property.
2424 my $default;
2425 my $property;
2426 if (@defaults >= 1) {
2427 if (@defaults == 1) {
2428 $default = $defaults[0];
2429 }
2430 else {
2431 $property = $defaults[0];
2432 $default = $defaults[1];
2433 }
2434 }
2435
2436 if (@defaults < 1
2437 || @defaults > 2
2438 || ($default =~ /^</
2439 && $default !~ /^<code *point>$/i
09f8d0ac
KW
2440 && $default !~ /^<none>$/i
2441 && $default !~ /^<script>$/i))
99870f4d
KW
2442 {
2443 $self->carp_bad_line("Unrecognized \@missing line: $_. Assuming no missing entries");
2444 }
2445 else {
2446
2447 # If the property is missing from the line, it should
2448 # be the one for the whole file
2449 $property = $property{$addr} if ! defined $property;
2450
2451 # Change <none> to the null string, which is what it
2452 # really means. If the default is the code point
2453 # itself, set it to <code point>, which is what
2454 # Unicode uses (but sometimes they've forgotten the
2455 # space)
2456 if ($default =~ /^<none>$/i) {
2457 $default = "";
2458 }
2459 elsif ($default =~ /^<code *point>$/i) {
2460 $default = $CODE_POINT;
2461 }
09f8d0ac
KW
2462 elsif ($default =~ /^<script>$/i) {
2463
2464 # Special case this one. Currently is from
2465 # ScriptExtensions.txt, and means for all unlisted
2466 # code points, use their Script property values.
2467 # For the code points not listed in that file, the
2468 # default value is 'Unknown'.
2469 $default = "Unknown";
2470 }
99870f4d
KW
2471
2472 # Store them as a sub-arrays with both components.
2473 push @{$missings{$addr}}, [ $default, $property ];
2474 }
2475 }
2476
2477 # There is nothing for the caller to process on this comment
2478 # line.
2479 next;
2480 }
2481
2482 # Remove comments and trailing space, and skip this line if the
2483 # result is empty
2484 s/#.*//;
2485 s/\s+$//;
2486 next if /^$/;
2487
2488 # Call any handlers for this line, and skip further processing of
2489 # the line if the handler sets the line to null.
2490 foreach my $sub_ref (@{$each_line_handler{$addr}}) {
2491 &{$sub_ref}($self);
2492 next LINE if /^$/;
2493 }
2494
2495 # Here the line is ok. return success.
2496 return 1;
2497 } # End of looping through lines.
2498
2499 # If there is an EOF handler, call it (only once) and if it generates
2500 # more lines to process go back in the loop to handle them.
2501 if ($eof_handler{$addr}) {
2502 &{$eof_handler{$addr}}($self);
2503 $eof_handler{$addr} = ""; # Currently only get one shot at it.
2504 goto LINE if $added_lines{$addr};
2505 }
2506
2507 # Return failure -- no more lines.
2508 return 0;
2509
2510 }
2511
2512# Not currently used, not fully tested.
2513# sub peek {
2514# # Non-destructive look-ahead one non-adjusted, non-comment, non-blank
2515# # record. Not callable from an each_line_handler(), nor does it call
2516# # an each_line_handler() on the line.
2517#
2518# my $self = shift;
ffe43484 2519# my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2520#
2521# foreach my $inserted_ref (@{$added_lines{$addr}}) {
2522# my ($adjusted, $line) = @{$inserted_ref};
2523# next if $adjusted;
2524#
2525# # Remove comments and trailing space, and return a non-empty
2526# # resulting line
2527# $line =~ s/#.*//;
2528# $line =~ s/\s+$//;
2529# return $line if $line ne "";
2530# }
2531#
2532# return if ! ref $handle{$addr}; # Don't read unless is real file
2533# while (1) { # Loop until find non-comment, non-empty line
2534# local $to_trace = 1 if main::DEBUG;
2535# trace $_ if main::DEBUG && $to_trace;
2536# return if ! defined (my $line = readline $handle{$addr});
2537# chomp $line;
2538# push @{$added_lines{$addr}}, [ 0, $line ];
2539#
2540# $line =~ s/#.*//;
2541# $line =~ s/\s+$//;
2542# return $line if $line ne "";
2543# }
2544#
2545# return;
2546# }
2547
2548
2549 sub insert_lines {
2550 # Lines can be inserted so that it looks like they were in the input
2551 # file at the place it was when this routine is called. See also
2552 # insert_adjusted_lines(). Lines inserted via this routine go through
2553 # any each_line_handler()
2554
2555 my $self = shift;
2556
2557 # Each inserted line is an array, with the first element being 0 to
2558 # indicate that this line hasn't been adjusted, and needs to be
2559 # processed.
f998e60c 2560 no overloading;
051df77b 2561 push @{$added_lines{pack 'J', $self}}, map { [ 0, $_ ] } @_;
99870f4d
KW
2562 return;
2563 }
2564
2565 sub insert_adjusted_lines {
2566 # Lines can be inserted so that it looks like they were in the input
2567 # file at the place it was when this routine is called. See also
2568 # insert_lines(). Lines inserted via this routine are already fully
2569 # adjusted, ready to be processed; each_line_handler()s handlers will
2570 # not be called. This means this is not a completely general
2571 # facility, as only the last each_line_handler on the stack should
2572 # call this. It could be made more general, by passing to each of the
2573 # line_handlers their position on the stack, which they would pass on
2574 # to this routine, and that would replace the boolean first element in
2575 # the anonymous array pushed here, so that the next_line routine could
2576 # use that to call only those handlers whose index is after it on the
2577 # stack. But this is overkill for what is needed now.
2578
2579 my $self = shift;
2580 trace $_[0] if main::DEBUG && $to_trace;
2581
2582 # Each inserted line is an array, with the first element being 1 to
2583 # indicate that this line has been adjusted
f998e60c 2584 no overloading;
051df77b 2585 push @{$added_lines{pack 'J', $self}}, map { [ 1, $_ ] } @_;
99870f4d
KW
2586 return;
2587 }
2588
2589 sub get_missings {
2590 # Returns the stored up @missings lines' values, and clears the list.
2591 # The values are in an array, consisting of the default in the first
2592 # element, and the property in the 2nd. However, since these lines
2593 # can be stacked up, the return is an array of all these arrays.
2594
2595 my $self = shift;
2596 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2597
ffe43484 2598 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2599
2600 # If not accepting a list return, just return the first one.
2601 return shift @{$missings{$addr}} unless wantarray;
2602
2603 my @return = @{$missings{$addr}};
2604 undef @{$missings{$addr}};
2605 return @return;
2606 }
2607
2608 sub _insert_property_into_line {
2609 # Add a property field to $_, if this file requires it.
2610
f998e60c 2611 my $self = shift;
ffe43484 2612 my $addr = do { no overloading; pack 'J', $self; };
f998e60c 2613 my $property = $property{$addr};
99870f4d
KW
2614 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2615
2616 $_ =~ s/(;|$)/; $property$1/;
2617 return;
2618 }
2619
2620 sub carp_bad_line {
2621 # Output consistent error messages, using either a generic one, or the
2622 # one given by the optional parameter. To avoid gazillions of the
2623 # same message in case the syntax of a file is way off, this routine
2624 # only outputs the first instance of each message, incrementing a
2625 # count so the totals can be output at the end of the file.
2626
2627 my $self = shift;
2628 my $message = shift;
2629 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2630
ffe43484 2631 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2632
2633 $message = 'Unexpected line' unless $message;
2634
2635 # No trailing punctuation so as to fit with our addenda.
2636 $message =~ s/[.:;,]$//;
2637
2638 # If haven't seen this exact message before, output it now. Otherwise
2639 # increment the count of how many times it has occurred
2640 unless ($errors{$addr}->{$message}) {
2641 Carp::my_carp("$message in '$_' in "
f998e60c 2642 . $file{$addr}
99870f4d
KW
2643 . " at line $.. Skipping this line;");
2644 $errors{$addr}->{$message} = 1;
2645 }
2646 else {
2647 $errors{$addr}->{$message}++;
2648 }
2649
2650 # Clear the line to prevent any further (meaningful) processing of it.
2651 $_ = "";
2652
2653 return;
2654 }
2655} # End closure
2656
2657package Multi_Default;
2658
2659# Certain properties in early versions of Unicode had more than one possible
2660# default for code points missing from the files. In these cases, one
2661# default applies to everything left over after all the others are applied,
2662# and for each of the others, there is a description of which class of code
2663# points applies to it. This object helps implement this by storing the
2664# defaults, and for all but that final default, an eval string that generates
2665# the class that it applies to.
2666
2667
2668{ # Closure
2669
2670 main::setup_package();
2671
2672 my %class_defaults;
2673 # The defaults structure for the classes
2674 main::set_access('class_defaults', \%class_defaults);
2675
2676 my %other_default;
2677 # The default that applies to everything left over.
2678 main::set_access('other_default', \%other_default, 'r');
2679
2680
2681 sub new {
2682 # The constructor is called with default => eval pairs, terminated by
2683 # the left-over default. e.g.
2684 # Multi_Default->new(
2685 # 'T' => '$gc->table("Mn") + $gc->table("Cf") - 0x200C
2686 # - 0x200D',
2687 # 'R' => 'some other expression that evaluates to code points',
2688 # .
2689 # .
2690 # .
2691 # 'U'));
2692
2693 my $class = shift;
2694
2695 my $self = bless \do{my $anonymous_scalar}, $class;
ffe43484 2696 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2697
2698 while (@_ > 1) {
2699 my $default = shift;
2700 my $eval = shift;
2701 $class_defaults{$addr}->{$default} = $eval;
2702 }
2703
2704 $other_default{$addr} = shift;
2705
2706 return $self;
2707 }
2708
2709 sub get_next_defaults {
2710 # Iterates and returns the next class of defaults.
2711 my $self = shift;
2712 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2713
ffe43484 2714 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2715
2716 return each %{$class_defaults{$addr}};
2717 }
2718}
2719
2720package Alias;
2721
2722# An alias is one of the names that a table goes by. This class defines them
2723# including some attributes. Everything is currently setup in the
2724# constructor.
2725
2726
2727{ # Closure
2728
2729 main::setup_package();
2730
2731 my %name;
2732 main::set_access('name', \%name, 'r');
2733
2734 my %loose_match;
c12f2655 2735 # Should this name match loosely or not.
99870f4d
KW
2736 main::set_access('loose_match', \%loose_match, 'r');
2737
33e96e72
KW
2738 my %make_re_pod_entry;
2739 # Some aliases should not get their own entries in the re section of the
2740 # pod, because they are covered by a wild-card, and some we want to
2741 # discourage use of. Binary
f82fe4ba 2742 main::set_access('make_re_pod_entry', \%make_re_pod_entry, 'r', 's');
99870f4d 2743
fd1e3e84
KW
2744 my %ucd;
2745 # Is this documented to be accessible via Unicode::UCD
2746 main::set_access('ucd', \%ucd, 'r', 's');
2747
99870f4d
KW
2748 my %status;
2749 # Aliases have a status, like deprecated, or even suppressed (which means
2750 # they don't appear in documentation). Enum
2751 main::set_access('status', \%status, 'r');
2752
0eac1e20 2753 my %ok_as_filename;
99870f4d
KW
2754 # Similarly, some aliases should not be considered as usable ones for
2755 # external use, such as file names, or we don't want documentation to
2756 # recommend them. Boolean
0eac1e20 2757 main::set_access('ok_as_filename', \%ok_as_filename, 'r');
99870f4d
KW
2758
2759 sub new {
2760 my $class = shift;
2761
2762 my $self = bless \do { my $anonymous_scalar }, $class;
ffe43484 2763 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2764
2765 $name{$addr} = shift;
2766 $loose_match{$addr} = shift;
33e96e72 2767 $make_re_pod_entry{$addr} = shift;
0eac1e20 2768 $ok_as_filename{$addr} = shift;
99870f4d 2769 $status{$addr} = shift;
fd1e3e84 2770 $ucd{$addr} = shift;
99870f4d
KW
2771
2772 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2773
2774 # Null names are never ok externally
0eac1e20 2775 $ok_as_filename{$addr} = 0 if $name{$addr} eq "";
99870f4d
KW
2776
2777 return $self;
2778 }
2779}
2780
2781package Range;
2782
2783# A range is the basic unit for storing code points, and is described in the
2784# comments at the beginning of the program. Each range has a starting code
2785# point; an ending code point (not less than the starting one); a value
2786# that applies to every code point in between the two end-points, inclusive;
2787# and an enum type that applies to the value. The type is for the user's
2788# convenience, and has no meaning here, except that a non-zero type is
2789# considered to not obey the normal Unicode rules for having standard forms.
2790#
2791# The same structure is used for both map and match tables, even though in the
2792# latter, the value (and hence type) is irrelevant and could be used as a
2793# comment. In map tables, the value is what all the code points in the range
2794# map to. Type 0 values have the standardized version of the value stored as
2795# well, so as to not have to recalculate it a lot.
2796
2797sub trace { return main::trace(@_); }
2798
2799{ # Closure
2800
2801 main::setup_package();
2802
2803 my %start;
2804 main::set_access('start', \%start, 'r', 's');
2805
2806 my %end;
2807 main::set_access('end', \%end, 'r', 's');
2808
2809 my %value;
2810 main::set_access('value', \%value, 'r');
2811
2812 my %type;
2813 main::set_access('type', \%type, 'r');
2814
2815 my %standard_form;
2816 # The value in internal standard form. Defined only if the type is 0.
2817 main::set_access('standard_form', \%standard_form);
2818
2819 # Note that if these fields change, the dump() method should as well
2820
2821 sub new {
2822 return Carp::carp_too_few_args(\@_, 3) if main::DEBUG && @_ < 3;
2823 my $class = shift;
2824
2825 my $self = bless \do { my $anonymous_scalar }, $class;
ffe43484 2826 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2827
2828 $start{$addr} = shift;
2829 $end{$addr} = shift;
2830
2831 my %args = @_;
2832
2833 my $value = delete $args{'Value'}; # Can be 0
2834 $value = "" unless defined $value;
2835 $value{$addr} = $value;
2836
2837 $type{$addr} = delete $args{'Type'} || 0;
2838
2839 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
2840
2841 if (! $type{$addr}) {
2842 $standard_form{$addr} = main::standardize($value);
2843 }
2844
2845 return $self;
2846 }
2847
2848 use overload
2849 fallback => 0,
2850 qw("") => "_operator_stringify",
2851 "." => \&main::_operator_dot,
2852 ;
2853
2854 sub _operator_stringify {
2855 my $self = shift;
ffe43484 2856 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2857
2858 # Output it like '0041..0065 (value)'
2859 my $return = sprintf("%04X", $start{$addr})
2860 . '..'
2861 . sprintf("%04X", $end{$addr});
2862 my $value = $value{$addr};
2863 my $type = $type{$addr};
2864 $return .= ' (';
2865 $return .= "$value";
2866 $return .= ", Type=$type" if $type != 0;
2867 $return .= ')';
2868
2869 return $return;
2870 }
2871
2872 sub standard_form {
2873 # The standard form is the value itself if the standard form is
2874 # undefined (that is if the value is special)
2875
2876 my $self = shift;
2877 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2878
ffe43484 2879 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2880
2881 return $standard_form{$addr} if defined $standard_form{$addr};
2882 return $value{$addr};
2883 }
2884
2885 sub dump {
2886 # Human, not machine readable. For machine readable, comment out this
2887 # entire routine and let the standard one take effect.
2888 my $self = shift;
2889 my $indent = shift;
2890 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
2891
ffe43484 2892 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2893
2894 my $return = $indent
2895 . sprintf("%04X", $start{$addr})
2896 . '..'
2897 . sprintf("%04X", $end{$addr})
2898 . " '$value{$addr}';";
2899 if (! defined $standard_form{$addr}) {
2900 $return .= "(type=$type{$addr})";
2901 }
2902 elsif ($standard_form{$addr} ne $value{$addr}) {
2903 $return .= "(standard '$standard_form{$addr}')";
2904 }
2905 return $return;
2906 }
2907} # End closure
2908
2909package _Range_List_Base;
2910
2911# Base class for range lists. A range list is simply an ordered list of
2912# ranges, so that the ranges with the lowest starting numbers are first in it.
2913#
2914# When a new range is added that is adjacent to an existing range that has the
2915# same value and type, it merges with it to form a larger range.
2916#
2917# Ranges generally do not overlap, except that there can be multiple entries
2918# of single code point ranges. This is because of NameAliases.txt.
2919#
2920# In this program, there is a standard value such that if two different
2921# values, have the same standard value, they are considered equivalent. This
2922# value was chosen so that it gives correct results on Unicode data
2923
2924# There are a number of methods to manipulate range lists, and some operators
2925# are overloaded to handle them.
2926
99870f4d
KW
2927sub trace { return main::trace(@_); }
2928
2929{ # Closure
2930
2931 our $addr;
2932
2933 main::setup_package();
2934
2935 my %ranges;
2936 # The list of ranges
2937 main::set_access('ranges', \%ranges, 'readable_array');
2938
2939 my %max;
2940 # The highest code point in the list. This was originally a method, but
2941 # actual measurements said it was used a lot.
2942 main::set_access('max', \%max, 'r');
2943
2944 my %each_range_iterator;
2945 # Iterator position for each_range()
2946 main::set_access('each_range_iterator', \%each_range_iterator);
2947
2948 my %owner_name_of;
2949 # Name of parent this is attached to, if any. Solely for better error
2950 # messages.
2951 main::set_access('owner_name_of', \%owner_name_of, 'p_r');
2952
2953 my %_search_ranges_cache;
2954 # A cache of the previous result from _search_ranges(), for better
2955 # performance
2956 main::set_access('_search_ranges_cache', \%_search_ranges_cache);
2957
2958 sub new {
2959 my $class = shift;
2960 my %args = @_;
2961
2962 # Optional initialization data for the range list.
2963 my $initialize = delete $args{'Initialize'};
2964
2965 my $self;
2966
2967 # Use _union() to initialize. _union() returns an object of this
2968 # class, which means that it will call this constructor recursively.
2969 # But it won't have this $initialize parameter so that it won't
2970 # infinitely loop on this.
2971 return _union($class, $initialize, %args) if defined $initialize;
2972
2973 $self = bless \do { my $anonymous_scalar }, $class;
ffe43484 2974 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
2975
2976 # Optional parent object, only for debug info.
2977 $owner_name_of{$addr} = delete $args{'Owner'};
2978 $owner_name_of{$addr} = "" if ! defined $owner_name_of{$addr};
2979
2980 # Stringify, in case it is an object.
2981 $owner_name_of{$addr} = "$owner_name_of{$addr}";
2982
2983 # This is used only for error messages, and so a colon is added
2984 $owner_name_of{$addr} .= ": " if $owner_name_of{$addr} ne "";
2985
2986 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
2987
2988 # Max is initialized to a negative value that isn't adjacent to 0,
2989 # for simpler tests
2990 $max{$addr} = -2;
2991
2992 $_search_ranges_cache{$addr} = 0;
2993 $ranges{$addr} = [];
2994
2995 return $self;
2996 }
2997
2998 use overload
2999 fallback => 0,
3000 qw("") => "_operator_stringify",
3001 "." => \&main::_operator_dot,
3002 ;
3003
3004 sub _operator_stringify {
3005 my $self = shift;
ffe43484 3006 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
3007
3008 return "Range_List attached to '$owner_name_of{$addr}'"
3009 if $owner_name_of{$addr};
3010 return "anonymous Range_List " . \$self;
3011 }
3012
3013 sub _union {
3014 # Returns the union of the input code points. It can be called as
3015 # either a constructor or a method. If called as a method, the result
3016 # will be a new() instance of the calling object, containing the union
3017 # of that object with the other parameter's code points; if called as
d59563d0 3018 # a constructor, the first parameter gives the class that the new object
99870f4d
KW
3019 # should be, and the second parameter gives the code points to go into
3020 # it.
3021 # In either case, there are two parameters looked at by this routine;
3022 # any additional parameters are passed to the new() constructor.
3023 #
3024 # The code points can come in the form of some object that contains
3025 # ranges, and has a conventionally named method to access them; or
3026 # they can be an array of individual code points (as integers); or
3027 # just a single code point.
3028 #
3029 # If they are ranges, this routine doesn't make any effort to preserve
3198cc57
KW
3030 # the range values and types of one input over the other. Therefore
3031 # this base class should not allow _union to be called from other than
99870f4d
KW
3032 # initialization code, so as to prevent two tables from being added
3033 # together where the range values matter. The general form of this
3034 # routine therefore belongs in a derived class, but it was moved here
3035 # to avoid duplication of code. The failure to overload this in this
3036 # class keeps it safe.
3198cc57
KW
3037 #
3038 # It does make the effort during initialization to accept tables with
3039 # multiple values for the same code point, and to preserve the order
3040 # of these. If there is only one input range or range set, it doesn't
3041 # sort (as it should already be sorted to the desired order), and will
3042 # accept multiple values per code point. Otherwise it will merge
3043 # multiple values into a single one.
99870f4d
KW
3044
3045 my $self;
3046 my @args; # Arguments to pass to the constructor
3047
3048 my $class = shift;
3049
3050 # If a method call, will start the union with the object itself, and
3051 # the class of the new object will be the same as self.
3052 if (ref $class) {
3053 $self = $class;
3054 $class = ref $self;
3055 push @args, $self;
3056 }
3057
3058 # Add the other required parameter.
3059 push @args, shift;
3060 # Rest of parameters are passed on to the constructor
3061
3062 # Accumulate all records from both lists.
3063 my @records;
3198cc57 3064 my $input_count = 0;
99870f4d
KW
3065 for my $arg (@args) {
3066 #local $to_trace = 0 if main::DEBUG;
3067 trace "argument = $arg" if main::DEBUG && $to_trace;
3068 if (! defined $arg) {
3069 my $message = "";
3070 if (defined $self) {
f998e60c 3071 no overloading;
051df77b 3072 $message .= $owner_name_of{pack 'J', $self};
99870f4d
KW
3073 }
3074 Carp::my_carp_bug($message .= "Undefined argument to _union. No union done.");
3075 return;
3076 }
3198cc57 3077
99870f4d
KW
3078 $arg = [ $arg ] if ! ref $arg;
3079 my $type = ref $arg;
3080 if ($type eq 'ARRAY') {
3081 foreach my $element (@$arg) {
3082 push @records, Range->new($element, $element);
3198cc57 3083 $input_count++;
99870f4d
KW
3084 }
3085 }
3086 elsif ($arg->isa('Range')) {
3087 push @records, $arg;
3198cc57 3088 $input_count++;
99870f4d
KW
3089 }
3090 elsif ($arg->can('ranges')) {
3091 push @records, $arg->ranges;
3198cc57 3092 $input_count++;
99870f4d
KW
3093 }
3094 else {
3095 my $message = "";
3096 if (defined $self) {
f998e60c 3097 no overloading;
051df77b 3098 $message .= $owner_name_of{pack 'J', $self};
99870f4d
KW
3099 }
3100 Carp::my_carp_bug($message . "Cannot take the union of a $type. No union done.");
3101 return;
3102 }
3103 }
3104
3105 # Sort with the range containing the lowest ordinal first, but if
3106 # two ranges start at the same code point, sort with the bigger range
3107 # of the two first, because it takes fewer cycles.
3198cc57
KW
3108 if ($input_count > 1) {
3109 @records = sort { ($a->start <=> $b->start)
99870f4d
KW
3110 or
3111 # if b is shorter than a, b->end will be
3112 # less than a->end, and we want to select
3113 # a, so want to return -1
3114 ($b->end <=> $a->end)
3115 } @records;
3198cc57 3116 }
99870f4d
KW
3117
3118 my $new = $class->new(@_);
3119
3120 # Fold in records so long as they add new information.
3121 for my $set (@records) {
3122 my $start = $set->start;
3123 my $end = $set->end;
d59563d0 3124 my $value = $set->value;
3198cc57 3125 my $type = $set->type;
99870f4d 3126 if ($start > $new->max) {
3198cc57 3127 $new->_add_delete('+', $start, $end, $value, Type => $type);
99870f4d
KW
3128 }
3129 elsif ($end > $new->max) {
3198cc57
KW
3130 $new->_add_delete('+', $new->max +1, $end, $value,
3131 Type => $type);
3132 }
3133 elsif ($input_count == 1) {
3134 # Here, overlaps existing range, but is from a single input,
3135 # so preserve the multiple values from that input.
3136 $new->_add_delete('+', $start, $end, $value, Type => $type,
3137 Replace => $MULTIPLE_AFTER);
99870f4d
KW
3138 }
3139 }
3140
3141 return $new;
3142 }
3143
3144 sub range_count { # Return the number of ranges in the range list
3145 my $self = shift;
3146 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3147
f998e60c 3148 no overloading;
051df77b 3149 return scalar @{$ranges{pack 'J', $self}};
99870f4d
KW
3150 }
3151
3152 sub min {
3153 # Returns the minimum code point currently in the range list, or if
3154 # the range list is empty, 2 beyond the max possible. This is a
3155 # method because used so rarely, that not worth saving between calls,
3156 # and having to worry about changing it as ranges are added and
3157 # deleted.
3158
3159 my $self = shift;
3160 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3161
ffe43484 3162 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
3163
3164 # If the range list is empty, return a large value that isn't adjacent
3165 # to any that could be in the range list, for simpler tests
6189eadc 3166 return $MAX_UNICODE_CODEPOINT + 2 unless scalar @{$ranges{$addr}};
99870f4d
KW
3167 return $ranges{$addr}->[0]->start;
3168 }
3169
3170 sub contains {
3171 # Boolean: Is argument in the range list? If so returns $i such that:
3172 # range[$i]->end < $codepoint <= range[$i+1]->end
3173 # which is one beyond what you want; this is so that the 0th range
3174 # doesn't return false
3175 my $self = shift;
3176 my $codepoint = shift;
3177 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3178
99870f4d
KW
3179 my $i = $self->_search_ranges($codepoint);
3180 return 0 unless defined $i;
3181
3182 # The search returns $i, such that
3183 # range[$i-1]->end < $codepoint <= range[$i]->end
3184 # So is in the table if and only iff it is at least the start position
3185 # of range $i.
f998e60c 3186 no overloading;
051df77b 3187 return 0 if $ranges{pack 'J', $self}->[$i]->start > $codepoint;
99870f4d
KW
3188 return $i + 1;
3189 }
3190
2f7a8815
KW
3191 sub containing_range {
3192 # Returns the range object that contains the code point, undef if none
3193
3194 my $self = shift;
3195 my $codepoint = shift;
3196 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3197
3198 my $i = $self->contains($codepoint);
3199 return unless $i;
3200
3201 # contains() returns 1 beyond where we should look
3202 no overloading;
3203 return $ranges{pack 'J', $self}->[$i-1];
3204 }
3205
99870f4d
KW
3206 sub value_of {
3207 # Returns the value associated with the code point, undef if none
3208
3209 my $self = shift;
3210 my $codepoint = shift;
3211 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3212
d69c231b
KW
3213 my $range = $self->containing_range($codepoint);
3214 return unless defined $range;
99870f4d 3215
d69c231b 3216 return $range->value;
99870f4d
KW
3217 }
3218
0a9dbafc
KW
3219 sub type_of {
3220 # Returns the type of the range containing the code point, undef if
3221 # the code point is not in the table
3222
3223 my $self = shift;
3224 my $codepoint = shift;
3225 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3226
3227 my $range = $self->containing_range($codepoint);
3228 return unless defined $range;
3229
3230 return $range->type;
3231 }
3232
99870f4d
KW
3233 sub _search_ranges {
3234 # Find the range in the list which contains a code point, or where it
3235 # should go if were to add it. That is, it returns $i, such that:
3236 # range[$i-1]->end < $codepoint <= range[$i]->end
3237 # Returns undef if no such $i is possible (e.g. at end of table), or
3238 # if there is an error.
3239
3240 my $self = shift;
3241 my $code_point = shift;
3242 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
3243
ffe43484 3244 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
3245
3246 return if $code_point > $max{$addr};
3247 my $r = $ranges{$addr}; # The current list of ranges
3248 my $range_list_size = scalar @$r;
3249 my $i;
3250
3251 use integer; # want integer division
3252
3253 # Use the cached result as the starting guess for this one, because,
3254 # an experiment on 5.1 showed that 90% of the time the cache was the
3255 # same as the result on the next call (and 7% it was one less).
3256 $i = $_search_ranges_cache{$addr};
3257 $i = 0 if $i >= $range_list_size; # Reset if no longer valid (prob.
3258 # from an intervening deletion
3259 #local $to_trace = 1 if main::DEBUG;
3260 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);
3261 return $i if $code_point <= $r->[$i]->end
3262 && ($i == 0 || $r->[$i-1]->end < $code_point);
3263
3264 # Here the cache doesn't yield the correct $i. Try adding 1.
3265 if ($i < $range_list_size - 1
3266 && $r->[$i]->end < $code_point &&
3267 $code_point <= $r->[$i+1]->end)
3268 {
3269 $i++;
3270 trace "next \$i is correct: $i" if main::DEBUG && $to_trace;
3271 $_search_ranges_cache{$addr} = $i;
3272 return $i;
3273 }
3274
3275 # Here, adding 1 also didn't work. We do a binary search to
3276 # find the correct position, starting with current $i
3277 my $lower = 0;
3278 my $upper = $range_list_size - 1;
3279 while (1) {
3280 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;
3281
3282 if ($code_point <= $r->[$i]->end) {
3283
3284 # Here we have met the upper constraint. We can quit if we
3285 # also meet the lower one.
3286 last if $i == 0 || $r->[$i-1]->end < $code_point;
3287
3288 $upper = $i; # Still too high.
3289
3290 }
3291 else {
3292
3293 # Here, $r[$i]->end < $code_point, so look higher up.
3294 $lower = $i;
3295 }
3296
3297 # Split search domain in half to try again.
3298 my $temp = ($upper + $lower) / 2;
3299
3300 # No point in continuing unless $i changes for next time
3301 # in the loop.
3302 if ($temp == $i) {
3303
3304 # We can't reach the highest element because of the averaging.
3305 # So if one below the upper edge, force it there and try one
3306 # more time.
3307 if ($i == $range_list_size - 2) {
3308
3309 trace "Forcing to upper edge" if main::DEBUG && $to_trace;
3310 $i = $range_list_size - 1;
3311
3312 # Change $lower as well so if fails next time through,
3313 # taking the average will yield the same $i, and we will
3314 # quit with the error message just below.
3315 $lower = $i;
3316 next;
3317 }
3318 Carp::my_carp_bug("$owner_name_of{$addr}Can't find where the range ought to go. No action taken.");
3319 return;
3320 }
3321 $i = $temp;
3322 } # End of while loop
3323
3324 if (main::DEBUG && $to_trace) {
3325 trace 'i-1=[', $i-1, ']', $r->[$i-1] if $i;
3326 trace "i= [ $i ]", $r->[$i];
3327 trace 'i+1=[', $i+1, ']', $r->[$i+1] if $i < $range_list_size - 1;
3328 }
3329
3330 # Here we have found the offset. Cache it as a starting point for the
3331 # next call.
3332 $_search_ranges_cache{$addr} = $i;
3333 return $i;
3334 }
3335
3336 sub _add_delete {
3337 # Add, replace or delete ranges to or from a list. The $type
3338 # parameter gives which:
3339 # '+' => insert or replace a range, returning a list of any changed
3340 # ranges.
3341 # '-' => delete a range, returning a list of any deleted ranges.
3342 #
3343 # The next three parameters give respectively the start, end, and
3344 # value associated with the range. 'value' should be null unless the
3345 # operation is '+';
3346 #
3347 # The range list is kept sorted so that the range with the lowest
3348 # starting position is first in the list, and generally, adjacent
c1739a4a 3349 # ranges with the same values are merged into a single larger one (see
99870f4d
KW
3350 # exceptions below).
3351 #
c1739a4a 3352 # There are more parameters; all are key => value pairs:
99870f4d
KW
3353 # Type gives the type of the value. It is only valid for '+'.
3354 # All ranges have types; if this parameter is omitted, 0 is
3355 # assumed. Ranges with type 0 are assumed to obey the
3356 # Unicode rules for casing, etc; ranges with other types are
3357 # not. Otherwise, the type is arbitrary, for the caller's
3358 # convenience, and looked at only by this routine to keep
3359 # adjacent ranges of different types from being merged into
3360 # a single larger range, and when Replace =>
3361 # $IF_NOT_EQUIVALENT is specified (see just below).
3362 # Replace determines what to do if the range list already contains
3363 # ranges which coincide with all or portions of the input
3364 # range. It is only valid for '+':
3365 # => $NO means that the new value is not to replace
3366 # any existing ones, but any empty gaps of the
3367 # range list coinciding with the input range
3368 # will be filled in with the new value.
3369 # => $UNCONDITIONALLY means to replace the existing values with
3370 # this one unconditionally. However, if the
3371 # new and old values are identical, the
3372 # replacement is skipped to save cycles
3373 # => $IF_NOT_EQUIVALENT means to replace the existing values
d59563d0 3374 # (the default) with this one if they are not equivalent.
99870f4d 3375 # Ranges are equivalent if their types are the
c1739a4a 3376 # same, and they are the same string; or if
99870f4d
KW
3377 # both are type 0 ranges, if their Unicode
3378 # standard forms are identical. In this last
3379 # case, the routine chooses the more "modern"
3380 # one to use. This is because some of the
3381 # older files are formatted with values that
3382 # are, for example, ALL CAPs, whereas the
3383 # derived files have a more modern style,
3384 # which looks better. By looking for this
3385 # style when the pre-existing and replacement
3386 # standard forms are the same, we can move to
3387 # the modern style
9470941f 3388 # => $MULTIPLE_BEFORE means that if this range duplicates an
99870f4d
KW
3389 # existing one, but has a different value,
3390 # don't replace the existing one, but insert
3391 # this, one so that the same range can occur
53d84487
KW
3392 # multiple times. They are stored LIFO, so
3393 # that the final one inserted is the first one
3394 # returned in an ordered search of the table.
7f4b1e25
KW
3395 # => $MULTIPLE_AFTER is like $MULTIPLE_BEFORE, but is stored
3396 # FIFO, so that this one is inserted after all
3397 # others that currently exist.
99870f4d
KW
3398 # => anything else is the same as => $IF_NOT_EQUIVALENT
3399 #
c1739a4a
KW
3400 # "same value" means identical for non-type-0 ranges, and it means
3401 # having the same standard forms for type-0 ranges.
99870f4d
KW
3402
3403 return Carp::carp_too_few_args(\@_, 5) if main::DEBUG && @_ < 5;
3404
3405 my $self = shift;
3406 my $operation = shift; # '+' for add/replace; '-' for delete;
3407 my $start = shift;
3408 my $end = shift;
3409 my $value = shift;
3410
3411 my %args = @_;
3412
3413 $value = "" if not defined $value; # warning: $value can be "0"
3414
3415 my $replace = delete $args{'Replace'};
3416 $replace = $IF_NOT_EQUIVALENT unless defined $replace;
3417
3418 my $type = delete $args{'Type'};
3419 $type = 0 unless defined $type;
3420
3421 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
3422
ffe43484 3423 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
3424
3425 if ($operation ne '+' && $operation ne '-') {
3426 Carp::my_carp_bug("$owner_name_of{$addr}First parameter to _add_delete must be '+' or '-'. No action taken.");
3427 return;
3428 }
3429 unless (defined $start && defined $end) {
3430 Carp::my_carp_bug("$owner_name_of{$addr}Undefined start and/or end to _add_delete. No action taken.");
3431 return;
3432 }
3433 unless ($end >= $start) {
3434 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.");
3435 return;
3436 }
3437 #local $to_trace = 1 if main::DEBUG;
3438
3439 if ($operation eq '-') {
3440 if ($replace != $IF_NOT_EQUIVALENT) {
3441 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.");
3442 $replace = $IF_NOT_EQUIVALENT;
3443 }
3444 if ($type) {
3445 Carp::my_carp_bug("$owner_name_of{$addr}Type => 0 is required when deleting a range from a range list. Assuming Type => 0.");
3446 $type = 0;
3447 }
3448 if ($value ne "") {
3449 Carp::my_carp_bug("$owner_name_of{$addr}Value => \"\" is required when deleting a range from a range list. Assuming Value => \"\".");
3450 $value = "";
3451 }
3452 }
3453
3454 my $r = $ranges{$addr}; # The current list of ranges
3455 my $range_list_size = scalar @$r; # And its size
3456 my $max = $max{$addr}; # The current high code point in
3457 # the list of ranges
3458
3459 # Do a special case requiring fewer machine cycles when the new range
3460 # starts after the current highest point. The Unicode input data is
3461 # structured so this is common.
3462 if ($start > $max) {
3463
3464 trace "$owner_name_of{$addr} $operation", sprintf("%04X", $start) . '..' . sprintf("%04X", $end) . " ($value) type=$type" if main::DEBUG && $to_trace;
3465 return if $operation eq '-'; # Deleting a non-existing range is a
3466 # no-op
3467
3468 # If the new range doesn't logically extend the current final one
3469 # in the range list, create a new range at the end of the range
3470 # list. (max cleverly is initialized to a negative number not
3471 # adjacent to 0 if the range list is empty, so even adding a range
3472 # to an empty range list starting at 0 will have this 'if'
3473 # succeed.)
3474 if ($start > $max + 1 # non-adjacent means can't extend.
3475 || @{$r}[-1]->value ne $value # values differ, can't extend.
3476 || @{$r}[-1]->type != $type # types differ, can't extend.
3477 ) {
3478 push @$r, Range->new($start, $end,
3479 Value => $value,
3480 Type => $type);
3481 }
3482 else {
3483
3484 # Here, the new range starts just after the current highest in
3485 # the range list, and they have the same type and value.
3486 # Extend the current range to incorporate the new one.
3487 @{$r}[-1]->set_end($end);
3488 }
3489
3490 # This becomes the new maximum.
3491 $max{$addr} = $end;
3492
3493 return;
3494 }
3495 #local $to_trace = 0 if main::DEBUG;
3496
3497 trace "$owner_name_of{$addr} $operation", sprintf("%04X", $start) . '..' . sprintf("%04X", $end) . " ($value) replace=$replace" if main::DEBUG && $to_trace;
3498
3499 # Here, the input range isn't after the whole rest of the range list.
3500 # Most likely 'splice' will be needed. The rest of the routine finds
3501 # the needed splice parameters, and if necessary, does the splice.
3502 # First, find the offset parameter needed by the splice function for
3503 # the input range. Note that the input range may span multiple
3504 # existing ones, but we'll worry about that later. For now, just find
3505 # the beginning. If the input range is to be inserted starting in a
3506 # position not currently in the range list, it must (obviously) come
3507 # just after the range below it, and just before the range above it.
3508 # Slightly less obviously, it will occupy the position currently
3509 # occupied by the range that is to come after it. More formally, we
3510 # are looking for the position, $i, in the array of ranges, such that:
3511 #
3512 # r[$i-1]->start <= r[$i-1]->end < $start < r[$i]->start <= r[$i]->end
3513 #
3514 # (The ordered relationships within existing ranges are also shown in
3515 # the equation above). However, if the start of the input range is
3516 # within an existing range, the splice offset should point to that
3517 # existing range's position in the list; that is $i satisfies a
3518 # somewhat different equation, namely:
3519 #
3520 #r[$i-1]->start <= r[$i-1]->end < r[$i]->start <= $start <= r[$i]->end
3521 #
3522 # More briefly, $start can come before or after r[$i]->start, and at
3523 # this point, we don't know which it will be. However, these
3524 # two equations share these constraints:
3525 #
3526 # r[$i-1]->end < $start <= r[$i]->end
3527 #
3528 # And that is good enough to find $i.
3529
3530 my $i = $self->_search_ranges($start);
3531 if (! defined $i) {
3532 Carp::my_carp_bug("Searching $self for range beginning with $start unexpectedly returned undefined. Operation '$operation' not performed");
3533 return;
3534 }
3535
3536 # The search function returns $i such that:
3537 #
3538 # r[$i-1]->end < $start <= r[$i]->end
3539 #
3540 # That means that $i points to the first range in the range list
3541 # that could possibly be affected by this operation. We still don't
3542 # know if the start of the input range is within r[$i], or if it
3543 # points to empty space between r[$i-1] and r[$i].
3544 trace "[$i] is the beginning splice point. Existing range there is ", $r->[$i] if main::DEBUG && $to_trace;
3545
3546 # Special case the insertion of data that is not to replace any
3547 # existing data.
3548 if ($replace == $NO) { # If $NO, has to be operation '+'
3549 #local $to_trace = 1 if main::DEBUG;
3550 trace "Doesn't replace" if main::DEBUG && $to_trace;
3551
3552 # Here, the new range is to take effect only on those code points
3553 # that aren't already in an existing range. This can be done by
3554 # looking through the existing range list and finding the gaps in
3555 # the ranges that this new range affects, and then calling this
3556 # function recursively on each of those gaps, leaving untouched
3557 # anything already in the list. Gather up a list of the changed
3558 # gaps first so that changes to the internal state as new ranges
3559 # are added won't be a problem.
3560 my @gap_list;
3561
3562 # First, if the starting point of the input range is outside an
3563 # existing one, there is a gap from there to the beginning of the
3564 # existing range -- add a span to fill the part that this new
3565 # range occupies
3566 if ($start < $r->[$i]->start) {
3567 push @gap_list, Range->new($start,
3568 main::min($end,
3569 $r->[$i]->start - 1),
3570 Type => $type);
3571 trace "gap before $r->[$i] [$i], will add", $gap_list[-1] if main::DEBUG && $to_trace;
3572 }
3573
3574 # Then look through the range list for other gaps until we reach
3575 # the highest range affected by the input one.
3576 my $j;
3577 for ($j = $i+1; $j < $range_list_size; $j++) {
3578 trace "j=[$j]", $r->[$j] if main::DEBUG && $to_trace;
3579 last if $end < $r->[$j]->start;
3580
3581 # If there is a gap between when this range starts and the
3582 # previous one ends, add a span to fill it. Note that just
3583 # because there are two ranges doesn't mean there is a
3584 # non-zero gap between them. It could be that they have
3585 # different values or types
3586 if ($r->[$j-1]->end + 1 != $r->[$j]->start) {
3587 push @gap_list,
3588 Range->new($r->[$j-1]->end + 1,
3589 $r->[$j]->start - 1,
3590 Type => $type);
3591 trace "gap between $r->[$j-1] and $r->[$j] [$j], will add: $gap_list[-1]" if main::DEBUG && $to_trace;
3592 }
3593 }
3594
3595 # Here, we have either found an existing range in the range list,
3596 # beyond the area affected by the input one, or we fell off the
3597 # end of the loop because the input range affects the whole rest
3598 # of the range list. In either case, $j is 1 higher than the
3599 # highest affected range. If $j == $i, it means that there are no
3600 # affected ranges, that the entire insertion is in the gap between
3601 # r[$i-1], and r[$i], which we already have taken care of before
3602 # the loop.
3603 # On the other hand, if there are affected ranges, it might be
3604 # that there is a gap that needs filling after the final such
3605 # range to the end of the input range
3606 if ($r->[$j-1]->end < $end) {
3607 push @gap_list, Range->new(main::max($start,
3608 $r->[$j-1]->end + 1),
3609 $end,
3610 Type => $type);
3611 trace "gap after $r->[$j-1], will add $gap_list[-1]" if main::DEBUG && $to_trace;
3612 }
3613
3614 # Call recursively to fill in all the gaps.
3615 foreach my $gap (@gap_list) {
3616 $self->_add_delete($operation,
3617 $gap->start,
3618 $gap->end,
3619 $value,
3620 Type => $type);
3621 }
3622
3623 return;
3624 }
3625
53d84487
KW
3626 # Here, we have taken care of the case where $replace is $NO.
3627 # Remember that here, r[$i-1]->end < $start <= r[$i]->end
3628 # If inserting a multiple record, this is where it goes, before the
7f4b1e25
KW
3629 # first (if any) existing one if inserting LIFO. (If this is to go
3630 # afterwards, FIFO, we below move the pointer to there.) These imply
3631 # an insertion, and no change to any existing ranges. Note that $i
3632 # can be -1 if this new range doesn't actually duplicate any existing,
3633 # and comes at the beginning of the list.
3634 if ($replace == $MULTIPLE_BEFORE || $replace == $MULTIPLE_AFTER) {
53d84487
KW
3635
3636 if ($start != $end) {
3637 Carp::my_carp_bug("$owner_name_of{$addr}Can't cope with adding a multiple record when the range ($start..$end) contains more than one code point. No action taken.");
3638 return;
3639 }
3640
19155fcc 3641 # If the new code point is within a current range ...
53d84487 3642 if ($end >= $r->[$i]->start) {
19155fcc
KW
3643
3644 # Don't add an exact duplicate, as it isn't really a multiple
1f6798c4
KW
3645 my $existing_value = $r->[$i]->value;
3646 my $existing_type = $r->[$i]->type;
3647 return if $value eq $existing_value && $type eq $existing_type;
3648
3649 # If the multiple value is part of an existing range, we want
3650 # to split up that range, so that only the single code point
3651 # is affected. To do this, we first call ourselves
3652 # recursively to delete that code point from the table, having
3653 # preserved its current data above. Then we call ourselves
3654 # recursively again to add the new multiple, which we know by
3655 # the test just above is different than the current code
3656 # point's value, so it will become a range containing a single
3657 # code point: just itself. Finally, we add back in the
3658 # pre-existing code point, which will again be a single code
3659 # point range. Because 'i' likely will have changed as a
3660 # result of these operations, we can't just continue on, but
7f4b1e25
KW
3661 # do this operation recursively as well. If we are inserting
3662 # LIFO, the pre-existing code point needs to go after the new
3663 # one, so use MULTIPLE_AFTER; and vice versa.
53d84487 3664 if ($r->[$i]->start != $r->[$i]->end) {
1f6798c4
KW
3665 $self->_add_delete('-', $start, $end, "");
3666 $self->_add_delete('+', $start, $end, $value, Type => $type);
7f4b1e25
KW
3667 return $self->_add_delete('+',
3668 $start, $end,
3669 $existing_value,
3670 Type => $existing_type,
3671 Replace => ($replace == $MULTIPLE_BEFORE)
3672 ? $MULTIPLE_AFTER
3673 : $MULTIPLE_BEFORE);
3674 }
3675 }
3676
3677 # If to place this new record after, move to beyond all existing
3678 # ones.
3679 if ($replace == $MULTIPLE_AFTER) {
3680 while ($i < @$r && $r->[$i]->start == $start) {
3681 $i++;
53d84487 3682 }
53d84487
KW
3683 }
3684
3685 trace "Adding multiple record at $i with $start..$end, $value" if main::DEBUG && $to_trace;
3686 my @return = splice @$r,
3687 $i,
3688 0,
3689 Range->new($start,
3690 $end,
3691 Value => $value,
3692 Type => $type);
3693 if (main::DEBUG && $to_trace) {
3694 trace "After splice:";
3695 trace 'i-2=[', $i-2, ']', $r->[$i-2] if $i >= 2;
3696 trace 'i-1=[', $i-1, ']', $r->[$i-1] if $i >= 1;
3697 trace "i =[", $i, "]", $r->[$i] if $i >= 0;
3698 trace 'i+1=[', $i+1, ']', $r->[$i+1] if $i < @$r - 1;
3699 trace 'i+2=[', $i+2, ']', $r->[$i+2] if $i < @$r - 2;
3700 trace 'i+3=[', $i+3, ']', $r->[$i+3] if $i < @$r - 3;
3701 }
3702 return @return;
3703 }
3704
7f4b1e25
KW
3705 # Here, we have taken care of $NO and $MULTIPLE_foo replaces. This
3706 # leaves delete, insert, and replace either unconditionally or if not
53d84487
KW
3707 # equivalent. $i still points to the first potential affected range.
3708 # Now find the highest range affected, which will determine the length
3709 # parameter to splice. (The input range can span multiple existing
3710 # ones.) If this isn't a deletion, while we are looking through the
3711 # range list, see also if this is a replacement rather than a clean
3712 # insertion; that is if it will change the values of at least one
3713 # existing range. Start off assuming it is an insert, until find it
3714 # isn't.
3715 my $clean_insert = $operation eq '+';
99870f4d
KW
3716 my $j; # This will point to the highest affected range
3717
3718 # For non-zero types, the standard form is the value itself;
3719 my $standard_form = ($type) ? $value : main::standardize($value);
3720
3721 for ($j = $i; $j < $range_list_size; $j++) {
3722 trace "Looking for highest affected range; the one at $j is ", $r->[$j] if main::DEBUG && $to_trace;
3723
3724 # If find a range that it doesn't overlap into, we can stop
3725 # searching
3726 last if $end < $r->[$j]->start;
3727
969a34cc
KW
3728 # Here, overlaps the range at $j. If the values don't match,
3729 # and so far we think this is a clean insertion, it becomes a
3730 # non-clean insertion, i.e., a 'change' or 'replace' instead.
3731 if ($clean_insert) {
99870f4d 3732 if ($r->[$j]->standard_form ne $standard_form) {
969a34cc 3733 $clean_insert = 0;
56343c78
KW
3734 if ($replace == $CROAK) {
3735 main::croak("The range to add "
3736 . sprintf("%04X", $start)
3737 . '-'
3738 . sprintf("%04X", $end)
3739 . " with value '$value' overlaps an existing range $r->[$j]");
3740 }
99870f4d
KW
3741 }
3742 else {
3743
3744 # Here, the two values are essentially the same. If the
3745 # two are actually identical, replacing wouldn't change
3746 # anything so skip it.
3747 my $pre_existing = $r->[$j]->value;
3748 if ($pre_existing ne $value) {
3749
3750 # Here the new and old standardized values are the
3751 # same, but the non-standardized values aren't. If
3752 # replacing unconditionally, then replace
3753 if( $replace == $UNCONDITIONALLY) {
969a34cc 3754 $clean_insert = 0;
99870f4d
KW
3755 }
3756 else {
3757
3758 # Here, are replacing conditionally. Decide to
3759 # replace or not based on which appears to look
3760 # the "nicest". If one is mixed case and the
3761 # other isn't, choose the mixed case one.
3762 my $new_mixed = $value =~ /[A-Z]/
3763 && $value =~ /[a-z]/;
3764 my $old_mixed = $pre_existing =~ /[A-Z]/
3765 && $pre_existing =~ /[a-z]/;
3766
3767 if ($old_mixed != $new_mixed) {
969a34cc 3768 $clean_insert = 0 if $new_mixed;
99870f4d 3769 if (main::DEBUG && $to_trace) {
969a34cc
KW
3770 if ($clean_insert) {
3771 trace "Retaining $pre_existing over $value";
99870f4d
KW
3772 }
3773 else {
969a34cc 3774 trace "Replacing $pre_existing with $value";
99870f4d
KW
3775 }
3776 }
3777 }
3778 else {
3779
3780 # Here casing wasn't different between the two.
3781 # If one has hyphens or underscores and the
3782 # other doesn't, choose the one with the
3783 # punctuation.
3784 my $new_punct = $value =~ /[-_]/;
3785 my $old_punct = $pre_existing =~ /[-_]/;
3786
3787 if ($old_punct != $new_punct) {
969a34cc 3788 $clean_insert = 0 if $new_punct;
99870f4d 3789 if (main::DEBUG && $to_trace) {
969a34cc
KW
3790 if ($clean_insert) {
3791 trace "Retaining $pre_existing over $value";
99870f4d
KW
3792 }
3793 else {
969a34cc 3794 trace "Replacing $pre_existing with $value";
99870f4d
KW
3795 }
3796 }
3797 } # else existing one is just as "good";
3798 # retain it to save cycles.
3799 }
3800 }
3801 }
3802 }
3803 }
3804 } # End of loop looking for highest affected range.
3805
3806 # Here, $j points to one beyond the highest range that this insertion
3807 # affects (hence to beyond the range list if that range is the final
3808 # one in the range list).
3809
3810 # The splice length is all the affected ranges. Get it before
3811 # subtracting, for efficiency, so we don't have to later add 1.
3812 my $length = $j - $i;
3813
3814 $j--; # $j now points to the highest affected range.
3815 trace "Final affected range is $j: $r->[$j]" if main::DEBUG && $to_trace;
3816
7f4b1e25 3817 # Here, have taken care of $NO and $MULTIPLE_foo replaces.
99870f4d
KW
3818 # $j points to the highest affected range. But it can be < $i or even
3819 # -1. These happen only if the insertion is entirely in the gap
3820 # between r[$i-1] and r[$i]. Here's why: j < i means that the j loop
3821 # above exited first time through with $end < $r->[$i]->start. (And
3822 # then we subtracted one from j) This implies also that $start <
3823 # $r->[$i]->start, but we know from above that $r->[$i-1]->end <
3824 # $start, so the entire input range is in the gap.
3825 if ($j < $i) {
3826
3827 # Here the entire input range is in the gap before $i.
3828
3829 if (main::DEBUG && $to_trace) {
3830 if ($i) {
3831 trace "Entire range is between $r->[$i-1] and $r->[$i]";
3832 }
3833 else {
3834 trace "Entire range is before $r->[$i]";
3835 }
3836 }
3837 return if $operation ne '+'; # Deletion of a non-existent range is
3838 # a no-op
3839 }
3840 else {
3841
969a34cc
KW
3842 # Here part of the input range is not in the gap before $i. Thus,
3843 # there is at least one affected one, and $j points to the highest
3844 # such one.
99870f4d
KW
3845
3846 # At this point, here is the situation:
3847 # This is not an insertion of a multiple, nor of tentative ($NO)
3848 # data.
3849 # $i points to the first element in the current range list that
3850 # may be affected by this operation. In fact, we know
3851 # that the range at $i is affected because we are in
3852 # the else branch of this 'if'
3853 # $j points to the highest affected range.
3854 # In other words,
3855 # r[$i-1]->end < $start <= r[$i]->end
3856 # And:
3857 # r[$i-1]->end < $start <= $end <= r[$j]->end
3858 #
3859 # Also:
969a34cc
KW
3860 # $clean_insert is a boolean which is set true if and only if
3861 # this is a "clean insertion", i.e., not a change nor a
3862 # deletion (multiple was handled above).
99870f4d
KW
3863
3864 # We now have enough information to decide if this call is a no-op
969a34cc
KW
3865 # or not. It is a no-op if this is an insertion of already
3866 # existing data.
99870f4d 3867
969a34cc 3868 if (main::DEBUG && $to_trace && $clean_insert
99870f4d
KW
3869 && $i == $j
3870 && $start >= $r->[$i]->start)
3871 {
3872 trace "no-op";
3873 }
969a34cc 3874 return if $clean_insert
99870f4d
KW
3875 && $i == $j # more than one affected range => not no-op
3876
3877 # Here, r[$i-1]->end < $start <= $end <= r[$i]->end
3878 # Further, $start and/or $end is >= r[$i]->start
3879 # The test below hence guarantees that
3880 # r[$i]->start < $start <= $end <= r[$i]->end
3881 # This means the input range is contained entirely in
3882 # the one at $i, so is a no-op
3883 && $start >= $r->[$i]->start;
3884 }
3885
3886 # Here, we know that some action will have to be taken. We have
3887 # calculated the offset and length (though adjustments may be needed)
3888 # for the splice. Now start constructing the replacement list.
3889 my @replacement;
3890 my $splice_start = $i;
3891
3892 my $extends_below;
3893 my $extends_above;
3894
3895 # See if should extend any adjacent ranges.
3896 if ($operation eq '-') { # Don't extend deletions
3897 $extends_below = $extends_above = 0;
3898 }
3899 else { # Here, should extend any adjacent ranges. See if there are
3900 # any.
3901 $extends_below = ($i > 0
3902 # can't extend unless adjacent
3903 && $r->[$i-1]->end == $start -1
3904 # can't extend unless are same standard value
3905 && $r->[$i-1]->standard_form eq $standard_form
3906 # can't extend unless share type
3907 && $r->[$i-1]->type == $type);
3908 $extends_above = ($j+1 < $range_list_size
3909 && $r->[$j+1]->start == $end +1
3910 && $r->[$j+1]->standard_form eq $standard_form
23822bda 3911 && $r->[$j+1]->type == $type);
99870f4d
KW
3912 }
3913 if ($extends_below && $extends_above) { # Adds to both
3914 $splice_start--; # start replace at element below
3915 $length += 2; # will replace on both sides
3916 trace "Extends both below and above ranges" if main::DEBUG && $to_trace;
3917
3918 # The result will fill in any gap, replacing both sides, and
3919 # create one large range.
3920 @replacement = Range->new($r->[$i-1]->start,
3921 $r->[$j+1]->end,
3922 Value => $value,
3923 Type => $type);
3924 }
3925 else {
3926
3927 # Here we know that the result won't just be the conglomeration of
3928 # a new range with both its adjacent neighbors. But it could
3929 # extend one of them.
3930
3931 if ($extends_below) {
3932
3933 # Here the new element adds to the one below, but not to the
3934 # one above. If inserting, and only to that one range, can
3935 # just change its ending to include the new one.
969a34cc 3936 if ($length == 0 && $clean_insert) {
99870f4d
KW
3937 $r->[$i-1]->set_end($end);
3938 trace "inserted range extends range to below so it is now $r->[$i-1]" if main::DEBUG && $to_trace;
3939 return;
3940 }
3941 else {
3942 trace "Changing inserted range to start at ", sprintf("%04X", $r->[$i-1]->start), " instead of ", sprintf("%04X", $start) if main::DEBUG && $to_trace;
3943 $splice_start--; # start replace at element below
3944 $length++; # will replace the element below
3945 $start = $r->[$i-1]->start;
3946 }
3947 }
3948 elsif ($extends_above) {
3949
3950 # Here the new element adds to the one above, but not below.
3951 # Mirror the code above
969a34cc 3952 if ($length == 0 && $clean_insert) {
99870f4d
KW
3953 $r->[$j+1]->set_start($start);
3954 trace "inserted range extends range to above so it is now $r->[$j+1]" if main::DEBUG && $to_trace;
3955 return;
3956 }
3957 else {
3958 trace "Changing inserted range to end at ", sprintf("%04X", $r->[$j+1]->end), " instead of ", sprintf("%04X", $end) if main::DEBUG && $to_trace;
3959 $length++; # will replace the element above
3960 $end = $r->[$j+1]->end;
3961 }
3962 }
3963
3964 trace "Range at $i is $r->[$i]" if main::DEBUG && $to_trace;
3965
3966 # Finally, here we know there will have to be a splice.
3967 # If the change or delete affects only the highest portion of the
3968 # first affected range, the range will have to be split. The
3969 # splice will remove the whole range, but will replace it by a new
3970 # range containing just the unaffected part. So, in this case,
3971 # add to the replacement list just this unaffected portion.
3972 if (! $extends_below
3973 && $start > $r->[$i]->start && $start <= $r->[$i]->end)
3974 {
3975 push @replacement,
3976 Range->new($r->[$i]->start,
3977 $start - 1,
3978 Value => $r->[$i]->value,
3979 Type => $r->[$i]->type);
3980 }
3981
3982 # In the case of an insert or change, but not a delete, we have to
3983 # put in the new stuff; this comes next.
3984 if ($operation eq '+') {
3985 push @replacement, Range->new($start,
3986 $end,
3987 Value => $value,
3988 Type => $type);
3989 }
3990
3991 trace "Range at $j is $r->[$j]" if main::DEBUG && $to_trace && $j != $i;
3992 #trace "$end >=", $r->[$j]->start, " && $end <", $r->[$j]->end if main::DEBUG && $to_trace;
3993
3994 # And finally, if we're changing or deleting only a portion of the
3995 # highest affected range, it must be split, as the lowest one was.
3996 if (! $extends_above
3997 && $j >= 0 # Remember that j can be -1 if before first
3998 # current element
3999 && $end >= $r->[$j]->start
4000 && $end < $r->[$j]->end)
4001 {
4002 push @replacement,
4003 Range->new($end + 1,
4004 $r->[$j]->end,
4005 Value => $r->[$j]->value,
4006 Type => $r->[$j]->type);
4007 }
4008 }
4009
4010 # And do the splice, as calculated above
4011 if (main::DEBUG && $to_trace) {
4012 trace "replacing $length element(s) at $i with ";
4013 foreach my $replacement (@replacement) {
4014 trace " $replacement";
4015 }
4016 trace "Before splice:";
4017 trace 'i-2=[', $i-2, ']', $r->[$i-2] if $i >= 2;
4018 trace 'i-1=[', $i-1, ']', $r->[$i-1] if $i >= 1;
4019 trace "i =[", $i, "]", $r->[$i];
4020 trace 'i+1=[', $i+1, ']', $r->[$i+1] if $i < @$r - 1;
4021 trace 'i+2=[', $i+2, ']', $r->[$i+2] if $i < @$r - 2;
4022 }
4023
4024 my @return = splice @$r, $splice_start, $length, @replacement;
4025
4026 if (main::DEBUG && $to_trace) {
4027 trace "After splice:";
4028 trace 'i-2=[', $i-2, ']', $r->[$i-2] if $i >= 2;
4029 trace 'i-1=[', $i-1, ']', $r->[$i-1] if $i >= 1;
4030 trace "i =[", $i, "]", $r->[$i];
4031 trace 'i+1=[', $i+1, ']', $r->[$i+1] if $i < @$r - 1;
4032 trace 'i+2=[', $i+2, ']', $r->[$i+2] if $i < @$r - 2;
e6451557 4033 trace "removed ", @return if @return;
99870f4d
KW
4034 }
4035
4036 # An actual deletion could have changed the maximum in the list.
4037 # There was no deletion if the splice didn't return something, but
4038 # otherwise recalculate it. This is done too rarely to worry about
4039 # performance.
4040 if ($operation eq '-' && @return) {
4041 $max{$addr} = $r->[-1]->end;
4042 }
4043 return @return;
4044 }
4045
4046 sub reset_each_range { # reset the iterator for each_range();
4047 my $self = shift;
4048 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4049
f998e60c 4050 no overloading;
051df77b 4051 undef $each_range_iterator{pack 'J', $self};
99870f4d
KW
4052 return;
4053 }
4054
4055 sub each_range {
4056 # Iterate over each range in a range list. Results are undefined if
4057 # the range list is changed during the iteration.
4058
4059 my $self = shift;
4060 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4061
ffe43484 4062 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
4063
4064 return if $self->is_empty;
4065
4066 $each_range_iterator{$addr} = -1
4067 if ! defined $each_range_iterator{$addr};
4068 $each_range_iterator{$addr}++;
4069 return $ranges{$addr}->[$each_range_iterator{$addr}]
4070 if $each_range_iterator{$addr} < @{$ranges{$addr}};
4071 undef $each_range_iterator{$addr};
4072 return;
4073 }
4074
4075 sub count { # Returns count of code points in range list
4076 my $self = shift;
4077 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4078
ffe43484 4079 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
4080
4081 my $count = 0;
4082 foreach my $range (@{$ranges{$addr}}) {
4083 $count += $range->end - $range->start + 1;
4084 }
4085 return $count;
4086 }
4087
4088 sub delete_range { # Delete a range
4089 my $self = shift;
4090 my $start = shift;
4091 my $end = shift;
4092
4093 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4094
4095 return $self->_add_delete('-', $start, $end, "");
4096 }
4097
4098 sub is_empty { # Returns boolean as to if a range list is empty
4099 my $self = shift;
4100 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4101
f998e60c 4102 no overloading;
051df77b 4103 return scalar @{$ranges{pack 'J', $self}} == 0;
99870f4d
KW
4104 }
4105
4106 sub hash {
4107 # Quickly returns a scalar suitable for separating tables into
4108 # buckets, i.e. it is a hash function of the contents of a table, so
4109 # there are relatively few conflicts.
4110
4111 my $self = shift;
4112 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4113
ffe43484 4114 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
4115
4116 # These are quickly computable. Return looks like 'min..max;count'
4117 return $self->min . "..$max{$addr};" . scalar @{$ranges{$addr}};
4118 }
4119} # End closure for _Range_List_Base
4120
4121package Range_List;
4122use base '_Range_List_Base';
4123
4124# A Range_List is a range list for match tables; i.e. the range values are
4125# not significant. Thus a number of operations can be safely added to it,
4126# such as inversion, intersection. Note that union is also an unsafe
4127# operation when range values are cared about, and that method is in the base
4128# class, not here. But things are set up so that that method is callable only
4129# during initialization. Only in this derived class, is there an operation
4130# that combines two tables. A Range_Map can thus be used to initialize a
4131# Range_List, and its mappings will be in the list, but are not significant to
4132# this class.
4133
4134sub trace { return main::trace(@_); }
4135
4136{ # Closure
4137
4138 use overload
4139 fallback => 0,
4140 '+' => sub { my $self = shift;
4141 my $other = shift;
4142
4143 return $self->_union($other)
4144 },
4145 '&' => sub { my $self = shift;
4146 my $other = shift;
4147
4148 return $self->_intersect($other, 0);
4149 },
4150 '~' => "_invert",
4151 '-' => "_subtract",
4152 ;
4153
4154 sub _invert {
4155 # Returns a new Range_List that gives all code points not in $self.
4156
4157 my $self = shift;
4158
4159 my $new = Range_List->new;
4160
4161 # Go through each range in the table, finding the gaps between them
4162 my $max = -1; # Set so no gap before range beginning at 0
4163 for my $range ($self->ranges) {
4164 my $start = $range->start;
4165 my $end = $range->end;
4166
4167 # If there is a gap before this range, the inverse will contain
4168 # that gap.
4169 if ($start > $max + 1) {
4170 $new->add_range($max + 1, $start - 1);
4171 }
4172 $max = $end;
4173 }
4174
4175 # And finally, add the gap from the end of the table to the max
4176 # possible code point
6189eadc
KW
4177 if ($max < $MAX_UNICODE_CODEPOINT) {
4178 $new->add_range($max + 1, $MAX_UNICODE_CODEPOINT);
99870f4d
KW
4179 }
4180 return $new;
4181 }
4182
4183 sub _subtract {
4184 # Returns a new Range_List with the argument deleted from it. The
4185 # argument can be a single code point, a range, or something that has
4186 # a range, with the _range_list() method on it returning them
4187
4188 my $self = shift;
4189 my $other = shift;
4190 my $reversed = shift;
4191 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4192
4193 if ($reversed) {
4194 Carp::my_carp_bug("Can't cope with a "
4195 . __PACKAGE__
4196 . " being the second parameter in a '-'. Subtraction ignored.");
4197 return $self;
4198 }
4199
4200 my $new = Range_List->new(Initialize => $self);
4201
4202 if (! ref $other) { # Single code point
4203 $new->delete_range($other, $other);
4204 }
4205 elsif ($other->isa('Range')) {
4206 $new->delete_range($other->start, $other->end);
4207 }
4208 elsif ($other->can('_range_list')) {
4209 foreach my $range ($other->_range_list->ranges) {
4210 $new->delete_range($range->start, $range->end);
4211 }
4212 }
4213 else {
4214 Carp::my_carp_bug("Can't cope with a "
4215 . ref($other)
4216 . " argument to '-'. Subtraction ignored."
4217 );
4218 return $self;
4219 }
4220
4221 return $new;
4222 }
4223
4224 sub _intersect {
4225 # Returns either a boolean giving whether the two inputs' range lists
4226 # intersect (overlap), or a new Range_List containing the intersection
4227 # of the two lists. The optional final parameter being true indicates
4228 # to do the check instead of the intersection.
4229
4230 my $a_object = shift;
4231 my $b_object = shift;
4232 my $check_if_overlapping = shift;
4233 $check_if_overlapping = 0 unless defined $check_if_overlapping;
4234 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4235
4236 if (! defined $b_object) {
4237 my $message = "";
4238 $message .= $a_object->_owner_name_of if defined $a_object;
4239 Carp::my_carp_bug($message .= "Called with undefined value. Intersection not done.");
4240 return;
4241 }
4242
4243 # a & b = !(!a | !b), or in our terminology = ~ ( ~a + -b )
4244 # Thus the intersection could be much more simply be written:
4245 # return ~(~$a_object + ~$b_object);
4246 # But, this is slower, and when taking the inverse of a large
4247 # range_size_1 table, back when such tables were always stored that
4248 # way, it became prohibitively slow, hence the code was changed to the
4249 # below
4250
4251 if ($b_object->isa('Range')) {
4252 $b_object = Range_List->new(Initialize => $b_object,
4253 Owner => $a_object->_owner_name_of);
4254 }
4255 $b_object = $b_object->_range_list if $b_object->can('_range_list');
4256
4257 my @a_ranges = $a_object->ranges;
4258 my @b_ranges = $b_object->ranges;
4259
4260 #local $to_trace = 1 if main::DEBUG;
4261 trace "intersecting $a_object with ", scalar @a_ranges, "ranges and $b_object with", scalar @b_ranges, " ranges" if main::DEBUG && $to_trace;
4262
4263 # Start with the first range in each list
4264 my $a_i = 0;
4265 my $range_a = $a_ranges[$a_i];
4266 my $b_i = 0;
4267 my $range_b = $b_ranges[$b_i];
4268
4269 my $new = __PACKAGE__->new(Owner => $a_object->_owner_name_of)
4270 if ! $check_if_overlapping;
4271
4272 # If either list is empty, there is no intersection and no overlap
4273 if (! defined $range_a || ! defined $range_b) {
4274 return $check_if_overlapping ? 0 : $new;
4275 }
4276 trace "range_a[$a_i]=$range_a; range_b[$b_i]=$range_b" if main::DEBUG && $to_trace;
4277
4278 # Otherwise, must calculate the intersection/overlap. Start with the
4279 # very first code point in each list
4280 my $a = $range_a->start;
4281 my $b = $range_b->start;
4282
4283 # Loop through all the ranges of each list; in each iteration, $a and
4284 # $b are the current code points in their respective lists
4285 while (1) {
4286
4287 # If $a and $b are the same code point, ...
4288 if ($a == $b) {
4289
4290 # it means the lists overlap. If just checking for overlap
4291 # know the answer now,
4292 return 1 if $check_if_overlapping;
4293
4294 # The intersection includes this code point plus anything else
4295 # common to both current ranges.
4296 my $start = $a;
4297 my $end = main::min($range_a->end, $range_b->end);
4298 if (! $check_if_overlapping) {
4299 trace "adding intersection range ", sprintf("%04X", $start) . ".." . sprintf("%04X", $end) if main::DEBUG && $to_trace;
4300 $new->add_range($start, $end);
4301 }
4302
4303 # Skip ahead to the end of the current intersect
4304 $a = $b = $end;
4305
4306 # If the current intersect ends at the end of either range (as
4307 # it must for at least one of them), the next possible one
4308 # will be the beginning code point in it's list's next range.
4309 if ($a == $range_a->end) {
4310 $range_a = $a_ranges[++$a_i];
4311 last unless defined $range_a;
4312 $a = $range_a->start;
4313 }
4314 if ($b == $range_b->end) {
4315 $range_b = $b_ranges[++$b_i];
4316 last unless defined $range_b;
4317 $b = $range_b->start;
4318 }
4319
4320 trace "range_a[$a_i]=$range_a; range_b[$b_i]=$range_b" if main::DEBUG && $to_trace;
4321 }
4322 elsif ($a < $b) {
4323
4324 # Not equal, but if the range containing $a encompasses $b,
4325 # change $a to be the middle of the range where it does equal
4326 # $b, so the next iteration will get the intersection
4327 if ($range_a->end >= $b) {
4328 $a = $b;
4329 }
4330 else {
4331
4332 # Here, the current range containing $a is entirely below
4333 # $b. Go try to find a range that could contain $b.
4334 $a_i = $a_object->_search_ranges($b);
4335
4336 # If no range found, quit.
4337 last unless defined $a_i;
4338
4339 # The search returns $a_i, such that
4340 # range_a[$a_i-1]->end < $b <= range_a[$a_i]->end
4341 # Set $a to the beginning of this new range, and repeat.
4342 $range_a = $a_ranges[$a_i];
4343 $a = $range_a->start;
4344 }
4345 }
4346 else { # Here, $b < $a.
4347
4348 # Mirror image code to the leg just above
4349 if ($range_b->end >= $a) {
4350 $b = $a;
4351 }
4352 else {
4353 $b_i = $b_object->_search_ranges($a);
4354 last unless defined $b_i;
4355 $range_b = $b_ranges[$b_i];
4356 $b = $range_b->start;
4357 }
4358 }
4359 } # End of looping through ranges.
4360
4361 # Intersection fully computed, or now know that there is no overlap
4362 return $check_if_overlapping ? 0 : $new;
4363 }
4364
4365 sub overlaps {
4366 # Returns boolean giving whether the two arguments overlap somewhere
4367
4368 my $self = shift;
4369 my $other = shift;
4370 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4371
4372 return $self->_intersect($other, 1);
4373 }
4374
4375 sub add_range {
4376 # Add a range to the list.
4377
4378 my $self = shift;
4379 my $start = shift;
4380 my $end = shift;
4381 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4382
4383 return $self->_add_delete('+', $start, $end, "");
4384 }
4385
09aba7e4
KW
4386 sub matches_identically_to {
4387 # Return a boolean as to whether or not two Range_Lists match identical
4388 # sets of code points.
4389
4390 my $self = shift;
4391 my $other = shift;
4392 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4393
4394 # These are ordered in increasing real time to figure out (at least
4395 # until a patch changes that and doesn't change this)
4396 return 0 if $self->max != $other->max;
4397 return 0 if $self->min != $other->min;
4398 return 0 if $self->range_count != $other->range_count;
4399 return 0 if $self->count != $other->count;
4400
4401 # Here they could be identical because all the tests above passed.
4402 # The loop below is somewhat simpler since we know they have the same
4403 # number of elements. Compare range by range, until reach the end or
4404 # find something that differs.
4405 my @a_ranges = $self->ranges;
4406 my @b_ranges = $other->ranges;
4407 for my $i (0 .. @a_ranges - 1) {
4408 my $a = $a_ranges[$i];
4409 my $b = $b_ranges[$i];
4410 trace "self $a; other $b" if main::DEBUG && $to_trace;
c1c2d9e8
KW
4411 return 0 if ! defined $b
4412 || $a->start != $b->start
4413 || $a->end != $b->end;
09aba7e4
KW
4414 }
4415 return 1;
4416 }
4417
99870f4d
KW
4418 sub is_code_point_usable {
4419 # This used only for making the test script. See if the input
4420 # proposed trial code point is one that Perl will handle. If second
4421 # parameter is 0, it won't select some code points for various
4422 # reasons, noted below.
4423
4424 my $code = shift;
4425 my $try_hard = shift;
4426 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4427
4428 return 0 if $code < 0; # Never use a negative
4429
99870f4d
KW
4430 # shun null. I'm (khw) not sure why this was done, but NULL would be
4431 # the character very frequently used.
4432 return $try_hard if $code == 0x0000;
4433
99870f4d
KW
4434 # shun non-character code points.
4435 return $try_hard if $code >= 0xFDD0 && $code <= 0xFDEF;
4436 return $try_hard if ($code & 0xFFFE) == 0xFFFE; # includes FFFF
4437
6189eadc 4438 return $try_hard if $code > $MAX_UNICODE_CODEPOINT; # keep in range
99870f4d
KW
4439 return $try_hard if $code >= 0xD800 && $code <= 0xDFFF; # no surrogate
4440
4441 return 1;
4442 }
4443
4444 sub get_valid_code_point {
4445 # Return a code point that's part of the range list. Returns nothing
4446 # if the table is empty or we can't find a suitable code point. This
4447 # used only for making the test script.
4448
4449 my $self = shift;
4450 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4451
ffe43484 4452 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
4453
4454 # On first pass, don't choose less desirable code points; if no good
4455 # one is found, repeat, allowing a less desirable one to be selected.
4456 for my $try_hard (0, 1) {
4457
4458 # Look through all the ranges for a usable code point.
06feba9a 4459 for my $set (reverse $self->ranges) {
99870f4d
KW
4460
4461 # Try the edge cases first, starting with the end point of the
4462 # range.
4463 my $end = $set->end;
4464 return $end if is_code_point_usable($end, $try_hard);
4465
4466 # End point didn't, work. Start at the beginning and try
4467 # every one until find one that does work.
4468 for my $trial ($set->start .. $end - 1) {
4469 return $trial if is_code_point_usable($trial, $try_hard);
4470 }
4471 }
4472 }
4473 return (); # If none found, give up.
4474 }
4475
4476 sub get_invalid_code_point {
4477 # Return a code point that's not part of the table. Returns nothing
4478 # if the table covers all code points or a suitable code point can't
4479 # be found. This used only for making the test script.
4480
4481 my $self = shift;
4482 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4483
4484 # Just find a valid code point of the inverse, if any.
4485 return Range_List->new(Initialize => ~ $self)->get_valid_code_point;
4486 }
4487} # end closure for Range_List
4488
4489package Range_Map;
4490use base '_Range_List_Base';
4491
4492# A Range_Map is a range list in which the range values (called maps) are
4493# significant, and hence shouldn't be manipulated by our other code, which
4494# could be ambiguous or lose things. For example, in taking the union of two
4495# lists, which share code points, but which have differing values, which one
4496# has precedence in the union?
4497# It turns out that these operations aren't really necessary for map tables,
4498# and so this class was created to make sure they aren't accidentally
4499# applied to them.
4500
4501{ # Closure
4502
4503 sub add_map {
4504 # Add a range containing a mapping value to the list
4505
4506 my $self = shift;
4507 # Rest of parameters passed on
4508
4509 return $self->_add_delete('+', @_);
4510 }
4511
4512 sub add_duplicate {
4513 # Adds entry to a range list which can duplicate an existing entry
4514
4515 my $self = shift;
4516 my $code_point = shift;
4517 my $value = shift;
7f4b1e25
KW
4518 my %args = @_;
4519 my $replace = delete $args{'Replace'} // $MULTIPLE_BEFORE;
4520 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
99870f4d
KW
4521
4522 return $self->add_map($code_point, $code_point,
7f4b1e25 4523 $value, Replace => $replace);
99870f4d
KW
4524 }
4525} # End of closure for package Range_Map
4526
4527package _Base_Table;
4528
4529# A table is the basic data structure that gets written out into a file for
4530# use by the Perl core. This is the abstract base class implementing the
4531# common elements from the derived ones. A list of the methods to be
4532# furnished by an implementing class is just after the constructor.
4533
4534sub standardize { return main::standardize($_[0]); }
4535sub trace { return main::trace(@_); }
4536
4537{ # Closure
4538
4539 main::setup_package();
4540
4541 my %range_list;
4542 # Object containing the ranges of the table.
4543 main::set_access('range_list', \%range_list, 'p_r', 'p_s');
4544
4545 my %full_name;
4546 # The full table name.
4547 main::set_access('full_name', \%full_name, 'r');
4548
4549 my %name;
4550 # The table name, almost always shorter
4551 main::set_access('name', \%name, 'r');
4552
4553 my %short_name;
4554 # The shortest of all the aliases for this table, with underscores removed
4555 main::set_access('short_name', \%short_name);
4556
4557 my %nominal_short_name_length;
4558 # The length of short_name before removing underscores
4559 main::set_access('nominal_short_name_length',
4560 \%nominal_short_name_length);
4561
23e33b60
KW
4562 my %complete_name;
4563 # The complete name, including property.
4564 main::set_access('complete_name', \%complete_name, 'r');
4565
99870f4d
KW
4566 my %property;
4567 # Parent property this table is attached to.
4568 main::set_access('property', \%property, 'r');
4569
4570 my %aliases;
c12f2655
KW
4571 # Ordered list of alias objects of the table's name. The first ones in
4572 # the list are output first in comments
99870f4d
KW
4573 main::set_access('aliases', \%aliases, 'readable_array');
4574
4575 my %comment;
4576 # A comment associated with the table for human readers of the files
4577 main::set_access('comment', \%comment, 's');
4578
4579 my %description;
4580 # A comment giving a short description of the table's meaning for human
4581 # readers of the files.
4582 main::set_access('description', \%description, 'readable_array');
4583
4584 my %note;
4585 # A comment giving a short note about the table for human readers of the
4586 # files.
4587 main::set_access('note', \%note, 'readable_array');
4588
301ba948
KW
4589 my %fate;
4590 # Enum; there are a number of possibilities for what happens to this
4591 # table: it could be normal, or suppressed, or not for external use. See
4592 # values at definition for $SUPPRESSED.
4593 main::set_access('fate', \%fate, 'r');
99870f4d
KW
4594
4595 my %find_table_from_alias;
4596 # The parent property passes this pointer to a hash which this class adds
4597 # all its aliases to, so that the parent can quickly take an alias and
4598 # find this table.
4599 main::set_access('find_table_from_alias', \%find_table_from_alias, 'p_r');
4600
4601 my %locked;
4602 # After this table is made equivalent to another one; we shouldn't go
4603 # changing the contents because that could mean it's no longer equivalent
4604 main::set_access('locked', \%locked, 'r');
4605
4606 my %file_path;
4607 # This gives the final path to the file containing the table. Each
4608 # directory in the path is an element in the array
4609 main::set_access('file_path', \%file_path, 'readable_array');
4610
4611 my %status;
4612 # What is the table's status, normal, $OBSOLETE, etc. Enum
4613 main::set_access('status', \%status, 'r');
4614
4615 my %status_info;
4616 # A comment about its being obsolete, or whatever non normal status it has
4617 main::set_access('status_info', \%status_info, 'r');
4618
d867ccfb
KW
4619 my %caseless_equivalent;
4620 # The table this is equivalent to under /i matching, if any.
4621 main::set_access('caseless_equivalent', \%caseless_equivalent, 'r', 's');
4622
99870f4d
KW
4623 my %range_size_1;
4624 # Is the table to be output with each range only a single code point?
4625 # This is done to avoid breaking existing code that may have come to rely
4626 # on this behavior in previous versions of this program.)
4627 main::set_access('range_size_1', \%range_size_1, 'r', 's');
4628
4629 my %perl_extension;
4630 # A boolean set iff this table is a Perl extension to the Unicode
4631 # standard.
4632 main::set_access('perl_extension', \%perl_extension, 'r');
4633
0c07e538
KW
4634 my %output_range_counts;
4635 # A boolean set iff this table is to have comments written in the
4636 # output file that contain the number of code points in the range.
4637 # The constructor can override the global flag of the same name.
4638 main::set_access('output_range_counts', \%output_range_counts, 'r');
4639
f5817e0a
KW
4640 my %format;
4641 # The format of the entries of the table. This is calculated from the
4642 # data in the table (or passed in the constructor). This is an enum e.g.,
26561784
KW
4643 # $STRING_FORMAT. It is marked protected as it should not be generally
4644 # used to override calculations.
f5817e0a
KW
4645 main::set_access('format', \%format, 'r', 'p_s');
4646
99870f4d
KW
4647 sub new {
4648 # All arguments are key => value pairs, which you can see below, most
33e96e72 4649 # of which match fields documented above. Otherwise: Re_Pod_Entry,
0eac1e20 4650 # OK_as_Filename, and Fuzzy apply to the names of the table, and are
99870f4d
KW
4651 # documented in the Alias package
4652
4653 return Carp::carp_too_few_args(\@_, 2) if main::DEBUG && @_ < 2;
4654
4655 my $class = shift;
4656
4657 my $self = bless \do { my $anonymous_scalar }, $class;
ffe43484 4658 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
4659
4660 my %args = @_;
4661
4662 $name{$addr} = delete $args{'Name'};
4663 $find_table_from_alias{$addr} = delete $args{'_Alias_Hash'};
4664 $full_name{$addr} = delete $args{'Full_Name'};
23e33b60
KW
4665 my $complete_name = $complete_name{$addr}
4666 = delete $args{'Complete_Name'};
f5817e0a 4667 $format{$addr} = delete $args{'Format'};
0c07e538 4668 $output_range_counts{$addr} = delete $args{'Output_Range_Counts'};
99870f4d
KW
4669 $property{$addr} = delete $args{'_Property'};
4670 $range_list{$addr} = delete $args{'_Range_List'};
4671 $status{$addr} = delete $args{'Status'} || $NORMAL;
4672 $status_info{$addr} = delete $args{'_Status_Info'} || "";
4673 $range_size_1{$addr} = delete $args{'Range_Size_1'} || 0;
d867ccfb 4674 $caseless_equivalent{$addr} = delete $args{'Caseless_Equivalent'} || 0;
301ba948 4675 $fate{$addr} = delete $args{'Fate'} || $ORDINARY;
fd1e3e84 4676 my $ucd = delete $args{'UCD'};
99870f4d
KW
4677
4678 my $description = delete $args{'Description'};
0eac1e20 4679 my $ok_as_filename = delete $args{'OK_as_Filename'};
99870f4d
KW
4680 my $loose_match = delete $args{'Fuzzy'};
4681 my $note = delete $args{'Note'};
33e96e72 4682 my $make_re_pod_entry = delete $args{'Re_Pod_Entry'};
37e2e78e 4683 my $perl_extension = delete $args{'Perl_Extension'};
99870f4d
KW
4684
4685 # Shouldn't have any left over
4686 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
4687
4688 # Can't use || above because conceivably the name could be 0, and
4689 # can't use // operator in case this program gets used in Perl 5.8
4690 $full_name{$addr} = $name{$addr} if ! defined $full_name{$addr};
0c07e538
KW
4691 $output_range_counts{$addr} = $output_range_counts if
4692 ! defined $output_range_counts{$addr};
99870f4d
KW
4693
4694 $aliases{$addr} = [ ];
4695 $comment{$addr} = [ ];
4696 $description{$addr} = [ ];
4697 $note{$addr} = [ ];
4698 $file_path{$addr} = [ ];
4699 $locked{$addr} = "";
4700
4701 push @{$description{$addr}}, $description if $description;
4702 push @{$note{$addr}}, $note if $note;
4703
301ba948 4704 if ($fate{$addr} == $PLACEHOLDER) {
37e2e78e
KW
4705
4706 # A placeholder table doesn't get documented, is a perl extension,
4707 # and quite likely will be empty
33e96e72 4708 $make_re_pod_entry = 0 if ! defined $make_re_pod_entry;
37e2e78e 4709 $perl_extension = 1 if ! defined $perl_extension;
fd1e3e84 4710 $ucd = 0 if ! defined $ucd;
37e2e78e 4711 push @tables_that_may_be_empty, $complete_name{$addr};
301ba948
KW
4712 $self->add_comment(<<END);
4713This is a placeholder because it is not in Version $string_version of Unicode,
4714but is needed by the Perl core to work gracefully. Because it is not in this
4715version of Unicode, it will not be listed in $pod_file.pod
4716END
37e2e78e 4717 }
301ba948 4718 elsif (exists $why_suppressed{$complete_name}
98dc9551 4719 # Don't suppress if overridden
ec11e5f4
KW
4720 && ! grep { $_ eq $complete_name{$addr} }
4721 @output_mapped_properties)
301ba948
KW
4722 {
4723 $fate{$addr} = $SUPPRESSED;
4724 }
4725 elsif ($fate{$addr} == $SUPPRESSED
4726 && ! exists $why_suppressed{$property{$addr}->complete_name})
4727 {
4728 Carp::my_carp_bug("There is no current capability to set the reason for suppressing.");
4729 # perhaps Fate => [ $SUPPRESSED, "reason" ]
4730 }
4731
4732 # If hasn't set its status already, see if it is on one of the
4733 # lists of properties or tables that have particular statuses; if
4734 # not, is normal. The lists are prioritized so the most serious
4735 # ones are checked first
4736 if (! $status{$addr}) {
4737 if (exists $why_deprecated{$complete_name}) {
99870f4d
KW
4738 $status{$addr} = $DEPRECATED;
4739 }
4740 elsif (exists $why_stabilized{$complete_name}) {
4741 $status{$addr} = $STABILIZED;
4742 }
4743 elsif (exists $why_obsolete{$complete_name}) {
4744 $status{$addr} = $OBSOLETE;
4745 }
4746
4747 # Existence above doesn't necessarily mean there is a message
4748 # associated with it. Use the most serious message.
4749 if ($status{$addr}) {
301ba948 4750 if ($why_deprecated{$complete_name}) {
99870f4d
KW
4751 $status_info{$addr}
4752 = $why_deprecated{$complete_name};
4753 }
4754 elsif ($why_stabilized{$complete_name}) {
4755 $status_info{$addr}
4756 = $why_stabilized{$complete_name};
4757 }
4758 elsif ($why_obsolete{$complete_name}) {
4759 $status_info{$addr}
4760 = $why_obsolete{$complete_name};
4761 }
4762 }
4763 }
4764
37e2e78e
KW
4765 $perl_extension{$addr} = $perl_extension || 0;
4766
8050d00f 4767 # Don't list a property by default that is internal only
395dfc19 4768 if ($fate{$addr} > $MAP_PROXIED) {
301ba948 4769 $make_re_pod_entry = 0 if ! defined $make_re_pod_entry;
fd1e3e84
KW
4770 $ucd = 0 if ! defined $ucd;
4771 }
4772 else {
4773 $ucd = 1 if ! defined $ucd;
301ba948 4774 }
8050d00f 4775
99870f4d
KW
4776 # By convention what typically gets printed only or first is what's
4777 # first in the list, so put the full name there for good output
4778 # clarity. Other routines rely on the full name being first on the
4779 # list
4780 $self->add_alias($full_name{$addr},
0eac1e20 4781 OK_as_Filename => $ok_as_filename,
99870f4d 4782 Fuzzy => $loose_match,
33e96e72 4783 Re_Pod_Entry => $make_re_pod_entry,
99870f4d 4784 Status => $status{$addr},
fd1e3e84 4785 UCD => $ucd,
99870f4d
KW
4786 );
4787
4788 # Then comes the other name, if meaningfully different.
4789 if (standardize($full_name{$addr}) ne standardize($name{$addr})) {
4790 $self->add_alias($name{$addr},
0eac1e20 4791 OK_as_Filename => $ok_as_filename,
99870f4d 4792 Fuzzy => $loose_match,
33e96e72 4793 Re_Pod_Entry => $make_re_pod_entry,
99870f4d 4794 Status => $status{$addr},
fd1e3e84 4795 UCD => $ucd,
99870f4d
KW
4796 );
4797 }
4798
4799 return $self;
4800 }
4801
4802 # Here are the methods that are required to be defined by any derived
4803 # class
ea25a9b2 4804 for my $sub (qw(
668b3bfc 4805 handle_special_range
99870f4d 4806 append_to_body
99870f4d 4807 pre_body
ea25a9b2 4808 ))
668b3bfc
KW
4809 # write() knows how to write out normal ranges, but it calls
4810 # handle_special_range() when it encounters a non-normal one.
4811 # append_to_body() is called by it after it has handled all
4812 # ranges to add anything after the main portion of the table.
4813 # And finally, pre_body() is called after all this to build up
4814 # anything that should appear before the main portion of the
4815 # table. Doing it this way allows things in the middle to
4816 # affect what should appear before the main portion of the
99870f4d 4817 # table.
99870f4d
KW
4818 {
4819 no strict "refs";
4820 *$sub = sub {
4821 Carp::my_carp_bug( __LINE__
4822 . ": Must create method '$sub()' for "
4823 . ref shift);
4824 return;
4825 }
4826 }
4827
4828 use overload
4829 fallback => 0,
4830 "." => \&main::_operator_dot,
4831 '!=' => \&main::_operator_not_equal,
4832 '==' => \&main::_operator_equal,
4833 ;
4834
4835 sub ranges {
4836 # Returns the array of ranges associated with this table.
4837
f998e60c 4838 no overloading;
051df77b 4839 return $range_list{pack 'J', shift}->ranges;
99870f4d
KW
4840 }
4841
4842 sub add_alias {
4843 # Add a synonym for this table.
4844
4845 return Carp::carp_too_few_args(\@_, 3) if main::DEBUG && @_ < 3;
4846
4847 my $self = shift;
4848 my $name = shift; # The name to add.
4849 my $pointer = shift; # What the alias hash should point to. For
4850 # map tables, this is the parent property;
4851 # for match tables, it is the table itself.
4852
4853 my %args = @_;
4854 my $loose_match = delete $args{'Fuzzy'};
4855
33e96e72
KW
4856 my $make_re_pod_entry = delete $args{'Re_Pod_Entry'};
4857 $make_re_pod_entry = $YES unless defined $make_re_pod_entry;
99870f4d 4858
0eac1e20
KW
4859 my $ok_as_filename = delete $args{'OK_as_Filename'};
4860 $ok_as_filename = 1 unless defined $ok_as_filename;
99870f4d
KW
4861
4862 my $status = delete $args{'Status'};
4863 $status = $NORMAL unless defined $status;
4864
fd1e3e84
KW
4865 my $ucd = delete $args{'UCD'} // 1;
4866
99870f4d
KW
4867 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
4868
4869 # Capitalize the first letter of the alias unless it is one of the CJK
4870 # ones which specifically begins with a lower 'k'. Do this because
4871 # Unicode has varied whether they capitalize first letters or not, and
4872 # have later changed their minds and capitalized them, but not the
4873 # other way around. So do it always and avoid changes from release to
4874 # release
4875 $name = ucfirst($name) unless $name =~ /^k[A-Z]/;
4876
ffe43484 4877 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
4878
4879 # Figure out if should be loosely matched if not already specified.
4880 if (! defined $loose_match) {
4881
4882 # Is a loose_match if isn't null, and doesn't begin with an
4883 # underscore and isn't just a number
4884 if ($name ne ""
4885 && substr($name, 0, 1) ne '_'
4886 && $name !~ qr{^[0-9_.+-/]+$})
4887 {
4888 $loose_match = 1;
4889 }
4890 else {
4891 $loose_match = 0;
4892 }
4893 }
4894
4895 # If this alias has already been defined, do nothing.
4896 return if defined $find_table_from_alias{$addr}->{$name};
4897
4898 # That includes if it is standardly equivalent to an existing alias,
4899 # in which case, add this name to the list, so won't have to search
4900 # for it again.
4901 my $standard_name = main::standardize($name);
4902 if (defined $find_table_from_alias{$addr}->{$standard_name}) {
4903 $find_table_from_alias{$addr}->{$name}
4904 = $find_table_from_alias{$addr}->{$standard_name};
4905 return;
4906 }
4907
4908 # Set the index hash for this alias for future quick reference.
4909 $find_table_from_alias{$addr}->{$name} = $pointer;
4910 $find_table_from_alias{$addr}->{$standard_name} = $pointer;
4911 local $to_trace = 0 if main::DEBUG;
4912 trace "adding alias $name to $pointer" if main::DEBUG && $to_trace;
4913 trace "adding alias $standard_name to $pointer" if main::DEBUG && $to_trace;
4914
4915
4916 # Put the new alias at the end of the list of aliases unless the final
4917 # element begins with an underscore (meaning it is for internal perl
4918 # use) or is all numeric, in which case, put the new one before that
4919 # one. This floats any all-numeric or underscore-beginning aliases to
4920 # the end. This is done so that they are listed last in output lists,
4921 # to encourage the user to use a better name (either more descriptive
4922 # or not an internal-only one) instead. This ordering is relied on
4923 # implicitly elsewhere in this program, like in short_name()
4924 my $list = $aliases{$addr};
4925 my $insert_position = (@$list == 0
4926 || (substr($list->[-1]->name, 0, 1) ne '_'
4927 && $list->[-1]->name =~ /\D/))
4928 ? @$list
4929 : @$list - 1;
4930 splice @$list,
4931 $insert_position,
4932 0,
33e96e72 4933 Alias->new($name, $loose_match, $make_re_pod_entry,
0eac1e20 4934 $ok_as_filename, $status, $ucd);
99870f4d
KW
4935
4936 # This name may be shorter than any existing ones, so clear the cache
4937 # of the shortest, so will have to be recalculated.
f998e60c 4938 no overloading;
051df77b 4939 undef $short_name{pack 'J', $self};
99870f4d
KW
4940 return;
4941 }
4942
4943 sub short_name {
4944 # Returns a name suitable for use as the base part of a file name.
4945 # That is, shorter wins. It can return undef if there is no suitable
4946 # name. The name has all non-essential underscores removed.
4947
4948 # The optional second parameter is a reference to a scalar in which
4949 # this routine will store the length the returned name had before the
4950 # underscores were removed, or undef if the return is undef.
4951
4952 # The shortest name can change if new aliases are added. So using
4953 # this should be deferred until after all these are added. The code
4954 # that does that should clear this one's cache.
4955 # Any name with alphabetics is preferred over an all numeric one, even
4956 # if longer.
4957
4958 my $self = shift;
4959 my $nominal_length_ptr = shift;
4960 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
4961
ffe43484 4962 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
4963
4964 # For efficiency, don't recalculate, but this means that adding new
4965 # aliases could change what the shortest is, so the code that does
4966 # that needs to undef this.
4967 if (defined $short_name{$addr}) {
4968 if ($nominal_length_ptr) {
4969 $$nominal_length_ptr = $nominal_short_name_length{$addr};
4970 }
4971 return $short_name{$addr};
4972 }
4973
4974 # Look at each alias
4975 foreach my $alias ($self->aliases()) {
4976
4977 # Don't use an alias that isn't ok to use for an external name.
0eac1e20 4978 next if ! $alias->ok_as_filename;
99870f4d
KW
4979
4980 my $name = main::Standardize($alias->name);
4981 trace $self, $name if main::DEBUG && $to_trace;
4982
4983 # Take the first one, or a shorter one that isn't numeric. This
4984 # relies on numeric aliases always being last in the array
4985 # returned by aliases(). Any alpha one will have precedence.
4986 if (! defined $short_name{$addr}
4987 || ($name =~ /\D/
4988 && length($name) < length($short_name{$addr})))
4989 {
4990 # Remove interior underscores.
4991 ($short_name{$addr} = $name) =~ s/ (?<= . ) _ (?= . ) //xg;
4992
4993 $nominal_short_name_length{$addr} = length $name;
4994 }
4995 }
4996
ff485b9e
KW
4997 # If the short name isn't a nice one, perhaps an equivalent table has
4998 # a better one.
4999 if (! defined $short_name{$addr}
5000 || $short_name{$addr} eq ""
5001 || $short_name{$addr} eq "_")
5002 {
5003 my $return;
5004 foreach my $follower ($self->children) { # All equivalents
5005 my $follower_name = $follower->short_name;
5006 next unless defined $follower_name;
5007
5008 # Anything (except undefined) is better than underscore or
5009 # empty
5010 if (! defined $return || $return eq "_") {
5011 $return = $follower_name;
5012 next;
5013 }
5014
5015 # If the new follower name isn't "_" and is shorter than the
5016 # current best one, prefer the new one.
5017 next if $follower_name eq "_";
5018 next if length $follower_name > length $return;
5019 $return = $follower_name;
5020 }
5021 $short_name{$addr} = $return if defined $return;
5022 }
5023
99870f4d
KW
5024 # If no suitable external name return undef
5025 if (! defined $short_name{$addr}) {
5026 $$nominal_length_ptr = undef if $nominal_length_ptr;
5027 return;
5028 }
5029
c12f2655 5030 # Don't allow a null short name.
99870f4d
KW
5031 if ($short_name{$addr} eq "") {
5032 $short_name{$addr} = '_';
5033 $nominal_short_name_length{$addr} = 1;
5034 }
5035
5036 trace $self, $short_name{$addr} if main::DEBUG && $to_trace;
5037
5038 if ($nominal_length_ptr) {
5039 $$nominal_length_ptr = $nominal_short_name_length{$addr};
5040 }
5041 return $short_name{$addr};
5042 }
5043
5044 sub external_name {
5045 # Returns the external name that this table should be known by. This
c12f2655
KW
5046 # is usually the short_name, but not if the short_name is undefined,
5047 # in which case the external_name is arbitrarily set to the
5048 # underscore.
99870f4d
KW
5049
5050 my $self = shift;
5051 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5052
5053 my $short = $self->short_name;
5054 return $short if defined $short;
5055
5056 return '_';
5057 }
5058
5059 sub add_description { # Adds the parameter as a short description.
5060
5061 my $self = shift;
5062 my $description = shift;
5063 chomp $description;
5064 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5065
f998e60c 5066 no overloading;
051df77b 5067 push @{$description{pack 'J', $self}}, $description;
99870f4d
KW
5068
5069 return;
5070 }
5071
5072 sub add_note { # Adds the parameter as a short note.
5073
5074 my $self = shift;
5075 my $note = shift;
5076 chomp $note;
5077 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5078
f998e60c 5079 no overloading;
051df77b 5080 push @{$note{pack 'J', $self}}, $note;
99870f4d
KW
5081
5082 return;
5083 }
5084
5085 sub add_comment { # Adds the parameter as a comment.
5086
bd9ebcfd
KW
5087 return unless $debugging_build;
5088
99870f4d
KW
5089 my $self = shift;
5090 my $comment = shift;
5091 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5092
5093 chomp $comment;
f998e60c
KW
5094
5095 no overloading;
051df77b 5096 push @{$comment{pack 'J', $self}}, $comment;
99870f4d
KW
5097
5098 return;
5099 }
5100
5101 sub comment {
5102 # Return the current comment for this table. If called in list
5103 # context, returns the array of comments. In scalar, returns a string
5104 # of each element joined together with a period ending each.
5105
5106 my $self = shift;
5107 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5108
ffe43484 5109 my $addr = do { no overloading; pack 'J', $self; };
f998e60c 5110 my @list = @{$comment{$addr}};
99870f4d
KW
5111 return @list if wantarray;
5112 my $return = "";
5113 foreach my $sentence (@list) {
5114 $return .= '. ' if $return;
5115 $return .= $sentence;
5116 $return =~ s/\.$//;
5117 }
5118 $return .= '.' if $return;
5119 return $return;
5120 }
5121
5122 sub initialize {
5123 # Initialize the table with the argument which is any valid
5124 # initialization for range lists.
5125
5126 my $self = shift;
ffe43484 5127 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
5128 my $initialization = shift;
5129 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5130
5131 # Replace the current range list with a new one of the same exact
5132 # type.
f998e60c
KW
5133 my $class = ref $range_list{$addr};
5134 $range_list{$addr} = $class->new(Owner => $self,
99870f4d
KW
5135 Initialize => $initialization);
5136 return;
5137
5138 }
5139
5140 sub header {
5141 # The header that is output for the table in the file it is written
5142 # in.
5143
5144 my $self = shift;
5145 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5146
5147 my $return = "";
5148 $return .= $DEVELOPMENT_ONLY if $compare_versions;
5149 $return .= $HEADER;
99870f4d
KW
5150 return $return;
5151 }
5152
5153 sub write {
668b3bfc
KW
5154 # Write a representation of the table to its file. It calls several
5155 # functions furnished by sub-classes of this abstract base class to
5156 # handle non-normal ranges, to add stuff before the table, and at its
bbed833a
KW
5157 # end. If the table is to be written using deltas from the current
5158 # code point, this does that conversion.
99870f4d
KW
5159
5160 my $self = shift;
bbed833a 5161 my $use_delta_cp = shift; # ? output deltas or not
99870f4d
KW
5162 my $tab_stops = shift; # The number of tab stops over to put any
5163 # comment.
5164 my $suppress_value = shift; # Optional, if the value associated with
5165 # a range equals this one, don't write
5166 # the range
5167 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5168
ffe43484 5169 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
5170
5171 # Start with the header
668b3bfc 5172 my @HEADER = $self->header;
99870f4d
KW
5173
5174 # Then the comments
668b3bfc 5175 push @HEADER, "\n", main::simple_fold($comment{$addr}, '# '), "\n"
99870f4d
KW
5176 if $comment{$addr};
5177
668b3bfc
KW
5178 # Things discovered processing the main body of the document may
5179 # affect what gets output before it, therefore pre_body() isn't called
5180 # until after all other processing of the table is done.
99870f4d 5181
c4019d52
KW
5182 # The main body looks like a 'here' document. If annotating, get rid
5183 # of the comments before passing to the caller, as some callers, such
5184 # as charnames.pm, can't cope with them. (Outputting range counts
5185 # also introduces comments, but these don't show up in the tables that
5186 # can't cope with comments, and there aren't that many of them that
5187 # it's worth the extra real time to get rid of them).
668b3bfc 5188 my @OUT;
558712cf 5189 if ($annotate) {
c4019d52
KW
5190 # Use the line below in Perls that don't have /r
5191 #push @OUT, 'return join "\n", map { s/\s*#.*//mg; $_ } split "\n", <<\'END\';' . "\n";
5192 push @OUT, "return <<'END' =~ s/\\s*#.*//mgr;\n";
5193 } else {
5194 push @OUT, "return <<'END';\n";
5195 }
99870f4d
KW
5196
5197 if ($range_list{$addr}->is_empty) {
5198
5199 # This is a kludge for empty tables to silence a warning in
5200 # utf8.c, which can't really deal with empty tables, but it can
5201 # deal with a table that matches nothing, as the inverse of 'Any'
5202 # does.
67a53d68 5203 push @OUT, "!utf8::Any\n";
99870f4d 5204 }
c69a9c68
KW
5205 elsif ($self->name eq 'N'
5206
5207 # To save disk space and table cache space, avoid putting out
5208 # binary N tables, but instead create a file which just inverts
5209 # the Y table. Since the file will still exist and occupy a
5210 # certain number of blocks, might as well output the whole
5211 # thing if it all will fit in one block. The number of
5212 # ranges below is an approximate number for that.
06f26c45
KW
5213 && ($self->property->type == $BINARY
5214 || $self->property->type == $FORCED_BINARY)
c69a9c68
KW
5215 # && $self->property->tables == 2 Can't do this because the
5216 # non-binary properties, like NFDQC aren't specifiable
5217 # by the notation
5218 && $range_list{$addr}->ranges > 15
5219 && ! $annotate) # Under --annotate, want to see everything
5220 {
5221 push @OUT, "!utf8::" . $self->property->name . "\n";
5222 }
99870f4d
KW
5223 else {
5224 my $range_size_1 = $range_size_1{$addr};
558712cf
KW
5225 my $format; # Used only in $annotate option
5226 my $include_name; # Used only in $annotate option
c4019d52 5227
558712cf 5228 if ($annotate) {
c4019d52 5229
d59563d0 5230 # If annotating each code point, must print 1 per line.
c4019d52
KW
5231 # The variable could point to a subroutine, and we don't want
5232 # to lose that fact, so only set if not set already
5233 $range_size_1 = 1 if ! $range_size_1;
5234
5235 $format = $self->format;
5236
5237 # The name of the character is output only for tables that
5238 # don't already include the name in the output.
5239 my $property = $self->property;
5240 $include_name =
5241 ! ($property == $perl_charname
5242 || $property == main::property_ref('Unicode_1_Name')
5243 || $property == main::property_ref('Name')
5244 || $property == main::property_ref('Name_Alias')
5245 );
5246 }
99870f4d 5247
bbed833a
KW
5248 # Values for previous time through the loop. Initialize to
5249 # something that won't be adjacent to the first iteration;
5250 # only $previous_end matters for that.
5251 my $previous_start;
5252 my $previous_end = -2;
5253 my $previous_value;
5254
5255 # Values for next time through the portion of the loop that splits
5256 # the range. 0 in $next_start means there is no remaining portion
5257 # to deal with.
5258 my $next_start = 0;
5259 my $next_end;
5260 my $next_value;
5261
99870f4d 5262 # Output each range as part of the here document.
5a2b5ddb 5263 RANGE:
99870f4d 5264 for my $set ($range_list{$addr}->ranges) {
5a2b5ddb
KW
5265 if ($set->type != 0) {
5266 $self->handle_special_range($set);
5267 next RANGE;
5268 }
99870f4d
KW
5269 my $start = $set->start;
5270 my $end = $set->end;
5271 my $value = $set->value;
5272
5273 # Don't output ranges whose value is the one to suppress
c4019d52
KW
5274 next RANGE if defined $suppress_value
5275 && $value eq $suppress_value;
99870f4d 5276
bbed833a
KW
5277 { # This bare block encloses the scope where we may need to
5278 # split a range (when outputting deltas), and each time
5279 # through we handle the next portion of the original by
5280 # ending the block with a 'redo'. The values to use for
5281 # that next time through are set up just below in the
5282 # scalars whose names begin with '$next_'.
5283
5284 if ($use_delta_cp) {
5285
5286 # When converting to deltas, we can handle only single
5287 # element ranges. Set up so that this time through
5288 # the loop, we look at the first element, and the next
5289 # time through, we start off with the remainder. Thus
5290 # each time through we look at the first element of
5291 # the range
5292 if ($end != $start) {
5293 $next_start = $start + 1;
5294 $next_end = $end;
5295 $next_value = $value;
5296 $end = $start;
5297 }
5298
5299 # The values for these tables is stored as hex
5300 # strings. Get the delta by subtracting the code
5301 # point.
5302 $value = hex($value) - $start;
5303
5304 # If this range is adjacent to the previous one, and
5305 # the values in each are the same, then this range
5306 # really extends the previous one that is already in
5307 # element $OUT[-1]. So we pop that element, and
5308 # pretend that the range starts with whatever it
5309 # started with.
5310 if ($start == $previous_end + 1
5311 && $value == $previous_value)
5312 {
5313 pop @OUT;
5314 $start = $previous_start;
5315 }
5316
5317 # Save the current values for the next time through
5318 # the loop.
5319 $previous_start = $start;
5320 $previous_end = $end;
5321 $previous_value = $value;
5322 }
5323
74a3abe0
KW
5324 # If there is a range and doesn't need a single point range
5325 # output
5326 if ($start != $end && ! $range_size_1) {
5327 push @OUT, sprintf "%04X\t%04X", $start, $end;
5328 $OUT[-1] .= "\t$value" if $value ne "";
5329
5330 # Add a comment with the size of the range, if
5331 # requested. Expand Tabs to make sure they all start
5332 # in the same column, and then unexpand to use mostly
5333 # tabs.
5334 if (! $output_range_counts{$addr}) {
5335 $OUT[-1] .= "\n";
5336 }
5337 else {
5338 $OUT[-1] = Text::Tabs::expand($OUT[-1]);
5339 my $count = main::clarify_number($end - $start + 1);
5340 use integer;
5341
5342 my $width = $tab_stops * 8 - 1;
5343 $OUT[-1] = sprintf("%-*s # [%s]\n",
5344 $width,
5345 $OUT[-1],
5346 $count);
5347 $OUT[-1] = Text::Tabs::unexpand($OUT[-1]);
5348 }
99870f4d 5349 }
c4019d52 5350
74a3abe0
KW
5351 # Here to output a single code point per line.
5352 # If not to annotate, use the simple formats
5353 elsif (! $annotate) {
5354
5355 # Use any passed in subroutine to output.
5356 if (ref $range_size_1 eq 'CODE') {
5357 for my $i ($start .. $end) {
5358 push @OUT, &{$range_size_1}($i, $value);
5359 }
5360 }
5361 else {
c4019d52 5362
74a3abe0
KW
5363 # Here, caller is ok with default output.
5364 for (my $i = $start; $i <= $end; $i++) {
5365 push @OUT, sprintf "%04X\t\t%s\n", $i, $value;
5366 }
c4019d52
KW
5367 }
5368 }
5369 else {
5370
74a3abe0 5371 # Here, wants annotation.
c4019d52 5372 for (my $i = $start; $i <= $end; $i++) {
c4019d52 5373
74a3abe0
KW
5374 # Get character information if don't have it already
5375 main::populate_char_info($i)
5376 if ! defined $viacode[$i];
5377 my $type = $annotate_char_type[$i];
5378
5379 # Figure out if should output the next code points
5380 # as part of a range or not. If this is not in an
5381 # annotation range, then won't output as a range,
5382 # so returns $i. Otherwise use the end of the
5383 # annotation range, but no further than the
5384 # maximum possible end point of the loop.
5385 my $range_end = main::min(
5386 $annotate_ranges->value_of($i) || $i,
5387 $end);
5388
5389 # Use a range if it is a range, and either is one
5390 # of the special annotation ranges, or the range
5391 # is at most 3 long. This last case causes the
5392 # algorithmically named code points to be output
5393 # individually in spans of at most 3, as they are
5394 # the ones whose $type is > 0.
5395 if ($range_end != $i
5396 && ( $type < 0 || $range_end - $i > 2))
5397 {
5398 # Here is to output a range. We don't allow a
5399 # caller-specified output format--just use the
5400 # standard one.
5401 push @OUT, sprintf "%04X\t%04X\t%s\t#", $i,
c4019d52
KW
5402 $range_end,
5403 $value;
74a3abe0
KW
5404 my $range_name = $viacode[$i];
5405
5406 # For the code points which end in their hex
5407 # value, we eliminate that from the output
5408 # annotation, and capitalize only the first
5409 # letter of each word.
5410 if ($type == $CP_IN_NAME) {
5411 my $hex = sprintf "%04X", $i;
5412 $range_name =~ s/-$hex$//;
5413 my @words = split " ", $range_name;
5414 for my $word (@words) {
5415 $word =
5416 ucfirst(lc($word)) if $word ne 'CJK';
5417 }
5418 $range_name = join " ", @words;
5419 }
5420 elsif ($type == $HANGUL_SYLLABLE) {
5421 $range_name = "Hangul Syllable";
5422 }
c4019d52 5423
74a3abe0 5424 $OUT[-1] .= " $range_name" if $range_name;
c4019d52 5425
74a3abe0
KW
5426 # Include the number of code points in the
5427 # range
5428 my $count =
5429 main::clarify_number($range_end - $i + 1);
5430 $OUT[-1] .= " [$count]\n";
c4019d52 5431
74a3abe0
KW
5432 # Skip to the end of the range
5433 $i = $range_end;
c4019d52 5434 }
74a3abe0
KW
5435 else { # Not in a range.
5436 my $comment = "";
5437
5438 # When outputting the names of each character,
5439 # use the character itself if printable
5440 $comment .= "'" . chr($i) . "' "
5441 if $printable[$i];
5442
5443 # To make it more readable, use a minimum
5444 # indentation
5445 my $comment_indent;
5446
5447 # Determine the annotation
5448 if ($format eq $DECOMP_STRING_FORMAT) {
5449
5450 # This is very specialized, with the type
5451 # of decomposition beginning the line
5452 # enclosed in <...>, and the code points
5453 # that the code point decomposes to
5454 # separated by blanks. Create two
5455 # strings, one of the printable
5456 # characters, and one of their official
5457 # names.
5458 (my $map = $value) =~ s/ \ * < .*? > \ +//x;
5459 my $tostr = "";
5460 my $to_name = "";
5461 my $to_chr = "";
5462 foreach my $to (split " ", $map) {
5463 $to = CORE::hex $to;
5464 $to_name .= " + " if $to_name;
5465 $to_chr .= chr($to);
5466 main::populate_char_info($to)
5467 if ! defined $viacode[$to];
5468 $to_name .= $viacode[$to];
5469 }
c4019d52 5470
74a3abe0 5471 $comment .=
c4019d52 5472 "=> '$to_chr'; $viacode[$i] => $to_name";
74a3abe0
KW
5473 $comment_indent = 25; # Determined by
5474 # experiment
5475 }
5476 else {
5477
5478 # Assume that any table that has hex
5479 # format is a mapping of one code point to
5480 # another.
5481 if ($format eq $HEX_FORMAT) {
5482 my $decimal_value = CORE::hex $value;
5483 main::populate_char_info($decimal_value)
c4019d52 5484 if ! defined $viacode[$decimal_value];
74a3abe0
KW
5485 $comment .= "=> '"
5486 . chr($decimal_value)
5487 . "'; " if $printable[$decimal_value];
5488 }
5489 $comment .= $viacode[$i] if $include_name
5490 && $viacode[$i];
5491 if ($format eq $HEX_FORMAT) {
5492 my $decimal_value = CORE::hex $value;
5493 $comment .=
5494 " => $viacode[$decimal_value]"
5495 if $viacode[$decimal_value];
5496 }
c4019d52 5497
74a3abe0
KW
5498 # If including the name, no need to
5499 # indent, as the name will already be way
5500 # across the line.
5501 $comment_indent = ($include_name) ? 0 : 60;
5502 }
c4019d52 5503
74a3abe0
KW
5504 # Use any passed in routine to output the base
5505 # part of the line.
5506 if (ref $range_size_1 eq 'CODE') {
5507 my $base_part=&{$range_size_1}($i, $value);
5508 chomp $base_part;
5509 push @OUT, $base_part;
5510 }
5511 else {
5512 push @OUT, sprintf "%04X\t\t%s", $i, $value;
5513 }
c4019d52 5514
74a3abe0
KW
5515 # And add the annotation.
5516 $OUT[-1] = sprintf "%-*s\t# %s",
5517 $comment_indent,
5518 $OUT[-1],
5519 $comment
5520 if $comment;
5521 $OUT[-1] .= "\n";
5522 }
5523 }
c4019d52 5524 }
bbed833a
KW
5525
5526 # If we split the range, set up so the next time through
5527 # we get the remainder, and redo.
5528 if ($next_start) {
5529 $start = $next_start;
5530 $end = $next_end;
5531 $value = $next_value;
5532 $next_start = 0;
5533 redo;
5534 }
99870f4d
KW
5535 }
5536 } # End of loop through all the table's ranges
5537 }
5538
5539 # Add anything that goes after the main body, but within the here
5540 # document,
5541 my $append_to_body = $self->append_to_body;
5542 push @OUT, $append_to_body if $append_to_body;
5543
5544 # And finish the here document.
5545 push @OUT, "END\n";
5546
668b3bfc
KW
5547 # Done with the main portion of the body. Can now figure out what
5548 # should appear before it in the file.
5549 my $pre_body = $self->pre_body;
5550 push @HEADER, $pre_body, "\n" if $pre_body;
668b3bfc 5551
6b0079b5
KW
5552 # All these files should have a .pl suffix added to them.
5553 my @file_with_pl = @{$file_path{$addr}};
5554 $file_with_pl[-1] .= '.pl';
99870f4d 5555
6b0079b5 5556 main::write(\@file_with_pl,
558712cf 5557 $annotate, # utf8 iff annotating
9218f1cf
KW
5558 \@HEADER,
5559 \@OUT);
99870f4d
KW
5560 return;
5561 }
5562
5563 sub set_status { # Set the table's status
5564 my $self = shift;
5565 my $status = shift; # The status enum value
5566 my $info = shift; # Any message associated with it.
5567 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5568
ffe43484 5569 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
5570
5571 $status{$addr} = $status;
5572 $status_info{$addr} = $info;
5573 return;
5574 }
5575
301ba948
KW
5576 sub set_fate { # Set the fate of a table
5577 my $self = shift;
5578 my $fate = shift;
5579 my $reason = shift;
5580 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5581
5582 my $addr = do { no overloading; pack 'J', $self; };
5583
5584 return if $fate{$addr} == $fate; # If no-op
5585
395dfc19
KW
5586 # Can only change the ordinary fate, except if going to $MAP_PROXIED
5587 return if $fate{$addr} != $ORDINARY && $fate != $MAP_PROXIED;
301ba948
KW
5588
5589 $fate{$addr} = $fate;
5590
395dfc19
KW
5591 # Don't document anything to do with a non-normal fated table
5592 if ($fate != $ORDINARY) {
fd1e3e84 5593 my $put_in_pod = ($fate == $MAP_PROXIED) ? 1 : 0;
395dfc19 5594 foreach my $alias ($self->aliases) {
fd1e3e84 5595 $alias->set_ucd($put_in_pod);
395dfc19
KW
5596
5597 # MAP_PROXIED doesn't affect the match tables
5598 next if $fate == $MAP_PROXIED;
fd1e3e84 5599 $alias->set_make_re_pod_entry($put_in_pod);
395dfc19
KW
5600 }
5601 }
5602
301ba948
KW
5603 # Save the reason for suppression for output
5604 if ($fate == $SUPPRESSED && defined $reason) {
5605 $why_suppressed{$complete_name{$addr}} = $reason;
5606 }
5607
5608 return;
5609 }
5610
99870f4d
KW
5611 sub lock {
5612 # Don't allow changes to the table from now on. This stores a stack
5613 # trace of where it was called, so that later attempts to modify it
5614 # can immediately show where it got locked.
5615
5616 my $self = shift;
5617 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5618
ffe43484 5619 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
5620
5621 $locked{$addr} = "";
5622
5623 my $line = (caller(0))[2];
5624 my $i = 1;
5625
5626 # Accumulate the stack trace
5627 while (1) {
5628 my ($pkg, $file, $caller_line, $caller) = caller $i++;
5629
5630 last unless defined $caller;
5631
5632 $locked{$addr} .= " called from $caller() at line $line\n";
5633 $line = $caller_line;
5634 }
5635 $locked{$addr} .= " called from main at line $line\n";
5636
5637 return;
5638 }
5639
5640 sub carp_if_locked {
5641 # Return whether a table is locked or not, and, by the way, complain
5642 # if is locked
5643
5644 my $self = shift;
5645 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5646
ffe43484 5647 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
5648
5649 return 0 if ! $locked{$addr};
5650 Carp::my_carp_bug("Can't modify a locked table. Stack trace of locking:\n$locked{$addr}\n\n");
5651 return 1;
5652 }
5653
5654 sub set_file_path { # Set the final directory path for this table
5655 my $self = shift;
5656 # Rest of parameters passed on
5657
f998e60c 5658 no overloading;
051df77b 5659 @{$file_path{pack 'J', $self}} = @_;
99870f4d
KW
5660 return
5661 }
5662
5663 # Accessors for the range list stored in this table. First for
5664 # unconditional
ea25a9b2 5665 for my $sub (qw(
2f7a8815 5666 containing_range
99870f4d
KW
5667 contains
5668 count
5669 each_range
5670 hash
5671 is_empty
09aba7e4 5672 matches_identically_to
99870f4d
KW
5673 max
5674 min
5675 range_count
5676 reset_each_range
0a9dbafc 5677 type_of
99870f4d 5678 value_of
ea25a9b2 5679 ))
99870f4d
KW
5680 {
5681 no strict "refs";
5682 *$sub = sub {
5683 use strict "refs";
5684 my $self = shift;
ec40ee88 5685 return $self->_range_list->$sub(@_);
99870f4d
KW
5686 }
5687 }
5688
5689 # Then for ones that should fail if locked
ea25a9b2 5690 for my $sub (qw(
99870f4d 5691 delete_range
ea25a9b2 5692 ))
99870f4d
KW
5693 {
5694 no strict "refs";
5695 *$sub = sub {
5696 use strict "refs";
5697 my $self = shift;
5698
5699 return if $self->carp_if_locked;
f998e60c 5700 no overloading;
ec40ee88 5701 return $self->_range_list->$sub(@_);
99870f4d
KW
5702 }
5703 }
5704
5705} # End closure
5706
5707package Map_Table;
5708use base '_Base_Table';
5709
5710# A Map Table is a table that contains the mappings from code points to
5711# values. There are two weird cases:
5712# 1) Anomalous entries are ones that aren't maps of ranges of code points, but
5713# are written in the table's file at the end of the table nonetheless. It
5714# requires specially constructed code to handle these; utf8.c can not read
5715# these in, so they should not go in $map_directory. As of this writing,
5716# the only case that these happen is for named sequences used in
5717# charnames.pm. But this code doesn't enforce any syntax on these, so
5718# something else could come along that uses it.
5719# 2) Specials are anything that doesn't fit syntactically into the body of the
5720# table. The ranges for these have a map type of non-zero. The code below
5721# knows about and handles each possible type. In most cases, these are
5722# written as part of the header.
5723#
5724# A map table deliberately can't be manipulated at will unlike match tables.
5725# This is because of the ambiguities having to do with what to do with
5726# overlapping code points. And there just isn't a need for those things;
5727# what one wants to do is just query, add, replace, or delete mappings, plus
5728# write the final result.
5729# However, there is a method to get the list of possible ranges that aren't in
5730# this table to use for defaulting missing code point mappings. And,
5731# map_add_or_replace_non_nulls() does allow one to add another table to this
5732# one, but it is clearly very specialized, and defined that the other's
5733# non-null values replace this one's if there is any overlap.
5734
5735sub trace { return main::trace(@_); }
5736
5737{ # Closure
5738
5739 main::setup_package();
5740
5741 my %default_map;
5742 # Many input files omit some entries; this gives what the mapping for the
5743 # missing entries should be
5744 main::set_access('default_map', \%default_map, 'r');
5745
5746 my %anomalous_entries;
5747 # Things that go in the body of the table which don't fit the normal
5748 # scheme of things, like having a range. Not much can be done with these
5749 # once there except to output them. This was created to handle named
5750 # sequences.
5751 main::set_access('anomalous_entry', \%anomalous_entries, 'a');
5752 main::set_access('anomalous_entries', # Append singular, read plural
5753 \%anomalous_entries,
5754 'readable_array');
5755
99870f4d 5756 my %to_output_map;
bbed833a 5757 # Enum as to whether or not to write out this map table, and how:
c12f2655 5758 # 0 don't output
8572ace0
KW
5759 # $EXTERNAL_MAP means its existence is noted in the documentation, and
5760 # it should not be removed nor its format changed. This
5761 # is done for those files that have traditionally been
5762 # output.
5763 # $INTERNAL_MAP means Perl reserves the right to do anything it wants
5764 # with this file
bbed833a
KW
5765 # $OUTPUT_DELTAS means that it is an $INTERNAL_MAP, and instead of
5766 # outputting the actual mappings, we output the delta:
5767 # (mapping - code point). Doing this creates much more
5768 # compact tables. The default is false unless the
5769 # table's default mapping is to $CODE_POINT, and the
5770 # range size is not 1.
99870f4d
KW
5771 main::set_access('to_output_map', \%to_output_map, 's');
5772
99870f4d
KW
5773 sub new {
5774 my $class = shift;
5775 my $name = shift;
5776
5777 my %args = @_;
5778
5779 # Optional initialization data for the table.
5780 my $initialize = delete $args{'Initialize'};
5781
99870f4d 5782 my $default_map = delete $args{'Default_Map'};
99870f4d 5783 my $property = delete $args{'_Property'};
23e33b60 5784 my $full_name = delete $args{'Full_Name'};
bbed833a 5785 my $to_output_map = delete $args{'To_Output_Map'};
20863809 5786
99870f4d
KW
5787 # Rest of parameters passed on
5788
5789 my $range_list = Range_Map->new(Owner => $property);
5790
5791 my $self = $class->SUPER::new(
5792 Name => $name,
23e33b60
KW
5793 Complete_Name => $full_name,
5794 Full_Name => $full_name,
99870f4d
KW
5795 _Property => $property,
5796 _Range_List => $range_list,
5797 %args);
5798
ffe43484 5799 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
5800
5801 $anomalous_entries{$addr} = [];
99870f4d 5802 $default_map{$addr} = $default_map;
bbed833a 5803 $to_output_map{$addr} = $to_output_map;
99870f4d
KW
5804
5805 $self->initialize($initialize) if defined $initialize;
5806
5807 return $self;
5808 }
5809
5810 use overload
5811 fallback => 0,
5812 qw("") => "_operator_stringify",
5813 ;
5814
5815 sub _operator_stringify {
5816 my $self = shift;
5817
5818 my $name = $self->property->full_name;
5819 $name = '""' if $name eq "";
5820 return "Map table for Property '$name'";
5821 }
5822
99870f4d
KW
5823 sub add_alias {
5824 # Add a synonym for this table (which means the property itself)
5825 my $self = shift;
5826 my $name = shift;
5827 # Rest of parameters passed on.
5828
5829 $self->SUPER::add_alias($name, $self->property, @_);
5830 return;
5831 }
5832
5833 sub add_map {
5834 # Add a range of code points to the list of specially-handled code
5835 # points. $MULTI_CP is assumed if the type of special is not passed
5836 # in.
5837
5838 my $self = shift;
5839 my $lower = shift;
5840 my $upper = shift;
5841 my $string = shift;
5842 my %args = @_;
5843
5844 my $type = delete $args{'Type'} || 0;
5845 # Rest of parameters passed on
5846
5847 # Can't change the table if locked.
5848 return if $self->carp_if_locked;
5849
ffe43484 5850 my $addr = do { no overloading; pack 'J', $self; };
99870f4d 5851
99870f4d
KW
5852 $self->_range_list->add_map($lower, $upper,
5853 $string,
5854 @_,
5855 Type => $type);
5856 return;
5857 }
5858
5859 sub append_to_body {
5860 # Adds to the written HERE document of the table's body any anomalous
5861 # entries in the table..
5862
5863 my $self = shift;
5864 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5865
ffe43484 5866 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
5867
5868 return "" unless @{$anomalous_entries{$addr}};
5869 return join("\n", @{$anomalous_entries{$addr}}) . "\n";
5870 }
5871
5872 sub map_add_or_replace_non_nulls {
5873 # This adds the mappings in the table $other to $self. Non-null
5874 # mappings from $other override those in $self. It essentially merges
5875 # the two tables, with the second having priority except for null
5876 # mappings.
5877
5878 my $self = shift;
5879 my $other = shift;
5880 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5881
5882 return if $self->carp_if_locked;
5883
5884 if (! $other->isa(__PACKAGE__)) {
5885 Carp::my_carp_bug("$other should be a "
5886 . __PACKAGE__
5887 . ". Not a '"
5888 . ref($other)
5889 . "'. Not added;");
5890 return;
5891 }
5892
ffe43484
NC
5893 my $addr = do { no overloading; pack 'J', $self; };
5894 my $other_addr = do { no overloading; pack 'J', $other; };
99870f4d
KW
5895
5896 local $to_trace = 0 if main::DEBUG;
5897
5898 my $self_range_list = $self->_range_list;
5899 my $other_range_list = $other->_range_list;
5900 foreach my $range ($other_range_list->ranges) {
5901 my $value = $range->value;
5902 next if $value eq "";
5903 $self_range_list->_add_delete('+',
5904 $range->start,
5905 $range->end,
5906 $value,
5907 Type => $range->type,
5908 Replace => $UNCONDITIONALLY);
5909 }
5910
99870f4d
KW
5911 return;
5912 }
5913
5914 sub set_default_map {
5915 # Define what code points that are missing from the input files should
5916 # map to
5917
5918 my $self = shift;
5919 my $map = shift;
5920 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5921
ffe43484 5922 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
5923
5924 # Convert the input to the standard equivalent, if any (won't have any
5925 # for $STRING properties)
5926 my $standard = $self->_find_table_from_alias->{$map};
5927 $map = $standard->name if defined $standard;
5928
5929 # Warn if there already is a non-equivalent default map for this
5930 # property. Note that a default map can be a ref, which means that
5931 # what it actually means is delayed until later in the program, and it
5932 # IS permissible to override it here without a message.
5933 my $default_map = $default_map{$addr};
5934 if (defined $default_map
5935 && ! ref($default_map)
5936 && $default_map ne $map
5937 && main::Standardize($map) ne $default_map)
5938 {
5939 my $property = $self->property;
5940 my $map_table = $property->table($map);
5941 my $default_table = $property->table($default_map);
5942 if (defined $map_table
5943 && defined $default_table
5944 && $map_table != $default_table)
5945 {
5946 Carp::my_carp("Changing the default mapping for "
5947 . $property
5948 . " from $default_map to $map'");
5949 }
5950 }
5951
5952 $default_map{$addr} = $map;
5953
5954 # Don't also create any missing table for this map at this point,
5955 # because if we did, it could get done before the main table add is
5956 # done for PropValueAliases.txt; instead the caller will have to make
5957 # sure it exists, if desired.
5958 return;
5959 }
5960
5961 sub to_output_map {
5962 # Returns boolean: should we write this map table?
5963
5964 my $self = shift;
5965 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
5966
ffe43484 5967 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
5968
5969 # If overridden, use that
5970 return $to_output_map{$addr} if defined $to_output_map{$addr};
5971
5972 my $full_name = $self->full_name;
fcf1973c
KW
5973 return $global_to_output_map{$full_name}
5974 if defined $global_to_output_map{$full_name};
99870f4d 5975
20863809 5976 # If table says to output, do so; if says to suppress it, do so.
301ba948
KW
5977 my $fate = $self->fate;
5978 return $INTERNAL_MAP if $fate == $INTERNAL_ONLY;
8572ace0 5979 return $EXTERNAL_MAP if grep { $_ eq $full_name } @output_mapped_properties;
395dfc19 5980 return 0 if $fate == $SUPPRESSED || $fate == $MAP_PROXIED;
99870f4d
KW
5981
5982 my $type = $self->property->type;
5983
5984 # Don't want to output binary map tables even for debugging.
5985 return 0 if $type == $BINARY;
5986
ed307795
KW
5987 # But do want to output string ones. All the ones that remain to
5988 # be dealt with (i.e. which haven't explicitly been set to external)
bf7fe2df
KW
5989 # are for internal Perl use only. The default for those that map to
5990 # $CODE_POINT and haven't been restricted to a single element range
5991 # is to use the delta form.
5992 if ($type == $STRING) {
5993 return $INTERNAL_MAP if $self->range_size_1
5994 || $default_map{$addr} ne $CODE_POINT;
5995 return $OUTPUT_DELTAS;
5996 }
99870f4d 5997
8572ace0
KW
5998 # Otherwise is an $ENUM, do output it, for Perl's purposes
5999 return $INTERNAL_MAP;
99870f4d
KW
6000 }
6001
6002 sub inverse_list {
6003 # Returns a Range_List that is gaps of the current table. That is,
6004 # the inversion
6005
6006 my $self = shift;
6007 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
6008
6009 my $current = Range_List->new(Initialize => $self->_range_list,
6010 Owner => $self->property);
6011 return ~ $current;
6012 }
6013
8572ace0
KW
6014 sub header {
6015 my $self = shift;
6016 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
6017
6018 my $return = $self->SUPER::header();
6019
bbed833a 6020 if ($self->to_output_map >= $INTERNAL_MAP) {
ae92a9ae
KW
6021 $return .= $INTERNAL_ONLY_HEADER;
6022 }
6023 else {
6024 my $property_name = $self->property->full_name;
6025 $return .= <<END;
6026
6027# !!!!!!! IT IS DEPRECATED TO USE THIS FILE !!!!!!!
6028
6029# This file is for internal use by core Perl only. It is retained for
6030# backwards compatibility with applications that may have come to rely on it,
6031# but its format and even its name or existence are subject to change without
6032# notice in a future Perl version. Don't use it directly. Instead, its
6033# contents are now retrievable through a stable API in the Unicode::UCD
6034# module: Unicode::UCD::prop_invmap('$property_name').
6035END
6036 }
8572ace0
KW
6037 return $return;
6038 }
6039
99870f4d
KW
6040 sub set_final_comment {
6041 # Just before output, create the comment that heads the file
6042 # containing this table.
6043
bd9ebcfd
KW
6044 return unless $debugging_build;
6045
99870f4d
KW
6046 my $self = shift;
6047 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
6048
6049 # No sense generating a comment if aren't going to write it out.
6050 return if ! $self->to_output_map;
6051
ffe43484 6052 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
6053
6054 my $property = $self->property;
6055
6056 # Get all the possible names for this property. Don't use any that
6057 # aren't ok for use in a file name, etc. This is perhaps causing that
6058 # flag to do double duty, and may have to be changed in the future to
6059 # have our own flag for just this purpose; but it works now to exclude
6060 # Perl generated synonyms from the lists for properties, where the
6061 # name is always the proper Unicode one.
0eac1e20 6062 my @property_aliases = grep { $_->ok_as_filename } $self->aliases;
99870f4d
KW
6063
6064 my $count = $self->count;
6065 my $default_map = $default_map{$addr};
6066
6067 # The ranges that map to the default aren't output, so subtract that
6068 # to get those actually output. A property with matching tables
6069 # already has the information calculated.
6070 if ($property->type != $STRING) {
6071 $count -= $property->table($default_map)->count;
6072 }
6073 elsif (defined $default_map) {
6074
6075 # But for $STRING properties, must calculate now. Subtract the
6076 # count from each range that maps to the default.
6077 foreach my $range ($self->_range_list->ranges) {
99870f4d
KW
6078 if ($range->value eq $default_map) {
6079 $count -= $range->end +1 - $range->start;
6080 }
6081 }
6082
6083 }
6084
6085 # Get a string version of $count with underscores in large numbers,
6086 # for clarity.
6087 my $string_count = main::clarify_number($count);
6088
6089 my $code_points = ($count == 1)
6090 ? 'single code point'
6091 : "$string_count code points";
6092
6093 my $mapping;
6094 my $these_mappings;
6095 my $are;
6096 if (@property_aliases <= 1) {
6097 $mapping = 'mapping';
6098 $these_mappings = 'this mapping';
6099 $are = 'is'
6100 }
6101 else {
6102 $mapping = 'synonymous mappings';
6103 $these_mappings = 'these mappings';
6104 $are = 'are'
6105 }
6106 my $cp;
6107 if ($count >= $MAX_UNICODE_CODEPOINTS) {
6108 $cp = "any code point in Unicode Version $string_version";
6109 }
6110 else {
6111 my $map_to;
6112 if ($default_map eq "") {
6113 $map_to = 'the null string';
6114 }
6115 elsif ($default_map eq $CODE_POINT) {
6116 $map_to = "itself";
6117 }
6118 else {
6119 $map_to = "'$default_map'";
6120 }
6121 if ($count == 1) {
6122 $cp = "the single code point";
6123 }
6124 else {
6125 $cp = "one of the $code_points";
6126 }
6127 $cp .= " in Unicode Version $string_version for which the mapping is not to $map_to";
6128 }
6129
6130 my $comment = "";
6131
6132 my $status = $self->status;
6133 if ($status) {
6134 my $warn = uc $status_past_participles{$status};
6135 $comment .= <<END;
6136
6137!!!!!!! $warn !!!!!!!!!!!!!!!!!!!
6138 All property or property=value combinations contained in this file are $warn.
6139 See $unicode_reference_url for what this means.
6140
6141END
6142 }
6143 $comment .= "This file returns the $mapping:\n";
6144
6145 for my $i (0 .. @property_aliases - 1) {
6146 $comment .= sprintf("%-8s%s\n",
6147 " ",
6148 $property_aliases[$i]->name . '(cp)'
6149 );
6150 }
83b7c87d
KW
6151 my $full_name = $self->property->full_name;
6152 $comment .= "\nwhere 'cp' is $cp. Note that $these_mappings $are accessible via the function prop_invmap('$full_name') in Unicode::UCD";
99870f4d
KW
6153
6154 # And append any commentary already set from the actual property.
6155 $comment .= "\n\n" . $self->comment if $self->comment;
6156 if ($self->description) {
6157 $comment .= "\n\n" . join " ", $self->description;
6158 }
6159 if ($self->note) {
6160 $comment .= "\n\n" . join " ", $self->note;
6161 }
6162 $comment .= "\n";
6163
6164 if (! $self->perl_extension) {
6165 $comment .= <<END;
6166
6167For information about what this property really means, see:
6168$unicode_reference_url
6169END
6170 }
6171
6172 if ($count) { # Format differs for empty table
6173 $comment.= "\nThe format of the ";
6174 if ($self->range_size_1) {
6175 $comment.= <<END;
6176main body of lines of this file is: CODE_POINT\\t\\tMAPPING where CODE_POINT
6177is in hex; MAPPING is what CODE_POINT maps to.
6178END
6179 }
6180 else {
6181
6182 # There are tables which end up only having one element per
6183 # range, but it is not worth keeping track of for making just
6184 # this comment a little better.
6185 $comment.= <<END;
6186non-comment portions of the main body of lines of this file is:
6187START\\tSTOP\\tMAPPING where START is the starting code point of the
6188range, in hex; STOP is the ending point, or if omitted, the range has just one
6189code point; MAPPING is what each code point between START and STOP maps to.
6190END
0c07e538 6191 if ($self->output_range_counts) {
99870f4d
KW
6192 $comment .= <<END;
6193Numbers in comments in [brackets] indicate how many code points are in the
6194range (omitted when the range is a single code point or if the mapping is to
6195the null string).
6196END
6197 }
6198 }
6199 }
6200 $self->set_comment(main::join_lines($comment));
6201 return;
6202 }
6203
6204 my %swash_keys; # Makes sure don't duplicate swash names.
6205
668b3bfc
KW
6206 # The remaining variables are temporaries used while writing each table,
6207 # to output special ranges.
668b3bfc
KW
6208 my @multi_code_point_maps; # Map is to more than one code point.
6209
668b3bfc
KW
6210 sub handle_special_range {
6211 # Called in the middle of write when it finds a range it doesn't know
6212 # how to handle.
6213
6214 my $self = shift;
6215 my $range = shift;
6216 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
6217
6218 my $addr = do { no overloading; pack 'J', $self; };
6219
6220 my $type = $range->type;
6221
6222 my $low = $range->start;
6223 my $high = $range->end;
6224 my $map = $range->value;
6225
6226 # No need to output the range if it maps to the default.
6227 return if $map eq $default_map{$addr};
6228
bb1dd3da
KW
6229 my $property = $self->property;
6230
668b3bfc
KW
6231 # Switch based on the map type...
6232 if ($type == $HANGUL_SYLLABLE) {
6233
6234 # These are entirely algorithmically determinable based on
6235 # some constants furnished by Unicode; for now, just set a
6236 # flag to indicate that have them. After everything is figured
bb1dd3da
KW
6237 # out, we will output the code that does the algorithm. (Don't
6238 # output them if not needed because we are suppressing this
6239 # property.)
6240 $has_hangul_syllables = 1 if $property->to_output_map;
668b3bfc
KW
6241 }
6242 elsif ($type == $CP_IN_NAME) {
6243
bb1dd3da 6244 # Code points whose name ends in their code point are also
668b3bfc
KW
6245 # algorithmically determinable, but need information about the map
6246 # to do so. Both the map and its inverse are stored in data
bb1dd3da
KW
6247 # structures output in the file. They are stored in the mean time
6248 # in global lists The lists will be written out later into Name.pm,
6249 # which is created only if needed. In order to prevent duplicates
6250 # in the list, only add to them for one property, should multiple
6251 # ones need them.
6252 if ($needing_code_points_ending_in_code_point == 0) {
6253 $needing_code_points_ending_in_code_point = $property;
6254 }
6255 if ($property == $needing_code_points_ending_in_code_point) {
6c1bafed
KW
6256 push @{$names_ending_in_code_point{$map}->{'low'}}, $low;
6257 push @{$names_ending_in_code_point{$map}->{'high'}}, $high;
6258
6259 my $squeezed = $map =~ s/[-\s]+//gr;
6260 push @{$loose_names_ending_in_code_point{$squeezed}->{'low'}},
6261 $low;
6262 push @{$loose_names_ending_in_code_point{$squeezed}->{'high'}},
6263 $high;
6264
6265 push @code_points_ending_in_code_point, { low => $low,
6266 high => $high,
6267 name => $map
6268 };
bb1dd3da 6269 }
668b3bfc
KW
6270 }
6271 elsif ($range->type == $MULTI_CP || $range->type == $NULL) {
6272
6273 # Multi-code point maps and null string maps have an entry
6274 # for each code point in the range. They use the same
6275 # output format.
6276 for my $code_point ($low .. $high) {
6277
c12f2655
KW
6278 # The pack() below can't cope with surrogates. XXX This may
6279 # no longer be true
668b3bfc 6280 if ($code_point >= 0xD800 && $code_point <= 0xDFFF) {
98dc9551 6281 Carp::my_carp("Surrogate code point '$code_point' in mapping to '$map' in $self. No map created");
668b3bfc
KW
6282 next;
6283 }
6284
6285 # Generate the hash entries for these in the form that
6286 # utf8.c understands.
6287 my $tostr = "";
6288 my $to_name = "";
6289 my $to_chr = "";
6290 foreach my $to (split " ", $map) {
6291 if ($to !~ /^$code_point_re$/) {
6292 Carp::my_carp("Illegal code point '$to' in mapping '$map' from $code_point in $self. No map created");
6293 next;
6294 }
6295 $tostr .= sprintf "\\x{%s}", $to;
6296 $to = CORE::hex $to;
558712cf 6297 if ($annotate) {
c4019d52
KW
6298 $to_name .= " + " if $to_name;
6299 $to_chr .= chr($to);
6300 main::populate_char_info($to)
6301 if ! defined $viacode[$to];
6302 $to_name .= $viacode[$to];
6303 }
668b3bfc
KW
6304 }
6305
6306 # I (khw) have never waded through this line to
6307 # understand it well enough to comment it.
6308 my $utf8 = sprintf(qq["%s" => "$tostr",],
6309 join("", map { sprintf "\\x%02X", $_ }
6310 unpack("U0C*", pack("U", $code_point))));
6311
6312 # Add a comment so that a human reader can more easily
6313 # see what's going on.
6314 push @multi_code_point_maps,
6315 sprintf("%-45s # U+%04X", $utf8, $code_point);
558712cf 6316 if (! $annotate) {
c4019d52
KW
6317 $multi_code_point_maps[-1] .= " => $map";
6318 }
6319 else {
6320 main::populate_char_info($code_point)
6321 if ! defined $viacode[$code_point];
6322 $multi_code_point_maps[-1] .= " '"
6323 . chr($code_point)
6324 . "' => '$to_chr'; $viacode[$code_point] => $to_name";
6325 }
668b3bfc
KW
6326 }
6327 }
6328 else {
6329 Carp::my_carp("Unrecognized map type '$range->type' in '$range' in $self. Not written");
6330 }
6331
6332 return;
6333 }
6334
99870f4d
KW
6335 sub pre_body {
6336 # Returns the string that should be output in the file before the main
668b3bfc
KW
6337 # body of this table. It isn't called until the main body is
6338 # calculated, saving a pass. The string includes some hash entries
6339 # identifying the format of the body, and what the single value should
6340 # be for all ranges missing from it. It also includes any code points
6341 # which have map_types that don't go in the main table.
99870f4d
KW
6342
6343 my $self = shift;
6344 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
6345
ffe43484 6346 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
6347
6348 my $name = $self->property->swash_name;
6349
19f751d2
KW
6350 # Currently there is nothing in the pre_body unless a swash is being
6351 # generated.
6352 return unless defined $name;
6353
99870f4d 6354 if (defined $swash_keys{$name}) {
1675ea0d 6355 Carp::my_carp(main::join_lines(<<END
99870f4d
KW
6356Already created a swash name '$name' for $swash_keys{$name}. This means that
6357the same name desired for $self shouldn't be used. Bad News. This must be
6358fixed before production use, but proceeding anyway
6359END
6360 ));
6361 }
6362 $swash_keys{$name} = "$self";
6363
99870f4d 6364 my $pre_body = "";
99870f4d 6365
668b3bfc
KW
6366 # Here we assume we were called after have gone through the whole
6367 # file. If we actually generated anything for each map type, add its
6368 # respective header and trailer
ec2f0128 6369 my $specials_name = "";
668b3bfc 6370 if (@multi_code_point_maps) {
ec2f0128 6371 $specials_name = "utf8::ToSpec$name";
668b3bfc 6372 $pre_body .= <<END;
99870f4d
KW
6373
6374# Some code points require special handling because their mappings are each to
6375# multiple code points. These do not appear in the main body, but are defined
6376# in the hash below.
6377
76591e2b
KW
6378# Each key is the string of N bytes that together make up the UTF-8 encoding
6379# for the code point. (i.e. the same as looking at the code point's UTF-8
6380# under "use bytes"). Each value is the UTF-8 of the translation, for speed.
ec2f0128 6381\%$specials_name = (
99870f4d 6382END
668b3bfc
KW
6383 $pre_body .= join("\n", @multi_code_point_maps) . "\n);\n";
6384 }
99870f4d 6385
668b3bfc
KW
6386 my $format = $self->format;
6387
bbed833a
KW
6388 my $return = "";
6389
6390 my $output_deltas = ($self->to_output_map == $OUTPUT_DELTAS);
6391 if ($output_deltas) {
6392 if ($specials_name) {
6393 $return .= <<END;
6394# The mappings in the non-hash portion of this file must be modified to get the
6395# correct values by adding the code point ordinal number to each.
6396END
6397 }
6398 else {
6399 $return .= <<END;
6400# The mappings must be modified to get the correct values by adding the code
6401# point ordinal number to each.
6402END
6403 }
6404 }
6405
6406 $return .= <<END;
6407
668b3bfc
KW
6408# The name this swash is to be known by, with the format of the mappings in
6409# the main body of the table, and what all code points missing from this file
6410# map to.
6411\$utf8::SwashInfo{'To$name'}{'format'} = '$format'; # $map_table_formats{$format}
6412END
ec2f0128 6413 if ($specials_name) {
d59563d0 6414 $return .= <<END;
ec2f0128
KW
6415\$utf8::SwashInfo{'To$name'}{'specials_name'} = '$specials_name'; # Name of hash of special mappings
6416END
6417 }
668b3bfc 6418 my $default_map = $default_map{$addr};
bbed833a
KW
6419
6420 # For $CODE_POINT default maps and using deltas, instead the default
6421 # becomes zero.
6422 $return .= "\$utf8::SwashInfo{'To$name'}{'missing'} = '"
6423 . (($output_deltas && $default_map eq $CODE_POINT)
6424 ? "0"
6425 : $default_map)
6426 . "';";
668b3bfc
KW
6427
6428 if ($default_map eq $CODE_POINT) {
6429 $return .= ' # code point maps to itself';
6430 }
6431 elsif ($default_map eq "") {
6432 $return .= ' # code point maps to the null string';
6433 }
6434 $return .= "\n";
6435
6436 $return .= $pre_body;
6437
6438 return $return;
6439 }
6440
6441 sub write {
6442 # Write the table to the file.
6443
6444 my $self = shift;
6445 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
6446
6447 my $addr = do { no overloading; pack 'J', $self; };
6448
6449 # Clear the temporaries
668b3bfc 6450 undef @multi_code_point_maps;
99870f4d
KW
6451
6452 # Calculate the format of the table if not already done.
f5817e0a 6453 my $format = $self->format;
668b3bfc
KW
6454 my $type = $self->property->type;
6455 my $default_map = $self->default_map;
99870f4d
KW
6456 if (! defined $format) {
6457 if ($type == $BINARY) {
6458
6459 # Don't bother checking the values, because we elsewhere
6460 # verify that a binary table has only 2 values.
6461 $format = $BINARY_FORMAT;
6462 }
6463 else {
6464 my @ranges = $self->_range_list->ranges;
6465
6466 # default an empty table based on its type and default map
6467 if (! @ranges) {
6468
6469 # But it turns out that the only one we can say is a
6470 # non-string (besides binary, handled above) is when the
6471 # table is a string and the default map is to a code point
6472 if ($type == $STRING && $default_map eq $CODE_POINT) {
6473 $format = $HEX_FORMAT;
6474 }
6475 else {
6476 $format = $STRING_FORMAT;
6477 }
6478 }
6479 else {
6480
6481 # Start with the most restrictive format, and as we find
6482 # something that doesn't fit with that, change to the next
6483 # most restrictive, and so on.
6484 $format = $DECIMAL_FORMAT;
6485 foreach my $range (@ranges) {
668b3bfc
KW
6486 next if $range->type != 0; # Non-normal ranges don't
6487 # affect the main body
99870f4d
KW
6488 my $map = $range->value;
6489 if ($map ne $default_map) {
6490 last if $format eq $STRING_FORMAT; # already at
6491 # least
6492 # restrictive
6493 $format = $INTEGER_FORMAT
6494 if $format eq $DECIMAL_FORMAT
6495 && $map !~ / ^ [0-9] $ /x;
6496 $format = $FLOAT_FORMAT
6497 if $format eq $INTEGER_FORMAT
6498 && $map !~ / ^ -? [0-9]+ $ /x;
6499 $format = $RATIONAL_FORMAT
6500 if $format eq $FLOAT_FORMAT
6501 && $map !~ / ^ -? [0-9]+ \. [0-9]* $ /x;
6502 $format = $HEX_FORMAT
b91749bc
KW
6503 if ($format eq $RATIONAL_FORMAT
6504 && $map !~
6505 m/ ^ -? [0-9]+ ( \/ [0-9]+ )? $ /x)
6506 # Assume a leading zero means hex,
6507 # even if all digits are 0-9
6508 || ($format eq $INTEGER_FORMAT
6509 && $map =~ /^0/);
99870f4d
KW
6510 $format = $STRING_FORMAT if $format eq $HEX_FORMAT
6511 && $map =~ /[^0-9A-F]/;
6512 }
6513 }
6514 }
6515 }
6516 } # end of calculating format
6517
668b3bfc 6518 if ($default_map eq $CODE_POINT
99870f4d 6519 && $format ne $HEX_FORMAT
668b3bfc
KW
6520 && ! defined $self->format) # manual settings are always
6521 # considered ok
99870f4d
KW
6522 {
6523 Carp::my_carp_bug("Expecting hex format for mapping table for $self, instead got '$format'")
6524 }
99870f4d 6525
bbed833a
KW
6526 # If the output is a delta instead of the actual value, the format of
6527 # the table that gets output is actually 'i' instead of whatever it is
6528 # stored internally as.
6529 my $output_deltas = ($self->to_output_map == $OUTPUT_DELTAS);
6530 if ($output_deltas) {
6531 $format = 'i';
6532 }
6533
668b3bfc 6534 $self->_set_format($format);
99870f4d
KW
6535
6536 return $self->SUPER::write(
bbed833a 6537 $output_deltas,
99870f4d
KW
6538 ($self->property == $block)
6539 ? 7 # block file needs more tab stops
6540 : 3,
668b3bfc 6541 $default_map); # don't write defaulteds
99870f4d
KW
6542 }
6543
6544 # Accessors for the underlying list that should fail if locked.
ea25a9b2 6545 for my $sub (qw(
99870f4d 6546 add_duplicate
ea25a9b2 6547 ))
99870f4d
KW
6548 {
6549 no strict "refs";
6550 *$sub = sub {
6551 use strict "refs";
6552 my $self = shift;
6553
6554 return if $self->carp_if_locked;
6555 return $self->_range_list->$sub(@_);
6556 }
6557 }
6558} # End closure for Map_Table
6559
6560package Match_Table;
6561use base '_Base_Table';
6562
6563# A Match table is one which is a list of all the code points that have
6564# the same property and property value, for use in \p{property=value}
6565# constructs in regular expressions. It adds very little data to the base
6566# structure, but many methods, as these lists can be combined in many ways to
6567# form new ones.
6568# There are only a few concepts added:
6569# 1) Equivalents and Relatedness.
6570# Two tables can match the identical code points, but have different names.
6571# This always happens when there is a perl single form extension
6572# \p{IsProperty} for the Unicode compound form \P{Property=True}. The two
6573# tables are set to be related, with the Perl extension being a child, and
6574# the Unicode property being the parent.
6575#
6576# It may be that two tables match the identical code points and we don't
6577# know if they are related or not. This happens most frequently when the
6578# Block and Script properties have the exact range. But note that a
6579# revision to Unicode could add new code points to the script, which would
6580# now have to be in a different block (as the block was filled, or there
6581# would have been 'Unknown' script code points in it and they wouldn't have
6582# been identical). So we can't rely on any two properties from Unicode
6583# always matching the same code points from release to release, and thus
6584# these tables are considered coincidentally equivalent--not related. When
6585# two tables are unrelated but equivalent, one is arbitrarily chosen as the
6586# 'leader', and the others are 'equivalents'. This concept is useful
6587# to minimize the number of tables written out. Only one file is used for
6588# any identical set of code points, with entries in Heavy.pl mapping all
6589# the involved tables to it.
6590#
6591# Related tables will always be identical; we set them up to be so. Thus
6592# if the Unicode one is deprecated, the Perl one will be too. Not so for
6593# unrelated tables. Relatedness makes generating the documentation easier.
6594#
c12f2655
KW
6595# 2) Complement.
6596# Like equivalents, two tables may be the inverses of each other, the
6597# intersection between them is null, and the union is every Unicode code
6598# point. The two tables that occupy a binary property are necessarily like
6599# this. By specifying one table as the complement of another, we can avoid
6600# storing it on disk (using the other table and performing a fast
6601# transform), and some memory and calculations.
6602#
6603# 3) Conflicting. It may be that there will eventually be name clashes, with
99870f4d
KW
6604# the same name meaning different things. For a while, there actually were
6605# conflicts, but they have so far been resolved by changing Perl's or
6606# Unicode's definitions to match the other, but when this code was written,
6607# it wasn't clear that that was what was going to happen. (Unicode changed
6608# because of protests during their beta period.) Name clashes are warned
6609# about during compilation, and the documentation. The generated tables
6610# are sane, free of name clashes, because the code suppresses the Perl
6611# version. But manual intervention to decide what the actual behavior
6612# should be may be required should this happen. The introductory comments
6613# have more to say about this.
6614
6615sub standardize { return main::standardize($_[0]); }
6616sub trace { return main::trace(@_); }
6617
6618
6619{ # Closure
6620
6621 main::setup_package();
6622
6623 my %leader;
6624 # The leader table of this one; initially $self.
6625 main::set_access('leader', \%leader, 'r');
6626
6627 my %equivalents;
6628 # An array of any tables that have this one as their leader
6629 main::set_access('equivalents', \%equivalents, 'readable_array');
6630
6631 my %parent;
6632 # The parent table to this one, initially $self. This allows us to
c12f2655
KW
6633 # distinguish between equivalent tables that are related (for which this
6634 # is set to), and those which may not be, but share the same output file
6635 # because they match the exact same set of code points in the current
6636 # Unicode release.
99870f4d
KW
6637 main::set_access('parent', \%parent, 'r');
6638
6639 my %children;
6640 # An array of any tables that have this one as their parent
6641 main::set_access('children', \%children, 'readable_array');
6642
6643 my %conflicting;
6644 # Array of any tables that would have the same name as this one with
6645 # a different meaning. This is used for the generated documentation.
6646 main::set_access('conflicting', \%conflicting, 'readable_array');
6647
6648 my %matches_all;
6649 # Set in the constructor for tables that are expected to match all code
6650 # points.
6651 main::set_access('matches_all', \%matches_all, 'r');
6652
a92d5c2e
KW
6653 my %complement;
6654 # Points to the complement that this table is expressed in terms of; 0 if
6655 # none.
8ae00c8a 6656 main::set_access('complement', \%complement, 'r');
a92d5c2e 6657
99870f4d
KW
6658 sub new {
6659 my $class = shift;
6660
6661 my %args = @_;
6662
6663 # The property for which this table is a listing of property values.
6664 my $property = delete $args{'_Property'};
6665
23e33b60
KW
6666 my $name = delete $args{'Name'};
6667 my $full_name = delete $args{'Full_Name'};
6668 $full_name = $name if ! defined $full_name;
6669
99870f4d
KW
6670 # Optional
6671 my $initialize = delete $args{'Initialize'};
6672 my $matches_all = delete $args{'Matches_All'} || 0;
f5817e0a 6673 my $format = delete $args{'Format'};
99870f4d
KW
6674 # Rest of parameters passed on.
6675
6676 my $range_list = Range_List->new(Initialize => $initialize,
6677 Owner => $property);
6678
23e33b60
KW
6679 my $complete = $full_name;
6680 $complete = '""' if $complete eq ""; # A null name shouldn't happen,
6681 # but this helps debug if it
6682 # does
6683 # The complete name for a match table includes it's property in a
6684 # compound form 'property=table', except if the property is the
6685 # pseudo-property, perl, in which case it is just the single form,
6686 # 'table' (If you change the '=' must also change the ':' in lots of
6687 # places in this program that assume an equal sign)
6688 $complete = $property->full_name . "=$complete" if $property != $perl;
678f13d5 6689
99870f4d 6690 my $self = $class->SUPER::new(%args,
23e33b60
KW
6691 Name => $name,
6692 Complete_Name => $complete,
6693 Full_Name => $full_name,
99870f4d
KW
6694 _Property => $property,
6695 _Range_List => $range_list,
f5817e0a 6696 Format => $EMPTY_FORMAT,
99870f4d 6697 );
ffe43484 6698 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
6699
6700 $conflicting{$addr} = [ ];
6701 $equivalents{$addr} = [ ];
6702 $children{$addr} = [ ];
6703 $matches_all{$addr} = $matches_all;
6704 $leader{$addr} = $self;
6705 $parent{$addr} = $self;
a92d5c2e 6706 $complement{$addr} = 0;
99870f4d 6707
f5817e0a
KW
6708 if (defined $format && $format ne $EMPTY_FORMAT) {
6709 Carp::my_carp_bug("'Format' must be '$EMPTY_FORMAT' in a match table instead of '$format'. Using '$EMPTY_FORMAT'");
6710 }
6711
99870f4d
KW
6712 return $self;
6713 }
6714
6715 # See this program's beginning comment block about overloading these.
6716 use overload
6717 fallback => 0,
6718 qw("") => "_operator_stringify",
6719 '=' => sub {
6720 my $self = shift;
6721
6722 return if $self->carp_if_locked;
6723 return $self;
6724 },
6725
6726 '+' => sub {
6727 my $self = shift;
6728 my $other = shift;
6729
6730 return $self->_range_list + $other;
6731 },
6732 '&' => sub {
6733 my $self = shift;
6734 my $other = shift;
6735
6736 return $self->_range_list & $other;
6737 },
6738 '+=' => sub {
6739 my $self = shift;
6740 my $other = shift;
6741
6742 return if $self->carp_if_locked;
6743
ffe43484 6744 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
6745
6746 if (ref $other) {
6747
6748 # Change the range list of this table to be the
6749 # union of the two.
6750 $self->_set_range_list($self->_range_list
6751 + $other);
6752 }
6753 else { # $other is just a simple value
6754 $self->add_range($other, $other);
6755 }
6756 return $self;
6757 },
6758 '-' => sub { my $self = shift;
6759 my $other = shift;
6760 my $reversed = shift;
6761
6762 if ($reversed) {
6763 Carp::my_carp_bug("Can't cope with a "
6764 . __PACKAGE__
6765 . " being the first parameter in a '-'. Subtraction ignored.");
6766 return;
6767 }
6768
6769 return $self->_range_list - $other;
6770 },
6771 '~' => sub { my $self = shift;
6772 return ~ $self->_range_list;
6773 },
6774 ;
6775
6776 sub _operator_stringify {
6777 my $self = shift;
6778
23e33b60 6779 my $name = $self->complete_name;
99870f4d
KW
6780 return "Table '$name'";
6781 }
6782
ec40ee88
KW
6783 sub _range_list {
6784 # Returns the range list associated with this table, which will be the
6785 # complement's if it has one.
6786
6787 my $self = shift;
6788 my $complement;
6789 if (($complement = $self->complement) != 0) {
6790 return ~ $complement->_range_list;
6791 }
6792 else {
6793 return $self->SUPER::_range_list;
6794 }
6795 }
6796
99870f4d
KW
6797 sub add_alias {
6798 # Add a synonym for this table. See the comments in the base class
6799
6800 my $self = shift;
6801 my $name = shift;
6802 # Rest of parameters passed on.
6803
6804 $self->SUPER::add_alias($name, $self, @_);
6805 return;
6806 }
6807
6808 sub add_conflicting {
6809 # Add the name of some other object to the list of ones that name
6810 # clash with this match table.
6811
6812 my $self = shift;
6813 my $conflicting_name = shift; # The name of the conflicting object
6814 my $p = shift || 'p'; # Optional, is this a \p{} or \P{} ?
6815 my $conflicting_object = shift; # Optional, the conflicting object
6816 # itself. This is used to
6817 # disambiguate the text if the input
6818 # name is identical to any of the
6819 # aliases $self is known by.
6820 # Sometimes the conflicting object is
6821 # merely hypothetical, so this has to
6822 # be an optional parameter.
6823 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
6824
ffe43484 6825 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
6826
6827 # Check if the conflicting name is exactly the same as any existing
6828 # alias in this table (as long as there is a real object there to
6829 # disambiguate with).
6830 if (defined $conflicting_object) {
6831 foreach my $alias ($self->aliases) {
6832 if ($alias->name eq $conflicting_name) {
6833
6834 # Here, there is an exact match. This results in
6835 # ambiguous comments, so disambiguate by changing the
6836 # conflicting name to its object's complete equivalent.
6837 $conflicting_name = $conflicting_object->complete_name;
6838 last;
6839 }
6840 }
6841 }
6842
6843 # Convert to the \p{...} final name
6844 $conflicting_name = "\\$p" . "{$conflicting_name}";
6845
6846 # Only add once
6847 return if grep { $conflicting_name eq $_ } @{$conflicting{$addr}};
6848
6849 push @{$conflicting{$addr}}, $conflicting_name;
6850
6851 return;
6852 }
6853
6505c6e2 6854 sub is_set_equivalent_to {
99870f4d
KW
6855 # Return boolean of whether or not the other object is a table of this
6856 # type and has been marked equivalent to this one.
6857
6858 my $self = shift;
6859 my $other = shift;
6860 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
6861
6862 return 0 if ! defined $other; # Can happen for incomplete early
6863 # releases
6864 unless ($other->isa(__PACKAGE__)) {
6865 my $ref_other = ref $other;
6866 my $ref_self = ref $self;
6505c6e2 6867 Carp::my_carp_bug("Argument to 'is_set_equivalent_to' must be another $ref_self, not a '$ref_other'. $other not set equivalent to $self.");
99870f4d
KW
6868 return 0;
6869 }
6870
6871 # Two tables are equivalent if they have the same leader.
f998e60c 6872 no overloading;
051df77b 6873 return $leader{pack 'J', $self} == $leader{pack 'J', $other};
99870f4d
KW
6874 return;
6875 }
6876
99870f4d
KW
6877 sub set_equivalent_to {
6878 # Set $self equivalent to the parameter table.
6879 # The required Related => 'x' parameter is a boolean indicating
6880 # whether these tables are related or not. If related, $other becomes
6881 # the 'parent' of $self; if unrelated it becomes the 'leader'
6882 #
6883 # Related tables share all characteristics except names; equivalents
6884 # not quite so many.
6885 # If they are related, one must be a perl extension. This is because
6886 # we can't guarantee that Unicode won't change one or the other in a
98dc9551 6887 # later release even if they are identical now.
99870f4d
KW
6888
6889 my $self = shift;
6890 my $other = shift;
6891
6892 my %args = @_;
6893 my $related = delete $args{'Related'};
6894
6895 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
6896
6897 return if ! defined $other; # Keep on going; happens in some early
6898 # Unicode releases.
6899
6900 if (! defined $related) {
6901 Carp::my_carp_bug("set_equivalent_to must have 'Related => [01] parameter. Assuming $self is not related to $other");
6902 $related = 0;
6903 }
6904
6905 # If already are equivalent, no need to re-do it; if subroutine
6906 # returns null, it found an error, also do nothing
6505c6e2 6907 my $are_equivalent = $self->is_set_equivalent_to($other);
99870f4d
KW
6908 return if ! defined $are_equivalent || $are_equivalent;
6909
ffe43484 6910 my $addr = do { no overloading; pack 'J', $self; };
f998e60c 6911 my $current_leader = ($related) ? $parent{$addr} : $leader{$addr};
99870f4d 6912
45e32b91
KW
6913 if ($related) {
6914 if ($current_leader->perl_extension) {
6915 if ($other->perl_extension) {
6916 Carp::my_carp_bug("Use add_alias() to set two Perl tables '$self' and '$other', equivalent.");
6917 return;
6918 }
7610e9e2
KW
6919 } elsif ($self->property != $other->property # Depending on
6920 # situation, might
6921 # be better to use
6922 # add_alias()
6923 # instead for same
6924 # property
6925 && ! $other->perl_extension)
6926 {
45e32b91
KW
6927 Carp::my_carp_bug("set_equivalent_to should have 'Related => 0 for equivalencing two Unicode properties. Assuming $self is not related to $other");
6928 $related = 0;
6929 }
6930 }
6931
6932 if (! $self->is_empty && ! $self->matches_identically_to($other)) {
6933 Carp::my_carp_bug("$self should be empty or match identically to $other. Not setting equivalent");
6934 return;
99870f4d
KW
6935 }
6936
ffe43484
NC
6937 my $leader = do { no overloading; pack 'J', $current_leader; };
6938 my $other_addr = do { no overloading; pack 'J', $other; };
99870f4d
KW
6939
6940 # Any tables that are equivalent to or children of this table must now
6941 # instead be equivalent to or (children) to the new leader (parent),
6942 # still equivalent. The equivalency includes their matches_all info,
301ba948 6943 # and for related tables, their fate and status.
99870f4d
KW
6944 # All related tables are of necessity equivalent, but the converse
6945 # isn't necessarily true
6946 my $status = $other->status;
6947 my $status_info = $other->status_info;
301ba948 6948 my $fate = $other->fate;
99870f4d 6949 my $matches_all = $matches_all{other_addr};
d867ccfb 6950 my $caseless_equivalent = $other->caseless_equivalent;
99870f4d
KW
6951 foreach my $table ($current_leader, @{$equivalents{$leader}}) {
6952 next if $table == $other;
6953 trace "setting $other to be the leader of $table, status=$status" if main::DEBUG && $to_trace;
6954
ffe43484 6955 my $table_addr = do { no overloading; pack 'J', $table; };
99870f4d
KW
6956 $leader{$table_addr} = $other;
6957 $matches_all{$table_addr} = $matches_all;
6958 $self->_set_range_list($other->_range_list);
6959 push @{$equivalents{$other_addr}}, $table;
6960 if ($related) {
6961 $parent{$table_addr} = $other;
6962 push @{$children{$other_addr}}, $table;
6963 $table->set_status($status, $status_info);
301ba948
KW
6964
6965 # This reason currently doesn't get exposed outside; otherwise
6966 # would have to look up the parent's reason and use it instead.
6967 $table->set_fate($fate, "Parent's fate");
6968
d867ccfb 6969 $self->set_caseless_equivalent($caseless_equivalent);
99870f4d
KW
6970 }
6971 }
6972
6973 # Now that we've declared these to be equivalent, any changes to one
6974 # of the tables would invalidate that equivalency.
6975 $self->lock;
6976 $other->lock;
6977 return;
6978 }
6979
8ae00c8a
KW
6980 sub set_complement {
6981 # Set $self to be the complement of the parameter table. $self is
6982 # locked, as what it contains should all come from the other table.
6983
6984 my $self = shift;
6985 my $other = shift;
6986
6987 my %args = @_;
6988 Carp::carp_extra_args(\%args) if main::DEBUG && %args;
6989
6990 if ($other->complement != 0) {
6991 Carp::my_carp_bug("Can't set $self to be the complement of $other, which itself is the complement of " . $other->complement);
6992 return;
6993 }
6994 my $addr = do { no overloading; pack 'J', $self; };
6995 $complement{$addr} = $other;
6996 $self->lock;
6997 return;
6998 }
6999
99870f4d
KW
7000 sub add_range { # Add a range to the list for this table.
7001 my $self = shift;
7002 # Rest of parameters passed on
7003
7004 return if $self->carp_if_locked;
7005 return $self->_range_list->add_range(@_);
7006 }
7007
88c22f80
KW
7008 sub header {
7009 my $self = shift;
7010 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7011
7012 # All match tables are to be used only by the Perl core.
126c3d4e 7013 return $self->SUPER::header() . $INTERNAL_ONLY_HEADER;
88c22f80
KW
7014 }
7015
99870f4d
KW
7016 sub pre_body { # Does nothing for match tables.
7017 return
7018 }
7019
7020 sub append_to_body { # Does nothing for match tables.
7021 return
7022 }
7023
301ba948
KW
7024 sub set_fate {
7025 my $self = shift;
7026 my $fate = shift;
7027 my $reason = shift;
7028 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7029
7030 $self->SUPER::set_fate($fate, $reason);
7031
7032 # All children share this fate
7033 foreach my $child ($self->children) {
7034 $child->set_fate($fate, $reason);
7035 }
7036 return;
7037 }
7038
99870f4d
KW
7039 sub write {
7040 my $self = shift;
7041 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7042
bbed833a 7043 return $self->SUPER::write(0, 2); # No deltas; 2 tab stops
99870f4d
KW
7044 }
7045
7046 sub set_final_comment {
7047 # This creates a comment for the file that is to hold the match table
7048 # $self. It is somewhat convoluted to make the English read nicely,
7049 # but, heh, it's just a comment.
7050 # This should be called only with the leader match table of all the
7051 # ones that share the same file. It lists all such tables, ordered so
7052 # that related ones are together.
7053
bd9ebcfd
KW
7054 return unless $debugging_build;
7055
99870f4d
KW
7056 my $leader = shift; # Should only be called on the leader table of
7057 # an equivalent group
7058 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7059
ffe43484 7060 my $addr = do { no overloading; pack 'J', $leader; };
99870f4d
KW
7061
7062 if ($leader{$addr} != $leader) {
7063 Carp::my_carp_bug(<<END
7064set_final_comment() must be called on a leader table, which $leader is not.
7065It is equivalent to $leader{$addr}. No comment created
7066END
7067 );
7068 return;
7069 }
7070
7071 # Get the number of code points matched by each of the tables in this
7072 # file, and add underscores for clarity.
7073 my $count = $leader->count;
7074 my $string_count = main::clarify_number($count);
7075
7076 my $loose_count = 0; # how many aliases loosely matched
7077 my $compound_name = ""; # ? Are any names compound?, and if so, an
7078 # example
7079 my $properties_with_compound_names = 0; # count of these
7080
7081
7082 my %flags; # The status flags used in the file
7083 my $total_entries = 0; # number of entries written in the comment
7084 my $matches_comment = ""; # The portion of the comment about the
7085 # \p{}'s
7086 my @global_comments; # List of all the tables' comments that are
7087 # there before this routine was called.
7088
7089 # Get list of all the parent tables that are equivalent to this one
7090 # (including itself).
7091 my @parents = grep { $parent{main::objaddr $_} == $_ }
7092 main::uniques($leader, @{$equivalents{$addr}});
7093 my $has_unrelated = (@parents >= 2); # boolean, ? are there unrelated
7094 # tables
7095
7096 for my $parent (@parents) {
7097
7098 my $property = $parent->property;
7099
7100 # Special case 'N' tables in properties with two match tables when
7101 # the other is a 'Y' one. These are likely to be binary tables,
7102 # but not necessarily. In either case, \P{} will match the
7103 # complement of \p{}, and so if something is a synonym of \p, the
7104 # complement of that something will be the synonym of \P. This
7105 # would be true of any property with just two match tables, not
7106 # just those whose values are Y and N; but that would require a
7107 # little extra work, and there are none such so far in Unicode.
7108 my $perl_p = 'p'; # which is it? \p{} or \P{}
7109 my @yes_perl_synonyms; # list of any synonyms for the 'Y' table
7110
7111 if (scalar $property->tables == 2
7112 && $parent == $property->table('N')
7113 && defined (my $yes = $property->table('Y')))
7114 {
ffe43484 7115 my $yes_addr = do { no overloading; pack 'J', $yes; };
99870f4d
KW
7116 @yes_perl_synonyms
7117 = grep { $_->property == $perl }
7118 main::uniques($yes,
7119 $parent{$yes_addr},
7120 $parent{$yes_addr}->children);
7121
7122 # But these synonyms are \P{} ,not \p{}
7123 $perl_p = 'P';
7124 }
7125
7126 my @description; # Will hold the table description
7127 my @note; # Will hold the table notes.
7128 my @conflicting; # Will hold the table conflicts.
7129
7130 # Look at the parent, any yes synonyms, and all the children
ffe43484 7131 my $parent_addr = do { no overloading; pack 'J', $parent; };
99870f4d
KW
7132 for my $table ($parent,
7133 @yes_perl_synonyms,
f998e60c 7134 @{$children{$parent_addr}})
99870f4d 7135 {
ffe43484 7136 my $table_addr = do { no overloading; pack 'J', $table; };
99870f4d
KW
7137 my $table_property = $table->property;
7138
7139 # Tables are separated by a blank line to create a grouping.
7140 $matches_comment .= "\n" if $matches_comment;
7141
7142 # The table is named based on the property and value
7143 # combination it is for, like script=greek. But there may be
7144 # a number of synonyms for each side, like 'sc' for 'script',
7145 # and 'grek' for 'greek'. Any combination of these is a valid
7146 # name for this table. In this case, there are three more,
7147 # 'sc=grek', 'sc=greek', and 'script='grek'. Rather than
7148 # listing all possible combinations in the comment, we make
7149 # sure that each synonym occurs at least once, and add
7150 # commentary that the other combinations are possible.
da912e1e
KW
7151 # Because regular expressions don't recognize things like
7152 # \p{jsn=}, only look at non-null right-hand-sides
99870f4d 7153 my @property_aliases = $table_property->aliases;
da912e1e 7154 my @table_aliases = grep { $_->name ne "" } $table->aliases;
99870f4d
KW
7155
7156 # The alias lists above are already ordered in the order we
7157 # want to output them. To ensure that each synonym is listed,
da912e1e
KW
7158 # we must use the max of the two numbers. But if there are no
7159 # legal synonyms (nothing in @table_aliases), then we don't
7160 # list anything.
7161 my $listed_combos = (@table_aliases)
7162 ? main::max(scalar @table_aliases,
7163 scalar @property_aliases)
7164 : 0;
99870f4d
KW
7165 trace "$listed_combos, tables=", scalar @table_aliases, "; names=", scalar @property_aliases if main::DEBUG;
7166
da912e1e 7167
99870f4d
KW
7168 my $property_had_compound_name = 0;
7169
7170 for my $i (0 .. $listed_combos - 1) {
7171 $total_entries++;
7172
7173 # The current alias for the property is the next one on
7174 # the list, or if beyond the end, start over. Similarly
7175 # for the table (\p{prop=table})
7176 my $property_alias = $property_aliases
7177 [$i % @property_aliases]->name;
7178 my $table_alias_object = $table_aliases
7179 [$i % @table_aliases];
7180 my $table_alias = $table_alias_object->name;
7181 my $loose_match = $table_alias_object->loose_match;
7182
7183 if ($table_alias !~ /\D/) { # Clarify large numbers.
7184 $table_alias = main::clarify_number($table_alias)
7185 }
7186
7187 # Add a comment for this alias combination
7188 my $current_match_comment;
7189 if ($table_property == $perl) {
7190 $current_match_comment = "\\$perl_p"
7191 . "{$table_alias}";
7192 }
7193 else {
7194 $current_match_comment
7195 = "\\p{$property_alias=$table_alias}";
7196 $property_had_compound_name = 1;
7197 }
7198
7199 # Flag any abnormal status for this table.
7200 my $flag = $property->status
7201 || $table->status
7202 || $table_alias_object->status;
301ba948 7203 $flags{$flag} = $status_past_participles{$flag} if $flag;
99870f4d
KW
7204
7205 $loose_count++;
7206
7207 # Pretty up the comment. Note the \b; it says don't make
7208 # this line a continuation.
7209 $matches_comment .= sprintf("\b%-1s%-s%s\n",
7210 $flag,
7211 " " x 7,
7212 $current_match_comment);
7213 } # End of generating the entries for this table.
7214
7215 # Save these for output after this group of related tables.
7216 push @description, $table->description;
7217 push @note, $table->note;
7218 push @conflicting, $table->conflicting;
7219
37e2e78e
KW
7220 # And this for output after all the tables.
7221 push @global_comments, $table->comment;
7222
99870f4d
KW
7223 # Compute an alternate compound name using the final property
7224 # synonym and the first table synonym with a colon instead of
7225 # the equal sign used elsewhere.
7226 if ($property_had_compound_name) {
7227 $properties_with_compound_names ++;
7228 if (! $compound_name || @property_aliases > 1) {
7229 $compound_name = $property_aliases[-1]->name
7230 . ': '
7231 . $table_aliases[0]->name;
7232 }
7233 }
7234 } # End of looping through all children of this table
7235
7236 # Here have assembled in $matches_comment all the related tables
7237 # to the current parent (preceded by the same info for all the
7238 # previous parents). Put out information that applies to all of
7239 # the current family.
7240 if (@conflicting) {
7241
7242 # But output the conflicting information now, as it applies to
7243 # just this table.
7244 my $conflicting = join ", ", @conflicting;
7245 if ($conflicting) {
7246 $matches_comment .= <<END;
7247
7248 Note that contrary to what you might expect, the above is NOT the same as
7249END
7250 $matches_comment .= "any of: " if @conflicting > 1;
7251 $matches_comment .= "$conflicting\n";
7252 }
7253 }
7254 if (@description) {
7255 $matches_comment .= "\n Meaning: "
7256 . join('; ', @description)
7257 . "\n";
7258 }
7259 if (@note) {
7260 $matches_comment .= "\n Note: "
7261 . join("\n ", @note)
7262 . "\n";
7263 }
7264 } # End of looping through all tables
7265
7266
7267 my $code_points;
7268 my $match;
7269 my $any_of_these;
7270 if ($count == 1) {
7271 $match = 'matches';
7272 $code_points = 'single code point';
7273 }
7274 else {
7275 $match = 'match';
7276 $code_points = "$string_count code points";
7277 }
7278
7279 my $synonyms;
7280 my $entries;
da912e1e 7281 if ($total_entries == 1) {
99870f4d
KW
7282 $synonyms = "";
7283 $entries = 'entry';
7284 $any_of_these = 'this'
7285 }
7286 else {
7287 $synonyms = " any of the following regular expression constructs";
7288 $entries = 'entries';
7289 $any_of_these = 'any of these'
7290 }
7291
6efd5c72 7292 my $comment = "Use Unicode::UCD::prop_invlist() to access the contents of this file.\n\n";
99870f4d
KW
7293 if ($has_unrelated) {
7294 $comment .= <<END;
7295This file is for tables that are not necessarily related: To conserve
7296resources, every table that matches the identical set of code points in this
7297version of Unicode uses this file. Each one is listed in a separate group
7298below. It could be that the tables will match the same set of code points in
7299other Unicode releases, or it could be purely coincidence that they happen to
7300be the same in Unicode $string_version, and hence may not in other versions.
7301
7302END
7303 }
7304
7305 if (%flags) {
7306 foreach my $flag (sort keys %flags) {
7307 $comment .= <<END;
37e2e78e 7308'$flag' below means that this form is $flags{$flag}.
301ba948 7309Consult $pod_file.pod
99870f4d
KW
7310END
7311 }
7312 $comment .= "\n";
7313 }
7314
da912e1e
KW
7315 if ($total_entries == 0) {
7316 Carp::my_carp("No regular expression construct can match $leader, as all names for it are the null string. Creating file anyway.");
7317 $comment .= <<END;
7318This file returns the $code_points in Unicode Version $string_version for
7319$leader, but it is inaccessible through Perl regular expressions, as
7320"\\p{prop=}" is not recognized.
7321END
7322
7323 } else {
7324 $comment .= <<END;
99870f4d
KW
7325This file returns the $code_points in Unicode Version $string_version that
7326$match$synonyms:
7327
7328$matches_comment
37e2e78e 7329$pod_file.pod should be consulted for the syntax rules for $any_of_these,
99870f4d
KW
7330including if adding or subtracting white space, underscore, and hyphen
7331characters matters or doesn't matter, and other permissible syntactic
7332variants. Upper/lower case distinctions never matter.
7333END
7334
da912e1e 7335 }
99870f4d
KW
7336 if ($compound_name) {
7337 $comment .= <<END;
7338
7339A colon can be substituted for the equals sign, and
7340END
7341 if ($properties_with_compound_names > 1) {
7342 $comment .= <<END;
7343within each group above,
7344END
7345 }
7346 $compound_name = sprintf("%-8s\\p{%s}", " ", $compound_name);
7347
7348 # Note the \b below, it says don't make that line a continuation.
7349 $comment .= <<END;
7350anything to the left of the equals (or colon) can be combined with anything to
7351the right. Thus, for example,
7352$compound_name
7353\bis also valid.
7354END
7355 }
7356
7357 # And append any comment(s) from the actual tables. They are all
7358 # gathered here, so may not read all that well.
37e2e78e
KW
7359 if (@global_comments) {
7360 $comment .= "\n" . join("\n\n", @global_comments) . "\n";
7361 }
99870f4d
KW
7362
7363 if ($count) { # The format differs if no code points, and needs no
7364 # explanation in that case
7365 $comment.= <<END;
7366
7367The format of the lines of this file is:
7368END
7369 $comment.= <<END;
7370START\\tSTOP\\twhere START is the starting code point of the range, in hex;
7371STOP is the ending point, or if omitted, the range has just one code point.
7372END
0c07e538 7373 if ($leader->output_range_counts) {
99870f4d
KW
7374 $comment .= <<END;
7375Numbers in comments in [brackets] indicate how many code points are in the
7376range.
7377END
7378 }
7379 }
7380
7381 $leader->set_comment(main::join_lines($comment));
7382 return;
7383 }
7384
7385 # Accessors for the underlying list
ea25a9b2 7386 for my $sub (qw(
99870f4d
KW
7387 get_valid_code_point
7388 get_invalid_code_point
ea25a9b2 7389 ))
99870f4d
KW
7390 {
7391 no strict "refs";
7392 *$sub = sub {
7393 use strict "refs";
7394 my $self = shift;
7395
7396 return $self->_range_list->$sub(@_);
7397 }
7398 }
7399} # End closure for Match_Table
7400
7401package Property;
7402
7403# The Property class represents a Unicode property, or the $perl
7404# pseudo-property. It contains a map table initialized empty at construction
7405# time, and for properties accessible through regular expressions, various
7406# match tables, created through the add_match_table() method, and referenced
7407# by the table('NAME') or tables() methods, the latter returning a list of all
7408# of the match tables. Otherwise table operations implicitly are for the map
7409# table.
7410#
7411# Most of the data in the property is actually about its map table, so it
7412# mostly just uses that table's accessors for most methods. The two could
7413# have been combined into one object, but for clarity because of their
7414# differing semantics, they have been kept separate. It could be argued that
7415# the 'file' and 'directory' fields should be kept with the map table.
7416#
7417# Each property has a type. This can be set in the constructor, or in the
7418# set_type accessor, but mostly it is figured out by the data. Every property
7419# starts with unknown type, overridden by a parameter to the constructor, or
7420# as match tables are added, or ranges added to the map table, the data is
7421# inspected, and the type changed. After the table is mostly or entirely
7422# filled, compute_type() should be called to finalize they analysis.
7423#
7424# There are very few operations defined. One can safely remove a range from
7425# the map table, and property_add_or_replace_non_nulls() adds the maps from another
7426# table to this one, replacing any in the intersection of the two.
7427
7428sub standardize { return main::standardize($_[0]); }
7429sub trace { return main::trace(@_) if main::DEBUG && $to_trace }
7430
7431{ # Closure
7432
7433 # This hash will contain as keys, all the aliases of all properties, and
7434 # as values, pointers to their respective property objects. This allows
7435 # quick look-up of a property from any of its names.
7436 my %alias_to_property_of;
7437
7438 sub dump_alias_to_property_of {
7439 # For debugging
7440
7441 print "\n", main::simple_dumper (\%alias_to_property_of), "\n";
7442 return;
7443 }
7444
7445 sub property_ref {
7446 # This is a package subroutine, not called as a method.
7447 # If the single parameter is a literal '*' it returns a list of all
7448 # defined properties.
7449 # Otherwise, the single parameter is a name, and it returns a pointer
7450 # to the corresponding property object, or undef if none.
7451 #
7452 # Properties can have several different names. The 'standard' form of
7453 # each of them is stored in %alias_to_property_of as they are defined.
7454 # But it's possible that this subroutine will be called with some
7455 # variant, so if the initial lookup fails, it is repeated with the
98dc9551 7456 # standardized form of the input name. If found, besides returning the
99870f4d
KW
7457 # result, the input name is added to the list so future calls won't
7458 # have to do the conversion again.
7459
7460 my $name = shift;
7461
7462 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7463
7464 if (! defined $name) {
7465 Carp::my_carp_bug("Undefined input property. No action taken.");
7466 return;
7467 }
7468
7469 return main::uniques(values %alias_to_property_of) if $name eq '*';
7470
7471 # Return cached result if have it.
7472 my $result = $alias_to_property_of{$name};
7473 return $result if defined $result;
7474
7475 # Convert the input to standard form.
7476 my $standard_name = standardize($name);
7477
7478 $result = $alias_to_property_of{$standard_name};
7479 return unless defined $result; # Don't cache undefs
7480
7481 # Cache the result before returning it.
7482 $alias_to_property_of{$name} = $result;
7483 return $result;
7484 }
7485
7486
7487 main::setup_package();
7488
7489 my %map;
7490 # A pointer to the map table object for this property
7491 main::set_access('map', \%map);
7492
7493 my %full_name;
7494 # The property's full name. This is a duplicate of the copy kept in the
7495 # map table, but is needed because stringify needs it during
7496 # construction of the map table, and then would have a chicken before egg
7497 # problem.
7498 main::set_access('full_name', \%full_name, 'r');
7499
7500 my %table_ref;
7501 # This hash will contain as keys, all the aliases of any match tables
7502 # attached to this property, and as values, the pointers to their
7503 # respective tables. This allows quick look-up of a table from any of its
7504 # names.
7505 main::set_access('table_ref', \%table_ref);
7506
7507 my %type;
7508 # The type of the property, $ENUM, $BINARY, etc
7509 main::set_access('type', \%type, 'r');
7510
7511 my %file;
7512 # The filename where the map table will go (if actually written).
7513 # Normally defaulted, but can be overridden.
7514 main::set_access('file', \%file, 'r', 's');
7515
7516 my %directory;
7517 # The directory where the map table will go (if actually written).
7518 # Normally defaulted, but can be overridden.
7519 main::set_access('directory', \%directory, 's');
7520
7521 my %pseudo_map_type;
7522 # This is used to affect the calculation of the map types for all the
7523 # ranges in the table. It should be set to one of the values that signify
7524 # to alter the calculation.
7525 main::set_access('pseudo_map_type', \%pseudo_map_type, 'r');
7526
7527 my %has_only_code_point_maps;
7528 # A boolean used to help in computing the type of data in the map table.
7529 main::set_access('has_only_code_point_maps', \%has_only_code_point_maps);
7530
7531 my %unique_maps;
7532 # A list of the first few distinct mappings this property has. This is
7533 # used to disambiguate between binary and enum property types, so don't
7534 # have to keep more than three.
7535 main::set_access('unique_maps', \%unique_maps);
7536
56557540
KW
7537 my %pre_declared_maps;
7538 # A boolean that gives whether the input data should declare all the
7539 # tables used, or not. If the former, unknown ones raise a warning.
7540 main::set_access('pre_declared_maps',
047274f2 7541 \%pre_declared_maps, 'r', 's');
56557540 7542
99870f4d
KW
7543 sub new {
7544 # The only required parameter is the positionally first, name. All
7545 # other parameters are key => value pairs. See the documentation just
7546 # above for the meanings of the ones not passed directly on to the map
7547 # table constructor.
7548
7549 my $class = shift;
7550 my $name = shift || "";
7551
7552 my $self = property_ref($name);
7553 if (defined $self) {
7554 my $options_string = join ", ", @_;
7555 $options_string = ". Ignoring options $options_string" if $options_string;
7556 Carp::my_carp("$self is already in use. Using existing one$options_string;");
7557 return $self;
7558 }
7559
7560 my %args = @_;
7561
7562 $self = bless \do { my $anonymous_scalar }, $class;
ffe43484 7563 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
7564
7565 $directory{$addr} = delete $args{'Directory'};
7566 $file{$addr} = delete $args{'File'};
7567 $full_name{$addr} = delete $args{'Full_Name'} || $name;
7568 $type{$addr} = delete $args{'Type'} || $UNKNOWN;
7569 $pseudo_map_type{$addr} = delete $args{'Map_Type'};
56557540
KW
7570 $pre_declared_maps{$addr} = delete $args{'Pre_Declared_Maps'}
7571 # Starting in this release, property
7572 # values should be defined for all
7573 # properties, except those overriding this
7574 // $v_version ge v5.1.0;
c12f2655 7575
99870f4d
KW
7576 # Rest of parameters passed on.
7577
7578 $has_only_code_point_maps{$addr} = 1;
7579 $table_ref{$addr} = { };
7580 $unique_maps{$addr} = { };
7581
7582 $map{$addr} = Map_Table->new($name,
7583 Full_Name => $full_name{$addr},
7584 _Alias_Hash => \%alias_to_property_of,
7585 _Property => $self,
7586 %args);
7587 return $self;
7588 }
7589
7590 # See this program's beginning comment block about overloading the copy
7591 # constructor. Few operations are defined on properties, but a couple are
7592 # useful. It is safe to take the inverse of a property, and to remove a
7593 # single code point from it.
7594 use overload
7595 fallback => 0,
7596 qw("") => "_operator_stringify",
7597 "." => \&main::_operator_dot,
7598 '==' => \&main::_operator_equal,
7599 '!=' => \&main::_operator_not_equal,
7600 '=' => sub { return shift },
7601 '-=' => "_minus_and_equal",
7602 ;
7603
7604 sub _operator_stringify {
7605 return "Property '" . shift->full_name . "'";
7606 }
7607
7608 sub _minus_and_equal {
7609 # Remove a single code point from the map table of a property.
7610
7611 my $self = shift;
7612 my $other = shift;
7613 my $reversed = shift;
7614 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7615
7616 if (ref $other) {
7617 Carp::my_carp_bug("Can't cope with a "
7618 . ref($other)
7619 . " argument to '-='. Subtraction ignored.");
7620 return $self;
7621 }
98dc9551 7622 elsif ($reversed) { # Shouldn't happen in a -=, but just in case
99870f4d
KW
7623 Carp::my_carp_bug("Can't cope with a "
7624 . __PACKAGE__
7625 . " being the first parameter in a '-='. Subtraction ignored.");
7626 return $self;
7627 }
7628 else {
f998e60c 7629 no overloading;
051df77b 7630 $map{pack 'J', $self}->delete_range($other, $other);
99870f4d
KW
7631 }
7632 return $self;
7633 }
7634
7635 sub add_match_table {
7636 # Add a new match table for this property, with name given by the
7637 # parameter. It returns a pointer to the table.
7638
7639 my $self = shift;
7640 my $name = shift;
7641 my %args = @_;
7642
ffe43484 7643 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
7644
7645 my $table = $table_ref{$addr}{$name};
7646 my $standard_name = main::standardize($name);
7647 if (defined $table
7648 || (defined ($table = $table_ref{$addr}{$standard_name})))
7649 {
7650 Carp::my_carp("Table '$name' in $self is already in use. Using existing one");
7651 $table_ref{$addr}{$name} = $table;
7652 return $table;
7653 }
7654 else {
7655
7656 # See if this is a perl extension, if not passed in.
7657 my $perl_extension = delete $args{'Perl_Extension'};
7658 $perl_extension
7659 = $self->perl_extension if ! defined $perl_extension;
7660
7661 $table = Match_Table->new(
7662 Name => $name,
7663 Perl_Extension => $perl_extension,
7664 _Alias_Hash => $table_ref{$addr},
7665 _Property => $self,
7666
301ba948
KW
7667 # gets property's fate and status by default
7668 Fate => $self->fate,
99870f4d
KW
7669 Status => $self->status,
7670 _Status_Info => $self->status_info,
88c22f80 7671 %args);
99870f4d
KW
7672 return unless defined $table;
7673 }
7674
7675 # Save the names for quick look up
7676 $table_ref{$addr}{$standard_name} = $table;
7677 $table_ref{$addr}{$name} = $table;
7678
7679 # Perhaps we can figure out the type of this property based on the
7680 # fact of adding this match table. First, string properties don't
7681 # have match tables; second, a binary property can't have 3 match
7682 # tables
7683 if ($type{$addr} == $UNKNOWN) {
7684 $type{$addr} = $NON_STRING;
7685 }
7686 elsif ($type{$addr} == $STRING) {
7687 Carp::my_carp("$self Added a match table '$name' to a string property '$self'. Changed it to a non-string property. Bad News.");
7688 $type{$addr} = $NON_STRING;
7689 }
06f26c45 7690 elsif ($type{$addr} != $ENUM && $type{$addr} != $FORCED_BINARY) {
99870f4d
KW
7691 if (scalar main::uniques(values %{$table_ref{$addr}}) > 2
7692 && $type{$addr} == $BINARY)
7693 {
7694 Carp::my_carp("$self now has more than 2 tables (with the addition of '$name'), and so is no longer binary. Changing its type to 'enum'. Bad News.");
7695 $type{$addr} = $ENUM;
7696 }
7697 }
7698
7699 return $table;
7700 }
7701
4b9b0bc5
KW
7702 sub delete_match_table {
7703 # Delete the table referred to by $2 from the property $1.
7704
7705 my $self = shift;
7706 my $table_to_remove = shift;
7707 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7708
7709 my $addr = do { no overloading; pack 'J', $self; };
7710
7711 # Remove all names that refer to it.
7712 foreach my $key (keys %{$table_ref{$addr}}) {
7713 delete $table_ref{$addr}{$key}
7714 if $table_ref{$addr}{$key} == $table_to_remove;
7715 }
7716
7717 $table_to_remove->DESTROY;
7718 return;
7719 }
7720
99870f4d
KW
7721 sub table {
7722 # Return a pointer to the match table (with name given by the
7723 # parameter) associated with this property; undef if none.
7724
7725 my $self = shift;
7726 my $name = shift;
7727 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7728
ffe43484 7729 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
7730
7731 return $table_ref{$addr}{$name} if defined $table_ref{$addr}{$name};
7732
7733 # If quick look-up failed, try again using the standard form of the
7734 # input name. If that succeeds, cache the result before returning so
7735 # won't have to standardize this input name again.
7736 my $standard_name = main::standardize($name);
7737 return unless defined $table_ref{$addr}{$standard_name};
7738
7739 $table_ref{$addr}{$name} = $table_ref{$addr}{$standard_name};
7740 return $table_ref{$addr}{$name};
7741 }
7742
7743 sub tables {
7744 # Return a list of pointers to all the match tables attached to this
7745 # property
7746
f998e60c 7747 no overloading;
051df77b 7748 return main::uniques(values %{$table_ref{pack 'J', shift}});
99870f4d
KW
7749 }
7750
7751 sub directory {
7752 # Returns the directory the map table for this property should be
7753 # output in. If a specific directory has been specified, that has
7754 # priority; 'undef' is returned if the type isn't defined;
7755 # or $map_directory for everything else.
7756
ffe43484 7757 my $addr = do { no overloading; pack 'J', shift; };
99870f4d
KW
7758
7759 return $directory{$addr} if defined $directory{$addr};
7760 return undef if $type{$addr} == $UNKNOWN;
7761 return $map_directory;
7762 }
7763
7764 sub swash_name {
7765 # Return the name that is used to both:
7766 # 1) Name the file that the map table is written to.
7767 # 2) The name of swash related stuff inside that file.
7768 # The reason for this is that the Perl core historically has used
7769 # certain names that aren't the same as the Unicode property names.
7770 # To continue using these, $file is hard-coded in this file for those,
7771 # but otherwise the standard name is used. This is different from the
7772 # external_name, so that the rest of the files, like in lib can use
7773 # the standard name always, without regard to historical precedent.
7774
7775 my $self = shift;
7776 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7777
ffe43484 7778 my $addr = do { no overloading; pack 'J', $self; };
99870f4d 7779
19f751d2
KW
7780 # Swash names are used only on regular map tables; otherwise there
7781 # should be no access to the property map table from other parts of
7782 # Perl.
7783 return if $map{$addr}->fate != $ORDINARY;
7784
99870f4d
KW
7785 return $file{$addr} if defined $file{$addr};
7786 return $map{$addr}->external_name;
7787 }
7788
7789 sub to_create_match_tables {
7790 # Returns a boolean as to whether or not match tables should be
7791 # created for this property.
7792
7793 my $self = shift;
7794 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7795
7796 # The whole point of this pseudo property is match tables.
7797 return 1 if $self == $perl;
7798
ffe43484 7799 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
7800
7801 # Don't generate tables of code points that match the property values
7802 # of a string property. Such a list would most likely have many
7803 # property values, each with just one or very few code points mapping
7804 # to it.
7805 return 0 if $type{$addr} == $STRING;
7806
7807 # Don't generate anything for unimplemented properties.
7808 return 0 if grep { $self->complete_name eq $_ }
7809 @unimplemented_properties;
7810 # Otherwise, do.
7811 return 1;
7812 }
7813
7814 sub property_add_or_replace_non_nulls {
7815 # This adds the mappings in the property $other to $self. Non-null
7816 # mappings from $other override those in $self. It essentially merges
7817 # the two properties, with the second having priority except for null
7818 # mappings.
7819
7820 my $self = shift;
7821 my $other = shift;
7822 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7823
7824 if (! $other->isa(__PACKAGE__)) {
7825 Carp::my_carp_bug("$other should be a "
7826 . __PACKAGE__
7827 . ". Not a '"
7828 . ref($other)
7829 . "'. Not added;");
7830 return;
7831 }
7832
f998e60c 7833 no overloading;
051df77b 7834 return $map{pack 'J', $self}->map_add_or_replace_non_nulls($map{pack 'J', $other});
99870f4d
KW
7835 }
7836
5be997b0
KW
7837 sub set_proxy_for {
7838 # Certain tables are not generally written out to files, but
7839 # Unicode::UCD has the intelligence to know that the file for $self
7840 # can be used to reconstruct those tables. This routine just changes
7841 # things so that UCD pod entries for those suppressed tables are
7842 # generated, so the fact that a proxy is used is invisible to the
7843 # user.
7844
7845 my $self = shift;
7846
7847 foreach my $property_name (@_) {
7848 my $ref = property_ref($property_name);
7849 next if $ref->to_output_map;
7850 $ref->set_fate($MAP_PROXIED);
7851 }
7852 }
7853
99870f4d
KW
7854 sub set_type {
7855 # Set the type of the property. Mostly this is figured out by the
7856 # data in the table. But this is used to set it explicitly. The
7857 # reason it is not a standard accessor is that when setting a binary
7858 # property, we need to make sure that all the true/false aliases are
7859 # present, as they were omitted in early Unicode releases.
7860
7861 my $self = shift;
7862 my $type = shift;
7863 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7864
06f26c45
KW
7865 if ($type != $ENUM
7866 && $type != $BINARY
7867 && $type != $FORCED_BINARY
7868 && $type != $STRING)
7869 {
99870f4d
KW
7870 Carp::my_carp("Unrecognized type '$type'. Type not set");
7871 return;
7872 }
7873
051df77b 7874 { no overloading; $type{pack 'J', $self} = $type; }
06f26c45 7875 return if $type != $BINARY && $type != $FORCED_BINARY;
99870f4d
KW
7876
7877 my $yes = $self->table('Y');
7878 $yes = $self->table('Yes') if ! defined $yes;
01adf4be
KW
7879 $yes = $self->add_match_table('Y', Full_Name => 'Yes')
7880 if ! defined $yes;
7881
3c6bf941
KW
7882 # Add aliases in order wanted, duplicates will be ignored. We use a
7883 # binary property present in all releases for its ordered lists of
7884 # true/false aliases. Note, that could run into problems in
7885 # outputting things in that we don't distinguish between the name and
7886 # full name of these. Hopefully, if the table was already created
7887 # before this code is executed, it was done with these set properly.
7888 my $bm = property_ref("Bidi_Mirrored");
7889 foreach my $alias ($bm->table("Y")->aliases) {
7890 $yes->add_alias($alias->name);
7891 }
99870f4d
KW
7892 my $no = $self->table('N');
7893 $no = $self->table('No') if ! defined $no;
01adf4be 7894 $no = $self->add_match_table('N', Full_Name => 'No') if ! defined $no;
3c6bf941
KW
7895 foreach my $alias ($bm->table("N")->aliases) {
7896 $no->add_alias($alias->name);
7897 }
c12f2655 7898
99870f4d
KW
7899 return;
7900 }
7901
7902 sub add_map {
7903 # Add a map to the property's map table. This also keeps
7904 # track of the maps so that the property type can be determined from
7905 # its data.
7906
7907 my $self = shift;
7908 my $start = shift; # First code point in range
7909 my $end = shift; # Final code point in range
7910 my $map = shift; # What the range maps to.
7911 # Rest of parameters passed on.
7912
ffe43484 7913 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
7914
7915 # If haven't the type of the property, gather information to figure it
7916 # out.
7917 if ($type{$addr} == $UNKNOWN) {
7918
7919 # If the map contains an interior blank or dash, or most other
7920 # nonword characters, it will be a string property. This
7921 # heuristic may actually miss some string properties. If so, they
7922 # may need to have explicit set_types called for them. This
7923 # happens in the Unihan properties.
7924 if ($map =~ / (?<= . ) [ -] (?= . ) /x
7925 || $map =~ / [^\w.\/\ -] /x)
7926 {
7927 $self->set_type($STRING);
7928
7929 # $unique_maps is used for disambiguating between ENUM and
7930 # BINARY later; since we know the property is not going to be
7931 # one of those, no point in keeping the data around
7932 undef $unique_maps{$addr};
7933 }
7934 else {
7935
7936 # Not necessarily a string. The final decision has to be
7937 # deferred until all the data are in. We keep track of if all
7938 # the values are code points for that eventual decision.
7939 $has_only_code_point_maps{$addr} &=
7940 $map =~ / ^ $code_point_re $/x;
7941
7942 # For the purposes of disambiguating between binary and other
7943 # enumerations at the end, we keep track of the first three
7944 # distinct property values. Once we get to three, we know
7945 # it's not going to be binary, so no need to track more.
7946 if (scalar keys %{$unique_maps{$addr}} < 3) {
7947 $unique_maps{$addr}{main::standardize($map)} = 1;
7948 }
7949 }
7950 }
7951
7952 # Add the mapping by calling our map table's method
7953 return $map{$addr}->add_map($start, $end, $map, @_);
7954 }
7955
7956 sub compute_type {
7957 # Compute the type of the property: $ENUM, $STRING, or $BINARY. This
7958 # should be called after the property is mostly filled with its maps.
7959 # We have been keeping track of what the property values have been,
7960 # and now have the necessary information to figure out the type.
7961
7962 my $self = shift;
7963 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
7964
ffe43484 7965 my $addr = do { no overloading; pack 'J', $self; };
99870f4d
KW
7966
7967 my $type = $type{$addr};
7968
7969 # If already have figured these out, no need to do so again, but we do
7970 # a double check on ENUMS to make sure that a string property hasn't
7971 # improperly been classified as an ENUM, so continue on with those.
06f26c45
KW
7972 return if $type == $STRING
7973 || $type == $BINARY
7974 || $type == $FORCED_BINARY;
99870f4d
KW
7975
7976 # If every map is to a code point, is a string property.
7977 if ($type == $UNKNOWN
7978 && ($has_only_code_point_maps{$addr}
7979 || (defined $map{$addr}->default_map
7980 && $map{$addr}->default_map eq "")))
7981 {
7982 $self->set_type($STRING);
7983 }
7984 else {
7985
7986 # Otherwise, it is to some sort of enumeration. (The case where
7987 # it is a Unicode miscellaneous property, and treated like a
7988 # string in this program is handled in add_map()). Distinguish
7989 # between binary and some other enumeration type. Of course, if
7990 # there are more than two values, it's not binary. But more
7991 # subtle is the test that the default mapping is defined means it
7992 # isn't binary. This in fact may change in the future if Unicode
7993 # changes the way its data is structured. But so far, no binary
7994 # properties ever have @missing lines for them, so the default map
7995 # isn't defined for them. The few properties that are two-valued
7996 # and aren't considered binary have the default map defined
7997 # starting in Unicode 5.0, when the @missing lines appeared; and
7998 # this program has special code to put in a default map for them
7999 # for earlier than 5.0 releases.
8000 if ($type == $ENUM
8001 || scalar keys %{$unique_maps{$addr}} > 2
8002 || defined $self->default_map)
8003 {
8004 my $tables = $self->tables;
8005 my $count = $self->count;
8006 if ($verbosity && $count > 500 && $tables/$count > .1) {
8007 Carp::my_carp_bug("It appears that $self should be a \$STRING property, not an \$ENUM because it has too many match tables: $count\n");
8008 }
8009 $self->set_type($ENUM);
8010 }
8011 else {
8012 $self->set_type($BINARY);
8013 }
8014 }
8015 undef $unique_maps{$addr}; # Garbage collect
8016 return;
8017 }
8018
301ba948
KW
8019 sub set_fate {
8020 my $self = shift;
8021 my $fate = shift;
8022 my $reason = shift; # Ignored unless suppressing
8023 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
8024
8025 my $addr = do { no overloading; pack 'J', $self; };
8026 if ($fate == $SUPPRESSED) {
8027 $why_suppressed{$self->complete_name} = $reason;
8028 }
8029
395dfc19
KW
8030 # Each table shares the property's fate, except that MAP_PROXIED
8031 # doesn't affect match tables
8032 $map{$addr}->set_fate($fate, $reason);
8033 if ($fate != $MAP_PROXIED) {
13a49092
KW
8034 foreach my $table ($map{$addr}, $self->tables) {
8035 $table->set_fate($fate, $reason);
8036 }
395dfc19 8037 }
301ba948
KW
8038 return;
8039 }
8040
8041
99870f4d
KW
8042 # Most of the accessors for a property actually apply to its map table.
8043 # Setup up accessor functions for those, referring to %map
ea25a9b2 8044 for my $sub (qw(
99870f4d
KW
8045 add_alias
8046 add_anomalous_entry
8047 add_comment
8048 add_conflicting
8049 add_description
8050 add_duplicate
8051 add_note
8052 aliases
8053 comment
8054 complete_name
2f7a8815 8055 containing_range
99870f4d
KW
8056 count
8057 default_map
8058 delete_range
8059 description
8060 each_range
8061 external_name
301ba948 8062 fate
99870f4d
KW
8063 file_path
8064 format
8065 initialize
8066 inverse_list
8067 is_empty
8068 name
8069 note
8070 perl_extension
8071 property
8072 range_count
8073 ranges
8074 range_size_1
8075 reset_each_range
8076 set_comment
99870f4d
KW
8077 set_default_map
8078 set_file_path
8079 set_final_comment
26561784 8080 _set_format
99870f4d
KW
8081 set_range_size_1
8082 set_status
8083 set_to_output_map
8084 short_name
8085 status
8086 status_info
8087 to_output_map
0a9dbafc 8088 type_of
99870f4d
KW
8089 value_of
8090 write
ea25a9b2 8091 ))
99870f4d
KW
8092 # 'property' above is for symmetry, so that one can take
8093 # the property of a property and get itself, and so don't
8094 # have to distinguish between properties and tables in
8095 # calling code
8096 {
8097 no strict "refs";
8098 *$sub = sub {
8099 use strict "refs";
8100 my $self = shift;
f998e60c 8101 no overloading;
051df77b 8102 return $map{pack 'J', $self}->$sub(@_);
99870f4d
KW
8103 }
8104 }
8105
8106
8107} # End closure
8108
8109package main;
8110
8111sub join_lines($) {
8112 # Returns lines of the input joined together, so that they can be folded
8113 # properly.
8114 # This causes continuation lines to be joined together into one long line
8115 # for folding. A continuation line is any line that doesn't begin with a
8116 # space or "\b" (the latter is stripped from the output). This is so
8117 # lines can be be in a HERE document so as to fit nicely in the terminal
8118 # width, but be joined together in one long line, and then folded with
8119 # indents, '#' prefixes, etc, properly handled.
8120 # A blank separates the joined lines except if there is a break; an extra
8121 # blank is inserted after a period ending a line.
8122
98dc9551 8123 # Initialize the return with the first line.
99870f4d
KW
8124 my ($return, @lines) = split "\n", shift;
8125
8126 # If the first line is null, it was an empty line, add the \n back in
8127 $return = "\n" if $return eq "";
8128
8129 # Now join the remainder of the physical lines.
8130 for my $line (@lines) {
8131
8132 # An empty line means wanted a blank line, so add two \n's to get that
8133 # effect, and go to the next line.
8134 if (length $line == 0) {
8135 $return .= "\n\n";
8136 next;
8137 }
8138
8139 # Look at the last character of what we have so far.
8140 my $previous_char = substr($return, -1, 1);
8141
8142 # And at the next char to be output.
8143 my $next_char = substr($line, 0, 1);
8144
8145 if ($previous_char ne "\n") {
8146
8147 # Here didn't end wth a nl. If the next char a blank or \b, it
8148 # means that here there is a break anyway. So add a nl to the
8149 # output.
8150 if ($next_char eq " " || $next_char eq "\b") {
8151 $previous_char = "\n";
8152 $return .= $previous_char;
8153 }
8154
8155 # Add an extra space after periods.
8156 $return .= " " if $previous_char eq '.';
8157 }
8158
8159 # Here $previous_char is still the latest character to be output. If
8160 # it isn't a nl, it means that the next line is to be a continuation
8161 # line, with a blank inserted between them.
8162 $return .= " " if $previous_char ne "\n";
8163
8164 # Get rid of any \b
8165 substr($line, 0, 1) = "" if $next_char eq "\b";
8166
8167 # And append this next line.
8168 $return .= $line;
8169 }
8170
8171 return $return;
8172}
8173
8174sub simple_fold($;$$$) {
8175 # Returns a string of the input (string or an array of strings) folded
8176 # into multiple-lines each of no more than $MAX_LINE_WIDTH characters plus
8177 # a \n
8178 # This is tailored for the kind of text written by this program,
8179 # especially the pod file, which can have very long names with
8180 # underscores in the middle, or words like AbcDefgHij.... We allow
8181 # breaking in the middle of such constructs if the line won't fit
8182 # otherwise. The break in such cases will come either just after an
8183 # underscore, or just before one of the Capital letters.
8184
8185 local $to_trace = 0 if main::DEBUG;
8186
8187 my $line = shift;
8188 my $prefix = shift; # Optional string to prepend to each output
8189 # line
8190 $prefix = "" unless defined $prefix;
8191
8192 my $hanging_indent = shift; # Optional number of spaces to indent
8193 # continuation lines
8194 $hanging_indent = 0 unless $hanging_indent;
8195
8196 my $right_margin = shift; # Optional number of spaces to narrow the
8197 # total width by.
8198 $right_margin = 0 unless defined $right_margin;
8199
8200 # Call carp with the 'nofold' option to avoid it from trying to call us
8201 # recursively
8202 Carp::carp_extra_args(\@_, 'nofold') if main::DEBUG && @_;
8203
8204 # The space available doesn't include what's automatically prepended
8205 # to each line, or what's reserved on the right.
8206 my $max = $MAX_LINE_WIDTH - length($prefix) - $right_margin;
8207 # XXX Instead of using the 'nofold' perhaps better to look up the stack
8208
8209 if (DEBUG && $hanging_indent >= $max) {
8210 Carp::my_carp("Too large a hanging indent ($hanging_indent); must be < $max. Using 0", 'nofold');
8211 $hanging_indent = 0;
8212 }
8213
8214 # First, split into the current physical lines.
8215 my @line;
8216 if (ref $line) { # Better be an array, because not bothering to
8217 # test
8218 foreach my $line (@{$line}) {
8219 push @line, split /\n/, $line;
8220 }
8221 }
8222 else {
8223 @line = split /\n/, $line;
8224 }
8225
8226 #local $to_trace = 1 if main::DEBUG;
8227 trace "", join(" ", @line), "\n" if main::DEBUG && $to_trace;
8228
8229 # Look at each current physical line.
8230 for (my $i = 0; $i < @line; $i++) {
8231 Carp::my_carp("Tabs don't work well.", 'nofold') if $line[$i] =~ /\t/;
8232 #local $to_trace = 1 if main::DEBUG;
8233 trace "i=$i: $line[$i]\n" if main::DEBUG && $to_trace;
8234
8235 # Remove prefix, because will be added back anyway, don't want
8236 # doubled prefix
8237 $line[$i] =~ s/^$prefix//;
8238
8239 # Remove trailing space
8240 $line[$i] =~ s/\s+\Z//;
8241
8242 # If the line is too long, fold it.
8243 if (length $line[$i] > $max) {
8244 my $remainder;
8245
8246 # Here needs to fold. Save the leading space in the line for
8247 # later.
8248 $line[$i] =~ /^ ( \s* )/x;
8249 my $leading_space = $1;
8250 trace "line length", length $line[$i], "; lead length", length($leading_space) if main::DEBUG && $to_trace;
8251
8252 # If character at final permissible position is white space,
8253 # fold there, which will delete that white space
8254 if (substr($line[$i], $max - 1, 1) =~ /\s/) {
8255 $remainder = substr($line[$i], $max);
8256 $line[$i] = substr($line[$i], 0, $max - 1);
8257 }
8258 else {
8259
8260 # Otherwise fold at an acceptable break char closest to
8261 # the max length. Look at just the maximal initial
8262 # segment of the line
8263 my $segment = substr($line[$i], 0, $max - 1);
8264 if ($segment =~
8265 /^ ( .{$hanging_indent} # Don't look before the
8266 # indent.
8267 \ * # Don't look in leading
8268 # blanks past the indent
8269 [^ ] .* # Find the right-most
8270 (?: # acceptable break:
8271 [ \s = ] # space or equal
8272 | - (?! [.0-9] ) # or non-unary minus.
8273 ) # $1 includes the character
8274 )/x)
8275 {
8276 # Split into the initial part that fits, and remaining
8277 # part of the input
8278 $remainder = substr($line[$i], length $1);
8279 $line[$i] = $1;
8280 trace $line[$i] if DEBUG && $to_trace;
8281 trace $remainder if DEBUG && $to_trace;
8282 }
8283
8284 # If didn't find a good breaking spot, see if there is a
8285 # not-so-good breaking spot. These are just after
8286 # underscores or where the case changes from lower to
8287 # upper. Use \a as a soft hyphen, but give up
8288 # and don't break the line if there is actually a \a
8289 # already in the input. We use an ascii character for the
8290 # soft-hyphen to avoid any attempt by miniperl to try to
8291 # access the files that this program is creating.
8292 elsif ($segment !~ /\a/
8293 && ($segment =~ s/_/_\a/g
8294 || $segment =~ s/ ( [a-z] ) (?= [A-Z] )/$1\a/xg))
8295 {
8296 # Here were able to find at least one place to insert
8297 # our substitute soft hyphen. Find the right-most one
8298 # and replace it by a real hyphen.
8299 trace $segment if DEBUG && $to_trace;
8300 substr($segment,
8301 rindex($segment, "\a"),
8302 1) = '-';
8303
8304 # Then remove the soft hyphen substitutes.
8305 $segment =~ s/\a//g;
8306 trace $segment if DEBUG && $to_trace;
8307
8308 # And split into the initial part that fits, and
8309 # remainder of the line
8310 my $pos = rindex($segment, '-');
8311 $remainder = substr($line[$i], $pos);
8312 trace $remainder if DEBUG && $to_trace;
8313 $line[$i] = substr($segment, 0, $pos + 1);
8314 }
8315 }
8316
8317 # Here we know if we can fold or not. If we can, $remainder
8318 # is what remains to be processed in the next iteration.
8319 if (defined $remainder) {
8320 trace "folded='$line[$i]'" if main::DEBUG && $to_trace;
8321
8322 # Insert the folded remainder of the line as a new element
8323 # of the array. (It may still be too long, but we will
8324 # deal with that next time through the loop.) Omit any
8325 # leading space in the remainder.
8326 $remainder =~ s/^\s+//;
8327 trace "remainder='$remainder'" if main::DEBUG && $to_trace;
8328
8329 # But then indent by whichever is larger of:
8330 # 1) the leading space on the input line;
8331 # 2) the hanging indent.
8332 # This preserves indentation in the original line.
8333 my $lead = ($leading_space)
8334 ? length $leading_space
8335 : $hanging_indent;
8336 $lead = max($lead, $hanging_indent);
8337 splice @line, $i+1, 0, (" " x $lead) . $remainder;
8338 }
8339 }
8340
8341 # Ready to output the line. Get rid of any trailing space
8342 # And prefix by the required $prefix passed in.
8343 $line[$i] =~ s/\s+$//;
8344 $line[$i] = "$prefix$line[$i]\n";
8345 } # End of looping through all the lines.
8346
8347 return join "", @line;
8348}
8349
8350sub property_ref { # Returns a reference to a property object.
8351 return Property::property_ref(@_);
8352}
8353
8354sub force_unlink ($) {
8355 my $filename = shift;
8356 return unless file_exists($filename);
8357 return if CORE::unlink($filename);
8358
8359 # We might need write permission
8360 chmod 0777, $filename;
8361 CORE::unlink($filename) or Carp::my_carp("Couldn't unlink $filename. Proceeding anyway: $!");
8362 return;
8363}
8364
9218f1cf 8365sub write ($$@) {
9abe8df8
KW
8366 # Given a filename and references to arrays of lines, write the lines of
8367 # each array to the file
99870f4d
KW
8368 # Filename can be given as an arrayref of directory names
8369
9218f1cf 8370 return Carp::carp_too_few_args(\@_, 3) if main::DEBUG && @_ < 3;
99870f4d 8371
9abe8df8 8372 my $file = shift;
9218f1cf 8373 my $use_utf8 = shift;
99870f4d
KW
8374
8375 # Get into a single string if an array, and get rid of, in Unix terms, any
8376 # leading '.'
8377 $file= File::Spec->join(@$file) if ref $file eq 'ARRAY';
8378 $file = File::Spec->canonpath($file);
8379
8380 # If has directories, make sure that they all exist
8381 (undef, my $directories, undef) = File::Spec->splitpath($file);
8382 File::Path::mkpath($directories) if $directories && ! -d $directories;
8383
8384 push @files_actually_output, $file;
8385
99870f4d
KW
8386 force_unlink ($file);
8387
8388 my $OUT;
8389 if (not open $OUT, ">", $file) {
8390 Carp::my_carp("can't open $file for output. Skipping this file: $!");
8391 return;
8392 }
430ada4c 8393
9218f1cf
KW
8394 binmode $OUT, ":utf8" if $use_utf8;
8395
9abe8df8
KW
8396 while (defined (my $lines_ref = shift)) {
8397 unless (@$lines_ref) {
8398 Carp::my_carp("An array of lines for writing to file '$file' is empty; writing it anyway;");
8399 }
8400
8401 print $OUT @$lines_ref or die Carp::my_carp("write to '$file' failed: $!");
8402 }
430ada4c
NC
8403 close $OUT or die Carp::my_carp("close '$file' failed: $!");
8404
99870f4d
KW
8405 print "$file written.\n" if $verbosity >= $VERBOSE;
8406
99870f4d
KW
8407 return;
8408}
8409
8410
8411sub Standardize($) {
8412 # This converts the input name string into a standardized equivalent to
8413 # use internally.
8414
8415 my $name = shift;
8416 unless (defined $name) {
8417 Carp::my_carp_bug("Standardize() called with undef. Returning undef.");
8418 return;
8419 }
8420
8421 # Remove any leading or trailing white space
8422 $name =~ s/^\s+//g;
8423 $name =~ s/\s+$//g;
8424
98dc9551 8425 # Convert interior white space and hyphens into underscores.
99870f4d
KW
8426 $name =~ s/ (?<= .) [ -]+ (.) /_$1/xg;
8427
8428 # Capitalize the letter following an underscore, and convert a sequence of
8429 # multiple underscores to a single one
8430 $name =~ s/ (?<= .) _+ (.) /_\u$1/xg;
8431
8432 # And capitalize the first letter, but not for the special cjk ones.
8433 $name = ucfirst($name) unless $name =~ /^k[A-Z]/;
8434 return $name;
8435}
8436
8437sub standardize ($) {
8438 # Returns a lower-cased standardized name, without underscores. This form
8439 # is chosen so that it can distinguish between any real versus superficial
8440 # Unicode name differences. It relies on the fact that Unicode doesn't
8441 # have interior underscores, white space, nor dashes in any
8442 # stricter-matched name. It should not be used on Unicode code point
8443 # names (the Name property), as they mostly, but not always follow these
8444 # rules.
8445
8446 my $name = Standardize(shift);
8447 return if !defined $name;
8448
8449 $name =~ s/ (?<= .) _ (?= . ) //xg;
8450 return lc $name;
8451}
8452
c85f591a
KW
8453sub utf8_heavy_name ($$) {
8454 # Returns the name that utf8_heavy.pl will use to find a table. XXX
8455 # perhaps this function should be placed somewhere, like Heavy.pl so that
8456 # utf8_heavy can use it directly without duplicating code that can get
8457 # out-of sync.
8458
8459 my $table = shift;
8460 my $alias = shift;
8461 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
8462
8463 my $property = $table->property;
8464 $property = ($property == $perl)
8465 ? "" # 'perl' is never explicitly stated
8466 : standardize($property->name) . '=';
8467 if ($alias->loose_match) {
8468 return $property . standardize($alias->name);
8469 }
8470 else {
8471 return lc ($property . $alias->name);
8472 }
8473
8474 return;
8475}
8476
99870f4d
KW
8477{ # Closure
8478
7e3121cc 8479 my $indent_increment = " " x (($debugging_build) ? 2 : 0);
99870f4d
KW
8480 my %already_output;
8481
8482 $main::simple_dumper_nesting = 0;
8483
8484 sub simple_dumper {
8485 # Like Simple Data::Dumper. Good enough for our needs. We can't use
8486 # the real thing as we have to run under miniperl.
8487
8488 # It is designed so that on input it is at the beginning of a line,
8489 # and the final thing output in any call is a trailing ",\n".
8490
8491 my $item = shift;
8492 my $indent = shift;
7e3121cc 8493 $indent = "" if ! $debugging_build || ! defined $indent;
99870f4d
KW
8494
8495 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
8496
8497 # nesting level is localized, so that as the call stack pops, it goes
8498 # back to the prior value.
8499 local $main::simple_dumper_nesting = $main::simple_dumper_nesting;
8500 undef %already_output if $main::simple_dumper_nesting == 0;
8501 $main::simple_dumper_nesting++;
8502 #print STDERR __LINE__, ": $main::simple_dumper_nesting: $indent$item\n";
8503
8504 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
8505
8506 # Determine the indent for recursive calls.
8507 my $next_indent = $indent . $indent_increment;
8508
8509 my $output;
8510 if (! ref $item) {
8511
8512 # Dump of scalar: just output it in quotes if not a number. To do
8513 # so we must escape certain characters, and therefore need to
8514 # operate on a copy to avoid changing the original
8515 my $copy = $item;
8516 $copy = $UNDEF unless defined $copy;
8517
02cc6656
KW
8518 # Quote non-integers (integers also have optional leading '-')
8519 if ($copy eq "" || $copy !~ /^ -? \d+ $/x) {
99870f4d
KW
8520
8521 # Escape apostrophe and backslash
8522 $copy =~ s/ ( ['\\] ) /\\$1/xg;
8523 $copy = "'$copy'";
8524 }
8525 $output = "$indent$copy,\n";
8526 }
8527 else {
8528
8529 # Keep track of cycles in the input, and refuse to infinitely loop
ffe43484 8530 my $addr = do { no overloading; pack 'J', $item; };
f998e60c 8531 if (defined $already_output{$addr}) {
99870f4d
KW
8532 return "${indent}ALREADY OUTPUT: $item\n";
8533 }
f998e60c 8534 $already_output{$addr} = $item;
99870f4d
KW
8535
8536 if (ref $item eq 'ARRAY') {
8537 my $using_brackets;
8538 $output = $indent;
8539 if ($main::simple_dumper_nesting > 1) {
8540 $output .= '[';
8541 $using_brackets = 1;
8542 }
8543 else {
8544 $using_brackets = 0;
8545 }
8546
8547 # If the array is empty, put the closing bracket on the same
8548 # line. Otherwise, recursively add each array element
8549 if (@$item == 0) {
8550 $output .= " ";
8551 }
8552 else {
8553 $output .= "\n";
8554 for (my $i = 0; $i < @$item; $i++) {
8555
8556 # Indent array elements one level
8557 $output .= &simple_dumper($item->[$i], $next_indent);
7e3121cc 8558 next if ! $debugging_build;
c12f2655
KW
8559 $output =~ s/\n$//; # Remove any trailing nl so
8560 $output .= " # [$i]\n"; # as to add a comment giving
8561 # the array index
99870f4d
KW
8562 }
8563 $output .= $indent; # Indent closing ']' to orig level
8564 }
8565 $output .= ']' if $using_brackets;
8566 $output .= ",\n";
8567 }
8568 elsif (ref $item eq 'HASH') {
8569 my $is_first_line;
8570 my $using_braces;
8571 my $body_indent;
8572
8573 # No surrounding braces at top level
8574 $output .= $indent;
8575 if ($main::simple_dumper_nesting > 1) {
8576 $output .= "{\n";
8577 $is_first_line = 0;
8578 $body_indent = $next_indent;
8579 $next_indent .= $indent_increment;
8580 $using_braces = 1;
8581 }
8582 else {
8583 $is_first_line = 1;
8584 $body_indent = $indent;
8585 $using_braces = 0;
8586 }
8587
8588 # Output hashes sorted alphabetically instead of apparently
8589 # random. Use caseless alphabetic sort
8590 foreach my $key (sort { lc $a cmp lc $b } keys %$item)
8591 {
8592 if ($is_first_line) {
8593 $is_first_line = 0;
8594 }
8595 else {
8596 $output .= "$body_indent";
8597 }
8598
8599 # The key must be a scalar, but this recursive call quotes
8600 # it
8601 $output .= &simple_dumper($key);
8602
8603 # And change the trailing comma and nl to the hash fat
8604 # comma for clarity, and so the value can be on the same
8605 # line
8606 $output =~ s/,\n$/ => /;
8607
8608 # Recursively call to get the value's dump.
8609 my $next = &simple_dumper($item->{$key}, $next_indent);
8610
8611 # If the value is all on one line, remove its indent, so
8612 # will follow the => immediately. If it takes more than
8613 # one line, start it on a new line.
8614 if ($next !~ /\n.*\n/) {
8615 $next =~ s/^ *//;
8616 }
8617 else {
8618 $output .= "\n";
8619 }
8620 $output .= $next;
8621 }
8622
8623 $output .= "$indent},\n" if $using_braces;
8624 }
8625 elsif (ref $item eq 'CODE' || ref $item eq 'GLOB') {
8626 $output = $indent . ref($item) . "\n";
8627 # XXX see if blessed
8628 }
8629 elsif ($item->can('dump')) {
8630
8631 # By convention in this program, objects furnish a 'dump'
8632 # method. Since not doing any output at this level, just pass
8633 # on the input indent
8634 $output = $item->dump($indent);
8635 }
8636 else {
8637 Carp::my_carp("Can't cope with dumping a " . ref($item) . ". Skipping.");
8638 }
8639 }
8640 return $output;
8641 }
8642}
8643
8644sub dump_inside_out {
8645 # Dump inside-out hashes in an object's state by converting them to a
8646 # regular hash and then calling simple_dumper on that.
8647
8648 my $object = shift;
8649 my $fields_ref = shift;
8650 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
8651
ffe43484 8652 my $addr = do { no overloading; pack 'J', $object; };
99870f4d
KW
8653
8654 my %hash;
8655 foreach my $key (keys %$fields_ref) {
8656 $hash{$key} = $fields_ref->{$key}{$addr};
8657 }
8658
8659 return simple_dumper(\%hash, @_);
8660}
8661
8662sub _operator_dot {
8663 # Overloaded '.' method that is common to all packages. It uses the
8664 # package's stringify method.
8665
8666 my $self = shift;
8667 my $other = shift;
8668 my $reversed = shift;
8669 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
8670
8671 $other = "" unless defined $other;
8672
8673 foreach my $which (\$self, \$other) {
8674 next unless ref $$which;
8675 if ($$which->can('_operator_stringify')) {
8676 $$which = $$which->_operator_stringify;
8677 }
8678 else {
8679 my $ref = ref $$which;
ffe43484 8680 my $addr = do { no overloading; pack 'J', $$which; };
99870f4d
KW
8681 $$which = "$ref ($addr)";
8682 }
8683 }
8684 return ($reversed)
8685 ? "$other$self"
8686 : "$self$other";
8687}
8688
8689sub _operator_equal {
8690 # Generic overloaded '==' routine. To be equal, they must be the exact
8691 # same object
8692
8693 my $self = shift;
8694 my $other = shift;
8695
8696 return 0 unless defined $other;
8697 return 0 unless ref $other;
f998e60c 8698 no overloading;
2100aa98 8699 return $self == $other;
99870f4d
KW
8700}
8701
8702sub _operator_not_equal {
8703 my $self = shift;
8704 my $other = shift;
8705
8706 return ! _operator_equal($self, $other);
8707}
8708
8709sub process_PropertyAliases($) {
8710 # This reads in the PropertyAliases.txt file, which contains almost all
8711 # the character properties in Unicode and their equivalent aliases:
8712 # scf ; Simple_Case_Folding ; sfc
8713 #
8714 # Field 0 is the preferred short name for the property.
8715 # Field 1 is the full name.
8716 # Any succeeding ones are other accepted names.
8717
8718 my $file= shift;
8719 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
8720
8721 # This whole file was non-existent in early releases, so use our own
8722 # internal one.
8723 $file->insert_lines(get_old_property_aliases())
8724 if ! -e 'PropertyAliases.txt';
8725
8726 # Add any cjk properties that may have been defined.
8727 $file->insert_lines(@cjk_properties);
8728
8729 while ($file->next_line) {
8730
8731 my @data = split /\s*;\s*/;
8732
8733 my $full = $data[1];
8734
8735 my $this = Property->new($data[0], Full_Name => $full);
8736
8737 # Start looking for more aliases after these two.
8738 for my $i (2 .. @data - 1) {
8739 $this->add_alias($data[$i]);
8740 }
8741
8742 }
8743 return;
8744}
8745
8746sub finish_property_setup {
8747 # Finishes setting up after PropertyAliases.
8748
8749 my $file = shift;
8750 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
8751
8752 # This entry was missing from this file in earlier Unicode versions
8753 if (-e 'Jamo.txt') {
8754 my $jsn = property_ref('JSN');
8755 if (! defined $jsn) {
8756 $jsn = Property->new('JSN', Full_Name => 'Jamo_Short_Name');
8757 }
8758 }
8759
99870f4d
KW
8760 # These are used so much, that we set globals for them.
8761 $gc = property_ref('General_Category');
8762 $block = property_ref('Block');
359523e2 8763 $script = property_ref('Script');
99870f4d
KW
8764
8765 # Perl adds this alias.
8766 $gc->add_alias('Category');
8767
d3cbe105
KW
8768 # Unicode::Normalize expects this file with this name and directory.
8769 my $ccc = property_ref('Canonical_Combining_Class');
8770 if (defined $ccc) {
8771 $ccc->set_file('CombiningClass');
8772 $ccc->set_directory(File::Spec->curdir());
8773 }
8774
99870f4d
KW
8775 # These two properties aren't actually used in the core, but unfortunately
8776 # the names just above that are in the core interfere with these, so
8777 # choose different names. These aren't a problem unless the map tables
8778 # for these files get written out.
8779 my $lowercase = property_ref('Lowercase');
8780 $lowercase->set_file('IsLower') if defined $lowercase;
8781 my $uppercase = property_ref('Uppercase');
8782 $uppercase->set_file('IsUpper') if defined $uppercase;
8783
8784 # Set up the hard-coded default mappings, but only on properties defined
8785 # for this release
8786 foreach my $property (keys %default_mapping) {
8787 my $property_object = property_ref($property);
8788 next if ! defined $property_object;
8789 my $default_map = $default_mapping{$property};
8790 $property_object->set_default_map($default_map);
8791
8792 # A map of <code point> implies the property is string.
8793 if ($property_object->type == $UNKNOWN
8794 && $default_map eq $CODE_POINT)
8795 {
8796 $property_object->set_type($STRING);
8797 }
8798 }
8799
8800 # The following use the Multi_Default class to create objects for
8801 # defaults.
8802
8803 # Bidi class has a complicated default, but the derived file takes care of
8804 # the complications, leaving just 'L'.
8805 if (file_exists("${EXTRACTED}DBidiClass.txt")) {
8806 property_ref('Bidi_Class')->set_default_map('L');
8807 }
8808 else {
8809 my $default;
8810
8811 # The derived file was introduced in 3.1.1. The values below are
8812 # taken from table 3-8, TUS 3.0
8813 my $default_R =
8814 'my $default = Range_List->new;
8815 $default->add_range(0x0590, 0x05FF);
8816 $default->add_range(0xFB1D, 0xFB4F);'
8817 ;
8818
8819 # The defaults apply only to unassigned characters
a67f160a 8820 $default_R .= '$gc->table("Unassigned") & $default;';
99870f4d
KW
8821
8822 if ($v_version lt v3.0.0) {
8823 $default = Multi_Default->new(R => $default_R, 'L');
8824 }
8825 else {
8826
8827 # AL apparently not introduced until 3.0: TUS 2.x references are
8828 # not on-line to check it out
8829 my $default_AL =
8830 'my $default = Range_List->new;
8831 $default->add_range(0x0600, 0x07BF);
8832 $default->add_range(0xFB50, 0xFDFF);
8833 $default->add_range(0xFE70, 0xFEFF);'
8834 ;
8835
8836 # Non-character code points introduced in this release; aren't AL
8837 if ($v_version ge 3.1.0) {
8838 $default_AL .= '$default->delete_range(0xFDD0, 0xFDEF);';
8839 }
a67f160a 8840 $default_AL .= '$gc->table("Unassigned") & $default';
99870f4d
KW
8841 $default = Multi_Default->new(AL => $default_AL,
8842 R => $default_R,
8843 'L');
8844 }
8845 property_ref('Bidi_Class')->set_default_map($default);
8846 }
8847
8848 # Joining type has a complicated default, but the derived file takes care
8849 # of the complications, leaving just 'U' (or Non_Joining), except the file
8850 # is bad in 3.1.0
8851 if (file_exists("${EXTRACTED}DJoinType.txt") || -e 'ArabicShaping.txt') {
8852 if (file_exists("${EXTRACTED}DJoinType.txt") && $v_version ne 3.1.0) {
8853 property_ref('Joining_Type')->set_default_map('Non_Joining');
8854 }
8855 else {
8856
8857 # Otherwise, there are not one, but two possibilities for the
8858 # missing defaults: T and U.
8859 # The missing defaults that evaluate to T are given by:
8860 # T = Mn + Cf - ZWNJ - ZWJ
8861 # where Mn and Cf are the general category values. In other words,
8862 # any non-spacing mark or any format control character, except
8863 # U+200C ZERO WIDTH NON-JOINER (joining type U) and U+200D ZERO
8864 # WIDTH JOINER (joining type C).
8865 my $default = Multi_Default->new(
8866 'T' => '$gc->table("Mn") + $gc->table("Cf") - 0x200C - 0x200D',
8867 'Non_Joining');
8868 property_ref('Joining_Type')->set_default_map($default);
8869 }
8870 }
8871
8872 # Line break has a complicated default in early releases. It is 'Unknown'
8873 # for non-assigned code points; 'AL' for assigned.
8874 if (file_exists("${EXTRACTED}DLineBreak.txt") || -e 'LineBreak.txt') {
8875 my $lb = property_ref('Line_Break');
8876 if ($v_version gt 3.2.0) {
8877 $lb->set_default_map('Unknown');
8878 }
8879 else {
8880 my $default = Multi_Default->new( 'Unknown' => '$gc->table("Cn")',
8881 'AL');
8882 $lb->set_default_map($default);
8883 }
8884
8885 # If has the URS property, make sure that the standard aliases are in
8886 # it, since not in the input tables in some versions.
8887 my $urs = property_ref('Unicode_Radical_Stroke');
8888 if (defined $urs) {
8889 $urs->add_alias('cjkRSUnicode');
8890 $urs->add_alias('kRSUnicode');
8891 }
8892 }
f64b46a1
KW
8893
8894 # For backwards compatibility with applications that may read the mapping
8895 # file directly (it was documented in 5.12 and 5.14 as being thusly
8896 # usable), keep it from being compacted to use deltas. (range_size_1 is
8897 # used to force the traditional format.)
8898 if (defined (my $nfkc_cf = property_ref('NFKC_Casefold'))) {
8899 $nfkc_cf->set_to_output_map($EXTERNAL_MAP);
8900 $nfkc_cf->set_range_size_1(1);
8901 }
8902 if (defined (my $bmg = property_ref('Bidi_Mirroring_Glyph'))) {
8903 $bmg->set_to_output_map($EXTERNAL_MAP);
8904 $bmg->set_range_size_1(1);
8905 }
8906
99870f4d
KW
8907 return;
8908}
8909
8910sub get_old_property_aliases() {
8911 # Returns what would be in PropertyAliases.txt if it existed in very old
8912 # versions of Unicode. It was derived from the one in 3.2, and pared
8913 # down based on the data that was actually in the older releases.
8914 # An attempt was made to use the existence of files to mean inclusion or
8915 # not of various aliases, but if this was not sufficient, using version
8916 # numbers was resorted to.
8917
8918 my @return;
8919
8920 # These are to be used in all versions (though some are constructed by
8921 # this program if missing)
8922 push @return, split /\n/, <<'END';
8923bc ; Bidi_Class
8924Bidi_M ; Bidi_Mirrored
8925cf ; Case_Folding
8926ccc ; Canonical_Combining_Class
8927dm ; Decomposition_Mapping
8928dt ; Decomposition_Type
8929gc ; General_Category
8930isc ; ISO_Comment
8931lc ; Lowercase_Mapping
8932na ; Name
8933na1 ; Unicode_1_Name
8934nt ; Numeric_Type
8935nv ; Numeric_Value
8936sfc ; Simple_Case_Folding
8937slc ; Simple_Lowercase_Mapping
8938stc ; Simple_Titlecase_Mapping
8939suc ; Simple_Uppercase_Mapping
8940tc ; Titlecase_Mapping
8941uc ; Uppercase_Mapping
8942END
8943
8944 if (-e 'Blocks.txt') {
8945 push @return, "blk ; Block\n";
8946 }
8947 if (-e 'ArabicShaping.txt') {
8948 push @return, split /\n/, <<'END';
8949jg ; Joining_Group
8950jt ; Joining_Type
8951END
8952 }
8953 if (-e 'PropList.txt') {
8954
8955 # This first set is in the original old-style proplist.
8956 push @return, split /\n/, <<'END';
8957Alpha ; Alphabetic
8958Bidi_C ; Bidi_Control
8959Dash ; Dash
8960Dia ; Diacritic
8961Ext ; Extender
8962Hex ; Hex_Digit
8963Hyphen ; Hyphen
8964IDC ; ID_Continue
8965Ideo ; Ideographic
8966Join_C ; Join_Control
8967Math ; Math
8968QMark ; Quotation_Mark
8969Term ; Terminal_Punctuation
8970WSpace ; White_Space
8971END
8972 # The next sets were added later
8973 if ($v_version ge v3.0.0) {
8974 push @return, split /\n/, <<'END';
8975Upper ; Uppercase
8976Lower ; Lowercase
8977END
8978 }
8979 if ($v_version ge v3.0.1) {
8980 push @return, split /\n/, <<'END';
8981NChar ; Noncharacter_Code_Point
8982END
8983 }
8984 # The next sets were added in the new-style
8985 if ($v_version ge v3.1.0) {
8986 push @return, split /\n/, <<'END';
8987OAlpha ; Other_Alphabetic
8988OLower ; Other_Lowercase
8989OMath ; Other_Math
8990OUpper ; Other_Uppercase
8991END
8992 }
8993 if ($v_version ge v3.1.1) {
8994 push @return, "AHex ; ASCII_Hex_Digit\n";
8995 }
8996 }
8997 if (-e 'EastAsianWidth.txt') {
8998 push @return, "ea ; East_Asian_Width\n";
8999 }
9000 if (-e 'CompositionExclusions.txt') {
9001 push @return, "CE ; Composition_Exclusion\n";
9002 }
9003 if (-e 'LineBreak.txt') {
9004 push @return, "lb ; Line_Break\n";
9005 }
9006 if (-e 'BidiMirroring.txt') {
9007 push @return, "bmg ; Bidi_Mirroring_Glyph\n";
9008 }
9009 if (-e 'Scripts.txt') {
9010 push @return, "sc ; Script\n";
9011 }
9012 if (-e 'DNormalizationProps.txt') {
9013 push @return, split /\n/, <<'END';
9014Comp_Ex ; Full_Composition_Exclusion
9015FC_NFKC ; FC_NFKC_Closure
9016NFC_QC ; NFC_Quick_Check
9017NFD_QC ; NFD_Quick_Check
9018NFKC_QC ; NFKC_Quick_Check
9019NFKD_QC ; NFKD_Quick_Check
9020XO_NFC ; Expands_On_NFC
9021XO_NFD ; Expands_On_NFD
9022XO_NFKC ; Expands_On_NFKC
9023XO_NFKD ; Expands_On_NFKD
9024END
9025 }
9026 if (-e 'DCoreProperties.txt') {
9027 push @return, split /\n/, <<'END';
9028IDS ; ID_Start
9029XIDC ; XID_Continue
9030XIDS ; XID_Start
9031END
9032 # These can also appear in some versions of PropList.txt
9033 push @return, "Lower ; Lowercase\n"
9034 unless grep { $_ =~ /^Lower\b/} @return;
9035 push @return, "Upper ; Uppercase\n"
9036 unless grep { $_ =~ /^Upper\b/} @return;
9037 }
9038
9039 # This flag requires the DAge.txt file to be copied into the directory.
9040 if (DEBUG && $compare_versions) {
9041 push @return, 'age ; Age';
9042 }
9043
9044 return @return;
9045}
9046
9047sub process_PropValueAliases {
9048 # This file contains values that properties look like:
9049 # bc ; AL ; Arabic_Letter
9050 # blk; n/a ; Greek_And_Coptic ; Greek
9051 #
9052 # Field 0 is the property.
9053 # Field 1 is the short name of a property value or 'n/a' if no
9054 # short name exists;
9055 # Field 2 is the full property value name;
9056 # Any other fields are more synonyms for the property value.
9057 # Purely numeric property values are omitted from the file; as are some
9058 # others, fewer and fewer in later releases
9059
9060 # Entries for the ccc property have an extra field before the
9061 # abbreviation:
9062 # ccc; 0; NR ; Not_Reordered
9063 # It is the numeric value that the names are synonyms for.
9064
9065 # There are comment entries for values missing from this file:
9066 # # @missing: 0000..10FFFF; ISO_Comment; <none>
9067 # # @missing: 0000..10FFFF; Lowercase_Mapping; <code point>
9068
9069 my $file= shift;
9070 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
9071
9072 # This whole file was non-existent in early releases, so use our own
9073 # internal one if necessary.
9074 if (! -e 'PropValueAliases.txt') {
9075 $file->insert_lines(get_old_property_value_aliases());
9076 }
9077
9078 # Add any explicit cjk values
9079 $file->insert_lines(@cjk_property_values);
9080
9081 # This line is used only for testing the code that checks for name
9082 # conflicts. There is a script Inherited, and when this line is executed
9083 # it causes there to be a name conflict with the 'Inherited' that this
9084 # program generates for this block property value
9085 #$file->insert_lines('blk; n/a; Herited');
9086
9087
9088 # Process each line of the file ...
9089 while ($file->next_line) {
9090
9091 my ($property, @data) = split /\s*;\s*/;
9092
66b4eb0a
KW
9093 # The ccc property has an extra field at the beginning, which is the
9094 # numeric value. Move it to be after the other two, mnemonic, fields,
9095 # so that those will be used as the property value's names, and the
9096 # number will be an extra alias. (Rightmost splice removes field 1-2,
9097 # returning them in a slice; left splice inserts that before anything,
9098 # thus shifting the former field 0 to after them.)
9099 splice (@data, 0, 0, splice(@data, 1, 2)) if $property eq 'ccc';
9100
9101 # Field 0 is a short name unless "n/a"; field 1 is the full name. If
9102 # there is no short name, use the full one in element 1
027866c1
KW
9103 if ($data[0] eq "n/a") {
9104 $data[0] = $data[1];
9105 }
9106 elsif ($data[0] ne $data[1]
9107 && standardize($data[0]) eq standardize($data[1])
9108 && $data[1] !~ /[[:upper:]]/)
9109 {
9110 # Also, there is a bug in the file in which "n/a" is omitted, and
9111 # the two fields are identical except for case, and the full name
9112 # is all lower case. Copy the "short" name unto the full one to
9113 # give it some upper case.
9114
9115 $data[1] = $data[0];
9116 }
99870f4d
KW
9117
9118 # Earlier releases had the pseudo property 'qc' that should expand to
9119 # the ones that replace it below.
9120 if ($property eq 'qc') {
9121 if (lc $data[0] eq 'y') {
9122 $file->insert_lines('NFC_QC; Y ; Yes',
9123 'NFD_QC; Y ; Yes',
9124 'NFKC_QC; Y ; Yes',
9125 'NFKD_QC; Y ; Yes',
9126 );
9127 }
9128 elsif (lc $data[0] eq 'n') {
9129 $file->insert_lines('NFC_QC; N ; No',
9130 'NFD_QC; N ; No',
9131 'NFKC_QC; N ; No',
9132 'NFKD_QC; N ; No',
9133 );
9134 }
9135 elsif (lc $data[0] eq 'm') {
9136 $file->insert_lines('NFC_QC; M ; Maybe',
9137 'NFKC_QC; M ; Maybe',
9138 );
9139 }
9140 else {
9141 $file->carp_bad_line("qc followed by unexpected '$data[0]");
9142 }
9143 next;
9144 }
9145
9146 # The first field is the short name, 2nd is the full one.
9147 my $property_object = property_ref($property);
9148 my $table = $property_object->add_match_table($data[0],
9149 Full_Name => $data[1]);
9150
9151 # Start looking for more aliases after these two.
9152 for my $i (2 .. @data - 1) {
9153 $table->add_alias($data[$i]);
9154 }
9155 } # End of looping through the file
9156
9157 # As noted in the comments early in the program, it generates tables for
9158 # the default values for all releases, even those for which the concept
9159 # didn't exist at the time. Here we add those if missing.
9160 my $age = property_ref('age');
9161 if (defined $age && ! defined $age->table('Unassigned')) {
9162 $age->add_match_table('Unassigned');
9163 }
9164 $block->add_match_table('No_Block') if -e 'Blocks.txt'
9165 && ! defined $block->table('No_Block');
9166
9167
9168 # Now set the default mappings of the properties from the file. This is
9169 # done after the loop because a number of properties have only @missings
9170 # entries in the file, and may not show up until the end.
9171 my @defaults = $file->get_missings;
9172 foreach my $default_ref (@defaults) {
9173 my $default = $default_ref->[0];
9174 my $property = property_ref($default_ref->[1]);
9175 $property->set_default_map($default);
9176 }
9177 return;
9178}
9179
9180sub get_old_property_value_aliases () {
9181 # Returns what would be in PropValueAliases.txt if it existed in very old
9182 # versions of Unicode. It was derived from the one in 3.2, and pared
9183 # down. An attempt was made to use the existence of files to mean
9184 # inclusion or not of various aliases, but if this was not sufficient,
9185 # using version numbers was resorted to.
9186
9187 my @return = split /\n/, <<'END';
9188bc ; AN ; Arabic_Number
9189bc ; B ; Paragraph_Separator
9190bc ; CS ; Common_Separator
9191bc ; EN ; European_Number
9192bc ; ES ; European_Separator
9193bc ; ET ; European_Terminator
9194bc ; L ; Left_To_Right
9195bc ; ON ; Other_Neutral
9196bc ; R ; Right_To_Left
9197bc ; WS ; White_Space
9198
9199# The standard combining classes are very much different in v1, so only use
9200# ones that look right (not checked thoroughly)
9201ccc; 0; NR ; Not_Reordered
9202ccc; 1; OV ; Overlay
9203ccc; 7; NK ; Nukta
9204ccc; 8; KV ; Kana_Voicing
9205ccc; 9; VR ; Virama
9206ccc; 202; ATBL ; Attached_Below_Left
9207ccc; 216; ATAR ; Attached_Above_Right
9208ccc; 218; BL ; Below_Left
9209ccc; 220; B ; Below
9210ccc; 222; BR ; Below_Right
9211ccc; 224; L ; Left
9212ccc; 228; AL ; Above_Left
9213ccc; 230; A ; Above
9214ccc; 232; AR ; Above_Right
9215ccc; 234; DA ; Double_Above
9216
9217dt ; can ; canonical
9218dt ; enc ; circle
9219dt ; fin ; final
9220dt ; font ; font
9221dt ; fra ; fraction
9222dt ; init ; initial
9223dt ; iso ; isolated
9224dt ; med ; medial
9225dt ; n/a ; none
9226dt ; nb ; noBreak
9227dt ; sqr ; square
9228dt ; sub ; sub
9229dt ; sup ; super
9230
9231gc ; C ; Other # Cc | Cf | Cn | Co | Cs
9232gc ; Cc ; Control
9233gc ; Cn ; Unassigned
9234gc ; Co ; Private_Use
9235gc ; L ; Letter # Ll | Lm | Lo | Lt | Lu
9236gc ; LC ; Cased_Letter # Ll | Lt | Lu
9237gc ; Ll ; Lowercase_Letter
9238gc ; Lm ; Modifier_Letter
9239gc ; Lo ; Other_Letter
9240gc ; Lu ; Uppercase_Letter
9241gc ; M ; Mark # Mc | Me | Mn
9242gc ; Mc ; Spacing_Mark
9243gc ; Mn ; Nonspacing_Mark
9244gc ; N ; Number # Nd | Nl | No
9245gc ; Nd ; Decimal_Number
9246gc ; No ; Other_Number
9247gc ; P ; Punctuation # Pc | Pd | Pe | Pf | Pi | Po | Ps
9248gc ; Pd ; Dash_Punctuation
9249gc ; Pe ; Close_Punctuation
9250gc ; Po ; Other_Punctuation
9251gc ; Ps ; Open_Punctuation
9252gc ; S ; Symbol # Sc | Sk | Sm | So
9253gc ; Sc ; Currency_Symbol
9254gc ; Sm ; Math_Symbol
9255gc ; So ; Other_Symbol
9256gc ; Z ; Separator # Zl | Zp | Zs
9257gc ; Zl ; Line_Separator
9258gc ; Zp ; Paragraph_Separator
9259gc ; Zs ; Space_Separator
9260
9261nt ; de ; Decimal
9262nt ; di ; Digit
9263nt ; n/a ; None
9264nt ; nu ; Numeric
9265END
9266
9267 if (-e 'ArabicShaping.txt') {
9268 push @return, split /\n/, <<'END';
9269jg ; n/a ; AIN
9270jg ; n/a ; ALEF
9271jg ; n/a ; DAL
9272jg ; n/a ; GAF
9273jg ; n/a ; LAM
9274jg ; n/a ; MEEM
9275jg ; n/a ; NO_JOINING_GROUP
9276jg ; n/a ; NOON
9277jg ; n/a ; QAF
9278jg ; n/a ; SAD
9279jg ; n/a ; SEEN
9280jg ; n/a ; TAH
9281jg ; n/a ; WAW
9282
9283jt ; C ; Join_Causing
9284jt ; D ; Dual_Joining
9285jt ; L ; Left_Joining
9286jt ; R ; Right_Joining
9287jt ; U ; Non_Joining
9288jt ; T ; Transparent
9289END
9290 if ($v_version ge v3.0.0) {
9291 push @return, split /\n/, <<'END';
9292jg ; n/a ; ALAPH
9293jg ; n/a ; BEH
9294jg ; n/a ; BETH
9295jg ; n/a ; DALATH_RISH
9296jg ; n/a ; E
9297jg ; n/a ; FEH
9298jg ; n/a ; FINAL_SEMKATH
9299jg ; n/a ; GAMAL
9300jg ; n/a ; HAH
9301jg ; n/a ; HAMZA_ON_HEH_GOAL
9302jg ; n/a ; HE
9303jg ; n/a ; HEH
9304jg ; n/a ; HEH_GOAL
9305jg ; n/a ; HETH
9306jg ; n/a ; KAF
9307jg ; n/a ; KAPH
9308jg ; n/a ; KNOTTED_HEH
9309jg ; n/a ; LAMADH
9310jg ; n/a ; MIM
9311jg ; n/a ; NUN
9312jg ; n/a ; PE
9313jg ; n/a ; QAPH
9314jg ; n/a ; REH
9315jg ; n/a ; REVERSED_PE
9316jg ; n/a ; SADHE
9317jg ; n/a ; SEMKATH
9318jg ; n/a ; SHIN
9319jg ; n/a ; SWASH_KAF
9320jg ; n/a ; TAW
9321jg ; n/a ; TEH_MARBUTA
9322jg ; n/a ; TETH
9323jg ; n/a ; YEH
9324jg ; n/a ; YEH_BARREE
9325jg ; n/a ; YEH_WITH_TAIL
9326jg ; n/a ; YUDH
9327jg ; n/a ; YUDH_HE
9328jg ; n/a ; ZAIN
9329END
9330 }
9331 }
9332
9333
9334 if (-e 'EastAsianWidth.txt') {
9335 push @return, split /\n/, <<'END';
9336ea ; A ; Ambiguous
9337ea ; F ; Fullwidth
9338ea ; H ; Halfwidth
9339ea ; N ; Neutral
9340ea ; Na ; Narrow
9341ea ; W ; Wide
9342END
9343 }
9344
9345 if (-e 'LineBreak.txt') {
9346 push @return, split /\n/, <<'END';
9347lb ; AI ; Ambiguous
9348lb ; AL ; Alphabetic
9349lb ; B2 ; Break_Both
9350lb ; BA ; Break_After
9351lb ; BB ; Break_Before
9352lb ; BK ; Mandatory_Break
9353lb ; CB ; Contingent_Break
9354lb ; CL ; Close_Punctuation
9355lb ; CM ; Combining_Mark
9356lb ; CR ; Carriage_Return
9357lb ; EX ; Exclamation
9358lb ; GL ; Glue
9359lb ; HY ; Hyphen
9360lb ; ID ; Ideographic
9361lb ; IN ; Inseperable
9362lb ; IS ; Infix_Numeric
9363lb ; LF ; Line_Feed
9364lb ; NS ; Nonstarter
9365lb ; NU ; Numeric
9366lb ; OP ; Open_Punctuation
9367lb ; PO ; Postfix_Numeric
9368lb ; PR ; Prefix_Numeric
9369lb ; QU ; Quotation
9370lb ; SA ; Complex_Context
9371lb ; SG ; Surrogate
9372lb ; SP ; Space
9373lb ; SY ; Break_Symbols
9374lb ; XX ; Unknown
9375lb ; ZW ; ZWSpace
9376END
9377 }
9378
9379 if (-e 'DNormalizationProps.txt') {
9380 push @return, split /\n/, <<'END';
9381qc ; M ; Maybe
9382qc ; N ; No
9383qc ; Y ; Yes
9384END
9385 }
9386
9387 if (-e 'Scripts.txt') {
9388 push @return, split /\n/, <<'END';
9389sc ; Arab ; Arabic
9390sc ; Armn ; Armenian
9391sc ; Beng ; Bengali
9392sc ; Bopo ; Bopomofo
9393sc ; Cans ; Canadian_Aboriginal
9394sc ; Cher ; Cherokee
9395sc ; Cyrl ; Cyrillic
9396sc ; Deva ; Devanagari
9397sc ; Dsrt ; Deseret
9398sc ; Ethi ; Ethiopic
9399sc ; Geor ; Georgian
9400sc ; Goth ; Gothic
9401sc ; Grek ; Greek
9402sc ; Gujr ; Gujarati
9403sc ; Guru ; Gurmukhi
9404sc ; Hang ; Hangul
9405sc ; Hani ; Han
9406sc ; Hebr ; Hebrew
9407sc ; Hira ; Hiragana
9408sc ; Ital ; Old_Italic
9409sc ; Kana ; Katakana
9410sc ; Khmr ; Khmer
9411sc ; Knda ; Kannada
9412sc ; Laoo ; Lao
9413sc ; Latn ; Latin
9414sc ; Mlym ; Malayalam
9415sc ; Mong ; Mongolian
9416sc ; Mymr ; Myanmar
9417sc ; Ogam ; Ogham
9418sc ; Orya ; Oriya
9419sc ; Qaai ; Inherited
9420sc ; Runr ; Runic
9421sc ; Sinh ; Sinhala
9422sc ; Syrc ; Syriac
9423sc ; Taml ; Tamil
9424sc ; Telu ; Telugu
9425sc ; Thaa ; Thaana
9426sc ; Thai ; Thai
9427sc ; Tibt ; Tibetan
9428sc ; Yiii ; Yi
9429sc ; Zyyy ; Common
9430END
9431 }
9432
9433 if ($v_version ge v2.0.0) {
9434 push @return, split /\n/, <<'END';
9435dt ; com ; compat
9436dt ; nar ; narrow
9437dt ; sml ; small
9438dt ; vert ; vertical
9439dt ; wide ; wide
9440
9441gc ; Cf ; Format
9442gc ; Cs ; Surrogate
9443gc ; Lt ; Titlecase_Letter
9444gc ; Me ; Enclosing_Mark
9445gc ; Nl ; Letter_Number
9446gc ; Pc ; Connector_Punctuation
9447gc ; Sk ; Modifier_Symbol
9448END
9449 }
9450 if ($v_version ge v2.1.2) {
9451 push @return, "bc ; S ; Segment_Separator\n";
9452 }
9453 if ($v_version ge v2.1.5) {
9454 push @return, split /\n/, <<'END';
9455gc ; Pf ; Final_Punctuation
9456gc ; Pi ; Initial_Punctuation
9457END
9458 }
9459 if ($v_version ge v2.1.8) {
9460 push @return, "ccc; 240; IS ; Iota_Subscript\n";
9461 }
9462
9463 if ($v_version ge v3.0.0) {
9464 push @return, split /\n/, <<'END';
9465bc ; AL ; Arabic_Letter
9466bc ; BN ; Boundary_Neutral
9467bc ; LRE ; Left_To_Right_Embedding
9468bc ; LRO ; Left_To_Right_Override
9469bc ; NSM ; Nonspacing_Mark
9470bc ; PDF ; Pop_Directional_Format
9471bc ; RLE ; Right_To_Left_Embedding
9472bc ; RLO ; Right_To_Left_Override
9473
9474ccc; 233; DB ; Double_Below
9475END
9476 }
9477
9478 if ($v_version ge v3.1.0) {
9479 push @return, "ccc; 226; R ; Right\n";
9480 }
9481
9482 return @return;
9483}
9484
b1c167a3
KW
9485sub output_perl_charnames_line ($$) {
9486
9487 # Output the entries in Perl_charnames specially, using 5 digits instead
9488 # of four. This makes the entries a constant length, and simplifies
9489 # charnames.pm which this table is for. Unicode can have 6 digit
9490 # ordinals, but they are all private use or noncharacters which do not
9491 # have names, so won't be in this table.
9492
73d9566f 9493 return sprintf "%05X\t%s\n", $_[0], $_[1];
b1c167a3
KW
9494}
9495
99870f4d
KW
9496{ # Closure
9497 # This is used to store the range list of all the code points usable when
9498 # the little used $compare_versions feature is enabled.
9499 my $compare_versions_range_list;
9500
96cfc54a
KW
9501 # These are constants to the $property_info hash in this subroutine, to
9502 # avoid using a quoted-string which might have a typo.
9503 my $TYPE = 'type';
9504 my $DEFAULT_MAP = 'default_map';
9505 my $DEFAULT_TABLE = 'default_table';
9506 my $PSEUDO_MAP_TYPE = 'pseudo_map_type';
9507 my $MISSINGS = 'missings';
9508
99870f4d
KW
9509 sub process_generic_property_file {
9510 # This processes a file containing property mappings and puts them
9511 # into internal map tables. It should be used to handle any property
9512 # files that have mappings from a code point or range thereof to
9513 # something else. This means almost all the UCD .txt files.
9514 # each_line_handlers() should be set to adjust the lines of these
9515 # files, if necessary, to what this routine understands:
9516 #
9517 # 0374 ; NFD_QC; N
9518 # 003C..003E ; Math
9519 #
92f9d56c 9520 # the fields are: "codepoint-range ; property; map"
99870f4d
KW
9521 #
9522 # meaning the codepoints in the range all have the value 'map' under
9523 # 'property'.
98dc9551 9524 # Beginning and trailing white space in each field are not significant.
99870f4d
KW
9525 # Note there is not a trailing semi-colon in the above. A trailing
9526 # semi-colon means the map is a null-string. An omitted map, as
9527 # opposed to a null-string, is assumed to be 'Y', based on Unicode
9528 # table syntax. (This could have been hidden from this routine by
9529 # doing it in the $file object, but that would require parsing of the
9530 # line there, so would have to parse it twice, or change the interface
9531 # to pass this an array. So not done.)
9532 #
9533 # The map field may begin with a sequence of commands that apply to
9534 # this range. Each such command begins and ends with $CMD_DELIM.
9535 # These are used to indicate, for example, that the mapping for a
9536 # range has a non-default type.
9537 #
9538 # This loops through the file, calling it's next_line() method, and
9539 # then taking the map and adding it to the property's table.
9540 # Complications arise because any number of properties can be in the
9541 # file, in any order, interspersed in any way. The first time a
9542 # property is seen, it gets information about that property and
f86864ac 9543 # caches it for quick retrieval later. It also normalizes the maps
5d7f7709
KW
9544 # so that only one of many synonyms is stored. The Unicode input
9545 # files do use some multiple synonyms.
99870f4d
KW
9546
9547 my $file = shift;
9548 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
9549
9550 my %property_info; # To keep track of what properties
9551 # have already had entries in the
9552 # current file, and info about each,
9553 # so don't have to recompute.
9554 my $property_name; # property currently being worked on
9555 my $property_type; # and its type
9556 my $previous_property_name = ""; # name from last time through loop
9557 my $property_object; # pointer to the current property's
9558 # object
9559 my $property_addr; # the address of that object
9560 my $default_map; # the string that code points missing
9561 # from the file map to
9562 my $default_table; # For non-string properties, a
9563 # reference to the match table that
9564 # will contain the list of code
9565 # points that map to $default_map.
9566
9567 # Get the next real non-comment line
9568 LINE:
9569 while ($file->next_line) {
9570
9571 # Default replacement type; means that if parts of the range have
9572 # already been stored in our tables, the new map overrides them if
9573 # they differ more than cosmetically
9574 my $replace = $IF_NOT_EQUIVALENT;
9575 my $map_type; # Default type for the map of this range
9576
9577 #local $to_trace = 1 if main::DEBUG;
9578 trace $_ if main::DEBUG && $to_trace;
9579
9580 # Split the line into components
9581 my ($range, $property_name, $map, @remainder)
9582 = split /\s*;\s*/, $_, -1; # -1 => retain trailing null fields
9583
9584 # If more or less on the line than we are expecting, warn and skip
9585 # the line
9586 if (@remainder) {
9587 $file->carp_bad_line('Extra fields');
9588 next LINE;
9589 }
9590 elsif ( ! defined $property_name) {
9591 $file->carp_bad_line('Missing property');
9592 next LINE;
9593 }
9594
9595 # Examine the range.
9596 if ($range !~ /^ ($code_point_re) (?:\.\. ($code_point_re) )? $/x)
9597 {
9598 $file->carp_bad_line("Range '$range' not of the form 'CP1' or 'CP1..CP2' (where CP1,2 are code points in hex)");
9599 next LINE;
9600 }
9601 my $low = hex $1;
9602 my $high = (defined $2) ? hex $2 : $low;
9603
9604 # For the very specialized case of comparing two Unicode
9605 # versions...
9606 if (DEBUG && $compare_versions) {
9607 if ($property_name eq 'Age') {
9608
9609 # Only allow code points at least as old as the version
9610 # specified.
9611 my $age = pack "C*", split(/\./, $map); # v string
9612 next LINE if $age gt $compare_versions;
9613 }
9614 else {
9615
9616 # Again, we throw out code points younger than those of
9617 # the specified version. By now, the Age property is
9618 # populated. We use the intersection of each input range
9619 # with this property to find what code points in it are
9620 # valid. To do the intersection, we have to convert the
9621 # Age property map to a Range_list. We only have to do
9622 # this once.
9623 if (! defined $compare_versions_range_list) {
9624 my $age = property_ref('Age');
9625 if (! -e 'DAge.txt') {
9626 croak "Need to have 'DAge.txt' file to do version comparison";
9627 }
9628 elsif ($age->count == 0) {
9629 croak "The 'Age' table is empty, but its file exists";
9630 }
9631 $compare_versions_range_list
9632 = Range_List->new(Initialize => $age);
9633 }
9634
9635 # An undefined map is always 'Y'
9636 $map = 'Y' if ! defined $map;
9637
9638 # Calculate the intersection of the input range with the
9639 # code points that are known in the specified version
9640 my @ranges = ($compare_versions_range_list
9641 & Range->new($low, $high))->ranges;
9642
9643 # If the intersection is empty, throw away this range
9644 next LINE unless @ranges;
9645
9646 # Only examine the first range this time through the loop.
9647 my $this_range = shift @ranges;
9648
9649 # Put any remaining ranges in the queue to be processed
9650 # later. Note that there is unnecessary work here, as we
9651 # will do the intersection again for each of these ranges
9652 # during some future iteration of the LINE loop, but this
9653 # code is not used in production. The later intersections
9654 # are guaranteed to not splinter, so this will not become
9655 # an infinite loop.
9656 my $line = join ';', $property_name, $map;
9657 foreach my $range (@ranges) {
9658 $file->insert_adjusted_lines(sprintf("%04X..%04X; %s",
9659 $range->start,
9660 $range->end,
9661 $line));
9662 }
9663
9664 # And process the first range, like any other.
9665 $low = $this_range->start;
9666 $high = $this_range->end;
9667 }
9668 } # End of $compare_versions
9669
9670 # If changing to a new property, get the things constant per
9671 # property
9672 if ($previous_property_name ne $property_name) {
9673
9674 $property_object = property_ref($property_name);
9675 if (! defined $property_object) {
9676 $file->carp_bad_line("Unexpected property '$property_name'. Skipped");
9677 next LINE;
9678 }
051df77b 9679 { no overloading; $property_addr = pack 'J', $property_object; }
99870f4d
KW
9680
9681 # Defer changing names until have a line that is acceptable
9682 # (the 'next' statement above means is unacceptable)
9683 $previous_property_name = $property_name;
9684
9685 # If not the first time for this property, retrieve info about
9686 # it from the cache
96cfc54a
KW
9687 if (defined ($property_info{$property_addr}{$TYPE})) {
9688 $property_type = $property_info{$property_addr}{$TYPE};
9689 $default_map = $property_info{$property_addr}{$DEFAULT_MAP};
99870f4d 9690 $map_type
96cfc54a 9691 = $property_info{$property_addr}{$PSEUDO_MAP_TYPE};
99870f4d 9692 $default_table
96cfc54a 9693 = $property_info{$property_addr}{$DEFAULT_TABLE};
99870f4d
KW
9694 }
9695 else {
9696
9697 # Here, is the first time for this property. Set up the
9698 # cache.
96cfc54a 9699 $property_type = $property_info{$property_addr}{$TYPE}
99870f4d
KW
9700 = $property_object->type;
9701 $map_type
96cfc54a 9702 = $property_info{$property_addr}{$PSEUDO_MAP_TYPE}
99870f4d
KW
9703 = $property_object->pseudo_map_type;
9704
9705 # The Unicode files are set up so that if the map is not
9706 # defined, it is a binary property
9707 if (! defined $map && $property_type != $BINARY) {
9708 if ($property_type != $UNKNOWN
9709 && $property_type != $NON_STRING)
9710 {
9711 $file->carp_bad_line("No mapping defined on a non-binary property. Using 'Y' for the map");
9712 }
9713 else {
9714 $property_object->set_type($BINARY);
9715 $property_type
96cfc54a 9716 = $property_info{$property_addr}{$TYPE}
99870f4d
KW
9717 = $BINARY;
9718 }
9719 }
9720
9721 # Get any @missings default for this property. This
9722 # should precede the first entry for the property in the
9723 # input file, and is located in a comment that has been
9724 # stored by the Input_file class until we access it here.
9725 # It's possible that there is more than one such line
9726 # waiting for us; collect them all, and parse
9727 my @missings_list = $file->get_missings
9728 if $file->has_missings_defaults;
9729 foreach my $default_ref (@missings_list) {
9730 my $default = $default_ref->[0];
ffe43484 9731 my $addr = do { no overloading; pack 'J', property_ref($default_ref->[1]); };
99870f4d
KW
9732
9733 # For string properties, the default is just what the
9734 # file says, but non-string properties should already
9735 # have set up a table for the default property value;
9736 # use the table for these, so can resolve synonyms
9737 # later to a single standard one.
9738 if ($property_type == $STRING
9739 || $property_type == $UNKNOWN)
9740 {
96cfc54a 9741 $property_info{$addr}{$MISSINGS} = $default;
99870f4d
KW
9742 }
9743 else {
96cfc54a 9744 $property_info{$addr}{$MISSINGS}
99870f4d
KW
9745 = $property_object->table($default);
9746 }
9747 }
9748
9749 # Finished storing all the @missings defaults in the input
9750 # file so far. Get the one for the current property.
96cfc54a 9751 my $missings = $property_info{$property_addr}{$MISSINGS};
99870f4d
KW
9752
9753 # But we likely have separately stored what the default
9754 # should be. (This is to accommodate versions of the
9755 # standard where the @missings lines are absent or
9756 # incomplete.) Hopefully the two will match. But check
9757 # it out.
9758 $default_map = $property_object->default_map;
9759
9760 # If the map is a ref, it means that the default won't be
9761 # processed until later, so undef it, so next few lines
9762 # will redefine it to something that nothing will match
9763 undef $default_map if ref $default_map;
9764
9765 # Create a $default_map if don't have one; maybe a dummy
9766 # that won't match anything.
9767 if (! defined $default_map) {
9768
9769 # Use any @missings line in the file.
9770 if (defined $missings) {
9771 if (ref $missings) {
9772 $default_map = $missings->full_name;
9773 $default_table = $missings;
9774 }
9775 else {
9776 $default_map = $missings;
9777 }
678f13d5 9778
99870f4d
KW
9779 # And store it with the property for outside use.
9780 $property_object->set_default_map($default_map);
9781 }
9782 else {
9783
9784 # Neither an @missings nor a default map. Create
9785 # a dummy one, so won't have to test definedness
9786 # in the main loop.
9787 $default_map = '_Perl This will never be in a file
9788 from Unicode';
9789 }
9790 }
9791
9792 # Here, we have $default_map defined, possibly in terms of
9793 # $missings, but maybe not, and possibly is a dummy one.
9794 if (defined $missings) {
9795
9796 # Make sure there is no conflict between the two.
9797 # $missings has priority.
9798 if (ref $missings) {
23e33b60
KW
9799 $default_table
9800 = $property_object->table($default_map);
99870f4d
KW
9801 if (! defined $default_table
9802 || $default_table != $missings)
9803 {
9804 if (! defined $default_table) {
9805 $default_table = $UNDEF;
9806 }
9807 $file->carp_bad_line(<<END
9808The \@missings line for $property_name in $file says that missings default to
9809$missings, but we expect it to be $default_table. $missings used.
9810END
9811 );
9812 $default_table = $missings;
9813 $default_map = $missings->full_name;
9814 }
96cfc54a 9815 $property_info{$property_addr}{$DEFAULT_TABLE}
99870f4d
KW
9816 = $default_table;
9817 }
9818 elsif ($default_map ne $missings) {
9819 $file->carp_bad_line(<<END
9820The \@missings line for $property_name in $file says that missings default to
9821$missings, but we expect it to be $default_map. $missings used.
9822END
9823 );
9824 $default_map = $missings;
9825 }
9826 }
9827
96cfc54a 9828 $property_info{$property_addr}{$DEFAULT_MAP}
99870f4d
KW
9829 = $default_map;
9830
9831 # If haven't done so already, find the table corresponding
9832 # to this map for non-string properties.
9833 if (! defined $default_table
9834 && $property_type != $STRING
9835 && $property_type != $UNKNOWN)
9836 {
9837 $default_table = $property_info{$property_addr}
96cfc54a 9838 {$DEFAULT_TABLE}
99870f4d
KW
9839 = $property_object->table($default_map);
9840 }
9841 } # End of is first time for this property
9842 } # End of switching properties.
9843
9844 # Ready to process the line.
9845 # The Unicode files are set up so that if the map is not defined,
9846 # it is a binary property with value 'Y'
9847 if (! defined $map) {
9848 $map = 'Y';
9849 }
9850 else {
9851
9852 # If the map begins with a special command to us (enclosed in
9853 # delimiters), extract the command(s).
a35d7f90
KW
9854 while ($map =~ s/ ^ $CMD_DELIM (.*?) $CMD_DELIM //x) {
9855 my $command = $1;
9856 if ($command =~ / ^ $REPLACE_CMD= (.*) /x) {
9857 $replace = $1;
99870f4d 9858 }
a35d7f90
KW
9859 elsif ($command =~ / ^ $MAP_TYPE_CMD= (.*) /x) {
9860 $map_type = $1;
9861 }
9862 else {
9863 $file->carp_bad_line("Unknown command line: '$1'");
9864 next LINE;
9865 }
9866 }
99870f4d
KW
9867 }
9868
9869 if ($default_map eq $CODE_POINT && $map =~ / ^ $code_point_re $/x)
9870 {
9871
9872 # Here, we have a map to a particular code point, and the
9873 # default map is to a code point itself. If the range
9874 # includes the particular code point, change that portion of
9875 # the range to the default. This makes sure that in the final
9876 # table only the non-defaults are listed.
9877 my $decimal_map = hex $map;
9878 if ($low <= $decimal_map && $decimal_map <= $high) {
9879
9880 # If the range includes stuff before or after the map
9881 # we're changing, split it and process the split-off parts
9882 # later.
9883 if ($low < $decimal_map) {
9884 $file->insert_adjusted_lines(
9885 sprintf("%04X..%04X; %s; %s",
9886 $low,
9887 $decimal_map - 1,
9888 $property_name,
9889 $map));
9890 }
9891 if ($high > $decimal_map) {
9892 $file->insert_adjusted_lines(
9893 sprintf("%04X..%04X; %s; %s",
9894 $decimal_map + 1,
9895 $high,
9896 $property_name,
9897 $map));
9898 }
9899 $low = $high = $decimal_map;
9900 $map = $CODE_POINT;
9901 }
9902 }
9903
9904 # If we can tell that this is a synonym for the default map, use
9905 # the default one instead.
9906 if ($property_type != $STRING
9907 && $property_type != $UNKNOWN)
9908 {
9909 my $table = $property_object->table($map);
9910 if (defined $table && $table == $default_table) {
9911 $map = $default_map;
9912 }
9913 }
9914
9915 # And figure out the map type if not known.
9916 if (! defined $map_type || $map_type == $COMPUTE_NO_MULTI_CP) {
9917 if ($map eq "") { # Nulls are always $NULL map type
9918 $map_type = $NULL;
9919 } # Otherwise, non-strings, and those that don't allow
9920 # $MULTI_CP, and those that aren't multiple code points are
9921 # 0
9922 elsif
9923 (($property_type != $STRING && $property_type != $UNKNOWN)
9924 || (defined $map_type && $map_type == $COMPUTE_NO_MULTI_CP)
9925 || $map !~ /^ $code_point_re ( \ $code_point_re )+ $ /x)
9926 {
9927 $map_type = 0;
9928 }
9929 else {
9930 $map_type = $MULTI_CP;
9931 }
9932 }
9933
9934 $property_object->add_map($low, $high,
9935 $map,
9936 Type => $map_type,
9937 Replace => $replace);
9938 } # End of loop through file's lines
9939
9940 return;
9941 }
9942}
9943
99870f4d
KW
9944{ # Closure for UnicodeData.txt handling
9945
9946 # This file was the first one in the UCD; its design leads to some
9947 # awkwardness in processing. Here is a sample line:
9948 # 0041;LATIN CAPITAL LETTER A;Lu;0;L;;;;;N;;;;0061;
9949 # The fields in order are:
9950 my $i = 0; # The code point is in field 0, and is shifted off.
28093d0e 9951 my $CHARNAME = $i++; # character name (e.g. "LATIN CAPITAL LETTER A")
99870f4d
KW
9952 my $CATEGORY = $i++; # category (e.g. "Lu")
9953 my $CCC = $i++; # Canonical combining class (e.g. "230")
9954 my $BIDI = $i++; # directional class (e.g. "L")
9955 my $PERL_DECOMPOSITION = $i++; # decomposition mapping
9956 my $PERL_DECIMAL_DIGIT = $i++; # decimal digit value
9957 my $NUMERIC_TYPE_OTHER_DIGIT = $i++; # digit value, like a superscript
9958 # Dual-use in this program; see below
9959 my $NUMERIC = $i++; # numeric value
9960 my $MIRRORED = $i++; # ? mirrored
9961 my $UNICODE_1_NAME = $i++; # name in Unicode 1.0
9962 my $COMMENT = $i++; # iso comment
9963 my $UPPER = $i++; # simple uppercase mapping
9964 my $LOWER = $i++; # simple lowercase mapping
9965 my $TITLE = $i++; # simple titlecase mapping
9966 my $input_field_count = $i;
9967
9968 # This routine in addition outputs these extra fields:
d59563d0 9969
99870f4d 9970 my $DECOMP_TYPE = $i++; # Decomposition type
28093d0e
KW
9971
9972 # These fields are modifications of ones above, and are usually
9973 # suppressed; they must come last, as for speed, the loop upper bound is
9974 # normally set to ignore them
9975 my $NAME = $i++; # This is the strict name field, not the one that
9976 # charnames uses.
9977 my $DECOMP_MAP = $i++; # Strict decomposition mapping; not the one used
9978 # by Unicode::Normalize
99870f4d
KW
9979 my $last_field = $i - 1;
9980
9981 # All these are read into an array for each line, with the indices defined
9982 # above. The empty fields in the example line above indicate that the
9983 # value is defaulted. The handler called for each line of the input
9984 # changes these to their defaults.
9985
9986 # Here are the official names of the properties, in a parallel array:
9987 my @field_names;
9988 $field_names[$BIDI] = 'Bidi_Class';
9989 $field_names[$CATEGORY] = 'General_Category';
9990 $field_names[$CCC] = 'Canonical_Combining_Class';
28093d0e 9991 $field_names[$CHARNAME] = 'Perl_Charnames';
99870f4d
KW
9992 $field_names[$COMMENT] = 'ISO_Comment';
9993 $field_names[$DECOMP_MAP] = 'Decomposition_Mapping';
9994 $field_names[$DECOMP_TYPE] = 'Decomposition_Type';
959ce5bf 9995 $field_names[$LOWER] = 'Lowercase_Mapping';
99870f4d
KW
9996 $field_names[$MIRRORED] = 'Bidi_Mirrored';
9997 $field_names[$NAME] = 'Name';
9998 $field_names[$NUMERIC] = 'Numeric_Value';
9999 $field_names[$NUMERIC_TYPE_OTHER_DIGIT] = 'Numeric_Type';
10000 $field_names[$PERL_DECIMAL_DIGIT] = 'Perl_Decimal_Digit';
10001 $field_names[$PERL_DECOMPOSITION] = 'Perl_Decomposition_Mapping';
959ce5bf 10002 $field_names[$TITLE] = 'Titlecase_Mapping';
99870f4d 10003 $field_names[$UNICODE_1_NAME] = 'Unicode_1_Name';
959ce5bf 10004 $field_names[$UPPER] = 'Uppercase_Mapping';
99870f4d 10005
28093d0e
KW
10006 # Some of these need a little more explanation:
10007 # The $PERL_DECIMAL_DIGIT field does not lead to an official Unicode
10008 # property, but is used in calculating the Numeric_Type. Perl however,
10009 # creates a file from this field, so a Perl property is created from it.
10010 # Similarly, the Other_Digit field is used only for calculating the
10011 # Numeric_Type, and so it can be safely re-used as the place to store
10012 # the value for Numeric_Type; hence it is referred to as
10013 # $NUMERIC_TYPE_OTHER_DIGIT.
10014 # The input field named $PERL_DECOMPOSITION is a combination of both the
10015 # decomposition mapping and its type. Perl creates a file containing
10016 # exactly this field, so it is used for that. The two properties are
10017 # separated into two extra output fields, $DECOMP_MAP and $DECOMP_TYPE.
10018 # $DECOMP_MAP is usually suppressed (unless the lists are changed to
10019 # output it), as Perl doesn't use it directly.
10020 # The input field named here $CHARNAME is used to construct the
10021 # Perl_Charnames property, which is a combination of the Name property
10022 # (which the input field contains), and the Unicode_1_Name property, and
10023 # others from other files. Since, the strict Name property is not used
10024 # by Perl, this field is used for the table that Perl does use. The
10025 # strict Name property table is usually suppressed (unless the lists are
10026 # changed to output it), so it is accumulated in a separate field,
10027 # $NAME, which to save time is discarded unless the table is actually to
10028 # be output
99870f4d
KW
10029
10030 # This file is processed like most in this program. Control is passed to
10031 # process_generic_property_file() which calls filter_UnicodeData_line()
10032 # for each input line. This filter converts the input into line(s) that
10033 # process_generic_property_file() understands. There is also a setup
10034 # routine called before any of the file is processed, and a handler for
10035 # EOF processing, all in this closure.
10036
10037 # A huge speed-up occurred at the cost of some added complexity when these
10038 # routines were altered to buffer the outputs into ranges. Almost all the
10039 # lines of the input file apply to just one code point, and for most
10040 # properties, the map for the next code point up is the same as the
10041 # current one. So instead of creating a line for each property for each
10042 # input line, filter_UnicodeData_line() remembers what the previous map
10043 # of a property was, and doesn't generate a line to pass on until it has
10044 # to, as when the map changes; and that passed-on line encompasses the
10045 # whole contiguous range of code points that have the same map for that
10046 # property. This means a slight amount of extra setup, and having to
10047 # flush these buffers on EOF, testing if the maps have changed, plus
10048 # remembering state information in the closure. But it means a lot less
10049 # real time in not having to change the data base for each property on
10050 # each line.
10051
10052 # Another complication is that there are already a few ranges designated
10053 # in the input. There are two lines for each, with the same maps except
10054 # the code point and name on each line. This was actually the hardest
10055 # thing to design around. The code points in those ranges may actually
10056 # have real maps not given by these two lines. These maps will either
56339b2c 10057 # be algorithmically determinable, or be in the extracted files furnished
99870f4d
KW
10058 # with the UCD. In the event of conflicts between these extracted files,
10059 # and this one, Unicode says that this one prevails. But it shouldn't
10060 # prevail for conflicts that occur in these ranges. The data from the
10061 # extracted files prevails in those cases. So, this program is structured
10062 # so that those files are processed first, storing maps. Then the other
10063 # files are processed, generally overwriting what the extracted files
10064 # stored. But just the range lines in this input file are processed
10065 # without overwriting. This is accomplished by adding a special string to
10066 # the lines output to tell process_generic_property_file() to turn off the
10067 # overwriting for just this one line.
10068 # A similar mechanism is used to tell it that the map is of a non-default
10069 # type.
10070
10071 sub setup_UnicodeData { # Called before any lines of the input are read
10072 my $file = shift;
10073 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
10074
28093d0e
KW
10075 # Create a new property specially located that is a combination of the
10076 # various Name properties: Name, Unicode_1_Name, Named Sequences, and
10077 # Name_Alias properties. (The final duplicates elements of the
10078 # first.) A comment for it will later be constructed based on the
10079 # actual properties present and used
3e20195b 10080 $perl_charname = Property->new('Perl_Charnames',
28093d0e
KW
10081 Default_Map => "",
10082 Directory => File::Spec->curdir(),
10083 File => 'Name',
301ba948 10084 Fate => $INTERNAL_ONLY,
28093d0e 10085 Perl_Extension => 1,
b1c167a3 10086 Range_Size_1 => \&output_perl_charnames_line,
28093d0e
KW
10087 Type => $STRING,
10088 );
9ba5575c 10089 $perl_charname->set_proxy_for('Name');
28093d0e 10090
99870f4d 10091 my $Perl_decomp = Property->new('Perl_Decomposition_Mapping',
517956bf 10092 Directory => File::Spec->curdir(),
99870f4d 10093 File => 'Decomposition',
a14f3cb1 10094 Format => $DECOMP_STRING_FORMAT,
301ba948 10095 Fate => $INTERNAL_ONLY,
99870f4d
KW
10096 Perl_Extension => 1,
10097 Default_Map => $CODE_POINT,
10098
0c07e538
KW
10099 # normalize.pm can't cope with these
10100 Output_Range_Counts => 0,
10101
99870f4d
KW
10102 # This is a specially formatted table
10103 # explicitly for normalize.pm, which
10104 # is expecting a particular format,
10105 # which means that mappings containing
10106 # multiple code points are in the main
10107 # body of the table
10108 Map_Type => $COMPUTE_NO_MULTI_CP,
10109 Type => $STRING,
f64b46a1 10110 To_Output_Map => $INTERNAL_MAP,
99870f4d 10111 );
5be997b0 10112 $Perl_decomp->set_proxy_for('Decomposition_Mapping', 'Decomposition_Type');
99870f4d
KW
10113 $Perl_decomp->add_comment(join_lines(<<END
10114This mapping is a combination of the Unicode 'Decomposition_Type' and
10115'Decomposition_Mapping' properties, formatted for use by normalize.pm. It is
8d6427a5 10116identical to the official Unicode 'Decomposition_Mapping' property except for
99870f4d
KW
10117two things:
10118 1) It omits the algorithmically determinable Hangul syllable decompositions,
10119which normalize.pm handles algorithmically.
10120 2) It contains the decomposition type as well. Non-canonical decompositions
10121begin with a word in angle brackets, like <super>, which denotes the
10122compatible decomposition type. If the map does not begin with the <angle
10123brackets>, the decomposition is canonical.
10124END
10125 ));
10126
10127 my $Decimal_Digit = Property->new("Perl_Decimal_Digit",
10128 Default_Map => "",
10129 Perl_Extension => 1,
99870f4d
KW
10130 Directory => $map_directory,
10131 Type => $STRING,
b0b13ada 10132 To_Output_Map => $OUTPUT_DELTAS,
99870f4d
KW
10133 );
10134 $Decimal_Digit->add_comment(join_lines(<<END
10135This file gives the mapping of all code points which represent a single
b0b13ada
KW
10136decimal digit [0-9] to their respective digits, but it uses a delta to
10137make the table significantly smaller. For example, the code point U+0031 (an
10138ASCII '1') is mapped to a numeric "-48", because 0x31 = 49, and 49 + -48 = 1.
10139These code points are those that have Numeric_Type=Decimal; not special
10140things, like subscripts nor Roman numerals.
99870f4d
KW
10141END
10142 ));
10143
28093d0e
KW
10144 # These properties are not used for generating anything else, and are
10145 # usually not output. By making them last in the list, we can just
99870f4d 10146 # change the high end of the loop downwards to avoid the work of
28093d0e
KW
10147 # generating a table(s) that is/are just going to get thrown away.
10148 if (! property_ref('Decomposition_Mapping')->to_output_map
10149 && ! property_ref('Name')->to_output_map)
10150 {
10151 $last_field = min($NAME, $DECOMP_MAP) - 1;
10152 } elsif (property_ref('Decomposition_Mapping')->to_output_map) {
10153 $last_field = $DECOMP_MAP;
10154 } elsif (property_ref('Name')->to_output_map) {
10155 $last_field = $NAME;
99870f4d
KW
10156 }
10157 return;
10158 }
10159
10160 my $first_time = 1; # ? Is this the first line of the file
10161 my $in_range = 0; # ? Are we in one of the file's ranges
10162 my $previous_cp; # hex code point of previous line
10163 my $decimal_previous_cp = -1; # And its decimal equivalent
10164 my @start; # For each field, the current starting
10165 # code point in hex for the range
10166 # being accumulated.
10167 my @fields; # The input fields;
10168 my @previous_fields; # And those from the previous call
10169
10170 sub filter_UnicodeData_line {
10171 # Handle a single input line from UnicodeData.txt; see comments above
10172 # Conceptually this takes a single line from the file containing N
10173 # properties, and converts it into N lines with one property per line,
10174 # which is what the final handler expects. But there are
10175 # complications due to the quirkiness of the input file, and to save
10176 # time, it accumulates ranges where the property values don't change
10177 # and only emits lines when necessary. This is about an order of
10178 # magnitude fewer lines emitted.
10179
10180 my $file = shift;
10181 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
10182
10183 # $_ contains the input line.
10184 # -1 in split means retain trailing null fields
10185 (my $cp, @fields) = split /\s*;\s*/, $_, -1;
10186
10187 #local $to_trace = 1 if main::DEBUG;
10188 trace $cp, @fields , $input_field_count if main::DEBUG && $to_trace;
10189 if (@fields > $input_field_count) {
10190 $file->carp_bad_line('Extra fields');
10191 $_ = "";
10192 return;
10193 }
10194
10195 my $decimal_cp = hex $cp;
10196
10197 # We have to output all the buffered ranges when the next code point
10198 # is not exactly one after the previous one, which means there is a
10199 # gap in the ranges.
10200 my $force_output = ($decimal_cp != $decimal_previous_cp + 1);
10201
10202 # The decomposition mapping field requires special handling. It looks
10203 # like either:
10204 #
10205 # <compat> 0032 0020
10206 # 0041 0300
10207 #
10208 # The decomposition type is enclosed in <brackets>; if missing, it
10209 # means the type is canonical. There are two decomposition mapping
10210 # tables: the one for use by Perl's normalize.pm has a special format
10211 # which is this field intact; the other, for general use is of
10212 # standard format. In either case we have to find the decomposition
10213 # type. Empty fields have None as their type, and map to the code
10214 # point itself
10215 if ($fields[$PERL_DECOMPOSITION] eq "") {
10216 $fields[$DECOMP_TYPE] = 'None';
10217 $fields[$DECOMP_MAP] = $fields[$PERL_DECOMPOSITION] = $CODE_POINT;
10218 }
10219 else {
10220 ($fields[$DECOMP_TYPE], my $map) = $fields[$PERL_DECOMPOSITION]
10221 =~ / < ( .+? ) > \s* ( .+ ) /x;
10222 if (! defined $fields[$DECOMP_TYPE]) {
10223 $fields[$DECOMP_TYPE] = 'Canonical';
10224 $fields[$DECOMP_MAP] = $fields[$PERL_DECOMPOSITION];
10225 }
10226 else {
10227 $fields[$DECOMP_MAP] = $map;
10228 }
10229 }
10230
10231 # The 3 numeric fields also require special handling. The 2 digit
10232 # fields must be either empty or match the number field. This means
10233 # that if it is empty, they must be as well, and the numeric type is
10234 # None, and the numeric value is 'Nan'.
10235 # The decimal digit field must be empty or match the other digit
10236 # field. If the decimal digit field is non-empty, the code point is
10237 # a decimal digit, and the other two fields will have the same value.
10238 # If it is empty, but the other digit field is non-empty, the code
10239 # point is an 'other digit', and the number field will have the same
10240 # value as the other digit field. If the other digit field is empty,
10241 # but the number field is non-empty, the code point is a generic
10242 # numeric type.
10243 if ($fields[$NUMERIC] eq "") {
10244 if ($fields[$PERL_DECIMAL_DIGIT] ne ""
10245 || $fields[$NUMERIC_TYPE_OTHER_DIGIT] ne ""
10246 ) {
10247 $file->carp_bad_line("Numeric values inconsistent. Trying to process anyway");
10248 }
10249 $fields[$NUMERIC_TYPE_OTHER_DIGIT] = 'None';
10250 $fields[$NUMERIC] = 'NaN';
10251 }
10252 else {
10253 $file->carp_bad_line("'$fields[$NUMERIC]' should be a whole or rational number. Processing as if it were") if $fields[$NUMERIC] !~ qr{ ^ -? \d+ ( / \d+ )? $ }x;
10254 if ($fields[$PERL_DECIMAL_DIGIT] ne "") {
10255 $file->carp_bad_line("$fields[$PERL_DECIMAL_DIGIT] should equal $fields[$NUMERIC]. Processing anyway") if $fields[$PERL_DECIMAL_DIGIT] != $fields[$NUMERIC];
10256 $fields[$NUMERIC_TYPE_OTHER_DIGIT] = 'Decimal';
10257 }
10258 elsif ($fields[$NUMERIC_TYPE_OTHER_DIGIT] ne "") {
10259 $file->carp_bad_line("$fields[$NUMERIC_TYPE_OTHER_DIGIT] should equal $fields[$NUMERIC]. Processing anyway") if $fields[$NUMERIC_TYPE_OTHER_DIGIT] != $fields[$NUMERIC];
10260 $fields[$NUMERIC_TYPE_OTHER_DIGIT] = 'Digit';
10261 }
10262 else {
10263 $fields[$NUMERIC_TYPE_OTHER_DIGIT] = 'Numeric';
10264
10265 # Rationals require extra effort.
10266 register_fraction($fields[$NUMERIC])
10267 if $fields[$NUMERIC] =~ qr{/};
10268 }
10269 }
10270
10271 # For the properties that have empty fields in the file, and which
10272 # mean something different from empty, change them to that default.
10273 # Certain fields just haven't been empty so far in any Unicode
10274 # version, so don't look at those, namely $MIRRORED, $BIDI, $CCC,
10275 # $CATEGORY. This leaves just the two fields, and so we hard-code in
c1739a4a 10276 # the defaults; which are very unlikely to ever change.
99870f4d
KW
10277 $fields[$UPPER] = $CODE_POINT if $fields[$UPPER] eq "";
10278 $fields[$LOWER] = $CODE_POINT if $fields[$LOWER] eq "";
10279
10280 # UAX44 says that if title is empty, it is the same as whatever upper
10281 # is,
10282 $fields[$TITLE] = $fields[$UPPER] if $fields[$TITLE] eq "";
10283
10284 # There are a few pairs of lines like:
10285 # AC00;<Hangul Syllable, First>;Lo;0;L;;;;;N;;;;;
10286 # D7A3;<Hangul Syllable, Last>;Lo;0;L;;;;;N;;;;;
10287 # that define ranges. These should be processed after the fields are
10288 # adjusted above, as they may override some of them; but mostly what
28093d0e 10289 # is left is to possibly adjust the $CHARNAME field. The names of all the
99870f4d
KW
10290 # paired lines start with a '<', but this is also true of '<control>,
10291 # which isn't one of these special ones.
28093d0e 10292 if ($fields[$CHARNAME] eq '<control>') {
99870f4d
KW
10293
10294 # Some code points in this file have the pseudo-name
10295 # '<control>', but the official name for such ones is the null
28093d0e 10296 # string. For charnames.pm, we use the Unicode version 1 name
99870f4d 10297 $fields[$NAME] = "";
28093d0e 10298 $fields[$CHARNAME] = $fields[$UNICODE_1_NAME];
99870f4d
KW
10299
10300 # We had better not be in between range lines.
10301 if ($in_range) {
28093d0e 10302 $file->carp_bad_line("Expecting a closing range line, not a $fields[$CHARNAME]'. Trying anyway");
99870f4d
KW
10303 $in_range = 0;
10304 }
10305 }
28093d0e 10306 elsif (substr($fields[$CHARNAME], 0, 1) ne '<') {
99870f4d
KW
10307
10308 # Here is a non-range line. We had better not be in between range
10309 # lines.
10310 if ($in_range) {
28093d0e 10311 $file->carp_bad_line("Expecting a closing range line, not a $fields[$CHARNAME]'. Trying anyway");
99870f4d
KW
10312 $in_range = 0;
10313 }
edb80b88
KW
10314 if ($fields[$CHARNAME] =~ s/- $cp $//x) {
10315
10316 # These are code points whose names end in their code points,
10317 # which means the names are algorithmically derivable from the
10318 # code points. To shorten the output Name file, the algorithm
10319 # for deriving these is placed in the file instead of each
10320 # code point, so they have map type $CP_IN_NAME
10321 $fields[$CHARNAME] = $CMD_DELIM
10322 . $MAP_TYPE_CMD
10323 . '='
10324 . $CP_IN_NAME
10325 . $CMD_DELIM
10326 . $fields[$CHARNAME];
10327 }
28093d0e 10328 $fields[$NAME] = $fields[$CHARNAME];
99870f4d 10329 }
28093d0e
KW
10330 elsif ($fields[$CHARNAME] =~ /^<(.+), First>$/) {
10331 $fields[$CHARNAME] = $fields[$NAME] = $1;
99870f4d
KW
10332
10333 # Here we are at the beginning of a range pair.
10334 if ($in_range) {
28093d0e 10335 $file->carp_bad_line("Expecting a closing range line, not a beginning one, $fields[$CHARNAME]'. Trying anyway");
99870f4d
KW
10336 }
10337 $in_range = 1;
10338
10339 # Because the properties in the range do not overwrite any already
10340 # in the db, we must flush the buffers of what's already there, so
10341 # they get handled in the normal scheme.
10342 $force_output = 1;
10343
10344 }
28093d0e
KW
10345 elsif ($fields[$CHARNAME] !~ s/^<(.+), Last>$/$1/) {
10346 $file->carp_bad_line("Unexpected name starting with '<' $fields[$CHARNAME]. Ignoring this line.");
99870f4d
KW
10347 $_ = "";
10348 return;
10349 }
10350 else { # Here, we are at the last line of a range pair.
10351
10352 if (! $in_range) {
28093d0e 10353 $file->carp_bad_line("Unexpected end of range $fields[$CHARNAME] when not in one. Ignoring this line.");
99870f4d
KW
10354 $_ = "";
10355 return;
10356 }
10357 $in_range = 0;
10358
28093d0e
KW
10359 $fields[$NAME] = $fields[$CHARNAME];
10360
99870f4d
KW
10361 # Check that the input is valid: that the closing of the range is
10362 # the same as the beginning.
10363 foreach my $i (0 .. $last_field) {
10364 next if $fields[$i] eq $previous_fields[$i];
10365 $file->carp_bad_line("Expecting '$fields[$i]' to be the same as '$previous_fields[$i]'. Bad News. Trying anyway");
10366 }
10367
10368 # The processing differs depending on the type of range,
28093d0e
KW
10369 # determined by its $CHARNAME
10370 if ($fields[$CHARNAME] =~ /^Hangul Syllable/) {
99870f4d
KW
10371
10372 # Check that the data looks right.
10373 if ($decimal_previous_cp != $SBase) {
10374 $file->carp_bad_line("Unexpected Hangul syllable start = $previous_cp. Bad News. Results will be wrong");
10375 }
10376 if ($decimal_cp != $SBase + $SCount - 1) {
10377 $file->carp_bad_line("Unexpected Hangul syllable end = $cp. Bad News. Results will be wrong");
10378 }
10379
10380 # The Hangul syllable range has a somewhat complicated name
10381 # generation algorithm. Each code point in it has a canonical
10382 # decomposition also computable by an algorithm. The
10383 # perl decomposition map table built from these is used only
10384 # by normalize.pm, which has the algorithm built in it, so the
10385 # decomposition maps are not needed, and are large, so are
10386 # omitted from it. If the full decomposition map table is to
10387 # be output, the decompositions are generated for it, in the
10388 # EOF handling code for this input file.
10389
10390 $previous_fields[$DECOMP_TYPE] = 'Canonical';
10391
10392 # This range is stored in our internal structure with its
10393 # own map type, different from all others.
28093d0e
KW
10394 $previous_fields[$CHARNAME] = $previous_fields[$NAME]
10395 = $CMD_DELIM
99870f4d
KW
10396 . $MAP_TYPE_CMD
10397 . '='
10398 . $HANGUL_SYLLABLE
10399 . $CMD_DELIM
28093d0e 10400 . $fields[$CHARNAME];
99870f4d 10401 }
28093d0e 10402 elsif ($fields[$CHARNAME] =~ /^CJK/) {
99870f4d
KW
10403
10404 # The name for these contains the code point itself, and all
10405 # are defined to have the same base name, regardless of what
10406 # is in the file. They are stored in our internal structure
10407 # with a map type of $CP_IN_NAME
28093d0e
KW
10408 $previous_fields[$CHARNAME] = $previous_fields[$NAME]
10409 = $CMD_DELIM
99870f4d
KW
10410 . $MAP_TYPE_CMD
10411 . '='
10412 . $CP_IN_NAME
10413 . $CMD_DELIM
10414 . 'CJK UNIFIED IDEOGRAPH';
10415
10416 }
10417 elsif ($fields[$CATEGORY] eq 'Co'
10418 || $fields[$CATEGORY] eq 'Cs')
10419 {
10420 # The names of all the code points in these ranges are set to
10421 # null, as there are no names for the private use and
10422 # surrogate code points.
10423
28093d0e 10424 $previous_fields[$CHARNAME] = $previous_fields[$NAME] = "";
99870f4d
KW
10425 }
10426 else {
28093d0e 10427 $file->carp_bad_line("Unexpected code point range $fields[$CHARNAME] because category is $fields[$CATEGORY]. Attempting to process it.");
99870f4d
KW
10428 }
10429
10430 # The first line of the range caused everything else to be output,
10431 # and then its values were stored as the beginning values for the
10432 # next set of ranges, which this one ends. Now, for each value,
10433 # add a command to tell the handler that these values should not
10434 # replace any existing ones in our database.
10435 foreach my $i (0 .. $last_field) {
10436 $previous_fields[$i] = $CMD_DELIM
10437 . $REPLACE_CMD
10438 . '='
10439 . $NO
10440 . $CMD_DELIM
10441 . $previous_fields[$i];
10442 }
10443
10444 # And change things so it looks like the entire range has been
10445 # gone through with this being the final part of it. Adding the
10446 # command above to each field will cause this range to be flushed
10447 # during the next iteration, as it guaranteed that the stored
10448 # field won't match whatever value the next one has.
10449 $previous_cp = $cp;
10450 $decimal_previous_cp = $decimal_cp;
10451
10452 # We are now set up for the next iteration; so skip the remaining
10453 # code in this subroutine that does the same thing, but doesn't
10454 # know about these ranges.
10455 $_ = "";
c1739a4a 10456
99870f4d
KW
10457 return;
10458 }
10459
10460 # On the very first line, we fake it so the code below thinks there is
10461 # nothing to output, and initialize so that when it does get output it
10462 # uses the first line's values for the lowest part of the range.
10463 # (One could avoid this by using peek(), but then one would need to
10464 # know the adjustments done above and do the same ones in the setup
10465 # routine; not worth it)
10466 if ($first_time) {
10467 $first_time = 0;
10468 @previous_fields = @fields;
10469 @start = ($cp) x scalar @fields;
10470 $decimal_previous_cp = $decimal_cp - 1;
10471 }
10472
10473 # For each field, output the stored up ranges that this code point
10474 # doesn't fit in. Earlier we figured out if all ranges should be
10475 # terminated because of changing the replace or map type styles, or if
10476 # there is a gap between this new code point and the previous one, and
10477 # that is stored in $force_output. But even if those aren't true, we
10478 # need to output the range if this new code point's value for the
10479 # given property doesn't match the stored range's.
10480 #local $to_trace = 1 if main::DEBUG;
10481 foreach my $i (0 .. $last_field) {
10482 my $field = $fields[$i];
10483 if ($force_output || $field ne $previous_fields[$i]) {
10484
10485 # Flush the buffer of stored values.
10486 $file->insert_adjusted_lines("$start[$i]..$previous_cp; $field_names[$i]; $previous_fields[$i]");
10487
10488 # Start a new range with this code point and its value
10489 $start[$i] = $cp;
10490 $previous_fields[$i] = $field;
10491 }
10492 }
10493
10494 # Set the values for the next time.
10495 $previous_cp = $cp;
10496 $decimal_previous_cp = $decimal_cp;
10497
10498 # The input line has generated whatever adjusted lines are needed, and
10499 # should not be looked at further.
10500 $_ = "";
10501 return;
10502 }
10503
10504 sub EOF_UnicodeData {
10505 # Called upon EOF to flush the buffers, and create the Hangul
10506 # decomposition mappings if needed.
10507
10508 my $file = shift;
10509 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
10510
10511 # Flush the buffers.
10512 foreach my $i (1 .. $last_field) {
10513 $file->insert_adjusted_lines("$start[$i]..$previous_cp; $field_names[$i]; $previous_fields[$i]");
10514 }
10515
10516 if (-e 'Jamo.txt') {
10517
10518 # The algorithm is published by Unicode, based on values in
10519 # Jamo.txt, (which should have been processed before this
10520 # subroutine), and the results left in %Jamo
10521 unless (%Jamo) {
10522 Carp::my_carp_bug("Jamo.txt should be processed before Unicode.txt. Hangul syllables not generated.");
10523 return;
10524 }
10525
10526 # If the full decomposition map table is being output, insert
10527 # into it the Hangul syllable mappings. This is to avoid having
10528 # to publish a subroutine in it to compute them. (which would
10529 # essentially be this code.) This uses the algorithm published by
10530 # Unicode.
10531 if (property_ref('Decomposition_Mapping')->to_output_map) {
10532 for (my $S = $SBase; $S < $SBase + $SCount; $S++) {
10533 use integer;
10534 my $SIndex = $S - $SBase;
10535 my $L = $LBase + $SIndex / $NCount;
10536 my $V = $VBase + ($SIndex % $NCount) / $TCount;
10537 my $T = $TBase + $SIndex % $TCount;
10538
10539 trace "L=$L, V=$V, T=$T" if main::DEBUG && $to_trace;
10540 my $decomposition = sprintf("%04X %04X", $L, $V);
10541 $decomposition .= sprintf(" %04X", $T) if $T != $TBase;
10542 $file->insert_adjusted_lines(
10543 sprintf("%04X; Decomposition_Mapping; %s",
10544 $S,
10545 $decomposition));
10546 }
10547 }
10548 }
10549
10550 return;
10551 }
10552
10553 sub filter_v1_ucd {
10554 # Fix UCD lines in version 1. This is probably overkill, but this
10555 # fixes some glaring errors in Version 1 UnicodeData.txt. That file:
10556 # 1) had many Hangul (U+3400 - U+4DFF) code points that were later
10557 # removed. This program retains them
10558 # 2) didn't include ranges, which it should have, and which are now
10559 # added in @corrected_lines below. It was hand populated by
10560 # taking the data from Version 2, verified by analyzing
10561 # DAge.txt.
10562 # 3) There is a syntax error in the entry for U+09F8 which could
10563 # cause problems for utf8_heavy, and so is changed. It's
10564 # numeric value was simply a minus sign, without any number.
10565 # (Eventually Unicode changed the code point to non-numeric.)
10566 # 4) The decomposition types often don't match later versions
10567 # exactly, and the whole syntax of that field is different; so
10568 # the syntax is changed as well as the types to their later
10569 # terminology. Otherwise normalize.pm would be very unhappy
10570 # 5) Many ccc classes are different. These are left intact.
10571 # 6) U+FF10 - U+FF19 are missing their numeric values in all three
10572 # fields. These are unchanged because it doesn't really cause
10573 # problems for Perl.
10574 # 7) A number of code points, such as controls, don't have their
10575 # Unicode Version 1 Names in this file. These are unchanged.
10576
10577 my @corrected_lines = split /\n/, <<'END';
105784E00;<CJK Ideograph, First>;Lo;0;L;;;;;N;;;;;
105799FA5;<CJK Ideograph, Last>;Lo;0;L;;;;;N;;;;;
10580E000;<Private Use, First>;Co;0;L;;;;;N;;;;;
10581F8FF;<Private Use, Last>;Co;0;L;;;;;N;;;;;
10582F900;<CJK Compatibility Ideograph, First>;Lo;0;L;;;;;N;;;;;
10583FA2D;<CJK Compatibility Ideograph, Last>;Lo;0;L;;;;;N;;;;;
10584END
10585
10586 my $file = shift;
10587 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
10588
10589 #local $to_trace = 1 if main::DEBUG;
10590 trace $_ if main::DEBUG && $to_trace;
10591
10592 # -1 => retain trailing null fields
10593 my ($code_point, @fields) = split /\s*;\s*/, $_, -1;
10594
10595 # At the first place that is wrong in the input, insert all the
10596 # corrections, replacing the wrong line.
10597 if ($code_point eq '4E00') {
10598 my @copy = @corrected_lines;
10599 $_ = shift @copy;
10600 ($code_point, @fields) = split /\s*;\s*/, $_, -1;
10601
10602 $file->insert_lines(@copy);
10603 }
10604
10605
10606 if ($fields[$NUMERIC] eq '-') {
10607 $fields[$NUMERIC] = '-1'; # This is what 2.0 made it.
10608 }
10609
10610 if ($fields[$PERL_DECOMPOSITION] ne "") {
10611
10612 # Several entries have this change to superscript 2 or 3 in the
10613 # middle. Convert these to the modern version, which is to use
10614 # the actual U+00B2 and U+00B3 (the superscript forms) instead.
10615 # So 'HHHH HHHH <+sup> 0033 <-sup> HHHH' becomes
10616 # 'HHHH HHHH 00B3 HHHH'.
10617 # It turns out that all of these that don't have another
10618 # decomposition defined at the beginning of the line have the
10619 # <square> decomposition in later releases.
10620 if ($code_point ne '00B2' && $code_point ne '00B3') {
10621 if ($fields[$PERL_DECOMPOSITION]
10622 =~ s/<\+sup> 003([23]) <-sup>/00B$1/)
10623 {
10624 if (substr($fields[$PERL_DECOMPOSITION], 0, 1) ne '<') {
10625 $fields[$PERL_DECOMPOSITION] = '<square> '
10626 . $fields[$PERL_DECOMPOSITION];
10627 }
10628 }
10629 }
10630
10631 # If is like '<+circled> 0052 <-circled>', convert to
10632 # '<circled> 0052'
10633 $fields[$PERL_DECOMPOSITION] =~
10634 s/ < \+ ( .*? ) > \s* (.*?) \s* <-\1> /<$1> $2/x;
10635
10636 # Convert '<join> HHHH HHHH <join>' to '<medial> HHHH HHHH', etc.
10637 $fields[$PERL_DECOMPOSITION] =~
10638 s/ <join> \s* (.*?) \s* <no-join> /<final> $1/x
10639 or $fields[$PERL_DECOMPOSITION] =~
10640 s/ <join> \s* (.*?) \s* <join> /<medial> $1/x
10641 or $fields[$PERL_DECOMPOSITION] =~
10642 s/ <no-join> \s* (.*?) \s* <join> /<initial> $1/x
10643 or $fields[$PERL_DECOMPOSITION] =~
10644 s/ <no-join> \s* (.*?) \s* <no-join> /<isolated> $1/x;
10645
10646 # Convert '<break> HHHH HHHH <break>' to '<break> HHHH', etc.
10647 $fields[$PERL_DECOMPOSITION] =~
10648 s/ <(break|no-break)> \s* (.*?) \s* <\1> /<$1> $2/x;
10649
10650 # Change names to modern form.
10651 $fields[$PERL_DECOMPOSITION] =~ s/<font variant>/<font>/g;
10652 $fields[$PERL_DECOMPOSITION] =~ s/<no-break>/<noBreak>/g;
10653 $fields[$PERL_DECOMPOSITION] =~ s/<circled>/<circle>/g;
10654 $fields[$PERL_DECOMPOSITION] =~ s/<break>/<fraction>/g;
10655
10656 # One entry has weird braces
10657 $fields[$PERL_DECOMPOSITION] =~ s/[{}]//g;
10658 }
10659
10660 $_ = join ';', $code_point, @fields;
10661 trace $_ if main::DEBUG && $to_trace;
10662 return;
10663 }
10664
10665 sub filter_v2_1_5_ucd {
10666 # A dozen entries in this 2.1.5 file had the mirrored and numeric
10667 # columns swapped; These all had mirrored be 'N'. So if the numeric
10668 # column appears to be N, swap it back.
10669
10670 my ($code_point, @fields) = split /\s*;\s*/, $_, -1;
10671 if ($fields[$NUMERIC] eq 'N') {
10672 $fields[$NUMERIC] = $fields[$MIRRORED];
10673 $fields[$MIRRORED] = 'N';
10674 $_ = join ';', $code_point, @fields;
10675 }
10676 return;
10677 }
3ffed8c2
KW
10678
10679 sub filter_v6_ucd {
10680
c12f2655
KW
10681 # Unicode 6.0 co-opted the name BELL for U+1F514, but we haven't
10682 # accepted that yet to allow for some deprecation cycles.
3ffed8c2 10683
484741e1 10684 return if $_ !~ /^(?:0007|1F514|070F);/;
3ffed8c2
KW
10685
10686 my ($code_point, @fields) = split /\s*;\s*/, $_, -1;
10687 if ($code_point eq '0007') {
dcd72625 10688 $fields[$CHARNAME] = "";
3ffed8c2 10689 }
484741e1
KW
10690 elsif ($code_point eq '070F') { # Unicode Corrigendum #8; see
10691 # http://www.unicode.org/versions/corrigendum8.html
10692 $fields[$BIDI] = "AL";
10693 }
10914c78 10694 elsif ($^V lt v5.17.0) { # For 5.18 will convert to use Unicode's name
3ffed8c2
KW
10695 $fields[$CHARNAME] = "";
10696 }
10697
10698 $_ = join ';', $code_point, @fields;
10699
10700 return;
10701 }
99870f4d
KW
10702} # End closure for UnicodeData
10703
37e2e78e
KW
10704sub process_GCB_test {
10705
10706 my $file = shift;
10707 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
10708
10709 while ($file->next_line) {
10710 push @backslash_X_tests, $_;
10711 }
678f13d5 10712
37e2e78e
KW
10713 return;
10714}
10715
99870f4d
KW
10716sub process_NamedSequences {
10717 # NamedSequences.txt entries are just added to an array. Because these
10718 # don't look like the other tables, they have their own handler.
10719 # An example:
10720 # LATIN CAPITAL LETTER A WITH MACRON AND GRAVE;0100 0300
10721 #
10722 # This just adds the sequence to an array for later handling
10723
99870f4d
KW
10724 my $file = shift;
10725 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
10726
10727 while ($file->next_line) {
10728 my ($name, $sequence, @remainder) = split /\s*;\s*/, $_, -1;
10729 if (@remainder) {
10730 $file->carp_bad_line(
10731 "Doesn't look like 'KHMER VOWEL SIGN OM;17BB 17C6'");
10732 next;
10733 }
fb121860
KW
10734
10735 # Note single \t in keeping with special output format of
10736 # Perl_charnames. But it turns out that the code points don't have to
10737 # be 5 digits long, like the rest, based on the internal workings of
10738 # charnames.pm. This could be easily changed for consistency.
10739 push @named_sequences, "$sequence\t$name";
99870f4d
KW
10740 }
10741 return;
10742}
10743
10744{ # Closure
10745
10746 my $first_range;
10747
10748 sub filter_early_ea_lb {
10749 # Fixes early EastAsianWidth.txt and LineBreak.txt files. These had a
10750 # third field be the name of the code point, which can be ignored in
10751 # most cases. But it can be meaningful if it marks a range:
10752 # 33FE;W;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTY-ONE
10753 # 3400;W;<CJK Ideograph Extension A, First>
10754 #
10755 # We need to see the First in the example above to know it's a range.
10756 # They did not use the later range syntaxes. This routine changes it
10757 # to use the modern syntax.
10758 # $1 is the Input_file object.
10759
10760 my @fields = split /\s*;\s*/;
10761 if ($fields[2] =~ /^<.*, First>/) {
10762 $first_range = $fields[0];
10763 $_ = "";
10764 }
10765 elsif ($fields[2] =~ /^<.*, Last>/) {
10766 $_ = $_ = "$first_range..$fields[0]; $fields[1]";
10767 }
10768 else {
10769 undef $first_range;
10770 $_ = "$fields[0]; $fields[1]";
10771 }
10772
10773 return;
10774 }
10775}
10776
10777sub filter_old_style_arabic_shaping {
10778 # Early versions used a different term for the later one.
10779
10780 my @fields = split /\s*;\s*/;
10781 $fields[3] =~ s/<no shaping>/No_Joining_Group/;
10782 $fields[3] =~ s/\s+/_/g; # Change spaces to underscores
10783 $_ = join ';', @fields;
10784 return;
10785}
10786
10787sub filter_arabic_shaping_line {
10788 # ArabicShaping.txt has entries that look like:
10789 # 062A; TEH; D; BEH
10790 # The field containing 'TEH' is not used. The next field is Joining_Type
10791 # and the last is Joining_Group
10792 # This generates two lines to pass on, one for each property on the input
10793 # line.
10794
10795 my $file = shift;
10796 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
10797
10798 my @fields = split /\s*;\s*/, $_, -1; # -1 => retain trailing null fields
10799
10800 if (@fields > 4) {
10801 $file->carp_bad_line('Extra fields');
10802 $_ = "";
10803 return;
10804 }
10805
10806 $file->insert_adjusted_lines("$fields[0]; Joining_Group; $fields[3]");
10807 $_ = "$fields[0]; Joining_Type; $fields[2]";
10808
10809 return;
10810}
10811
d3fed3dd
KW
10812{ # Closure
10813 my $lc; # Table for lowercase mapping
10814 my $tc;
10815 my $uc;
10816
6c0259ad
KW
10817 sub setup_special_casing {
10818 # SpecialCasing.txt contains the non-simple case change mappings. The
10819 # simple ones are in UnicodeData.txt, which should already have been
10820 # read in to the full property data structures, so as to initialize
10821 # these with the simple ones. Then the SpecialCasing.txt entries
bc0cd415 10822 # add or overwrite the ones which have different full mappings.
6c0259ad
KW
10823
10824 # This routine sees if the simple mappings are to be output, and if
10825 # so, copies what has already been put into the full mapping tables,
10826 # while they still contain only the simple mappings.
10827
10828 # The reason it is done this way is that the simple mappings are
10829 # probably not going to be output, so it saves work to initialize the
10830 # full tables with the simple mappings, and then overwrite those
10831 # relatively few entries in them that have different full mappings,
10832 # and thus skip the simple mapping tables altogether.
10833
10834 my $file= shift;
10835 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
99870f4d 10836
6c0259ad
KW
10837 $lc = property_ref('lc');
10838 $tc = property_ref('tc');
10839 $uc = property_ref('uc');
10840
10841 # For each of the case change mappings...
66474459
KW
10842 foreach my $full_table ($lc, $tc, $uc) {
10843 my $full_name = $full_table->name;
10844 unless (defined $full_table && ! $full_table->is_empty) {
6c0259ad
KW
10845 Carp::my_carp_bug("Need to process UnicodeData before SpecialCasing. Only special casing will be generated.");
10846 }
10847
cdc18eb6
KW
10848 # Create a table in the old-style format and with the original
10849 # file name for backwards compatibility with applications that
ae1bcb1f
KW
10850 # read it directly. The new tables contain both the simple and
10851 # full maps, and the old are missing simple maps when there is a
10852 # conflicting full one. Probably it would have been ok to add
10853 # those to the legacy version, as was already done in 5.14 to the
10854 # case folding one, but this was not done, out of an abundance of
10855 # caution. The tables are set up here before we deal with the
10856 # full maps so that as we handle those, we can override the simple
10857 # maps for them in the legacy table, and merely add them in the
10858 # new-style one.
cdc18eb6
KW
10859 my $legacy = Property->new("Legacy_" . $full_table->full_name,
10860 File => $full_table->full_name =~
10861 s/case_Mapping//r,
10862 Range_Size_1 => 1,
10863 Format => $HEX_FORMAT,
10864 Default_Map => $CODE_POINT,
10865 UCD => 0,
10866 Initialize => $full_table,
f64b46a1 10867 To_Output_Map => $EXTERNAL_MAP,
cdc18eb6
KW
10868 );
10869
ae1bcb1f
KW
10870 $full_table->add_comment(join_lines( <<END
10871This file includes both the simple and full case changing maps. The simple
10872ones are in the main body of the table below, and the full ones adding to or
10873overriding them are in the hash.
10874END
10875 ));
10876
6c0259ad
KW
10877 # The simple version's name in each mapping merely has an 's' in
10878 # front of the full one's
66474459 10879 my $simple_name = 's' . $full_name;
301ba948 10880 my $simple = property_ref($simple_name);
66474459 10881 $simple->initialize($full_table) if $simple->to_output_map();
6c0259ad 10882
5be997b0 10883 unless ($simple->to_output_map()) {
ae1bcb1f 10884 $full_table->set_proxy_for($simple_name);
5be997b0 10885 }
6c0259ad 10886 }
99870f4d 10887
6c0259ad
KW
10888 return;
10889 }
99870f4d 10890
6c0259ad
KW
10891 sub filter_special_casing_line {
10892 # Change the format of $_ from SpecialCasing.txt into something that
10893 # the generic handler understands. Each input line contains three
10894 # case mappings. This will generate three lines to pass to the
10895 # generic handler for each of those.
99870f4d 10896
6c0259ad
KW
10897 # The input syntax (after stripping comments and trailing white space
10898 # is like one of the following (with the final two being entries that
10899 # we ignore):
10900 # 00DF; 00DF; 0053 0073; 0053 0053; # LATIN SMALL LETTER SHARP S
10901 # 03A3; 03C2; 03A3; 03A3; Final_Sigma;
10902 # 0307; ; 0307; 0307; tr After_I; # COMBINING DOT ABOVE
10903 # Note the trailing semi-colon, unlike many of the input files. That
10904 # means that there will be an extra null field generated by the split
99870f4d 10905
6c0259ad
KW
10906 my $file = shift;
10907 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
99870f4d 10908
6c0259ad
KW
10909 my @fields = split /\s*;\s*/, $_, -1; # -1 => retain trailing null
10910 # fields
10911
10912 # field #4 is when this mapping is conditional. If any of these get
10913 # implemented, it would be by hard-coding in the casing functions in
10914 # the Perl core, not through tables. But if there is a new condition
10915 # we don't know about, output a warning. We know about all the
10916 # conditions through 6.0
10917 if ($fields[4] ne "") {
10918 my @conditions = split ' ', $fields[4];
10919 if ($conditions[0] ne 'tr' # We know that these languages have
10920 # conditions, and some are multiple
10921 && $conditions[0] ne 'az'
10922 && $conditions[0] ne 'lt'
10923
10924 # And, we know about a single condition Final_Sigma, but
10925 # nothing else.
10926 && ($v_version gt v5.2.0
10927 && (@conditions > 1 || $conditions[0] ne 'Final_Sigma')))
10928 {
10929 $file->carp_bad_line("Unknown condition '$fields[4]'. You should inspect it and either add code to handle it, or add to list of those that are to ignore");
10930 }
10931 elsif ($conditions[0] ne 'Final_Sigma') {
99870f4d 10932
6c0259ad
KW
10933 # Don't print out a message for Final_Sigma, because we
10934 # have hard-coded handling for it. (But the standard
10935 # could change what the rule should be, but it wouldn't
10936 # show up here anyway.
99870f4d 10937
6c0259ad 10938 print "# SKIPPING Special Casing: $_\n"
99870f4d 10939 if $verbosity >= $VERBOSE;
6c0259ad
KW
10940 }
10941 $_ = "";
10942 return;
10943 }
10944 elsif (@fields > 6 || (@fields == 6 && $fields[5] ne "" )) {
10945 $file->carp_bad_line('Extra fields');
10946 $_ = "";
10947 return;
99870f4d 10948 }
99870f4d 10949
107e47c9
KW
10950 my $decimal_code_point = hex $fields[0];
10951
10952 # Loop to handle each of the three mappings in the input line, in
10953 # order, with $i indicating the current field number.
10954 my $i = 0;
10955 for my $object ($lc, $tc, $uc) {
10956 $i++; # First time through, $i = 0 ... 3rd time = 3
10957
10958 my $value = $object->value_of($decimal_code_point);
10959 $value = ($value eq $CODE_POINT)
10960 ? $decimal_code_point
10961 : hex $value;
10962
10963 # If this isn't a multi-character mapping, it should already have
10964 # been read in.
10965 if ($fields[$i] !~ / /) {
10966 if ($value != hex $fields[$i]) {
10967 Carp::my_carp("Bad news. UnicodeData.txt thinks "
10968 . $object->name
10969 . "(0x$fields[0]) is $value"
10970 . " and SpecialCasing.txt thinks it is "
10971 . hex $fields[$i]
10972 . ". Good luck. Proceeding anyway.");
10973 }
10974 }
10975 else {
cdc18eb6 10976
ae1bcb1f
KW
10977 # The mapping goes into both the legacy table, in which it
10978 # replaces the simple one...
cdc18eb6 10979 $file->insert_adjusted_lines("$fields[0]; Legacy_"
107e47c9
KW
10980 . $object->full_name
10981 . "; $fields[$i]");
10982
ae1bcb1f
KW
10983 # ... and, the The regular table, in which it is additional,
10984 # beyond the simple mapping.
cdc18eb6
KW
10985 $file->insert_adjusted_lines("$fields[0]; "
10986 . $object->name
10987 . "; "
ae1bcb1f
KW
10988 . $CMD_DELIM
10989 . "$REPLACE_CMD=$MULTIPLE_BEFORE"
10990 . $CMD_DELIM
cdc18eb6 10991 . $fields[$i]);
107e47c9 10992 }
6c0259ad 10993 }
d3fed3dd 10994
107e47c9
KW
10995 # Everything has been handled by the insert_adjusted_lines()
10996 $_ = "";
10997
6c0259ad
KW
10998 return;
10999 }
d3fed3dd 11000}
99870f4d
KW
11001
11002sub filter_old_style_case_folding {
11003 # This transforms $_ containing the case folding style of 3.0.1, to 3.1
f86864ac 11004 # and later style. Different letters were used in the earlier.
99870f4d
KW
11005
11006 my $file = shift;
11007 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
11008
11009 my @fields = split /\s*;\s*/;
11010 if ($fields[0] =~ /^ 013 [01] $/x) { # The two turkish fields
11011 $fields[1] = 'I';
11012 }
11013 elsif ($fields[1] eq 'L') {
11014 $fields[1] = 'C'; # L => C always
11015 }
11016 elsif ($fields[1] eq 'E') {
11017 if ($fields[2] =~ / /) { # E => C if one code point; F otherwise
11018 $fields[1] = 'F'
11019 }
11020 else {
11021 $fields[1] = 'C'
11022 }
11023 }
11024 else {
11025 $file->carp_bad_line("Expecting L or E in second field");
11026 $_ = "";
11027 return;
11028 }
11029 $_ = join("; ", @fields) . ';';
11030 return;
11031}
11032
11033{ # Closure for case folding
11034
11035 # Create the map for simple only if are going to output it, for otherwise
11036 # it takes no part in anything we do.
11037 my $to_output_simple;
802ba51d 11038 my $non_final_folds;
99870f4d 11039
99870f4d
KW
11040 sub setup_case_folding($) {
11041 # Read in the case foldings in CaseFolding.txt. This handles both
11042 # simple and full case folding.
11043
11044 $to_output_simple
11045 = property_ref('Simple_Case_Folding')->to_output_map;
11046
5be997b0
KW
11047 if (! $to_output_simple) {
11048 property_ref('Case_Folding')->set_proxy_for('Simple_Case_Folding');
11049 }
11050
802ba51d
KW
11051 $non_final_folds = $perl->add_match_table("_Perl_Non_Final_Folds",
11052 Perl_Extension => 1,
11053 Fate => $INTERNAL_ONLY,
d59563d0 11054 Description => "Code points that particpate in a multi-char fold and are not the final character of said fold",
802ba51d
KW
11055 );
11056
6f2a3287
KW
11057 # If we ever wanted to show that these tables were combined, a new
11058 # property method could be created, like set_combined_props()
11059 property_ref('Case_Folding')->add_comment(join_lines( <<END
11060This file includes both the simple and full case folding maps. The simple
11061ones are in the main body of the table below, and the full ones adding to or
11062overriding them are in the hash.
11063END
11064 ));
99870f4d
KW
11065 return;
11066 }
11067
11068 sub filter_case_folding_line {
11069 # Called for each line in CaseFolding.txt
11070 # Input lines look like:
11071 # 0041; C; 0061; # LATIN CAPITAL LETTER A
11072 # 00DF; F; 0073 0073; # LATIN SMALL LETTER SHARP S
11073 # 1E9E; S; 00DF; # LATIN CAPITAL LETTER SHARP S
11074 #
11075 # 'C' means that folding is the same for both simple and full
11076 # 'F' that it is only for full folding
11077 # 'S' that it is only for simple folding
11078 # 'T' is locale-dependent, and ignored
11079 # 'I' is a type of 'F' used in some early releases.
11080 # Note the trailing semi-colon, unlike many of the input files. That
11081 # means that there will be an extra null field generated by the split
11082 # below, which we ignore and hence is not an error.
11083
11084 my $file = shift;
11085 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
11086
11087 my ($range, $type, $map, @remainder) = split /\s*;\s*/, $_, -1;
11088 if (@remainder > 1 || (@remainder == 1 && $remainder[0] ne "" )) {
11089 $file->carp_bad_line('Extra fields');
11090 $_ = "";
11091 return;
11092 }
11093
11094 if ($type eq 'T') { # Skip Turkic case folding, is locale dependent
11095 $_ = "";
11096 return;
11097 }
11098
11099 # C: complete, F: full, or I: dotted uppercase I -> dotless lowercase
3c099872
KW
11100 # I are all full foldings; S is single-char. For S, there is always
11101 # an F entry, so we must allow multiple values for the same code
11102 # point. Fortunately this table doesn't need further manipulation
11103 # which would preclude using multiple-values. The S is now included
11104 # so that _swash_inversion_hash() is able to construct closures
11105 # without having to worry about F mappings.
11106 if ($type eq 'C' || $type eq 'F' || $type eq 'I' || $type eq 'S') {
9470941f
KW
11107 $_ = "$range; Case_Folding; "
11108 . "$CMD_DELIM$REPLACE_CMD=$MULTIPLE_BEFORE$CMD_DELIM$map";
802ba51d
KW
11109 if ($type eq 'F') {
11110 my @string = split " ", $map;
11111 for my $i (0 .. @string - 1 -1) {
11112 $non_final_folds->add_range(hex $string[$i], hex $string[$i]);
11113 }
11114 }
99870f4d
KW
11115 }
11116 else {
11117 $_ = "";
3c099872 11118 $file->carp_bad_line('Expecting C F I S or T in second field');
99870f4d
KW
11119 }
11120
11121 # C and S are simple foldings, but simple case folding is not needed
11122 # unless we explicitly want its map table output.
11123 if ($to_output_simple && $type eq 'C' || $type eq 'S') {
11124 $file->insert_adjusted_lines("$range; Simple_Case_Folding; $map");
11125 }
11126
99870f4d
KW
11127 return;
11128 }
11129
99870f4d
KW
11130} # End case fold closure
11131
11132sub filter_jamo_line {
11133 # Filter Jamo.txt lines. This routine mainly is used to populate hashes
11134 # from this file that is used in generating the Name property for Jamo
11135 # code points. But, it also is used to convert early versions' syntax
11136 # into the modern form. Here are two examples:
11137 # 1100; G # HANGUL CHOSEONG KIYEOK # Modern syntax
11138 # U+1100; G; HANGUL CHOSEONG KIYEOK # 2.0 syntax
11139 #
11140 # The input is $_, the output is $_ filtered.
11141
11142 my @fields = split /\s*;\s*/, $_, -1; # -1 => retain trailing null fields
11143
11144 # Let the caller handle unexpected input. In earlier versions, there was
11145 # a third field which is supposed to be a comment, but did not have a '#'
11146 # before it.
11147 return if @fields > (($v_version gt v3.0.0) ? 2 : 3);
11148
11149 $fields[0] =~ s/^U\+//; # Also, early versions had this extraneous
11150 # beginning.
11151
11152 # Some 2.1 versions had this wrong. Causes havoc with the algorithm.
11153 $fields[1] = 'R' if $fields[0] eq '1105';
11154
11155 # Add to structure so can generate Names from it.
11156 my $cp = hex $fields[0];
11157 my $short_name = $fields[1];
11158 $Jamo{$cp} = $short_name;
11159 if ($cp <= $LBase + $LCount) {
11160 $Jamo_L{$short_name} = $cp - $LBase;
11161 }
11162 elsif ($cp <= $VBase + $VCount) {
11163 $Jamo_V{$short_name} = $cp - $VBase;
11164 }
11165 elsif ($cp <= $TBase + $TCount) {
11166 $Jamo_T{$short_name} = $cp - $TBase;
11167 }
11168 else {
11169 Carp::my_carp_bug("Unexpected Jamo code point in $_");
11170 }
11171
11172
11173 # Reassemble using just the first two fields to look like a typical
11174 # property file line
11175 $_ = "$fields[0]; $fields[1]";
11176
11177 return;
11178}
11179
99870f4d
KW
11180sub register_fraction($) {
11181 # This registers the input rational number so that it can be passed on to
11182 # utf8_heavy.pl, both in rational and floating forms.
11183
11184 my $rational = shift;
11185
11186 my $float = eval $rational;
11187 $nv_floating_to_rational{$float} = $rational;
11188 return;
11189}
11190
11191sub filter_numeric_value_line {
11192 # DNumValues contains lines of a different syntax than the typical
11193 # property file:
11194 # 0F33 ; -0.5 ; ; -1/2 # No TIBETAN DIGIT HALF ZERO
11195 #
11196 # This routine transforms $_ containing the anomalous syntax to the
11197 # typical, by filtering out the extra columns, and convert early version
11198 # decimal numbers to strings that look like rational numbers.
11199
11200 my $file = shift;
11201 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
11202
11203 # Starting in 5.1, there is a rational field. Just use that, omitting the
11204 # extra columns. Otherwise convert the decimal number in the second field
11205 # to a rational, and omit extraneous columns.
11206 my @fields = split /\s*;\s*/, $_, -1;
11207 my $rational;
11208
11209 if ($v_version ge v5.1.0) {
11210 if (@fields != 4) {
11211 $file->carp_bad_line('Not 4 semi-colon separated fields');
11212 $_ = "";
11213 return;
11214 }
11215 $rational = $fields[3];
11216 $_ = join '; ', @fields[ 0, 3 ];
11217 }
11218 else {
11219
11220 # Here, is an older Unicode file, which has decimal numbers instead of
11221 # rationals in it. Use the fraction to calculate the denominator and
11222 # convert to rational.
11223
11224 if (@fields != 2 && @fields != 3) {
11225 $file->carp_bad_line('Not 2 or 3 semi-colon separated fields');
11226 $_ = "";
11227 return;
11228 }
11229
11230 my $codepoints = $fields[0];
11231 my $decimal = $fields[1];
11232 if ($decimal =~ s/\.0+$//) {
11233
11234 # Anything ending with a decimal followed by nothing but 0's is an
11235 # integer
11236 $_ = "$codepoints; $decimal";
11237 $rational = $decimal;
11238 }
11239 else {
11240
11241 my $denominator;
11242 if ($decimal =~ /\.50*$/) {
11243 $denominator = 2;
11244 }
11245
11246 # Here have the hardcoded repeating decimals in the fraction, and
11247 # the denominator they imply. There were only a few denominators
11248 # in the older Unicode versions of this file which this code
11249 # handles, so it is easy to convert them.
11250
11251 # The 4 is because of a round-off error in the Unicode 3.2 files
11252 elsif ($decimal =~ /\.33*[34]$/ || $decimal =~ /\.6+7$/) {
11253 $denominator = 3;
11254 }
11255 elsif ($decimal =~ /\.[27]50*$/) {
11256 $denominator = 4;
11257 }
11258 elsif ($decimal =~ /\.[2468]0*$/) {
11259 $denominator = 5;
11260 }
11261 elsif ($decimal =~ /\.16+7$/ || $decimal =~ /\.83+$/) {
11262 $denominator = 6;
11263 }
11264 elsif ($decimal =~ /\.(12|37|62|87)50*$/) {
11265 $denominator = 8;
11266 }
11267 if ($denominator) {
11268 my $sign = ($decimal < 0) ? "-" : "";
11269 my $numerator = int((abs($decimal) * $denominator) + .5);
11270 $rational = "$sign$numerator/$denominator";
11271 $_ = "$codepoints; $rational";
11272 }
11273 else {
11274 $file->carp_bad_line("Can't cope with number '$decimal'.");
11275 $_ = "";
11276 return;
11277 }
11278 }
11279 }
11280
11281 register_fraction($rational) if $rational =~ qr{/};
11282 return;
11283}
11284
11285{ # Closure
11286 my %unihan_properties;
99870f4d
KW
11287
11288 sub setup_unihan {
11289 # Do any special setup for Unihan properties.
11290
11291 # This property gives the wrong computed type, so override.
11292 my $usource = property_ref('kIRG_USource');
11293 $usource->set_type($STRING) if defined $usource;
11294
b2abbe5b
KW
11295 # This property is to be considered binary (it says so in
11296 # http://www.unicode.org/reports/tr38/)
46b2142f 11297 my $iicore = property_ref('kIICore');
99870f4d 11298 if (defined $iicore) {
46b2142f
KW
11299 $iicore->set_type($FORCED_BINARY);
11300 $iicore->table("Y")->add_note("Forced to a binary property as per unicode.org UAX #38.");
11301
11302 # Unicode doesn't include the maps for this property, so don't
11303 # warn that they are missing.
11304 $iicore->set_pre_declared_maps(0);
11305 $iicore->add_comment(join_lines( <<END
11306This property contains enum values, but Unicode UAX #38 says it should be
11307interpreted as binary, so Perl creates tables for both 1) its enum values,
11308plus 2) true/false tables in which it is considered true for all code points
11309that have a non-null value
11310END
11311 ));
99870f4d
KW
11312 }
11313
11314 return;
11315 }
11316
11317 sub filter_unihan_line {
11318 # Change unihan db lines to look like the others in the db. Here is
11319 # an input sample:
11320 # U+341C kCangjie IEKN
11321
11322 # Tabs are used instead of semi-colons to separate fields; therefore
11323 # they may have semi-colons embedded in them. Change these to periods
11324 # so won't screw up the rest of the code.
11325 s/;/./g;
11326
11327 # Remove lines that don't look like ones we accept.
11328 if ($_ !~ /^ [^\t]* \t ( [^\t]* ) /x) {
11329 $_ = "";
11330 return;
11331 }
11332
11333 # Extract the property, and save a reference to its object.
11334 my $property = $1;
11335 if (! exists $unihan_properties{$property}) {
11336 $unihan_properties{$property} = property_ref($property);
11337 }
11338
11339 # Don't do anything unless the property is one we're handling, which
11340 # we determine by seeing if there is an object defined for it or not
11341 if (! defined $unihan_properties{$property}) {
11342 $_ = "";
11343 return;
11344 }
11345
99870f4d
KW
11346 # Convert the tab separators to our standard semi-colons, and convert
11347 # the U+HHHH notation to the rest of the standard's HHHH
11348 s/\t/;/g;
11349 s/\b U \+ (?= $code_point_re )//xg;
11350
11351 #local $to_trace = 1 if main::DEBUG;
11352 trace $_ if main::DEBUG && $to_trace;
11353
11354 return;
11355 }
11356}
11357
11358sub filter_blocks_lines {
11359 # In the Blocks.txt file, the names of the blocks don't quite match the
11360 # names given in PropertyValueAliases.txt, so this changes them so they
11361 # do match: Blanks and hyphens are changed into underscores. Also makes
11362 # early release versions look like later ones
11363 #
11364 # $_ is transformed to the correct value.
11365
11366 my $file = shift;
11367 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
11368
11369 if ($v_version lt v3.2.0) {
11370 if (/FEFF.*Specials/) { # Bug in old versions: line wrongly inserted
11371 $_ = "";
11372 return;
11373 }
11374
11375 # Old versions used a different syntax to mark the range.
11376 $_ =~ s/;\s+/../ if $v_version lt v3.1.0;
11377 }
11378
11379 my @fields = split /\s*;\s*/, $_, -1;
11380 if (@fields != 2) {
11381 $file->carp_bad_line("Expecting exactly two fields");
11382 $_ = "";
11383 return;
11384 }
11385
11386 # Change hyphens and blanks in the block name field only
11387 $fields[1] =~ s/[ -]/_/g;
11388 $fields[1] =~ s/_ ( [a-z] ) /_\u$1/g; # Capitalize first letter of word
11389
11390 $_ = join("; ", @fields);
11391 return;
11392}
11393
11394{ # Closure
11395 my $current_property;
11396
11397 sub filter_old_style_proplist {
11398 # PropList.txt has been in Unicode since version 2.0. Until 3.1, it
11399 # was in a completely different syntax. Ken Whistler of Unicode says
11400 # that it was something he used as an aid for his own purposes, but
11401 # was never an official part of the standard. However, comments in
11402 # DAge.txt indicate that non-character code points were available in
11403 # the UCD as of 3.1. It is unclear to me (khw) how they could be
11404 # there except through this file (but on the other hand, they first
11405 # appeared there in 3.0.1), so maybe it was part of the UCD, and maybe
11406 # not. But the claim is that it was published as an aid to others who
11407 # might want some more information than was given in the official UCD
11408 # of the time. Many of the properties in it were incorporated into
11409 # the later PropList.txt, but some were not. This program uses this
11410 # early file to generate property tables that are otherwise not
11411 # accessible in the early UCD's, and most were probably not really
11412 # official at that time, so one could argue that it should be ignored,
11413 # and you can easily modify things to skip this. And there are bugs
11414 # in this file in various versions. (For example, the 2.1.9 version
11415 # removes from Alphabetic the CJK range starting at 4E00, and they
11416 # weren't added back in until 3.1.0.) Many of this file's properties
11417 # were later sanctioned, so this code generates tables for those
11418 # properties that aren't otherwise in the UCD of the time but
11419 # eventually did become official, and throws away the rest. Here is a
11420 # list of all the ones that are thrown away:
11421 # Bidi=* duplicates UnicodeData.txt
11422 # Combining never made into official property;
11423 # is \P{ccc=0}
11424 # Composite never made into official property.
11425 # Currency Symbol duplicates UnicodeData.txt: gc=sc
11426 # Decimal Digit duplicates UnicodeData.txt: gc=nd
11427 # Delimiter never made into official property;
11428 # removed in 3.0.1
11429 # Format Control never made into official property;
11430 # similar to gc=cf
11431 # High Surrogate duplicates Blocks.txt
11432 # Ignorable Control never made into official property;
11433 # similar to di=y
11434 # ISO Control duplicates UnicodeData.txt: gc=cc
11435 # Left of Pair never made into official property;
11436 # Line Separator duplicates UnicodeData.txt: gc=zl
11437 # Low Surrogate duplicates Blocks.txt
11438 # Non-break was actually listed as a property
11439 # in 3.2, but without any code
11440 # points. Unicode denies that this
11441 # was ever an official property
11442 # Non-spacing duplicate UnicodeData.txt: gc=mn
11443 # Numeric duplicates UnicodeData.txt: gc=cc
11444 # Paired Punctuation never made into official property;
11445 # appears to be gc=ps + gc=pe
11446 # Paragraph Separator duplicates UnicodeData.txt: gc=cc
11447 # Private Use duplicates UnicodeData.txt: gc=co
11448 # Private Use High Surrogate duplicates Blocks.txt
11449 # Punctuation duplicates UnicodeData.txt: gc=p
11450 # Space different definition than eventual
11451 # one.
11452 # Titlecase duplicates UnicodeData.txt: gc=lt
11453 # Unassigned Code Value duplicates UnicodeData.txt: gc=cc
98dc9551 11454 # Zero-width never made into official property;
99870f4d
KW
11455 # subset of gc=cf
11456 # Most of the properties have the same names in this file as in later
11457 # versions, but a couple do not.
11458 #
11459 # This subroutine filters $_, converting it from the old style into
11460 # the new style. Here's a sample of the old-style
11461 #
11462 # *******************************************
11463 #
11464 # Property dump for: 0x100000A0 (Join Control)
11465 #
11466 # 200C..200D (2 chars)
11467 #
11468 # In the example, the property is "Join Control". It is kept in this
11469 # closure between calls to the subroutine. The numbers beginning with
11470 # 0x were internal to Ken's program that generated this file.
11471
11472 # If this line contains the property name, extract it.
11473 if (/^Property dump for: [^(]*\((.*)\)/) {
11474 $_ = $1;
11475
11476 # Convert white space to underscores.
11477 s/ /_/g;
11478
11479 # Convert the few properties that don't have the same name as
11480 # their modern counterparts
11481 s/Identifier_Part/ID_Continue/
11482 or s/Not_a_Character/NChar/;
11483
11484 # If the name matches an existing property, use it.
11485 if (defined property_ref($_)) {
11486 trace "new property=", $_ if main::DEBUG && $to_trace;
11487 $current_property = $_;
11488 }
11489 else { # Otherwise discard it
11490 trace "rejected property=", $_ if main::DEBUG && $to_trace;
11491 undef $current_property;
11492 }
11493 $_ = ""; # The property is saved for the next lines of the
11494 # file, but this defining line is of no further use,
11495 # so clear it so that the caller won't process it
11496 # further.
11497 }
11498 elsif (! defined $current_property || $_ !~ /^$code_point_re/) {
11499
11500 # Here, the input line isn't a header defining a property for the
11501 # following section, and either we aren't in such a section, or
11502 # the line doesn't look like one that defines the code points in
11503 # such a section. Ignore this line.
11504 $_ = "";
11505 }
11506 else {
11507
11508 # Here, we have a line defining the code points for the current
11509 # stashed property. Anything starting with the first blank is
11510 # extraneous. Otherwise, it should look like a normal range to
11511 # the caller. Append the property name so that it looks just like
11512 # a modern PropList entry.
11513
11514 $_ =~ s/\s.*//;
11515 $_ .= "; $current_property";
11516 }
11517 trace $_ if main::DEBUG && $to_trace;
11518 return;
11519 }
11520} # End closure for old style proplist
11521
11522sub filter_old_style_normalization_lines {
11523 # For early releases of Unicode, the lines were like:
11524 # 74..2A76 ; NFKD_NO
11525 # For later releases this became:
11526 # 74..2A76 ; NFKD_QC; N
11527 # Filter $_ to look like those in later releases.
11528 # Similarly for MAYBEs
11529
11530 s/ _NO \b /_QC; N/x || s/ _MAYBE \b /_QC; M/x;
11531
11532 # Also, the property FC_NFKC was abbreviated to FNC
11533 s/FNC/FC_NFKC/;
11534 return;
11535}
11536
82aed44a
KW
11537sub setup_script_extensions {
11538 # The Script_Extensions property starts out with a clone of the Script
11539 # property.
11540
4fec90df
KW
11541 my $scx = property_ref("Script_Extensions");
11542 $scx = Property->new("scx", Full_Name => "Script_Extensions")
d59563d0 11543 if ! defined $scx;
4fec90df
KW
11544 $scx->_set_format($STRING_WHITE_SPACE_LIST);
11545 $scx->initialize($script);
11546 $scx->set_default_map($script->default_map);
11547 $scx->set_pre_declared_maps(0); # PropValueAliases doesn't list these
82aed44a
KW
11548 $scx->add_comment(join_lines( <<END
11549The values for code points that appear in one script are just the same as for
11550the 'Script' property. Likewise the values for those that appear in many
11551scripts are either 'Common' or 'Inherited', same as with 'Script'. But the
11552values of code points that appear in a few scripts are a space separated list
11553of those scripts.
11554END
11555 ));
11556
8d35804a 11557 # Initialize scx's tables and the aliases for them to be the same as sc's
4fec90df 11558 foreach my $table ($script->tables) {
82aed44a
KW
11559 my $scx_table = $scx->add_match_table($table->name,
11560 Full_Name => $table->full_name);
11561 foreach my $alias ($table->aliases) {
11562 $scx_table->add_alias($alias->name);
11563 }
11564 }
11565}
11566
fbe1e607
KW
11567sub filter_script_extensions_line {
11568 # The Scripts file comes with the full name for the scripts; the
11569 # ScriptExtensions, with the short name. The final mapping file is a
11570 # combination of these, and without adjustment, would have inconsistent
11571 # entries. This filters the latter file to convert to full names.
11572 # Entries look like this:
11573 # 064B..0655 ; Arab Syrc # Mn [11] ARABIC FATHATAN..ARABIC HAMZA BELOW
11574
11575 my @fields = split /\s*;\s*/;
11576 my @full_names;
11577 foreach my $short_name (split " ", $fields[1]) {
11578 push @full_names, $script->table($short_name)->full_name;
11579 }
11580 $fields[1] = join " ", @full_names;
11581 $_ = join "; ", @fields;
11582
11583 return;
11584}
11585
ce432655 11586sub setup_early_name_alias {
b8ba2307
KW
11587 my $aliases = property_ref('Name_Alias');
11588 $aliases = Property->new('Name_Alias') if ! defined $aliases;
11589
11590 # Before 6.0, this wasn't a problem, and after it, this alias is part of
11591 # the Unicode-delivered file.
11592 $aliases->add_map(7, 7, "ALERT: control") if $v_version eq v6.0.0;
11593 return;
11594}
11595
11596sub filter_later_version_name_alias_line {
11597
11598 # This file has an extra entry per line for the alias type. This is
11599 # handled by creating a compound entry: "$alias: $type"; First, split
11600 # the line into components.
11601 my ($range, $alias, $type, @remainder)
11602 = split /\s*;\s*/, $_, -1; # -1 => retain trailing null fields
11603
11604 # This file contains multiple entries for some components, so tell the
11605 # downstream code to allow this in our internal tables; the
11606 # $MULTIPLE_AFTER preserves the input ordering.
11607 $_ = join ";", $range, $CMD_DELIM
11608 . $REPLACE_CMD
11609 . '='
11610 . $MULTIPLE_AFTER
11611 . $CMD_DELIM
11612 . "$alias: $type",
11613 @remainder;
11614 return;
58b75e36
KW
11615}
11616
11617sub filter_early_version_name_alias_line {
b8ba2307
KW
11618
11619 # Early versions did not have the trailing alias type field; implicitly it
11620 # was 'correction'
11621 $_ .= "; correction";
11622 filter_later_version_name_alias_line;
58b75e36 11623 return;
dcd72625
KW
11624}
11625
99870f4d
KW
11626sub finish_Unicode() {
11627 # This routine should be called after all the Unicode files have been read
11628 # in. It:
11629 # 1) Adds the mappings for code points missing from the files which have
11630 # defaults specified for them.
11631 # 2) At this this point all mappings are known, so it computes the type of
11632 # each property whose type hasn't been determined yet.
11633 # 3) Calculates all the regular expression match tables based on the
11634 # mappings.
11635 # 3) Calculates and adds the tables which are defined by Unicode, but
d59563d0
KW
11636 # which aren't derived by them, and certain derived tables that Perl
11637 # uses.
99870f4d
KW
11638
11639 # For each property, fill in any missing mappings, and calculate the re
11640 # match tables. If a property has more than one missing mapping, the
11641 # default is a reference to a data structure, and requires data from other
11642 # properties to resolve. The sort is used to cause these to be processed
11643 # last, after all the other properties have been calculated.
11644 # (Fortunately, the missing properties so far don't depend on each other.)
11645 foreach my $property
11646 (sort { (defined $a->default_map && ref $a->default_map) ? 1 : -1 }
11647 property_ref('*'))
11648 {
11649 # $perl has been defined, but isn't one of the Unicode properties that
11650 # need to be finished up.
11651 next if $property == $perl;
11652
9f877a47
KW
11653 # Nor do we need to do anything with properties that aren't going to
11654 # be output.
11655 next if $property->fate == $SUPPRESSED;
11656
99870f4d
KW
11657 # Handle the properties that have more than one possible default
11658 if (ref $property->default_map) {
11659 my $default_map = $property->default_map;
11660
11661 # These properties have stored in the default_map:
11662 # One or more of:
11663 # 1) A default map which applies to all code points in a
11664 # certain class
11665 # 2) an expression which will evaluate to the list of code
11666 # points in that class
11667 # And
11668 # 3) the default map which applies to every other missing code
11669 # point.
11670 #
11671 # Go through each list.
11672 while (my ($default, $eval) = $default_map->get_next_defaults) {
11673
11674 # Get the class list, and intersect it with all the so-far
11675 # unspecified code points yielding all the code points
11676 # in the class that haven't been specified.
11677 my $list = eval $eval;
11678 if ($@) {
11679 Carp::my_carp("Can't set some defaults for missing code points for $property because eval '$eval' failed with '$@'");
11680 last;
11681 }
11682
11683 # Narrow down the list to just those code points we don't have
11684 # maps for yet.
11685 $list = $list & $property->inverse_list;
11686
11687 # Add mappings to the property for each code point in the list
11688 foreach my $range ($list->ranges) {
56343c78
KW
11689 $property->add_map($range->start, $range->end, $default,
11690 Replace => $CROAK);
99870f4d
KW
11691 }
11692 }
11693
11694 # All remaining code points have the other mapping. Set that up
11695 # so the normal single-default mapping code will work on them
11696 $property->set_default_map($default_map->other_default);
11697
11698 # And fall through to do that
11699 }
11700
11701 # We should have enough data now to compute the type of the property.
11702 $property->compute_type;
11703 my $property_type = $property->type;
11704
11705 next if ! $property->to_create_match_tables;
11706
11707 # Here want to create match tables for this property
11708
11709 # The Unicode db always (so far, and they claim into the future) have
11710 # the default for missing entries in binary properties be 'N' (unless
11711 # there is a '@missing' line that specifies otherwise)
11712 if ($property_type == $BINARY && ! defined $property->default_map) {
11713 $property->set_default_map('N');
11714 }
11715
11716 # Add any remaining code points to the mapping, using the default for
5d7f7709 11717 # missing code points.
d8fb1cc3 11718 my $default_table;
99870f4d 11719 if (defined (my $default_map = $property->default_map)) {
1520492f 11720
f4c2a127 11721 # Make sure there is a match table for the default
f4c2a127
KW
11722 if (! defined ($default_table = $property->table($default_map))) {
11723 $default_table = $property->add_match_table($default_map);
11724 }
11725
a92d5c2e
KW
11726 # And, if the property is binary, the default table will just
11727 # be the complement of the other table.
11728 if ($property_type == $BINARY) {
11729 my $non_default_table;
11730
11731 # Find the non-default table.
11732 for my $table ($property->tables) {
11733 next if $table == $default_table;
11734 $non_default_table = $table;
11735 }
11736 $default_table->set_complement($non_default_table);
11737 }
862fd107 11738 else {
a92d5c2e 11739
3981d009
KW
11740 # This fills in any missing values with the default. It's not
11741 # necessary to do this with binary properties, as the default
11742 # is defined completely in terms of the Y table.
6189eadc 11743 $property->add_map(0, $MAX_UNICODE_CODEPOINT,
3981d009 11744 $default_map, Replace => $NO);
862fd107 11745 }
99870f4d
KW
11746 }
11747
11748 # Have all we need to populate the match tables.
11749 my $property_name = $property->name;
56557540 11750 my $maps_should_be_defined = $property->pre_declared_maps;
99870f4d
KW
11751 foreach my $range ($property->ranges) {
11752 my $map = $range->value;
f5e9a6ca 11753 my $table = $property->table($map);
99870f4d
KW
11754 if (! defined $table) {
11755
11756 # Integral and rational property values are not necessarily
56557540
KW
11757 # defined in PropValueAliases, but whether all the other ones
11758 # should be depends on the property.
11759 if ($maps_should_be_defined
99870f4d
KW
11760 && $map !~ /^ -? \d+ ( \/ \d+ )? $/x)
11761 {
11762 Carp::my_carp("Table '$property_name=$map' should have been defined. Defining it now.")
11763 }
f5e9a6ca 11764 $table = $property->add_match_table($map);
99870f4d
KW
11765 }
11766
862fd107 11767 next if $table->complement != 0; # Don't need to populate these
99870f4d
KW
11768 $table->add_range($range->start, $range->end);
11769 }
11770
06f26c45
KW
11771 # A forced binary property has additional true/false tables which
11772 # should have been set up when it was forced into binary. The false
11773 # table matches exactly the same set as the property's default table.
11774 # The true table matches the complement of that. The false table is
11775 # not the same as an additional set of aliases on top of the default
11776 # table, so use 'set_equivalent_to'. If it were implemented as
11777 # additional aliases, various things would have to be adjusted, but
11778 # especially, if the user wants to get a list of names for the table
11779 # using Unicode::UCD::prop_value_aliases(), s/he should get a
11780 # different set depending on whether they want the default table or
11781 # the false table.
11782 if ($property_type == $FORCED_BINARY) {
11783 $property->table('N')->set_equivalent_to($default_table,
11784 Related => 1);
11785 $property->table('Y')->set_complement($default_table);
11786 }
11787
807807b7
KW
11788 # For Perl 5.6 compatibility, all properties matchable in regexes can
11789 # have an optional 'Is_' prefix. This is now done in utf8_heavy.pl.
11790 # But warn if this creates a conflict with a (new) Unicode property
11791 # name, although it appears that Unicode has made a decision never to
11792 # begin a property name with 'Is_', so this shouldn't happen.
99870f4d
KW
11793 foreach my $alias ($property->aliases) {
11794 my $Is_name = 'Is_' . $alias->name;
807807b7 11795 if (defined (my $pre_existing = property_ref($Is_name))) {
99870f4d 11796 Carp::my_carp(<<END
807807b7
KW
11797There is already an alias named $Is_name (from " . $pre_existing . "), so
11798creating one for $property won't work. This is bad news. If it is not too
11799late, get Unicode to back off. Otherwise go back to the old scheme (findable
11800from the git blame log for this area of the code that suppressed individual
11801aliases that conflict with the new Unicode names. Proceeding anyway.
99870f4d
KW
11802END
11803 );
99870f4d
KW
11804 }
11805 } # End of loop through aliases for this property
11806 } # End of loop through all Unicode properties.
11807
11808 # Fill in the mappings that Unicode doesn't completely furnish. First the
11809 # single letter major general categories. If Unicode were to start
11810 # delivering the values, this would be redundant, but better that than to
11811 # try to figure out if should skip and not get it right. Ths could happen
11812 # if a new major category were to be introduced, and the hard-coded test
11813 # wouldn't know about it.
11814 # This routine depends on the standard names for the general categories
11815 # being what it thinks they are, like 'Cn'. The major categories are the
11816 # union of all the general category tables which have the same first
11817 # letters. eg. L = Lu + Lt + Ll + Lo + Lm
11818 foreach my $minor_table ($gc->tables) {
11819 my $minor_name = $minor_table->name;
11820 next if length $minor_name == 1;
11821 if (length $minor_name != 2) {
11822 Carp::my_carp_bug("Unexpected general category '$minor_name'. Skipped.");
11823 next;
11824 }
11825
11826 my $major_name = uc(substr($minor_name, 0, 1));
11827 my $major_table = $gc->table($major_name);
11828 $major_table += $minor_table;
11829 }
11830
11831 # LC is Ll, Lu, and Lt. (used to be L& or L_, but PropValueAliases.txt
11832 # defines it as LC)
11833 my $LC = $gc->table('LC');
11834 $LC->add_alias('L_', Status => $DISCOURAGED); # For backwards...
11835 $LC->add_alias('L&', Status => $DISCOURAGED); # compatibility.
11836
11837
11838 if ($LC->is_empty) { # Assume if not empty that Unicode has started to
11839 # deliver the correct values in it
11840 $LC->initialize($gc->table('Ll') + $gc->table('Lu'));
11841
11842 # Lt not in release 1.
a5c376b7
KW
11843 if (defined $gc->table('Lt')) {
11844 $LC += $gc->table('Lt');
11845 $gc->table('Lt')->set_caseless_equivalent($LC);
11846 }
99870f4d
KW
11847 }
11848 $LC->add_description('[\p{Ll}\p{Lu}\p{Lt}]');
11849
a5c376b7
KW
11850 $gc->table('Ll')->set_caseless_equivalent($LC);
11851 $gc->table('Lu')->set_caseless_equivalent($LC);
11852
99870f4d 11853 my $Cs = $gc->table('Cs');
99870f4d
KW
11854
11855
11856 # Folding information was introduced later into Unicode data. To get
11857 # Perl's case ignore (/i) to work at all in releases that don't have
11858 # folding, use the best available alternative, which is lower casing.
11859 my $fold = property_ref('Simple_Case_Folding');
11860 if ($fold->is_empty) {
11861 $fold->initialize(property_ref('Simple_Lowercase_Mapping'));
11862 $fold->add_note(join_lines(<<END
11863WARNING: This table uses lower case as a substitute for missing fold
11864information
11865END
11866 ));
11867 }
11868
11869 # Multiple-character mapping was introduced later into Unicode data. If
11870 # missing, use the single-characters maps as best available alternative
11871 foreach my $map (qw { Uppercase_Mapping
11872 Lowercase_Mapping
11873 Titlecase_Mapping
11874 Case_Folding
d59563d0
KW
11875 } )
11876 {
99870f4d
KW
11877 my $full = property_ref($map);
11878 if ($full->is_empty) {
11879 my $simple = property_ref('Simple_' . $map);
11880 $full->initialize($simple);
11881 $full->add_comment($simple->comment) if ($simple->comment);
11882 $full->add_note(join_lines(<<END
11883WARNING: This table uses simple mapping (single-character only) as a
11884substitute for missing multiple-character information
11885END
11886 ));
11887 }
11888 }
82aed44a 11889
cdc18eb6
KW
11890 # Create digit and case fold tables with the original file names for
11891 # backwards compatibility with applications that read them directly.
11892 my $Digit = Property->new("Legacy_Perl_Decimal_Digit",
11893 Default_Map => "",
11894 Perl_Extension => 1,
11895 File => 'Digit', # Trad. location
11896 Directory => $map_directory,
11897 UCD => 0,
11898 Type => $STRING,
f64b46a1 11899 To_Output_Map => $EXTERNAL_MAP,
cdc18eb6
KW
11900 Range_Size_1 => 1,
11901 Initialize => property_ref('Perl_Decimal_Digit'),
11902 );
11903 $Digit->add_comment(join_lines(<<END
11904This file gives the mapping of all code points which represent a single
11905decimal digit [0-9] to their respective digits. For example, the code point
11906U+0031 (an ASCII '1') is mapped to a numeric 1. These code points are those
11907that have Numeric_Type=Decimal; not special things, like subscripts nor Roman
11908numerals.
11909END
11910 ));
11911
11912 Property->new('Legacy_Case_Folding',
11913 File => "Fold",
11914 Directory => $map_directory,
11915 Default_Map => $CODE_POINT,
11916 UCD => 0,
11917 Range_Size_1 => 1,
11918 Type => $STRING,
f64b46a1 11919 To_Output_Map => $EXTERNAL_MAP,
cdc18eb6
KW
11920 Format => $HEX_FORMAT,
11921 Initialize => property_ref('cf'),
11922 );
11923
82aed44a
KW
11924 # The Script_Extensions property started out as a clone of the Script
11925 # property. But processing its data file caused some elements to be
11926 # replaced with different data. (These elements were for the Common and
11927 # Inherited properties.) This data is a qw() list of all the scripts that
11928 # the code points in the given range are in. An example line is:
11929 # 060C ; Arab Syrc Thaa # Po ARABIC COMMA
11930 #
11931 # The code above has created a new match table named "Arab Syrc Thaa"
11932 # which contains 060C. (The cloned table started out with this code point
11933 # mapping to "Common".) Now we add 060C to each of the Arab, Syrc, and
11934 # Thaa match tables. Then we delete the now spurious "Arab Syrc Thaa"
11935 # match table. This is repeated for all these tables and ranges. The map
11936 # data is retained in the map table for reference, but the spurious match
11937 # tables are deleted.
11938
11939 my $scx = property_ref("Script_Extensions");
d53a7e7d 11940 if (defined $scx) {
c3a37f64
KW
11941 foreach my $table ($scx->tables) {
11942 next unless $table->name =~ /\s/; # All the new and only the new
11943 # tables have a space in their
11944 # names
11945 my @scripts = split /\s+/, $table->name;
11946 foreach my $script (@scripts) {
11947 my $script_table = $scx->table($script);
11948 $script_table += $table;
11949 }
11950 $scx->delete_match_table($table);
82aed44a 11951 }
d53a7e7d 11952 }
82aed44a
KW
11953
11954 return;
99870f4d
KW
11955}
11956
11957sub compile_perl() {
11958 # Create perl-defined tables. Almost all are part of the pseudo-property
11959 # named 'perl' internally to this program. Many of these are recommended
11960 # in UTS#18 "Unicode Regular Expressions", and their derivations are based
11961 # on those found there.
11962 # Almost all of these are equivalent to some Unicode property.
11963 # A number of these properties have equivalents restricted to the ASCII
11964 # range, with their names prefaced by 'Posix', to signify that these match
11965 # what the Posix standard says they should match. A couple are
11966 # effectively this, but the name doesn't have 'Posix' in it because there
cbc24f92
KW
11967 # just isn't any Posix equivalent. 'XPosix' are the Posix tables extended
11968 # to the full Unicode range, by our guesses as to what is appropriate.
99870f4d
KW
11969
11970 # 'Any' is all code points. As an error check, instead of just setting it
11971 # to be that, construct it to be the union of all the major categories
7fc6cb55 11972 $Any = $perl->add_match_table('Any',
6189eadc 11973 Description => "[\\x{0000}-\\x{$MAX_UNICODE_CODEPOINT_STRING}]",
99870f4d
KW
11974 Matches_All => 1);
11975
11976 foreach my $major_table ($gc->tables) {
11977
11978 # Major categories are the ones with single letter names.
11979 next if length($major_table->name) != 1;
11980
11981 $Any += $major_table;
11982 }
11983
6189eadc 11984 if ($Any->max != $MAX_UNICODE_CODEPOINT) {
99870f4d
KW
11985 Carp::my_carp_bug("Generated highest code point ("
11986 . sprintf("%X", $Any->max)
6189eadc 11987 . ") doesn't match expected value $MAX_UNICODE_CODEPOINT_STRING.")
99870f4d
KW
11988 }
11989 if ($Any->range_count != 1 || $Any->min != 0) {
11990 Carp::my_carp_bug("Generated table 'Any' doesn't match all code points.")
11991 }
11992
11993 $Any->add_alias('All');
11994
11995 # Assigned is the opposite of gc=unassigned
11996 my $Assigned = $perl->add_match_table('Assigned',
11997 Description => "All assigned code points",
11998 Initialize => ~ $gc->table('Unassigned'),
11999 );
12000
12001 # Our internal-only property should be treated as more than just a
8050d00f 12002 # synonym; grandfather it in to the pod.
b15a0a3b
KW
12003 $perl->add_match_table('_CombAbove', Re_Pod_Entry => 1,
12004 Fate => $INTERNAL_ONLY, Status => $DISCOURAGED)
99870f4d
KW
12005 ->set_equivalent_to(property_ref('ccc')->table('Above'),
12006 Related => 1);
12007
12008 my $ASCII = $perl->add_match_table('ASCII', Description => '[[:ASCII:]]');
12009 if (defined $block) { # This is equivalent to the block if have it.
12010 my $Unicode_ASCII = $block->table('Basic_Latin');
12011 if (defined $Unicode_ASCII && ! $Unicode_ASCII->is_empty) {
12012 $ASCII->set_equivalent_to($Unicode_ASCII, Related => 1);
12013 }
12014 }
12015
12016 # Very early releases didn't have blocks, so initialize ASCII ourselves if
12017 # necessary
12018 if ($ASCII->is_empty) {
12019 $ASCII->initialize([ 0..127 ]);
12020 }
12021
99870f4d
KW
12022 # Get the best available case definitions. Early Unicode versions didn't
12023 # have Uppercase and Lowercase defined, so use the general category
12024 # instead for them.
12025 my $Lower = $perl->add_match_table('Lower');
12026 my $Unicode_Lower = property_ref('Lowercase');
12027 if (defined $Unicode_Lower && ! $Unicode_Lower->is_empty) {
12028 $Lower->set_equivalent_to($Unicode_Lower->table('Y'), Related => 1);
a5c376b7
KW
12029 $Unicode_Lower->table('Y')->set_caseless_equivalent(property_ref('Cased')->table('Y'));
12030 $Unicode_Lower->table('N')->set_caseless_equivalent(property_ref('Cased')->table('N'));
12031 $Lower->set_caseless_equivalent(property_ref('Cased')->table('Y'));
12032
99870f4d
KW
12033 }
12034 else {
12035 $Lower->set_equivalent_to($gc->table('Lowercase_Letter'),
12036 Related => 1);
12037 }
cbc24f92 12038 $Lower->add_alias('XPosixLower');
a5c376b7 12039 my $Posix_Lower = $perl->add_match_table("PosixLower",
ad5e8af1
KW
12040 Description => "[a-z]",
12041 Initialize => $Lower & $ASCII,
12042 );
99870f4d
KW
12043
12044 my $Upper = $perl->add_match_table('Upper');
12045 my $Unicode_Upper = property_ref('Uppercase');
12046 if (defined $Unicode_Upper && ! $Unicode_Upper->is_empty) {
12047 $Upper->set_equivalent_to($Unicode_Upper->table('Y'), Related => 1);
a5c376b7
KW
12048 $Unicode_Upper->table('Y')->set_caseless_equivalent(property_ref('Cased')->table('Y'));
12049 $Unicode_Upper->table('N')->set_caseless_equivalent(property_ref('Cased')->table('N'));
12050 $Upper->set_caseless_equivalent(property_ref('Cased')->table('Y'));
99870f4d
KW
12051 }
12052 else {
12053 $Upper->set_equivalent_to($gc->table('Uppercase_Letter'),
12054 Related => 1);
12055 }
cbc24f92 12056 $Upper->add_alias('XPosixUpper');
a5c376b7 12057 my $Posix_Upper = $perl->add_match_table("PosixUpper",
ad5e8af1
KW
12058 Description => "[A-Z]",
12059 Initialize => $Upper & $ASCII,
12060 );
99870f4d
KW
12061
12062 # Earliest releases didn't have title case. Initialize it to empty if not
12063 # otherwise present
4364919a
KW
12064 my $Title = $perl->add_match_table('Title', Full_Name => 'Titlecase',
12065 Description => '(= \p{Gc=Lt})');
99870f4d 12066 my $lt = $gc->table('Lt');
a5c376b7
KW
12067
12068 # Earlier versions of mktables had this related to $lt since they have
c12f2655
KW
12069 # identical code points, but their caseless equivalents are not the same,
12070 # one being 'Cased' and the other being 'LC', and so now must be kept as
12071 # separate entities.
a5c376b7 12072 $Title += $lt if defined $lt;
99870f4d
KW
12073
12074 # If this Unicode version doesn't have Cased, set up our own. From
12075 # Unicode 5.1: Definition D120: A character C is defined to be cased if
12076 # and only if C has the Lowercase or Uppercase property or has a
12077 # General_Category value of Titlecase_Letter.
a5c376b7
KW
12078 my $Unicode_Cased = property_ref('Cased');
12079 unless (defined $Unicode_Cased) {
99870f4d
KW
12080 my $cased = $perl->add_match_table('Cased',
12081 Initialize => $Lower + $Upper + $Title,
12082 Description => 'Uppercase or Lowercase or Titlecase',
12083 );
a5c376b7 12084 $Unicode_Cased = $cased;
99870f4d 12085 }
a5c376b7 12086 $Title->set_caseless_equivalent($Unicode_Cased->table('Y'));
99870f4d
KW
12087
12088 # Similarly, set up our own Case_Ignorable property if this Unicode
12089 # version doesn't have it. From Unicode 5.1: Definition D121: A character
12090 # C is defined to be case-ignorable if C has the value MidLetter or the
12091 # value MidNumLet for the Word_Break property or its General_Category is
12092 # one of Nonspacing_Mark (Mn), Enclosing_Mark (Me), Format (Cf),
12093 # Modifier_Letter (Lm), or Modifier_Symbol (Sk).
12094
8050d00f
KW
12095 # Perl has long had an internal-only alias for this property; grandfather
12096 # it in to the pod, but discourage its use.
12097 my $perl_case_ignorable = $perl->add_match_table('_Case_Ignorable',
b15a0a3b
KW
12098 Re_Pod_Entry => 1,
12099 Fate => $INTERNAL_ONLY,
12100 Status => $DISCOURAGED);
99870f4d
KW
12101 my $case_ignorable = property_ref('Case_Ignorable');
12102 if (defined $case_ignorable && ! $case_ignorable->is_empty) {
12103 $perl_case_ignorable->set_equivalent_to($case_ignorable->table('Y'),
12104 Related => 1);
12105 }
12106 else {
12107
12108 $perl_case_ignorable->initialize($gc->table('Mn') + $gc->table('Lm'));
12109
12110 # The following three properties are not in early releases
12111 $perl_case_ignorable += $gc->table('Me') if defined $gc->table('Me');
12112 $perl_case_ignorable += $gc->table('Cf') if defined $gc->table('Cf');
12113 $perl_case_ignorable += $gc->table('Sk') if defined $gc->table('Sk');
12114
12115 # For versions 4.1 - 5.0, there is no MidNumLet property, and
12116 # correspondingly the case-ignorable definition lacks that one. For
12117 # 4.0, it appears that it was meant to be the same definition, but was
12118 # inadvertently omitted from the standard's text, so add it if the
12119 # property actually is there
12120 my $wb = property_ref('Word_Break');
12121 if (defined $wb) {
12122 my $midlet = $wb->table('MidLetter');
12123 $perl_case_ignorable += $midlet if defined $midlet;
12124 my $midnumlet = $wb->table('MidNumLet');
12125 $perl_case_ignorable += $midnumlet if defined $midnumlet;
12126 }
12127 else {
12128
12129 # In earlier versions of the standard, instead of the above two
12130 # properties , just the following characters were used:
12131 $perl_case_ignorable += 0x0027 # APOSTROPHE
12132 + 0x00AD # SOFT HYPHEN (SHY)
12133 + 0x2019; # RIGHT SINGLE QUOTATION MARK
12134 }
12135 }
12136
12137 # The remaining perl defined tables are mostly based on Unicode TR 18,
12138 # "Annex C: Compatibility Properties". All of these have two versions,
12139 # one whose name generally begins with Posix that is posix-compliant, and
12140 # one that matches Unicode characters beyond the Posix, ASCII range
12141
ad5e8af1 12142 my $Alpha = $perl->add_match_table('Alpha');
99870f4d
KW
12143
12144 # Alphabetic was not present in early releases
12145 my $Alphabetic = property_ref('Alphabetic');
12146 if (defined $Alphabetic && ! $Alphabetic->is_empty) {
12147 $Alpha->set_equivalent_to($Alphabetic->table('Y'), Related => 1);
12148 }
12149 else {
12150
12151 # For early releases, we don't get it exactly right. The below
12152 # includes more than it should, which in 5.2 terms is: L + Nl +
12153 # Other_Alphabetic. Other_Alphabetic contains many characters from
12154 # Mn and Mc. It's better to match more than we should, than less than
12155 # we should.
12156 $Alpha->initialize($gc->table('Letter')
12157 + $gc->table('Mn')
12158 + $gc->table('Mc'));
12159 $Alpha += $gc->table('Nl') if defined $gc->table('Nl');
ad5e8af1 12160 $Alpha->add_description('Alphabetic');
99870f4d 12161 }
cbc24f92 12162 $Alpha->add_alias('XPosixAlpha');
a5c376b7 12163 my $Posix_Alpha = $perl->add_match_table("PosixAlpha",
ad5e8af1
KW
12164 Description => "[A-Za-z]",
12165 Initialize => $Alpha & $ASCII,
12166 );
a5c376b7
KW
12167 $Posix_Upper->set_caseless_equivalent($Posix_Alpha);
12168 $Posix_Lower->set_caseless_equivalent($Posix_Alpha);
99870f4d
KW
12169
12170 my $Alnum = $perl->add_match_table('Alnum',
56339b2c 12171 Description => 'Alphabetic and (decimal) Numeric',
99870f4d
KW
12172 Initialize => $Alpha + $gc->table('Decimal_Number'),
12173 );
cbc24f92 12174 $Alnum->add_alias('XPosixAlnum');
ad5e8af1
KW
12175 $perl->add_match_table("PosixAlnum",
12176 Description => "[A-Za-z0-9]",
12177 Initialize => $Alnum & $ASCII,
12178 );
99870f4d
KW
12179
12180 my $Word = $perl->add_match_table('Word',
d35dd6c6
KW
12181 Description => '\w, including beyond ASCII;'
12182 . ' = \p{Alnum} + \pM + \p{Pc}',
99870f4d
KW
12183 Initialize => $Alnum + $gc->table('Mark'),
12184 );
cbc24f92 12185 $Word->add_alias('XPosixWord');
99870f4d
KW
12186 my $Pc = $gc->table('Connector_Punctuation'); # 'Pc' Not in release 1
12187 $Word += $Pc if defined $Pc;
12188
f38f76ae 12189 # This is a Perl extension, so the name doesn't begin with Posix.
cbc24f92 12190 my $PerlWord = $perl->add_match_table('PerlWord',
99870f4d
KW
12191 Description => '\w, restricted to ASCII = [A-Za-z0-9_]',
12192 Initialize => $Word & $ASCII,
12193 );
cbc24f92 12194 $PerlWord->add_alias('PosixWord');
99870f4d
KW
12195
12196 my $Blank = $perl->add_match_table('Blank',
12197 Description => '\h, Horizontal white space',
12198
12199 # 200B is Zero Width Space which is for line
12200 # break control, and was listed as
12201 # Space_Separator in early releases
12202 Initialize => $gc->table('Space_Separator')
12203 + 0x0009 # TAB
12204 - 0x200B, # ZWSP
12205 );
12206 $Blank->add_alias('HorizSpace'); # Another name for it.
cbc24f92 12207 $Blank->add_alias('XPosixBlank');
ad5e8af1
KW
12208 $perl->add_match_table("PosixBlank",
12209 Description => "\\t and ' '",
12210 Initialize => $Blank & $ASCII,
12211 );
99870f4d
KW
12212
12213 my $VertSpace = $perl->add_match_table('VertSpace',
12214 Description => '\v',
12215 Initialize => $gc->table('Line_Separator')
12216 + $gc->table('Paragraph_Separator')
12217 + 0x000A # LINE FEED
12218 + 0x000B # VERTICAL TAB
12219 + 0x000C # FORM FEED
12220 + 0x000D # CARRIAGE RETURN
12221 + 0x0085, # NEL
12222 );
12223 # No Posix equivalent for vertical space
12224
12225 my $Space = $perl->add_match_table('Space',
ad5e8af1
KW
12226 Description => '\s including beyond ASCII plus vertical tab',
12227 Initialize => $Blank + $VertSpace,
99870f4d 12228 );
cbc24f92 12229 $Space->add_alias('XPosixSpace');
ad5e8af1 12230 $perl->add_match_table("PosixSpace",
f38f76ae 12231 Description => "\\t, \\n, \\cK, \\f, \\r, and ' '. (\\cK is vertical tab)",
ad5e8af1
KW
12232 Initialize => $Space & $ASCII,
12233 );
99870f4d
KW
12234
12235 # Perl's traditional space doesn't include Vertical Tab
cbc24f92 12236 my $XPerlSpace = $perl->add_match_table('XPerlSpace',
99870f4d
KW
12237 Description => '\s, including beyond ASCII',
12238 Initialize => $Space - 0x000B,
12239 );
cbc24f92
KW
12240 $XPerlSpace->add_alias('SpacePerl'); # A pre-existing synonym
12241 my $PerlSpace = $perl->add_match_table('PerlSpace',
de25ec47
KW
12242 Description => '\s, restricted to ASCII = [ \f\n\r\t]',
12243 Initialize => $XPerlSpace & $ASCII,
99870f4d
KW
12244 );
12245
cbc24f92 12246
99870f4d 12247 my $Cntrl = $perl->add_match_table('Cntrl',
ad5e8af1 12248 Description => 'Control characters');
99870f4d 12249 $Cntrl->set_equivalent_to($gc->table('Cc'), Related => 1);
cbc24f92 12250 $Cntrl->add_alias('XPosixCntrl');
ad5e8af1 12251 $perl->add_match_table("PosixCntrl",
f38f76ae 12252 Description => "ASCII control characters: NUL, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS, HT, LF, VT, FF, CR, SO, SI, DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB, CAN, EOM, SUB, ESC, FS, GS, RS, US, and DEL",
ad5e8af1
KW
12253 Initialize => $Cntrl & $ASCII,
12254 );
99870f4d
KW
12255
12256 # $controls is a temporary used to construct Graph.
12257 my $controls = Range_List->new(Initialize => $gc->table('Unassigned')
12258 + $gc->table('Control'));
12259 # Cs not in release 1
12260 $controls += $gc->table('Surrogate') if defined $gc->table('Surrogate');
12261
12262 # Graph is ~space & ~(Cc|Cs|Cn) = ~(space + $controls)
12263 my $Graph = $perl->add_match_table('Graph',
ad5e8af1 12264 Description => 'Characters that are graphical',
99870f4d
KW
12265 Initialize => ~ ($Space + $controls),
12266 );
cbc24f92 12267 $Graph->add_alias('XPosixGraph');
ad5e8af1 12268 $perl->add_match_table("PosixGraph",
f38f76ae
KW
12269 Description =>
12270 '[-!"#$%&\'()*+,./:;<>?@[\\\]^_`{|}~0-9A-Za-z]',
ad5e8af1
KW
12271 Initialize => $Graph & $ASCII,
12272 );
99870f4d 12273
3e20195b 12274 $print = $perl->add_match_table('Print',
ad5e8af1 12275 Description => 'Characters that are graphical plus space characters (but no controls)',
ae5b72c8 12276 Initialize => $Blank + $Graph - $gc->table('Control'),
99870f4d 12277 );
cbc24f92 12278 $print->add_alias('XPosixPrint');
ad5e8af1 12279 $perl->add_match_table("PosixPrint",
66fd7fd0 12280 Description =>
f38f76ae 12281 '[- 0-9A-Za-z!"#$%&\'()*+,./:;<>?@[\\\]^_`{|}~]',
3e20195b 12282 Initialize => $print & $ASCII,
ad5e8af1 12283 );
99870f4d
KW
12284
12285 my $Punct = $perl->add_match_table('Punct');
12286 $Punct->set_equivalent_to($gc->table('Punctuation'), Related => 1);
12287
12288 # \p{punct} doesn't include the symbols, which posix does
cbc24f92
KW
12289 my $XPosixPunct = $perl->add_match_table('XPosixPunct',
12290 Description => '\p{Punct} + ASCII-range \p{Symbol}',
12291 Initialize => $gc->table('Punctuation')
12292 + ($ASCII & $gc->table('Symbol')),
bb080638 12293 Perl_Extension => 1
cbc24f92 12294 );
bb080638 12295 $perl->add_match_table('PosixPunct', Perl_Extension => 1,
f38f76ae 12296 Description => '[-!"#$%&\'()*+,./:;<>?@[\\\]^_`{|}~]',
cbc24f92 12297 Initialize => $ASCII & $XPosixPunct,
ad5e8af1 12298 );
99870f4d
KW
12299
12300 my $Digit = $perl->add_match_table('Digit',
f3a73f6e 12301 Description => '[0-9] + all other decimal digits');
99870f4d 12302 $Digit->set_equivalent_to($gc->table('Decimal_Number'), Related => 1);
cbc24f92 12303 $Digit->add_alias('XPosixDigit');
ad5e8af1
KW
12304 my $PosixDigit = $perl->add_match_table("PosixDigit",
12305 Description => '[0-9]',
12306 Initialize => $Digit & $ASCII,
12307 );
99870f4d 12308
eadadd41
KW
12309 # Hex_Digit was not present in first release
12310 my $Xdigit = $perl->add_match_table('XDigit');
cbc24f92 12311 $Xdigit->add_alias('XPosixXDigit');
eadadd41
KW
12312 my $Hex = property_ref('Hex_Digit');
12313 if (defined $Hex && ! $Hex->is_empty) {
12314 $Xdigit->set_equivalent_to($Hex->table('Y'), Related => 1);
99870f4d
KW
12315 }
12316 else {
eadadd41
KW
12317 # (Have to use hex instead of e.g. '0', because could be running on an
12318 # non-ASCII machine, and we want the Unicode (ASCII) values)
12319 $Xdigit->initialize([ 0x30..0x39, 0x41..0x46, 0x61..0x66,
12320 0xFF10..0xFF19, 0xFF21..0xFF26, 0xFF41..0xFF46]);
12321 $Xdigit->add_description('[0-9A-Fa-f] and corresponding fullwidth versions, like U+FF10: FULLWIDTH DIGIT ZERO');
99870f4d 12322 }
4efcc33b
KW
12323
12324 # AHex was not present in early releases
12325 my $PosixXDigit = $perl->add_match_table('PosixXDigit');
12326 my $AHex = property_ref('ASCII_Hex_Digit');
12327 if (defined $AHex && ! $AHex->is_empty) {
12328 $PosixXDigit->set_equivalent_to($AHex->table('Y'), Related => 1);
12329 }
12330 else {
12331 $PosixXDigit->initialize($Xdigit & $ASCII);
12332 }
12333 $PosixXDigit->add_description('[0-9A-Fa-f]');
99870f4d 12334
99870f4d
KW
12335 my $dt = property_ref('Decomposition_Type');
12336 $dt->add_match_table('Non_Canon', Full_Name => 'Non_Canonical',
12337 Initialize => ~ ($dt->table('None') + $dt->table('Canonical')),
12338 Perl_Extension => 1,
d57ccc9a 12339 Note => 'Union of all non-canonical decompositions',
99870f4d
KW
12340 );
12341
12342 # _CanonDCIJ is equivalent to Soft_Dotted, but if on a release earlier
12343 # than SD appeared, construct it ourselves, based on the first release SD
8050d00f 12344 # was in. A pod entry is grandfathered in for it
33e96e72 12345 my $CanonDCIJ = $perl->add_match_table('_CanonDCIJ', Re_Pod_Entry => 1,
301ba948
KW
12346 Perl_Extension => 1,
12347 Fate => $INTERNAL_ONLY,
12348 Status => $DISCOURAGED);
99870f4d
KW
12349 my $soft_dotted = property_ref('Soft_Dotted');
12350 if (defined $soft_dotted && ! $soft_dotted->is_empty) {
12351 $CanonDCIJ->set_equivalent_to($soft_dotted->table('Y'), Related => 1);
12352 }
12353 else {
12354
12355 # This list came from 3.2 Soft_Dotted.
12356 $CanonDCIJ->initialize([ 0x0069,
12357 0x006A,
12358 0x012F,
12359 0x0268,
12360 0x0456,
12361 0x0458,
12362 0x1E2D,
12363 0x1ECB,
12364 ]);
12365 $CanonDCIJ = $CanonDCIJ & $Assigned;
12366 }
12367
f86864ac 12368 # These are used in Unicode's definition of \X
6ba2d696 12369 my $begin = $perl->add_match_table('_X_Begin', Perl_Extension => 1,
301ba948 12370 Fate => $INTERNAL_ONLY);
6ba2d696 12371 my $extend = $perl->add_match_table('_X_Extend', Perl_Extension => 1,
301ba948 12372 Fate => $INTERNAL_ONLY);
37e2e78e 12373
ee24a51c
KW
12374 # For backward compatibility, Perl has its own definition for IDStart
12375 # First, we include the underscore, and then the regular XID_Start also
12376 # have to be Words
12377 $perl->add_match_table('_Perl_IDStart',
12378 Perl_Extension => 1,
301ba948 12379 Fate => $INTERNAL_ONLY,
ee24a51c
KW
12380 Initialize =>
12381 ord('_')
12382 + (property_ref('XID_Start')->table('Y') & $Word)
12383 );
12384
99870f4d 12385 my $gcb = property_ref('Grapheme_Cluster_Break');
37e2e78e 12386
678f13d5 12387 # The 'extended' grapheme cluster came in 5.1. The non-extended
37e2e78e
KW
12388 # definition differs too much from the traditional Perl one to use.
12389 if (defined $gcb && defined $gcb->table('SpacingMark')) {
12390
12391 # Note that assumes HST is defined; it came in an earlier release than
12392 # GCB. In the line below, two negatives means: yes hangul
12393 $begin += ~ property_ref('Hangul_Syllable_Type')
12394 ->table('Not_Applicable')
12395 + ~ ($gcb->table('Control')
12396 + $gcb->table('CR')
12397 + $gcb->table('LF'));
12398 $begin->add_comment('For use in \X; matches: Hangul_Syllable | ! Control');
12399
12400 $extend += $gcb->table('Extend') + $gcb->table('SpacingMark');
12401 $extend->add_comment('For use in \X; matches: Extend | SpacingMark');
99870f4d
KW
12402 }
12403 else { # Old definition, used on early releases.
f86864ac 12404 $extend += $gc->table('Mark')
37e2e78e
KW
12405 + 0x200C # ZWNJ
12406 + 0x200D; # ZWJ
12407 $begin += ~ $extend;
12408
12409 # Here we may have a release that has the regular grapheme cluster
12410 # defined, or a release that doesn't have anything defined.
12411 # We set things up so the Perl core degrades gracefully, possibly with
12412 # placeholders that match nothing.
12413
12414 if (! defined $gcb) {
12415 $gcb = Property->new('GCB', Status => $PLACEHOLDER);
12416 }
12417 my $hst = property_ref('HST');
12418 if (!defined $hst) {
12419 $hst = Property->new('HST', Status => $PLACEHOLDER);
12420 $hst->add_match_table('Not_Applicable',
12421 Initialize => $Any,
12422 Matches_All => 1);
12423 }
12424
12425 # On some releases, here we may not have the needed tables for the
12426 # perl core, in some releases we may.
12427 foreach my $name (qw{ L LV LVT T V prepend }) {
12428 my $table = $gcb->table($name);
12429 if (! defined $table) {
12430 $table = $gcb->add_match_table($name);
12431 push @tables_that_may_be_empty, $table->complete_name;
12432 }
12433
12434 # The HST property predates the GCB one, and has identical tables
12435 # for some of them, so use it if we can.
12436 if ($table->is_empty
12437 && defined $hst
12438 && defined $hst->table($name))
12439 {
12440 $table += $hst->table($name);
12441 }
12442 }
12443 }
12444
12445 # More GCB. If we found some hangul syllables, populate a combined
12446 # table.
301ba948
KW
12447 my $lv_lvt_v = $perl->add_match_table('_X_LV_LVT_V',
12448 Perl_Extension => 1,
12449 Fate => $INTERNAL_ONLY);
37e2e78e
KW
12450 my $LV = $gcb->table('LV');
12451 if ($LV->is_empty) {
12452 push @tables_that_may_be_empty, $lv_lvt_v->complete_name;
12453 } else {
12454 $lv_lvt_v += $LV + $gcb->table('LVT') + $gcb->table('V');
12455 $lv_lvt_v->add_comment('For use in \X; matches: HST=LV | HST=LVT | HST=V');
99870f4d
KW
12456 }
12457
28093d0e 12458 # Was previously constructed to contain both Name and Unicode_1_Name
99870f4d
KW
12459 my @composition = ('Name', 'Unicode_1_Name');
12460
12461 if (@named_sequences) {
12462 push @composition, 'Named_Sequence';
12463 foreach my $sequence (@named_sequences) {
12464 $perl_charname->add_anomalous_entry($sequence);
12465 }
12466 }
12467
12468 my $alias_sentence = "";
12469 my $alias = property_ref('Name_Alias');
12470 if (defined $alias) {
12471 push @composition, 'Name_Alias';
9ba5575c 12472 $perl_charname->set_proxy_for('Name_Alias');
b8ba2307
KW
12473 my $unicode_1 = property_ref('Unicode_1_Name');
12474 my %abbreviations;
12475
12476 # Add each entry in Name_Alias to Perl_Charnames. Where these go with
12477 # respect to any existing entry depends on the entry type.
12478 # Corrections go before said entry, as they should be returned in
12479 # preference over the existing entry. (A correction to a correction
12480 # should be later in the Name_Alias table, so it will correctly
12481 # precede the erroneous correction in Perl_Charnames.)
12482 #
12483 # Abbreviations go after everything else, so they are saved
12484 # temporarily in a hash for later.
12485 #
12486 # Controls are currently added afterwards. This is because Perl has
12487 # previously used the Unicode1 name, and so should still use that.
12488 # (Most of them will be the same anyway, in which case we don't add a
12489 # duplicate)
12490
99870f4d
KW
12491 $alias->reset_each_range;
12492 while (my ($range) = $alias->each_range) {
12493 next if $range->value eq "";
b8ba2307
KW
12494 my $code_point = $range->start;
12495 if ($code_point != $range->end) {
12496 Carp::my_carp_bug("Bad News. Expecting only one code point in the range $range. Just to keep going, using only the first code point;");
12497 }
12498 my ($value, $type) = split ': ', $range->value;
12499 my $replace_type;
12500 if ($type eq 'correction') {
12501 $replace_type = $MULTIPLE_BEFORE;
99870f4d 12502 }
b8ba2307
KW
12503 elsif ($type eq 'abbreviation') {
12504
12505 # Save for later
12506 $abbreviations{$value} = $code_point;
12507 next;
12508 }
12509 elsif ($type eq 'control') {
12510 my $unicode_1_value = $unicode_1->value_of($code_point);
12511 next if $unicode_1_value eq $value;
12512 $replace_type = $MULTIPLE_AFTER;
12513 }
12514 else {
12515 $replace_type = $MULTIPLE_AFTER;
12516 }
12517
12518 # Actually add; before or after current entry(ies) as determined
12519 # above.
12520 $perl_charname->add_duplicate($code_point, $value, Replace => $replace_type);
12521 }
12522
12523 # Now that have everything added, add in abbreviations after
12524 # everything else.
12525 foreach my $value (keys %abbreviations) {
12526 $perl_charname->add_duplicate($abbreviations{$value}, $value, Replace => $MULTIPLE_AFTER);
99870f4d
KW
12527 }
12528 $alias_sentence = <<END;
7620cb10
KW
12529The Name_Alias property adds duplicate code point entries that are
12530alternatives to the original name. If an addition is a corrected
12531name, it will be physically first in the table. The original (less correct,
12532but still valid) name will be next; then any alternatives, in no particular
12533order; and finally any abbreviations, again in no particular order.
99870f4d
KW
12534END
12535 }
7620cb10 12536
99870f4d
KW
12537 my $comment;
12538 if (@composition <= 2) { # Always at least 2
12539 $comment = join " and ", @composition;
12540 }
12541 else {
12542 $comment = join ", ", @composition[0 .. scalar @composition - 2];
12543 $comment .= ", and $composition[-1]";
12544 }
12545
99870f4d
KW
12546 $perl_charname->add_comment(join_lines( <<END
12547This file is for charnames.pm. It is the union of the $comment properties.
7620cb10
KW
12548Unicode_1_Name entries are used only for nameless code points in the Name
12549property.
99870f4d 12550$alias_sentence
a03f0b9f
KW
12551This file doesn't include the algorithmically determinable names. For those,
12552use 'unicore/Name.pm'
12553END
12554 ));
12555 property_ref('Name')->add_comment(join_lines( <<END
12556This file doesn't include the algorithmically determinable names. For those,
12557use 'unicore/Name.pm'
99870f4d
KW
12558END
12559 ));
12560
99870f4d
KW
12561 # Construct the Present_In property from the Age property.
12562 if (-e 'DAge.txt' && defined (my $age = property_ref('Age'))) {
12563 my $default_map = $age->default_map;
12564 my $in = Property->new('In',
12565 Default_Map => $default_map,
12566 Full_Name => "Present_In",
99870f4d
KW
12567 Perl_Extension => 1,
12568 Type => $ENUM,
12569 Initialize => $age,
12570 );
12571 $in->add_comment(join_lines(<<END
c12f2655 12572THIS FILE SHOULD NOT BE USED FOR ANY PURPOSE. The values in this file are the
99870f4d
KW
12573same as for $age, and not for what $in really means. This is because anything
12574defined in a given release should have multiple values: that release and all
12575higher ones. But only one value per code point can be represented in a table
12576like this.
12577END
12578 ));
12579
12580 # The Age tables are named like 1.5, 2.0, 2.1, .... Sort so that the
12581 # lowest numbered (earliest) come first, with the non-numeric one
12582 # last.
12583 my ($first_age, @rest_ages) = sort { ($a->name !~ /^[\d.]*$/)
12584 ? 1
12585 : ($b->name !~ /^[\d.]*$/)
12586 ? -1
12587 : $a->name <=> $b->name
12588 } $age->tables;
12589
12590 # The Present_In property is the cumulative age properties. The first
12591 # one hence is identical to the first age one.
12592 my $previous_in = $in->add_match_table($first_age->name);
12593 $previous_in->set_equivalent_to($first_age, Related => 1);
12594
12595 my $description_start = "Code point's usage introduced in version ";
12596 $first_age->add_description($description_start . $first_age->name);
12597
98dc9551 12598 # To construct the accumulated values, for each of the age tables
99870f4d
KW
12599 # starting with the 2nd earliest, merge the earliest with it, to get
12600 # all those code points existing in the 2nd earliest. Repeat merging
12601 # the new 2nd earliest with the 3rd earliest to get all those existing
12602 # in the 3rd earliest, and so on.
12603 foreach my $current_age (@rest_ages) {
12604 next if $current_age->name !~ /^[\d.]*$/; # Skip the non-numeric
12605
12606 my $current_in = $in->add_match_table(
12607 $current_age->name,
12608 Initialize => $current_age + $previous_in,
12609 Description => $description_start
12610 . $current_age->name
12611 . ' or earlier',
12612 );
12613 $previous_in = $current_in;
12614
12615 # Add clarifying material for the corresponding age file. This is
12616 # in part because of the confusing and contradictory information
12617 # given in the Standard's documentation itself, as of 5.2.
12618 $current_age->add_description(
12619 "Code point's usage was introduced in version "
12620 . $current_age->name);
12621 $current_age->add_note("See also $in");
12622
12623 }
12624
12625 # And finally the code points whose usages have yet to be decided are
12626 # the same in both properties. Note that permanently unassigned code
12627 # points actually have their usage assigned (as being permanently
12628 # unassigned), so that these tables are not the same as gc=cn.
12629 my $unassigned = $in->add_match_table($default_map);
12630 my $age_default = $age->table($default_map);
12631 $age_default->add_description(<<END
12632Code point's usage has not been assigned in any Unicode release thus far.
12633END
12634 );
12635 $unassigned->set_equivalent_to($age_default, Related => 1);
12636 }
12637
12638
12639 # Finished creating all the perl properties. All non-internal non-string
12640 # ones have a synonym of 'Is_' prefixed. (Internal properties begin with
12641 # an underscore.) These do not get a separate entry in the pod file
12642 foreach my $table ($perl->tables) {
12643 foreach my $alias ($table->aliases) {
12644 next if $alias->name =~ /^_/;
12645 $table->add_alias('Is_' . $alias->name,
33e96e72 12646 Re_Pod_Entry => 0,
fd1e3e84 12647 UCD => 0,
99870f4d 12648 Status => $alias->status,
0eac1e20 12649 OK_as_Filename => 0);
99870f4d
KW
12650 }
12651 }
12652
c4019d52
KW
12653 # Here done with all the basic stuff. Ready to populate the information
12654 # about each character if annotating them.
558712cf 12655 if ($annotate) {
c4019d52
KW
12656
12657 # See comments at its declaration
12658 $annotate_ranges = Range_Map->new;
12659
12660 # This separates out the non-characters from the other unassigneds, so
12661 # can give different annotations for each.
12662 $unassigned_sans_noncharacters = Range_List->new(
12663 Initialize => $gc->table('Unassigned')
12664 & property_ref('Noncharacter_Code_Point')->table('N'));
12665
6189eadc 12666 for (my $i = 0; $i <= $MAX_UNICODE_CODEPOINT; $i++ ) {
c4019d52
KW
12667 $i = populate_char_info($i); # Note sets $i so may cause skips
12668 }
12669 }
12670
99870f4d
KW
12671 return;
12672}
12673
12674sub add_perl_synonyms() {
12675 # A number of Unicode tables have Perl synonyms that are expressed in
12676 # the single-form, \p{name}. These are:
12677 # All the binary property Y tables, so that \p{Name=Y} gets \p{Name} and
12678 # \p{Is_Name} as synonyms
12679 # \p{Script=Value} gets \p{Value}, \p{Is_Value} as synonyms
12680 # \p{General_Category=Value} gets \p{Value}, \p{Is_Value} as synonyms
12681 # \p{Block=Value} gets \p{In_Value} as a synonym, and, if there is no
12682 # conflict, \p{Value} and \p{Is_Value} as well
12683 #
12684 # This routine generates these synonyms, warning of any unexpected
12685 # conflicts.
12686
12687 # Construct the list of tables to get synonyms for. Start with all the
12688 # binary and the General_Category ones.
06f26c45
KW
12689 my @tables = grep { $_->type == $BINARY || $_->type == $FORCED_BINARY }
12690 property_ref('*');
99870f4d
KW
12691 push @tables, $gc->tables;
12692
12693 # If the version of Unicode includes the Script property, add its tables
359523e2 12694 push @tables, $script->tables if defined $script;
99870f4d
KW
12695
12696 # The Block tables are kept separate because they are treated differently.
12697 # And the earliest versions of Unicode didn't include them, so add only if
12698 # there are some.
12699 my @blocks;
12700 push @blocks, $block->tables if defined $block;
12701
12702 # Here, have the lists of tables constructed. Process blocks last so that
12703 # if there are name collisions with them, blocks have lowest priority.
12704 # Should there ever be other collisions, manual intervention would be
12705 # required. See the comments at the beginning of the program for a
12706 # possible way to handle those semi-automatically.
12707 foreach my $table (@tables, @blocks) {
12708
12709 # For non-binary properties, the synonym is just the name of the
12710 # table, like Greek, but for binary properties the synonym is the name
12711 # of the property, and means the code points in its 'Y' table.
12712 my $nominal = $table;
12713 my $nominal_property = $nominal->property;
12714 my $actual;
12715 if (! $nominal->isa('Property')) {
12716 $actual = $table;
12717 }
12718 else {
12719
12720 # Here is a binary property. Use the 'Y' table. Verify that is
12721 # there
12722 my $yes = $nominal->table('Y');
12723 unless (defined $yes) { # Must be defined, but is permissible to
12724 # be empty.
12725 Carp::my_carp_bug("Undefined $nominal, 'Y'. Skipping.");
12726 next;
12727 }
12728 $actual = $yes;
12729 }
12730
12731 foreach my $alias ($nominal->aliases) {
12732
12733 # Attempt to create a table in the perl directory for the
12734 # candidate table, using whatever aliases in it that don't
12735 # conflict. Also add non-conflicting aliases for all these
12736 # prefixed by 'Is_' (and/or 'In_' for Block property tables)
12737 PREFIX:
12738 foreach my $prefix ("", 'Is_', 'In_') {
12739
12740 # Only Block properties can have added 'In_' aliases.
12741 next if $prefix eq 'In_' and $nominal_property != $block;
12742
12743 my $proposed_name = $prefix . $alias->name;
12744
12745 # No Is_Is, In_In, nor combinations thereof
12746 trace "$proposed_name is a no-no" if main::DEBUG && $to_trace && $proposed_name =~ /^ I [ns] _I [ns] _/x;
12747 next if $proposed_name =~ /^ I [ns] _I [ns] _/x;
12748
12749 trace "Seeing if can add alias or table: 'perl=$proposed_name' based on $nominal" if main::DEBUG && $to_trace;
12750
12751 # Get a reference to any existing table in the perl
12752 # directory with the desired name.
12753 my $pre_existing = $perl->table($proposed_name);
12754
12755 if (! defined $pre_existing) {
12756
12757 # No name collision, so ok to add the perl synonym.
12758
33e96e72 12759 my $make_re_pod_entry;
0eac1e20 12760 my $ok_as_filename;
4cd1260a 12761 my $status = $alias->status;
99870f4d
KW
12762 if ($nominal_property == $block) {
12763
12764 # For block properties, the 'In' form is preferred for
12765 # external use; the pod file contains wild cards for
12766 # this and the 'Is' form so no entries for those; and
12767 # we don't want people using the name without the
12768 # 'In', so discourage that.
12769 if ($prefix eq "") {
33e96e72 12770 $make_re_pod_entry = 1;
99870f4d 12771 $status = $status || $DISCOURAGED;
0eac1e20 12772 $ok_as_filename = 0;
99870f4d
KW
12773 }
12774 elsif ($prefix eq 'In_') {
33e96e72 12775 $make_re_pod_entry = 0;
99870f4d 12776 $status = $status || $NORMAL;
0eac1e20 12777 $ok_as_filename = 1;
99870f4d
KW
12778 }
12779 else {
33e96e72 12780 $make_re_pod_entry = 0;
99870f4d 12781 $status = $status || $DISCOURAGED;
0eac1e20 12782 $ok_as_filename = 0;
99870f4d
KW
12783 }
12784 }
12785 elsif ($prefix ne "") {
12786
12787 # The 'Is' prefix is handled in the pod by a wild
12788 # card, and we won't use it for an external name
33e96e72 12789 $make_re_pod_entry = 0;
99870f4d 12790 $status = $status || $NORMAL;
0eac1e20 12791 $ok_as_filename = 0;
99870f4d
KW
12792 }
12793 else {
12794
12795 # Here, is an empty prefix, non block. This gets its
12796 # own pod entry and can be used for an external name.
33e96e72 12797 $make_re_pod_entry = 1;
99870f4d 12798 $status = $status || $NORMAL;
0eac1e20 12799 $ok_as_filename = 1;
99870f4d
KW
12800 }
12801
12802 # Here, there isn't a perl pre-existing table with the
12803 # name. Look through the list of equivalents of this
12804 # table to see if one is a perl table.
12805 foreach my $equivalent ($actual->leader->equivalents) {
12806 next if $equivalent->property != $perl;
12807
12808 # Here, have found a table for $perl. Add this alias
12809 # to it, and are done with this prefix.
12810 $equivalent->add_alias($proposed_name,
33e96e72 12811 Re_Pod_Entry => $make_re_pod_entry,
fd1e3e84
KW
12812
12813 # Currently don't output these in the
12814 # ucd pod, as are strongly discouraged
12815 # from being used
12816 UCD => 0,
12817
99870f4d 12818 Status => $status,
0eac1e20 12819 OK_as_Filename => $ok_as_filename);
99870f4d
KW
12820 trace "adding alias perl=$proposed_name to $equivalent" if main::DEBUG && $to_trace;
12821 next PREFIX;
12822 }
12823
12824 # Here, $perl doesn't already have a table that is a
12825 # synonym for this property, add one.
12826 my $added_table = $perl->add_match_table($proposed_name,
33e96e72 12827 Re_Pod_Entry => $make_re_pod_entry,
fd1e3e84
KW
12828
12829 # See UCD comment just above
12830 UCD => 0,
12831
99870f4d 12832 Status => $status,
0eac1e20 12833 OK_as_Filename => $ok_as_filename);
99870f4d
KW
12834 # And it will be related to the actual table, since it is
12835 # based on it.
12836 $added_table->set_equivalent_to($actual, Related => 1);
12837 trace "added ", $perl->table($proposed_name) if main::DEBUG && $to_trace;
12838 next;
12839 } # End of no pre-existing.
12840
12841 # Here, there is a pre-existing table that has the proposed
12842 # name. We could be in trouble, but not if this is just a
12843 # synonym for another table that we have already made a child
12844 # of the pre-existing one.
6505c6e2 12845 if ($pre_existing->is_set_equivalent_to($actual)) {
99870f4d
KW
12846 trace "$pre_existing is already equivalent to $actual; adding alias perl=$proposed_name to it" if main::DEBUG && $to_trace;
12847 $pre_existing->add_alias($proposed_name);
12848 next;
12849 }
12850
12851 # Here, there is a name collision, but it still could be ok if
12852 # the tables match the identical set of code points, in which
12853 # case, we can combine the names. Compare each table's code
12854 # point list to see if they are identical.
12855 trace "Potential name conflict with $pre_existing having ", $pre_existing->count, " code points" if main::DEBUG && $to_trace;
12856 if ($pre_existing->matches_identically_to($actual)) {
12857
12858 # Here, they do match identically. Not a real conflict.
12859 # Make the perl version a child of the Unicode one, except
12860 # in the non-obvious case of where the perl name is
12861 # already a synonym of another Unicode property. (This is
12862 # excluded by the test for it being its own parent.) The
12863 # reason for this exclusion is that then the two Unicode
12864 # properties become related; and we don't really know if
12865 # they are or not. We generate documentation based on
12866 # relatedness, and this would be misleading. Code
12867 # later executed in the process will cause the tables to
12868 # be represented by a single file anyway, without making
12869 # it look in the pod like they are necessarily related.
12870 if ($pre_existing->parent == $pre_existing
12871 && ($pre_existing->property == $perl
12872 || $actual->property == $perl))
12873 {
12874 trace "Setting $pre_existing equivalent to $actual since one is \$perl, and match identical sets" if main::DEBUG && $to_trace;
12875 $pre_existing->set_equivalent_to($actual, Related => 1);
12876 }
12877 elsif (main::DEBUG && $to_trace) {
12878 trace "$pre_existing is equivalent to $actual since match identical sets, but not setting them equivalent, to preserve the separateness of the perl aliases";
12879 trace $pre_existing->parent;
12880 }
12881 next PREFIX;
12882 }
12883
12884 # Here they didn't match identically, there is a real conflict
12885 # between our new name and a pre-existing property.
12886 $actual->add_conflicting($proposed_name, 'p', $pre_existing);
12887 $pre_existing->add_conflicting($nominal->full_name,
12888 'p',
12889 $actual);
12890
12891 # Don't output a warning for aliases for the block
12892 # properties (unless they start with 'In_') as it is
12893 # expected that there will be conflicts and the block
12894 # form loses.
12895 if ($verbosity >= $NORMAL_VERBOSITY
12896 && ($actual->property != $block || $prefix eq 'In_'))
12897 {
12898 print simple_fold(join_lines(<<END
12899There is already an alias named $proposed_name (from " . $pre_existing . "),
12900so not creating this alias for " . $actual
12901END
12902 ), "", 4);
12903 }
12904
12905 # Keep track for documentation purposes.
12906 $has_In_conflicts++ if $prefix eq 'In_';
12907 $has_Is_conflicts++ if $prefix eq 'Is_';
12908 }
12909 }
12910 }
12911
12912 # There are some properties which have No and Yes (and N and Y) as
12913 # property values, but aren't binary, and could possibly be confused with
12914 # binary ones. So create caveats for them. There are tables that are
12915 # named 'No', and tables that are named 'N', but confusion is not likely
12916 # unless they are the same table. For example, N meaning Number or
12917 # Neutral is not likely to cause confusion, so don't add caveats to things
12918 # like them.
06f26c45
KW
12919 foreach my $property (grep { $_->type != $BINARY
12920 && $_->type != $FORCED_BINARY }
12921 property_ref('*'))
12922 {
99870f4d
KW
12923 my $yes = $property->table('Yes');
12924 if (defined $yes) {
12925 my $y = $property->table('Y');
12926 if (defined $y && $yes == $y) {
12927 foreach my $alias ($property->aliases) {
12928 $yes->add_conflicting($alias->name);
12929 }
12930 }
12931 }
12932 my $no = $property->table('No');
12933 if (defined $no) {
12934 my $n = $property->table('N');
12935 if (defined $n && $no == $n) {
12936 foreach my $alias ($property->aliases) {
12937 $no->add_conflicting($alias->name, 'P');
12938 }
12939 }
12940 }
12941 }
12942
12943 return;
12944}
12945
12946sub register_file_for_name($$$) {
12947 # Given info about a table and a datafile that it should be associated
98dc9551 12948 # with, register that association
99870f4d
KW
12949
12950 my $table = shift;
12951 my $directory_ref = shift; # Array of the directory path for the file
e6ebc4c0 12952 my $file = shift; # The file name in the final directory.
99870f4d
KW
12953 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
12954
12955 trace "table=$table, file=$file, directory=@$directory_ref" if main::DEBUG && $to_trace;
12956
12957 if ($table->isa('Property')) {
12958 $table->set_file_path(@$directory_ref, $file);
48cf9da9 12959 push @map_properties, $table;
315bfd4e
KW
12960
12961 # No swash means don't do the rest of this.
12962 return if $table->fate != $ORDINARY;
12963
12964 # Get the path to the file
12965 my @path = $table->file_path;
12966
12967 # Use just the file name if no subdirectory.
12968 shift @path if $path[0] eq File::Spec->curdir();
12969
12970 my $file = join '/', @path;
12971
12972 # Create a hash entry for utf8_heavy to get the file that stores this
12973 # property's map table
12974 foreach my $alias ($table->aliases) {
12975 my $name = $alias->name;
12976 $loose_property_to_file_of{standardize($name)} = $file;
12977 }
12978
89cf10cc
KW
12979 # And a way for utf8_heavy to find the proper key in the SwashInfo
12980 # hash for this property.
12981 $file_to_swash_name{$file} = "To" . $table->swash_name;
99870f4d
KW
12982 return;
12983 }
12984
12985 # Do all of the work for all equivalent tables when called with the leader
12986 # table, so skip if isn't the leader.
12987 return if $table->leader != $table;
12988
a92d5c2e
KW
12989 # If this is a complement of another file, use that other file instead,
12990 # with a ! prepended to it.
12991 my $complement;
12992 if (($complement = $table->complement) != 0) {
12993 my @directories = $complement->file_path;
12994
12995 # This assumes that the 0th element is something like 'lib',
12996 # the 1th element the property name (in its own directory), like
12997 # 'AHex', and the 2th element the file like 'Y' which will have a .pl
12998 # appended to it later.
12999 $directories[1] =~ s/^/!/;
13000 $file = pop @directories;
13001 $directory_ref =\@directories;
13002 }
13003
99870f4d
KW
13004 # Join all the file path components together, using slashes.
13005 my $full_filename = join('/', @$directory_ref, $file);
13006
13007 # All go in the same subdirectory of unicore
13008 if ($directory_ref->[0] ne $matches_directory) {
13009 Carp::my_carp("Unexpected directory in "
13010 . join('/', @{$directory_ref}, $file));
13011 }
13012
13013 # For this table and all its equivalents ...
13014 foreach my $table ($table, $table->equivalents) {
13015
13016 # Associate it with its file internally. Don't include the
13017 # $matches_directory first component
13018 $table->set_file_path(@$directory_ref, $file);
c15fda25
KW
13019
13020 # No swash means don't do the rest of this.
13021 next if $table->isa('Map_Table') && $table->fate != $ORDINARY;
13022
99870f4d
KW
13023 my $sub_filename = join('/', $directory_ref->[1, -1], $file);
13024
13025 my $property = $table->property;
ae51efca
KW
13026 my $property_name = ($property == $perl)
13027 ? "" # 'perl' is never explicitly stated
13028 : standardize($property->name) . '=';
99870f4d 13029
c15fda25
KW
13030 my $is_default = 0; # Is this table the default one for the property?
13031
13032 # To calculate $is_default, we find if this table is the same as the
13033 # default one for the property. But this is complicated by the
13034 # possibility that there is a master table for this one, and the
13035 # information is stored there instead of here.
9e4a1e86
KW
13036 my $parent = $table->parent;
13037 my $leader_prop = $parent->property;
c15fda25
KW
13038 my $default_map = $leader_prop->default_map;
13039 if (defined $default_map) {
13040 my $default_table = $leader_prop->table($default_map);
13041 $is_default = 1 if defined $default_table && $parent == $default_table;
13042 }
9e4a1e86
KW
13043
13044 # Calculate the loose name for this table. Mostly it's just its name,
13045 # standardized. But in the case of Perl tables that are single-form
13046 # equivalents to Unicode properties, it is the latter's name.
13047 my $loose_table_name =
13048 ($property != $perl || $leader_prop == $perl)
13049 ? standardize($table->name)
13050 : standardize($parent->name);
13051
99870f4d
KW
13052 my $deprecated = ($table->status eq $DEPRECATED)
13053 ? $table->status_info
13054 : "";
d867ccfb 13055 my $caseless_equivalent = $table->caseless_equivalent;
99870f4d
KW
13056
13057 # And for each of the table's aliases... This inner loop eventually
13058 # goes through all aliases in the UCD that we generate regex match
13059 # files for
13060 foreach my $alias ($table->aliases) {
c85f591a 13061 my $standard = utf8_heavy_name($table, $alias);
99870f4d
KW
13062
13063 # Generate an entry in either the loose or strict hashes, which
13064 # will translate the property and alias names combination into the
13065 # file where the table for them is stored.
99870f4d 13066 if ($alias->loose_match) {
99870f4d
KW
13067 if (exists $loose_to_file_of{$standard}) {
13068 Carp::my_carp("Can't change file registered to $loose_to_file_of{$standard} to '$sub_filename'.");
13069 }
13070 else {
13071 $loose_to_file_of{$standard} = $sub_filename;
13072 }
13073 }
13074 else {
99870f4d
KW
13075 if (exists $stricter_to_file_of{$standard}) {
13076 Carp::my_carp("Can't change file registered to $stricter_to_file_of{$standard} to '$sub_filename'.");
13077 }
13078 else {
13079 $stricter_to_file_of{$standard} = $sub_filename;
13080
13081 # Tightly coupled with how utf8_heavy.pl works, for a
13082 # floating point number that is a whole number, get rid of
13083 # the trailing decimal point and 0's, so that utf8_heavy
13084 # will work. Also note that this assumes that such a
13085 # number is matched strictly; so if that were to change,
13086 # this would be wrong.
c85f591a 13087 if ((my $integer_name = $alias->name)
99870f4d
KW
13088 =~ s/^ ( -? \d+ ) \.0+ $ /$1/x)
13089 {
ae51efca 13090 $stricter_to_file_of{$property_name . $integer_name}
c12f2655 13091 = $sub_filename;
99870f4d
KW
13092 }
13093 }
13094 }
13095
9e4a1e86
KW
13096 # For Unicode::UCD, create a mapping of the prop=value to the
13097 # canonical =value for that property.
13098 if ($standard =~ /=/) {
13099
13100 # This could happen if a strict name mapped into an existing
13101 # loose name. In that event, the strict names would have to
13102 # be moved to a new hash.
13103 if (exists($loose_to_standard_value{$standard})) {
13104 Carp::my_carp_bug("'$standard' conflicts with a pre-existing use. Bad News. Continuing anyway");
13105 }
13106 $loose_to_standard_value{$standard} = $loose_table_name;
13107 }
13108
99870f4d 13109 # Keep a list of the deprecated properties and their filenames
a92d5c2e 13110 if ($deprecated && $complement == 0) {
99870f4d
KW
13111 $utf8::why_deprecated{$sub_filename} = $deprecated;
13112 }
d867ccfb
KW
13113
13114 # And a substitute table, if any, for case-insensitive matching
13115 if ($caseless_equivalent != 0) {
13116 $caseless_equivalent_to{$standard} = $caseless_equivalent;
13117 }
c15fda25
KW
13118
13119 # Add to defaults list if the table this alias belongs to is the
13120 # default one
13121 $loose_defaults{$standard} = 1 if $is_default;
99870f4d
KW
13122 }
13123 }
13124
13125 return;
13126}
13127
13128{ # Closure
13129 my %base_names; # Names already used for avoiding DOS 8.3 filesystem
13130 # conflicts
13131 my %full_dir_name_of; # Full length names of directories used.
13132
13133 sub construct_filename($$$) {
13134 # Return a file name for a table, based on the table name, but perhaps
13135 # changed to get rid of non-portable characters in it, and to make
13136 # sure that it is unique on a file system that allows the names before
13137 # any period to be at most 8 characters (DOS). While we're at it
13138 # check and complain if there are any directory conflicts.
13139
13140 my $name = shift; # The name to start with
13141 my $mutable = shift; # Boolean: can it be changed? If no, but
13142 # yet it must be to work properly, a warning
13143 # is given
13144 my $directories_ref = shift; # A reference to an array containing the
13145 # path to the file, with each element one path
13146 # component. This is used because the same
13147 # name can be used in different directories.
13148 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
13149
13150 my $warn = ! defined wantarray; # If true, then if the name is
13151 # changed, a warning is issued as well.
13152
13153 if (! defined $name) {
13154 Carp::my_carp("Undefined name in directory "
13155 . File::Spec->join(@$directories_ref)
13156 . ". '_' used");
13157 return '_';
13158 }
13159
13160 # Make sure that no directory names conflict with each other. Look at
13161 # each directory in the input file's path. If it is already in use,
13162 # assume it is correct, and is merely being re-used, but if we
13163 # truncate it to 8 characters, and find that there are two directories
13164 # that are the same for the first 8 characters, but differ after that,
13165 # then that is a problem.
13166 foreach my $directory (@$directories_ref) {
13167 my $short_dir = substr($directory, 0, 8);
13168 if (defined $full_dir_name_of{$short_dir}) {
13169 next if $full_dir_name_of{$short_dir} eq $directory;
13170 Carp::my_carp("$directory conflicts with $full_dir_name_of{$short_dir}. Bad News. Continuing anyway");
13171 }
13172 else {
13173 $full_dir_name_of{$short_dir} = $directory;
13174 }
13175 }
13176
13177 my $path = join '/', @$directories_ref;
13178 $path .= '/' if $path;
13179
13180 # Remove interior underscores.
13181 (my $filename = $name) =~ s/ (?<=.) _ (?=.) //xg;
13182
13183 # Change any non-word character into an underscore, and truncate to 8.
13184 $filename =~ s/\W+/_/g; # eg., "L&" -> "L_"
13185 substr($filename, 8) = "" if length($filename) > 8;
13186
13187 # Make sure the basename doesn't conflict with something we
13188 # might have already written. If we have, say,
13189 # InGreekExtended1
13190 # InGreekExtended2
13191 # they become
13192 # InGreekE
13193 # InGreek2
13194 my $warned = 0;
13195 while (my $num = $base_names{$path}{lc $filename}++) {
13196 $num++; # so basenames with numbers start with '2', which
13197 # just looks more natural.
13198
13199 # Want to append $num, but if it'll make the basename longer
13200 # than 8 characters, pre-truncate $filename so that the result
13201 # is acceptable.
13202 my $delta = length($filename) + length($num) - 8;
13203 if ($delta > 0) {
13204 substr($filename, -$delta) = $num;
13205 }
13206 else {
13207 $filename .= $num;
13208 }
13209 if ($warn && ! $warned) {
13210 $warned = 1;
13211 Carp::my_carp("'$path$name' conflicts with another name on a filesystem with 8 significant characters (like DOS). Proceeding anyway.");
13212 }
13213 }
13214
13215 return $filename if $mutable;
13216
13217 # If not changeable, must return the input name, but warn if needed to
13218 # change it beyond shortening it.
13219 if ($name ne $filename
13220 && substr($name, 0, length($filename)) ne $filename) {
13221 Carp::my_carp("'$path$name' had to be changed into '$filename'. Bad News. Proceeding anyway.");
13222 }
13223 return $name;
13224 }
13225}
13226
13227# The pod file contains a very large table. Many of the lines in that table
13228# would exceed a typical output window's size, and so need to be wrapped with
13229# a hanging indent to make them look good. The pod language is really
13230# insufficient here. There is no general construct to do that in pod, so it
13231# is done here by beginning each such line with a space to cause the result to
13232# be output without formatting, and doing all the formatting here. This leads
13233# to the result that if the eventual display window is too narrow it won't
13234# look good, and if the window is too wide, no advantage is taken of that
13235# extra width. A further complication is that the output may be indented by
13236# the formatter so that there is less space than expected. What I (khw) have
13237# done is to assume that that indent is a particular number of spaces based on
13238# what it is in my Linux system; people can always resize their windows if
13239# necessary, but this is obviously less than desirable, but the best that can
13240# be expected.
13241my $automatic_pod_indent = 8;
13242
13243# Try to format so that uses fewest lines, but few long left column entries
13244# slide into the right column. An experiment on 5.1 data yielded the
13245# following percentages that didn't cut into the other side along with the
13246# associated first-column widths
13247# 69% = 24
13248# 80% not too bad except for a few blocks
13249# 90% = 33; # , cuts 353/3053 lines from 37 = 12%
13250# 95% = 37;
13251my $indent_info_column = 27; # 75% of lines didn't have overlap
13252
13253my $FILLER = 3; # Length of initial boiler-plate columns in a pod line
13254 # The 3 is because of:
13255 # 1 for the leading space to tell the pod formatter to
13256 # output as-is
13257 # 1 for the flag
13258 # 1 for the space between the flag and the main data
13259
13260sub format_pod_line ($$$;$$) {
13261 # Take a pod line and return it, formatted properly
13262
13263 my $first_column_width = shift;
13264 my $entry = shift; # Contents of left column
13265 my $info = shift; # Contents of right column
13266
13267 my $status = shift || ""; # Any flag
13268
13269 my $loose_match = shift; # Boolean.
13270 $loose_match = 1 unless defined $loose_match;
13271
13272 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
13273
13274 my $flags = "";
13275 $flags .= $STRICTER if ! $loose_match;
13276
13277 $flags .= $status if $status;
13278
13279 # There is a blank in the left column to cause the pod formatter to
13280 # output the line as-is.
13281 return sprintf " %-*s%-*s %s\n",
13282 # The first * in the format is replaced by this, the -1 is
13283 # to account for the leading blank. There isn't a
13284 # hard-coded blank after this to separate the flags from
13285 # the rest of the line, so that in the unlikely event that
13286 # multiple flags are shown on the same line, they both
13287 # will get displayed at the expense of that separation,
13288 # but since they are left justified, a blank will be
13289 # inserted in the normal case.
13290 $FILLER - 1,
13291 $flags,
13292
13293 # The other * in the format is replaced by this number to
13294 # cause the first main column to right fill with blanks.
13295 # The -1 is for the guaranteed blank following it.
13296 $first_column_width - $FILLER - 1,
13297 $entry,
13298 $info;
13299}
13300
13301my @zero_match_tables; # List of tables that have no matches in this release
13302
d1476e4d 13303sub make_re_pod_entries($) {
99870f4d
KW
13304 # This generates the entries for the pod file for a given table.
13305 # Also done at this time are any children tables. The output looks like:
13306 # \p{Common} \p{Script=Common} (Short: \p{Zyyy}) (5178)
13307
13308 my $input_table = shift; # Table the entry is for
13309 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
13310
13311 # Generate parent and all its children at the same time.
13312 return if $input_table->parent != $input_table;
13313
13314 my $property = $input_table->property;
13315 my $type = $property->type;
13316 my $full_name = $property->full_name;
13317
13318 my $count = $input_table->count;
13319 my $string_count = clarify_number($count);
13320 my $status = $input_table->status;
13321 my $status_info = $input_table->status_info;
56ca34ca 13322 my $caseless_equivalent = $input_table->caseless_equivalent;
99870f4d
KW
13323
13324 my $entry_for_first_table; # The entry for the first table output.
13325 # Almost certainly, it is the parent.
13326
13327 # For each related table (including itself), we will generate a pod entry
13328 # for each name each table goes by
13329 foreach my $table ($input_table, $input_table->children) {
13330
d4da3f74
KW
13331 # utf8_heavy.pl cannot deal with null string property values, so skip
13332 # any tables that have no non-null names.
13333 next if ! grep { $_->name ne "" } $table->aliases;
99870f4d
KW
13334
13335 # First, gather all the info that applies to this table as a whole.
13336
13337 push @zero_match_tables, $table if $count == 0;
13338
13339 my $table_property = $table->property;
13340
13341 # The short name has all the underscores removed, while the full name
13342 # retains them. Later, we decide whether to output a short synonym
13343 # for the full one, we need to compare apples to apples, so we use the
13344 # short name's length including underscores.
13345 my $table_property_short_name_length;
13346 my $table_property_short_name
13347 = $table_property->short_name(\$table_property_short_name_length);
13348 my $table_property_full_name = $table_property->full_name;
13349
13350 # Get how much savings there is in the short name over the full one
13351 # (delta will always be <= 0)
13352 my $table_property_short_delta = $table_property_short_name_length
13353 - length($table_property_full_name);
13354 my @table_description = $table->description;
13355 my @table_note = $table->note;
13356
13357 # Generate an entry for each alias in this table.
13358 my $entry_for_first_alias; # saves the first one encountered.
13359 foreach my $alias ($table->aliases) {
13360
13361 # Skip if not to go in pod.
33e96e72 13362 next unless $alias->make_re_pod_entry;
99870f4d
KW
13363
13364 # Start gathering all the components for the entry
13365 my $name = $alias->name;
13366
d4da3f74
KW
13367 # Skip if name is empty, as can't be accessed by regexes.
13368 next if $name eq "";
13369
99870f4d
KW
13370 my $entry; # Holds the left column, may include extras
13371 my $entry_ref; # To refer to the left column's contents from
13372 # another entry; has no extras
13373
13374 # First the left column of the pod entry. Tables for the $perl
13375 # property always use the single form.
13376 if ($table_property == $perl) {
13377 $entry = "\\p{$name}";
13378 $entry_ref = "\\p{$name}";
13379 }
13380 else { # Compound form.
13381
13382 # Only generate one entry for all the aliases that mean true
13383 # or false in binary properties. Append a '*' to indicate
13384 # some are missing. (The heading comment notes this.)
60e471b3 13385 my $rhs;
99870f4d
KW
13386 if ($type == $BINARY) {
13387 next if $name ne 'N' && $name ne 'Y';
60e471b3 13388 $rhs = "$name*";
99870f4d 13389 }
06f26c45 13390 elsif ($type != $FORCED_BINARY) {
60e471b3 13391 $rhs = $name;
99870f4d 13392 }
06f26c45
KW
13393 else {
13394
13395 # Forced binary properties require special handling. It
13396 # has two sets of tables, one set is true/false; and the
13397 # other set is everything else. Entries are generated for
13398 # each set. Use the Bidi_Mirrored property (which appears
13399 # in all Unicode versions) to get a list of the aliases
13400 # for the true/false tables. Of these, only output the N
13401 # and Y ones, the same as, a regular binary property. And
13402 # output all the rest, same as a non-binary property.
13403 my $bm = property_ref("Bidi_Mirrored");
13404 if ($name eq 'N' || $name eq 'Y') {
13405 $rhs = "$name*";
13406 } elsif (grep { $name eq $_->name } $bm->table("Y")->aliases,
13407 $bm->table("N")->aliases)
13408 {
13409 next;
13410 }
13411 else {
13412 $rhs = $name;
13413 }
13414 }
99870f4d
KW
13415
13416 # Colon-space is used to give a little more space to be easier
13417 # to read;
13418 $entry = "\\p{"
13419 . $table_property_full_name
60e471b3 13420 . ": $rhs}";
99870f4d
KW
13421
13422 # But for the reference to this entry, which will go in the
13423 # right column, where space is at a premium, use equals
13424 # without a space
13425 $entry_ref = "\\p{" . $table_property_full_name . "=$name}";
13426 }
13427
13428 # Then the right (info) column. This is stored as components of
13429 # an array for the moment, then joined into a string later. For
13430 # non-internal only properties, begin the info with the entry for
13431 # the first table we encountered (if any), as things are ordered
13432 # so that that one is the most descriptive. This leads to the
13433 # info column of an entry being a more descriptive version of the
13434 # name column
13435 my @info;
13436 if ($name =~ /^_/) {
13437 push @info,
13438 '(For internal use by Perl, not necessarily stable)';
13439 }
13440 elsif ($entry_for_first_alias) {
13441 push @info, $entry_for_first_alias;
13442 }
13443
13444 # If this entry is equivalent to another, add that to the info,
13445 # using the first such table we encountered
13446 if ($entry_for_first_table) {
13447 if (@info) {
13448 push @info, "(= $entry_for_first_table)";
13449 }
13450 else {
13451 push @info, $entry_for_first_table;
13452 }
13453 }
13454
13455 # If the name is a large integer, add an equivalent with an
13456 # exponent for better readability
13457 if ($name =~ /^[+-]?[\d]+$/ && $name >= 10_000) {
13458 push @info, sprintf "(= %.1e)", $name
13459 }
13460
13461 my $parenthesized = "";
13462 if (! $entry_for_first_alias) {
13463
13464 # This is the first alias for the current table. The alias
13465 # array is ordered so that this is the fullest, most
13466 # descriptive alias, so it gets the fullest info. The other
13467 # aliases are mostly merely pointers to this one, using the
13468 # information already added above.
13469
13470 # Display any status message, but only on the parent table
13471 if ($status && ! $entry_for_first_table) {
13472 push @info, $status_info;
13473 }
13474
13475 # Put out any descriptive info
13476 if (@table_description || @table_note) {
13477 push @info, join "; ", @table_description, @table_note;
13478 }
13479
13480 # Look to see if there is a shorter name we can point people
13481 # at
13482 my $standard_name = standardize($name);
13483 my $short_name;
13484 my $proposed_short = $table->short_name;
13485 if (defined $proposed_short) {
13486 my $standard_short = standardize($proposed_short);
13487
13488 # If the short name is shorter than the standard one, or
13489 # even it it's not, but the combination of it and its
13490 # short property name (as in \p{prop=short} ($perl doesn't
13491 # have this form)) saves at least two characters, then,
13492 # cause it to be listed as a shorter synonym.
13493 if (length $standard_short < length $standard_name
13494 || ($table_property != $perl
13495 && (length($standard_short)
13496 - length($standard_name)
13497 + $table_property_short_delta) # (<= 0)
13498 < -2))
13499 {
13500 $short_name = $proposed_short;
13501 if ($table_property != $perl) {
13502 $short_name = $table_property_short_name
13503 . "=$short_name";
13504 }
13505 $short_name = "\\p{$short_name}";
13506 }
13507 }
13508
13509 # And if this is a compound form name, see if there is a
13510 # single form equivalent
13511 my $single_form;
13512 if ($table_property != $perl) {
13513
13514 # Special case the binary N tables, so that will print
13515 # \P{single}, but use the Y table values to populate
c12f2655 13516 # 'single', as we haven't likewise populated the N table.
06f26c45
KW
13517 # For forced binary tables, we can't just look at the N
13518 # table, but must see if this table is equivalent to the N
13519 # one, as there are two equivalent beasts in these
13520 # properties.
99870f4d
KW
13521 my $test_table;
13522 my $p;
06f26c45
KW
13523 if ( ($type == $BINARY
13524 && $input_table == $property->table('No'))
13525 || ($type == $FORCED_BINARY
13526 && $property->table('No')->
13527 is_set_equivalent_to($input_table)))
99870f4d
KW
13528 {
13529 $test_table = $property->table('Yes');
13530 $p = 'P';
13531 }
13532 else {
13533 $test_table = $input_table;
13534 $p = 'p';
13535 }
13536
13537 # Look for a single form amongst all the children.
13538 foreach my $table ($test_table->children) {
13539 next if $table->property != $perl;
13540 my $proposed_name = $table->short_name;
13541 next if ! defined $proposed_name;
13542
13543 # Don't mention internal-only properties as a possible
13544 # single form synonym
13545 next if substr($proposed_name, 0, 1) eq '_';
13546
13547 $proposed_name = "\\$p\{$proposed_name}";
13548 if (! defined $single_form
13549 || length($proposed_name) < length $single_form)
13550 {
13551 $single_form = $proposed_name;
13552
13553 # The goal here is to find a single form; not the
13554 # shortest possible one. We've already found a
13555 # short name. So, stop at the first single form
13556 # found, which is likely to be closer to the
13557 # original.
13558 last;
13559 }
13560 }
13561 }
13562
13563 # Ouput both short and single in the same parenthesized
13564 # expression, but with only one of 'Single', 'Short' if there
13565 # are both items.
13566 if ($short_name || $single_form || $table->conflicting) {
99870f4d
KW
13567 $parenthesized .= "Short: $short_name" if $short_name;
13568 if ($short_name && $single_form) {
13569 $parenthesized .= ', ';
13570 }
13571 elsif ($single_form) {
13572 $parenthesized .= 'Single: ';
13573 }
13574 $parenthesized .= $single_form if $single_form;
13575 }
13576 }
13577
56ca34ca
KW
13578 if ($caseless_equivalent != 0) {
13579 $parenthesized .= '; ' if $parenthesized ne "";
13580 $parenthesized .= "/i= " . $caseless_equivalent->complete_name;
13581 }
13582
99870f4d
KW
13583
13584 # Warn if this property isn't the same as one that a
13585 # semi-casual user might expect. The other components of this
13586 # parenthesized structure are calculated only for the first entry
13587 # for this table, but the conflicting is deemed important enough
13588 # to go on every entry.
13589 my $conflicting = join " NOR ", $table->conflicting;
13590 if ($conflicting) {
e5228720 13591 $parenthesized .= '; ' if $parenthesized ne "";
99870f4d
KW
13592 $parenthesized .= "NOT $conflicting";
13593 }
99870f4d 13594
e5228720 13595 push @info, "($parenthesized)" if $parenthesized;
d57ccc9a 13596
0f88d393
KW
13597 if ($name =~ /_$/ && $alias->loose_match) {
13598 push @info, "Note the trailing '_' matters in spite of loose matching rules.";
13599 }
13600
d57ccc9a
KW
13601 if ($table_property != $perl && $table->perl_extension) {
13602 push @info, '(Perl extension)';
13603 }
2cf724d4 13604 push @info, "($string_count)";
99870f4d
KW
13605
13606 # Now, we have both the entry and info so add them to the
13607 # list of all the properties.
13608 push @match_properties,
13609 format_pod_line($indent_info_column,
13610 $entry,
13611 join( " ", @info),
13612 $alias->status,
13613 $alias->loose_match);
13614
13615 $entry_for_first_alias = $entry_ref unless $entry_for_first_alias;
13616 } # End of looping through the aliases for this table.
13617
13618 if (! $entry_for_first_table) {
13619 $entry_for_first_table = $entry_for_first_alias;
13620 }
13621 } # End of looping through all the related tables
13622 return;
13623}
13624
2df7880f
KW
13625sub make_ucd_table_pod_entries {
13626 my $table = shift;
13627
ee94c7d1
KW
13628 # Generate the entries for the UCD section of the pod for $table. This
13629 # also calculates if names are ambiguous, so has to be called even if the
13630 # pod is not being output
13631
13632 my $short_name = $table->name;
13633 my $standard_short_name = standardize($short_name);
13634 my $full_name = $table->full_name;
13635 my $standard_full_name = standardize($full_name);
13636
13637 my $full_info = ""; # Text of info column for full-name entries
13638 my $other_info = ""; # Text of info column for short-name entries
13639 my $short_info = ""; # Text of info column for other entries
13640 my $meaning = ""; # Synonym of this table
2df7880f
KW
13641
13642 my $property = ($table->isa('Property'))
13643 ? $table
13644 : $table->parent->property;
13645
ee94c7d1
KW
13646 my $perl_extension = $table->perl_extension;
13647
13648 # Get the more official name for for perl extensions that aren't
13649 # stand-alone properties
13650 if ($perl_extension && $property != $table) {
13651 if ($property == $perl ||$property->type == $BINARY) {
13652 $meaning = $table->complete_name;
13653 }
13654 else {
13655 $meaning = $property->full_name . "=$full_name";
13656 }
13657 }
13658
13659 # There are three types of info column. One for the short name, one for
13660 # the full name, and one for everything else. They mostly are the same,
13661 # so initialize in the same loop.
13662 foreach my $info_ref (\$full_info, \$short_info, \$other_info) {
13663 if ($perl_extension && $property != $table) {
13664
13665 # Add the synonymous name for the non-full name entries; and to
13666 # the full-name entry if it adds extra information
13667 if ($info_ref == \$other_info
13668 || ($info_ref == \$short_info
13669 && $standard_short_name ne $standard_full_name)
13670 || standardize($meaning) ne $standard_full_name
13671 ) {
13672 $$info_ref .= "$meaning.";
13673 }
13674 }
13675 elsif ($info_ref != \$full_info) {
13676
13677 # Otherwise, the non-full name columns include the full name
13678 $$info_ref .= $full_name;
13679 }
13680
13681 # And the full-name entry includes the short name, if different
13682 if ($info_ref == \$full_info
13683 && $standard_short_name ne $standard_full_name)
13684 {
13685 $full_info =~ s/\.\Z//;
13686 $full_info .= " " if $full_info;
13687 $full_info .= "(Short: $short_name)";
13688 }
13689
13690 if ($table->perl_extension) {
13691 $$info_ref =~ s/\.\Z//;
13692 $$info_ref .= ". " if $$info_ref;
13693 $$info_ref .= "(Perl extension)";
13694 }
13695 }
13696
13697 # Add any extra annotations to the full name entry
13698 foreach my $more_info ($table->description,
13699 $table->note,
13700 $table->status_info)
13701 {
13702 next unless $more_info;
13703 $full_info =~ s/\.\Z//;
13704 $full_info .= ". " if $full_info;
13705 $full_info .= $more_info;
13706 }
13707
13708 # These keep track if have created full and short name pod entries for the
13709 # property
13710 my $done_full = 0;
13711 my $done_short = 0;
13712
2df7880f
KW
13713 # Every possible name is kept track of, even those that aren't going to be
13714 # output. This way we can be sure to find the ambiguities.
13715 foreach my $alias ($table->aliases) {
13716 my $name = $alias->name;
13717 my $standard = standardize($name);
ee94c7d1
KW
13718 my $info;
13719 my $output_this = $alias->ucd;
13720
13721 # If the full and short names are the same, we want to output the full
13722 # one's entry, so it has priority.
13723 if ($standard eq $standard_full_name) {
13724 next if $done_full;
13725 $done_full = 1;
13726 $info = $full_info;
13727 }
13728 elsif ($standard eq $standard_short_name) {
13729 next if $done_short;
13730 $done_short = 1;
13731 next if $standard_short_name eq $standard_full_name;
13732 $info = $short_info;
13733 }
13734 else {
13735 $info = $other_info;
13736 }
2df7880f 13737
ee94c7d1
KW
13738 # Here, we have set up the two columns for this entry. But if an
13739 # entry already exists for this name, we have to decide which one
13740 # we're going to later output.
2df7880f
KW
13741 if (exists $ucd_pod{$standard}) {
13742
13743 # If the two entries refer to the same property, it's not going to
ee94c7d1
KW
13744 # be ambiguous. (Likely it's because the names when standardized
13745 # are the same.) But that means if they are different properties,
13746 # there is ambiguity.
2df7880f
KW
13747 if ($ucd_pod{$standard}->{'property'} != $property) {
13748
ee94c7d1
KW
13749 # Here, we have an ambiguity. This code assumes that one is
13750 # scheduled to be output and one not and that one is a perl
13751 # extension (which is not to be output) and the other isn't.
13752 # If those assumptions are wrong, things have to be rethought.
13753 if ($ucd_pod{$standard}{'output_this'} == $output_this
13754 || $ucd_pod{$standard}{'perl_extension'} == $perl_extension
13755 || $output_this == $perl_extension)
13756 {
d59563d0 13757 Carp::my_carp("Bad news. $property and $ucd_pod{$standard}->{'property'} have unexpected output status and perl-extension combinations. Proceeding anyway.");
ee94c7d1
KW
13758 }
13759
13760 # We modifiy the info column of the one being output to
13761 # indicate the ambiguity. Set $which to point to that one's
13762 # info.
13763 my $which;
13764 if ($ucd_pod{$standard}{'output_this'}) {
13765 $which = \$ucd_pod{$standard}->{'info'};
13766 }
13767 else {
13768 $which = \$info;
13769 $meaning = $ucd_pod{$standard}{'meaning'};
13770 }
13771
13772 chomp $$which;
13773 $$which =~ s/\.\Z//;
13774 $$which .= "; NOT '$standard' meaning '$meaning'";
13775
2df7880f
KW
13776 $ambiguous_names{$standard} = 1;
13777 }
13778
ee94c7d1
KW
13779 # Use the non-perl-extension variant
13780 next unless $ucd_pod{$standard}{'perl_extension'};
2df7880f
KW
13781 }
13782
ee94c7d1
KW
13783 # Store enough information about this entry that we can later look for
13784 # ambiguities, and output it properly.
13785 $ucd_pod{$standard} = { 'name' => $name,
13786 'info' => $info,
13787 'meaning' => $meaning,
13788 'output_this' => $output_this,
13789 'perl_extension' => $perl_extension,
2df7880f 13790 'property' => $property,
ee94c7d1 13791 'status' => $alias->status,
2df7880f
KW
13792 };
13793 } # End of looping through all this table's aliases
13794
13795 return;
13796}
13797
99870f4d
KW
13798sub pod_alphanumeric_sort {
13799 # Sort pod entries alphanumerically.
13800
99f78760
KW
13801 # The first few character columns are filler, plus the '\p{'; and get rid
13802 # of all the trailing stuff, starting with the trailing '}', so as to sort
13803 # on just 'Name=Value'
13804 (my $a = lc $a) =~ s/^ .*? { //x;
99870f4d 13805 $a =~ s/}.*//;
99f78760 13806 (my $b = lc $b) =~ s/^ .*? { //x;
99870f4d
KW
13807 $b =~ s/}.*//;
13808
99f78760
KW
13809 # Determine if the two operands are both internal only or both not.
13810 # Character 0 should be a '\'; 1 should be a p; 2 should be '{', so 3
13811 # should be the underscore that begins internal only
13812 my $a_is_internal = (substr($a, 0, 1) eq '_');
13813 my $b_is_internal = (substr($b, 0, 1) eq '_');
13814
13815 # Sort so the internals come last in the table instead of first (which the
13816 # leading underscore would otherwise indicate).
13817 if ($a_is_internal != $b_is_internal) {
13818 return 1 if $a_is_internal;
13819 return -1
13820 }
13821
99870f4d 13822 # Determine if the two operands are numeric property values or not.
99f78760 13823 # A numeric property will look like xyz: 3. But the number
99870f4d 13824 # can begin with an optional minus sign, and may have a
99f78760 13825 # fraction or rational component, like xyz: 3/2. If either
99870f4d
KW
13826 # isn't numeric, use alphabetic sort.
13827 my ($a_initial, $a_number) =
99f78760 13828 ($a =~ /^ ( [^:=]+ [:=] \s* ) (-? \d+ (?: [.\/] \d+)? )/ix);
99870f4d
KW
13829 return $a cmp $b unless defined $a_number;
13830 my ($b_initial, $b_number) =
99f78760 13831 ($b =~ /^ ( [^:=]+ [:=] \s* ) (-? \d+ (?: [.\/] \d+)? )/ix);
99870f4d
KW
13832 return $a cmp $b unless defined $b_number;
13833
13834 # Here they are both numeric, but use alphabetic sort if the
13835 # initial parts don't match
13836 return $a cmp $b if $a_initial ne $b_initial;
13837
13838 # Convert rationals to floating for the comparison.
13839 $a_number = eval $a_number if $a_number =~ qr{/};
13840 $b_number = eval $b_number if $b_number =~ qr{/};
13841
13842 return $a_number <=> $b_number;
13843}
13844
13845sub make_pod () {
13846 # Create the .pod file. This generates the various subsections and then
13847 # combines them in one big HERE document.
13848
07c070a8
KW
13849 my $Is_flags_text = "If an entry has flag(s) at its beginning, like \"$DEPRECATED\", the \"Is_\" form has the same flag(s)";
13850
99870f4d
KW
13851 return unless defined $pod_directory;
13852 print "Making pod file\n" if $verbosity >= $PROGRESS;
13853
13854 my $exception_message =
13855 '(Any exceptions are individually noted beginning with the word NOT.)';
13856 my @block_warning;
13857 if (-e 'Blocks.txt') {
13858
13859 # Add the line: '\p{In_*} \p{Block: *}', with the warning message
13860 # if the global $has_In_conflicts indicates we have them.
13861 push @match_properties, format_pod_line($indent_info_column,
13862 '\p{In_*}',
13863 '\p{Block: *}'
13864 . (($has_In_conflicts)
13865 ? " $exception_message"
13866 : ""));
13867 @block_warning = << "END";
13868
77173124
KW
13869Matches in the Block property have shortcuts that begin with "In_". For
13870example, C<\\p{Block=Latin1}> can be written as C<\\p{In_Latin1}>. For
13871backward compatibility, if there is no conflict with another shortcut, these
13872may also be written as C<\\p{Latin1}> or C<\\p{Is_Latin1}>. But, N.B., there
13873are numerous such conflicting shortcuts. Use of these forms for Block is
13874discouraged, and are flagged as such, not only because of the potential
13875confusion as to what is meant, but also because a later release of Unicode may
13876preempt the shortcut, and your program would no longer be correct. Use the
13877"In_" form instead to avoid this, or even more clearly, use the compound form,
13878e.g., C<\\p{blk:latin1}>. See L<perlunicode/"Blocks"> for more information
13879about this.
99870f4d
KW
13880END
13881 }
07c070a8 13882 my $text = $Is_flags_text;
99870f4d
KW
13883 $text = "$exception_message $text" if $has_Is_conflicts;
13884
13885 # And the 'Is_ line';
13886 push @match_properties, format_pod_line($indent_info_column,
13887 '\p{Is_*}',
13888 "\\p{*} $text");
13889
13890 # Sort the properties array for output. It is sorted alphabetically
13891 # except numerically for numeric properties, and only output unique lines.
13892 @match_properties = sort pod_alphanumeric_sort uniques @match_properties;
13893
13894 my $formatted_properties = simple_fold(\@match_properties,
13895 "",
13896 # indent succeeding lines by two extra
13897 # which looks better
13898 $indent_info_column + 2,
13899
13900 # shorten the line length by how much
13901 # the formatter indents, so the folded
13902 # line will fit in the space
13903 # presumably available
13904 $automatic_pod_indent);
13905 # Add column headings, indented to be a little more centered, but not
13906 # exactly
13907 $formatted_properties = format_pod_line($indent_info_column,
13908 ' NAME',
13909 ' INFO')
13910 . "\n"
13911 . $formatted_properties;
13912
13913 # Generate pod documentation lines for the tables that match nothing
0090c5d1 13914 my $zero_matches = "";
99870f4d
KW
13915 if (@zero_match_tables) {
13916 @zero_match_tables = uniques(@zero_match_tables);
13917 $zero_matches = join "\n\n",
13918 map { $_ = '=item \p{' . $_->complete_name . "}" }
13919 sort { $a->complete_name cmp $b->complete_name }
c0de960f 13920 @zero_match_tables;
99870f4d
KW
13921
13922 $zero_matches = <<END;
13923
77173124 13924=head2 Legal C<\\p{}> and C<\\P{}> constructs that match no characters
99870f4d
KW
13925
13926Unicode has some property-value pairs that currently don't match anything.
c12f2655
KW
13927This happens generally either because they are obsolete, or they exist for
13928symmetry with other forms, but no language has yet been encoded that uses
13929them. In this version of Unicode, the following match zero code points:
99870f4d
KW
13930
13931=over 4
13932
13933$zero_matches
13934
13935=back
13936
13937END
13938 }
13939
13940 # Generate list of properties that we don't accept, grouped by the reasons
13941 # why. This is so only put out the 'why' once, and then list all the
13942 # properties that have that reason under it.
13943
13944 my %why_list; # The keys are the reasons; the values are lists of
13945 # properties that have the key as their reason
13946
13947 # For each property, add it to the list that are suppressed for its reason
13948 # The sort will cause the alphabetically first properties to be added to
13949 # each list first, so each list will be sorted.
13950 foreach my $property (sort keys %why_suppressed) {
13951 push @{$why_list{$why_suppressed{$property}}}, $property;
13952 }
13953
13954 # For each reason (sorted by the first property that has that reason)...
13955 my @bad_re_properties;
13956 foreach my $why (sort { $why_list{$a}->[0] cmp $why_list{$b}->[0] }
13957 keys %why_list)
13958 {
54ce19c9 13959 # Add to the output, all the properties that have that reason.
99870f4d
KW
13960 my $has_item = 0; # Flag if actually output anything.
13961 foreach my $name (@{$why_list{$why}}) {
13962
13963 # Split compound names into $property and $table components
13964 my $property = $name;
13965 my $table;
13966 if ($property =~ / (.*) = (.*) /x) {
13967 $property = $1;
13968 $table = $2;
13969 }
13970
13971 # This release of Unicode may not have a property that is
13972 # suppressed, so don't reference a non-existent one.
13973 $property = property_ref($property);
13974 next if ! defined $property;
13975
13976 # And since this list is only for match tables, don't list the
13977 # ones that don't have match tables.
13978 next if ! $property->to_create_match_tables;
13979
13980 # Find any abbreviation, and turn it into a compound name if this
13981 # is a property=value pair.
13982 my $short_name = $property->name;
13983 $short_name .= '=' . $property->table($table)->name if $table;
13984
54ce19c9
KW
13985 # Start with an empty line.
13986 push @bad_re_properties, "\n\n" unless $has_item;
13987
99870f4d
KW
13988 # And add the property as an item for the reason.
13989 push @bad_re_properties, "\n=item I<$name> ($short_name)\n";
13990 $has_item = 1;
13991 }
13992
13993 # And add the reason under the list of properties, if such a list
13994 # actually got generated. Note that the header got added
13995 # unconditionally before. But pod ignores extra blank lines, so no
13996 # harm.
13997 push @bad_re_properties, "\n$why\n" if $has_item;
13998
13999 } # End of looping through each reason.
14000
54ce19c9
KW
14001 if (! @bad_re_properties) {
14002 push @bad_re_properties,
14003 "*** This installation accepts ALL non-Unihan properties ***";
14004 }
14005 else {
14006 # Add =over only if non-empty to avoid an empty =over/=back section,
14007 # which is considered bad form.
14008 unshift @bad_re_properties, "\n=over 4\n";
14009 push @bad_re_properties, "\n=back\n";
14010 }
14011
8d099389
KW
14012 # Similiarly, generate a list of files that we don't use, grouped by the
14013 # reasons why. First, create a hash whose keys are the reasons, and whose
14014 # values are anonymous arrays of all the files that share that reason.
14015 my %grouped_by_reason;
14016 foreach my $file (keys %ignored_files) {
14017 push @{$grouped_by_reason{$ignored_files{$file}}}, $file;
14018 }
1fec9f60
KW
14019 foreach my $file (keys %skipped_files) {
14020 push @{$grouped_by_reason{$skipped_files{$file}}}, $file;
14021 }
8d099389
KW
14022
14023 # Then, sort each group.
14024 foreach my $group (keys %grouped_by_reason) {
14025 @{$grouped_by_reason{$group}} = sort { lc $a cmp lc $b }
14026 @{$grouped_by_reason{$group}} ;
14027 }
14028
14029 # Finally, create the output text. For each reason (sorted by the
14030 # alphabetically first file that has that reason)...
14031 my @unused_files;
14032 foreach my $reason (sort { lc $grouped_by_reason{$a}->[0]
14033 cmp lc $grouped_by_reason{$b}->[0]
14034 }
14035 keys %grouped_by_reason)
14036 {
14037 # Add all the files that have that reason to the output. Start
14038 # with an empty line.
14039 push @unused_files, "\n\n";
14040 push @unused_files, map { "\n=item F<$_> \n" }
14041 @{$grouped_by_reason{$reason}};
14042 # And add the reason under the list of files
14043 push @unused_files, "\n$reason\n";
14044 }
14045
ee94c7d1
KW
14046 # Similarly, create the output text for the UCD section of the pod
14047 my @ucd_pod;
14048 foreach my $key (keys %ucd_pod) {
14049 next unless $ucd_pod{$key}->{'output_this'};
14050 push @ucd_pod, format_pod_line($indent_info_column,
14051 $ucd_pod{$key}->{'name'},
14052 $ucd_pod{$key}->{'info'},
14053 $ucd_pod{$key}->{'status'},
14054 );
14055 }
14056
14057 # Sort alphabetically, and fold for output
14058 @ucd_pod = sort { lc substr($a, 2) cmp lc substr($b, 2) } @ucd_pod;
14059 my $ucd_pod = simple_fold(\@ucd_pod,
14060 ' ',
14061 $indent_info_column,
14062 $automatic_pod_indent);
14063 $ucd_pod = format_pod_line($indent_info_column, 'NAME', ' INFO')
14064 . "\n"
14065 . $ucd_pod;
12916dad
MS
14066 local $" = "";
14067
99870f4d
KW
14068 # Everything is ready to assemble.
14069 my @OUT = << "END";
14070=begin comment
14071
14072$HEADER
14073
14074To change this file, edit $0 instead.
14075
14076=end comment
14077
14078=head1 NAME
14079
8d099389 14080$pod_file - Index of Unicode Version $string_version character properties in Perl
99870f4d
KW
14081
14082=head1 DESCRIPTION
14083
8d099389
KW
14084This document provides information about the portion of the Unicode database
14085that deals with character properties, that is the portion that is defined on
14086single code points. (L</Other information in the Unicode data base>
14087below briefly mentions other data that Unicode provides.)
99870f4d 14088
8d099389
KW
14089Perl can provide access to all non-provisional Unicode character properties,
14090though not all are enabled by default. The omitted ones are the Unihan
14091properties (accessible via the CPAN module L<Unicode::Unihan>) and certain
14092deprecated or Unicode-internal properties. (An installation may choose to
ea5acc0f 14093recompile Perl's tables to change this. See L<Unicode character
8d099389
KW
14094properties that are NOT accepted by Perl>.)
14095
ee94c7d1
KW
14096For most purposes, access to Unicode properties from the Perl core is through
14097regular expression matches, as described in the next section.
14098For some special purposes, and to access the properties that are not suitable
14099for regular expression matching, all the Unicode character properties that
14100Perl handles are accessible via the standard L<Unicode::UCD> module, as
14101described in the section L</Properties accessible through Unicode::UCD>.
14102
8d099389
KW
14103Perl also provides some additional extensions and short-cut synonyms
14104for Unicode properties.
99870f4d
KW
14105
14106This document merely lists all available properties and does not attempt to
14107explain what each property really means. There is a brief description of each
043f3b3f
KW
14108Perl extension; see L<perlunicode/Other Properties> for more information on
14109these. There is some detail about Blocks, Scripts, General_Category,
99870f4d 14110and Bidi_Class in L<perlunicode>, but to find out about the intricacies of the
043f3b3f
KW
14111official Unicode properties, refer to the Unicode standard. A good starting
14112place is L<$unicode_reference_url>.
99870f4d
KW
14113
14114Note that you can define your own properties; see
14115L<perlunicode/"User-Defined Character Properties">.
14116
77173124 14117=head1 Properties accessible through C<\\p{}> and C<\\P{}>
99870f4d 14118
77173124
KW
14119The Perl regular expression C<\\p{}> and C<\\P{}> constructs give access to
14120most of the Unicode character properties. The table below shows all these
14121constructs, both single and compound forms.
99870f4d
KW
14122
14123B<Compound forms> consist of two components, separated by an equals sign or a
14124colon. The first component is the property name, and the second component is
14125the particular value of the property to match against, for example,
77173124 14126C<\\p{Script: Greek}> and C<\\p{Script=Greek}> both mean to match characters
99870f4d
KW
14127whose Script property is Greek.
14128
77173124 14129B<Single forms>, like C<\\p{Greek}>, are mostly Perl-defined shortcuts for
99870f4d 14130their equivalent compound forms. The table shows these equivalences. (In our
77173124 14131example, C<\\p{Greek}> is a just a shortcut for C<\\p{Script=Greek}>.)
99870f4d 14132There are also a few Perl-defined single forms that are not shortcuts for a
77173124 14133compound form. One such is C<\\p{Word}>. These are also listed in the table.
99870f4d
KW
14134
14135In parsing these constructs, Perl always ignores Upper/lower case differences
77173124
KW
14136everywhere within the {braces}. Thus C<\\p{Greek}> means the same thing as
14137C<\\p{greek}>. But note that changing the case of the C<"p"> or C<"P"> before
14138the left brace completely changes the meaning of the construct, from "match"
14139(for C<\\p{}>) to "doesn't match" (for C<\\P{}>). Casing in this document is
14140for improved legibility.
99870f4d
KW
14141
14142Also, white space, hyphens, and underscores are also normally ignored
14143everywhere between the {braces}, and hence can be freely added or removed
14144even if the C</x> modifier hasn't been specified on the regular expression.
14145But $a_bold_stricter at the beginning of an entry in the table below
14146means that tighter (stricter) rules are used for that entry:
14147
14148=over 4
14149
77173124 14150=item Single form (C<\\p{name}>) tighter rules:
99870f4d
KW
14151
14152White space, hyphens, and underscores ARE significant
14153except for:
14154
14155=over 4
14156
14157=item * white space adjacent to a non-word character
14158
14159=item * underscores separating digits in numbers
14160
14161=back
14162
14163That means, for example, that you can freely add or remove white space
14164adjacent to (but within) the braces without affecting the meaning.
14165
77173124 14166=item Compound form (C<\\p{name=value}> or C<\\p{name:value}>) tighter rules:
99870f4d
KW
14167
14168The tighter rules given above for the single form apply to everything to the
14169right of the colon or equals; the looser rules still apply to everything to
14170the left.
14171
14172That means, for example, that you can freely add or remove white space
14173adjacent to (but within) the braces and the colon or equal sign.
14174
14175=back
14176
78bb419c
KW
14177Some properties are considered obsolete by Unicode, but still available.
14178There are several varieties of obsolescence:
99870f4d
KW
14179
14180=over 4
14181
99870f4d
KW
14182=item Stabilized
14183
f8c38b14 14184A property may be stabilized. Such a determination does not indicate
5f7264c7
KW
14185that the property should or should not be used; instead it is a declaration
14186that the property will not be maintained nor extended for newly encoded
14187characters. Such properties are marked with $a_bold_stabilized in the
14188table.
99870f4d
KW
14189
14190=item Deprecated
14191
f8c38b14 14192A property may be deprecated, perhaps because its original intent
78bb419c
KW
14193has been replaced by another property, or because its specification was
14194somehow defective. This means that its use is strongly
99870f4d
KW
14195discouraged, so much so that a warning will be issued if used, unless the
14196regular expression is in the scope of a C<S<no warnings 'deprecated'>>
14197statement. $A_bold_deprecated flags each such entry in the table, and
14198the entry there for the longest, most descriptive version of the property will
14199give the reason it is deprecated, and perhaps advice. Perl may issue such a
14200warning, even for properties that aren't officially deprecated by Unicode,
14201when there used to be characters or code points that were matched by them, but
14202no longer. This is to warn you that your program may not work like it did on
14203earlier Unicode releases.
14204
14205A deprecated property may be made unavailable in a future Perl version, so it
14206is best to move away from them.
14207
c12f2655
KW
14208A deprecated property may also be stabilized, but this fact is not shown.
14209
14210=item Obsolete
14211
14212Properties marked with $a_bold_obsolete in the table are considered (plain)
14213obsolete. Generally this designation is given to properties that Unicode once
14214used for internal purposes (but not any longer).
14215
99870f4d
KW
14216=back
14217
14218Some Perl extensions are present for backwards compatibility and are
c12f2655
KW
14219discouraged from being used, but are not obsolete. $A_bold_discouraged
14220flags each such entry in the table. Future Unicode versions may force
14221some of these extensions to be removed without warning, replaced by another
14222property with the same name that means something different. Use the
14223equivalent shown instead.
99870f4d
KW
14224
14225@block_warning
14226
77173124 14227The table below has two columns. The left column contains the C<\\p{}>
98dc9551 14228constructs to look up, possibly preceded by the flags mentioned above; and
99870f4d
KW
14229the right column contains information about them, like a description, or
14230synonyms. It shows both the single and compound forms for each property that
14231has them. If the left column is a short name for a property, the right column
14232will give its longer, more descriptive name; and if the left column is the
14233longest name, the right column will show any equivalent shortest name, in both
14234single and compound forms if applicable.
14235
14236The right column will also caution you if a property means something different
14237than what might normally be expected.
14238
d57ccc9a
KW
14239All single forms are Perl extensions; a few compound forms are as well, and
14240are noted as such.
14241
99870f4d
KW
14242Numbers in (parentheses) indicate the total number of code points matched by
14243the property. For emphasis, those properties that match no code points at all
14244are listed as well in a separate section following the table.
14245
56ca34ca
KW
14246Most properties match the same code points regardless of whether C<"/i">
14247case-insensitive matching is specified or not. But a few properties are
14248affected. These are shown with the notation
14249
14250 (/i= other_property)
14251
14252in the second column. Under case-insensitive matching they match the
14253same code pode points as the property "other_property".
14254
99870f4d 14255There is no description given for most non-Perl defined properties (See
77173124 14256L<$unicode_reference_url> for that).
d73e5302 14257
99870f4d
KW
14258For compactness, 'B<*>' is used as a wildcard instead of showing all possible
14259combinations. For example, entries like:
d73e5302 14260
99870f4d 14261 \\p{Gc: *} \\p{General_Category: *}
5beb625e 14262
99870f4d
KW
14263mean that 'Gc' is a synonym for 'General_Category', and anything that is valid
14264for the latter is also valid for the former. Similarly,
5beb625e 14265
99870f4d 14266 \\p{Is_*} \\p{*}
5beb625e 14267
77173124
KW
14268means that if and only if, for example, C<\\p{Foo}> exists, then
14269C<\\p{Is_Foo}> and C<\\p{IsFoo}> are also valid and all mean the same thing.
14270And similarly, C<\\p{Foo=Bar}> means the same as C<\\p{Is_Foo=Bar}> and
14271C<\\p{IsFoo=Bar}>. "*" here is restricted to something not beginning with an
14272underscore.
5beb625e 14273
99870f4d
KW
14274Also, in binary properties, 'Yes', 'T', and 'True' are all synonyms for 'Y'.
14275And 'No', 'F', and 'False' are all synonyms for 'N'. The table shows 'Y*' and
14276'N*' to indicate this, and doesn't have separate entries for the other
14277possibilities. Note that not all properties which have values 'Yes' and 'No'
14278are binary, and they have all their values spelled out without using this wild
14279card, and a C<NOT> clause in their description that highlights their not being
14280binary. These also require the compound form to match them, whereas true
14281binary properties have both single and compound forms available.
5beb625e 14282
99870f4d
KW
14283Note that all non-essential underscores are removed in the display of the
14284short names below.
5beb625e 14285
c12f2655 14286B<Legend summary:>
5beb625e 14287
99870f4d 14288=over 4
cf25bb62 14289
21405004 14290=item Z<>B<*> is a wild-card
cf25bb62 14291
99870f4d
KW
14292=item B<(\\d+)> in the info column gives the number of code points matched by
14293this property.
cf25bb62 14294
99870f4d 14295=item B<$DEPRECATED> means this is deprecated.
cf25bb62 14296
99870f4d 14297=item B<$OBSOLETE> means this is obsolete.
cf25bb62 14298
99870f4d 14299=item B<$STABILIZED> means this is stabilized.
cf25bb62 14300
99870f4d 14301=item B<$STRICTER> means tighter (stricter) name matching applies.
d73e5302 14302
c12f2655
KW
14303=item B<$DISCOURAGED> means use of this form is discouraged, and may not be
14304stable.
5beb625e 14305
99870f4d 14306=back
da7fcca4 14307
99870f4d 14308$formatted_properties
cf25bb62 14309
99870f4d 14310$zero_matches
cf25bb62 14311
ee94c7d1
KW
14312=head1 Properties accessible through Unicode::UCD
14313
14314All the Unicode character properties mentioned above (except for those marked
14315as for internal use by Perl) are also accessible by
14316L<Unicode::UCD/prop_invlist()>.
14317
14318Due to their nature, not all Unicode character properties are suitable for
14319regular expression matches, nor C<prop_invlist()>. The remaining
14320non-provisional, non-internal ones are accessible via
14321L<Unicode::UCD/prop_invmap()> (except for those that this Perl installation
14322hasn't included; see L<below for which those are|/Unicode character properties
14323that are NOT accepted by Perl>).
14324
14325For compatibility with other parts of Perl, all the single forms given in the
14326table in the L<section above|/Properties accessible through \\p{} and \\P{}>
14327are recognized. BUT, there are some ambiguities between some Perl extensions
14328and the Unicode properties, all of which are silently resolved in favor of the
14329official Unicode property. To avoid surprises, you should only use
14330C<prop_invmap()> for forms listed in the table below, which omits the
14331non-recommended ones. The affected forms are the Perl single form equivalents
14332of Unicode properties, such as C<\\p{sc}> being a single-form equivalent of
14333C<\\p{gc=sc}>, which is treated by C<prop_invmap()> as the C<Script> property,
14334whose short name is C<sc>. The table indicates the current ambiguities in the
14335INFO column, beginning with the word C<"NOT">.
14336
14337The standard Unicode properties listed below are documented in
14338L<$unicode_reference_url>; Perl_Decimal_Digit is documented in
14339L<Unicode::UCD/prop_invmap()>. The other Perl extensions are in
14340L<perlunicode/Other Properties>;
14341
14342The first column in the table is a name for the property; the second column is
14343an alternative name, if any, plus possibly some annotations. The alternative
14344name is the property's full name, unless that would simply repeat the first
14345column, in which case the second column indicates the property's short name
14346(if different). The annotations are given only in the entry for the full
14347name. If a property is obsolete, etc, the entry will be flagged with the same
14348characters used in the table in the L<section above|/Properties accessible
14349through \\p{} and \\P{}>, like B<$DEPRECATED> or B<$STABILIZED>.
14350
14351$ucd_pod
14352
14353=head1 Properties accessible through other means
14354
14355Certain properties are accessible also via core function calls. These are:
78bb419c 14356
99870f4d
KW
14357 Lowercase_Mapping lc() and lcfirst()
14358 Titlecase_Mapping ucfirst()
14359 Uppercase_Mapping uc()
12ac2576 14360
043f3b3f
KW
14361Also, Case_Folding is accessible through the C</i> modifier in regular
14362expressions.
cf25bb62 14363
043f3b3f 14364And, the Name and Name_Aliases properties are accessible through the C<\\N{}>
fbb93542
KW
14365interpolation in double-quoted strings and regular expressions; and functions
14366C<charnames::viacode()>, C<charnames::vianame()>, and
14367C<charnames::string_vianame()> (which require a C<use charnames ();> to be
14368specified.
cf25bb62 14369
ee94c7d1
KW
14370Finally, most properties related to decomposition are accessible via
14371L<Unicode::Normalize>.
14372
ea5acc0f 14373=head1 Unicode character properties that are NOT accepted by Perl
d2d499f5 14374
99870f4d
KW
14375Perl will generate an error for a few character properties in Unicode when
14376used in a regular expression. The non-Unihan ones are listed below, with the
14377reasons they are not accepted, perhaps with work-arounds. The short names for
14378the properties are listed enclosed in (parentheses).
c12f2655
KW
14379As described after the list, an installation can change the defaults and choose
14380to accept any of these. The list is machine generated based on the
14381choices made for the installation that generated this document.
ae6979a8 14382
99870f4d 14383@bad_re_properties
a3a8c5f0 14384
b7986f4f
KW
14385An installation can choose to allow any of these to be matched by downloading
14386the Unicode database from L<http://www.unicode.org/Public/> to
f3514a2f
KW
14387C<\$Config{privlib}>/F<unicore/> in the Perl source tree, changing the
14388controlling lists contained in the program
14389C<\$Config{privlib}>/F<unicore/mktables> and then re-compiling and installing.
14390(C<\%Config> is available from the Config module).
d73e5302 14391
8d099389
KW
14392=head1 Other information in the Unicode data base
14393
14394The Unicode data base is delivered in two different formats. The XML version
14395is valid for more modern Unicode releases. The other version is a collection
14396of files. The two are intended to give equivalent information. Perl uses the
14397older form; this allows you to recompile Perl to use early Unicode releases.
14398
14399The only non-character property that Perl currently supports is Named
14400Sequences, in which a sequence of code points
14401is given a name and generally treated as a single entity. (Perl supports
14402these via the C<\\N{...}> double-quotish construct,
14403L<charnames/charnames::string_vianame(name)>, and L<Unicode::UCD/namedseq()>.
14404
14405Below is a list of the files in the Unicode data base that Perl doesn't
14406currently use, along with very brief descriptions of their purposes.
14407Some of the names of the files have been shortened from those that Unicode
14408uses, in order to allow them to be distinguishable from similarly named files
14409on file systems for which only the first 8 characters of a name are
14410significant.
14411
14412=over 4
14413
14414@unused_files
14415
14416=back
14417
99870f4d 14418=head1 SEE ALSO
d73e5302 14419
99870f4d 14420L<$unicode_reference_url>
12ac2576 14421
99870f4d 14422L<perlrecharclass>
12ac2576 14423
99870f4d 14424L<perlunicode>
d73e5302 14425
99870f4d 14426END
d73e5302 14427
9218f1cf
KW
14428 # And write it. The 0 means no utf8.
14429 main::write([ $pod_directory, "$pod_file.pod" ], 0, \@OUT);
99870f4d
KW
14430 return;
14431}
d73e5302 14432
99870f4d
KW
14433sub make_Heavy () {
14434 # Create and write Heavy.pl, which passes info about the tables to
14435 # utf8_heavy.pl
12ac2576 14436
143b2c48
KW
14437 # Stringify structures for output
14438 my $loose_property_name_of
14439 = simple_dumper(\%loose_property_name_of, ' ' x 4);
14440 chomp $loose_property_name_of;
14441
14442 my $stricter_to_file_of = simple_dumper(\%stricter_to_file_of, ' ' x 4);
14443 chomp $stricter_to_file_of;
14444
14445 my $loose_to_file_of = simple_dumper(\%loose_to_file_of, ' ' x 4);
14446 chomp $loose_to_file_of;
14447
14448 my $nv_floating_to_rational
14449 = simple_dumper(\%nv_floating_to_rational, ' ' x 4);
14450 chomp $nv_floating_to_rational;
14451
14452 my $why_deprecated = simple_dumper(\%utf8::why_deprecated, ' ' x 4);
14453 chomp $why_deprecated;
14454
14455 # We set the key to the file when we associated files with tables, but we
14456 # couldn't do the same for the value then, as we might not have the file
14457 # for the alternate table figured out at that time.
14458 foreach my $cased (keys %caseless_equivalent_to) {
14459 my @path = $caseless_equivalent_to{$cased}->file_path;
14460 my $path = join '/', @path[1, -1];
14461 $caseless_equivalent_to{$cased} = $path;
14462 }
14463 my $caseless_equivalent_to
14464 = simple_dumper(\%caseless_equivalent_to, ' ' x 4);
14465 chomp $caseless_equivalent_to;
14466
315bfd4e
KW
14467 my $loose_property_to_file_of
14468 = simple_dumper(\%loose_property_to_file_of, ' ' x 4);
14469 chomp $loose_property_to_file_of;
14470
89cf10cc
KW
14471 my $file_to_swash_name = simple_dumper(\%file_to_swash_name, ' ' x 4);
14472 chomp $file_to_swash_name;
14473
99870f4d
KW
14474 my @heavy = <<END;
14475$HEADER
126c3d4e 14476$INTERNAL_ONLY_HEADER
d73e5302 14477
01da8b85 14478# This file is for the use of utf8_heavy.pl and Unicode::UCD
12ac2576 14479
c12f2655
KW
14480# Maps Unicode (not Perl single-form extensions) property names in loose
14481# standard form to their corresponding standard names
99870f4d 14482\%utf8::loose_property_name_of = (
143b2c48 14483$loose_property_name_of
99870f4d 14484);
12ac2576 14485
99870f4d
KW
14486# Maps property, table to file for those using stricter matching
14487\%utf8::stricter_to_file_of = (
143b2c48 14488$stricter_to_file_of
99870f4d 14489);
12ac2576 14490
99870f4d
KW
14491# Maps property, table to file for those using loose matching
14492\%utf8::loose_to_file_of = (
143b2c48 14493$loose_to_file_of
99870f4d 14494);
12ac2576 14495
99870f4d
KW
14496# Maps floating point to fractional form
14497\%utf8::nv_floating_to_rational = (
143b2c48 14498$nv_floating_to_rational
99870f4d 14499);
12ac2576 14500
99870f4d
KW
14501# If a floating point number doesn't have enough digits in it to get this
14502# close to a fraction, it isn't considered to be that fraction even if all the
14503# digits it does have match.
14504\$utf8::max_floating_slop = $MAX_FLOATING_SLOP;
12ac2576 14505
99870f4d
KW
14506# Deprecated tables to generate a warning for. The key is the file containing
14507# the table, so as to avoid duplication, as many property names can map to the
14508# file, but we only need one entry for all of them.
14509\%utf8::why_deprecated = (
143b2c48 14510$why_deprecated
99870f4d 14511);
12ac2576 14512
143b2c48 14513# A few properties have different behavior under /i matching. This maps
d867ccfb
KW
14514# those to substitute files to use under /i.
14515\%utf8::caseless_equivalent = (
143b2c48 14516$caseless_equivalent_to
d867ccfb
KW
14517);
14518
315bfd4e
KW
14519# Property names to mapping files
14520\%utf8::loose_property_to_file_of = (
14521$loose_property_to_file_of
14522);
14523
89cf10cc
KW
14524# Files to the swash names within them.
14525\%utf8::file_to_swash_name = (
14526$file_to_swash_name
14527);
14528
99870f4d
KW
145291;
14530END
12ac2576 14531
9218f1cf 14532 main::write("Heavy.pl", 0, \@heavy); # The 0 means no utf8.
99870f4d 14533 return;
12ac2576
JP
14534}
14535
52dc8b5d 14536sub make_Name_pm () {
6f424f62 14537 # Create and write Name.pm, which contains subroutines and data to use in
52dc8b5d
KW
14538 # conjunction with Name.pl
14539
bb1dd3da
KW
14540 # Maybe there's nothing to do.
14541 return unless $has_hangul_syllables || @code_points_ending_in_code_point;
14542
52dc8b5d
KW
14543 my @name = <<END;
14544$HEADER
126c3d4e 14545$INTERNAL_ONLY_HEADER
52dc8b5d 14546END
0f6f7bc2 14547
fb848dce
KW
14548 # Convert these structures to output format.
14549 my $code_points_ending_in_code_point =
14550 main::simple_dumper(\@code_points_ending_in_code_point,
14551 ' ' x 8);
14552 my $names = main::simple_dumper(\%names_ending_in_code_point,
14553 ' ' x 8);
14554 my $loose_names = main::simple_dumper(\%loose_names_ending_in_code_point,
0f6f7bc2 14555 ' ' x 8);
0f6f7bc2 14556
fb848dce
KW
14557 # Do the same with the Hangul names,
14558 my $jamo;
14559 my $jamo_l;
14560 my $jamo_v;
14561 my $jamo_t;
14562 my $jamo_re;
14563 if ($has_hangul_syllables) {
0f6f7bc2 14564
fb848dce
KW
14565 # Construct a regular expression of all the possible
14566 # combinations of the Hangul syllables.
14567 my @L_re; # Leading consonants
14568 for my $i ($LBase .. $LBase + $LCount - 1) {
14569 push @L_re, $Jamo{$i}
14570 }
14571 my @V_re; # Middle vowels
14572 for my $i ($VBase .. $VBase + $VCount - 1) {
14573 push @V_re, $Jamo{$i}
14574 }
14575 my @T_re; # Trailing consonants
14576 for my $i ($TBase + 1 .. $TBase + $TCount - 1) {
14577 push @T_re, $Jamo{$i}
14578 }
0f6f7bc2 14579
fb848dce
KW
14580 # The whole re is made up of the L V T combination.
14581 $jamo_re = '('
14582 . join ('|', sort @L_re)
14583 . ')('
14584 . join ('|', sort @V_re)
14585 . ')('
14586 . join ('|', sort @T_re)
14587 . ')?';
0f6f7bc2 14588
fb848dce
KW
14589 # These hashes needed by the algorithm were generated
14590 # during reading of the Jamo.txt file
14591 $jamo = main::simple_dumper(\%Jamo, ' ' x 8);
14592 $jamo_l = main::simple_dumper(\%Jamo_L, ' ' x 8);
14593 $jamo_v = main::simple_dumper(\%Jamo_V, ' ' x 8);
14594 $jamo_t = main::simple_dumper(\%Jamo_T, ' ' x 8);
14595 }
0f6f7bc2 14596
6f424f62 14597 push @name, <<END;
0f6f7bc2 14598
e7a078a0
KW
14599package charnames;
14600
6f424f62
KW
14601# This module contains machine-generated tables and code for the
14602# algorithmically-determinable Unicode character names. The following
14603# routines can be used to translate between name and code point and vice versa
0f6f7bc2
KW
14604
14605{ # Closure
14606
92199589
KW
14607 # Matches legal code point. 4-6 hex numbers, If there are 6, the first
14608 # two must be 10; if there are 5, the first must not be a 0. Written this
14609 # way to decrease backtracking. The first regex allows the code point to
14610 # be at the end of a word, but to work properly, the word shouldn't end
14611 # with a valid hex character. The second one won't match a code point at
14612 # the end of a word, and doesn't have the run-on issue
0f6f7bc2
KW
14613 my \$run_on_code_point_re = qr/$run_on_code_point_re/;
14614 my \$code_point_re = qr/$code_point_re/;
14615
14616 # In the following hash, the keys are the bases of names which includes
14617 # the code point in the name, like CJK UNIFIED IDEOGRAPH-4E01. The values
14618 # of each key is another hash which is used to get the low and high ends
14619 # for each range of code points that apply to the name.
14620 my %names_ending_in_code_point = (
14621$names
14622 );
14623
14624 # The following hash is a copy of the previous one, except is for loose
14625 # matching, so each name has blanks and dashes squeezed out
14626 my %loose_names_ending_in_code_point = (
14627$loose_names
14628 );
14629
14630 # And the following array gives the inverse mapping from code points to
14631 # names. Lowest code points are first
14632 my \@code_points_ending_in_code_point = (
14633$code_points_ending_in_code_point
14634 );
14635END
fb848dce
KW
14636 # Earlier releases didn't have Jamos. No sense outputting
14637 # them unless will be used.
14638 if ($has_hangul_syllables) {
6f424f62 14639 push @name, <<END;
0f6f7bc2
KW
14640
14641 # Convert from code point to Jamo short name for use in composing Hangul
14642 # syllable names
14643 my %Jamo = (
14644$jamo
14645 );
14646
14647 # Leading consonant (can be null)
14648 my %Jamo_L = (
14649$jamo_l
14650 );
14651
14652 # Vowel
14653 my %Jamo_V = (
14654$jamo_v
14655 );
14656
14657 # Optional trailing consonant
14658 my %Jamo_T = (
14659$jamo_t
14660 );
14661
14662 # Computed re that splits up a Hangul name into LVT or LV syllables
14663 my \$syllable_re = qr/$jamo_re/;
14664
14665 my \$HANGUL_SYLLABLE = "HANGUL SYLLABLE ";
14666 my \$loose_HANGUL_SYLLABLE = "HANGULSYLLABLE";
14667
14668 # These constants names and values were taken from the Unicode standard,
14669 # version 5.1, section 3.12. They are used in conjunction with Hangul
14670 # syllables
14671 my \$SBase = $SBase_string;
14672 my \$LBase = $LBase_string;
14673 my \$VBase = $VBase_string;
14674 my \$TBase = $TBase_string;
14675 my \$SCount = $SCount;
14676 my \$LCount = $LCount;
14677 my \$VCount = $VCount;
14678 my \$TCount = $TCount;
14679 my \$NCount = \$VCount * \$TCount;
14680END
fb848dce 14681 } # End of has Jamos
0f6f7bc2 14682
6f424f62 14683 push @name, << 'END';
0f6f7bc2
KW
14684
14685 sub name_to_code_point_special {
14686 my ($name, $loose) = @_;
14687
14688 # Returns undef if not one of the specially handled names; otherwise
14689 # returns the code point equivalent to the input name
14690 # $loose is non-zero if to use loose matching, 'name' in that case
14691 # must be input as upper case with all blanks and dashes squeezed out.
14692END
fb848dce 14693 if ($has_hangul_syllables) {
6f424f62 14694 push @name, << 'END';
0f6f7bc2
KW
14695
14696 if ((! $loose && $name =~ s/$HANGUL_SYLLABLE//)
14697 || ($loose && $name =~ s/$loose_HANGUL_SYLLABLE//))
14698 {
14699 return if $name !~ qr/^$syllable_re$/;
14700 my $L = $Jamo_L{$1};
14701 my $V = $Jamo_V{$2};
14702 my $T = (defined $3) ? $Jamo_T{$3} : 0;
14703 return ($L * $VCount + $V) * $TCount + $T + $SBase;
14704 }
14705END
fb848dce 14706 }
6f424f62 14707 push @name, << 'END';
0f6f7bc2
KW
14708
14709 # Name must end in 'code_point' for this to handle.
14710 return if (($loose && $name !~ /^ (.*?) ($run_on_code_point_re) $/x)
14711 || (! $loose && $name !~ /^ (.*) ($code_point_re) $/x));
14712
14713 my $base = $1;
14714 my $code_point = CORE::hex $2;
14715 my $names_ref;
14716
14717 if ($loose) {
14718 $names_ref = \%loose_names_ending_in_code_point;
14719 }
14720 else {
14721 return if $base !~ s/-$//;
14722 $names_ref = \%names_ending_in_code_point;
14723 }
14724
14725 # Name must be one of the ones which has the code point in it.
14726 return if ! $names_ref->{$base};
14727
14728 # Look through the list of ranges that apply to this name to see if
14729 # the code point is in one of them.
14730 for (my $i = 0; $i < scalar @{$names_ref->{$base}{'low'}}; $i++) {
14731 return if $names_ref->{$base}{'low'}->[$i] > $code_point;
14732 next if $names_ref->{$base}{'high'}->[$i] < $code_point;
14733
14734 # Here, the code point is in the range.
14735 return $code_point;
14736 }
14737
14738 # Here, looked like the name had a code point number in it, but
14739 # did not match one of the valid ones.
14740 return;
14741 }
14742
14743 sub code_point_to_name_special {
14744 my $code_point = shift;
14745
14746 # Returns the name of a code point if algorithmically determinable;
14747 # undef if not
14748END
fb848dce 14749 if ($has_hangul_syllables) {
6f424f62 14750 push @name, << 'END';
0f6f7bc2
KW
14751
14752 # If in the Hangul range, calculate the name based on Unicode's
14753 # algorithm
14754 if ($code_point >= $SBase && $code_point <= $SBase + $SCount -1) {
14755 use integer;
14756 my $SIndex = $code_point - $SBase;
14757 my $L = $LBase + $SIndex / $NCount;
14758 my $V = $VBase + ($SIndex % $NCount) / $TCount;
14759 my $T = $TBase + $SIndex % $TCount;
14760 $name = "$HANGUL_SYLLABLE$Jamo{$L}$Jamo{$V}";
14761 $name .= $Jamo{$T} if $T != $TBase;
14762 return $name;
14763 }
14764END
fb848dce 14765 }
6f424f62 14766 push @name, << 'END';
0f6f7bc2
KW
14767
14768 # Look through list of these code points for one in range.
14769 foreach my $hash (@code_points_ending_in_code_point) {
14770 return if $code_point < $hash->{'low'};
14771 if ($code_point <= $hash->{'high'}) {
14772 return sprintf("%s-%04X", $hash->{'name'}, $code_point);
14773 }
14774 }
14775 return; # None found
14776 }
14777} # End closure
14778
6f424f62 147791;
0f6f7bc2 14780END
52dc8b5d
KW
14781
14782 main::write("Name.pm", 0, \@name); # The 0 means no utf8.
14783 return;
14784}
14785
9f077a68
KW
14786sub make_UCD () {
14787 # Create and write UCD.pl, which passes info about the tables to
14788 # Unicode::UCD
14789
f7be2375
KW
14790 # Create a mapping from each alias of Perl single-form extensions to all
14791 # its equivalent aliases, for quick look-up.
14792 my %perlprop_to_aliases;
14793 foreach my $table ($perl->tables) {
14794
14795 # First create the list of the aliases of each extension
14796 my @aliases_list; # List of legal aliases for this extension
14797
14798 my $table_name = $table->name;
14799 my $standard_table_name = standardize($table_name);
14800 my $table_full_name = $table->full_name;
14801 my $standard_table_full_name = standardize($table_full_name);
14802
14803 # Make sure that the list has both the short and full names
14804 push @aliases_list, $table_name, $table_full_name;
14805
14806 my $found_ucd = 0; # ? Did we actually get an alias that should be
14807 # output for this table
14808
14809 # Go through all the aliases (including the two just added), and add
14810 # any new unique ones to the list
14811 foreach my $alias ($table->aliases) {
14812
14813 # Skip non-legal names
0eac1e20 14814 next unless $alias->ok_as_filename;
f7be2375
KW
14815 next unless $alias->ucd;
14816
14817 $found_ucd = 1; # have at least one legal name
14818
14819 my $name = $alias->name;
14820 my $standard = standardize($name);
14821
14822 # Don't repeat a name that is equivalent to one already on the
14823 # list
14824 next if $standard eq $standard_table_name;
14825 next if $standard eq $standard_table_full_name;
14826
14827 push @aliases_list, $name;
14828 }
14829
14830 # If there were no legal names, don't output anything.
14831 next unless $found_ucd;
14832
14833 # To conserve memory in the program reading these in, omit full names
14834 # that are identical to the short name, when those are the only two
14835 # aliases for the property.
14836 if (@aliases_list == 2 && $aliases_list[0] eq $aliases_list[1]) {
14837 pop @aliases_list;
14838 }
14839
14840 # Here, @aliases_list is the list of all the aliases that this
14841 # extension legally has. Now can create a map to it from each legal
14842 # standardized alias
14843 foreach my $alias ($table->aliases) {
14844 next unless $alias->ucd;
0eac1e20 14845 next unless $alias->ok_as_filename;
f7be2375
KW
14846 push @{$perlprop_to_aliases{standardize($alias->name)}},
14847 @aliases_list;
14848 }
14849 }
14850
55a40252
KW
14851 # Make a list of all combinations of properties/values that are suppressed.
14852 my @suppressed;
14853 foreach my $property_name (keys %why_suppressed) {
14854
14855 # Just the value
14856 my $value_name = $1 if $property_name =~ s/ = ( .* ) //x;
14857
14858 # The hash may contain properties not in this release of Unicode
14859 next unless defined (my $property = property_ref($property_name));
14860
14861 # Find all combinations
14862 foreach my $prop_alias ($property->aliases) {
14863 my $prop_alias_name = standardize($prop_alias->name);
14864
14865 # If no =value, there's just one combination possibe for this
14866 if (! $value_name) {
14867
14868 # The property may be suppressed, but there may be a proxy for
14869 # it, so it shouldn't be listed as suppressed
14870 next if $prop_alias->ucd;
14871 push @suppressed, $prop_alias_name;
14872 }
14873 else { # Otherwise
14874 foreach my $value_alias ($property->table($value_name)->aliases)
14875 {
14876 next if $value_alias->ucd;
14877
14878 push @suppressed, "$prop_alias_name="
14879 . standardize($value_alias->name);
14880 }
14881 }
14882 }
14883 }
14884
6a40599f
KW
14885 # Convert the structure below (designed for Name.pm) to a form that UCD
14886 # wants, so it doesn't have to modify it at all; i.e. so that it includes
14887 # an element for the Hangul syllables in the appropriate place, and
14888 # otherwise changes the name to include the "-<code point>" suffix.
14889 my @algorithm_names;
14890 my $done_hangul = 0;
14891
14892 # Copy it linearly.
14893 for my $i (0 .. @code_points_ending_in_code_point - 1) {
14894
14895 # Insert the hanguls in the correct place.
14896 if (! $done_hangul
14897 && $code_points_ending_in_code_point[$i]->{'low'} > $SBase)
14898 {
14899 $done_hangul = 1;
14900 push @algorithm_names, { low => $SBase,
14901 high => $SBase + $SCount - 1,
14902 name => '<hangul syllable>',
14903 };
14904 }
14905
14906 # Copy the current entry, modified.
14907 push @algorithm_names, {
14908 low => $code_points_ending_in_code_point[$i]->{'low'},
14909 high => $code_points_ending_in_code_point[$i]->{'high'},
14910 name =>
14911 "$code_points_ending_in_code_point[$i]->{'name'}-<code point>",
14912 };
14913 }
14914
9e4a1e86
KW
14915 # Serialize these structures for output.
14916 my $loose_to_standard_value
14917 = simple_dumper(\%loose_to_standard_value, ' ' x 4);
14918 chomp $loose_to_standard_value;
14919
86a52d1e
KW
14920 my $string_property_loose_to_name
14921 = simple_dumper(\%string_property_loose_to_name, ' ' x 4);
14922 chomp $string_property_loose_to_name;
14923
f7be2375
KW
14924 my $perlprop_to_aliases = simple_dumper(\%perlprop_to_aliases, ' ' x 4);
14925 chomp $perlprop_to_aliases;
14926
5d1df013
KW
14927 my $prop_aliases = simple_dumper(\%prop_aliases, ' ' x 4);
14928 chomp $prop_aliases;
14929
1e863613
KW
14930 my $prop_value_aliases = simple_dumper(\%prop_value_aliases, ' ' x 4);
14931 chomp $prop_value_aliases;
14932
55a40252
KW
14933 my $suppressed = (@suppressed) ? simple_dumper(\@suppressed, ' ' x 4) : "";
14934 chomp $suppressed;
14935
6a40599f
KW
14936 my $algorithm_names = simple_dumper(\@algorithm_names, ' ' x 4);
14937 chomp $algorithm_names;
14938
2df7880f
KW
14939 my $ambiguous_names = simple_dumper(\%ambiguous_names, ' ' x 4);
14940 chomp $ambiguous_names;
14941
c15fda25
KW
14942 my $loose_defaults = simple_dumper(\%loose_defaults, ' ' x 4);
14943 chomp $loose_defaults;
14944
9f077a68
KW
14945 my @ucd = <<END;
14946$HEADER
14947$INTERNAL_ONLY_HEADER
14948
14949# This file is for the use of Unicode::UCD
14950
14951# Highest legal Unicode code point
14952\$Unicode::UCD::MAX_UNICODE_CODEPOINT = 0x$MAX_UNICODE_CODEPOINT_STRING;
14953
14954# Hangul syllables
14955\$Unicode::UCD::HANGUL_BEGIN = $SBase_string;
14956\$Unicode::UCD::HANGUL_COUNT = $SCount;
14957
9e4a1e86
KW
14958# Keys are all the possible "prop=value" combinations, in loose form; values
14959# are the standard loose name for the 'value' part of the key
14960\%Unicode::UCD::loose_to_standard_value = (
14961$loose_to_standard_value
14962);
14963
86a52d1e
KW
14964# String property loose names to standard loose name
14965\%Unicode::UCD::string_property_loose_to_name = (
14966$string_property_loose_to_name
14967);
14968
f7be2375
KW
14969# Keys are Perl extensions in loose form; values are each one's list of
14970# aliases
14971\%Unicode::UCD::loose_perlprop_to_name = (
14972$perlprop_to_aliases
14973);
14974
5d1df013
KW
14975# Keys are standard property name; values are each one's aliases
14976\%Unicode::UCD::prop_aliases = (
14977$prop_aliases
14978);
14979
1e863613
KW
14980# Keys of top level are standard property name; values are keys to another
14981# hash, Each one is one of the property's values, in standard form. The
14982# values are that prop-val's aliases. If only one specified, the short and
14983# long alias are identical.
14984\%Unicode::UCD::prop_value_aliases = (
14985$prop_value_aliases
14986);
14987
6a40599f
KW
14988# Ordered (by code point ordinal) list of the ranges of code points whose
14989# names are algorithmically determined. Each range entry is an anonymous hash
14990# of the start and end points and a template for the names within it.
14991\@Unicode::UCD::algorithmic_named_code_points = (
14992$algorithm_names
14993);
14994
2df7880f
KW
14995# The properties that as-is have two meanings, and which must be disambiguated
14996\%Unicode::UCD::ambiguous_names = (
14997$ambiguous_names
14998);
14999
c15fda25
KW
15000# Keys are the prop-val combinations which are the default values for the
15001# given property, expressed in standard loose form
15002\%Unicode::UCD::loose_defaults = (
15003$loose_defaults
15004);
15005
55a40252
KW
15006# All combinations of names that are suppressed.
15007# This is actually for UCD.t, so it knows which properties shouldn't have
15008# entries. If it got any bigger, would probably want to put it in its own
15009# file to use memory only when it was needed, in testing.
15010\@Unicode::UCD::suppressed_properties = (
15011$suppressed
15012);
15013
9f077a68
KW
150141;
15015END
15016
15017 main::write("UCD.pl", 0, \@ucd); # The 0 means no utf8.
15018 return;
15019}
52dc8b5d 15020
99870f4d
KW
15021sub write_all_tables() {
15022 # Write out all the tables generated by this program to files, as well as
15023 # the supporting data structures, pod file, and .t file.
15024
15025 my @writables; # List of tables that actually get written
15026 my %match_tables_to_write; # Used to collapse identical match tables
15027 # into one file. Each key is a hash function
15028 # result to partition tables into buckets.
15029 # Each value is an array of the tables that
15030 # fit in the bucket.
15031
15032 # For each property ...
15033 # (sort so that if there is an immutable file name, it has precedence, so
15034 # some other property can't come in and take over its file name. If b's
15035 # file name is defined, will return 1, meaning to take it first; don't
7fc6cb55
KW
15036 # care if both defined, as they had better be different anyway. And the
15037 # property named 'Perl' needs to be first (it doesn't have any immutable
15038 # file name) because empty properties are defined in terms of it's table
15039 # named 'Any'.)
99870f4d 15040 PROPERTY:
7fc6cb55
KW
15041 foreach my $property (sort { return -1 if $a == $perl;
15042 return 1 if $b == $perl;
15043 return defined $b->file
15044 } property_ref('*'))
15045 {
99870f4d
KW
15046 my $type = $property->type;
15047
15048 # And for each table for that property, starting with the mapping
15049 # table for it ...
15050 TABLE:
15051 foreach my $table($property,
15052
15053 # and all the match tables for it (if any), sorted so
15054 # the ones with the shortest associated file name come
15055 # first. The length sorting prevents problems of a
15056 # longer file taking a name that might have to be used
15057 # by a shorter one. The alphabetic sorting prevents
15058 # differences between releases
15059 sort { my $ext_a = $a->external_name;
15060 return 1 if ! defined $ext_a;
15061 my $ext_b = $b->external_name;
15062 return -1 if ! defined $ext_b;
a92d5c2e
KW
15063
15064 # But return the non-complement table before
15065 # the complement one, as the latter is defined
15066 # in terms of the former, and needs to have
15067 # the information for the former available.
15068 return 1 if $a->complement != 0;
15069 return -1 if $b->complement != 0;
15070
0a695432
KW
15071 # Similarly, return a subservient table after
15072 # a leader
15073 return 1 if $a->leader != $a;
15074 return -1 if $b->leader != $b;
15075
99870f4d
KW
15076 my $cmp = length $ext_a <=> length $ext_b;
15077
15078 # Return result if lengths not equal
15079 return $cmp if $cmp;
15080
15081 # Alphabetic if lengths equal
15082 return $ext_a cmp $ext_b
15083 } $property->tables
15084 )
15085 {
12ac2576 15086
99870f4d
KW
15087 # Here we have a table associated with a property. It could be
15088 # the map table (done first for each property), or one of the
15089 # other tables. Determine which type.
15090 my $is_property = $table->isa('Property');
15091
15092 my $name = $table->name;
15093 my $complete_name = $table->complete_name;
15094
15095 # See if should suppress the table if is empty, but warn if it
15096 # contains something.
0332277c
KW
15097 my $suppress_if_empty_warn_if_not
15098 = $why_suppress_if_empty_warn_if_not{$complete_name} || 0;
99870f4d
KW
15099
15100 # Calculate if this table should have any code points associated
15101 # with it or not.
15102 my $expected_empty =
15103
15104 # $perl should be empty, as well as properties that we just
15105 # don't do anything with
15106 ($is_property
15107 && ($table == $perl
15108 || grep { $complete_name eq $_ }
15109 @unimplemented_properties
15110 )
15111 )
15112
15113 # Match tables in properties we skipped populating should be
15114 # empty
15115 || (! $is_property && ! $property->to_create_match_tables)
15116
15117 # Tables and properties that are expected to have no code
15118 # points should be empty
15119 || $suppress_if_empty_warn_if_not
15120 ;
15121
15122 # Set a boolean if this table is the complement of an empty binary
15123 # table
15124 my $is_complement_of_empty_binary =
15125 $type == $BINARY &&
15126 (($table == $property->table('Y')
15127 && $property->table('N')->is_empty)
15128 || ($table == $property->table('N')
15129 && $property->table('Y')->is_empty));
15130
99870f4d
KW
15131 if ($table->is_empty) {
15132
99870f4d 15133 if ($suppress_if_empty_warn_if_not) {
301ba948
KW
15134 $table->set_fate($SUPPRESSED,
15135 $suppress_if_empty_warn_if_not);
99870f4d 15136 }
12ac2576 15137
c12f2655 15138 # Suppress (by skipping them) expected empty tables.
99870f4d
KW
15139 next TABLE if $expected_empty;
15140
15141 # And setup to later output a warning for those that aren't
15142 # known to be allowed to be empty. Don't do the warning if
15143 # this table is a child of another one to avoid duplicating
15144 # the warning that should come from the parent one.
15145 if (($table == $property || $table->parent == $table)
301ba948 15146 && $table->fate != $SUPPRESSED
395dfc19 15147 && $table->fate != $MAP_PROXIED
99870f4d
KW
15148 && ! grep { $complete_name =~ /^$_$/ }
15149 @tables_that_may_be_empty)
15150 {
15151 push @unhandled_properties, "$table";
15152 }
7fc6cb55
KW
15153
15154 # An empty table is just the complement of everything.
15155 $table->set_complement($Any) if $table != $property;
99870f4d
KW
15156 }
15157 elsif ($expected_empty) {
15158 my $because = "";
15159 if ($suppress_if_empty_warn_if_not) {
0332277c 15160 $because = " because $suppress_if_empty_warn_if_not";
99870f4d 15161 }
12ac2576 15162
99870f4d
KW
15163 Carp::my_carp("Not expecting property $table$because. Generating file for it anyway.");
15164 }
12ac2576 15165
14479722
KW
15166 # Some tables should match everything
15167 my $expected_full =
1583a95b
KW
15168 ($table->fate == $SUPPRESSED)
15169 ? 0
e75669bd
KW
15170 : ($is_property)
15171 ? # All these types of map tables will be full because
15172 # they will have been populated with defaults
15173 ($type == $ENUM || $type == $FORCED_BINARY)
15174
15175 : # A match table should match everything if its method
15176 # shows it should
15177 ($table->matches_all
15178
15179 # The complement of an empty binary table will match
15180 # everything
15181 || $is_complement_of_empty_binary
15182 )
14479722
KW
15183 ;
15184
99870f4d
KW
15185 my $count = $table->count;
15186 if ($expected_full) {
15187 if ($count != $MAX_UNICODE_CODEPOINTS) {
15188 Carp::my_carp("$table matches only "
15189 . clarify_number($count)
15190 . " Unicode code points but should match "
15191 . clarify_number($MAX_UNICODE_CODEPOINTS)
15192 . " (off by "
15193 . clarify_number(abs($MAX_UNICODE_CODEPOINTS - $count))
15194 . "). Proceeding anyway.");
15195 }
12ac2576 15196
99870f4d
KW
15197 # Here is expected to be full. If it is because it is the
15198 # complement of an (empty) binary table that is to be
15199 # suppressed, then suppress this one as well.
15200 if ($is_complement_of_empty_binary) {
15201 my $opposing_name = ($name eq 'Y') ? 'N' : 'Y';
15202 my $opposing = $property->table($opposing_name);
15203 my $opposing_status = $opposing->status;
15204 if ($opposing_status) {
15205 $table->set_status($opposing_status,
15206 $opposing->status_info);
15207 }
15208 }
15209 }
15210 elsif ($count == $MAX_UNICODE_CODEPOINTS) {
15211 if ($table == $property || $table->leader == $table) {
15212 Carp::my_carp("$table unexpectedly matches all Unicode code points. Proceeding anyway.");
15213 }
15214 }
d73e5302 15215
301ba948 15216 if ($table->fate == $SUPPRESSED) {
99870f4d
KW
15217 if (! $is_property) {
15218 my @children = $table->children;
15219 foreach my $child (@children) {
301ba948 15220 if ($child->fate != $SUPPRESSED) {
99870f4d
KW
15221 Carp::my_carp_bug("'$table' is suppressed and has a child '$child' which isn't");
15222 }
15223 }
15224 }
15225 next TABLE;
d73e5302 15226
99870f4d 15227 }
2df7880f 15228
99870f4d
KW
15229 if (! $is_property) {
15230
2df7880f
KW
15231 make_ucd_table_pod_entries($table) if $table->property == $perl;
15232
99870f4d
KW
15233 # Several things need to be done just once for each related
15234 # group of match tables. Do them on the parent.
15235 if ($table->parent == $table) {
15236
15237 # Add an entry in the pod file for the table; it also does
15238 # the children.
d1476e4d 15239 make_re_pod_entries($table) if defined $pod_directory;
99870f4d
KW
15240
15241 # See if the the table matches identical code points with
15242 # something that has already been output. In that case,
15243 # no need to have two files with the same code points in
15244 # them. We use the table's hash() method to store these
15245 # in buckets, so that it is quite likely that if two
15246 # tables are in the same bucket they will be identical, so
15247 # don't have to compare tables frequently. The tables
15248 # have to have the same status to share a file, so add
15249 # this to the bucket hash. (The reason for this latter is
15250 # that Heavy.pl associates a status with a file.)
06671cbc
KW
15251 # We don't check tables that are inverses of others, as it
15252 # would lead to some coding complications, and checking
15253 # all the regular ones should find everything.
15254 if ($table->complement == 0) {
21be712a 15255 my $hash = $table->hash . ';' . $table->status;
99870f4d 15256
21be712a
KW
15257 # Look at each table that is in the same bucket as
15258 # this one would be.
15259 foreach my $comparison
15260 (@{$match_tables_to_write{$hash}})
15261 {
15262 if ($table->matches_identically_to($comparison)) {
15263 $table->set_equivalent_to($comparison,
99870f4d 15264 Related => 0);
21be712a
KW
15265 next TABLE;
15266 }
99870f4d 15267 }
d73e5302 15268
21be712a
KW
15269 # Here, not equivalent, add this table to the bucket.
15270 push @{$match_tables_to_write{$hash}}, $table;
06671cbc 15271 }
99870f4d
KW
15272 }
15273 }
15274 else {
15275
15276 # Here is the property itself.
15277 # Don't write out or make references to the $perl property
15278 next if $table == $perl;
15279
2df7880f
KW
15280 make_ucd_table_pod_entries($table);
15281
382cadab
KW
15282 # There is a mapping stored of the various synonyms to the
15283 # standardized name of the property for utf8_heavy.pl.
15284 # Also, the pod file contains entries of the form:
15285 # \p{alias: *} \p{full: *}
15286 # rather than show every possible combination of things.
99870f4d 15287
382cadab 15288 my @property_aliases = $property->aliases;
99870f4d 15289
382cadab
KW
15290 my $full_property_name = $property->full_name;
15291 my $property_name = $property->name;
15292 my $standard_property_name = standardize($property_name);
5d1df013
KW
15293 my $standard_property_full_name
15294 = standardize($full_property_name);
15295
15296 # We also create for Unicode::UCD a list of aliases for
15297 # the property. The list starts with the property name;
15298 # then its full name.
15299 my @property_list;
15300 my @standard_list;
15301 if ( $property->fate <= $MAP_PROXIED) {
15302 @property_list = ($property_name, $full_property_name);
15303 @standard_list = ($standard_property_name,
15304 $standard_property_full_name);
15305 }
99870f4d 15306
382cadab
KW
15307 # For each synonym ...
15308 for my $i (0 .. @property_aliases - 1) {
15309 my $alias = $property_aliases[$i];
15310 my $alias_name = $alias->name;
15311 my $alias_standard = standardize($alias_name);
99870f4d 15312
382cadab 15313
5d1df013
KW
15314 # Add other aliases to the list of property aliases
15315 if ($property->fate <= $MAP_PROXIED
15316 && ! grep { $alias_standard eq $_ } @standard_list)
15317 {
15318 push @property_list, $alias_name;
15319 push @standard_list, $alias_standard;
15320 }
382cadab
KW
15321
15322 # For utf8_heavy, set the mapping of the alias to the
15323 # property
86a52d1e
KW
15324 if ($type == $STRING) {
15325 if ($property->fate <= $MAP_PROXIED) {
15326 $string_property_loose_to_name{$alias_standard}
15327 = $standard_property_name;
15328 }
15329 }
15330 else {
99870f4d
KW
15331 if (exists ($loose_property_name_of{$alias_standard}))
15332 {
15333 Carp::my_carp("There already is a property with the same standard name as $alias_name: $loose_property_name_of{$alias_standard}. Old name is retained");
15334 }
15335 else {
15336 $loose_property_name_of{$alias_standard}
15337 = $standard_property_name;
15338 }
15339
d1476e4d 15340 # Now for the re pod entry for this alias. Skip if not
23e33b60
KW
15341 # outputting a pod; skip the first one, which is the
15342 # full name so won't have an entry like: '\p{full: *}
15343 # \p{full: *}', and skip if don't want an entry for
15344 # this one.
15345 next if $i == 0
15346 || ! defined $pod_directory
33e96e72 15347 || ! $alias->make_re_pod_entry;
99870f4d 15348
01d970b5 15349 my $rhs = "\\p{$full_property_name: *}";
d57ccc9a
KW
15350 if ($property != $perl && $table->perl_extension) {
15351 $rhs .= ' (Perl extension)';
15352 }
99870f4d
KW
15353 push @match_properties,
15354 format_pod_line($indent_info_column,
15355 '\p{' . $alias->name . ': *}',
d57ccc9a 15356 $rhs,
99870f4d
KW
15357 $alias->status);
15358 }
382cadab 15359 }
d73e5302 15360
5d1df013
KW
15361 # The list of all possible names is attached to each alias, so
15362 # lookup is easy
15363 if (@property_list) {
15364 push @{$prop_aliases{$standard_list[0]}}, @property_list;
15365 }
15366
1e863613
KW
15367 if ($property->fate <= $MAP_PROXIED) {
15368
15369 # Similarly, we create for Unicode::UCD a list of
15370 # property-value aliases.
15371
15372 my $property_full_name = $property->full_name;
15373
15374 # Look at each table in the property...
15375 foreach my $table ($property->tables) {
15376 my @values_list;
15377 my $table_full_name = $table->full_name;
15378 my $standard_table_full_name
15379 = standardize($table_full_name);
15380 my $table_name = $table->name;
15381 my $standard_table_name = standardize($table_name);
15382
15383 # The list starts with the table name and its full
15384 # name.
15385 push @values_list, $table_name, $table_full_name;
15386
15387 # We add to the table each unique alias that isn't
15388 # discouraged from use.
15389 foreach my $alias ($table->aliases) {
15390 next if $alias->status
15391 && $alias->status eq $DISCOURAGED;
15392 my $name = $alias->name;
15393 my $standard = standardize($name);
15394 next if $standard eq $standard_table_name;
15395 next if $standard eq $standard_table_full_name;
15396 push @values_list, $name;
15397 }
5d1df013 15398
1e863613
KW
15399 # Here @values_list is a list of all the aliases for
15400 # the table. That is, all the property-values given
15401 # by this table. By agreement with Unicode::UCD,
15402 # if the name and full name are identical, and there
15403 # are no other names, drop the duplcate entry to save
15404 # memory.
15405 if (@values_list == 2
15406 && $values_list[0] eq $values_list[1])
15407 {
15408 pop @values_list
15409 }
15410
15411 # To save memory, unlike the similar list for property
15412 # aliases above, only the standard forms hve the list.
15413 # This forces an extra step of converting from input
15414 # name to standard name, but the savings are
15415 # considerable. (There is only marginal savings if we
15416 # did this with the property aliases.)
15417 push @{$prop_value_aliases{$standard_property_name}{$standard_table_name}}, @values_list;
15418 }
15419 }
d73e5302 15420
c12f2655 15421 # Don't write out a mapping file if not desired.
99870f4d
KW
15422 next if ! $property->to_output_map;
15423 }
d73e5302 15424
99870f4d
KW
15425 # Here, we know we want to write out the table, but don't do it
15426 # yet because there may be other tables that come along and will
15427 # want to share the file, and the file's comments will change to
15428 # mention them. So save for later.
15429 push @writables, $table;
15430
15431 } # End of looping through the property and all its tables.
15432 } # End of looping through all properties.
15433
15434 # Now have all the tables that will have files written for them. Do it.
15435 foreach my $table (@writables) {
15436 my @directory;
15437 my $filename;
15438 my $property = $table->property;
15439 my $is_property = ($table == $property);
15440 if (! $is_property) {
15441
15442 # Match tables for the property go in lib/$subdirectory, which is
15443 # the property's name. Don't use the standard file name for this,
15444 # as may get an unfamiliar alias
15445 @directory = ($matches_directory, $property->external_name);
15446 }
15447 else {
d73e5302 15448
99870f4d
KW
15449 @directory = $table->directory;
15450 $filename = $table->file;
15451 }
d73e5302 15452
98dc9551 15453 # Use specified filename if available, or default to property's
99870f4d
KW
15454 # shortest name. We need an 8.3 safe filename (which means "an 8
15455 # safe" filename, since after the dot is only 'pl', which is < 3)
15456 # The 2nd parameter is if the filename shouldn't be changed, and
15457 # it shouldn't iff there is a hard-coded name for this table.
15458 $filename = construct_filename(
15459 $filename || $table->external_name,
15460 ! $filename, # mutable if no filename
15461 \@directory);
d73e5302 15462
99870f4d 15463 register_file_for_name($table, \@directory, $filename);
d73e5302 15464
99870f4d
KW
15465 # Only need to write one file when shared by more than one
15466 # property
a92d5c2e
KW
15467 next if ! $is_property
15468 && ($table->leader != $table || $table->complement != 0);
d73e5302 15469
99870f4d
KW
15470 # Construct a nice comment to add to the file
15471 $table->set_final_comment;
15472
15473 $table->write;
cf25bb62 15474 }
d73e5302 15475
d73e5302 15476
99870f4d
KW
15477 # Write out the pod file
15478 make_pod;
15479
9f077a68 15480 # And Heavy.pl, Name.pm, UCD.pl
99870f4d 15481 make_Heavy;
52dc8b5d 15482 make_Name_pm;
9f077a68 15483 make_UCD;
d73e5302 15484
99870f4d
KW
15485 make_property_test_script() if $make_test_script;
15486 return;
cf25bb62 15487}
d73e5302 15488
99870f4d
KW
15489my @white_space_separators = ( # This used only for making the test script.
15490 "",
15491 ' ',
15492 "\t",
15493 ' '
15494 );
d73e5302 15495
99870f4d
KW
15496sub generate_separator($) {
15497 # This used only for making the test script. It generates the colon or
15498 # equal separator between the property and property value, with random
15499 # white space surrounding the separator
d73e5302 15500
99870f4d 15501 my $lhs = shift;
d73e5302 15502
99870f4d 15503 return "" if $lhs eq ""; # No separator if there's only one (the r) side
d73e5302 15504
99870f4d
KW
15505 # Choose space before and after randomly
15506 my $spaces_before =$white_space_separators[rand(@white_space_separators)];
15507 my $spaces_after = $white_space_separators[rand(@white_space_separators)];
76ccdbe2 15508
99870f4d
KW
15509 # And return the whole complex, half the time using a colon, half the
15510 # equals
15511 return $spaces_before
15512 . (rand() < 0.5) ? '=' : ':'
15513 . $spaces_after;
15514}
76ccdbe2 15515
430ada4c 15516sub generate_tests($$$$$) {
99870f4d
KW
15517 # This used only for making the test script. It generates test cases that
15518 # are expected to compile successfully in perl. Note that the lhs and
15519 # rhs are assumed to already be as randomized as the caller wants.
15520
99870f4d
KW
15521 my $lhs = shift; # The property: what's to the left of the colon
15522 # or equals separator
15523 my $rhs = shift; # The property value; what's to the right
15524 my $valid_code = shift; # A code point that's known to be in the
15525 # table given by lhs=rhs; undef if table is
15526 # empty
15527 my $invalid_code = shift; # A code point known to not be in the table;
15528 # undef if the table is all code points
15529 my $warning = shift;
15530
15531 # Get the colon or equal
15532 my $separator = generate_separator($lhs);
15533
15534 # The whole 'property=value'
15535 my $name = "$lhs$separator$rhs";
15536
430ada4c 15537 my @output;
99870f4d
KW
15538 # Create a complete set of tests, with complements.
15539 if (defined $valid_code) {
430ada4c
NC
15540 push @output, <<"EOC"
15541Expect(1, $valid_code, '\\p{$name}', $warning);
15542Expect(0, $valid_code, '\\p{^$name}', $warning);
15543Expect(0, $valid_code, '\\P{$name}', $warning);
15544Expect(1, $valid_code, '\\P{^$name}', $warning);
15545EOC
99870f4d
KW
15546 }
15547 if (defined $invalid_code) {
430ada4c
NC
15548 push @output, <<"EOC"
15549Expect(0, $invalid_code, '\\p{$name}', $warning);
15550Expect(1, $invalid_code, '\\p{^$name}', $warning);
15551Expect(1, $invalid_code, '\\P{$name}', $warning);
15552Expect(0, $invalid_code, '\\P{^$name}', $warning);
15553EOC
15554 }
15555 return @output;
99870f4d 15556}
cf25bb62 15557
430ada4c 15558sub generate_error($$$) {
99870f4d
KW
15559 # This used only for making the test script. It generates test cases that
15560 # are expected to not only not match, but to be syntax or similar errors
15561
99870f4d
KW
15562 my $lhs = shift; # The property: what's to the left of the
15563 # colon or equals separator
15564 my $rhs = shift; # The property value; what's to the right
15565 my $already_in_error = shift; # Boolean; if true it's known that the
15566 # unmodified lhs and rhs will cause an error.
15567 # This routine should not force another one
15568 # Get the colon or equal
15569 my $separator = generate_separator($lhs);
15570
15571 # Since this is an error only, don't bother to randomly decide whether to
15572 # put the error on the left or right side; and assume that the rhs is
15573 # loosely matched, again for convenience rather than rigor.
15574 $rhs = randomize_loose_name($rhs, 'ERROR') unless $already_in_error;
15575
15576 my $property = $lhs . $separator . $rhs;
15577
430ada4c
NC
15578 return <<"EOC";
15579Error('\\p{$property}');
15580Error('\\P{$property}');
15581EOC
d73e5302
JH
15582}
15583
99870f4d
KW
15584# These are used only for making the test script
15585# XXX Maybe should also have a bad strict seps, which includes underscore.
15586
15587my @good_loose_seps = (
15588 " ",
15589 "-",
15590 "\t",
15591 "",
15592 "_",
15593 );
15594my @bad_loose_seps = (
15595 "/a/",
15596 ':=',
15597 );
15598
15599sub randomize_stricter_name {
15600 # This used only for making the test script. Take the input name and
15601 # return a randomized, but valid version of it under the stricter matching
15602 # rules.
15603
15604 my $name = shift;
15605 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
15606
15607 # If the name looks like a number (integer, floating, or rational), do
15608 # some extra work
15609 if ($name =~ qr{ ^ ( -? ) (\d+ ( ( [./] ) \d+ )? ) $ }x) {
15610 my $sign = $1;
15611 my $number = $2;
15612 my $separator = $3;
15613
15614 # If there isn't a sign, part of the time add a plus
15615 # Note: Not testing having any denominator having a minus sign
15616 if (! $sign) {
15617 $sign = '+' if rand() <= .3;
15618 }
15619
15620 # And add 0 or more leading zeros.
15621 $name = $sign . ('0' x int rand(10)) . $number;
15622
15623 if (defined $separator) {
15624 my $extra_zeros = '0' x int rand(10);
cf25bb62 15625
99870f4d
KW
15626 if ($separator eq '.') {
15627
15628 # Similarly, add 0 or more trailing zeros after a decimal
15629 # point
15630 $name .= $extra_zeros;
15631 }
15632 else {
15633
15634 # Or, leading zeros before the denominator
15635 $name =~ s,/,/$extra_zeros,;
15636 }
15637 }
cf25bb62 15638 }
d73e5302 15639
99870f4d
KW
15640 # For legibility of the test, only change the case of whole sections at a
15641 # time. To do this, first split into sections. The split returns the
15642 # delimiters
15643 my @sections;
15644 for my $section (split / ( [ - + \s _ . ]+ ) /x, $name) {
15645 trace $section if main::DEBUG && $to_trace;
15646
15647 if (length $section > 1 && $section !~ /\D/) {
15648
15649 # If the section is a sequence of digits, about half the time
15650 # randomly add underscores between some of them.
15651 if (rand() > .5) {
15652
15653 # Figure out how many underscores to add. max is 1 less than
15654 # the number of digits. (But add 1 at the end to make sure
15655 # result isn't 0, and compensate earlier by subtracting 2
15656 # instead of 1)
15657 my $num_underscores = int rand(length($section) - 2) + 1;
15658
15659 # And add them evenly throughout, for convenience, not rigor
15660 use integer;
15661 my $spacing = (length($section) - 1)/ $num_underscores;
15662 my $temp = $section;
15663 $section = "";
15664 for my $i (1 .. $num_underscores) {
15665 $section .= substr($temp, 0, $spacing, "") . '_';
15666 }
15667 $section .= $temp;
15668 }
15669 push @sections, $section;
15670 }
15671 else {
d73e5302 15672
99870f4d
KW
15673 # Here not a sequence of digits. Change the case of the section
15674 # randomly
15675 my $switch = int rand(4);
15676 if ($switch == 0) {
15677 push @sections, uc $section;
15678 }
15679 elsif ($switch == 1) {
15680 push @sections, lc $section;
15681 }
15682 elsif ($switch == 2) {
15683 push @sections, ucfirst $section;
15684 }
15685 else {
15686 push @sections, $section;
15687 }
15688 }
cf25bb62 15689 }
99870f4d
KW
15690 trace "returning", join "", @sections if main::DEBUG && $to_trace;
15691 return join "", @sections;
15692}
71d929cb 15693
99870f4d
KW
15694sub randomize_loose_name($;$) {
15695 # This used only for making the test script
71d929cb 15696
99870f4d
KW
15697 my $name = shift;
15698 my $want_error = shift; # if true, make an error
15699 Carp::carp_extra_args(\@_) if main::DEBUG && @_;
15700
15701 $name = randomize_stricter_name($name);
5beb625e
JH
15702
15703 my @parts;
99870f4d 15704 push @parts, $good_loose_seps[rand(@good_loose_seps)];
45376db6
KW
15705
15706 # Preserve trailing ones for the sake of not stripping the underscore from
15707 # 'L_'
15708 for my $part (split /[-\s_]+ (?= . )/, $name) {
5beb625e 15709 if (@parts) {
99870f4d
KW
15710 if ($want_error and rand() < 0.3) {
15711 push @parts, $bad_loose_seps[rand(@bad_loose_seps)];
15712 $want_error = 0;
15713 }
15714 else {
15715 push @parts, $good_loose_seps[rand(@good_loose_seps)];
5beb625e
JH
15716 }
15717 }
99870f4d 15718 push @parts, $part;
5beb625e 15719 }
99870f4d
KW
15720 my $new = join("", @parts);
15721 trace "$name => $new" if main::DEBUG && $to_trace;
5beb625e 15722
99870f4d 15723 if ($want_error) {
5beb625e 15724 if (rand() >= 0.5) {
99870f4d
KW
15725 $new .= $bad_loose_seps[rand(@bad_loose_seps)];
15726 }
15727 else {
15728 $new = $bad_loose_seps[rand(@bad_loose_seps)] . $new;
5beb625e
JH
15729 }
15730 }
15731 return $new;
15732}
15733
99870f4d
KW
15734# Used to make sure don't generate duplicate test cases.
15735my %test_generated;
5beb625e 15736
99870f4d
KW
15737sub make_property_test_script() {
15738 # This used only for making the test script
15739 # this written directly -- it's huge.
5beb625e 15740
99870f4d 15741 print "Making test script\n" if $verbosity >= $PROGRESS;
5beb625e 15742
99870f4d
KW
15743 # This uses randomness to test different possibilities without testing all
15744 # possibilities. To ensure repeatability, set the seed to 0. But if
15745 # tests are added, it will perturb all later ones in the .t file
15746 srand 0;
5beb625e 15747
3df51b85
KW
15748 $t_path = 'TestProp.pl' unless defined $t_path; # the traditional name
15749
99870f4d
KW
15750 # Keep going down an order of magnitude
15751 # until find that adding this quantity to
15752 # 1 remains 1; but put an upper limit on
15753 # this so in case this algorithm doesn't
15754 # work properly on some platform, that we
15755 # won't loop forever.
15756 my $digits = 0;
15757 my $min_floating_slop = 1;
15758 while (1+ $min_floating_slop != 1
15759 && $digits++ < 50)
5beb625e 15760 {
99870f4d
KW
15761 my $next = $min_floating_slop / 10;
15762 last if $next == 0; # If underflows,
15763 # use previous one
15764 $min_floating_slop = $next;
5beb625e 15765 }
430ada4c
NC
15766
15767 # It doesn't matter whether the elements of this array contain single lines
15768 # or multiple lines. main::write doesn't count the lines.
15769 my @output;
99870f4d
KW
15770
15771 foreach my $property (property_ref('*')) {
15772 foreach my $table ($property->tables) {
15773
15774 # Find code points that match, and don't match this table.
15775 my $valid = $table->get_valid_code_point;
15776 my $invalid = $table->get_invalid_code_point;
15777 my $warning = ($table->status eq $DEPRECATED)
15778 ? "'deprecated'"
15779 : '""';
15780
15781 # Test each possible combination of the property's aliases with
15782 # the table's. If this gets to be too many, could do what is done
15783 # in the set_final_comment() for Tables
15784 my @table_aliases = $table->aliases;
15785 my @property_aliases = $table->property->aliases;
807807b7
KW
15786
15787 # Every property can be optionally be prefixed by 'Is_', so test
15788 # that those work, by creating such a new alias for each
15789 # pre-existing one.
15790 push @property_aliases, map { Alias->new("Is_" . $_->name,
15791 $_->loose_match,
33e96e72 15792 $_->make_re_pod_entry,
0eac1e20 15793 $_->ok_as_filename,
fd1e3e84
KW
15794 $_->status,
15795 $_->ucd,
15796 )
807807b7 15797 } @property_aliases;
99870f4d
KW
15798 my $max = max(scalar @table_aliases, scalar @property_aliases);
15799 for my $j (0 .. $max - 1) {
15800
15801 # The current alias for property is the next one on the list,
15802 # or if beyond the end, start over. Similarly for table
15803 my $property_name
15804 = $property_aliases[$j % @property_aliases]->name;
15805
15806 $property_name = "" if $table->property == $perl;
15807 my $table_alias = $table_aliases[$j % @table_aliases];
15808 my $table_name = $table_alias->name;
15809 my $loose_match = $table_alias->loose_match;
15810
15811 # If the table doesn't have a file, any test for it is
15812 # already guaranteed to be in error
15813 my $already_error = ! $table->file_path;
15814
15815 # Generate error cases for this alias.
430ada4c
NC
15816 push @output, generate_error($property_name,
15817 $table_name,
15818 $already_error);
99870f4d
KW
15819
15820 # If the table is guaranteed to always generate an error,
15821 # quit now without generating success cases.
15822 next if $already_error;
15823
15824 # Now for the success cases.
15825 my $random;
15826 if ($loose_match) {
15827
15828 # For loose matching, create an extra test case for the
15829 # standard name.
15830 my $standard = standardize($table_name);
15831
15832 # $test_name should be a unique combination for each test
15833 # case; used just to avoid duplicate tests
15834 my $test_name = "$property_name=$standard";
15835
15836 # Don't output duplicate test cases.
15837 if (! exists $test_generated{$test_name}) {
15838 $test_generated{$test_name} = 1;
430ada4c
NC
15839 push @output, generate_tests($property_name,
15840 $standard,
15841 $valid,
15842 $invalid,
15843 $warning,
15844 );
5beb625e 15845 }
99870f4d
KW
15846 $random = randomize_loose_name($table_name)
15847 }
15848 else { # Stricter match
15849 $random = randomize_stricter_name($table_name);
99598c8c 15850 }
99598c8c 15851
99870f4d
KW
15852 # Now for the main test case for this alias.
15853 my $test_name = "$property_name=$random";
15854 if (! exists $test_generated{$test_name}) {
15855 $test_generated{$test_name} = 1;
430ada4c
NC
15856 push @output, generate_tests($property_name,
15857 $random,
15858 $valid,
15859 $invalid,
15860 $warning,
15861 );
99870f4d
KW
15862
15863 # If the name is a rational number, add tests for the
15864 # floating point equivalent.
15865 if ($table_name =~ qr{/}) {
15866
15867 # Calculate the float, and find just the fraction.
15868 my $float = eval $table_name;
15869 my ($whole, $fraction)
15870 = $float =~ / (.*) \. (.*) /x;
15871
15872 # Starting with one digit after the decimal point,
15873 # create a test for each possible precision (number of
15874 # digits past the decimal point) until well beyond the
15875 # native number found on this machine. (If we started
15876 # with 0 digits, it would be an integer, which could
15877 # well match an unrelated table)
15878 PLACE:
15879 for my $i (1 .. $min_floating_slop + 3) {
15880 my $table_name = sprintf("%.*f", $i, $float);
15881 if ($i < $MIN_FRACTION_LENGTH) {
15882
15883 # If the test case has fewer digits than the
15884 # minimum acceptable precision, it shouldn't
15885 # succeed, so we expect an error for it.
15886 # E.g., 2/3 = .7 at one decimal point, and we
15887 # shouldn't say it matches .7. We should make
15888 # it be .667 at least before agreeing that the
15889 # intent was to match 2/3. But at the
15890 # less-than- acceptable level of precision, it
15891 # might actually match an unrelated number.
15892 # So don't generate a test case if this
15893 # conflating is possible. In our example, we
15894 # don't want 2/3 matching 7/10, if there is
15895 # a 7/10 code point.
15896 for my $existing
15897 (keys %nv_floating_to_rational)
15898 {
15899 next PLACE
15900 if abs($table_name - $existing)
15901 < $MAX_FLOATING_SLOP;
15902 }
430ada4c
NC
15903 push @output, generate_error($property_name,
15904 $table_name,
15905 1 # 1 => already an error
15906 );
99870f4d
KW
15907 }
15908 else {
15909
15910 # Here the number of digits exceeds the
15911 # minimum we think is needed. So generate a
15912 # success test case for it.
430ada4c
NC
15913 push @output, generate_tests($property_name,
15914 $table_name,
15915 $valid,
15916 $invalid,
15917 $warning,
15918 );
99870f4d
KW
15919 }
15920 }
99598c8c
JH
15921 }
15922 }
99870f4d
KW
15923 }
15924 }
15925 }
37e2e78e 15926
9218f1cf
KW
15927 &write($t_path,
15928 0, # Not utf8;
15929 [<DATA>,
15930 @output,
15931 (map {"Test_X('$_');\n"} @backslash_X_tests),
15932 "Finished();\n"]);
99870f4d
KW
15933 return;
15934}
99598c8c 15935
99870f4d
KW
15936# This is a list of the input files and how to handle them. The files are
15937# processed in their order in this list. Some reordering is possible if
15938# desired, but the v0 files should be first, and the extracted before the
15939# others except DAge.txt (as data in an extracted file can be over-ridden by
15940# the non-extracted. Some other files depend on data derived from an earlier
15941# file, like UnicodeData requires data from Jamo, and the case changing and
dbe7a391 15942# folding requires data from Unicode. Mostly, it is safest to order by first
99870f4d
KW
15943# version releases in (except the Jamo). DAge.txt is read before the
15944# extracted ones because of the rarely used feature $compare_versions. In the
15945# unlikely event that there were ever an extracted file that contained the Age
15946# property information, it would have to go in front of DAge.
15947#
15948# The version strings allow the program to know whether to expect a file or
15949# not, but if a file exists in the directory, it will be processed, even if it
15950# is in a version earlier than expected, so you can copy files from a later
15951# release into an earlier release's directory.
15952my @input_file_objects = (
15953 Input_file->new('PropertyAliases.txt', v0,
15954 Handler => \&process_PropertyAliases,
15955 ),
15956 Input_file->new(undef, v0, # No file associated with this
3df51b85 15957 Progress_Message => 'Finishing property setup',
99870f4d
KW
15958 Handler => \&finish_property_setup,
15959 ),
15960 Input_file->new('PropValueAliases.txt', v0,
15961 Handler => \&process_PropValueAliases,
15962 Has_Missings_Defaults => $NOT_IGNORED,
15963 ),
15964 Input_file->new('DAge.txt', v3.2.0,
15965 Has_Missings_Defaults => $NOT_IGNORED,
15966 Property => 'Age'
15967 ),
15968 Input_file->new("${EXTRACTED}DGeneralCategory.txt", v3.1.0,
15969 Property => 'General_Category',
15970 ),
15971 Input_file->new("${EXTRACTED}DCombiningClass.txt", v3.1.0,
15972 Property => 'Canonical_Combining_Class',
15973 Has_Missings_Defaults => $NOT_IGNORED,
15974 ),
15975 Input_file->new("${EXTRACTED}DNumType.txt", v3.1.0,
15976 Property => 'Numeric_Type',
15977 Has_Missings_Defaults => $NOT_IGNORED,
15978 ),
15979 Input_file->new("${EXTRACTED}DEastAsianWidth.txt", v3.1.0,
15980 Property => 'East_Asian_Width',
15981 Has_Missings_Defaults => $NOT_IGNORED,
15982 ),
15983 Input_file->new("${EXTRACTED}DLineBreak.txt", v3.1.0,
15984 Property => 'Line_Break',
15985 Has_Missings_Defaults => $NOT_IGNORED,
15986 ),
15987 Input_file->new("${EXTRACTED}DBidiClass.txt", v3.1.1,
15988 Property => 'Bidi_Class',
15989 Has_Missings_Defaults => $NOT_IGNORED,
15990 ),
15991 Input_file->new("${EXTRACTED}DDecompositionType.txt", v3.1.0,
15992 Property => 'Decomposition_Type',
15993 Has_Missings_Defaults => $NOT_IGNORED,
15994 ),
15995 Input_file->new("${EXTRACTED}DBinaryProperties.txt", v3.1.0),
15996 Input_file->new("${EXTRACTED}DNumValues.txt", v3.1.0,
15997 Property => 'Numeric_Value',
15998 Each_Line_Handler => \&filter_numeric_value_line,
15999 Has_Missings_Defaults => $NOT_IGNORED,
16000 ),
16001 Input_file->new("${EXTRACTED}DJoinGroup.txt", v3.1.0,
16002 Property => 'Joining_Group',
16003 Has_Missings_Defaults => $NOT_IGNORED,
16004 ),
16005
16006 Input_file->new("${EXTRACTED}DJoinType.txt", v3.1.0,
16007 Property => 'Joining_Type',
16008 Has_Missings_Defaults => $NOT_IGNORED,
16009 ),
16010 Input_file->new('Jamo.txt', v2.0.0,
16011 Property => 'Jamo_Short_Name',
16012 Each_Line_Handler => \&filter_jamo_line,
16013 ),
16014 Input_file->new('UnicodeData.txt', v1.1.5,
16015 Pre_Handler => \&setup_UnicodeData,
16016
16017 # We clean up this file for some early versions.
16018 Each_Line_Handler => [ (($v_version lt v2.0.0 )
16019 ? \&filter_v1_ucd
16020 : ($v_version eq v2.1.5)
16021 ? \&filter_v2_1_5_ucd
3ffed8c2
KW
16022
16023 # And for 5.14 Perls with 6.0,
16024 # have to also make changes
16025 : ($v_version ge v6.0.0)
16026 ? \&filter_v6_ucd
16027 : undef),
99870f4d
KW
16028
16029 # And the main filter
16030 \&filter_UnicodeData_line,
16031 ],
16032 EOF_Handler => \&EOF_UnicodeData,
16033 ),
16034 Input_file->new('ArabicShaping.txt', v2.0.0,
16035 Each_Line_Handler =>
16036 [ ($v_version lt 4.1.0)
16037 ? \&filter_old_style_arabic_shaping
16038 : undef,
16039 \&filter_arabic_shaping_line,
16040 ],
16041 Has_Missings_Defaults => $NOT_IGNORED,
16042 ),
16043 Input_file->new('Blocks.txt', v2.0.0,
16044 Property => 'Block',
16045 Has_Missings_Defaults => $NOT_IGNORED,
16046 Each_Line_Handler => \&filter_blocks_lines
16047 ),
16048 Input_file->new('PropList.txt', v2.0.0,
16049 Each_Line_Handler => (($v_version lt v3.1.0)
16050 ? \&filter_old_style_proplist
16051 : undef),
16052 ),
16053 Input_file->new('Unihan.txt', v2.0.0,
16054 Pre_Handler => \&setup_unihan,
16055 Optional => 1,
16056 Each_Line_Handler => \&filter_unihan_line,
16057 ),
16058 Input_file->new('SpecialCasing.txt', v2.1.8,
16059 Each_Line_Handler => \&filter_special_casing_line,
16060 Pre_Handler => \&setup_special_casing,
dbf17f82 16061 Has_Missings_Defaults => $IGNORED,
99870f4d
KW
16062 ),
16063 Input_file->new(
16064 'LineBreak.txt', v3.0.0,
16065 Has_Missings_Defaults => $NOT_IGNORED,
16066 Property => 'Line_Break',
16067 # Early versions had problematic syntax
16068 Each_Line_Handler => (($v_version lt v3.1.0)
16069 ? \&filter_early_ea_lb
16070 : undef),
16071 ),
16072 Input_file->new('EastAsianWidth.txt', v3.0.0,
16073 Property => 'East_Asian_Width',
16074 Has_Missings_Defaults => $NOT_IGNORED,
16075 # Early versions had problematic syntax
16076 Each_Line_Handler => (($v_version lt v3.1.0)
16077 ? \&filter_early_ea_lb
16078 : undef),
16079 ),
16080 Input_file->new('CompositionExclusions.txt', v3.0.0,
16081 Property => 'Composition_Exclusion',
16082 ),
16083 Input_file->new('BidiMirroring.txt', v3.0.1,
16084 Property => 'Bidi_Mirroring_Glyph',
16085 ),
37e2e78e 16086 Input_file->new("NormalizationTest.txt", v3.0.1,
09ca89ce 16087 Skip => 'Validation Tests',
37e2e78e 16088 ),
99870f4d
KW
16089 Input_file->new('CaseFolding.txt', v3.0.1,
16090 Pre_Handler => \&setup_case_folding,
16091 Each_Line_Handler =>
16092 [ ($v_version lt v3.1.0)
16093 ? \&filter_old_style_case_folding
16094 : undef,
16095 \&filter_case_folding_line
16096 ],
dbf17f82 16097 Has_Missings_Defaults => $IGNORED,
99870f4d
KW
16098 ),
16099 Input_file->new('DCoreProperties.txt', v3.1.0,
16100 # 5.2 changed this file
16101 Has_Missings_Defaults => (($v_version ge v5.2.0)
16102 ? $NOT_IGNORED
16103 : $NO_DEFAULTS),
16104 ),
16105 Input_file->new('Scripts.txt', v3.1.0,
16106 Property => 'Script',
16107 Has_Missings_Defaults => $NOT_IGNORED,
16108 ),
16109 Input_file->new('DNormalizationProps.txt', v3.1.0,
16110 Has_Missings_Defaults => $NOT_IGNORED,
16111 Each_Line_Handler => (($v_version lt v4.0.1)
16112 ? \&filter_old_style_normalization_lines
16113 : undef),
16114 ),
16115 Input_file->new('HangulSyllableType.txt', v4.0.0,
16116 Has_Missings_Defaults => $NOT_IGNORED,
16117 Property => 'Hangul_Syllable_Type'),
16118 Input_file->new("$AUXILIARY/WordBreakProperty.txt", v4.1.0,
16119 Property => 'Word_Break',
16120 Has_Missings_Defaults => $NOT_IGNORED,
16121 ),
16122 Input_file->new("$AUXILIARY/GraphemeBreakProperty.txt", v4.1.0,
16123 Property => 'Grapheme_Cluster_Break',
16124 Has_Missings_Defaults => $NOT_IGNORED,
16125 ),
37e2e78e
KW
16126 Input_file->new("$AUXILIARY/GCBTest.txt", v4.1.0,
16127 Handler => \&process_GCB_test,
16128 ),
16129 Input_file->new("$AUXILIARY/LBTest.txt", v4.1.0,
09ca89ce 16130 Skip => 'Validation Tests',
37e2e78e
KW
16131 ),
16132 Input_file->new("$AUXILIARY/SBTest.txt", v4.1.0,
09ca89ce 16133 Skip => 'Validation Tests',
37e2e78e
KW
16134 ),
16135 Input_file->new("$AUXILIARY/WBTest.txt", v4.1.0,
09ca89ce 16136 Skip => 'Validation Tests',
37e2e78e 16137 ),
99870f4d
KW
16138 Input_file->new("$AUXILIARY/SentenceBreakProperty.txt", v4.1.0,
16139 Property => 'Sentence_Break',
16140 Has_Missings_Defaults => $NOT_IGNORED,
16141 ),
16142 Input_file->new('NamedSequences.txt', v4.1.0,
16143 Handler => \&process_NamedSequences
16144 ),
16145 Input_file->new('NameAliases.txt', v5.0.0,
16146 Property => 'Name_Alias',
b8ba2307 16147 Pre_Handler => ($v_version le v6.0.0)
ce432655 16148 ? \&setup_early_name_alias
dcd72625 16149 : undef,
b8ba2307
KW
16150 Each_Line_Handler => ($v_version le v6.0.0)
16151 ? \&filter_early_version_name_alias_line
16152 : \&filter_later_version_name_alias_line,
99870f4d 16153 ),
37e2e78e 16154 Input_file->new("BidiTest.txt", v5.2.0,
09ca89ce 16155 Skip => 'Validation Tests',
37e2e78e 16156 ),
99870f4d
KW
16157 Input_file->new('UnihanIndicesDictionary.txt', v5.2.0,
16158 Optional => 1,
16159 Each_Line_Handler => \&filter_unihan_line,
16160 ),
16161 Input_file->new('UnihanDataDictionaryLike.txt', v5.2.0,
16162 Optional => 1,
16163 Each_Line_Handler => \&filter_unihan_line,
16164 ),
16165 Input_file->new('UnihanIRGSources.txt', v5.2.0,
16166 Optional => 1,
16167 Pre_Handler => \&setup_unihan,
16168 Each_Line_Handler => \&filter_unihan_line,
16169 ),
16170 Input_file->new('UnihanNumericValues.txt', v5.2.0,
16171 Optional => 1,
16172 Each_Line_Handler => \&filter_unihan_line,
16173 ),
16174 Input_file->new('UnihanOtherMappings.txt', v5.2.0,
16175 Optional => 1,
16176 Each_Line_Handler => \&filter_unihan_line,
16177 ),
16178 Input_file->new('UnihanRadicalStrokeCounts.txt', v5.2.0,
16179 Optional => 1,
16180 Each_Line_Handler => \&filter_unihan_line,
16181 ),
16182 Input_file->new('UnihanReadings.txt', v5.2.0,
16183 Optional => 1,
16184 Each_Line_Handler => \&filter_unihan_line,
16185 ),
16186 Input_file->new('UnihanVariants.txt', v5.2.0,
16187 Optional => 1,
16188 Each_Line_Handler => \&filter_unihan_line,
16189 ),
82aed44a
KW
16190 Input_file->new('ScriptExtensions.txt', v6.0.0,
16191 Property => 'Script_Extensions',
16192 Pre_Handler => \&setup_script_extensions,
fbe1e607 16193 Each_Line_Handler => \&filter_script_extensions_line,
4fec90df
KW
16194 Has_Missings_Defaults => (($v_version le v6.0.0)
16195 ? $NO_DEFAULTS
16196 : $IGNORED),
82aed44a 16197 ),
3111abc0
KW
16198 # The two Indic files are actually available starting in v6.0.0, but their
16199 # property values are missing from PropValueAliases.txt in that release,
16200 # so that further work would have to be done to get them to work properly
16201 # for that release.
16202 Input_file->new('IndicMatraCategory.txt', v6.1.0,
16203 Property => 'Indic_Matra_Category',
16204 Has_Missings_Defaults => $NOT_IGNORED,
16205 Skip => "Provisional; for the analysis and processing of Indic scripts",
16206 ),
16207 Input_file->new('IndicSyllabicCategory.txt', v6.1.0,
16208 Property => 'Indic_Syllabic_Category',
16209 Has_Missings_Defaults => $NOT_IGNORED,
16210 Skip => "Provisional; for the analysis and processing of Indic scripts",
16211 ),
99870f4d 16212);
99598c8c 16213
99870f4d
KW
16214# End of all the preliminaries.
16215# Do it...
99598c8c 16216
99870f4d
KW
16217if ($compare_versions) {
16218 Carp::my_carp(<<END
16219Warning. \$compare_versions is set. Output is not suitable for production
16220END
16221 );
16222}
99598c8c 16223
99870f4d
KW
16224# Put into %potential_files a list of all the files in the directory structure
16225# that could be inputs to this program, excluding those that we should ignore.
37e2e78e 16226# Use absolute file names because it makes it easier across machine types.
99870f4d
KW
16227my @ignored_files_full_names = map { File::Spec->rel2abs(
16228 internal_file_to_platform($_))
16229 } keys %ignored_files;
16230File::Find::find({
16231 wanted=>sub {
37e2e78e 16232 return unless /\.txt$/i; # Some platforms change the name's case
517956bf 16233 my $full = lc(File::Spec->rel2abs($_));
99870f4d 16234 $potential_files{$full} = 1
37e2e78e 16235 if ! grep { $full eq lc($_) } @ignored_files_full_names;
99870f4d
KW
16236 return;
16237 }
16238}, File::Spec->curdir());
99598c8c 16239
99870f4d 16240my @mktables_list_output_files;
cdcef19a 16241my $old_start_time = 0;
cf25bb62 16242
3644ba60
KW
16243if (! -e $file_list) {
16244 print "'$file_list' doesn't exist, so forcing rebuild.\n" if $verbosity >= $VERBOSE;
16245 $write_unchanged_files = 1;
16246} elsif ($write_unchanged_files) {
99870f4d
KW
16247 print "Not checking file list '$file_list'.\n" if $verbosity >= $VERBOSE;
16248}
16249else {
16250 print "Reading file list '$file_list'\n" if $verbosity >= $VERBOSE;
16251 my $file_handle;
23e33b60 16252 if (! open $file_handle, "<", $file_list) {
3644ba60 16253 Carp::my_carp("Failed to open '$file_list'; turning on -globlist option instead: $!");
99870f4d
KW
16254 $glob_list = 1;
16255 }
16256 else {
16257 my @input;
16258
16259 # Read and parse mktables.lst, placing the results from the first part
16260 # into @input, and the second part into @mktables_list_output_files
16261 for my $list ( \@input, \@mktables_list_output_files ) {
16262 while (<$file_handle>) {
16263 s/^ \s+ | \s+ $//xg;
cdcef19a
KW
16264 if (/^ \s* \# .* Autogenerated\ starting\ on\ (\d+)/x) {
16265 $old_start_time = $1;
16266 }
99870f4d
KW
16267 next if /^ \s* (?: \# .* )? $/x;
16268 last if /^ =+ $/x;
16269 my ( $file ) = split /\t/;
16270 push @$list, $file;
cf25bb62 16271 }
99870f4d
KW
16272 @$list = uniques(@$list);
16273 next;
cf25bb62
JH
16274 }
16275
99870f4d
KW
16276 # Look through all the input files
16277 foreach my $input (@input) {
16278 next if $input eq 'version'; # Already have checked this.
cf25bb62 16279
99870f4d
KW
16280 # Ignore if doesn't exist. The checking about whether we care or
16281 # not is done via the Input_file object.
16282 next if ! file_exists($input);
5beb625e 16283
99870f4d
KW
16284 # The paths are stored with relative names, and with '/' as the
16285 # delimiter; convert to absolute on this machine
517956bf 16286 my $full = lc(File::Spec->rel2abs(internal_file_to_platform($input)));
faf3cf6b
KW
16287 $potential_files{lc $full} = 1
16288 if ! grep { lc($full) eq lc($_) } @ignored_files_full_names;
99870f4d 16289 }
5beb625e 16290 }
cf25bb62 16291
99870f4d
KW
16292 close $file_handle;
16293}
16294
16295if ($glob_list) {
16296
16297 # Here wants to process all .txt files in the directory structure.
16298 # Convert them to full path names. They are stored in the platform's
16299 # relative style
f86864ac
KW
16300 my @known_files;
16301 foreach my $object (@input_file_objects) {
16302 my $file = $object->file;
16303 next unless defined $file;
16304 push @known_files, File::Spec->rel2abs($file);
16305 }
99870f4d
KW
16306
16307 my @unknown_input_files;
faf3cf6b
KW
16308 foreach my $file (keys %potential_files) { # The keys are stored in lc
16309 next if grep { $file eq lc($_) } @known_files;
99870f4d
KW
16310
16311 # Here, the file is unknown to us. Get relative path name
16312 $file = File::Spec->abs2rel($file);
16313 push @unknown_input_files, $file;
16314
16315 # What will happen is we create a data structure for it, and add it to
16316 # the list of input files to process. First get the subdirectories
16317 # into an array
16318 my (undef, $directories, undef) = File::Spec->splitpath($file);
16319 $directories =~ s;/$;;; # Can have extraneous trailing '/'
16320 my @directories = File::Spec->splitdir($directories);
16321
16322 # If the file isn't extracted (meaning none of the directories is the
16323 # extracted one), just add it to the end of the list of inputs.
16324 if (! grep { $EXTRACTED_DIR eq $_ } @directories) {
99f78760 16325 push @input_file_objects, Input_file->new($file, v0);
99870f4d
KW
16326 }
16327 else {
16328
16329 # Here, the file is extracted. It needs to go ahead of most other
16330 # processing. Search for the first input file that isn't a
16331 # special required property (that is, find one whose first_release
16332 # is non-0), and isn't extracted. Also, the Age property file is
16333 # processed before the extracted ones, just in case
16334 # $compare_versions is set.
16335 for (my $i = 0; $i < @input_file_objects; $i++) {
16336 if ($input_file_objects[$i]->first_released ne v0
517956bf
CB
16337 && lc($input_file_objects[$i]->file) ne 'dage.txt'
16338 && $input_file_objects[$i]->file !~ /$EXTRACTED_DIR/i)
99870f4d 16339 {
99f78760 16340 splice @input_file_objects, $i, 0,
37e2e78e 16341 Input_file->new($file, v0);
99870f4d
KW
16342 last;
16343 }
cf25bb62 16344 }
99870f4d 16345
cf25bb62 16346 }
d2d499f5 16347 }
99870f4d 16348 if (@unknown_input_files) {
23e33b60 16349 print STDERR simple_fold(join_lines(<<END
99870f4d
KW
16350
16351The following files are unknown as to how to handle. Assuming they are
16352typical property files. You'll know by later error messages if it worked or
16353not:
16354END
99f78760 16355 ) . " " . join(", ", @unknown_input_files) . "\n\n");
99870f4d
KW
16356 }
16357} # End of looking through directory structure for more .txt files.
5beb625e 16358
99870f4d
KW
16359# Create the list of input files from the objects we have defined, plus
16360# version
16361my @input_files = 'version';
16362foreach my $object (@input_file_objects) {
16363 my $file = $object->file;
16364 next if ! defined $file; # Not all objects have files
16365 next if $object->optional && ! -e $file;
16366 push @input_files, $file;
16367}
5beb625e 16368
99870f4d
KW
16369if ( $verbosity >= $VERBOSE ) {
16370 print "Expecting ".scalar( @input_files )." input files. ",
16371 "Checking ".scalar( @mktables_list_output_files )." output files.\n";
16372}
cf25bb62 16373
aeab6150
KW
16374# We set $most_recent to be the most recently changed input file, including
16375# this program itself (done much earlier in this file)
99870f4d 16376foreach my $in (@input_files) {
cdcef19a
KW
16377 next unless -e $in; # Keep going even if missing a file
16378 my $mod_time = (stat $in)[9];
aeab6150 16379 $most_recent = $mod_time if $mod_time > $most_recent;
99870f4d
KW
16380
16381 # See that the input files have distinct names, to warn someone if they
16382 # are adding a new one
16383 if ($make_list) {
16384 my ($volume, $directories, $file ) = File::Spec->splitpath($in);
16385 $directories =~ s;/$;;; # Can have extraneous trailing '/'
16386 my @directories = File::Spec->splitdir($directories);
16387 my $base = $file =~ s/\.txt$//;
16388 construct_filename($file, 'mutable', \@directories);
cf25bb62 16389 }
99870f4d 16390}
cf25bb62 16391
dff6c046 16392my $rebuild = $write_unchanged_files # Rebuild: if unconditional rebuild
cdcef19a 16393 || ! scalar @mktables_list_output_files # or if no outputs known
aeab6150 16394 || $old_start_time < $most_recent; # or out-of-date
cf25bb62 16395
99870f4d
KW
16396# Now we check to see if any output files are older than youngest, if
16397# they are, we need to continue on, otherwise we can presumably bail.
d1d1cd7a 16398if (! $rebuild) {
99870f4d
KW
16399 foreach my $out (@mktables_list_output_files) {
16400 if ( ! file_exists($out)) {
16401 print "'$out' is missing.\n" if $verbosity >= $VERBOSE;
d1d1cd7a 16402 $rebuild = 1;
99870f4d
KW
16403 last;
16404 }
16405 #local $to_trace = 1 if main::DEBUG;
aeab6150
KW
16406 trace $most_recent, (stat $out)[9] if main::DEBUG && $to_trace;
16407 if ( (stat $out)[9] <= $most_recent ) {
16408 #trace "$out: most recent mod time: ", (stat $out)[9], ", youngest: $most_recent\n" if main::DEBUG && $to_trace;
99870f4d 16409 print "'$out' is too old.\n" if $verbosity >= $VERBOSE;
d1d1cd7a 16410 $rebuild = 1;
99870f4d 16411 last;
cf25bb62 16412 }
cf25bb62 16413 }
99870f4d 16414}
d1d1cd7a 16415if (! $rebuild) {
1265e11f 16416 print "Files seem to be ok, not bothering to rebuild. Add '-w' option to force build\n";
99870f4d
KW
16417 exit(0);
16418}
16419print "Must rebuild tables.\n" if $verbosity >= $VERBOSE;
cf25bb62 16420
99870f4d
KW
16421# Ready to do the major processing. First create the perl pseudo-property.
16422$perl = Property->new('perl', Type => $NON_STRING, Perl_Extension => 1);
cf25bb62 16423
99870f4d
KW
16424# Process each input file
16425foreach my $file (@input_file_objects) {
16426 $file->run;
d2d499f5
JH
16427}
16428
99870f4d 16429# Finish the table generation.
c4051cc5 16430
99870f4d
KW
16431print "Finishing processing Unicode properties\n" if $verbosity >= $PROGRESS;
16432finish_Unicode();
c4051cc5 16433
99870f4d
KW
16434print "Compiling Perl properties\n" if $verbosity >= $PROGRESS;
16435compile_perl();
c4051cc5 16436
99870f4d
KW
16437print "Creating Perl synonyms\n" if $verbosity >= $PROGRESS;
16438add_perl_synonyms();
c4051cc5 16439
99870f4d
KW
16440print "Writing tables\n" if $verbosity >= $PROGRESS;
16441write_all_tables();
c4051cc5 16442
99870f4d
KW
16443# Write mktables.lst
16444if ( $file_list and $make_list ) {
c4051cc5 16445
99870f4d
KW
16446 print "Updating '$file_list'\n" if $verbosity >= $PROGRESS;
16447 foreach my $file (@input_files, @files_actually_output) {
16448 my (undef, $directories, $file) = File::Spec->splitpath($file);
16449 my @directories = File::Spec->splitdir($directories);
16450 $file = join '/', @directories, $file;
16451 }
16452
16453 my $ofh;
16454 if (! open $ofh,">",$file_list) {
16455 Carp::my_carp("Can't write to '$file_list'. Skipping: $!");
16456 return
16457 }
16458 else {
cdcef19a 16459 my $localtime = localtime $start_time;
99870f4d
KW
16460 print $ofh <<"END";
16461#
16462# $file_list -- File list for $0.
97050450 16463#
cdcef19a 16464# Autogenerated starting on $start_time ($localtime)
97050450
YO
16465#
16466# - First section is input files
99870f4d 16467# ($0 itself is not listed but is automatically considered an input)
98dc9551 16468# - Section separator is /^=+\$/
97050450
YO
16469# - Second section is a list of output files.
16470# - Lines matching /^\\s*#/ are treated as comments
16471# which along with blank lines are ignored.
16472#
16473
16474# Input files:
16475
99870f4d
KW
16476END
16477 print $ofh "$_\n" for sort(@input_files);
16478 print $ofh "\n=================================\n# Output files:\n\n";
16479 print $ofh "$_\n" for sort @files_actually_output;
16480 print $ofh "\n# ",scalar(@input_files)," input files\n",
16481 "# ",scalar(@files_actually_output)+1," output files\n\n",
16482 "# End list\n";
16483 close $ofh
16484 or Carp::my_carp("Failed to close $ofh: $!");
16485
16486 print "Filelist has ",scalar(@input_files)," input files and ",
16487 scalar(@files_actually_output)+1," output files\n"
16488 if $verbosity >= $VERBOSE;
16489 }
16490}
16491
16492# Output these warnings unless -q explicitly specified.
c83dffeb 16493if ($verbosity >= $NORMAL_VERBOSITY && ! $debug_skip) {
99870f4d
KW
16494 if (@unhandled_properties) {
16495 print "\nProperties and tables that unexpectedly have no code points\n";
16496 foreach my $property (sort @unhandled_properties) {
16497 print $property, "\n";
16498 }
16499 }
16500
16501 if (%potential_files) {
16502 print "\nInput files that are not considered:\n";
16503 foreach my $file (sort keys %potential_files) {
16504 print File::Spec->abs2rel($file), "\n";
16505 }
16506 }
16507 print "\nAll done\n" if $verbosity >= $VERBOSE;
16508}
5beb625e 16509exit(0);
cf25bb62 16510
99870f4d 16511# TRAILING CODE IS USED BY make_property_test_script()
5beb625e 16512__DATA__
99870f4d 16513
5beb625e
JH
16514use strict;
16515use warnings;
16516
66fd7fd0
KW
16517# If run outside the normal test suite on an ASCII platform, you can
16518# just create a latin1_to_native() function that just returns its
16519# inputs, because that's the only function used from test.pl
16520require "test.pl";
16521
37e2e78e
KW
16522# Test qr/\X/ and the \p{} regular expression constructs. This file is
16523# constructed by mktables from the tables it generates, so if mktables is
16524# buggy, this won't necessarily catch those bugs. Tests are generated for all
16525# feasible properties; a few aren't currently feasible; see
16526# is_code_point_usable() in mktables for details.
99870f4d
KW
16527
16528# Standard test packages are not used because this manipulates SIG_WARN. It
16529# exits 0 if every non-skipped test succeeded; -1 if any failed.
16530
5beb625e
JH
16531my $Tests = 0;
16532my $Fails = 0;
99870f4d 16533
99870f4d
KW
16534sub Expect($$$$) {
16535 my $expected = shift;
16536 my $ord = shift;
16537 my $regex = shift;
16538 my $warning_type = shift; # Type of warning message, like 'deprecated'
16539 # or empty if none
16540 my $line = (caller)[2];
66fd7fd0 16541 $ord = ord(latin1_to_native(chr($ord)));
37e2e78e 16542
99870f4d 16543 # Convert the code point to hex form
23e33b60 16544 my $string = sprintf "\"\\x{%04X}\"", $ord;
99870f4d 16545
99870f4d 16546 my @tests = "";
5beb625e 16547
37e2e78e
KW
16548 # The first time through, use all warnings. If the input should generate
16549 # a warning, add another time through with them turned off
99870f4d
KW
16550 push @tests, "no warnings '$warning_type';" if $warning_type;
16551
16552 foreach my $no_warnings (@tests) {
16553
16554 # Store any warning messages instead of outputting them
16555 local $SIG{__WARN__} = $SIG{__WARN__};
16556 my $warning_message;
16557 $SIG{__WARN__} = sub { $warning_message = $_[0] };
16558
16559 $Tests++;
16560
16561 # A string eval is needed because of the 'no warnings'.
16562 # Assumes no parens in the regular expression
16563 my $result = eval "$no_warnings
16564 my \$RegObj = qr($regex);
16565 $string =~ \$RegObj ? 1 : 0";
16566 if (not defined $result) {
16567 print "not ok $Tests - couldn't compile /$regex/; line $line: $@\n";
16568 $Fails++;
16569 }
16570 elsif ($result ^ $expected) {
16571 print "not ok $Tests - expected $expected but got $result for $string =~ qr/$regex/; line $line\n";
16572 $Fails++;
16573 }
16574 elsif ($warning_message) {
16575 if (! $warning_type || ($warning_type && $no_warnings)) {
16576 print "not ok $Tests - for qr/$regex/ did not expect warning message '$warning_message'; line $line\n";
16577 $Fails++;
16578 }
16579 else {
16580 print "ok $Tests - expected and got a warning message for qr/$regex/; line $line\n";
16581 }
16582 }
16583 elsif ($warning_type && ! $no_warnings) {
16584 print "not ok $Tests - for qr/$regex/ expected a $warning_type warning message, but got none; line $line\n";
16585 $Fails++;
16586 }
16587 else {
16588 print "ok $Tests - got $result for $string =~ qr/$regex/; line $line\n";
16589 }
5beb625e 16590 }
99870f4d 16591 return;
5beb625e 16592}
d73e5302 16593
99870f4d
KW
16594sub Error($) {
16595 my $regex = shift;
5beb625e 16596 $Tests++;
99870f4d 16597 if (eval { 'x' =~ qr/$regex/; 1 }) {
5beb625e 16598 $Fails++;
99870f4d
KW
16599 my $line = (caller)[2];
16600 print "not ok $Tests - re compiled ok, but expected error for qr/$regex/; line $line: $@\n";
5beb625e 16601 }
99870f4d
KW
16602 else {
16603 my $line = (caller)[2];
16604 print "ok $Tests - got and expected error for qr/$regex/; line $line\n";
16605 }
16606 return;
5beb625e
JH
16607}
16608
37e2e78e
KW
16609# GCBTest.txt character that separates grapheme clusters
16610my $breakable_utf8 = my $breakable = chr(0xF7);
16611utf8::upgrade($breakable_utf8);
16612
16613# GCBTest.txt character that indicates that the adjoining code points are part
16614# of the same grapheme cluster
16615my $nobreak_utf8 = my $nobreak = chr(0xD7);
16616utf8::upgrade($nobreak_utf8);
16617
16618sub Test_X($) {
16619 # Test qr/\X/ matches. The input is a line from auxiliary/GCBTest.txt
16620 # Each such line is a sequence of code points given by their hex numbers,
16621 # separated by the two characters defined just before this subroutine that
16622 # indicate that either there can or cannot be a break between the adjacent
16623 # code points. If there isn't a break, that means the sequence forms an
16624 # extended grapheme cluster, which means that \X should match the whole
16625 # thing. If there is a break, \X should stop there. This is all
16626 # converted by this routine into a match:
16627 # $string =~ /(\X)/,
16628 # Each \X should match the next cluster; and that is what is checked.
16629
16630 my $template = shift;
16631
16632 my $line = (caller)[2];
16633
16634 # The line contains characters above the ASCII range, but in Latin1. It
16635 # may or may not be in utf8, and if it is, it may or may not know it. So,
16636 # convert these characters to 8 bits. If knows is in utf8, simply
16637 # downgrade.
16638 if (utf8::is_utf8($template)) {
16639 utf8::downgrade($template);
16640 } else {
16641
16642 # Otherwise, if it is in utf8, but doesn't know it, the next lines
16643 # convert the two problematic characters to their 8-bit equivalents.
16644 # If it isn't in utf8, they don't harm anything.
16645 use bytes;
16646 $template =~ s/$nobreak_utf8/$nobreak/g;
16647 $template =~ s/$breakable_utf8/$breakable/g;
16648 }
16649
16650 # Get rid of the leading and trailing breakables
16651 $template =~ s/^ \s* $breakable \s* //x;
16652 $template =~ s/ \s* $breakable \s* $ //x;
16653
16654 # And no-breaks become just a space.
16655 $template =~ s/ \s* $nobreak \s* / /xg;
16656
16657 # Split the input into segments that are breakable between them.
16658 my @segments = split /\s*$breakable\s*/, $template;
16659
16660 my $string = "";
16661 my $display_string = "";
16662 my @should_match;
16663 my @should_display;
16664
16665 # Convert the code point sequence in each segment into a Perl string of
16666 # characters
16667 foreach my $segment (@segments) {
16668 my @code_points = split /\s+/, $segment;
16669 my $this_string = "";
16670 my $this_display = "";
16671 foreach my $code_point (@code_points) {
66fd7fd0 16672 $this_string .= latin1_to_native(chr(hex $code_point));
37e2e78e
KW
16673 $this_display .= "\\x{$code_point}";
16674 }
16675
16676 # The next cluster should match the string in this segment.
16677 push @should_match, $this_string;
16678 push @should_display, $this_display;
16679 $string .= $this_string;
16680 $display_string .= $this_display;
16681 }
16682
16683 # If a string can be represented in both non-ut8 and utf8, test both cases
16684 UPGRADE:
16685 for my $to_upgrade (0 .. 1) {
678f13d5 16686
37e2e78e
KW
16687 if ($to_upgrade) {
16688
16689 # If already in utf8, would just be a repeat
16690 next UPGRADE if utf8::is_utf8($string);
16691
16692 utf8::upgrade($string);
16693 }
16694
16695 # Finally, do the \X match.
16696 my @matches = $string =~ /(\X)/g;
16697
16698 # Look through each matched cluster to verify that it matches what we
16699 # expect.
16700 my $min = (@matches < @should_match) ? @matches : @should_match;
16701 for my $i (0 .. $min - 1) {
16702 $Tests++;
16703 if ($matches[$i] eq $should_match[$i]) {
16704 print "ok $Tests - ";
16705 if ($i == 0) {
16706 print "In \"$display_string\" =~ /(\\X)/g, \\X #1";
16707 } else {
16708 print "And \\X #", $i + 1,
16709 }
16710 print " correctly matched $should_display[$i]; line $line\n";
16711 } else {
16712 $matches[$i] = join("", map { sprintf "\\x{%04X}", $_ }
16713 unpack("U*", $matches[$i]));
16714 print "not ok $Tests - In \"$display_string\" =~ /(\\X)/g, \\X #",
16715 $i + 1,
16716 " should have matched $should_display[$i]",
16717 " but instead matched $matches[$i]",
16718 ". Abandoning rest of line $line\n";
16719 next UPGRADE;
16720 }
16721 }
16722
16723 # And the number of matches should equal the number of expected matches.
16724 $Tests++;
16725 if (@matches == @should_match) {
16726 print "ok $Tests - Nothing was left over; line $line\n";
16727 } else {
16728 print "not ok $Tests - There were ", scalar @should_match, " \\X matches expected, but got ", scalar @matches, " instead; line $line\n";
16729 }
16730 }
16731
16732 return;
16733}
16734
99870f4d 16735sub Finished() {
f86864ac 16736 print "1..$Tests\n";
99870f4d 16737 exit($Fails ? -1 : 0);
5beb625e 16738}
99870f4d
KW
16739
16740Error('\p{Script=InGreek}'); # Bug #69018
37e2e78e 16741Test_X("1100 $nobreak 1161"); # Bug #70940
ae5b72c8
KW
16742Expect(0, 0x2028, '\p{Print}', ""); # Bug # 71722
16743Expect(0, 0x2029, '\p{Print}', ""); # Bug # 71722
eadadd41 16744Expect(1, 0xFF10, '\p{XDigit}', ""); # Bug # 71726