fix(cpp): keep local callable values out of global call resolution
Refs #4917.
Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit a8cf1d4103)
This commit is contained in:
1 parent
9466cac7e5
commit
bd318e933c
2 files changed
+73
No files matched your search
@@ -3148,6 +3148,34 @@ def _cpp_qualified_name(node, name: str, source: bytes) -> str:
|
||||
return "::".join([*reversed(parents), name])
|
||||
|
||||
|
||||
def _cpp_local_binding_ranges(body, source: bytes) -> dict[str, list[tuple[int, int]]]:
|
||||
"""Lexical lifetimes of named C++ locals/parameters, not corpus callees."""
|
||||
ranges: dict[str, list[tuple[int, int]]] = {}
|
||||
scopes = {"compound_statement", "for_statement", "for_range_loop", "if_statement",
|
||||
"switch_statement", "catch_clause", "function_definition", "lambda_expression"}
|
||||
stack = [body]
|
||||
function = body.parent
|
||||
if function is not None and function.type == "function_definition":
|
||||
declarator = function.child_by_field_name("declarator")
|
||||
if declarator is not None:
|
||||
stack.append(declarator)
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if node.type in {"class_specifier", "struct_specifier", "function_definition"}:
|
||||
continue
|
||||
if node.type in {"declaration", "parameter_declaration", "optional_parameter_declaration"}:
|
||||
scope = node.parent
|
||||
while scope is not None and scope.type not in scopes:
|
||||
scope = scope.parent
|
||||
if scope is not None:
|
||||
for declarator in node.children_by_field_name("declarator"):
|
||||
name = _cpp_declarator_name(declarator, source)
|
||||
if name:
|
||||
ranges.setdefault(name, []).append((declarator.start_byte, scope.end_byte))
|
||||
stack.extend(node.named_children)
|
||||
return ranges
|
||||
|
||||
|
||||
def _cpp_local_var_types(body_node, source: bytes, table: dict[str, str]) -> None:
|
||||
"""Collect ``var -> ClassName`` from local variable declarations in a C++
|
||||
function body, for receiver-type inference in the cross-file member-call pass
|
||||
@@ -9851,6 +9879,9 @@ def _extract_generic(
|
||||
if func_node:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
if any(start <= node.start_byte < end for start, end in
|
||||
cpp_local_bindings.get(caller_nid, {}).get(callee_name, ())):
|
||||
callee_name = None
|
||||
elif func_node.type == "field_expression":
|
||||
# `f.bar()` / `f->bar()` / `this->bar()`: receiver is the
|
||||
# `argument` (object) field, callee is the `field` (#1547).
|
||||
@@ -10719,6 +10750,7 @@ def _extract_generic(
|
||||
# every function body so the cross-file member-call pass can type a receiver
|
||||
# (#1547). File-scoped (not per-body): a later body's `Foo f;` doesn't clobber
|
||||
# an earlier binding (`var not in table`), keeping resolution conservative.
|
||||
cpp_local_bindings: dict[str, dict[str, list[tuple[int, int]]]] = {}
|
||||
if config.ts_module == "tree_sitter_cpp":
|
||||
# Each function's table first: a local shadows a parameter there. The
|
||||
# file table is shared by every function, so a name typed differently in
|
||||
@@ -10736,6 +10768,7 @@ def _extract_generic(
|
||||
_cpp_local_var_types(body_node, source, fn_table)
|
||||
_cpp_parameter_types(body_node, source, fn_table)
|
||||
_fold(fn_table)
|
||||
cpp_local_bindings[_caller_nid] = _cpp_local_binding_ranges(body_node, source)
|
||||
field_table: dict[str, str] = {}
|
||||
_cpp_field_types(root, source, field_table)
|
||||
_fold(field_table)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Local C++ values cannot bind to same-named corpus symbols."""
|
||||
import pytest
|
||||
from graphify.extract import extract
|
||||
|
||||
|
||||
@pytest.mark.parametrize("declaration", ["auto box = [](int x){return x;};", "std::function<int(int)> box = [](int x){return x;};", "TFunction<int(int)> box;"])
|
||||
@pytest.mark.parametrize("same_file", [False, True])
|
||||
def test_local_callable_shadows_function(tmp_path, declaration, same_file):
|
||||
other = "int box(int x){return x;}"
|
||||
a = tmp_path / "a.cpp"
|
||||
a.write_text((other if same_file else "") + "\nint run(){" + declaration + " return box(1);}", encoding="utf-8")
|
||||
paths = [a]
|
||||
if not same_file:
|
||||
b = tmp_path / "b.cpp"
|
||||
b.write_text(other, encoding="utf-8")
|
||||
paths.append(b)
|
||||
r = extract(paths, root=tmp_path, parallel=False, cache_root=tmp_path)
|
||||
caller = next(n["id"] for n in r["nodes"] if n["label"] == "run()")
|
||||
assert not any(e["source"] == caller and e["relation"] == "calls" for e in r["edges"])
|
||||
|
||||
|
||||
def test_block_local_does_not_hide_a_later_free_call(tmp_path):
|
||||
a = tmp_path / "a.cpp"
|
||||
a.write_text("void box() {}\nvoid run() {{auto box=[]{}; box();} box();}", encoding="utf-8")
|
||||
r = extract([a], root=tmp_path, parallel=False, cache_root=tmp_path)
|
||||
calls = [e for e in r["edges"] if e["relation"] == "calls"]
|
||||
assert len(calls) == 1
|
||||
assert calls[0]["source_location"] == "L2"
|
||||
|
||||
|
||||
def test_parameter_shadowing_keeps_nested_argument_calls(tmp_path):
|
||||
a = tmp_path / "a.cpp"
|
||||
a.write_text("int helper(){return 1;}\nint run(std::function<int(int)> box){return box(helper());}", encoding="utf-8")
|
||||
b = tmp_path / "b.cpp"
|
||||
b.write_text("int box(int x){return x;}", encoding="utf-8")
|
||||
r = extract([a,b], root=tmp_path, parallel=False, cache_root=tmp_path)
|
||||
nodes = {n["id"]: n for n in r["nodes"]}
|
||||
caller = next(n["id"] for n in r["nodes"] if n["label"] == "run()")
|
||||
calls = [e for e in r["edges"] if e["source"] == caller and e["relation"] == "calls"]
|
||||
assert [nodes[e["target"]]["label"] for e in calls] == ["helper()"]
|
||||
Reference in new issue
Block a user