Skip to content

feat(parsers): add Metal (.metal) language support via the cpp grammar - #351

Merged
ofriw merged 2 commits into
chunkhound:mainfrom
GoodOlClint:feat/metal-language-support
Jun 27, 2026
Merged

ofriw merged 2 commits into
chunkhound:mainfrom
GoodOlClint:feat/metal-language-support

Conversation

@GoodOlClint

@GoodOlClint GoodOlClint commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Why

Metal Shading Language is a C++14 dialect. MLX's GPU backend is a
Python↔C++↔Metal seam where the .metal kernels carry the real compute
(reduce, arg_reduce, gemm, …). Today ChunkHound routes .metal to
Language.UNKNOWN, so those kernels chunk through the generic text fallback —
no struct/function-typed symbols, so semantic and --regex symbol search can't
find a kernel by its struct or reducer name. Metal/MSL users (and anyone
indexing an MLX tree) get struct/function-aware chunks instead.

Approach (cheap path)

MSL is C++14, so the existing tree-sitter-cpp grammar already parses the real
structure. Keep a distinct Language.METAL identity (so a dedicated
tree-sitter-metal grammar can be swapped in later by changing one line) while
reusing all of CppMapping's node handling through a thin subclass:

class MetalMapping(CppMapping):
    def __init__(self) -> None:
        super().__init__()
        self.language = Language.METAL   # CppMapping hardcodes CPP; re-tag

LanguageConfig is registered with language_name="metal". The cpp grammar
comes from the ts_cpp module object, not that string — the string only
drives the public language identity (ParseResult.language / Chunk.language)
and diagnostic labels. This mirrors the existing JSX→tsx-grammar precedent
(language_name="jsx" over the tsx grammar). Result: .metal stays
Language.METAL end-to-end — detection, parse result, emitted chunks, and
persisted chunk language all agree.

Touchpoints (4 + test)

  • chunkhound/core/types/common.py — Language.METAL; .metal → METAL in
    the extension map; METAL added to is_programming_language and
    supports_classes.
  • chunkhound/parsers/mappings/metal.py — new, MetalMapping(CppMapping).
  • chunkhound/parsers/mappings/__init__.py — export MetalMapping.
  • chunkhound/parsers/parser_factory.py — MetalMapping import,
    LANGUAGE_CONFIGS[Language.METAL] = LanguageConfig(ts_cpp, MetalMapping, True, "metal"),
    and ".metal": Language.METAL in EXTENSION_TO_LANGUAGE.
  • tests/test_metal_mapping.py — new contract test through the real parser.

Evidence — before → after

1. Routing flips

Before (origin/main):

detect_language(x.metal) = Language.UNKNOWN
METAL in Language enum: False

After (branch):

detect_language(x.metal) = Language.METAL

2. Typed chunks the UNKNOWN fallback can't emit

Parsing the real mlx/backend/metal/kernels/arg_reduce.metal (182 lines) via
create_parser(Language.METAL).parse_content(...):

n chunks: 28
types: {'function': 11, 'comment': 10, 'namespace': 4, 'class': 2, 'import': 1}
struct/class symbols: ['IndexValPair<U>', 'ArgMax<U>']
function symbols: ['reduce_many', 'simd_shuffle_down<U>', 'arg_reduce_general...', ...]

tests/test_metal_mapping.py pins this contract against a real MLX snippet —
asserts a ChunkType.CLASS for IndexValPair by name and a
ChunkType.FUNCTION for reduce_many by name. Both are typed symbols the
UNKNOWN text fallback cannot produce. The test references Language.METAL,
which does not exist on main, so it fails there and passes on the branch.

3. Language identity stays METAL end-to-end

