fix(objc): NS_ASSUME_NONNULL parse failure, dangling .m imports, alloc/init refs (#1475)

Three residual ObjC extractor bugs from the #1475 thread, each reproduced
against the real tree-sitter-objc grammar:

1. NS_ASSUME_NONNULL_BEGIN before @interface made the parser fail to emit
   a class_interface node at all (the whole interface was swallowed into
   ERROR nodes), so headers using the macro produced no class node. Blank
   the two argument-less annotation macros to equal-length spaces before
   parsing (offset-preserving; macro-free files are byte-identical). The
   reporter's "@class breaks it" hypothesis was wrong — only the macro does.

2. Quoted `#import "X.h"` edges dangled once a `.h`/`.m` pair existed: the
   target used the bare stem, which the post-pass canonicalizes and then
   _disambiguate_colliding_node_ids salts apart by path, so the import
   target no longer matched. Resolve the include to a real file (mirroring
   _import_c), and repoint imports/imports_from edges to the header variant
   in _disambiguate_colliding_node_ids — taking precedence over the
   same-source-file salt so a `.m` importing its own `.h` resolves to the
   header instead of self-looping. Also repairs the equivalent latent
   C-include dangling bug.

3. `[[Foo alloc] init]` produced no edge — walk_calls only reconstructed
   selectors and skipped the receiver. Emit a `references` edge from the
   allocating method to the class, resolved via the unique-class stub guard
   (ensure_named_node + _rewire_unique_stub_nodes) so unknown/ambiguous
   names produce no false edge. The calls-to-init edge is deliberately
   deferred (init selectors are ambiguous across classes).

Reported by JabberYQ with a precise repro and test repo. Adds regression
tests incl. a self-loop guard on the import edges. Still open on #1475:
dot-syntax property accesses (Bug 5) and @selector target-action (Bug 6b).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
safishamsi
2026-06-29 14:41:22 +01:00
co-authored by Claude Opus 4.8
parent e8dabadeb0
commit 1652dadd60
2 changed files with 175 additions and 5 deletions
+63 -5
View File
@@ -7883,6 +7883,24 @@ def _disambiguate_colliding_node_ids(
if len(candidates) == 1:
unambiguous_remaps[old_id] = next(iter(candidates))
# A C/ObjC/C++ `#include "foo.h"` / `#import "foo.h"` resolves to the header's
# file node, but `foo.h` and its sibling `foo.c`/`foo.m`/`foo.cpp` collapse to
# the same `foo` file id, so disambiguation salts them apart by path. A
# cross-file import edge from a THIRD file carries neither salt's source_key, so
# the (target, edge_source_key) lookup misses and the edge dangles on the now
# dead `foo` id. Repoint those import edges to the HEADER variant (the include
# always targeted the header), keyed by the original colliding id (#1475).
_HEADER_SUFFIXES = (".h", ".hpp", ".hh", ".hxx")
header_remaps: dict[str, str] = {}
for old_id in ambiguous_ids:
for node in by_id.get(old_id, []):
sk = _node_disambiguation_source_key(node, root)
if sk and Path(sk).suffix.lower() in _HEADER_SUFFIXES:
new_id = remap.get((old_id, sk))
if new_id:
header_remaps[old_id] = new_id
break
for edge in edges:
edge_source_key = _source_key(str(edge.get("source_file", "")), root)
source_key = (edge.get("source", ""), edge_source_key)
@@ -7891,7 +7909,15 @@ def _disambiguate_colliding_node_ids(
edge["source"] = remap[source_key]
elif edge.get("source") in unambiguous_remaps:
edge["source"] = unambiguous_remaps[str(edge["source"])]
if target_key in remap:
# imports/imports_from always target a header file, so they must resolve to
# the header variant BEFORE the same-source-file salt is considered. Keying
# the import target by the importer's own source file mis-points a `.m`
# importing its own `.h` back at itself (self-loop), and is wrong for any
# cross-file import whose importer shares the colliding id (#1475).
if (edge.get("relation") in ("imports", "imports_from")
and edge.get("target") in header_remaps):
edge["target"] = header_remaps[str(edge["target"])]
elif target_key in remap:
edge["target"] = remap[target_key]
elif edge.get("target") in unambiguous_remaps:
edge["target"] = unambiguous_remaps[str(edge["target"])]
@@ -9673,6 +9699,13 @@ def extract_objc(path: Path) -> dict:
language = Language(tsobjc.language())
parser = Parser(language)
source = path.read_bytes()
# tree-sitter-objc cannot expand these argument-less annotation macros (no
# trailing ';'), and their presence before @interface makes the parser fail to
# emit a class_interface node (#1475). Blank them to equal-length spaces so byte
# offsets / line numbers are preserved and the interface parses.
_OBJC_BLANK_MACROS = (b"NS_ASSUME_NONNULL_BEGIN", b"NS_ASSUME_NONNULL_END")
for _m in _OBJC_BLANK_MACROS:
source = source.replace(_m, b" " * len(_m))
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
@@ -9765,10 +9798,18 @@ def extract_objc(path: Path) -> dict:
for sub in child.children:
if sub.type == "string_content":
raw = _read(sub)
module = raw.split("/")[-1].replace(".h", "")
if module:
tgt_nid = _make_id(module)
add_edge(file_nid, tgt_nid, "imports", line, context="import")
# Resolve the quoted include to a real file so the target id
# matches the (possibly disambiguated) node id _make_id gives
# that file; the bare-stem id never survives
# _disambiguate_colliding_node_ids when a .h/.m pair exists,
# so the edge dangled and was dropped (#1475).
resolved = _resolve_c_include_path(raw, str_path)
if resolved is not None:
add_edge(file_nid, _make_id(str(resolved)), "imports", line, context="import")
else:
module = raw.split("/")[-1].replace(".h", "")
if module:
add_edge(file_nid, _make_id(module), "imports", line, context="import")
return
if t == "module_import":
@@ -9903,6 +9944,23 @@ def extract_objc(path: Path) -> dict:
for caller_nid, body_node in method_bodies:
def walk_calls(n) -> None:
if n.type == "message_expression":
# `[[Foo alloc] init]` is a message_expression whose method is the
# identifier `alloc` and whose receiver is the bare class identifier
# `Foo`; resolve that class name and emit a `references` edge so the
# allocating method links to the allocated type. ensure_named_node
# emits a sourceless stub for unknown names, which the corpus rewire
# collapses ONLY when exactly one real class of that name exists, so an
# unknown/ambiguous class produces no false resolved edge (#1475).
meth = n.child_by_field_name("method")
recv = n.child_by_field_name("receiver")
if (meth is not None and meth.type == "identifier" and _read(meth) == "alloc"
and recv is not None and recv.type == "identifier"):
tname = _read(recv)
ref_line = n.start_point[0] + 1
type_nid = ensure_named_node(tname, ref_line)
if type_nid != caller_nid:
edges.append(_semantic_reference_edge(
caller_nid, type_nid, "type", str_path, ref_line))
# [receiver sel] and [receiver kw1:a kw2:b] both parse to a
# message_expression whose selector parts carry the field name
# "method" (one for a simple selector, several for a compound one);
+112
View File
@@ -1102,6 +1102,118 @@ def test_objc_header_dispatch_routes_objc_not_c(tmp_path):
assert _get_extractor(c_h) is _ec
def test_objc_ns_assume_nonnull_macro_does_not_break_parsing(tmp_path):
"""`NS_ASSUME_NONNULL_BEGIN` before `@interface` made tree-sitter-objc fail to
emit a class_interface node, swallowing the whole interface; blanking the
argument-less macro restores it (#1475)."""
p = tmp_path / "AlertManager.h"
p.write_text(
"#import <Foundation/Foundation.h>\n"
"NS_ASSUME_NONNULL_BEGIN\n"
"@class Other;\n"
"@interface AlertManager : NSObject\n"
"- (void)show;\n"
"@end\n"
"NS_ASSUME_NONNULL_END\n"
)
r = extract_objc(p)
labels = {n["label"] for n in r["nodes"]}
assert "AlertManager" in labels
assert ("AlertManager", "NSObject") in _edge_labels(r, "inherits")
# `@class Other;` is only a forward declaration; it must not mint a class node.
assert "Other" not in labels
def test_objc_macro_free_header_unchanged(tmp_path):
"""A macro-free header still parses exactly as before (regression)."""
p = tmp_path / "Plain.h"
p.write_text(
"@interface Plain : NSObject\n"
"- (void)go;\n"
"@end\n"
)
r = extract_objc(p)
labels = {n["label"] for n in r["nodes"]}
assert "Plain" in labels
assert ("Plain", "NSObject") in _edge_labels(r, "inherits")
def test_objc_quoted_import_edges_resolve_to_real_nodes(tmp_path):
"""Quoted `#import "X.h"` edges must target the real (disambiguated) file node id,
not the bare stem, which gets salted away when a `.h`/`.m` pair exists and left
the import edge dangling (#1475)."""
from graphify.extract import extract
(tmp_path / "Product.h").write_text("@interface Product : NSObject\n@end\n")
(tmp_path / "Product.m").write_text("#import \"Product.h\"\n@implementation Product\n@end\n")
(tmp_path / "Order.h").write_text("@interface Order : NSObject\n@end\n")
(tmp_path / "Order.m").write_text("#import \"Order.h\"\n@implementation Order\n@end\n")
consumer_a = tmp_path / "ConsumerA.m"
consumer_a.write_text("#import \"Product.h\"\n@implementation ConsumerA\n@end\n")
consumer_b = tmp_path / "ConsumerB.m"
consumer_b.write_text("#import \"Order.h\"\n@implementation ConsumerB\n@end\n")
files = [
tmp_path / "Product.h", tmp_path / "Product.m",
tmp_path / "Order.h", tmp_path / "Order.m",
consumer_a, consumer_b,
]
r = extract(files, parallel=False)
node_ids = {n["id"] for n in r["nodes"]}
id_to_label = {n["id"]: n.get("label", "") for n in r["nodes"]}
import_edges = [e for e in r["edges"] if e["relation"] in ("imports", "imports_from")]
assert import_edges
for e in import_edges:
# No dangling targets...
assert e["target"] in node_ids, f"dangling import target: {e}"
# ...and no self-loops: a `.m` importing its own `.h` must resolve to the
# header file node, not get salted back to the importing `.m` (#1475).
assert e["source"] != e["target"], f"self-loop import edge: {e}"
# every quoted import targets a header (.h) file node
assert str(id_to_label.get(e["target"], "")).endswith(".h"), (
f"import target is not a header file node: {e} -> {id_to_label.get(e['target'])}"
)
# the self-import (Product.m -> Product.h) specifically lands on the .h variant
prod_imports = [e for e in import_edges if id_to_label.get(e["source"], "").endswith("Product.m")]
assert prod_imports and all(id_to_label.get(e["target"]) == "Product.h" for e in prod_imports), (
f"Product.m should import the Product.h node, got {[(id_to_label.get(e['source']), id_to_label.get(e['target'])) for e in prod_imports]}"
)
def test_objc_alloc_init_emits_type_reference(tmp_path):
"""`[[Foo alloc] init]` must emit a `references` edge to the project class Foo (#1475)."""
from graphify.extract import extract
(tmp_path / "Foo.h").write_text("@interface Foo : NSObject\n@end\n")
(tmp_path / "Foo.m").write_text("#import \"Foo.h\"\n@implementation Foo\n@end\n")
user = tmp_path / "User.m"
user.write_text(
"#import \"Foo.h\"\n"
"@implementation User\n"
"- (void)build { Foo *x = [[Foo alloc] init]; }\n"
"@end\n"
)
r = extract([tmp_path / "Foo.h", tmp_path / "Foo.m", user], parallel=False)
assert ("-build", "Foo") in _edge_labels(r, "references")
def test_objc_alloc_init_unknown_class_no_resolved_edge(tmp_path):
"""`[[Unknown alloc] init]` with no such class must not produce a resolved
reference edge (the sourceless stub is collapsed only when a real class exists)."""
p = tmp_path / "Caller.m"
p.write_text(
"@implementation Caller\n"
"- (void)build { id x = [[Unknown alloc] init]; }\n"
"- (void)other { [self build]; [x doStuff]; }\n"
"@end\n"
)
r = extract_objc(p)
# The single-file extractor emits the edge to a sourceless stub; assert there is
# no resolved reference to a *real* (sourced) Unknown node and that ordinary
# selector sends ([self build] / [x doStuff]) produce no alloc reference.
sourced_ids = {n["id"] for n in r["nodes"] if n.get("source_file")}
refs = [e for e in r["edges"] if e["relation"] == "references"]
for e in refs:
assert e["target"] not in sourced_ids, f"unexpected resolved ref: {e}"
# ---------------------------------------------------------------------------
# Go
# ---------------------------------------------------------------------------