forked from exaloop/codon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathre.codon
More file actions
452 lines (367 loc) · 12.9 KB
/
re.codon
File metadata and controls
452 lines (367 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# Copyright (C) 2022 Exaloop Inc. <https://exaloop.io>
# Adapted in part from Google's Python re2 wrapper
# https://github.com/google/re2/blob/abseil/python/re2.py
A = (1 << 0)
ASCII = (1 << 0)
DEBUG = (1 << 1)
I = (1 << 2)
IGNORECASE = (1 << 2)
L = (1 << 3)
LOCALE = (1 << 3)
M = (1 << 4)
MULTILINE = (1 << 4)
S = (1 << 5)
DOTALL = (1 << 5)
X = (1 << 6)
VERBOSE = (1 << 6)
_ANCHOR_NONE = 0
_ANCHOR_START = 1
_ANCHOR_BOTH = 2
@tuple
class Span:
start: int
end: int
def __bool__(self):
return not (self.start == -1 and self.end == -1)
@C
@pure
def seq_re_match(re: cobj,
anchor: int,
string: str,
pos: int,
endpos: int) -> Ptr[Span]:
pass
@C
@pure
def seq_re_match_one(re: cobj,
anchor: int,
string: str,
pos: int,
endpos: int) -> Span:
pass
@C
@pure
def seq_re_pattern_groups(re: cobj) -> int:
pass
@C
@pure
def seq_re_group_name_to_index(re: cobj, name: str) -> int:
pass
@C
@pure
def seq_re_group_index_to_name(re: cobj, index: int) -> str:
pass
@C
@pure
def seq_re_pattern_error(re: cobj) -> str:
pass
@C
@pure
def seq_re_escape(pattern: str) -> str:
pass
@C
def seq_re_purge() -> None:
pass
@C
@pure
def seq_re_compile(pattern: str, flags: int) -> cobj:
pass
class error(Static[Exception]):
pattern: str
def __init__(self, message: str = "", pattern: str = ""):
super().__init__("re.error", message)
self.pattern = pattern
@property
def msg(self):
return self.message
@tuple
class Pattern:
pattern: str
flags: int
_re: cobj
def compile(pattern: str, flags: int = 0):
re = seq_re_compile(pattern, flags)
err_msg = seq_re_pattern_error(re)
if err_msg:
raise error(err_msg, pattern)
return Pattern(pattern, flags, re)
def search(pattern: str, string: str, flags: int = 0):
return compile(pattern, flags).search(string)
def match(pattern: str, string: str, flags: int = 0):
return compile(pattern, flags).match(string)
def fullmatch(pattern: str, string: str, flags: int = 0):
return compile(pattern, flags).fullmatch(string)
def finditer(pattern: str, string: str, flags: int = 0):
return compile(pattern, flags).finditer(string)
def findall(pattern: str, string: str, flags: int = 0):
return compile(pattern, flags).findall(string)
def split(pattern: str, string: str, maxsplit: int = 0, flags: int = 0):
return compile(pattern, flags).split(string, maxsplit)
def sub(pattern: str, repl, string: str, count: int = 0, flags: int = 0):
return compile(pattern, flags).sub(repl, string, count)
def subn(pattern: str, repl, string: str, count: int = 0, flags: int = 0):
return compile(pattern, flags).subn(repl, string, count)
def escape(pattern: str):
return seq_re_escape(pattern)
def purge():
seq_re_purge()
@tuple
class Match:
_spans: Ptr[Span]
pos: int
endpos: int
re: Pattern
string: str
def _get_group_int(self, g: int, n: int):
if not (0 <= g <= n):
raise IndexError("no such group")
return self._spans[g]
def _get_group_str(self, g: str, n: int):
return self._get_group_int(seq_re_group_name_to_index(self.re._re, g), n)
def _get_group(self, g, n: int):
if isinstance(g, int):
return self._get_group_int(g, n)
elif isinstance(g, str):
return self._get_group_str(g, n)
else:
return self._get_group(g.__index__(), n)
def _span_match(self, span: Span):
if not span:
return None
return self.string._slice(span.start, span.end)
def _get_match(self, g, n: int):
span = self._get_group(g, n)
return self._span_match(span)
def _group_multi(self, n: int, *args):
if staticlen(args) == 1:
return (self._get_match(args[0], n),)
else:
return (self._get_match(args[0], n), *self._group_multi(n, *args[1:]))
def group(self, *args):
if staticlen(args) == 0:
return self._get_match(0, 1).__val__()
elif staticlen(args) == 1:
return self._get_match(args[0], self.re.groups)
else:
return self._group_multi(self.re.groups, *args)
def __getitem__(self, g):
return self._get_match(g, self.re.groups)
def start(self, group = 0):
return self._get_group(group, self.re.groups).start
def end(self, group = 0):
return self._get_group(group, self.re.groups).end
def span(self, group = 0):
start, end = self._get_group(group, self.re.groups)
return start, end
def _split(template: str):
backslash = '\\'
pieces = ['']
index = template.find(backslash)
OCTAL = compile(r'\\[0-7][0-7][0-7]')
GROUP = compile(r'\\[1-9][0-9]?|\\g<\w+>')
while index != -1:
piece, template = template[:index], template[index:]
pieces[-1] += piece
octal_match = OCTAL.match(template)
group_match = GROUP.match(template)
if (not octal_match) and group_match:
index = group_match.end()
piece, template = template[:index], template[index:]
pieces.extend((piece, ''))
else:
index = 2
piece, template = template[:index], template[index:]
pieces[-1] += piece
index = template.find(backslash)
pieces[-1] += template
return pieces
def _unescape(s: str):
r = []
n = len(s)
i = 0
while i < n:
if s[i] == '\\' and i + 1 < n:
c = s[i + 1]
if c == 'a':
r.append('\a')
i += 1
elif c == 'b':
r.append('\b')
i += 1
elif c == 'f':
r.append('\f')
i += 1
elif c == 'n':
r.append('\n')
i += 1
elif c == 'r':
r.append('\r')
i += 1
elif c == 't':
r.append('\t')
i += 1
elif c == 'v':
r.append('\v')
i += 1
elif c == '"':
r.append('\"')
i += 1
elif c == '\'':
r.append('\'')
i += 1
elif c == '\\':
r.append('\\')
i += 1
elif '0' <= c <= '7':
k = i + 2
while k < n and k - i <= 4 and '0' <= s[k] <= '7':
k += 1
code = int(s[i+1:k], 8)
p = Ptr[byte](1)
p[0] = byte(code)
r.append(str(p, 1))
i = k - 1
elif c.isalpha():
raise error(f"bad escape \\{c} at position {i}")
else:
r.append(s[i])
else:
r.append(s[i])
i += 1
return str.cat(r)
def expand(self, template: str):
def get_or_empty(s: Optional[str]):
return s if s is not None else ''
pieces = list(Match._split(template))
INT = compile(r'[+-]?\d+')
for index, piece in enumerate(pieces):
if not (index % 2):
pieces[index] = Match._unescape(piece)
else:
if len(piece) <= 3:
pieces[index] = get_or_empty(self[int(piece[1:])])
else:
group = piece[3:-1]
if INT.fullmatch(group):
pieces[index] = get_or_empty(self[int(group)])
else:
pieces[index] = get_or_empty(self[group])
return str.cat(pieces)
@property
def lastindex(self):
max_end = -1
max_group = None
for group in range(1, self.re.groups + 1):
end = self._spans[group].end
if max_end < end:
max_end = end
max_group = group
return max_group
@property
def lastgroup(self):
max_group = self.lastindex
if max_group is None:
return None
return seq_re_group_index_to_name(self.re._re, max_group)
def groups(self, default: Optional[str] = None):
def get_or_default(item, default):
return item if item is not None else default
n = self.re.groups
return [get_or_default(self._span_match(self._spans[i]), default)
for i in range(1, n + 1)]
def groupdict(self, default: Optional[str] = None):
d = {}
for group, index in self.re.groupindex.items():
item = self[index]
d[group] = item if item is not None else default
return d
def __copy__(self):
return self
def __deepcopy__(self):
return self
def __bool__(self):
return True
@extend
class Pattern:
@property
def groups(self):
return seq_re_pattern_groups(self._re)
@property
def groupindex(self):
d = {}
for i in range(1, self.groups + 1):
name = seq_re_group_index_to_name(self._re, i)
if name:
d[name] = i
return d
def _match_one(self, anchor: int, string: str, pos: Optional[int], endpos: Optional[int]):
posx = 0 if pos is None else max(0, min(pos.__val__(), len(string)))
endposx = len(string) if endpos is None else max(0, min(endpos.__val__(), len(string)))
if posx > endposx:
return None
spans = seq_re_match(self._re, anchor, string, posx, endposx)
if not spans[0]:
return None
return Match(spans, posx, endposx, self, string)
def _match(self, anchor: int, string: str, pos: Optional[int], endpos: Optional[int]):
posx = 0 if pos is None else max(0, min(pos.__val__(), len(string)))
endposx = len(string) if endpos is None else max(0, min(endpos.__val__(), len(string)))
if posx > endposx:
return
while True:
spans = seq_re_match(self._re, anchor, string, posx, endposx)
if not spans[0]:
break
yield Match(spans, posx, endposx, self, string)
if posx == endposx:
break
elif posx == spans[0][1]:
# We matched the empty string at pos and would be stuck, so in order
# to make forward progress, increment the bytes offset.
posx += 1
else:
posx = spans[0][1]
def search(self, string: str, pos: Optional[int] = None, endpos: Optional[int] = None):
return self._match_one(_ANCHOR_NONE, string, pos, endpos)
def match(self, string: str, pos: Optional[int] = None, endpos: Optional[int] = None):
return self._match_one(_ANCHOR_START, string, pos, endpos)
def fullmatch(self, string: str, pos: Optional[int] = None, endpos: Optional[int] = None):
return self._match_one(_ANCHOR_BOTH, string, pos, endpos)
def finditer(self, string: str, pos: Optional[int] = None, endpos: Optional[int] = None):
return self._match(_ANCHOR_NONE, string, pos, endpos)
def findall(self, string: str, pos: Optional[int] = None, endpos: Optional[int] = None):
return [m.group() for m in self.finditer(string, pos, endpos)]
def _split(self, cb, string: str, maxsplit: int = 0, T: type = str):
if maxsplit < 0:
return [T(string)], 0
pieces: List[T] = []
end = 0
numsplit = 0
for match in self.finditer(string):
if (maxsplit > 0 and numsplit >= maxsplit):
break
pieces.append(string[end:match.start()])
pieces.extend(cb(match))
end = match.end()
numsplit += 1
pieces.append(string[end:])
return pieces, numsplit
def split(self, string: str, maxsplit: int = 0):
cb = lambda match: [match[group] for group in range(1, self.groups + 1)]
pieces, _ = self._split(cb, string, maxsplit, Optional[str])
return pieces
def _repl(match, repl):
if isinstance(repl, str):
return match.expand(repl)
else:
return repl(match)
def subn(self, repl, string: str, count: int = 0):
cb = lambda match: [Pattern._repl(match, repl)]
pieces, numsplit = self._split(cb, string, count, str)
joined_pieces = str.cat(pieces)
return joined_pieces, numsplit
def sub(self, repl, string: str, count: int = 0):
joined_pieces, _ = self.subn(repl, string, count)
return joined_pieces
def __bool__(self):
return True