Cache first_sets on the grammar
@@ -732,6 +732,10 @@ def first(grammar):
assert isinstance(grammar, Grammar), \
"grammar parameter should be Grammar instance."
+ if hasattr(grammar, '_first_sets'):
+ # If first sets is already calculated return it
+ return grammar._first_sets
+
first_sets = {}
for t in grammar.terminals.values():
first_sets[t] = set([t])
@@ -761,6 +765,7 @@ def first(grammar):
# we must add EMPTY to the first set of LHS symbol.
first_sets[nonterm].add(EMPTY)
+ grammar._first_sets = first_sets
return first_sets
