highlight: Handle textmate end and while rules

500bb0cfceb3de7a09e12a83209568338869b273
Support applyEndPatternLast tie-breaking and run begin/while conditions
before continued-line scanning. While captures now emit scopes on
continuation prefixes, matching grammars such as Markdown block quotes.
Alexis Sellier committed ago 1 parent 58ca2c61
crates/diff/src/highlight.rs +97 -2
382 382
        assert_eq!(source.line_index(2), Some(0));
383 383
        assert_eq!(source.line(2), Some("two"));
384 384
    }
385 385
386 386
    #[test]
387 -
    fn css_declaration_fragment_uses_property_value_scopes() {
387 +
    fn css_root_comments_are_highlighted() {
388 388
        let grammar = syntax::Grammar::from_str(include_str!("syntaxes/css.json")).unwrap();
389 389
        let mut state = syntax::LineState::default();
390 -
        let line = "background: url(data:image/svg+xml;utf8,icon.svg);";
390 +
        let line = "/**/";
391 391
        let spans = grammar.tokenize_line(&mut state, line);
392 392
        let scopes = spans
393 393
            .iter()
394 394
            .filter_map(|span| grammar.scopes.get(span.scope.index()))
395 395
            .map(String::as_str)
396 396
            .collect::<Vec<_>>();
397 397
398 +
        assert!(scopes.contains(&"comment.block.css"));
399 +
    }
400 +
401 +
    #[test]
402 +
    fn css_property_values_highlight_urls_and_colors_inside_rule() {
403 +
        let grammar = syntax::Grammar::from_str(include_str!("syntaxes/css.json")).unwrap();
404 +
        let scopes = css_rule_scopes(
405 +
            &grammar,
406 +
            "background: url(icon.svg); color: rgb(1 2 3); border-color: #aabbcc;",
407 +
        );
408 +
398 409
        assert!(scopes.contains(&"meta.property-list.css"));
399 410
        assert!(scopes.contains(&"meta.property-value.css"));
400 411
        assert!(scopes.contains(&"meta.function.url.css"));
412 +
        assert!(scopes.contains(&"meta.function.color.css"));
413 +
        assert!(scopes.contains(&"constant.other.color.rgb-value.hex.css"));
414 +
    }
415 +
416 +
    #[test]
417 +
    fn css_custom_properties_use_variable_theme_style() {
418 +
        let grammar = syntax::Grammar::from_str(include_str!("syntaxes/css.json")).unwrap();
419 +
        let theme =
420 +
            syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap();
421 +
        let line = "  --color-background-light: #dad8d8;";
422 +
        let mut state = syntax::LineState::default();
423 +
        let mut tokenizer = syntax::LineTokenizer::new(&grammar);
424 +
        let _ = tokenizer.tokenize_line(&mut state, ":root {");
425 +
        let spans = tokenizer.tokenize_line(&mut state, line);
426 +
        let styles = theme.style_spans(&grammar, line, &spans);
427 +
        let custom_property = line.find("--color-background-light").unwrap();
428 +
        let style = styles
429 +
            .iter()
430 +
            .find(|style| style.start <= custom_property && style.end > custom_property)
431 +
            .unwrap();
432 +
433 +
        assert!(scopes_for_byte(&grammar, &spans, custom_property).contains(&"variable.css"));
434 +
        assert_eq!(
435 +
            style.style.foreground,
436 +
            Some(syntax::Rgb {
437 +
                r: 137,
438 +
                g: 180,
439 +
                b: 250
440 +
            })
441 +
        );
442 +
    }
443 +
444 +
    #[test]
445 +
    fn css_var_references_use_variable_theme_style() {
446 +
        let grammar = syntax::Grammar::from_str(include_str!("syntaxes/css.json")).unwrap();
447 +
        let theme =
448 +
            syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap();
449 +
        let line = "  color: var(--color-dimmer);";
450 +
        let mut state = syntax::LineState::default();
451 +
        let mut tokenizer = syntax::LineTokenizer::new(&grammar);
452 +
        let _ = tokenizer.tokenize_line(&mut state, ".note-meta {");
453 +
        let spans = tokenizer.tokenize_line(&mut state, line);
454 +
        let styles = theme.style_spans(&grammar, line, &spans);
455 +
        let variable = line.find("--color-dimmer").unwrap();
456 +
        let style = styles
457 +
            .iter()
458 +
            .find(|style| style.start <= variable && style.end > variable)
459 +
            .unwrap();
460 +
461 +
        assert!(scopes_for_byte(&grammar, &spans, variable).contains(&"variable.argument.css"));
462 +
        assert_eq!(
463 +
            style.style.foreground,
464 +
            Some(syntax::Rgb {
465 +
                r: 235,
466 +
                g: 160,
467 +
                b: 172
468 +
            })
469 +
        );
470 +
    }
471 +
472 +
    fn css_rule_scopes<'a>(grammar: &'a syntax::Grammar, line: &str) -> Vec<&'a str> {
