Patch from Andrew Taylor to improve tables and reduce relocations by using
[platform/upstream/glib.git] / glib / gen-unicode-tables.pl
1 #! /usr/bin/perl -w
2
3 #    Copyright (C) 1998, 1999 Tom Tromey
4 #    Copyright (C) 2001 Red Hat Software
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, or (at your option)
9 #    any later version.
10
11 #    This program is distributed in the hope that it will be useful,
12 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #    GNU 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
19 #    02111-1307, USA.
20
21 # Contributer(s):
22 #   Andrew Taylor <andrew.taylor@montage.ca>
23
24 # gen-unicode-tables.pl - Generate tables for libunicode from Unicode data.
25 # See http://www.unicode.org/Public/UNIDATA/UnicodeCharacterDatabase.html
26 # Usage: gen-unicode-tables.pl [-decomp | -both] UNICODE-VERSION UnicodeData.txt LineBreak.txt SpecialCasing.txt CaseFolding.txt
27 # I consider the output of this program to be unrestricted.  Use it as
28 # you will.
29
30 # FIXME:
31 # * For decomp table it might make sense to use a shift count other
32 #   than 8.  We could easily compute the perfect shift count.
33
34 use vars qw($CODE $NAME $CATEGORY $COMBINING_CLASSES $BIDI_CATEGORY $DECOMPOSITION $DECIMAL_VALUE $DIGIT_VALUE $NUMERIC_VALUE $MIRRORED $OLD_NAME $COMMENT $UPPER $LOWER $TITLE $BREAK_CODE $BREAK_CATEGORY $BREAK_NAME $CASE_CODE $CASE_LOWER $CASE_TITLE $CASE_UPPER $CASE_CONDITION);
35
36 # Names of fields in Unicode data table.
37 $CODE = 0;
38 $NAME = 1;
39 $CATEGORY = 2;
40 $COMBINING_CLASSES = 3;
41 $BIDI_CATEGORY = 4;
42 $DECOMPOSITION = 5;
43 $DECIMAL_VALUE = 6;
44 $DIGIT_VALUE = 7;
45 $NUMERIC_VALUE = 8;
46 $MIRRORED = 9;
47 $OLD_NAME = 10;
48 $COMMENT = 11;
49 $UPPER = 12;
50 $LOWER = 13;
51 $TITLE = 14;
52
53 # Names of fields in the line break table
54 $BREAK_CODE = 0;
55 $BREAK_PROPERTY = 1;
56
57 # Names of fields in the SpecialCasing table
58 $CASE_CODE = 0;
59 $CASE_LOWER = 1;
60 $CASE_TITLE = 2;
61 $CASE_UPPER = 3;
62 $CASE_CONDITION = 4;
63
64 # Names of fields in the CaseFolding table
65 $FOLDING_CODE = 0;
66 $FOLDING_STATUS = 1;
67 $FOLDING_MAPPING = 2;
68
69 # Map general category code onto symbolic name.
70 %mappings =
71     (
72      # Normative.
73      'Lu' => "G_UNICODE_UPPERCASE_LETTER",
74      'Ll' => "G_UNICODE_LOWERCASE_LETTER",
75      'Lt' => "G_UNICODE_TITLECASE_LETTER",
76      'Mn' => "G_UNICODE_NON_SPACING_MARK",
77      'Mc' => "G_UNICODE_COMBINING_MARK",
78      'Me' => "G_UNICODE_ENCLOSING_MARK",
79      'Nd' => "G_UNICODE_DECIMAL_NUMBER",
80      'Nl' => "G_UNICODE_LETTER_NUMBER",
81      'No' => "G_UNICODE_OTHER_NUMBER",
82      'Zs' => "G_UNICODE_SPACE_SEPARATOR",
83      'Zl' => "G_UNICODE_LINE_SEPARATOR",
84      'Zp' => "G_UNICODE_PARAGRAPH_SEPARATOR",
85      'Cc' => "G_UNICODE_CONTROL",
86      'Cf' => "G_UNICODE_FORMAT",
87      'Cs' => "G_UNICODE_SURROGATE",
88      'Co' => "G_UNICODE_PRIVATE_USE",
89      'Cn' => "G_UNICODE_UNASSIGNED",
90
91      # Informative.
92      'Lm' => "G_UNICODE_MODIFIER_LETTER",
93      'Lo' => "G_UNICODE_OTHER_LETTER",
94      'Pc' => "G_UNICODE_CONNECT_PUNCTUATION",
95      'Pd' => "G_UNICODE_DASH_PUNCTUATION",
96      'Ps' => "G_UNICODE_OPEN_PUNCTUATION",
97      'Pe' => "G_UNICODE_CLOSE_PUNCTUATION",
98      'Pi' => "G_UNICODE_INITIAL_PUNCTUATION",
99      'Pf' => "G_UNICODE_FINAL_PUNCTUATION",
100      'Po' => "G_UNICODE_OTHER_PUNCTUATION",
101      'Sm' => "G_UNICODE_MATH_SYMBOL",
102      'Sc' => "G_UNICODE_CURRENCY_SYMBOL",
103      'Sk' => "G_UNICODE_MODIFIER_SYMBOL",
104      'So' => "G_UNICODE_OTHER_SYMBOL"
105      );
106
107 %break_mappings =
108     (
109      'BK' => "G_UNICODE_BREAK_MANDATORY",
110      'CR' => "G_UNICODE_BREAK_CARRIAGE_RETURN",
111      'LF' => "G_UNICODE_BREAK_LINE_FEED",
112      'CM' => "G_UNICODE_BREAK_COMBINING_MARK",
113      'SG' => "G_UNICODE_BREAK_SURROGATE",
114      'ZW' => "G_UNICODE_BREAK_ZERO_WIDTH_SPACE",
115      'IN' => "G_UNICODE_BREAK_INSEPARABLE",
116      'GL' => "G_UNICODE_BREAK_NON_BREAKING_GLUE",
117      'CB' => "G_UNICODE_BREAK_CONTINGENT",
118      'SP' => "G_UNICODE_BREAK_SPACE",
119      'BA' => "G_UNICODE_BREAK_AFTER",
120      'BB' => "G_UNICODE_BREAK_BEFORE",
121      'B2' => "G_UNICODE_BREAK_BEFORE_AND_AFTER",
122      'HY' => "G_UNICODE_BREAK_HYPHEN",
123      'NS' => "G_UNICODE_BREAK_NON_STARTER",
124      'OP' => "G_UNICODE_BREAK_OPEN_PUNCTUATION",
125      'CL' => "G_UNICODE_BREAK_CLOSE_PUNCTUATION",
126      'QU' => "G_UNICODE_BREAK_QUOTATION",
127      'EX' => "G_UNICODE_BREAK_EXCLAMATION",
128      'ID' => "G_UNICODE_BREAK_IDEOGRAPHIC",
129      'NU' => "G_UNICODE_BREAK_NUMERIC",
130      'IS' => "G_UNICODE_BREAK_INFIX_SEPARATOR",
131      'SY' => "G_UNICODE_BREAK_SYMBOL",
132      'AL' => "G_UNICODE_BREAK_ALPHABETIC",
133      'PR' => "G_UNICODE_BREAK_PREFIX",
134      'PO' => "G_UNICODE_BREAK_POSTFIX",
135      'SA' => "G_UNICODE_BREAK_COMPLEX_CONTEXT",
136      'AI' => "G_UNICODE_BREAK_AMBIGUOUS",
137      'XX' => "G_UNICODE_BREAK_UNKNOWN"
138      );
139
140 # Title case mappings.
141 %title_to_lower = ();
142 %title_to_upper = ();
143
144 # Maximum length of special-case strings
145
146 my $special_case_len = 0;
147 my @special_cases;
148
149 $do_decomp = 0;
150 $do_props = 1;
151 if (@ARGV && $ARGV[0] eq '-decomp')
152 {
153     $do_decomp = 1;
154     $do_props = 0;
155     shift @ARGV;
156 }
157 elsif (@ARGV && $ARGV[0] eq '-both')
158 {
159     $do_decomp = 1;
160     shift @ARGV;
161 }
162
163 if (@ARGV != 6) {
164     $0 =~ s@.*/@@;
165     die "Usage: $0 [-decomp | -both] UNICODE-VERSION UnicodeData.txt LineBreak.txt SpecialCasing.txt CaseFolding.txt CompositionExclusions.txt\n";
166 }
167  
168 print "Creating decomp table\n" if ($do_decomp);
169 print "Creating property table\n" if ($do_props);
170
171 print "Composition exlusions from $ARGV[5]\n";
172
173 open (INPUT, "< $ARGV[5]") || exit 1;
174
175 while (<INPUT>) {
176
177     chop;
178
179     next if /^#/;
180     next if /^\s*$/;
181
182     s/\s*#.*//;
183
184     s/^\s*//;
185     s/\s*$//;
186
187     $composition_exclusions{hex($_)} = 1;
188 }
189
190 close INPUT;
191
192 print "Unicode data from $ARGV[1]\n";
193
194 open (INPUT, "< $ARGV[1]") || exit 1;
195
196 $last_code = -1;
197 while (<INPUT>)
198 {
199     chop;
200     @fields = split (';', $_, 30);
201     if ($#fields != 14)
202     {
203         printf STDERR ("Entry for $fields[$CODE] has wrong number of fields (%d)\n", $#fields);
204     }
205
206     $code = hex ($fields[$CODE]);
207
208     last if ($code > 0xFFFF); # ignore characters out of the basic plane
209
210     if ($code > $last_code + 1)
211     {
212         # Found a gap.
213         if ($fields[$NAME] =~ /Last>/)
214         {
215             # Fill the gap with the last character read,
216             # since this was a range specified in the char database
217             @gfields = @fields;
218         }
219         else
220         {
221             # The gap represents undefined characters.  Only the type
222             # matters.
223             @gfields = ('', '', 'Cn', '0', '', '', '', '', '', '', '',
224                         '', '', '', '');
225         }
226         for (++$last_code; $last_code < $code; ++$last_code)
227         {
228             $gfields{$CODE} = sprintf ("%04x", $last_code);
229             &process_one ($last_code, @gfields);
230         }
231     }
232     &process_one ($code, @fields);
233     $last_code = $code;
234 }
235
236 close INPUT;
237
238 @gfields = ('', '', 'Cn', '0', '', '', '', '', '', '', '',
239             '', '', '', '');
240 for (++$last_code; $last_code < 0x10000; ++$last_code)
241 {
242     $gfields{$CODE} = sprintf ("%04x", $last_code);
243     &process_one ($last_code, @gfields);
244 }
245 --$last_code;                   # Want last to be 0xFFFF.
246
247 print "Creating line break table\n";
248
249 print "Line break data from $ARGV[2]\n";
250
251 open (INPUT, "< $ARGV[2]") || exit 1;
252
253 $last_code = -1;
254 while (<INPUT>)
255 {
256     my ($start_code, $end_code);
257     
258     chop;
259
260     next if /^#/;
261
262     s/\s*#.*//;
263     
264     @fields = split (';', $_, 30);
265     if ($#fields != 1)
266     {
267         printf STDERR ("Entry for $fields[$CODE] has wrong number of fields (%d)\n", $#fields);
268         next;
269     }
270
271     if ($fields[$CODE] =~ /([A-F0-9]{4})..([A-F0-9]{4})/) 
272     {
273         $start_code = hex ($1);
274         $end_code = hex ($2);
275     } else {
276         $start_code = $end_code = hex ($fields[$CODE]);
277         
278     }
279
280     last if ($start_code > 0xFFFF); # FIXME ignore characters out of the basic plane 
281
282     if ($start_code > $last_code + 1)
283     {
284         # The gap represents undefined characters. If assigned,
285         # they are AL, if not assigned, XX
286         for (++$last_code; $last_code < $start_code; ++$last_code)
287         {
288             if ($type[$last_code] eq 'Cn')
289             {
290                 $break_props[$last_code] = 'XX';
291             }
292             else
293             {
294                 $break_props[$last_code] = 'AL';
295             }
296         }
297     }
298
299     for ($last_code = $start_code; $last_code <= $end_code; $last_code++)
300     {
301         $break_props[$last_code] = $fields[$BREAK_PROPERTY];
302     }
303     
304     $last_code = $end_code;
305 }
306
307 close INPUT;
308
309 for (++$last_code; $last_code < 0x10000; ++$last_code)
310 {
311   if ($type[$last_code] eq 'Cn')
312     {
313       $break_props[$last_code] = 'XX';
314     }
315   else
316     {
317       $break_props[$last_code] = 'AL';
318     }
319 }
320 --$last_code;                   # Want last to be 0xFFFF.
321
322 print STDERR "Last code is not 0xFFFF" if ($last_code != 0xFFFF);
323
324 print "Reading special-casing table for case conversion\n";
325
326 open (INPUT, "< $ARGV[3]") || exit 1;
327
328 while (<INPUT>)
329 {
330     my $code;
331     
332     chop;
333
334     next if /^#/;
335     next if /^\s*$/;
336
337     s/\s*#.*//;
338
339     @fields = split ('\s*;\s*', $_, 30);
340
341     $raw_code = $fields[$CASE_CODE];
342     $code = hex ($raw_code);
343
344     if ($#fields != 4 && $#fields != 5)
345     {
346         printf STDERR ("Entry for $raw_code has wrong number of fields (%d)\n", $#fields);
347         next;
348     }
349
350     if (!defined $type[$code])
351     {
352         printf STDERR "Special case for code point: $code, which has no defined type\n";
353         next;
354     }
355
356     if (defined $fields[5]) {
357         # Ignore conditional special cases - we'll handle them in code
358         next;
359     }
360     
361     if ($type[$code] eq 'Lu') 
362     {
363         (hex $fields[$CASE_UPPER] == $code) || die "$raw_code is Lu and UCD_Upper($raw_code) != $raw_code";
364
365         &add_special_case ($code, $value[$code],$fields[$CASE_LOWER], $fields[$CASE_TITLE]);
366         
367     } elsif ($type[$code] eq 'Lt') 
368     {
369         (hex $fields[$CASE_TITLE] == $code) || die "$raw_code is Lt and UCD_Title($raw_code) != $raw_code";
370         
371         &add_special_case ($code, undef,$fields[$CASE_LOWER], $fields[$CASE_UPPER]);
372     } elsif ($type[$code] eq 'Ll') 
373     {
374         (hex $fields[$CASE_LOWER] == $code) || die "$raw_code is Ll and UCD_Lower($raw_code) != $raw_code";
375         
376         &add_special_case ($code, $value[$code],$fields[$CASE_UPPER], $fields[$CASE_TITLE]);
377     } else {
378         printf STDERR "Special case for non-alphabetic code point: $raw_code\n";
379         next;
380     }
381 }
382
383 close INPUT;
384
385 open (INPUT, "< $ARGV[4]") || exit 1;
386
387 my $casefoldlen = 0;
388 my @casefold;
389  
390 while (<INPUT>)
391 {
392     my $code;
393     
394     chop;
395
396     next if /^#/;
397     next if /^\s*$/;
398
399     s/\s*#.*//;
400
401     @fields = split ('\s*;\s*', $_, 30);
402
403     $raw_code = $fields[$FOLDING_CODE];
404     $code = hex ($raw_code);
405
406     next if $code > 0xffff;     # FIXME!
407     
408     if ($#fields != 3)
409     {
410         printf STDERR ("Entry for $raw_code has wrong number of fields (%d)\n", $#fields);
411         next;
412     }
413
414     next if ($fields[$FOLDING_STATUS] eq 'S');
415
416     @values = map { hex ($_) } split /\s+/, $fields[$FOLDING_MAPPING];
417
418     # Check simple case
419
420     if (@values == 1 && 
421         !(defined $value[$code] && $value[$code] >= 0xd800 && $value[$code] < 0xdc00) &&
422         defined $type[$code]) {
423
424         my $lower;
425         if ($type[$code] eq 'Ll') 
426         {
427             $lower = $code;
428         } elsif ($type[$code] eq 'Lt') 
429         {
430             $lower = $title_to_lower{$code};
431         } elsif ($type[$code] eq 'Lu') 
432         {
433             $lower = $value[$code];
434         } else {
435             $lower = $code;
436         }
437         
438         if ($lower == $values[0]) {
439             next;
440         }
441     }
442
443     my $string = pack ("U*", @values);
444     if (1 + length $string > $casefoldlen) {
445         $casefoldlen = 1 + length $string;
446     }
447
448     push @casefold, [ $code, $string ];
449 }
450
451 close INPUT;
452
453 if ($do_props) {
454     &print_tables ($last_code)
455 }
456 if ($do_decomp) {
457     &print_decomp ($last_code);
458     &output_composition_table;
459 }
460
461 &print_line_break ($last_code);
462
463 exit 0;
464
465 # Process a single character.
466 sub process_one
467 {
468     my ($code, @fields) = @_;
469
470     $type[$code] = $fields[$CATEGORY];
471     if ($type[$code] eq 'Nd')
472     {
473         $value[$code] = int ($fields[$DECIMAL_VALUE]);
474     }
475     elsif ($type[$code] eq 'Ll')
476     {
477         $value[$code] = hex ($fields[$UPPER]);
478     }
479     elsif ($type[$code] eq 'Lu')
480     {
481         $value[$code] = hex ($fields[$LOWER]);
482     }
483
484     if ($type[$code] eq 'Lt')
485     {
486         $title_to_lower{$code} = hex ($fields[$LOWER]);
487         $title_to_upper{$code} = hex ($fields[$UPPER]);
488     }
489
490     $cclass[$code] = $fields[$COMBINING_CLASSES];
491
492     # Handle decompositions.
493     if ($fields[$DECOMPOSITION] ne '')
494     {
495         if ($fields[$DECOMPOSITION] =~ s/\<.*\>\s*//) {
496            $decompose_compat[$code] = 1;
497         } else {
498            $decompose_compat[$code] = 0;
499
500            if (!exists $composition_exclusions{$code}) {
501                $compositions{$code} = $fields[$DECOMPOSITION];
502            }
503         }
504         $decompositions[$code] = $fields[$DECOMPOSITION];
505     }
506 }
507
508 sub print_tables
509 {
510     my ($last) = @_;
511     my ($outfile) = "gunichartables.h";
512
513     local ($bytes_out) = 0;
514
515     print "Writing $outfile...\n";
516
517     open (OUT, "> $outfile");
518
519     print OUT "/* This file is automatically generated.  DO NOT EDIT!\n";
520     print OUT "   Instead, edit gen-unicode-tables.pl and re-run.  */\n\n";
521
522     print OUT "#ifndef CHARTABLES_H\n";
523     print OUT "#define CHARTABLES_H\n\n";
524
525     print OUT "#define G_UNICODE_DATA_VERSION \"$ARGV[0]\"\n\n";
526
527     printf OUT "#define G_UNICODE_LAST_CHAR 0x%04x\n\n", $last;
528
529     printf OUT "#define G_UNICODE_MAX_TABLE_INDEX 1000\n\n";
530
531     $table_index = 0;
532     printf OUT "static const char type_data[][256] = {\n";
533     for ($count = 0; $count <= $last; $count += 256)
534     {
535         $row[$count / 256] = &print_row ($count, 1, \&fetch_type);
536     }
537     printf OUT "\n};\n\n";
538
539     print OUT "static const short type_table[256] = {\n";
540     for ($count = 0; $count <= $last; $count += 256)
541     {
542         print OUT ",\n" if $count > 0;
543         print OUT "  ", $row[$count / 256];
544         $bytes_out += 2;
545     }
546     print OUT "\n};\n\n";
547
548
549     #
550     # Now print attribute table.
551     #
552
553     $table_index = 0;
554     printf OUT "static const unsigned short attr_data[][256] = {\n";
555     for ($count = 0; $count <= $last; $count += 256)
556     {
557         $row[$count / 256] = &print_row ($count, 2, \&fetch_attr);
558     }
559     printf OUT "\n};\n\n";
560
561     print OUT "static const short attr_table[256] = {\n";
562     for ($count = 0; $count <= $last; $count += 256)
563     {
564         print OUT ",\n" if $count > 0;
565         print OUT "  ", $row[$count / 256];
566         $bytes_out += 2;
567     }
568     print OUT "\n};\n\n";
569
570     #
571     # print title case table
572     #
573
574     # FIXME: type.
575     print OUT "static const unsigned short title_table[][3] = {\n";
576     my ($item);
577     my ($first) = 1;
578     foreach $item (sort keys %title_to_lower)
579     {
580         print OUT ",\n"
581             unless $first;
582         $first = 0;
583         printf OUT "  { 0x%04x, 0x%04x, 0x%04x }", $item, $title_to_upper{$item}, $title_to_lower{$item};
584         $bytes_out += 6;
585     }
586     print OUT "\n};\n\n";
587
588     #
589     # And special case conversion table -- conversions that change length
590     #
591     &output_special_case_table (\*OUT);
592     &output_casefold_table (\*OUT);
593
594     print OUT "#endif /* CHARTABLES_H */\n";
595
596     close (OUT);
597
598     printf STDERR "Generated %d bytes in tables\n", $bytes_out;
599 }
600
601 # A fetch function for the type table.
602 sub fetch_type
603 {
604     my ($index) = @_;
605     return $mappings{$type[$index]};
606 }
607
608 # A fetch function for the attribute table.
609 sub fetch_attr
610 {
611     my ($index) = @_;
612     if (defined $value[$index])
613       {
614         return sprintf ("0x%04x", $value[$index]);
615       }
616     else
617       {
618         return "0x0000";
619       }
620 }
621
622 sub print_row
623 {
624     my ($start, $typsize, $fetcher) = @_;
625
626     my ($i);
627     my (@values);
628     my ($flag) = 1;
629     my ($off);
630
631     for ($off = 0; $off < 256; ++$off)
632     {
633         $values[$off] = $fetcher->($off + $start);
634         if ($values[$off] ne $values[0])
635         {
636             $flag = 0;
637         }
638     }
639     if ($flag)
640     {
641         return $values[0] . " + G_UNICODE_MAX_TABLE_INDEX";
642     }
643
644     printf OUT ",\n" if ($table_index != 0);
645     printf OUT "  { /* page %d, index %d */\n    ", $start / 256, $table_index;
646     my ($column) = 4;
647     for ($i = $start; $i < $start + 256; ++$i)
648     {
649         print OUT ", "
650             if $i > $start;
651         my ($text) = $values[$i - $start];
652         if (length ($text) + $column + 2 > 78)
653         {
654             print OUT "\n    ";
655             $column = 4;
656         }
657         print OUT $text;
658         $column += length ($text) + 2;
659     }
660     print OUT "\n  }";
661
662     $bytes_out += 256 * $typsize;
663
664     return sprintf "%d /* page %d */", $table_index++, $start / 256;
665 }
666
667 # Generate the character decomposition header.
668 sub print_decomp
669 {
670     my ($last) = @_;
671     my ($outfile) = "gunidecomp.h";
672
673     local ($bytes_out) = 0;
674
675     print "Writing $outfile...\n";
676
677     open (OUT, "> $outfile") || exit 1;
678
679     print OUT "/* This file is automatically generated.  DO NOT EDIT! */\n\n";
680     print OUT "#ifndef DECOMP_H\n";
681     print OUT "#define DECOMP_H\n\n";
682
683     printf OUT "#define G_UNICODE_LAST_CHAR 0x%04x\n\n", $last;
684
685     printf OUT "#define G_UNICODE_MAX_TABLE_INDEX 1000\n\n";
686
687     my ($count, @row);
688     $table_index = 0;
689     printf OUT "static const unsigned char cclass_data[][256] = {\n";
690     for ($count = 0; $count <= $last; $count += 256)
691     {
692         $row[$count / 256] = &print_row ($count, 1, \&fetch_cclass);
693     }
694     printf OUT "\n};\n\n";
695
696     print OUT "static const short combining_class_table[256] = {\n";
697     for ($count = 0; $count <= $last; $count += 256)
698     {
699         print OUT ",\n" if $count > 0;
700         print OUT "  ", $row[$count / 256];
701         $bytes_out += 2;
702     }
703     print OUT "\n};\n\n";
704
705     print OUT "typedef struct\n{\n";
706     # FIXME: type.
707     print OUT "  unsigned short ch;\n";
708     print OUT "  unsigned char canon_offset;\n";
709     print OUT "  unsigned char compat_offset;\n";
710     print OUT "  unsigned char *expansion;\n";
711     print OUT "} decomposition;\n\n";
712
713     print OUT "static const decomposition decomp_table[] =\n{\n";
714     my ($iter);
715     my ($first) = 1;
716     for ($count = 0; $count <= $last; ++$count)
717     {
718         if (defined $decompositions[$count])
719         {
720             print OUT ",\n"
721                 if ! $first;
722             $first = 0;
723
724             my $canon_decomp;
725             my $compat_decomp;
726
727             if (!$decompose_compat[$count]) {
728                 $canon_decomp = make_decomp ($count, 0);
729             }
730             $compat_decomp = make_decomp ($count, 1);
731
732             if (defined $canon_decomp && $compat_decomp eq $canon_decomp) {
733                 undef $compat_decomp; 
734             }
735
736             my $string = "";
737             my $canon_offset = 0xff;
738             my $compat_offset = 0xff;
739             
740             if (defined $canon_decomp) {
741                 $canon_offset = 0;
742                 $string .= $canon_decomp;
743             }
744             if (defined $compat_decomp) {
745                 if (defined $canon_decomp) {
746                     $string .= "\\x00\\x00";
747                 }
748                 $compat_offset = (length $string) / 4;
749                 $string .= $compat_decomp;
750             }
751
752             $bytes_out += (length $string) / 4; # "\x20"
753             
754             # Only a single terminator because one is implied in the string.
755             printf OUT qq(  { 0x%04x, %u, %u, "%s\\0" }), 
756                 $count, $canon_offset, $compat_offset, $string;
757                 
758             
759             $bytes_out += 6;
760         }
761     }
762     print OUT "\n};\n\n";
763
764     print OUT "#endif /* DECOMP_H */\n";
765
766     printf STDERR "Generated %d bytes in decomp tables\n", $bytes_out;
767 }
768
769 sub print_line_break
770 {
771     my ($last) = @_;
772     my ($outfile) = "gunibreak.h";
773
774     local ($bytes_out) = 0;
775
776     print "Writing $outfile...\n";
777
778     open (OUT, "> $outfile");
779
780     print OUT "/* This file is automatically generated.  DO NOT EDIT!\n";
781     print OUT "   Instead, edit gen-unicode-tables.pl and re-run.  */\n\n";
782
783     print OUT "#ifndef BREAKTABLES_H\n";
784     print OUT "#define BREAKTABLES_H\n\n";
785
786     print OUT "#define G_UNICODE_DATA_VERSION \"$ARGV[0]\"\n\n";
787
788     printf OUT "#define G_UNICODE_LAST_CHAR 0x%04x\n\n", $last;
789
790     printf OUT "#define G_UNICODE_MAX_TABLE_INDEX 1000\n\n";
791
792     $table_index = 0;
793     printf OUT "static const char break_property_data[][256] = {\n";
794     for ($count = 0; $count <= $last; $count += 256)
795     {
796         $row[$count / 256] = &print_row ($count, 1, \&fetch_break_type);
797     }
798     printf OUT "\n};\n\n";
799
800     print OUT "static const short break_property_table[256] = {\n";
801     for ($count = 0; $count <= $last; $count += 256)
802     {
803         print OUT ",\n" if $count > 0;
804         print OUT "  ", $row[$count / 256];
805         $bytes_out += 2;
806     }
807     print OUT "\n};\n\n";
808
809     print OUT "#endif /* BREAKTABLES_H */\n";
810
811     close (OUT);
812
813     printf STDERR "Generated %d bytes in break tables\n", $bytes_out;
814 }
815
816
817 # A fetch function for the break properties table.
818 sub fetch_break_type
819 {
820     my ($index) = @_;
821     return $break_mappings{$break_props[$index]};
822 }
823
824 # Fetcher for combining class.
825 sub fetch_cclass
826 {
827     my ($i) = @_;
828     return $cclass[$i];
829 }
830
831 # Expand a character decomposition recursively.
832 sub expand_decomp
833 {
834     my ($code, $compat) = @_;
835
836     my ($iter, $val);
837     my (@result) = ();
838     foreach $iter (split (' ', $decompositions[$code]))
839     {
840         $val = hex ($iter);
841         if (defined $decompositions[$val] && 
842             ($compat || !$decompose_compat[$val]))
843         {
844             push (@result, &expand_decomp ($val, $compat));
845         }
846         else
847         {
848             push (@result, $val);
849         }
850     }
851
852     return @result;
853 }
854
855 sub make_decomp
856 {
857     my ($code, $compat) = @_;
858
859     my $result = "";
860     foreach $iter (&expand_decomp ($code, $compat))
861     {
862         $result .= sprintf "\\x%02x\\x%02x", $iter / 256, $iter & 0xff;
863     }
864
865     $result;
866 }
867 # Generate special case data string from two fields
868 sub add_special_case
869 {
870     my ($code, $single, $field1, $field2) = @_;
871
872     @values = (defined $single ? $single : (),
873                (map { hex ($_) } split /\s+/, $field1),
874                0,
875                (map { hex ($_) } split /\s+/, $field2));
876     $result = "";
877
878
879     for $value (@values) {
880         $result .= sprintf ("\\x%02x\\x%02x", $value / 256, $value & 0xff);
881     }
882
883     $result .= "\\0";
884     
885     if (2 * @values + 2 > $special_case_len) {
886         $special_case_len = 2 * @values + 2;
887     }
888
889     push @special_cases, $result;
890
891     #
892     # We encode special cases in the surrogate pair space
893     #
894     $value[$code] = 0xD800 + scalar(@special_cases) - 1;
895 }
896
897 sub output_special_case_table
898 {
899     my $out = shift;
900
901     print $out <<EOT;
902
903 /* Table of special cases for case conversion; each record contains
904  * First, the best single character mapping to lowercase if Lu, 
905  * and to uppercase if Ll, followed by the output mapping for the two cases 
906  * other than the case of the codepoint, in the order [Ll],[Lu],[Lt],
907  * separated and terminated by a double NUL.
908  */
909 static const guchar special_case_table[][$special_case_len] = {
910 EOT
911
912     for $case (@special_cases) {
913         print $out qq( "$case",\n);
914     }
915
916     print $out <<EOT;
917 };
918
919 EOT
920
921     print STDERR "Generated ", ($special_case_len * scalar @special_cases), " bytes in special case table\n";
922 }
923
924 sub enumerate_ordered
925 {
926     my ($array) = @_;
927
928     my $n = 0;
929     for my $code (sort { $a <=> $b } keys %$array) {
930         if ($array->{$code} == 1) {
931             delete $array->{$code};
932             next;
933         }
934         $array->{$code} = $n++;
935     }
936
937     return $n;
938 }
939
940 sub output_composition_table
941 {
942     print STDERR "Generating composition table\n";
943     
944     local ($bytes_out) = 0;
945
946     my %first;
947     my %second;
948
949     # First we need to go through and remove decompositions
950     # starting with a non-starter, and single-character 
951     # decompositions. At the same time, record
952     # the first and second character of each decomposition
953     
954     for $code (keys %compositions) {
955         @values = map { hex ($_) } split /\s+/, $compositions{$code};
956         if ($cclass[$values[0]]) {
957             delete $compositions{$code};
958             next;
959         }
960         if (@values == 1) {
961             delete $compositions{$code};
962             next;
963         }
964         if (@values != 2) {
965             die "$code has more than two elements in its decomposition!\n";
966         }
967
968         if (exists $first{$values[0]}) {
969             $first{$values[0]}++;
970         } else {
971             $first{$values[0]} = 1;
972         }
973     }
974
975     # Assign integer indicices, removing singletons
976     my $n_first = enumerate_ordered (\%first);
977
978     # Now record the second character if each (non-singleton) decomposition
979     for $code (keys %compositions) {
980         @values = map { hex ($_) } split /\s+/, $compositions{$code};
981
982         if (exists $first{$values[0]}) {
983             if (exists $second{$values[1]}) {
984                 $second{$values[1]}++;
985             } else {
986                 $second{$values[1]} = 1;
987             }
988         }
989     }
990
991     # Assign integer indices, removing duplicate
992     my $n_second = enumerate_ordered (\%second);
993
994     # Build reverse table
995
996     my @first_singletons;
997     my @second_singletons;
998     my %reverse;
999     for $code (keys %compositions) {
1000         @values = map { hex ($_) } split /\s+/, $compositions{$code};
1001
1002         my $first = $first{$values[0]};
1003         my $second = $second{$values[1]};
1004
1005         if (defined $first && defined $second) {
1006             $reverse{"$first|$second"} = $code;
1007         } elsif (!defined $first) {
1008             push @first_singletons, [ $values[0], $values[1], $code ];
1009         } else {
1010             push @second_singletons, [ $values[1], $values[0], $code ];
1011         }
1012     }
1013
1014     @first_singletons = sort { $a->[0] <=> $b->[0] } @first_singletons;
1015     @second_singletons = sort { $a->[0] <=> $b->[0] } @second_singletons;
1016
1017     my %vals;
1018     
1019     open OUT, ">gunicomp.h" or die "Cannot open gunicomp.h: $!\n";
1020     
1021     # Assign values in lookup table for all code points involved
1022     
1023     my $total = 1;
1024     my $last = 0;
1025     printf OUT "#define COMPOSE_FIRST_START %d\n", $total;
1026     for $code (keys %first) {
1027         $vals{$code} = $first{$code} + $total;
1028         $last = $code if $code > $last;
1029     }
1030     $total += $n_first;
1031     $i = 0;
1032     printf OUT "#define COMPOSE_FIRST_SINGLE_START %d\n", $total;
1033     for $record (@first_singletons) {
1034         my $code = $record->[0];
1035         $vals{$code} = $i++ + $total;
1036         $last = $code if $code > $last;
1037     }
1038     $total += @first_singletons;
1039     printf OUT "#define COMPOSE_SECOND_START %d\n", $total;
1040     for $code (keys %second) {
1041         $vals{$code} = $second{$code} + $total;
1042         $last = $code if $code > $last;
1043     }
1044     $total += $n_second;
1045     $i = 0;
1046     printf OUT "#define COMPOSE_SECOND_SINGLE_START %d\n\n", $total;
1047     for $record (@second_singletons) {
1048         my $code = $record->[0];
1049         $vals{$code} = $i++ + $total;
1050         $last = $code if $code > $last;
1051     }
1052
1053     # Output lookup table
1054
1055     my @row;                                              
1056     $table_index = 0;
1057     printf OUT "static const gushort compose_data[][256] = {\n";
1058     for (my $count = 0; $count <= $last; $count += 256)
1059     {
1060         $row[$count / 256] = &print_row ($count, 2, sub { exists $vals{$_[0]} ? $vals{$_[0]} : 0; });
1061     }
1062     printf OUT "\n};\n\n";
1063
1064     print OUT "static const short compose_table[256] = {\n";
1065     for (my $count = 0; $count <= $last; $count += 256)
1066     {
1067         print OUT ",\n" if $count > 0;
1068         print OUT "  ", $row[$count / 256];
1069         $bytes_out += 4;
1070     }
1071     print OUT "\n};\n\n";
1072
1073     # Output first singletons
1074
1075     print OUT "static const gushort compose_first_single[][2] = {\n";
1076     $i = 0;                                  
1077     for $record (@first_singletons) {
1078         print OUT ",\n" if $i++ > 0;
1079         printf OUT " { %#06x, %#06x }", $record->[1], $record->[2];
1080     }
1081     print OUT "\n};\n";
1082                                      
1083     $bytes_out += @first_singletons * 4;                                     
1084                   
1085     # Output second singletons
1086
1087     print OUT "static const gushort compose_second_single[][2] = {\n";
1088     $i = 0;                                  
1089     for $record (@second_singletons) {
1090         print OUT ",\n" if $i++ > 0;
1091         printf OUT " { %#06x, %#06x }", $record->[1], $record->[2];
1092     }
1093     print OUT "\n};\n";
1094                                      
1095     $bytes_out += @second_singletons * 4;                                    
1096                   
1097     # Output array of composition pairs
1098
1099     print OUT <<EOT;
1100 static const gushort compose_array[$n_first][$n_second] = {
1101 EOT
1102                         
1103     for (my $i = 0; $i < $n_first; $i++) {
1104         print OUT ",\n" if $i;
1105         print OUT " { ";
1106         for (my $j = 0; $j < $n_second; $j++) {
1107             print OUT ", " if $j;
1108             if (exists $reverse{"$i|$j"}) {
1109                 printf OUT "%#06x", $reverse{"$i|$j"};
1110             } else {
1111                 print OUT "     0";
1112             }
1113         }
1114         print OUT " }";
1115     }
1116     print OUT "\n";
1117
1118     print OUT <<EOT;
1119 };
1120 EOT
1121
1122     $bytes_out += $n_first * $n_second * 2;
1123     
1124     printf STDERR "Generated %d bytes in compose tables\n", $bytes_out;
1125 }
1126
1127 sub output_casefold_table
1128 {
1129     my $out = shift;
1130
1131     print $out <<EOT;
1132
1133 /* Table of casefolding cases that can't be derived by lowercasing
1134  */
1135 static const struct {
1136   guint16 ch;
1137   gchar data[$casefoldlen];
1138 } casefold_table[] = {
1139 EOT
1140
1141    @casefold = sort { $a->[0] <=> $b->[0] } @casefold; 
1142     
1143    for $case (@casefold) {
1144        $code = $case->[0];
1145        $string = $case->[1];
1146        print $out sprintf(qq({ %#04x, "$string" },\n), $code);
1147     
1148    }
1149
1150     print $out <<EOT;
1151 };
1152
1153 EOT
1154
1155    my $recordlen = (2+$casefoldlen+1) & ~1;
1156    printf "Generated %d bytes for casefold table\n", $recordlen * @casefold;
1157 }
1158
1159                              
1160