Add `highlight` crate for syntax highlighting

061ce9b976e9b272bab4ed298ff285d1a85398a9
Alexis Sellier committed ago 1 parent d80dcb6a
Cargo.lock +126 -0
1 1
# This file is automatically @generated by Cargo.
2 2
# It is not intended for manual editing.
3 3
version = 4
4 4
5 +
[[package]]
6 +
name = "bitflags"
7 +
version = "2.11.1"
8 +
source = "registry+https://github.com/rust-lang/crates.io-index"
9 +
checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
10 +
11 +
[[package]]
12 +
name = "cc"
13 +
version = "1.2.61"
14 +
source = "registry+https://github.com/rust-lang/crates.io-index"
15 +
checksum = "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d"
16 +
dependencies = [
17 +
 "find-msvc-tools",
18 +
 "shlex",
19 +
]
20 +
21 +
[[package]]
22 +
name = "find-msvc-tools"
23 +
version = "0.1.9"
24 +
source = "registry+https://github.com/rust-lang/crates.io-index"
25 +
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
26 +
5 27
[[package]]
6 28
name = "libc"
7 29
version = "0.2.186"
8 30
source = "registry+https://github.com/rust-lang/crates.io-index"
9 31
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
10 32
33 +
[[package]]
34 +
name = "microserde"
35 +
version = "0.1.13"
36 +
source = "registry+https://github.com/rust-lang/crates.io-index"
37 +
checksum = "bc73d64402c57ce913a4a4788ca4e0c60329a2e29782f8e88d510c1c951fac46"
38 +
dependencies = [
39 +
 "microserde-derive",
40 +
]
41 +
42 +
[[package]]
43 +
name = "microserde-derive"
44 +
version = "0.1.13"
45 +
source = "registry+https://github.com/rust-lang/crates.io-index"
46 +
checksum = "6e3afa8ee462bb9ed735b544476a9e4ece0f10be76864ff9b80a6a525b837232"
47 +
dependencies = [
48 +
 "proc-macro2",
49 +
 "quote",
50 +
 "syn",
51 +
]
52 +
11 53
[[package]]
12 54
name = "numtoa"
13 55
version = "0.2.4"
14 56
source = "registry+https://github.com/rust-lang/crates.io-index"
15 57
checksum = "6aa2c4e539b869820a2b82e1aef6ff40aa85e65decdd5185e83fb4b1249cd00f"
16 58
59 +
[[package]]
60 +
name = "once_cell"
61 +
version = "1.21.4"
62 +
source = "registry+https://github.com/rust-lang/crates.io-index"
63 +
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
64 +
65 +
[[package]]
66 +
name = "onig-regset"
67 +
version = "6.7.0"
68 +
source = "registry+https://github.com/rust-lang/crates.io-index"
69 +
checksum = "080c4eeac92e475efa2893e52522ee3de48086cdad5fb5f36631a7fcb5293c81"
70 +
dependencies = [
71 +
 "bitflags",
72 +
 "libc",
73 +
 "once_cell",
74 +
 "onig_sys",
75 +
]
76 +
77 +
[[package]]
78 +
name = "onig_sys"
79 +
version = "69.9.3"
80 +
source = "registry+https://github.com/rust-lang/crates.io-index"
81 +
checksum = "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7"
82 +
dependencies = [
83 +
 "cc",
84 +
 "pkg-config",
85 +
]
86 +
87 +
[[package]]
88 +
name = "pkg-config"
89 +
version = "0.3.33"
90 +
source = "registry+https://github.com/rust-lang/crates.io-index"
91 +
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
92 +
93 +
[[package]]
94 +
name = "proc-macro2"
95 +
version = "1.0.106"
96 +
source = "registry+https://github.com/rust-lang/crates.io-index"
97 +
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
98 +
dependencies = [
99 +
 "unicode-ident",
100 +
]
101 +
102 +
[[package]]
103 +
name = "quote"
104 +
version = "1.0.45"
105 +
source = "registry+https://github.com/rust-lang/crates.io-index"
106 +
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
107 +
dependencies = [
108 +
 "proc-macro2",
109 +
]
110 +
17 111
[[package]]
18 112
name = "rustik"
19 113
version = "0.1.0"
20 114
dependencies = [
115 +
 "rustik-highlight",
21 116
 "rustik-tui",
22 117
]
23 118
119 +
[[package]]
120 +
name = "rustik-highlight"
121 +
version = "0.1.0"
122 +
dependencies = [
123 +
 "microserde",
124 +
 "onig-regset",
125 +
]
126 +
24 127
[[package]]
25 128
name = "rustik-tui"
26 129
version = "0.1.0"
27 130
dependencies = [
28 131
 "rustik-tui-core",
47 150
version = "0.1.0"
48 151
dependencies = [
49 152
 "rustik-tui-core",
50 153
]
51 154
155 +
[[package]]
156 +
name = "shlex"
157 +
version = "1.3.0"
158 +
source = "registry+https://github.com/rust-lang/crates.io-index"
159 +
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
160 +
161 +
[[package]]
162 +
name = "syn"
163 +
version = "1.0.109"
164 +
source = "registry+https://github.com/rust-lang/crates.io-index"
165 +
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
166 +
dependencies = [
167 +
 "proc-macro2",
168 +
 "quote",
169 +
 "unicode-ident",
170 +
]
171 +
52 172
[[package]]
53 173
name = "termion"
54 174
version = "4.0.6"
55 175
source = "registry+https://github.com/rust-lang/crates.io-index"
56 176
checksum = "f44138a9ae08f0f502f24104d82517ef4da7330c35acd638f1f29d3cd5475ecb"
57 177
dependencies = [
58 178
 "libc",
59 179
 "numtoa",
60 180
]
181 +
182 +
[[package]]
183 +
name = "unicode-ident"
184 +
version = "1.0.24"
185 +
source = "registry+https://github.com/rust-lang/crates.io-index"
186 +
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
Cargo.toml +7 -3
1 1
[workspace]
2 2
members = [
3 +
  "crates/highlight",
3 4
  "crates/tui",
4 5
  "crates/tui-core",
5 6
  "crates/tui-termion",
6 7
  "crates/tui-widgets"
7 8
]
16 17
edition.workspace = true
17 18
license.workspace = true
18 19
19 20
[features]
20 21
default = []
22 +
highlight = ["dep:rustik-highlight"]
21 23
widgets = ["rustik-tui/widgets"]
22 -
all = ["widgets"]
24 +
all = ["highlight", "widgets"]
23 25
24 26
[dependencies]
27 +
rustik-highlight = { workspace = true, optional = true }
25 28
rustik-tui = { workspace = true }
26 29
27 30
[lints]
28 31
workspace = true
29 32
31 34
version = "0.1.0"
32 35
edition = "2024"
33 36
license = "MIT"
34 37
35 38
[workspace.dependencies]
39 +
onig = { package = "onig-regset", version = "6.7.0", default-features = false }
40 +
serde = { package = "microserde", version = "0.1.13" }
36 41
termion = "4"
42 +
rustik-highlight = { path = "crates/highlight", version = "0.1.0" }
37 43
rustik-tui = { path = "crates/tui", version = "0.1.0" }
38 44
rustik-tui-core = { path = "crates/tui-core", version = "0.1.0" }
39 45
rustik-tui-widgets = { path = "crates/tui-widgets", version = "0.1.0" }
40 46
rustik-tui-termion = { path = "crates/tui-termion", version = "0.1.0" }
41 47
42 48
[workspace.lints.clippy]
43 49
inline_always = "allow"
44 -
must_use_candidate = "allow"
45 50
needless_pass_by_value = "allow"
46 -
return_self_not_must_use = "allow"
47 51
too_many_lines = "allow"
48 52
trivially_copy_pass_by_ref = "allow"
49 53
unused_self = "allow"
50 54
unwrap_used = "warn"
51 55
expect_used = "warn"
crates/highlight/Cargo.toml added +15 -0
1 +
[package]
2 +
name = "rustik-highlight"
3 +
description = "Rustik code highlighter."
4 +
documentation = "https://docs.rs/rustik-highlight"
5 +
homepage = "https://crates.io/crates/rustik-highlight"
6 +
version.workspace = true
7 +
edition.workspace = true
8 +
license.workspace = true
9 +
10 +
[dependencies]
11 +
onig.workspace = true
12 +
serde.workspace = true
13 +
14 +
[lints]
15 +
workspace = true
crates/highlight/src/blob.rs added +417 -0
1 +
//! Incremental highlighting over complete text blobs.
2 +
//!
3 +
//! This module sits above raw line tokenization and keeps the per-line parser
4 +
//! state needed by editor and pager workloads. Callers can ask for one line or
5 +
//! a visible range, and unchanged lines reuse cached start states and scope
6 +
//! spans instead of reparsing from the top of the file.
7 +
8 +
use std::ops::Range;
9 +
10 +
use crate::grammar::{Grammar, LineState, LineTokenizer, ScopeSpan};
11 +
use crate::theme::{StyleCache, StyleScratch, StyleSpan, Theme};
12 +
use crate::util::line_starts;
13 +
14 +
/// Scratch space for highlighting one line without reallocating per call.
15 +
///
16 +
/// A buffer holds the latest tokenization and styling results so callers can
17 +
/// reuse allocations while scanning many lines or repeatedly re-highlighting a
18 +
/// changing line.
19 +
#[derive(Debug, Default)]
20 +
pub struct LineBuffer {
21 +
    /// Current scope spans.
22 +
    pub scopes: Vec<ScopeSpan>,
23 +
    /// Current style spans.
24 +
    pub styles: Vec<StyleSpan>,
25 +
    /// Cached resolved styles for the active grammar/theme pair.
26 +
    style_cache: StyleCache,
27 +
    /// Per-line scratch storage used when converting scope spans into style spans.
28 +
    style_scratch: StyleScratch,
29 +
}
30 +
31 +
/// Borrowed tokenization result for a line visited by a range highlighter.
32 +
///
33 +
/// This is the zero-copy callback view used when callers need grammar scopes
34 +
/// but not themed styles. The borrowed text and spans remain valid only for
35 +
/// the duration of the callback.
36 +
#[derive(Debug)]
37 +
pub struct LineTokens<'text, 'spans> {
38 +
    /// Zero-based line index in the blob.
39 +
    pub line_index: usize,
40 +
    /// Byte range of this line in the blob, excluding line terminators.
41 +
    pub byte_range: Range<usize>,
42 +
    /// Line text, excluding line terminators.
43 +
    pub text: &'text str,
44 +
    /// Scope spans for this line.
45 +
    pub scopes: &'spans [ScopeSpan],
46 +
}
47 +
48 +
/// Borrowed tokenization and styling result for a line visited by a range highlighter.
49 +
///
50 +
/// This is the zero-copy callback view used when callers need both grammar
51 +
/// scopes and theme-resolved style spans. The borrowed text and spans remain
52 +
/// valid only for the duration of the callback.
53 +
#[derive(Debug)]
54 +
pub struct StyledLine<'text, 'spans> {
55 +
    /// Zero-based line index in the blob.
56 +
    pub line_index: usize,
57 +
    /// Byte range of this line in the blob, excluding line terminators.
58 +
    pub byte_range: Range<usize>,
59 +
    /// Line text, excluding line terminators.
60 +
    pub text: &'text str,
61 +
    /// Scope spans for this line.
62 +
    pub scopes: &'spans [ScopeSpan],
63 +
    /// Styled spans for this line.
64 +
    pub styles: &'spans [StyleSpan],
65 +
}
66 +
67 +
/// Owned tokenization result for APIs that collect highlighted lines.
68 +
///
69 +
/// Unlike [`LineTokens`], this type owns its scope spans so callers can keep
70 +
/// the result after range traversal has moved on to another line.
71 +
#[derive(Clone, Debug, Eq, PartialEq)]
72 +
pub struct OwnedLineTokens {
73 +
    /// Zero-based line index in the blob.
74 +
    pub line_index: usize,
75 +
    /// Byte range of this line in the blob, excluding line terminators.
76 +
    pub byte_range: Range<usize>,
77 +
    /// Scope spans for this line.
78 +
    pub scopes: Vec<ScopeSpan>,
79 +
}
80 +
81 +
/// Incremental highlighter for a complete text blob.
82 +
///
83 +
/// The highlighter caches parser states and per-line scope spans so callers can
84 +
/// ask for individual lines or ranges without reparsing the whole blob each
85 +
/// time. Editing callers should call [`BlobHighlighter::reset_text`] or
86 +
/// [`BlobHighlighter::invalidate_from`] to keep those caches aligned with the
87 +
/// backing text.
88 +
#[derive(Debug)]
89 +
pub struct BlobHighlighter<'text> {
90 +
    /// Reusable tokenizer for the backing grammar.
91 +
    tokenizer: LineTokenizer<'text>,
92 +
    /// Backing source text.
93 +
    text: &'text str,
94 +
    /// Byte offsets for each source line start.
95 +
    line_starts: Vec<usize>,
96 +
    /// Parser state at the start of each source line.
97 +
    states: Vec<Option<LineState>>,
98 +
    /// Cached scope spans for each source line.
99 +
    scopes: Vec<Option<Vec<ScopeSpan>>>,
100 +
    /// Reusable per-line scratch for styled range calls.
101 +
    buffer: LineBuffer,
102 +
}
103 +
104 +
impl LineBuffer {
105 +
    /// Clears all buffered spans while retaining allocations.
106 +
    ///
107 +
    /// Cached scope styles are intentionally retained: they are keyed by `(theme,
108 +
    /// grammar, scope_count)` and stays valid across line resets.
109 +
    pub fn clear(&mut self) {
110 +
        self.scopes.clear();
111 +
        self.styles.clear();
112 +
        self.style_scratch.clear_line();
113 +
    }
114 +
115 +
    /// Tokenizes one line into this reusable buffer.
116 +
    pub fn tokenize<'a>(
117 +
        &'a mut self,
118 +
        grammar: &Grammar,
119 +
        state: &mut LineState,
120 +
        line: &str,
121 +
    ) -> &'a [ScopeSpan] {
122 +
        grammar.tokenize_line_into(state, line, &mut self.scopes);
123 +
        &self.scopes
124 +
    }
125 +
126 +
    /// Applies a theme to this buffer's current scope spans.
127 +
    pub fn style<'a>(
128 +
        &'a mut self,
129 +
        grammar: &Grammar,
130 +
        theme: &Theme,
131 +
        line: &str,
132 +
    ) -> &'a [StyleSpan] {
133 +
        self.style_cache.refresh(theme, grammar);
134 +
        theme.style_line_into(
135 +
            grammar,
136 +
            line,
137 +
            &self.scopes,
138 +
            &self.style_cache,
139 +
            &mut self.style_scratch,
140 +
            &mut self.styles,
141 +
        );
142 +
        &self.styles
143 +
    }
144 +
145 +
    /// Tokenizes and styles one line into this reusable buffer.
146 +
    pub fn highlight<'a>(
147 +
        &'a mut self,
148 +
        grammar: &Grammar,
149 +
        theme: &Theme,
150 +
        state: &mut LineState,
151 +
        line: &str,
152 +
    ) -> (&'a [ScopeSpan], &'a [StyleSpan]) {
153 +
        grammar.tokenize_line_into(state, line, &mut self.scopes);
154 +
        self.style(grammar, theme, line);
155 +
        (&self.scopes, &self.styles)
156 +
    }
157 +
}
158 +
159 +
impl<'text> BlobHighlighter<'text> {
160 +
    /// Creates a blob highlighter and caches only the initial empty state.
161 +
    pub fn new(grammar: &'text Grammar, text: &'text str) -> Self {
162 +
        let mut highlighter = Self {
163 +
            tokenizer: LineTokenizer::new(grammar),
164 +
            text,
165 +
            line_starts: Vec::new(),
166 +
            states: Vec::new(),
167 +
            scopes: Vec::new(),
168 +
            buffer: LineBuffer::default(),
169 +
        };
170 +
        highlighter.rebuild_caches();
171 +
        highlighter
172 +
    }
173 +
174 +
    /// Replaces the blob text and clears cached line states.
175 +
    pub fn reset_text(&mut self, text: &'text str) {
176 +
        self.text = text;
177 +
        self.rebuild_caches();
178 +
    }
179 +
180 +
    /// Rebuilds line metadata and clears cached highlighting results.
181 +
    fn rebuild_caches(&mut self) {
182 +
        self.line_starts = line_starts(self.text);
183 +
        self.states = vec![None; self.line_starts.len() + 1];
184 +
        self.states[0] = Some(LineState::default());
185 +
        self.scopes = vec![None; self.line_starts.len()];
186 +
    }
187 +
188 +
    /// Returns the number of highlightable lines in the blob.
189 +
    pub fn line_count(&self) -> usize {
190 +
        self.line_starts.len()
191 +
    }
192 +
193 +
    /// Returns a line by index, excluding line terminators.
194 +
    pub fn line(&self, line: usize) -> Option<&'text str> {
195 +
        let range = self.line_byte_range(line)?;
196 +
        Some(&self.text[range])
197 +
    }
198 +
199 +
    /// Returns a line's byte range, excluding line terminators.
200 +
    pub fn line_byte_range(&self, line: usize) -> Option<Range<usize>> {
201 +
        (line < self.line_count()).then(|| self.line_range_unchecked(line))
202 +
    }
203 +
204 +
    /// Returns whether a start state for `line` is already cached.
205 +
    pub fn is_state_cached(&self, line: usize) -> bool {
206 +
        self.states.get(line).is_some_and(Option::is_some)
207 +
    }
208 +
209 +
    /// Invalidates cached states after a changed line.
210 +
    pub fn invalidate_from(&mut self, line: usize) {
211 +
        let start = line.saturating_add(1).min(self.states.len());
212 +
        for state in &mut self.states[start..] {
213 +
            *state = None;
214 +
        }
215 +
        let start = line.min(self.scopes.len());
216 +
        for scopes in &mut self.scopes[start..] {
217 +
            *scopes = None;
218 +
        }
219 +
    }
