-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast_test.py
executable file
·176 lines (136 loc) · 4.7 KB
/
ast_test.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import os
import os.path
import ast
import inspect
import traceback
# Variables ===================================================================
# Functions & classes =========================================================
bigus_dictus = {
"r:import": {
"@xmlns:r": "http://resolver.nkp.cz/v3/",
"r:monograph": {
"r:titleInfo": {
"r:title": "asdad",
},
"r:primaryOriginator": {
"@type": "AUTHOR",
"#text": "asd"
},
},
}
}
def xex(asd=1, bsd=2, aaa=3):
print traceback.print_stack()
return {
"r:import": {
"@xmlns:r": "http://resolver.nkp.cz/v3/",
"r:monograph": {
"r:titleInfo": {
"r:title": asd,
},
"r:primaryOriginator": {
"@type": "AUTHOR",
"#text": bsd
},
},
}
}
# xex()
# tree = ast.parse(inspect.getsource(xex))
# for el in ast.walk(tree):
# print el
def _disable_nested_calls(func_name, args_ast):
for arg in args_ast:
for el in ast.walk(arg):
if not isinstance(el, ast.Call):
continue
if not hasattr(el.func, "id"):
continue
if el.func.id == func_name:
raise ValueError(
"Sorry, nested calls are not supported!\n"
"All dicts are converted by default."
)
def _match_by_lineno(func_name, known_fn, list_of_unknown):
for candidate in list_of_unknown:
_disable_nested_calls(func_name, candidate.args)
candidates = filter(lambda x: x.lineno <= known_fn.lineno, list_of_unknown)
if candidates:
return max(candidates, key=lambda x: x.lineno)
raise ValueError("Couldn't identify matching fuction.")
# Možná jen resortovat výstupní OrderedDict na základě pořadí klíčů ve vstupním?
# Nedovolit zanořené cally order()u, tím se eliminuje problém s jeho korektním
# vyhledáním
#
# Detekce dvou funkcí na jednom řádku
def order(input_dict):
if not isinstance(input_dict, dict):
raise ValueError("`input_dict` have to be instance of `dict`.")
# TODO: this may fuck the 'from import ..' functionality
frame = inspect.currentframe()
# get name of current function
func_name = inspect.getframeinfo(frame).function
# this helps to reduce lookup complexity
first_line = frame.f_back.f_code.co_firstlineno
# get outer frames
outer_frames = inspect.getouterframes(inspect.currentframe())
if len(outer_frames) <= 1:
raise ValueError("Can't inspect outer frame!")
# select proper outer frame
frame_info = inspect.getframeinfo(outer_frames[1][0])
# TODO: remove this data example
# Traceback(filename='./ast_test.py', lineno=84, function='whops', code_context=[' "#text": "asd"\n'], index=0)
# parse the file from which the function call originated
if not os.path.exists(frame_info.filename):
raise IOError("Can't open '%s'!" % frame_info.filename)
with open(frame_info.filename) as f:
source = f.read()
tree = ast.parse(source, frame_info.filename)
# get AST nodes for function call to function with `func_name` name
func_calls = filter(
lambda x:
isinstance(x, ast.Call) and
hasattr(x.func, "id") and
x.func.id == func_name,
ast.walk(tree)
)
# filter functions with lineno <= than lineno of frame_info (inspect
# returns LAST active line of function call, ast returns FIRST line - we
# need to match those)
func_calls = filter(
lambda x: x.lineno <= frame_info.lineno and x.lineno >= first_line,
func_calls
)
if not func_calls:
raise ValueError("Couldn't find the %s call!" % func_name)
matching_fn = _match_by_lineno(func_name, frame_info, func_calls)
print matching_fn.lineno, matching_fn.func.id
def return_xex():
pass
def whops():
a = "asd"
order({"azgabash": a})
order({
"r:import": {
"@xmlns:r": "http://resolver.nkp.cz/v3/",
"r:monograph": {
"r:titleInfo": {
"r:title": return_xex(
),
},
"r:primaryOriginator": {
"@type": "AUTHOR",
"#text": {"asd":"bsd"}
},
},
}
})
order({"asd": "xerexin"})
return_xex()
whops()