chiark / gitweb /
untested utf32_is_word_boundary() and associated table changes
[disorder] / scripts / make-unidata
1 #! /usr/bin/perl -w
2 #
3 # This file is part of DisOrder.
4 # Copyright (C) 2007 Richard Kettlewell
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 # USA
20 #
21 #
22 # Generate Unicode support tables
23 #
24 # This script will download data from unicode.org if the required files
25 # aren't in the current directory.
26 #
27 # After modifying this script you should run:
28 #  make -C lib rebuild-unicode check
29 #
30 # Things not supported yet:
31 #  - SpecialCasing.txt data for case mapping
32 #  - Title case offsets
33 #  - Some kind of hinting for composition
34 #  - Word boundary support
35 #  - ...
36 #
37 # NB the generated files DO NOT offer a stable ABI and so are not immediately
38 # suitable for use in a general-purpose library.  Things that would need to
39 # be done:
40 #  - Hide unidata.h from applications; it will never be ABI- or even API-stable.
41 #  - Stablized General_Category values
42 #  - Extend the unicode.h API to general utility rather than just what
43 #    DisOrder needs.
44 #  - ...
45 #
46 use strict;
47 use File::Basename;
48
49 sub out {
50     print @_ or die "$!\n";
51 }
52
53 sub key {
54     my $d = shift;
55     local $_;
56
57     return join("-", map($d->{$_}, sort keys %$d));
58 }
59
60 # Size of a subtable
61 #
62 # This can be varied to trade off the number of subtables against their size.
63 our $modulus = 128;
64
65 my %cats = ();                  # known general categories
66 my %data = ();                  # mapping of codepoints to information
67 my $max = 0;                    # maximum codepoint
68 my $maxccc = 0;                 # maximum combining class
69 my $maxud = 0;
70 my $minud = 0;                  # max/min upper case offset
71 my $maxld = 0;
72 my $minld = 0;                  # max/min lower case offset
73
74 # Make sure we have our desired input files.  We explicitly specify a
75 # Unicode standard version to make sure that a given version of DisOrder
76 # supports a given version of Unicode.
77 sub input {
78     my $path = shift;
79     my $lpath = basename($path);
80     if(!-e $lpath) {
81         system("wget http://www.unicode.org/Public/5.0.0/ucd/$path");
82         chmod(0444, $lpath) or die "$lpath: $!\n";
83     }
84     open(STDIN, "<$lpath") or die "$lpath: $!\n";
85 }
86
87
88 # Read the main data file
89 input("UnicodeData.txt");
90 while(<>) {
91     my @f = split(/;/, $_);
92     my $c = hex($f[0]);         # codepoint
93     next if $c >= 0xE0000;      # ignore various high-numbered stuff
94     # TODO justify this exclusion!
95     my $name = $f[1];
96     my $gc = $f[2];             # General_Category
97     my $ccc = $f[3];            # Canonical_Combining_Class
98     my $dm = $f[5];             # Decomposition_Type + Decomposition_Mapping
99     my $sum = hex($f[12]) || $c; # Simple_Uppercase_Mapping
100     my $slm = hex($f[13]) || $c; # Simple_Lowercase_Mapping
101     # recalculate the upper/lower case mappings as offsets
102     my $ud = $sum - $c;
103     my $ld = $slm - $c;
104     # update bounds on various values
105     $maxccc = $ccc if $ccc > $maxccc; # assumed never to be -ve
106     $minud = $ud if $ud < $minud;
107     $maxud = $ud if $ud > $maxud;
108     $minld = $ld if $ld < $minld;
109     $maxld = $ld if $ld > $maxld;
110     $data{$c} = {
111         "gc" => $gc,
112         "ccc" => $ccc,
113         "ud" => $ud,
114         "ld" => $ld,
115         };
116     if($dm ne '') {
117         if($dm !~ /</) {
118             # This is a canonical decomposition
119             $data{$c}->{canon} = $dm;
120             $data{$c}->{compat} = $dm;
121         } else {
122             # This is only a compatibility decomposition
123             $dm =~ s/^<.*>\s*//;
124             $data{$c}->{compat} = $dm;
125         }
126     }
127     $cats{$gc} = 1;
128     $max = $c if $c > $max;
129 }
130
131 sub read_prop_with_ranges {
132     my $path = shift;
133     my $propkey = shift;
134     input($path);
135     while(<>) {
136         chomp;
137         s/\s*\#.*//;
138         next if $_ eq '';
139         my ($range, $propval) = split(/\s*;\s*/, $_);
140         if($range =~ /(.*)\.\.(.*)/) {
141             for my $c (hex($1) .. hex($2)) {
142                 if(exists $data{$c}) {
143                     $data{$c}->{$propkey} = $propval;
144                 }
145             }
146         } else {
147             my $c = hex($range);
148             if(exists $data{$c}) {
149                 $data{$c}->{$propkey} = $propval;
150             }
151         }
152     }
153 }
154
155 # Grapheme_Break
156 # NB we do this BEFORE filling in blanks so that the Hangul characters
157 # don't get filled in; we can compute their properties mechanically.
158 read_prop_with_ranges("auxiliary/GraphemeBreakProperty.txt", "gbreak");
159
160 # Word_Break
161 # Same remarks about Hangul as above.  This one currently seems just too
162 # complicated to do programmatically so we'll take a byte to store it.
163 read_prop_with_ranges("auxiliary/WordBreakProperty.txt", "wbreak");
164
165 # Make the list of Word_Break values
166 my %wbpropvals = ();
167 for my $c (keys %data) {
168     if(!exists $data{$c}->{wbreak}) {
169         if(exists $data{$c}->{gbreak} && $data{$c}->{gbreak} eq 'Extend') {
170             $data{$c}->{wbreak} = 'Extend';
171         } else {
172             $data{$c}->{wbreak} = 'Other';
173         }
174     }
175     $wbpropvals{$data{$c}->{wbreak}} = 1;
176 }
177
178 # Round up the maximum value to a whole number of subtables
179 $max += ($modulus - 1) - ($max % $modulus);
180
181 # Make sure there are no gaps
182 for(my $c = 0; $c <= $max; ++$c) {
183     if(!exists $data{$c}) {
184         $data{$c} = {
185             "gc" => "Cn",       # not assigned
186             "ccc" => 0,
187             "ud" => 0,
188             "ld" => 0,
189             "wbreak" => 'Other',
190             };
191     }
192 }
193 $cats{'Cn'} = 1;
194
195 # Read the casefolding data too
196 input("CaseFolding.txt");
197 while(<>) {
198     chomp;
199     next if /^\#/ or $_ eq '';
200     my @f = split(/\s*;\s*/, $_);
201     # Full case folding means use status C and F.
202     # We discard status T, Turkish users may wish to change this.
203     if($f[1] eq 'C' or $f[1] eq 'F') {
204         my $c = hex($f[0]);
205         $data{$c}->{casefold} = $f[2];
206         # We are particularly interest in combining characters that
207         # case-fold to non-combining characters, or characters that
208         # case-fold to sequences with combining characters in non-initial
209         # positions, as these required decomposiiton before case-folding
210         my @d = map(hex($_), split(/\s+/, $data{$c}->{casefold}));
211         if($data{$c}->{ccc} != 0) {
212             # This is a combining character
213             if($data{$d[0]}->{ccc} == 0) {
214                 # The first character of its case-folded form is NOT
215                 # a combining character.  The field name is the example
216                 # explicitly mentioned in the spec.
217                 $data{$c}->{ypogegrammeni} = 1;
218             }
219         } else {
220             # This is a non-combining character; inspect the non-initial
221             # code points of the case-folded sequence
222             shift(@d);
223             if(grep($data{$_}->{ccc} != 0, @d)) {
224                 # Some non-initial code point in the case-folded for is NOT a
225                 # a combining character.
226                 $data{$c}->{ypogegrammeni} = 1;
227             }
228         }
229     }
230 }
231
232 # Generate the header file
233 open(STDOUT, ">unidata.h") or die "unidata.h: $!\n";
234
235 out("/* Automatically generated file, see scripts/make-unidata */\n",
236     "#ifndef UNIDATA_H\n",
237     "#define UNIDATA_H\n");
238
239 # TODO choose stable values for General_Category
240 out("enum unicode_gc_cat {\n",
241     join(",\n",
242          map("  unicode_gc_$_", sort keys %cats)), "\n};\n");
243
244 out("enum unicode_Word_Break {\n",
245     join(",\n",
246          map("  unicode_Word_Break_$_", sort keys %wbpropvals)),
247     "\n};\n");
248
249 out("enum unicode_flags {\n",
250     "  unicode_normalize_before_casefold = 1\n",
251     "};\n",
252     "\n");
253
254 # Choose the narrowest type that will fit the required values
255 sub choosetype {
256     my ($min, $max) = @_;
257     if($min >= 0) {
258         return "char" if $max <= 127;
259         return "unsigned char" if $max <= 255;
260         return "int16_t" if $max < 32767;
261         return "uint16_t" if $max < 65535;
262         return "int32_t";
263     } else {
264         return "char" if $min >= -127 && $max <= 127;
265         return "int16_t" if $min >= -32767 && $max <= 32767;
266         return "int32_t";
267     }
268 }
269
270 out("struct unidata {\n",
271     "  const uint32_t *compat;\n",
272     "  const uint32_t *canon;\n",
273     "  const uint32_t *casefold;\n",
274     "  ".choosetype($minud, $maxud)." upper_offset;\n",
275     "  ".choosetype($minld, $maxld)." lower_offset;\n",
276     "  ".choosetype(0, $maxccc)." ccc;\n",
277     "  char gc;\n",
278     "  uint8_t flags;\n",
279     "  char word_break;\n",
280     "};\n");
281 # compat, canon and casefold do have have non-BMP characters, so we
282 # can't use a simple 16-bit table.  We could use UTF-8 or UTF-16
283 # though, saving a bit of space (probably not that much...) at the
284 # cost of marginally reduced performance and additional complexity
285
286 out("extern const struct unidata *const unidata[];\n");
287
288 out("#define UNICODE_NCHARS ", ($max + 1), "\n");
289 out("#define UNICODE_MODULUS $modulus\n");
290
291 out("#endif\n");
292
293 close STDOUT or die "unidata.h: $!\n";
294
295 open(STDOUT, ">unidata.c") or die "unidata.c: $!\n";
296
297 out("/* Automatically generated file, see scripts/make-unidata */\n",
298     "#include <config.h>\n",
299     "#include \"types.h\"\n",
300     "#include \"unidata.h\"\n");
301
302 # Short aliases for general category codes
303
304 out(map(sprintf("#define %s unicode_gc_%s\n", $_, $_), sort keys %cats));
305
306 # Generate the decomposition mapping tables.  We look out for duplicates
307 # in order to save space and report this as decompsaved at the end.  In
308 # Unicode 5.0.0 this saves 1795 entries, which is at least 14Kbytes.
309 my $decompnum = 0;
310 my %decompnums = ();
311 my $decompsaved = 0;
312 out("static const uint32_t ");
313 for(my $c = 0; $c <= $max; ++$c) {
314     # If canon is set then compat will be too and will be identical.
315     # If compat is set the canon might be clear.  So we use the
316     # compat version and fix up the symbols after.
317     if(exists $data{$c}->{compat}) {
318         my $s = join(",",
319                      (map(hex($_), split(/\s+/, $data{$c}->{compat})), 0));
320         if(!exists $decompnums{$s}) {
321             out(",\n") if $decompnum != 0;
322             out("cd$decompnum\[]={$s}");
323             $decompnums{$s} = $decompnum++;
324         } else {
325             ++$decompsaved;
326         }
327         $data{$c}->{compatsym} = "cd$decompnums{$s}";
328         if(exists $data{$c}->{canon}) {
329             $data{$c}->{canonsym} = "cd$decompnums{$s}";
330         }
331     }
332 }
333 out(";\n");
334
335 # ...and the case folding table.  Again we compress equal entries to save
336 # space.  In Unicode 5.0.0 this saves 51 entries or at least 408 bytes.
337 # This doesns't seem as worthwhile as the decomposition mapping saving above.
338 my $cfnum = 0;
339 my %cfnums = ();
340 my $cfsaved = 0;
341 out("static const uint32_t ");
342 for(my $c = 0; $c <= $max; ++$c) {
343     if(exists $data{$c}->{casefold}) {
344         my $s = join(",",
345                      (map(hex($_), split(/\s+/, $data{$c}->{casefold})), 0));
346         if(!exists $cfnums{$s}) {
347             out(",\n") if $cfnum != 0;
348             out("cf$cfnum\[]={$s}");
349             $cfnums{$s} = $cfnum++;
350         } else {
351             ++$cfsaved;
352         }
353         $data{$c}->{cfsym} = "cf$cfnums{$s}";
354     }
355 }
356 out(";\n");
357
358 # Visit all the $modulus-character blocks in turn and generate the
359 # required subtables.  As above we spot duplicates to save space.  In
360 # Unicode 5.0.0 with $modulus=128 and current table data this saves
361 # 1372 subtables or at least three and a half megabytes on 32-bit
362 # platforms.
363
364 my %subtable = ();              # base->subtable number
365 my %subtableno = ();            # subtable number -> content
366 my $subtablecounter = 0;        # counter for subtable numbers
367 my $subtablessaved = 0;         # number of tables saved
368 for(my $base = 0; $base <= $max; $base += $modulus) {
369     my @t;
370     for(my $c = $base; $c < $base + $modulus; ++$c) {
371         my $d = $data{$c};
372         my $canonsym = ($data{$c}->{canonsym} or "0");
373         my $compatsym = ($data{$c}->{compatsym} or "0");
374         my $cfsym = ($data{$c}->{cfsym} or "0");
375         my @flags = ();
376         if($data{$c}->{ypogegrammeni}) {
377             push(@flags, "unicode_normalize_before_casefold");
378         }
379         my $flags = @flags ? join("|", @flags) : 0;
380         push(@t, "{".
381              join(",",
382                   $compatsym,
383                   $canonsym,
384                   $cfsym,
385                   $d->{ud},
386                   $d->{ld},
387                   $d->{ccc},
388                   $d->{gc},
389                   $flags,
390                   "unicode_Word_Break_$d->{wbreak}",
391              )."}");
392     }
393     my $t = join(",\n", @t);
394     if(!exists $subtable{$t}) {
395         out("static const struct unidata st$subtablecounter\[] = {\n",
396             "$t\n",
397             "};\n");
398         $subtable{$t} = $subtablecounter++;
399     } else {
400         ++$subtablessaved;
401     }
402     $subtableno{$base} = $subtable{$t};
403 }
404
405 out("const struct unidata*const unidata[]={\n");
406 for(my $base = 0; $base <= $max; $base += $modulus) {
407     out("st$subtableno{$base},\n");
408 }
409 out("};\n");
410
411 close STDOUT or die "unidata.c: $!\n";
412
413 print STDERR "max=$max, subtables=$subtablecounter, subtablessaved=$subtablessaved\n";
414 print STDERR "decompsaved=$decompsaved cfsaved=$cfsaved\n";