-
Notifications
You must be signed in to change notification settings - Fork 1
/
core.py
973 lines (834 loc) · 32 KB
/
core.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
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
# The contents of this file are subject to the Mozilla Public License
# (MPL) Version 1.1 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License
# at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and
# limitations under the License.
#
# The Original Code is LEPL (http://www.acooke.org/lepl)
# The Initial Developer of the Original Code is Andrew Cooke.
# Portions created by the Initial Developer are Copyright (C) 2009-2010
# Andrew Cooke (andrew@acooke.org). All Rights Reserved.
#
# Alternatively, the contents of this file may be used under the terms
# of the LGPL license (the GNU Lesser General Public License,
# http://www.gnu.org/licenses/lgpl.html), in which case the provisions
# of the LGPL License are applicable instead of those above.
#
# If you wish to allow use of your version of this file only under the
# terms of the LGPL License and not to allow others to use your version
# of this file under the MPL, indicate your decision by deleting the
# provisions above and replace them with the notice and other provisions
# required by the LGPL License. If you do not delete the provisions
# above, a recipient may use your version of this file under either the
# MPL or the LGPL License.
'''
A simple regular expression engine in pure Python.
This takes a set of regular expressions (only the most basic functionality is
supported) and generates a finite state machines that can match them against
a stream of values.
Although simple (and slow compared to a C version), it has some advantages
from being implemented in Python.
* It can use a variety of alphabets - it is not restricted to strings.
It could, for example, match lists of integers, or sequences of tokens.
* The NFA implementation can yield intermediate matches.
* It is extensible.
The classes here form a layered series of representations for regular
expressions.
The first layer contains the classes `Sequence`, `Option`, `Repeat`, `Choice`,
`Labelled` and `Regexp`. These are a high level representation that will
typically be constructed by an alphabet-specific parser.
The second layer encodes the regular expression as a non-deterministic
finite automaton (NFA) with empty transitions. This is a "natural"
representation of the transitions that can be generated by the first layer.
The third layer encodes the regular expression as a deterministic finite
automaton (DFA). This is a more "machine friendly" representation that allows
for more efficient matching. It is generated by transforming a representation
from the second layer.
'''
from abc import ABCMeta, abstractmethod
from collections import deque
from itertools import chain
from lepl.stream.core import s_next, s_empty, s_line
from lepl.support.graph import ConstructorWalker, clone, Clone
from lepl.support.node import Node
from lepl.regexp.interval import Character, TaggedFragments, IntervalMap,\
_Character
from lepl.support.lib import fmt, basestring, str, LogMixin
# pylint: disable-msg=C0103
# Python 2.6
#class Alphabet(metaclass=ABCMeta):
_Alphabet = ABCMeta('_Alphabet', (object, ), {})
# pylint: disable-msg=E1002
# pylint can't find ABCs
class Alphabet(LogMixin, _Alphabet):
'''
Regular expressions are generalised over alphabets, which describe the set
of acceptable characters.
The characters in an alphabet must have an order, which is defined by
`__lt__` on the character instances themselves (equality and inequality
are also assumed to be defined). In addition, `before(c)` and `after(c)`
below should give the previous and subsequent characters in the ordering
and `min` and `max` should give the two most extreme characters.
Internally, within the routines here, ranges of characters are used.
These are encoded as pairs of values `(a, b)` which are inclusive.
Each pair is called an "interval".
Alphabets include additional methods used for display and may also have
methods specific to a given instance (typically named with an initial
underscore).
'''
def __init__(self, min_, max_):
self.__min = min_
self.__max = max_
super(Alphabet, self).__init__()
@property
def min(self):
'''
The "smallest" character.
'''
return self.__min
@property
def max(self):
'''
The "largest" character.
'''
return self.__max
@abstractmethod
def before(self, c):
'''
Must return the character before c in the alphabet. Never called with
min (assuming input data are in range).
'''
@abstractmethod
def after(self, c):
'''
Must return the character after c in the alphabet. Never called with
max (assuming input data are in range).
'''
@abstractmethod
def fmt_intervals(self, intervals):
'''
This must fully describe the data in the intervals (it is used to
hash the data).
'''
def invert(self, intervals):
'''
Return a list of intervals that describes the complement of the given
interval. Note - the input interval must be ordered (and the result
will be ordered too).
'''
if not intervals:
return [(self.min, self.max)]
inverted = []
(a, last) = intervals[0]
if a != self.min:
inverted.append((self.min, self.before(a)))
for (a, b) in intervals[1:]:
inverted.append((self.after(last), self.before(a)))
last = b
if last != self.max:
inverted.append((self.after(last), self.max))
self._debug(fmt('invert {0} -> {1}', intervals, inverted))
return inverted
def extension(self, text):
'''
This is called for extensions for the form (*NAME) where NAME is any
sequence of capitals. It should return a character range. Further
uses of (*...) are still to be decided.
'''
raise RegexpError(fmt('Extension {0!r} not supported by {1!s}',
text, self.__class__))
@abstractmethod
def fmt_sequence(self, children):
'''
This must fully describe the data in the children (it is used to
hash the data).
'''
@abstractmethod
def fmt_repeat(self, children):
'''
This must fully describe the data in the children (it is used to
hash the data).
'''
@abstractmethod
def fmt_choice(self, children):
'''
This must fully describe the data in the children (it is used to
hash the data).
'''
@abstractmethod
def fmt_option(self, children):
'''
This must fully describe the data in the children (it is used to
hash the data).
'''
@abstractmethod
def fmt_label(self, label, child):
'''
This must fully describe the data in the child (it is used to
hash the data).
'''
@abstractmethod
def join(self, chars):
'''
Join a list of characters into a string (or the equivalent).
'''
@abstractmethod
def parse(self, regexp):
'''
Generate a Sequence from the given regexp text.
'''
class Sequence(Node):
'''
A sequence of Characters, etc.
'''
def __init__(self, alphabet, *children):
assert isinstance(alphabet, Alphabet)
# pylint: disable-msg=W0142
# have to disable this assertion to embed error nodes
# for child in children:
# assert isinstance(child, RegexpGraphNode), type(child)
super(Sequence, self).__init__(*children)
self.alphabet = alphabet
self.state = None
self.__str = self._build_str()
def _build_str(self):
'''
Construct a string representation of self.
'''
return self.alphabet.fmt_sequence(self)
def __str__(self):
return self.__str
def __hash__(self):
return hash(self.__str)
def build(self, graph, before, after):
'''
Connect in sequence.
'''
if self:
src = before
last = self[-1]
for child in self:
dest = after if child is last else graph.new_node()
child.build(graph, src, dest)
src = dest
else:
graph.connect(before, after)
@staticmethod
def __clone(node, args, kargs):
try:
args = list(args)
args.insert(0, node.alphabet)
except AttributeError:
pass
return clone(node, args, kargs)
def clone(self):
return ConstructorWalker(self, RegexpGraphNode)(Clone(self.__clone))
#class RegexpGraphNode(metaclass=ABCMeta):
RegexpGraphNode = ABCMeta('RegexpGraphNode', (object, ), {})
RegexpGraphNode.register(_Character)
RegexpGraphNode.register(Sequence)
class Option(Sequence):
'''
An optional sequence of Characters (or sequences).
'''
def _build_str(self):
'''
Construct a string representation of self.
'''
return self.alphabet.fmt_option(self)
def build(self, graph, before, after):
'''
Connect as sequence and also directly from start to end
'''
super(Option, self).build(graph, before, after)
graph.connect(before, after)
class Empty(Sequence):
'''
Matches an empty sequence.
'''
def _build_str(self):
'''
Construct a string representation of self.
'''
return self.alphabet.fmt_sequence([])
def build(self, graph, before, after):
'''
Connect directly from start to end.
'''
graph.connect(before, after)
class Repeat(Sequence):
'''
A sequence of Characters (or sequences) that can repeat 0 or more times.
'''
def _build_str(self):
'''
Construct a string representation of self.
'''
return self.alphabet.fmt_repeat(self)
def build(self, graph, before, after):
'''
Connect in loop from before to before, and also directly from
start to end.
'''
node = graph.new_node()
graph.connect(before, node)
super(Repeat, self).build(graph, node, node)
graph.connect(node, after)
def Choice(alphabet, *children):
'''
Encase a choice in a sequence so that it can be treated in the same
way as other components (if we don't do this, then passing it to another
sequence will split it into constituents and then sequence them).
'''
return Sequence(alphabet, _Choice(alphabet, *children))
class _Choice(Sequence):
'''
A set of alternative Characters (or sequences).
'''
def _build_str(self):
'''
Construct a string representation of self.
'''
return self.alphabet.fmt_choice(self)
def build(self, graph, before, after):
'''
Connect in parallel from start to end, but add extra nodes so that
the sequence is tried in order (because evaluation tries empty
transitions last) and that loops don't return to start.
'''
if self:
last = self[-1]
for child in self:
# this places numbering first, so empty transition chosen in order
if child is not last:
node = graph.new_node()
child.build(graph, before, after)
if child is not last:
graph.connect(before, node)
before = node
# if self:
# last = self[-1]
# for child in self:
# node = graph.new_node()
# graph.connect(before, node)
# child.build(graph, node, after)
# if child is not last:
# node = graph.new_node()
# graph.connect(before, node)
# before = node
class Labelled(Sequence):
'''
A labelled sequence. Within our limited implementation these are
restricted to (1) being children of Regexp and (2) not being followed
by any other sequence. Their termination defines terminal nodes.
'''
def __init__(self, alphabet, label, *children):
self.label = label
super(Labelled, self).__init__(alphabet, *children)
def _build_str(self):
'''
Construct a string representation of self.
'''
return self.alphabet.fmt_label(self.label,
self.alphabet.fmt_sequence(self))
def build(self, graph, before, after):
'''
A sequence, but with an extra final empty transition to force
any loops before termination.
'''
node = graph.new_node()
super(Labelled, self).build(graph, before, node)
graph.connect(node, after)
graph.terminate(node, [self.label])
class RegexpError(Exception):
'''
An error associated with (problems in) the regexp implementation.
'''
pass
class Compiler(LogMixin):
'''
Compile an expression.
'''
def __init__(self, expression, alphabet):
super(Compiler, self).__init__()
self.expression = expression
self.alphabet = alphabet
def nfa(self):
'''
Generate a NFA-based matcher.
'''
self._debug(fmt('compiling to nfa: {0}', self))
graph = NfaGraph(self.alphabet)
self.expression.build(graph, graph.new_node(), graph.new_node())
self._debug(fmt('nfa graph: {0}', graph))
return NfaPattern(graph, self.alphabet)
def dfa(self):
'''
Generate a DFA-based matcher (faster than NFA, but returns only a
single, greedy match).
'''
self._debug(fmt('compiling to dfa: {0}', self))
ngraph = NfaGraph(self.alphabet)
self.expression.build(ngraph, ngraph.new_node(), ngraph.new_node())
self._debug(fmt('nfa graph: {0}', ngraph))
dgraph = NfaToDfa(ngraph, self.alphabet).dfa
self._debug(fmt('dfa graph: {0}', dgraph))
return DfaPattern(dgraph, self.alphabet)
def re(self):
'''
Generate a matcher that wraps the standard "re" package.
'''
return RePattern(str(self), self.alphabet)
def __str__(self):
'''
Show the expression itself.
'''
return str(self.expression)
@staticmethod
def _coerce(regexp, alphabet):
'''
Coerce to a regexp.
'''
if isinstance(regexp, basestring):
coerced = alphabet.parse(regexp)
if not coerced:
raise RegexpError(fmt('Cannot parse regexp {0!r} using {1}',
regexp, alphabet))
return coerced
else:
return regexp
@staticmethod
def single(alphabet, regexp, label='label'):
'''
Generate an instance for a single expression or sequence.
'''
return Compiler(Labelled(alphabet, label,
*Compiler._coerce(regexp, alphabet)), alphabet)
@staticmethod
def multiple(alphabet, regexps):
'''
Generate an instance for several expressions.
'''
return Compiler(
Choice(alphabet,
*[Labelled(alphabet, label,
*Compiler._coerce(regexp, alphabet))
for (label, regexp) in regexps]), alphabet)
class BaseGraph(object):
'''
Describes a collection of connected nodes.
'''
def __init__(self, alphabet):
super(BaseGraph, self).__init__()
self._alphabet = alphabet
self._next_node = 0
self._transitions = {} # map from source to (dest, edge)
self._terminals = {} # node to label
def terminate(self, node, labels):
'''
Indicate that the node terminates with the given labels.
'''
assert node < self._next_node
if node not in self._terminals:
self._terminals[node] = set()
self._terminals[node].update(labels)
def new_node(self):
'''
Get a new node.
'''
node = self._next_node
self._next_node += 1
return node
def connect(self, src, dest, edge):
'''
Define a connection between src and dest, with an edge
value (a character).
'''
assert src < self._next_node
assert dest < self._next_node
if src not in self._transitions:
self._transitions[src] = []
self._transitions[src].append((dest, edge))
def __iter__(self):
'''
An iterator over all nodes.
'''
return iter(range(self._next_node))
def transitions(self, src):
'''
An iterator over all non-empty transitions from src - returns
(dest, edge) pairs.
'''
return iter(self._transitions.get(src, []))
def terminals(self, node):
'''
An iterator over the terminals for the give node.
'''
return iter(self._terminals.get(node, []))
def __len__(self):
return self._next_node
class NfaGraph(BaseGraph):
'''
Describes a NFA with epsilon (empty) transitions.
'''
def __init__(self, alphabet):
super(NfaGraph, self).__init__(alphabet)
self._empty_transitions = {} # map from source to set(dest)
def new_node(self):
'''
Get a new (unconnected) node.
'''
node = super(NfaGraph, self).new_node()
self._empty_transitions[node] = set()
return node
def connect(self, src, dest, edge=None):
'''
Define a connection between src and dest, with an optional edge
value (a character).
'''
if edge:
super(NfaGraph, self).connect(src, dest, edge)
else:
assert src < self._next_node
assert dest < self._next_node
assert src not in self._terminals, 'Source is terminal'
self._empty_transitions[src].add(dest)
def empty_transitions(self, src):
'''
An iterator over all empty transitions from src.
'''
return iter(self._empty_transitions.get(src, []))
def connected(self, nodes):
'''
Return all nodes connected to the given node.
'''
connected = set()
stack = deque(nodes)
while stack:
src = stack.pop()
connected.add(src)
for dest in self.empty_transitions(src):
if dest not in connected:
connected.add(dest)
stack.append(dest)
return (frozenset(connected),
chain(*[self.terminals(node) for node in connected]))
def terminal(self, node):
'''
The NFA graph has single terminal.
'''
terminals = list(self.terminals(node))
if terminals:
assert len(terminals) == 1, 'Multiple terminals in NFA'
return terminals[0]
else:
return None
def __str__(self):
'''
Example:
0: 3, 4; 1: 2; 2(Tk1); 3: [{u'\x00'}-`b-{u'\U0010ffff'}]->3, 1;
4: {$}->5, 7; 5: 6; 6($); 7: {^}->10; 8: 9; 9(^); 10: 11;
11: [ ]->11, 8
Node 0 leads to 3 and 4 (both empty)
Node 1 leads to 2 (empty)
Node 2 is terminal, labelled with "Tk1"
Node 3 loops back to 3 for a character in the given range, or to 1
etc.
'''
lines = []
for node in self:
edges = []
for (dest, edge) in self.transitions(node):
edges.append(fmt('{0}->{1}', edge, dest))
for dest in self.empty_transitions(node):
edges.append(str(dest))
label = '' if self.terminal(node) is None \
else fmt('({0})', self.terminal(node))
if edges:
lines.append(
fmt('{0}{1}: {2}', node, label, ', '.join(edges)))
else:
lines.append(fmt('{0}{1}', node, label))
return '; '.join(lines)
class NfaPattern(LogMixin):
'''
Given a graph this constructs a transition table and an associated
matcher. The matcher attempts to find longest matches but does not
guarantee termination (if a possible empty match is repeated).
Note that the matcher returns a triple, including label. This is not
the same interface as the matchers used in recursive descent parsing.
Evaluation order for transition:
- Transition with character, if defined
- Empty transition to largest numbered node
these ensure we do deepest match first.
'''
def __init__(self, graph, alphabet):
super(NfaPattern, self).__init__()
self.__graph = graph
self.__alphabet = alphabet
self.__table = {}
self.__build_table()
def __build_table(self):
'''
Rewrite the graph as a transition table, with appropriate ordering.
'''
for src in self.__graph:
# construct an interval map of possible destinations and terminals
# given a character
fragments = TaggedFragments(self.__alphabet)
for (dest, char) in self.__graph.transitions(src):
fragments.append(char, (dest, self.__graph.terminal(dest)))
map_ = IntervalMap()
for (interval, dts) in fragments:
map_[interval] = dts
# collect empty transitions
empties = [(dest, self.__graph.terminal(dest))
# ordering here is reverse of what is required, which
# is ok because we use empties[-1] below
for dest in sorted(self.__graph.empty_transitions(src))]
self.__table[src] = (map_, empties)
def match(self, stream):
'''
Use the table to match a stream.
The stack holds the current state, which is consumed from left to
right. An entry on the stack contains:
- map_ - a map from character to [(dest state, terminals)]
- matched - the [(dest state, terminals)] generated by the map for
a given character
- empties - empty transitions for this state
- match - the current match, as a list of tokens consumed from the
stream
- stream - the current stream
'''
#self._debug(str(self.__table))
stack = deque()
(map_, empties) = self.__table[0]
stack.append((map_, None, empties, [], stream))
while stack:
#self._debug(str(stack))
(map_, matched, empties, match, stream) = stack.pop()
if not map_ and not matched and not empties:
# if we have no more transitions, drop
pass
elif map_:
# re-add empties with old match
stack.append((None, None, empties, match, stream))
# and try matching a character
if not s_empty(stream):
(value, next_stream) = s_next(stream)
try:
matched = map_[value]
if matched:
stack.append((None, matched, None,
match + [value], next_stream))
except IndexError:
pass
elif matched:
(dest, terminal) = matched[-1]
# add back reduced matched
if len(matched) > 1: # avoid discard iteration
stack.append((map_, matched[:-1], empties, match, stream))
# and expand this destination
(map_, empties) = self.__table[dest]
stack.append((map_, None, empties, match, stream))
if terminal:
yield (terminal, self.__alphabet.join(match), stream)
else:
# we must have an empty transition
(dest, terminal) = empties[-1]
# add back reduced empties
if len(empties) > 1: # avoid discard iteration
stack.append((map_, matched, empties[:-1], match, stream))
# and expand this destination
(map_, empties) = self.__table[dest]
stack.append((map_, None, empties, match, stream))
if terminal:
yield (terminal, self.__alphabet.join(match), stream)
def __repr__(self):
return '<NFA>'
class DfaGraph(BaseGraph):
'''
Describes a DFA where each node is a collection of NFA nodes.
'''
def __init__(self, alphabet):
super(DfaGraph, self).__init__(alphabet)
self._dfa_to_nfa = {} # map from dfa node to set(nfa nodes)
self._nfa_to_dfa = {} # map from set(nfa nodes) to dfa nodes
def node(self, nfa_nodes):
'''
Add a node, defined as a set of nfa nodes. If the set already exists,
(False, old node) is returned, with the existing DFA node.
Otherwise (True, new node) is returned.
'''
new = nfa_nodes not in self._nfa_to_dfa
if new:
dfa_node = self.new_node()
self._nfa_to_dfa[nfa_nodes] = dfa_node
self._dfa_to_nfa[dfa_node] = nfa_nodes
return (new, self._nfa_to_dfa[nfa_nodes])
def nfa_nodes(self, node):
'''
An iterator over NFA nodes associated with the given DFA node.
'''
return iter(self._dfa_to_nfa[node])
def __str__(self):
lines = []
for node in self:
edges = []
for (dest, edge) in self.transitions(node):
edges.append(fmt('{0}->{1}', edge, dest))
nodes = [n for n in self.nfa_nodes(node)]
edges = ' ' + ','.join(edges) if edges else ''
labels = list(self.terminals(node))
labels = fmt('({0})', ','.join(str(label) for label in labels)) \
if labels else ''
lines.append(fmt('{0}{1}: {2}{3}', node, labels, nodes, edges))
return '; '.join(lines)
# pylint: disable-msg=R0903
# this is complex enough
class NfaToDfa(object):
'''
Convert a NFA graph to a DFA graph (uses the usual superset approach but
does combination of states in a way that seems to fit better with the idea
of character ranges).
'''
def __init__(self, nfa, alphabet):
super(NfaToDfa, self).__init__()
self.__nfa = nfa
self.__alphabet = alphabet
self.dfa = DfaGraph(alphabet)
self.__build_graph()
def __build_graph(self):
'''
This is the driver for the "usual" superset algorithm - we find
all states that correspond to a DFA state, then look at transitions
to other states. This repeats until we have covered all the
different combinations of NFA states that could occur.
'''
stack = deque() # (dfa node, set(nfa nodes), set(terminals))
# start with initial node
(nfa_nodes, terminals) = self.__nfa.connected([0])
(_, src) = self.dfa.node(nfa_nodes)
stack.append((src, nfa_nodes, terminals))
# continue until all states covered
while stack:
(src, nfa_nodes, terminals) = stack.pop()
self.dfa.terminate(src, terminals)
fragments = self.__fragment_transitions(nfa_nodes)
groups = self.__group_fragments(fragments)
self.__add_groups(src, groups, stack)
def __fragment_transitions(self, nfa_nodes):
'''
From the given nodes we can accumulate the destination nodes and
terminals associated with each transition (edge/character).
At the same time we separate the character matches into non-overlapping
fragments.
'''
fragments = TaggedFragments(self.__alphabet)
for nfa_node in nfa_nodes:
for (dest, edge) in self.__nfa.transitions(nfa_node):
(nodes, terminals) = self.__nfa.connected([dest])
fragments.append(edge, (nodes, list(terminals)))
return fragments
@staticmethod
def __group_fragments(fragments):
'''
For each fragment, we for the complete set of possible destinations
and associated terminals. Since it is possible that more than one
fragment will lead to the same set of target nodes we group all
related fragments together.
'''
# map from set(nfa nodes) to (set(intervals), set(terminals))
groups = {}
for (interval, nts) in fragments:
if len(nts) > 1:
# collect all nodes and terminals for fragment
(nodes, terminals) = (set(), set())
for (n, t) in nts:
nodes.update(n)
terminals.update(t)
nodes = frozenset(nodes)
else:
(nodes, terminals) = nts[0]
if nodes not in groups:
groups[nodes] = (set(), set())
groups[nodes][0].add(interval)
groups[nodes][1].update(terminals)
return groups
def __add_groups(self, src, groups, stack):
'''
The target nfa nodes identified above are now used to create dfa
nodes.
'''
for nfa_nodes in groups:
(intervals, terminals) = groups[nfa_nodes]
char = Character(intervals, self.__alphabet)
(new, dest) = self.dfa.node(nfa_nodes)
self.dfa.connect(src, dest, char)
if new:
stack.append((dest, nfa_nodes, terminals))
class DfaPattern(LogMixin):
'''
Create a lookup table for a DFA and a matcher to evaluate it.
'''
def __init__(self, graph, alphabet):
super(DfaPattern, self).__init__()
self.__graph = graph
self.__alphabet = alphabet
self.__table = [None] * len(graph)
self.__empty_labels = list(graph.terminals(0))
self.__build_table()
def __build_table(self):
'''
Construct a transition table.
'''
for src in self.__graph:
row = IntervalMap()
for (dest, char) in self.__graph.transitions(src):
# use tuple rather than list to allow hashing of tokens!
labels = tuple(self.__graph.terminals(dest))
for interval in char:
row[interval] = (dest, labels)
self.__table[src] = row
def match(self, stream_in):
'''
Match against the stream.
'''
try:
(terminals, size, _) = self.size_match(stream_in)
(value, stream_out) = s_next(stream_in, count=size)
return (terminals, value, stream_out)
except TypeError:
# the matcher returned None
return None
def size_match(self, stream):
'''
Match against the stream, but return the length of the match.
'''
state = 0
size = 0
longest = (self.__empty_labels, 0, stream) \
if self.__empty_labels else None
(line, _) = s_line(stream, True)
while size < len(line):
future = self.__table[state][line[size]]
if future is None:
break
# update state
(state, terminals) = future
size += 1
# match is strictly increasing, so storing the length is enough
# (no need to make an expensive copy)
if terminals:
try:
(_, next_stream) = s_next(stream, count=size)
longest = (terminals, size, next_stream)
except StopIteration:
pass
return longest
def __repr__(self):
return '<DFA>'