Skip to content

Commit 41b4e19

Browse files
xiongjianxusafishamsi
authored andcommitted
Finish Objective-C member calls across a repository boundary (#3152)
`_resolve_objc_member_calls` types a receiver from `self`/`super`, an explicit class name, the file's local table or the class's @property/ivar table, then requires exactly one declaration of that type. Zero declarations and more than one shared a single bail, so a call into a class another repository declares was dropped with the receiver type already in hand — the case #3152 parks for the merge in Java, C++, C# and Swift. Split the three type-known bails: zero declarations parks `{callee, receiver_type, lang: "objc", line}` on the caller, more than one stays dropped as before (a local ambiguity that merging only widens). A builtin receiver type is filtered out at the parking sites, matching what the Swift and C++ resolvers already skip before resolving. On the merge side an ObjC method label keeps its `+`/`-` sigil where every other extractor writes `.name()`, and a parked selector does not say which was meant, so both spellings are tried and a class declaring both counts as ambiguous. The sigil is what keeps ObjC and C++ members disjoint inside a shared `.h`, which is in both languages' suffix sets. Depends on the `_callable` / `_callable_class` markers (#3228) that `_index_declarations` indexes declarations by; the commit before this one carries them. (cherry picked from commit 487fd54)
1 parent 70f1022 commit 41b4e19

3 files changed

Lines changed: 140 additions & 11 deletions

File tree

‎graphify/cross_repo_calls.py‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
"go": frozenset({".go"}),
4545
"java": frozenset({".java"}),
4646
"kotlin": frozenset({".kt", ".kts"}),
47+
"objc": frozenset({".h", ".m", ".mm"}),
4748
"swift": frozenset({".swift"}),
4849
"php": frozenset({".php", ".phtml", ".php3", ".php4", ".php5", ".php7", ".phps"}),
4950
# TS and JS share one key: a TS class legitimately answers a JS call site, so
@@ -65,7 +66,8 @@ def _key(label: object) -> str:
6566
Type labels are plain (``Greeter``) while method labels carry the extractor's
6667
decoration (``.greet()``). Case is preserved: every language that parks calls
6768
here is case-sensitive, and folding case would let `greeter` answer for
68-
`Greeter`.
69+
`Greeter`. Objective-C's ``+``/``-`` sigil is deliberately kept, so an ObjC
70+
``-greet`` and a C++ ``.greet()`` stay distinct members of a shared header.
6971
"""
7072
return str(label or "").strip().removeprefix(".").removesuffix("()")
7173

@@ -156,6 +158,20 @@ def _member_relations(lang: str) -> tuple[str, ...]:
156158
return ("method", "defines") if lang == "cpp" else ("method",)
157159

158160

161+
def _member_keys(lang: str, callee: str) -> tuple[str, ...]:
162+
"""Which member-index keys a parked callee may answer to.
163+
164+
An ObjC selector carries no class/instance distinction, so both sigils are
165+
tried; a type declaring `+greet` and `-greet` both is an ambiguity, not a hit.
166+
A selector cannot itself begin with a sigil, so stripping one first keeps an
167+
entry that already carries it from asking for `--greet`.
168+
"""
169+
if lang == "objc":
170+
selector = callee.lstrip("+-")
171+
return (f"-{selector}", f"+{selector}")
172+
return (callee,)
173+
174+
159175
def link_cross_repo_member_calls(merged: "nx.Graph") -> int:
160176
"""Emit `calls` edges for parked member calls another repo answers.
161177
@@ -229,7 +245,9 @@ def link_cross_repo_member_calls(merged: "nx.Graph") -> int:
229245
continue
230246
targets: list[str] = []
231247
for relation in _member_relations(lang):
232-
targets = members_by_relation[relation].get((candidates[0], callee), [])
248+
members = members_by_relation[relation]
249+
for member_key in _member_keys(lang, callee):
250+
targets.extend(members.get((candidates[0], member_key), []))
233251
if targets:
234252
break
235253
if len(targets) != 1:

‎graphify/extract.py‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6130,7 +6130,9 @@ def _resolve_objc_member_calls(
61306130
captured; a dotted receiver like ``Foo.shared`` is never passed through,
61316131
because ``_key`` would strip the dot and collide with a real ``FooShared``.
61326132
An uninferable receiver is SKIPPED (no guess), so an ambiguous selector across
6133-
classes never fans out. ``_merge_decl_def_classes`` folds each @interface/@impl
6133+
classes never fans out. A receiver typed to a class this corpus declares nowhere
6134+
is parked on the caller for a merged graph to finish (#3152).
6135+
``_merge_decl_def_classes`` folds each @interface/@impl
61346136
pair into one node, so a paired class clears the single-definition guard.
61356137
``@protocol`` declarations are excluded from the receiver-type index: a protocol
61366138
is a contract, not a message receiver, and ObjC keeps protocol and class names in
@@ -6229,6 +6231,16 @@ def _field_type_up_chain(cls, receiver):
62296231
queue.extend(_objc_bases.get(c, []))
62306232
return None
62316233

6234+
def _park_absent(caller: str, callee: str, type_name: str, rc: dict) -> None:
6235+
"""Park a typed receiver whose class is declared nowhere here (#3152).
6236+
6237+
A builtin type (NSString, DispatchQueue, ...) is not what another repo
6238+
declares, so parking one would only let a same-named user class answer it.
6239+
"""
6240+
if type_name in _LANGUAGE_BUILTIN_GLOBALS:
6241+
return
6242+
_park_unresolved_member_call(node_by_id.get(caller), callee, type_name, "objc", rc)
6243+
62326244
for rc in all_raw_calls:
62336245
if not rc.get("is_member_call"):
62346246
continue
@@ -6249,7 +6261,10 @@ def _field_type_up_chain(cls, receiver):
62496261
if not type_name:
62506262
continue
62516263
type_defs = type_def_nids.get(_key(type_name), [])
6252-
if len(type_defs) != 1: # ambiguous or absent -> bail (god-node guard)
6264+
if not type_defs:
6265+
_park_absent(caller, callee, type_name, rc)
6266+
continue
6267+
if len(type_defs) != 1: # ambiguous -> bail (god-node guard)
62536268
continue
62546269
type_nid = type_defs[0]
62556270
type_qualified = False
@@ -6260,7 +6275,10 @@ def _field_type_up_chain(cls, receiver):
62606275
type_qualified = True
62616276
elif receiver[:1].isupper():
62626277
type_defs = type_def_nids.get(_key(receiver), [])
6263-
if len(type_defs) != 1: # ambiguous or absent -> bail (god-node guard)
6278+
if not type_defs:
6279+
_park_absent(caller, callee, receiver, rc)
6280+
continue
6281+
if len(type_defs) != 1: # ambiguous -> bail (god-node guard)
62646282
continue
62656283
type_nid = type_defs[0]
62666284
type_qualified = True
@@ -6274,7 +6292,10 @@ def _field_type_up_chain(cls, receiver):
62746292
if not type_name:
62756293
continue
62766294
type_defs = type_def_nids.get(_key(type_name), [])
6277-
if len(type_defs) != 1: # ambiguous or absent -> bail (god-node guard)
6295+
if not type_defs:
6296+
_park_absent(caller, callee, type_name, rc)
6297+
continue
6298+
if len(type_defs) != 1: # ambiguous -> bail (god-node guard)
62786299
continue
62796300
type_nid = type_defs[0]
62806301
type_qualified = False

‎tests/test_cross_repo_member_calls.py‎

Lines changed: 95 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@
66
`merge-graphs` and `global add` read. The two-repo graph was missing precisely the
77
edges that make it a call graph.
88
9-
The Java, C++, C#, Swift, Go, Kotlin, PHP and TS/JS resolvers now park those calls on
10-
the caller node and this pass finishes them after the merge. The cases below pin what
11-
it must NOT do as much as what it must: the single-definition guard, the cross-repo-only
12-
scope, and the language guard are what keep it from fabricating an edge from a name
13-
collision.
9+
The Java, C++, C#, Swift, Go, Kotlin, Objective-C, PHP and TS/JS resolvers now park
10+
those calls on the caller node and this pass finishes them after the merge. The cases
11+
below pin what it must NOT do as much as what it must: the single-definition guard, the
12+
cross-repo-only scope, and the language guard are what keep it from fabricating an edge
13+
from a name collision.
1414
"""
1515
from __future__ import annotations
1616

@@ -44,6 +44,7 @@ def _needs(module: str):
4444
needs_java = _needs("tree_sitter_java")
4545
needs_cpp = _needs("tree_sitter_cpp")
4646
needs_csharp = _needs("tree_sitter_c_sharp")
47+
needs_objc = _needs("tree_sitter_objc")
4748
needs_swift = _needs("tree_sitter_swift")
4849
needs_go = _needs("tree_sitter_go")
4950
needs_typescript = _needs("tree_sitter_typescript")
@@ -230,6 +231,79 @@ def test_a_typescript_call_does_not_bind_to_a_python_declaration():
230231
assert link_cross_repo_member_calls(G) == 0
231232

232233

234+
PARKED_OBJC = [{"callee": "greet", "receiver_type": "Greeter", "lang": "objc", "line": "L5"}]
235+
236+
237+
def test_an_objc_selector_answers_through_either_sigil():
238+
# An ObjC method label keeps its +/- sigil while a parked selector carries no
239+
# class/instance distinction, so both spellings have to be tried.
240+
for label in ("-greet", "+greet"):
241+
G = _graph(
242+
caller=_caller("a", PARKED_OBJC, source_file="src/App.m"),
243+
declarations=[(_declaration("b", "Greeter", "Greeter.m"),
244+
_method("b", label, source_file="Greeter.m"))],
245+
)
246+
assert link_cross_repo_member_calls(G) == 1, label
247+
assert _added_calls(G) == {("a::app_run", "b::greeter_greet")}
248+
249+
250+
def test_an_objc_callee_that_already_carries_a_sigil_still_binds():
251+
# A parked selector is written bare, but the payload comes from `graph.json`
252+
# and a sigiled one must not ask the index for `--greet`.
253+
G = _graph(
254+
caller=_caller("a", [dict(PARKED_OBJC[0], callee="-greet")],
255+
source_file="src/App.m"),
256+
declarations=[(_declaration("b", "Greeter", "Greeter.m"),
257+
_method("b", "-greet", source_file="Greeter.m"))],
258+
)
259+
assert link_cross_repo_member_calls(G) == 1
260+
assert _added_calls(G) == {("a::app_run", "b::greeter_greet")}
261+
262+
263+
def test_a_type_declaring_both_objc_sigils_binds_nothing():
264+
# `+greet` and `-greet` on one class are two different methods and the parked
265+
# selector cannot say which was meant.
266+
decl = _declaration("b", "Greeter", "Greeter.m")
267+
G = _graph(
268+
caller=_caller("a", PARKED_OBJC, source_file="src/App.m"),
269+
declarations=[(decl, _method("b", "-greet", "greeter_inst", "Greeter.m"))],
270+
)
271+
class_method = _method("b", "+greet", "greeter_cls", "Greeter.m")
272+
G.add_node(class_method[0], **class_method[1])
273+
G.add_edge(decl[0], class_method[0], relation="method")
274+
275+
assert link_cross_repo_member_calls(G) == 0
276+
277+
278+
def test_an_objc_call_does_not_bind_to_a_cpp_member_of_a_shared_header():
279+
# `.h` belongs to both languages, so the sigil is what keeps an ObjC `-greet`
280+
# and a C++ `.greet()` from answering for each other inside one header.
281+
G = _graph(
282+
caller=_caller("a", PARKED_OBJC, source_file="src/App.m"),
283+
declarations=[(_declaration("b", "Greeter", "greeter.h"),
284+
_method("b", ".greet()", source_file="greeter.h"))],
285+
)
286+
assert link_cross_repo_member_calls(G) == 0
287+
288+
G = _graph(
289+
caller=_caller("a", PARKED_CPP, source_file="src/app.cpp"),
290+
declarations=[(_declaration("b", "Greeter", "greeter.h"),
291+
_method("b", "-greet", source_file="greeter.h"))],
292+
)
293+
assert link_cross_repo_member_calls(G) == 0
294+
295+
296+
def test_an_objc_protocol_does_not_answer_a_parked_call():
297+
# A protocol carries the same markers as a class but is labelled `<Greeter>`,
298+
# which no parked receiver type ever spells.
299+
G = _graph(
300+
caller=_caller("a", PARKED_OBJC, source_file="src/App.m"),
301+
declarations=[(_declaration("b", "<Greeter>", "Greeter.h"),
302+
_method("b", "-greet", source_file="Greeter.h"))],
303+
)
304+
assert link_cross_repo_member_calls(G) == 0
305+
306+
233307
def test_the_definition_answers_before_a_same_named_declaration():
234308
# A C++ class declares `void greet();` in its header (`defines`) and defines
235309
# it out of line in the `.cpp` (`method`). Both hang off the one folded class
@@ -451,6 +525,22 @@ def test_a_java_build_parks_the_call_and_the_merge_finishes_it(tmp_path: Path):
451525
("src/greeter.ts", "export class Greeter {\n greet(): void {}\n}\n"),
452526
marks=needs_typescript, id="typescript-parameter-property",
453527
),
528+
pytest.param(
529+
"objc", "greet",
530+
("src/App.m", "@interface App : NSObject\n"
531+
"@property (nonatomic, strong) Greeter *greeter;\n"
532+
"@end\n"
533+
"@implementation App\n"
534+
"- (void)run { [self.greeter greet]; }\n"
535+
"@end\n"),
536+
("src/Greeter.m", "@interface Greeter : NSObject\n"
537+
"- (void)greet;\n"
538+
"@end\n"
539+
"@implementation Greeter\n"
540+
"- (void)greet {}\n"
541+
"@end\n"),
542+
marks=needs_objc, id="objc-property-receiver",
543+
),
454544
pytest.param(
455545
"swift", "greet",
456546
("src/App.swift", "class App {\n"

0 commit comments

Comments
 (0)