Repository navigation
feat(syntax): support tree-sitter language injections - #192
Conversation
Resolve `@injection.content` / `@injection.language` captures, re-parse
those ranges with the target language, and merge the resulting spans
into the outer highlight output. Enables proper highlighting of:
- Astro frontmatter, `<script>`, `<style>`, and `{expr}` interpolations
- Svelte `<script lang="ts">` and `<style>`
- HTML `<script>` / `<style>` bodies
- Markdown fenced code blocks (per-language)
- PHP embedded HTML
Introduce `LanguageSupport` plus `get_language_by_name` so injection
target names (e.g. "typescript", "css", "rust") resolve through a
single canonical table with common aliases. Recursion is capped at
depth 4; unsupported injected languages silently fall back to plain
text.
Closes #191
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughAdds Tree-sitter injection-query support to syntax highlighting: language modules expose Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Highlighter
participant Parser
participant HighlightQuery
participant InjectionQuery
participant SpanMerger
Client->>Highlighter: set_language_from_path(path)
Highlighter->>Parser: set_language(Language)
Highlighter->>HighlightQuery: compile(highlight_query)
Highlighter->>InjectionQuery: compile(injection_query?)
Client->>Highlighter: highlight(source)
Highlighter->>Parser: parse(source)
Parser-->>Highlighter: tree
Highlighter->>HighlightQuery: collect_spans(tree)
HighlightQuery-->>Highlighter: outer_spans
Highlighter->>InjectionQuery: find_injected_regions(tree)
loop for each injected region (bounded depth)
InjectionQuery->>Parser: parse(injected_region, injected_lang)
Parser-->>InjectionQuery: injected_tree
InjectionQuery->>HighlightQuery: collect_spans(injected_tree)
HighlightQuery-->>InjectionQuery: injected_spans
InjectionQuery-->>Highlighter: injected_spans
end
Highlighter->>SpanMerger: merge_and_filter(outer_spans, injected_spans)
SpanMerger-->>Highlighter: merged_spans
Highlighter-->>Client: merged_spans
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (5)
src/syntax/languages/markdown.rs (1)
5-9: Minor: the "Custom highlight query…" comment no longer precedes the item it documents.Lines 5–6 describe the custom
HIGHLIGHT_QUERY, but insertingINJECTION_QUERYbetween them andHIGHLIGHT_QUERYleaves the comment detached. Move theINJECTION_QUERYdeclaration belowHIGHLIGHT_QUERY, or relocate the comment, so the doc stays adjacent to the highlight query it describes.Proposed fix
-// Custom highlight query for better visibility -// Based on tree_sitter_md::HIGHLIGHT_QUERY_BLOCK with improved colors -pub const INJECTION_QUERY: &str = tree_sitter_md::INJECTION_QUERY_BLOCK; - -pub const HIGHLIGHT_QUERY: &str = r#" +pub const INJECTION_QUERY: &str = tree_sitter_md::INJECTION_QUERY_BLOCK; + +// Custom highlight query for better visibility +// Based on tree_sitter_md::HIGHLIGHT_QUERY_BLOCK with improved colors +pub const HIGHLIGHT_QUERY: &str = r#"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/syntax/languages/markdown.rs` around lines 5 - 9, The comment "Custom highlight query for better visibility..." is now separated from the symbol it documents; move the declaration of INJECTION_QUERY so the comment directly precedes HIGHLIGHT_QUERY (or relocate the comment) to keep documentation adjacent to HIGHLIGHT_QUERY; specifically, ensure HIGHLIGHT_QUERY remains immediately after the comment and place INJECTION_QUERY (tree_sitter_md::INJECTION_QUERY_BLOCK) below HIGHLIGHT_QUERY to restore correct proximity between the comment and the HIGHLIGHT_QUERY constant.src/syntax/mod.rs (2)
287-304: Minor: quote stripping may not cover all info-string shapes.
resolve_injection_languagestrips",', and`from the capture text. That covers the common cases, but Markdown fenced code blocks sometimes carry info strings likets {highlight=...}orrust,no_run— only the first token is the language. After trimming quotes you might still end up with"ts {…}"as the "language name", which then fails theget_language_by_namelookup silently.Consider splitting on whitespace /
,/{and taking the first token before lowercasing:- let cleaned = text.trim_matches(|ch: char| ch == '"' || ch == '\'' || ch == '`'); - (!cleaned.is_empty()).then(|| cleaned.to_ascii_lowercase()) + let cleaned = text + .trim_matches(|ch: char| ch == '"' || ch == '\'' || ch == '`') + .split(|ch: char| ch.is_whitespace() || ch == ',' || ch == '{') + .next() + .unwrap_or(""); + (!cleaned.is_empty()).then(|| cleaned.to_ascii_lowercase())Low priority since the current code still works for plain
” ```rust ”fences.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/syntax/mod.rs` around lines 287 - 304, resolve_injection_language currently only strips quote characters and may return an info-string like "ts {highlight=...}" which breaks language lookup; update the post-cleaning step in resolve_injection_language (referencing the function name and the m.captures handling) to split the cleaned string on whitespace, comma, and '{' and take the first token, trim it, ensure it's non-empty, then return that token lowercased (instead of the entire cleaned string) so only the language name is returned for get_language_by_name.
306-338: Consider caching compiled queries per injected language.
highlight_sliceconstructs a freshParserand callsQuery::newfor bothHIGHLIGHT_QUERYand (conditionally)INJECTION_QUERYon every injection match. For typical inputs this can multiply quickly — e.g., a Markdown document with many fencedrust /js blocks will recompile the Rust and JS highlight queries once per block. Tree-sitter query compilation is not free (it parses the S-expression query and builds automata).For a single
Highlighter::highlightcall, a small per-call cache keyed by language name (or byLanguagepointer/id) holding the compiledQuery(and optionally aParser) would avoid the repeated work without changing any observable behavior. Threading that cache throughgather_injections/highlight_sliceis mechanical.Not a blocker for this PR, but worth filing as a follow-up if there's any intent to highlight larger Markdown/HTML blobs in hot paths.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/syntax/mod.rs` around lines 306 - 338, highlight_slice currently constructs a new Parser and calls Query::new for support.highlight_query and for each injection via gather_injections on every invocation, causing redundant Tree-sitter query compilation for repeated injected languages; introduce a per-highlight-call cache (e.g., a HashMap keyed by language name or Language pointer) and thread it into highlight_slice and gather_injections so you reuse compiled Query instances (and optionally Parsers) instead of calling Query::new/Parser::new repeatedly for the same language, updating references to support.highlight_query, support.injection_query, highlight_slice, and gather_injections to look up or insert into the cache before creating new Query/Parser.src/syntax/languages/mod.rs (1)
51-206: Optional: the 30×LanguageSupport { … }arms are begging for a small macro or table.Every arm is structurally identical: canonical name →
(language(), HIGHLIGHT_QUERY, Option<INJECTION_QUERY>). Amacro_rules!or a&[(name, fn() -> LanguageSupport)]table would cut ~150 lines of boilerplate and make it much harder to drift (e.g., forgetting to setinjection_query: Noneon a new language, or swapping a module name). Non-blocking; the current form is perfectly readable.Sketch
macro_rules! lang { ($m:ident, $inj:expr) => { Some(LanguageSupport { language: $m::language(), highlight_query: $m::HIGHLIGHT_QUERY, injection_query: $inj, }) }; } match canonical { "astro" => lang!(astro, Some(astro::INJECTION_QUERY)), "bash" => lang!(bash, None), "html" => lang!(html, Some(html::INJECTION_QUERY)), "markdown" => lang!(markdown, Some(markdown::INJECTION_QUERY)), "php" => lang!(php, Some(php::INJECTION_QUERY)), "svelte" => lang!(svelte, Some(svelte::INJECTION_QUERY)), // … _ => None, }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/syntax/languages/mod.rs` around lines 51 - 206, The match arms in by_name return many identical LanguageSupport structs causing boilerplate and potential drift; introduce a small helper (e.g., a macro like lang! or a table mapping canonical names to module identifiers and optional injection flags) and refactor by_name to call that helper instead of repeating the struct literal for each language; keep the same semantics: call each module's language() for language, use MODULE::HIGHLIGHT_QUERY for highlight_query and pass Some(MODULE::INJECTION_QUERY) or None for injection_query so the public API (by_name and LanguageSupport) remains unchanged (refer to by_name, LanguageSupport, and each module constant like html::INJECTION_QUERY).examples/test_highlighter.rs (1)
57-98: Optional: extract a helper to reduce the 4× copy-paste in this example.The Astro and HTML cases are structurally identical to the Rust/Markdown ones (set language, print success, highlight, print N spans). A small helper would make it trivial to add more languages later (e.g., Svelte/PHP) without duplicating the loop.
Proposed helper
fn run_case(label: &str, path: &str, code: &str, take: usize) { println!("\n=== Testing {label} highlighting ==="); let mut h = gitlogue::syntax::Highlighter::new(); println!("Language set: {}", h.set_language_from_path(path)); let spans = h.highlight(code); println!("Number of highlights: {}", spans.len()); for (i, s) in spans.iter().enumerate().take(take) { println!("{}: [{}-{}] {:?} = '{}'", i, s.start, s.end, s.token_type, &code[s.start..s.end]); } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/test_highlighter.rs` around lines 57 - 98, Extract a small helper function (e.g., fn run_case(label: &str, path: &str, code: &str, take: usize)) and replace the duplicated Astro and HTML test blocks with calls to that helper; the helper should create a gitlogue::syntax::Highlighter, call set_language_from_path(path) and print its bool result, call highlight(code), print the number of spans, and iterate the first `take` spans printing the same "{}: [{}-{}] {:?} = '{}'" output using span.start/span.end/span.token_type and &code[span.start..span.end]; update the Astro and HTML blocks to call run_case("Astro","test.astro", astro_code, 25) and run_case("HTML","test.html", html_code, 25) to remove the copy-paste.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/syntax/languages/mod.rs`:
- Line 217: The match arm that maps file extensions to a tree-sitter language
currently groups "sass" with CSS: the tuple "css" | "scss" | "sass" | "postcss"
| "less" => Some("css") should be changed so that "sass" is not mapped to "css"
(remove "sass" from that pattern) so indented-syntax Sass falls through to plain
text; alternatively, if a dedicated Sass grammar is available, map "sass" to its
proper language name instead of "css".
In `@src/syntax/mod.rs`:
- Around line 340-357: The function merge_injection_spans currently drops any
outer HighlightSpan that even partially overlaps an injection Range, causing
delimiter highlights to vanish; update merge_injection_spans to clip outer spans
to the non-overlapping portions instead of discarding them: for each outer span
in the incoming outer Vec<HighlightSpan>, iterate the sorted injection ranges
(sort ranges first to allow a linear sweep) and produce one or more clipped
spans for the portions of the outer span that lie entirely outside each
injection range, then extend merged with those clipped spans plus all inner
spans, and finally sort by span.start; keep references to merge_injection_spans,
HighlightSpan, and the injections Vec<(Range<usize>, Vec<HighlightSpan>)> when
making changes.
---
Nitpick comments:
In `@examples/test_highlighter.rs`:
- Around line 57-98: Extract a small helper function (e.g., fn run_case(label:
&str, path: &str, code: &str, take: usize)) and replace the duplicated Astro and
HTML test blocks with calls to that helper; the helper should create a
gitlogue::syntax::Highlighter, call set_language_from_path(path) and print its
bool result, call highlight(code), print the number of spans, and iterate the
first `take` spans printing the same "{}: [{}-{}] {:?} = '{}'" output using
span.start/span.end/span.token_type and &code[span.start..span.end]; update the
Astro and HTML blocks to call run_case("Astro","test.astro", astro_code, 25) and
run_case("HTML","test.html", html_code, 25) to remove the copy-paste.
In `@src/syntax/languages/markdown.rs`:
- Around line 5-9: The comment "Custom highlight query for better visibility..."
is now separated from the symbol it documents; move the declaration of
INJECTION_QUERY so the comment directly precedes HIGHLIGHT_QUERY (or relocate
the comment) to keep documentation adjacent to HIGHLIGHT_QUERY; specifically,
ensure HIGHLIGHT_QUERY remains immediately after the comment and place
INJECTION_QUERY (tree_sitter_md::INJECTION_QUERY_BLOCK) below HIGHLIGHT_QUERY to
restore correct proximity between the comment and the HIGHLIGHT_QUERY constant.
In `@src/syntax/languages/mod.rs`:
- Around line 51-206: The match arms in by_name return many identical
LanguageSupport structs causing boilerplate and potential drift; introduce a
small helper (e.g., a macro like lang! or a table mapping canonical names to
module identifiers and optional injection flags) and refactor by_name to call
that helper instead of repeating the struct literal for each language; keep the
same semantics: call each module's language() for language, use
MODULE::HIGHLIGHT_QUERY for highlight_query and pass
Some(MODULE::INJECTION_QUERY) or None for injection_query so the public API
(by_name and LanguageSupport) remains unchanged (refer to by_name,
LanguageSupport, and each module constant like html::INJECTION_QUERY).
In `@src/syntax/mod.rs`:
- Around line 287-304: resolve_injection_language currently only strips quote
characters and may return an info-string like "ts {highlight=...}" which breaks
language lookup; update the post-cleaning step in resolve_injection_language
(referencing the function name and the m.captures handling) to split the cleaned
string on whitespace, comma, and '{' and take the first token, trim it, ensure
it's non-empty, then return that token lowercased (instead of the entire cleaned
string) so only the language name is returned for get_language_by_name.
- Around line 306-338: highlight_slice currently constructs a new Parser and
calls Query::new for support.highlight_query and for each injection via
gather_injections on every invocation, causing redundant Tree-sitter query
compilation for repeated injected languages; introduce a per-highlight-call
cache (e.g., a HashMap keyed by language name or Language pointer) and thread it
into highlight_slice and gather_injections so you reuse compiled Query instances
(and optionally Parsers) instead of calling Query::new/Parser::new repeatedly
for the same language, updating references to support.highlight_query,
support.injection_query, highlight_slice, and gather_injections to look up or
insert into the cache before creating new Query/Parser.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 379fcb4c-9af2-4af3-9b2d-f20777cee084
📒 Files selected for processing (8)
examples/test_highlighter.rssrc/syntax/languages/astro.rssrc/syntax/languages/html.rssrc/syntax/languages/markdown.rssrc/syntax/languages/mod.rssrc/syntax/languages/php.rssrc/syntax/languages/svelte.rssrc/syntax/mod.rs
| fn merge_injection_spans( | ||
| outer: Vec<HighlightSpan>, | ||
| injections: Vec<(Range<usize>, Vec<HighlightSpan>)>, | ||
| ) -> Vec<HighlightSpan> { | ||
| if injections.is_empty() { | ||
| return outer; | ||
| } | ||
| let ranges: Vec<Range<usize>> = injections.iter().map(|(r, _)| r.clone()).collect(); | ||
| let mut merged: Vec<HighlightSpan> = outer | ||
| .into_iter() | ||
| .filter(|s| !ranges.iter().any(|r| s.start < r.end && r.start < s.end)) | ||
| .collect(); | ||
| for (_, inner) in injections { | ||
| merged.extend(inner); | ||
| } | ||
| merged.sort_by_key(|span| span.start); | ||
| merged | ||
| } |
There was a problem hiding this comment.
Outer spans that partially overlap an injection range are dropped entirely.
The filter !ranges.iter().any(|r| s.start < r.end && r.start < s.end) discards any outer span that touches any injection range, even if it only overlaps at one edge. For Tree-sitter grammars where a node happens to span the delimiters plus the content (e.g., a capture that covers <script>…</script> as one span), you'd lose the delimiter highlights rather than clipping them.
In practice most grammars emit separate captures for delimiters vs. content, so this is usually fine — but it's worth (a) confirming for the wired languages (Astro/Svelte/HTML/Markdown/PHP) that no outer capture crosses the injection boundary, and (b) eventually replacing the all-or-nothing filter with a clip-to-injection-boundary pass if you notice dropped highlights at script/style edges. A small unit test asserting that <script> / </script> delimiters remain highlighted on HTML would be a cheap safety net.
Also a perf nit: the overlap check is O(outer × injections). For long files with many Markdown code fences, consider sorting ranges and doing a linear sweep.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/syntax/mod.rs` around lines 340 - 357, The function merge_injection_spans
currently drops any outer HighlightSpan that even partially overlaps an
injection Range, causing delimiter highlights to vanish; update
merge_injection_spans to clip outer spans to the non-overlapping portions
instead of discarding them: for each outer span in the incoming outer
Vec<HighlightSpan>, iterate the sorted injection ranges (sort ranges first to
allow a linear sweep) and produce one or more clipped spans for the portions of
the outer span that lie entirely outside each injection range, then extend
merged with those clipped spans plus all inner spans, and finally sort by
span.start; keep references to merge_injection_spans, HighlightSpan, and the
injections Vec<(Range<usize>, Vec<HighlightSpan>)> when making changes.
- Drop `sass` from the css alias list. Indented-syntax Sass cannot be
parsed cleanly by tree-sitter-css; falling back to plain text is safer
than producing noisy highlights.
- In `resolve_injection_language`, split the captured info-string on
whitespace / `,` / `{` and take only the first token so markdown fences
like ```` ```ts {highlight=1-3} ```` and ```` ```rust,no_run ```` still
resolve to the correct language.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/syntax/mod.rs (2)
248-251: Minor: collapse the two-stepcapture_indexunwrap.Tiny readability tweak — the intermediate binding isn't used:
♻️ Proposed diff
- let content_index = capture_index(query, "injection.content"); - let Some(content_index) = content_index else { - return Vec::new(); - }; + let Some(content_index) = capture_index(query, "injection.content") else { + return Vec::new(); + };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/syntax/mod.rs` around lines 248 - 251, Collapse the two-step unwrap into a single pattern match: replace the separate binding of capture_index and the subsequent `let Some(content_index) = content_index else { return Vec::new(); }` with a one-line `let Some(content_index) = capture_index(query, "injection.content") else { return Vec::new(); };` (or equivalently use `if let Some(content_index) = capture_index(...) { ... } else { return Vec::new(); }`) so the intermediate `content_index` binding is removed; this change affects the use of the capture_index call and the local variable content_index in mod.rs.
310-342: Per-slice parser + query recompilation will bite on Markdown-heavy inputs.
highlight_sliceruns once per@injection.contentmatch and, on every invocation:
- constructs a fresh
Parser(Parser::new()+set_language),- recompiles
support.highlight_queryfrom source,- (if present) recompiles
support.injection_queryfrom source.Tree-sitter
Query::newparses the full.scmsource, which is non-trivial (the Rust bindings walk every pattern/capture). For a large Markdown document with many fenced code blocks — or a.html/.phpfile with several<script>/<style>regions — you're paying that cost N times per highlight pass, plus any recursion cost at depth > 1.Consider caching compiled
Querys (and optionally aParserpool) keyed by canonical language name inside theHighlighter, e.g. aHashMap<&'static str, (Query, Option<Query>)>populated lazily on first injection into a language. The outerself.parsercan't be reused directly for injections while mid-traversal, but a per-language cachedQueryis the big win and is straightforward.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/syntax/mod.rs` around lines 310 - 342, highlight_slice repeatedly constructs a Parser and recompiles Query::new from support.highlight_query and support.injection_query on every call, which is expensive for Markdown-heavy inputs; fix this by moving Query compilation out of highlight_slice into a per-language cache on the Highlighter (e.g., add a HashMap keyed by canonical language name that stores the compiled highlight Query and optional injection Query, populate it lazily on first use), have highlight_slice look up the cached Query(s) instead of calling Query::new each time, and optionally reuse a pool of Parser instances rather than calling Parser::new inside highlight_slice; reference the functions/fields highlight_slice, Parser::new, Query::new, support.highlight_query, support.injection_query, and the Highlighter struct when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/syntax/languages/mod.rs`:
- Line 237: The `"tsx"` alias currently canonicalizes to `"typescript"` and ends
up using the non-JSX TypeScript grammar; change the mapping so `"tsx"`
canonicalizes to a distinct `"tsx"` case and ensure the selector that returns a
Language uses the TSX-capable symbol (e.g., typescript::LANGUAGE_TSX or
typescript::language_tsx()) instead of
typescript::language()/LANGUAGE_TYPESCRIPT so .tsx files and JSX-containing
fences are parsed with the TSX grammar.
---
Nitpick comments:
In `@src/syntax/mod.rs`:
- Around line 248-251: Collapse the two-step unwrap into a single pattern match:
replace the separate binding of capture_index and the subsequent `let
Some(content_index) = content_index else { return Vec::new(); }` with a one-line
`let Some(content_index) = capture_index(query, "injection.content") else {
return Vec::new(); };` (or equivalently use `if let Some(content_index) =
capture_index(...) { ... } else { return Vec::new(); }`) so the intermediate
`content_index` binding is removed; this change affects the use of the
capture_index call and the local variable content_index in mod.rs.
- Around line 310-342: highlight_slice repeatedly constructs a Parser and
recompiles Query::new from support.highlight_query and support.injection_query
on every call, which is expensive for Markdown-heavy inputs; fix this by moving
Query compilation out of highlight_slice into a per-language cache on the
Highlighter (e.g., add a HashMap keyed by canonical language name that stores
the compiled highlight Query and optional injection Query, populate it lazily on
first use), have highlight_slice look up the cached Query(s) instead of calling
Query::new each time, and optionally reuse a pool of Parser instances rather
than calling Parser::new inside highlight_slice; reference the functions/fields
highlight_slice, Parser::new, Query::new, support.highlight_query,
support.injection_query, and the Highlighter struct when making the change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: d235550f-a739-4076-a5bd-a0a2a5f961c7
📒 Files selected for processing (2)
src/syntax/languages/mod.rssrc/syntax/mod.rs
| "scala" | "sc" | "sbt" => Some("scala"), | ||
| "svelte" => Some("svelte"), | ||
| "swift" => Some("swift"), | ||
| "ts" | "tsx" | "mts" | "cts" | "typescript" => Some("typescript"), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect the language() functions for typescript/javascript to see which tree-sitter grammar they return.
fd -t f 'typescript.rs|javascript.rs' src/syntax/languages --exec cat {}Repository: unhappychoice/gitlogue
Length of output: 420
🌐 Web query:
tree-sitter-typescript crate language_typescript vs language_tsx difference
💡 Result:
In the tree-sitter-typescript Rust crate (crates.io/crates/tree-sitter-typescript), LANGUAGE_TYPESCRIPT and LANGUAGE_TSX are two distinct constants providing Tree-sitter LanguageFn objects for parsing different dialects. LANGUAGE_TYPESCRIPT is for plain TypeScript (.ts files), supporting full TypeScript syntax including type assertions like <Type>expr. LANGUAGE_TSX is for TSX (.tsx files), which is TypeScript with JSX. It excludes type assertions because they conflict with JSX element syntax (<Type>expr looks like a JSX tag), avoiding parsing ambiguities. This separation was introduced to resolve conflicts, especially with type arguments in JSX. Use LANGUAGE_TYPESCRIPT for TypeScript code without JSX, and LANGUAGE_TSX for code with JSX elements. The grammars share a common base but have dialect-specific rules and separate node-types.json (TYPESCRIPT_NODE_TYPES vs TSX_NODE_TYPES). Example usage: use tree_sitter_typescript::{LANGUAGE_TYPESCRIPT, LANGUAGE_TSX}; let mut parser = Parser::new; parser.set_language(&LANGUAGE_TYPESCRIPT.into).unwrap; // for .ts // or parser.set_language(&LANGUAGE_TSX.into).unwrap; // for .tsx
Citations:
- 1: https://docs.rs/tree-sitter-typescript/latest/tree_sitter_typescript/
- 2: https://docs.rs/tree-sitter-typescript/0.21.2/tree_sitter_typescript/
- 3: https://github.com/tree-sitter/tree-sitter-typescript
- 4: https://crates.io/crates/tree-sitter-typescript
- 5: https://docs.rs/tree-sitter-typescript
- 6: https://docs.rs/tree-sitter-typescript/0.23.2/
- 7: Separate TypeScript and TSX grammars to avoid ambiguity and support type arguments in TSX tree-sitter/tree-sitter-typescript#68
- 8: https://www.syntax.tools
Fix tsx language alias to use TSX-capable grammar.
tsx (and .tsx file paths) currently canonicalize to "typescript", which dispatches to typescript::language(). However, the Rust tree-sitter-typescript crate exposes two distinct Language constants: LANGUAGE_TYPESCRIPT (plain TypeScript, without JSX) and LANGUAGE_TSX (TypeScript with JSX support). The code currently returns LANGUAGE_TYPESCRIPT, which cannot parse JSX element syntax. This causes .tsx files and markdown fences tagged ```tsx containing JSX to fail silently (the parser returns None and syntax highlighting is lost).
The jsx alias mapping to javascript is correct — tree-sitter-javascript accepts JSX in its default grammar.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/syntax/languages/mod.rs` at line 237, The `"tsx"` alias currently
canonicalizes to `"typescript"` and ends up using the non-JSX TypeScript
grammar; change the mapping so `"tsx"` canonicalizes to a distinct `"tsx"` case
and ensure the selector that returns a Language uses the TSX-capable symbol
(e.g., typescript::LANGUAGE_TSX or typescript::language_tsx()) instead of
typescript::language()/LANGUAGE_TYPESCRIPT so .tsx files and JSX-containing
fences are parsed with the TSX grammar.
Summary
@injection.content/@injection.languagecaptures, re-parse those ranges with the target language, and merge spans into the outer highlight — per approach 2 in feat(syntax): support tree-sitter language injections #191.INJECTION_QUERYfor Astro, Svelte, HTML, Markdown (block), and PHP. IntroduceLanguageSupport+get_language_by_nameso injected language names (with common aliases likets→typescript,scss→css) resolve through one canonical table.Behavior impact
{expr}+<style>/<script>now syntax-highlighted.<script lang="ts">/<style>now highlighted.<script>/<style>bodies now highlighted.Out of scope (follow-ups)
#set! injection.combined— each injection parsed independently.INJECTION_QUERY_INLINEnot wired).phpdoc,pug).Test plan
cargo buildcargo clippy --all-targets -- -D warningscargo test(17 passed)cargo run --example test_highlighter— confirmed inner-language tokens appear for Markdown\``rust, Astro frontmatter +{name}+<style>, HTML<style>` body.cargo runon a repo containing.astro/.svelte/.md/.html/.phpdiffs — eyeball editor pane.Closes #191
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests