crates/highlight/src/grammar.rs 10.3 KiB raw
1
//! Grammar compilation and line tokenization.
2
//!
3
//! TextMate grammars are parsed into immutable pattern trees with interned
4
//! scope names and compiled Oniguruma regex sets. The public tokenizer APIs use
5
//! caller-owned [`LineState`] values so multi-line constructs can continue
6
//! across line boundaries without forcing whole-file parsing.
7
8
use std::collections::{BTreeMap, HashSet};
9
use std::path::Path;
10
use std::str::FromStr;
11
12
use onig::{RegSet, RegSetLead, Regex, RegexOptions, Region, SearchOptions, Syntax};
13
14
use crate::json;
15
use crate::raw::{RawCapture, RawGrammar, RawPattern, head_patterns};
16
use crate::util::{key, next_char_boundary, path_keys, trim_line_end};
17
use crate::{Error, MAX_INCLUDE_DEPTH};
18
19
mod end;
20
mod pattern;
21
mod selector;
22
mod tokenize;
23
24
pub use tokenize::LineTokenizer;
25
26
use pattern::{Injection, OpenRule, PatternCompiler, PatternSet, PatternSetId, RuleLocation};
27
28
/// Display name for the built-in plain-text fallback grammar.
29
pub(crate) const PLAIN_TEXT_NAME: &str = "Plain Text";
30
31
/// Regex options used for TextMate pattern compilation.
32
pub(super) const TEXTMATE_REGEX_OPTIONS: RegexOptions = RegexOptions::REGEX_OPTION_CAPTURE_GROUP;
33
34
/// Compiles a TextMate regex with capture semantics expected by grammar captures.
35
pub(super) fn regex(pattern: &str) -> Result<Regex, onig::Error> {
36
    Regex::with_options(pattern, TEXTMATE_REGEX_OPTIONS, Syntax::default())
37
}
38
39
/// Interned scope identifier.
40
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
41
pub struct ScopeId(
42
    /// Index into a grammar's interned scope-name table.
43
    usize,
44
);
45
46
impl ScopeId {
47
    /// Returns this id's index into its grammar's interned scope-name table.
48
    pub const fn index(self) -> usize {
49
        self.0
50
    }
51
52
    /// Creates a scope id from an interned scope-name table index.
53
    pub(crate) const fn new(index: usize) -> Self {
54
        Self(index)
55
    }
56
}
57
58
/// Scope span produced by tokenization.
59
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60
pub struct ScopeSpan {
61
    /// Start byte in the line.
62
    pub start: usize,
63
    /// End byte in the line.
64
    pub end: usize,
65
    /// Interned scope id.
66
    pub scope: ScopeId,
67
}
68
69
/// Per-line parser state.
70
#[derive(Clone, Debug, Eq, PartialEq)]
71
pub struct LineState {
72
    /// Open begin/end rules carried across line boundaries.
73
    stack: Vec<OpenRule>,
74
    /// Whether the next line tokenized from this state is the first line.
75
    first_line: bool,
76
}
77
78
impl LineState {
79
    /// Returns true when there are no open multi-line rules.
80
    pub fn is_empty(&self) -> bool {
81
        self.stack.is_empty()
82
    }
83
84
    /// Returns the number of open multi-line rules.
85
    pub fn depth(&self) -> usize {
86
        self.stack.len()
87
    }
88
}
89
90
impl Default for LineState {
91
    /// Creates parser state for the first line of a document.
92
    fn default() -> Self {
93
        Self {
94
            stack: Vec::new(),
95
            first_line: true,
96
        }
97
    }
98
}
99
100
/// Regex anchor availability for one tokenizer step.
101
#[derive(Clone, Copy, Debug)]
102
pub(super) struct AnchorState {
103
    /// Whether `\A` should be allowed for this line.
104
    first_line: bool,
105
    /// Byte position where `\G` should be allowed.
106
    begin_position: Option<usize>,
107
}
108
109
impl AnchorState {
110
    /// Creates anchor state for a new line.
111
    pub(super) fn new(first_line: bool) -> Self {
112
        Self {
113
            first_line,
114
            begin_position: None,
115
        }
116
    }
117
118
    /// Allows `\G` at `position`.
119
    pub(super) fn set_begin_position(&mut self, position: usize) {
120
        self.begin_position = Some(position);
121
    }
122
123
    /// Replaces the active `\G` position with a previous stack frame's value.
124
    pub(super) fn restore_begin_position(&mut self, position: Option<usize>) {
125
        self.begin_position = position;
126
    }
127
128
    /// Returns the active `\G` position.
129
    pub(super) fn begin_position(self) -> Option<usize> {
130
        self.begin_position
131
    }
132
133
    /// Returns Oniguruma search options for a search starting at `position`.
134
    pub(super) fn search_options(self, position: usize) -> SearchOptions {
135
        let mut options = SearchOptions::SEARCH_OPTION_NONE;
136
        if !self.first_line {
137
            options |= SearchOptions::SEARCH_OPTION_NOT_BEGIN_STRING;
138
        }
139
        if self.begin_position != Some(position) {
140
            options |= SearchOptions::SEARCH_OPTION_NOT_BEGIN_POSITION;
141
        }
142
        options
143
    }
144
}
145
146
/// Immutable compiled grammar data.
147
#[derive(Debug)]
148
pub struct Grammar {
149
    /// Human-readable grammar name.
150
    pub name: String,
151
    /// Root scope name.
152
    pub scope_name: String,
153
    /// Interned scope names used by this grammar.
154
    pub scopes: Vec<String>,
155
    /// Tokenization strategy used by this grammar.
156
    pub kind: GrammarKind,
157
    /// Lowercase file extensions, file names, and aliases matched by this grammar.
158
    file_types: HashSet<String>,
159
    /// Regexes used to match a source file's head line.
160
    head_match: Vec<Regex>,
161
    /// Root pattern set for TextMate tokenization.
162
    patterns: PatternSetId,
163
    /// Arena of compiled pattern sets.
164
    pattern_sets: Vec<PatternSet>,
165
    /// Direct pattern locations indexed by rule id.
166
    rule_locations: Vec<Option<RuleLocation>>,
167
    /// Runtime injections applied while tokenizing this grammar.
168
    injections: Vec<Injection>,
169
}
170
171
/// Tokenization strategy used by a grammar.
172
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
173
pub enum GrammarKind {
174
    /// TextMate grammar compiled to Oniguruma regex sets.
175
    TextMate,
176
    /// Dedicated line-oriented JSON scanner.
177
    Json,
178
}
179
180
impl Grammar {
181
    /// Compiles a raw grammar.
182
    pub fn compile(raw: &RawGrammar) -> Result<Self, Error> {
183
        Self::compile_with(raw, &[])
184
    }
185
186
    /// Compiles a raw grammar with raw cross-grammar include dependencies.
187
    pub fn compile_with(raw: &RawGrammar, dependencies: &[RawGrammar]) -> Result<Self, Error> {
188
        let compiled = PatternCompiler::new(raw, dependencies).compile()?;
189
        let head_match = head_patterns(raw.first_line_match.as_ref())
190
            .iter()
191
            .map(|pattern| regex(pattern).map_err(|_| Error::InvalidRegex(pattern.clone())))
192
            .collect::<Result<Vec<_>, _>>()?;
193
194
        Ok(Self {
195
            name: raw.display_name.clone().unwrap_or_else(|| raw.name.clone()),
196
            scope_name: raw.scope_name.clone(),
197
            file_types: raw
198
                .file_types
199
                .iter()
200
                .chain(std::iter::once(&raw.name))
201
                .map(|item| key(item))
202
                .collect(),
203
            head_match,
204
            patterns: compiled.root,
205
            pattern_sets: compiled.sets,
206
            rule_locations: compiled.rule_locations,
207
            injections: compiled.injections,
208
            scopes: compiled.scopes,
209
            kind: GrammarKind::TextMate,
210
        })
211
    }
212
213
    /// Builds a grammar with no patterns for plain text fallback.
214
    pub fn plain_text() -> Self {
215
        Self {
216
            name: PLAIN_TEXT_NAME.to_owned(),
217
            scope_name: "text.plain".to_owned(),
218
            file_types: ["txt".to_owned(), "text".to_owned()].into_iter().collect(),
219
            head_match: Vec::new(),
220
            patterns: PatternSetId::new(0),
221
            pattern_sets: vec![PatternSet::empty()],
222
            rule_locations: Vec::new(),
223
            injections: Vec::new(),
224
            scopes: Vec::new(),
225
            kind: GrammarKind::TextMate,
226
        }
227
    }
228
229
    /// Builds the dedicated fast JSON grammar.
230
    ///
231
    /// This does not use the recursive TextMate tokenizer. It emits the same
232
    /// kind of [`ScopeSpan`] values as compiled grammars while scanning each
233
    /// line directly.
234
    pub fn json() -> Self {
235
        Self {
236
            name: "JSON".to_owned(),
237
            scope_name: "source.json".to_owned(),
238
            file_types: ["json".to_owned()].into_iter().collect(),
239
            head_match: Vec::new(),
240
            patterns: PatternSetId::new(0),
241
            pattern_sets: vec![PatternSet::empty()],
242
            rule_locations: Vec::new(),
243
            injections: Vec::new(),
244
            scopes: json::SCOPES
245
                .iter()
246
                .map(|scope| (*scope).to_owned())
247
                .collect(),
248
            kind: GrammarKind::Json,
249
        }
250
    }
251
252
    /// Returns true when this grammar matches a syntax name or alias.
253
    pub fn matches_name(&self, name: &str) -> bool {
254
        name.eq_ignore_ascii_case(&self.name)
255
            || name.eq_ignore_ascii_case(&self.scope_name)
256
            || self.file_types.contains(&key(name))
257
    }
258
259
    /// Returns true when this grammar matches a file path.
260
    pub fn matches_path(&self, path: &Path) -> bool {
261
        path_keys(path).any(|key| self.file_types.contains(&key))
262
    }
263
264
    /// Returns true when this grammar matches the head source line.
265
    pub fn matches_head(&self, line: &str) -> bool {
266
        self.head_match
267
            .iter()
268
            .any(|regex| regex.find(line).is_some())
269
    }
270
271
    /// Tokenizes one line, mutating the caller-owned line state.
272
    pub fn tokenize_line(&self, state: &mut LineState, line: &str) -> Vec<ScopeSpan> {
273
        let mut spans = Vec::new();
274
        self.tokenize_line_into(state, line, &mut spans);
275
        spans
276
    }
277
278
    /// Tokenizes one line into a caller-owned buffer.
279
    pub fn tokenize_line_into(
280
        &self,
281
        state: &mut LineState,
282
        line: &str,
283
        spans: &mut Vec<ScopeSpan>,
284
    ) {
285
        LineTokenizer::new(self).tokenize_line_into(state, line, spans);
286
    }
287
288
    /// Returns the compiled pattern for a stored rule id.
289
    fn pattern_by_rule(&self, rule_id: usize) -> Option<&pattern::Pattern> {
290
        let location = self.rule_locations.get(rule_id)?.as_ref()?;
291
        self.pattern_sets
292
            .get(location.set.index())?
293
            .patterns
294
            .get(location.index)
295
    }
296
297
    /// Builds the active scope stack used by injection selectors.
298
    fn scope_names_for_state<'grammar>(
299
        &'grammar self,
300
        state: &LineState,
301
        scopes: &mut Vec<&'grammar str>,
302
    ) {
303
        scopes.clear();
304
        scopes.push(&self.scope_name);
305
        for open in &state.stack {
306
            let Some(pattern) = self.pattern_by_rule(open.rule_id) else {
307
                continue;
308
            };
309
            pattern.extend_scope_names(&self.scopes, scopes);
310
        }
311
    }
312
}
313
314
impl FromStr for Grammar {
315
    type Err = Error;
316
317
    /// Parses and compiles a grammar from JSON.
318
    fn from_str(input: &str) -> Result<Self, Self::Err> {
319
        let raw = RawGrammar::from_str(input)?;
320
        Self::compile(&raw)
321
    }
322
}