chiark / gitweb /
transition various bits of code to unicode.h interfaces
[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 #  - ...
35 #
36 # NB the generated files DO NOT offer a stable ABI and so are not immediately
37 # suitable for use in a general-purpose library.  Things that would need to
38 # be done:
39 #  - Hide unidata.h from applications; it will never be ABI- or even API-stable.
40 #  - Stablized General_Category values
41 #  - Extend the unicode.h API to general utility rather than just what
42 #    DisOrder needs.
43 #  - ...
44 #
45 use strict;
46 use File::Basename;
47
48 sub out {
49     print @_ or die "$!\n";
50 }
51
52 sub key {
53     my $d = shift;
54     local $_;
55
56     return join("-", map($d->{$_}, sort keys %$d));
57 }
58
59 # Size of a subtable
60 #
61 # This can be varied to trade off the number of subtables against their size.
62 # 16 gave the smallest results last time I checked (on a Mac with a 32-bit
63 # build).
64 our $modulus = 16;
65
66 if(@ARGV) {
67     $modulus = shift;
68 }
69
70 # Where to break the table.  There is a huge empty section of the Unicode
71 # code space and we deal with this by simply leaving it out of the table.
72 # This complicates the lookup function a little but should not affect
73 # performance in the cases we care about.
74 our $break_start = 0x30000;
75 our $break_end = 0xE0000;
76
77 # Similarly we simply omit the very top of the table and sort it out in the
78 # lookup function.
79 our $break_top = 0xE0200;
80
81 my %cats = ();                  # known general categories
82 my %data = ();                  # mapping of codepoints to information
83 my $max = 0;                    # maximum codepoint
84 my $maxccc = 0;                 # maximum combining class
85 my $maxud = 0;
86 my $minud = 0;                  # max/min upper case offset
87 my $maxld = 0;
88 my $minld = 0;                  # max/min lower case offset
89
90 # Make sure we have our desired input files.  We explicitly specify a
91 # Unicode standard version to make sure that a given version of DisOrder
92 # supports a given version of Unicode.
93 sub input {
94     my $path = shift;
95     my $lpath = basename($path);
96     if(!-e $lpath) {
97         system("wget http://www.unicode.org/Public/5.0.0/ucd/$path");
98         chmod(0444, $lpath) or die "$lpath: $!\n";
99     }
100     open(STDIN, "<$lpath") or die "$lpath: $!\n";
101     print STDERR "Reading $lpath...\n";
102 }
103
104
105 # Read the main data file
106 input("UnicodeData.txt");
107 my ($start, $end);
108 while(<>) {
109     my @f = split(/;/, $_);
110     my $c = hex($f[0]);         # codepoint
111     my $name = $f[1];
112     die "$f[0] $name is in the break\n" 
113         if $c >= $break_start && $c < $break_end;
114     my $gc = $f[2];             # General_Category
115     # Variuos GCs we don't expect to see in UnicodeData.txt
116     $cats{$gc} = 1;             # always record all GCs
117     if($name =~ /first>/i) {
118         $start = $c;
119         next;
120     } elsif($name =~ /last>/i) {
121         $end = $c;
122     } else {
123         $start = $end = $c;
124     }
125     die "unexpected Cn" if $gc eq 'Cn';
126     my $ccc = $f[3];            # Canonical_Combining_Class
127     my $dm = $f[5];             # Decomposition_Type + Decomposition_Mapping
128     my $sum = hex($f[12]) || $c; # Simple_Uppercase_Mapping
129     my $slm = hex($f[13]) || $c; # Simple_Lowercase_Mapping
130     # recalculate the upper/lower case mappings as offsets
131     my $ud = $sum - $c;
132     my $ld = $slm - $c;
133     # update bounds on various values
134     $maxccc = $ccc if $ccc > $maxccc; # assumed never to be -ve
135     $minud = $ud if $ud < $minud;
136     $maxud = $ud if $ud > $maxud;
137     $minld = $ld if $ld < $minld;
138     $maxld = $ld if $ld > $maxld;
139     if($start != $end) {
140         printf STDERR "> range %04X-%04X is %s\n", $start, $end, $gc;
141     }
142     for($c = $start; $c <= $end; ++$c) {
143         my $d = {
144             "gc" => $gc,
145             "ccc" => $ccc,
146             "ud" => $ud,
147             "ld" => $ld,
148         };
149         if($dm ne '') {
150             if($dm !~ /</) {
151                 # This is a canonical decomposition
152                 $d->{canon} = $dm;
153                 $d->{compat} = $dm;
154             } else {
155                 # This is only a compatibility decomposition
156                 $dm =~ s/^<.*>\s*//;
157                 $d->{compat} = $dm;
158             }
159         }
160         $data{$c} = $d;
161     }
162     $cats{$gc} = 1;
163     $max = $end if $end > $max;
164 }
165
166 sub read_prop_with_ranges {
167     my $path = shift;
168     my $propkey = shift;
169     input($path);
170     while(<>) {
171         chomp;
172         s/\s*\#.*//;
173         next if $_ eq '';
174         my ($range, $propval) = split(/\s*;\s*/, $_);
175         if($range =~ /(.*)\.\.(.*)/) {
176             for my $c (hex($1) .. hex($2)) {
177                 die "($range)\n" if($c == 0xAC00 and $propkey eq 'gbreak');
178                 $data{$c}->{$propkey} = $propval;
179             }
180         } else {
181             my $c = hex($range);
182             $data{$c}->{$propkey} = $propval;
183         }
184     }
185 }
186
187 # Grapheme_Break etc
188 read_prop_with_ranges("auxiliary/GraphemeBreakProperty.txt", "gbreak");
189 read_prop_with_ranges("auxiliary/WordBreakProperty.txt", "wbreak");
190 read_prop_with_ranges("auxiliary/SentenceBreakProperty.txt", "sbreak");
191
192 # Compute the full list and fill in the Extend category properly
193 my %gbreak = ();
194 my %wbreak = ();
195 my %sbreak = ();
196 for my $c (keys %data) {
197     if(!exists $data{$c}->{gbreak}) {
198         $data{$c}->{gbreak} = 'Other';
199     }
200     $gbreak{$data{$c}->{gbreak}} = 1;
201
202     if(!exists $data{$c}->{wbreak}) {
203         if($data{$c}->{gbreak} eq 'Extend') {
204             $data{$c}->{wbreak} = 'Extend';
205         } else {
206             $data{$c}->{wbreak} = 'Other';
207         }
208     }
209     $wbreak{$data{$c}->{wbreak}} = 1;
210
211     if(!exists $data{$c}->{sbreak}) {
212         if($data{$c}->{gbreak} eq 'Extend') {
213             $data{$c}->{sbreak} = 'Extend';
214         } else {
215             $data{$c}->{sbreak} = 'Other';
216         }
217     }
218     $sbreak{$data{$c}->{sbreak}} = 1;
219 }
220
221 # Round up the maximum value to a whole number of subtables
222 $max += ($modulus - 1) - ($max % $modulus);
223
224 # Private use characters
225 # We only fill in values below $max, utf32__unidata() 
226 my $Co = {
227     "gc" => "Co",
228     "ccc" => 0,
229     "ud" => 0,
230     "ld" => 0
231 };
232 for(my $c = 0xE000; $c <= 0xF8FF && $c <= $max; ++$c) {
233     $data{$c} = $Co;
234 }
235 for(my $c = 0xF0000; $c <= 0xFFFFD && $c <= $max; ++$c) {
236     $data{$c} = $Co;
237 }
238 for(my $c = 0x100000; $c <= 0x10FFFD && $c <= $max; ++$c) {
239     $data{$c} = $Co;
240 }
241
242 # Anything left is not assigned
243 my $Cn = {
244     "gc" => "Cn",               # not assigned
245     "ccc" => 0,
246     "ud" => 0,
247     "ld" => 0
248 };
249 for(my $c = 0; $c <= $max; ++$c) {
250     if(!exists $data{$c}) {
251         $data{$c} = $Cn;
252     }
253     if(!exists $data{$c}->{wbreak}) {
254         $data{$c}->{wbreak} = 'Other';
255     }
256     if(!exists $data{$c}->{gbreak}) {
257         $data{$c}->{gbreak} = 'Other';
258     }
259     if(!exists $data{$c}->{sbreak}) {
260         $data{$c}->{sbreak} = 'Other';
261     }
262 }
263 $cats{'Cn'} = 1;
264
265 # Read the casefolding data too
266 input("CaseFolding.txt");
267 while(<>) {
268     chomp;
269     next if /^\#/ or $_ eq '';
270     my @f = split(/\s*;\s*/, $_);
271     # Full case folding means use status C and F.
272     # We discard status T, Turkish users may wish to change this.
273     if($f[1] eq 'C' or $f[1] eq 'F') {
274         my $c = hex($f[0]);
275         $data{$c}->{casefold} = $f[2];
276         # We are particularly interest in combining characters that
277         # case-fold to non-combining characters, or characters that
278         # case-fold to sequences with combining characters in non-initial
279         # positions, as these required decomposiiton before case-folding
280         my @d = map(hex($_), split(/\s+/, $data{$c}->{casefold}));
281         if($data{$c}->{ccc} != 0) {
282             # This is a combining character
283             if($data{$d[0]}->{ccc} == 0) {
284                 # The first character of its case-folded form is NOT
285                 # a combining character.  The field name is the example
286                 # explicitly mentioned in the spec.
287                 $data{$c}->{ypogegrammeni} = 1;
288             }
289         } else {
290             # This is a non-combining character; inspect the non-initial
291             # code points of the case-folded sequence
292             shift(@d);
293             if(grep($data{$_}->{ccc} != 0, @d)) {
294                 # Some non-initial code point in the case-folded for is NOT a
295                 # a combining character.
296                 $data{$c}->{ypogegrammeni} = 1;
297             }
298         }
299     }
300 }
301
302 # Generate the header file
303 print STDERR "Generating unidata.h...\n";
304 open(STDOUT, ">unidata.h") or die "unidata.h: $!\n";
305
306 out("/* Automatically generated file, see scripts/make-unidata */\n",
307     "#ifndef UNIDATA_H\n",
308     "#define UNIDATA_H\n");
309
310 # TODO choose stable values for General_Category
311 out("enum unicode_General_Category {\n",
312     join(",\n",
313          map("  unicode_General_Category_$_", sort keys %cats)), "\n};\n");
314
315 out("enum unicode_Grapheme_Break {\n",
316     join(",\n",
317          map("  unicode_Grapheme_Break_$_", sort keys %gbreak)),
318     "\n};\n");
319 out("extern const char *const unicode_Grapheme_Break_names[];\n");
320
321 out("enum unicode_Word_Break {\n",
322     join(",\n",
323          map("  unicode_Word_Break_$_", sort keys %wbreak)),
324     "\n};\n");
325 out("extern const char *const unicode_Word_Break_names[];\n");
326
327 out("enum unicode_Sentence_Break {\n",
328     join(",\n",
329          map("  unicode_Sentence_Break_$_", sort keys %sbreak)),
330     "\n};\n");
331 out("extern const char *const unicode_Sentence_Break_names[];\n");
332
333 out("enum unicode_flags {\n",
334     "  unicode_normalize_before_casefold = 1\n",
335     "};\n",
336     "\n");
337
338 # Choose the narrowest type that will fit the required values
339 sub choosetype {
340     my ($min, $max) = @_;
341     if($min >= 0) {
342         return "char" if $max <= 127;
343         return "unsigned char" if $max <= 255;
344         return "int16_t" if $max < 32767;
345         return "uint16_t" if $max < 65535;
346         return "int32_t";
347     } else {
348         return "char" if $min >= -127 && $max <= 127;
349         return "int16_t" if $min >= -32767 && $max <= 32767;
350         return "int32_t";
351     }
352 }
353
354 out("struct unidata {\n",
355     "  const uint32_t *compat;\n",
356     "  const uint32_t *canon;\n",
357     "  const uint32_t *casefold;\n",
358 #    "  ".choosetype($minud, $maxud)." upper_offset;\n",
359 #    "  ".choosetype($minld, $maxld)." lower_offset;\n",
360     "  ".choosetype(0, $maxccc)." ccc;\n",
361     "  char general_category;\n",
362     "  uint8_t flags;\n",
363     "  char grapheme_break;\n",
364     "  char word_break;\n",
365     "  char sentence_break;\n",
366     "};\n");
367 # compat, canon and casefold do have have non-BMP characters, so we
368 # can't use a simple 16-bit table.  We could use UTF-8 or UTF-16
369 # though, saving a bit of space (probably not that much...) at the
370 # cost of marginally reduced performance and additional complexity
371
372 out("extern const struct unidata *const unidata[];\n");
373
374 out("extern const struct unicode_utf8_row {\n",
375     "  uint8_t count;\n",
376     "  uint8_t min2, max2;\n",
377     "} unicode_utf8_valid[];\n");
378
379 out("#define UNICODE_NCHARS ", ($max + 1), "\n");
380 out("#define UNICODE_MODULUS $modulus\n");
381 out("#define UNICODE_BREAK_START $break_start\n");
382 out("#define UNICODE_BREAK_END $break_end\n");
383 out("#define UNICODE_BREAK_TOP $break_top\n");
384
385 out("#endif\n");
386
387 close STDOUT or die "unidata.h: $!\n";
388
389 print STDERR "Generating unidata.c...\n";
390 open(STDOUT, ">unidata.c") or die "unidata.c: $!\n";
391
392 out("/* Automatically generated file, see scripts/make-unidata */\n",
393     "#include <config.h>\n",
394     "#include \"types.h\"\n",
395     "#include \"unidata.h\"\n");
396
397 # Short aliases to keep .c file small
398
399 out(map(sprintf("#define %s unicode_General_Category_%s\n", $_, $_),
400         sort keys %cats));
401 out(map(sprintf("#define GB%s unicode_Grapheme_Break_%s\n", $_, $_),
402         sort keys %gbreak));
403 out(map(sprintf("#define WB%s unicode_Word_Break_%s\n", $_, $_),
404         sort keys %wbreak));
405 out(map(sprintf("#define SB%s unicode_Sentence_Break_%s\n", $_, $_),
406         sort keys %sbreak));
407
408 # Names for *_Break properties
409 out("const char *const unicode_Grapheme_Break_names[] = {\n",
410     join(",\n",
411          map("  \"$_\"", sort keys %gbreak)),
412     "\n};\n");
413 out("const char *const unicode_Word_Break_names[] = {\n",
414     join(",\n",
415          map("  \"$_\"", sort keys %wbreak)),
416     "\n};\n");
417 out("const char *const unicode_Sentence_Break_names[] = {\n",
418     join(",\n",
419          map("  \"$_\"", sort keys %sbreak)),
420     "\n};\n");
421
422 # Generate the decomposition mapping tables.  We look out for duplicates
423 # in order to save space and report this as decompsaved at the end.  In
424 # Unicode 5.0.0 this saves 1795 entries, which is at least 14Kbytes.
425 my $decompnum = 0;
426 my %decompnums = ();
427 my $decompsaved = 0;
428 out("static const uint32_t ");
429 for(my $c = 0; $c <= $max; ++$c) {
430     # If canon is set then compat will be too and will be identical.
431     # If compat is set the canon might be clear.  So we use the
432     # compat version and fix up the symbols after.
433     if(exists $data{$c} && exists $data{$c}->{compat}) {
434         my $s = join(",",
435                      (map(hex($_), split(/\s+/, $data{$c}->{compat})), 0));
436         if(!exists $decompnums{$s}) {
437             out(",\n") if $decompnum != 0;
438             out("cd$decompnum\[]={$s}");
439             $decompnums{$s} = $decompnum++;
440         } else {
441             ++$decompsaved;
442         }
443         $data{$c}->{compatsym} = "cd$decompnums{$s}";
444         if(exists $data{$c}->{canon}) {
445             $data{$c}->{canonsym} = "cd$decompnums{$s}";
446         }
447     }
448 }
449 out(";\n");
450
451 # ...and the case folding table.  Again we compress equal entries to save
452 # space.  In Unicode 5.0.0 this saves 51 entries or at least 408 bytes.
453 # This doesns't seem as worthwhile as the decomposition mapping saving above.
454 my $cfnum = 0;
455 my %cfnums = ();
456 my $cfsaved = 0;
457 out("static const uint32_t ");
458 for(my $c = 0; $c <= $max; ++$c) {
459     if(exists $data{$c} && exists $data{$c}->{casefold}) {
460         my $s = join(",",
461                      (map(hex($_), split(/\s+/, $data{$c}->{casefold})), 0));
462         if(!exists $cfnums{$s}) {
463             out(",\n") if $cfnum != 0;
464             out("cf$cfnum\[]={$s}");
465             $cfnums{$s} = $cfnum++;
466         } else {
467             ++$cfsaved;
468         }
469         $data{$c}->{cfsym} = "cf$cfnums{$s}";
470     }
471 }
472 out(";\n");
473
474 # Visit all the $modulus-character blocks in turn and generate the
475 # required subtables.  As above we spot duplicates to save space.  In
476 # Unicode 5.0.0 with $modulus=128 and current table data this saves
477 # 1372 subtables or at least three and a half megabytes on 32-bit
478 # platforms.
479
480 my %subtable = ();              # base->subtable number
481 my %subtableno = ();            # subtable number -> content
482 my $subtablecounter = 0;        # counter for subtable numbers
483 my $subtablessaved = 0;         # number of tables saved
484 for(my $base = 0; $base <= $max; $base += $modulus) {
485     next if $base >= $break_start && $base < $break_end;
486     next if $base >= $break_top;
487     my @t;
488     for(my $c = $base; $c < $base + $modulus; ++$c) {
489         my $d = $data{$c};
490         my $canonsym = ($data{$c}->{canonsym} or "0");
491         my $compatsym = ($data{$c}->{compatsym} or "0");
492         my $cfsym = ($data{$c}->{cfsym} or "0");
493         my @flags = ();
494         if($data{$c}->{ypogegrammeni}) {
495             push(@flags, "unicode_normalize_before_casefold");
496         }
497         my $flags = @flags ? join("|", @flags) : 0;
498         push(@t, "{".
499              join(",",
500                   $compatsym,
501                   $canonsym,
502                   $cfsym,
503 #                 $d->{ud},
504 #                 $d->{ld},
505                   $d->{ccc},
506                   $d->{gc},
507                   $flags,
508                   "GB$d->{gbreak}",
509                   "WB$d->{wbreak}",
510                   "SB$d->{sbreak}",
511              )."}");
512     }
513     my $t = join(",\n", @t);
514     if(!exists $subtable{$t}) {
515         out(sprintf("/* %04X-%04X */\n", $base, $base + $modulus - 1));
516         out("static const struct unidata st$subtablecounter\[] = {\n",
517             "$t\n",
518             "};\n");
519         $subtable{$t} = $subtablecounter++;
520     } else {
521         ++$subtablessaved;
522     }
523     $subtableno{$base} = $subtable{$t};
524 }
525
526 out("const struct unidata *const unidata[]={\n");
527 for(my $base = 0; $base <= $max; $base += $modulus) {
528     next if $base >= $break_start && $base < $break_end;
529     next if $base >= $break_top;
530     #out("st$subtableno{$base} /* ".sprintf("%04x", $base)." */,\n");
531     out("st$subtableno{$base},\n");
532 }
533 out("};\n");
534
535 out("const struct unicode_utf8_row unicode_utf8_valid[] = {\n");
536 for(my $c = 0; $c <= 0x7F; ++$c) {
537     out(" { 1, 0, 0 }, /* $c */\n");
538 }
539 for(my $c = 0x80; $c < 0xC2; ++$c) {
540     out(" { 0, 0, 0 }, /* $c */\n");
541 }
542 for(my $c = 0xC2; $c <= 0xDF; ++$c) {
543     out(" { 2, 0x80, 0xBF }, /* $c */\n");
544 }
545 for(my $c = 0xE0; $c <= 0xE0; ++$c) {
546     out(" { 3, 0xA0, 0xBF }, /* $c */\n");
547 }
548 for(my $c = 0xE1; $c <= 0xEC; ++$c) {
549     out(" { 3, 0x80, 0xBF }, /* $c */\n");
550 }
551 for(my $c = 0xED; $c <= 0xED; ++$c) {
552     out(" { 3, 0x80, 0x9F }, /* $c */\n");
553 }
554 for(my $c = 0xEE; $c <= 0xEF; ++$c) {
555     out(" { 3, 0x80, 0xBF }, /* $c */\n");
556 }
557 for(my $c = 0xF0; $c <= 0xF0; ++$c) {
558     out(" { 4, 0x90, 0xBF }, /* $c */\n");
559 }
560 for(my $c = 0xF1; $c <= 0xF3; ++$c) {
561     out(" { 4, 0x80, 0xBF }, /* $c */\n");
562 }
563 for(my $c = 0xF4; $c <= 0xF4; ++$c) {
564     out(" { 4, 0x80, 0x8F }, /* $c */\n");
565 }
566 for(my $c = 0xF5; $c <= 0xFF; ++$c) {
567     out(" { 0, 0, 0 }, /* $c */\n");
568 }
569 out("};\n");
570
571 close STDOUT or die "unidata.c: $!\n";
572
573 printf STDERR "modulus=%d\n", $modulus;
574 printf STDERR "max=%04X\n", $max;
575 print STDERR "subtables=$subtablecounter, subtablessaved=$subtablessaved\n";
576 print STDERR "decompsaved=$decompsaved cfsaved=$cfsaved\n";