rustik-highlight 0.1.0

Rustik code highlighter.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Theme compilation and style-span generation.
//!
//! Themes resolve TextMate-style selectors into compact [`Style`] values, then
//! apply those styles to token scope spans one line at a time. The hot paths
//! reuse caller-owned output buffers and an optional per-grammar style cache so
//! editors can restyle visible text without allocating for every token.

use std::cmp::Reverse;
use std::{convert::Infallible, ptr, str::FromStr};

use crate::Error;
use crate::grammar::{Grammar, ScopeId, ScopeSpan};
use crate::raw::{RawStyle, RawTheme};
use crate::util::{next_char_boundary, previous_char_boundary, trim_line_end};

/// Immutable compiled theme data.
#[derive(Debug)]
pub struct Theme {
    /// Theme name.
    pub name: String,
    /// Default style for unscoped text.
    pub default: Style,
    /// Compiled selector rules.
    rules: Vec<ThemeRule>,
}

/// One selector-to-style rule compiled from a theme.
#[derive(Debug)]
struct ThemeRule {
    /// TextMate-style scope selector matched against token scopes.
    selector: String,
    /// Style applied when the selector matches.
    style: Style,
}

/// Cached resolved styles indexed by a grammar's scope ids.
///
/// The cache is keyed by the addresses of the theme and grammar plus the
/// grammar's scope count, so a `LineBuffer` can be reused across many lines and
/// even different grammars without recomputing styles for every token.
#[derive(Debug, Default)]
pub(crate) struct StyleCache {
    /// Identity of the theme, grammar, and scope count this cache was built for.
    key: Option<CacheKey>,
    /// Resolved styles indexed by [`ScopeId`].
    styles: Vec<Style>,
}

/// Identity tuple used to validate a [`StyleCache`].
type CacheKey = (usize, usize, usize);

/// Per-line scratch buffer used while applying a theme.
#[derive(Debug, Default)]
pub(crate) struct StyleScratch {
    /// Sorted byte boundaries that split a line into uniformly styled segments.
    boundaries: Vec<usize>,
}

/// Byte range for one fully resolved style segment.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Segment {
    /// Start byte in the line.
    start: usize,
    /// End byte in the line.
    end: usize,
}

/// Fully styled span produced by applying a [`Theme`] to scope spans.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StyleSpan {
    /// Start byte in the line.
    pub start: usize,
    /// End byte in the line.
    pub end: usize,
    /// The most specific scope covering this styled span, if any.
    pub scope: Option<ScopeId>,
    /// Resolved style.
    pub style: Style,
}

/// RGB color parsed from a theme.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Rgb {
    /// Red channel.
    pub r: u8,
    /// Green channel.
    pub g: u8,
    /// Blue channel.
    pub b: u8,
}

/// Error returned when parsing an RGB color.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ParseRgbError;

/// Bitset of font style flags.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct FontStyle(u8);

/// Resolved style for a token.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct Style {
    /// Optional foreground color.
    pub foreground: Option<Rgb>,
    /// Font style flags.
    pub font_style: FontStyle,
}

impl Theme {
    /// Compiles a raw theme.
    pub fn compile(raw: &RawTheme) -> Self {
        let mut default = Style::default();
        let mut rules = Vec::new();
        let raw_rules = raw.settings.as_deref().or(raw.token_colors.as_deref());

        for rule in raw_rules.unwrap_or_default() {
            let style = Style::from_raw(&rule.settings);
            let selectors = rule.scope_selectors();
            if selectors.is_empty() {
                default = style;
            } else {
                rules.extend(
                    selectors
                        .into_iter()
                        .map(|selector| ThemeRule { selector, style }),
                );
            }
        }
        Self {
            name: raw.name.clone(),
            default,
            rules,
        }
    }

    /// Parses and compiles a theme from JSON.
    pub fn parse(input: &str) -> Result<Self, Error> {
        input.parse()
    }

    /// Resolves a style for a scope string.
    ///
    /// The most specific selector wins, with ties broken by longer selectors.
    pub fn style_for_scope(&self, scope: &str) -> Style {
        let mut style = self.default;
        let mut best = 0;
        for rule in &self.rules {
            if rule.matches(scope) && rule.selector.len() >= best {
                best = rule.selector.len();
                style = rule.style.merge(style);
            }
        }
        style
    }

