highlight: Fix grammar interpretation

180c0cb2306030db31c1c7f7f1dec9f8410e17ba
Alexis Sellier committed ago 1 parent 42ec5b90
crates/highlight/src/grammar/pattern.rs +122 -22
427 427
        start: usize,
428 428
        end: usize,
429 429
        context: &mut SpanContext<'_, '_, '_>,
430 430
    ) {
431 431
        Scope::push_content_visible(&self.scope, &self.content_scope, spans, start, end);
432 -
        let Some(nested) = self.nested else {
433 -
            return;
432 +
        if let Some(nested) = self.nested {
433 +
            retokenize_capture(nested, spans, start, end, context);
434 +
        }
435 +
    }
436 +
}
437 +
438 +
/// One event found while retokenizing a captured region.
439 +
enum CaptureEvent {
440 +
    /// A pattern matched inside the region, possibly opening a begin/end rule.
441 +
    Match(Match),
442 +
    /// The innermost open rule's end pattern matched.
443 +
    Close(RegexMatch),
444 +
    /// Nothing further matches inside the region.
445 +
    None,
446 +
}
447 +
448 +
/// Returns the pattern for a rule id by scanning the pattern sets.
449 +
fn pattern_by_rule(sets: &[PatternSet], rule_id: usize) -> Option<&Pattern> {
450 +
    sets.iter()
451 +
        .find_map(|set| set.patterns.iter().find(|pattern| pattern.id == rule_id))
452 +
}
453 +
454 +
/// Retokenizes one captured region against a nested pattern set.
455 +
///
456 +
/// This mirrors the main tokenizer loop, bounded to the region: begin/end
457 +
/// rules opened inside the region are tracked on a local stack so that their
458 +
/// nested patterns and end captures apply, and every emitted span is clamped
459 +
/// to the region. `\G` is allowed at each step's search position, since the
460 +
/// region has no begin match of its own to anchor against.
461 +
fn retokenize_capture(
462 +
    root: PatternSetId,
463 +
    spans: &mut Vec<ScopeSpan>,
464 +
    start: usize,
465 +
    end: usize,
466 +
    context: &mut SpanContext<'_, '_, '_>,
467 +
) {
468 +
    let sets = context.sets;
469 +
    let line = context.line;
470 +
    let mut search = PatternSearch::new(sets, &line[..end], end, context.cache, context.anchors);
471 +
    let emit_open_content =
472 +
        |spans: &mut Vec<ScopeSpan>, stack: &[OpenRule], from: usize, to: usize| {
473 +
            for open in stack.iter().rev() {
474 +
                if let Some(pattern) = pattern_by_rule(sets, open.rule_id) {
475 +
                    pattern.push_content_visible(spans, from, to);
476 +
                }
477 +
            }
434 478
        };
435 -
        let mut search = PatternSearch::new(
436 -
            context.sets,
437 -
            context.line,
438 -
            end,
439 -
            context.cache,
440 -
            context.anchors,
441 -
        );
442 -
        let mut pos = start;
443 -
        while pos < end {
444 -
            let Some(matched) = nested.find_next(&mut search, pos) else {
445 -
                break;
479 +
    let mut stack = Vec::<OpenRule>::new();
480 +
    let mut pos = start;
481 +
482 +
    while pos < end {
483 +
        search.anchors.set_begin_position(pos);
484 +
        let event = if let Some(open) = stack.last().cloned() {
485 +
            let Some(pattern) = pattern_by_rule(sets, open.rule_id) else {
486 +
                stack.pop();
487 +
                continue;
488 +
            };
489 +
            let Some(end_regex) = pattern.resume_end(open.dynamic_rule.as_deref(), search.cache)
490 +
            else {
491 +
                stack.pop();
492 +
                continue;
446 493
            };
447 -
            // The search is bounded at `end`, but a zero-width match can still
448 -
            // land on the boundary; stop before emitting spans past the capture.
449 -
            if matched.start >= end {
494 +
            let nested = pattern.nested.find_next(&mut search, pos);
495 +
            let close = pattern
496 +
                .find_end_match(&end_regex, line, pos, search.anchors)
497 +
                .filter(|close| close.start <= end);
498 +
            match (nested, close) {
499 +
                (Some(nested), Some(close))
500 +
                    if nested.start < close.start
501 +
                        || (pattern.apply_end_pattern_last() && nested.start == close.start) =>
502 +
                {
503 +
                    CaptureEvent::Match(nested)
504 +
                }
505 +
                (_, Some(close)) => CaptureEvent::Close(close),
506 +
                (Some(nested), None) => CaptureEvent::Match(nested),
507 +
                (None, None) => CaptureEvent::None,
508 +
            }
509 +
        } else {
510 +
            match root.find_next(&mut search, pos) {
511 +
                Some(matched) => CaptureEvent::Match(matched),
512 +
                None => CaptureEvent::None,
513 +
            }
514 +
        };
515 +
516 +
        let previous_depth = stack.len();
517 +
        let next_pos = match event {
518 +
            CaptureEvent::Match(matched) => {
519 +
                let next_pos = matched.next_pos_after_open(line).min(end);
520 +
                emit_open_content(spans, &stack, pos, next_pos);
521 +
                spans.extend(matched.spans.into_iter().filter_map(|mut span| {
522 +
                    span.end = span.end.min(end);
523 +
                    (span.start < span.end).then_some(span)
524 +
                }));
525 +
                if let Some(opened) = matched.open_rule {
526 +
                    stack.push(opened);
527 +
                }
528 +
                next_pos
529 +
            }
530 +
            CaptureEvent::Close(close) => {
531 +
                emit_open_content(spans, &stack, pos, close.start);
532 +
                if let Some(pattern) = stack
533 +
                    .last()
534 +
                    .and_then(|open| pattern_by_rule(sets, open.rule_id))
535 +
                {
536 +
                    let mut context =
537 +
                        SpanContext::new(sets, search.line, search.cache, search.anchors);
538 +
                    pattern.append_capture_spans(
539 +
                        &close,
540 +
                        &pattern.captures.end,
541 +
                        spans,
542 +
                        &mut context,
543 +
                    );
544 +
                }
545 +
                stack.pop();
546 +
                close.end.min(end)
547 +
            }
548 +
            CaptureEvent::None => {
549 +
                emit_open_content(spans, &stack, pos, end);
450 550
                break;
451 551
            }
452 -
            let next_pos = matched.next_pos(context.line).min(end);
453 -
            spans.extend(matched.spans.into_iter().filter_map(|mut span| {
454 -
                span.end = span.end.min(end);
455 -
                (span.start < span.end).then_some(span)
456 -
            }));
552 +
        };
553 +
        // A match either advances or opens a rule; otherwise skip one byte.
554 +
        if next_pos > pos || stack.len() != previous_depth {
457 555
            pos = next_pos;
556 +
        } else {
557 +
            pos = (pos + 1).min(end);
458 558
        }
459 559
    }
460 560
}
461 561
462 562
impl ScopeInterner {
1119 1219
        spans: &mut Vec<ScopeSpan>,
1120 1220
        context: &mut SpanContext<'_, '_, '_>,
1121 1221
    ) {
1122 1222
        for (index, capture) in captures {
1123 1223
            if let Some(Some((start, end))) = matched.captures.get(*index)
1124 -
                && start < end
1224 +
                && *start < *end
1125 1225
            {
1126 1226
                capture.push_spans(spans, *start, *end, context);
1127 1227
            }
1128 1228
        }
1129 1229
    }
crates/highlight/tests/syntaxes.rs +30 -0
144 144
    assert!(scopes.contains(&"meta.function.url.css"));
145 145
    assert!(scopes.contains(&"meta.function.color.css"));
146 146
    assert!(scopes.contains(&"constant.other.color.rgb-value.hex.css"));
147 147
}
148 148
149 +
#[test]
150 +
fn go_make_calls_highlight_arguments_and_type_brackets() {
151 +
    let grammar = Grammar::from_str(syntaxes::GO).unwrap();
152 +
    let line = "make([]LayerModule, 0, len(layer.Modules))";
153 +
    let mut state = LineState::default();
154 +
    let mut tokenizer = LineTokenizer::new(&grammar);
155 +
    let spans = tokenizer.tokenize_line(&mut state, line);
156 +
    let scopes = spans
157 +
        .iter()
158 +
        .filter_map(|span| grammar.scopes.get(span.scope.index()))
159 +
        .map(String::as_str)
160 +
        .collect::<Vec<_>>();
161 +
    assert!(
162 +
        scopes.contains(&"constant.numeric.decimal.go"),
163 +
        "{scopes:?}"
164 +
    );
165 +
    assert!(
166 +
        scopes.contains(&"entity.name.function.support.builtin.go"),
167 +
        "{scopes:?}"
168 +
    );
169 +
    assert!(
170 +
        scopes.contains(&"punctuation.definition.begin.bracket.square.go"),
171 +
        "{scopes:?}"
172 +
    );
173 +
    assert!(
174 +
        scopes.contains(&"punctuation.definition.end.bracket.square.go"),
175 +
        "{scopes:?}"
176 +
    );
177 +
}
178 +
149 179
#[test]
150 180
fn toml_highlights_keys_sections_strings_and_booleans() {
151 181
    let grammar = Grammar::from_str(syntaxes::TOML).unwrap();
152 182
    let section_scopes = tokenize_scopes(&grammar, "[package]");
153 183
    let value_scopes = tokenize_scopes(&grammar, "name = \"rustik\"");