- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython-parser.py
More file actions
Latest commit
30 lines (25 loc) · 988 Bytes
/
Copy pathpython-parser.py
File metadata and controls
30 lines (25 loc) · 988 Bytes
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
importast
importsys
importjson
classJSONVisitorException(Exception):
pass
classQuickVisitor(ast.NodeVisitor):
defgeneric_visit(self, n):
if (not (isinstance(n, ast.AST))):
raiseJSONVisitorException("Unexpected error: Non-ast passed to visit. Please report to the TAs.")
fields=ast.iter_fields(n)
defget_item(v):
t=type(v)
ifvisNone: returnNone
elift==list: returnlist(map (lambdaelt: get_item(elt), v))
elifisinstance(v, ast.AST): returnself.visit(v)
eliftin [int, float, str]: returnv
eliftin [complex]: return {'nodetype': 'Complex', 'value': str(v)}
else:
raiseJSONVisitorException("Unexpected error: Missed case: %s. Please report to the TAs."
%v)
n_dict=dict([(f,get_item(v)) for (f,v) infields])
n_dict['nodetype'] =n.__class__.__name__
returnn_dict
if__name__=='__main__':
print(json.dumps(QuickVisitor().visit(ast.parse(sys.stdin.read()))))