highlight: Resolve grammar includes and injections

49add220432f03ad3eeafdeb634f458fada9ab23
Teach the TextMate compiler to resolve cross-grammar includes from
caller-provided raw grammar dependencies and to compile/apply TextMate
injections at tokenization time.

Wire HTML's embedded CSS and JavaScript dependencies through the
rustik-diff builtin loader so script and style blocks can use the
bundled grammars.

Assisted-by: Codex:gpt-5.5
Alexis Sellier committed ago 1 parent cff4428c
crates/diff/src/bin/rustik-diff/builtins.rs +20 -1
12 12
/// Common syntax grammars loaded by the interactive pager.
13 13
const SYNTAXES: [SyntaxAsset; 12] = [
14 14
    SyntaxAsset {
15 15
        source: syntax::syntaxes::C,
16 16
        file_types: &["c", "h"],
17 +
        dependencies: &[],
17 18
    },
18 19
    SyntaxAsset {
19 20
        source: syntax::syntaxes::CSS,
20 21
        file_types: &["css"],
22 +
        dependencies: &[],
21 23
    },
22 24
    SyntaxAsset {
23 25
        source: syntax::syntaxes::GO,
24 26
        file_types: &["go"],
27 +
        dependencies: &[],
25 28
    },
26 29
    SyntaxAsset {
27 30
        source: syntax::syntaxes::HTML,
28 31
        file_types: &["html", "htm"],
32 +
        dependencies: &[syntax::syntaxes::CSS, syntax::syntaxes::JAVASCRIPT],
29 33
    },
30 34
    SyntaxAsset {
31 35
        source: syntax::syntaxes::JAVASCRIPT,
32 36
        file_types: &["js", "cjs", "mjs"],
37 +
        dependencies: &[],
33 38
    },
34 39
    SyntaxAsset {
35 40
        source: syntax::syntaxes::MAKE,
36 41
        file_types: &["makefile", "mk"],
42 +
        dependencies: &[],
37 43
    },
38 44
    SyntaxAsset {
39 45
        source: syntax::syntaxes::MARKDOWN,
40 46
        file_types: &["md", "markdown", "mdown"],
47 +
        dependencies: &[],
41 48
    },
42 49
    SyntaxAsset {
43 50
        source: syntax::syntaxes::PYTHON,
44 51
        file_types: &["py", "pyw"],
52 +
        dependencies: &[],
45 53
    },
46 54
    SyntaxAsset {
47 55
        source: syntax::syntaxes::RUBY,
48 56
        file_types: &["rb", "rake", "gemspec"],
57 +
        dependencies: &[],
49 58
    },
50 59
    SyntaxAsset {
51 60
        source: syntax::syntaxes::RUST,
52 61
        file_types: &["rs"],
62 +
        dependencies: &[],
53 63
    },
54 64
    SyntaxAsset {
55 65
        source: syntax::syntaxes::SHELL,
56 66
        file_types: &["sh", "bash", "zsh"],
67 +
        dependencies: &[],
57 68
    },
58 69
    SyntaxAsset {
59 70
        source: syntax::syntaxes::TYPESCRIPT,
60 71
        file_types: &["ts", "cts", "mts"],
72 +
        dependencies: &[],
61 73
    },
62 74
];
63 75
64 76
/// Binary-local highlight assets loaded for one diff document.
65 77
pub(super) struct Builtins {
94 106
struct SyntaxAsset {
95 107
    /// TextMate grammar JSON source.
96 108
    source: &'static str,
97 109
    /// File names and extensions recognized by the registry.
98 110
    file_types: &'static [&'static str],
111 +
    /// Raw grammars required by cross-grammar includes in this syntax.
112 +
    dependencies: &'static [&'static str],
99 113
}
100 114
101 115
impl SyntaxAsset {
102 116
    /// Returns whether this syntax matches any path in a diff document.
103 117
    fn matches_document(&self, document: &DiffDocument) -> bool {
136 150
                .any(|existing| existing.eq_ignore_ascii_case(file_type))
137 151
            {
138 152
                raw.file_types.push((*file_type).to_owned());
139 153
            }
140 154
        }
141 -
        syntax::Grammar::compile(&raw)
155 +
        let dependencies = self
156 +
            .dependencies
157 +
            .iter()
158 +
            .map(|source| source.parse())
159 +
            .collect::<Result<Vec<syntax::RawGrammar>, syntax::Error>>()?;
160 +
        syntax::Grammar::compile_with(&raw, &dependencies)
142 161
    }
143 162
}
144 163
145 164
#[cfg(test)]
146 165
mod tests {
crates/highlight/src/grammar.rs +29 -2
16 16
use crate::util::{key, next_char_boundary, path_keys, trim_line_end};
17 17
use crate::{Error, MAX_INCLUDE_DEPTH};
18 18
19 19
mod end;
20 20
mod pattern;
21 +
mod selector;
21 22
mod tokenize;
22 23
23 24
pub use tokenize::LineTokenizer;
24 25
25 -
use pattern::{OpenRule, PatternCompiler, PatternSet, PatternSetId, RuleLocation};
26 +
use pattern::{Injection, OpenRule, PatternCompiler, PatternSet, PatternSetId, RuleLocation};
26 27
27 28
/// Display name for the built-in plain-text fallback grammar.
28 29
pub(crate) const PLAIN_TEXT_NAME: &str = "Plain Text";
29 30
30 31
/// Interned scope identifier.
153 154
    patterns: PatternSetId,
154 155
    /// Arena of compiled pattern sets.
155 156
    pattern_sets: Vec<PatternSet>,
156 157
    /// Direct pattern locations indexed by rule id.
157 158
    rule_locations: Vec<Option<RuleLocation>>,
159 +
    /// Runtime injections applied while tokenizing this grammar.
160 +
    injections: Vec<Injection>,
158 161
}
159 162
160 163
/// Tokenization strategy used by a grammar.
161 164
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
162 165
pub enum GrammarKind {
167 170
}
168 171
169 172
impl Grammar {
170 173
    /// Compiles a raw grammar.
171 174
    pub fn compile(raw: &RawGrammar) -> Result<Self, Error> {
172 -
        let compiled = PatternCompiler::new(raw).compile()?;
175 +
        Self::compile_with(raw, &[])
176 +
    }
177 +
178 +
    /// Compiles a raw grammar with raw cross-grammar include dependencies.
179 +
    pub fn compile_with(raw: &RawGrammar, dependencies: &[RawGrammar]) -> Result<Self, Error> {
180 +
        let compiled = PatternCompiler::new(raw, dependencies).compile()?;
173 181
        let head_match = head_patterns(raw.first_line_match.as_ref())
174 182
            .iter()
175 183
            .map(|pattern| Regex::new(pattern).map_err(|_| Error::InvalidRegex(pattern.clone())))
176 184
            .collect::<Result<Vec<_>, _>>()?;
177 185
186 194
                .collect(),
187 195
            head_match,
188 196
            patterns: compiled.root,
189 197
            pattern_sets: compiled.sets,
190 198
            rule_locations: compiled.rule_locations,
199 +
            injections: compiled.injections,
191 200
            scopes: compiled.scopes,
192 201
            kind: GrammarKind::TextMate,
193 202
        })
