tracer: add support for Python 3.7.
[nmigen.git] / nmigen / tracer.py
1 import inspect
2 from opcode import opname
3
4
5 class NameNotFound(Exception):
6 pass
7
8
9 def get_var_name(depth=2):
10 frame = inspect.currentframe()
11 for _ in range(depth):
12 frame = frame.f_back
13
14 code = frame.f_code
15 call_index = frame.f_lasti
16 call_opc = opname[code.co_code[call_index]]
17 if call_opc not in ("CALL_FUNCTION", "CALL_FUNCTION_KW", "CALL_FUNCTION_EX", "CALL_METHOD"):
18 return None
19
20 index = call_index + 2
21 while True:
22 opc = opname[code.co_code[index]]
23 if opc in ("STORE_NAME", "STORE_ATTR"):
24 name_index = int(code.co_code[index + 1])
25 return code.co_names[name_index]
26 elif opc == "STORE_FAST":
27 name_index = int(code.co_code[index + 1])
28 return code.co_varnames[name_index]
29 elif opc == "STORE_DEREF":
30 name_index = int(code.co_code[index + 1])
31 return code.co_cellvars[name_index]
32 elif opc in ("LOAD_GLOBAL", "LOAD_ATTR", "LOAD_FAST", "LOAD_DEREF",
33 "DUP_TOP", "BUILD_LIST"):
34 index += 2
35 else:
36 raise NameNotFound