-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathast_helpers.py
72 lines (57 loc) · 1.64 KB
/
ast_helpers.py
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
68
69
70
71
72
# pyastest:
# a command line tool to parse, modify, and compare Python ASTs
#
# helpers.py:
# utility/helper functions for interacting with source code/ASTs
#
# @jwiaduck 6 March 2022
#
import ast
from visitors import InfoVisitor
###
### Helpers
###
# parses source code to AST
def parse_ast(source):
tree = ast.parse(source)
ast.fix_missing_locations(tree)
return tree
# compiles and executes AST
def exec_co_ast(tree_in):
exec(compile(tree_in, filename="<ast>", mode="exec"))
# ast.py unparse method
def unparse_ast(tree_in):
print(ast.unparse(tree_in))
# agg. fxn to call AST helpers - namely, get_ast (and return tree)
def get_ast(source):
tree = parse_ast(source)
# print("Got AST!")
return tree
# diff two asts from orginal and changed source codes
def ast_diff(args):
# Get FileType objects (opened and ready to read)
args.original = args.diff[0].read()
args.changed = args.diff[1].read()
args.diff[0].close()
args.diff[1].close()
src1 = args.original
src2 = args.changed
print(f"Original Source: {args.diff[0].name}\nChanged Source: {args.diff[1].name}")
tree_1 = get_ast(src1)
tree_2 = get_ast(src2)
# simple diff check
if ast.dump(tree_1) == ast.dump(tree_2):
print("\nTrue: ASTs are equal!")
else:
print("\nFalse: Not equal.")
# get the info from a source code file
def ast_info(args):
args.source = args.info[0].read()
args.info[0].close()
tree = parse_ast(args.source)
Visitor = InfoVisitor()
Visitor.visit(tree)
Visitor.get_counts()
Visitor.get_compares()
Visitor.get_binary()
Visitor.get_assignments()