194 203
    }
195 204
201 210
            file_types: ["txt".to_owned(), "text".to_owned()].into_iter().collect(),
202 211
            head_match: Vec::new(),
203 212
            patterns: PatternSetId::new(0),
204 213
            pattern_sets: vec![PatternSet::empty()],
205 214
            rule_locations: Vec::new(),
215 +
            injections: Vec::new(),
206 216
            scopes: Vec::new(),
207 217
            kind: GrammarKind::TextMate,
208 218
        }
209 219
    }
210 220
220 230
            file_types: ["json".to_owned()].into_iter().collect(),
221 231
            head_match: Vec::new(),
222 232
            patterns: PatternSetId::new(0),
223 233
            pattern_sets: vec![PatternSet::empty()],
224 234
            rule_locations: Vec::new(),
235 +
            injections: Vec::new(),
225 236
            scopes: json::SCOPES
226 237
                .iter()
227 238
                .map(|scope| (*scope).to_owned())
228 239
                .collect(),
229 240
            kind: GrammarKind::Json,
272 283
        self.pattern_sets
273 284
            .get(location.set.index())?
274 285
            .patterns
275 286
            .get(location.index)
276 287
    }
288 +
289 +
    /// Builds the active scope stack used by injection selectors.
290 +
    fn scope_names_for_state<'grammar>(
291 +
        &'grammar self,
292 +
        state: &LineState,
293 +
        scopes: &mut Vec<&'grammar str>,
294 +
    ) {
295 +
        scopes.clear();
296 +
        scopes.push(&self.scope_name);
297 +
        for open in &state.stack {
298 +
            let Some(pattern) = self.pattern_by_rule(open.rule_id) else {
299 +
                continue;
300 +
            };
301 +
            pattern.extend_scope_names(&self.scopes, scopes);
302 +
        }
303 +
    }
277 304
}
278 305
279 306
impl FromStr for Grammar {
280 307
    type Err = Error;
281 308
crates/highlight/src/grammar/pattern.rs +240 -37
7 7
//! on the same node; static end patterns are precompiled, while dynamic ones
8 8
//! are resolved against the begin match the first time they are needed and
9 9
//! cached for subsequent lines.
10 10
11 11
use super::end::{EndPattern, EndRegex, EndRegexCache};
12 +
use super::selector::ScopeSelector;
12 13
use super::*;
13 14
use crate::raw::truthy_flag;
14 15
15 16
/// Capture-group index to capture metadata mapping.
16 17
pub(super) type Captures = BTreeMap<usize, Capture>;
92 93
    includes: Vec<PatternSetId>,
93 94
    /// Combined RegSet covering each pattern's match or begin source.
94 95
    regexes: Option<RegSet>,
95 96
}
96 97
98 +
/// Compiled injection rule searched against matching scope stacks.
99 +
#[derive(Debug)]
100 +
pub(super) struct Injection {
101 +
    /// Selector that decides when this injection applies.
102 +
    pub(super) selector: ScopeSelector,
103 +
    /// Pattern set searched when the selector matches.
104 +
    pub(super) patterns: PatternSetId,
105 +
}
106 +
97 107
/// One compiled TextMate pattern with its scope, captures, and nested rules.
98 108
///
99 109
/// A [`Pattern`] is what the grammar tokenizer matches against the source text.
100 110
/// One match produces a [`Match`] (the higher-level result with emitted spans),
101 111
/// which wraps the underlying [`RegexMatch`] (raw capture positions).
233 243
    pub(super) sets: Vec<PatternSet>,
234 244
    /// Interned scope names in id order.
235 245
    pub(super) scopes: Vec<String>,
236 246
    /// Direct lookup from rule id to its pattern's arena location.
237 247
    pub(super) rule_locations: Vec<Option<RuleLocation>>,
248 +
    /// Compiled runtime injections.
249 +
    pub(super) injections: Vec<Injection>,
238 250
}
239 251
240 252
/// Direct arena location for a compiled rule.
241 253
#[derive(Clone, Copy, Debug)]
242 254
pub(super) struct RuleLocation {
253 265
    pub(super) scopes: Vec<String>,
254 266
    /// Lookup table from scope name to interned id.
255 267
    ids: BTreeMap<String, ScopeId>,
256 268
}
257 269
270 +
/// Parsed TextMate include target.
271 +
enum IncludeReference {
272 +
    /// `$base`.
273 +
    Base,
274 +
    /// `$self`.
275 +
    SelfReference,
276 +
    /// `#name`.
277 +
    Repository(String),
278 +
    /// `scope.name`.
279 +
    External(String),
280 +
    /// `scope.name#name`.
281 +
    ExternalRepository(String, String),
282 +
}
283 +
284 +
impl IncludeReference {
285 +
    /// Parses a raw include string.
286 +
    fn parse(include: &str) -> Self {
287 +
        if include == "$base" {
288 +
            return Self::Base;
289 +
        }
290 +
        if include == "$self" {
291 +
            return Self::SelfReference;
292 +
        }
293 +
        let Some((scope, name)) = include.split_once('#') else {
294 +
            return Self::External(include.to_owned());
295 +
        };
296 +
        if scope.is_empty() {
297 +
            Self::Repository(name.to_owned())
298 +
        } else {
299 +
            Self::ExternalRepository(scope.to_owned(), name.to_owned())
300 +
        }
301 +
    }
302 +
}
303 +
258 304
/// Compiler for one raw TextMate grammar.
259 305
pub(super) struct PatternCompiler<'raw> {
260 306
    /// Source grammar being compiled.
261 307
    raw: &'raw RawGrammar,
308 +
    /// Raw grammars visible to cross-grammar includes.
309 +
    grammars: BTreeMap<&'raw str, &'raw RawGrammar>,
262 310
    /// Root pattern set, available while compiling `$self` includes.
263 311
    root: PatternSetId,
312 +
    /// Root pattern sets compiled for raw grammars in this arena.
313 +
    roots: BTreeMap<&'raw str, PatternSetId>,
264 314
    /// Compiled pattern-set arena.
265 315
    sets: Vec<PatternSet>,
266 316
    /// Repository entries compiled so far.
267 -
    repository: BTreeMap<String, PatternSetId>,
317 +
    repository: BTreeMap<(&'raw str, String), PatternSetId>,
268 318
    /// Repository include nesting depth, used as a recursion guard.
269 319
    repository_depth: usize,
270 320
    /// Next stable rule id.
271 321
    next_rule: usize,
272 322
    /// Scope-name interner.
310 360
                });
311 361
            }
312 362
        }
313 363
    }