220 +
221 +
    /// Ensures the parser state at the start of `line` is cached.
222 +
    pub fn ensure_state(&mut self, line: usize) -> Option<&LineState> {
223 +
        if line > self.line_count() {
224 +
            return None;
225 +
        }
226 +
        if self.states[line].is_none() {
227 +
            let state = self.compute_state(line)?;
228 +
            self.states[line] = Some(state);
229 +
        }
230 +
        self.states[line].as_ref()
231 +
    }
232 +
233 +
    /// Tokenizes one line into a caller-owned buffer.
234 +
    pub fn highlight_line_into(&mut self, line: usize, scopes: &mut Vec<ScopeSpan>) -> bool {
235 +
        if line >= self.line_count() {
236 +
            scopes.clear();
237 +
            return false;
238 +
        }
239 +
        let Some(mut state) = self.ensure_state(line).cloned() else {
240 +
            scopes.clear();
241 +
            return false;
242 +
        };
243 +
        let range = self.line_range_unchecked(line);
244 +
        let text = &self.text[range];
245 +
246 +
        tokenize_or_cache_into(
247 +
            &mut self.tokenizer,
248 +
            &mut self.states,
249 +
            &mut self.scopes,
250 +
            &mut state,
251 +
            line,
252 +
            text,
253 +
            scopes,
254 +
        );
255 +
        true
256 +
    }
257 +
258 +
    /// Tokenizes a line range and invokes `f` for each requested line.
259 +
    pub fn highlight_range<F>(&mut self, range: Range<usize>, mut f: F)
260 +
    where
261 +
        F: FnMut(LineTokens<'_, '_>),
262 +
    {
263 +
        let start = range.start.min(self.line_count());
264 +
        let end = range.end.min(self.line_count());
265 +
        if start >= end {
266 +
            return;
267 +
        }
268 +
        let Some(mut state) = self.ensure_state(start).cloned() else {
269 +
            return;
270 +
        };
271 +
272 +
        let mut scopes = Vec::new();
273 +
        for line_index in start..end {
274 +
            let byte_range = self.line_range_unchecked(line_index);
275 +
            let text = &self.text[byte_range.clone()];
276 +
277 +
            tokenize_or_cache_into(
278 +
                &mut self.tokenizer,
279 +
                &mut self.states,
280 +
                &mut self.scopes,
281 +
                &mut state,
282 +
                line_index,
283 +
                text,
284 +
                &mut scopes,
285 +
            );
286 +
            f(LineTokens {
287 +
                line_index,
288 +
                byte_range,
289 +
                text,
290 +
                scopes: &scopes,
291 +
            });
292 +
        }
293 +
    }
294 +
295 +
    /// Tokenizes and styles a line range and invokes `f` for each requested line.
296 +
    pub fn highlight_styled_range<F>(&mut self, theme: &Theme, range: Range<usize>, mut f: F)
297 +
    where
298 +
        F: FnMut(StyledLine<'_, '_>),
299 +
    {
300 +
        let start = range.start.min(self.line_count());
301 +
        let end = range.end.min(self.line_count());
302 +
        if start >= end {
303 +
            return;
304 +
        }
305 +
        let Some(mut state) = self.ensure_state(start).cloned() else {
306 +
            return;
307 +
        };
308 +
309 +
        let grammar = self.tokenizer.grammar;
310 +
        for line_index in start..end {
311 +
            let byte_range = self.line_range_unchecked(line_index);
312 +
            let text = &self.text[byte_range.clone()];
313 +
314 +
            tokenize_or_cache_into(
315 +
                &mut self.tokenizer,
316 +
                &mut self.states,
317 +
                &mut self.scopes,
318 +
                &mut state,
319 +
                line_index,
320 +
                text,
321 +
                &mut self.buffer.scopes,
322 +
            );
323 +
            self.buffer.style(grammar, theme, text);
324 +
325 +
            f(StyledLine {
326 +
                line_index,
327 +
                byte_range,
328 +
                text,
329 +
                scopes: &self.buffer.scopes,
330 +
                styles: &self.buffer.styles,
331 +
            });
332 +
        }
333 +
    }
334 +
335 +
    /// Tokenizes a line range into an owned output vector.
336 +
    pub fn highlight_range_into(&mut self, range: Range<usize>, output: &mut Vec<OwnedLineTokens>) {
337 +
        output.clear();
338 +
339 +
        self.highlight_range(range, |line| {
340 +
            output.push(OwnedLineTokens {
341 +
                line_index: line.line_index,
342 +
                byte_range: line.byte_range,
343 +
                scopes: line.scopes.to_vec(),
344 +
            });
345 +
        });
346 +
    }
347 +
348 +
    /// Returns newly allocated token data for a line range.
349 +
    pub fn highlighted_range(&mut self, range: Range<usize>) -> Vec<OwnedLineTokens> {
350 +
        let mut output = Vec::new();
351 +
        self.highlight_range_into(range, &mut output);
352 +
        output
353 +
    }
354 +
355 +
    /// Computes the parser state at the start of `line` from the nearest cached predecessor.
356 +
    fn compute_state(&mut self, line: usize) -> Option<LineState> {
357 +
        let mut index = line;
358 +
        while index > 0 && self.states[index].is_none() {
359 +
            index -= 1;
360 +
        }
361 +
        let mut state = self.states[index].clone().unwrap_or_default();
362 +
        let mut scratch = Vec::new();
363 +
364 +
        while index < line {
365 +
            let range = self.line_range_unchecked(index);
366 +
            let text = &self.text[range];
367 +
368 +
            self.tokenizer
369 +
                .tokenize_line_into(&mut state, text, &mut scratch);
370 +
371 +
            index += 1;
372 +
            self.states[index] = Some(state.clone());
373 +
        }
374 +
        Some(state)
375 +
    }
376 +
377 +
    /// Returns a line's byte range without checking that the line index exists.
378 +
    fn line_range_unchecked(&self, line: usize) -> Range<usize> {
379 +
        let start = self.line_starts[line];
380 +
        let mut end = self
381 +
            .line_starts
382 +
            .get(line + 1)
383 +
            .copied()
384 +
            .unwrap_or(self.text.len());
385 +
        let bytes = self.text.as_bytes();
386 +
        if end > start && bytes[end - 1] == b'\n' {
387 +
            end -= 1;
388 +
        }
389 +
        if end > start && bytes[end - 1] == b'\r' {
390 +
            end -= 1;
391 +
        }
392 +
        start..end
393 +
    }
394 +
}
395 +
396 +
/// Tokenizes a line or copies its cached scopes and following parser state.
397 +
fn tokenize_or_cache_into(
398 +
    tokenizer: &mut LineTokenizer<'_>,
399 +
    states: &mut [Option<LineState>],
400 +
    scopes_cache: &mut [Option<Vec<ScopeSpan>>],
401 +
    state: &mut LineState,
402 +
    line_index: usize,
403 +
    text: &str,
404 +
    out: &mut Vec<ScopeSpan>,
405 +
) {
406 +
    if let Some(cached) = scopes_cache[line_index].as_ref()
407 +
        && let Some(next_state) = states[line_index + 1].as_ref()
408 +
    {
409 +
        out.clone_from(cached);
410 +
        *state = next_state.clone();
411 +
    } else {
412 +
        tokenizer.tokenize_line_into(state, text, out);
413 +
414 +
        states[line_index + 1] = Some(state.clone());
415 +
        scopes_cache[line_index] = Some(out.clone());
416 +
    }
417 +
}
crates/highlight/src/error.rs added +37 -0
1 +
//! Error types for grammar, theme, and registry operations.
2 +
//!
3 +
//! The crate intentionally exposes a small error surface: invalid source data,
4 +
//! invalid regexes, and failed registry lookups. Lower-level parser details are
5 +
//! collapsed here so callers can report actionable load or selection failures
6 +
//! without depending on the JSON or regex implementation.
7 +
8 +
use std::fmt;
9 +
10 +
/// Highlighting error.
11 +
#[derive(Clone, Debug, Eq, PartialEq)]
12 +
pub enum Error {
13 +
    /// Input could not be parsed as a valid grammar.
14 +
    InvalidGrammar,
15 +
    /// Input could not be parsed as a valid theme.
16 +
    InvalidTheme,
17 +
    /// Regex data could not be compiled.
18 +
    InvalidRegex(String),
19 +
    /// A named grammar was not found.
20 +
    UnknownSyntax(String),
21 +
    /// A named theme was not found.
22 +
    UnknownTheme(String),
23 +
}
24 +
25 +
impl fmt::Display for Error {
26 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 +
        match self {
28 +
            Self::InvalidGrammar => f.write_str("invalid grammar"),
29 +
            Self::InvalidTheme => f.write_str("invalid theme"),
30 +
            Self::InvalidRegex(pattern) => write!(f, "invalid regex `{pattern}`"),
31 +
            Self::UnknownSyntax(name) => write!(f, "unknown syntax `{name}`"),
32 +
            Self::UnknownTheme(name) => write!(f, "unknown theme `{name}`"),
33 +
        }
34 +
    }
35 +
}
36 +
37 +
impl std::error::Error for Error {}
crates/highlight/src/grammar.rs added +226 -0
1 +
//! Grammar compilation and line tokenization.
2 +
//!
3 +
//! TextMate grammars are parsed into immutable pattern trees with interned
4 +
//! scope names and compiled Oniguruma regex sets. The public tokenizer APIs use
5 +
//! caller-owned [`LineState`] values so multi-line constructs can continue
6 +
//! across line boundaries without forcing whole-file parsing.
7 +
8 +
use std::collections::{BTreeMap, HashSet};
9 +
use std::path::Path;
10 +
use std::str::FromStr;
11 +
12 +
use onig::{RegSet, RegSetLead, Regex, Region, SearchOptions};
13 +
14 +
use crate::json;
15 +
use crate::raw::{RawCapture, RawGrammar, RawPattern, first_line_patterns};
16 +
use crate::util::{key, next_char_boundary, path_keys, trim_line_end};
17 +
use crate::{Error, MAX_INCLUDE_DEPTH};
18 +
19 +
mod end;
20 +
mod pattern;
21 +
mod tokenize;
22 +
23 +
pub use tokenize::LineTokenizer;
24 +
25 +
use pattern::{OpenRule, PatternSet, ScopeInterner};
26 +
27 +
/// Display name for the built-in plain-text fallback grammar.
28 +
pub(crate) const PLAIN_TEXT_NAME: &str = "Plain Text";
29 +
30 +
/// Interned scope identifier.
31 +
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
32 +
pub struct ScopeId(
33 +
    /// Index into a grammar's interned scope-name table.
34 +
    usize,
35 +
);
36 +
37 +
impl ScopeId {
38 +
    /// Returns this id's index into its grammar's interned scope-name table.
39 +
    pub const fn index(self) -> usize {
40 +
        self.0
41 +
    }
42 +
43 +
    /// Creates a scope id from an interned scope-name table index.
44 +
    pub(crate) const fn new(index: usize) -> Self {
45 +
        Self(index)
46 +
    }
47 +
}
48 +
49 +
/// Scope span produced by tokenization.
50 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
51 +
pub struct ScopeSpan {
52 +
    /// Start byte in the line.
53 +
    pub start: usize,
54 +
    /// End byte in the line.
55 +
    pub end: usize,
56 +
    /// Interned scope id.
57 +
    pub scope: ScopeId,
58 +
}
59 +
60 +
/// Per-line parser state.
61 +
#[derive(Clone, Debug, Default, Eq, PartialEq)]
62 +
pub struct LineState {
63 +
    /// Open begin/end rules carried across line boundaries.
64 +
    stack: Vec<OpenRule>,
65 +
}
66 +
67 +
impl LineState {
68 +
    /// Returns true when there are no open multi-line rules.
69 +
    pub fn is_empty(&self) -> bool {
70 +
        self.stack.is_empty()
71 +
    }
72 +
73 +
    /// Returns the number of open multi-line rules.
74 +
    pub fn depth(&self) -> usize {
75 +
        self.stack.len()
76 +
    }
77 +
}
78 +
79 +
/// Immutable compiled grammar data.
80 +
#[derive(Debug)]
81 +
pub struct Grammar {
82 +
    /// Human-readable grammar name.
83 +
    pub name: String,
84 +
    /// Root scope name.
85 +
    pub scope_name: String,
86 +
    /// Interned scope names used by this grammar.
87 +
    pub scopes: Vec<String>,
88 +
    /// Tokenization strategy used by this grammar.
89 +
    pub kind: GrammarKind,
90 +
    /// Lowercase file extensions, file names, and aliases matched by this grammar.
91 +
    file_types: HashSet<String>,
92 +
    /// Regexes used to match a source file's first line.
93 +
    first_line_match: Vec<Regex>,
94 +
    /// Root pattern set for TextMate tokenization.
95 +
    patterns: PatternSet,
96 +
    /// Path of pattern indices into `patterns`, indexed by rule id.
97 +
    rule_paths: Vec<Box<[usize]>>,
98 +
}
99 +
100 +
/// Tokenization strategy used by a grammar.
101 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
102 +
pub enum GrammarKind {
103 +
    /// TextMate grammar compiled to Oniguruma regex sets.
104 +
    TextMate,
105 +
    /// Dedicated line-oriented JSON scanner.
106 +
    Json,
107 +
}
108 +
109 +
impl Grammar {
110 +
    /// Compiles a raw grammar.
111 +
    pub fn compile(raw: &RawGrammar) -> Result<Self, Error> {
112 +
        let mut next_rule = 0;
113 +
        let mut interner = ScopeInterner::default();
114 +
        let patterns = PatternSet::compile(raw, &raw.patterns, &mut next_rule, 0, &mut interner)?;
115 +
        let first_line_match = first_line_patterns(raw.first_line_match.as_ref())
116 +
            .iter()
117 +
            .map(|pattern| Regex::new(pattern).map_err(|_| Error::InvalidRegex(pattern.clone())))
118 +
            .collect::<Result<Vec<_>, _>>()?;
119 +
        let rule_paths = patterns.collect_rule_paths(next_rule);
120 +
121 +
        Ok(Self {
122 +
            name: raw.display_name.clone().unwrap_or_else(|| raw.name.clone()),
123 +
            scope_name: raw.scope_name.clone(),
124 +
            file_types: raw
125 +
                .file_types
126 +
                .as_deref()
127 +
                .unwrap_or_default()
128 +
                .iter()
129 +
                .chain(std::iter::once(&raw.name))
130 +
                .map(|item| key(item))
131 +
                .collect(),
132 +
            first_line_match,
133 +
            patterns,
134 +
            rule_paths,
135 +
            scopes: interner.scopes,
136 +
            kind: GrammarKind::TextMate,
137 +
        })
138 +
    }
139 +
140 +
    /// Builds a grammar with no patterns for plain text fallback.
141 +
    pub fn plain_text() -> Self {
142 +
        Self {
143 +
            name: PLAIN_TEXT_NAME.to_owned(),
144 +
            scope_name: "text.plain".to_owned(),
145 +
            file_types: ["txt".to_owned(), "text".to_owned()].into_iter().collect(),
146 +
            first_line_match: Vec::new(),
147 +
            patterns: PatternSet::empty(),
148 +
            rule_paths: Vec::new(),
149 +
            scopes: Vec::new(),
150 +
            kind: GrammarKind::TextMate,
151 +
        }
152 +
    }
153 +
154 +
    /// Builds the dedicated fast JSON grammar.
155 +
    ///
156 +
    /// This does not use the recursive TextMate tokenizer. It emits the same
157 +
    /// kind of [`ScopeSpan`] values as compiled grammars while scanning each
158 +
    /// line directly.
159 +
    pub fn json() -> Self {
160 +
        Self {
161 +
            name: "JSON".to_owned(),
162 +
            scope_name: "source.json".to_owned(),
163 +
            file_types: ["json".to_owned()].into_iter().collect(),
164 +
            first_line_match: Vec::new(),
165 +
            patterns: PatternSet::empty(),
166 +
            rule_paths: Vec::new(),
167 +
            scopes: json::SCOPES
168 +
                .iter()
169 +
                .map(|scope| (*scope).to_owned())
170 +
                .collect(),
171 +
            kind: GrammarKind::Json,
172 +
        }
173 +
    }
174 +
175 +
    /// Returns true when this grammar matches a syntax name or alias.
176 +
    pub fn matches_name(&self, name: &str) -> bool {
177 +
        name.eq_ignore_ascii_case(&self.name)
178 +
            || name.eq_ignore_ascii_case(&self.scope_name)
179 +
            || self.file_types.contains(&key(name))
180 +
    }
181 +
182 +
    /// Returns true when this grammar matches a file path.
183 +
    pub fn matches_path(&self, path: &Path) -> bool {
184 +
        path_keys(path).any(|key| self.file_types.contains(&key))
185 +
    }
186 +
187 +
    /// Returns true when this grammar matches the first source line.
188 +
    pub fn matches_first_line(&self, line: &str) -> bool {
189 +
        self.first_line_match
190 +
            .iter()
191 +
            .any(|regex| regex.find(line).is_some())
192 +
    }
193 +
194 +
    /// Tokenizes one line, mutating the caller-owned line state.
195 +
    pub fn tokenize_line(&self, state: &mut LineState, line: &str) -> Vec<ScopeSpan> {
196 +
        let mut spans = Vec::new();
197 +
        self.tokenize_line_into(state, line, &mut spans);
198 +
        spans
199 +
    }
200 +
201 +
    /// Tokenizes one line into a caller-owned buffer.
202 +
    pub fn tokenize_line_into(
203 +
        &self,
204 +
        state: &mut LineState,
205 +
        line: &str,
206 +
        spans: &mut Vec<ScopeSpan>,
207 +
    ) {
208 +
        LineTokenizer::new(self).tokenize_line_into(state, line, spans);
209 +
    }
210 +
211 +
    /// Returns the compiled pattern for a stored rule id.
212 +
    fn pattern_by_rule(&self, rule_id: usize) -> Option<&pattern::Pattern> {
213 +
        let path = self.rule_paths.get(rule_id)?;
214 +
        self.patterns.pattern_at(path)
215 +
    }
216 +
}
217 +
218 +
impl FromStr for Grammar {
219 +
    type Err = Error;
220 +
221 +
    /// Parses and compiles a grammar from JSON.
222 +
    fn from_str(input: &str) -> Result<Self, Self::Err> {
223 +
        let raw = RawGrammar::from_str(input)?;
224 +
        Self::compile(&raw)
225 +
    }
226 +
}
crates/highlight/src/grammar/end.rs added +171 -0
1 +
//! End-pattern resolution for begin/end rules.
2 +
//!
3 +
//! TextMate end patterns can be static (a regex known at compile time) or
4 +
//! dynamic (numeric backrefs into the begin match resolved per occurrence).
5 +
//! Resolved dynamic end regexes are cached so that a multi-line construct does
6 +
//! not recompile its end regex on every line.
7 +
8 +
use std::collections::BTreeMap;
9 +
use std::sync::Arc;
10 +
11 +
use onig::Regex;
12 +
13 +
use super::pattern::RegexMatch;
14 +
15 +
/// Cache of regexes for resolved dynamic end patterns.
16 +
pub(super) type EndRegexCache = BTreeMap<String, Arc<Regex>>;
17 +
18 +
/// End-pattern definition stored on a compiled begin/end rule.
19 +
#[derive(Debug)]
20 +
pub(super) enum EndPattern {
21 +
    /// End regex compiled at grammar-compile time.
22 +
    Static {
23 +
        /// Original regex source.
24 +
        source: String,
25 +
        /// Compiled regex.
26 +
        regex: Regex,
27 +
    },
28 +
    /// End regex deferred until begin-match captures are known.
29 +
    Dynamic {
30 +
        /// Regex source containing numeric backrefs.
31 +
        source: String,
32 +
    },
33 +
}
34 +
35 +
/// End regex resolved against a specific begin match.
36 +
///
37 +
/// Static end patterns borrow their regex from the compiled grammar, while
38 +
/// dynamic patterns own a shared handle into the [`EndRegexCache`]. Both
39 +
/// variants expose the same [`Self::source`] and [`Self::regex`] accessors so
40 +
/// the tokenizer can treat them uniformly.
41 +
pub(super) enum EndRegex<'pat> {
42 +
    /// End regex compiled with the grammar.
