@@ -32,6 +32,7 @@ def __init__(self, tree, grammarText):
32
32
self .tree = tree
33
33
self .grammarText = grammarText
34
34
self .gensymCounter = 0
35
+ self .compiledExprCache = None
35
36
36
37
37
38
def _generate (self , out , expr , retrn = False , debugname = None ):
@@ -109,9 +110,19 @@ def compilePythonExpr(self, out, expr, debugname=None):
109
110
ast .literal_eval (expr )
110
111
return self ._expr (out , 'python' , '(' + expr + '), None' , debugname )
111
112
except ValueError :
112
- return self ._expr (out , 'python' ,
113
- 'eval(%r, self.globals, _locals), None' % (expr ,),
114
- debugname )
113
+ if self .compiledExprCache is None :
114
+ return self ._expr (out , 'python' ,
115
+ 'eval(%r, self.globals, _locals), None' % (expr ,),
116
+ debugname )
117
+ else :
118
+ if expr in self .compiledExprCache :
119
+ sym = self .compiledExprCache [expr ]
120
+ else :
121
+ sym = self .compiledExprCache [expr ] = self ._gensym ('expr' )
122
+
123
+ return self ._expr (out , 'python' ,
124
+ 'eval(self.%s, self.globals, _locals), None' % (sym ,),
125
+ debugname )
115
126
116
127
def _convertArgs (self , out , rawArgs , debugname ):
117
128
return [self ._generateNode (out , x , debugname ) for x in rawArgs ]
@@ -325,6 +336,7 @@ def generate_Rule(self, prevOut, name, expr, debugname=None):
325
336
326
337
def generate_Grammar (self , out , name , takesTreeInput , rules ,
327
338
debugname = None ):
339
+ self .compiledExprCache = {}
328
340
self .takesTreeInput = takesTreeInput .tag .name == 'true'
329
341
out .writeln ("def createParserClass(GrammarBase, ruleGlobals):" )
330
342
funcOut = out .indent ()
@@ -338,6 +350,8 @@ def generate_Grammar(self, out, name, takesTreeInput, rules,
338
350
out .writeln ("" )
339
351
if self .takesTreeInput :
340
352
out .writeln ("tree = %s" % self .takesTreeInput )
353
+ for expr , sym in self .compiledExprCache .items ():
354
+ out .writeln ("%s = compile(%r, '<string>', 'eval')" % (sym , expr ))
341
355
funcOut .writeln (
342
356
"if %s.globals is not None:" % (name .data ,))
343
357
out .writeln ("%s.globals = %s.globals.copy()" % (name .data ,
@@ -347,6 +361,7 @@ def generate_Grammar(self, out, name, takesTreeInput, rules,
347
361
"else:" )
348
362
out .writeln ("%s.globals = ruleGlobals" % (name .data ,))
349
363
funcOut .writeln ("return " + name .data )
364
+ self .compiledExprCache = None
350
365
351
366
352
367
class _Term2PythonAction (object ):
0 commit comments