highlight: Split textmate scope paths

355417ff843eecb366a0d80ad8a69c577d367237
Treat space-separated TextMate scope names as scope stacks instead of
one interned atom. This lets contentName and capture scopes expose
embedded language and nested selector scopes to the theme resolver.
Alexis Sellier committed ago 1 parent 62683433
crates/highlight/src/grammar/pattern.rs +36 -37
9 9
//! cached for subsequent lines.
10 10
11 11
use super::end::{EndPattern, EndRegex, EndRegexCache};
12 12
use super::*;
13 13
14 -
/// Capture-group index → interned scope id mapping.
15 -
pub(super) type Captures = BTreeMap<usize, ScopeId>;
14 +
/// Capture-group index to scope path mapping.
15 +
pub(super) type Captures = BTreeMap<usize, Scope>;
16 16
17 17
/// A scope assigned by a pattern.
18 -
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18 +
#[derive(Clone, Debug, Eq, PartialEq)]
19 19
pub(super) enum Scope {
20 20
    /// Pattern names no scope.
21 21
    None,
22 22
    /// Pattern names a visible scope that emits spans.
23 -
    Visible(ScopeId),
23 +
    Visible(Vec<ScopeId>),
24 24
    /// Pattern names a structural scope used only to hold parser state.
25 -
    Structural(ScopeId),
25 +
    Structural(Vec<ScopeId>),
26 26
}
27 27
28 28
/// Capture-scope mappings for a pattern's three regex slots.
29 29
#[derive(Debug, Default)]
30 30
pub(super) struct PatternCaptures {
195 195
196 196
impl Scope {
197 197
    /// Builds a scope from an optional raw TextMate name.
198 198
    fn from_raw(name: Option<&str>, interner: &mut ScopeInterner) -> Self {
199 199
        let Some(name) = name else { return Self::None };
200 -
        let id = interner.intern(name);
200 +
        let path = name
201 +
            .split_whitespace()
202 +
            .map(|scope| interner.intern(scope))
203 +
            .collect::<Vec<_>>();
204 +
        if path.is_empty() {
205 +
            return Self::None;
206 +
        }
201 207
        if name.starts_with("meta.structure.") {
202 -
            Self::Structural(id)
208 +
            Self::Structural(path)
203 209
        } else {
204 -
            Self::Visible(id)
210 +
            Self::Visible(path)
205 211
        }
206 212
    }
207 213
208 -
    /// Returns the interned scope id, regardless of visibility.
209 -
    pub(super) fn id(self) -> Option<ScopeId> {
210 -
        match self {
211 -
            Self::None => None,
212 -
            Self::Visible(id) | Self::Structural(id) => Some(id),
213 -
        }
214 +
    /// Returns true when this scope carries parser state.
215 +
    pub(super) fn has_scope(&self) -> bool {
216 +
        !matches!(self, Self::None)
214 217
    }
215 218
216 219
    /// Pushes a span for this scope's region when it is visible and non-empty.
217 -
    pub(super) fn push_visible(self, spans: &mut Vec<ScopeSpan>, start: usize, end: usize) {
218 -
        if let Self::Visible(scope) = self
219 -
            && start < end
220 -
        {
221 -
            spans.push(ScopeSpan { start, end, scope });
220 +
    pub(super) fn push_visible(&self, spans: &mut Vec<ScopeSpan>, start: usize, end: usize) {
221 +
        if let Self::Visible(path) = self {
222 +
            for scope in path {
223 +
                if start < end {
224 +
                    spans.push(ScopeSpan {
225 +
                        start,
226 +
                        end,
227 +
                        scope: *scope,
228 +
                    });
229 +
                }
230 +
            }
222 231
        }
223 232
    }
224 233
225 234
    /// Pushes visible name and content scopes for an inner rule region.
226 235
    pub(super) fn push_content_visible(
227 -
        name: Self,
228 -
        content: Self,
236 +
        name: &Self,
237 +
        content: &Self,
229 238
        spans: &mut Vec<ScopeSpan>,
230 239
        start: usize,
231 240
        end: usize,
232 241
    ) {
233 242
        name.push_visible(spans, start, end);
252 261
        raw.into_iter()
253 262
            .flat_map(BTreeMap::iter)
254 263
            .filter_map(|(index, capture)| {
255 264
                let index = index.parse().ok()?;
256 265
                let name = capture.name.as_ref()?;
257 -
                let scope = self.intern(name);
266 +
                let scope = Scope::from_raw(Some(name), self);
258 267
                Some((index, scope))
259 268
            })
260 269
            .collect()
261 270
    }
262 271
}
468 477
                    begin_source: begin.clone(),
469 478
                    end,
470 479
                }
471 480
            }
472 481
            (None, Some(begin), None, Some(while_rule)) => {
473 -
                if scope.id().is_none() {
482 +
                if !scope.has_scope() {
474 483
                    self.inline_patterns(pattern, compiled, includes)?;
475 484
                    return Ok(());
476 485
                }
477 486
                if Regex::new(begin).is_err() {
478 487
                    return Ok(());
621 630
        &self,
622 631
        matched: &RegexMatch,
623 632
        captures: &Captures,
624 633
        spans: &mut Vec<ScopeSpan>,
625 634
    ) {
626 -
        if let Some(scope) = self.scope.id() {
627 -
            spans.push(ScopeSpan {
628 -
                start: matched.start,
629 -
                end: matched.end,
630 -
                scope,
631 -
            });
632 -
        }
635 +
        self.scope.push_visible(spans, matched.start, matched.end);
633 636
        for (index, scope) in captures {
634 637
            if let Some(Some((start, end))) = matched.captures.get(*index)
635 638
                && start < end
636 639
            {
637 -
                spans.push(ScopeSpan {
638 -
                    start: *start,
639 -
                    end: *end,
640 -
                    scope: *scope,
641 -
                });
640 +
                scope.push_visible(spans, *start, *end);
642 641
            }
643 642
        }
644 643
        spans.sort_by_key(|span| (span.start, span.end));
645 644
    }
646 645
711 710
        let mut spans = Vec::new();
712 711
        self.append_match_spans(&begin, &self.captures.begin, &mut spans);
713 712
714 713
        let (end_byte, open_rule) = if let Some(close) = &same_line_end {
715 714
            Scope::push_content_visible(
716 -
                self.scope,
717 -
                self.content_scope,
715 +
                &self.scope,
716 +
                &self.content_scope,
718 717
                &mut spans,
719 718
                begin.end,
720 719
                close.matched.start,
721 720
            );
722 721
            spans.extend(close.spans.iter().copied());
crates/highlight/src/grammar/tokenize.rs +15 -9
141 141
            pattern
142 142
                .nested
143 143
                .find_next(&self.grammar.pattern_sets, line, pos, &mut self.cache);
144 144
        let Some(nested) = nested else {
145 145
            Scope::push_content_visible(
146 -
                pattern.scope,
147 -
                pattern.content_scope,
146 +
                &pattern.scope,
147 +
                &pattern.content_scope,
148 148
                spans,
149 149
                pos,
150 150
                line.len(),
151 151
            );
152 152
            return line.len();
153 153
        };
154 154
        let next_pos = nested.next_pos_after_open(line);
155 155
        let opened = nested.open_rule();
156 156
157 -
        Scope::push_content_visible(pattern.scope, pattern.content_scope, spans, pos, next_pos);
157 +
        Scope::push_content_visible(
158 +
            &pattern.scope,
159 +
            &pattern.content_scope,
160 +
            spans,
161 +
            pos,
162 +
            next_pos,
163 +
        );
158 164
        spans.extend(nested.spans);
159 165
160 166
        if let Some(opened) = opened {
161 167
            state.stack.push(opened);
162 168
        }
231 237
        pattern: &Pattern,
232 238
    ) -> usize {
233 239
        match self {
234 240
            Self::Close(close) => {
235 241
                Scope::push_content_visible(
236 -
                    pattern.scope,
237 -
                    pattern.content_scope,
242 +
                    &pattern.scope,
243 +
                    &pattern.content_scope,
238 244
                    spans,
239 245
                    pos,
240 246
                    close.start,
241 247
                );
242 248
                pattern.append_match_spans(&close, &pattern.captures.end, spans);
245 251
            }
246 252
            Self::Nested(nested) => {
247 253
                let next_pos = nested.next_pos_after_open(line);
248 254
249 255
                Scope::push_content_visible(
250 -
                    pattern.scope,
251 -
                    pattern.content_scope,
256 +
                    &pattern.scope,
257 +
                    &pattern.content_scope,
252 258
                    spans,
253 259
                    pos,
254 260
                    next_pos,
255 261
                );
256 262
                let opened = nested.open_rule();
262 268
                }
263 269
                next_pos
264 270
            }
265 271
            Self::None => {
266 272
                Scope::push_content_visible(
267 -
                    pattern.scope,
268 -
                    pattern.content_scope,
273 +
                    &pattern.scope,
274 +
                    &pattern.content_scope,
269 275
                    spans,
270 276
                    pos,
271 277
                    line.len(),
272 278
                );
273 279
                line.len()
crates/highlight/src/tests.rs +52 -0
305 305
    assert!(scopes.contains(&"meta.block.test"));
306 306
    assert!(scopes.contains(&"meta.block.content.test"));
307 307
    assert!(scopes.contains(&"variable.other.test"));
308 308
}
309 309
310 +
#[test]
311 +
fn content_name_scope_paths_emit_each_scope() {
312 +
    let grammar = Grammar::from_str(
313 +
        r#"{
314 +
            "name":"Test",
315 +
            "scopeName":"source.test",
316 +
            "patterns":[
317 +
                {
318 +
                    "begin":"\\{",
319 +
                    "end":"\\}",
320 +
                    "name":"meta.block.test",
321 +
                    "contentName":"meta.embedded.block.test source.embedded.test"
322 +
                }
323 +
            ],
324 +
            "repository":{}
325 +
        }"#,
326 +
    )
327 +
    .unwrap();
328 +
    let mut state = LineState::default();
329 +
330 +
    let spans = grammar.tokenize_line(&mut state, "{x}");
331 +
    let scopes = scope_names(&grammar, &spans);
332 +
333 +
    assert!(scopes.contains(&"meta.embedded.block.test"));
334 +
    assert!(scopes.contains(&"source.embedded.test"));
335 +
}
336 +
337 +
#[test]
338 +
fn capture_scope_paths_emit_each_scope() {
339 +
    let grammar = Grammar::from_str(
340 +
        r#"{
341 +
            "name":"Test",
342 +
            "scopeName":"source.test",
343 +
            "patterns":[
344 +
                {
345 +
                    "match":"(x)",
346 +
                    "captures":{"1":{"name":"meta.capture.test variable.other.test"}}
347 +
                }
348 +
            ],
349 +
            "repository":{}
350 +
        }"#,
351 +
    )
352 +
    .unwrap();
353 +
    let mut state = LineState::default();
354 +
355 +
    let spans = grammar.tokenize_line(&mut state, "x");
356 +
    let scopes = scope_names(&grammar, &spans);
357 +
358 +
    assert!(scopes.contains(&"meta.capture.test"));
359 +
    assert!(scopes.contains(&"variable.other.test"));
360 +
}
361 +
310 362
#[test]
311 363
fn line_buffer_reuses_storage_for_incremental_highlighting() {
312 364
    let grammar = test_grammar();
313 365
    let theme = test_theme();
314 366
    let mut state = LineState::default();