tracer: factor out get_src_loc().

This commit is contained in:
whitequark 2018-12-28 01:31:24 +00:00
parent 3ea35b8566
commit d66bbb0df8
3 changed files with 16 additions and 15 deletions

View file

@ -39,12 +39,7 @@ class Value(metaclass=ABCMeta):
def __init__(self, src_loc_at=0):
super().__init__()
tb = traceback.extract_stack(limit=3 + src_loc_at)
if len(tb) < src_loc_at:
self.src_loc = None
else:
self.src_loc = (tb[0].filename, tb[0].lineno)
self.src_loc = tracer.get_src_loc(1 + src_loc_at)
def __bool__(self):
raise TypeError("Attempted to convert nMigen value to boolean")
@ -721,8 +716,7 @@ class Array(MutableSequence):
def __getitem__(self, index):
if isinstance(index, Value):
if self._mutable:
tb = traceback.extract_stack(limit=2)
self._proxy_at = (tb[0].filename, tb[0].lineno)
self._proxy_at = tracer.get_src_loc()
self._mutable = False
return ArrayProxy(self, index)
else:

View file

@ -1,5 +1,3 @@
import traceback
from .. import tracer
from .ast import *
from .ir import Instance
@ -17,15 +15,13 @@ class Memory:
raise TypeError("Memory depth must be a non-negative integer, not '{!r}'"
.format(depth))
tb = traceback.extract_stack(limit=2)
self.src_loc = (tb[0].filename, tb[0].lineno)
if name is None:
try:
name = tracer.get_var_name(depth=2)
except tracer.NameNotFound:
name = "$memory"
self.name = name
self.name = name
self.src_loc = tracer.get_src_loc()
self.width = width
self.depth = depth

View file

@ -1,8 +1,9 @@
import traceback
import inspect
from opcode import opname
__all__ = ["NameNotFound", "get_var_name"]
__all__ = ["NameNotFound", "get_var_name", "get_src_loc"]
class NameNotFound(Exception):
@ -37,3 +38,13 @@ def get_var_name(depth=2):
index += 2
else:
raise NameNotFound
def get_src_loc(src_loc_at=0):
# n-th frame: get_src_loc()
# n-1th frame: caller of get_src_loc() (usually constructor)
# n-2th frame: caller of caller (usually user code)
# Python returns the stack frames reversed, so it is enough to set limit and grab the very
# first one in the array.
tb = traceback.extract_stack(limit=3 + src_loc_at)
return (tb[0].filename, tb[0].lineno)