This repository was archived by the owner on Jun 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathreCompiler.py
More file actions
344 lines (304 loc) · 10.8 KB
/
reCompiler.py
File metadata and controls
344 lines (304 loc) · 10.8 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
""" Module re_compile -- compile a regular expression into an FSA
To Do
-----
New features:
- add \-, \~
- add remaining metachars
- char set with ^ as first char will print wrong
- figure out when to print spaces between operators
"""
__author__ = "Oliver Steele <steele@osteele.com>"
import FSA
from types import TupleType
def compileSymbolRE(str):
return SymbolRECompiler(str).toFSA()
class SymbolRECompiler:
EOF = -1
def __init__(self, str, recordSourcePositions=0):
self.str = str
self.recordSourcePositions = recordSourcePositions
def toFSA(self, minimize=1):
self.index = 0
self.nextToken = None
fsa = self.compileExpr()
if self.index < len(self.str):
raise 'extra ' + `')'`
del self.index
fsa.label = self.str
if minimize:
fsa = fsa.minimized()
return fsa
def readChar(self):
if self.index < len(self.str):
c, self.index = self.str[self.index], self.index + 1
return c
def peekChar(self):
if self.index < len(self.str):
return self.str[self.index]
def readToken(self):
token = self.nextToken or self._readNextToken()
self.nextToken = None
return token != self.EOF and token
def peekToken(self):
token = self.nextToken = self.nextToken or self._readNextToken()
#print 'peekToken', token
return token != self.EOF and token
def _readNextToken(self):
c = self.readChar()
if not c:
return self.EOF
elif c in '()|&':
return c
elif c == '.':
return ANY
return c
def skipTokens(self, bag):
while self.peekToken() and self.peekToken() in bag:
self.readToken()
def compileExpr(self):
fsa = FSA.NULL_FSA
while self.peekToken() and self.peekToken() != ')':
fsa = FSA.union(fsa, self.compileConjunction())
self.skipTokens(['|'])
return fsa
def compileConjunction(self):
fsa = None
while self.peekToken() and self.peekToken() not in (')', '|'):
sequence = self.compileSequence()
fsa = fsa and FSA.intersection(fsa, sequence) or sequence
self.skipTokens(['&'])
return fsa
def compileSequence(self):
fsa = FSA.EMPTY_STRING_FSA
while self.peekToken() and self.peekToken() not in (')', '|', '&'):
fsa = FSA.concatenation(fsa, self.compileItem())
return fsa
def compileItem(self):
startPosition = self.index
c = self.readToken()
if c == '(':
fsa = self.compileExpr()
if self.readToken() != ')':
raise "missing ')'"
elif c == '~':
fsa = FSA.complement(self.compileItem())
else:
fsa = FSA.singleton(c, arcMetadata=self.recordSourcePositions and [startPosition])
while self.peekChar() and self.peekChar() in '?*+':
c = self.readChar()
if c == '*':
fsa = FSA.closure(fsa)
elif c == '?':
fsa = FSA.union(fsa, FSA.EMPTY_STRING_FSA)
elif c == '+':
fsa = FSA.iteration(fsa)
else:
raise 'program error'
return fsa
#
# Character REs
#
class CharacterSet:
def __init__(self, ranges):
from types import StringType
if type(ranges) == StringType:
ranges = self.convertString(ranges)
accum = []
# copy, so sort doesn't destroy the arg
for item in ranges:
if type(item) == TupleType:
if len(item) == 1:
accum.append((item, item))
elif len(item) == 2:
accum.append(item)
else:
raise "invalid argument to CharacterSet"
elif type(item) == String:
for c in item:
accum.append((c, c))
else:
raise "invalid argument to CharacterSet"
ranges = accum
ranges.sort()
index = 0
while index < len(ranges) - 1:
[(c0, c1), (c2, c3)] = ranges[index:index + 2]
if c1 >= c2:
ranges[index:index + 2] = [(c0, max(c1, c3))]
else:
index = index + 1
self.ranges = ranges
def __cmp__(self, other):
return cmp(type(self), type(other)) or cmp(self.__class__, other.__class__) or cmp(self.ranges, other.ranges)
def __hash__(self):
return reduce(lambda a, b:a ^ b, map(hash, self.ranges))
def convertString(self, str):
ranges = []
index = 0
while index < len(str):
c0 = c1 = str[index]
index = index + 1
if index + 1 < len(str) and str[index ] == '-':
c1 = str[index + 1]
index = index + 2
ranges.append((c0, c1))
return ranges
def matches(self, c):
for c0, c1 in self.ranges:
if c0 <= c and c <= c1:
return 1
return 0
def complement(self):
results = []
for (_, c0), (c1, _) in map(None, [(None, None)] + self.ranges, self.ranges + [(None, None)]):
i0 = c0 and ord(c0) + 1 or 0
i1 = c1 and ord(c1) - 1 or 255
if i0 <= i1:
results.append((chr(i0), chr(i1)))
if results:
return CharacterSet(results)
def union(self, other):
a = self.complement()
b = other.complement()
if a and b:
c = a.intersection(b)
if c:
return c.complement()
else:
return self.ANY
else:
return a or b
def __add__(self, other):
return self.union(other)
def intersection(self, other):
if self.ranges == other.ranges:
return self
results = []
for (a0, a1) in self.ranges:
for (b0, b1) in other.ranges:
c0 = max(a0, b0)
c1 = min(a1, b1)
if c0 <= c1:
results.append((c0, c1))
results.sort()
if results:
return CharacterSet(results)
def __str__(self):
"""
>>> print CharacterSet([('a', 'a')])
a
>>> print CharacterSet([('a', 'b')])
[ab]
"""
if self == self.ANY:
return '.'
elif not self.ranges:
return '[^.]'
for key, value in METACHARS.items():
if self == value:
return '\\' + key
ranges = self.ranges
if len(ranges) == 1 and ranges[0][0] == ranges[0][1]:
return ranges[0][0]
if ranges[0][0] == chr(0) and ranges[-1][1] == chr(255):
s = str(self.complement())
if s[0] == '[' and s[-1] == ']':
s = s[1:-1]
return '[^' + s + ']'
s = ''
for c0, c1 in ranges:
if c0 == c1 and c0 != '-':
s = s + self.crep(c0)
elif ord(c0) + 1 == ord(c1) and c0 != '-' and c1 != '-':
s = s + "%s%s" % (self.crep(c0), self.crep(c1))
else:
s = s + "%s-%s" % (self.crep(c0), self.crep(c1))
return '[' + s + ']'
def crep(self, c):
return {'\t': '\\t', '\n': '\\n', '\r': '\\r', '\f': '\\f', '\v': '\\v'}.get(c, c)
def __repr__(self):
return '<' + self.__class__.__name__ + ' ' + str(self) + '>'
METACHARS = {
'd': CharacterSet('0-9'),
's': CharacterSet(' \t\n\r\f\v'),
'w': CharacterSet('a-zA-Z0-9')}
METACHARS['D'] = METACHARS['d'].complement()
METACHARS['S'] = METACHARS['s'].complement()
METACHARS['W'] = METACHARS['w'].complement()
CharacterSet.ANY = CharacterSet([(chr(0), chr(255))])
class RECompiler(SymbolRECompiler):
def _readNextToken(self):
c = self.readChar()
if not c:
return self.EOF
elif c in '()|':
return c
elif c == '.':
return CharacterSet.ANY
elif c == '[':
if self.peekChar() == '~':
self.readChar()
return self.readCSetInnards().complement()
else:
return self.readCSetInnards()
elif c == '\\':
c = self.readChar()
if METACHARS.get(c):
return METACHARS.get(c)
elif c == '&':
return c
else:
return CharacterSet([(c,c)])
else:
return CharacterSet([(c,c)])
def readCSetInnards(self):
cset = CharacterSet([])
while 1:
c = self.readChar()
if c == ']':
return cset
if self.peekChar() == '-':
self.readChar()
cset = cset.union(CharacterSet([(c, self.readChar())]))
else:
cset = cset.union(CharacterSet([(c, c)]))
def compileRE(str, minimize=1, recordSourcePositions=0):
return RECompiler(str, recordSourcePositions=recordSourcePositions).toFSA(minimize=minimize)
#
# testing
#
def _printCompiledREs():
print compileRE('a')
print compileRE('ab')
print compileRE('a|b')
print compileRE('abc')
print compileRE('ab*c')
print compileRE('ab?c')
print compileRE('ab+c')
print compileRE('ab|c')
print compileRE('a(b|c)')
#print compileRE('a\&a')
#print compileRE('ab+\&a+b')
#print compileRE('ab*\&a*b')
print compileRE('ab|c?')
print compileRE('ab|bc?')
print compileRE('a?')
print compileRE('abc|acb|bac|bca|cab|cba')
print compileRE('abc|acb|bac|bca|cab|cba', 0).determinized()
print compileRE('abc|acb|bac|bca|cab|cba', 0).determinized()
print compileRE('abc|acb|bac|bca|cab|cba', 0).minimized()
print compileRE('abc|acb|bac|bca|cab', 0).determinized()
print compileRE('a', 0)
print compileRE('a', 0).determinized()
print compileRE('ab', 0).determinized()
print compileRE('a', 0).minimized()
print compileRE('ab', 0).minimized()
print compileRE('a')
print compileRE('a|b', 0).determinized()
print compileRE('a|b', 0).minimized().getArcMetadata()
print compileRE('a|b', 0).minimized()
def _test(reset=0):
import doctest, compileRE
if reset:
doctest.master = None # This keeps doctest from complaining after a reload.
return doctest.testmod(compileRE)