43 +
    Static {
44 +
        /// Source string for tokenizer heuristics (e.g. escaped-quote skip).
45 +
        source: &'pat str,
46 +
        /// Compiled regex.
47 +
        regex: &'pat Regex,
48 +
    },
49 +
    /// End regex resolved from begin captures and shared via the cache.
50 +
    Dynamic {
51 +
        /// Resolved source string (after backref substitution).
52 +
        source: String,
53 +
        /// Compiled regex held jointly with the cache.
54 +
        regex: Arc<Regex>,
55 +
    },
56 +
}
57 +
58 +
impl EndPattern {
59 +
    /// Compiles an end pattern, deferring numeric-backref patterns until match time.
60 +
    pub(super) fn compile(source: &str) -> Option<Self> {
61 +
        if has_numeric_backrefs(source) {
62 +
            return Some(Self::Dynamic {
63 +
                source: source.to_owned(),
64 +
            });
65 +
        }
66 +
        let regex = Regex::new(source).ok()?;
67 +
68 +
        Some(Self::Static {
69 +
            source: source.to_owned(),
70 +
            regex,
71 +
        })
72 +
    }
73 +
74 +
    /// Resolves this end pattern when its begin/end rule first opens.
75 +
    pub(super) fn resolve_for_begin<'pat>(
76 +
        &'pat self,
77 +
        begin: &RegexMatch,
78 +
        line: &str,
79 +
        cache: &mut EndRegexCache,
80 +
    ) -> Option<EndRegex<'pat>> {
81 +
        match self {
82 +
            Self::Static { source, regex } => Some(EndRegex::Static { source, regex }),
83 +
            Self::Dynamic { source } => {
84 +
                let resolved = begin.expand_backrefs(source, line);
85 +
                let regex = lookup_or_compile(cache, &resolved)?;
86 +
87 +
                Some(EndRegex::Dynamic {
88 +
                    source: resolved,
89 +
                    regex,
90 +
                })
91 +
            }
92 +
        }
93 +
    }
94 +
95 +
    /// Resumes this end pattern using a dynamic source previously stored in line state.
96 +
    pub(super) fn resume<'pat>(
97 +
        &'pat self,
98 +
        dynamic_source: Option<&str>,
99 +
        cache: &mut EndRegexCache,
100 +
    ) -> Option<EndRegex<'pat>> {
101 +
        match self {
102 +
            Self::Static { source, regex } => Some(EndRegex::Static { source, regex }),
103 +
            Self::Dynamic { .. } => {
104 +
                let source = dynamic_source?;
105 +
                let regex = lookup_or_compile(cache, source)?;
106 +
107 +
                Some(EndRegex::Dynamic {
108 +
                    source: source.to_owned(),
109 +
                    regex,
110 +
                })
111 +
            }
112 +
        }
113 +
    }
114 +
115 +
    /// Returns true when this end pattern depends on begin-match captures.
116 +
    pub(super) fn is_dynamic(&self) -> bool {
117 +
        matches!(self, Self::Dynamic { .. })
118 +
    }
119 +
}
120 +
121 +
impl EndRegex<'_> {
122 +
    /// End-regex source string.
123 +
    pub(super) fn source(&self) -> &str {
124 +
        match self {
125 +
            Self::Static { source, .. } => source,
126 +
            Self::Dynamic { source, .. } => source.as_str(),
127 +
        }
128 +
    }
129 +
130 +
    /// Compiled regex used for searching.
131 +
    pub(super) fn regex(&self) -> &Regex {
132 +
        match self {
133 +
            Self::Static { regex, .. } => regex,
134 +
            Self::Dynamic { regex, .. } => regex,
135 +
        }
136 +
    }
137 +
138 +
    /// Returns the resolved dynamic source that should be stored in line state.
139 +
    pub(super) fn dynamic_source(&self) -> Option<String> {
140 +
        match self {
141 +
            Self::Static { .. } => None,
142 +
            Self::Dynamic { source, .. } => Some(source.clone()),
143 +
        }
144 +
    }
145 +
}
146 +
147 +
/// Returns the cached regex for `source`, compiling and inserting it on first use.
148 +
fn lookup_or_compile(cache: &mut EndRegexCache, source: &str) -> Option<Arc<Regex>> {
149 +
    if let Some(regex) = cache.get(source) {
150 +
        return Some(Arc::clone(regex));
151 +
    }
152 +
    let regex = Arc::new(Regex::new(source).ok()?);
153 +
    cache.insert(source.to_owned(), Arc::clone(&regex));
154 +
    Some(regex)
155 +
}
156 +
157 +
/// Returns true when `source` contains an unescaped numeric backreference.
158 +
fn has_numeric_backrefs(source: &str) -> bool {
159 +
    let mut backslashes = 0_usize;
160 +
    for byte in source.bytes() {
161 +
        if byte == b'\\' {
162 +
            backslashes += 1;
163 +
        } else {
164 +
            if byte.is_ascii_digit() && backslashes % 2 == 1 {
165 +
                return true;
166 +
            }
167 +
            backslashes = 0;
168 +
        }
169 +
    }
170 +
    false
171 +
}
crates/highlight/src/grammar/pattern.rs added +762 -0
1 +
//! Pattern compilation and matching for TextMate grammars.
2 +
//!
3 +
//! Raw TextMate patterns compile into a tree of [`Pattern`] values grouped into
4 +
//! [`PatternSet`]s. Each set keeps a combined Oniguruma [`RegSet`] so that
5 +
//! finding the next match in a line is one regex search regardless of how many
6 +
//! patterns share that nesting level. Begin/end rules carry their end pattern
7 +
//! on the same node; static end patterns are precompiled, while dynamic ones
8 +
//! are resolved against the begin match the first time they are needed and
9 +
//! cached for subsequent lines.
10 +
11 +
use super::end::{EndPattern, EndRegex, EndRegexCache};
12 +
use super::*;
13 +
14 +
/// Capture-group index → interned scope id mapping.
15 +
pub(super) type Captures = BTreeMap<usize, ScopeId>;
16 +
17 +
/// A scope assigned by a pattern.
18 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19 +
pub(super) enum Scope {
20 +
    /// Pattern names no scope.
21 +
    None,
22 +
    /// Pattern names a visible scope that emits spans.
23 +
    Visible(ScopeId),
24 +
    /// Pattern names a structural scope used only to hold parser state.
25 +
    Structural(ScopeId),
26 +
}
27 +
28 +
/// Capture-scope mappings for a pattern's three regex slots.
29 +
#[derive(Debug, Default)]
30 +
pub(super) struct PatternCaptures {
31 +
    /// Captures applied to a single match rule.
32 +
    pub(super) matched: Captures,
33 +
    /// Captures applied to a begin-match rule.
34 +
    pub(super) begin: Captures,
35 +
    /// Captures applied to an end-match rule.
36 +
    pub(super) end: Captures,
37 +
}
38 +
39 +
/// Match form used by a compiled pattern.
40 +
#[derive(Debug)]
41 +
enum PatternBody {
42 +
    /// Single regex match rule.
43 +
    Match {
44 +
        /// Regex source.
45 +
        source: String,
46 +
    },
47 +
    /// Stateful begin/end rule.
48 +
    BeginEnd {
49 +
        /// Begin regex source (also the entry inside the parent set's RegSet).
50 +
        begin_source: String,
51 +
        /// End regex (compiled now or deferred until begin captures are known).
52 +
        end: EndPattern,
53 +
    },
54 +
}
55 +
56 +
/// Compiled patterns at one nesting level plus their combined search regex.
57 +
#[derive(Debug)]
58 +
pub(super) struct PatternSet {
59 +
    /// Patterns in declaration order.
60 +
    patterns: Vec<Pattern>,
61 +
    /// Combined RegSet covering each pattern's match or begin source.
62 +
    regexes: Option<RegSet>,
63 +
}
64 +
65 +
/// Result of compiling one raw pattern.
66 +
enum Compiled {
67 +
    /// Pattern compiled to a single rule and should be added to the parent set.
68 +
    Rule(Pattern),
69 +
    /// Pattern was a grouping (no match/begin-end of its own); its nested patterns
70 +
    /// should be inlined directly into the parent set.
71 +
    Inline(Vec<Pattern>),
72 +
    /// Pattern was malformed and should be ignored.
73 +
    Skip,
74 +
}
75 +
76 +
/// One compiled TextMate pattern with its scope, captures, and nested rules.
77 +
///
78 +
/// A [`Pattern`] is what the grammar tokenizer matches against the source text.
79 +
/// One match produces a [`Match`] (the higher-level result with emitted spans),
80 +
/// which wraps the underlying [`RegexMatch`] (raw capture positions).
81 +
#[derive(Debug)]
82 +
pub(super) struct Pattern {
83 +
    /// Stable rule id used to reopen this pattern from line state.
84 +
    id: usize,
85 +
    /// Scope assigned by this pattern.
86 +
    pub(super) scope: Scope,
87 +
    /// Per-slot capture-scope mappings.
88 +
    pub(super) captures: PatternCaptures,
89 +
    /// Match form (single match or begin/end pair).
90 +
    body: PatternBody,
91 +
    /// Patterns that may match inside this one.
92 +
    pub(super) nested: PatternSet,
93 +
}
94 +
95 +
/// Begin/end rule pushed onto the parser stack and held across line boundaries.
96 +
///
97 +
/// The matching [`Pattern`] is recovered through `Grammar::pattern_by_rule`, so
98 +
/// the open rule itself only stores what cannot be derived from the grammar:
99 +
/// the rule's id and the resolved end-regex source for dynamic end patterns.
100 +
#[derive(Clone, Debug, Eq, PartialEq)]
101 +
pub(super) struct OpenRule {
102 +
    /// Compiled rule id.
103 +
    pub(super) rule_id: usize,
104 +
    /// Resolved end-regex source (populated only for dynamic end patterns).
105 +
    pub(super) dynamic_end: Option<String>,
106 +
}
107 +
108 +
/// Result of one pattern matching in a line: the byte range it covered, the
109 +
/// scope spans it emitted, and any begin/end rule it pushed onto the stack.
110 +
pub(super) struct Match {
111 +
    /// Start byte of the match in the line.
112 +
    pub(super) start: usize,
113 +
    /// End byte of the match (or of the same-line close, for begin/end rules).
114 +
    end: usize,
115 +
    /// Scope spans emitted by the match and its captures.
116 +
    pub(super) spans: Vec<ScopeSpan>,
117 +
    /// New rule pushed onto the parser stack, when this match opened one.
118 +
    open_rule: Option<OpenRule>,
119 +
}
120 +
121 +
/// Raw regex hit: byte range plus the positions of any retained capture groups.
122 +
pub(super) struct RegexMatch {
123 +
    /// Start byte of the full regex match.
124 +
    pub(super) start: usize,
125 +
    /// End byte of the full regex match.
126 +
    end: usize,
127 +
    /// Byte ranges for capture groups by capture index, when captures were retained.
128 +
    captures: Vec<Option<(usize, usize)>>,
129 +
}
130 +
131 +
/// Builder-time table that assigns stable ids to scope names.
132 +
#[derive(Default)]
133 +
pub(super) struct ScopeInterner {
134 +
    /// Interned scope names in id order.
135 +
    pub(super) scopes: Vec<String>,
136 +
    /// Lookup table from scope name to interned id.
137 +
    ids: BTreeMap<String, ScopeId>,
138 +
}
139 +
140 +
/// End match found before any nested match on the current line.
141 +
struct EndOnLine {
142 +
    /// The regex match that closed the rule.
143 +
    matched: RegexMatch,
144 +
    /// Spans emitted by nested patterns scanned while looking for the end.
145 +
    spans: Vec<ScopeSpan>,
146 +
}
147 +
148 +
impl Scope {
149 +
    /// Builds a scope from an optional raw TextMate name.
150 +
    fn from_raw(name: Option<&str>, interner: &mut ScopeInterner) -> Self {
151 +
        let Some(name) = name else { return Self::None };
152 +
        let id = interner.intern(name);
153 +
        if name.starts_with("meta.structure.") {
154 +
            Self::Structural(id)
155 +
        } else {
156 +
            Self::Visible(id)
157 +
        }
158 +
    }
159 +
160 +
    /// Returns the interned scope id, regardless of visibility.
161 +
    pub(super) fn id(self) -> Option<ScopeId> {
162 +
        match self {
163 +
            Self::None => None,
164 +
            Self::Visible(id) | Self::Structural(id) => Some(id),
165 +
        }
166 +
    }
167 +
168 +
    /// Pushes a span for this scope's region when it is visible and non-empty.
169 +
    pub(super) fn push_visible(self, spans: &mut Vec<ScopeSpan>, start: usize, end: usize) {
170 +
        if let Self::Visible(scope) = self
171 +
            && start < end
172 +
        {
173 +
            spans.push(ScopeSpan { start, end, scope });
174 +
        }
175 +
    }
176 +
}
177 +
178 +
impl ScopeInterner {
179 +
    /// Returns the id for a scope, inserting it when needed.
180 +
    fn intern(&mut self, scope: &str) -> ScopeId {
181 +
        if let Some(id) = self.ids.get(scope) {
182 +
            return *id;
183 +
        }
184 +
        let id = ScopeId::new(self.scopes.len());
185 +
        self.scopes.push(scope.to_owned());
186 +
        self.ids.insert(scope.to_owned(), id);
187 +
        id
188 +
    }
189 +
190 +
    /// Converts raw capture maps into interned capture scopes.
191 +
    fn captures(&mut self, raw: Option<&BTreeMap<String, RawCapture>>) -> Captures {
192 +
        raw.into_iter()
193 +
            .flat_map(BTreeMap::iter)
194 +
            .filter_map(|(index, capture)| {
195 +
                let index = index.parse().ok()?;
196 +
                let name = capture.name.as_ref()?;
197 +
                let scope = self.intern(name);
198 +
                Some((index, scope))
199 +
            })
200 +
            .collect()
201 +
    }
202 +
}
203 +
204 +
impl PatternSet {
205 +
    /// Creates an empty pattern set.
206 +
    pub(super) fn empty() -> Self {
207 +
        Self {
208 +
            patterns: Vec::new(),
209 +
            regexes: None,
210 +
        }
211 +
    }
212 +
213 +
    /// Compiles raw TextMate patterns into a regex-searchable pattern set.
214 +
    pub(super) fn compile(
215 +
        raw: &RawGrammar,
216 +
        patterns: &[RawPattern],
217 +
        next_rule: &mut usize,
218 +
        depth: usize,
219 +
        interner: &mut ScopeInterner,
220 +
    ) -> Result<Self, Error> {
221 +
        if depth > MAX_INCLUDE_DEPTH {
222 +
            return Ok(Self::empty());
223 +
        }
224 +
        let mut compiled = Vec::new();
225 +
        for pattern in patterns {
226 +
            if let Some(include) = &pattern.include {
227 +
                let expanded = expand_include(raw, include, next_rule, depth, interner)?;
228 +
                compiled.extend(expanded);
229 +
                continue;
230 +
            }
231 +
            match Pattern::compile(raw, pattern, next_rule, depth, interner)? {
232 +
                Compiled::Rule(pattern) => compiled.push(pattern),
233 +
                Compiled::Inline(patterns) => compiled.extend(patterns),
234 +
                Compiled::Skip => {}
235 +
            }
236 +
        }
237 +
        Ok(Self::new(compiled))
238 +
    }
239 +
240 +
    /// Builds a pattern set and its combined regex search set.
241 +
    fn new(patterns: Vec<Pattern>) -> Self {
242 +
        let sources: Vec<&str> = patterns.iter().map(Pattern::search_source).collect();
243 +
        let regexes = (!sources.is_empty())
244 +
            .then(|| RegSet::new(&sources).ok())
245 +
            .flatten();
246 +
247 +
        Self { patterns, regexes }
248 +
    }
249 +
250 +
    /// Walks the rule tree to collect index paths from rule ids back to patterns.
251 +
    pub(super) fn collect_rule_paths(&self, total_rules: usize) -> Vec<Box<[usize]>> {
252 +
        let mut paths = vec![Box::default(); total_rules];
253 +
        let mut current = Vec::new();
254 +
        self.fill_rule_paths(&mut current, &mut paths);
255 +
        paths
256 +
    }
257 +
258 +
    /// Recursively fills `paths[rule_id]` with the index path to that pattern.
259 +
    fn fill_rule_paths(&self, current: &mut Vec<usize>, paths: &mut [Box<[usize]>]) {
260 +
        for (index, pattern) in self.patterns.iter().enumerate() {
261 +
            current.push(index);
262 +
            if let Some(slot) = paths.get_mut(pattern.id) {
263 +
                *slot = current.as_slice().into();
264 +
            }
265 +
            pattern.nested.fill_rule_paths(current, paths);
266 +
            current.pop();
267 +
        }
268 +
    }
269 +
270 +
    /// Returns a nested compiled pattern by index path.
271 +
    pub(super) fn pattern_at(&self, path: &[usize]) -> Option<&Pattern> {
272 +
        let (last, rest) = path.split_last()?;
273 +
        let mut current = self;
274 +
        for &index in rest {
275 +
            current = &current.patterns.get(index)?.nested;
276 +
        }
277 +
        current.patterns.get(*last)
278 +
    }
279 +
280 +
    /// Finds the next pattern match at or after `pos`.
281 +
    pub(super) fn find_next(
282 +
        &self,
283 +
        line: &str,
284 +
        pos: usize,
285 +
        cache: &mut EndRegexCache,
286 +
    ) -> Option<Match> {
287 +
        if pos > line.len() || !line.is_char_boundary(pos) {
288 +
            return None;
289 +
        }
290 +
        let regexes = self.regexes.as_ref()?;
291 +
        let (entry, captures) = regexes.captures_with_options(
292 +
            line,
293 +
            pos,
294 +
            line.len(),
295 +
            RegSetLead::Position,
296 +
            SearchOptions::SEARCH_OPTION_NONE,
297 +
        )?;
298 +
        let pattern = self.patterns.get(entry)?;
299 +
        let regex_match = RegexMatch::from_captures(captures, pattern.needs_match_captures())?;
300 +
301 +
        pattern.match_result(regex_match, line, cache)
302 +
    }
303 +
}
304 +
305 +
/// Expands a single include directive into compiled patterns.
306 +
fn expand_include(
307 +
    raw: &RawGrammar,
308 +
    include: &str,
309 +
    next_rule: &mut usize,
310 +
    depth: usize,
311 +
    interner: &mut ScopeInterner,
312 +
) -> Result<Vec<Pattern>, Error> {
313 +
    // `$base` should reference the outermost grammar across cross-grammar
314 +
    // includes, but the registry does not yet support that, so it is
315 +
    // collapsed to `$self` (the current grammar's root patterns).
316 +
    if include == "$self" || include == "$base" {
317 +
        let set = PatternSet::compile(raw, &raw.patterns, next_rule, depth + 1, interner)?;
318 +
        return Ok(set.patterns);
319 +
    }
320 +
    let Some(name) = include.strip_prefix('#') else {
321 +
        return Ok(Vec::new());
322 +
    };
323 +
    let Some(pattern) = raw
324 +
        .repository
325 +
        .as_ref()
326 +
        .and_then(|repository| repository.get(name))
327 +
    else {
328 +
        return Ok(Vec::new());
329 +
    };
330 +
    let set = PatternSet::compile(
331 +
        raw,
332 +
        std::slice::from_ref(pattern),
333 +
        next_rule,
334 +
        depth + 1,
335 +
        interner,
336 +
    )?;
337 +
    Ok(set.patterns)
338 +
}
339 +
340 +
impl Pattern {
341 +
    /// Compiles one raw pattern.
342 +
    ///
343 +
    /// Returns [`Compiled::Inline`] for grouping patterns (no match/begin-end of
344 +
    /// their own) so the parent set absorbs their nested patterns rather than
345 +
    /// keeping a placeholder node.
346 +
    fn compile(
347 +
        raw: &RawGrammar,
348 +
        pattern: &RawPattern,
349 +
        next_rule: &mut usize,
350 +
        depth: usize,
351 +
        interner: &mut ScopeInterner,
352 +
    ) -> Result<Compiled, Error> {
353 +
        let scope = Scope::from_raw(pattern.name.as_deref(), interner);
354 +
        let nested = PatternSet::compile(
355 +
            raw,
356 +
            pattern.patterns.as_deref().unwrap_or_default(),
357 +
            next_rule,
358 +
            depth + 1,
359 +
            interner,
360 +
        )?;
361 +
362 +
        let body = match (&pattern.match_rule, &pattern.begin, &pattern.end) {
363 +
            (Some(source), _, _) => {
364 +
                if Regex::new(source).is_err() {
365 +
                    return Ok(Compiled::Skip);
366 +
                }
367 +
                PatternBody::Match {
368 +
                    source: source.clone(),
369 +
                }
370 +
            }
371 +
            (None, Some(begin), Some(end)) => {
372 +
                if Regex::new(begin).is_err() {
373 +
                    return Ok(Compiled::Skip);
374 +
                }
375 +
                let Some(end) = EndPattern::compile(end) else {
376 +
                    return Ok(Compiled::Skip);
377 +
                };
378 +
                PatternBody::BeginEnd {
379 +
                    begin_source: begin.clone(),
380 +
                    end,
381 +
                }
382 +
            }
383 +
            _ => return Ok(Compiled::Inline(nested.patterns)),
384 +
        };
385 +
        let id = *next_rule;
386 +
        *next_rule += 1;
387 +
388 +
        Ok(Compiled::Rule(Self {
389 +
            id,
390 +
            scope,
391 +
            captures: PatternCaptures {
392 +
                matched: interner.captures(pattern.captures.as_ref()),
393 +
                begin: interner.captures(pattern.begin_captures.as_ref()),
394 +
                end: interner.captures(pattern.end_captures.as_ref()),
395 +
            },
396 +
            body,
397 +
            nested,
398 +
        }))
399 +
    }
400 +
401 +
    /// Returns the active end regex when reopening this pattern from line state.
402 +
    pub(super) fn resume_end<'pat>(
403 +
        &'pat self,
404 +
        dynamic_end: Option<&str>,
405 +
        cache: &mut EndRegexCache,
406 +
    ) -> Option<EndRegex<'pat>> {
