3
3
from compiler import ast, compile as python_compile
4
4
from compiler.pycodegen import ExpressionCodeGenerator
6
class TreeBuilder(object):
8
Produce an abstract syntax tree of OMeta operations.
10
def __init__(self, name, grammar):
12
self.grammar = grammar
14
def makeGrammar(self, rules):
15
return ["Grammar", rules]
17
def apply(self, ruleName, codeName=None, *exprs):
18
return ["Apply", ruleName, codeName or '', exprs]
20
def exactly(self, expr):
21
return ["Exactly", expr]
26
def many1(self, expr):
27
return ["Many1", expr]
29
def optional(self, expr):
30
return ["Optional", expr]
38
def lookahead(self, expr):
39
return ["Lookahead", expr]
41
def sequence(self, exprs):
42
return ["And"] + exprs
44
def bind(self, expr, name):
45
return ["Bind", name, expr]
48
return ["Predicate", expr]
50
def action(self, expr):
51
return ["Action", expr]
53
def listpattern(self, exprs):
54
return ["List", exprs]
56
def compilePythonExpr(self, name, expr):
57
return ["Python", name, expr]
6
59
class AstBuilder(object):
8
61
Builder of Python code objects via the 'compiler.ast' module.
79
132
methodDict.update(ruleMethods)
82
def apply(self, ruleName, codeName=None, *exprs):
135
def apply(self, ruleName, codeName='', *exprs):
84
137
Create a call to self.apply(ruleName, *args).
301
355
@param rules: A mapping of names to rule bodies.
303
357
lines = list(itertools.chain(*[self._function("def rule_%s(self):"%(name,),
304
["_locals = {'self': self}", "self.locals[%s] = _locals" % (name,)] + list(body)) + ['\n\n']
358
["_locals = {'self': self}", "self.locals[%r] = _locals" % (name,)] + list(body)) + ['\n\n']
305
359
for (name, body) in rules]))
306
360
code = '\n'.join(self._suite("class %s(%s):" %(self.name, self.grammar.__class__.__name__), lines))
307
361
module = "from %s import %s\n" % (self.grammar.__class__.__module__, self.grammar.__class__.__name__) + code