tracer: factor out get_src_loc().
authorwhitequark <whitequark@whitequark.org>
Fri, 28 Dec 2018 01:31:24 +0000 (01:31 +0000)
committerwhitequark <whitequark@whitequark.org>
Fri, 28 Dec 2018 01:31:24 +0000 (01:31 +0000)
nmigen/hdl/ast.py
nmigen/hdl/mem.py
nmigen/tracer.py

index 52e7dd38899688ad408a64cecf4c3212a8eed813..462a422b07a589df1d41d97fd353fb59f1c5f420 100644 (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:
index 727311880570635b0087a66a68160a6d4432268e..4863fd80e7a8de6af28a0c3d6b33d14320517afb 100644 (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
index e018c8f4abacfb8e99d2be2292f17c04a9a4db48..225ee1ac6e2061b165569fc109c6fa5cfbb9e0bd 100644 (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)