    /// Applies this theme to scope spans and returns a freshly allocated vector.
    pub fn style_spans(
        &self,
        grammar: &Grammar,
        line: &str,
        scopes: &[ScopeSpan],
    ) -> Vec<StyleSpan> {
        let mut cache = StyleCache::default();
        let mut scratch = StyleScratch::default();
        let mut output = Vec::new();

        cache.refresh(self, grammar);
        self.style_line_into(grammar, line, scopes, &cache, &mut scratch, &mut output);
        output
    }

    /// Applies this theme one line at a time using caller-owned scratch storage.
    pub(crate) fn style_line_into(
        &self,
        grammar: &Grammar,
        line: &str,
        scopes: &[ScopeSpan],
        cache: &StyleCache,
        scratch: &mut StyleScratch,
        output: &mut Vec<StyleSpan>,
    ) {
        output.clear();
        let line = trim_line_end(line);
        if line.is_empty() {
            return;
        }
        scratch.collect_boundaries(line, scopes);

        for segment in scratch.segments() {
            output.push(self.style_segment(grammar, scopes, cache, segment));
        }
    }

    /// Resolves a single styled segment from its covering scope spans.
    fn style_segment(
        &self,
        grammar: &Grammar,
        scopes: &[ScopeSpan],
        cache: &StyleCache,
        segment: Segment,
    ) -> StyleSpan {
        let Some(span) = segment.best_covering(scopes, grammar) else {
            return segment.styled(None, self.default);
        };
        let style = cache
            .style_for(span.scope)
            .unwrap_or_else(|| self.style_for_scope_id(grammar, span.scope));
        segment.styled(Some(span.scope), style)
    }

    /// Resolves a style for an interned scope id without going through the cache.
    fn style_for_scope_id(&self, grammar: &Grammar, scope: ScopeId) -> Style {
        grammar
            .scopes
            .get(scope.index())
            .map_or(self.default, |name| self.style_for_scope(name))
    }
}

impl FromStr for Theme {
    type Err = Error;

    /// Parses and compiles a theme from JSON.
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let raw = RawTheme::from_str(input)?;
        Ok(Self::compile(&raw))
    }
}

impl ThemeRule {
    /// Returns whether this rule's selector applies to a concrete scope.
    fn matches(&self, scope: &str) -> bool {
        scope == self.selector
            || (scope.len() > self.selector.len()
                && scope.starts_with(&self.selector)
                && scope.as_bytes().get(self.selector.len()) == Some(&b'.'))
    }
}

impl StyleCache {
    /// Refreshes cached scope styles for a theme and grammar when needed.
    pub(crate) fn refresh(&mut self, theme: &Theme, grammar: &Grammar) {
        let key = (
            ptr::from_ref(theme).addr(),
            ptr::from_ref(grammar).addr(),
            grammar.scopes.len(),
        );
        if self.key == Some(key) {
            return;
        }
        self.styles.clear();
        self.styles.extend(
            grammar
                .scopes
                .iter()
                .map(|scope| theme.style_for_scope(scope)),
        );
        self.key = Some(key);
    }

    /// Returns the cached style for an interned scope id, if available.
    fn style_for(&self, scope: ScopeId) -> Option<Style> {
        self.styles.get(scope.index()).copied()
    }
}

impl StyleScratch {
    /// Clears per-line scratch storage while retaining allocations.
    pub(crate) fn clear_line(&mut self) {
        self.boundaries.clear();
    }

    /// Collects sorted byte boundaries for the style segments in a line.
    fn collect_boundaries(&mut self, line: &str, scopes: &[ScopeSpan]) {
        self.boundaries.clear();
        self.boundaries.push(0);
        self.boundaries.push(line.len());

        for span in scopes {
            let start = next_char_boundary(line, span.start);
            let end = previous_char_boundary(line, span.end);
            if start < end {
                self.boundaries.push(start);
                self.boundaries.push(end);
            }
        }
        self.boundaries.sort_unstable();
        self.boundaries.dedup();
    }

