Skip to content

Commit c967797

Browse files
hopstreaxsafishamsi
authored andcommitted
Fix Python nested function resolution
(cherry picked from commit 416be1e)
1 parent 3f82bf7 commit c967797

2 files changed

Lines changed: 448 additions & 51 deletions

File tree

‎graphify/extractors/engine.py‎

Lines changed: 159 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -2161,6 +2161,75 @@ def _scan_js_nested_function_declarations(
21612161
)
21622162

21632163

2164+
def _scan_python_nested_function_declarations(
2165+
container_node, parent_nid: str, *, source: bytes, config,
2166+
add_node, add_edge, callable_def_nids: set | None,
2167+
local_bound_names: dict | None, function_bodies: list,
2168+
scope_parents: dict[str, str] | None = None,
2169+
lexical_nids_by_scope: dict[str, dict[str, str]] | None = None,
2170+
) -> None:
2171+
"""Emit a node + `contains` edge for every function lexically nested inside
2172+
*container_node*, scoped under *parent_nid*, track its body, and record lexical
2173+
scope hierarchy so calls resolve to local definitions instead of falling through
2174+
to corpus-wide resolution (#3405).
2175+
2176+
Recurses through Python statements (including blocks, if/while/for/try/with),
2177+
unwrapping `decorated_definition` when it wraps a `function_definition`.
2178+
"""
2179+
if container_node is None:
2180+
return
2181+
for child in container_node.children:
2182+
target = child
2183+
if target.type == "decorated_definition":
2184+
inner = target.child_by_field_name("definition")
2185+
if inner is not None:
2186+
target = inner
2187+
if target.type == "function_definition":
2188+
name_node = target.child_by_field_name(config.name_field)
2189+
if name_node is None:
2190+
for c in target.children:
2191+
if c.type in config.name_fallback_child_types:
2192+
name_node = c
2193+
break
2194+
func_name = _read_text(name_node, source) if name_node else None
2195+
if func_name and normalize_id(func_name):
2196+
line = target.start_point[0] + 1
2197+
nested_nid = _make_id(parent_nid, func_name)
2198+
add_node(nested_nid, f"{func_name}()", line)
2199+
add_edge(parent_nid, nested_nid, "contains", line)
2200+
if callable_def_nids is not None:
2201+
callable_def_nids.add(nested_nid)
2202+
if local_bound_names is not None:
2203+
local_bound_names[nested_nid] = _python_local_bound_names(target, source)
2204+
if scope_parents is not None:
2205+
scope_parents[nested_nid] = parent_nid
2206+
if lexical_nids_by_scope is not None:
2207+
lexical_nids_by_scope.setdefault(parent_nid, {})[func_name] = nested_nid
2208+
lexical_nids_by_scope.setdefault(nested_nid, {})[func_name] = nested_nid
2209+
nested_body = _find_body(target, config)
2210+
if nested_body:
2211+
function_bodies.append((nested_nid, nested_body))
2212+
_scan_python_nested_function_declarations(
2213+
nested_body, nested_nid, source=source, config=config,
2214+
add_node=add_node, add_edge=add_edge,
2215+
callable_def_nids=callable_def_nids,
2216+
local_bound_names=local_bound_names,
2217+
function_bodies=function_bodies,
2218+
scope_parents=scope_parents,
2219+
lexical_nids_by_scope=lexical_nids_by_scope,
2220+
)
2221+
else:
2222+
_scan_python_nested_function_declarations(
2223+
child, parent_nid, source=source, config=config,
2224+
add_node=add_node, add_edge=add_edge,
2225+
callable_def_nids=callable_def_nids,
2226+
local_bound_names=local_bound_names,
2227+
function_bodies=function_bodies,
2228+
scope_parents=scope_parents,
2229+
lexical_nids_by_scope=lexical_nids_by_scope,
2230+
)
2231+
2232+
21642233
def _js_topmost_closures(node, out: list) -> None:
21652234
"""Collect the TOPMOST closure nodes (arrow / function expressions) under
21662235
``node``, without descending into a found closure — its nested closures
@@ -3149,6 +3218,10 @@ def _extract_generic(
31493218
# guard skips any call-argument identifier in the enclosing function's set,
31503219
# so a param/local that shadows a module function name yields no edge.
31513220
local_bound_names: dict[str, set[str]] = {}
3221+
# Python nested-function lexical scope tracking (#3405): maps child_nid -> parent_scope_nid
3222+
scope_parents: dict[str, str] = {}
3223+
# maps scope_nid -> {bare_func_name -> nested_func_nid}
3224+
lexical_nids_by_scope: dict[str, dict[str, str]] = {}
31523225
# JS/TS only (#2568): per-BODY locals for sibling closures tracked under a
31533226
# single const nid by the #2552 branch (`const h = wrapper(cb1, cb2)`).
31543227
# Keyed by id(body) — like receiver_types_by_body — and fed to the per-body
@@ -4805,6 +4878,16 @@ def scala_base_name(type_node) -> str | None:
48054878
local_bound_names=local_bound_names,
48064879
function_bodies=function_bodies,
48074880
)
4881+
if config.ts_module == "tree_sitter_python":
4882+
_scan_python_nested_function_declarations(
4883+
body, func_nid, source=source, config=config,
4884+
add_node=add_node, add_edge=add_edge,
4885+
callable_def_nids=callable_def_nids,
4886+
local_bound_names=local_bound_names,
4887+
function_bodies=function_bodies,
4888+
scope_parents=scope_parents,
4889+
lexical_nids_by_scope=lexical_nids_by_scope,
4890+
)
48084891
if config.ts_module == "tree_sitter_kotlin":
48094892
# #2347: Kotlin anonymous objects (`object : Foo { … }`,
48104893
# node type `object_literal`). The function branch never
@@ -5039,8 +5122,14 @@ def scala_base_name(type_node) -> str | None:
50395122
continue
50405123
raw = n["label"]
50415124
normalised = raw.strip("()").lstrip(".")
5042-
label_to_nid[normalised] = n["id"]
5043-
label_to_nid_ci[normalised.lower()] = n["id"]
5125+
# For languages with lexical nesting (Python), nested functions should not overwrite
5126+
# module-level definitions in the module/file-level label_to_nid map (#3405).
5127+
if n["id"] not in scope_parents:
5128+
label_to_nid[normalised] = n["id"]
5129+
label_to_nid_ci[normalised.lower()] = n["id"]
5130+
else:
5131+
label_to_nid.setdefault(normalised, n["id"])
5132+
label_to_nid_ci.setdefault(normalised.lower(), n["id"])
50445133

50455134
seen_call_pairs: set[tuple[str, str]] = set()
50465135
seen_indirect_pairs: set[tuple[str, str]] = set() # Python indirect_call dedup
@@ -5745,7 +5834,18 @@ def walk_calls(
57455834
):
57465835
tgt_nid = None
57475836
else:
5748-
tgt_nid = label_to_nid.get(callee_name)
5837+
if config.ts_module == "tree_sitter_python" and not is_member_call:
5838+
curr_scope = caller_nid
5839+
tgt_nid = None
5840+
while curr_scope:
5841+
if curr_scope in lexical_nids_by_scope and callee_name in lexical_nids_by_scope[curr_scope]:
5842+
tgt_nid = lexical_nids_by_scope[curr_scope][callee_name]
5843+
break
5844+
curr_scope = scope_parents.get(curr_scope)
5845+
if not tgt_nid:
5846+
tgt_nid = label_to_nid.get(callee_name)
5847+
else:
5848+
tgt_nid = label_to_nid.get(callee_name)
57495849
# A qualified `new A.B.Foo()` whose bare name matches only a
57505850
# sourceless stub in this file would bind the call to the stub
57515851
# and never reach _resolve_csharp_qualified_calls, the one pass
@@ -5756,7 +5856,7 @@ def walk_calls(
57565856
and not nid_to_sf.get(tgt_nid)
57575857
):
57585858
tgt_nid = None
5759-
if tgt_nid and tgt_nid != caller_nid:
5859+
if tgt_nid:
57605860
pair = (caller_nid, tgt_nid)
57615861
if pair not in seen_call_pairs:
57625862
seen_call_pairs.add(pair)
@@ -5772,53 +5872,61 @@ def walk_calls(
57725872
"weight": 1.0,
57735873
})
57745874
elif callee_name and not tgt_nid:
5775-
# Callee not in this file — save for cross-file resolution in extract()
5776-
rc_entry = {
5777-
"caller_nid": caller_nid,
5778-
"callee": callee_name,
5779-
"is_member_call": is_member_call,
5780-
"source_file": str_path,
5781-
"source_location": f"L{node.start_point[0] + 1}",
5782-
"receiver": swift_receiver or member_receiver,
5783-
}
5784-
# Ruby: attach the receiver's inferred type from the method's
5785-
# local `var = Const.new` bindings, when unambiguously known.
5786-
if member_receiver and config.ts_module == "tree_sitter_ruby":
5787-
rc_entry["receiver_type"] = ruby_var_types.get(
5788-
caller_nid, {}
5789-
).get(member_receiver)
5790-
# Tag the C++ raw_call's language so the cross-file C++ resolver
5791-
# claims it unambiguously: a `.h` file routes to extract_cpp or
5792-
# extract_objc by content, and both resolvers see `.h` in their
5793-
# suffix sets, so a source_file suffix alone can't separate them.
5794-
if config.ts_module == "tree_sitter_cpp":
5795-
rc_entry["lang"] = "cpp"
5796-
# C#: tag the raw_call so _resolve_csharp_member_calls claims
5797-
# it, and stamp the receiver's type from the method's SCOPED
5798-
# bindings by the call's byte offset (#1609, per-method since
5799-
# #2299, position-aware since #2472). `this.field.M()` is
5800-
# covered too: member_receiver is the bare field name, and
5801-
# class fields/properties are the base scope.
5802-
if config.ts_module == "tree_sitter_c_sharp":
5803-
rc_entry["lang"] = "csharp"
5804-
if csharp_qualified_prefix:
5805-
rc_entry["qualified_prefix"] = csharp_qualified_prefix
5806-
receiver_type = _csharp_scoped_receiver_type(
5807-
receiver_types, member_receiver, node.start_byte
5808-
)
5809-
if receiver_type:
5810-
rc_entry["receiver_type"] = receiver_type
5811-
if config.ts_module == "tree_sitter_java":
5812-
rc_entry["lang"] = "java"
5813-
receiver_type = (receiver_types or {}).get(member_receiver or "")
5814-
if receiver_type:
5815-
rc_entry["receiver_type"] = receiver_type
5816-
# Kotlin fully-qualified call (#2550): the dotted prefix +
5817-
# lang tag let _resolve_kotlin_qualified_calls claim it.
5818-
if kotlin_qualified_prefix:
5819-
rc_entry["lang"] = "kotlin"
5820-
rc_entry["qualified_prefix"] = kotlin_qualified_prefix
5821-
raw_calls.append(rc_entry)
5875+
# In Python, if an unqualified call names a local non-callable variable or parameter,
5876+
# do NOT append it to raw_calls (#3405 Part 3/4).
5877+
is_py_local_data = (
5878+
config.ts_module == "tree_sitter_python"
5879+
and not is_member_call
5880+
and callee_name in (local_bound_names.get(caller_nid, frozenset()) | extra_locals)
5881+
)
5882+
if not is_py_local_data:
5883+
# Callee not in this file — save for cross-file resolution in extract()
5884+
rc_entry = {
5885+
"caller_nid": caller_nid,
5886+
"callee": callee_name,
5887+
"is_member_call": is_member_call,
5888+
"source_file": str_path,
5889+
"source_location": f"L{node.start_point[0] + 1}",
5890+
"receiver": swift_receiver or member_receiver,
5891+
}
5892+
# Ruby: attach the receiver's inferred type from the method's
5893+
# local `var = Const.new` bindings, when unambiguously known.
5894+
if member_receiver and config.ts_module == "tree_sitter_ruby":
5895+
rc_entry["receiver_type"] = ruby_var_types.get(
5896+
caller_nid, {}
5897+
).get(member_receiver)
5898+
# Tag the C++ raw_call's language so the cross-file C++ resolver
5899+
# claims it unambiguously: a `.h` file routes to extract_cpp or
5900+
# extract_objc by content, and both resolvers see `.h` in their
5901+
# suffix sets, so a source_file suffix alone can't separate them.
5902+
if config.ts_module == "tree_sitter_cpp":
5903+
rc_entry["lang"] = "cpp"
5904+
# C#: tag the raw_call so _resolve_csharp_member_calls claims
5905+
# it, and stamp the receiver's type from the method's SCOPED
5906+
# bindings by the call's byte offset (#1609, per-method since
5907+
# #2299, position-aware since #2472). `this.field.M()` is
5908+
# covered too: member_receiver is the bare field name, and
5909+
# class fields/properties are the base scope.
5910+
if config.ts_module == "tree_sitter_c_sharp":
5911+
rc_entry["lang"] = "csharp"
5912+
if csharp_qualified_prefix:
5913+
rc_entry["qualified_prefix"] = csharp_qualified_prefix
5914+
receiver_type = _csharp_scoped_receiver_type(
5915+
receiver_types, member_receiver, node.start_byte
5916+
)
5917+
if receiver_type:
5918+
rc_entry["receiver_type"] = receiver_type
5919+
if config.ts_module == "tree_sitter_java":
5920+
rc_entry["lang"] = "java"
5921+
receiver_type = (receiver_types or {}).get(member_receiver or "")
5922+
if receiver_type:
5923+
rc_entry["receiver_type"] = receiver_type
5924+
# Kotlin fully-qualified call (#2550): the dotted prefix +
5925+
# lang tag let _resolve_kotlin_qualified_calls claim it.
5926+
if kotlin_qualified_prefix:
5927+
rc_entry["lang"] = "kotlin"
5928+
rc_entry["qualified_prefix"] = kotlin_qualified_prefix
5929+
raw_calls.append(rc_entry)
58225930

58235931
# Indirect dispatch: a function passed BY NAME as a call argument
58245932
# (executor.submit(fn), Thread(target=fn), map(fn, xs)) is a real dependency

0 commit comments

Comments
 (0)