473 +
        let mut state = syntax::LineState::default();
474 +
        let mut tokenizer = syntax::LineTokenizer::new(grammar);
475 +
        let _ = tokenizer.tokenize_line(&mut state, ".x {");
476 +
        let spans = tokenizer.tokenize_line(&mut state, line);
477 +
478 +
        spans
479 +
            .iter()
480 +
            .filter_map(|span| grammar.scopes.get(span.scope.index()))
481 +
            .map(String::as_str)
482 +
            .collect()
483 +
    }
484 +
485 +
    fn scopes_for_byte<'a>(
486 +
        grammar: &'a syntax::Grammar,
487 +
        spans: &'a [syntax::ScopeSpan],
488 +
        byte: usize,
489 +
    ) -> Vec<&'a str> {
490 +
        spans
491 +
            .iter()
492 +
            .filter(|span| span.start <= byte && span.end > byte)
493 +
            .filter_map(|span| grammar.scopes.get(span.scope.index()))
494 +
            .map(String::as_str)
495 +
            .collect()
401 496
    }
402 497
}
crates/highlight/src/grammar.rs +10 -0
109 109
    /// Allows `\G` at `position`.
110 110
    pub(super) fn set_begin_position(&mut self, position: usize) {
111 111
        self.begin_position = Some(position);
112 112
    }
113 113
114 +
    /// Replaces the active `\G` position with a previous stack frame's value.
115 +
    pub(super) fn restore_begin_position(&mut self, position: Option<usize>) {
116 +
        self.begin_position = position;
117 +
    }
118 +
119 +
    /// Returns the active `\G` position.
120 +
    pub(super) fn begin_position(self) -> Option<usize> {
121 +
        self.begin_position
122 +
    }
123 +
114 124
    /// Returns Oniguruma search options for a search starting at `position`.
