-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgrammar.py
1753 lines (1408 loc) · 66.4 KB
/
grammar.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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
epycc - Embedded Python C Compiler
Copyright (C) 2021 Antonio Tejada
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
# See ISO/IEC 9899:1999 Annex A (aka C99) or ISO/IEC 9899:TC2 6.4.1
# See
# Packrat parsers can support left recursion
# http://web.cs.ucla.edu/~todd/research/pepm08.pdf
# Packrat Parsing: Simple, Powerful, Lazy, Linear Time
# https://pdos.csail.mit.edu/~baford/packrat/icfp02/packrat-icfp02.pdf
# Lexer Hack
# https://en.wikipedia.org/wiki/Lexer_hack
# C99 Yacc and Lex
# http://www.quut.com/c/ANSI-C-grammar-l-1999.html
# http://www.quut.com/c/ANSI-C-grammar-y-1999.html
# https://stackoverflow.com/questions/44141686/how-to-make-c-language-context-free
import re
import string
import StringIO
from cstruct import Struct
def vrb(*args):
if (False):
print (args)
def dbg(*args):
print(args)
def get_first(s):
return next(iter(s))
def is_empty(l):
return (len(l) == 0)
def get_char(state):
# Right now this does a simple preprocessing by removing \\n
# XXX Do other standard C preprocessing (macros, etc)
# XXX Keep track of file row and col
c = None
if (state.prec != ''):
c = state.prec
state.prec = ''
else:
while (c is None):
c = state.f.read(1)
if (c == '\\'):
prec = c
c = state.f.read(1)
if (c == '\n'):
c = None
else:
state.prec = prec
print "get_char: ", c
return c
# XXX Could generate numba python to make simpler codegen?
def get_token(state):
s = state.c
m = r.match(s)
mm = None
while (m is not None):
# XXX This could read in chunks
c = get_char(state)
if (c == ''):
return None, None
# print 'read', repr(c)
s += c
mm = m
m = r.match(s)
if (mm is None):
# Unrecognized token
print "unable to match", repr(s)
return Struct(token = None, value = s)
m = mm
state.c = c
return Struct( token = m.lastgroup, value = m.group(0))
def parse_grammar(grammar_text):
"""
Parse a text extracted from the ISO/IEC 9899:1999 pdf Annex "A.1 Lexical
grammar" or "A.2 Phrase structure grammar"
"""
symbols = {}
current_symbol = None
for l in grammar_text:
if (is_empty(l.strip())):
# Allow and ignore empty lines
print "ignoring empty line"
# New symbol starts with parens, otherwise comment
elif (l[0] == "("):
# New symbol
# (6.4.2.1) identifier:
# (6.4.2.1) nondigit: one of
m = re.match(r"\([^)]*\)\s+(?P<name>[^:]+):\s*((?P<none_of>none of)|(?P<one_of>one of))?", l)
assert None is dbg("found symbol", l)
symbol_name = m.group("name")
one_of = m.group("one_of") is not None
none_of = m.group("none_of") is not None
current_symbol = Struct(name=symbol_name, one_of=one_of, none_of=none_of, rules=[])
assert current_symbol not in symbols
symbols[symbol_name] = current_symbol
elif (l[0].isspace()):
# New rules for the current symbol start with whitespace, eg
# identifier-nondigit
# identifier identifier-nondigit
# identifier digit
# XXX Support continuing previous symbol if indentation is larger?
# (the spec does that in two or three rules)
assert None is dbg("found rule", l)
rule_symbols = re.split(r"\s+", l)
if (not(none_of or one_of)):
current_symbol.rules.append([])
for rule_symbol in rule_symbols:
rule_symbol = rule_symbol.decode('string_escape')
if (rule_symbol == "opt"):
# Opt applies to the previous symbol
current_symbol.rules[-1][-1].opt = True
elif (rule_symbol != ""):
# split can return empty strings, ignore those
# "One of" symbols create one rule per rule_symbol
if (none_of or one_of):
# XXX We only support none of single chars, for
# multichar it could be implemented with recursion,
# eg the regexp for none of "*/" is
# r"/\*(([^*]*)\*[^/]*)*\*/" and likewise for nfas
assert (not none_of) or (len(rule_symbol) == 1)
current_symbol.rules.append([])
current_symbol.rules[-1].append(Struct(symbol=rule_symbol, opt=False))
else:
# Comment
print "ignoring comment", repr(l)
return symbols
def build_regexp(symbols, terminal_symbols, symbol_name):
"""
XXX Many of these are not correct and just doodles
A: a A: a opt A: a b A: a opt b
r(A) = a r(A) = a? r(A) = ab r(A) = a?b
A: a A: a A: B
b b B: b
r(A) = "a|b" r(A) = "a|b" r(A) = r(B) = b
A: B C A: B opt C
B: b B: b
C: c C: c
r(A) = r(B)r(C) = bc r(A) = r(B)?r(C) = b?c
A: B A: B opt
C C
B: b B: b
C: c C: c
r(A) = r(B)|r(C) = a|b r(A) = r(B)?|r(C) = b?|c
A: a A: a
A b A b c
r(A) = a|r(A)b = ... = a(b)* r(A) = a(bc)*
A: a A: a
A b A b c
A c A d e
r(A) = a|r(A)b|r(A)c = ... = a|a(b|c)* = (a)(b|c)*
A: a
b c A
r(A) = (bc)*a
A: a
b A c
r(A) = ??
A: a
B
B: A
r(A) = a|r(B) = a|r(A) =
A: one of A: none of
a a
b b
r(A) = a|b r(A) 0 [^ab]
A: one of
ab
cd
r(A) = ab|cd
A: none of
ab
r(A) = (a[^b]|[^a].)
"""
symbol = symbols[symbol_name]
rs = []
rs_recursive = []
for rule in symbol.rules:
ss = ""
recursive = False
for rule_symbol in rule:
if (rule_symbol.symbol in terminal_symbols):
# Don't escape one_of or none_of, since they will be escaped
# after put into sets below and need to be unescaped for the set
# calculation
if (symbol.one_of or symbol.none_of):
ss += rule_symbol.symbol
else:
ss += re.escape(rule_symbol.symbol)
else:
if (rule_symbol.symbol == symbol_name):
# XXX This doesn't support more than one recursion inside
# the same rule (ie must be strictly left recursive)
assert(not recursive)
# XXX Only left recursive grammars supported
assert(ss == "")
# XXX Recursive opts not supported
assert(not rule_symbol.opt)
recursive = True
else:
# Use non-named groups since there's a limit of 100 named
# groups in Python's re module
sss = "(?:%s)" % build_regexp(symbols, terminal_symbols, rule_symbol.symbol)
if (rule_symbol.opt):
sss = "%s?" % sss
ss += sss
if (recursive):
rs_recursive.append(ss)
else:
rs.append(ss)
if (len(rs_recursive) > 0):
# XXX This probably wrong in the general case, it's assuming left
# recursive (will break for right or middle-recursive)
assert(not symbol.one_of and not symbol.none_of)
s = "(?:%s)(?:%s)*" % (string.join(rs, "|"), string.join(rs_recursive, "|"))
else:
if (symbol.one_of or symbol.none_of):
# Compress multiple single chars into set, consecutive into ranges
new_rs = []
ranges = []
prev = None
first = None
for r in sorted(rs):
if (len(r) == 1):
if (prev is None):
ranges.append(re.escape(r))
first = r
else:
if ((ord(r[0]) - ord(prev[0])) == 1):
ranges[-1] = "%s-%s" % (first, re.escape(r))
else:
if (ord(first[0]) - ord(prev[0]) == 1):
# Don't use ranges for just two chars in the
# range
ranges[-1] = re.escape(first)
ranges.append(re.escape(prev))
ranges.append(re.escape(r))
first = r
prev = r
else:
new_rs.append(re.escape(r))
if (len(ranges) > 0):
if (symbol.none_of):
# XXX This only accepts "none of" for single chars, otherwise
# it's ill defined? what does "none of" */ mean, how many
# chars should it match?
assert(len(new_rs) == 0)
# invert the set
fmt = "[^%s]"
else:
fmt = "[%s]"
ranges = fmt % string.join(ranges, "")
new_rs.append(ranges)
rs = new_rs
s = string.join(rs, "|")
# Add the symbol name as debugging info
add_debug_info = False
if (add_debug_info):
# XXX This could use named groups (?P<name>expr) but note that the group
# name must be a valid python identifier (eg cannot contain "-") and
# a group name can only be defined once, but there's one of this for
# every symbol with a rule that uses this symbol_name, so the oher
# occurrences have to be with some incremental count
s = "(?:(?#%s)%s)" % (symbol_name, s)
else:
s = "%s" % s
return s
def create_transition(target, charset=set(), negated=False):
transition = Struct(target=target, charset=set(charset), negated=negated)
return transition
def create_state(name, final = False, transitions = []):
state = Struct(name=name, transitions=list(transitions), final=final)
return state
def create_nfa(first, last):
nfa = Struct(first=first, last=last)
return nfa
# XXX Most of the following build_xxx_nfa functions generate lots of spurious
# lambda transitions for simplicity, remove the unnecessary ones?
def build_string_nfa(s):
# Create first and last dummy states and the nfa for this string
first_state = create_state(name="%s" % s)
last_state = create_state(name="@%s#last" % s)
nfa = create_nfa(first_state, last_state)
# Create one state per char, linking the first dummy state to the first
# char state with a lambda
prev_c = []
prev_state = first_state
for c in s:
state = create_state("%s-%c" % (s, c))
prev_state.transitions.append(create_transition(state, set(prev_c)))
prev_c = [c]
prev_state = state
# Link last char to last dummy state
prev_state.transitions.append(create_transition(nfa.last,set(prev_c)))
return nfa
def build_charset_nfa(name, charset, negated):
# Create first and last dummy states and the nfa for this charset
first_state = create_state(name="%s" % name)
last_state = create_state(name="@%s#last" % name)
nfa = create_nfa(first_state, last_state)
state = create_state("%s" % name)
first_state.transitions.append(create_transition(state))
state.transitions.append(create_transition(last_state, charset, negated))
return nfa
def build_recursive_nfa(name, sub_nfa):
# Link first to last and last to first
first_state = create_state(name="@%s-recursive#first" % name)
last_state = create_state(name="@%s-recursive#last" % name)
nfa = create_nfa(first_state, last_state)
# Link the incoming nfa to the new first and last states
first_state.transitions.append(create_transition(sub_nfa.first))
sub_nfa.last.transitions.append(create_transition(last_state))
# Link the last to first and first to last
first_state.transitions.append(create_transition(last_state))
last_state.transitions.append(create_transition(first_state))
return nfa
def build_concatenation_nfa(name, nfas):
if (len(nfas) == 1):
return nfas[0]
# Link first to last and last to first
first_state = create_state(name="@%s#concatenation-first" % name)
last_state = create_state(name="@%s#concatenation-last" % name)
nfa = create_nfa(first_state, last_state)
for i, sub_nfa in enumerate(nfas[:-1]):
sub_nfa.last.transitions.append(create_transition(nfas[i+1].first))
# Link first to first
first_state.transitions.append(create_transition(nfas[0].first))
# Link last to last
nfas[-1].last.transitions.append(create_transition(last_state))
return nfa
def build_union_nfa(name, nfas):
# Create first and last dummy states and the nfa for this string
first_state = create_state(name="@%s#union-first" % name)
last_state = create_state(name="@%s#union-last" % name)
nfa = create_nfa(first_state, last_state)
for sub_nfa in nfas:
nfa.first.transitions.append(create_transition(sub_nfa.first))
sub_nfa.last.transitions.append(create_transition(nfa.last))
return nfa
def build_optional_nfa(nfa):
# connect first and last states
# XXX Should check there's not a link already?
nfa.first.transitions.append(create_transition(nfa.last))
return nfa
def find_lambda_transitions(first_state):
visited_states = set()
pending_states = set([first_state])
# XXX Should this be a set? the lambda_transition are wrapper objects so it's
# unlikely testing for belonging, etc is useful
lambda_transitions = []
while (len(pending_states) > 0):
state = pending_states.pop()
# Mark early as visited, don't want to add to pending below if it has
# loops
visited_states.add(state)
for t in state.transitions:
if (is_empty(t.charset)):
# XXX This assert shouldn't be necessary, it's just to check
# if there are direct loops
assert(t.target is not state)
assert t not in set([lt.transition for lt in lambda_transitions])
lambda_transitions.append(Struct(source=state, transition=t))
if (t.target not in visited_states):
pending_states.add(t.target)
return lambda_transitions
def remove_lambda_transitions(nfa):
lambda_transitions = find_lambda_transitions(nfa.first)
first_states = set([nfa.first])
while (len(lambda_transitions) > 0):
lambda_transition = lambda_transitions.pop(0)
source, transition = lambda_transition.source, lambda_transition.transition
target = transition.target
# Remove the transition
assert None is vrb(len(lambda_transitions), ": removing transition id", id(transition), "from", source.name, "to", target.name)
source.transitions.remove(transition)
if (source is target):
continue
# append the target transitions to the source, updating the lambda
# transitions table if necessary
for t in target.transitions:
t = create_transition(t.target, t.charset, t.negated)
source.transitions.append(t)
if (is_empty(t.charset)):
assert t not in set([lt.transition for lt in lambda_transitions])
lambda_transitions.append(Struct(source=source, transition=t))
# XXX Remove duplicates in some other way? Have transitions be a set?
source.transitions = list(set(source.transitions))
# mark source as final if target is final
if (target.final):
source.final = True
# mark target as initial if source is initial
if (source in first_states):
first_states.add(target)
# XXX This can generate equivalent states, find a way to remove them?
return first_states
def find_lambda_closure(state):
# lambda closure of a state is that state plus the states it can reach using
# only lambda transitions
lambda_closure = set([state])
pending_states = set([state])
while (len(pending_states) > 0):
state = pending_states.pop()
for t in state.transitions:
if (is_empty(t.charset) and (t.target not in lambda_closure)):
pending_states.add(t.target)
lambda_closure.add(t.target)
return lambda_closure
def nfa_to_dfa(first_state):
"""
Take a lambda NFA/eNFA (NFA with epsilon moves) and convert to DFA.
The states of the DFA will be lambda closures of NFA states.
The transitions of the DFA will be transitions between those the
states in those closures.
1. Set as initial DFA state the lambda closure of the initial NFA state
2. For each character in the input alphabet, collect the NFA states each
NFA state in that closure transitions to (ie non-lambda transitions).
Create a new DFA state with the closure of those NFA states.
3.
4. Continue until there are no new states added to the NFA
5. Mark as final any DFA state that includes a final state of the NFA
"""
# XXX This should be done finding the lambda closures for all the states
# reusing the dependent lambda closure information
def lookup_or_find_lambda_closure(lambda_closures, state):
lambda_closure = lambda_closures.get(state, None)
if (lambda_closure is None):
lambda_closure = find_lambda_closure(state)
lambda_closures[state] = lambda_closure
# We don't need this as a set anymore, convert to tuple for ease of
# hashing into dictionaries, other sets
return tuple(lambda_closure)
lambda_closures = {}
closure_to_dfa_state = {}
first_lambda_closure = lookup_or_find_lambda_closure(lambda_closures, first_state)
# Set a new DFA state as the closure of the NFA state
# XXX Pick the appropriate name:
# - If the closure has a final state, use the name of that final state
# - Otherwise avoid picking a fake node (starting with @) if possible
final_state_node_names = [_.name for _ in first_lambda_closure if _.final ]
non_fake_node_names = [_.name for _ in first_lambda_closure if not(_.name.startswith("@"))]
if (is_empty(final_state_node_names)):
if (is_empty(non_fake_node_names)):
dfa_state_name = first_lambda_closure[0].name
else:
dfa_state_name = non_fake_node_names[0]
else:
# XXX Should this pick the non fake if several exist?
dfa_state_name = final_state_node_names[0]
dfa_state = create_state(
dfa_state_name,
# Final if any state in the lambda closure is final
# XXX This should calculate whether the closure is final when generating
# it rather than after the fact
any([_.final for _ in first_lambda_closure])
)
# XXX Cache this tuple?
closure_to_dfa_state[first_lambda_closure] = dfa_state
pending_closures = [first_lambda_closure]
while (len(pending_closures) > 0):
lambda_closure = pending_closures.pop()
dfa_state = closure_to_dfa_state[lambda_closure]
# Find out the transitions of this DFA state
# the transitions of the closure are the closure of the transitions
# let
# - d() as the transition set
# - alphabet symbol a
# - nfa states q1, q2, ..., qn
# - dfa state A={q1, q2}
# d(A, a) = closure(d({q1, q2}, a)) = closure(d(q1, a) U d(q2, a))
used_chars = set()
char_to_targets = {}
for nfa_state in lambda_closure:
# Collect all the transitions per char
for t in nfa_state.transitions:
if (is_empty(t.charset)):
# Ignore lambda transitions
continue
charset = t.charset
if (t.negated):
# Convert from negated charset to regular
# XXX There should be a better way of doing this by union of
# negated and union of non-negated?
# XXX At least we should be able to not expand if all the
# transitions use negated charsets or all the transitions
# use non-negated?
charset = [chr(i) for i in xrange(256) if chr(i) not in t.charset]
used_chars.update(charset)
for c in charset:
try:
char_to_targets[c].add(t.target)
except KeyError:
char_to_targets[c] = set([t.target])
# Create a DFA state for every char target, ideally merging transitions
# that go to the same target
target_dfa_state_to_transition = {}
for c in used_chars:
# Calculate the closure of the target for this char
targets = char_to_targets[c]
targets_closure = set()
for target in targets:
target_closure = lookup_or_find_lambda_closure(lambda_closures, target)
targets_closure.update(target_closure)
# XXX Cache this tuple?
tuple_targets_closure = tuple(targets_closure)
target_dfa_state = closure_to_dfa_state.get(tuple_targets_closure, None)
if (target_dfa_state is None):
# This is a new state, create it and add to pending
# Add the closure of targets as new DFA state
target_dfa_state = create_state(
# XXX Pick another way of naming the state?
tuple_targets_closure[0].name,
# Final if any state in the lambda closure is final
any([_.final for _ in tuple_targets_closure])
)
pending_closures.append(tuple_targets_closure)
closure_to_dfa_state[tuple_targets_closure] = target_dfa_state
# Add the transition to the state or merge if there's already a
# transition to that dfa state
target_dfa_transition = target_dfa_state_to_transition.get(target_dfa_state, None)
if (target_dfa_transition is None):
# Create a new one
target_dfa_transition = create_transition(target_dfa_state, set(), False)
target_dfa_state_to_transition[target_dfa_state] = target_dfa_transition
dfa_state.transitions.append(target_dfa_transition)
target_dfa_transition.charset.add(c)
# Compact the charset by turning into negated if more than 128 elements
for t in dfa_state.transitions:
if (len(t.charset) > 128):
negated_charset = [chr(i) for i in xrange(256) if chr(i) not in t.charset]
t.negated = True
t.charset.clear()
t.charset.update(negated_charset)
return closure_to_dfa_state[first_lambda_closure]
def build_dot(first_states):
def dot_escape(s):
# Graphviz needs to escape the chars:
# - can't contain "
# - can't contain \
# - can't contain the usual non-printable chars
# Use string_escape plus manual " and \\ escaping
s = s.encode("string_escape")
s = s.replace("\\", "\\\\")
s = s.replace("\"", "\\\"")
return s
l = [ "digraph graphname {" ]
pending_states = set(first_states)
visited_states = set()
while (len(pending_states) > 0):
state = pending_states.pop()
visited_states.add(state)
node_attribs = ['label="%s"' % dot_escape(state.name)]
if (state.final):
# Use double lines for final states
node_attribs.append("peripheries=2")
# Use id's as nodes since different nodes can have the same name when
# used in different parts of the grammar
l.append('%d [%s];' % (id(state), string.join(node_attribs, ",")))
for t in state.transitions:
# label the edge with lambda, single char or the list of chars
if (is_empty(t.charset)):
# λ works for html viewer but gives missing entity erro
# on svg and verbatim in png, use the &# encoding instead which
# works on all
edge_label = "λ"
elif ((len(t.charset) == 1) and not t.negated):
edge_label = dot_escape(str(get_first(t.charset)))
else:
# try to compress the charset
prev = None
ranges = []
for c in sorted(t.charset):
if (prev is None):
ranges.append(dot_escape(c))
first = c
else:
if ((ord(c[0]) - ord(prev[0])) == 1):
ranges[-1] = "%s-%s" % (
dot_escape(first),
dot_escape(c)
)
else:
if (ord(first[0]) - ord(prev[0]) == 1):
# Don't use ranges for just two chars in the
# range
ranges[-1] = dot_escape(first)
ranges.append(dot_escape(prev))
ranges.append(dot_escape(c))
first = c
prev = c
# XXX This could ignore the incoming negated value and pack the
# set as negated/non-negated if it has more than 128 chars?
if (t.negated):
# invert the set
fmt = "[^%s]"
else:
fmt = "[%s]"
edge_label = fmt % string.join(ranges, "")
# Create the edge using the ids as node identifiers
l.append('%d->%d [label="%s"];' % (id(state), id(t.target), edge_label))
if (t.target not in visited_states):
pending_states.add(t.target)
l.append("}")
return string.join(l, "\n")
def create_nfa_builder(symbols, terminal_symbols):
return Struct(nfa_stack = dict(), symbols = symbols, terminal_symbols = terminal_symbols)
def build_nfa(nfa_builder, symbol_name):
# XXX This works for lexical grammars, but the phrase structure grammar has
# a lot of recursion which causes combinatory explosion when inlining
# the eNFAs, since every path ends up inlining the ~50 NFAs of the
# grammar
# It needs some way of referring to smaller eNFAs by reference rather
# than reworking and inlining the smaller eNFA all over again.
# Unfortunately it's not clear how using those eNFAs by reference can be
# preserved when doing eNFA->NFA or eNFA->DFA conversions, maybe some
# kind of closure can be obtained from the NFA by ref?
assert None is dbg("build_nfa", symbol_name)
symbols = nfa_builder.symbols
terminal_symbols = nfa_builder.terminal_symbols
nfa_stack = nfa_builder.nfa_stack
print "stack depth", len( nfa_stack.keys())
if (symbol_name in nfa_stack):
return nfa_stack[symbol_name]
symbol = symbols[symbol_name]
if (symbol.one_of or symbol.none_of):
# "one of" and "none of" rules only have one symbol rule per rule, the
# symbol is a string or a charset
assert all([len(rule) == 1 for rule in symbol.rules])
ones = [rule[0].symbol for rule in symbol.rules]
assert all([one in terminal_symbols for one in ones])
# XXX Grammars are normally good in using "one of" and "none of" rules
# but it's possible they should use them and they don't, have the
# grammar parser catch that case and convert into "one of"/"none of"?
# XXX This assumes "one of" and "none of" are used only on terminal
# symbols, probably the grammar parser should check that
# if all are single chars can use charset nodes, otherwise need to use
# string nodes
if (max([len(one) for one in ones]) == 1):
nfa = build_charset_nfa(symbol.name, ones, symbol.none_of)
else:
nfas = []
for one in ones:
nfas.append(build_string_nfa(one))
nfa = build_union_nfa(symbol.name, nfas)
# These don't need to update the stack since they are terminal
else:
# Create the first and last states even if they are dummy and push the
# nfa to the the stack early, this allows handling the rules much more
# easily (especially in the presence of direct and indirect recursion)
# at the expense of a less compact NFA (but it can be compacted later
# either by removing lambda transitions or converting to DFA)
first_state = create_state(name="%s" % symbol_name)
last_state = create_state(name="@%s#last" % symbol_name)
nfa = create_nfa(first_state, last_state)
nfa_stack[symbol_name] = nfa
union_nfas = []
for rule in symbol.rules:
concatenation_nfas = []
for rule_symbol in rule:
if (rule_symbol.symbol in terminal_symbols):
concatenation_nfa = build_string_nfa(rule_symbol.symbol)
else:
concatenation_nfa = build_nfa(nfa_builder, rule_symbol.symbol)
if (rule_symbol.opt):
concatenation_nfa = build_optional_nfa(concatenation_nfa)
concatenation_nfas.append(concatenation_nfa)
# Don't support empty rules
# XXX Check this at the grammar parsing level?
assert(not is_empty(concatenation_nfas))
union_nfa = build_concatenation_nfa(symbol.name, concatenation_nfas)
union_nfas.append(union_nfa)
all_nfa = build_union_nfa(symbol.name, union_nfas)
# Hook to first and last
nfa.first.transitions.append(create_transition(all_nfa.first))
all_nfa.last.transitions.append(create_transition(nfa.last))
# del nfa_stack[symbol_name]
return nfa
def build_checkable_grammar(symbols, terminal_symbols, start_symbol):
"""
Build a grammar that can be checked at http://smlweb.cpsc.ucalgary.ca/start.html
Following the format at http://smlweb.cpsc.ucalgary.ca/readme.html
head -> RHS1
| RHS2
....
| RHSn.
"""
long_to_short = {}
def escape_checkable(s):
if s not in long_to_short:
if (s[0].isupper()):
long_to_short[s] = "%s%03d" % (s[:3], len(long_to_short))
else:
long_to_short[s] = "a%03d" % len(long_to_short)
s = long_to_short[s]
return s
def escape_non_terminal(s):
# Non-terminal uppercase
return escape_checkable(s.upper())
def escape_terminal(s):
# Terminal go in lowercase
return escape_checkable(s.lower())
l = []
for symbol_name, symbol in symbols.items():
# symbols separated by "\n"
for i, rule in enumerate(symbol.rules):
ll = []
# rules in a symbol by "|" or -> if it's the first rule
if (i == 0):
ll.append("%s -> " % escape_non_terminal(symbol_name))
else:
ll.append(" | ")
for rule_symbol in rule:
# rule symbols by " "
if (rule_symbol.symbol in terminal_symbols):
s = escape_terminal(rule_symbol.symbol)
else:
s = escape_non_terminal(rule_symbol.symbol)
ll.append(s)
if (i == (len(symbol.rules) - 1)):
ll.append(".")
l.append(string.join(ll, " "))
l.append("S -> %s." % escape_non_terminal(start_symbol))
grammar = string.join(l, "\n")
return grammar
def build_lark_grammar(symbols, terminal_symbols, start_symbol):
"""
Return the grammar in Lark format, rules in lowercase, terminals in
uppercase.
Rule prefixes like ! and ? can be used to affect the tree generation
(removing intermediate nodes, tokens, etc), but are not necessary just for
parsing itself
see https://lark-parser.readthedocs.io/en/latest/grammar.html
see https://lark-parser.github.io/ide/#
start: value
value: object
| array
| string
| SIGNED_NUMBER
| "true"
| "false"
| "null"
array : "[" [value ("," value)*] "]"
object : "{" [pair ("," pair)*] "}"
pair : string ":" value
WHITESPACE: (" " | /\t/ | /\n/ )+
%ignore WHITESPACE
"""
long_to_short = {}
def escape_lark(s):
return s
def escape_non_terminal(s):
# Non-terminal lowercase
return escape_lark(s.lower().replace("-", "_"))
def escape_terminal(s):
# Terminal uppercase or in quotation marks
return '"%s"' % escape_lark(s).encode("string_escape").replace('"', '\\"')
l = []
for symbol_name, symbol in symbols.items():
# symbols separated by "\n"
for i, rule in enumerate(symbol.rules):
ll = []
# rules in a symbol separated by "|" or : if it's the first rule
if (i == 0):
ll.append("%s: " % escape_non_terminal(symbol_name))
else:
ll.append(" | ")
for rule_symbol in rule:
# rule symbols separated by " "
if (rule_symbol.symbol in terminal_symbols):
s = escape_terminal(rule_symbol.symbol)
else:
s = escape_non_terminal(rule_symbol.symbol)
if (rule_symbol.opt):
s = s + "?"
ll.append(s)
l.append(string.join(ll, " "))
# Add a few generic rules/terminals/directives
l.append("start: %s" % escape_non_terminal(start_symbol))
# XXX These should be taken from the scanner?
l.extend([
r"WHITESPACE: (/ / | /\t/ | /\n/ | /\r/ )+",
"%ignore WHITESPACE"
])
grammar = string.join(l, "\n")
return grammar
def build_test_nfa(symbols, terminal_symbols):
sub_nfas = []
for keyword in ["char", "int", "case", "break", "breakage"]:
sub_nfa = build_string_nfa(keyword)
sub_nfas.append(sub_nfa)
sub_nfa = build_concatenation_nfa(
"test",
[
build_string_nfa("s"),
build_recursive_nfa(build_string_nfa("tar"))
]
)
sub_nfas.append(sub_nfa)
sub_nfa = build_charset_nfa("identifier", set(string.letters + string.digits))