Debian Codegraph @

vendor/onigmo-source/tool/case-folding.rb

raw
1 #!/usr/bin/ruby
2 require 'stringio'
3
4 # Usage (for case folding only):
5 # $ wget http://www.unicode.org/Public/UNIDATA/CaseFolding.txt
6 # $ ruby case-folding.rb CaseFolding.txt -o casefold.h
7 # or (for case folding and case mapping):
8 # $ wget http://www.unicode.org/Public/UNIDATA/CaseFolding.txt
9 # $ wget http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
10 # $ wget http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt
11 # $ ruby case-folding.rb -m . -o casefold.h
12 # using -d or --debug will include UTF-8 characters in comments for debugging
13
14 class CaseFolding
15 module Util
16 module_function
17
18 def hex_seq(v)
19 v.map { |i| "0x%04x" % i }.join(", ")
20 end
21
22 def print_table_1(dest, type, mapping_data, data)
23 for k, v in data = data.sort
24 sk = (Array === k and k.length > 1) ? "{#{hex_seq(k)}}" : ("0x%04x" % k)
25 if type=='CaseUnfold_11' and v.length>1
26 # reorder CaseUnfold_11 entries to avoid special treatment for U+03B9/U+03BC/U+A64B
27 item = mapping_data.map("%04X" % k[0])
28 upper = item.upper if item
29 v = v.sort_by { |i| ("%04X"%i) == upper ? 0 : 1 }
30 end
31 ck = @debug ? ' /* ' + Array(k).pack("U*") + ' */' : ''
32 cv = @debug ? ' /* ' + Array(v).map{|c|[c].pack("U*")}.join(", ") + ' */' : ''
33 dest.print(" {#{sk}#{ck}, {#{v.length}#{mapping_data.flags(k, type, v)}, {#{hex_seq(v)}#{cv}}}},\n")
34 end
35 data
36 end
37
38 def print_table(dest, type, mapping_data, data)
39 dest.print("static const #{type}_Type #{type}_Table[] = {\n")
40 i = 0
41 ret = data.inject([]) do |a, (n, d)|
42 dest.print("#define #{n} (*(#{type}_Type (*)[#{d.size}])(#{type}_Table+#{i}))\n")
43 i += d.size
44 a.concat(print_table_1(dest, type, mapping_data, d))
45 end
46 dest.print("};\n\n")
47 ret
48 end
49 end
50
51 include Util
52
53 attr_reader :fold, :fold_locale, :unfold, :unfold_locale, :version
54
55 def load(filename)
56 pattern = /([0-9A-F]{4,6}); ([CFT]); ([0-9A-F]{4,6})(?: ([0-9A-F]{4,6}))?(?: ([0-9A-F]{4,6}))?;/
57
58 @fold = fold = {}
59 @unfold = unfold = [{}, {}, {}]
60 @debug = false
61 @version = nil
62 turkic = []
63
64 IO.foreach(filename, mode: "rb") do |line|
65 @version ||= line[/-([0-9.]+).txt/, 1]
66 next unless res = pattern.match(line)
67 ch_from = res[1].to_i(16)
68
69 if res[2] == 'T'
70 # Turkic case folding
71 turkic << ch_from
72 next
73 end
74
75 # store folding data
76 ch_to = res[3..6].inject([]) do |a, i|
77 break a unless i
78 a << i.to_i(16)
79 end
80 fold[ch_from] = ch_to
81
82 # store unfolding data
83 i = ch_to.length - 1
84 (unfold[i][ch_to] ||= []) << ch_from
85 end
86
87 # move locale dependent data to (un)fold_locale
88 @fold_locale = fold_locale = {}
89 @unfold_locale = unfold_locale = [{}, {}]
90 for ch_from in turkic
91 key = fold[ch_from]
92 i = key.length - 1
93 unfold_locale[i][i == 0 ? key[0] : key] = unfold[i].delete(key)
94 fold_locale[ch_from] = fold.delete(ch_from)
95 end
96 self
97 end
98
99 def range_check(code)
100 "#{code} <= MAX_CODE_VALUE && #{code} >= MIN_CODE_VALUE"
101 end
102
103 def lookup_hash(key, type, data)
104 hash = "onigenc_unicode_#{key}_hash"
105 lookup = "onigenc_unicode_#{key}_lookup"
106 arity = Array(data[0][0]).size
107 gperf = %W"gperf -7 -k#{[*1..(arity*3)].join(',')} -F,-1 -c -j1 -i1 -t -T -E -C -H #{hash} -N #{lookup} -n"
108 argname = arity > 1 ? "codes" : "code"
109 argdecl = "const OnigCodePoint #{arity > 1 ? "*": ""}#{argname}"
110 n = 7
111 m = (1 << n) - 1
112 min, max = data.map {|c, *|c}.flatten.minmax
113 src = IO.popen(gperf, "r+") {|f|
114 f << "short\n%%\n"
115 data.each_with_index {|(k, _), i|
116 k = Array(k)
117 ks = k.map {|j| [(j >> n*2) & m, (j >> n) & m, (j) & m]}.flatten.map {|c| "\\x%.2x" % c}.join("")
118 f.printf "\"%s\", ::::/*%s*/ %d\n", ks, k.map {|c| "0x%.4x" % c}.join(","), i
119 }
120 f << "%%\n"
121 f.close_write
122 f.read
123 }
124 src.sub!(/^(#{hash})\s*\(.*?\).*?\n\{\n(.*)^\}/m) {
125 name = $1
126 body = $2
127 body.gsub!(/\(unsigned char\)str\[(\d+)\]/, "bits_#{arity > 1 ? 'at' : 'of'}(#{argname}, \\1)")
128 "#{name}(#{argdecl})\n{\n#{body}}"
129 }
130 src.sub!(/const short *\*\n^(#{lookup})\s*\(.*?\).*?\n\{\n(.*)^\}/m) {
131 name = $1
132 body = $2
133 body.sub!(/\benum\s+\{(\n[ \t]+)/, "\\&MIN_CODE_VALUE = 0x#{min.to_s(16)},\\1""MAX_CODE_VALUE = 0x#{max.to_s(16)},\\1")
134 body.gsub!(/(#{hash})\s*\(.*?\)/, "\\1(#{argname})")
135 body.gsub!(/\{"",-1}/, "-1")
136 body.gsub!(/\{"(?:[^"]|\\")+", *::::(.*)\}/, '\1')
137 body.sub!(/(\s+if\s)\(len\b.*\)/) do
138 "#$1(" <<
139 (arity > 1 ? (0...arity).map {|i| range_check("#{argname}[#{i}]")}.join(" &&\n ") : range_check(argname)) <<
140 ")"
141 end
142 v = nil
143 body.sub!(/(if\s*\(.*MAX_HASH_VALUE.*\)\n([ \t]*))\{(.*?)\n\2\}/m) {
144 pre = $1
145 indent = $2
146 s = $3
147 s.sub!(/const char *\* *(\w+)( *= *wordlist\[\w+\]).\w+/, 'short \1 = wordlist[key]')
148 v = $1
149 s.sub!(/\bif *\(.*\)/, "if (#{v} >= 0 && code#{arity}_equal(#{argname}, #{key}_Table[#{v}].from))")
150 "#{pre}{#{s}\n#{indent}}"
151 }
152 body.sub!(/\b(return\s+&)([^;]+);/, '\1'"#{key}_Table[#{v}].to;")
153 "static const #{type} *\n#{name}(#{argdecl})\n{\n#{body}}"
154 }
155 src
156 end
157
158 def display(dest, mapping_data)
159 # print the header
160 dest.print("/* DO NOT EDIT THIS FILE. */\n")
161 dest.print("/* Generated by tool/case-folding.rb */\n\n")
162
163 versions = version.scan(/\d+/)
164 dest.print("#if defined ONIG_UNICODE_VERSION_STRING && !( \\\n")
165 %w[MAJOR MINOR TEENY].zip(versions) do |n, v|
166 dest.print(" ONIG_UNICODE_VERSION_#{n} == #{v} && \\\n")
167 end
168 dest.print(" 1)\n")
169 dest.print("# error ONIG_UNICODE_VERSION_STRING mismatch\n")
170 dest.print("#endif\n")
171 dest.print("#define ONIG_UNICODE_VERSION_STRING #{version.dump}\n")
172 %w[MAJOR MINOR TEENY].zip(versions) do |n, v|
173 dest.print("#define ONIG_UNICODE_VERSION_#{n} #{v}\n")
174 end
175 dest.print("\n")
176
177 # print folding data
178
179 # CaseFold + CaseFold_Locale
180 name = "CaseFold_11"
181 data = print_table(dest, name, mapping_data, "CaseFold"=>fold, "CaseFold_Locale"=>fold_locale)
182 dest.print lookup_hash(name, "CodePointList3", data)
183
184 # print unfolding data
185
186 # CaseUnfold_11 + CaseUnfold_11_Locale
187 name = "CaseUnfold_11"
188 data = print_table(dest, name, mapping_data, name=>unfold[0], "#{name}_Locale"=>unfold_locale[0])
189 dest.print lookup_hash(name, "CodePointList3", data)
190
191 # CaseUnfold_12 + CaseUnfold_12_Locale
192 name = "CaseUnfold_12"
193 data = print_table(dest, name, mapping_data, name=>unfold[1], "#{name}_Locale"=>unfold_locale[1])
194 dest.print lookup_hash(name, "CodePointList2", data)
195
196 # CaseUnfold_13
197 name = "CaseUnfold_13"
198 data = print_table(dest, name, mapping_data, name=>unfold[2])
199 dest.print lookup_hash(name, "CodePointList2", data)
200
201 # TitleCase
202 dest.print mapping_data.specials_output
203 end
204
205 def debug!
206 @debug = true
207 end
208
209 def self.load(*args)
210 new.load(*args)
211 end
212 end
213
214 class MapItem
215 attr_accessor :upper, :lower, :title, :code
216
217 def initialize(code, upper, lower, title)
218 @code = code
219 @upper = upper unless upper == ''
220 @lower = lower unless lower == ''
221 @title = title unless title == ''
222 end
223 end
224
225 class CaseMapping
226 attr_reader :filename, :version
227
228 def initialize(mapping_directory)
229 @mappings = {}
230 @specials = []
231 @specials_length = 0
232 @version = nil
233 IO.foreach(File.join(mapping_directory, 'UnicodeData.txt'), mode: "rb") do |line|
234 next if line =~ /^</
235 code, _1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11, upper, lower, title = line.chomp.split ';'
236 unless upper and lower and title and (upper+lower+title)==''
237 @mappings[code] = MapItem.new(code, upper, lower, title)
238 end
239 end
240
241 @filename = File.join(mapping_directory, 'SpecialCasing.txt')
242 IO.foreach(@filename, mode: "rb") do |line|
243 @version ||= line[/-([0-9.]+).txt/, 1]
244 line.chomp!
245 line, comment = line.split(/ *#/)
246 next if not line or line == ''
247 code, lower, title, upper, conditions = line.split(/ *; */)
248 unless conditions
249 item = @mappings[code]
250 item.lower = lower
251 item.title = title
252 item.upper = upper
253 end
254 end
255 end
256
257 def map (from)
258 @mappings[from]
259 end
260
261 def flags(from, type, to)
262 # types: CaseFold_11, CaseUnfold_11, CaseUnfold_12, CaseUnfold_13
263 flags = ""
264 from = Array(from).map {|i| "%04X" % i}.join(" ")
265 to = Array(to).map {|i| "%04X" % i}.join(" ")
266 item = map(from)
267 specials_index = nil
268 specials = []
269 case type
270 when 'CaseFold_11'
271 flags += '|F'
272 if item
273 flags += '|U' if to==item.upper
274 flags += '|D' if to==item.lower
275 unless item.upper == item.title
276 if item.code == item.title
277 flags += '|IT'
278 swap = case item.code
279 when '01C5' then '0064 017D'
280 when '01C8' then '006C 004A'
281 when '01CB' then '006E 004A'
282 when '01F2' then '0064 005A'
283 else # Greek
284 to.split(' ').first + ' 0399'
285 end
286 specials << swap
287 else
288 flags += '|ST'
289 specials << item.title
290 end
291 end
292 unless item.lower.nil? or item.lower==from or item.lower==to
293 specials << item.lower
294 flags += '|SL'
295 end
296 unless item.upper.nil? or item.upper==from or item.upper==to
297 specials << item.upper
298 flags += '|SU'
299 end
300 end
301 when 'CaseUnfold_11'
302 to = to.split(/ /)
303 if item
304 case to.first
305 when item.upper then flags += '|U'
306 when item.lower then flags += '|D'
307 else
308 raise "Unpredicted case 0 in enc/unicode/case_folding.rb. Please contact https://bugs.ruby-lang.org/."
309 end
310 unless item.upper == item.title
311 if item.code == item.title
312 raise "Unpredicted case 1 in enc/unicode/case_folding.rb. Please contact https://bugs.ruby-lang.org/."
313 elsif item.title==to[1]
314 flags += '|ST'
315 else
316 raise "Unpredicted case 2 in enc/unicode/case_folding.rb. Please contact https://bugs.ruby-lang.org/."
317 end
318 end
319 end
320 end
321 unless specials.empty?
322 flags += "|I(#{@specials_length})"
323 @specials_length += specials.map { |s| s.split(/ /).length }.reduce(:+)
324 @specials << specials
325 end
326 flags
327 end
328
329 def debug!
330 @debug = true
331 end
332
333 def specials_output
334 "static const OnigCodePoint CaseMappingSpecials[] = {\n" +
335 @specials.map do |sps|
336 ' ' + sps.map do |sp|
337 chars = sp.split(/ /)
338 ct = ' /* ' + Array(chars).map{|c|[c.to_i(16)].pack("U*")}.join(", ") + ' */' if @debug
339 " L(#{chars.length})|#{chars.map {|c| "0x"+c }.join(', ')}#{ct},"
340 end.join + "\n"
341 end.join + "};\n"
342 end
343
344 def self.load(*args)
345 new(*args)
346 end
347 end
348
349 class CaseMappingDummy
350 def flags(from, type, to)
351 ""
352 end
353
354 def titlecase_output() '' end
355 def debug!() end
356 end
357
358 if $0 == __FILE__
359 require 'optparse'
360 dest = nil
361 mapping_directory = nil
362 mapping_data = nil
363 debug = false
364 fold_1 = false
365 ARGV.options do |opt|
366 opt.banner << " [INPUT]"
367 opt.on("--output-file=FILE", "-o", "output to the FILE instead of STDOUT") {|output|
368 dest = (output unless output == '-')
369 }
370 opt.on('--mapping-data-directory=DIRECTORY', '-m', 'data DIRECTORY of mapping files') { |directory|
371 mapping_directory = directory
372 }
373 opt.on('--debug', '-d') {
374 debug = true
375 }
376 opt.parse!
377 abort(opt.to_s) if ARGV.size > 1
378 end
379 if mapping_directory
380 if ARGV[0]
381 warn "Either specify directory or individual file, but not both."
382 exit
383 end
384 filename = File.join(mapping_directory, 'CaseFolding.txt')
385 mapping_data = CaseMapping.load(mapping_directory)
386 end
387 filename ||= ARGV[0] || 'CaseFolding.txt'
388 data = CaseFolding.load(filename)
389 if mapping_data and data.version != mapping_data.version
390 abort "Unicode data version mismatch\n" \
391 " #{filename} = #{data.version}\n" \
392 " #{mapping_data.filename} = #{mapping_data.version}"
393 end
394 mapping_data ||= CaseMappingDummy.new
395
396 if debug
397 data.debug!
398 mapping_data.debug!
399 end
400 f = StringIO.new
401 begin
402 data.display(f, mapping_data)
403 rescue Errno::ENOENT => e
404 raise unless /gperf/ =~ e.message
405 warn e.message
406 abort unless dest
407 File.utime(nil, nil, dest) # assume existing file is OK
408 exit
409 else
410 s = f.string
411 end
412 if dest
413 open(dest, "wb") do |f|
414 f.print(s)
415 end
416 else
417 STDOUT.print(s)
418 end
419 end