115 125
    pub(super) fn search_options(self, position: usize) -> SearchOptions {
116 126
        let mut options = SearchOptions::SEARCH_OPTION_NONE;
117 127
        if !self.first_line {
118 128
            options |= SearchOptions::SEARCH_OPTION_NOT_BEGIN_STRING;
crates/highlight/src/grammar/pattern.rs +66 -23
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 12
use super::*;
13 +
use crate::raw::truthy_flag;
13 14
14 15
/// Capture-group index to capture metadata mapping.
15 16
pub(super) type Captures = BTreeMap<usize, Capture>;
16 17
17 18
/// A scope assigned by a pattern.
61 62
    BeginEnd {
62 63
        /// Begin regex source (also the entry inside the parent set's RegSet).
63 64
        begin_source: String,
64 65
        /// End regex (compiled now or deferred until begin captures are known).
65 66
        end: EndPattern,
67 +
        /// Whether nested patterns take priority over the end pattern at the same position.
68 +
        apply_end_pattern_last: bool,
66 69
    },
67 70
    /// Stateful begin/while rule.
68 71
    BeginWhile {
69 72
        /// Begin regex source (also the entry inside the parent set's RegSet).
70 73
        begin_source: String,
121 124
pub(super) struct OpenRule {
122 125
    /// Compiled rule id.
123 126
    pub(super) rule_id: usize,
124 127
    /// Resolved end-regex source (populated only for dynamic end patterns).
125 128
    pub(super) dynamic_end: Option<String>,
129 +
    /// Parent `\G` anchor restored when this rule closes.
130 +
    pub(super) anchor_position: Option<usize>,
126 131
}
127 132
128 133
/// Result of one pattern matching in a line: the byte range it covered, the
129 134
/// scope spans it emitted, and any begin/end rule it pushed onto the stack.
130 135
pub(super) struct Match {
299 304
        let id = ScopeId::new(self.scopes.len());
300 305
        self.scopes.push(scope.to_owned());
301 306
        self.ids.insert(scope.to_owned(), id);
302 307
        id
303 308
    }
304 -
305 309
}
306 310
307 311
impl PatternSetId {
308 312
    /// Creates a pattern-set id from an arena index.
309 313
    pub(super) fn new(index: usize) -> Self {
518 522
                    return Ok(());
519 523
                };
520 524
                PatternBody::BeginEnd {
521 525
                    begin_source: begin.clone(),
522 526
                    end,
527 +
                    apply_end_pattern_last: truthy_flag(pattern.apply_end_pattern_last.as_ref()),
523 528
                }
524 529
            }
525 530
            (None, Some(begin), None, Some(while_rule)) => {
526 531
                if !scope.has_scope() {
527 532
                    self.inline_patterns(pattern, compiled, includes)?;
546 551
        let nested = self.compile_nested_set(&pattern.patterns)?;
547 552
        let id = self.next_rule;
548 553
        self.next_rule += 1;
549 554
550 555
        let matched = self.captures(pattern.captures.as_ref())?;
551 -
        let begin = self.captures(pattern.begin_captures.as_ref().or(pattern.captures.as_ref()))?;
556 +
        let begin = self.captures(
557 +
            pattern
558 +
                .begin_captures
559 +
                .as_ref()
560 +
                .or(pattern.captures.as_ref()),
561 +
        )?;
552 562
        let end = self.captures(pattern.end_captures.as_ref().or(pattern.captures.as_ref()))?;
553 -
        let while_rule =
554 -
            self.captures(pattern.while_captures.as_ref().or(pattern.captures.as_ref()))?;
563 +
        let while_rule = self.captures(
564 +
            pattern
565 +
                .while_captures
566 +
                .as_ref()
567 +
                .or(pattern.captures.as_ref()),
568 +
        )?;
555 569
556 570
        compiled.push(Pattern {
557 571
            id,
558 572
            scope,
559 573
            content_scope: Scope::from_raw(pattern.content_name.as_deref(), &mut self.interner),
629 643
630 644
        Ok(Some(id))
631 645
    }
632 646
633 647
    /// Compiles capture metadata.
634 -
    fn captures(
635 -
        &mut self,
636 -
        raw: Option<&BTreeMap<String, RawCapture>>,
637 -
    ) -> Result<Captures, Error> {
648 +
    fn captures(&mut self, raw: Option<&BTreeMap<String, RawCapture>>) -> Result<Captures, Error> {
638 649
        let mut captures = Captures::new();
639 650
        let Some(raw) = raw else {
640 651
            return Ok(captures);
641 652
        };
642 653
        for (index, capture) in raw {
689 700
            return None;
690 701
        };
691 702
        end.resume(dynamic_end, cache)
692 703
    }
693 704
694 -
    /// Returns true when this begin/while rule continues on `line`.
695 -
    pub(super) fn continues_while(&self, line: &str, anchors: AnchorState) -> bool {
696 -
        match &self.body {
697 -
            PatternBody::BeginWhile { while_regex, .. } => {
698 -
                RegexMatch::find(while_regex, line, 0, false, anchors)
699 -
                    .is_some_and(|matched| matched.start == 0)
705 +
    /// Finds this rule's while match at the start of a continued line.
706 +
    pub(super) fn while_match(&self, line: &str, anchors: AnchorState) -> Option<RegexMatch> {
707 +
        let PatternBody::BeginWhile { while_regex, .. } = &self.body else {
708 +
            return None;
709 +
        };
710 +
        let matched = RegexMatch::find(
711 +
            while_regex,
712 +
            line,
713 +
            0,
714 +
            !self.captures.while_rule.is_empty(),
715 +
            anchors,
716 +
        )?;
717 +
        (matched.start == 0).then_some(matched)
718 +
    }
719 +
720 +
    /// Returns true when nested patterns should win same-position end matches.
721 +
    pub(super) fn apply_end_pattern_last(&self) -> bool {
722 +
        matches!(
723 +
            &self.body,
724 +
            PatternBody::BeginEnd {
725 +
                apply_end_pattern_last: true,
726 +
                ..
700 727
            }
701 -
            PatternBody::Match { .. } | PatternBody::BeginEnd { .. } => true,
702 -
        }
728 +
        )
703 729
    }
704 730
705 731
    /// Finds this rule's end match at or after `pos`.
706 732
    pub(super) fn find_end_match(
707 733
        &self,
736 762
        line: &str,
737 763
        cache: &mut EndRegexCache,
738 764
        anchors: AnchorState,
739 765
    ) {
740 766
        self.scope.push_visible(spans, matched.start, matched.end);
767 +
        self.append_capture_spans(matched, captures, spans, sets, line, cache, anchors);
768 +
        spans.sort_by_key(|span| (span.start, span.end));
769 +
    }
770 +
771 +
    /// Adds capture-group spans for one regex match.
772 +
    pub(super) fn append_capture_spans(
773 +
        &self,
774 +
        matched: &RegexMatch,
775 +
        captures: &Captures,
776 +
        spans: &mut Vec<ScopeSpan>,
777 +
        sets: &[PatternSet],
778 +
        line: &str,
779 +
        cache: &mut EndRegexCache,
780 +
        anchors: AnchorState,
781 +
    ) {
741 782
        for (index, capture) in captures {
742 783
            if let Some(Some((start, end))) = matched.captures.get(*index)
743 784
                && start < end
744 785
            {
745 786
                capture.push_spans(spans, sets, line, *start, *end, cache, anchors);
746 787
            }
747 788
        }
748 -
        spans.sort_by_key(|span| (span.start, span.end));
749 789
    }
750 790
751 791
    /// Whether match-time regex captures must be retained.
752 792
    fn needs_match_captures(&self) -> bool {
753 793
        match &self.body {
777 817
        sets: &[PatternSet],
778 818
        line: &str,
779 819
        cache: &mut EndRegexCache,
780 820
    ) -> Option<Match> {
781 821
        match &self.body {
782 -
            PatternBody::Match { .. } => {
783 -
                Some(self.simple_match(regex_match, sets, line, cache))
784 -
            }
822 +
            PatternBody::Match { .. } => Some(self.simple_match(regex_match, sets, line, cache)),
785 823
            PatternBody::BeginEnd { end, .. } => {
786 824
                self.begin_match(end, regex_match, sets, line, cache)
787 825
            }
788 826
            PatternBody::BeginWhile { .. } => {
789 827
                Some(self.begin_while_match(regex_match, sets, line, cache))
844 882
            end: begin.end,
845 883
            spans,
846 884
            open_rule: Some(OpenRule {
847 885
                rule_id: self.id,
848 886
                dynamic_end,
887 +
                anchor_position: search.anchors.begin_position(),
849 888
            }),
850 889
        })
851 890
    }
852 891
853 892
    /// Builds a match for a begin/while rule.
877 916
            end,
878 917
            spans,
879 918
            open_rule: Some(OpenRule {
880 919
                rule_id: self.id,
881 920
                dynamic_end: None,
921 +
                anchor_position: search.anchors.begin_position(),
882 922
            }),
883 923
        }
884 924
    }
885 -
886 925
}
887 926
888 927
/// Whether the byte at `pos` is preceded by an odd number of backslashes.
889 928
fn is_escaped_at(line: &str, pos: usize) -> bool {
890 929
    if pos > line.len() || !line.is_char_boundary(pos) {
1004 1043
    /// Returns the next byte position after this regex match.
1005 1044
    pub(super) fn next_pos(&self, line: &str) -> usize {
1006 1045
        next_pos_after(line, self.start, self.end)
1007 1046
    }
1008 1047
1048 +
    /// Returns the byte position where this match ended.
1049 +
    pub(super) fn end(&self) -> usize {
1050 +
        self.end
1051 +
    }
1052 +
1009 1053
    /// Returns the captured text for one group, or `None` when the group is unset.
1010 1054
    pub(super) fn capture_text<'a>(&self, index: usize, line: &'a str) -> Option<&'a str> {
1011 1055
        let (start, end) = self.captures.get(index)?.as_ref().copied()?;
1012 1056
        line.get(start..end)
1013 1057
    }
1075 1119
    fn invalid_regex_offsets_are_ignored() {
1076 1120
        let regex = Regex::new("\"").unwrap();
1077 1121
        let anchors = AnchorState::new(true);
1078 1122
1079 1123
        assert!(
1080 -
            RegexMatch::find(&regex, r#"      "patterns": ["#, usize::MAX, true, anchors)
1081 -
                .is_none()
1124 +
            RegexMatch::find(&regex, r#"      "patterns": ["#, usize::MAX, true, anchors).is_none()
1082 1125
        );
1083 1126
        assert!(RegexMatch::find(&regex, "รฉ", 1, true, anchors).is_none());
1084 1127
    }
1085 1128
1086 1129
    #[test]
crates/highlight/src/grammar/tokenize.rs +78 -25
58 58
        let visible = trim_line_end(line);
59 59
        let visible_len = visible.len();
60 60
        let mut line = String::with_capacity(visible_len + 1);
61 61
        line.push_str(visible);
62 62
        line.push('\n');
63 -
        let mut pos = 0;
64 63
        let mut anchors = AnchorState::new(state.first_line);
64 +
        let mut pos = self.check_while_conditions(state, &line, spans, &mut anchors);
65 65
66 66
        while pos < line.len() {
67 67
            pos = self.advance(state, &line, pos, spans, &mut anchors);
68 68
        }
69 69
        self.close_empty_rules_at_end(state, &line, spans, &mut anchors);
101 101
            line,
102 102
            pos,
103 103
            line.len(),
104 104
            &mut self.cache,
105 105
            *anchors,
106 -
        )
107 -
        else {
106 +
        ) else {
108 107
            return line.len();
109 108
        };
110 109
        let next_pos = found.next_pos_after_open(line);
111 110
        let opened = found.open_rule();
112 111
        let anchor = found.end();
131 130
    ) -> usize {
132 131
        let Some(pattern) = self.grammar.pattern_by_rule(open.rule_id) else {
133 132
            state.stack.pop();
134 133
            return pos;
135 134
        };
136 -
        if pos == 0 && !pattern.continues_while(line, *anchors) {
137 -
            state.stack.pop();
138 -
            return pos;
139 -
        }
140 135
        let Some(end) = pattern.resume_end(open.dynamic_end.as_deref(), &mut self.cache) else {
141 136
            return self.advance_inside_while_rule(state, line, pos, spans, pattern, anchors);
142 137
        };
143 -
        self.next_event_inside(pattern, &end, line, pos, *anchors)
144 -
            .apply(
145 -
                state,
146 -
                line,
147 -
                pos,
138 +
        let event = self.next_event_inside(pattern, &end, line, pos, *anchors);
139 +
        let next_pos = match &event {
140 +
            InsideEvent::Close(close) => close.end(),
141 +
            InsideEvent::Nested(nested) => nested.next_pos_after_open(line),
142 +
            InsideEvent::None => line.len(),
143 +
        };
144 +
        for open in state.stack.iter().take(state.stack.len().saturating_sub(1)) {
145 +
            if let Some(pattern) = self.grammar.pattern_by_rule(open.rule_id) {
146 +
                Scope::push_content_visible(
147 +
                    &pattern.scope,
148 +
                    &pattern.content_scope,
149 +
                    spans,
150 +
                    pos,
151 +
                    next_pos,
152 +
                );
153 +
            }
154 +
        }
155 +
        event.apply(
156 +
            state,
157 +
            line,
158 +
            pos,
159 +
            spans,
160 +
            pattern,
161 +
            &self.grammar.pattern_sets,
162 +
            &mut self.cache,
163 +
            anchors,
164 +
        )
165 +
    }
166 +
167 +
    /// Checks active begin/while rules before scanning a continued line.
168 +
    fn check_while_conditions(
169 +
        &mut self,
170 +
        state: &mut LineState,
171 +
        line: &str,
172 +
        spans: &mut Vec<ScopeSpan>,
173 +
        anchors: &mut AnchorState,
174 +
    ) -> usize {
175 +
        let mut pos = 0;
176 +
        let mut index = 0;
177 +
        while index < state.stack.len() {
178 +
            let Some(pattern) = self.grammar.pattern_by_rule(state.stack[index].rule_id) else {
179 +
                state.stack.truncate(index);
180 +
                break;
181 +
            };
182 +
            let Some(matched) = pattern.while_match(line, *anchors) else {
183 +
                if pattern
184 +
                    .resume_end(state.stack[index].dynamic_end.as_deref(), &mut self.cache)
185 +
                    .is_none()
186 +
                {
187 +
                    state.stack.truncate(index);
188 +
                    break;
189 +
                }
190 +
                index += 1;
191 +
                continue;
192 +
            };
193 +
            pattern.append_capture_spans(
194 +
                &matched,
195 +
                &pattern.captures.while_rule,
148 196
                spans,
149 -
                pattern,
150 197
                &self.grammar.pattern_sets,
198 +
                line,
151 199
                &mut self.cache,
152 -
                anchors,
153 -
            )
200 +
                *anchors,
201 +
            );
202 +
            anchors.set_begin_position(matched.end());
203 +
            pos = pos.max(matched.end());
204 +
            index += 1;
205 +
        }
206 +
        spans.sort_by_key(|span| (span.start, span.end));
207 +
        pos
154 208
    }
155 209
156 210
    /// Advances past one nested event inside an open begin/while rule.
157 211
    fn advance_inside_while_rule(
158 212
        &mut self,
183 237
        };
184 238
        let next_pos = nested.next_pos_after_open(line);
185 239
        let opened = nested.open_rule();
186 240
        let anchor = nested.end();
187 241
188 -
        Scope::push_content_visible(
189 -
            &pattern.scope,
190 -
            &pattern.content_scope,
191 -
            spans,
192 -
            pos,
193 -
            next_pos,
194 -
        );
242 +
        Scope::push_content_visible(&pattern.scope, &pattern.content_scope, spans, pos, next_pos);
195 243
        spans.extend(nested.spans);
196 244
197 245
        if let Some(opened) = opened {
198 246
            state.stack.push(opened);
199 247
            anchors.set_begin_position(anchor);
236 284
            anchors,
237 285
        );
238 286
        let close = pattern.find_end_match(end, line, pos, anchors);
239 287
240 288
        match (nested, close) {
241 -
            (Some(nested), Some(close)) if nested.start < close.start => {
289 +
            (Some(nested), Some(close))
290 +
                if nested.start < close.start
291 +
                    || (pattern.apply_end_pattern_last() && nested.start == close.start) =>
292 +
            {
242 293
                InsideEvent::Nested(nested)
243 294
            }
244 295
            (_, Some(close)) => InsideEvent::Close(close),
245 296
            (Some(nested), None) => InsideEvent::Nested(nested),
246 297
            (None, None) => InsideEvent::None,
301 352
                    sets,
302 353
                    line,
303 354
                    cache,
304 355
                    *anchors,
305 356
                );
306 -
                state.stack.pop();
307 -
                close.next_pos(line)
357 +
                if let Some(closed) = state.stack.pop() {
358 +
                    anchors.restore_begin_position(closed.anchor_position);
359 +
                }
360 +
                close.end()
308 361
            }
309 362
            Self::Nested(nested) => {
310 363
                let next_pos = nested.next_pos_after_open(line);
311 364
                let anchor = nested.end();
312 365
crates/highlight/src/raw.rs +14 -0
50 50
    pub match_rule: Option<String>,
51 51
    /// Begin expression for a stateful rule.
52 52
    pub begin: Option<String>,
53 53
    /// End expression for a stateful rule.
54 54
    pub end: Option<String>,
55 +
    /// Whether nested patterns should be searched before this rule's end pattern.
56 +
    #[serde(rename = "applyEndPatternLast")]
57 +
    pub apply_end_pattern_last: Option<serde_json::Value>,
55 58
    /// While expression for a stateful rule.
56 59
    #[serde(rename = "while")]
57 60
    pub while_rule: Option<String>,
58 61
    /// Nested patterns.
59 62
    #[serde(default)]
191 194
            .collect(),
192 195
        _ => Vec::new(),
193 196
    }
194 197
}
195 198
199 +
/// Returns true for TextMate's loose truthy JSON flag values.
200 +
pub(crate) fn truthy_flag(value: Option<&serde_json::Value>) -> bool {
201 +
    matches!(
202 +
        value,
203 +
        Some(serde_json::Value::Bool(true))
204 +
            | Some(serde_json::Value::Number(serde_json::Number::U64(1)))
205 +
            | Some(serde_json::Value::Number(serde_json::Number::I64(1)))
206 +
            | Some(serde_json::Value::Number(serde_json::Number::F64(1.0)))
207 +
    )
208 +
}
209 +
196 210
/// Splits a comma-separated TextMate selector list.
197 211
fn push_selectors(input: &str, selectors: &mut Vec<String>) {
198 212
    selectors.extend(
199 213
        input
200 214
            .split(',')
crates/highlight/src/tests.rs +170 -0
380 380
381 381
    assert!(scope_names(&grammar, &adjacent).contains(&"keyword.anchor.test"));
382 382
    assert!(!scope_names(&grammar, &separated).contains(&"keyword.anchor.test"));
383 383
}
384 384
385 +
#[test]
386 +
fn zero_width_end_keeps_parent_position_available() {
387 +
    let grammar = Grammar::from_str(
388 +
        r#"{
389 +
            "name":"Test",
390 +
            "scopeName":"source.test",
391 +
            "patterns":[
392 +
                {
393 +
                    "begin":"(?=a)",
394 +
                    "end":"(?=\\{)",
395 +
                    "name":"meta.selector.test",
396 +
                    "patterns":[{"match":"a","name":"entity.name.test"}]
397 +
                },
398 +
                {
399 +
                    "begin":"\\{",
400 +
                    "end":"\\}",
401 +
                    "name":"meta.block.test",
402 +
                    "patterns":[{"match":"x","name":"keyword.value.test"}]
403 +
                }
404 +
            ],
405 +
            "repository":{}
406 +
        }"#,
407 +
    )
408 +
    .unwrap();
409 +
410 +
    let spans = grammar.tokenize_line(&mut LineState::default(), "a{x}");
411 +
    let scopes = scope_names(&grammar, &spans);
412 +
413 +
    assert!(scopes.contains(&"meta.block.test"));
414 +
    assert!(scopes.contains(&"keyword.value.test"));
415 +
}
416 +
417 +
#[test]
418 +
fn nested_begin_position_anchor_does_not_leak_to_parent() {
419 +
    let grammar = Grammar::from_str(
420 +
        r#"{
421 +
            "name":"Test",
422 +
            "scopeName":"source.test",
423 +
            "patterns":[
424 +
                {
425 +
                    "begin":"a",
426 +
                    "end":"z",
427 +
                    "name":"meta.parent.test",
428 +
                    "patterns":[
429 +
                        {"begin":"b","end":"(?=c)","name":"meta.child.test"},
430 +
                        {"match":"\\Gc","name":"keyword.anchor.test"}
431 +
                    ]
432 +
                }
433 +
            ],
434 +
            "repository":{}
435 +
        }"#,
436 +
    )
437 +
    .unwrap();
438 +
439 +
    let spans = grammar.tokenize_line(&mut LineState::default(), "abcz");
440 +
441 +
    assert!(!scope_names(&grammar, &spans).contains(&"keyword.anchor.test"));
442 +
}
443 +
444 +
#[test]
445 +
fn nested_begin_rules_keep_parent_content_scope() {
446 +
    let grammar = Grammar::from_str(
447 +
        r#"{
448 +
            "name":"Test",
449 +
            "scopeName":"source.test",
450 +
            "patterns":[
451 +
                {
452 +
                    "begin":"\\{",
453 +
                    "end":"\\}",
454 +
                    "name":"meta.block.test",
455 +
                    "contentName":"meta.block.content.test",
456 +
                    "patterns":[
457 +
                        {
458 +
                            "begin":"var\\(",
459 +
                            "end":"\\)",
460 +
                            "name":"meta.function.test",
461 +
                            "patterns":[{"match":"--x","name":"variable.argument.test"}]
462 +
                        }
463 +
                    ]
464 +
                }
465 +
            ],
466 +
            "repository":{}
467 +
        }"#,
468 +
    )
469 +
    .unwrap();
470 +
    let theme = r##"{
471 +
        "name":"Parent Theme",
472 +
        "settings":[
473 +
            {"settings":{"foreground":"#010203"}},
474 +
            {"scope":"meta.block.content variable","settings":{"foreground":"#222222"}}
475 +
        ]
476 +
    }"##
477 +
    .parse::<Theme>()
478 +
    .unwrap();
479 +
    let line = "{a: var(--x);}";
480 +
    let variable = line.find("--x").unwrap();
481 +
    let spans = grammar.tokenize_line(&mut LineState::default(), line);
482 +
    let styles = theme.style_spans(&grammar, line, &spans);
483 +
    let style = styles
484 +
        .iter()
485 +
        .find(|style| style.start <= variable && style.end > variable)
486 +
        .unwrap();
487 +
488 +
    assert_eq!(
489 +
        style.style.foreground,
490 +
        Some(Rgb {
491 +
            r: 34,
492 +
            g: 34,
493 +
            b: 34
494 +
        })
495 +
    );
496 +
}
497 +
385 498
#[test]
386 499
fn tokenizer_exposes_textmate_line_terminator_to_patterns() {
387 500
    let grammar = Grammar::from_str(
388 501
        r#"{
389 502
            "name":"Test",
402 515
    assert!(state.is_empty());
403 516
    assert!(scope_names(&grammar, &spans).contains(&"meta.line.test"));
404 517
    assert!(spans.iter().all(|span| span.end <= 1));
405 518
}
406 519
520 +
#[test]
521 +
fn apply_end_pattern_last_lets_nested_match_win_ties() {
522 +
    let grammar = Grammar::from_str(
523 +
        r#"{
524 +
            "name":"Test",
525 +
            "scopeName":"source.test",
526 +
            "patterns":[
527 +
                {
528 +
                    "begin":"a",
529 +
                    "end":"b|\\n",
530 +
                    "applyEndPatternLast":1,
531 +
                    "name":"meta.outer.test",
532 +
                    "patterns":[{"match":"b","name":"keyword.inner.test"}]
533 +
                }
534 +
            ],
535 +
            "repository":{}
536 +
        }"#,
537 +
    )
538 +
    .unwrap();
539 +
    let mut state = LineState::default();
540 +
541 +
    let spans = grammar.tokenize_line(&mut state, "ab");
542 +
    let scopes = scope_names(&grammar, &spans);
543 +
544 +
    assert!(state.is_empty());
545 +
    assert!(scopes.contains(&"keyword.inner.test"));
546 +
}
547 +
548 +
#[test]
549 +
fn while_rules_emit_while_captures_on_continued_lines() {
550 +
    let grammar = Grammar::from_str(
551 +
        r#"{
552 +
            "name":"Test",
553 +
            "scopeName":"source.test",
554 +
            "patterns":[
555 +
                {
556 +
                    "begin":"(^|\\G)(>) ?",
557 +
                    "captures":{"2":{"name":"punctuation.definition.quote.test"}},
558 +
                    "while":"(^|\\G)(>) ?",
559 +
                    "name":"markup.quote.test"
560 +
                }
561 +
            ],
562 +
            "repository":{}
563 +
        }"#,
564 +
    )
565 +
    .unwrap();
566 +
    let mut state = LineState::default();
567 +
568 +
    let _ = grammar.tokenize_line(&mut state, "> first");
569 +
    let continued = grammar.tokenize_line(&mut state, "> second");
570 +
    let ended = grammar.tokenize_line(&mut state, "plain");
571 +
572 +
    assert!(scope_names(&grammar, &continued).contains(&"punctuation.definition.quote.test"));
573 +
    assert!(scope_names(&grammar, &ended).is_empty());
574 +
    assert!(state.is_empty());
575 +
}
576 +
407 577
#[test]
408 578
fn capture_scope_paths_emit_each_scope() {
409 579
    let grammar = Grammar::from_str(
410 580
        r#"{
411 581
            "name":"Test",