vendor.lattice_{ecp5,machxo_2_3l}: remove -forceAll from Diamond scripts.
[nmigen.git] / nmigen / tracer.py
1 import sys
2 from opcode import opname
3
4
5 __all__ = ["NameNotFound", "get_var_name", "get_src_loc"]
6
7
8 class NameNotFound(Exception):
9 pass
10
11
12 _raise_exception = object()
13
14
15 def get_var_name(depth=2, default=_raise_exception):
16 frame = sys._getframe(depth)
17 code = frame.f_code
18 call_index = frame.f_lasti
19 while True:
20 call_opc = opname[code.co_code[call_index]]
21 if call_opc in ("EXTENDED_ARG",):
22 call_index += 2
23 else:
24 break
25 if call_opc not in ("CALL_FUNCTION", "CALL_FUNCTION_KW", "CALL_FUNCTION_EX", "CALL_METHOD"):
26 return None
27
28 index = call_index + 2
29 while True:
30 opc = opname[code.co_code[index]]
31 if opc in ("STORE_NAME", "STORE_ATTR"):
32 name_index = int(code.co_code[index + 1])
33 return code.co_names[name_index]
34 elif opc == "STORE_FAST":
35 name_index = int(code.co_code[index + 1])
36 return code.co_varnames[name_index]
37 elif opc == "STORE_DEREF":
38 name_index = int(code.co_code[index + 1])
39 return code.co_cellvars[name_index]
40 elif opc in ("LOAD_GLOBAL", "LOAD_NAME", "LOAD_ATTR", "LOAD_FAST", "LOAD_DEREF",
41 "DUP_TOP", "BUILD_LIST"):
42 index += 2
43 else:
44 if default is _raise_exception:
45 raise NameNotFound
46 else:
47 return default
48
49
50 def get_src_loc(src_loc_at=0):
51 # n-th frame: get_src_loc()
52 # n-1th frame: caller of get_src_loc() (usually constructor)
53 # n-2th frame: caller of caller (usually user code)
54 frame = sys._getframe(2 + src_loc_at)
55 return (frame.f_code.co_filename, frame.f_lineno)