Debian Codegraph @

rpython/rlib/rsre/rsre_char.py

raw symbols SCIP
1 """
2 Character categories and charsets.
3 """
4 import sys
5 from rpython.rlib.rlocale import tolower, toupper, isalnum
6 from rpython.rlib.unroll import unrolling_iterable
7 from rpython.rlib import jit
8 from rpython.rlib.rarithmetic import int_between
9 from rpython.rlib.rsre import rsre_constants as consts
10
11 # Note: the unicode parts of this module require you to call
12 # rsre_char.set_unicode_db() first, to select one of the modules
13 # pypy.module.unicodedata.unicodedb_x_y_z. This allows PyPy to use sre
14 # with the same version of the unicodedb as it uses for
15 # unicodeobject.py. If unset, the RPython program cannot use unicode
16 # matching.
17
18 unicodedb = None # possibly patched by set_unicode_db()
19
20 def set_unicode_db(newunicodedb):
21 # check the validity of the following optimization for the given unicodedb:
22 # for all ascii chars c, getlower(c)/getupper(c) behaves like on ascii
23 # (very unlikely to change, but who knows)
24 if newunicodedb is not None:
25 for i in range(128):
26 assert newunicodedb.tolower(i) == getlower_ascii(i)
27 assert newunicodedb.toupper(i) == getupper_ascii(i)
28 assert newunicodedb.toupper_full(i) == [getupper_ascii(i)]
29 global unicodedb
30 unicodedb = newunicodedb
31
32
33 #### Constants
34
35 if sys.maxint > 2**32:
36 MAXREPEAT = int(2**32 - 1)
37 MAXGROUPS = int(2**31 - 1)
38 else:
39 MAXREPEAT = int(2**31 - 1)
40 MAXGROUPS = int(2**30 - 1)
41
42 # In _sre.c this is bytesize of the code word type of the C implementation.
43 # There it's 2 for normal Python builds and more for wide unicode builds (large
44 # enough to hold a 32-bit UCS-4 encoded character). Since here in pure Python
45 # we only see re bytecodes as Python longs, we shouldn't have to care about the
46 # codesize. But sre_compile will compile some stuff differently depending on the
47 # codesize (e.g., charsets).
48 from rpython.rlib.runicode import MAXUNICODE
49 if MAXUNICODE == 65535 and not consts.V37:
50 CODESIZE = 2
51 else:
52 CODESIZE = 4 # always 4 from py3.7
53
54 copyright = "_sre.py 2.4 Copyright 2005 by Nik Haldimann"
55
56 BIG_ENDIAN = sys.byteorder == "big"
57
58 def getlower_ascii(char_ord):
59 return char_ord + int_between(ord('A'), char_ord, ord('Z') + 1) * (ord('a') - ord('A'))
60
61 def getlower_locale(char_ord):
62 if char_ord < 256: # cheating! Well, CPython does too.
63 char_ord = tolower(char_ord)
64 return char_ord
65
66 def getlower_unicode(char_ord):
67 if char_ord < 128: # shortcut for ascii
68 return getlower_ascii(char_ord)
69 assert unicodedb is not None
70 try:
71 return unicodedb.tolower(char_ord)
72 except KeyError:
73 return char_ord
74
75 def getlower(char_ord, flags):
76 if flags & consts.SRE_FLAG_LOCALE:
77 char_ord = getlower_locale(char_ord)
78 elif flags & consts.SRE_FLAG_UNICODE:
79 char_ord = getlower_unicode(char_ord)
80 else:
81 char_ord = getlower_ascii(char_ord)
82 return char_ord
83
84 def getupper_ascii(char_ord):
85 return char_ord - int_between(ord('a'), char_ord, ord('z') + 1) * (ord('a') - ord('A'))
86
87 def getupper_locale(char_ord):
88 if char_ord < 256: # cheating! Well, CPython does too.
89 char_ord = toupper(char_ord)
90 return char_ord
91
92 def getupper_unicode(char_ord):
93 if char_ord < 128: # shortcut for ascii
94 return getupper_ascii(char_ord)
95 # Note: this is like CPython's sre_upper_unicode(), including for a few
96 # arguments like 0xfb05, whose uppercase is *several letters* in unicode.
97 # We return the first of these letters. That's rather random but no
98 # caller expects a sane result in this case, I think: iscased_unicode()
99 # is fine as long as it returns anything != char_ord in this case.
100 assert unicodedb is not None
101 try:
102 return unicodedb.toupper_full(char_ord)[0]
103 except KeyError:
104 return char_ord
105
106 def getupper(char_ord, flags):
107 if flags & consts.SRE_FLAG_LOCALE:
108 char_ord = getupper_locale(char_ord)
109 elif flags & consts.SRE_FLAG_UNICODE:
110 char_ord = getupper_unicode(char_ord)
111 else:
112 char_ord = getupper_ascii(char_ord)
113 return char_ord
114
115 def iscased_ascii(char_ord): # used by py3.7
116 upper = int_between(ord('A'), char_ord, ord('Z')+1)
117 lower = int_between(ord('a'), char_ord, ord('z')+1)
118 return upper | lower
119
120 def iscased_unicode(char_ord): # used by py3.7
121 # NOTE: this is not unicodedb.iscased(). As per CPython 3.7, it is
122 # something different which---as far as I can tell---doesn't really
123 # have a meaning on its own, but well.
124 return (char_ord != getlower_unicode(char_ord) or
125 char_ord != getupper_unicode(char_ord))
126
127 #### Category helpers
128
129 is_a_word = [(chr(i).isalnum() or chr(i) == '_') for i in range(256)]
130 linebreak = ord("\n")
131 underline = ord("_")
132
133 def is_digit(code):
134 return int_between(48, code, 58)
135
136 def is_uni_digit(code):
137 assert unicodedb is not None
138 try:
139 return unicodedb.isdecimal(code)
140 except KeyError:
141 return False
142
143 def is_space(code):
144 return (code == 32) | int_between(9, code, 14)
145
146 def is_uni_space(code):
147 assert unicodedb is not None
148 try:
149 return unicodedb.isspace(code)
150 except KeyError:
151 return False
152
153 def is_word(code):
154 assert code >= 0
155 return code < 256 and is_a_word[code]
156
157 def is_uni_word(code):
158 assert unicodedb is not None
159 try:
160 return unicodedb.isalnum(code) or code == underline
161 except KeyError:
162 return False
163
164 def is_loc_alnum(code):
165 return code < 256 and isalnum(code)
166
167 def is_loc_word(code):
168 return code == underline or is_loc_alnum(code)
169
170 def is_linebreak(code):
171 return code == linebreak
172
173 def is_uni_linebreak(code):
174 assert unicodedb is not None
175 try:
176 return unicodedb.islinebreak(code)
177 except KeyError:
178 return False
179
180
181 #### Category dispatch
182
183 def category_dispatch(category_code, char_code):
184 for i, (function, negate) in category_dispatch_unroll:
185 if category_code == i:
186 result = function(char_code)
187 if negate:
188 return not result # XXX this might lead to a guard
189 else:
190 return result
191 else:
192 return False
193
194
195 # Maps opcodes to (function, negate) tuples.
196 category_dispatch_table = {
197 consts.CATEGORY_DIGIT: (is_digit, False),
198 consts.CATEGORY_NOT_DIGIT: (is_digit, True),
199 consts.CATEGORY_SPACE: (is_space, False),
200 consts.CATEGORY_NOT_SPACE: (is_space, True),
201 consts.CATEGORY_WORD: (is_word, False),
202 consts.CATEGORY_NOT_WORD: (is_word, True),
203 consts.CATEGORY_LINEBREAK: (is_linebreak, False),
204 consts.CATEGORY_NOT_LINEBREAK: (is_linebreak, True),
205 consts.CATEGORY_LOC_WORD: (is_loc_word, False),
206 consts.CATEGORY_LOC_NOT_WORD: (is_loc_word, True),
207 consts.CATEGORY_UNI_DIGIT: (is_uni_digit, False),
208 consts.CATEGORY_UNI_NOT_DIGIT: (is_uni_digit, True),
209 consts.CATEGORY_UNI_SPACE: (is_uni_space, False),
210 consts.CATEGORY_UNI_NOT_SPACE: (is_uni_space, True),
211 consts.CATEGORY_UNI_WORD: (is_uni_word, False),
212 consts.CATEGORY_UNI_NOT_WORD: (is_uni_word, True),
213 consts.CATEGORY_UNI_LINEBREAK: (is_uni_linebreak, False),
214 consts.CATEGORY_UNI_NOT_LINEBREAK: (is_uni_linebreak, True),
215 }
216 category_dispatch_unroll = unrolling_iterable(sorted(category_dispatch_table.items()))
217
218 ##### Charset evaluation
219
220 @jit.unroll_safe
221 def check_charset(ctx, pattern, ppos, char_code):
222 """Checks whether a character matches set of arbitrary length.
223 The set starts at pattern[ppos]."""
224 negated = False
225 result = False
226 while True:
227 opcode = pattern.pattern[ppos]
228 for i, function in set_dispatch_unroll:
229 if opcode == i:
230 newresult, ppos = function(ctx, pattern, ppos, char_code)
231 result |= newresult
232 break
233 else:
234 if opcode == consts.OPCODE_FAILURE:
235 break
236 elif opcode == consts.OPCODE_NEGATE:
237 negated ^= True
238 ppos += 1
239 else:
240 return False
241 if negated:
242 return not result
243 return result
244
245 def set_literal(ctx, pattern, index, char_code):
246 # <LITERAL> <code>
247 match = pattern.pattern[index+1] == char_code
248 return match, index + 2
249
250 def set_category(ctx, pattern, index, char_code):
251 # <CATEGORY> <code>
252 match = category_dispatch(pattern.pattern[index+1], char_code)
253 return match, index + 2
254
255 def set_charset(ctx, pattern, index, char_code):
256 # <CHARSET> <bitmap> (16 bits per code word)
257 if CODESIZE == 2:
258 match = char_code < 256 and \
259 (pattern.pattern[index+1+(char_code >> 4)] >> (char_code & 15)) & 1
260 return match, index + 17 # skip bitmap
261 else:
262 match = char_code < 256 and \
263 (pattern.pattern[index+1+(char_code >> 5)] >> (char_code & 31)) & 1
264 return match, index + 9 # skip bitmap
265
266 def set_range(ctx, pattern, index, char_code):
267 # <RANGE> <lower> <upper>
268 match = int_between(pattern.pattern[index+1], char_code, pattern.pattern[index+2] + 1)
269 return match, index + 3
270
271 def set_range_ignore(ctx, pattern, index, char_code):
272 # <RANGE_IGNORE> <lower> <upper>
273 # the char_code is already lower cased
274 assert not consts.V37
275 lower = pattern.pattern[index + 1]
276 upper = pattern.pattern[index + 2]
277 match1 = int_between(lower, char_code, upper + 1)
278 match2 = int_between(lower, getupper(char_code, pattern.flags), upper + 1)
279 return match1 | match2, index + 3
280
281 def set_range_uni_ignore(ctx, pattern, index, char_code):
282 # <RANGE_UNI_IGNORE> <lower> <upper>
283 # the char_code is already lower cased
284 lower = pattern.pattern[index + 1]
285 upper = pattern.pattern[index + 2]
286 match1 = int_between(lower, char_code, upper + 1)
287 match2 = int_between(lower, getupper_unicode(char_code), upper + 1)
288 return match1 | match2, index + 3
289
290 def set_bigcharset(ctx, pattern, index, char_code):
291 # <BIGCHARSET> <blockcount> <256 blockindices> <blocks>
292 count = pattern.pattern[index+1]
293 index += 2
294
295 if CODESIZE == 2:
296 # One bytecode is 2 bytes, so contains 2 of the blockindices.
297 # So the 256 blockindices are packed in 128 bytecodes, but
298 # we need to unpack it as a byte.
299 assert char_code < 65536
300 shift = 4
301 else:
302 # One bytecode is 4 bytes, so contains 4 of the blockindices.
303 # So the 256 blockindices are packed in 64 bytecodes, but
304 # we need to unpack it as a byte.
305 if char_code >= 65536:
306 index += 256 / CODESIZE + count * (32 / CODESIZE)
307 return False, index
308 shift = 5
309
310 block = pattern.pattern[index + (char_code >> (shift + 5))]
311
312 block_shift = char_code >> 5
313 if BIG_ENDIAN:
314 block_shift = ~block_shift
315 block_shift &= (CODESIZE - 1) * 8
316 block = (block >> block_shift) & 0xFF
317
318 index += 256 / CODESIZE
319 block_value = pattern.pattern[index+(block * (32 / CODESIZE)
320 + ((char_code & 255) >> shift))]
321 match = (block_value & (1 << (char_code & ((8 * CODESIZE) - 1))))
322 index += count * (32 / CODESIZE) # skip blocks
323 return match, index
324
325 def set_unicode_general_category(ctx, pattern, index, char_code):
326 # Unicode "General category property code" (not used by Python).
327 # A general category is two letters. 'pattern.pattern[index+1]' contains both
328 # the first character, and the second character shifted by 8.
329 # http://en.wikipedia.org/wiki/Unicode_character_property#General_Category
330 # Also supports single-character categories, if the second character is 0.
331 # Negative matches are triggered by bit number 7.
332 assert unicodedb is not None
333 cat = unicodedb.category(char_code)
334 category_code = pattern.pattern[index + 1]
335 first_character = category_code & 0x7F
336 second_character = (category_code >> 8) & 0x7F
337 negative_match = category_code & 0x80
338 #
339 if second_character == 0:
340 # single-character match
341 check = ord(cat[0])
342 expected = first_character
343 else:
344 # two-characters match
345 check = ord(cat[0]) | (ord(cat[1]) << 8)
346 expected = first_character | (second_character << 8)
347 #
348 if negative_match:
349 result = check != expected
350 else:
351 result = check == expected
352 #
353 return result, index + 2
354
355 set_dispatch_table = {
356 consts.OPCODE_CATEGORY: set_category,
357 consts.OPCODE_CHARSET: set_charset,
358 consts.OPCODE_BIGCHARSET: set_bigcharset,
359 consts.OPCODE_LITERAL: set_literal,
360 consts.OPCODE_RANGE: set_range,
361 consts.OPCODE27_RANGE_IGNORE: set_range_ignore,
362 consts.OPCODE37_RANGE_UNI_IGNORE: set_range_uni_ignore,
363 consts.OPCODE_UNICODE_GENERAL_CATEGORY: set_unicode_general_category,
364 }
365 set_dispatch_table.pop(None, None) # remove the OPCODE27_* or OPCODE37_*
366 set_dispatch_unroll = unrolling_iterable(sorted(set_dispatch_table.items()))