Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(core): a parameter or local shadows a bare call's module-level target (#2775)

Raghav Chamadiya18d1fb7c948c
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
index e0ba3437e..4c0a4aa7b 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -2,9 +2,10 @@
from __future__ import annotations
+from bisect import bisect_left, bisect_right
from dataclasses import replace
from pathlib import Path
-from typing import TypeVar
+from typing import NamedTuple, TypeVar
from .languages.receiver_types import (
BINDING_LANGUAGES,
@@ -12,6 +13,7 @@ from .languages.receiver_types import (
IMPLICIT_FIELD_LANGUAGES,
RECEIVER_TYPE_LANGUAGES,
Declaration,
+ ScopeMarks,
bound_types,
framework_decorated_type,
in_spans,
@@ -19,6 +21,7 @@ from .languages.receiver_types import (
names_in_span,
scan_bindings,
scan_declarations,
+ scan_scope_marks,
types_by_class,
types_in_span,
unwrapped_names_in_span,
@@ -49,6 +52,7 @@ _BODY_TYPE_CACHE_ENTRIES = 2048
_K = TypeVar("_K")
_V = TypeVar("_V")
+_T = TypeVar("_T", bound=tuple)
def _store_capped(cache: dict[_K, _V], key: _K, value: _V, cap: int) -> None:
@@ -58,6 +62,43 @@ def _store_capped(cache: dict[_K, _V], key: _K, value: _V, cap: int) -> None:
cache[key] = value
+class _Scope(NamedTuple):
+ """What one symbol's span binds, less the symbol's own name."""
+
+ first_bound: dict[str, int] # name -> first line a positional binding binds it
+ hoisted: frozenset[str]
+ escaped: frozenset[str]
+
+
+def _in_lines(pairs: tuple[_T, ...], start: int, end: int) -> tuple[_T, ...]:
+ """The entries (each led by its line) on lines *start* through *end*."""
+ lo = bisect_left(pairs, start, key=lambda pair: pair[0])
+ return pairs[lo : bisect_right(pairs, end, lo=lo, key=lambda pair: pair[0])]
+
+
+def _scope_of(symbol: Symbol, bindings: tuple[tuple[int, str], ...], marks: ScopeMarks) -> _Scope:
+ start, end, own = symbol.start_line, symbol.end_line, symbol.name
+ first_bound: dict[str, int] = {}
+ for line, name in _in_lines(bindings, start, end):
+ if name != own:
+ first_bound.setdefault(name, line)
+ return _Scope(
+ first_bound,
+ frozenset(
+ name
+ for _, name, depth in _in_lines(marks.hoisted, start, end)
+ if name != own and depth == _body_depth(marks, start)
+ ),
+ frozenset(name for _, name in _in_lines(marks.escaped, start, end)),
+ )
+
+
+def _body_depth(marks: ScopeMarks, start_line: int) -> int:
+ """The brace depth of the statements directly in the body opening on *start_line*."""
+ depths = marks.line_depths
+ return (depths[start_line] if start_line < len(depths) else 0) + 1
+
+
def _is_module_level_function(symbol: Symbol) -> bool:
return symbol.kind in _FUNCTION_KINDS and not symbol.parent_name
@@ -94,6 +135,7 @@ class ReceiverTypingMixin:
self._type_ids: dict[str, dict[str, list[str]]] | None = None
self._bindings: dict[str, tuple[tuple[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.
self._framework_types: dict[str, dict[str, str]] = {}
self._external_names: dict[str, frozenset[str]] = {}
@@ -312,25 +354,73 @@ class ReceiverTypingMixin:
if language not in BINDING_LANGUAGES:
return None
type_name = self._module_types_in(file_path, language).get(receiver_name)
- if type_name is None:
+ if type_name is None or self._binds_locally(file_path, caller_id, language, receiver_name):
return None
- span = self._spans_for(file_path).get(caller_id)
- if span is not None:
- bindings = self._bindings_for(file_path, language)
- for start, end in (span, *self._enclosing_function_spans(file_path, span)):
- if receiver_name in names_in_span(bindings, start, end):
- return None
return type_name
- def _enclosing_function_spans(
- self, file_path: str, span: tuple[int, int]
- ) -> list[tuple[int, int]]:
+ def _shadowed_by_local(self, file_path: str, call: CallSite, caller_id: str) -> bool:
+ """Is a bare call's name a parameter or local of the calling function?
+
+ Then no module, import or repo-wide symbol of that name is the callee.
+ """
+ language = self._language_of(file_path) or ""
+ return language in BINDING_LANGUAGES and self._binds_locally(
+ file_path, caller_id, language, call.target_name, call.line
+ )
+
+ def _binds_locally(
+ self,
+ file_path: str,
+ caller_id: str,
+ language: str,
+ name: str,
+ through_line: int | None = None,
+ ) -> bool:
+ """Does the caller, or a function enclosing it, bind *name* itself?
+
+ 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.
+ """
+ for scope in self._scope_chains(file_path, language).get(caller_id, ()):
+ if name in scope.escaped:
+ return False
+ line = scope.first_bound.get(name)
+ if name in scope.hoisted or (
+ line is not None and (through_line is None or line <= through_line)
+ ):
+ return True
+ return False
+
+ def _scope_chains(self, file_path: str, language: str) -> dict[str, tuple[_Scope, ...]]:
+ """``{symbol_id: scopes}``, the symbol's own then each enclosing function's.
+
+ Built once per file in one sweep over the symbols in span order, so a
+ call site's question is a few dict hits however many it asks.
+ """
+ chains = self._scope_chain_cache.get(file_path)
+ if chains is not None:
+ return chains
parsed = self._parsed_files.get(file_path)
- return [
- (s.start_line, s.end_line)
- for s in (parsed.symbols if parsed else ())
- if s.kind in _FUNCTION_KINDS and s.start_line <= span[0] and span[1] <= s.end_line
- ]
+ text = self._text_of(file_path)
+ bindings = self._bindings_for(file_path, language)
+ marks = scan_scope_marks(text, language)
+ chains = {}
+ open_functions: list[tuple[Symbol, _Scope]] = []
+ symbols = sorted(parsed.symbols if parsed else (), key=lambda s: (s.start_line, -s.end_line))
+ for symbol in symbols:
+ while open_functions and open_functions[-1][0].end_line < symbol.start_line:
+ open_functions.pop()
+ own = _scope_of(symbol, bindings, marks)
+ enclosing = tuple(
+ scope for outer, scope in reversed(open_functions) if symbol.end_line <= outer.end_line
+ )
+ chains[symbol.id] = (own, *enclosing)
+ if symbol.kind in _FUNCTION_KINDS:
+ open_functions.append((symbol, own))
+ _store_capped(self._scope_chain_cache, file_path, chains, _SOURCE_CACHE_FILES)
+ return chains
def _resolve_chained_receiver(
self,
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 9c10266ba..f513f6bd6 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -991,6 +991,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# Every tier keys on the target name, so a name the repo declares
# nowhere can only be matched under an import alias (2a below).
declared = target_name in self._global_symbols
+ # A parameter or local of that name hides every tier below.
+ if self._shadowed_by_local(file_path, call, caller_id):
+ return None
# Tier 1: same-file
handled, resolved = self._same_file_free_call(file_path, call, caller_id)
diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
index f2f340d53..f909a0f73 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -325,12 +325,11 @@ _PY_BINDINGS = (
# `with ... as n`, `except ... as n`, `import x as n`.
re.compile(r"\bas\s+(?P<name>[a-z_]\w*)\b"),
re.compile(r"\b(?P<name>[a-z_]\w*)\s*:="),
- re.compile(r"\b(?:global|nonlocal)\s+(?P<name>[a-z_]\w*)"),
)
# Every parameter of any `def` or `lambda` in the span, the enclosing one
-# included: its signature starts its own span. Each lowercase identifier in the
-# list counts, a default's names too, since over-matching only refuses.
+# included: its signature starts its own span. Each lowercase identifier the
+# list binds counts; an annotation or a default binds nothing.
# Ceiling: a `def` list ends at its first `)`, so a default that calls hides
# the parameters after it.
_PY_PARAMETER_LISTS = (
@@ -344,15 +343,16 @@ _PY_NAME = re.compile(r"(?<![\w.])[a-z_]\w*")
_PY_IDENTIFIER = re.compile(r"^[a-z_]\w*$")
-# The TypeScript shapes that bind a name, typed or not. Over-matching only
-# refuses, so every identifier in a destructuring pattern or a parameter list
-# counts, a type name or a renamed key included. Ceiling: a parameter list
-# holding parentheses (a default that calls, a function type) is not read.
+# The TypeScript shapes that bind a name, typed or not. Every identifier in a
+# destructuring pattern counts, a renamed key included; a parameter's type
+# annotation and default do not. Ceiling: a parameter list holding
+# parentheses (a default that calls, a function type) is not read.
_TS_IDENTIFIER = re.compile(r"[A-Za-z_$][\w$]*")
_TS_BINDINGS = (
re.compile(r"(?<![\w$.])(?:const|let|var)\s+(?P<name>[A-Za-z_$][\w$]*)"),
re.compile(r"(?<![\w$.])(?:function\*?|class)\s+(?P<name>[A-Za-z_$][\w$]*)"),
- re.compile(r"(?<![\w$.])(?P<name>[A-Za-z_$][\w$]*)\s*=>"),
+ # A lone arrow parameter; ``): Foo =>`` is a return type, not one.
+ re.compile(r"(?<![\w$.:])(?<!:\s)(?P<name>[A-Za-z_$][\w$]*)\s*=>"),
# An assignment at the start of a statement, plain or compound.
re.compile(
r"(?m)^[ \t]*(?P<name>[A-Za-z_$][\w$]*)\s*"
@@ -360,9 +360,15 @@ _TS_BINDINGS = (
),
)
_TS_TARGET_LISTS = (
- re.compile(r"(?<![\w$.])(?:const|let|var)\s*(?P<lhs>\{[^;=]*\}|\[[^;=]*\])\s*(?:=|of\b|in\b)"),
- # A parameter list: a function, a method, an arrow, a catch clause.
- re.compile(r"(?P<head>[\w$]*)\s*(?P<lhs>\([^()]*\))\s*(?::[^=;{}()]*?)?\s*(?:=>|\{)"),
+ # Lazy, so a pattern ends at its own bracket, not at one lines later.
+ re.compile(
+ r"(?<![\w$.])(?:const|let|var)\s*(?P<lhs>\{[^;=]*?\}|\[[^;=]*?\])\s*(?:=|of\b|in\b)"
+ ),
+ # A parameter list: a function, a method, an arrow, a catch clause. Not
+ # one after a colon: ``cb: (x: T) => void`` is a function type.
+ re.compile(
+ r"(?<!:)(?<!:\s)(?P<head>[\w$]*)\s*(?P<lhs>\([^()]*\))\s*(?::[^=;{}()]*?)?\s*(?:=>|\{)"
+ ),
)
# Heads whose parenthesised part is a condition, not a parameter list.
_TS_CONDITION_HEADS = frozenset({"if", "for", "while", "switch", "with", "return", "await"})
@@ -379,13 +385,37 @@ def _named_bindings(
}
+def _without_annotations(names: str) -> str:
+ """*names* with each top-level item's annotation and default blanked.
+
+ ``(a: Foo, b = make)`` binds ``a`` and ``b``, never ``Foo`` or ``make``: a
+ bare call to either is still the module's. Blanked, not cut, so every name
+ kept stays at its offset. A bracket opens a nested pattern or a generic,
+ whose commas and colons are not the list's own.
+ """
+ out: list[str] = []
+ depth = 0
+ blanking = False
+ for ch in names:
+ if ch in "{[<":
+ depth += 1
+ elif ch in "}]>":
+ depth = max(depth - 1, 0)
+ elif depth == 0 and ch in ":=":
+ blanking = True
+ elif depth == 0 and ch == ",":
+ blanking = False
+ out.append(" " if blanking and ch != "\n" else ch)
+ return "".join(out)
+
+
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 in each pattern's ``lhs`` list."""
+ """``(line, 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):
@@ -393,7 +423,7 @@ def _listed_bindings(
if match.groupdict().get("head") in _TS_CONDITION_HEADS:
continue
offset = match.start("lhs")
- for name in identifier.finditer(match.group("lhs")):
+ for name in identifier.finditer(_without_annotations(match.group("lhs"))):
found.add((bisect_right(starts, offset + name.start()), name.group()))
return found
@@ -412,14 +442,16 @@ def _python_target_bindings(cleaned: str, starts: list[int]) -> set[tuple[int, s
# The languages ``scan_bindings`` reads: only there can a scope be shown not
-# to bind a name.
-BINDING_LANGUAGES = frozenset({"python", "typescript"})
+# to bind a name. JavaScript binds with TypeScript's shapes, less annotations.
+BINDING_LANGUAGES = frozenset({"javascript", "python", "typescript"})
+_BINDING_SCAN_AS = {"javascript": "typescript"}
def scan_bindings(text: str, language: str) -> tuple[tuple[int, str], ...]:
"""Every ``(line, name)`` *text* binds, in line order."""
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":
@@ -432,6 +464,76 @@ def scan_bindings(text: str, language: str) -> tuple[tuple[int, str], ...]:
return tuple(sorted(found))
+# What a scope binds beyond its positional bindings. A TypeScript/JavaScript
+# ``function`` declaration is hoisted, so it binds from the top of its scope
+# whatever its line. A Python ``global`` name is the module's in that scope,
+# however the body assigns it.
+_HOISTED = {"typescript": re.compile(r"(?<![\w$.])function\*?\s+(?P<name>[A-Za-z_$][\w$]*)")}
+_ESCAPES = {"python": re.compile(r"\bglobal\s+(?P<names>\w+(?:\s*,\s*\w+)*)")}
+
+
+class ScopeMarks(NamedTuple):
+ """Names a scope treats specially, each in line order.
+
+ A hoisted entry is ``(line, name, brace depth)``: a declaration hoists
+ only into the function whose body holds it directly, one brace below the
+ line that function starts on (``line_depths``, indexed by line). A block
+ declaration is block-scoped in a module, so it hoists nowhere.
+ """
+
+ hoisted: tuple[tuple[int, str, int], ...]
+ escaped: tuple[tuple[int, str], ...]
+ line_depths: tuple[int, ...]
+
+
+def _brace_depths(cleaned: str) -> tuple[list[int], list[int]]:
+ """Brace depth at every offset of *cleaned*, and at each line's first character."""
+ at: list[int] = []
+ lines = [0]
+ depth = 0
+ seen_code = False
+ for ch in cleaned:
+ at.append(depth)
+ if ch == "\n":
+ lines.append(depth)
+ seen_code = False
+ continue
+ if not seen_code and not ch.isspace():
+ lines[-1] = depth
+ seen_code = True
+ if ch == "{":
+ depth += 1
+ elif ch == "}":
+ depth = max(depth - 1, 0)
+ return at, lines
+
+
+def scan_scope_marks(text: str, language: str) -> ScopeMarks:
+ """The hoisted and module-escaped names *text* declares."""
+ language = _BINDING_SCAN_AS.get(language, language)
+ hoisted, escapes = _HOISTED.get(language), _ESCAPES.get(language)
+ if hoisted is None and escapes is None:
+ return ScopeMarks((), (), ())
+ cleaned = _without_comments(text, language)
+ starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]
+ found_hoisted: set[tuple[int, str, int]] = set()
+ line_depths: list[int] = []
+ if hoisted is not None:
+ at, line_depths = _brace_depths(cleaned)
+ found_hoisted = {
+ (bisect_right(starts, match.start("name")), match.group("name"), at[match.start()])
+ for match in hoisted.finditer(cleaned)
+ }
+ found_escaped = {
+ (bisect_right(starts, match.start("names")), name.strip())
+ for match in (escapes.finditer(cleaned) if escapes else ())
+ for name in match.group("names").split(",")
+ }
+ return ScopeMarks(
+ tuple(sorted(found_hoisted)), tuple(sorted(found_escaped)), (0, *line_depths)
+ )
+
+
def names_in_span(
bindings: tuple[tuple[int, str], ...],
start_line: int,
diff --git a/tests/unit/ingestion/test_shadowed_bare_calls.py b/tests/unit/ingestion/test_shadowed_bare_calls.py
new file mode 100644
index 000000000..42fc1ad04
--- /dev/null
+++ b/tests/unit/ingestion/test_shadowed_bare_calls.py
@@ -0,0 +1,275 @@
+"""A bare call whose name the calling function binds itself.
+
+``function make(Class) { return new Class() }`` calls whatever class the
+caller passes in, not the module's ``Class``: the parameter shadows every
+same-named import and top-level declaration. The same holds for a local and
+for a parameter of a function enclosing the caller, in TypeScript,
+JavaScript and Python alike.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion.call_resolver import CallResolver
+from repowise.core.ingestion.languages.receiver_types import scan_bindings
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import parse_file
+
+
+def _parse_all(tmp_path: Path, files: dict[str, str], language: str) -> dict[str, ParsedFile]:
+ out: dict[str, ParsedFile] = {}
+ for rel, content in files.items():
+ abs_ = tmp_path / rel
+ abs_.parent.mkdir(parents=True, exist_ok=True)
+ abs_.write_text(content, encoding="utf-8")
+ info = FileInfo(
+ path=rel,
+ abs_path=str(abs_),
+ language=language,
+ size_bytes=abs_.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ out[rel] = parse_file(info, content.encode("utf-8"))
+ return out
+
+
+def _callees(tmp_path: Path, files: dict[str, str], language: str, caller: str) -> set[str]:
+ """Every callee of *caller* in ``api.*``, which imports ``util.*``."""
+ parsed = _parse_all(tmp_path, files, language)
+ api, util = sorted(parsed, key=lambda rel: not rel.startswith("api"))
+ for imp in parsed[api].imports:
+ imp.resolved_file = util
+ for binding in imp.bindings:
+ binding.source_file = util
+ resolver = CallResolver(parsed, {api: {util}}, repo_path=str(tmp_path))
+ return {
+ rc.callee_id
+ for rc in resolver.resolve_file(api, parsed[api].calls)
+ if rc.caller_id == f"{api}::{caller}"
+ }
+
+
+TS_UTIL = """\
+export abstract class Class {}
+export function helper(x: number): number {
+ return x + 1;
+}
+"""
+
+TS_API = """\
+import * as util from "./util";
+import { Class, helper } from "./util";
+
+export function _union(
+ Class: util.SchemaClass<util.Class>,
+ options: unknown,
+) {
+ return new Class(options);
+}
+
+export function withLocal(n: number) {
+ const helper = (v: number) => v * 2;
+ return helper(n);
+}
+
+export function plain(n: number) {
+ return new Class(helper(n));
+}
+
+export function typed(a: Class, b = helper) {
+ return helper(a, b);
+}
+
+export function laterCallback(xs: number[]) {
+ const y = helper(1);
+ return xs.map((helper) => helper + y);
+}
+"""
+
+
+class TestTypeScript:
+ @pytest.fixture
+ def files(self) -> dict[str, str]:
+ return {"util.ts": TS_UTIL, "api.ts": TS_API}
+
+ def test_parameter_shadows_the_imported_class(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "typescript", "_union") == set()
+
+ def test_local_shadows_the_imported_function(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "typescript", "withLocal") == set()
+
+ def test_unshadowed_names_still_resolve(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "typescript", "plain") == {
+ "util.ts::Class",
+ "util.ts::helper",
+ }
+
+ def test_annotation_and_default_bind_nothing(self, tmp_path: Path, files) -> None:
+ # `Class` is only a type and `helper` only a default here.
+ assert _callees(tmp_path, files, "typescript", "typed") == {"util.ts::helper"}
+
+ def test_a_later_callback_parameter_does_not_shadow(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "typescript", "laterCallback") == {"util.ts::helper"}
+
+
+JS_UTIL = """\
+export function helper(x) {
+ return x + 1;
+}
+"""
+
+JS_API = """\
+import { helper } from "./util.js";
+
+export function shadowed(helper, n) {
+ return helper(n);
+}
+
+export function plain(n) {
+ return helper(n);
+}
+
+export function hoisted(n) {
+ const r = helper(n);
+ return r;
+
+ function helper(v) {
+ return v;
+ }
+}
+
+export function outer() {
+ return helper(1);
+ function later() {
+ function helper() {}
+ }
+}
+"""
+
+
+class TestJavaScript:
+ @pytest.fixture
+ def files(self) -> dict[str, str]:
+ return {"util.js": JS_UTIL, "api.js": JS_API}
+
+ def test_parameter_shadows_the_import(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "javascript", "shadowed") == set()
+
+ def test_unshadowed_name_still_resolves(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "javascript", "plain") == {"util.js::helper"}
+
+ def test_a_later_function_declaration_is_hoisted(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "javascript", "hoisted") == set()
+
+ def test_a_declaration_hoists_only_into_its_own_function(self, tmp_path: Path, files) -> None:
+ # `helper` is declared inside `later`, so `outer` still calls the import.
+ assert _callees(tmp_path, files, "javascript", "outer") == {"util.js::helper"}
+
+
+PY_UTIL = """\
+def helper(x):
+ return x + 1
+"""
+
+PY_API = """\
+from util import helper
+
+
+def shadowed(helper, n):
+ return helper(n)
+
+
+def plain(n, fallback: int = 0):
+ return helper(n)
+
+
+def rebinds(n):
+ helper = len
+ return helper(n)
+
+
+def declares_global(n):
+ global helper
+ helper = helper or len
+ return helper(n)
+
+
+def encloses(n):
+ helper = len
+
+ def inner():
+ nonlocal helper
+ return helper(n)
+
+ return inner
+"""
+
+
+class TestPython:
+ @pytest.fixture
+ def files(self) -> dict[str, str]:
+ return {"util.py": PY_UTIL, "api.py": PY_API}
+
+ def test_parameter_shadows_the_import(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "python", "shadowed") == set()
+
+ def test_unshadowed_name_still_resolves(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "python", "plain") == {"util.py::helper"}
+
+ def test_an_assignment_shadows_the_import(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "python", "rebinds") == set()
+
+ def test_a_global_name_is_the_modules(self, tmp_path: Path, files) -> None:
+ assert _callees(tmp_path, files, "python", "declares_global") == {"util.py::helper"}
+
+ def test_a_nonlocal_name_stays_the_enclosing_functions(self, tmp_path: Path, files) -> None:
+ # Nothing module-level is the callee, whichever caller the site is filed under.
+ parsed_callees = _callees(tmp_path, files, "python", "encloses") | _callees(
+ tmp_path, files, "python", "encloses::inner"
+ )
+ assert "util.py::helper" not in parsed_callees
+
+
+class TestBindingScan:
+ def test_typescript_parameter_types_and_defaults_are_not_bindings(self) -> None:
+ names = {n for _, n in scan_bindings("function f(a: Foo<K, V>, b = make) {}", "typescript")}
+ assert names == {"f", "a", "b"}
+
+ def test_an_arrow_return_type_is_not_a_binding(self) -> None:
+ text = "const create = (params?: P): ZodString => new ZodString(params);"
+ names = {n for _, n in scan_bindings(text, "typescript")}
+ assert "ZodString" not in names
+ assert {"create", "params"} <= names
+
+ def test_a_function_type_parameter_is_not_a_binding(self) -> None:
+ text = "const f = (c: C, cb: (stream: S) => void): R => {\n return stream(c, cb)\n}"
+ assert "stream" not in {n for _, n in scan_bindings(text, "typescript")}
+
+ def test_a_destructuring_pattern_ends_at_its_own_bracket(self) -> None:
+ text = "for (const [k, v] of xs) {\n out.push(serialize(k, v))\n}\nh['x'] = 1\n"
+ bound = scan_bindings(text, "typescript")
+ assert "serialize" not in {n for _, n in bound}
+ assert {(1, "k"), (1, "v")} <= set(bound)
+
+ def test_destructured_parameters_are_bindings(self) -> None:
+ text = "function f({ a, b: c }: Props, [d]: T[]) {}"
+ names = {n for _, n in scan_bindings(text, "typescript")}
+ assert {"a", "b", "c", "d"} <= names
+ assert "Props" not in names
+
+ def test_python_annotations_and_defaults_are_not_bindings(self) -> None:
+ names = {n for _, n in scan_bindings("def f(a: int, b=make):\n pass\n", "python")}
+ assert names == {"a", "b"}
+
+ def test_javascript_reads_with_the_typescript_shapes(self) -> None:
+ names = {n for _, n in scan_bindings("const f = (x, y) => x;", "javascript")}
+ assert {"f", "x", "y"} <= names