Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(languages): parse Objective-C to a full AST and move it to Good (#2135)

Raghav Chamadiyaeb4010c34caf
diff --git a/README.md b/README.md
index 6ebd426d4..c662741c9 100644
--- a/README.md
+++ b/README.md
@@ -480,7 +480,7 @@ the orchestrators. Full matrix and the contributor recipe:
## Supported languages
-**24 languages parsed to AST · 39 on a five-rung ladder · framework-aware across
+**25 languages parsed to AST · 39 on a five-rung ladder · framework-aware across
all of them.**
"Do you support X" has five useful answers, not two, so languages land on a
@@ -516,6 +516,7 @@ ladder and every rung says what it buys you.
<img src="https://img.shields.io/badge/VB.NET-945DB7?style=flat-square&logo=dotnet&logoColor=white" alt="VB.NET" />
<img src="https://img.shields.io/badge/Elixir-6E4A7E?style=flat-square&logo=elixir&logoColor=white" alt="Elixir" />
<img src="https://img.shields.io/badge/F%23-378BBA?style=flat-square&logo=fsharp&logoColor=white" alt="F#" />
+ <img src="https://img.shields.io/badge/Objective--C-438EFF?style=flat-square&logo=apple&logoColor=white" alt="Objective-C" />
&nbsp;<strong>· Partial &nbsp;</strong>
<img src="https://img.shields.io/badge/Luau-00A2FF?style=flat-square&logo=lua&logoColor=white" alt="Luau" />
<img src="https://img.shields.io/badge/Razor-512BD4?style=flat-square&logo=blazor&logoColor=white" alt="Razor / Blazor" />
@@ -527,11 +528,11 @@ still doing real work rather than being ignored:
| Rung | Languages | What you get |
|---|---|---|
| **Full** (13) | Python · TypeScript · JavaScript · Svelte · Vue · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | The whole pipeline: AST symbols, import resolution, a resolved call graph, heritage, docstrings, framework edges, **and code-health markers** |
-| **Good** (9) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET · Elixir · F# | All of the above except the full health suite |
+| **Good** (10) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET · Elixir · F# · Objective-C | All of the above except the full health suite |
| **Partial** (2) | Luau / Roblox · Razor / Blazor | Luau: AST symbols and `require()` resolution, Rojo and `.luaurc` aware. Razor: component symbols, `@code` and component-tag call edges, C# health markers; no import resolution yet |
| | | ⎯⎯ *tree-sitter parsing stops here; the rungs below come from git and imports* ⎯⎯ |
| **Lightweight** (6) | Clojure · Haskell · Lean 4 · Erlang · HTML · QML | A real file-to-file import graph, and no symbol-level claims |
-| **Structural** (9) | Objective-C · R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history: blame, hotspots, co-change, ownership, bug history |
+| **Structural** (8) | R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history: blame, hotspots, co-change, ownership, bug history |
**Every language ships in the open-source distribution.** None is gated behind
the commercial licence, and none will be. Languages on the way up the ladder,
diff --git a/ROADMAP.md b/ROADMAP.md
index 6018a656c..e216333bc 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -34,7 +34,7 @@ Languages land on a five-rung ladder rather than a yes/no list, because "do you
support X" has five different useful answers. Each rung is defined, with what it
buys you, in
[docs/layers/LANGUAGE_SUPPORT.md](docs/layers/LANGUAGE_SUPPORT.md). Today that
-ladder covers **39 languages, 24 of them parsed to a full AST**.
+ladder covers **39 languages, 25 of them parsed to a full AST**.
### New languages
@@ -47,7 +47,6 @@ ladder covers **39 languages, 24 of them parsed to a full AST**.
| **Fortran** | Exploring | Scientific and engineering codebases with long lifespans and thin documentation. |
| **Apex** | Planned | Salesforce estates, where the org is often the least documented system a company runs. Apex is Java-shaped, and Lightning Web Components are already covered as JavaScript and HTML. |
| **Ada** | Exploring | Defense and aerospace, long-lived and thinly documented, and usually in the same estates asking about COBOL. |
-| **Objective-C** | Planned | Currently Structural, meaning history only. The grammar is mature, so this is a climb up the ladder rather than new ground. |
| **Template dialects** (Django/Jinja, ERB, Blade, Thymeleaf, Go templates) | Planned | Today they parse cleanly as HTML and yield nothing, because `{% extends "base.html" %}` is plain text to an HTML parser. A stated ceiling, not an oversight. |
### Deepening languages we already parse
@@ -62,6 +61,7 @@ ladder covers **39 languages, 24 of them parsed to a full AST**.
| Object Pascal | Planned | Assertion and performance markers, a dedicated `uses` resolver |
| Elixir | Planned | Health markers, and a call-resolution strategy so a bare-name call reaches beyond its own file |
| F# | Planned | Health markers, and a resolver that reads the AST index instead of the declared-name regex |
+| Objective-C | Planned | Health markers, a resolver that reads the Xcode project rather than file stems, and pairing a header with its implementation across files |
| Razor / Blazor | Planned | `@using` and `@inject` edges so component tags resolve through imports, `@code` members as symbols rather than call edges only |
### Need a language that is not here
diff --git a/docs/README.md b/docs/README.md
index c05fa541f..a0086b8d6 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -59,7 +59,7 @@ your agent in under five minutes, with no API key.
| [layers/DECISIONS.md](layers/DECISIONS.md) | Architectural decisions mined from your repo and from your own agent sessions |
| [layers/DEAD_CODE.md](layers/DEAD_CODE.md) | Unreachable files, unused exports, and zombie packages by confidence tier |
| [layers/SECURITY.md](layers/SECURITY.md) | The local pattern scan: what the sixteen patterns catch, what they do not, and how far to trust the result |
-| [layers/LANGUAGE_SUPPORT.md](layers/LANGUAGE_SUPPORT.md) | What works per language: 24 parsed to a full AST, 39 on the five-rung ladder |
+| [layers/LANGUAGE_SUPPORT.md](layers/LANGUAGE_SUPPORT.md) | What works per language: 25 parsed to a full AST, 39 on the five-rung ladder |
| [layers/WIKI.md](layers/WIKI.md) | The generated wiki: page types, what `update` re-renders, styles, output language |
## Scale it
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 8bef8069b..3551da973 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -32,7 +32,7 @@ new language needs one only when it hits the same kind of wall.
- [Call resolution](#call-resolution) · [the strategy seam](#the-per-language-strategy-seam) · [resolution origins](#resolution-origins) · [receiver typing](#receiver-typing) · [inherited dispatch](#inherited-dispatch)
- [The edge vocabulary](#the-edge-vocabulary)
- [Multi-language files (the SFC pattern)](#multi-language-files-the-sfc-pattern)
-- [Per-language mechanics](#per-language-mechanics) · [Elixir](#elixir) · [F#](#f) · [GDScript / Godot](#gdscript--godot) · [VB.NET](#vbnet) · [QML](#qml) · [Flutter widget trees](#flutter-widget-trees)
+- [Per-language mechanics](#per-language-mechanics) · [Elixir](#elixir) · [F#](#f) · [Objective-C](#objective-c) · [GDScript / Godot](#gdscript--godot) · [VB.NET](#vbnet) · [QML](#qml) · [Flutter widget trees](#flutter-widget-trees)
- [Optional language-specific passes](#optional-language-specific-passes)
- [The three code-health dialect registries](#the-three-code-health-dialect-registries)
- [Workspace contract extraction](#workspace-contract-extraction)
@@ -750,6 +750,88 @@ splits one namespace across many single-file assemblies, most `open` targets
are ambiguous and stay unresolved by design, which puts that repo's F#
unused-export findings at the review tier rather than the asserted one.
+### Objective-C
+
+Three shapes the recipe does not cover.
+
+- **Header routing is by content, not extension.** The extension map holds one
+ language per extension for the whole repository, and `.h` belongs to C++, so
+ claiming it for Objective-C as well would reroute every C and C++ header
+ everywhere. `_objc_header_language` in `traverser.py` runs immediately after
+ the extension lookup and only when that lookup answered `cpp`. It reads the
+ first 4 KB of a `.h`, blanks the `//` and `/* */` spans in place, and returns
+ `objectivec` when an `@interface`, `@implementation` or `@protocol` opens a
+ line in what is left. All three are keywords no C or C++ header can carry
+ outside a comment. Both the anchoring and the comment blanking are load
+ bearing: `@interface` and `@class` are Doxygen commands too, and an
+ anywhere-in-the-file token match routed C++ headers documented with
+ `/** @class Widget */` to this grammar. `@class` and `#import` are not in the
+ set at all, since neither can be anchored the same way and neither adds a
+ header the rule above misses. A header carrying only preprocessor macros
+ stays `cpp`, which is the right answer for it. The C/C++ `header_source_pair` hint is still gated to the
+ `c` and `cpp` tags and is deliberately not widened here, so a sniffed
+ Objective-C header does not yet pair with its `.m`.
+
+- **A method is named by its whole selector.** `initWithName:age:` is one name,
+ and the grammar has no selector node and no selector field for it: the keyword
+ parts are bare `identifier` children of the `method_declaration`, interleaved
+ with the `method_parameter` nodes that carry the colon, the type and the
+ parameter name. The query captures the first keyword and `_objc_selector_name`
+ joins the rest; without the join every multi-keyword method would be named
+ after its first part and two of them would collide on one symbol id. A
+ keyword is only an identifier that a `method_parameter` follows: anything
+ after the last parameter is an attribute macro, and joining
+ `NS_DESIGNATED_INITIALIZER` or `NS_REQUIRES_SUPER` into the name stopped a
+ header pairing with the `.m` that defines the same method. A message
+ send is the mirror image: `message_expression` does field-label every keyword
+ as `method:`, so the one query pattern matches once per part, and
+ `_objc_message_selector` joins them on the first match and drops the rest so
+ the call-site name meets the symbol name. `@selector(a:b:)` is not captured at
+ all: this grammar leaves the text between the parens out of the tree entirely,
+ so there is nothing for a query to match.
+
+- **A whole-line nullability macro is blanked before parsing.**
+ `NS_ASSUME_NONNULL_BEGIN` is not a preprocessor directive and the grammar has
+ no rule for it, so it parses as the start of an ordinary C declaration and
+ error recovery folds the entire `@interface … @end` block after it into one
+ ERROR node. `prepare_objectivec_source` blanks those lines with spaces,
+ preserving every other byte offset, through the same
+ `sfc_source.prepare_source` hook Pascal uses, so the health walkers see the
+ same projection the ingestion parser does. Call-shaped macros are a different
+ problem and are left alone. `typedef NS_ENUM(Type, Name) { … }` still
+ produces ERROR nodes, and because only its enum *cases* survive as
+ declarators, capturing them mints a symbol per case named as though it were
+ the type and never one for the type itself, so `_objc_is_macro_enum` skips
+ the whole typedef: no symbol beats a wrong one.
+
+An `@interface` and its `@implementation` are two symbols in two files, told
+apart by `is_declaration`, following the C/C++ precedent rather than merging
+across files. Within one file they collapse in
+`_dedupe_objc_interface_symbols`, which is what stops the class extension a `.m`
+opens with from duplicating the implementation below it. A category is named for
+the class it extends plus its own name (`NSString(Trimming)`), so two categories
+on one class stay two symbols; a class extension binds no `category` field and
+keeps the plain class name. The dedup keys on which container declared each
+member, because a `@protocol` and a class may share a name in one file and the
+class's `-ping` would otherwise dedupe the protocol's `-ping` away. The two
+still share a symbol id, a stated ceiling: the id scheme has no room for a
+namespace, and renaming the protocol would break the `implements` heritage
+edges and type references that name it as written. Because a declaration and a
+definition are separate symbols, an `unused_export` finding on either is
+evidence about that one declaration and stays review tier: a header method with
+no in-repo caller may be exactly the public API the implementation serves.
+
+Two shapes are handled in the parser rather than the query. A block held in a
+parameter or a local is invoked with C call syntax, so `completionBlock(hit)`
+is a `call_expression` on a bare identifier that nothing in the grammar
+separates from a call to a C function; `_objc_call_is_block_variable` walks out
+to the enclosing method and drops the call when the name is one of its
+parameters or locals, which is what stops the resolver binding it to a
+same-named `@property` in an unrelated class. And nothing ever `#import`s a
+`.m`, so `is_file_reachable` lets a same-stem, same-directory `.h` answer for
+its implementation: without it every implementation file in an Objective-C
+library reported as an unreachable file.
+
### GDScript / Godot
`preload(...)`, `load(...)` and `extends "res://..."` resolve as absolute paths
diff --git a/docs/business/COMMERCIAL.md b/docs/business/COMMERCIAL.md
index b7ed85b6d..602fef6a6 100644
--- a/docs/business/COMMERCIAL.md
+++ b/docs/business/COMMERCIAL.md
@@ -42,7 +42,7 @@ scale, in a regulated or security-sensitive environment**:
All of the following ship in `pip install repowise` today, free for internal use.
- **[Five intelligence layers](../layers/INTELLIGENCE_LAYERS.md)**: Graph
- (tree-sitter AST across 24 languages, two-tier dependency graph, call
+ (tree-sitter AST across 25 languages, two-tier dependency graph, call
resolution, heritage extraction, Leiden communities, PageRank / betweenness /
SCC), Git (hotspots, ownership, co-change pairs, bus factor, significant
commits, contributor profiles, module health), Documentation (a wiki page per
@@ -99,23 +99,23 @@ All of the following ship in `pip install repowise` today, free for internal use
## 3. First-class language coverage
-Repowise parses **24 languages to a full AST** and places **39 on a five-rung
+Repowise parses **25 languages to a full AST** and places **39 on a five-rung
ladder**, so "do you support X" gets the rung as its answer rather than a yes or a
no. Both numbers matter and neither is worth quoting alone.
-The 24 are the top three rungs. At **Full tier sit 13** (Python, TypeScript,
+The 25 are the top three rungs. At **Full tier sit 13** (Python, TypeScript,
JavaScript, Svelte, Vue, Java, Kotlin, Go, Rust, C++, **C#**, Scala, and Ruby) with
AST parsing, import resolution, named bindings, call resolution, heritage
extraction, multi-project workspace resolvers, framework-aware edges, per-language
-dynamic-hint extractors, and code-health markers. A further **9 at Good tier** (C,
-Swift, PHP, Dart, Object Pascal/Delphi, GDScript, VB.NET, Elixir, F#) get all of that except the full
+dynamic-hint extractors, and code-health markers. A further **10 at Good tier** (C,
+Swift, PHP, Dart, Object Pascal/Delphi, GDScript, VB.NET, Elixir, F#, Objective-C) get all of that except the full
health suite, with GDScript and F# also lacking framework edges and named bindings, and Luau
and Razor/Blazor are partial. SQL/dbt, shell, HTML, and the config formats are
handled by dedicated extractors on top of that.
Below the AST line the ladder continues rather than stopping: **6 at Lightweight**
(Clojure, Haskell, Lean 4, Erlang, HTML, QML) get a real file-to-file import
-graph with no symbol-level claims, and **9 at Structural** (Objective-C, R, Zig,
+graph with no symbol-level claims, and **8 at Structural** (R, Zig,
Julia, Elm, OCaml, Crystal, Nim, D) get the git intelligence layer only: blame,
hotspots, co-change, ownership and bug history, with no parsing. Stating the rung
per language is deliberate, because a support claim that averages these together
diff --git a/docs/layers/GRAPH.md b/docs/layers/GRAPH.md
index b65854a4b..5dcde3368 100644
--- a/docs/layers/GRAPH.md
+++ b/docs/layers/GRAPH.md
@@ -11,7 +11,7 @@ that **every edge carries its own evidence**.
<p>
<img src="https://img.shields.io/badge/17-edge_types-3178C6?style=flat-square&labelColor=0A0A0A" alt="17 edge types" />
<img src="https://img.shields.io/badge/29-resolution_origins-059669?style=flat-square&labelColor=0A0A0A" alt="29 resolution origins" />
- <img src="https://img.shields.io/badge/24-languages-F59520?style=flat-square&labelColor=0A0A0A" alt="24 languages" />
+ <img src="https://img.shields.io/badge/25-languages-F59520?style=flat-square&labelColor=0A0A0A" alt="25 languages" />
<img src="https://img.shields.io/badge/22-framework_detectors-7F52FF?style=flat-square&labelColor=0A0A0A" alt="22 framework detectors" />
<img src="https://img.shields.io/badge/0-LLM_calls-1E293B?style=flat-square&labelColor=0A0A0A" alt="zero LLM calls" />
<img src="https://img.shields.io/badge/compiler_graded-7_of_7_cells_undominated-DC2626?style=flat-square&labelColor=0A0A0A" alt="no tool is both more precise and more complete, in 7 of 7 compiler-graded cells" />
diff --git a/docs/layers/INTELLIGENCE_LAYERS.md b/docs/layers/INTELLIGENCE_LAYERS.md
index ff8b709c9..9846514ba 100644
--- a/docs/layers/INTELLIGENCE_LAYERS.md
+++ b/docs/layers/INTELLIGENCE_LAYERS.md
@@ -43,7 +43,7 @@ requirement for the index.
## Graph Intelligence
tree-sitter parses your source into a **two-tier dependency graph**: file nodes
-and symbol nodes (functions, classes, methods). 24 languages parse to a full
+and symbol nodes (functions, classes, methods). 25 languages parse to a full
AST; see [`LANGUAGE_SUPPORT.md`](LANGUAGE_SUPPORT.md) for per-language tiers.
A **confidence-scored call resolver** handles import aliases, barrel
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index d9b256413..7d2b7a03d 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -1,6 +1,6 @@
# Language Support
-**24 languages parsed to a full AST · 39 on the five-rung ladder ·
+**25 languages parsed to a full AST · 39 on the five-rung ladder ·
framework-aware across all of them.** "Do you support X" has five useful answers
rather than two, so every language lands on a rung and the rung says what it
buys you. Everything else in your repo still appears in the wiki and is tracked
@@ -34,6 +34,7 @@ reference.
<img src="https://img.shields.io/badge/VB.NET-945DB7?style=flat-square&logo=dotnet&logoColor=white" alt="VB.NET" />
<img src="https://img.shields.io/badge/Elixir-6E4A7E?style=flat-square&logo=elixir&logoColor=white" alt="Elixir" />
<img src="https://img.shields.io/badge/F%23-378BBA?style=flat-square&logo=fsharp&logoColor=white" alt="F#" />
+ <img src="https://img.shields.io/badge/Objective--C-438EFF?style=flat-square&logo=apple&logoColor=white" alt="Objective-C" />
&nbsp;<strong>· Partial &nbsp;</strong>
<img src="https://img.shields.io/badge/Luau-00A2FF?style=flat-square&logo=lua&logoColor=white" alt="Luau" />
<img src="https://img.shields.io/badge/Razor-512BD4?style=flat-square&logo=blazor&logoColor=white" alt="Razor / Blazor" />
@@ -57,13 +58,13 @@ produce meaningful output.
| Tier | Languages | What you get |
|------|-----------|--------------|
| **Full** (13) | Python · TypeScript · JavaScript · Svelte · Vue · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | The whole pipeline: AST symbols, import resolution, a resolved call graph, heritage, docstrings, framework edges, **and code-health markers** |
-| **Good** (9) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET · Elixir · F# | Everything above except the full health suite. Dart and Object Pascal *do* get health markers; C, Swift, PHP, GDScript, VB.NET, Elixir and F# don't yet. GDScript has a dedicated import resolver and Godot-specific framework edges but no named bindings (see [Known gaps](../architecture/language-support.md#gdscript--godot)) |
+| **Good** (10) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET · Elixir · F# · Objective-C | Everything above except the full health suite. Dart and Object Pascal *do* get health markers; C, Swift, PHP, GDScript, VB.NET, Elixir, F# and Objective-C don't yet. GDScript has a dedicated import resolver and Godot-specific framework edges but no named bindings (see [Known gaps](../architecture/language-support.md#gdscript--godot)) |
| **Partial** (2) | Luau / Roblox · Razor / Blazor | Luau: AST symbols and `require()` resolution (Rojo / `.luaurc` aware), no health markers yet. Razor: a component symbol per file, call edges from `@code` blocks and component tags, C# health markers; no import resolution yet |
| | | ⎯⎯ *tree-sitter parsing stops here. The rungs below are derived from git and imports, not from an AST.* ⎯⎯ |
| **Lightweight** (6) | Clojure · Haskell · Lean 4 · Erlang · HTML · QML | A real file-to-file import graph, no symbol-level claims |
-| **Structural** (9) | Objective-C · R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history only: blame, hotspots, co-change. No AST parsing |
+| **Structural** (8) | R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history only: blame, hotspots, co-change. No AST parsing |
-The first three rungs are the **24 languages parsed to a full AST**; all five are
+The first three rungs are the **25 languages parsed to a full AST**; all five are
the **39** on the ladder. Both numbers are worth stating and neither is worth
stating alone, so if you only take one thing from this page, take the rung your
language sits on rather than either count.
@@ -255,6 +256,7 @@ bindings and heritage, with a dedicated workspace resolver per language.
| **VB.NET** | `.vb` | `Imports` through the same MSBuild project index C# uses: `.vbproj` / `.sln` parsing, `<RootNamespace>`-aware namespace lookup, NuGet package references |
| **Elixir** | `.ex` `.exs` | `alias` / `import` / `require` / `use` against a `defmodule` index, with the Mix `lib/foo/bar.ex` → `Foo.Bar` convention as the fallback; `alias Foo.{Bar, Baz}` names both modules (no heritage: `use` and `@behaviour` are not inheritance) |
| **F#** | `.fs` `.fsx` `.fsi` | `open` / `open type` against a declared-name index (namespace/module headers), plus the fsproj `<Compile Include>` compile order. `.fsi` signature files contribute imports only, no symbols. A layout that shares one namespace across many single-file projects leaves most `open` targets ambiguous by design, so unused-export findings there sit at the review tier (0.4) rather than being asserted |
+| **Objective-C** | `.m` `.mm` `.h` | `#import` / `#include` through the generic header-stem index, which covers the one-class-per-file convention; a framework import names no in-repo file and resolves to nothing |
---
@@ -412,6 +414,7 @@ Per-language mechanics behind these:
| VB.NET | Good | Health markers, project-level `<Import Include=...>` as implicit imports |
| Elixir | Good | Health markers, and a call-resolution strategy beyond same-file |
| F# | Good | Health markers, and a resolver that reads the AST index instead of the declared-name regex |
+| Objective-C | Good | Health markers, a resolver that reads the Xcode project rather than file stems, and pairing a header with its implementation across files |
| SQL / dbt | — | Column-level blast radius |
| Shell | — | Shebang detection for extensionless executables |
| HTML | Lightweight | A regex import tier for template dialects, gated on a framework manifest |
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index 51bbca47e..142c70c8b 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -80,6 +80,15 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
# Instantiated by type name and loaded by the runtime (qrc, Loader,
# qmlRegisterType), so a QML file never has a static importer.
"*.qml",
+ # ---- Objective-C conventions ------------------------------------
+ # The app delegate is named in Info.plist and instantiated by
+ # UIApplicationMain / NSApplicationMain, and a scene delegate by the
+ # scene manifest, so no file ever imports either by name. (main.m is
+ # already an entry point through the language spec.)
+ "*AppDelegate.m",
+ "*AppDelegate.h",
+ "*SceneDelegate.m",
+ "*SceneDelegate.h",
# ---- .NET / C# conventions --------------------------------------
# Implicit / generated / framework-loaded files that have no
# static importers by design.
diff --git a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
index 43566dbe8..fcd167ce1 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/file_reachability.py
@@ -79,6 +79,9 @@ _NON_DEPENDENCY_EDGES: frozenset[str] = frozenset({"co_changes"})
_JVM_SUFFIXES: tuple[str, ...] = (".java", ".kt")
+#: Objective-C implementation files, which no source ever imports.
+_OBJC_SOURCE_SUFFIXES: tuple[str, ...] = (".m", ".mm")
+
@dataclass(frozen=True)
class PackageFileMap:
@@ -298,6 +301,18 @@ def is_file_reachable(
if path in rescues.bundler_alias_targets:
return True
+ # Nothing ever ``#import``s an Objective-C ``.m``: the header declares the
+ # interface and the implementation is joined to it by target membership in
+ # the Xcode project, which is not source. ``in_degree=0`` on a ``.m`` is
+ # therefore a property of the language rather than evidence of deadness,
+ # and left alone it reported every implementation file in a library as
+ # unreachable. The header answers for it. Recursion is one level deep: a
+ # ``.h`` never re-enters this branch.
+ if path.endswith(_OBJC_SOURCE_SUFFIXES) and node_data.get("language") == "objectivec":
+ header = f"{path.rsplit('.', 1)[0]}.h"
+ if header in graph and is_file_reachable(header, graph, rescues):
+ return True
+
packages = rescues.package_files
if path.endswith(".go"):
return True if packages is None else is_go_file_reachable(path, graph, packages.go)
diff --git a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
index 7a6664a50..fc3e736e2 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
@@ -174,7 +174,7 @@ def extract_module_docstring(root: Node, src: str, lang: str) -> str | None:
break
if inner_lines:
return "\n".join(inner_lines)
- elif lang in ("cpp", "c"):
+ elif lang in ("cpp", "c", "objectivec"):
# Doxygen: first /** ... */ block comment before any declaration
for child in root.children:
if child.type in ("comment", "block_comment"):
@@ -407,7 +407,7 @@ def extract_symbol_docstring(def_node: Node, src: str, lang: str) -> str | None:
# /** Javadoc */ comment before the method/class
return find_preceding_block_comment(def_node, src, "/**")
- elif lang in ("cpp", "c"):
+ elif lang in ("cpp", "c", "objectivec"):
# Doxygen: /** ... */ block comment or /// line comments
result = find_preceding_block_comment(def_node, src, "/**")
if result:
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
index d2fd23cb4..5f1a0ac9f 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
@@ -29,6 +29,7 @@ from .gdscript import _extract_gdscript_heritage
from .go import _extract_go_heritage
from .java import _extract_java_heritage
from .kotlin import _extract_kotlin_heritage
+from .objectivec import _extract_objectivec_heritage
from .pascal import _extract_pascal_heritage
from .php import _extract_php_heritage
from .python import _extract_python_heritage
@@ -64,6 +65,7 @@ HERITAGE_EXTRACTORS: dict[str, Callable[..., None]] = {
"swift": _extract_swift_heritage,
"scala": _extract_scala_heritage,
"php": _extract_php_heritage,
+ "objectivec": _extract_objectivec_heritage,
"pascal": _extract_pascal_heritage,
"gdscript": _extract_gdscript_heritage,
"vbnet": _extract_vbnet_heritage,
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/objectivec.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/objectivec.py
new file mode 100644
index 000000000..d9c743d92
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/objectivec.py
@@ -0,0 +1,56 @@
+"""Objective-C heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ...type_names import bare_type_name
+from ..helpers import node_text
+
+
+def _extract_objectivec_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Objective-C: ``@interface Foo : NSObject <Delegate, NSCopying>``.
+
+ The superclass is the ``superclass`` field and the adopted protocols are
+ the ``type_name`` children of the ``parameterized_arguments`` list that
+ follows it, which is the C grammar's generic-argument node reused for the
+ ``<...>`` conformance syntax.
+
+ Only a plain ``@interface`` carries heritage: a class extension has no
+ superclass and no conformance list in this position, and the
+ ``@implementation`` repeats neither.
+
+ Stated ceiling: a category that adopts a protocol
+ (``@interface Foo (Extras) <Bar>``) emits nothing either. The early return
+ below drops the whole node, and a category's conformance belongs to the
+ class rather than to the category symbol, which is a separate question.
+ """
+ if def_node.child_by_field_name("category") is not None:
+ return
+
+ superclass = def_node.child_by_field_name("superclass")
+ if superclass is not None:
+ parent = bare_type_name(node_text(superclass, src))
+ if parent and parent != name:
+ out.append(
+ HeritageRelation(
+ child_name=name, parent_name=parent, kind="extends", line=line
+ )
+ )
+
+ for child in def_node.named_children:
+ if child.type != "parameterized_arguments":
+ continue
+ for protocol_node in child.named_children:
+ if protocol_node.type != "type_name":
+ continue
+ protocol = bare_type_name(node_text(protocol_node, src))
+ if protocol and protocol != name:
+ out.append(
+ HeritageRelation(
+ child_name=name, parent_name=protocol, kind="implements", line=line
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.py
index 4e13cef46..2aa10d387 100644
--- a/packages/core/src/repowise/core/ingestion/language_configs.py
+++ b/packages/core/src/repowise/core/ingestion/language_configs.py
@@ -455,6 +455,52 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
# see _fsharp_parent_name.
parent_class_types=frozenset(),
),
+ "objectivec": LanguageConfig(
+ symbol_node_types={
+ # An @interface and its @implementation are two physical nodes in
+ # (usually) two files, the same way a C declaration and its
+ # definition are: both become symbols, the @interface one marked
+ # is_declaration. Within one file they collapse -- see
+ # _dedupe_objc_interface_symbols.
+ "class_interface": "class",
+ "class_implementation": "class",
+ "protocol_declaration": "interface",
+ "method_declaration": "method",
+ "method_definition": "method",
+ # Matches C#'s and Pascal's choice for the same concept: a field
+ # and a callable value share "variable" everywhere except Rust.
+ "property_declaration": "variable",
+ # Plain C inside a .m file, mapped the way c/cpp map it.
+ "function_definition": "function",
+ "declaration": "function",
+ "preproc_def": "variable",
+ "preproc_function_def": "function",
+ "enum_specifier": "enum",
+ "struct_specifier": "struct",
+ "type_definition": "struct",
+ },
+ import_node_types=["preproc_include"],
+ export_node_types=[], # no re-export syntax; the header is the export
+ # Objective-C has no method access modifiers. @private/@protected on
+ # instance variables is the only visibility syntax and no ivars are
+ # captured, so the placeholder C/C++/Pascal use is honest here.
+ visibility_fn=public_by_default,
+ parent_extraction="nesting",
+ # A method_declaration is a direct child of its class_interface and
+ # a method_definition of its class_implementation, so the ancestor
+ # walk needs no per-language dig -- unlike C++ and Pascal, where a
+ # definition sits outside the class body. Reading the ancestor's name
+ # does: these nodes carry it as a bare first identifier child and not
+ # in a `name` field, so _objc_container_parent supplies it.
+ parent_class_types=frozenset(
+ {"class_interface", "class_implementation", "protocol_declaration"}
+ ),
+ # A @protocol is not a declaration of anything defined elsewhere:
+ # nothing ever implements it under its own name.
+ declaration_node_types=frozenset(
+ {"class_interface", "method_declaration", "declaration"}
+ ),
+ ),
"pascal": LanguageConfig(
symbol_node_types={
# declType wraps class/record/interface/helper/enum/set/array/alias
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/objectivec.py b/packages/core/src/repowise/core/ingestion/languages/specs/objectivec.py
index d42d39545..0d835bc8d 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/objectivec.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/objectivec.py
@@ -1,12 +1,107 @@
-"""LanguageSpec for objectivec (extracted from the registry data table)."""
+"""LanguageSpec for Objective-C.
+
+Grammar: tree-sitter-objc (PyPI ``tree-sitter-objc``, import name
+``tree_sitter_objc``), a superset of the C grammar, so ordinary C
+declarations, calls and preprocessor directives inside a ``.m`` file parse
+with the same node shapes ``c.scm`` targets.
+
+Two shapes drive the rest of this entry:
+
+* A method's name is its whole selector (``initWithName:age:``), which the
+ grammar never puts in one node. ``queries/objectivec.scm`` captures the
+ first keyword and ``_objc_selector_name`` joins the rest.
+* ``.h`` is claimed by the C++ spec, and one extension maps to one tag
+ globally. An Objective-C header is recognised by its content instead, in
+ the traverser, right after the extension lookup.
+
+``heritage_node_types`` names only ``class_interface``: the superclass and
+the protocol list are declared on the ``@interface``, and an
+``@implementation`` repeats neither.
+"""
from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="objectivec",
display_name="Objective-C",
+ # ``.h`` is deliberately not claimed here. It belongs to the C++ spec
+ # globally, and a second claim on it would flip every C and C++ header in
+ # every repo to this grammar. Objective-C headers are routed by content.
extensions=frozenset({".m", ".mm"}),
+ grammar_package="tree_sitter_objc",
+ scm_file="objectivec.scm",
+ heritage_node_types=frozenset({"class_interface"}),
+ # No dedicated resolver. ``#import "Foo.h"`` resolves through the generic
+ # stem map, which covers the near-universal one-class-per-file naming
+ # convention; a framework import (``<Foundation/Foundation.h>``) names no
+ # in-repo file and correctly resolves to nothing.
+ import_support="none",
# main.m holds UIApplicationMain/NSApplicationMain.
entry_point_patterns=("main.m",),
- is_passthrough=True,
+ # XCTest names a test file for the class under test plus a ``Tests``
+ # suffix -- ``FooTests.m`` for ``Foo.m``.
+ test_camel_suffixes=("Tests", "Test"),
+ # Foundation / libSystem / runtime functions. Each is an ordinary C call
+ # in the AST, so without this set every one mints an edge to a target
+ # that can never exist in the repo. Matched receiver-blind, so the set
+ # stays to names no project would define itself.
+ builtin_calls=frozenset({
+ "NSLog", "NSAssert", "NSCAssert", "NSParameterAssert",
+ "NSCParameterAssert", "NSStringFromClass", "NSStringFromSelector",
+ "NSStringFromProtocol", "NSClassFromString", "NSSelectorFromString",
+ "NSProtocolFromString", "NSMakeRange", "NSLocalizedString",
+ "NSLocalizedStringFromTable", "NSLocalizedStringWithDefaultValue",
+ "NSApplicationMain", "UIApplicationMain",
+ "CFRetain", "CFRelease", "CFAutorelease", "CFBridgingRetain",
+ "CFBridgingRelease", "CFEqual", "CFGetTypeID",
+ "objc_msgSend", "objc_msgSendSuper", "objc_getClass",
+ "objc_getAssociatedObject", "objc_setAssociatedObject",
+ "class_getName", "sel_registerName", "sel_getName",
+ "method_exchangeImplementations", "class_addMethod",
+ "class_getInstanceMethod", "class_getClassMethod",
+ "dispatch_async", "dispatch_sync", "dispatch_once",
+ "dispatch_after", "dispatch_group_async", "dispatch_group_notify",
+ "dispatch_get_main_queue", "dispatch_get_global_queue",
+ "dispatch_queue_create", "dispatch_semaphore_create",
+ "dispatch_semaphore_wait", "dispatch_semaphore_signal",
+ "free", "malloc", "calloc", "realloc", "memcpy", "memset",
+ "strlen", "strcmp", "printf", "fprintf", "sprintf", "snprintf",
+ }),
+ # Universal Foundation / UIKit / AppKit roots. A class extending one of
+ # these has no in-repo parent to resolve, so the heritage edge is dropped
+ # the same way ``object`` is dropped from Python heritage.
+ builtin_parents=frozenset({
+ "NSObject", "NSProxy",
+ "UIView", "UIViewController", "UIControl", "UIButton", "UILabel",
+ "UITableViewCell", "UICollectionViewCell", "UITableViewController",
+ "UICollectionViewController", "UINavigationController",
+ "UIResponder", "UIWindow", "UIApplication",
+ "NSView", "NSViewController", "NSWindowController", "NSDocument",
+ "NSOperation", "NSOperationQueue", "NSThread", "NSFormatter",
+ "NSValueTransformer", "NSURLProtocol", "NSIncrementalStore",
+ "NSManagedObject", "NSPersistentStore", "NSCoder",
+ "NSArray", "NSMutableArray", "NSDictionary", "NSMutableDictionary",
+ "NSString", "NSMutableString", "NSNumber", "NSError",
+ }),
+ # Foundation / CoreGraphics types plus the C primitives. None of these
+ # ever has an in-repo declaration, so resolving one as a type reference
+ # is a guaranteed miss. Read back through ``is_resolvable_type_name``.
+ builtin_types=frozenset({
+ "id", "instancetype", "Class", "SEL", "IMP", "Protocol", "BOOL",
+ "void", "char", "short", "int", "long", "float", "double", "signed",
+ "unsigned", "size_t", "ssize_t", "ptrdiff_t", "uintptr_t", "intptr_t",
+ "int8_t", "int16_t", "int32_t", "int64_t",
+ "uint8_t", "uint16_t", "uint32_t", "uint64_t",
+ "NSInteger", "NSUInteger", "CGFloat", "NSTimeInterval",
+ "NSString", "NSMutableString", "NSNumber", "NSValue", "NSData",
+ "NSMutableData", "NSArray", "NSMutableArray", "NSDictionary",
+ "NSMutableDictionary", "NSSet", "NSMutableSet", "NSOrderedSet",
+ "NSDate", "NSURL", "NSURLRequest", "NSURLResponse", "NSURLSession",
+ "NSError", "NSException", "NSObject", "NSRange", "NSNotification",
+ "NSBundle", "NSFileManager", "NSLock", "NSCoder", "NSIndexPath",
+ "CGRect", "CGPoint", "CGSize", "CGAffineTransform", "CGColorRef",
+ "dispatch_queue_t", "dispatch_group_t", "dispatch_semaphore_t",
+ "dispatch_block_t", "dispatch_time_t",
+ }),
+ color_hex="#438EFF",
)
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 560d138fa..79b28591e 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -83,6 +83,7 @@ from .parser_helpers import (
_classify_param_origin,
_collect_error_nodes,
_count_arguments,
+ _dedupe_objc_interface_symbols,
_dedupe_pascal_interface_symbols,
_elixir_call_is_definitional,
_elixir_is_template_definition,
@@ -97,6 +98,12 @@ from .parser_helpers import (
_has_callable_ancestor,
_head_type_identifier,
_is_async_node,
+ _objc_call_is_block_variable,
+ _objc_container_node,
+ _objc_container_parent,
+ _objc_is_macro_enum,
+ _objc_message_selector,
+ _objc_symbol_name,
_qualified_cpp_parent,
_qualified_pascal_parent,
_run_query,
@@ -1141,9 +1148,14 @@ class ASTParser:
symbols: list[Symbol] = []
seen: set[tuple[int, str]] = set() # (start_line, name) — dedup decorated dupes
# Parallel to ``symbols`` (same indices) -- only populated/consumed
- # for Pascal, to dedupe interface-declaration vs. implementation
- # method pairs after the loop. See _dedupe_pascal_interface_symbols.
+ # for Pascal and Objective-C, to dedupe interface-declaration vs.
+ # implementation method pairs after the loop. See
+ # _dedupe_pascal_interface_symbols / _dedupe_objc_interface_symbols.
node_types: list[str] = []
+ # Also parallel to ``symbols``, Objective-C only: which of @interface /
+ # @implementation / @protocol declared each member, so a protocol's
+ # method is never deduped against a same-named class method.
+ objc_container_kinds: list[str | None] = []
# Deferred-export names (``export { x }`` / ``export default x``),
# computed once per file for the TS/JS visibility refinement.
@@ -1262,6 +1274,17 @@ class ASTParser:
# compiler generates, not for the protocol alone.
name = _elixir_symbol_name(def_node, name, src)
+ elif file_info.language == "objectivec":
+ # `typedef NS_ENUM(NSInteger, Kind) { ... }` has no grammar
+ # rule, so only its enum *cases* survive as declarators and
+ # each would become a symbol named as though it were the type.
+ if _objc_is_macro_enum(def_node, src):
+ continue
+ # A method is named by its whole selector
+ # (`initWithName:age:`), which no single node holds, and a
+ # category by the class it extends plus its own name.
+ name = _objc_symbol_name(def_node, name, src)
+
export_type = cpp_export_type_defs.get(def_node.id)
if export_type is not None and name != export_type.name:
# The ordinary struct/class query sees the same specifier, but
@@ -1554,6 +1577,13 @@ class ASTParser:
if parent_name is None and file_info.language == "elixir":
parent_name = _elixir_module_parent(def_node, src)
+ # Objective-C: an @interface / @implementation / @protocol names
+ # itself with a bare first identifier and no ``name`` field, so
+ # the nesting walk above finds the right ancestor and reads
+ # nothing off it.
+ if parent_name is None and file_info.language == "objectivec":
+ parent_name = _objc_container_parent(def_node, config.parent_class_types, src)
+
# A ``field_declaration`` cannot occur outside a class body, so a
# missing parent means the class did not parse. Grammar recovery,
# not a member function.
@@ -1616,10 +1646,19 @@ class ASTParser:
)
)
node_types.append(node_type)
+ if file_info.language == "objectivec":
+ container = _objc_container_node(def_node, config.parent_class_types)
+ objc_container_kinds.append(container.type if container else None)
if file_info.language == "pascal":
symbols = _dedupe_pascal_interface_symbols(symbols, node_types)
+ # A .m file routinely declares its private methods in a class
+ # extension and defines them below in the @implementation, which
+ # builds each symbol id twice in one file.
+ if file_info.language == "objectivec":
+ symbols = _dedupe_objc_interface_symbols(symbols, node_types, objc_container_kinds)
+
return symbols
def _find_parent(
@@ -2031,6 +2070,25 @@ class ASTParser:
if not target_name:
continue
+ # Objective-C: a message send binds one `method:` child per
+ # keyword, so `[view setTitle:t forState:s]` matches the one
+ # query pattern twice. Join the whole selector on the first match
+ # so it can meet the symbol side, and drop the rest.
+ if file_info.language == "objectivec":
+ if site_node.type == "message_expression":
+ joined = _objc_message_selector(site_node, target_nodes[0], src)
+ if joined is None:
+ continue
+ target_name = joined
+ # A block held in a parameter or a local is invoked with C call
+ # syntax, so `completionBlock(hit)` is indistinguishable from a
+ # call to a C function by name alone. Left in, the resolver
+ # binds it to whatever same-named @property the repo holds.
+ elif not receiver_nodes and _objc_call_is_block_variable(
+ site_node, target_name, src
+ ):
+ continue
+
if target_name in _call_builtins:
continue
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index 865578c2f..f162c70a0 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -427,11 +427,23 @@ def _sanitize_pascal_project_source(source: bytes) -> bytes:
it, so there's nothing to blank there and no reason to run the regex
over every unit file in a codebase.
"""
- if not _PASCAL_USES_IN_CLAUSE_RE.search(source):
+ return _blank_matches(source, _PASCAL_USES_IN_CLAUSE_RE)
+
+
+def _blank_matches(source: bytes, pattern: re.Pattern[bytes]) -> bytes:
+ """Overwrite every match of *pattern* with spaces, keeping the length.
+
+ The shared half of every byte-preserving source sanitizer: a construct the
+ grammar has no rule for is replaced in place, never removed, so line
+ numbers and byte offsets for everything else in the file survive. Spaces
+ and never a newline, so no pattern can consume a line break it did not
+ match.
+ """
+ if not pattern.search(source):
return source
out = bytearray(source)
- for m in _PASCAL_USES_IN_CLAUSE_RE.finditer(source):
- start, end = m.span()
+ for match in pattern.finditer(source):
+ start, end = match.span()
out[start:end] = b" " * (end - start)
return bytes(out)
@@ -546,6 +558,283 @@ def _pascal_dedupe_key(parent_name: str | None, signature: str) -> tuple[str | N
return (parent_key, sig_key)
+# ---------------------------------------------------------------------------
+# Objective-C helpers
+# ---------------------------------------------------------------------------
+
+_OBJC_METHOD_NODE_TYPES = frozenset({"method_declaration", "method_definition"})
+_OBJC_CLASS_NODE_TYPES = frozenset({"class_interface", "class_implementation"})
+
+# A declaration and the definition that answers it, keyed the way the dedup
+# below pairs them.
+_OBJC_DEFINITION_NODE_TYPES = frozenset({"class_implementation", "method_definition"})
+_OBJC_DECLARATION_NODE_TYPES = frozenset({"class_interface", "method_declaration"})
+
+# Macros that expand to nothing but are spelled as a bare identifier, so the
+# grammar makes them a keyword child of the method they trail.
+_OBJC_TRAILING_MACRO_NAMES = frozenset({
+ "NS_DESIGNATED_INITIALIZER", "NS_UNAVAILABLE", "NS_REQUIRES_SUPER",
+ "NS_RETURNS_INNER_POINTER", "NS_REFINED_FOR_SWIFT", "NS_SWIFT_UI_ACTOR",
+ "NS_REQUIRES_NIL_TERMINATION", "UNAVAILABLE_ATTRIBUTE", "DEPRECATED_ATTRIBUTE",
+})
+
+# ``typedef NS_ENUM(NSInteger, Kind) { KindA }`` shapes. See _objc_is_macro_enum.
+_OBJC_ENUM_MACRO_NAMES = frozenset({
+ "NS_ENUM", "NS_OPTIONS", "NS_CLOSED_ENUM", "NS_ERROR_ENUM",
+ "CF_ENUM", "CF_OPTIONS", "CF_CLOSED_ENUM",
+})
+
+
+def _objc_selector_name(def_node: Node, default_name: str, src: str) -> str:
+ """Join a method's keyword parts into its full selector.
+
+ A keyword is an ``identifier`` child that a ``method_parameter`` follows;
+ anything trailing the last parameter is an attribute macro, not part of
+ the name. See the Objective-C section of the architecture doc.
+ """
+ if def_node.type not in _OBJC_METHOD_NODE_TYPES:
+ return default_name
+ parts: list[str] = []
+ pending: str | None = None
+ for child in def_node.children:
+ if child.type == "identifier":
+ # Only the identifier immediately before a method_parameter is a
+ # keyword; a bare trailing one is a macro like
+ # NS_DESIGNATED_INITIALIZER, which would otherwise join into the
+ # selector and stop the header pairing with its implementation.
+ pending = _node_text(child, src).strip() or None
+ elif child.type == "method_parameter":
+ if pending is not None:
+ parts.append(pending)
+ pending = None
+ elif child.type in ("compound_statement", ";"):
+ break
+ if parts:
+ return "".join(f"{p}:" for p in parts)
+ # No parameters at all: the selector is the first keyword, unadorned.
+ first = next((c for c in def_node.children if c.type == "identifier"), None)
+ if first is None:
+ return default_name
+ text = _node_text(first, src).strip()
+ if not text or text in _OBJC_TRAILING_MACRO_NAMES:
+ return default_name
+ return text
+
+
+def _objc_is_macro_enum(def_node: Node, src: str) -> bool:
+ """True for a ``typedef NS_ENUM(Type, Name) { … }`` typedef.
+
+ This grammar has no rule for the macro, so the name argument and the brace
+ body land in ERROR nodes and only the *enumerators* survive as
+ ``declarator`` children. Capturing those mints a symbol per enum case named
+ as though it were the type, and never one for the type itself, so the whole
+ typedef is skipped: no symbol beats a wrong one.
+ """
+ if def_node.type != "type_definition":
+ return False
+ for child in def_node.children:
+ if child.type != "macro_type_specifier":
+ continue
+ name = child.child_by_field_name("name")
+ if name is not None and _node_text(name, src).strip() in _OBJC_ENUM_MACRO_NAMES:
+ return True
+ return False
+
+
+def _objc_category_name(def_node: Node, default_name: str, src: str) -> str:
+ """Name a category for the class it extends plus its own name.
+
+ Two categories on one class are two declarations about it, so naming both
+ for the class alone would merge them. A class extension (``Foo ()``) binds
+ no ``category`` field and keeps the plain name.
+ """
+ if def_node.type not in _OBJC_CLASS_NODE_TYPES:
+ return default_name
+ category = def_node.child_by_field_name("category")
+ if category is None:
+ return default_name
+ text = _node_text(category, src).strip()
+ return f"{default_name}({text})" if text else default_name
+
+
+def _objc_symbol_name(def_node: Node, default_name: str, src: str) -> str:
+ """The name a captured Objective-C definition carries."""
+ if def_node.type in _OBJC_METHOD_NODE_TYPES:
+ return _objc_selector_name(def_node, default_name, src)
+ return _objc_category_name(def_node, default_name, src)
+
+
+def _objc_container_node(def_node: Node, container_types: frozenset[str]) -> Node | None:
+ """The ``@interface`` / ``@implementation`` / ``@protocol`` around a member."""
+ ancestor = def_node.parent
+ while ancestor is not None:
+ if ancestor.type in container_types:
+ return ancestor
+ ancestor = ancestor.parent
+ return None
+
+
+def _objc_container_parent(def_node: Node, container_types: frozenset[str], src: str) -> str | None:
+ """The name of the container a method or property is declared in.
+
+ The generic nesting walk finds the same ancestor and then reads a ``name``
+ field these nodes do not have: each carries its name as a bare first
+ ``identifier`` child. Members of a category take the category's own name.
+ """
+ container = _objc_container_node(def_node, container_types)
+ if container is None:
+ return None
+ identifier = next((c for c in container.children if c.type == "identifier"), None)
+ if identifier is None:
+ return None
+ name = _node_text(identifier, src).strip()
+ return _objc_category_name(container, name, src) if name else None
+
+
+def _objc_message_selector(site_node: Node, target_node: Node, src: str) -> str | None:
+ """Join a message send's keyword parts, or None for a repeat match.
+
+ ``[view setTitle:t forState:s]`` binds one ``method:`` child per keyword,
+ so the one query pattern matches once per keyword. Returns the joined
+ selector for the match carrying the first keyword and None for every later
+ one, so the extra matches are dropped rather than emitted as targets that
+ name nothing. The node's own ``:`` tokens say whether the selector takes
+ arguments: ``[obj run]`` is ``run`` and ``[obj run:x]`` is ``run:``.
+ """
+ methods = site_node.children_by_field_name("method")
+ if not methods or methods[0].id != target_node.id:
+ return None
+ parts = [_node_text(m, src).strip() for m in methods]
+ parts = [p for p in parts if p]
+ if not parts:
+ return None
+ takes_arguments = any(c.type == ":" for c in site_node.children)
+ if not takes_arguments:
+ return parts[0]
+ return "".join(f"{p}:" for p in parts)
+
+
+def _objc_call_is_block_variable(site_node: Node, target_name: str, src: str) -> bool:
+ """True when a bare-identifier call invokes a block held in a variable.
+
+ Objective-C invokes a block with C call syntax, so ``completionBlock(hit)``
+ is a ``call_expression`` on a bare identifier that nothing in the grammar
+ separates from a call to a C function. Names like this are ubiquitous as
+ both a parameter and a ``@property``, so without the scope check the
+ resolver binds the invocation to an unrelated class's property.
+ """
+ node: Node | None = site_node
+ while node is not None:
+ if node.type == "compound_statement":
+ for statement in node.named_children:
+ if statement.type == "declaration" and _objc_declares_name(
+ statement, target_name, src
+ ):
+ return True
+ elif node.type == "method_definition":
+ return any(
+ child.type == "method_parameter"
+ and _objc_declares_name(child, target_name, src)
+ for child in node.children
+ )
+ elif node.type == "function_definition":
+ declarator = node.child_by_field_name("declarator")
+ return declarator is not None and _objc_declares_name(declarator, target_name, src)
+ node = node.parent
+ return False
+
+
+def _objc_declares_name(node: Node, name: str, src: str) -> bool:
+ """True when *node* binds *name* as a parameter or a variable.
+
+ A declarator nests (``void (^block)(int)``, ``SDBlock done = ^{}``), so
+ every identifier under the node is checked rather than only the direct
+ children. The node is a parameter or a declaration, never a body, so the
+ walk stays small; a nested block body is skipped for the same reason.
+ """
+ stack = [node]
+ while stack:
+ current = stack.pop()
+ if current.type in ("identifier", "field_identifier"):
+ if _node_text(current, src).strip() == name:
+ return True
+ elif current.type != "compound_statement":
+ stack.extend(current.children)
+ return False
+
+
+def _objc_container_family(container_kind: str | None) -> str | None:
+ """Which namespace a member belongs to: a protocol's, or a class's.
+
+ An ``@interface`` and its ``@implementation`` are the same class, so a
+ declaration in one must still dedupe against a definition in the other; a
+ ``@protocol`` of the same name is a different thing entirely.
+ """
+ return "protocol" if container_kind == "protocol_declaration" else container_kind and "class"
+
+
+def _dedupe_objc_interface_symbols(
+ symbols: list[Symbol], node_types: list[str], container_kinds: list[str | None]
+) -> list[Symbol]:
+ """Collapse a declaration into the definition standing beside it.
+
+ A ``.m`` routinely opens with a class extension (``@interface Foo ()``)
+ declaring the private methods its ``@implementation Foo`` then defines, so
+ each builds the same symbol id twice in one file. The definition wins: it
+ carries the body. Across two files the split is real and both symbols are
+ kept, marked with ``is_declaration`` the way a C header's prototype and its
+ ``.c`` definition already are.
+
+ The key carries the container kind because a protocol and a class may share
+ a name in one file, and ``-ping`` on the protocol is then a different method
+ from ``-ping`` on the class. Keyed on the name and not the signature:
+ Objective-C has no overloading, and a declaration and its definition
+ routinely differ in parameter names and nullability annotations.
+ """
+ definition_keys = {
+ (_objc_container_family(kind), s.parent_name, s.name)
+ for s, nt, kind in zip(symbols, node_types, container_kinds, strict=True)
+ if nt in _OBJC_DEFINITION_NODE_TYPES
+ }
+ seen_declarations: set[tuple[str | None, str | None, str]] = set()
+ kept: list[Symbol] = []
+ for symbol, node_type, kind in zip(symbols, node_types, container_kinds, strict=True):
+ if node_type in _OBJC_DECLARATION_NODE_TYPES:
+ key = (_objc_container_family(kind), symbol.parent_name, symbol.name)
+ if key in definition_keys or key in seen_declarations:
+ continue
+ seen_declarations.add(key)
+ kept.append(symbol)
+ return kept
+
+
+# Whole-line macros that expand to nothing a parser needs but which this
+# grammar reads as the start of a C declaration, swallowing whatever follows
+# into an ERROR node. Only bare whole-line forms are listed: a macro that
+# opens a real declaration (``FOUNDATION_EXPORT NSString *const kFoo;``) must
+# stay, and a call-shaped one (``NS_ENUM(NSInteger, Kind)``) is a different
+# problem that blanking a line cannot fix.
+_OBJC_BARE_MACRO_LINE_RE = re.compile(
+ rb"^[ \t]*(?:NS_ASSUME_NONNULL_BEGIN|NS_ASSUME_NONNULL_END"
+ rb"|NS_HEADER_AUDIT_BEGIN\([^)\r\n]*\)|NS_HEADER_AUDIT_END"
+ rb"|CF_ASSUME_NONNULL_BEGIN|CF_ASSUME_NONNULL_END"
+ rb"|NS_REFINED_FOR_SWIFT|NS_SWIFT_UI_ACTOR)[ \t]*(?=\r?\n|$)",
+ re.MULTILINE,
+)
+
+
+def prepare_objectivec_source(source: bytes) -> bytes:
+ """Blank whole-line nullability-audit macros, preserving every offset.
+
+ ``NS_ASSUME_NONNULL_BEGIN`` is not a preprocessor directive and this
+ grammar has no rule for it, so it parses as the opening of a C declaration
+ and error recovery folds the whole ``@interface … @end`` block after it
+ into one ERROR node. The macro wraps almost every modern Objective-C
+ header, so this is the dominant parse failure in real source.
+ """
+ return _blank_matches(source, _OBJC_BARE_MACRO_LINE_RE)
+
+
# ---------------------------------------------------------------------------
# Type reference helpers (used by _extract_type_refs)
# ---------------------------------------------------------------------------
@@ -1347,6 +1636,43 @@ def _elixir_head_type_identifier(type_node: Node, src: str) -> str | None:
return node_text(type_node, src).strip() or None
+def _objc_head_type_identifier(type_node: Node, src: str) -> str | None:
+ """Return the head class name of an Objective-C type position, or None.
+
+ Examples:
+ ``(NSString *)`` -> None (Foundation, never in-repo)
+ ``(AFHTTPClient *)`` -> the name
+ ``(instancetype)`` -> None (builtin)
+ ``(void)`` / ``(id)`` -> None (primitive / builtin)
+ ``@class Helper;`` -> "Helper"
+
+ The capture is a ``type_name`` wrapper for a method return or parameter
+ type, a bare ``type_identifier`` for a property, and a plain
+ ``identifier`` for a ``@class`` forward declaration or a protocol name, so
+ all four shapes start here. A pointer star lives in an
+ ``abstract_pointer_declarator`` inside the ``type_name``, which is skipped
+ rather than unwrapped: the star is not part of the name.
+ """
+ node: Node | None = type_node
+ for _ in range(6):
+ if node is None:
+ return None
+ kind = node.type
+ if kind in ("type_identifier", "identifier"):
+ text = _node_text(node, src).strip()
+ return text if is_resolvable_type_name(text, "objectivec") else None
+ if kind in ("primitive_type", "sized_type_specifier", "typedefed_specifier"):
+ return None
+ if kind in ("struct_specifier", "union_specifier", "enum_specifier"):
+ name = node.child_by_field_name("name")
+ if name is None:
+ return None # anonymous aggregate -- no named type to resolve
+ text = _node_text(name, src).strip()
+ return text if is_resolvable_type_name(text, "objectivec") else None
+ node = node.named_children[0] if node.named_children else None
+ return None
+
+
TYPE_HEAD_EXTRACTORS: dict[str, Callable[[Node, str], str | None]] = {
"go": _go_head_type_identifier,
"c": _c_head_type_identifier,
@@ -1359,6 +1685,7 @@ TYPE_HEAD_EXTRACTORS: dict[str, Callable[[Node, str], str | None]] = {
"pascal": _pascal_head_type_identifier,
"elixir": _elixir_head_type_identifier,
"fsharp": _fsharp_head_type_identifier,
+ "objectivec": _objc_head_type_identifier,
}
diff --git a/packages/core/src/repowise/core/ingestion/queries/objectivec.scm b/packages/core/src/repowise/core/ingestion/queries/objectivec.scm
new file mode 100644
index 000000000..c202cdb9e
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/queries/objectivec.scm
@@ -0,0 +1,187 @@
+; =============================================================================
+; repowise: Objective-C symbol, import and call queries
+; tree-sitter-objc (amaanq/tree-sitter-objc) >= 3.0.2, a C-grammar superset
+; =============================================================================
+;
+; Node-shape reference, read off the installed grammar because the wheel ships
+; no node-types.json:
+; class_interface := "@interface" (identifier) ; class name is the FIRST
+; (":" superclass:(identifier))? ; named child; a category is
+; (parameterized_arguments)? ; the `category:` field and an
+; ("(" category:(identifier)? ")")? … "@end" ; empty "()" is an extension
+; class_implementation := "@implementation" (identifier) … "@end"
+; protocol_declaration := "@protocol" (identifier) (protocol_reference_list)? … "@end"
+; method_declaration := ("+"|"-") (method_type) (identifier) (method_parameter)* ";"
+; method_definition := the same, with a compound_statement instead of ";"
+; message_expression := "[" receiver:(_) method:(identifier) (":" arg)* … "]"
+;
+; Two things this grammar gives no single node for:
+; * a method's selector. `initWithName:age:` is a flat, unlabelled run of
+; bare `identifier` children interleaved with `method_parameter`s, so the
+; query captures the first keyword and `_objc_selector_name` joins the
+; rest from the definition node.
+; * a multi-part `@selector(a:b:)` literal. The text between the parens is
+; absent from the parse tree entirely, so there is nothing to capture and
+; no `selector_expression` pattern here.
+
+; ---------------------------------------------------------------------------
+; Symbols: classes, categories, class extensions
+; ---------------------------------------------------------------------------
+; Anchored on the first named child so the `superclass:` and `category:`
+; identifiers, which are the same node kind, cannot be read as the name.
+; A category (`Foo (Extras)`) is renamed to `Foo(Extras)` afterwards and a
+; class extension (`Foo ()`) keeps the plain name and is deduped against the
+; `@implementation` in its own file, see `_objc_symbol_name` and
+; `_dedupe_objc_interface_symbols`.
+
+(class_interface
+ . (identifier) @symbol.name) @symbol.def
+
+(class_implementation
+ . (identifier) @symbol.name) @symbol.def
+
+(protocol_declaration
+ . (identifier) @symbol.name) @symbol.def
+
+; ---------------------------------------------------------------------------
+; Symbols: methods
+; ---------------------------------------------------------------------------
+; Anchored immediately after the return type, which pins the capture to the
+; first keyword of the selector. An unanchored `(identifier)` child pattern
+; fires once per keyword and would mint one symbol per selector part.
+
+(method_declaration
+ (method_type) . (identifier) @symbol.name) @symbol.def
+
+(method_definition
+ (method_type) . (identifier) @symbol.name) @symbol.def
+
+; ---------------------------------------------------------------------------
+; Symbols: properties
+; ---------------------------------------------------------------------------
+; The name sits under `declarator:` for a pointer property (`NSString *name`)
+; and is a bare identifier for a scalar one (`int hidden`).
+
+(property_declaration
+ (struct_declaration
+ (struct_declarator
+ (pointer_declarator
+ declarator: (identifier) @symbol.name)))) @symbol.def
+
+(property_declaration
+ (struct_declaration
+ (struct_declarator
+ (identifier) @symbol.name))) @symbol.def
+
+; ---------------------------------------------------------------------------
+; Symbols: plain C, the same shapes c.scm uses
+; ---------------------------------------------------------------------------
+; Objective-C files carry ordinary C freely, and a static helper function is
+; as much a symbol here as it is in a .c file.
+
+(function_definition
+ declarator: (function_declarator
+ declarator: (identifier) @symbol.name
+ parameters: (parameter_list) @symbol.params)) @symbol.def
+
+(declaration
+ declarator: (function_declarator
+ declarator: (identifier) @symbol.name
+ parameters: (parameter_list) @symbol.params)) @symbol.def
+
+(preproc_def
+ name: (identifier) @symbol.name) @symbol.def
+
+(preproc_function_def
+ name: (identifier) @symbol.name
+ parameters: (preproc_params) @symbol.params) @symbol.def
+
+(enum_specifier
+ name: (type_identifier) @symbol.name) @symbol.def
+
+(struct_specifier
+ name: (type_identifier) @symbol.name) @symbol.def
+
+(type_definition
+ declarator: (type_identifier) @symbol.name) @symbol.def
+
+; ---------------------------------------------------------------------------
+; Imports: `#import` and `#include`
+; ---------------------------------------------------------------------------
+; Both are `preproc_include` in this grammar, told apart only by the
+; `directive:` field text, which these patterns deliberately do not read: an
+; `#import "Foo.h"` and an `#include "foo.h"` name a file the same way and
+; resolve the same way. Same pair of patterns as c.scm.
+
+(preproc_include
+ path: (system_lib_string) @import.module) @import.statement
+
+(preproc_include
+ path: (string_literal) @import.module) @import.statement
+
+; ---------------------------------------------------------------------------
+; Calls: message sends
+; ---------------------------------------------------------------------------
+; `[obj doThis:a that:b]` binds one `method:` child per keyword, so this
+; pattern matches once per keyword part. The parser joins the whole selector
+; from the site node and keeps only the first match, see
+; `_objc_message_selector`. A nested send (`[[Foo alloc] init]`) sits in the
+; outer send's `receiver:` field and matches on its own, so it stays a second,
+; separate call site. `self` and `super` keep their literal text as receiver.
+
+(message_expression
+ receiver: (_) @call.receiver
+ method: (identifier) @call.target) @call.site
+
+; ---------------------------------------------------------------------------
+; Calls: plain C, the same shapes c.scm uses
+; ---------------------------------------------------------------------------
+
+(call_expression
+ function: (identifier) @call.target
+ arguments: (argument_list) @call.arguments) @call.site
+
+(call_expression
+ function: (field_expression
+ argument: (identifier) @call.receiver
+ field: (field_identifier) @call.target)
+ arguments: (argument_list) @call.arguments) @call.site
+
+; ---------------------------------------------------------------------------
+; Type references, drive file-level ``type_use`` edges
+; ---------------------------------------------------------------------------
+; A class named only in a parameter type, a return type, a property type or a
+; `@class` forward declaration carries no import naming it: the `#import`
+; names the header file, not the class; without these captures every class
+; declared in a header reads as an unused export. Everything below is a type
+; position, and none of it is ever a call.
+
+; Method return types and method parameter types both wrap the type in
+; `method_type`.
+(method_type
+ (type_name) @param.type)
+
+; `@property (nonatomic) NSString *name;`
+(property_declaration
+ (struct_declaration
+ (type_identifier) @param.type))
+
+; `@class Helper;` names a class, not a file, so it is a type reference and
+; never an import.
+(class_declaration
+ (identifier) @param.type)
+
+; Protocol conformance lists: `<Delegate, NSCopying>` on an `@interface` is a
+; `parameterized_arguments`, on an `@protocol` a `protocol_reference_list`.
+(parameterized_arguments
+ (type_name) @param.type)
+
+(protocol_reference_list
+ (identifier) @param.type)
+
+; Plain C type positions, as in c.scm.
+(parameter_declaration
+ type: (_) @param.type)
+
+(field_declaration
+ type: (_) @param.type)
diff --git a/packages/core/src/repowise/core/ingestion/sfc_source.py b/packages/core/src/repowise/core/ingestion/sfc_source.py
index 14e9886c0..d421a8234 100644
--- a/packages/core/src/repowise/core/ingestion/sfc_source.py
+++ b/packages/core/src/repowise/core/ingestion/sfc_source.py
@@ -787,4 +787,8 @@ def prepare_source(language: str, source: bytes, *, path: str | None = None) ->
from .parser_helpers import prepare_pascal_source
return prepare_pascal_source(source, path)
+ if language == "objectivec" and source:
+ from .parser_helpers import prepare_objectivec_source
+
+ return prepare_objectivec_source(source)
return source
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.py
index bf32990a6..d628db670 100644
--- a/packages/core/src/repowise/core/ingestion/traverser.py
+++ b/packages/core/src/repowise/core/ingestion/traverser.py
@@ -17,6 +17,7 @@ from __future__ import annotations
import configparser
import os
+import re
import threading
from collections.abc import Callable, Iterable, Iterator
from dataclasses import dataclass, field
@@ -747,6 +748,10 @@ class FileTraverser:
# fall through to binary detection + shebang when the extension is
# unrecognised, avoiding an 8 KB read for every .py/.ts/.go/… file.
language = _language_from_name_or_ext(abs_path)
+ # A .h is C++ by extension and may be Objective-C by content; only a
+ # short read of the file itself can tell the two apart.
+ if language == "cpp":
+ language = _objc_header_language(abs_path) or language
if language is None:
if _is_binary(abs_path):
with self._count_lock:
@@ -921,10 +926,62 @@ def _language_from_name_or_ext(abs_path: Path) -> LanguageTag | None:
return EXTENSION_TO_LANGUAGE.get(abs_path.suffix.lower())
+# A declaration or an import that opens its own line. Anchored rather than
+# matched anywhere in the file, and matched only after comments are blanked:
+# ``@interface`` and ``@class`` are Doxygen commands too, so an
+# anywhere-in-the-file token match routed C++ headers documented with
+# ``/** @class Widget */`` to the Objective-C grammar. ``@class`` is left out
+# because a bare forward declaration adds no header the rest of this rule
+# misses; ``#import`` stays because an umbrella header is a run of imports
+# with no declaration of its own, and dropping it lost every one of them.
+_OBJC_HEADER_DECLARATION_RE = re.compile(
+ rb"^[ \t]*(?:@(?:interface|implementation|protocol)\b|#[ \t]*import\b)", re.MULTILINE
+)
+
+# Comment spans to blank before that match runs, so a commented-out or
+# documented declaration cannot decide the routing.
+_C_COMMENT_RE = re.compile(rb"//[^\n]*|/\*.*?(?:\*/|\Z)", re.DOTALL)
+
+# How much of a .h file to read looking for one. Generous because the first
+# declaration sits below the licence banner and a Doxygen block per method:
+# in the corpus the first ``@interface`` landed at byte 4128 and 4374 in two
+# headers, so a 4 KB budget missed both.
+_OBJC_HEADER_SNIFF_BYTES = 16384
+
+
+def _objc_header_language(abs_path: Path) -> LanguageTag | None:
+ """``objectivec`` for a ``.h`` that reads as Objective-C, else ``None``.
+
+ One extension maps to one language for the whole repository, and ``.h``
+ belongs to C++; claiming it for Objective-C as well would reroute every C
+ and C++ header everywhere. Content is the only signal that can tell one
+ ``.h`` from another: an ``@interface``, ``@implementation``, ``@protocol``
+ or ``#import`` opening a line outside a comment is not C or C++.
+
+ Called only where the extension lookup already answered ``cpp``, so it
+ costs one read per ``.h`` file and nothing at all for anything else.
+ The traverser's existing head read, for binary detection and shebang
+ sniffing, fires only for an *unrecognised* extension, so there is no
+ earlier read of a ``.h`` to share.
+ """
+ if abs_path.suffix.lower() != ".h":
+ return None
+ try:
+ with open(abs_path, "rb") as f:
+ head = f.read(_OBJC_HEADER_SNIFF_BYTES)
+ except OSError:
+ return None
+ # Blank the comments in place so line starts are preserved.
+ head = _C_COMMENT_RE.sub(lambda m: b" " * len(m.group(0)), head)
+ return "objectivec" if _OBJC_HEADER_DECLARATION_RE.search(head) else None
+
+
def _detect_language(abs_path: Path) -> LanguageTag:
- """Detect the language of a file from name, extension, or shebang."""
+ """Detect the language of a file from name, extension, content, or shebang."""
lang = _language_from_name_or_ext(abs_path)
if lang is not None:
+ if lang == "cpp":
+ return _objc_header_language(abs_path) or lang
return lang
return _detect_by_shebang(abs_path)
diff --git a/pyproject.toml b/pyproject.toml
index f349b5319..e79d0e8e5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -56,6 +56,7 @@ dependencies = [
"tree-sitter-vb-dotnet>=0.3,<1",
"tree-sitter-elixir>=0.3.5,<1",
"tree-sitter-fsharp>=0.3.11,<1",
+ "tree-sitter-objc>=3.0.2,<4",
# Markup grammars for single-file components: these locate <script> blocks
# and markup expressions only; the JS inside them is parsed with the
# TypeScript grammar (see sfc_source.py). There is no tree-sitter-vue on
diff --git a/tests/unit/dead_code/test_reachability.py b/tests/unit/dead_code/test_reachability.py
index 4116e4834..caff25aae 100644
--- a/tests/unit/dead_code/test_reachability.py
+++ b/tests/unit/dead_code/test_reachability.py
@@ -219,3 +219,61 @@ def test_framework_anchor_node_not_flagged_as_unreachable():
assert "framework:typo3-core" not in paths
# ext_localconf.php should also not be flagged: it has a framework: predecessor.
assert "ext_localconf.php" not in paths
+
+
+def _objc_node(**overrides):
+ node = {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "language": "objectivec",
+ "symbol_count": 3,
+ "symbols": [],
+ }
+ node.update(overrides)
+ return node
+
+
+def test_objc_implementation_is_reached_through_its_header():
+ """Nothing ever ``#import``s a ``.m``.
+
+ A header declares the interface and the Xcode project joins the
+ implementation to it by target membership, which is not source. Without
+ the header standing in, every implementation file in an Objective-C
+ library reported as unreachable at full confidence.
+ """
+ g = _build_graph(
+ nodes={
+ "Lib/Widget.h": _objc_node(),
+ "Lib/Widget.m": _objc_node(),
+ "Lib/Umbrella.h": _objc_node(),
+ },
+ edges=[("Lib/Umbrella.h", "Lib/Widget.h", {"type": "imports"})],
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
+ paths = {f.file_path for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE}
+ assert "Lib/Widget.m" not in paths
+
+
+def test_objc_implementation_with_no_header_is_still_flagged():
+ """The rescue is the header, not the extension.
+
+ A ``.m`` whose header nothing imports, or which has no header at all, is
+ as unreachable as any other orphan.
+ """
+ g = _build_graph(
+ nodes={
+ "Lib/Orphan.m": _objc_node(),
+ "Lib/Lonely.h": _objc_node(),
+ "Lib/Lonely.m": _objc_node(),
+ },
+ edges=[],
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
+ paths = {f.file_path for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE}
+ assert "Lib/Orphan.m" in paths
+ assert "Lib/Lonely.m" in paths
diff --git a/tests/unit/ingestion/parser/test_objectivec.py b/tests/unit/ingestion/parser/test_objectivec.py
new file mode 100644
index 000000000..c952e22de
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_objectivec.py
@@ -0,0 +1,452 @@
+"""Unit tests for the Objective-C language pipeline.
+
+Tests parse inline byte strings so no filesystem I/O is needed. Covers
+symbols (including joined selector names, categories and class extensions),
+imports, type references, message sends, heritage, docstrings and the
+whole-line macro sanitiser -- see docs/architecture/language-support.md's
+"one .scm file + one LanguageConfig" recipe.
+"""
+
+from __future__ import annotations
+
+import tree_sitter_objc # noqa: F401 -- a real dependency; the import proves it
+
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.parser_helpers import prepare_objectivec_source
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+
+def _objc(path: str = "Foo.m") -> object:
+ return _make_file_info(path, "objectivec")
+
+
+HEADER = b"""\
+#import <Foundation/Foundation.h>
+#import "Helper.h"
+#include <stdio.h>
+@class Sidecar;
+
+NS_ASSUME_NONNULL_BEGIN
+
+@protocol Feeder <NSObject>
+- (void)didFinish:(id)sender;
+@end
+
+/** The widget everything hangs off. */
+@interface Widget : Panel <Feeder, NSCopying>
+@property (nonatomic, strong) Sidecar *sidecar;
+@property (nonatomic) int slot;
+- (instancetype)initWithName:(NSString *)name age:(NSInteger)age;
++ (instancetype)widgetWithName:(NSString *)name;
+- (void)run;
+@end
+
+@interface Widget (Trimming)
+- (void)trim;
+@end
+
+NS_ASSUME_NONNULL_END
+"""
+
+IMPLEMENTATION = b"""\
+#import "Widget.h"
+
+@interface Widget ()
+- (void)secret;
+@end
+
+@implementation Widget
+
+- (instancetype)initWithName:(NSString *)name age:(NSInteger)age {
+ self = [super init];
+ NSLog(@"%@", name);
+ normalise(3);
+ [self secret];
+ return [[Sidecar alloc] initWithName:name age:0];
+}
+
+- (void)run {}
+- (void)secret {}
+
+@end
+
+static int normalise(int x) { return x; }
+"""
+
+
+class TestObjectiveCSymbols:
+ def test_finds_the_top_level_kinds(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ kinds = {(s.name, s.kind) for s in result.symbols}
+ assert ("Widget", "class") in kinds
+ assert ("Feeder", "interface") in kinds
+ assert ("sidecar", "variable") in kinds
+ assert ("slot", "variable") in kinds
+
+ def test_a_method_is_named_by_its_whole_selector(self, parser: ASTParser) -> None:
+ # The grammar has no selector node: `initWithName:age:` is a flat run
+ # of bare identifiers interleaved with method_parameter nodes, and the
+ # query can only capture the first. Without the join, this method and
+ # any other method starting `initWithName:` collide on one symbol id.
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ names = {s.name for s in result.symbols}
+ assert "initWithName:age:" in names
+ assert "widgetWithName:" in names
+ # A method taking no arguments carries no colon at all.
+ assert "run" in names
+
+ def test_methods_belong_to_their_interface(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ owned = {(s.name, s.parent_name) for s in result.symbols}
+ assert ("initWithName:age:", "Widget") in owned
+ assert ("run", "Widget") in owned
+ assert ("didFinish:", "Feeder") in owned
+
+ def test_a_category_is_a_symbol_of_its_own(self, parser: ASTParser) -> None:
+ # Two categories on one class are two declarations, so naming both for
+ # the class alone would merge them and hide the second.
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ names = {s.name for s in result.symbols}
+ assert "Widget(Trimming)" in names
+ assert ("trim", "Widget(Trimming)") in {(s.name, s.parent_name) for s in result.symbols}
+
+ def test_a_class_extension_does_not_duplicate_the_implementation(
+ self, parser: ASTParser
+ ) -> None:
+ # A .m opens with `@interface Widget ()` declaring the private methods
+ # its `@implementation Widget` then defines. Both build the same symbol
+ # id, so the declaration must fold into the definition.
+ result = parser.parse_file(_objc("Widget.m"), IMPLEMENTATION)
+ widgets = [s for s in result.symbols if s.name == "Widget"]
+ assert len(widgets) == 1
+ assert widgets[0].is_declaration is False
+ # The survivor is the definition, which is what carries the body.
+ secrets = [s for s in result.symbols if s.name == "secret"]
+ assert len(secrets) == 1
+ assert secrets[0].is_declaration is False
+
+ def test_a_header_and_a_source_are_two_files_and_two_symbols(
+ self, parser: ASTParser
+ ) -> None:
+ # The C/C++ precedent: a declaration and its definition live in two
+ # files and stay two symbols, told apart by is_declaration rather than
+ # merged by a cross-file pass.
+ header = parser.parse_file(_objc("Widget.h"), HEADER)
+ impl = parser.parse_file(_objc("Widget.m"), IMPLEMENTATION)
+ declared = next(s for s in header.symbols if s.name == "Widget")
+ defined = next(s for s in impl.symbols if s.name == "Widget")
+ assert declared.is_declaration is True
+ assert defined.is_declaration is False
+ assert declared.id != defined.id
+
+ def test_plain_c_in_a_dot_m_file_is_a_symbol(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.m"), IMPLEMENTATION)
+ assert ("normalise", "function") in {(s.name, s.kind) for s in result.symbols}
+
+ def test_non_ascii_round_trips(self, parser: ASTParser) -> None:
+ src = "@implementation Café\n- (void)prêt {}\n@end\n".encode()
+ result = parser.parse_file(_objc(), src)
+ names = {s.name for s in result.symbols}
+ assert "Café" in names
+ assert "prêt" in names
+
+
+class TestObjectiveCImports:
+ def test_both_import_forms_and_include(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ modules = {i.module_path for i in result.imports}
+ assert "<Foundation/Foundation.h>" in modules
+ assert "Helper.h" in modules
+ assert "<stdio.h>" in modules
+
+ def test_a_forward_declaration_is_never_an_import(self, parser: ASTParser) -> None:
+ # `@class Sidecar;` names a class, not a file. It has no path to
+ # resolve, so treating it as an import would mint a broken edge.
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ assert "Sidecar" not in {i.module_path for i in result.imports}
+
+
+class TestObjectiveCTypeReferences:
+ def test_a_forward_declared_class_is_a_type_reference(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ names = {t.type_name for t in result.type_refs}
+ assert "Sidecar" in names
+ assert "Feeder" in names
+
+ def test_a_forward_declaration_is_never_a_call(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ assert "Sidecar" not in {c.target_name for c in result.calls}
+
+ def test_foundation_types_are_filtered(self, parser: ASTParser) -> None:
+ # NSString has no in-repo declaration, so resolving it is a
+ # guaranteed miss.
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ assert "NSString" not in {t.type_name for t in result.type_refs}
+
+
+class TestObjectiveCCalls:
+ def test_a_message_send_carries_its_whole_selector(self, parser: ASTParser) -> None:
+ # `[[Sidecar alloc] initWithName:name age:0]` binds one `method:`
+ # child per keyword, so the query matches twice. Only the joined
+ # selector is a real target, and it has to match the symbol side.
+ result = parser.parse_file(_objc("Widget.m"), IMPLEMENTATION)
+ targets = [c.target_name for c in result.calls]
+ assert "initWithName:age:" in targets
+ assert "age" not in targets
+
+ def test_a_nested_send_is_two_call_sites(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.m"), IMPLEMENTATION)
+ by_target = {c.target_name: c for c in result.calls}
+ assert by_target["alloc"].receiver_name == "Sidecar"
+ assert by_target["initWithName:age:"].receiver_name == "[Sidecar alloc]"
+
+ def test_self_and_super_keep_their_text(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.m"), IMPLEMENTATION)
+ receivers = {(c.target_name, c.receiver_name) for c in result.calls}
+ assert ("init", "super") in receivers
+ assert ("secret", "self") in receivers
+
+ def test_a_plain_c_call_is_captured(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.m"), IMPLEMENTATION)
+ assert "normalise" in {c.target_name for c in result.calls}
+
+ def test_a_runtime_function_mints_no_edge(self, parser: ASTParser) -> None:
+ # NSLog is a Foundation function and can never resolve in-repo.
+ result = parser.parse_file(_objc("Widget.m"), IMPLEMENTATION)
+ assert "NSLog" not in {c.target_name for c in result.calls}
+
+ def test_calls_are_attributed_to_the_enclosing_method(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.m"), IMPLEMENTATION)
+ call = next(c for c in result.calls if c.target_name == "normalise")
+ assert call.caller_symbol_id == "Widget.m::Widget::initWithName:age:"
+
+
+class TestObjectiveCHeritage:
+ def test_superclass_and_protocols(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ pairs = {(h.parent_name, h.kind) for h in result.heritage if h.child_name == "Widget"}
+ assert ("Panel", "extends") in pairs
+ assert ("Feeder", "implements") in pairs
+ assert ("NSCopying", "implements") in pairs
+
+ def test_a_universal_base_is_skipped(self, parser: ASTParser) -> None:
+ # NSObject has no in-repo declaration, so the edge would resolve to
+ # nothing -- the same filter Python applies to `object`.
+ src = b"@interface Thing : NSObject\n@end\n"
+ result = parser.parse_file(_objc("Thing.h"), src)
+ assert [h for h in result.heritage if h.parent_name == "NSObject"] == []
+
+ def test_a_category_emits_no_heritage(self, parser: ASTParser) -> None:
+ # A category has no superclass in this position; the class it extends
+ # is already in its own name.
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ assert [h for h in result.heritage if h.child_name.startswith("Widget(")] == []
+
+
+class TestObjectiveCDocstrings:
+ def test_a_doxygen_block_before_an_interface(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ widget = next(s for s in result.symbols if s.name == "Widget")
+ assert "widget everything hangs off" in (widget.docstring or "")
+
+ def test_line_doc_comments_before_a_method(self, parser: ASTParser) -> None:
+ src = b"""\
+@interface Thing : Panel
+/// Resets the thing.
+- (void)reset;
+@end
+"""
+ result = parser.parse_file(_objc("Thing.h"), src)
+ reset = next(s for s in result.symbols if s.name == "reset")
+ assert "Resets the thing." in (reset.docstring or "")
+
+
+class TestObjectiveCSourceSanitiser:
+ def test_the_wrapped_interface_survives(self, parser: ASTParser) -> None:
+ # NS_ASSUME_NONNULL_BEGIN is not a preprocessor directive and this
+ # grammar has no rule for it, so unsanitised it reads as the start of
+ # a C declaration and swallows the whole interface into an ERROR node.
+ result = parser.parse_file(_objc("Widget.h"), HEADER)
+ assert result.parse_errors == []
+ assert "Widget" in {s.name for s in result.symbols}
+
+ def test_every_other_byte_keeps_its_offset(self) -> None:
+ src = b"NS_ASSUME_NONNULL_BEGIN\n@interface Thing : Panel\n@end\n"
+ out = prepare_objectivec_source(src)
+ assert len(out) == len(src)
+ assert out.count(b"\n") == src.count(b"\n")
+ assert out.startswith(b" \n")
+
+ def test_a_macro_that_opens_a_declaration_is_untouched(self) -> None:
+ # FOUNDATION_EXPORT leads a real extern declaration the grammar
+ # parses; blanking the line would delete the declaration with it.
+ src = b'FOUNDATION_EXPORT NSString *const kThingKey;\n'
+ assert prepare_objectivec_source(src) == src
+
+ def test_a_file_without_the_macro_is_returned_unchanged(self) -> None:
+ src = b"@interface Thing : Panel\n@end\n"
+ assert prepare_objectivec_source(src) is src
+
+
+BLOCK_INVOCATION = b"""\
+@interface Token : NSObject
+@property (nonatomic, copy) SDBlock completionBlock;
+@property (nonatomic, copy) SDBlock doneBlock;
+@end
+
+@implementation Cache
+- (void)existsForKey:(NSString *)key completion:(SDBlock)completionBlock {
+ SDBlock doneBlock = ^{};
+ completionBlock(YES);
+ doneBlock(nil);
+ normalise(1);
+}
+@end
+"""
+
+
+class TestObjectiveCBlockInvocation:
+ def test_a_block_parameter_call_is_not_an_edge(self, parser: ASTParser) -> None:
+ # `completionBlock(YES)` invokes the method's own block parameter. It
+ # is a call_expression on a bare identifier, indistinguishable from a
+ # C function call by name, so left in, the resolver bound it to
+ # whatever same-named @property the repo held.
+ result = parser.parse_file(_objc("Cache.m"), BLOCK_INVOCATION)
+ assert "completionBlock" not in {c.target_name for c in result.calls}
+
+ def test_a_block_local_call_is_not_an_edge(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Cache.m"), BLOCK_INVOCATION)
+ assert "doneBlock" not in {c.target_name for c in result.calls}
+
+ def test_a_real_c_call_in_the_same_body_survives(self, parser: ASTParser) -> None:
+ # The scope check must not swallow every bare-identifier call.
+ result = parser.parse_file(_objc("Cache.m"), BLOCK_INVOCATION)
+ assert "normalise" in {c.target_name for c in result.calls}
+
+ def test_the_property_itself_is_still_a_symbol(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_objc("Cache.m"), BLOCK_INVOCATION)
+ assert ("completionBlock", "Token") in {
+ (s.name, s.parent_name) for s in result.symbols
+ }
+
+
+class TestObjectiveCSelectorAttributes:
+ def test_a_trailing_macro_is_not_part_of_the_selector(self, parser: ASTParser) -> None:
+ # `initWithName:NS_DESIGNATED_INITIALIZER:` never pairs with the
+ # `initWithName:` the .m defines, so the header and the implementation
+ # of one method read as two unrelated symbols.
+ src = b"""\
+@interface Widget : NSObject
+- (instancetype)initWithName:(NSString *)name NS_DESIGNATED_INITIALIZER;
+- (void)sup:(int)a NS_REQUIRES_SUPER;
+- (void)swiftly:(int)a NS_SWIFT_NAME(sw(a:));
+- (void)avail:(int)a NS_AVAILABLE_IOS(10_0);
+- (void)attr:(int)a __attribute__((deprecated));
+@end
+"""
+ result = parser.parse_file(_objc("Widget.h"), src)
+ names = {s.name for s in result.symbols if s.kind == "method"}
+ assert names == {"initWithName:", "sup:", "swiftly:", "avail:", "attr:"}
+
+ def test_an_unnamed_keyword_part_adds_no_colon(self, parser: ASTParser) -> None:
+ # `- (void)baz:(int)a :(int)b` is the selector `baz::` to the compiler,
+ # but the grammar gives the second part no keyword identifier at all,
+ # so only the colons it can see are counted.
+ src = b"@interface Widget : NSObject\n- (void)baz:(int)a :(int)b;\n@end\n"
+ result = parser.parse_file(_objc("Widget.h"), src)
+ assert "baz:" in {s.name for s in result.symbols}
+
+ def test_a_header_selector_matches_its_implementation(self, parser: ASTParser) -> None:
+ header = parser.parse_file(
+ _objc("Widget.h"),
+ b"@interface Widget : NSObject\n"
+ b"- (instancetype)initWithName:(NSString *)n NS_DESIGNATED_INITIALIZER;\n@end\n",
+ )
+ impl = parser.parse_file(
+ _objc("Widget.m"),
+ b"@implementation Widget\n- (instancetype)initWithName:(NSString *)n { return self; }\n@end\n",
+ )
+ declared = next(s for s in header.symbols if s.kind == "method")
+ defined = next(s for s in impl.symbols if s.kind == "method")
+ assert declared.name == defined.name == "initWithName:"
+
+
+class TestObjectiveCMacroEnum:
+ def test_an_ns_enum_typedef_mints_no_symbol(self, parser: ASTParser) -> None:
+ # The grammar has no rule for the macro, so the type name and the brace
+ # body land in ERROR nodes and only the enum *cases* survive as
+ # declarators -- each becoming a symbol named as though it were the
+ # type. No symbol beats a wrong one.
+ src = b"""\
+typedef NS_ENUM(NSInteger, Kind) { KindA, KindB };
+typedef NS_OPTIONS(NSUInteger, Mask) { MaskNone = 0 };
+typedef int Plain;
+"""
+ result = parser.parse_file(_objc("Kind.h"), src)
+ names = {s.name for s in result.symbols}
+ assert "KindA" not in names
+ assert "MaskNone" not in names
+ # An ordinary typedef is untouched.
+ assert "Plain" in names
+
+
+class TestObjectiveCProtocolAndClassCollision:
+ def test_a_protocol_method_survives_a_same_named_class_method(
+ self, parser: ASTParser
+ ) -> None:
+ # A protocol and a class may share a name in one file, and `-ping` on
+ # the protocol is a different method from `-ping` on the class. Keyed
+ # on the name alone, the class definition deduped the protocol's
+ # declaration away.
+ src = b"""\
+@protocol Widget <NSObject>
+- (void)ping;
+@end
+
+@implementation Widget
+- (void)ping {}
+@end
+"""
+ result = parser.parse_file(_objc("Widget.m"), src)
+ pings = [s for s in result.symbols if s.name == "ping"]
+ assert len(pings) == 2
+ assert {p.is_declaration for p in pings} == {True, False}
+
+ def test_a_class_extension_still_dedupes(self, parser: ASTParser) -> None:
+ # The container kind in the key must not stop the case the dedup
+ # exists for: both of these are declared on a class.
+ src = b"""\
+@interface Widget ()
+- (void)secret;
+@end
+
+@implementation Widget
+- (void)secret {}
+@end
+"""
+ result = parser.parse_file(_objc("Widget.m"), src)
+ assert len([s for s in result.symbols if s.name == "secret"]) == 1
+
+
+class TestObjectiveCConditionalCompilation:
+ def test_a_method_inside_a_preproc_if_keeps_its_symbol_and_callers(
+ self, parser: ASTParser
+ ) -> None:
+ # Conditionally compiled methods are the norm in cross-platform
+ # Objective-C; a call inside one must not be attributed to the module.
+ src = b"""\
+@implementation Manager
+#if !TARGET_OS_WATCH
+- (instancetype)initWithConfiguration:(NSURLSessionConfiguration *)configuration {
+ self.reachability = [AFNetworkReachabilityManager sharedManager];
+ return self;
+}
+#endif
+@end
+"""
+ result = parser.parse_file(_objc("Manager.m"), src)
+ assert ("initWithConfiguration:", "Manager") in {
+ (s.name, s.parent_name) for s in result.symbols
+ }
+ call = next(c for c in result.calls if c.target_name == "sharedManager")
+ assert call.caller_symbol_id == "Manager.m::Manager::initWithConfiguration:"
diff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.py
index 998dafa3b..66d107429 100644
--- a/tests/unit/ingestion/test_language_capabilities.py
+++ b/tests/unit/ingestion/test_language_capabilities.py
@@ -101,7 +101,7 @@ class TestParityGoldens:
camel = REGISTRY.camel_test_res_by_extension()
assert set(camel) == {
".java", ".kt", ".kts", ".scala", ".cs", ".swift", ".php",
- ".hs", ".lhs", ".vb",
+ ".hs", ".lhs", ".vb", ".m", ".mm",
}
assert camel[".java"].pattern == r"(?<=[a-z0-9])(?:Tests|Test|IT)$"
assert camel[".scala"].pattern == r"(?<=[a-z0-9])(?:Suite|Spec|Test)$"
diff --git a/tests/unit/ingestion/test_self_call_resolution.py b/tests/unit/ingestion/test_self_call_resolution.py
index 18dddd936..7e62891b8 100644
--- a/tests/unit/ingestion/test_self_call_resolution.py
+++ b/tests/unit/ingestion/test_self_call_resolution.py
@@ -277,3 +277,32 @@ class TestStrategy4Shadowing:
edges = _edges(parsed, tmp_path)
bad = [e for e in edges if e[0].endswith("::use_missing")]
assert bad == [], f"unknown method must stay unresolved: {bad}"
+
+
+OBJC_INHERITED_SELECTOR = '''
+@implementation ImageRep
+- (void)load {
+ [self setProperty:NSImageLoopCount withValue:@(2)];
+ [self decode];
+}
+- (void)decode {}
+@end
+'''
+
+
+def test_objc_self_send_of_an_inherited_selector_resolves_to_nothing(tmp_path: Path):
+ """A framework method called on ``self`` has no in-repo target.
+
+ ``-setProperty:withValue:`` belongs to the AppKit superclass, so the repo
+ holds no declaration of it anywhere. The self-receiver tier is a lookup in
+ the ``(class, selector)`` index rather than an id built from the two
+ halves, so it declines; a synthesized id here would mint a confident edge
+ to a symbol that does not exist. The sibling call in the same body pins
+ that the tier still answers when the method is real.
+ """
+ pytest.importorskip("tree_sitter_objc")
+ parsed = _parse_all(tmp_path, {"ImageRep.m": ("objectivec", OBJC_INHERITED_SELECTOR)})
+ edges = _edges(parsed, tmp_path)
+ callees = {callee for _caller, callee, _conf in edges}
+ assert not any("setProperty" in c for c in callees)
+ assert "ImageRep.m::ImageRep::decode" in callees
diff --git a/tests/unit/ingestion/test_traverser.py b/tests/unit/ingestion/test_traverser.py
index f0474bf86..be559b739 100644
--- a/tests/unit/ingestion/test_traverser.py
+++ b/tests/unit/ingestion/test_traverser.py
@@ -93,6 +93,39 @@ class TestLanguageDetection:
def test_cpp_extension(self, tmp_path: Path) -> None:
assert _detect_language(tmp_path / "calc.cpp") == "cpp"
+ def test_objectivec_header_is_routed_by_content(self, tmp_path: Path) -> None:
+ # One extension maps to one language repo-wide and ``.h`` belongs to
+ # C++, so an Objective-C header can only be told apart by what is in
+ # it: an @interface / @implementation / @protocol opening a line
+ # outside a comment is not valid C or C++.
+ f = tmp_path / "Widget.h"
+ f.write_text('#import <Foundation/Foundation.h>\n@interface Widget\n@end\n')
+ assert _detect_language(f) == "objectivec"
+
+ def test_a_protocol_declaration_is_enough(self, tmp_path: Path) -> None:
+ f = tmp_path / "Feeder.h"
+ f.write_text('@protocol Feeder <NSObject>\n- (void)feed;\n@end\n')
+ assert _detect_language(f) == "objectivec"
+
+ def test_a_doxygen_comment_does_not_route_a_cpp_header(self, tmp_path: Path) -> None:
+ # ``@interface`` and ``@class`` are also Doxygen commands, so an
+ # anywhere-in-the-file token match sent documented C++ headers to the
+ # Objective-C grammar.
+ f = tmp_path / "widget.h"
+ f.write_text(
+ '/**\n * @interface Widget\n * @class Widget\n */\n'
+ '// #import "legacy.h"\nclass Widget { int add(int a); };\n'
+ )
+ assert _detect_language(f) == "cpp"
+
+ def test_a_plain_c_header_stays_cpp(self, tmp_path: Path) -> None:
+ f = tmp_path / "calc.h"
+ f.write_text('#include <stdio.h>\nint add(int a, int b);\n')
+ assert _detect_language(f) == "cpp"
+
+ def test_a_dot_m_needs_no_sniff(self, tmp_path: Path) -> None:
+ assert _detect_language(tmp_path / "Widget.m") == "objectivec"
+
def test_special_dockerfile(self, tmp_path: Path) -> None:
assert _detect_language(tmp_path / "Dockerfile") == "dockerfile"
diff --git a/tests/unit/ingestion/test_unparseable_language_sets.py b/tests/unit/ingestion/test_unparseable_language_sets.py
index 592205e32..99e7b16b2 100644
--- a/tests/unit/ingestion/test_unparseable_language_sets.py
+++ b/tests/unit/ingestion/test_unparseable_language_sets.py
@@ -70,8 +70,9 @@ def test_passthrough_code_languages_are_not_in_the_set():
clojure/haskell are ``is_passthrough`` but real code: zero symbols
there is a gap in us, not a property of the file, so they must stay
- eligible for the analyses this set exempts. Elixir used to sit here and
- now parses to an AST, which is where a language in this state is headed.
+ eligible for the analyses this set exempts. Elixir and Objective-C used to
+ sit here and now parse to an AST, which is where a language in this state
+ is headed.
"""
for tag in ("clojure", "haskell"):
assert tag in REGISTRY.passthrough_languages(), tag
diff --git a/uv.lock b/uv.lock
index aad1932c4..51e707ddc 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3093,6 +3093,7 @@ dependencies = [
{ name = "tree-sitter-javascript" },
{ name = "tree-sitter-kotlin" },
{ name = "tree-sitter-luau" },
+ { name = "tree-sitter-objc" },
{ name = "tree-sitter-pascal" },
{ name = "tree-sitter-php" },
{ name = "tree-sitter-python" },
@@ -3192,6 +3193,7 @@ requires-dist = [
{ name = "tree-sitter-javascript", specifier = ">=0.23,<1" },
{ name = "tree-sitter-kotlin", specifier = ">=1,<2" },
{ name = "tree-sitter-luau", specifier = ">=1.2,<2" },
+ { name = "tree-sitter-objc", specifier = ">=3.0.2,<4" },
{ name = "tree-sitter-pascal", specifier = ">=0.11,<1" },
{ name = "tree-sitter-php", specifier = ">=0.23,<1" },
{ name = "tree-sitter-python", specifier = ">=0.23,<1" },
@@ -4176,6 +4178,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/1a/df/db574405f592f1f4f039dc83db8545d634b68481ce0c457bbab26e155a4a/tree_sitter_luau-1.2.0-cp39-abi3-win_arm64.whl", hash = "sha256:37e9a2e2dd9795800c98c160eabcfed9a90a25a80e2f207658902b0444a40440", size = 31300, upload-time = "2024-12-22T22:42:45.64Z" },
]
+[[package]]
+name = "tree-sitter-objc"
+version = "3.0.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/f2/f979251e2100753160fcee515bc36ee60997c2e79d166232c93bc6519e02/tree_sitter_objc-3.0.2.tar.gz", hash = "sha256:ac55aefe8a4f3ea6f1da2a2e05372a4f37100001934e36a81e0f96c4c6252809", size = 1507881, upload-time = "2024-12-16T00:37:40.427Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f4/c9/39436200acd5db5c229845857eda011a102fd01d0fdb5fee82961842d558/tree_sitter_objc-3.0.2-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:bd25b3c4ca99263c0898aa7a362a1b8d9bb642692ae9ddd357755586019b1544", size = 303010, upload-time = "2024-12-16T00:37:17.847Z" },
+ { url = "https://files.pythonhosted.org/packages/32/11/051f22252ee02ac3d0ca00ebcd99476da586b5d916390dc2f251e610ca7c/tree_sitter_objc-3.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:9fa8b1221d2651a51cf42e1551c0804e9f48707da70f41f3195910c599b5522b", size = 343653, upload-time = "2024-12-16T00:37:24.994Z" },
+ { url = "https://files.pythonhosted.org/packages/bd/d8/fa3808fad119b0d4ba47453ad69c7520649ddc7d0716c087443c1aa4a03c/tree_sitter_objc-3.0.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:30b6f9cd49593bac50161a6de6e1b8d591b318d64b33b8bde5385faa05461084", size = 350656, upload-time = "2024-12-16T00:37:27.616Z" },
+ { url = "https://files.pythonhosted.org/packages/60/cd/a153a4268b9b405a69ee3e427f19fc570a3c63d4b4d7766bee5a7ba28744/tree_sitter_objc-3.0.2-cp39-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e71282ac9c096a966bf2fa6a4ecdbea4bd037d3e01ea4aa9bbc64d9a4c0022f6", size = 328889, upload-time = "2024-12-16T00:37:28.882Z" },
+ { url = "https://files.pythonhosted.org/packages/8c/16/46acba3a303776b719064970ad40de6a4a8a71a17bf84d188fec05886689/tree_sitter_objc-3.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d288d5ad4951fa31eeaf39972b39b41694eec8cc70739d48e745357c2e2c4aad", size = 321812, upload-time = "2024-12-16T00:37:31.506Z" },
+ { url = "https://files.pythonhosted.org/packages/93/0a/1653cd34758bd5436980ad8e68e2893f323a487afef4a6504bbfc654b1cc/tree_sitter_objc-3.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:f3c93e991a86e96b8996cc735a4b31b38c65820913bf5a96904d07a51a8d9423", size = 305006, upload-time = "2024-12-16T00:37:34.11Z" },
+ { url = "https://files.pythonhosted.org/packages/bb/ec/34de4da134f48373d2986137e785da86f4df2b70f688307856588a473cff/tree_sitter_objc-3.0.2-cp39-abi3-win_arm64.whl", hash = "sha256:9a99d9b81a4e507bd33329be136928b3ebe424ce8b9d6b8a8339083ceb453b5b", size = 301378, upload-time = "2024-12-16T00:37:36.424Z" },
+]
+
[[package]]
name = "tree-sitter-pascal"
version = "0.11.0"