407 +
        let PatternBody::BeginEnd { end, .. } = &self.body else {
408 +
            return None;
409 +
        };
410 +
        end.resume(dynamic_end, cache)
411 +
    }
412 +
413 +
    /// Adds capture-group spans plus the pattern's own scope span for one regex match.
414 +
    pub(super) fn append_match_spans(
415 +
        &self,
416 +
        matched: &RegexMatch,
417 +
        captures: &Captures,
418 +
        spans: &mut Vec<ScopeSpan>,
419 +
    ) {
420 +
        for (index, scope) in captures {
421 +
            if let Some(Some((start, end))) = matched.captures.get(*index)
422 +
                && start < end
423 +
            {
424 +
                spans.push(ScopeSpan {
425 +
                    start: *start,
426 +
                    end: *end,
427 +
                    scope: *scope,
428 +
                });
429 +
            }
430 +
        }
431 +
        if let Some(scope) = self.scope.id() {
432 +
            spans.push(ScopeSpan {
433 +
                start: matched.start,
434 +
                end: matched.end,
435 +
                scope,
436 +
            });
437 +
        }
438 +
        spans.sort_by_key(|span| (span.start, span.end));
439 +
    }
440 +
441 +
    /// Whether match-time regex captures must be retained.
442 +
    fn needs_match_captures(&self) -> bool {
443 +
        match &self.body {
444 +
            PatternBody::Match { .. } => !self.captures.matched.is_empty(),
445 +
            PatternBody::BeginEnd { end, .. } => {
446 +
                !self.captures.begin.is_empty() || end.is_dynamic()
447 +
            }
448 +
        }
449 +
    }
450 +
451 +
    /// The regex source used in the parent set's combined `RegSet`.
452 +
    fn search_source(&self) -> &str {
453 +
        match &self.body {
454 +
            PatternBody::Match { source } => source,
455 +
            PatternBody::BeginEnd { begin_source, .. } => begin_source,
456 +
        }
457 +
    }
458 +
459 +
    /// Builds a [`Match`] for one regex hit, dispatching by body kind.
460 +
    fn match_result(
461 +
        &self,
462 +
        regex_match: RegexMatch,
463 +
        line: &str,
464 +
        cache: &mut EndRegexCache,
465 +
    ) -> Option<Match> {
466 +
        match &self.body {
467 +
            PatternBody::Match { .. } => Some(self.simple_match(regex_match)),
468 +
            PatternBody::BeginEnd { end, .. } => self.begin_match(end, regex_match, line, cache),
469 +
        }
470 +
    }
471 +
472 +
    /// Builds a match for a single-line match rule.
473 +
    fn simple_match(&self, regex_match: RegexMatch) -> Match {
474 +
        let mut spans = Vec::new();
475 +
        self.append_match_spans(&regex_match, &self.captures.matched, &mut spans);
476 +
        Match {
477 +
            start: regex_match.start,
478 +
            end: regex_match.end,
479 +
            spans,
480 +
            open_rule: None,
481 +
        }
482 +
    }
483 +
484 +
    /// Builds a match for a begin/end rule, eagerly closing on the same line if possible.
485 +
    fn begin_match(
486 +
        &self,
487 +
        end_pattern: &EndPattern,
488 +
        begin: RegexMatch,
489 +
        line: &str,
490 +
        cache: &mut EndRegexCache,
491 +
    ) -> Option<Match> {
492 +
        let end_regex = end_pattern.resolve_for_begin(&begin, line, cache)?;
493 +
        let dynamic_end = end_regex.dynamic_source();
494 +
        let same_line_end = self.find_same_line_end(&end_regex, line, begin.end, cache);
495 +
496 +
        let mut spans = Vec::new();
497 +
        self.append_match_spans(&begin, &self.captures.begin, &mut spans);
498 +
499 +
        let (end_byte, open_rule) = if let Some(close) = &same_line_end {
500 +
            self.scope
501 +
                .push_visible(&mut spans, begin.end, close.matched.start);
502 +
            spans.extend(close.spans.iter().copied());
503 +
            self.append_match_spans(&close.matched, &self.captures.end, &mut spans);
504 +
            (close.matched.end, None)
505 +
        } else {
506 +
            // The begin region is already covered by `append_match_spans` above;
507 +
            // the rest of the line is emitted by the tokenizer once this rule
508 +
            // is pushed and the next event is handled inside it.
509 +
            (
510 +
                begin.end,
511 +
                Some(OpenRule {
512 +
                    rule_id: self.id,
513 +
                    dynamic_end,
514 +
                }),
515 +
            )
516 +
        };
517 +
518 +
        Some(Match {
519 +
            start: begin.start,
520 +
            end: end_byte,
521 +
            spans,
522 +
            open_rule,
523 +
        })
524 +
    }
525 +
526 +
    /// Finds the first end match on the line, scanning past nested matches that occur before it.
527 +
    fn find_same_line_end(
528 +
        &self,
529 +
        end: &EndRegex<'_>,
530 +
        line: &str,
531 +
        mut pos: usize,
532 +
        cache: &mut EndRegexCache,
533 +
    ) -> Option<EndOnLine> {
534 +
        let end_regex = end.regex();
535 +
        let end_source = end.source();
536 +
        let capture_end = !self.captures.end.is_empty();
537 +
        let mut spans = Vec::new();
538 +
        loop {
539 +
            let matched = RegexMatch::find(end_regex, line, pos, capture_end)?;
540 +
            // Skip escaped quote-character ends — only `"` and `'` are handled.
541 +
            // Other end-pattern shapes are matched literally without escape awareness.
542 +
            if is_simple_quote(end_source) && is_escaped_at(line, matched.start) {
543 +
                pos = matched.next_pos(line);
544 +
                continue;
545 +
            }
546 +
            let nested_match = self.nested.find_next(line, pos, cache);
547 +
            let Some(nested_match) = nested_match else {
548 +
                return Some(EndOnLine { matched, spans });
549 +
            };
550 +
            if nested_match.start >= matched.start {
551 +
                return Some(EndOnLine { matched, spans });
552 +
            }
553 +
            pos = nested_match.next_pos(line);
554 +
            spans.extend(nested_match.spans);
555 +
        }
556 +
    }
557 +
}
558 +
559 +
/// Whether `source` is a single literal quote pattern.
560 +
fn is_simple_quote(source: &str) -> bool {
561 +
    matches!(source, "\"" | "'")
562 +
}
563 +
564 +
/// Whether the byte at `pos` is preceded by an odd number of backslashes.
565 +
fn is_escaped_at(line: &str, pos: usize) -> bool {
566 +
    if pos > line.len() || !line.is_char_boundary(pos) {
567 +
        return false;
568 +
    }
569 +
    line[..pos]
570 +
        .bytes()
571 +
        .rev()
572 +
        .take_while(|byte| *byte == b'\\')
573 +
        .count()
574 +
        % 2
575 +
        == 1
576 +
}
577 +
578 +
impl Match {
579 +
    /// Returns the next byte position after this match, ensuring forward progress.
580 +
    pub(super) fn next_pos(&self, line: &str) -> usize {
581 +
        next_pos_after(line, self.start, self.end)
582 +
    }
583 +
584 +
    /// Returns the open rule pushed onto the parser stack by this match, if any.
585 +
    pub(super) fn open_rule(&self) -> Option<OpenRule> {
586 +
        self.open_rule.clone()
587 +
    }
588 +
}
589 +
590 +
impl RegexMatch {
591 +
    /// Finds one regex match starting at `pos`.
592 +
    pub(super) fn find(regex: &Regex, line: &str, pos: usize, keep_captures: bool) -> Option<Self> {
593 +
        if pos > line.len() || !line.is_char_boundary(pos) {
594 +
            return None;
595 +
        }
596 +
        let mut region = Region::new();
597 +
        let _ = regex.search_with_options(
598 +
            line,
599 +
            pos,
600 +
            line.len(),
601 +
            SearchOptions::SEARCH_OPTION_NONE,
602 +
            Some(&mut region),
603 +
        )?;
604 +
        let (start, end) = region.pos(0)?;
605 +
        if start > end || end > line.len() {
606 +
            return None;
607 +
        }
608 +
        let captures = if keep_captures {
609 +
            (0..region.len())
610 +
                .map(|index| {
611 +
                    region.pos(index).and_then(|(start, end)| {
612 +
                        (start <= end && end <= line.len()).then_some((start, end))
613 +
                    })
614 +
                })
615 +
                .collect()
616 +
        } else {
617 +
            Vec::new()
618 +
        };
619 +
        Some(Self {
620 +
            start,
621 +
            end,
622 +
            captures,
623 +
        })
624 +
    }
625 +
626 +
    /// Builds a match record from Oniguruma captures.
627 +
    fn from_captures(captures: onig::Captures<'_>, keep_captures: bool) -> Option<Self> {
628 +
        let (start, end) = captures.pos(0)?;
629 +
        let captures = if keep_captures {
630 +
            (0..captures.len())
631 +
                .map(|index| captures.pos(index))
632 +
                .collect()
633 +
        } else {
634 +
            Vec::new()
635 +
        };
636 +
        Some(Self {
637 +
            start,
638 +
            end,
639 +
            captures,
640 +
        })
641 +
    }
642 +
643 +
    /// Returns the next byte position after this regex match.
644 +
    pub(super) fn next_pos(&self, line: &str) -> usize {
645 +
        next_pos_after(line, self.start, self.end)
646 +
    }
647 +
648 +
    /// Returns the captured text for one group, or `None` when the group is unset.
649 +
    pub(super) fn capture_text<'a>(&self, index: usize, line: &'a str) -> Option<&'a str> {
650 +
        let (start, end) = self.captures.get(index)?.as_ref().copied()?;
651 +
        line.get(start..end)
652 +
    }
653 +
654 +
    /// Substitutes this match's captures into a regex template containing
655 +
    /// backslash-prefixed numeric backreferences (`\1`, `\2`, …).
656 +
    ///
657 +
    /// Captured text is regex-escaped before substitution so that metacharacters
658 +
    /// in the source line are matched literally on the next invocation.
659 +
    pub(super) fn expand_backrefs(&self, template: &str, line: &str) -> String {
660 +
        let mut resolved = String::new();
661 +
        let mut chars = template.chars();
662 +
        while let Some(ch) = chars.next() {
663 +
            if ch != '\\' {
664 +
                resolved.push(ch);
665 +
                continue;
666 +
            }
667 +
            let Some(next) = chars.next() else {
668 +
                resolved.push(ch);
669 +
                break;
670 +
            };
671 +
            if let Some(index) = next.to_digit(10)
672 +
                && let Some(text) = self.capture_text(index as usize, line)
673 +
            {
674 +
                push_regex_escaped(&mut resolved, text);
675 +
            } else {
676 +
                resolved.push(ch);
677 +
                resolved.push(next);
678 +
            }
679 +
        }
680 +
        resolved
681 +
    }
