-
Notifications
You must be signed in to change notification settings - Fork 3
/
lola.py
executable file
·1389 lines (1158 loc) · 38.2 KB
/
lola.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 python3
# coding: utf-8
#
# Copyright © 2019 Keith Packard <[email protected]>
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
import argparse
import collections
import pprint
import re
import sys
actions_marker = "@@ACTIONS@@"
parse_code = """
static token_t parse_stack[PARSE_STACK_SIZE];
#if PARSE_STACK_SIZE < 256
typedef uint8_t parse_stack_p_t;
#else
#if PARSE_STACK_SIZE < 65536
typedef uint16_t parse_stack_p_t;
#else
typedef uint32_t parse_stack_p_t;
#endif
#endif
#if NON_TERMINAL_SIZE < 256
typedef uint8_t non_terminal_index_t;
#else
#if NON_TERMINAL_SIZE < 65536
typedef uint16_t non_terminal_index_t;
#else
typedef uint32_t non_terminal_index_t;
#endif
#endif
#ifndef PARSE_TABLE_FETCH_TOKEN
#define PARSE_TABLE_FETCH_TOKEN(addr) (*(addr))
#endif
#ifndef PARSE_TABLE_FETCH_INDEX
#define PARSE_TABLE_FETCH_INDEX(addr) (*(addr))
#endif
static CONST token_t *
match_state(token_t terminal, token_t non_terminal)
{
token_key_t terminal_key = terminal;
if (terminal_key >= sizeof(terminal_table) / sizeof(terminal_table[0]))
return 0;
non_terminal_index_t non_term = non_terminal_index(PARSE_TABLE_FETCH_INDEX(&terminal_table[terminal_key]));
for (;;) {
uint8_t i = PARSE_TABLE_FETCH_INDEX(&non_terminal_table[non_term]);
if (i == 0xfe) {
i = PARSE_TABLE_FETCH_INDEX(&non_terminal_table[non_term+1]);
non_term = non_terminal_index(i);
} else if (i == 0xff) {
break;
} else {
CONST token_t *production = &production_table[production_index(i)];
if (PARSE_TABLE_FETCH_TOKEN(production) == non_terminal) {
return production + 1;
}
non_term++;
}
}
return 0;
}
static inline token_t
parse_pop(int *parse_stack_p)
{
if ((*parse_stack_p) == 0)
return TOKEN_NONE;
return parse_stack[--(*parse_stack_p)];
}
static inline bool
parse_push(CONST token_t *tokens, int *parse_stack_p)
{
token_t token;
while ((token = PARSE_TABLE_FETCH_TOKEN(tokens++)) != TOKEN_NONE) {
if ((*parse_stack_p) >= PARSE_STACK_SIZE)
return false;
parse_stack[(*parse_stack_p)++] = token;
}
return true;
}
static inline bool
is_terminal(token_t token)
{
return token < FIRST_NON_TERMINAL;
}
static inline bool
is_action(token_t token)
{
return token >= FIRST_ACTION;
}
static inline bool
is_non_terminal(token_t token)
{
return !is_terminal(token) && !is_action(token);
}
typedef enum {
parse_return_success,
parse_return_syntax,
parse_return_end,
parse_return_oom,
parse_return_error,
} __attribute__((packed)) parse_return_t;
static parse_return_t
parse(void *lex_context)
{
token_t token = TOKEN_NONE;
int parse_stack_p = 0;
#ifdef PARSE_TOP
PARSE_TOP
#endif
parse_stack[parse_stack_p++] = NON_TERMINAL_start;
for (;;) {
token_t top = parse_pop(&parse_stack_p);
if (is_action(top)) {
switch(top) {
@@ACTIONS@@
default:
break;
}
#ifdef PARSE_ACTION_BOTTOM
PARSE_ACTION_BOTTOM;
#endif
continue;
}
if (token == TOKEN_NONE)
token = lex(lex_context);
if (top == TOKEN_NONE) {
if (token != END)
return parse_return_syntax;
return parse_return_success;
}
#ifdef PARSE_DEBUG
{
int i;
#ifdef token_name
printf("%-15s : %s", token_names[token], token_names[top]);
for (i = parse_stack_p-1; i >= 0; i--) {
if (!is_action(parse_stack[i]))
printf(" %s", token_names[parse_stack[i]]);
else
printf(" <%d>", parse_stack[i]);
}
#else
printf("token %d stack %d", token, top);
for (i = parse_stack_p-1; i >= 0; i--)
printf(" %d", parse_stack[i]);
#endif
printf("\\n");
}
#endif
if (is_terminal(top)) {
if (top != token) {
if (token == END)
return parse_return_end;
return parse_return_syntax;
}
token = TOKEN_NONE;
} else {
CONST token_t *tokens = match_state(token, top);
if (!tokens)
return parse_return_syntax;
if (!parse_push(tokens, &parse_stack_p))
return parse_return_oom;
}
}
}
"""
# ll parser table generator
#
# the format of the grammar is:
#
# {"non-terminal": (("SYMBOL", "non-terminal", "@action"), (production), (production)),
# "non-terminal": ((production), (production), (production)),
# }
#
# The start symbol must be named "start", the EOF token must be named "END"
#
end_token="END"
def productions(grammar, non_terminal):
if non_terminal not in grammar:
error("Undefined non-terminal %s" % non_terminal)
return grammar[non_terminal]
# data abstraction
#
# a non terminal is a string starting with lower case
# a terminal is a string starting with upper case
# an action is a string starting with '@'
#
def is_non_terminal(item):
return item[0].islower()
def is_terminal(item):
return item[0].isupper()
def is_action(item):
return item[0] == '@'
def is_null_production(p):
if len(p) == 0:
return True
elif is_action(p[0]):
return is_null_production(p[1:])
else:
return False
start_symbol = "start"
def is_start_symbol(item):
global start_symbol
return item == start_symbol
def head(list):
return list[0]
def rest(list):
return list[1:]
def fprint(msg, end='\n', file=sys.stdout):
file.write(msg)
file.write(end)
def error(msg):
fprint(msg, file=sys.stderr)
exit(1)
#
# generate the first set for the productions
# of a non-terminal
#
def first_set(grammar, non_terminal):
ret=()
for prod in productions(grammar, non_terminal):
if is_null_production(prod):
ret += ((),)
else:
ret += first(grammar, prod)
return ret
first_list = ()
def unique(list):
if not list:
return list
f = head(list)
r = rest(list)
if f in r:
return unique(r)
else:
return (f,) + unique(r)
def delete(elt, list):
ret = ()
for i in list:
if i != elt:
ret = ret + (i,)
return ret
#
# generate the first set for a single symbol This is easy for a
# terminal -- the result is the item itself. For non-terminals, the
# first set is the union of the first sets of all the productions
# that derive the non-terminal
#
# Note that this also checks to see if the grammar is left-recursive.
# This will succeed because a left recursive grammar will always
# re-reference a particular non-terminal when trying to generate a
# first set containing it.
#
def first_for_symbol(grammar, item):
global first_list
if item in first_list:
error("lola: left-recursive grammar for symbol %s" % item)
first_list = (item,) + first_list
ret = False
if is_terminal(item):
ret = (item,)
elif is_non_terminal(item):
set = first_set(grammar, item)
ret = unique(set)
first_list = rest(first_list)
return ret
#
# generate the first list for a production.
#
# the first list is the set of symbols which are legal
# as the first symbols in some possible expansion of the
# production. The cases are simple:
#
# if the (car production) is a terminal, then obviously
# the only possible first symbol is that terminal
#
# Otherwise, generate the first lists for *all* expansions
# of the non-terminal (car production). If that list doesn't
# contain an epsilon production 'nil, the we're done. Otherwise,
# this set must be added to the first set of (cdr production) because
# some of the possible expansions of the production will not have any
# terminals at all from (car production).
#
# Note the crufty use of dictionaries to save old expansion of first
# sets. This is because both ll and follow call first quite often,
# frequently for the same production
#
first_dictionary = {}
def reset_first():
global first_dictionary
global first_list
first_dictionary = {}
first_list = ()
def first(grammar, production):
global first_dictionary
while production and is_action(head(production)):
production = rest(production)
if production in first_dictionary:
ret = first_dictionary[production]
else:
if production:
ret = first_for_symbol(grammar, head(production))
if () in ret:
ret = delete((), ret) + first(grammar, rest(production))
else:
ret = ((),)
first_dictionary[production] = ret
return ret
#
# generate the follow set of a for an item in a particular
# production which derives a particular non-terminal.
#
# This is nil if the production does
# not contain the item.
#
# Otherwise, it is the first set for the portion of the production
# which follows the item -- if that first set contains nil, then the
# follow set also contains the follow set for the non-terminal which
# is derived by the production
#
def follow_in_production(grammar, item, non_terminal, production, non_terminals):
# Find all instances of the item in this production; it
# may be repeated
f = ()
for i in range(len(production)):
if production[i] == item:
f += first(grammar, production[i+1:])
if () in f:
f = delete((), f) + follow(grammar, non_terminal, non_terminals)
return f
#
# loop through the productions of a non-terminal adding
# the follow sets for each one. Note that this will often
# generate duplicate entries -- as possibly many of the
# follow sets for productions will contain the entire follow
# set for the non-terminal
#
def follow_in_non_terminal (grammar, item, non_terminal, non_terminals):
ret = ()
for prod in productions(grammar, non_terminal):
ret += follow_in_production(grammar, item, non_terminal, prod, non_terminals)
return ret
#
# generate the follow set for a particular non-terminal
# The only special case is for the
# start symbol who's follow set also contains the
# end-token
#
follow_dictionary = {}
def reset_follow():
global follow_dictionary
follow_dictionary = {}
#
# A list of in-process follow calls
# Use this to avoid recursing into the same
# non-terminal
#
follow_stack = []
def follow(grammar, item, non_terminals):
global follow_dictionary, follow_stack
if item in follow_dictionary:
ret = follow_dictionary[item]
else:
ret = ()
follow_stack.append(item)
for non_terminal in non_terminals:
if non_terminal not in follow_stack:
ret += follow_in_non_terminal(grammar, item, non_terminal, non_terminals)
follow_stack.pop()
if is_start_symbol(item):
ret = (end_token,) + ret
ret = unique(ret)
follow_dictionary[item] = ret
return ret
#
# this makes an entry in the output list, this is just one
# of many possible formats
#
def make_entry(terminal, non_terminal, production):
return {(terminal, non_terminal): production}
def add_dict(a,b):
for key,value in b.items():
if key in a:
fprint("multiple productions match %r - %r and %r" % (key, value, a[key]), file=sys.stderr)
if len(value) < len(a[key]):
continue
a[key] = value
#
# generate the table entries for a particular production
# this is taken directly from Aho, Ullman and Seti
#
# Note: this function uses dynamic scoping -- both non-terminal
# and non-terminals are expected to have been set by the caller
#
def ll_one_production(grammar, production, non_terminal, non_terminals):
firsts = first(grammar, production)
ret = {}
for f in firsts:
if not f:
follows = follow(grammar, non_terminal, non_terminals)
for f in follows:
add_dict(ret, make_entry(f, non_terminal, production))
elif is_terminal(f):
add_dict(ret, make_entry(f, non_terminal, production))
return ret
#
# generate the table entries for all productions of
# a particular non-terminal
#
def ll_one_non_terminal(grammar, non_terminal, non_terminals):
ret = {}
# print("ll_one_non_terminal %r" % non_terminal)
for p in productions(grammar, non_terminal):
add_dict(ret, ll_one_production(grammar, p, non_terminal, non_terminals))
# print("ll for %r is %r" % (non_terminal, ret))
return ret
#
# generate the table entries for all the non-terminals
#
def ll_non_terminals(grammar, non_terminals):
ret = {}
for non_terminal in non_terminals:
add_dict(ret, ll_one_non_terminal(grammar, non_terminal, non_terminals))
return ret
def get_non_terminals(grammar):
non_terminals = ()
for non_terminal in grammar:
non_terminals += (non_terminal,)
return non_terminals
def get_terminals(grammar):
terminals = ("END",)
for non_terminal, prods in grammar.items():
for prod in prods:
for token in prod:
if is_terminal(token) and not token in terminals:
terminals += (token,)
return terminals
def count_actions(grammar):
actions = 0
for non_terminal, prods in grammar.items():
for prod in prods:
for token in prod:
if is_action(token):
actions += 1
return actions
def compress_action(action):
# trailing comments
action = re.sub("//.*\n", "\n", action)
# embedded comments
action = re.sub("/\\*.*?\\*/", " ", action)
# compress whitespace
action = re.sub("\\s+", " ", action)
# remove leading and trailing whitespace and braces
action = action.strip('@ \t\n{}')
return action
def has_action(actions, action):
for a in actions:
if compress_action(a) == compress_action(action):
return True
return False
def action_sort(action):
return len(compress_action(action))
def get_actions(grammar):
actions = ()
for non_terminal, prods in grammar.items():
for prod in prods:
for token in prod:
if is_action(token) and not has_action(actions, token):
actions += (token,)
return sorted(actions, key=action_sort)
#
# produce a parse table for the given grammar
#
def ll (grammar):
reset_first()
reset_follow()
non_terminals = get_non_terminals(grammar)
return ll_non_terminals(grammar, non_terminals)
def dump_table(table, file=sys.stdout):
fprint("Parse table", file=file)
for key,value in table.items():
fprint("\t%r -> %r" % (key, value), file=file)
def dump_grammar(grammar, file=sys.stdout):
for non_term, prods in grammar.items():
fprint("%-20.20s" % non_term, end='', file=file)
first=True
for prod in prods:
if first:
fprint(":", end='', file=file)
first = False
else:
fprint(" |", end='', file=file)
for token in prod:
fprint(" %s" % token, end='', file=file)
fprint("", file=file)
fprint(" ;", file=file)
grammar = {
start_symbol: (("non-term", start_symbol),
()
),
"non-term" : (("SYMBOL", "@NONTERM", "COLON", "rules", "@RULES", "SEMI"),
),
"rules" : (("rule", "rules-p"),
),
"rules-p" : (("VBAR", "rule", "rules-p"),
(),
),
"rule" : (("symbols", "@RULE"),
),
"symbols" : (("SYMBOL", "@SYMBOL", "symbols"),
(),
),
}
lex_c = False
lex_file = sys.stdin
lex_file_name = "<stdin>"
lex_line = 1
def onec():
global lex_line
global lex_file
c = lex_file.read(1)
if c == '\n':
lex_line = lex_line + 1
return c
def getc():
global lex_c
if lex_c:
c = lex_c
lex_c = False
else:
c = onec()
if c == '#':
while c != '\n':
c = onec()
return c
def ungetc(c):
global lex_c
lex_c = c
lex_value = False
def is_symbol_start(c):
return c.isalpha() or c == '_' or c == '-'
def is_symbol_cont(c):
return is_symbol_start(c) or c.isdigit()
action_lines = {}
def action_line(action):
global action_lines
return action_lines[action]
def mark_action_line(action, line):
global action_lines
action_lines[action] = line
ppsyms = {}
def lex_sym(c):
v = c
while True:
c = getc()
if is_symbol_cont(c):
v += c
else:
ungetc(c)
break;
return v
def define_pp(name):
ppsyms[name] = True
def defined_pp(name):
return name in ppsyms
pp_stack = []
def include_pp():
global pp_stack
return len(pp_stack) == 0 or pp_stack[-1]
def push_pp():
global pp_stack
name = lex_sym(getc())
pp_stack.append(include_pp() and defined_pp(name))
def pop_pp():
global pp_stack
if len(pp_stack):
pp_stack.pop()
def lex():
global lex_value
lex_value = False
while True:
c = getc()
if c == '{':
push_pp()
continue
if c == '}':
pop_pp()
continue
if not include_pp():
continue
if c == '':
return 'END'
if c == '|':
return "VBAR"
if c == ':':
return "COLON"
if c == ';':
return "SEMI"
if c == '@':
v = c
at_line = lex_line
while True:
c = getc()
if c == '':
error("Missing @, token started at line %d" % at_line)
elif c == '@':
c = getc()
if c != '@':
ungetc(c)
break
v += c
lex_value = v
mark_action_line(v, at_line)
return "SYMBOL"
if is_symbol_start(c):
lex_value = lex_sym(c)
return "SYMBOL"
def lola():
global lex_value
global value_stack
# Construct the parser for lola input files
table = ll(grammar)
# Run the lola parser
stack = (start_symbol,)
token = False
result = {}
non_term = False
prod = ()
prods = ()
while True:
if stack:
top = head(stack)
stack = rest(stack)
else:
top = False
if top and is_action(top):
if top == "@NONTERM":
non_term = lex_value
elif top == "@RULES":
result[non_term] = prods
prods = ()
non_term = False
elif top == "@RULE":
prods = prods + (prod,)
prod = ()
elif top == "@SYMBOL":
prod = prod + (lex_value,)
continue
if not token:
token = lex()
# print("token %r top %r stack %r" % (token, top, stack))
if not top:
if token == end_token:
return result
error("parse stack empty at %r" % token)
if is_terminal(top):
if top == token:
token = False
else:
error("%s:%d: parse error. got %r expected %r" % (lex_file_name, lex_line, token, top))
else:
key = (token, top)
if key not in table:
error("%s:%d: parse error at %r %r" % (lex_file_name, lex_line, token, top))
stack = table[key] + stack
def to_c(string):
return string.replace("-", "_")
def action_has_name(action):
return action[1].isalpha()
def action_name(token_values, action):
if action_has_name(action):
action = to_c(action)[1:]
end = action.find(' ')
if end != -1:
action = action[0:end]
return "ACTION_" + action
else:
return "ACTION_%d" % token_values[compress_action(action)]
def action_value(action):
if action_has_name(action):
end = action.find(' ')
if end == -1:
return ""
else:
end = 0
return action[end+1:]
def terminal_name(terminal):
return to_c(terminal)
def terminal_names(terminals):
names = None
for terminal in terminals:
name = terminal_name(terminal)
if names:
names += " " + name
else:
names = name
return names
def non_terminal_name(non_terminal):
return "NON_TERMINAL_" + to_c(non_terminal)
def token_name(token_values, token):
if is_action(token):
return action_name(token_values, token)
elif is_terminal(token):
return terminal_name(token)
else:
return non_terminal_name(token)
def dump_python(grammar, parse_table, file=sys.stdout):
fprint('parse_table = \\', file=file)
pp = pprint.PrettyPrinter(indent=4, stream=file)
pp.pprint(parse_table)
def pad(value, round):
p = value % round
if p != 0:
return round - p
return 0
c_line = 1
def print_c(string, end='\n', file=None):
global c_line
c_line += string.count("\n") + end.count("\n")
fprint(string, file=file, end=end)
def pretty(title, a):
print("%s" % title)
pp = pprint.PrettyPrinter(indent=4, stream=sys.stdout)
pp.pprint(a)
def is_subset(sub,sup):
return set(sub) - set(sup) == set()
def pick_binding(possibles, n):
binding = {}
for sub, supers in possibles.items():
pick = n % len(supers)
n //= len(supers)
binding[sub] = supers[pick]
if n:
return None
return binding
def pick_binding_simple(possibles, indices):
binding = {}
for sub, supers in possibles.items():
pick = indices[sub]
binding[sub] = supers[pick]
return binding
def total_bindings(possibles):
n = 1
for sub, supers in possibles.items():
n *= len(supers)
return n
def lookup_optimized(table, binding, terminal, non_terminal):
terms = (terminal,)
while True:
if not terms in table:
return False
for prod in table[terms]:
if prod[0] == non_terminal:
return prod
if not terms in binding:
return False
terms = binding[terms]
def non_terminal_table(terminals, terminal_map, binding):
table = collections.OrderedDict()
finished = {}
for terminal in terminals:
while True:
terms = (terminal,)
if not terms in terminal_map:
break
if terms in finished:
break
# Now follow that to the end of the list of bindings
while terms in binding and not binding[terms] in finished:
terms = binding[terms]
table[terms] = terminal_map[terms]
finished[terms] = True
for terms, prods in terminal_map.items():
for term in terms:
ts = (term,)
for prod in prods:
if not lookup_optimized(table, binding, term, prod[0]):
if not ts in table:
table[ts] = ()
table[ts] += (prod,)
return table
def prod_size(prod):
return len(prod) + 1
def non_terminal_size(table):
l = 0
for terms, prods in table.items():
l += len(prods) + 2
return l
def optimize(grammar, parse_table, terminals, non_terminals, output):
#
# Walk over the parse table
# and figure out which non-terminal → production
# mappings are shared between terminals
#
non_terminal_map = {}
for terminal in terminals:
for non_terminal in non_terminals:
parse_key = (terminal, non_terminal)
if parse_key in parse_table:
prod = parse_table[parse_key]
prod_key = (non_terminal, prod)
if prod_key not in non_terminal_map:
non_terminal_map[prod_key] = ()
non_terminal_map[prod_key] = non_terminal_map[prod_key] + (terminal,)
# Now flip that over to generate a map from a set of terminals to the
# non-terminal/productions they match
terminal_map = {}
for prod, terms in non_terminal_map.items():
if terms not in terminal_map:
terminal_map[terms] = ()
terminal_map[terms] += (prod,)
possibles = {}
# Build possible terminals mappings for each entry in
# non_terminal_map. This means, for each set of terminals,
# find the list of all supersets
for prod_sub, term_sub in non_terminal_map.items():
for prod_sup, term_sup in non_terminal_map.items():
if term_sub != term_sup and is_subset(term_sub, term_sup):
# add this set to the list of possible first bindings
if not term_sub in possibles:
possibles[term_sub] = ()
if not term_sup in possibles[term_sub]:
possibles[term_sub] = possibles[term_sub] + (term_sup,)