//! TextMate injection selector matching. //! //! Injection selectors are evaluated against the active scope stack while a //! line is tokenized. The supported expression grammar matches VS Code's small //! selector language: priorities, negation, grouping, adjacency as `and`, and //! `|` or `,` as `or`. /// Priority attached to an injection selector. #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub(super) enum InjectionPriority { /// Left-priority injection that wins ties with a normal grammar rule. Left, /// Default-priority injection. Default, /// Right-priority injection. Right, } /// One parsed selector matcher. #[derive(Clone, Debug)] pub(super) struct ScopeSelector { /// Priority marker attached to this selector. pub(super) priority: InjectionPriority, /// Parsed selector expression. expression: SelectorExpression, } /// Boolean expression over a scope stack. #[derive(Clone, Debug)] enum SelectorExpression { /// Matches every scope stack. Any, /// Matches when all child expressions match. All(Vec), /// Matches when any child expression matches. AnyOf(Vec), /// Inverts the child expression. Not(Box), /// Matches identifiers in order across the scope stack. Path(Vec), } /// Tokenizer for TextMate selector expressions. struct SelectorTokens<'a> { /// Selector source. input: &'a str, /// Current byte position. pos: usize, } impl ScopeSelector { /// Parses one TextMate selector into one or more matchers. pub(super) fn parse_all(source: &str) -> Vec { let mut tokens = SelectorTokens::new(source); let mut selectors = Vec::new(); let mut token = tokens.next(); while token.is_some() { let mut priority = InjectionPriority::Default; if let Some(marker) = token.as_ref() && marker.len() == 2 && marker.ends_with(':') { priority = match marker.as_bytes()[0] { b'L' => InjectionPriority::Left, b'R' => InjectionPriority::Right, _ => InjectionPriority::Default, }; token = tokens.next(); } let (expression, next) = parse_conjunction(&mut tokens, token); selectors.push(Self { priority, expression, }); if next.as_deref() != Some(",") { break; } token = tokens.next(); } selectors } /// Returns true when this selector matches `scopes`. pub(super) fn matches(&self, scopes: &[&str]) -> bool { self.expression.matches(scopes) } } impl SelectorExpression { /// Returns true when this expression matches `scopes`. fn matches(&self, scopes: &[&str]) -> bool { match self { Self::Any => true, Self::All(expressions) => expressions .iter() .all(|expression| expression.matches(scopes)), Self::AnyOf(expressions) => expressions .iter() .any(|expression| expression.matches(scopes)), Self::Not(expression) => !expression.matches(scopes), Self::Path(path) => path_matches(path, scopes), } } } impl SelectorTokens<'_> { /// Creates a tokenizer for `input`. fn new(input: &str) -> SelectorTokens<'_> { SelectorTokens { input, pos: 0 } } /// Returns the next selector token. fn next(&mut self) -> Option { while self.pos < self.input.len() && self.input.as_bytes()[self.pos].is_ascii_whitespace() { self.pos += 1; } let start = self.pos; let ch = self.input[start..].chars().next()?; if matches!(ch, 'L' | 'R') && self .input .as_bytes() .get(start + ch.len_utf8()) .is_some_and(|byte| *byte == b':') { self.pos += ch.len_utf8() + 1; return Some(self.input[start..self.pos].to_owned()); } if matches!(ch, ',' | '|' | '-' | '(' | ')') { self.pos += ch.len_utf8(); return Some(self.input[start..self.pos].to_owned()); } while self.pos < self.input.len() { let ch = self.input[self.pos..].chars().next()?; if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | ':' | '-' | '*') { self.pos += ch.len_utf8(); } else { break; } } (self.pos > start).then(|| self.input[start..self.pos].to_owned()) } } /// Parses one selector operand. fn parse_operand( tokens: &mut SelectorTokens<'_>, token: Option, ) -> (Option, Option) { match token.as_deref() { Some("-") => { let next_token = tokens.next(); let (expression, next) = parse_operand(tokens, next_token); ( expression.map(|expression| SelectorExpression::Not(Box::new(expression))), next, ) } Some("(") => { let next_token = tokens.next(); let (expression, next) = parse_disjunction(tokens, next_token); let next = if next.as_deref() == Some(")") { tokens.next() } else { next }; (Some(expression), next) } Some(token) if is_identifier(token) => { let mut path = vec![token.to_owned()]; let mut next = tokens.next(); while let Some(token) = next.as_deref() { if !is_identifier(token) { break; } path.push(token.to_owned()); next = tokens.next(); } (Some(SelectorExpression::Path(path)), next) } _ => (None, token), } } /// Parses adjacent operands as a conjunction. fn parse_conjunction( tokens: &mut SelectorTokens<'_>, token: Option, ) -> (SelectorExpression, Option) { let mut expressions = Vec::new(); let (mut expression, mut next) = parse_operand(tokens, token); while let Some(value) = expression { expressions.push(value); (expression, next) = parse_operand(tokens, next); } let expression = match expressions.len() { 0 => SelectorExpression::Any, 1 => expressions.remove(0), _ => SelectorExpression::All(expressions), }; (expression, next) } /// Parses `|` and `,` separated expressions. fn parse_disjunction( tokens: &mut SelectorTokens<'_>, token: Option, ) -> (SelectorExpression, Option) { let mut expressions = Vec::new(); let (mut expression, mut next) = parse_conjunction(tokens, token); expressions.push(expression); while matches!(next.as_deref(), Some("|" | ",")) { next = tokens.next(); while matches!(next.as_deref(), Some("|" | ",")) { next = tokens.next(); } (expression, next) = parse_conjunction(tokens, next); expressions.push(expression); } let expression = match expressions.len() { 1 => expressions.remove(0), _ => SelectorExpression::AnyOf(expressions), }; (expression, next) } /// Returns true when `token` can be a selector identifier. fn is_identifier(token: &str) -> bool { token .bytes() .next() .is_some_and(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'*') } /// Returns true when all identifiers appear in order in `scopes`. fn path_matches(path: &[String], scopes: &[&str]) -> bool { if scopes.len() < path.len() { return false; } let mut start = 0; path.iter().all(|identifier| { for (index, scope) in scopes.iter().enumerate().skip(start) { if scope_matches(scope, identifier) { start = index + 1; return true; } } false }) } /// Returns true when a selector identifier matches one scope. fn scope_matches(scope: &str, identifier: &str) -> bool { let mut scope_segments = scope.split('.'); for identifier in identifier.split('.') { let Some(scope) = scope_segments.next() else { return false; }; if identifier != "*" && scope != identifier { return false; } } true } #[cfg(test)] mod tests { use super::*; #[test] fn selector_supports_negation_groups_and_priority() { let selectors = ScopeSelector::parse_all("text.html.php - (meta.embedded | meta.tag), L:source.js"); assert_eq!(selectors.len(), 2); assert_eq!(selectors[1].priority, InjectionPriority::Left); assert!(selectors[0].matches(&["text.html.php", "source.ruby"])); assert!(!selectors[0].matches(&["text.html.php", "meta.embedded.block"])); assert!(selectors[1].matches(&["text.html.php", "source.js.embedded.html"])); assert!( ScopeSelector::parse_all("meta.tag.*.*.*.html")[0] .matches(&["text.html", "meta.tag.structure.h1.start.html"]) ); } }