-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathre2dfa.py
405 lines (296 loc) · 10.6 KB
/
re2dfa.py
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
from abc import ABC, abstractmethod
from collections import defaultdict
import functools
import itertools
INPUT_FILE = 'regex.in'
OUTPUT_FILE = 'dfa.out'
# Based on http://matt.might.net/articles/parsing-regex-with-recursive-descent/
class Parser:
"""Parses a string as a regular expression and constructs an abstract
syntax tree."""
def __init__(self, input):
self.input = input
self.input_len = len(input)
self.cursor = 0
self.id = 0
@property
def position(self):
return self.cursor + 1
@property
def symbol(self):
return self.input[self.cursor]
def expect(self, expected):
if self.symbol == expected:
self.cursor += 1
else:
raise Exception(f"Expected '{expected}' at {self.position}, " +
"got '{self.symbol}' instead")
def next(self):
"""Consumes the next symbol from the output and returns it."""
sym = self.symbol
self.expect(sym)
return sym
def more(self):
"""Returns true if there still are some characters in the input."""
return self.cursor < self.input_len
def parse(self):
root = self.expression()
if self.cursor != self.input_len:
raise Exception("More input left after expression")
return root
def expression(self):
term = self.term()
if self.more() and self.symbol == '|':
self.expect('|')
rhs = self.expression()
return OrNode(term, rhs)
return term
def term(self):
factor = self.factor()
while self.more() and self.symbol != ')' and self.symbol != '|':
rhs = self.factor()
factor = ConcatNode(factor, rhs)
return factor
def factor(self):
base = self.base()
while self.more() and self.symbol == '*':
self.expect('*')
base = StarNode(base)
return base
def base(self):
sym = self.symbol
if sym == '(':
self.expect('(')
expr = self.expression()
self.expect(')')
return expr
else:
self.id += 1
return SymbolNode(self.id, self.next())
# Based on:
# http://staff.cs.upt.ro/~chirila/teaching/upt/mse11-cd/slides/cd0309.pdf
class Node(ABC):
@property
@abstractmethod
def nullable(self) -> bool:
"""Returns true if lambda is contained in the language
represented by this node's subtree.
"""
@property
@abstractmethod
def first_pos(self) -> frozenset:
"""Returns the set of positions in this subtree which can begin a word
accepted by this subexpression's language.
"""
@property
@abstractmethod
def last_pos(self) -> frozenset:
"""Returns the set of positions in this subtree which can end a word
accepted by this subexpression's language.
"""
@property
@abstractmethod
def alphabet(self) -> frozenset:
"""Returns the set of symbols which appear in this subtree."""
def compute_follow_pos(self, follow_pos) -> None:
"""Computes the follow positions of this subtree recursively."""
def compute_follow_union(self, follow_pos, union, state, symbol) -> None:
"""Computes the union of possible follow positions for all the states
in a superstate, through the given symbol."""
class SymbolNode(Node):
"""Leaf node of the AST, generated by a literal symbol in the input regex,
corresponding to an important position in the final DFA.
"""
def __init__(self, position, symbol):
assert len(symbol) == 1, "Symbol should be only 1 character"
self.position = position
self.symbol = symbol
def is_lambda(self):
return self.symbol == '.'
@property
def nullable(self):
return self.is_lambda()
@property
def first_pos(self):
return frozenset() if self.is_lambda() else frozenset((self.position,))
@property
def last_pos(self):
return frozenset() if self.is_lambda() else frozenset((self.position,))
@property
def alphabet(self):
return frozenset() if self.is_lambda() else frozenset((self.symbol,))
def compute_follow_union(self, follow_pos, union, state, symbol):
if self.position in state and self.symbol == symbol:
union |= follow_pos[self.position]
def __repr__(self):
return self.symbol
class OrNode(Node):
"""Node representing the disjunction between its left and right child."""
def __init__(self, left, right):
self.left = left
self.right = right
@property
def nullable(self):
return self.left.nullable or self.right.nullable
@property
def first_pos(self):
return self.left.first_pos | self.right.first_pos
@property
def last_pos(self):
return self.left.last_pos | self.right.last_pos
@property
def alphabet(self):
return self.left.alphabet | self.right.alphabet
def compute_follow_pos(self, follow_pos):
self.left.compute_follow_pos(follow_pos)
self.right.compute_follow_pos(follow_pos)
def compute_follow_union(self, follow_pos, union, state, symbol):
self.left.compute_follow_union(follow_pos, union, state, symbol)
self.right.compute_follow_union(follow_pos, union, state, symbol)
def __repr__(self):
return f'({self.left}|{self.right})'
class ConcatNode(Node):
"""Concatenates the expression represented by the left subtree with the one
represented by the right subtree.
"""
def __init__(self, left, right):
self.left = left
self.right = right
@property
def nullable(self):
return self.left.nullable and self.right.nullable
@property
def first_pos(self):
if self.left.nullable:
return self.left.first_pos | self.right.first_pos
else:
return self.left.first_pos
@property
def last_pos(self):
if self.right.nullable:
return self.right.last_pos | self.left.last_pos
else:
return self.right.last_pos
@property
def alphabet(self):
return self.left.alphabet | self.right.alphabet
def compute_follow_pos(self, follow_pos):
"""When concatenating two nodes, the last positions"""
for position in self.left.last_pos:
follow_pos[position] |= self.right.first_pos
self.left.compute_follow_pos(follow_pos)
self.right.compute_follow_pos(follow_pos)
def compute_follow_union(self, follow_pos, union, state, symbol):
self.left.compute_follow_union(follow_pos, union, state, symbol)
self.right.compute_follow_union(follow_pos, union, state, symbol)
def __repr__(self):
return f'({self.left}{self.right})'
class StarNode(Node):
"""Node applying the Kleene star to its child node."""
def __init__(self, child):
self.child = child
@property
def nullable(self):
"""Starring always also contains the empty word."""
return True
@property
def first_pos(self):
return self.child.first_pos
@property
def last_pos(self):
return self.child.last_pos
@property
def alphabet(self):
return self.child.alphabet
def compute_follow_pos(self, follow_pos):
# Since a star can contain its child concatenated with another copy
# of its child, the last position of its child can be followed by the
# first position of the other copy of the child.
for position in self.last_pos:
follow_pos[position] |= self.first_pos
self.child.compute_follow_pos(follow_pos)
def compute_follow_union(self, follow_pos, union, state, symbol):
self.child.compute_follow_union(follow_pos, union, state, symbol)
def __repr__(self):
return f'({self.child}*)'
class StateMapper:
"""Dictionary-like class which maps frozen sets of states to
new states with numeric IDs."""
def __init__(self):
counter = itertools.count(1)
self.mappings = defaultdict(lambda: next(counter))
def __getitem__(self, index):
return self.mappings[index]
def final_states(self):
return [
state_id for state, state_id
in self.mappings.items()
if -1 in state
]
def value_list(self):
return list(self.mappings.values())
def regex_to_dfa(root):
"""Builds a DFA which accepts the same language as the regular expression
stored in the abstract syntax tree passed as an argument to this function.
Returns a 5-tuple representing the DFA:
- the set of states
- the alphabet
- the transition function
- the initial state
- the set of final states.
"""
root = ConcatNode(root, SymbolNode(-1, '#'))
follow_pos = defaultdict(lambda: set())
root.compute_follow_pos(follow_pos)
alphabet = root.left.alphabet
visited = set()
queue = [root.first_pos]
transitions = {}
state_mapper = StateMapper()
while queue:
state = queue.pop()
state_id = state_mapper[state]
visited.add(state_id)
for symbol in alphabet:
union = set()
root.compute_follow_union(follow_pos, union, state, symbol)
union = frozenset(union)
union_id = state_mapper[union]
if union_id not in visited:
queue.append(union)
transitions[(state_id, symbol)] = union_id
states = state_mapper.value_list()
alphabet = list(alphabet)
initial_state = 1
final_states = state_mapper.final_states()
return states, alphabet, transitions, initial_state, final_states
def read_regex(file):
"""Reads a regular expression from a given files-like object,
presumed to be in text mode.
Returns the AST of the parsed regex.
"""
line = file.readline().strip()
return Parser(line).parse()
def print_dfa(dfa, file):
"""Prints the 5-tuple representing a DFA to a file-like object.
"""
states, alphabet, transitions, initial_state, final_states = dfa
fprint = functools.partial(print, file=file)
fprint(len(states))
fprint(*states, sep=' ')
fprint(len(alphabet))
fprint(*alphabet, sep=' ')
fprint(initial_state)
fprint(len(final_states))
fprint(*final_states, sep=' ')
fprint(len(transitions))
for (start, symbol), end in transitions.items():
fprint(start, symbol, end, sep=' ')
def main():
with open(INPUT_FILE, 'r') as f:
re = read_regex(f)
dfa = regex_to_dfa(re)
with open(OUTPUT_FILE, 'w') as f:
print_dfa(dfa, f)
if __name__ == '__main__':
main()