fix(extract): recover dropped Objective-C relationships (#1475)
A detailed report (#1475) showed the ObjC extractor silently dropping ~60% of code-level relationships. Five fixes: 1. Dispatch: ObjC `.h` headers were parsed by extract_c (1 node, 0 edges, losing every @interface/@protocol/@property/method). _get_extractor now routes a `.h` to extract_objc when it contains an ObjC-only directive (@interface/@protocol/@implementation/@import) — these are illegal in C/C++, so the sniff never hijacks a genuine C/C++ header (verified: a plain C/C++ `.h` stays on its existing extractor). 2. Calls: the method-body pass produced zero `calls` edges because it matched child types `selector`/`keyword_argument_list`, but tree-sitter-objc tags selector parts with the field name `method` (type `identifier`). The selector is now reconstructed from every `method`-field child, explicitly skipping the `receiver` field — so self/super/ClassName receivers are never mistaken for a selector, and compound sends ([self a:x b:y]) resolve too. (Avoids the report's suggested `"identifier"` fix, which would have matched receivers as selectors.) 3. Generic property types: NSArray<Product *> * wraps the type in a generic_specifier, so the old direct-type_identifier scan saw nothing. The element (Product) and container (NSArray) are now both referenced. 4. Class methods: `+ (…)shared` was labeled -shared; the +/- sigil is now read from the method node's first child. 5. @import: `@import Foundation;` (a module_import node) now emits an imports edge. Dot-syntax property `accesses` (Bug 5) and @selector(...) target-action edges (Bug 6b) need type/name resolution policy and are left as follow-ups. Added six regression tests; the reporter's claim that compound messages lack a message_expression wrapper (Bug 6a) was checked against the real AST and refuted — they share Bug 2's root cause, fixed by the same field-name change. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
905e0a7a2e
commit
8994b5500c
@@ -4,6 +4,7 @@ Full release notes with details on each version: [GitHub Releases](https://githu
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Fix: the Objective-C extractor was silently dropping most code-level relationships (#1475, thanks @JabberYQ for the detailed report). Five fixes: (1) ObjC `.h` headers were parsed by the C extractor (1 node, 0 edges, losing every `@interface`/`@protocol`/`@property`/method) — a `.h` is now routed to the ObjC extractor when it contains an ObjC-only directive (`@interface`/`@protocol`/`@implementation`/`@import`), which never hijacks a real C/C++ header; (2) `[receiver selector]` calls produced no `calls` edges at all because the method-body pass looked for `selector`/`keyword_argument_list` nodes, but the grammar tags selector parts with the field name `method` (type `identifier`) — the selector is now read from the `method` fields, skipping the receiver, which also makes compound sends like `[self a:x b:y]` resolve; (3) generic property types (`NSArray<Product *> *`) were invisible because the type was wrapped in a `generic_specifier` — the element and container types are now both referenced; (4) class methods (`+foo`) were mislabeled `-foo`; (5) `@import Foundation;` now produces an `imports` edge. Property/dot-syntax `accesses` and `@selector(...)` target-action edges remain follow-ups.
|
||||
- Feat: link WPF/XAML views to their ViewModels and extract richer binding references (#1473, thanks @MikeKatsoulakis). Builds on the initial XAML support (#1460). Resolves a view to its ViewModel from an explicit `<Window.DataContext><vm:MainViewModel/>`, a design-time `d:DataContext="{d:DesignInstance Type=…}"`, the `View`→`ViewModel` naming convention, or Prism `ViewModelLocator.AutoWireViewModel="True"` — always against an actually-extracted C# class, so a name with no matching class (or an ambiguous one) emits no edge (explicit DataContext is EXTRACTED, conventions are INFERRED). Also extracts binding paths (`{Binding User.Name}`, `Path=Order.Total`), commands (`Command="{Binding SaveCommand}"`), converters, and CommunityToolkit `[ObservableProperty]`/`[RelayCommand]` generated members. The event-handler resolution stays gated on the .NET handler signature (no spurious event edges), and ViewModel discovery is bounded to the extraction root.
|
||||
- Fix: `.vue` Single File Components now extract their `<script>` with the right grammar (#1468, thanks @papinto). `.vue` was dispatched to `extract_js`, which selects a tree-sitter grammar by suffix; `.vue` is neither `.ts` nor `.tsx`, so the whole SFC — `<template>` markup, `<script>`, and `<style>` — was parsed as JavaScript, producing a top-level ERROR node and recovering no imports, symbols, or type references. A dedicated `extract_vue` now masks everything outside `<script>` (replacing it with spaces so line numbers stay accurate) and parses just the script with the grammar named by `lang` (`ts` default, `tsx`/`js`/`jsx` honored). The open-tag scan tolerates `>` inside quoted attributes, so Vue 3.3+ generic components (`generic="T extends Record<string, unknown>"`) parse correctly.
|
||||
- Fix: `graphify reflect --if-stale` now also checks the `.graphify_analysis.json` and `.graphify_labels.json` sidecars (and any custom `--analysis`/`--labels` paths) when deciding whether `LESSONS.md` is up to date (#1470, thanks @oleksii-tumanov). It previously only stat'd the memory docs and `graph.json`, so lessons could stay stale after community analysis or labels changed without the graph changing. A missing sidecar is treated as not-an-input, so no-cluster builds are unaffected.
|
||||
|
||||
+98
-34
@@ -9380,6 +9380,18 @@ def extract_objc(path: Path) -> dict:
|
||||
n = node.child_by_field_name(field)
|
||||
return _read(n) if n else None
|
||||
|
||||
def _type_identifiers(node):
|
||||
"""Yield every type_identifier under a property's type node, descending
|
||||
through generic_specifier/type_name so NSArray<Product *> yields both
|
||||
NSArray and the element type Product (the generic case was invisible
|
||||
because the type was wrapped in a generic_specifier, not a bare
|
||||
type_identifier child) (#1475)."""
|
||||
if node.type == "type_identifier":
|
||||
yield node
|
||||
return
|
||||
for c in node.children:
|
||||
yield from _type_identifiers(c)
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = _make_id(stem, name)
|
||||
if nid in seen_ids:
|
||||
@@ -9427,6 +9439,15 @@ def extract_objc(path: Path) -> dict:
|
||||
add_edge(file_nid, tgt_nid, "imports", line, context="import")
|
||||
return
|
||||
|
||||
if t == "module_import":
|
||||
# @import Foundation; / @import Foundation.NSString;
|
||||
path_node = node.child_by_field_name("path")
|
||||
if path_node is not None:
|
||||
module = _read(path_node).split(".")[0].strip()
|
||||
if module:
|
||||
add_edge(file_nid, _make_id(module), "imports", line, context="import")
|
||||
return
|
||||
|
||||
if t == "class_interface":
|
||||
# @interface ClassName : SuperClass <Protocols>
|
||||
# children: @interface, identifier(name), ':', identifier(super), parameterized_arguments, ...
|
||||
@@ -9460,12 +9481,23 @@ def extract_objc(path: Path) -> dict:
|
||||
prop_line = child.start_point[0] + 1
|
||||
for sub in child.children:
|
||||
if sub.type == "struct_declaration":
|
||||
# The type is either a direct type_identifier
|
||||
# (NSString *x) or wrapped in a generic_specifier
|
||||
# (NSArray<Product *> *xs). Walk every type name in the
|
||||
# type portion, skipping the declarator (the *field
|
||||
# name), so generic collections are no longer invisible.
|
||||
seen_types: set[str] = set()
|
||||
for s in sub.children:
|
||||
if s.type == "type_identifier":
|
||||
type_nid = ensure_named_node(_read(s), prop_line)
|
||||
if s.type in ("struct_declarator", ";"):
|
||||
continue
|
||||
for ti in _type_identifiers(s):
|
||||
tname = _read(ti)
|
||||
if tname in seen_types:
|
||||
continue
|
||||
seen_types.add(tname)
|
||||
type_nid = ensure_named_node(tname, prop_line)
|
||||
edges.append(_semantic_reference_edge(
|
||||
cls_nid, type_nid, "field", str_path, prop_line))
|
||||
break
|
||||
elif child.type == "method_declaration":
|
||||
walk(child, cls_nid)
|
||||
return
|
||||
@@ -9507,21 +9539,22 @@ def extract_objc(path: Path) -> dict:
|
||||
|
||||
if t in ("method_declaration", "method_definition"):
|
||||
container = parent_nid or file_nid
|
||||
# method name is the first identifier child (simple selector)
|
||||
# for compound selectors: identifier + method_parameter pairs
|
||||
parts = []
|
||||
# Class methods start with '+', instance methods with '-' (the grammar
|
||||
# emits the sigil as the first child). The selector is the concatenation
|
||||
# of the direct identifier children: one for a simple selector (-go),
|
||||
# several for a compound one (-tableView:numberOfRowsInSection: ->
|
||||
# "tableViewnumberOfRowsInSection"); method_parameter holds the arg
|
||||
# types/names, not selector keywords, so it is correctly skipped.
|
||||
prefix = "-"
|
||||
for child in node.children:
|
||||
if child.type == "identifier":
|
||||
parts.append(_read(child))
|
||||
elif child.type == "method_parameter":
|
||||
for sub in child.children:
|
||||
if sub.type == "identifier":
|
||||
# selector keyword before ':'
|
||||
pass
|
||||
if child.type in ("+", "-"):
|
||||
prefix = child.type
|
||||
break
|
||||
parts = [_read(c) for c in node.children if c.type == "identifier"]
|
||||
method_name = "".join(parts) if parts else None
|
||||
if method_name:
|
||||
method_nid = _make_id(container, method_name)
|
||||
add_node(method_nid, f"-{method_name}", line)
|
||||
add_node(method_nid, f"{prefix}{method_name}", line)
|
||||
add_edge(container, method_nid, "method", line)
|
||||
if t == "method_definition":
|
||||
method_bodies.append((method_nid, node))
|
||||
@@ -9538,26 +9571,30 @@ def extract_objc(path: Path) -> dict:
|
||||
for caller_nid, body_node in method_bodies:
|
||||
def walk_calls(n) -> None:
|
||||
if n.type == "message_expression":
|
||||
# [receiver selector]
|
||||
for child in n.children:
|
||||
if child.type in ("selector", "keyword_argument_list"):
|
||||
sel = []
|
||||
if child.type == "selector":
|
||||
sel.append(_read(child))
|
||||
else:
|
||||
for sub in child.children:
|
||||
if sub.type == "keyword_argument":
|
||||
for s in sub.children:
|
||||
if s.type == "selector":
|
||||
sel.append(_read(s))
|
||||
method_name = "".join(sel)
|
||||
for candidate in all_method_nids:
|
||||
if candidate.endswith(_make_id("", method_name).lstrip("_")):
|
||||
pair = (caller_nid, candidate)
|
||||
if pair not in seen_calls and caller_nid != candidate:
|
||||
seen_calls.add(pair)
|
||||
add_edge(caller_nid, candidate, "calls", body_node.start_point[0] + 1,
|
||||
confidence="EXTRACTED", weight=1.0, context="call")
|
||||
# [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);
|
||||
# the receiver carries field name "receiver". Reconstruct the
|
||||
# selector from every "method" child so self/super/ClassName
|
||||
# receivers are never mistaken for a selector, and compound sends
|
||||
# resolve too (the whole second pass was previously dead code for
|
||||
# ObjC because the grammar emits these as `identifier`, not
|
||||
# `selector`/`keyword_argument_list`) (#1475).
|
||||
sel_parts = [
|
||||
_read(child)
|
||||
for i, child in enumerate(n.children)
|
||||
if n.field_name_for_child(i) == "method" and child.type == "identifier"
|
||||
]
|
||||
method_name = "".join(sel_parts)
|
||||
if method_name:
|
||||
needle = _make_id("", method_name).lstrip("_")
|
||||
for candidate in all_method_nids:
|
||||
if candidate.endswith(needle):
|
||||
pair = (caller_nid, candidate)
|
||||
if pair not in seen_calls and caller_nid != candidate:
|
||||
seen_calls.add(pair)
|
||||
add_edge(caller_nid, candidate, "calls", n.start_point[0] + 1,
|
||||
confidence="EXTRACTED", weight=1.0, context="call")
|
||||
for child in n.children:
|
||||
walk_calls(child)
|
||||
walk_calls(body_node)
|
||||
@@ -12764,6 +12801,29 @@ _DISPATCH: dict[str, Any] = {
|
||||
}
|
||||
|
||||
|
||||
# ObjC-only directives. They are illegal in C and C++, so finding one in a `.h`
|
||||
# file is a near-zero-false-positive signal that the header is Objective-C (and so
|
||||
# belongs to extract_objc, not extract_c). `@property` is deliberately excluded: it
|
||||
# doubles as a Doxygen comment command and ObjC properties only ever live inside an
|
||||
# @interface/@protocol anyway, so the stronger directives already cover them.
|
||||
_OBJC_HEADER_MARKERS = (b"@interface", b"@protocol", b"@implementation", b"@import")
|
||||
|
||||
|
||||
def _is_objc_header(path: Path) -> bool:
|
||||
"""Whether a `.h` file is Objective-C rather than C/C++ (#1475).
|
||||
|
||||
`.h` is shared by C, C++, and ObjC; the suffix map routes it to extract_c,
|
||||
which silently drops every @interface/@protocol/@property/method (1 node, 0
|
||||
edges). Sniffing for an ObjC-only directive reroutes genuine ObjC headers to
|
||||
extract_objc while leaving every C/C++ header on its existing extractor.
|
||||
"""
|
||||
try:
|
||||
head = path.read_bytes()[:256 * 1024]
|
||||
except OSError:
|
||||
return False
|
||||
return any(marker in head for marker in _OBJC_HEADER_MARKERS)
|
||||
|
||||
|
||||
def _get_extractor(path: Path) -> Any | None:
|
||||
"""Return the correct extractor function for a file, or None if unsupported."""
|
||||
if path.name.endswith(".blade.php"):
|
||||
@@ -12778,6 +12838,10 @@ def _get_extractor(path: Path) -> Any | None:
|
||||
# (#1377). apm.yml would otherwise be a .yml document handled by the LLM.
|
||||
if is_package_manifest_path(path):
|
||||
return extract_package_manifest
|
||||
# `.h` is C/C++/ObjC-ambiguous; route Objective-C headers to extract_objc
|
||||
# (the suffix map sends `.h` to extract_c, which can't read @interface etc.).
|
||||
if path.suffix == ".h" and _is_objc_header(path):
|
||||
return extract_objc
|
||||
return _DISPATCH.get(path.suffix)
|
||||
|
||||
|
||||
|
||||
@@ -865,6 +865,70 @@ def test_objc_no_dangling_edges():
|
||||
assert e["source"] in node_ids, f"Dangling source: {e}"
|
||||
|
||||
|
||||
def test_objc_resolves_self_method_calls():
|
||||
"""`[self speak]` inside Dog.fetch must produce a calls edge. The method-body
|
||||
second pass was dead code for ObjC because the grammar emits a simple selector
|
||||
as `identifier`, not `selector`/`keyword_argument_list` (#1475)."""
|
||||
r = extract_objc(FIXTURES / "sample.m")
|
||||
nid2label = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
calls = [nid2label.get(e["target"]) for e in r["edges"] if e["relation"] == "calls"]
|
||||
assert any(t and "speak" in t for t in calls), calls
|
||||
|
||||
|
||||
def test_objc_class_method_labeled_with_plus(tmp_path):
|
||||
"""`+ (…)shared` is a class method and must be labeled +shared, not -shared (#1475)."""
|
||||
p = tmp_path / "S.m"
|
||||
p.write_text("@implementation S\n+ (instancetype)shared { return nil; }\n- (void)go { }\n@end\n")
|
||||
labels = {n["label"] for n in extract_objc(p)["nodes"]}
|
||||
assert "+shared" in labels and "-go" in labels
|
||||
|
||||
|
||||
def test_objc_compound_selector_call_resolves(tmp_path):
|
||||
"""A compound message `[self a:x b:y]` resolves to the compound method def (#1475)."""
|
||||
p = tmp_path / "V.m"
|
||||
p.write_text(
|
||||
"@implementation V\n"
|
||||
"- (void)tableView:(id)tv numberOfRowsInSection:(int)s { }\n"
|
||||
"- (void)go { [self tableView:nil numberOfRowsInSection:0]; }\n"
|
||||
"@end\n"
|
||||
)
|
||||
r = extract_objc(p)
|
||||
nid2label = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
calls = [nid2label.get(e["target"]) for e in r["edges"] if e["relation"] == "calls"]
|
||||
assert any(t and "tableViewnumberOfRowsInSection" in t for t in calls), calls
|
||||
|
||||
|
||||
def test_objc_generic_property_type_extracted(tmp_path):
|
||||
"""`NSArray<Product *> *` must reference the element type Product (and the
|
||||
container NSArray); the generic wrapper made the type invisible before (#1475)."""
|
||||
p = tmp_path / "M.h"
|
||||
p.write_text("@interface M : NSObject\n@property (strong) NSArray<Product *> *items;\n@end\n")
|
||||
refs = _edge_labels(extract_objc(p), "references", "field")
|
||||
assert ("M", "Product") in refs
|
||||
assert ("M", "NSArray") in refs
|
||||
|
||||
|
||||
def test_objc_module_import_edge(tmp_path):
|
||||
"""`@import Foundation;` / `@import UIKit.UIView;` produce imports edges (#1475)."""
|
||||
from graphify.extract import _make_id
|
||||
p = tmp_path / "X.m"
|
||||
p.write_text("@import Foundation;\n@import UIKit.UIView;\n@implementation X\n@end\n")
|
||||
targets = {e["target"] for e in extract_objc(p)["edges"] if e["relation"] == "imports"}
|
||||
assert _make_id("Foundation") in targets and _make_id("UIKit") in targets
|
||||
|
||||
|
||||
def test_objc_header_dispatch_routes_objc_not_c(tmp_path):
|
||||
"""An ObjC `.h` (has @interface) routes to extract_objc; a plain C `.h` stays
|
||||
on extract_c, so C/C++ headers are never hijacked by the sniff (#1475)."""
|
||||
from graphify.extract import _get_extractor, extract_objc as _eo, extract_c as _ec
|
||||
objc_h = tmp_path / "AppDelegate.h"
|
||||
objc_h.write_text("@interface AppDelegate : NSObject <UIApplicationDelegate>\n@end\n")
|
||||
c_h = tmp_path / "util.h"
|
||||
c_h.write_text("#include <stdio.h>\nint add(int a, int b);\nstruct Point { int x; };\n")
|
||||
assert _get_extractor(objc_h) is _eo
|
||||
assert _get_extractor(c_h) is _ec
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Go
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user