Skip to content

Commit 5a37c2b

Browse files
BloggerBustjayanth-kumar-morem
authored andcommitted
refactor(ast): cache source lines in transformer to avoid repeated file reads
Previously, `_build_callsite_metadata` opened and read the script file on every invocation, which occurred frequently during atom lifting and top level function registration. This commit moves the file read into the transformer's `__init__` method and stores the result in a `self._source_lines` buffer. Now, `_build_callsite_metadata` uses this in memory list to resolve the source line for a given AST node, eliminating repeated disk I/O and improving performance.
1 parent 5a261f2 commit 5a37c2b

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

preswald/engine/transformers/reactive_runtime.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ class AutoAtomTransformer(ast.NodeTransformer):
6060

6161
def __init__(self, filename: str = "<script>"):
6262
self.filename = filename
63+
self._source_lines = []
6364
self.current_function = None
6465
self.dependencies = {}
6566
self.known_components = self._discover_known_components()
@@ -77,6 +78,12 @@ def __init__(self, filename: str = "<script>"):
7778
self._module: ast.Module | None = None
7879
self._used_display_renderer_fns: set[str] = set()
7980

81+
try:
82+
with open(filename, "r") as f:
83+
self._source_lines = f.readlines()
84+
except Exception as e:
85+
logger.warning(f"[AST] Could not read source lines for file {filename}: {e}")
86+
8087
@property
8188
def _current_frame(self) -> Frame:
8289
return self._frames[-1]
@@ -2694,13 +2701,9 @@ def _build_callsite_metadata(self, node: ast.AST, filename: str) -> dict:
26942701
lineno = getattr(node, "lineno", None)
26952702
source = ""
26962703

2697-
if filename and lineno:
2698-
try:
2699-
with open(filename, "r") as f:
2700-
lines = f.readlines()
2701-
source = lines[lineno - 1].strip() if 0 < lineno <= len(lines) else ""
2702-
except Exception:
2703-
pass
2704+
if lineno and self._source_lines:
2705+
if 0 < lineno <= len(self._source_lines):
2706+
source = self._source_lines[lineno - 1].strip()
27042707

27052708
return {
27062709
"callsite_filename": filename,

0 commit comments

Comments
 (0)