crates/highlight/src/grammar/selector.rs 9.2 KiB raw
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
}