Debian Codegraph @

vendor/onigmo-source/tool/enc-unicode.rb

raw
1 #!/usr/bin/env ruby
2
3 # Creates the data structures needed by Oniguruma to map Unicode codepoints to
4 # property names and POSIX character classes
5 #
6 # To use this, get UnicodeData.txt, Scripts.txt, PropList.txt,
7 # PropertyAliases.txt, PropertyValueAliases.txt, DerivedCoreProperties.txt,
8 # DerivedAge.txt and Blocks.txt from unicode.org.
9 # (http://unicode.org/Public/UNIDATA/) And run following command.
10 # ruby1.9 tool/enc-unicode.rb data_dir > enc/unicode/name2ctype.kwd
11 # You can get source file for gperf. After this, simply make ruby.
12
13 if ARGV[0] == "--header"
14 header = true
15 ARGV.shift
16 end
17 unless ARGV.size == 1
18 abort "Usage: #{$0} data_directory"
19 end
20
21 $unicode_version = File.basename(ARGV[0])[/\A[.\d]+\z/]
22
23 POSIX_NAMES = %w[NEWLINE Alpha Blank Cntrl Digit Graph Lower Print XPosixPunct Space Upper XDigit Word Alnum ASCII Punct]
24
25 def pair_codepoints(codepoints)
26
27 # We have a sorted Array of codepoints that we wish to partition into
28 # ranges such that the start- and endpoints form an inclusive set of
29 # codepoints with property _property_. Note: It is intended that some ranges
30 # will begin with the value with which they end, e.g. 0x0020 -> 0x0020
31
32 codepoints.sort!
33 last_cp = codepoints.first
34 pairs = [[last_cp, nil]]
35 codepoints[1..-1].each do |codepoint|
36 next if last_cp == codepoint
37
38 # If the current codepoint does not follow directly on from the last
39 # codepoint, the last codepoint represents the end of the current range,
40 # and the current codepoint represents the start of the next range.
41 if last_cp.next != codepoint
42 pairs[-1][-1] = last_cp
43 pairs << [codepoint, nil]
44 end
45 last_cp = codepoint
46 end
47
48 # The final pair has as its endpoint the last codepoint for this property
49 pairs[-1][-1] = codepoints.last
50 pairs
51 end
52
53 def parse_unicode_data(file)
54 last_cp = 0
55 data = {'Any' => (0x0000..0x10ffff).to_a, 'Assigned' => [],
56 'ASCII' => (0..0x007F).to_a, 'NEWLINE' => [0x0a], 'Cn' => []}
57 beg_cp = nil
58 IO.foreach(file) do |line|
59 fields = line.split(';')
60 cp = fields[0].to_i(16)
61
62 case fields[1]
63 when /\A<(.*),\s*First>\z/
64 beg_cp = cp
65 next
66 when /\A<(.*),\s*Last>\z/
67 cps = (beg_cp..cp).to_a
68 else
69 beg_cp = cp
70 cps = [cp]
71 end
72
73 # The Cn category represents unassigned characters. These are not listed in
74 # UnicodeData.txt so we must derive them by looking for 'holes' in the range
75 # of listed codepoints. We increment the last codepoint seen and compare it
76 # with the current codepoint. If the current codepoint is less than
77 # last_cp.next we have found a hole, so we add the missing codepoint to the
78 # Cn category.
79 data['Cn'].concat((last_cp.next...beg_cp).to_a)
80
81 # Assigned - Defined in unicode.c; interpreted as every character in the
82 # Unicode range minus the unassigned characters
83 data['Assigned'].concat(cps)
84
85 # The third field denotes the 'General' category, e.g. Lu
86 (data[fields[2]] ||= []).concat(cps)
87
88 # The 'Major' category is the first letter of the 'General' category, e.g.
89 # 'Lu' -> 'L'
90 (data[fields[2][0,1]] ||= []).concat(cps)
91 last_cp = cp
92 end
93
94 # The last Cn codepoint should be 0x10ffff. If it's not, append the missing
95 # codepoints to Cn and C
96 cn_remainder = (last_cp.next..0x10ffff).to_a
97 data['Cn'] += cn_remainder
98 data['C'] += data['Cn']
99
100 # Special case for LC (Cased_Letter). LC = Ll + Lt + Lu
101 data['LC'] = data['Ll'] + data['Lt'] + data['Lu']
102
103 # Define General Category properties
104 gcps = data.keys.sort - POSIX_NAMES
105
106 # Returns General Category Property names and the data
107 [gcps, data]
108 end
109
110 def define_posix_props(data)
111 # We now derive the character classes (POSIX brackets), e.g. [[:alpha:]]
112 #
113
114 data['Alpha'] = data['Alphabetic']
115 data['Upper'] = data['Uppercase']
116 data['Lower'] = data['Lowercase']
117 data['Punct'] = data['Punctuation']
118 data['XPosixPunct'] = data['Punctuation'] + [0x24, 0x2b, 0x3c, 0x3d, 0x3e, 0x5e, 0x60, 0x7c, 0x7e]
119 data['Digit'] = data['Decimal_Number']
120 data['XDigit'] = (0x0030..0x0039).to_a + (0x0041..0x0046).to_a +
121 (0x0061..0x0066).to_a
122 data['Alnum'] = data['Alpha'] + data['Digit']
123 data['Space'] = data['White_Space']
124 data['Blank'] = data['Space_Separator'] + [0x0009]
125 data['Cntrl'] = data['Cc']
126 data['Word'] = data['Alpha'] + data['Mark'] + data['Digit'] + data['Connector_Punctuation']
127 data['Graph'] = data['Any'] - data['Space'] - data['Cntrl'] -
128 data['Surrogate'] - data['Unassigned']
129 data['Print'] = data['Graph'] + data['Space_Separator']
130 end
131
132 def parse_scripts(data, categories)
133 files = [
134 {:fn => 'DerivedCoreProperties.txt', :title => 'Derived Property'},
135 {:fn => 'Scripts.txt', :title => 'Script'},
136 {:fn => 'PropList.txt', :title => 'Binary Property'}
137 ]
138 current = nil
139 cps = []
140 names = {}
141 files.each do |file|
142 data_foreach(file[:fn]) do |line|
143 if /^# Total code points: / =~ line
144 data[current] = cps
145 categories[current] = file[:title]
146 (names[file[:title]] ||= []) << current
147 cps = []
148 elsif /^([0-9a-fA-F]+)(?:\.\.([0-9a-fA-F]+))?\s*;\s*(\w+)/ =~ line
149 current = $3
150 $2 ? cps.concat(($1.to_i(16)..$2.to_i(16)).to_a) : cps.push($1.to_i(16))
151 end
152 end
153 end
154 # All code points not explicitly listed for Script
155 # have the value Unknown (Zzzz).
156 data['Unknown'] = (0..0x10ffff).to_a - data.values_at(*names['Script']).flatten
157 categories['Unknown'] = 'Script'
158 names.values.flatten << 'Unknown'
159 end
160
161 def parse_aliases(data)
162 kv = {}
163 data_foreach('PropertyAliases.txt') do |line|
164 next unless /^(\w+)\s*; (\w+)/ =~ line
165 data[$1] = data[$2]
166 kv[normalize_propname($1)] = normalize_propname($2)
167 end
168 data_foreach('PropertyValueAliases.txt') do |line|
169 next unless /^(sc|gc)\s*; (\w+)\s*; (\w+)(?:\s*; (\w+))?/ =~ line
170 if $1 == 'gc'
171 data[$3] = data[$2]
172 data[$4] = data[$2]
173 kv[normalize_propname($3)] = normalize_propname($2)
174 kv[normalize_propname($4)] = normalize_propname($2) if $4
175 else
176 data[$2] = data[$3]
177 data[$4] = data[$3]
178 kv[normalize_propname($2)] = normalize_propname($3)
179 kv[normalize_propname($4)] = normalize_propname($3) if $4
180 end
181 end
182 kv
183 end
184
185 # According to Unicode6.0.0/ch03.pdf, Section 3.1, "An update version
186 # never involves any additions to the character repertoire." Versions
187 # in DerivedAge.txt should always be /\d+\.\d+/
188 def parse_age(data)
189 current = nil
190 last_constname = nil
191 cps = []
192 ages = []
193 data_foreach('DerivedAge.txt') do |line|
194 if /^# Total code points: / =~ line
195 constname = constantize_agename(current)
196 # each version matches all previous versions
197 cps.concat(data[last_constname]) if last_constname
198 data[constname] = cps
199 make_const(constname, cps, "Derived Age #{current}")
200 ages << current
201 last_constname = constname
202 cps = []
203 elsif /^([0-9a-fA-F]+)(?:\.\.([0-9a-fA-F]+))?\s*;\s*(\d+\.\d+)/ =~ line
204 current = $3
205 $2 ? cps.concat(($1.to_i(16)..$2.to_i(16)).to_a) : cps.push($1.to_i(16))
206 end
207 end
208 ages
209 end
210
211 def parse_GraphemeBreakProperty(data)
212 current = nil
213 cps = []
214 ages = []
215 data_foreach('GraphemeBreakProperty.txt') do |line|
216 if /^# Total code points: / =~ line
217 constname = constantize_Grapheme_Cluster_Break(current)
218 data[constname] = cps
219 make_const(constname, cps, "Grapheme_Cluster_Break=#{current}")
220 ages << current
221 cps = []
222 elsif /^([0-9a-fA-F]+)(?:\.\.([0-9a-fA-F]+))?\s*;\s*(\w+)/ =~ line
223 current = $3
224 $2 ? cps.concat(($1.to_i(16)..$2.to_i(16)).to_a) : cps.push($1.to_i(16))
225 end
226 end
227 ages
228 end
229
230 def parse_block(data)
231 current = nil
232 cps = []
233 blocks = []
234 data_foreach('Blocks.txt') do |line|
235 if /^([0-9a-fA-F]+)\.\.([0-9a-fA-F]+);\s*(.*)/ =~ line
236 cps = ($1.to_i(16)..$2.to_i(16)).to_a
237 constname = constantize_blockname($3)
238 data[constname] = cps
239 make_const(constname, cps, "Block")
240 blocks << constname
241 end
242 end
243
244 # All code points not belonging to any of the named blocks
245 # have the value No_Block.
246 no_block = (0..0x10ffff).to_a - data.values_at(*blocks).flatten
247 constname = constantize_blockname("No_Block")
248 make_const(constname, no_block, "Block")
249 blocks << constname
250 end
251
252 # shim for Ruby 1.8
253 unless {}.respond_to?(:key)
254 class Hash
255 alias key index
256 end
257 end
258
259 $const_cache = {}
260 # make_const(property, pairs, name): Prints a 'static const' structure for a
261 # given property, group of paired codepoints, and a human-friendly name for
262 # the group
263 def make_const(prop, data, name)
264 if name.empty?
265 puts "\n/* '#{prop}' */"
266 else
267 puts "\n/* '#{prop}': #{name} */"
268 end
269 if origprop = $const_cache.key(data)
270 puts "#define CR_#{prop} CR_#{origprop}"
271 else
272 $const_cache[prop] = data
273 pairs = pair_codepoints(data)
274 puts "static const OnigCodePoint CR_#{prop}[] = {"
275 # The first element of the constant is the number of pairs of codepoints
276 puts "\t#{pairs.size},"
277 pairs.each do |pair|
278 pair.map! { |c| c == 0 ? '0x0000' : sprintf("%0#6x", c) }
279 puts "\t#{pair.first}, #{pair.last},"
280 end
281 puts "}; /* CR_#{prop} */"
282 end
283 end
284
285 def normalize_propname(name)
286 name = name.downcase
287 name.delete!('- _')
288 name
289 end
290
291 def constantize_agename(name)
292 "Age_#{name.sub(/\./, '_')}"
293 end
294
295 def constantize_Grapheme_Cluster_Break(name)
296 "Grapheme_Cluster_Break_#{name}"
297 end
298
299 def constantize_blockname(name)
300 "In_#{name.gsub(/\W/, '_')}"
301 end
302
303 def get_file(name)
304 File.join(ARGV[0], name)
305 end
306
307 def data_foreach(name, &block)
308 fn = get_file(name)
309 warn "Reading #{name}"
310 pat = /^# #{name.sub(/\./, '-([\\d.]+)\\.')}/
311 File.open(fn, 'rb') do |f|
312 line = f.gets
313 unless pat =~ line
314 raise ArgumentError, "#{name}: no Unicode version"
315 end
316 if !$unicode_version
317 $unicode_version = $1
318 elsif $unicode_version != $1
319 raise ArgumentError, "#{name}: Unicode version mismatch: #$1"
320 end
321 f.each(&block)
322 end
323 end
324
325 # Write Data
326 class Unifdef
327 attr_accessor :output, :top, :stack, :stdout, :kwdonly
328 def initialize(out)
329 @top = @output = []
330 @stack = []
331 $stdout, @stdout = self, out
332 end
333 def restore
334 $stdout = @stdout
335 end
336 def ifdef(sym)
337 if @kwdonly
338 @stdout.puts "#ifdef #{sym}"
339 return
340 end
341 @stack << @top
342 @top << tmp = [sym]
343 @top = tmp
344 end
345 def endif(sym)
346 if @kwdonly
347 @stdout.puts "#endif /* #{sym} */"
348 return
349 end
350 unless sym == @top[0]
351 restore
352 raise ArgumentError, "#{sym} unmatch to #{@top[0]}"
353 end
354 @top = @stack.pop
355 end
356 def show(dest, *syms)
357 _show(dest, @output, syms)
358 end
359 def _show(dest, ary, syms)
360 if Symbol === (sym = ary[0])
361 unless syms.include?(sym)
362 return
363 end
364 end
365 ary.each do |e|
366 case e
367 when Array
368 _show(dest, e, syms)
369 when String
370 dest.print e
371 end
372 end
373 end
374 def write(str)
375 if @kwdonly
376 @stdout.write(str)
377 else
378 @top << str
379 end
380 self
381 end
382 alias << write
383 end
384
385 output = Unifdef.new($stdout)
386 output.kwdonly = !header
387
388 puts '%{'
389 props, data = parse_unicode_data(get_file('UnicodeData.txt'))
390 categories = {}
391 props.concat parse_scripts(data, categories)
392 aliases = parse_aliases(data)
393 define_posix_props(data)
394 POSIX_NAMES.each do |name|
395 if name == 'XPosixPunct'
396 make_const(name, data[name], "[[:Punct:]]")
397 elsif name == 'Punct'
398 make_const(name, data[name], "")
399 else
400 make_const(name, data[name], "[[:#{name}:]]")
401 end
402 end
403 output.ifdef :USE_UNICODE_PROPERTIES
404 props.each do |name|
405 category = categories[name] ||
406 case name.size
407 when 1 then 'Major Category'
408 when 2 then 'General Category'
409 else '-'
410 end
411 make_const(name, data[name], category)
412 end
413 output.ifdef :USE_UNICODE_AGE_PROPERTIES
414 ages = parse_age(data)
415 output.endif :USE_UNICODE_AGE_PROPERTIES
416 graphemeBreaks = parse_GraphemeBreakProperty(data)
417 blocks = parse_block(data)
418 output.endif :USE_UNICODE_PROPERTIES
419 puts(<<'__HEREDOC')
420
421 static const OnigCodePoint* const CodeRanges[] = {
422 __HEREDOC
423 POSIX_NAMES.each{|name|puts" CR_#{name},"}
424 output.ifdef :USE_UNICODE_PROPERTIES
425 props.each{|name| puts" CR_#{name},"}
426 output.ifdef :USE_UNICODE_AGE_PROPERTIES
427 ages.each{|name| puts" CR_#{constantize_agename(name)},"}
428 output.endif :USE_UNICODE_AGE_PROPERTIES
429 graphemeBreaks.each{|name| puts" CR_#{constantize_Grapheme_Cluster_Break(name)},"}
430 blocks.each{|name|puts" CR_#{name},"}
431 output.endif :USE_UNICODE_PROPERTIES
432
433 puts(<<'__HEREDOC')
434 };
435 struct uniname2ctype_struct {
436 short name;
437 unsigned short ctype;
438 };
439
440 static const struct uniname2ctype_struct *uniname2ctype_p(const char *, unsigned int);
441 %}
442 struct uniname2ctype_struct;
443 %%
444 __HEREDOC
445
446 i = -1
447 name_to_index = {}
448 POSIX_NAMES.each do |name|
449 i += 1
450 next if name == 'NEWLINE'
451 name = normalize_propname(name)
452 name_to_index[name] = i
453 puts"%-40s %3d" % [name + ',', i]
454 end
455 output.ifdef :USE_UNICODE_PROPERTIES
456 props.each do |name|
457 i += 1
458 name = normalize_propname(name)
459 name_to_index[name] = i
460 puts "%-40s %3d" % [name + ',', i]
461 end
462 aliases.each_pair do |k, v|
463 next if name_to_index[k]
464 next unless v = name_to_index[v]
465 puts "%-40s %3d" % [k + ',', v]
466 end
467 output.ifdef :USE_UNICODE_AGE_PROPERTIES
468 ages.each do |name|
469 i += 1
470 name = "age=#{name}"
471 name_to_index[name] = i
472 puts "%-40s %3d" % [name + ',', i]
473 end
474 output.endif :USE_UNICODE_AGE_PROPERTIES
475 graphemeBreaks.each do |name|
476 i += 1
477 name = "graphemeclusterbreak=#{name.delete('_').downcase}"
478 name_to_index[name] = i
479 puts "%-40s %3d" % [name + ',', i]
480 end
481 blocks.each do |name|
482 i += 1
483 name = normalize_propname(name)
484 name_to_index[name] = i
485 puts "%-40s %3d" % [name + ',', i]
486 end
487 output.endif :USE_UNICODE_PROPERTIES
488 puts(<<'__HEREDOC')
489 %%
490 static int
491 uniname2ctype(const UChar *name, unsigned int len)
492 {
493 const struct uniname2ctype_struct *p = uniname2ctype_p((const char *)name, len);
494 if (p) return p->ctype;
495 return -1;
496 }
497 __HEREDOC
498 versions = $unicode_version.scan(/\d+/)
499 print("#if defined ONIG_UNICODE_VERSION_STRING && !( \\\n")
500 %w[MAJOR MINOR TEENY].zip(versions) do |n, v|
501 print(" ONIG_UNICODE_VERSION_#{n} == #{v} && \\\n")
502 end
503 print(" 1)\n")
504 print("# error ONIG_UNICODE_VERSION_STRING mismatch\n")
505 print("#endif\n")
506 print("#define ONIG_UNICODE_VERSION_STRING #{$unicode_version.dump}\n")
507 %w[MAJOR MINOR TEENY].zip(versions) do |n, v|
508 print("#define ONIG_UNICODE_VERSION_#{n} #{v}\n")
509 end
510
511 output.restore
512
513 if header
514 require 'tempfile'
515
516 NAME2CTYPE = %w[gperf -7 -c -j1 -i1 -t -C -P -T -H uniname2ctype_hash -Q uniname2ctype_pool -N uniname2ctype_p]
517
518 fds = []
519 syms = %i[USE_UNICODE_PROPERTIES USE_UNICODE_AGE_PROPERTIES]
520 begin
521 fds << (tmp = Tempfile.new(%w"name2ctype .h"))
522 IO.popen([*NAME2CTYPE, out: tmp], "w") {|f| output.show(f, *syms)}
523 end while syms.pop
524 fds.each(&:close)
525 IO.popen(%W[diff -DUSE_UNICODE_AGE_PROPERTIES #{fds[1].path} #{fds[0].path}], "r") {|age|
526 IO.popen(%W[diff -DUSE_UNICODE_PROPERTIES #{fds[2].path} -], "r", in: age) {|f|
527 f.each {|line|
528 line.gsub!(/\(int\)\(long\)&\(\((struct uniname2ctype_pool_t) \*\)0\)->(uniname2ctype_pool_str\d+),\s+/,
529 'offsetof(\1, \2), ')
530 puts line
531 }
532 }
533 }
534 end