The first revision routed .metal to METAL but emitted chunks tagged cpp
(the config's language_name fed both grammar selection and identity). That
split is now fixed — tests/test_metal_mapping.py pins the invariant:

tests/test_metal_mapping.py::test_metal_extension_routes_to_metal        PASSED
tests/test_metal_mapping.py::test_metal_captures_struct_as_class_chunk   PASSED
tests/test_metal_mapping.py::test_metal_captures_method_as_function_chunk PASSED
tests/test_metal_mapping.py::test_metal_chunks_stay_tagged_metal         PASSED
tests/test_metal_mapping.py::test_metal_parse_result_tagged_metal        PASSED
5 passed
  • test_metal_chunks_stay_tagged_metal — every emitted chunk is Language.METAL
  • test_metal_parse_result_tagged_metal — ParseResult.language == Language.METAL

4. CLI e2e

$ chunkhound index ./e2e --no-embeddings
Processed: 1 files / Errors: 0 / Total chunks: 28

$ chunkhound search --regex "IndexValPair" ./e2e
<returns the IndexValPair chunk from arg_reduce.metal>

5. No regression

uv run pytest tests/test_smoke.py -v -n auto  →  18 passed
uv run pytest tests/test_parsers.py            →  passed (Metal in coverage)

Lint: changed/new files clean (ruff check, no ruff format per version-skew
policy). The I001 import-sort warning ruff reports on common.py/
parser_factory.py pre-exists on origin/main and is not touched by this
change.

Cheap-path scope (expected)

  • ERROR nodes around Metal-only qualifiers are expected. thread/
    threadgroup address spaces and [[kernel]] attributes aren't C++; the cpp
    grammar emits ~16 localized ERROR nodes on a real kernel and cAST chunks
    around them. These tests assert functions/structs are captured, not zero
    errors.
  • Chunks are tagged Language.METAL. Identity is derived from the routed
    language, not the grammar object, so detection / ParseResult.language /
    Chunk.language / persisted chunks.language all read metal.
  • Dedicated tree-sitter-metal grammar deferred. Swapping it in later is a
    one-line change to the LanguageConfig for Language.METAL.

🤖 Generated with Claude Code

Metal Shading Language is C++14, so MLX-style Python/C++/Metal kernels parse
cleanly with the existing tree-sitter-cpp grammar. Add a Language.METAL
identity backed by a thin MetalMapping(CppMapping) so .metal files get
struct/function-aware chunks instead of the generic UNKNOWN fallback that
emits no typed symbols. A dedicated tree-sitter-metal grammar can follow
later; ERROR nodes around Metal-only qualifiers (thread/threadgroup,
[[kernel]]) are expected and cAST chunks around them.

Includes the required per-language coverage entries (LARGE_LANGUAGE_SAMPLES,
parser minimal-code, QA content + extension maps) so the "every Language must
be covered" guards pass; Metal samples mirror C++.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@ofriw ofriw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


Nice direction overall—the cheap-path reuse of the C++ grammar is reasonable. The blocking issue is that Language.METAL currently only exists at file-detection time, not end-to-end through parser output. In chunkhound/parsers/parser_factory.py, Metal is registered with language_name="cpp", and chunkhound/parsers/universal_parser.py derives both ParseResult.language and emitted Chunk.language from that config string. So a .metal file is detected and stored as metal, but its parsed chunks are emitted and persisted as cpp.

That split identity is the main thing to fix before merge. It leaks into storage and APIs (chunk_language vs file_language), and it also means the current tests miss the most important invariant: they verify routing and symbol extraction, but not that Metal stays Metal after parsing. I’d tighten this by making chunk/result language tagging consistent with the routed language, then adding contract coverage that asserts chunk.language == Language.METAL and ParseResult.language == Language.METAL for .metal inputs.


Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

Reviewer (PR chunkhound#351) flagged a split identity: .metal files were detected
as METAL but parsed chunks/results were emitted and persisted as cpp,
because the LanguageConfig used language_name="cpp".

The grammar comes from the ts_cpp module object, not that string — the
string only drives identity (ParseResult.language / Chunk.language) plus
diagnostic labels. Dedup only special-cases vue/haskell, and queries
come from MetalMapping, so nothing parse-relevant keys on "cpp". Tag it
"metal" (mirrors the existing JSX→tsx-grammar precedent); identity now
flows METAL through detection → ParseResult → Chunk with no changes to
universal_parser.

Add contract tests for the two missing invariants: chunk.language and
ParseResult.language are METAL for .metal input.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@GoodOlClint

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review — you were right, the identity was only half wired up.

Fixed in d7cec40. Root cause was exactly as you described: the LanguageConfig registered Metal with language_name="cpp", and universal_parser derives both ParseResult.language and Chunk.language from that string, so chunks were emitted (and persisted) as cpp.

The fix is a one-word change — language_name "cpp" → "metal". The cpp grammar comes from the ts_cpp module object, not the string, so parsing is unchanged; the string only fed the public identity tags and diagnostic labels. I confirmed nothing parse-relevant keys on "cpp": dedup only special-cases vue/haskell, and the tree-sitter queries come from MetalMapping. This mirrors the existing JSX→tsx-grammar precedent (language_name="jsx" over the tsx grammar). No changes to universal_parser were needed — identity now flows METAL through detection → ParseResult → Chunk → persisted chunks.language.

Added the two contract tests for the invariant the first revision missed:

  • test_metal_chunks_stay_tagged_metal — every emitted chunk is Language.METAL
  • test_metal_parse_result_tagged_metal — ParseResult.language == Language.METAL

Both fail against the old "cpp" config and pass now. Full run: tests/test_metal_mapping.py 5 passed; test_parsers + smoke 106 passed.

@ofriw ofriw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@ofriw
ofriw added this pull request to the merge queue Jun 27, 2026
Merged via the queue into chunkhound:main with commit db17924 Jun 27, 2026
17 checks passed
@GoodOlClint
GoodOlClint deleted the feat/metal-language-support branch July 3, 2026 17:31
ofriw added a commit that referenced this pull request Jul 6, 2026
…CP read-only, and fixes

Merge main into matryoshka-fix-6-26.

main changes incorporated:
- DuckDB compaction with atomic swap (#339)
- PowerShell (#350) and Metal (#351) language parsers
- MCP --read-only flag (#329)
- Research per-step timing (#355)
- Various fixes: websearch late-completion guard, quickresearch
  orphan cleanup, token literal counting, claude-cli auto-updater
- openai_compatible in factory's supported_providers()

Conflict resolution: chunkhound/services/realtime_indexing_service.py
was deleted on main (dead code, no production callers). The branch's
ModuleType __class__ hack + its test were removed to match.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants