Debian Codegraph @

lib/nfkc.rb

raw symbols SCIP
1 #!/usr/bin/env ruby
2 #
3 # Copyright (C) 2010-2018 Brazil
4 # Copyright (C) 2019-2024 Sutou Kouhei <[email protected]>
5 #
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License, or (at your option) any later version.
10 #
11 # This library 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 GNU
14 # Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
20 require "English"
21
22 CUSTOM_RULE_PATH = 'nfkc-custom-rules.txt'
23
24 class SwitchGenerator
25 def initialize(unicode_version, output)
26 @unicode_version = unicode_version
27 @output = output
28 end
29
30 def generate(bc, decompose_map, compose_map)
31 STDERR.puts('generating char type code..')
32 generate_blockcode_char_type(bc)
33 STDERR.puts('generating decompose code..')
34 generate_decompose(decompose_map)
35 STDERR.puts('generating compose code..')
36 generate_compose(compose_map)
37 end
38
39 private
40 def generate_blockcode_char_type(bc)
41 @output.puts(<<-HEADER)
42
43 grn_char_type
44 grn_nfkc#{@unicode_version}_char_type(const unsigned char *str)
45 {
46 HEADER
47
48 @lv = 0
49 gen_bc(bc, 0)
50
51 @output.puts(<<-FOOTER)
52 return -1;
53 }
54 FOOTER
55 end
56
57 def gen_bc(hash, level)
58 bl = ' ' * (level * 2)
59 h2 = {}
60 hash.each{|key,val|
61 key = key.dup
62 key.force_encoding("ASCII-8BIT")
63 head = key.bytes[0]
64 rest = key[1..-1]
65 if h2[head]
66 h2[head][rest] = val
67 else
68 h2[head] = {rest => val}
69 end
70 }
71 if h2.size < 3
72 h2.keys.sort.each{|k|
73 if (0x80 < k)
74 @output.printf("#{bl}if (str[#{level}] < 0x%02X) { return #{@lv}; }\n", k)
75 end
76 h = h2[k]
77 if h.keys.join =~ /^\x80*$/n
78 @lv, = h.values
79 else
80 @output.printf("#{bl}if (str[#{level}] == 0x%02X) {\n", k)
81 gen_bc(h, level + 1)
82 @output.puts bl + '}'
83 end
84 }
85 @output.puts bl + "return #{@lv};"
86 else
87 @output.puts bl + "switch (str[#{level}]) {"
88 lk = 0x80
89 br = true
90 h2.keys.sort.each{|k|
91 if (lk < k)
92 for j in lk..k-1
93 @output.printf("#{bl}case 0x%02X :\n", j)
94 end
95 br = false
96 end
97 unless br
98 @output.puts bl + " return #{@lv};"
99 @output.puts bl + ' break;'
100 end
101 h = h2[k]
102 @output.printf("#{bl}case 0x%02X :\n", k)
103 if h.keys.join =~ /^\x80*$/n
104 @lv, = h.values
105 br = false
106 else
107 gen_bc(h, level + 1)
108 @output.puts bl + ' break;'
109 br = true
110 end
111 lk = k + 1
112 }
113 @output.puts bl + 'default :'
114 @output.puts bl + " return #{@lv};"
115 @output.puts bl + ' break;'
116 @output.puts bl + '}'
117 end
118 end
119
120 def generate_decompose(hash)
121 @output.puts(<<-HEADER)
122
123 const char *
124 grn_nfkc#{@unicode_version}_decompose(const unsigned char *str)
125 {
126 HEADER
127
128 gen_decompose(hash, 0)
129
130 @output.puts(<<-FOOTER)
131 return 0;
132 }
133 FOOTER
134 end
135
136 def gen_decompose(hash, level)
137 bl = ' ' * ((level + 0) * 2)
138 if hash['']
139 dst = ''
140 hash[''].each_byte{|b| dst << format('\x%02X', b)}
141 @output.puts "#{bl}return \"#{dst}\";"
142 hash.delete('')
143 end
144 return if hash.empty?
145 h2 = {}
146 hash.each{|key,val|
147 key = key.dup
148 key.force_encoding("ASCII-8BIT")
149 head = key.bytes[0]
150 rest = key[1..-1]
151 if h2[head]
152 h2[head][rest] = val
153 else
154 h2[head] = {rest => val}
155 end
156 }
157 if h2.size == 1
158 h2.each{|key,val|
159 @output.printf("#{bl}if (str[#{level}] == 0x%02X) {\n", key)
160 gen_decompose(val, level + 1)
161 @output.puts bl + '}'
162 }
163 else
164 @output.puts "#{bl}switch (str[#{level}]) {"
165 h2.keys.sort.each{|k|
166 @output.printf("#{bl}case 0x%02X :\n", k)
167 gen_decompose(h2[k], level + 1)
168 @output.puts("#{bl} break;")
169 }
170 @output.puts bl + '}'
171 end
172 end
173
174 def generate_compose(compose_map)
175 @output.puts(<<-HEADER)
176
177 const char *
178 grn_nfkc#{@unicode_version}_compose(const unsigned char *prefix, const unsigned char *suffix)
179 {
180 HEADER
181 suffix = {}
182 compose_map.each{|src,dst|
183 chars = src.chars
184 if chars.size != 2
185 STDERR.puts "caution: more than two chars in pattern #{chars.join('|')}"
186 end
187 s = chars.pop
188 if suffix[s]
189 suffix[s][chars.join] = dst
190 else
191 suffix[s] = {chars.join=>dst}
192 end
193 }
194 gen_compose_sub(suffix, 0)
195 @output.puts(<<-FOOTER)
196 return 0;
197 }
198 FOOTER
199 end
200
201 def gen_compose_sub2(hash, level, indent)
202 bl = ' ' * ((level + indent + 0) * 2)
203 if hash['']
204 @output.print "#{bl}return \""
205 hash[''].each_byte{|b| @output.printf('\x%02X', b)}
206 @output.puts "\";"
207 hash.delete('')
208 end
209 return if hash.empty?
210
211 h2 = {}
212 hash.each{|key,val|
213 key = key.dup
214 key.force_encoding("ASCII-8BIT")
215 head = key.bytes[0]
216 rest = key[1..-1]
217 if h2[head]
218 h2[head][rest] = val
219 else
220 h2[head] = {rest => val}
221 end
222 }
223
224 if h2.size == 1
225 h2.each{|key,val|
226 @output.printf("#{bl}if (prefix[#{level}] == 0x%02X) {\n", key)
227 gen_compose_sub2(val, level + 1, indent)
228 @output.puts bl + '}'
229 }
230 else
231 @output.puts "#{bl}switch (prefix[#{level}]) {"
232 h2.keys.sort.each{|k|
233 @output.printf("#{bl}case 0x%02X :\n", k)
234 gen_compose_sub2(h2[k], level + 1, indent)
235 @output.puts("#{bl} break;")
236 }
237 @output.puts bl + '}'
238 end
239 end
240
241 def gen_compose_sub(hash, level)
242 bl = ' ' * ((level + 0) * 2)
243 if hash['']
244 gen_compose_sub2(hash[''], 0, level)
245 hash.delete('')
246 end
247 return if hash.empty?
248 h2 = {}
249 hash.each{|key,val|
250 key = key.dup
251 key.force_encoding("ASCII-8BIT")
252 head = key.bytes[0]
253 rest = key[1..-1]
254 if h2[head]
255 h2[head][rest] = val
256 else
257 h2[head] = {rest => val}
258 end
259 }
260 if h2.size == 1
261 h2.each{|key,val|
262 @output.printf("#{bl}if (suffix[#{level}] == 0x%02X) {\n", key)
263 gen_compose_sub(val, level + 1)
264 @output.puts bl + '}'
265 }
266 else
267 @output.puts "#{bl}switch (suffix[#{level}]) {"
268 h2.keys.sort.each{|k|
269 @output.printf("#{bl}case 0x%02X :\n", k)
270 gen_compose_sub(h2[k], level + 1)
271 @output.puts("#{bl} break;")
272 }
273 @output.puts bl + '}'
274 end
275 end
276 end
277
278 class TableGenerator < SwitchGenerator
279 private
280 def name_prefix
281 "grn_nfkc#{@unicode_version}_"
282 end
283
284 def table_name(type, common_bytes)
285 suffix = common_bytes.collect {|byte| "%02x" % byte}.join("")
286 "#{name_prefix}#{type}_table_#{suffix}"
287 end
288
289 def function_name(type)
290 "#{name_prefix}#{type}"
291 end
292
293 def generate_char_convert_tables(type, return_type, byte_size_groups)
294 if return_type.end_with?("*")
295 space = ""
296 else
297 space = " "
298 end
299 byte_size_groups.keys.sort.each do |common_bytes|
300 chars = byte_size_groups[common_bytes]
301 lines = []
302 all_values = []
303 last_bytes = chars.collect {|char| char.bytes.last}
304 last_bytes.min.step(last_bytes.max).each_slice(8) do |slice|
305 values = slice.collect do |last_byte|
306 char = (common_bytes + [last_byte]).pack("c*")
307 char.force_encoding("UTF-8")
308 yield(char)
309 end
310 all_values.concat(values)
311 lines << (" " + values.join(", "))
312 end
313
314 next if all_values.uniq.size == 1
315
316 @output.puts(<<-TABLE_HEADER)
317
318 static #{return_type}#{space}#{table_name(type, common_bytes)}[] = {
319 TABLE_HEADER
320 @output.puts(lines.join(",\n"))
321 @output.puts(<<-TABLE_FOOTER)
322 };
323 TABLE_FOOTER
324 end
325 end
326
327 def generate_char_convert_function(type,
328 argument_list,
329 char_variable,
330 default,
331 return_type,
332 byte_size_groups,
333 options={})
334 modifier = options[:internal] ? "static inline " : ""
335 @output.puts(<<-HEADER)
336
337 #{modifier}#{return_type}
338 #{function_name(type)}(#{argument_list})
339 {
340 HEADER
341
342 prev_common_bytes = []
343 switch_depth = 0
344 first_group = true
345 byte_size_groups.keys.sort.each do |common_bytes|
346 chars = byte_size_groups[common_bytes]
347 chars_bytes = chars.collect(&:bytes).sort
348 min = chars_bytes.first.last
349 max = chars_bytes.last.last
350 if common_bytes.empty?
351 indent = " "
352 yield(:no_common_bytes, indent, chars, chars_bytes)
353 else
354 if first_group
355 @output.puts(<<-BODY)
356 {
357 BODY
358 end
359
360 found_different_byte = false
361 common_bytes.each_with_index do |common_byte, i|
362 unless found_different_byte
363 if prev_common_bytes[i] == common_byte
364 next
365 end
366 found_different_byte = true
367 end
368 indent = " " * i
369 # p [type, i, prev_common_bytes.collect{|x| "%#04x" % x}, common_bytes.collect{|x| "%#04x" % x}, "%#04x" % common_byte, switch_depth]
370 # TODO: The following code may be able to be simplified.
371 if prev_common_bytes[i].nil?
372 # p nil
373 switch_depth += 1
374 @output.puts(<<-BODY)
375 #{indent}switch (#{char_variable}[#{i}]) {
376 BODY
377 elsif i < switch_depth - 1
378 # p :prev
379 switch_depth -= 1
380 @output.puts(<<-BODY)
381 #{indent} default :
382 #{indent} break;
383 #{indent} }
384 #{indent} break;
385 BODY
386 elsif i == switch_depth
387 # p :common_prev
388 switch_depth += 1
389 @output.puts(<<-BODY)
390 #{indent}switch (#{char_variable}[#{i}]) {
391 BODY
392 else
393 # p [:else, prev_common_bytes.size, common_bytes.size + 1, switch_depth]
394 prev_common_bytes.size.downto(common_bytes.size + 1) do |j|
395 sub_indent = " " * (j - 1)
396 switch_depth -= 1
397 @output.puts(<<-BODY)
398 #{indent}#{sub_indent}default :
399 #{indent}#{sub_indent} break;
400 #{indent}#{sub_indent}}
401 #{indent}#{sub_indent}break;
402 BODY
403 end
404 end
405 @output.puts(<<-BODY)
406 #{indent}case #{"%#04x" % common_byte} :
407 BODY
408 end
409
410 n = chars_bytes.first.size - 1
411 indent = " " + (" " * common_bytes.size)
412 yield(:have_common_bytes, indent, chars, chars_bytes, n, common_bytes)
413 end
414
415 prev_common_bytes = common_bytes
416 first_group = false
417 end
418
419 # p [prev_common_bytes.collect{|x| "%#04x" % x}]
420
421 (prev_common_bytes.size - 1).step(0, -1) do |i|
422 indent = " " * i
423 @output.puts(<<-BODY)
424 #{indent}default :
425 #{indent} break;
426 #{indent}}
427 BODY
428 if i > 0
429 @output.puts(<<-BODY)
430 #{indent}break;
431 BODY
432 end
433 end
434
435 @output.puts(<<-FOOTER)
436 }
437
438 return #{default};
439 }
440 FOOTER
441 end
442
443 def generate_char_converter(type,
444 function_type,
445 char_map,
446 default,
447 return_type,
448 options={},
449 &converter)
450 byte_size_groups = char_map.keys.group_by do |from|
451 bytes = from.bytes
452 bytes[0..-2]
453 end
454
455 generate_char_convert_tables(type,
456 return_type,
457 byte_size_groups,
458 &converter)
459
460 char_variable = "utf8"
461 generate_char_convert_function(function_type,
462 "const unsigned char *#{char_variable}",
463 char_variable,
464 default,
465 return_type,
466 byte_size_groups,
467 options) do |state, *args|
468 case state
469 when :no_common_bytes
470 indent, chars, chars_bytes = args
471 if chars.size == 1
472 char = chars[0]
473 char_byte = chars_bytes.first.first
474 value = yield(char)
475 @output.puts(<<-BODY)
476 #{indent}if (#{char_variable}[0] < 0x80) {
477 #{indent} if (#{char_variable}[0] == #{"%#04x" % char_byte}) {
478 #{indent} return #{value};
479 #{indent} } else {
480 #{indent} return #{default};
481 #{indent} }
482 #{indent}} else {
483 BODY
484 else
485 min = chars_bytes.first.first
486 max = chars_bytes.last.first
487 @output.puts(<<-BODY)
488 #{indent}if (#{char_variable}[0] < 0x80) {
489 #{indent} if (#{char_variable}[0] >= #{"%#04x" % min} &&
490 #{indent} #{char_variable}[0] <= #{"%#04x" % max}) {
491 #{indent} return #{table_name(type, [])}[#{char_variable}[0] - #{"%#04x" % min}];
492 #{indent} } else {
493 #{indent} return #{default};
494 #{indent} }
495 #{indent}} else {
496 BODY
497 end
498 when :have_common_bytes
499 indent, chars, chars_bytes, n, common_bytes = args
500 if chars.size == 1
501 char = chars[0]
502 char_byte = chars_bytes.first.last
503 value = yield(char)
504 @output.puts(<<-BODY)
505 #{indent}if (#{char_variable}[#{n}] == #{"%#04x" % char_byte}) {
506 #{indent} return #{value};
507 #{indent}}
508 #{indent}break;
509 BODY
510 else
511 sorted_chars = chars.sort
512 min = chars_bytes.first.last
513 max = chars_bytes.last.last
514 all_values = (min..max).collect do |last_byte|
515 char = (common_bytes + [last_byte]).pack("c*")
516 char.force_encoding("UTF-8")
517 yield(char)
518 end
519 if all_values.uniq.size == 1
520 value = all_values.first
521 else
522 value = "#{table_name(type, common_bytes)}[#{char_variable}[#{n}] - #{"%#04x" % min}]"
523 end
524 last_n_bits_for_char_in_utf8 = 6
525 max_n_chars_in_byte = 2 ** last_n_bits_for_char_in_utf8
526 if all_values.size == max_n_chars_in_byte
527 @output.puts(<<-BODY)
528 #{indent}return #{value};
529 BODY
530 else
531 @output.puts(<<-BODY)
532 #{indent}if (#{char_variable}[#{n}] >= #{"%#04x" % min} &&
533 #{indent} #{char_variable}[#{n}] <= #{"%#04x" % max}) {
534 #{indent} return #{value};
535 #{indent}}
536 #{indent}break;
537 BODY
538 end
539 end
540 end
541 end
542 end
543
544 def generate_blockcode_char_type(block_codes)
545 default = "GRN_CHAR_OTHERS"
546
547 char_types = {}
548 current_type = default
549 prev_char = nil
550 block_codes.keys.sort.each do |char|
551 type = block_codes[char]
552 if current_type != default
553 prev_code_point = prev_char.codepoints[0]
554 code_point = char.codepoints[0]
555 (prev_code_point...code_point).each do |target_code_point|
556 target_char = [target_code_point].pack("U*")
557 char_types[target_char] = current_type
558 end
559 end
560 current_type = type
561 prev_char = char
562 end
563 unless current_type == default
564 raise "TODO: Consider the max unicode character"
565 max_unicode_char = "\u{10ffff}"
566 (prev_char..max_unicode_char).each do |target_char|
567 char_types[target_char] = current_type
568 end
569 end
570
571 generate_char_converter("char_type",
572 "char_type",
573 char_types,
574 default,
575 "grn_char_type") do |char|
576 char_types[char] || default
577 end
578 end
579
580 def generate_decompose(decompose_map)
581 default = "NULL"
582 generate_char_converter("decompose",
583 "decompose",
584 decompose_map,
585 default,
586 "const char *") do |from|
587 to = decompose_map[from]
588 if to
589 escaped_value = to.bytes.collect {|char| "\\x%02x" % char}.join("")
590 "\"#{escaped_value}\""
591 else
592 default
593 end
594 end
595 end
596
597 def generate_compose(compose_map)
598 # require "pp"
599 # p compose_map.size
600 # pp compose_map.keys.group_by {|x| x.chars[1]}.size
601 # pp compose_map.keys.group_by {|x| x.chars[1]}.collect {|k, vs| [k, k.codepoints, vs.size, vs.group_by {|x| x.chars[0].bytesize}.collect {|k2, vs2| [k2, vs2.size]}]}
602 # pp compose_map.keys.group_by {|x| x.chars[0].bytesize}.collect {|k, vs| [k, vs.size]}
603 # pp compose_map
604
605 suffix_char_map = {}
606 compose_map.each do |source, destination|
607 chars = source.chars
608 if chars.size != 2
609 STDERR.puts "caution: more than two chars in pattern #{chars.join('|')}"
610 return
611 end
612 prefix, suffix = chars
613 suffix_char_map[suffix] ||= {}
614 suffix_char_map[suffix][prefix] = destination
615 end
616
617 suffix_char_map.each do |suffix, prefix_char_map|
618 suffix_bytes = suffix.bytes.collect {|byte| "%02x" % byte}.join("")
619 default = "NULL"
620 generate_char_converter("compose_prefix_#{suffix_bytes}",
621 "compose_prefix_#{suffix_bytes}",
622 prefix_char_map,
623 default,
624 "const char *",
625 :internal => true) do |prefix|
626 to = prefix_char_map[prefix]
627 if to
628 escaped_value = to.bytes.collect {|char| "\\x%02x" % char}.join("")
629 "\"#{escaped_value}\""
630 else
631 default
632 end
633 end
634 end
635
636
637 char_variable = "suffix_utf8"
638 argument_list =
639 "const unsigned char *prefix_utf8, " +
640 "const unsigned char *#{char_variable}"
641 default = "NULL"
642 byte_size_groups = suffix_char_map.keys.group_by do |from|
643 bytes = from.bytes
644 bytes[0..-2]
645 end
646 generate_char_convert_function("compose",
647 argument_list,
648 char_variable,
649 default,
650 "const char *",
651 byte_size_groups) do |type, *args|
652 case type
653 when :no_common_bytes
654 indent, chars, chars_bytes = args
655 @output.puts(<<-BODY)
656 #{indent}switch (#{char_variable}[0]) {
657 BODY
658 chars.each do |char|
659 suffix_bytes = char.bytes.collect {|byte| "%02x" % byte}.join("")
660 type = "compose_prefix_#{suffix_bytes}"
661 @output.puts(<<-BODY)
662 #{indent}case #{"%#04x" % char.bytes.last} :
663 #{indent} return #{function_name(type)}(prefix_utf8);
664 BODY
665 end
666 @output.puts(<<-BODY)
667 #{indent}default :
668 #{indent} return #{default};
669 #{indent}}
670 #{indent}break;
671 BODY
672 when :have_common_bytes
673 indent, chars, chars_bytes, n, common_bytes = args
674 @output.puts(<<-BODY)
675 #{indent}switch (#{char_variable}[#{n}]) {
676 BODY
677 chars.each do |char|
678 suffix_bytes = char.bytes.collect {|byte| "%02x" % byte}.join("")
679 type = "compose_prefix_#{suffix_bytes}"
680 @output.puts(<<-BODY)
681 #{indent}case #{"%#04x" % char.bytes.last} :
682 #{indent} return #{function_name(type)}(prefix_utf8);
683 BODY
684 end
685 @output.puts(<<-BODY)
686 #{indent}default :
687 #{indent} return #{default};
688 #{indent}}
689 #{indent}break;
690 BODY
691 end
692 end
693 end
694
695 def to_bytes_map(char_map)
696 bytes_map = {}
697 char_map.each_key do |from|
698 parent = bytes_map
699 from.bytes[0..-2].each do |byte|
700 parent[byte] ||= {}
701 parent = parent[byte]
702 end
703 parent[from.bytes.last] = char_map[from]
704 end
705 bytes_map
706 end
707 end
708
709 def create_bc(option)
710 bc = {}
711 open("|./icudump --#{option}").each{|l|
712 src,_,code = l.chomp.split("\t")
713 str = src.split(':').collect(&:hex).pack("c*")
714 str.force_encoding("UTF-8")
715 bc[str] = code
716 }
717 bc
718 end
719
720 def ccpush(hash, src, dst)
721 head = src.shift
722 hash[head] = {} unless hash[head]
723 if head
724 ccpush(hash[head], src, dst)
725 else
726 hash[head] = dst
727 end
728 end
729
730 def subst(hash, str)
731 cand = nil
732 src = str.chars
733 for i in 0..src.size-1
734 h = hash
735 for j in i..src.size-1
736 head = src[j]
737 h = h[head]
738 break unless h
739 if h[nil]
740 cand = src[0,i].join("") + h[nil] + src[j + 1..-1].join("")
741 end
742 end
743 return cand if cand
744 end
745 return str
746 end
747
748 def downcase(character)
749 downcased_character = character.downcase
750 if character == "\u0130" and downcased_character == "\u0069\u0307"
751 # The lowercase of "U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE"
752 # must be "U+0069 LATIN SMALL LETTER I" but Ruby uses "U+0069
753 # LATIN SMALL LETTER I" + "U+0307 COMBINING DOT ABOVE".
754 downcased_character = "\u0069"
755 elsif character == "\u0049\u0307" and downcased_character == "\u0069\u0307"
756 # The lowercase of "U+0049 LATIN CAPITAL LETTER I" + "U+0307
757 # COMBINING DOT ABOVE" must be "U+0069 LATIN
758 # SMALL LETTER I".
759 downcased_character = "\u0069"
760 end
761 downcased_character
762 end
763
764 def map_entry(decompose, cc, src, dst)
765 dst = downcase(dst) unless $case_sensitive
766 loop {
767 dst2 = subst(cc, dst)
768 break if dst2 == dst
769 dst = dst2
770 }
771 unless $keep_space
772 dst = $1 if dst =~ /^ +([^ ].*)$/
773 end
774 decompose[src] = dst if src != dst
775 end
776
777 def create_decompose_map()
778 cc = {}
779 open('|./icudump --cc').each{|l|
780 _,src,dst = l.chomp.split("\t")
781 if cc[src]
782 STDERR.puts "caution: ambiguous mapping #{src}|#{cc[src]}|#{dst}" if cc[src] != dst
783 end
784 ccpush(cc, src.chars, dst)
785 }
786 decompose_map = {}
787 open('|./icudump --nfkd').each{|l|
788 n,src,dst = l.chomp.split("\t")
789 map_entry(decompose_map, cc, src, dst)
790 }
791 if File.readable?(CUSTOM_RULE_PATH)
792 open(CUSTOM_RULE_PATH).each{|l|
793 src,dst = l.chomp.split("\t")
794 map_entry(decompose_map, cc, src, dst)
795 }
796 end
797 unless $case_sensitive
798 (0x1..0x110000).each do |code_point|
799 char = [code_point].pack("U")
800 next unless char.valid_encoding?
801 downcased_char = downcase(char)
802 next if char == downcased_char
803 decompose_map[char] ||= downcased_char
804 end
805 end
806 return decompose_map
807 end
808
809 def create_compose_map(decompose_map)
810 cc = {}
811 open('|./icudump --cc').each{|l|
812 _,src,dst = l.chomp.split("\t")
813 src = src.chars.collect{|c| decompose_map[c] || c}.join
814 dst = decompose_map[dst] || dst
815 if cc[src] && cc[src] != dst
816 STDERR.puts("caution: inconsistent mapping '#{src}' => '#{cc[src]}'|'#{dst}'")
817 end
818 cc[src] = dst if src != dst
819 }
820 loop {
821 noccur = 0
822 cc2 = {}
823 cc.each {|src,dst|
824 src2 = src
825 chars = src.chars
826 l = chars.size - 1
827 for i in 0..l
828 for j in i..l
829 next if i == 0 && j == l
830 str = chars[i..j].join
831 if decompose_map[str]
832 STDERR.printf("caution: recursive mapping '%s'=>'%s'\n",
833 str, decompose_map[str])
834 end
835 if cc[str]
836 src2 = (i > 0 ? chars[0..i-1].join : '') + cc[str] + (j < l ? chars[j+1..l].join : '')
837 noccur += 1
838 end
839 end
840 end
841 cc2[src2] = dst if src2 != dst
842 }
843 cc = cc2
844 STDERR.puts("substituted #{noccur} patterns.")
845 break if noccur == 0
846 STDERR.puts('try again..')
847 }
848 return cc
849 end
850
851 def license_header
852 File.read(__FILE__).
853 # Extract the header comment
854 split(/^[^#]/, 2)[0].
855 # Remove Ruby style comment marks
856 gsub(/^# ?/, "").
857 # Remove shebang
858 gsub(/\A.*$/, "").
859 strip.
860 # Indent
861 gsub(/^(\w)/, " \\1")
862 end
863
864 ######## main #######
865
866 generator_class = TableGenerator
867 source_directory = "."
868 ARGV.each do |arg|
869 case arg
870 when /\A--source-directory=/
871 source_directory = $POSTMATCH
872 when /-*c/i
873 $case_sensitive = true
874 when /-*s/i
875 $keep_space = true
876 when "--impl=switch"
877 generator_class = SwitchGenerator
878 when "--impl=table"
879 generator_class = TableGenerator
880 end
881 end
882
883 icu_home = ENV["ICU_HOME"] || "/tmp/local"
884 STDERR.puts("compiling icudump on #{icu_home}")
885 system("cc",
886 "-Wall",
887 "-O3",
888 "-g3",
889 "-o", "icudump",
890 "-I#{icu_home}/include",
891 "-L#{icu_home}/lib",
892 File.join(source_directory, "icudump.c"),
893 "-licuuc",
894 "-licui18n",
895 "-licudata") or exit(false)
896
897 ENV["LD_LIBRARY_PATH"] = "#{icu_home}/lib:#{ENV["LD_LIBRARY_PATH"]}"
898
899 STDERR.puts('getting Unicode version')
900 unicode_version = `./icudump --version`.strip.gsub(".", "")
901
902 STDERR.puts('creating bc..')
903 bc = create_bc("gc")
904
905 STDERR.puts('creating decompose map..')
906 decompose_map = create_decompose_map()
907
908 STDERR.puts('creating compose map..')
909 compose_map = create_compose_map(decompose_map)
910
911 output_path = File.join(source_directory, "nfkc#{unicode_version}.c")
912 File.open(output_path, "w") do |output|
913 output.puts(<<-HEADER)
914 /* -*- c-basic-offset: 2 -*- */
915 /*
916 #{license_header}
917 */
918
919 /*
920 Don't edit this file by hand. it generated automatically by nfkc.rb.
921 */
922
923 #include "grn.h"
924 #include "grn_nfkc.h"
925 #include <groonga/nfkc.h>
926
927 #ifdef GRN_WITH_NFKC
928 HEADER
929
930 generator = generator_class.new(unicode_version, output)
931 generator.generate(bc, decompose_map, compose_map)
932
933 output.puts(<<-FOOTER)
934
935 #endif /* GRN_WITH_NFKC */
936
937 FOOTER
938 end