682 +
}
683 +
684 +
/// Appends `input` to `out`, escaping any regex metacharacters.
685 +
fn push_regex_escaped(out: &mut String, input: &str) {
686 +
    const META: &[char] = &[
687 +
        '\\', '.', '+', '*', '?', '(', ')', '|', '[', ']', '{', '}', '^', '$',
688 +
    ];
689 +
    for ch in input.chars() {
690 +
        if META.contains(&ch) {
691 +
            out.push('\\');
692 +
        }
693 +
        out.push(ch);
694 +
    }
695 +
}
696 +
697 +
/// Returns a forward-progress position after a possibly-empty regex match.
698 +
fn next_pos_after(line: &str, start: usize, end: usize) -> usize {
699 +
    if end > start {
700 +
        end
701 +
    } else {
702 +
        next_char_boundary(line, start.saturating_add(1))
703 +
    }
704 +
}
705 +
706 +
#[cfg(test)]
707 +
#[allow(clippy::unwrap_used)]
708 +
mod tests {
709 +
    use std::str::FromStr;
710 +
711 +
    use super::*;
712 +
713 +
    #[test]
714 +
    fn invalid_regex_offsets_are_ignored() {
715 +
        let regex = Regex::new("\"").unwrap();
716 +
717 +
        assert!(RegexMatch::find(&regex, r#"      "patterns": ["#, usize::MAX, true).is_none());
718 +
        assert!(RegexMatch::find(&regex, "é", 1, true).is_none());
719 +
    }
720 +
721 +
    #[test]
722 +
    fn regex_match_offsets_are_absolute_after_full_line_search() {
723 +
        let regex = Regex::new("(bar)").unwrap();
724 +
        let matched = RegexMatch::find(&regex, "foobar", 3, true).unwrap();
725 +
726 +
        assert_eq!(matched.start, 3);
727 +
        assert_eq!(matched.end, 6);
728 +
        assert_eq!(matched.captures[1], Some((3, 6)));
729 +
    }
730 +
731 +
    #[test]
732 +
    fn line_tokenizer_caches_dynamic_end_regexes() {
733 +
        let grammar = Grammar::from_str(
734 +
            r#"{
735 +
                "name":"Demo",
736 +
                "scopeName":"source.demo",
737 +
                "patterns":[
738 +
                    {
739 +
                        "begin":"<([A-Za-z.]+)>",
740 +
                        "end":"</\\1>",
741 +
                        "name":"meta.tag.demo"
742 +
                    }
743 +
                ],
744 +
                "repository":{}
745 +
            }"#,
746 +
        )
747 +
        .unwrap();
748 +
        let mut tokenizer = LineTokenizer::new(&grammar);
749 +
        let mut state = LineState::default();
750 +
        let mut spans = Vec::new();
751 +
752 +
        tokenizer.tokenize_line_into(&mut state, "<foo.bar>", &mut spans);
753 +
        assert_eq!(tokenizer.end_regex_cache_len(), 1);
754 +
755 +
        tokenizer.tokenize_line_into(&mut state, "body", &mut spans);
756 +
        assert_eq!(tokenizer.end_regex_cache_len(), 1);
757 +
758 +
        tokenizer.tokenize_line_into(&mut state, "</foo.bar>", &mut spans);
759 +
        assert!(state.is_empty());
760 +
        assert_eq!(tokenizer.end_regex_cache_len(), 1);
761 +
    }
762 +
}
crates/highlight/src/grammar/tokenize.rs added +203 -0
1 +
//! Runtime line tokenization for compiled grammars.
2 +
//!
3 +
//! Each step picks the next event in the line — a fresh root-pattern match, a
4 +
//! nested match inside the currently open begin/end rule, or that rule's end —
5 +
//! emits the spans it produces, and updates the parser state accordingly.
6 +
7 +
use super::end::{EndRegex, EndRegexCache};
8 +
use super::pattern::{Match, OpenRule, Pattern, RegexMatch};
9 +
use super::*;
10 +
11 +
/// Reusable line tokenizer for one compiled grammar.
12 +
///
13 +
/// The tokenizer keeps runtime scratch that is not part of immutable grammar
14 +
/// data, such as dynamically resolved end regexes. Reuse one tokenizer across
15 +
/// a blob or visible range to avoid recompiling those regexes unnecessarily.
16 +
#[derive(Debug)]
17 +
pub struct LineTokenizer<'grammar> {
18 +
    /// Grammar this tokenizer emits scopes for.
19 +
    pub(crate) grammar: &'grammar Grammar,
20 +
    /// Cache of compiled regexes for resolved dynamic end patterns.
21 +
    end_regex_cache: EndRegexCache,
22 +
}
23 +
24 +
impl<'grammar> LineTokenizer<'grammar> {
25 +
    /// Creates a tokenizer for a compiled grammar.
26 +
    pub fn new(grammar: &'grammar Grammar) -> Self {
27 +
        Self {
28 +
            grammar,
29 +
            end_regex_cache: EndRegexCache::new(),
30 +
        }
31 +
    }
32 +
33 +
    /// Clears cached dynamic end regexes while retaining allocations.
34 +
    pub fn clear_caches(&mut self) {
35 +
        self.end_regex_cache.clear();
36 +
    }
37 +
38 +
    /// Tokenizes one line, mutating the caller-owned line state.
39 +
    pub fn tokenize_line(&mut self, state: &mut LineState, line: &str) -> Vec<ScopeSpan> {
40 +
        let mut spans = Vec::new();
41 +
        self.tokenize_line_into(state, line, &mut spans);
42 +
        spans
43 +
    }
44 +
45 +
    /// Tokenizes one line into a caller-owned buffer.
46 +
    pub fn tokenize_line_into(
47 +
        &mut self,
48 +
        state: &mut LineState,
49 +
        line: &str,
50 +
        spans: &mut Vec<ScopeSpan>,
51 +
    ) {
52 +
        spans.clear();
53 +
54 +
        if matches!(self.grammar.kind, GrammarKind::Json) {
55 +
            json::tokenize_line_into(line, spans);
56 +
            return;
57 +
        }
58 +
        let line = trim_line_end(line);
59 +
        let mut pos = 0;
60 +
61 +
        while pos < line.len() {
62 +
            pos = self.advance(state, line, pos, spans);
63 +
        }
64 +
    }
65 +
66 +
    /// Performs one tokenization step and returns the next byte position.
67 +
    fn advance(
68 +
        &mut self,
69 +
        state: &mut LineState,
70 +
        line: &str,
71 +
        pos: usize,
72 +
        spans: &mut Vec<ScopeSpan>,
73 +
    ) -> usize {
74 +
        if let Some(open) = state.stack.last().cloned() {
75 +
            self.advance_inside_open_rule(state, line, pos, spans, open)
76 +
        } else {
77 +
            self.advance_at_root(state, line, pos, spans)
78 +
        }
79 +
    }
80 +
81 +
    /// Advances past one root-level pattern match, or to end of line if there is none.
82 +
    fn advance_at_root(
83 +
        &mut self,
84 +
        state: &mut LineState,
85 +
        line: &str,
86 +
        pos: usize,
87 +
        spans: &mut Vec<ScopeSpan>,
88 +
    ) -> usize {
89 +
        let Some(found) = self
90 +
            .grammar
91 +
            .patterns
92 +
            .find_next(line, pos, &mut self.end_regex_cache)
93 +
        else {
94 +
            return line.len();
95 +
        };
96 +
        let next_pos = found.next_pos(line);
97 +
        let opened = found.open_rule();
98 +
        spans.extend(found.spans);
99 +
        if let Some(opened) = opened {
100 +
            state.stack.push(opened);
101 +
        }
102 +
        next_pos
103 +
    }
104 +
105 +
    /// Advances past one event inside the currently open begin/end rule.
106 +
    fn advance_inside_open_rule(
107 +
        &mut self,
108 +
        state: &mut LineState,
109 +
        line: &str,
110 +
        pos: usize,
111 +
        spans: &mut Vec<ScopeSpan>,
112 +
        open: OpenRule,
113 +
    ) -> usize {
114 +
        let Some(pattern) = self.grammar.pattern_by_rule(open.rule_id) else {
115 +
            state.stack.pop();
116 +
            return pos;
117 +
        };
118 +
        let Some(end) = pattern.resume_end(open.dynamic_end.as_deref(), &mut self.end_regex_cache)
119 +
        else {
120 +
            state.stack.pop();
121 +
            return pos;
122 +
        };
123 +
        let event = self.next_event_inside(pattern, &end, line, pos);
124 +
        event.apply(state, line, pos, spans, pattern)
125 +
    }
126 +
127 +
    /// Finds the next event (nested match, end match, or end of line) inside an open rule.
128 +
    fn next_event_inside(
129 +
        &mut self,
130 +
        pattern: &Pattern,
131 +
        end: &EndRegex<'_>,
132 +
        line: &str,
133 +
        pos: usize,
134 +
    ) -> InsideEvent {
135 +
        let nested = pattern
136 +
            .nested
137 +
            .find_next(line, pos, &mut self.end_regex_cache);
138 +
        let close = RegexMatch::find(end.regex(), line, pos, !pattern.captures.end.is_empty());
139 +
140 +
        match (nested, close) {
141 +
            (Some(nested), Some(close)) if nested.start < close.start => {
142 +
                InsideEvent::Nested(nested)
143 +
            }
144 +
            (_, Some(close)) => InsideEvent::Close(close),
145 +
            (Some(nested), None) => InsideEvent::Nested(nested),
146 +
            (None, None) => InsideEvent::None,
147 +
        }
148 +
    }
149 +
150 +
    /// Returns the number of cached dynamic end regexes (test helper).
151 +
    #[cfg(test)]
152 +
    pub(super) fn end_regex_cache_len(&self) -> usize {
153 +
        self.end_regex_cache.len()
154 +
    }
155 +
}
156 +
157 +
/// One event found inside an open begin/end rule.
158 +
enum InsideEvent {
159 +
    /// Nested pattern matched before the end pattern.
160 +
    Nested(Match),
161 +
    /// End pattern closed the open rule.
162 +
    Close(RegexMatch),
163 +
    /// Neither nested nor end matched on the rest of this line.
164 +
    None,
165 +
}
166 +
167 +
impl InsideEvent {
168 +
    /// Emits the event's spans, updates the parser stack, and returns the next byte position.
169 +
    fn apply(
170 +
        self,
171 +
        state: &mut LineState,
172 +
        line: &str,
173 +
        pos: usize,
174 +
        spans: &mut Vec<ScopeSpan>,
175 +
        pattern: &Pattern,
176 +
    ) -> usize {
177 +
        match self {
178 +
            Self::Close(close) => {
179 +
                pattern.scope.push_visible(spans, pos, close.start);
180 +
                pattern.append_match_spans(&close, &pattern.captures.end, spans);
181 +
                state.stack.pop();
182 +
                close.next_pos(line)
183 +
            }
184 +
            Self::Nested(nested) => {
185 +
                pattern.scope.push_visible(spans, pos, nested.start);
186 +
187 +
                let next_pos = nested.next_pos(line);
188 +
                let opened = nested.open_rule();
189 +
190 +
                spans.extend(nested.spans);
191 +
192 +
                if let Some(opened) = opened {
193 +
                    state.stack.push(opened);
194 +
                }
195 +
                next_pos
196 +
            }
197 +
            Self::None => {
198 +
                pattern.scope.push_visible(spans, pos, line.len());
199 +
                line.len()
200 +
            }
201 +
        }
202 +
    }
203 +
}
crates/highlight/src/json.rs added +180 -0
1 +
//! Fast line-oriented JSON tokenization.
2 +
//!
3 +
//! The TextMate JSON grammar is expensive for large blobs because it drives a
4 +
//! recursive regex stack. This module keeps JSON highlighting bounded and
5 +
//! allocation-light by scanning one line at a time.
6 +
7 +
use crate::{ScopeId, ScopeSpan};
8 +
9 +
/// Scope id for JSON property names.
10 +
pub const PROPERTY_NAME: ScopeId = ScopeId::new(0);
11 +
/// Scope id for JSON string delimiters.
12 +
pub const STRING_PUNCTUATION: ScopeId = ScopeId::new(1);
13 +
/// Scope id for JSON string content.
14 +
pub const STRING: ScopeId = ScopeId::new(2);
15 +
/// Scope id for JSON numbers.
16 +
pub const NUMBER: ScopeId = ScopeId::new(3);
17 +
/// Scope id for JSON constants such as `true`, `false`, and `null`.
18 +
pub const CONSTANT: ScopeId = ScopeId::new(4);
19 +
20 +
/// Scope names emitted by [`tokenize_line_into`].
21 +
pub const SCOPES: &[&str] = &[
22 +
    "support.type.property-name.json",
23 +
    "punctuation.definition.string.json",
24 +
    "string.quoted.double.json",
25 +
    "constant.numeric.json",
26 +
    "constant.language.json",
27 +
];
28 +
29 +
/// Tokenizes one JSON line into caller-owned storage.
30 +
pub fn tokenize_line_into(line: &str, spans: &mut Vec<ScopeSpan>) {
31 +
    spans.clear();
32 +
    let line = line.trim_end_matches(['\r', '\n']);
33 +
    let bytes = line.as_bytes();
34 +
    let mut pos = 0;
35 +
36 +
    while pos < bytes.len() {
37 +
        match bytes[pos] {
38 +
            b'"' => {
39 +
                let end = string_end(bytes, pos + 1);
40 +
                let content_scope = if string_is_key(bytes, end) {
41 +
                    PROPERTY_NAME
42 +
                } else {
43 +
                    STRING
44 +
                };
45 +
                push(spans, pos, pos + 1, STRING_PUNCTUATION);
46 +
                push(spans, pos + 1, end, content_scope);
47 +
48 +
                if end < bytes.len() {
49 +
                    push(spans, end, end + 1, STRING_PUNCTUATION);
50 +
                    pos = end + 1;
51 +
                } else {
52 +
                    pos = end;
53 +
                }
54 +
            }
55 +
            b'-' | b'0'..=b'9' => {
56 +
                let end = number_end(bytes, pos);
57 +
                push(spans, pos, end, NUMBER);
58 +
                pos = end;
59 +
            }
60 +
            b't' if bytes[pos..].starts_with(b"true") => {
61 +
                push(spans, pos, pos + 4, CONSTANT);
62 +
                pos += 4;
63 +
            }
64 +
            b'f' if bytes[pos..].starts_with(b"false") => {
65 +
                push(spans, pos, pos + 5, CONSTANT);
66 +
                pos += 5;
67 +
            }
68 +
            b'n' if bytes[pos..].starts_with(b"null") => {
69 +
                push(spans, pos, pos + 4, CONSTANT);
70 +
                pos += 4;
71 +
            }
72 +
            _ => pos += 1,
73 +
        }
74 +
    }
75 +
}
76 +
77 +
/// Adds a non-empty JSON scope span.
78 +
fn push(spans: &mut Vec<ScopeSpan>, start: usize, end: usize, scope: ScopeId) {
79 +
    if start < end {
80 +
        spans.push(ScopeSpan { start, end, scope });
81 +
    }
82 +
}
83 +
84 +
/// Finds the closing quote for a JSON string, honoring backslash escapes.
85 +
fn string_end(bytes: &[u8], mut pos: usize) -> usize {
86 +
    let mut escaped = false;
87 +
    while pos < bytes.len() {
88 +
        match (bytes[pos], escaped) {
89 +
            (_, true) => escaped = false,
90 +
            (b'\\', false) => escaped = true,
91 +
            (b'"', false) => return pos,
92 +
            _ => {}
93 +
        }
94 +
        pos += 1;
95 +
    }
96 +
    pos
97 +
}
98 +
99 +
/// Returns whether the string ending at `end` is followed by a JSON object colon.
100 +
fn string_is_key(bytes: &[u8], end: usize) -> bool {
101 +
    let mut pos = end.saturating_add(1);
102 +
    while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
103 +
        pos += 1;
104 +
    }
105 +
    pos < bytes.len() && bytes[pos] == b':'
