Debian Codegraph @

src/index/gen_index.py

raw symbols SCIP
1 # This is a part of rust-encoding.
2 # Copyright (c) 2013-2015, Kang Seonghoon.
3 # See README.md and LICENSE.txt for details.
4
5 import urllib
6 import sys
7 import os.path
8
9 def whatwg_index(name, comments):
10 for line in urllib.urlopen('http://encoding.spec.whatwg.org/index-%s.txt' % name):
11 line = line.strip()
12 if not line: continue
13 if line.startswith('#'):
14 comments.append('//' + line[1:])
15 continue
16 parts = line.split(None, 2)
17 key = int(parts[0], 0)
18 value = int(parts[1], 0)
19 yield key, value
20
21 def mkdir_and_open(crate, name):
22 dirname = os.path.join(os.path.dirname(__file__), crate)
23 try:
24 os.mkdir(dirname)
25 except Exception:
26 pass
27 return open(os.path.join(dirname, '%s.rs' % name.replace('-', '_')), 'wb')
28
29 def write_header(f, name, comments):
30 print >>f, '// AUTOGENERATED FROM index-%s.txt, ORIGINAL COMMENT FOLLOWS:' % name
31 print >>f, '//'
32 for line in comments:
33 print >>f, line
34
35 def write_comma_separated(f, prefix, l, width=80):
36 buffered = ''
37 for i in l:
38 i = str(i)
39 if len(prefix) + len(buffered) + len(i) <= width:
40 buffered += i
41 else:
42 print >>f, prefix + buffered.rstrip()
43 buffered = i
44 if buffered:
45 print >>f, prefix + buffered.rstrip()
46
47 def make_minimal_trie(invdata, lowerlimit=0x10000):
48 maxvalue = max(invdata.keys()) + 1
49 best = 0xffffffff
50 besttrie = None
51 for triebits in xrange(21):
52 lower = [None] * (1<<triebits)
53 upper = []
54 lowermap = {tuple(lower): 0}
55 for i in xrange(0, maxvalue, 1<<triebits):
56 blk = [invdata.get(j) for j in xrange(i, i + (1<<triebits))]
57 loweridx = lowermap.get(tuple(blk))
58 if loweridx is None:
59 loweridx = len(lower)
60 lowermap[tuple(blk)] = loweridx
61 lower += blk
62 upper.append(loweridx)
63 if len(lower) < lowerlimit and best >= len(lower) + len(upper):
64 best = len(lower) + len(upper)
65 besttrie = (triebits, lower, upper)
66 return besttrie
67
68 def generate_single_byte_index(crate, name):
69 modname = name.replace('-', '_')
70
71 data = [None] * 128
72 invdata = {}
73 comments = []
74 for key, value in whatwg_index(name, comments):
75 assert 0 <= key < 128 and 0 <= value < 0xffff and data[key] is None and value not in invdata
76 data[key] = value
77 invdata[value] = key
78
79 # generate a trie with a minimal amount of data
80 triebits, lower, upper = make_minimal_trie(invdata, lowerlimit=0x10000)
81
82 with mkdir_and_open(crate, name) as f:
83 write_header(f, name, comments)
84 print >>f
85 print >>f, "static FORWARD_TABLE: &'static [u16] = &["
86 write_comma_separated(f, ' ',
87 ['%d, ' % (0xffff if value is None else value) for value in data])
88 print >>f, '];'
89 print >>f
90 print >>f, '/// Returns the index code point for pointer `code` in this index.'
91 print >>f, '#[inline]'
92 print >>f, 'pub fn forward(code: u8) -> u16 {'
93 print >>f, ' FORWARD_TABLE[(code - 0x80) as usize]'
94 print >>f, '}'
95 print >>f
96 print >>f, "static BACKWARD_TABLE_LOWER: &'static [u8] = &["
97 write_comma_separated(f, ' ', ['%d, ' % (0 if v is None else v+0x80) for v in lower])
98 print >>f, '];'
99 print >>f
100 print >>f, "static BACKWARD_TABLE_UPPER: &'static [u16] = &["
101 write_comma_separated(f, ' ', ['%d, ' % v for v in upper])
102 print >>f, '];'
103 print >>f
104 print >>f, '/// Returns the index pointer for code point `code` in this index.'
105 print >>f, '#[inline]'
106 print >>f, 'pub fn backward(code: u32) -> u8 {'
107 print >>f, ' let offset = (code >> %d) as usize;' % triebits
108 print >>f, ' let offset = if offset < %d {BACKWARD_TABLE_UPPER[offset] as usize} else {0};' % len(upper)
109 print >>f, ' BACKWARD_TABLE_LOWER[offset + ((code & %d) as usize)]' % ((1<<triebits)-1)
110 print >>f, '}'
111 print >>f
112 print >>f, '#[cfg(test)]'
113 print >>f, 'single_byte_tests!('
114 print >>f, ' mod = %s' % modname
115 print >>f, ');'
116
117 return 2 * len(data) + len(lower) + 2 * len(upper)
118
119 def generate_multi_byte_index(crate, name):
120 modname = name.replace('-', '_')
121
122 data = {}
123 invdata = {}
124 dups = []
125 comments = []
126 morebits = False
127 for key, value in whatwg_index(name, comments):
128 assert 0 <= key < 0xffff and 0 <= value < 0x110000 and value != 0xffff and key not in data
129 if value >= 0x10001:
130 assert (value >> 16) == 2
131 morebits = True
132 data[key] = value
133 if value not in invdata:
134 invdata[value] = key
135 else:
136 dups.append(key)
137
138 # Big5 has four two-letter forward mappings, we use special entries for them
139 if name == 'big5':
140 specialidx = [1133, 1135, 1164, 1166]
141 assert all(key not in data for key in specialidx)
142 assert all(value not in invdata for value in xrange(len(specialidx)))
143 for value, key in enumerate(specialidx):
144 data[key] = value
145 dups.append(key) # no consistency testing for them
146
147 # generate a trie with a minimal amount of data
148 triebits, lower, upper = make_minimal_trie(invdata, lowerlimit=0x10000)
149
150 # JIS X 0208 index has two ranges [8272,8836) and [8836,11280) to support two slightly
151 # different encodings EUC-JP and Shift_JIS; the default backward function would favor
152 # the former, so we need a separate mapping for the latter.
153 #
154 # fortunately for us, all allocated codes in [8272,8836) have counterparts in others,
155 # so we only need a smaller remapping from [8272,8836) to other counterparts.
156 remap = None
157 if name == 'jis0208':
158 REMAP_MIN = 8272
159 REMAP_MAX = 8835
160
161 invdataminusremap = {}
162 for key, value in data.items():
163 if value not in invdataminusremap and not REMAP_MIN <= key <= REMAP_MAX:
164 invdataminusremap[value] = key
165
166 remap = []
167 for i in xrange(REMAP_MIN, REMAP_MAX+1):
168 if i in data:
169 assert data[i] in invdataminusremap
170 value = invdataminusremap[data[i]]
171 assert value < 0x10000
172 remap.append(value)
173 else:
174 remap.append(0xffff)
175
176 minkey = min(data)
177 maxkey = max(data) + 1
178 with mkdir_and_open(crate, name) as f:
179 write_header(f, name, comments)
180 print >>f
181 print >>f, "static FORWARD_TABLE: &'static [u16] = &["
182 write_comma_separated(f, ' ',
183 ['%d, ' % (data.get(key, 0xffff) & 0xffff) for key in xrange(minkey, maxkey)])
184 print >>f, '];'
185 if morebits:
186 print >>f
187 print >>f, "static FORWARD_TABLE_MORE: &'static [u32] = &["
188 bits = []
189 for i in xrange(minkey, maxkey, 32):
190 v = 0
191 for j in xrange(32):
192 v |= (data.get(i+j, 0) >= 0x10000) << j
193 bits.append(v)
194 write_comma_separated(f, ' ', ['%d, ' % v for v in bits])
195 print >>f, '];'
196 print >>f
197 print >>f, '/// Returns the index code point for pointer `code` in this index.'
198 print >>f, '#[inline]'
199 print >>f, 'pub fn forward(code: u16) -> u32 {'
200 if minkey != 0:
201 print >>f, ' let code = (code as usize).wrapping_sub(%d);' % minkey
202 else:
203 print >>f, ' let code = code as usize;'
204 print >>f, ' if code < %d {' % (maxkey - minkey)
205 if morebits:
206 print >>f, ' (FORWARD_TABLE[code] as u32) | ' + \
207 '(((FORWARD_TABLE_MORE[code >> 5] >> (code & 31)) & 1) << 17)'
208 else:
209 print >>f, ' FORWARD_TABLE[code] as u32'
210 print >>f, ' } else {'
211 print >>f, ' 0xffff'
212 print >>f, ' }'
213 print >>f, '}'
214 print >>f
215 print >>f, "static BACKWARD_TABLE_LOWER: &'static [u16] = &["
216 write_comma_separated(f, ' ', ['%d, ' % (0xffff if v is None else v) for v in lower])
217 print >>f, '];'
218 print >>f
219 print >>f, "static BACKWARD_TABLE_UPPER: &'static [u16] = &["
220 write_comma_separated(f, ' ', ['%d, ' % v for v in upper])
221 print >>f, '];'
222 if remap:
223 print >>f
224 print >>f, "static BACKWARD_TABLE_REMAPPED: &'static [u16] = &["
225 write_comma_separated(f, ' ', ['%d, ' % v for v in remap])
226 print >>f, '];'
227 print >>f
228 print >>f, '/// Returns the index pointer for code point `code` in this index.'
229 print >>f, '#[inline]'
230 print >>f, 'pub fn backward(code: u32) -> u16 {'
231 print >>f, ' let offset = (code >> %d) as usize;' % triebits
232 print >>f, ' let offset = if offset < %d {BACKWARD_TABLE_UPPER[offset] as usize} else {0};' % len(upper)
233 print >>f, ' BACKWARD_TABLE_LOWER[offset + ((code & %d) as usize)]' % ((1<<triebits)-1)
234 print >>f, '}'
235 if remap:
236 print >>f
237 assert name == 'jis0208'
238 print >>f, '/// Returns the index shift_jis pointer for code point `code`.'
239 print >>f, '#[inline]'
240 print >>f, 'pub fn backward_remapped(code: u32) -> u16 {'
241 print >>f, ' let value = backward(code);'
242 print >>f, ' if %d <= value && value <= %d {' % (REMAP_MIN, REMAP_MAX)
243 print >>f, ' BACKWARD_TABLE_REMAPPED[(value - %d) as usize]' % REMAP_MIN
244 print >>f, ' } else {'
245 print >>f, ' value'
246 print >>f, ' }'
247 print >>f, '}'
248 print >>f
249 print >>f, '#[cfg(test)]'
250 print >>f, 'multi_byte_tests!('
251 print >>f, ' mod = %s,' % modname
252 if remap:
253 print >>f, ' remap = [%d, %d],' % (REMAP_MIN, REMAP_MAX)
254 if dups:
255 print >>f, ' dups = ['
256 write_comma_separated(f, ' ', ['%d, ' % v for v in sorted(dups)])
257 print >>f, ' ]'
258 else:
259 print >>f, ' dups = []'
260 print >>f, ');'
261
262 tablesz = 2 * (maxkey - minkey) + 2 * len(lower) + 2 * len(upper)
263 if morebits: tablesz += 4 * ((maxkey - minkey + 31) // 32)
264 if remap: tablesz += 2 * len(remap)
265 return tablesz
266
267 def generate_multi_byte_range_lbound_index(crate, name):
268 modname = name.replace('-', '_')
269
270 data = []
271 comments = []
272 for key, value in whatwg_index(name, comments):
273 data.append((key, value))
274 assert data and data == sorted(data)
275
276 minkey, minvalue = data[0]
277 maxkey, maxvalue = data[-1]
278 if data[0] != (0, 0):
279 data.insert(0, (0, 0))
280 maxlog2 = 0
281 while 2**(maxlog2 + 1) <= len(data):
282 maxlog2 += 1
283
284 if name == 'gb18030-ranges':
285 keyubound = 0x110000
286 valueubound = 126 * 10 * 126 * 10
287 else:
288 keyubound = maxkey + 1
289 valueubound = maxvalue + 1
290
291 with mkdir_and_open(crate, name) as f:
292 write_header(f, name, comments)
293 print >>f
294 print >>f, "static FORWARD_TABLE: &'static [u32] = &["
295 write_comma_separated(f, ' ', ['%d, ' % value for key, value in data])
296 print >>f, '];'
297 print >>f
298 print >>f, "static BACKWARD_TABLE: &'static [u32] = &["
299 write_comma_separated(f, ' ', ['%d, ' % key for key, value in data])
300 print >>f, '];'
301 print >>f
302 print >>f, '/// Returns the index code point for pointer `code` in this index.'
303 print >>f, '#[inline]'
304 print >>f, 'pub fn forward(code: u32) -> u32 {'
305 if minkey > 0:
306 print >>f, ' if code < %d { return 0xffffffff; }' % minkey
307 if name == 'gb18030-ranges': # has "invalid" region inside
308 print >>f, ' if (code > 39419 && code < 189000) || code > 1237575 { return 0xffffffff; }'
309 print >>f, ' let mut i = if code >= BACKWARD_TABLE[%d] {%d} else {0};' % \
310 (2**maxlog2 - 1, len(data) - 2**maxlog2 + 1)
311 for i in xrange(maxlog2-1, -1, -1):
312 print >>f, ' if code >= BACKWARD_TABLE[i%s] { i += %d; }' % \
313 ('+%d' % (2**i-1) if i > 0 else '', 2**i)
314 print >>f, ' (code - BACKWARD_TABLE[i-1]) + FORWARD_TABLE[i-1]'
315 print >>f, '}'
316 print >>f
317 print >>f, '/// Returns the index pointer for code point `code` in this index.'
318 print >>f, '#[inline]'
319 print >>f, 'pub fn backward(code: u32) -> u32 {'
320 if minvalue > 0:
321 print >>f, ' if code < %d { return 0xffffffff; }' % minvalue
322 print >>f, ' let mut i = if code >= FORWARD_TABLE[%d] {%d} else {0};' % \
323 (2**maxlog2 - 1, len(data) - 2**maxlog2 + 1)
324 for i in xrange(maxlog2-1, -1, -1):
325 print >>f, ' if code >= FORWARD_TABLE[i%s] { i += %d; }' % \
326 ('+%d' % (2**i-1) if i > 0 else '', 2**i)
327 print >>f, ' (code - FORWARD_TABLE[i-1]) + BACKWARD_TABLE[i-1]'
328 print >>f, '}'
329 print >>f
330 print >>f, '#[cfg(test)]'
331 print >>f, 'multi_byte_range_tests!('
332 print >>f, ' mod = %s,' % modname
333 print >>f, ' key = [%d, %d], key < %d,' % (minkey, maxkey, keyubound)
334 print >>f, ' value = [%d, %d], value < %d' % (minvalue, maxvalue, valueubound)
335 print >>f, ');'
336
337 return 8 * len(data)
338
339 INDICES = {
340 'singlebyte/ibm866': generate_single_byte_index,
341 'singlebyte/iso-8859-2': generate_single_byte_index,
342 'singlebyte/iso-8859-3': generate_single_byte_index,
343 'singlebyte/iso-8859-4': generate_single_byte_index,
344 'singlebyte/iso-8859-5': generate_single_byte_index,
345 'singlebyte/iso-8859-6': generate_single_byte_index,
346 'singlebyte/iso-8859-7': generate_single_byte_index,
347 'singlebyte/iso-8859-8': generate_single_byte_index,
348 'singlebyte/iso-8859-10': generate_single_byte_index,
349 'singlebyte/iso-8859-13': generate_single_byte_index,
350 'singlebyte/iso-8859-14': generate_single_byte_index,
351 'singlebyte/iso-8859-15': generate_single_byte_index,
352 'singlebyte/iso-8859-16': generate_single_byte_index,
353 'singlebyte/koi8-r': generate_single_byte_index,
354 'singlebyte/koi8-u': generate_single_byte_index,
355 'singlebyte/macintosh': generate_single_byte_index,
356 'singlebyte/windows-874': generate_single_byte_index,
357 'singlebyte/windows-1250': generate_single_byte_index,
358 'singlebyte/windows-1251': generate_single_byte_index,
359 'singlebyte/windows-1252': generate_single_byte_index,
360 'singlebyte/windows-1253': generate_single_byte_index,
361 'singlebyte/windows-1254': generate_single_byte_index,
362 'singlebyte/windows-1255': generate_single_byte_index,
363 'singlebyte/windows-1256': generate_single_byte_index,
364 'singlebyte/windows-1257': generate_single_byte_index,
365 'singlebyte/windows-1258': generate_single_byte_index,
366 'singlebyte/x-mac-cyrillic': generate_single_byte_index,
367
368 'tradchinese/big5': generate_multi_byte_index,
369 'korean/euc-kr': generate_multi_byte_index,
370 'simpchinese/gb18030': generate_multi_byte_index,
371 'japanese/jis0208': generate_multi_byte_index,
372 'japanese/jis0212': generate_multi_byte_index,
373
374 'simpchinese/gb18030-ranges': generate_multi_byte_range_lbound_index,
375 }
376
377 if __name__ == '__main__':
378 import sys
379 filter = sys.argv[1] if len(sys.argv) > 1 else ''
380 for index, generate in INDICES.items():
381 crate, _, index = index.partition('/')
382 if filter not in index: continue
383 print >>sys.stderr, 'generating index %s...' % index,
384 tablesz = generate(crate, index)
385 print >>sys.stderr, '%d bytes.' % tablesz
386