-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateast.py
More file actions
67 lines (57 loc) · 3.15 KB
/
Copy pathgenerateast.py
File metadata and controls
67 lines (57 loc) · 3.15 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
def define_ast(output_dir, base_name, types):
path = "{output_dir}/{base_name}.py".format(**locals())
with open(path, 'w') as output:
output.print = lambda x: output.write(str(x)+'\n')
output.print("from expression import Expr, Stmt\n\n")
for type in types:
class_name = type.split(":")[0].strip()
fields = type.split(":")[1].strip()
define_type(output, base_name, class_name, fields)
output.print('')
def define_type(writer, base_name, class_name, fields):
writer.print("class {}({}):".format(
class_name, str.capitalize(base_name)))
if len(fields) > 0:
writer.print(" def __init__(self, {fields}):".format(**locals()))
for field in [f.strip() for f in fields.split(',')]:
writer.print(" self.{field} = {field}".format(**locals()))
writer.print('')
# Visitor pattern
writer.print(" def accept(self, visitor):")
writer.print(" return visitor.visit_{}_{}(self)".format(
str.lower(class_name), str.lower(base_name)))
writer.print('')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Generate AST')
parser.add_argument('output_dir', metavar='output directory')
args = parser.parse_args()
define_ast(args.output_dir, "expr", ["Assign : name, value",
"Binary : left, operator, right",
"Call : callee, paren, arguments",
"Index : collection, paren, indicies",
"Lambda : parameters, body",
"Get : object, name",
"Grouping : expression",
"List : expression",
"Literal : value",
"Logical : left, operator, right",
"Set : object, name, value",
"Unary : operator, right",
"ListConstructor : start, next, stop, token",
"Variable : name"])
define_ast(args.output_dir, "stmt", ["Block : statements",
"Class : name, methods",
"Expression : expression",
"Function : name, parameters, body",
"If : condition, then_branch, else_branch",
"Print : expression",
"Return : keyword, value",
"Var : name, initializer",
"Mut : name, initializer",
"Unstable : name, initializer",
"While : condition, body",
"Break : ",
"Continue : "])