Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(graph): bind names destructured from a dynamic import() (#3181)
Raghav Chamadiya7d900be04e21
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing.pyindex 5a57834db..10b781c8b 100644--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py@@ -30,6 +30,7 @@ from .languages.receiver_types import (names_in_span,range_element_types,record_type,+ scan_binding_positions,scan_bindings,scan_call_assignments,scan_declarations,@@ -39,7 +40,7 @@ from .languages.receiver_types import (types_in_span,unwrapped_names_in_span,)-from .models import CallSite, ParsedFile, Symbol, symbol_id_language+from .models import CallSite, NamedBinding, ParsedFile, Symbol, symbol_id_languagefrom .resolved_call import ResolvedCallfrom .return_types import declared_return_type, go_first_resultfrom .symbol_identity import id_segment_name@@ -155,6 +156,7 @@ class ReceiverTypingMixin:# {file: {type name: [type symbol ids]}}, built once on first use.self._type_ids: dict[str, dict[str, list[str]]] | None = Noneself._bindings: dict[str, tuple[tuple[int, str], ...]] = {}+ self._binding_positions: dict[str, tuple[tuple[int, int, str], ...]] = {}self._bound_names: dict[tuple[str, str], frozenset[str]] = {}self._scope_chain_cache: dict[str, dict[str, tuple[_Scope, ...]]] = {}# {file: {name: type}} — module-level defs a framework decorator retyped.@@ -439,15 +441,38 @@ class ReceiverTypingMixin:Scopes are asked innermost first, so a ``global`` stops the walk. When*through_line* is given only positional bindings at or before it count:a callback's parameter further down cannot shadow a use above, while a- hoisted declaration binds its whole scope.+ hoisted declaration binds its whole scope. When the scope first binds+ *name* on the line an in-body import binds it (``const { f } =+ require(...)``), *name* is the import's unless another binding of it,+ at any other position from that line through *through_line*, shadows it."""+ binding = self._import_bindings.get(file_path, {}).get(name)+ import_line = binding.line if binding is not None else Nonefor scope in self._scope_chains(file_path, language).get(caller_id, ()):if name in scope.escaped:return False+ if name in scope.hoisted:+ return Trueline = scope.first_bound.get(name)- if name in scope.hoisted or (- line is not None and (through_line is None or line <= through_line)- ):+ if line is None or (through_line is not None and line > through_line):+ continue+ if binding is None or line != import_line or through_line is None:+ return True+ return self._rebinds_import(file_path, language, binding, through_line)+ return False++ def _rebinds_import(+ self, file_path: str, language: str, binding: NamedBinding, through_line: int+ ) -> bool:+ """Is *binding*'s name bound anywhere but at the import itself, up to *through_line*?"""+ line = binding.line or 0+ line_text = self._text_of(file_path).split("\n", line)[line - 1]+ positions = self._binding_positions_for(file_path, language)+ for bound_line, column, bound in _in_lines(positions, line, through_line):+ if bound != binding.local_name:+ continue+ # The scan counts characters, tree-sitter counts bytes.+ if bound_line > line or len(line_text[:column].encode()) != binding.column:return Truereturn False@@ -1107,6 +1132,16 @@ class ReceiverTypingMixin:_store_capped(self._bindings, file_path, found, _SOURCE_CACHE_FILES)return found+ def _binding_positions_for(+ self, file_path: str, language: str+ ) -> tuple[tuple[int, int, str], ...]:+ """``_bindings_for`` with columns, scanned only for files that ask."""+ found = self._binding_positions.get(file_path)+ if found is None:+ found = scan_binding_positions(self._text_of(file_path), language)+ _store_capped(self._binding_positions, file_path, found, _SOURCE_CACHE_FILES)+ return found+def _framework_names(self, language: str) -> frozenset[str]:"""Every name a framework decorator retypes anywhere in the repo."""if self._framework_name_set is not None:diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.pyindex 29100e49a..1dbac76df 100644--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py@@ -30,43 +30,91 @@ def _extract_require_bindings(name_node = stmt_node.child_by_field_name("name")if name_node is None:return [], []+ return _module_pattern_bindings(name_node, src)++def _bound_at(+ local_node: Node, exported: str | None, src: str, *, module_alias: bool = False+) -> NamedBinding:+ """A binding that records where its local name sits (1-based line, byte column)."""+ return NamedBinding(+ local_name=node_text(local_node, src),+ exported_name=exported,+ source_file=None,+ is_module_alias=module_alias,+ line=local_node.start_point[0] + 1,+ column=local_node.start_point[1],+ )+++def _module_pattern_bindings(name_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:+ """Bindings for the pattern a module is bound to: ``m`` or ``{ a, b: c }``.++ Each binding carries the position of its local name, so the call resolver+ can tell this binding apart from a parameter or local that shadows it.+ """names: list[str] = []bindings: list[NamedBinding] = []if name_node.type == "identifier":- local = node_text(name_node, src)- names.append(local)- bindings.append(- NamedBinding(- local_name=local,- exported_name=None,- source_file=None,- is_module_alias=True,- )- )+ names.append(node_text(name_node, src))+ bindings.append(_bound_at(name_node, None, src, module_alias=True))elif name_node.type == "object_pattern":for el in name_node.children:if el.type == "shorthand_property_identifier_pattern":local = node_text(el, src)names.append(local)- bindings.append(- NamedBinding(local_name=local, exported_name=local, source_file=None)- )+ bindings.append(_bound_at(el, local, src))elif el.type == "pair_pattern":key = el.child_by_field_name("key")val = el.child_by_field_name("value")if key is not None and val is not None:exported = node_text(key, src)- local = node_text(val, src)names.append(exported)- bindings.append(- NamedBinding(local_name=local, exported_name=exported, source_file=None)- )+ bindings.append(_bound_at(val, exported, src))return names, bindings+def dynamic_import_bindings(call_node: Node, src: str) -> list[NamedBinding]:+ """Bindings for what an ``import('./m')`` call's module is bound to.++ ``const { f } = await import('./m')`` binds through its declarator, and+ ``import('./m').then(({ f }) => …)`` through the callback's first+ parameter; either may be a namespace identifier instead. Any other use+ binds nothing nameable.+ """+ node = call_node+ while node.parent is not None and node.parent.type in _VALUE_WRAPPER_NODE_TYPES:+ node = node.parent+ parent = node.parent+ if parent is None:+ return []++ pattern: Node | None = None+ if parent.type == "variable_declarator" and parent.child_by_field_name("value") == node:+ pattern = parent.child_by_field_name("name")+ elif (+ parent.type == "member_expression"+ and parent.child_by_field_name("object") == node+ and node_text(parent.child_by_field_name("property"), src) == "then"+ and parent.parent is not None+ and parent.parent.type == "call_expression"+ ):+ args = parent.parent.child_by_field_name("arguments")+ callback = args.named_children[0] if args is not None and args.named_children else None+ if callback is not None and callback.type in _CALLABLE_VALUE_NODE_TYPES:+ pattern = callback.child_by_field_name("parameter")+ params = callback.child_by_field_name("parameters")+ if pattern is None and params is not None and params.named_children:+ first = params.named_children[0]+ # TypeScript wraps each parameter, JavaScript does not.+ pattern = first.child_by_field_name("pattern") or first+ if pattern is None:+ return []+ return _module_pattern_bindings(pattern, src)[1]++def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:"""Extract bindings from TypeScript/JavaScript import and re-export statements.diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.pyindex 5129b5904..81cef27ba 100644--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py@@ -414,12 +414,10 @@ _TS_TARGET_LISTS = (_TS_CONDITION_HEADS = frozenset({"if", "for", "while", "switch", "with", "return", "await"})-def _named_bindings(- patterns: Iterable[re.Pattern[str]], cleaned: str, starts: list[int]-) -> set[tuple[int, str]]:- """``(line, name)`` for each pattern's ``name`` group."""+def _named_bindings(patterns: Iterable[re.Pattern[str]], cleaned: str) -> set[tuple[int, str]]:+ """``(offset, name)`` for each pattern's ``name`` group."""return {- (bisect_right(starts, match.start("name")), match.group("name"))+ (match.start("name"), match.group("name"))for pattern in patternsfor match in pattern.finditer(cleaned)}@@ -453,9 +451,8 @@ def _listed_bindings(patterns: Iterable[re.Pattern[str]],identifier: re.Pattern[str],cleaned: str,- starts: list[int],) -> set[tuple[int, str]]:- """``(line, name)`` for every identifier each pattern's ``lhs`` list binds."""+ """``(offset, name)`` for every identifier each pattern's ``lhs`` list binds."""found: set[tuple[int, str]] = set()for pattern in patterns:for match in pattern.finditer(cleaned):@@ -464,20 +461,19 @@ def _listed_bindings(continueoffset = match.start("lhs")for name in identifier.finditer(_without_annotations(match.group("lhs"))):- found.add((bisect_right(starts, offset + name.start()), name.group()))+ found.add((offset + name.start(), name.group()))return found-def _python_target_bindings(cleaned: str, starts: list[int]) -> set[tuple[int, str]]:+def _python_target_bindings(cleaned: str) -> set[tuple[int, str]]:found: set[tuple[int, str]] = set()for pattern in _PY_TARGET_LISTS:for match in pattern.finditer(cleaned):- line = bisect_right(starts, match.start("lhs"))for target in match.group("lhs").split(","):# `self.x = ...` and `d[k] = ...` bind no bare name.name = target.strip()if _PY_IDENTIFIER.match(name):- found.add((line, name))+ found.add((match.start("lhs"), name))return found@@ -489,19 +485,32 @@ _BINDING_SCAN_AS = {"javascript": "typescript"}def scan_bindings(text: str, language: str) -> tuple[tuple[int, str], ...]:"""Every ``(line, name)`` *text* binds, in line order."""+ return tuple(sorted({(line, name) for line, _, name in scan_binding_positions(text, language)}))+++def scan_binding_positions(text: str, language: str) -> tuple[tuple[int, int, str], ...]:+ """Every ``(line, column, name)`` *text* binds, in order.++ Ceiling: a block comment earlier on the same line shifts the column, since+ comments are blanked without keeping their width.+ """if language not in BINDING_LANGUAGES:return ()language = _BINDING_SCAN_AS.get(language, language)cleaned = _without_comments(text, language)starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]if language == "typescript":- found = _named_bindings(_TS_BINDINGS, cleaned, starts)- found |= _listed_bindings(_TS_TARGET_LISTS, _TS_IDENTIFIER, cleaned, starts)+ found = _named_bindings(_TS_BINDINGS, cleaned)+ found |= _listed_bindings(_TS_TARGET_LISTS, _TS_IDENTIFIER, cleaned)else:- found = _python_target_bindings(cleaned, starts)- found |= _named_bindings(_PY_BINDINGS, cleaned, starts)- found |= _listed_bindings(_PY_PARAMETER_LISTS, _PY_NAME, cleaned, starts)- return tuple(sorted(found))+ found = _python_target_bindings(cleaned)+ found |= _named_bindings(_PY_BINDINGS, cleaned)+ found |= _listed_bindings(_PY_PARAMETER_LISTS, _PY_NAME, cleaned)+ positions = set()+ for offset, name in found:+ line = bisect_right(starts, offset)+ positions.add((line, offset - starts[line - 1], name))+ return tuple(sorted(positions))# What a scope binds beyond its positional bindings. A TypeScript/JavaScriptdiff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 70bf49621..bbb5c1587 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -247,6 +247,11 @@ class NamedBinding:is_module_alias: bool = False # True for "import x" / "import * as ns"is_global: bool = False # C# `global using` — applies to every file in the projectis_static_import: bool = False # C# `using static` / Java static import — pulls members+ # Position of the local name (1-based line, byte column), set where a+ # binding can sit inside a function body (``require``, ``import()``), so+ # it is not read as a shadowing local.+ line: int | None = None+ column: int | None = None@dataclassdiff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex e6b60d318..b37e8ddf9 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -61,6 +61,7 @@ from .extractors.bindings.python import expand_bare_relative_importsfrom .extractors.bindings.ts_js import (declarator_binds_callable,declarator_value_is_module_ref,+ dynamic_import_bindings,)from .extractors.synthetic_symbols import extract_synthetic_symbolsfrom .extractors.visibility import (@@ -1029,7 +1030,8 @@ def _statement_imports(return macro_mod_imports(module_node, raw) if "mod" in raw else []if language in _TS_JS_LANGUAGES and _is_dynamic_esm_import(stmt_node):# ``import('./mod')`` binds a module namespace at runtime, so it is a- # wildcard, which keeps the target's exports live.+ # wildcard, which keeps the target's exports live. The names it is+ # destructured into still bind, for call resolution.return [Import(raw_statement=raw,@@ -1037,7 +1039,7 @@ def _statement_imports(imported_names=["*"],is_relative=module_text.startswith("."),resolved_file=None,- bindings=[],+ bindings=dynamic_import_bindings(stmt_node, src),is_reexport=False,)]@@ -1868,6 +1870,10 @@ class ASTParser:mod_path_attr = _rust_mod_path_attribute(stmt_node, src)if mod_path_attr is not None:dedup_key = f"{raw}|path={mod_path_attr}"+ # Two ``import('./m')`` calls share their text but not the names+ # each one binds.+ if language in _TS_JS_LANGUAGES and _is_dynamic_esm_import(stmt_node):+ dedup_key = f"{raw}|at={stmt_node.start_byte}"if dedup_key in seen_raws:continueseen_raws.add(dedup_key)diff --git a/tests/unit/ingestion/test_dynamic_import_bindings.py b/tests/unit/ingestion/test_dynamic_import_bindings.pynew file mode 100644index 000000000..a0715d450--- /dev/null+++ b/tests/unit/ingestion/test_dynamic_import_bindings.py@@ -0,0 +1,116 @@+"""Names bound from a dynamic ``import()`` resolve calls like a static import.++``f`` is declared in two modules so a call can only reach ``m``'s through the+import binding, never through a repo-wide unique-name fallback.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++_EXTENSIONS = ("ts", "js", "tsx")++_BOUND = {+ "then_shorthand": 'export function run() { import("./m.js").then(({ f }) => f()); }\n',+ "then_renamed": 'export function run() { import("./m.js").then(({ f: g }) => g()); }\n',+ "then_function": (+ 'export function run() { import("./m.js").then(function ({ f }) { f(); }); }\n'+ ),+ "then_namespace": 'export function run() { import("./m.js").then((m) => m.f()); }\n',+ "await_shorthand": (+ 'export async function run() { const { f } = await import("./m.js"); f(); }\n'+ ),+ "await_renamed": (+ 'export async function run() {\n const { f: g } = await import("./m.js");\n g();\n}\n'+ ),+ "await_namespace": (+ 'export async function run() { const m = await import("./m.js"); m.f(); }\n'+ ),+ "non_ascii_earlier_on_the_line": (+ 'export async function run() { const s = "é"; const { f } = await import("./m.js"); f(); }\n'+ ),+ "module_level_await": (+ 'const { f: g } = await import("./m.js");\nexport function run() { g(); }\n'+ ),+ "require_in_body": (+ 'export function run() { const { f: g } = require("./m.js"); g(); }\n'+ ),+}++_UNBOUND = {+ "package_specifier": (+ 'export async function run() { const { f } = await import("pkg"); f(); }\n'+ ),+ "variable_specifier": (+ 'export async function run(p) { const { f } = await import(p); f(); }\n'+ ),+ "not_exported": (+ 'export async function run() { const { nope } = await import("./m.js"); nope(); }\n'+ ),+ "shadowed_by_callback_parameter": (+ 'export async function run() {\n const { f } = await import("./m.js");\n'+ " [1].map((f) => f());\n}\n"+ ),+ "shadowed_on_the_import_line_by_a_parameter": (+ 'export async function run() { const { f } = await import("./m.js");'+ " [1].map((f) => f()); }\n"+ ),+ "shadowed_on_the_import_line_by_a_nested_local": (+ 'export async function run() { const { f } = await import("./m.js");'+ " function g() { const f = 1; f(); } }\n"+ ),+}+++def _calls(+ tmp_path: Path, ext: str, source: str, m_source: str = "export function f() { return 1; }\n"+) -> set[tuple[str, str]]:+ files = {+ f"m.{ext}": m_source,+ f"n.{ext}": "export function f() { return 2; }\n",+ f"a.{ext}": source,+ }+ for rel, text in files.items():+ (tmp_path / rel).write_text(text, encoding="utf-8")+ builder = GraphBuilder(tmp_path)+ parser = ASTParser()+ source_map: dict[str, bytes] = {}+ for fi in FileTraverser(tmp_path).traverse():+ src = Path(fi.abs_path).read_bytes()+ builder.add_file(parser.parse_file(fi, src))+ source_map[fi.path] = src+ builder.set_source_map(source_map)+ builder.build()+ graph = builder.graph()+ return {(u, v) for u, v, d in graph.edges(data=True) if d.get("edge_type") == "calls"}++[email protected]("ext", _EXTENSIONS)[email protected]("shape", sorted(_BOUND))+def test_bound_name_calls_the_imported_function(tmp_path: Path, ext: str, shape: str) -> None:+ calls = _calls(tmp_path, ext, _BOUND[shape])+ assert (f"a.{ext}::run", f"m.{ext}::f") in calls+ assert (f"a.{ext}::run", f"n.{ext}::f") not in calls++[email protected]("ext", _EXTENSIONS)[email protected]("shape", sorted(_UNBOUND))+def test_unbound_name_gets_no_edge(tmp_path: Path, ext: str, shape: str) -> None:+ calls = _calls(tmp_path, ext, _UNBOUND[shape])+ assert not {edge for edge in calls if edge[0].startswith(f"a.{ext}::")}+++def test_each_dynamic_import_of_one_module_keeps_its_own_names(tmp_path: Path) -> None:+ calls = _calls(+ tmp_path,+ "ts",+ 'export async function run() { const { f } = await import("./m.js"); f(); }\n'+ 'export async function other() { const { h } = await import("./m.js"); h(); }\n',+ m_source="export function f() { return 1; }\nexport function h() { return 3; }\n",+ )+ assert ("a.ts::run", "m.ts::f") in calls+ assert ("a.ts::other", "m.ts::h") in calls