    /// Iterates over the non-empty segments produced by the collected boundaries.
    fn segments(&self) -> impl Iterator<Item = Segment> + '_ {
        self.boundaries.windows(2).filter_map(|window| {
            let [start, end] = *window else {
                return None;
            };
            (start < end).then_some(Segment { start, end })
        })
    }
}

impl Segment {
    /// Builds a styled span from this segment.
    fn styled(self, scope: Option<ScopeId>, style: Style) -> StyleSpan {
        StyleSpan {
            start: self.start,
            end: self.end,
            scope,
            style,
        }
    }

    /// Picks the smallest scope span covering this segment, breaking ties by selector specificity.
    fn best_covering<'a>(self, spans: &'a [ScopeSpan], grammar: &Grammar) -> Option<&'a ScopeSpan> {
        spans
            .iter()
            .filter(|span| span.start <= self.start && span.end >= self.end)
            .min_by_key(|span| {
                let scope_len = grammar
                    .scopes
                    .get(span.scope.index())
                    .map_or(0, String::len);
                (span.end - span.start, Reverse(scope_len))
            })
    }
}

impl FromStr for Rgb {
    type Err = ParseRgbError;

    /// Parses a six-digit hex color of the form `#rrggbb`.
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let hex = input.strip_prefix('#').ok_or(ParseRgbError)?;
        if hex.len() != 6 {
            return Err(ParseRgbError);
        }
        let r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| ParseRgbError)?;
        let g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| ParseRgbError)?;
        let b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| ParseRgbError)?;

        Ok(Self { r, g, b })
    }
}

impl FontStyle {
    /// Bold text.
    pub const BOLD: Self = Self(1 << 0);
    /// Italic text.
    pub const ITALIC: Self = Self(1 << 1);
    /// Underlined text.
    pub const UNDERLINE: Self = Self(1 << 2);
    /// Strikethrough text.
    pub const STRIKETHROUGH: Self = Self(1 << 3);

    /// Returns an empty font-style set.
    pub const fn empty() -> Self {
        Self(0)
    }

    /// Returns true when all flags in `other` are set.
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    /// Adds all flags from `other`.
    pub fn insert(&mut self, other: Self) {
        self.0 |= other.0;
    }
}

impl FromStr for FontStyle {
    type Err = Infallible;

    /// Parses a space-separated list of TextMate font-style flags.
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let mut style = Self::empty();
        for flag in input.split_whitespace() {
            match flag {
                "bold" => style.insert(Self::BOLD),
                "italic" => style.insert(Self::ITALIC),
                "underline" => style.insert(Self::UNDERLINE),
                "strikethrough" => style.insert(Self::STRIKETHROUGH),
                _ => {}
            }
        }
        Ok(style)
    }
}

impl Style {
    /// Builds a runtime style from raw TextMate settings.
    fn from_raw(raw: &RawStyle) -> Self {
        let mut style = Self::default();
        if let Some(foreground) = &raw.foreground {
            style.foreground = foreground.parse().ok();
        }
        if let Some(flags) = &raw.font_style {
            style.font_style = flags.parse().unwrap_or_else(|error| match error {});
        }
        style
    }

    /// Returns `self` overlaid on `base`.
    pub fn merge(self, base: Self) -> Self {
        let mut font_style = base.font_style;
        font_style.insert(self.font_style);
        Self {
            foreground: self.foreground.or(base.foreground),
            font_style,
        }
    }

    /// Returns this style with a foreground color.
    pub const fn fg(mut self, color: Rgb) -> Self {
        self.foreground = Some(color);
        self
    }

    /// Returns this style with bold enabled.
    pub fn bold(mut self) -> Self {
        self.font_style.insert(FontStyle::BOLD);
        self
    }

    /// Returns this style with italic enabled.
    pub fn italic(mut self) -> Self {
        self.font_style.insert(FontStyle::ITALIC);
        self
    }

    /// Returns this style with underline enabled.
    pub fn underline(mut self) -> Self {
        self.font_style.insert(FontStyle::UNDERLINE);
        self
    }

    /// Returns this style with strikethrough enabled.
    pub fn strikethrough(mut self) -> Self {
        self.font_style.insert(FontStyle::STRIKETHROUGH);
        self
    }
}