106 +
}
107 +
108 +
/// Returns the byte position after a JSON number-like token.
109 +
fn number_end(bytes: &[u8], mut pos: usize) -> usize {
110 +
    if bytes.get(pos) == Some(&b'-') {
111 +
        pos += 1;
112 +
    }
113 +
    while pos < bytes.len() && bytes[pos].is_ascii_digit() {
114 +
        pos += 1;
115 +
    }
116 +
    if bytes.get(pos) == Some(&b'.') {
117 +
        pos += 1;
118 +
        while pos < bytes.len() && bytes[pos].is_ascii_digit() {
119 +
            pos += 1;
120 +
        }
121 +
    }
122 +
    if matches!(bytes.get(pos), Some(b'e' | b'E')) {
123 +
        pos += 1;
124 +
        if matches!(bytes.get(pos), Some(b'+' | b'-')) {
125 +
            pos += 1;
126 +
        }
127 +
        while pos < bytes.len() && bytes[pos].is_ascii_digit() {
128 +
            pos += 1;
129 +
        }
130 +
    }
131 +
    pos
132 +
}
133 +
134 +
#[cfg(test)]
135 +
mod tests {
136 +
    use super::*;
137 +
138 +
    #[test]
139 +
    fn tokenizes_keys_strings_numbers_and_constants() {
140 +
        let line = r#"  "a": "b\"c", "n": 12.5e-1, "ok": true"#;
141 +
        let mut spans = Vec::new();
142 +
143 +
        tokenize_line_into(line, &mut spans);
144 +
145 +
        assert!(
146 +
            spans
147 +
                .iter()
148 +
                .any(|span| span.scope == PROPERTY_NAME && &line[span.start..span.end] == "a")
149 +
        );
150 +
        assert!(
151 +
            spans
152 +
                .iter()
153 +
                .any(|span| span.scope == STRING && &line[span.start..span.end] == r#"b\"c"#)
154 +
        );
155 +
        assert!(
156 +
            spans
157 +
                .iter()
158 +
                .any(|span| span.scope == NUMBER && &line[span.start..span.end] == "12.5e-1")
159 +
        );
160 +
        assert!(
161 +
            spans
162 +
                .iter()
163 +
                .any(|span| span.scope == CONSTANT && &line[span.start..span.end] == "true")
164 +
        );
165 +
    }
166 +
167 +
    #[test]
168 +
    fn keeps_unterminated_strings_on_the_same_line() {
169 +
        let line = r#"  "a": "unterminated"#;
170 +
        let mut spans = Vec::new();
171 +
172 +
        tokenize_line_into(line, &mut spans);
173 +
174 +
        assert!(
175 +
            spans
176 +
                .iter()
177 +
                .any(|span| span.scope == STRING && &line[span.start..span.end] == "unterminated")
178 +
        );
179 +
    }
180 +
}
crates/highlight/src/lib.rs added +41 -0
1 +
//! Syntax tokenization and theme application.
2 +
//!
3 +
//! The crate keeps expensive work in the load/compile path. TextMate grammars
4 +
//! compile into Oniguruma regex sets, JSON uses a dedicated lexer, scope names
5 +
//! are interned, and the hot line APIs write into caller-owned buffers so
6 +
//! editors and pagers can reuse allocations.
7 +
#![allow(non_local_definitions)]
8 +
#![warn(missing_docs)]
9 +
#![warn(clippy::unwrap_used)]
10 +
#![warn(rustdoc::missing_crate_level_docs)]
11 +
#![warn(rustdoc::broken_intra_doc_links)]
12 +
#![warn(rustdoc::bare_urls)]
13 +
#![deny(unsafe_code)]
14 +
15 +
// `serde` is the local alias for the `microserde` crate; the derive macro emits
16 +
// `microserde::*` paths so the original crate name must remain in scope.
17 +
extern crate serde as microserde;
18 +
19 +
mod blob;
20 +
mod error;
21 +
mod grammar;
22 +
mod raw;
23 +
mod registry;
24 +
mod theme;
25 +
mod util;
26 +
27 +
pub mod json;
28 +
29 +
pub use blob::{BlobHighlighter, LineBuffer, LineTokens, OwnedLineTokens, StyledLine};
30 +
pub use error::Error;
31 +
pub use grammar::{Grammar, GrammarKind, LineState, LineTokenizer, ScopeId, ScopeSpan};
32 +
pub use raw::{RawCapture, RawGrammar, RawPattern, RawStyle, RawTheme, RawThemeRule};
33 +
pub use registry::{GrammarQuery, Registry};
34 +
pub use theme::{FontStyle, Rgb, Style, StyleSpan, Theme};
35 +
36 +
/// Maximum include depth when expanding `$self`, `$base`, and repository rules.
37 +
pub const MAX_INCLUDE_DEPTH: usize = 8;
38 +
39 +
#[cfg(test)]
40 +
#[allow(clippy::unwrap_used)]
41 +
mod tests;
crates/highlight/src/raw.rs added +181 -0
1 +
//! Raw TextMate JSON data structures.
2 +
//!
3 +
//! These types mirror the loose JSON shapes accepted by TextMate and VS Code
4 +
//! grammar/theme files before the crate compiles them into stricter runtime
5 +
//! data. Keeping this layer separate lets parsing tolerate source-file quirks
6 +
//! without leaking those shapes into tokenization and styling code.
7 +
8 +
use std::collections::BTreeMap;
9 +
use std::str::FromStr;
10 +
11 +
use serde::{Deserialize, json as serde_json};
12 +
13 +
use crate::Error;
14 +
15 +
/// A parsed, uncompiled TextMate grammar.
16 +
#[derive(Clone, Debug, Deserialize)]
17 +
pub struct RawGrammar {
18 +
    /// Human-readable display name.
19 +
    #[serde(rename = "displayName")]
20 +
    pub display_name: Option<String>,
21 +
    /// Human-readable grammar name.
22 +
    pub name: String,
23 +
    /// Root scope name.
24 +
    #[serde(rename = "scopeName")]
25 +
    pub scope_name: String,
26 +
    /// File extensions and special file names.
27 +
    #[serde(rename = "fileTypes")]
28 +
    pub file_types: Option<Vec<String>>,
29 +
    /// First-line match expressions, as either a string or string array.
30 +
    #[serde(rename = "firstLineMatch")]
31 +
    pub first_line_match: Option<serde_json::Value>,
32 +
    /// Root patterns.
33 +
    pub patterns: Vec<RawPattern>,
34 +
    /// Named pattern repository.
35 +
    pub repository: Option<BTreeMap<String, RawPattern>>,
36 +
}
37 +
38 +
/// A parsed, uncompiled TextMate pattern.
39 +
#[derive(Clone, Debug, Default, Deserialize)]
40 +
pub struct RawPattern {
41 +
    /// Scope assigned to the match.
42 +
    pub name: Option<String>,
43 +
    /// Single-line match expression.
44 +
    #[serde(rename = "match")]
45 +
    pub match_rule: Option<String>,
46 +
    /// Begin expression for a stateful rule.
47 +
    pub begin: Option<String>,
48 +
    /// End expression for a stateful rule.
49 +
    pub end: Option<String>,
50 +
    /// Nested patterns.
51 +
    pub patterns: Option<Vec<RawPattern>>,
52 +
    /// Include target such as `$self`, `$base`, or `#name`.
53 +
    pub include: Option<String>,
54 +
    /// Match captures.
55 +
    pub captures: Option<BTreeMap<String, RawCapture>>,
56 +
    /// Begin captures.
57 +
    #[serde(rename = "beginCaptures")]
58 +
    pub begin_captures: Option<BTreeMap<String, RawCapture>>,
59 +
    /// End captures.
60 +
    #[serde(rename = "endCaptures")]
61 +
    pub end_captures: Option<BTreeMap<String, RawCapture>>,
62 +
}
63 +
64 +
/// A parsed, uncompiled TextMate capture.
65 +
#[derive(Clone, Debug, Deserialize)]
66 +
pub struct RawCapture {
67 +
    /// Scope assigned to the captured group.
68 +
    pub name: Option<String>,
69 +
}
70 +
71 +
/// A parsed, uncompiled TextMate theme.
72 +
#[derive(Clone, Debug, Deserialize)]
73 +
pub struct RawTheme {
74 +
    /// Theme name.
75 +
    pub name: String,
76 +
    /// TextMate theme settings.
77 +
    pub settings: Option<Vec<RawThemeRule>>,
78 +
    /// VS Code token color rules.
79 +
    #[serde(rename = "tokenColors")]
80 +
    pub token_colors: Option<Vec<RawThemeRule>>,
81 +
}
82 +
83 +
/// One parsed TextMate theme rule.
84 +
#[derive(Clone, Debug, Deserialize)]
85 +
pub struct RawThemeRule {
86 +
    /// Optional selector string or selector array.
87 +
    pub scope: Option<serde_json::Value>,
88 +
    /// Style settings.
89 +
    pub settings: RawStyle,
90 +
}
91 +
92 +
/// Parsed TextMate style settings.
93 +
#[derive(Clone, Debug, Default, Deserialize)]
94 +
pub struct RawStyle {
95 +
    /// Foreground color as `#rrggbb`.
96 +
    pub foreground: Option<String>,
97 +
    /// Space-separated text style flags.
98 +
    #[serde(rename = "fontStyle")]
99 +
    pub font_style: Option<String>,
100 +
}
101 +
102 +
impl RawGrammar {
103 +
    /// Parses a raw grammar from JSON.
104 +
    pub fn parse(input: &str) -> Result<Self, Error> {
105 +
        input.parse()
106 +
    }
107 +
}
108 +
109 +
impl FromStr for RawGrammar {
110 +
    type Err = Error;
111 +
112 +
    fn from_str(input: &str) -> Result<Self, Self::Err> {
113 +
        serde_json::from_str(input).map_err(|_| Error::InvalidGrammar)
114 +
    }
115 +
}
116 +
117 +
impl RawTheme {
118 +
    /// Parses a raw theme from JSON.
119 +
    pub fn parse(input: &str) -> Result<Self, Error> {
120 +
        input.parse()
121 +
    }
122 +
}
123 +
124 +
impl FromStr for RawTheme {
125 +
    type Err = Error;
126 +
127 +
    fn from_str(input: &str) -> Result<Self, Self::Err> {
128 +
        serde_json::from_str(input).map_err(|_| Error::InvalidTheme)
129 +
    }
130 +
}
131 +
132 +
impl RawThemeRule {
133 +
    /// Returns normalized selector strings from a TextMate `scope` value.
134 +
    pub(crate) fn scope_selectors(&self) -> Vec<String> {
135 +
        let Some(scope) = self.scope.as_ref() else {
136 +
            return Vec::new();
137 +
        };
138 +
        let mut selectors = Vec::new();
139 +
        match scope {
140 +
            serde_json::Value::String(scope) => push_selectors(scope, &mut selectors),
141 +
            serde_json::Value::Array(scopes) => {
142 +
                for scope in scopes {
143 +
                    if let serde_json::Value::String(scope) = scope {
144 +
                        push_selectors(scope, &mut selectors);
145 +
                    }
146 +
                }
147 +
            }
148 +
            _ => {}
149 +
        }
150 +
        selectors
151 +
    }
152 +
}
153 +
154 +
/// Normalizes `firstLineMatch` from TextMate's string-or-array shape.
155 +
pub(crate) fn first_line_patterns(value: Option<&serde_json::Value>) -> Vec<String> {
156 +
    match value {
157 +
        Some(serde_json::Value::String(pattern)) => vec![pattern.clone()],
158 +
        Some(serde_json::Value::Array(values)) => values
159 +
            .iter()
160 +
            .filter_map(|value| {
161 +
                if let serde_json::Value::String(pattern) = value {
162 +
                    Some(pattern.clone())
163 +
                } else {
164 +
                    None
165 +
                }
166 +
            })
167 +
            .collect(),
168 +
        _ => Vec::new(),
169 +
    }
170 +
}
171 +
172 +
/// Splits a comma-separated TextMate selector list.
173 +
fn push_selectors(input: &str, selectors: &mut Vec<String>) {
174 +
    selectors.extend(
175 +
        input
176 +
            .split(',')
177 +
            .map(str::trim)
178 +
            .filter(|selector| !selector.is_empty())
179 +
            .map(str::to_owned),
180 +
    );
181 +
}
crates/highlight/src/registry.rs added +123 -0
1 +
//! Grammar and theme registry.
2 +
//!
3 +
//! A registry is the lookup layer between user-facing names, file paths, first
4 +
//! lines, and the compiled grammars/themes used by the highlighter. It keeps
5 +
//! inference policy out of tokenization so callers can load syntaxes once and
6 +
//! cheaply select the right one for each buffer.
7 +
8 +
use std::path::Path;
9 +
use std::str::FromStr;
10 +
11 +
use crate::Error;
12 +
use crate::grammar::{Grammar, PLAIN_TEXT_NAME};
13 +
use crate::theme::Theme;
14 +
15 +
/// A reusable registry of compiled grammars and themes.
16 +
#[derive(Debug, Default)]
17 +
pub struct Registry {
18 +
    /// Registered grammars.
19 +
    pub grammars: Vec<Grammar>,
20 +
    /// Registered themes.
21 +
    pub themes: Vec<Theme>,
22 +
}
23 +
24 +
/// Inputs used to select a grammar from a registry.
25 +
#[derive(Clone, Copy, Debug, Default)]
26 +
pub struct GrammarQuery<'a> {
27 +
    /// Explicit syntax name, root scope, extension, or file-type alias.
28 +
    pub syntax: Option<&'a str>,
29 +
    /// Source path used for file-name and extension inference.
30 +
    pub path: Option<&'a Path>,
31 +
    /// First source line used for shebang and modeline inference.
32 +
    pub first_line: Option<&'a str>,
33 +
}
34 +
35 +
impl Registry {
36 +
    /// Creates an empty registry.
37 +
    pub fn new() -> Self {
38 +
        Self::default()
39 +
    }
40 +
41 +
    /// Creates an empty registry with a plain-text fallback grammar.
42 +
    pub fn with_plain_text() -> Self {
43 +
        let mut registry = Self::new();
44 +
        registry.add_grammar(Grammar::plain_text());
45 +
        registry
46 +
    }
47 +
48 +
    /// Creates an empty registry with the built-in fast grammars.
49 +
    pub fn with_builtin_syntaxes() -> Self {
50 +
        let mut registry = Self::with_plain_text();
51 +
        registry.add_grammar(Grammar::json());
52 +
        registry
53 +
    }
54 +
55 +
    /// Adds a compiled grammar.
56 +
    pub fn add_grammar(&mut self, grammar: Grammar) {
57 +
        self.grammars.push(grammar);
58 +
    }
59 +
60 +
    /// Adds the dedicated fast JSON grammar.
61 +
    pub fn add_json(&mut self) {
62 +
        self.add_grammar(Grammar::json());
63 +
    }
64 +
65 +
    /// Parses, compiles, and adds a grammar from JSON.
66 +
    pub fn add_grammar_json(&mut self, input: &str) -> Result<(), Error> {
67 +
        let grammar = Grammar::from_str(input)?;
68 +
        self.add_grammar(grammar);
69 +
        Ok(())
70 +
    }
71 +
72 +
    /// Adds a compiled theme.
73 +
    pub fn add_theme(&mut self, theme: Theme) {
74 +
        self.themes.push(theme);
75 +
    }
76 +
77 +
    /// Parses, compiles, and adds a theme from JSON.
78 +
    pub fn add_theme_json(&mut self, input: &str) -> Result<(), Error> {
79 +
        let theme = Theme::from_str(input)?;
80 +
        self.add_theme(theme);
81 +
        Ok(())
82 +
    }
83 +
84 +
    /// Finds a grammar by name, root scope, extension, or file-type alias.
85 +
    pub fn grammar_by_name(&self, name: &str) -> Result<&Grammar, Error> {
86 +
        self.grammars
87 +
            .iter()
88 +
            .find(|grammar| grammar.matches_name(name))
89 +
            .ok_or_else(|| Error::UnknownSyntax(name.to_owned()))
90 +
    }
91 +
92 +
    /// Finds a theme by name.
93 +
    pub fn theme_by_name(&self, name: &str) -> Result<&Theme, Error> {
94 +
        self.themes
95 +
            .iter()
96 +
            .find(|theme| theme.name.eq_ignore_ascii_case(name))
97 +
            .ok_or_else(|| Error::UnknownTheme(name.to_owned()))
98 +
    }
99 +
100 +
    /// Infers a grammar from explicit syntax, path, extension, and first line.
101 +
    pub fn query(&self, query: GrammarQuery<'_>) -> Result<&Grammar, Error> {
102 +
        if let Some(syntax) = query.syntax {
103 +
            return self.grammar_by_name(syntax);
104 +
        }
105 +
        if let Some(path) = query.path
106 +
            && let Some(grammar) = self
107 +
                .grammars
108 +
                .iter()
109 +
                .find(|grammar| grammar.matches_path(path))
110 +
        {
111 +
            return Ok(grammar);
112 +
        }
113 +
        if let Some(first_line) = query.first_line
114 +
            && let Some(grammar) = self
115 +
                .grammars
116 +
                .iter()
117 +
                .find(|grammar| grammar.matches_first_line(first_line))
118 +
        {
119 +
            return Ok(grammar);
120 +
        }
121 +
        self.grammar_by_name(PLAIN_TEXT_NAME)
122 +
    }
123 +
}
crates/highlight/src/tests.rs added +468 -0
1 +
use std::path::Path;
2 +
use std::str::FromStr;
3 +
4 +
use super::*;
5 +
6 +
fn test_grammar() -> Grammar {
7 +
    Grammar::from_str(
8 +
        r#"{
9 +
            "name":"Test",
10 +
            "scopeName":"source.test",
11 +
            "fileTypes":["test"],
12 +
            "firstLineMatch":"^#!.*test",
13 +
            "patterns":[
14 +
                {"match":"\\blet\\b","name":"keyword.control.test"},
15 +
                {"begin":"/\\*","end":"\\*/","name":"comment.block.test"}
16 +
            ],
17 +
            "repository":{}
18 +
        }"#,
19 +
    )
20 +
    .unwrap()
21 +
}
22 +
23 +
fn test_theme() -> Theme {
24 +
    Theme::from_str(
25 +
        r##"{
26 +
            "name":"Test Theme",
27 +
            "settings":[
28 +
                {"settings":{"foreground":"#010203"}},
29 +
                {"scope":"keyword.control","settings":{"foreground":"#0a0b0c","fontStyle":"bold"}},
30 +
                {"scope":["comment.block.test"],"settings":{"foreground":"#222222","fontStyle":"italic"}}
31 +
            ]
32 +
        }"##,
33 +
    )
34 +
    .unwrap()
35 +
}
36 +
37 +
fn scope_names<'a>(grammar: &'a Grammar, spans: &'a [ScopeSpan]) -> Vec<&'a str> {
38 +
    spans
39 +
        .iter()
40 +
        .filter_map(|span| grammar.scopes.get(span.scope.index()).map(String::as_str))
41 +
        .collect()
42 +
}
43 +
44 +
#[test]
45 +
fn grammar_parses_textmate_keys_and_first_line_match() {
46 +
    let grammar = test_grammar();
47 +
48 +
    assert_eq!(grammar.name, "Test");
49 +
    assert!(grammar.matches_name("test"));
50 +
    assert!(grammar.matches_path(Path::new("main.test")));
51 +
    assert!(grammar.matches_first_line("#!/usr/bin/env test"));
52 +
}
53 +
54 +
#[test]
55 +
fn tokenizer_preserves_multiline_state_incrementally() {
56 +
    let grammar = test_grammar();
57 +
    let mut state = LineState::default();
58 +
    let first = grammar.tokenize_line(&mut state, "let x = /* comment");
59 +
    let second = grammar.tokenize_line(&mut state, "still */ let y = 1");
60 +
61 +
    assert_eq!(state.depth(), 0);
62 +
    assert!(
63 +
        scope_names(&grammar, &first)
64 +
            .iter()
65 +
            .any(|scope| scope.starts_with("keyword.control"))
66 +
    );
67 +
    assert!(
68 +
        scope_names(&grammar, &first)
69 +
            .iter()
70 +
            .any(|scope| scope.starts_with("comment.block"))
71 +
    );
72 +
    assert!(
73 +
        scope_names(&grammar, &second)
74 +
            .iter()
75 +
            .any(|scope| scope.starts_with("comment.block"))
76 +
    );
77 +
    assert!(
78 +
        scope_names(&grammar, &second)
79 +
            .iter()
80 +
            .any(|scope| scope.starts_with("keyword.control"))
81 +
    );
82 +
}
83 +
84 +
#[test]
85 +
fn scoped_nested_rules_keep_state_even_when_container_has_no_scope() {
86 +
    let grammar = Grammar::from_str(
87 +
        r#"{
88 +
            "name":"Test",
89 +
            "scopeName":"source.test",
90 +
            "patterns":[
91 +
                {
92 +
                    "begin":"BEGIN",
93 +
                    "end":"END",
94 +
                    "patterns":[{"match":"\\bx\\b","name":"variable.other.test"}]
95 +
                }
96 +
            ],
97 +
            "repository":{}
98 +
        }"#,
99 +
    )
