From: whitequark Date: Fri, 28 Dec 2018 01:31:24 +0000 (+0000) Subject: tracer: factor out get_src_loc(). X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=add718f701796b69c2f1ffc16a060a432978f0be;p=nmigen.git tracer: factor out get_src_loc(). --- diff --git a/nmigen/hdl/ast.py b/nmigen/hdl/ast.py index 52e7dd3..462a422 100644 --- a/nmigen/hdl/ast.py +++ b/nmigen/hdl/ast.py @@ -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: diff --git a/nmigen/hdl/mem.py b/nmigen/hdl/mem.py index 7273118..4863fd8 100644 --- a/nmigen/hdl/mem.py +++ b/nmigen/hdl/mem.py @@ -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 diff --git a/nmigen/tracer.py b/nmigen/tracer.py index e018c8f..225ee1a 100644 --- a/nmigen/tracer.py +++ b/nmigen/tracer.py @@ -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)