fix(js): resolve calls through default-exported object methods
Refs #4963
(cherry picked from commit fadb09db1a)
This commit is contained in:
1 parent
2460bab3b9
commit
5bab54d8d6
5 files changed
+329
-8
No files matched your search
@@ -79,6 +79,11 @@ Every extractor returns:
|
||||
|
||||
`validate.py` enforces this schema before `build()` consumes it.
|
||||
|
||||
JS/TS calls through default imports of directly default-exported object literals reuse existing static method nodes.
|
||||
Members match the imported module path, exact label and source line. Lexically shadowed receivers, constructor calls,
|
||||
spread, computed keys, accessors, duplicate keys and dynamic aliases are not inferred. These files bypass the per-file
|
||||
AST cache, so resolving these cross-file calls does not require an AST cache schema bump.
|
||||
|
||||
|
||||
## Semantic provenance during file-node folding
|
||||
|
||||
|
||||
@@ -10284,6 +10284,7 @@ def extract(
|
||||
paths, all_nodes, all_edges, root,
|
||||
ambiguous_python_modules=ambiguous_python_modules,
|
||||
resolution_context_nodes=resolution_context_nodes,
|
||||
raw_calls=all_raw_calls,
|
||||
)
|
||||
|
||||
# Merge a header-declared class (and its methods) with its sibling-impl
|
||||
|
||||
@@ -2831,6 +2831,44 @@ def _js_direct_lexical_names(node, source: bytes) -> frozenset[str]:
|
||||
_js_collect_pattern_idents(name, source, names)
|
||||
return frozenset(names)
|
||||
|
||||
def _js_receiver_shadowed(node, name: str | None, source: bytes, bindings_by_scope: dict) -> bool:
|
||||
"""接收者必须沿调用点的全部词法祖先查找绑定,独立追踪的内层函数也不能丢失外层遮蔽。"""
|
||||
if not name:
|
||||
return False
|
||||
scope = node.parent
|
||||
while scope is not None:
|
||||
bindings = bindings_by_scope.get(scope)
|
||||
if bindings is None:
|
||||
bound: set[str] = set()
|
||||
if scope.type in _JS_SCOPE_BOUNDARY:
|
||||
bound.update(_js_local_bound_names(scope, source))
|
||||
if scope.type not in ("method_definition", "arrow_function"):
|
||||
own_name = scope.child_by_field_name("name")
|
||||
if own_name is not None:
|
||||
bound.add(_read_text(own_name, source))
|
||||
if scope.type in ("program", "statement_block", "for_statement"):
|
||||
bound.update(_js_direct_lexical_names(scope, source))
|
||||
for child in scope.named_children:
|
||||
if child.type in (
|
||||
"function_declaration", "generator_function_declaration",
|
||||
"class_declaration", "abstract_class_declaration",
|
||||
):
|
||||
declared_name = child.child_by_field_name("name")
|
||||
if declared_name is not None:
|
||||
bound.add(_read_text(declared_name, source))
|
||||
if scope.type in ("catch_clause", "for_in_statement"):
|
||||
field = "parameter" if scope.type == "catch_clause" else "left"
|
||||
pattern = scope.child_by_field_name(field)
|
||||
if pattern is not None:
|
||||
_js_collect_pattern_idents(pattern, source, bound)
|
||||
bindings = frozenset(bound)
|
||||
bindings_by_scope[scope] = bindings
|
||||
if name in bindings:
|
||||
return True
|
||||
scope = scope.parent
|
||||
return False
|
||||
|
||||
|
||||
def _js_module_bound_names(root, source: bytes) -> set[str]:
|
||||
"""Module-scope names rebound to NON-function data (`const X = {...}`, `let y = 5`).
|
||||
|
||||
@@ -6385,6 +6423,7 @@ def _extract_generic(
|
||||
# walk_calls as extra_locals, so each closure sees only its own
|
||||
# params/locals instead of a shared union that over-suppresses siblings.
|
||||
closure_locals_by_body: dict[int, set[str]] = {}
|
||||
js_receiver_bindings: dict = {}
|
||||
# PHP only: ordinal counter for anonymous closures, keyed by scope id
|
||||
# (parent_class_nid or stem). Stable across line-only edits (#3409).
|
||||
php_closure_counts: dict[str, int] = {}
|
||||
@@ -10304,6 +10343,13 @@ def _extract_generic(
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"receiver": swift_receiver or member_receiver,
|
||||
}
|
||||
if config.ts_module in (
|
||||
"tree_sitter_javascript", "tree_sitter_typescript",
|
||||
) and is_member_call:
|
||||
rc_entry["_js_receiver_shadowed"] = _js_receiver_shadowed(
|
||||
node, member_receiver, source, js_receiver_bindings,
|
||||
)
|
||||
rc_entry["_js_construct"] = node.type == "new_expression"
|
||||
if python_receiver_shadowed is not None and is_member_call:
|
||||
rc_entry["_python_receiver_shadowed"] = python_receiver_shadowed(
|
||||
node, member_receiver or ""
|
||||
|
||||
@@ -1268,6 +1268,7 @@ def _apply_symbol_resolution_facts(
|
||||
root: Path,
|
||||
facts: _SymbolResolutionFacts,
|
||||
resolution_context_nodes: list[dict] | None = None,
|
||||
raw_calls: list[dict] | None = None,
|
||||
) -> None:
|
||||
"""Apply language-provided import/export/use facts to graph edges."""
|
||||
if not (
|
||||
@@ -1690,6 +1691,55 @@ def _apply_symbol_resolution_facts(
|
||||
import_fact.file_path,
|
||||
)
|
||||
|
||||
if raw_calls and any(
|
||||
fact.imported_name == "default"
|
||||
and effective_suffix(fact.file_path) in _JS_CACHE_BYPASS_SUFFIXES
|
||||
for fact in facts.imports
|
||||
):
|
||||
default_imports = {
|
||||
(_resolve_cached(fact.file_path), fact.local_name): _resolve_cached(fact.target_path)
|
||||
for fact in facts.imports
|
||||
if fact.imported_name == "default"
|
||||
and effective_suffix(fact.file_path) in _JS_CACHE_BYPASS_SUFFIXES
|
||||
}
|
||||
member_nodes: dict[tuple[Path, str, str], set[str]] = {}
|
||||
fresh_paths = {_resolve_cached(path) for path in paths}
|
||||
for node in nodes + [
|
||||
node for node in resolution_context_nodes or []
|
||||
if _js_source_path(str(node.get("source_file", "")), root) not in fresh_paths
|
||||
]:
|
||||
if not node.get("_callable"):
|
||||
continue
|
||||
source_path = _js_source_path(str(node.get("source_file", "")), root)
|
||||
if source_path is None:
|
||||
continue
|
||||
key = (source_path, str(node.get("label", "")), str(node.get("source_location", "")))
|
||||
member_nodes.setdefault(key, set()).add(str(node["id"]))
|
||||
default_members: dict[Path, dict[str, tuple[str, str]]] = {}
|
||||
for call in raw_calls:
|
||||
if (not call.get("is_member_call") or call.get("_js_receiver_shadowed")
|
||||
or call.get("_js_construct") or call.get("ts_this_field")):
|
||||
continue
|
||||
source_path = _js_source_path(str(call.get("source_file", "")), root)
|
||||
if source_path is None:
|
||||
continue
|
||||
target_path = default_imports.get((source_path, str(call.get("receiver") or "")))
|
||||
if target_path is None:
|
||||
continue
|
||||
if target_path not in default_members:
|
||||
default_members[target_path] = _js_default_object_members(target_path)
|
||||
member = default_members[target_path].get(str(call.get("callee") or ""))
|
||||
if member is None:
|
||||
continue
|
||||
targets = member_nodes.get((target_path, *member), set())
|
||||
if len(targets) != 1:
|
||||
continue
|
||||
add_edge(
|
||||
call["caller_nid"], next(iter(targets)), "calls", "call",
|
||||
int(str(call["source_location"]).removeprefix("L")),
|
||||
Path(call["source_file"]), target_file=str(target_path),
|
||||
)
|
||||
|
||||
# The structural extractor names the imported symbol on the immediate barrel,
|
||||
# which defines nothing, so its edge dangles and build mints an external stub
|
||||
# beside the edge the loop above added to the defining symbol (#4486). Drop
|
||||
@@ -2014,14 +2064,7 @@ def _js_default_import_name(node, source: bytes) -> str | None:
|
||||
return None
|
||||
|
||||
def _js_default_export_name(node, source: bytes) -> str | None:
|
||||
"""Local name of a default export, or None for anonymous defaults.
|
||||
|
||||
Handles `export default class Foo {}`, `export default function foo() {}`,
|
||||
`export default abstract class Foo {}` (name on the `declaration` field) and
|
||||
`export default Foo` (an identifier on the `value` field). Anonymous defaults
|
||||
(`export default class {}`, `export default {...}`) have no resolvable symbol
|
||||
and return None.
|
||||
"""
|
||||
"""返回默认导出的本地绑定名;匿名对象的成员由 _js_default_object_members 单独解析。"""
|
||||
if not any(child.type == "default" for child in node.children):
|
||||
return None
|
||||
declaration = node.child_by_field_name("declaration")
|
||||
@@ -2033,6 +2076,45 @@ def _js_default_export_name(node, source: bytes) -> str | None:
|
||||
return _read_text(value, source)
|
||||
return None
|
||||
|
||||
def _js_default_object_members(path: Path) -> dict[str, tuple[str, str]]:
|
||||
"""仅返回直接默认对象中可定位到已有节点的静态方法。"""
|
||||
parsed = _parse_js_tree(path)
|
||||
if parsed is None:
|
||||
return {}
|
||||
source, root_node = parsed
|
||||
for node in root_node.named_children:
|
||||
if node.type != "export_statement" or not any(
|
||||
child.type == "default" for child in node.children
|
||||
):
|
||||
continue
|
||||
value = node.child_by_field_name("value")
|
||||
if value is None or value.type != "object":
|
||||
continue
|
||||
members: dict[str, tuple[str, str]] = {}
|
||||
seen: set[str] = set()
|
||||
for prop in value.named_children:
|
||||
if prop.type == "comment":
|
||||
continue
|
||||
key = prop.child_by_field_name("name") or prop.child_by_field_name("key")
|
||||
# spread 和计算键可能覆盖任意方法,不能仅凭同名节点补边。
|
||||
if key is None or key.type not in ("property_identifier", "string"):
|
||||
return {}
|
||||
raw_name = _read_text(key, source)
|
||||
if "\\" in raw_name:
|
||||
return {}
|
||||
name = raw_name[1:-1] if key.type == "string" else raw_name
|
||||
if name in seen:
|
||||
members.pop(name, None)
|
||||
continue
|
||||
seen.add(name)
|
||||
if prop.type == "method_definition" and not any(
|
||||
child.type in ("get", "set") for child in prop.children
|
||||
):
|
||||
members[name] = (f"{raw_name}()", f"L{prop.start_point[0] + 1}")
|
||||
return members
|
||||
return {}
|
||||
|
||||
|
||||
def _js_top_level_function_bodies(path: Path, root_node, source: bytes) -> list[tuple[str, object]]:
|
||||
bodies: list[tuple[str, object]] = []
|
||||
stem = _file_stem(path)
|
||||
@@ -2963,6 +3045,7 @@ def _augment_symbol_resolution_edges(
|
||||
root: Path,
|
||||
ambiguous_python_modules: set[str] | None = None,
|
||||
resolution_context_nodes: list[dict] | None = None,
|
||||
raw_calls: list[dict] | None = None,
|
||||
) -> None:
|
||||
facts = _SymbolResolutionFacts()
|
||||
_collect_js_symbol_resolution_facts(paths, facts)
|
||||
@@ -2974,7 +3057,10 @@ def _augment_symbol_resolution_edges(
|
||||
_apply_symbol_resolution_facts(
|
||||
paths, nodes, edges, root, facts,
|
||||
resolution_context_nodes=resolution_context_nodes,
|
||||
raw_calls=raw_calls,
|
||||
)
|
||||
elif raw_calls:
|
||||
_apply_symbol_resolution_facts(paths, nodes, edges, root, facts, raw_calls=raw_calls)
|
||||
else:
|
||||
_apply_symbol_resolution_facts(paths, nodes, edges, root, facts)
|
||||
|
||||
|
||||
@@ -753,6 +753,189 @@ def test_default_import_call_resolves_to_default_exported_function(tmp_path: Pat
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("suffix", [".ts", ".js"])
|
||||
@pytest.mark.parametrize("binding", ["native", "renamed"])
|
||||
def test_default_object_member_call_resolves(tmp_path: Path, suffix: str, binding: str):
|
||||
target = _write(tmp_path / f"native{suffix}", "export default { toast() {} };\n")
|
||||
importer = _write(
|
||||
tmp_path / f"app{suffix}",
|
||||
f"import {binding} from './native';\n"
|
||||
f"export function run() {{ {binding}.toast(); }}\n",
|
||||
)
|
||||
|
||||
result = _extract_for([target, importer], tmp_path)
|
||||
|
||||
assert _has_symbol_to_symbol_edge(
|
||||
result, f"app{suffix}", "run", f"native{suffix}", "toast", "calls"
|
||||
)
|
||||
methods = [node for node in result["nodes"] if node.get("label") == "toast()"]
|
||||
assert len(methods) == 1
|
||||
assert methods[0]["source_file"] == f"native{suffix}"
|
||||
assert not any(node.get("label") == "default" for node in result["nodes"])
|
||||
|
||||
|
||||
def test_default_object_member_calls_stay_in_imported_module(tmp_path: Path):
|
||||
left = _write(tmp_path / "left/native.ts", "export default { toast() {} };\n")
|
||||
right = _write(tmp_path / "right/native.ts", "export default { toast() {} };\n")
|
||||
importer = _write(
|
||||
tmp_path / "app.ts",
|
||||
"import left from './left/native';\n"
|
||||
"import right from './right/native';\n"
|
||||
"function useLeft() { left.toast(); }\n"
|
||||
"function useRight() { right.toast(); }\n",
|
||||
)
|
||||
|
||||
for paths in ([left, right, importer], [importer, right, left]):
|
||||
result = _extract_for(paths, tmp_path)
|
||||
for caller, target in (("useLeft", "left/native.ts"), ("useRight", "right/native.ts")):
|
||||
assert _has_symbol_to_symbol_edge(result, "app.ts", caller, target, "toast", "calls")
|
||||
other = "right/native.ts" if target == "left/native.ts" else "left/native.ts"
|
||||
assert _has_no_symbol_to_symbol_edge(result, "app.ts", caller, other, "toast", "calls")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exported",
|
||||
[
|
||||
"export default { toast() {} };",
|
||||
"const key = 'toast'; export default { [key]() {} };",
|
||||
"export default { ['toast']() {} };",
|
||||
"const extra = {}; export default { toast() {}, ...extra };",
|
||||
"const extra = {}; export default { ...extra, toast() {} };",
|
||||
"export default { toast() {}, toast: 1 };",
|
||||
"export default { get toast() { return () => {}; } };",
|
||||
"export default { nested: { toast() {} } };",
|
||||
],
|
||||
)
|
||||
def test_default_object_unknown_or_uncertain_member_has_no_call(tmp_path: Path, exported: str):
|
||||
target = _write(tmp_path / "native.ts", exported + "\n")
|
||||
importer = _write(
|
||||
tmp_path / "app.ts",
|
||||
"import native from './native';\n"
|
||||
"function run() { native.missing(); native.toast(); }\n",
|
||||
)
|
||||
unrelated = _write(tmp_path / "other.ts", "export function missing() {}\n")
|
||||
|
||||
result = _extract_for([target, importer, unrelated], tmp_path)
|
||||
calls = [edge for edge in result["edges"] if edge["relation"] == "calls"]
|
||||
|
||||
if exported == "export default { toast() {} };":
|
||||
assert _has_symbol_to_symbol_edge(result, "app.ts", "run", "native.ts", "toast", "calls")
|
||||
assert len(calls) == 1
|
||||
else:
|
||||
assert calls == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"statement",
|
||||
[
|
||||
"import * as native from './native'; function run() { native.toast(); }",
|
||||
"import { native } from './native'; function run() { native.toast(); }",
|
||||
"import native from './native'; const alias = native; function run() { alias.toast(); }",
|
||||
"import native from './native'; function run(native: any) { native.toast(); }",
|
||||
"import native from './native'; function run() { const native = {}; native.toast(); }",
|
||||
"import native from './native'; function run() { native['toast'](); }",
|
||||
],
|
||||
)
|
||||
def test_default_object_member_requires_direct_default_binding(tmp_path: Path, statement: str):
|
||||
target = _write(tmp_path / "native.ts", "export default { toast() {} };\n")
|
||||
importer = _write(tmp_path / "app.ts", statement + "\n")
|
||||
|
||||
result = _extract_for([target, importer], tmp_path)
|
||||
|
||||
assert not [edge for edge in result["edges"] if edge["relation"] == "calls"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
"function run(native: any) { function inner() { native.toast(); } inner(); }",
|
||||
"function run() { const native = {}; function inner() { native.toast(); } inner(); }",
|
||||
"function run() { function native() {} native.toast(); }",
|
||||
"function run() { class native {} native.toast(); }",
|
||||
"function run() { const inner = function native() { native.toast(); }; inner(); }",
|
||||
"function run() { new native.toast(); }",
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("incremental", [False, True])
|
||||
def test_default_object_member_requires_unshadowed_method_call(
|
||||
tmp_path: Path, body: str, incremental: bool,
|
||||
):
|
||||
target = _write(tmp_path / "native.ts", "export default { toast() {} };\n")
|
||||
importer = _write(tmp_path / "app.ts", "import native from './native';\n" + body + "\n")
|
||||
|
||||
if incremental:
|
||||
baseline = extract([target], root=tmp_path, cache_root=tmp_path, parallel=False)
|
||||
result = extract(
|
||||
[importer], root=tmp_path, cache_root=tmp_path, parallel=False,
|
||||
resolution_context_nodes=baseline["nodes"],
|
||||
)
|
||||
else:
|
||||
result = _extract_for([target, importer], tmp_path)
|
||||
|
||||
target_id = _make_id(_file_stem(Path("native.ts")), "toast")
|
||||
assert not [
|
||||
edge for edge in result["edges"]
|
||||
if edge["relation"] == "calls" and edge["target"] == target_id
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
"function run() { function inner() { native.toast(); } inner(); }",
|
||||
"function run() { { const native = {}; } function inner() { native.toast(); } inner(); }",
|
||||
"function run() { { class native {} } native.toast(); }",
|
||||
],
|
||||
)
|
||||
def test_default_object_member_keeps_calls_outside_shadow_scope(tmp_path: Path, body: str):
|
||||
target = _write(tmp_path / "native.ts", "export default { toast() {} };\n")
|
||||
importer = _write(tmp_path / "app.ts", "import native from './native';\n" + body + "\n")
|
||||
|
||||
result = _extract_for([target, importer], tmp_path)
|
||||
|
||||
target_id = _make_id(_file_stem(Path("native.ts")), "toast")
|
||||
assert len([
|
||||
edge for edge in result["edges"]
|
||||
if edge["relation"] == "calls" and edge["target"] == target_id
|
||||
]) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["toast", "'toast'", '"toast"'])
|
||||
def test_default_object_member_call_from_class(tmp_path: Path, method: str):
|
||||
target = _write(tmp_path / "native.ts", f"export default {{ {method}() {{}} }};\n")
|
||||
importer = _write(
|
||||
tmp_path / "app.ts",
|
||||
"import renamed from './native';\n"
|
||||
"class App { run() { renamed.toast(); } }\n",
|
||||
)
|
||||
|
||||
result = _extract_for([target, importer], tmp_path)
|
||||
|
||||
calls = [edge for edge in result["edges"] if edge["relation"] == "calls"]
|
||||
assert len(calls) == 1
|
||||
nodes = {node["id"]: node for node in result["nodes"]}
|
||||
assert nodes[calls[0]["source"]]["label"] == ".run()"
|
||||
assert nodes[calls[0]["target"]]["source_file"] == "native.ts"
|
||||
assert nodes[calls[0]["target"]]["label"] == f"{method}()"
|
||||
assert calls[0]["confidence"] == "EXTRACTED"
|
||||
|
||||
|
||||
def test_default_object_changed_caller_resolves_with_context(tmp_path: Path):
|
||||
target = _write(tmp_path / "native.ts", "export default { toast() {} };\n")
|
||||
baseline = extract([target], root=tmp_path, cache_root=tmp_path, parallel=False)
|
||||
importer = _write(
|
||||
tmp_path / "app.ts",
|
||||
"import native from './native';\nfunction run() { native.toast(); }\n",
|
||||
)
|
||||
|
||||
result = extract(
|
||||
[importer], root=tmp_path, cache_root=tmp_path, parallel=False,
|
||||
resolution_context_nodes=baseline["nodes"],
|
||||
)
|
||||
|
||||
assert _has_symbol_to_symbol_edge(result, "app.ts", "run", "native.ts", "toast", "calls")
|
||||
|
||||
|
||||
def test_pnpm_workspace_package_import_resolves_package_entry(tmp_path: Path):
|
||||
_write(
|
||||
tmp_path / "pnpm-workspace.yaml",
|
||||
|
||||
Reference in new issue
Block a user