100 +
    .unwrap();
101 +
    let mut state = LineState::default();
102 +
103 +
    let first = grammar.tokenize_line(&mut state, "BEGIN");
104 +
    assert!(first.is_empty());
105 +
    assert_eq!(state.depth(), 1);
106 +
107 +
    let second = grammar.tokenize_line(&mut state, "x");
108 +
    assert_eq!(state.depth(), 1);
109 +
110 +
    let third = grammar.tokenize_line(&mut state, "END");
111 +
112 +
    assert_eq!(state.depth(), 0);
113 +
    assert!(scope_names(&grammar, &second).contains(&"variable.other.test"));
114 +
    assert!(third.is_empty());
115 +
}
116 +
117 +
#[test]
118 +
fn dynamic_end_backrefs_are_resolved_from_the_begin_match() {
119 +
    let grammar = Grammar::from_str(
120 +
        r#"{
121 +
            "name":"Test",
122 +
            "scopeName":"source.test",
123 +
            "patterns":[
124 +
                {
125 +
                    "begin":"<([A-Za-z]+)>",
126 +
                    "end":"</\\1>",
127 +
                    "name":"meta.tag.test"
128 +
                }
129 +
            ],
130 +
            "repository":{}
131 +
        }"#,
132 +
    )
133 +
    .unwrap();
134 +
    let mut state = LineState::default();
135 +
136 +
    let _ = grammar.tokenize_line(&mut state, "<section>");
137 +
    assert_eq!(state.depth(), 1);
138 +
139 +
    let _ = grammar.tokenize_line(&mut state, "</section>");
140 +
    assert!(state.is_empty());
141 +
}
142 +
143 +
#[test]
144 +
fn dynamic_end_backrefs_escape_captured_regex_metacharacters() {
145 +
    let grammar = Grammar::from_str(
146 +
        r#"{
147 +
            "name":"Test",
148 +
            "scopeName":"source.test",
149 +
            "patterns":[
150 +
                {
151 +
                    "begin":"<([A-Za-z.]+)>",
152 +
                    "end":"</\\1>",
153 +
                    "name":"meta.tag.test"
154 +
                }
155 +
            ],
156 +
            "repository":{}
157 +
        }"#,
158 +
    )
159 +
    .unwrap();
160 +
    let mut state = LineState::default();
161 +
162 +
    let _ = grammar.tokenize_line(&mut state, "<foo.bar>");
163 +
    assert_eq!(state.depth(), 1);
164 +
165 +
    let _ = grammar.tokenize_line(&mut state, "</fooXbar>");
166 +
    assert_eq!(state.depth(), 1);
167 +
168 +
    let _ = grammar.tokenize_line(&mut state, "</foo.bar>");
169 +
    assert!(state.is_empty());
170 +
}
171 +
172 +
#[test]
173 +
fn tokenizer_preserves_left_context_for_lookbehind_matches() {
174 +
    let grammar = Grammar::from_str(
175 +
        r#"{
176 +
            "name":"Test",
177 +
            "scopeName":"source.test",
178 +
            "patterns":[
179 +
                {"match":"foo","name":"keyword.control.test"},
180 +
                {"match":"(?<=foo)bar","name":"entity.name.test"}
181 +
            ],
182 +
            "repository":{}
183 +
        }"#,
184 +
    )
185 +
    .unwrap();
186 +
    let mut state = LineState::default();
187 +
188 +
    let spans = grammar.tokenize_line(&mut state, "foobar");
189 +
    let scopes = scope_names(&grammar, &spans);
190 +
191 +
    assert!(scopes.contains(&"keyword.control.test"));
192 +
    assert!(scopes.contains(&"entity.name.test"));
193 +
}
194 +
195 +
#[test]
196 +
fn nested_patterns_only_match_inside_their_parent_rule() {
197 +
    let grammar = Grammar::from_str(
198 +
        r#"{
199 +
            "name":"Test",
200 +
            "scopeName":"source.test",
201 +
            "patterns":[
202 +
                {
203 +
                    "begin":"\"",
204 +
                    "end":"\"",
205 +
                    "name":"string.quoted.double.test",
206 +
                    "patterns":[{"match":"\\\\.","name":"constant.character.escape.test"}]
207 +
                }
208 +
            ],
209 +
            "repository":{}
210 +
        }"#,
211 +
    )
212 +
    .unwrap();
213 +
    let mut state = LineState::default();
214 +
215 +
    let outside = grammar.tokenize_line(&mut state, r#"outside \n"#);
216 +
    assert!(!scope_names(&grammar, &outside).contains(&"constant.character.escape.test"));
217 +
218 +
    let inside = grammar.tokenize_line(&mut state, r#""inside \n""#);
219 +
    assert!(scope_names(&grammar, &inside).contains(&"constant.character.escape.test"));
220 +
}
221 +
222 +
#[test]
223 +
fn explicit_match_captures_still_emit_capture_scopes() {
224 +
    let grammar = Grammar::from_str(
225 +
        r#"{
226 +
            "name":"Test",
227 +
            "scopeName":"source.test",
228 +
            "patterns":[
229 +
                {
230 +
                    "match":"(foo)(bar)",
231 +
                    "name":"meta.word.test",
232 +
                    "captures":{"1":{"name":"entity.name.function.test"}}
233 +
                }
234 +
            ],
235 +
            "repository":{}
236 +
        }"#,
237 +
    )
238 +
    .unwrap();
239 +
    let mut state = LineState::default();
240 +
241 +
    let spans = grammar.tokenize_line(&mut state, "foobar");
242 +
    let scopes = scope_names(&grammar, &spans);
243 +
244 +
    assert!(scopes.contains(&"meta.word.test"));
245 +
    assert!(scopes.contains(&"entity.name.function.test"));
246 +
}
247 +
248 +
#[test]
249 +
fn line_buffer_reuses_storage_for_incremental_highlighting() {
250 +
    let grammar = test_grammar();
251 +
    let theme = test_theme();
252 +
    let mut state = LineState::default();
253 +
    let mut buffer = LineBuffer::default();
254 +
255 +
    let (scopes, styles) = buffer.highlight(&grammar, &theme, &mut state, "let x = 1");
256 +
257 +
    assert!(scopes.iter().any(
258 +
        |span| grammar.scopes.get(span.scope.index()).map(String::as_str)
259 +
            == Some("keyword.control.test")
260 +
    ));
261 +
    assert!(styles.iter().any(|span| {
262 +
        span.style.foreground
263 +
            == Some(Rgb {
264 +
                r: 10,
265 +
                g: 11,
266 +
                b: 12,
267 +
            })
268 +
    }));
269 +
}
270 +
271 +
#[test]
272 +
fn blob_highlighter_outputs_only_requested_range() {
273 +
    let grammar = test_grammar();
274 +
    let text = "let a\n/* comment\ninside\n*/ let b\nlet c";
275 +
    let mut blob = BlobHighlighter::new(&grammar, text);
276 +
    let mut visited = Vec::new();
277 +
    let mut inside_comment = false;
278 +
279 +
    blob.highlight_range(2..4, |line| {
280 +
        visited.push(line.line_index);
281 +
        if line.line_index == 2 {
282 +
            inside_comment = line.scopes.iter().any(|span| {
283 +
                grammar.scopes.get(span.scope.index()).map(String::as_str)
284 +
                    == Some("comment.block.test")
285 +
            });
286 +
        }
287 +
    });
288 +
289 +
    assert_eq!(visited, vec![2, 3]);
290 +
    assert!(inside_comment);
291 +
    assert!(blob.is_state_cached(2));
292 +
    assert!(blob.is_state_cached(4));
293 +
}
294 +
295 +
#[test]
296 +
fn blob_highlighter_collects_owned_ranges() {
297 +
    let grammar = test_grammar();
298 +
    let mut blob = BlobHighlighter::new(&grammar, "let a\nlet b\n");
299 +
    let lines = blob.highlighted_range(1..3);
300 +
301 +
    assert_eq!(lines.len(), 1);
302 +
    assert_eq!(lines[0].line_index, 1);
303 +
    assert_eq!(lines[0].byte_range, 6..11);
304 +
}
305 +
306 +
#[test]
307 +
fn styled_range_applies_theme_without_returning_unrequested_lines() {
308 +
    let grammar = test_grammar();
309 +
    let theme = test_theme();
310 +
    let mut blob = BlobHighlighter::new(&grammar, "let a\nlet b");
311 +
    let mut styled = Vec::new();
312 +
313 +
    blob.highlight_styled_range(&theme, 1..2, |line| {
314 +
        styled.push((
315 +
            line.line_index,
316 +
            line.styles
317 +
                .iter()
318 +
                .any(|span| span.style.font_style.contains(FontStyle::BOLD)),
319 +
        ));
320 +
    });
321 +
322 +
    assert_eq!(styled, vec![(1, true)]);
323 +
}
324 +
325 +
#[test]
326 +
fn rgb_parses_six_digit_hex_colors() {
327 +
    assert_eq!("#01020a".parse::<Rgb>().unwrap(), Rgb { r: 1, g: 2, b: 10 });
328 +
    assert!("01020a".parse::<Rgb>().is_err());
329 +
    assert!("#01020".parse::<Rgb>().is_err());
330 +
    assert!("#01020x".parse::<Rgb>().is_err());
331 +
}
332 +
333 +
#[test]
334 +
fn font_style_parses_textmate_flags() {
335 +
    let style = "bold italic underline strikethrough unknown"
336 +
        .parse::<FontStyle>()
337 +
        .unwrap();
338 +
339 +
    assert!(style.contains(FontStyle::BOLD));
340 +
    assert!(style.contains(FontStyle::ITALIC));
341 +
    assert!(style.contains(FontStyle::UNDERLINE));
342 +
    assert!(style.contains(FontStyle::STRIKETHROUGH));
343 +
}
344 +
345 +
#[test]
346 +
fn theme_clamps_invalid_utf8_span_boundaries() {
347 +
    let grammar = test_grammar();
348 +
    let theme = test_theme();
349 +
    let keyword = grammar
350 +
        .scopes
351 +
        .iter()
352 +
        .position(|scope| scope == "keyword.control.test")
353 +
        .map(ScopeId::new)
354 +
        .unwrap();
355 +
    let spans = [ScopeSpan {
356 +
        start: 1,
357 +
        end: 2,
358 +
        scope: keyword,
359 +
    }];
360 +
    let styles = theme.style_spans(&grammar, "éx", &spans);
361 +
362 +
    assert_eq!(
363 +
        styles,
364 +
        vec![StyleSpan {
365 +
            start: 0,
366 +
            end: "éx".len(),
367 +
            scope: None,
368 +
            style: theme.default,
369 +
        }]
370 +
    );
371 +
}
372 +
373 +
#[test]
374 +
fn registry_infers_by_path_and_falls_back_to_plain_text() {
375 +
    let mut registry = Registry::with_plain_text();
376 +
    registry.add_grammar(test_grammar());
377 +
    registry.add_theme(test_theme());
378 +
379 +
    assert_eq!(
380 +
        registry
381 +
            .query(GrammarQuery {
382 +
                path: Some(Path::new("main.test")),
383 +
                ..GrammarQuery::default()
384 +
            })
385 +
            .unwrap()
386 +
            .name,
387 +
        "Test"
388 +
    );
389 +
    assert_eq!(
390 +
        registry
391 +
            .query(GrammarQuery {
392 +
                path: Some(Path::new("README")),
393 +
                ..GrammarQuery::default()
394 +
            })
395 +
            .unwrap()
396 +
            .name,
397 +
        crate::grammar::PLAIN_TEXT_NAME
398 +
    );
399 +
    assert_eq!(
400 +
        registry.theme_by_name("test theme").unwrap().name,
401 +
        "Test Theme"
402 +
    );
403 +
}
404 +
405 +
#[test]
406 +
fn json_grammar_uses_dedicated_fast_path() {
407 +
    let grammar = Grammar::json();
408 +
    let mut state = LineState::default();
409 +
    let line = r#"  "a": "b\"c", "n": 12.5e-1, "ok": true"#;
410 +
    let spans = grammar.tokenize_line(&mut state, line);
411 +
412 +
    assert_eq!(grammar.kind, GrammarKind::Json);
413 +
    assert!(state.is_empty());
414 +
    assert!(spans.iter().any(|span| {
415 +
        grammar.scopes.get(span.scope.index()).map(String::as_str)
416 +
            == Some("support.type.property-name.json")
417 +
            && &line[span.start..span.end] == "a"
418 +
    }));
419 +
    assert!(spans.iter().any(|span| {
420 +
        grammar.scopes.get(span.scope.index()).map(String::as_str)
421 +
            == Some("string.quoted.double.json")
422 +
            && &line[span.start..span.end] == r#"b\"c"#
423 +
    }));
424 +
    assert!(spans.iter().any(|span| {
425 +
        grammar.scopes.get(span.scope.index()).map(String::as_str) == Some("constant.numeric.json")
426 +
            && &line[span.start..span.end] == "12.5e-1"
427 +
    }));
428 +
    assert!(spans.iter().any(|span| {
429 +
        grammar.scopes.get(span.scope.index()).map(String::as_str) == Some("constant.language.json")
430 +
            && &line[span.start..span.end] == "true"
431 +
    }));
432 +
}
433 +
434 +
#[test]
435 +
fn json_fast_path_works_with_blob_ranges() {
436 +
    let grammar = Grammar::json();
437 +
    let text = "{\n  \"a\": \"b\",\n  \"n\": 1,\n  \"ok\": false\n}";
438 +
    let mut blob = BlobHighlighter::new(&grammar, text);
439 +
    let mut visited = Vec::new();
440 +
    let mut saw_number = false;
441 +
442 +
    blob.highlight_range(2..4, |line| {
443 +
        visited.push(line.line_index);
444 +
        saw_number |= line.scopes.iter().any(|span| {
445 +
            grammar.scopes.get(span.scope.index()).map(String::as_str)
446 +
                == Some("constant.numeric.json")
447 +
                && &line.text[span.start..span.end] == "1"
448 +
        });
449 +
    });
450 +
451 +
    assert_eq!(visited, vec![2, 3]);
452 +
    assert!(saw_number);
453 +
}
454 +
455 +
#[test]
456 +
fn registry_can_infer_builtin_json_by_path() {
457 +
    let registry = Registry::with_builtin_syntaxes();
458 +
459 +
    let grammar = registry
460 +
        .query(GrammarQuery {
461 +
            path: Some(Path::new("data.json")),
462 +
            ..GrammarQuery::default()
463 +
        })
464 +
        .unwrap();
465 +
466 +
    assert_eq!(grammar.name, "JSON");
467 +
    assert_eq!(grammar.kind, GrammarKind::Json);
468 +
}
crates/highlight/src/theme.rs added +442 -0
1 +
//! Theme compilation and style-span generation.
2 +
//!
3 +
//! Themes resolve TextMate-style selectors into compact [`Style`] values, then
4 +
//! apply those styles to token scope spans one line at a time. The hot paths
5 +
//! reuse caller-owned output buffers and an optional per-grammar style cache so
6 +
//! editors can restyle visible text without allocating for every token.
7 +
8 +
use std::cmp::Reverse;
9 +
use std::{convert::Infallible, ptr, str::FromStr};
10 +
11 +
use crate::Error;
12 +
use crate::grammar::{Grammar, ScopeId, ScopeSpan};
13 +
use crate::raw::{RawStyle, RawTheme};
14 +
use crate::util::{next_char_boundary, previous_char_boundary, trim_line_end};
15 +
16 +
/// Immutable compiled theme data.
17 +
#[derive(Debug)]
18 +
pub struct Theme {
19 +
    /// Theme name.
20 +
    pub name: String,
21 +
    /// Default style for unscoped text.
22 +
    pub default: Style,
23 +
    /// Compiled selector rules.
24 +
    rules: Vec<ThemeRule>,
25 +
}
26 +
27 +
/// One selector-to-style rule compiled from a theme.
28 +
#[derive(Debug)]
29 +
struct ThemeRule {
30 +
    /// TextMate-style scope selector matched against token scopes.
31 +
    selector: String,
32 +
    /// Style applied when the selector matches.
33 +
    style: Style,
34 +
}
35 +
36 +
/// Cached resolved styles indexed by a grammar's scope ids.
37 +
///
38 +
/// The cache is keyed by the addresses of the theme and grammar plus the
39 +
/// grammar's scope count, so a `LineBuffer` can be reused across many lines and
40 +
/// even different grammars without recomputing styles for every token.
41 +
#[derive(Debug, Default)]
42 +
pub(crate) struct StyleCache {
43 +
    /// Identity of the theme, grammar, and scope count this cache was built for.
44 +
    key: Option<CacheKey>,
45 +
    /// Resolved styles indexed by [`ScopeId`].
46 +
    styles: Vec<Style>,
47 +
}
48 +
49 +
/// Identity tuple used to validate a [`StyleCache`].
50 +
type CacheKey = (usize, usize, usize);
51 +
52 +
/// Per-line scratch buffer used while applying a theme.
53 +
#[derive(Debug, Default)]
54 +
pub(crate) struct StyleScratch {
55 +
    /// Sorted byte boundaries that split a line into uniformly styled segments.
56 +
    boundaries: Vec<usize>,
57 +
}
58 +
59 +
/// Byte range for one fully resolved style segment.
60 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61 +
struct Segment {
62 +
    /// Start byte in the line.
63 +
    start: usize,
64 +
    /// End byte in the line.
65 +
    end: usize,
66 +
}
67 +
68 +
/// Fully styled span produced by applying a [`Theme`] to scope spans.
69 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
70 +
pub struct StyleSpan {
71 +
    /// Start byte in the line.
72 +
    pub start: usize,
73 +
    /// End byte in the line.
74 +
    pub end: usize,
75 +
    /// The most specific scope covering this styled span, if any.
76 +
    pub scope: Option<ScopeId>,
77 +
    /// Resolved style.
78 +
    pub style: Style,
79 +
}
80 +
81 +
/// RGB color parsed from a theme.
82 +
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
83 +
pub struct Rgb {
84 +
    /// Red channel.
85 +
    pub r: u8,
86 +
    /// Green channel.
87 +
    pub g: u8,
88 +
    /// Blue channel.
89 +
    pub b: u8,
90 +
}
91 +
92 +
/// Error returned when parsing an RGB color.
93 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
94 +
pub struct ParseRgbError;
95 +
96 +
/// Bitset of font style flags.
97 +
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
98 +
pub struct FontStyle(u8);
99 +
100 +
/// Resolved style for a token.
101 +
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
102 +
pub struct Style {
103 +
    /// Optional foreground color.
104 +
    pub foreground: Option<Rgb>,
105 +
    /// Font style flags.
106 +
    pub font_style: FontStyle,
107 +
}
108 +
109 +
impl Theme {
110 +
    /// Compiles a raw theme.
111 +
    pub fn compile(raw: &RawTheme) -> Self {
112 +
        let mut default = Style::default();
113 +
        let mut rules = Vec::new();
114 +
        let raw_rules = raw.settings.as_deref().or(raw.token_colors.as_deref());
115 +
116 +
        for rule in raw_rules.unwrap_or_default() {
117 +
            let style = Style::from_raw(&rule.settings);
118 +
            let selectors = rule.scope_selectors();
119 +
            if selectors.is_empty() {
120 +
                default = style;
121 +
            } else {
122 +
                rules.extend(
123 +
                    selectors
124 +
                        .into_iter()
125 +
                        .map(|selector| ThemeRule { selector, style }),
126 +
                );
127 +
            }
128 +
        }
129 +
        Self {
130 +
            name: raw.name.clone(),
131 +
            default,
132 +
            rules,
133 +
        }
134 +
    }
135 +
136 +
    /// Parses and compiles a theme from JSON.
137 +
    pub fn parse(input: &str) -> Result<Self, Error> {
138 +
        input.parse()
139 +
    }
140 +
141 +
    /// Resolves a style for a scope string.
142 +
    ///
143 +
    /// The most specific selector wins, with ties broken by longer selectors.
144 +
    pub fn style_for_scope(&self, scope: &str) -> Style {
145 +
        let mut style = self.default;
146 +
        let mut best = 0;
147 +
        for rule in &self.rules {
148 +
            if rule.matches(scope) && rule.selector.len() >= best {
149 +
                best = rule.selector.len();
150 +
                style = rule.style.merge(style);
151 +
            }
152 +
        }
153 +
        style
154 +
    }
155 +
156 +
    /// Applies this theme to scope spans and returns a freshly allocated vector.
157 +
    pub fn style_spans(
158 +
        &self,
159 +
        grammar: &Grammar,
160 +
        line: &str,
161 +
        scopes: &[ScopeSpan],
162 +
    ) -> Vec<StyleSpan> {
163 +
        let mut cache = StyleCache::default();
164 +
        let mut scratch = StyleScratch::default();
165 +
        let mut output = Vec::new();
166 +
167 +
        cache.refresh(self, grammar);
168 +
        self.style_line_into(grammar, line, scopes, &cache, &mut scratch, &mut output);
169 +
        output
170 +
    }
171 +
172 +
    /// Applies this theme one line at a time using caller-owned scratch storage.
173 +
    pub(crate) fn style_line_into(
174 +
        &self,
175 +
        grammar: &Grammar,
176 +
        line: &str,
177 +
        scopes: &[ScopeSpan],
178 +
        cache: &StyleCache,
179 +
        scratch: &mut StyleScratch,
180 +
        output: &mut Vec<StyleSpan>,
181 +
    ) {
182 +
        output.clear();
183 +
        let line = trim_line_end(line);
184 +
        if line.is_empty() {
185 +
            return;
186 +
        }
187 +
        scratch.collect_boundaries(line, scopes);
188 +
189 +
        for segment in scratch.segments() {
190 +
            output.push(self.style_segment(grammar, scopes, cache, segment));
191 +
        }
192 +
    }
193 +
194 +
    /// Resolves a single styled segment from its covering scope spans.
195 +
    fn style_segment(
196 +
        &self,
197 +
        grammar: &Grammar,
198 +
        scopes: &[ScopeSpan],
199 +
        cache: &StyleCache,
200 +
        segment: Segment,
201 +
    ) -> StyleSpan {
202 +
        let Some(span) = segment.best_covering(scopes, grammar) else {
203 +
            return segment.styled(None, self.default);
204 +
        };
205 +
        let style = cache
206 +
            .style_for(span.scope)
207 +
            .unwrap_or_else(|| self.style_for_scope_id(grammar, span.scope));
208 +
        segment.styled(Some(span.scope), style)
209 +
    }
210 +
211 +
    /// Resolves a style for an interned scope id without going through the cache.
212 +
    fn style_for_scope_id(&self, grammar: &Grammar, scope: ScopeId) -> Style {
213 +
        grammar
214 +
            .scopes
215 +
            .get(scope.index())
216 +
            .map_or(self.default, |name| self.style_for_scope(name))
217 +
    }
218 +
}
219 +
220 +
impl FromStr for Theme {
221 +
    type Err = Error;
222 +
223 +
    /// Parses and compiles a theme from JSON.
224 +
    fn from_str(input: &str) -> Result<Self, Self::Err> {
225 +
        let raw = RawTheme::from_str(input)?;
226 +
        Ok(Self::compile(&raw))
227 +
    }
228 +
}
229 +
230 +
impl ThemeRule {
231 +
    /// Returns whether this rule's selector applies to a concrete scope.
232 +
    fn matches(&self, scope: &str) -> bool {
233 +
        scope == self.selector
234 +
            || (scope.len() > self.selector.len()
235 +
                && scope.starts_with(&self.selector)
236 +
                && scope.as_bytes().get(self.selector.len()) == Some(&b'.'))
237 +
    }
238 +
}
239 +
240 +
impl StyleCache {
241 +
    /// Refreshes cached scope styles for a theme and grammar when needed.
242 +
    pub(crate) fn refresh(&mut self, theme: &Theme, grammar: &Grammar) {
243 +
        let key = (
244 +
            ptr::from_ref(theme).addr(),
245 +
            ptr::from_ref(grammar).addr(),
246 +
            grammar.scopes.len(),
247 +
        );
248 +
        if self.key == Some(key) {
249 +
            return;
250 +
        }
251 +
        self.styles.clear();
252 +
        self.styles.extend(
253 +
            grammar
254 +
                .scopes
255 +
                .iter()
256 +
                .map(|scope| theme.style_for_scope(scope)),
257 +
        );
258 +
        self.key = Some(key);
259 +
    }
260 +
261 +
    /// Returns the cached style for an interned scope id, if available.
262 +
    fn style_for(&self, scope: ScopeId) -> Option<Style> {
263 +
        self.styles.get(scope.index()).copied()
264 +
    }
265 +
}
266 +
267 +
impl StyleScratch {
268 +
    /// Clears per-line scratch storage while retaining allocations.
269 +
    pub(crate) fn clear_line(&mut self) {
270 +
        self.boundaries.clear();
271 +
    }
272 +
273 +
    /// Collects sorted byte boundaries for the style segments in a line.
274 +
    fn collect_boundaries(&mut self, line: &str, scopes: &[ScopeSpan]) {
275 +
        self.boundaries.clear();
276 +
        self.boundaries.push(0);
277 +
        self.boundaries.push(line.len());
278 +
279 +
        for span in scopes {
280 +
            let start = next_char_boundary(line, span.start);
281 +
            let end = previous_char_boundary(line, span.end);
282 +
            if start < end {
283 +
                self.boundaries.push(start);
284 +
                self.boundaries.push(end);
285 +
            }
286 +
        }
287 +
        self.boundaries.sort_unstable();
288 +
        self.boundaries.dedup();
289 +
    }
290 +
291 +
    /// Iterates over the non-empty segments produced by the collected boundaries.
292 +
    fn segments(&self) -> impl Iterator<Item = Segment> + '_ {
293 +
        self.boundaries.windows(2).filter_map(|window| {
294 +
            let [start, end] = *window else {
295 +
                return None;
296 +
            };
297 +
            (start < end).then_some(Segment { start, end })
298 +
        })
299 +
    }