314 364
365 +
    /// Extends `scopes` with every scope name carried by this scope.
366 +
    pub(super) fn extend_names<'grammar>(
367 +
        &self,
368 +
        names: &'grammar [String],
369 +
        scopes: &mut Vec<&'grammar str>,
370 +
    ) {
371 +
        match self {
372 +
            Self::None => {}
373 +
            Self::Visible(path) | Self::Structural(path) => scopes.extend(
374 +
                path.iter()
375 +
                    .filter_map(|scope| names.get(scope.index()).map(String::as_str)),
376 +
            ),
377 +
        }
378 +
    }
379 +
315 380
    /// Pushes visible name and content scopes for an inner rule region.
316 381
    pub(super) fn push_content_visible(
317 382
        name: &Self,
318 383
        content: &Self,
319 384
        spans: &mut Vec<ScopeSpan>,
323 388
        name.push_visible(spans, start, end);
324 389
        content.push_visible(spans, start, end);
325 390
    }
326 391
}
327 392
393 +
impl Pattern {
394 +
    /// Extends `scopes` with this pattern's name and content scope names.
395 +
    pub(super) fn extend_scope_names<'grammar>(
396 +
        &self,
397 +
        names: &'grammar [String],
398 +
        scopes: &mut Vec<&'grammar str>,
399 +
    ) {
400 +
        self.scope.extend_names(names, scopes);
401 +
        self.content_scope.extend_names(names, scopes);
402 +
    }
