highlight: Fall back to shared captures

626834336a515a0dc74798d2f3e26d48647ef985
Use TextMate's shared captures as the default for begin, end, and while
rules when slot-specific captures are absent. This keeps delimiter
scopes from disappearing in grammars that rely on the common captures
field.
Alexis Sellier committed ago 1 parent be4ef104
crates/highlight/src/grammar/pattern.rs +18 -6
32 32
    pub(super) matched: Captures,
33 33
    /// Captures applied to a begin-match rule.
34 34
    pub(super) begin: Captures,
35 35
    /// Captures applied to an end-match rule.
36 36
    pub(super) end: Captures,
37 +
    /// Captures applied to a while-match rule.
38 +
    pub(super) while_rule: Captures,
37 39
}
38 40
39 41
/// Match form used by a compiled pattern.
40 42
#[derive(Debug)]
41 43
enum PatternBody {
244 246
        self.ids.insert(scope.to_owned(), id);
245 247
        id
246 248
    }
247 249
248 250
    /// Converts raw capture maps into interned capture scopes.
249 -
    fn captures(&mut self, raw: &BTreeMap<String, RawCapture>) -> Captures {
250 -
        raw.iter()
251 +
    fn captures(&mut self, raw: Option<&BTreeMap<String, RawCapture>>) -> Captures {
252 +
        raw.into_iter()
253 +
            .flat_map(BTreeMap::iter)
251 254
            .filter_map(|(index, capture)| {
252 255
                let index = index.parse().ok()?;
253 256
                let name = capture.name.as_ref()?;
254 257
                let scope = self.intern(name);
255 258
                Some((index, scope))
494 497
        compiled.push(Pattern {
495 498
            id,
496 499
            scope,
497 500
            content_scope: Scope::from_raw(pattern.content_name.as_deref(), &mut self.interner),
498 501
            captures: PatternCaptures {
499 -
                matched: self.interner.captures(&pattern.captures),
500 -
                begin: self.interner.captures(&pattern.begin_captures),
501 -
                end: self.interner.captures(&pattern.end_captures),
502 +
                matched: self.interner.captures(pattern.captures.as_ref()),
503 +
                begin: self
504 +
                    .interner
505 +
                    .captures(pattern.begin_captures.as_ref().or(pattern.captures.as_ref())),
506 +
                end: self
507 +
                    .interner
508 +
                    .captures(pattern.end_captures.as_ref().or(pattern.captures.as_ref())),
509 +
                while_rule: self
510 +
                    .interner
511 +
                    .captures(pattern.while_captures.as_ref().or(pattern.captures.as_ref())),
502 512
            },
503 513
            body,
504 514
            nested,
505 515
        });
506 516
        Ok(())
639 649
        match &self.body {
640 650
            PatternBody::Match { .. } => !self.captures.matched.is_empty(),
641 651
            PatternBody::BeginEnd { end, .. } => {
642 652
                !self.captures.begin.is_empty() || end.is_dynamic()
643 653
            }
644 -
            PatternBody::BeginWhile { .. } => !self.captures.begin.is_empty(),
654 +
            PatternBody::BeginWhile { .. } => {
655 +
                !self.captures.begin.is_empty() || !self.captures.while_rule.is_empty()
656 +
            }
645 657
        }
646 658
    }
647 659
648 660
    /// The regex source used in the parent set's combined `RegSet`.
649 661
    fn search_source(&self) -> &str {
crates/highlight/src/raw.rs +8 -7
58 58
    /// Nested patterns.
59 59
    #[serde(default)]
60 60
    pub patterns: Vec<RawPattern>,
61 61
    /// Include target such as `$self`, `$base`, or `#name`.
62 62
    pub include: Option<String>,
63 -
    /// Match captures.
64 -
    #[serde(default)]
65 -
    pub captures: BTreeMap<String, RawCapture>,
63 +
    /// Captures shared by match rules and by begin/end/while rules that do not
64 +
    /// define slot-specific captures.
65 +
    pub captures: Option<BTreeMap<String, RawCapture>>,
66 66
    /// Begin captures.
67 -
    #[serde(default)]
68 67
    #[serde(rename = "beginCaptures")]
69 -
    pub begin_captures: BTreeMap<String, RawCapture>,
68 +
    pub begin_captures: Option<BTreeMap<String, RawCapture>>,
70 69
    /// End captures.
71 -
    #[serde(default)]
72 70
    #[serde(rename = "endCaptures")]
73 -
    pub end_captures: BTreeMap<String, RawCapture>,
71 +
    pub end_captures: Option<BTreeMap<String, RawCapture>>,
72 +
    /// While captures.
73 +
    #[serde(rename = "whileCaptures")]
74 +
    pub while_captures: Option<BTreeMap<String, RawCapture>>,
74 75
}
75 76
76 77
/// A parsed, uncompiled TextMate capture.
77 78
#[derive(Clone, Debug, Deserialize)]
78 79
pub struct RawCapture {
crates/highlight/src/tests.rs +32 -0
243 243
244 244
    assert!(scopes.contains(&"meta.word.test"));
245 245
    assert!(scopes.contains(&"entity.name.function.test"));
246 246
}
247 247
248 +
#[test]
249 +
fn begin_end_rules_fallback_to_shared_captures() {
250 +
    let grammar = Grammar::from_str(
251 +
        r#"{
252 +
            "name":"Test",
253 +
            "scopeName":"source.test",
254 +
            "patterns":[
255 +
                {
256 +
                    "begin":"(\\[)",
257 +
                    "end":"(\\])",
258 +
                    "name":"meta.brackets.test",
259 +
                    "captures":{"1":{"name":"punctuation.definition.bracket.test"}}
260 +
                }
261 +
            ],
262 +
            "repository":{}
263 +
        }"#,
264 +
    )
265 +
    .unwrap();
266 +
    let mut state = LineState::default();
267 +
268 +
    let spans = grammar.tokenize_line(&mut state, "[x]");
269 +
    let scopes = scope_names(&grammar, &spans);
270 +
271 +
    assert_eq!(
272 +
        scopes
273 +
            .iter()
274 +
            .filter(|scope| **scope == "punctuation.definition.bracket.test")
275 +
            .count(),
276 +
        2
277 +
    );
278 +
}
279 +
248 280
#[test]
249 281
fn content_name_scopes_begin_rule_content() {
250 282
    let grammar = Grammar::from_str(
251 283
        r#"{
252 284
            "name":"Test",