300 +
}
301 +
302 +
impl Segment {
303 +
    /// Builds a styled span from this segment.
304 +
    fn styled(self, scope: Option<ScopeId>, style: Style) -> StyleSpan {
305 +
        StyleSpan {
306 +
            start: self.start,
307 +
            end: self.end,
308 +
            scope,
309 +
            style,
310 +
        }
311 +
    }
312 +
313 +
    /// Picks the smallest scope span covering this segment, breaking ties by selector specificity.
314 +
    fn best_covering<'a>(self, spans: &'a [ScopeSpan], grammar: &Grammar) -> Option<&'a ScopeSpan> {
315 +
        spans
316 +
            .iter()
317 +
            .filter(|span| span.start <= self.start && span.end >= self.end)
318 +
            .min_by_key(|span| {
319 +
                let scope_len = grammar
320 +
                    .scopes
321 +
                    .get(span.scope.index())
322 +
                    .map_or(0, String::len);
323 +
                (span.end - span.start, Reverse(scope_len))
324 +
            })
325 +
    }
326 +
}
327 +
328 +
impl FromStr for Rgb {
329 +
    type Err = ParseRgbError;
330 +
331 +
    /// Parses a six-digit hex color of the form `#rrggbb`.
332 +
    fn from_str(input: &str) -> Result<Self, Self::Err> {
333 +
        let hex = input.strip_prefix('#').ok_or(ParseRgbError)?;
334 +
        if hex.len() != 6 {
335 +
            return Err(ParseRgbError);
336 +
        }
337 +
        let r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| ParseRgbError)?;
338 +
        let g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| ParseRgbError)?;
339 +
        let b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| ParseRgbError)?;
340 +
341 +
        Ok(Self { r, g, b })
342 +
    }
343 +
}
344 +
345 +
impl FontStyle {
346 +
    /// Bold text.
347 +
    pub const BOLD: Self = Self(1 << 0);
348 +
    /// Italic text.
349 +
    pub const ITALIC: Self = Self(1 << 1);
350 +
    /// Underlined text.
351 +
    pub const UNDERLINE: Self = Self(1 << 2);
352 +
    /// Strikethrough text.
353 +
    pub const STRIKETHROUGH: Self = Self(1 << 3);
354 +
355 +
    /// Returns an empty font-style set.
356 +
    pub const fn empty() -> Self {
357 +
        Self(0)
358 +
    }
359 +
360 +
    /// Returns true when all flags in `other` are set.
361 +
    pub const fn contains(self, other: Self) -> bool {
362 +
        (self.0 & other.0) == other.0
363 +
    }
364 +
365 +
    /// Adds all flags from `other`.
366 +
    pub fn insert(&mut self, other: Self) {
367 +
        self.0 |= other.0;
368 +
    }
369 +
}
370 +
371 +
impl FromStr for FontStyle {
372 +
    type Err = Infallible;
373 +
374 +
    /// Parses a space-separated list of TextMate font-style flags.
375 +
    fn from_str(input: &str) -> Result<Self, Self::Err> {
376 +
        let mut style = Self::empty();
377 +
        for flag in input.split_whitespace() {
378 +
            match flag {
379 +
                "bold" => style.insert(Self::BOLD),
380 +
                "italic" => style.insert(Self::ITALIC),
381 +
                "underline" => style.insert(Self::UNDERLINE),
382 +
                "strikethrough" => style.insert(Self::STRIKETHROUGH),
383 +
                _ => {}
384 +
            }
385 +
        }
386 +
        Ok(style)
387 +
    }
388 +
}
389 +
390 +
impl Style {
391 +
    /// Builds a runtime style from raw TextMate settings.
392 +
    fn from_raw(raw: &RawStyle) -> Self {
393 +
        let mut style = Self::default();
394 +
        if let Some(foreground) = &raw.foreground {
395 +
            style.foreground = foreground.parse().ok();
396 +
        }
397 +
        if let Some(flags) = &raw.font_style {
398 +
            style.font_style = flags.parse().unwrap_or_else(|error| match error {});
399 +
        }
400 +
        style
401 +
    }
402 +
403 +
    /// Returns `self` overlaid on `base`.
404 +
    pub fn merge(self, base: Self) -> Self {
405 +
        let mut font_style = base.font_style;
406 +
        font_style.insert(self.font_style);
407 +
        Self {
408 +
            foreground: self.foreground.or(base.foreground),
409 +
            font_style,
410 +
        }
411 +
    }
412 +
413 +
    /// Returns this style with a foreground color.
414 +
    pub const fn fg(mut self, color: Rgb) -> Self {
415 +
        self.foreground = Some(color);
416 +
        self
417 +
    }
418 +
419 +
    /// Returns this style with bold enabled.
420 +
    pub fn bold(mut self) -> Self {
421 +
        self.font_style.insert(FontStyle::BOLD);
422 +
        self
423 +
    }
424 +
425 +
    /// Returns this style with italic enabled.
426 +
    pub fn italic(mut self) -> Self {
427 +
        self.font_style.insert(FontStyle::ITALIC);
428 +
        self
429 +
    }
430 +
431 +
    /// Returns this style with underline enabled.
432 +
    pub fn underline(mut self) -> Self {
433 +
        self.font_style.insert(FontStyle::UNDERLINE);
434 +
        self
435 +
    }
436 +
437 +
    /// Returns this style with strikethrough enabled.
438 +
    pub fn strikethrough(mut self) -> Self {
439 +
        self.font_style.insert(FontStyle::STRIKETHROUGH);
440 +
        self
441 +
    }
442 +
}
crates/highlight/src/util.rs added +62 -0
1 +
//! Small shared helpers for text and lookup normalization.
2 +
//!
3 +
//! The highlighter works in byte ranges but must avoid splitting UTF-8 code
4 +
//! points when regex captures or caller ranges land inside a character. This
5 +
//! module also centralizes lowercase lookup-key handling for syntax inference.
6 +
7 +
use std::path::Path;
8 +
9 +
/// Returns the next valid UTF-8 boundary at or after `index`.
10 +
pub(crate) fn next_char_boundary(text: &str, index: usize) -> usize {
11 +
    let mut index = index.min(text.len());
12 +
    while index < text.len() && !text.is_char_boundary(index) {
13 +
        index += 1;
14 +
    }
15 +
    index
16 +
}
17 +
18 +
/// Returns the previous valid UTF-8 boundary at or before `index`.
19 +
pub(crate) fn previous_char_boundary(text: &str, index: usize) -> usize {
20 +
    let mut index = index.min(text.len());
21 +
    while index > 0 && !text.is_char_boundary(index) {
22 +
        index -= 1;
23 +
    }
24 +
    index
25 +
}
26 +
27 +
/// Returns `line` without trailing line terminators.
28 +
#[inline]
29 +
pub(crate) fn trim_line_end(line: &str) -> &str {
30 +
    line.trim_end_matches(['\r', '\n'])
31 +
}
32 +
33 +
/// Returns byte offsets for each source line start.
34 +
pub(crate) fn line_starts(input: &str) -> Vec<usize> {
35 +
    if input.is_empty() {
36 +
        return Vec::new();
37 +
    }
38 +
    let mut starts = vec![0];
39 +
    for (index, byte) in input.bytes().enumerate() {
40 +
        if byte == b'\n' && index + 1 < input.len() {
41 +
            starts.push(index + 1);
42 +
        }
43 +
    }
44 +
    starts
45 +
}
46 +
47 +
/// Lowercases a lookup key.
48 +
#[inline]
49 +
pub(crate) fn key(input: &str) -> String {
50 +
    input.to_ascii_lowercase()
51 +
}
52 +
53 +
/// Returns lowercase syntax lookup keys for a path.
54 +
pub(crate) fn path_keys(path: &Path) -> impl Iterator<Item = String> + '_ {
55 +
    [
56 +
        path.file_name().and_then(|name| name.to_str()),
57 +
        path.extension().and_then(|extension| extension.to_str()),
58 +
    ]
59 +
    .into_iter()
60 +
    .flatten()
61 +
    .map(key)
62 +
}
src/lib.rs +6 -1
1 1
//! Umbrella crate that re-exports the `rustik-tui` facade crate.
2 2
//!
3 3
//! Use `rustik::tui::*` for the full facade API. Enable `widgets` to forward
4 -
//! to `rustik-tui`’s optional `widgets` feature.
4 +
//! to `rustik-tui`’s optional `widgets` feature, or `highlight` to re-export
5 +
//! the `rustik-highlight` parser/highlighter crate.
5 6
//!
6 7
#![deny(unsafe_code)]
7 8
#![warn(missing_docs)]
8 9
#![warn(clippy::unwrap_used)]
9 10
10 11
/// Re-export of the facade crate.
11 12
pub use rustik_tui as tui;
13 +
14 +
/// Re-export of the TextMate grammar parser and highlighter crate.
15 +
#[cfg(feature = "highlight")]
16 +
pub use rustik_highlight as highlight;