403 +
}
404 +
328 405
impl Capture {
329 406
    /// Pushes this capture's direct and retokenized spans.
330 407
    fn push_spans(
331 408
        &self,
332 409
        spans: &mut Vec<ScopeSpan>,
484 561
485 562
        pattern.match_result(regex_match, search)
486 563
    }
487 564
}
488 565
489 -
impl PatternCompiler<'_> {
566 +
impl<'raw> PatternCompiler<'raw> {
490 567
    /// Creates a compiler for a raw grammar.
491 -
    pub(super) fn new(raw: &RawGrammar) -> PatternCompiler<'_> {
568 +
    pub(super) fn new(raw: &'raw RawGrammar, dependencies: &'raw [RawGrammar]) -> Self {
569 +
        let mut grammars = BTreeMap::new();
570 +
        for dependency in dependencies {
571 +
            grammars.insert(dependency.scope_name.as_str(), dependency);
572 +
        }
573 +
        grammars.insert(raw.scope_name.as_str(), raw);
492 574
        PatternCompiler {
493 575
            raw,
576 +
            grammars,
494 577
            root: PatternSetId::new(0),
578 +
            roots: BTreeMap::new(),
495 579
            sets: Vec::new(),
496 580
            repository: BTreeMap::new(),
497 581
            repository_depth: 0,
498 582
            next_rule: 0,
499 583
            interner: ScopeInterner::default(),
502 586
503 587
    /// Compiles the grammar's root pattern set and any referenced repository sets.
504 588
    pub(super) fn compile(mut self) -> Result<CompiledPatterns, Error> {
505 589
        let root = self.reserve_set();
506 590
        self.root = root;
507 -
        let root_set = self.compile_patterns(&self.raw.patterns)?;
591 +
        self.roots.insert(self.raw.scope_name.as_str(), root);
592 +
        let root_set = self.compile_patterns(
593 +
            self.raw,
594 +
            &self.raw.patterns,
595 +
            &mut vec![&self.raw.repository],
596 +
        )?;
508 597
        self.assign_set(root, root_set);
598 +
        let injections = self.compile_injections()?;
509 599
        let rule_locations = self.rule_locations();
510 600
511 601
        Ok(CompiledPatterns {
512 602
            root,
513 603
            sets: self.sets,
514 604
            scopes: self.interner.scopes,
515 605
            rule_locations,
606 +
            injections,
516 607
        })
517 608
    }
518 609
519 610
    /// Reserves an empty pattern-set slot and returns its id.
520 611
    fn reserve_set(&mut self) -> PatternSetId {
527 618
    fn assign_set(&mut self, id: PatternSetId, set: PatternSet) {
528 619
        self.sets[id.index()] = set;
529 620
    }
530 621
531 622
    /// Compiles raw TextMate patterns into one pattern set.
532 -
    fn compile_patterns(&mut self, patterns: &[RawPattern]) -> Result<PatternSet, Error> {
623 +
    fn compile_patterns(
624 +
        &mut self,
625 +
        current: &'raw RawGrammar,
626 +
        patterns: &'raw [RawPattern],
627 +
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
628 +
    ) -> Result<PatternSet, Error> {
533 629
        let mut compiled = Vec::new();
534 630
        let mut includes = Vec::new();
535 631
        for pattern in patterns {
536 632
            if let Some(include) = &pattern.include {
537 -
                if let Some(include) = self.compile_include(include)? {
633 +
                if let Some(include) = self.compile_include(current, include, repositories)? {
538 634
                    includes.push(include);
539 635
                }
540 636
                continue;
541 637
            }
542 -
            self.compile_pattern(pattern, &mut compiled, &mut includes)?;
638 +
            self.compile_pattern(current, pattern, repositories, &mut compiled, &mut includes)?;
543 639
        }
544 640
        Ok(PatternSet::new(compiled, includes))
545 641
    }
546 642
547 643
    /// Compiles one raw pattern into the current pattern-set builder.
548 644
    fn compile_pattern(
549 645
        &mut self,
550 -
        pattern: &RawPattern,
646 +
        current: &'raw RawGrammar,
647 +
        pattern: &'raw RawPattern,
648 +
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
551 649
        compiled: &mut Vec<Pattern>,
552 650
        includes: &mut Vec<PatternSetId>,
553 651
    ) -> Result<(), Error> {
554 652
        let scope = Scope::from_raw(pattern.name.as_deref(), &mut self.interner);
555 653
        let body = match (
579 677
                    apply_end_pattern_last: truthy_flag(pattern.apply_end_pattern_last.as_ref()),
580 678
                }
581 679
            }
582 680
            (None, Some(begin), None, Some(while_rule)) => {
583 681
                if !scope.has_scope() {
584 -
                    self.inline_patterns(pattern, compiled, includes)?;
682 +
                    self.inline_patterns(current, pattern, repositories, compiled, includes)?;
585 683
                    return Ok(());
586 684
                }
587 685
                if Regex::new(begin).is_err() {
588 686
                    return Ok(());
589 687
                }
594 692
                    begin_source: begin.clone(),
595 693
                    while_regex,
596 694
                }
597 695
            }
598 696
            _ => {
599 -
                self.inline_patterns(pattern, compiled, includes)?;
697 +
                self.inline_patterns(current, pattern, repositories, compiled, includes)?;
600 698
                return Ok(());
601 699
            }
602 700
        };
603 701
        // Nested children are compiled โ€” and assigned their rule ids โ€” before
604 702
        // this pattern, so every parent has a higher rule id than its children.
605 -
        let nested = self.compile_nested_set(&pattern.patterns)?;
703 +
        let nested = self.compile_nested_set(current, &pattern.patterns, repositories)?;
606 704
        let id = self.next_rule;
607 705
        self.next_rule += 1;
608 706
609 707
        // The slot-specific capture maps fall back to the shared `captures` map.
610 708
        let shared = pattern.captures.as_ref();
611 -
        let matched = self.captures(shared)?;
612 -
        let begin = self.captures(pattern.begin_captures.as_ref().or(shared))?;
613 -
        let end = self.captures(pattern.end_captures.as_ref().or(shared))?;
614 -
        let while_rule = self.captures(pattern.while_captures.as_ref().or(shared))?;
709 +
        let matched = self.captures(current, shared, repositories)?;
710 +
        let begin = self.captures(
711 +
            current,
712 +
            pattern.begin_captures.as_ref().or(shared),
713 +
            repositories,
714 +
        )?;
715 +
        let end = self.captures(
716 +
            current,
717 +
            pattern.end_captures.as_ref().or(shared),
718 +
            repositories,
719 +
        )?;
720 +
        let while_rule = self.captures(
721 +
            current,
722 +
            pattern.while_captures.as_ref().or(shared),
723 +
            repositories,
724 +
        )?;
615 725
616 726
        compiled.push(Pattern {
617 727
            id,
618 728
            scope,
619 729
            content_scope: Scope::from_raw(pattern.content_name.as_deref(), &mut self.interner),
630 740
    }
631 741
632 742
    /// Compiles grouping pattern children directly into the parent builder.
633 743
    fn inline_patterns(
634 744
        &mut self,
635 -
        pattern: &RawPattern,
745 +
        current: &'raw RawGrammar,
746 +
        pattern: &'raw RawPattern,
747 +
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
636 748
        compiled: &mut Vec<Pattern>,
637 749
        includes: &mut Vec<PatternSetId>,
638 750
    ) -> Result<(), Error> {
639 -
        let inline = self.compile_patterns(&pattern.patterns)?;
751 +
        let inline = self.compile_patterns(current, &pattern.patterns, repositories)?;
640 752
        compiled.extend(inline.patterns);
641 753
        includes.extend(inline.includes);
642 754
643 755
        Ok(())
644 756
    }
645 757
646 758
    /// Compiles a nested pattern set into the arena and returns its id.
647 -
    fn compile_nested_set(&mut self, patterns: &[RawPattern]) -> Result<PatternSetId, Error> {
759 +
    fn compile_nested_set(
760 +
        &mut self,
761 +
        current: &'raw RawGrammar,
762 +
        patterns: &'raw [RawPattern],
763 +
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
764 +
    ) -> Result<PatternSetId, Error> {
648 765
        let id = self.reserve_set();
649 -
        let set = self.compile_patterns(patterns)?;
766 +
        let set = self.compile_patterns(current, patterns, repositories)?;
650 767
        self.assign_set(id, set);
651 768
652 769
        Ok(id)
653 770
    }
654 771
655 772
    /// Compiles an include target into a pattern-set reference.
656 -
    fn compile_include(&mut self, include: &str) -> Result<Option<PatternSetId>, Error> {
657 -
        // `$base` should reference the outermost grammar across cross-grammar
658 -
        // includes, but the registry does not yet support that, so it is
659 -
        // collapsed to `$self` (the current grammar's root patterns).
660 -
        if include == "$self" || include == "$base" {
661 -
            return Ok(Some(self.root));
773 +
    fn compile_include(
774 +
        &mut self,
775 +
        current: &'raw RawGrammar,
776 +
        include: &str,
777 +
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
778 +
    ) -> Result<Option<PatternSetId>, Error> {
779 +
        match IncludeReference::parse(include) {
780 +
            IncludeReference::Base => Ok(Some(self.root)),
781 +
            IncludeReference::SelfReference => self.compile_root(current),
782 +
            IncludeReference::Repository(name) => {
783 +
                self.compile_repository_entry(current, &name, repositories)
784 +
            }
785 +
            IncludeReference::External(scope) => {
786 +
                let Some(grammar) = self.grammars.get(scope.as_str()).copied() else {
787 +
                    return Ok(None);
788 +
                };
789 +
                self.compile_external_root(grammar)
790 +
            }
791 +
            IncludeReference::ExternalRepository(scope, name) => {
792 +
                let Some(grammar) = self.grammars.get(scope.as_str()).copied() else {
793 +
                    return Ok(None);
794 +
                };
795 +
                self.compile_external_repository_entry(grammar, &name)
796 +
            }
662 797
        }
663 -
        let Some(name) = include.strip_prefix('#') else {
664 -
            return Ok(None);
665 -
        };
666 -
        self.compile_repository_entry(name)
667 798
    }
668 799
669 -
    /// Compiles one repository entry once and returns its pattern-set id.
670 -
    fn compile_repository_entry(&mut self, name: &str) -> Result<Option<PatternSetId>, Error> {
671 -
        if let Some(id) = self.repository.get(name) {
800 +
    /// Compiles one raw grammar root once and returns its pattern-set id.
801 +
    fn compile_root(&mut self, raw: &'raw RawGrammar) -> Result<Option<PatternSetId>, Error> {
802 +
        if let Some(id) = self.roots.get(raw.scope_name.as_str()) {
672 803
            return Ok(Some(*id));
673 804
        }
805 +
        let id = self.reserve_set();
806 +
        self.roots.insert(raw.scope_name.as_str(), id);
807 +
        let set = self.compile_patterns(raw, &raw.patterns, &mut vec![&raw.repository])?;
808 +
        self.assign_set(id, set);
809 +
        Ok(Some(id))
810 +
    }
811 +
812 +
    /// Compiles one external raw grammar root with an independent include budget.
813 +
    fn compile_external_root(
814 +
        &mut self,
815 +
        raw: &'raw RawGrammar,
816 +
    ) -> Result<Option<PatternSetId>, Error> {
817 +
        let depth = self.repository_depth;
818 +
        self.repository_depth = 0;
819 +
        let root = self.compile_root(raw);
820 +
        self.repository_depth = depth;
821 +
        root
822 +
    }
823 +
824 +
    /// Compiles one external repository entry with an independent include budget.
825 +
    fn compile_external_repository_entry(
826 +
        &mut self,
827 +
        raw: &'raw RawGrammar,
828 +
        name: &str,
829 +
    ) -> Result<Option<PatternSetId>, Error> {
830 +
        let depth = self.repository_depth;
831 +
        self.repository_depth = 0;
832 +
        let entry = self.compile_repository_entry(raw, name, &mut vec![&raw.repository]);
833 +
        self.repository_depth = depth;
834 +
        entry
835 +
    }
836 +
837 +
    /// Compiles one repository entry once and returns its pattern-set id.
838 +
    fn compile_repository_entry(
839 +
        &mut self,
840 +
        current: &'raw RawGrammar,
841 +
        name: &str,
842 +
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
843 +
    ) -> Result<Option<PatternSetId>, Error> {
674 844
        if self.repository_depth > MAX_INCLUDE_DEPTH {
675 845
            return Ok(None);
676 846
        }
677 -
        let Some(pattern) = self.raw.repository.get(name) else {
847 +
        let Some((pattern, top_level)) = repositories.iter().rev().find_map(|repository| {
848 +
            repository.get(name).map(|pattern| {
849 +
                let top_level = std::ptr::eq(*repository, &current.repository);
850 +
                (pattern, top_level)
851 +
            })
852 +
        }) else {
678 853
            return Ok(None);
679 854
        };
855 +
        let key = (current.scope_name.as_str(), name.to_owned());
856 +
        if top_level && let Some(id) = self.repository.get(&key) {
857 +
            return Ok(Some(*id));
858 +
        }
680 859
        let id = self.reserve_set();
681 860
682 -
        self.repository.insert(name.to_owned(), id);
861 +
        if top_level {
862 +
            self.repository.insert(key, id);
863 +
        }
683 864
        self.repository_depth += 1;
684 865
685 -
        let set = self.compile_patterns(std::slice::from_ref(pattern))?;
866 +
        let set = self.compile_patterns(current, std::slice::from_ref(pattern), repositories)?;
686 867
687 868
        self.repository_depth -= 1;
688 869
        self.assign_set(id, set);
689 870
690 871
        Ok(Some(id))
691 872
    }
692 873
874 +
    /// Compiles injections from the root grammar.
875 +
    fn compile_injections(&mut self) -> Result<Vec<Injection>, Error> {
876 +
        let mut injections = Vec::new();
877 +
        for (selector, pattern) in &self.raw.injections {
878 +
            let patterns = self.compile_nested_set(
879 +
                self.raw,
880 +
                std::slice::from_ref(pattern),
881 +
                &mut vec![&self.raw.repository],
882 +
            )?;
883 +
            for selector in ScopeSelector::parse_all(selector) {
884 +
                injections.push(Injection { selector, patterns });
885 +
            }
886 +
        }
887 +
        injections.sort_by_key(|injection| injection.selector.priority);
888 +
        Ok(injections)
889 +
    }
890 +
693 891
    /// Compiles capture metadata.
694 -
    fn captures(&mut self, raw: Option<&BTreeMap<String, RawCapture>>) -> Result<Captures, Error> {
892 +
    fn captures(
893 +
        &mut self,
894 +
        current: &'raw RawGrammar,
895 +
        raw: Option<&'raw BTreeMap<String, RawCapture>>,
896 +
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
897 +
    ) -> Result<Captures, Error> {
695 898
        let mut captures = Captures::new();
696 899
        let Some(raw) = raw else {
697 900
            return Ok(captures);
698 901
        };
699 902
        for (index, capture) in raw {
701 904
                continue;
702 905
            };
703 906
            let nested = if capture.patterns.is_empty() {
704 907
                None
705 908
            } else {
706 -
                Some(self.compile_nested_set(&capture.patterns)?)
909 +
                Some(self.compile_nested_set(current, &capture.patterns, repositories)?)
707 910
            };
708 911
            captures.insert(
709 912
                scope_index,
710 913
                Capture {
711 914
                    scope: Scope::from_raw(capture.name.as_deref(), &mut self.interner),
crates/highlight/src/grammar/selector.rs added +291 -0
1 +
//! TextMate injection selector matching.
2 +
//!
3 +
//! Injection selectors are evaluated against the active scope stack while a
4 +
//! line is tokenized. The supported expression grammar matches VS Code's small
5 +
//! selector language: priorities, negation, grouping, adjacency as `and`, and
6 +
//! `|` or `,` as `or`.
7 +
8 +
/// Priority attached to an injection selector.
9 +
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
10 +
pub(super) enum InjectionPriority {
11 +
    /// Left-priority injection that wins ties with a normal grammar rule.
12 +
    Left,
13 +
    /// Default-priority injection.
14 +
    Default,
15 +
    /// Right-priority injection.
16 +
    Right,
17 +
}
18 +
19 +
/// One parsed selector matcher.
20 +
#[derive(Clone, Debug)]
21 +
pub(super) struct ScopeSelector {
22 +
    /// Priority marker attached to this selector.
23 +
    pub(super) priority: InjectionPriority,
24 +
    /// Parsed selector expression.
25 +
    expression: SelectorExpression,
26 +
}
27 +
28 +
/// Boolean expression over a scope stack.
29 +
#[derive(Clone, Debug)]
30 +
enum SelectorExpression {
31 +
    /// Matches every scope stack.
32 +
    Any,
33 +
    /// Matches when all child expressions match.
34 +
    All(Vec<SelectorExpression>),
35 +
    /// Matches when any child expression matches.
36 +
    AnyOf(Vec<SelectorExpression>),
37 +
    /// Inverts the child expression.
38 +
    Not(Box<SelectorExpression>),
39 +
    /// Matches identifiers in order across the scope stack.
40 +
    Path(Vec<String>),
41 +
}
42 +
43 +
/// Tokenizer for TextMate selector expressions.
44 +
struct SelectorTokens<'a> {
45 +
    /// Selector source.
46 +
    input: &'a str,
47 +
    /// Current byte position.
48 +
    pos: usize,
49 +
}
50 +
51 +
impl ScopeSelector {
52 +
    /// Parses one TextMate selector into one or more matchers.
53 +
    pub(super) fn parse_all(source: &str) -> Vec<Self> {
54 +
        let mut tokens = SelectorTokens::new(source);
55 +
        let mut selectors = Vec::new();
56 +
        let mut token = tokens.next();
57 +
58 +
        while token.is_some() {
59 +
            let mut priority = InjectionPriority::Default;
60 +
            if let Some(marker) = token.as_ref()
61 +
                && marker.len() == 2
62 +
                && marker.ends_with(':')
63 +
            {
64 +
                priority = match marker.as_bytes()[0] {
65 +
                    b'L' => InjectionPriority::Left,
66 +
                    b'R' => InjectionPriority::Right,
67 +
                    _ => InjectionPriority::Default,
68 +
                };
69 +
                token = tokens.next();
70 +
            }
71 +
72 +
            let (expression, next) = parse_conjunction(&mut tokens, token);
73 +
            selectors.push(Self {
74 +
                priority,
75 +
                expression,
76 +
            });
77 +
            if next.as_deref() != Some(",") {
78 +
                break;
79 +
            }
80 +
            token = tokens.next();
81 +
        }
82 +
83 +
        selectors
84 +
    }
85 +
86 +
    /// Returns true when this selector matches `scopes`.
87 +
    pub(super) fn matches(&self, scopes: &[&str]) -> bool {
88 +
        self.expression.matches(scopes)
89 +
    }
90 +
}
91 +
92 +
impl SelectorExpression {
93 +
    /// Returns true when this expression matches `scopes`.
94 +
    fn matches(&self, scopes: &[&str]) -> bool {
95 +
        match self {
96 +
            Self::Any => true,
97 +
            Self::All(expressions) => expressions
98 +
                .iter()
99 +
                .all(|expression| expression.matches(scopes)),
100 +
            Self::AnyOf(expressions) => expressions
101 +
                .iter()
102 +
                .any(|expression| expression.matches(scopes)),
103 +
            Self::Not(expression) => !expression.matches(scopes),
104 +
            Self::Path(path) => path_matches(path, scopes),
105 +
        }
106 +
    }
107 +
}
108 +
109 +
impl SelectorTokens<'_> {
110 +
    /// Creates a tokenizer for `input`.
111 +
    fn new(input: &str) -> SelectorTokens<'_> {
112 +
        SelectorTokens { input, pos: 0 }
113 +
    }
114 +
115 +
    /// Returns the next selector token.
116 +
    fn next(&mut self) -> Option<String> {
117 +
        while self.pos < self.input.len() && self.input.as_bytes()[self.pos].is_ascii_whitespace() {
118 +
            self.pos += 1;
119 +
        }
120 +
        let start = self.pos;
121 +
        let ch = self.input[start..].chars().next()?;
122 +
        if matches!(ch, 'L' | 'R')
123 +
            && self
124 +
                .input
125 +
                .as_bytes()
126 +
                .get(start + ch.len_utf8())
127 +
                .is_some_and(|byte| *byte == b':')
128 +
        {
129 +
            self.pos += ch.len_utf8() + 1;
130 +
            return Some(self.input[start..self.pos].to_owned());
131 +
        }
132 +
        if matches!(ch, ',' | '|' | '-' | '(' | ')') {
133 +
            self.pos += ch.len_utf8();
134 +
            return Some(self.input[start..self.pos].to_owned());
135 +
        }
136 +
        while self.pos < self.input.len() {
137 +
            let ch = self.input[self.pos..].chars().next()?;
138 +
            if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | ':' | '-' | '*') {
139 +
                self.pos += ch.len_utf8();
140 +
            } else {
141 +
                break;
142 +
            }
143 +
        }
144 +
        (self.pos > start).then(|| self.input[start..self.pos].to_owned())
145 +
    }
146 +
}
147 +
148 +
/// Parses one selector operand.
149 +
fn parse_operand(
150 +
    tokens: &mut SelectorTokens<'_>,
151 +
    token: Option<String>,
152 +
) -> (Option<SelectorExpression>, Option<String>) {
153 +
    match token.as_deref() {
154 +
        Some("-") => {
155 +
            let next_token = tokens.next();
156 +
            let (expression, next) = parse_operand(tokens, next_token);
157 +
            (
158 +
                expression.map(|expression| SelectorExpression::Not(Box::new(expression))),
159 +
                next,
160 +
            )
161 +
        }
162 +
        Some("(") => {
163 +
            let next_token = tokens.next();
164 +
            let (expression, next) = parse_disjunction(tokens, next_token);
165 +
            let next = if next.as_deref() == Some(")") {
166 +
                tokens.next()
167 +
            } else {
168 +
                next
169 +
            };
170 +
            (Some(expression), next)
171 +
        }
172 +
        Some(token) if is_identifier(token) => {
173 +
            let mut path = vec![token.to_owned()];
174 +
            let mut next = tokens.next();
175 +
            while let Some(token) = next.as_deref() {
176 +
                if !is_identifier(token) {
177 +
                    break;
178 +
                }
179 +
                path.push(token.to_owned());
180 +
                next = tokens.next();
181 +
            }
182 +
            (Some(SelectorExpression::Path(path)), next)
183 +
        }
184 +
        _ => (None, token),
185 +
    }
186 +
}
187 +
188 +
/// Parses adjacent operands as a conjunction.
189 +
fn parse_conjunction(
190 +
    tokens: &mut SelectorTokens<'_>,
191 +
    token: Option<String>,
192 +
) -> (SelectorExpression, Option<String>) {
193 +
    let mut expressions = Vec::new();
194 +
    let (mut expression, mut next) = parse_operand(tokens, token);
195 +
    while let Some(value) = expression {
196 +
        expressions.push(value);
197 +
        (expression, next) = parse_operand(tokens, next);
198 +
    }
199 +
200 +
    let expression = match expressions.len() {
201 +
        0 => SelectorExpression::Any,
202 +
        1 => expressions.remove(0),
203 +
        _ => SelectorExpression::All(expressions),
204 +
    };
205 +
    (expression, next)
206 +
}
207 +
208 +
/// Parses `|` and `,` separated expressions.
209 +
fn parse_disjunction(
210 +
    tokens: &mut SelectorTokens<'_>,
211 +
    token: Option<String>,
212 +
) -> (SelectorExpression, Option<String>) {
213 +
    let mut expressions = Vec::new();
214 +
    let (mut expression, mut next) = parse_conjunction(tokens, token);
215 +
    expressions.push(expression);
216 +
217 +
    while matches!(next.as_deref(), Some("|" | ",")) {
218 +
        next = tokens.next();
219 +
        while matches!(next.as_deref(), Some("|" | ",")) {
220 +
            next = tokens.next();
221 +
        }
222 +
        (expression, next) = parse_conjunction(tokens, next);
223 +
        expressions.push(expression);
224 +
    }
225 +
226 +
    let expression = match expressions.len() {
227 +
        1 => expressions.remove(0),
228 +
        _ => SelectorExpression::AnyOf(expressions),
229 +
    };
230 +
    (expression, next)
231 +
}
232 +
233 +
/// Returns true when `token` can be a selector identifier.
234 +
fn is_identifier(token: &str) -> bool {
235 +
    token
236 +
        .bytes()
237 +
        .next()
238 +
        .is_some_and(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'*')
239 +
}
240 +
241 +
/// Returns true when all identifiers appear in order in `scopes`.
242 +
fn path_matches(path: &[String], scopes: &[&str]) -> bool {
243 +
    if scopes.len() < path.len() {
244 +
        return false;
245 +
    }
246 +
    let mut start = 0;
247 +
    path.iter().all(|identifier| {
248 +
        for (index, scope) in scopes.iter().enumerate().skip(start) {
249 +
            if scope_matches(scope, identifier) {
250 +
                start = index + 1;
251 +
                return true;
252 +
            }
253 +
        }
254 +
        false
255 +
    })
256 +
}
257 +
258 +
/// Returns true when a selector identifier matches one scope.
259 +
fn scope_matches(scope: &str, identifier: &str) -> bool {
260 +
    let mut scope_segments = scope.split('.');
261 +
    for identifier in identifier.split('.') {
262 +
        let Some(scope) = scope_segments.next() else {
263 +
            return false;
264 +
        };
265 +
        if identifier != "*" && scope != identifier {
266 +
            return false;
267 +
        }
268 +
    }
269 +
    true
270 +
}
271 +
272 +
#[cfg(test)]
273 +
mod tests {
274 +
    use super::*;
275 +
276 +
    #[test]
277 +
    fn selector_supports_negation_groups_and_priority() {
278 +
        let selectors =
279 +
            ScopeSelector::parse_all("text.html.php - (meta.embedded | meta.tag), L:source.js");
280 +
281 +
        assert_eq!(selectors.len(), 2);
282 +
        assert_eq!(selectors[1].priority, InjectionPriority::Left);
283 +
        assert!(selectors[0].matches(&["text.html.php", "source.ruby"]));
284 +
        assert!(!selectors[0].matches(&["text.html.php", "meta.embedded.block"]));
285 +
        assert!(selectors[1].matches(&["text.html.php", "source.js.embedded.html"]));
286 +
        assert!(
287 +
            ScopeSelector::parse_all("meta.tag.*.*.*.html")[0]
288 +
                .matches(&["text.html", "meta.tag.structure.h1.start.html"])
289 +
        );
290 +
    }
291 +
}
crates/highlight/src/grammar/tokenize.rs +58 -16
4 4
//! nested match inside the currently open begin/end rule, or that rule's end โ€”
5 5
//! emits the spans it produces, and updates the parser state accordingly.
6 6
7 7
use super::end::{EndRegex, EndRegexCache};
8 8
use super::pattern::{Match, OpenRule, Pattern, PatternSearch, RegexMatch, SpanContext};
9 +
use super::selector::InjectionPriority;
9 10
use super::*;
10 11
11 12
/// Reusable line tokenizer for one compiled grammar.
12 13
///
13 14
/// The tokenizer keeps runtime scratch that is not part of immutable grammar
94 95
        line: &str,
95 96
        pos: usize,
96 97
        spans: &mut Vec<ScopeSpan>,
97 98
        anchors: &mut AnchorState,
98 99
    ) -> usize {
99 -
        let mut search = PatternSearch::new(
100 -
            &self.grammar.pattern_sets,
101 -
            line,
102 -
            line.len(),
103 -
            &mut self.cache,
104 -
            *anchors,
105 -
        );
106 -
        let Some(found) = self.grammar.patterns.find_next(&mut search, pos) else {
100 +
        let found =
101 +
            self.match_rule_or_injections(self.grammar.patterns, state, line, pos, *anchors);
102 +
        let Some(found) = found else {
107 103
            return line.len();
108 104
        };
109 105
        let next_pos = found.next_pos_after_open(line);
110 106
        let opened = found.open_rule;
111 107
        let anchor = found.end;
226 222
        pos: usize,
227 223
        spans: &mut Vec<ScopeSpan>,
228 224
        pattern: &Pattern,
229 225
        anchors: &mut AnchorState,
230 226
    ) -> usize {
231 -
        let mut search = PatternSearch::new(
232 -
            &self.grammar.pattern_sets,
233 -
            line,
234 -
            line.len(),
235 -
            &mut self.cache,
236 -
            *anchors,
237 -
        );
238 -
        let nested = pattern.nested.find_next(&mut search, pos);
227 +
        let nested = self.match_rule_or_injections(pattern.nested, state, line, pos, *anchors);
239 228
        let Some(nested) = nested else {
240 229
            pattern.push_content_visible(spans, pos, line.len());
241 230
            return line.len();
242 231
        };
243 232
        let next_pos = nested.next_pos_after_open(line);
252 241
            anchors.set_begin_position(anchor);
253 242
        }
254 243
        next_pos
255 244
    }
256 245
246 +
    /// Returns the next normal grammar or injected pattern match.
247 +
    fn match_rule_or_injections(
248 +
        &mut self,
249 +
        patterns: PatternSetId,
250 +
        state: &LineState,
251 +
        line: &str,
252 +
        pos: usize,
253 +
        anchors: AnchorState,
254 +
    ) -> Option<Match> {
255 +
        let mut found = {
256 +
            let mut search = PatternSearch::new(
257 +
                &self.grammar.pattern_sets,
258 +
                line,
259 +
                line.len(),
260 +
                &mut self.cache,
261 +
                anchors,
262 +
            );
263 +
            patterns.find_next(&mut search, pos)
264 +
        };
265 +
        if self.grammar.injections.is_empty() {
266 +
            return found;
267 +
        }
268 +
269 +
        let mut scopes = Vec::new();
270 +
        self.grammar.scope_names_for_state(state, &mut scopes);
271 +
        for injection in &self.grammar.injections {
272 +
            if !injection.selector.matches(&scopes) {
273 +
                continue;
274 +
            }
275 +
            let mut search = PatternSearch::new(
276 +
                &self.grammar.pattern_sets,
277 +
                line,
278 +
                line.len(),
279 +
                &mut self.cache,
280 +
                anchors,
281 +
            );
282 +
            let Some(candidate) = injection.patterns.find_next(&mut search, pos) else {
283 +
                continue;
284 +
            };
285 +
            found = match found {
286 +
                Some(current)
287 +
                    if current.start < candidate.start
288 +
                        || (current.start == candidate.start
289 +
                            && injection.selector.priority != InjectionPriority::Left) =>
290 +
                {
291 +
                    Some(current)
292 +
                }
293 +
                _ => Some(candidate),
294 +
            };
295 +
        }
296 +
        found
297 +
    }
298 +
257 299
    /// Closes zero-width end rules that match at the end of a line.
258 300
    fn close_empty_rules_at_end(
259 301
        &mut self,
260 302
        state: &mut LineState,
261 303
        line: &str,
crates/highlight/src/raw.rs +3 -0
33 33
    /// Root patterns.
34 34
    pub patterns: Vec<RawPattern>,
35 35
    /// Named pattern repository.
36 36
    #[serde(default)]
37 37
    pub repository: BTreeMap<String, RawPattern>,
38 +
    /// Injection selectors and the pattern injected at each selector.
39 +
    #[serde(default)]
40 +
    pub injections: BTreeMap<String, RawPattern>,
38 41
}
39 42
40 43
/// A parsed, uncompiled TextMate pattern.
41 44
#[derive(Clone, Debug, Default, Deserialize)]
42 45
pub struct RawPattern {
crates/highlight/src/tests.rs +83 -0
39 39
        .iter()
40 40
        .filter_map(|span| grammar.scopes.get(span.scope.index()).map(String::as_str))
41 41
        .collect()
42 42
}
43 43
44 +
fn erb_grammar() -> RawGrammar {
45 +
    RawGrammar::parse(
46 +
        r##"{
47 +
            "name": "erb",
48 +
            "scopeName": "text.html.erb",
49 +
            "fileTypes": ["erb", "html.erb"],
50 +
            "patterns": [{ "include": "text.html.basic" }],
51 +
            "injections": {
52 +
                "text.html.erb - (meta.embedded.block.erb | comment)": {
53 +
                    "patterns": [{ "include": "#tags" }]
54 +
                }
55 +
            },
56 +
            "repository": {
57 +
                "tags": {
58 +
                    "patterns": [{
59 +
                        "begin": "<%",
60 +
                        "beginCaptures": {
61 +
                            "0": { "name": "punctuation.section.embedded.begin.erb" }
62 +
                        },
63 +
                        "contentName": "source.ruby",
64 +
                        "end": "%>",
65 +
                        "endCaptures": {
66 +
                            "0": { "name": "punctuation.section.embedded.end.erb" }
67 +
                        },
68 +
                        "name": "meta.embedded.block.erb",
69 +
                        "patterns": [{ "include": "source.ruby" }]
70 +
                    }]
71 +
                }
72 +
            }
73 +
        }"##,
74 +
    )
75 +
    .unwrap()
76 +
}
77 +
78 +
fn html_grammar() -> RawGrammar {
79 +
    RawGrammar::parse(
80 +
        r#"{
81 +
            "name": "html",
82 +
            "scopeName": "text.html.basic",
83 +
            "patterns": [{
84 +
                "match": "</?[A-Za-z][^>]*>",
85 +
                "name": "entity.name.tag.html"
86 +
            }],
87 +
            "repository": {}
88 +
        }"#,
89 +
    )
90 +
    .unwrap()
91 +
}
92 +
93 +
fn ruby_grammar() -> RawGrammar {
94 +
    RawGrammar::parse(
95 +
        r#"{
96 +
            "name": "ruby",
97 +
            "scopeName": "source.ruby",
98 +
            "patterns": [{
99 +
                "match": "\\bif\\b",
100 +
                "name": "keyword.control.ruby"
101 +
            }],
102 +
            "repository": {}
103 +
        }"#,
104 +
    )
105 +
    .unwrap()
106 +
}
107 +
44 108
#[test]
45 109
fn grammar_parses_textmate_keys_and_head_match() {
46 110
    let grammar = test_grammar();
47 111
48 112
    assert_eq!(grammar.name, "Test");
79 143
            .iter()
80 144
            .any(|scope| scope.starts_with("keyword.control"))
81 145
    );
82 146
}
83 147
148 +
#[test]
149 +
fn tokenizer_resolves_external_includes_and_injections() {
150 +
    let erb = erb_grammar();
151 +
    let html = html_grammar();
152 +
    let ruby = ruby_grammar();
153 +
    let grammar = Grammar::compile_with(&erb, &[html, ruby]).unwrap();
154 +
    let mut state = LineState::default();
155 +
156 +
    let spans = grammar.tokenize_line(&mut state, "<h1><% if ok %></h1>");
157 +
    let scopes = scope_names(&grammar, &spans);
158 +
159 +
    assert!(scopes.contains(&"entity.name.tag.html"));
160 +
    assert!(scopes.contains(&"punctuation.section.embedded.begin.erb"));
161 +
    assert!(scopes.contains(&"meta.embedded.block.erb"));
162 +
    assert!(scopes.contains(&"source.ruby"));
163 +
    assert!(scopes.contains(&"keyword.control.ruby"));
164 +
    assert!(scopes.contains(&"punctuation.section.embedded.end.erb"));
165 +
}
166 +
84 167
#[test]
85 168
fn scoped_nested_rules_keep_state_even_when_container_has_no_scope() {
86 169
    let grammar = Grammar::from_str(
87 170
        r#"{
88 171
            "name":"Test",
crates/highlight/tests/syntaxes.rs +43 -0
23 23
    ] {
24 24
        Grammar::from_str(source).unwrap();
25 25
    }
26 26
}
27 27
28 +
#[test]
29 +
fn html_embeds_javascript_scopes() {
30 +
    let html: rustik_highlight::RawGrammar = syntaxes::HTML.parse().unwrap();
31 +
    let css: rustik_highlight::RawGrammar = syntaxes::CSS.parse().unwrap();
32 +
    let javascript: rustik_highlight::RawGrammar = syntaxes::JAVASCRIPT.parse().unwrap();
33 +
    let grammar = Grammar::compile_with(&html, &[css, javascript]).unwrap();
34 +
    let scopes = tokenize_scopes(&grammar, "<Script>if (ok) { return; }</Script>");
35 +
36 +
    assert!(scopes.contains(&"source.js"));
37 +
    assert!(scopes.contains(&"keyword.control.conditional.js"));
38 +
    assert!(scopes.contains(&"keyword.control.flow.js"));
39 +
}
40 +
41 +
#[test]
42 +
fn javascript_highlights_function_call_arguments() {
43 +
    let grammar = Grammar::from_str(syntaxes::JAVASCRIPT).unwrap();
44 +
    let line = "document.addEventListener('DOMContentLoaded', function () {";
45 +
    let mut state = LineState::default();
46 +
    let mut tokenizer = LineTokenizer::new(&grammar);
47 +
    let spans = tokenizer.tokenize_line(&mut state, line);
48 +
    let scopes = spans
49 +
        .iter()
50 +
        .filter_map(|span| grammar.scopes.get(span.scope.index()))
51 +
        .map(String::as_str)
52 +
        .collect::<Vec<_>>();
53 +
54 +
    assert!(scopes.contains(&"string.quoted.single.js"));
55 +
    assert!(scopes.contains(&"storage.type.function.js"));
56 +
}
57 +
28 58
#[test]
29 59
fn css_root_comments_are_highlighted() {
30 60
    let grammar = Grammar::from_str(syntaxes::CSS).unwrap();
31 61
    let mut state = LineState::default();
32 62
    let line = "/**/";
53 83
    assert!(scopes.contains(&"meta.function.url.css"));
54 84
    assert!(scopes.contains(&"meta.function.color.css"));
55 85
    assert!(scopes.contains(&"constant.other.color.rgb-value.hex.css"));
56 86
}
57 87
88 +
/// Tokenizes `line` and returns its scope names.
89 +
fn tokenize_scopes<'a>(grammar: &'a Grammar, line: &str) -> Vec<&'a str> {
90 +
    let mut state = LineState::default();
91 +
    let mut tokenizer = LineTokenizer::new(grammar);
92 +
    let spans = tokenizer.tokenize_line(&mut state, line);
93 +
94 +
    spans
95 +
        .iter()
96 +
        .filter_map(|span| grammar.scopes.get(span.scope.index()))
97 +
        .map(String::as_str)
98 +
        .collect()
99 +
}
100 +
58 101
/// Tokenizes `line` inside a CSS rule body and returns its scope names.
59 102
fn css_rule_scopes<'a>(grammar: &'a Grammar, line: &str) -> Vec<&'a str> {
60 103
    let mut state = LineState::default();
61 104
    let mut tokenizer = LineTokenizer::new(grammar);
62 105
    let _ = tokenizer.tokenize_line(&mut state, ".x {");