crates/highlight/src/grammar/end.rs 4.9 KiB raw
1
//! End-pattern resolution for begin/end rules.
2
//!
3
//! TextMate end patterns can be static (a regex known at compile time) or
4
//! dynamic (numeric backrefs into the begin match resolved per occurrence).
5
//! Resolved dynamic end regexes are cached so that a multi-line construct does
6
//! not recompile its end regex on every line.
7
8
use std::borrow::Cow;
9
use std::collections::BTreeMap;
10
use std::sync::Arc;
11
12
use onig::Regex;
13
14
use super::pattern::RegexMatch;
15
use super::regex;
16
17
/// Cache of regexes for resolved dynamic end patterns.
18
pub(super) type EndRegexCache = BTreeMap<String, Arc<Regex>>;
19
20
/// End-pattern definition stored on a compiled begin/end rule.
21
#[derive(Debug)]
22
pub(super) enum EndPattern {
23
    /// End regex compiled at grammar-compile time.
24
    Static {
25
        /// Original regex source.
26
        source: String,
27
        /// Compiled regex.
28
        regex: Arc<Regex>,
29
    },
30
    /// End regex deferred until begin-match captures are known.
31
    Dynamic {
32
        /// Regex source containing numeric backrefs.
33
        source: String,
34
    },
35
}
36
37
/// End regex resolved against a specific begin match.
38
///
39
/// Static end patterns borrow their source from the compiled grammar, while
40
/// dynamic patterns own the source resolved from the begin captures; the
41
/// compiled regex is shared with the grammar or the [`EndRegexCache`].
42
pub(super) struct EndRegex<'pat> {
43
    /// Source string, owned when resolved from a dynamic end pattern.
44
    source: Cow<'pat, str>,
45
    /// Compiled regex used for searching.
46
    regex: Arc<Regex>,
47
}
48
49
impl EndPattern {
50
    /// Compiles an end pattern, deferring numeric-backref patterns until match time.
51
    pub(super) fn compile(source: &str) -> Option<Self> {
52
        if has_numeric_backrefs(source) {
53
            return Some(Self::Dynamic {
54
                source: source.to_owned(),
55
            });
56
        }
57
        let regex = Arc::new(regex(source).ok()?);
58
59
        Some(Self::Static {
60
            source: source.to_owned(),
61
            regex,
62
        })
63
    }
64
65
    /// Resolves this end pattern when its begin/end rule first opens.
66
    pub(super) fn resolve_for_begin<'pat>(
67
        &'pat self,
68
        begin: &RegexMatch,
69
        line: &str,
70
        cache: &mut EndRegexCache,
71
    ) -> Option<EndRegex<'pat>> {
72
        let resolved = match self {
73
            Self::Static { .. } => None,
74
            Self::Dynamic { source } => Some(begin.expand_backrefs(source, line)),
75
        };
76
        self.resolve(resolved, cache)
77
    }
78
79
    /// Resumes this end pattern using a dynamic source previously stored in line state.
80
    pub(super) fn resume<'pat>(
81
        &'pat self,
82
        dynamic_source: Option<&str>,
83
        cache: &mut EndRegexCache,
84
    ) -> Option<EndRegex<'pat>> {
85
        self.resolve(dynamic_source.map(str::to_owned), cache)
86
    }
87
88
    /// Builds the resolved end regex, compiling and caching a dynamic source.
89
    fn resolve<'pat>(
90
        &'pat self,
91
        dynamic_source: Option<String>,
92
        cache: &mut EndRegexCache,
93
    ) -> Option<EndRegex<'pat>> {
94
        match self {
95
            Self::Static { source, regex } => Some(EndRegex {
96
                source: Cow::Borrowed(source),
97
                regex: Arc::clone(regex),
98
            }),
99
            Self::Dynamic { .. } => {
100
                let source = dynamic_source?;
101
                let regex = lookup_or_compile(cache, &source)?;
102
103
                Some(EndRegex {
104
                    source: Cow::Owned(source),
105
                    regex,
106
                })
107
            }
108
        }
109
    }
110
111
    /// Returns true when this end pattern depends on begin-match captures.
112
    pub(super) fn is_dynamic(&self) -> bool {
113
        matches!(self, Self::Dynamic { .. })
114
    }
115
}
116
117
impl EndRegex<'_> {
118
    /// End-regex source string.
119
    pub(super) fn source(&self) -> &str {
120
        &self.source
121
    }
122
123
    /// Compiled regex used for searching.
124
    pub(super) fn regex(&self) -> &Regex {
125
        &self.regex
126
    }
127
128
    /// Returns the resolved dynamic source that should be stored in line state.
129
    pub(super) fn dynamic_source(&self) -> Option<String> {
130
        match &self.source {
131
            Cow::Owned(source) => Some(source.clone()),
132
            Cow::Borrowed(_) => None,
133
        }
134
    }
135
}
136
137
/// Returns the cached regex for `source`, compiling and inserting it on first use.
138
fn lookup_or_compile(cache: &mut EndRegexCache, source: &str) -> Option<Arc<Regex>> {
139
    if let Some(regex) = cache.get(source) {
140
        return Some(Arc::clone(regex));
141
    }
142
    let regex = Arc::new(regex(source).ok()?);
143
    cache.insert(source.to_owned(), Arc::clone(&regex));
144
    Some(regex)
145
}
146
147
/// Returns true when `source` contains an unescaped numeric backreference.
148
fn has_numeric_backrefs(source: &str) -> bool {
149
    let mut backslashes = 0_usize;
150
    for byte in source.bytes() {
151
        if byte == b'\\' {
152
            backslashes += 1;
153
        } else {
154
            if byte.is_ascii_digit() && backslashes % 2 == 1 {
155
                return true;
156
            }
157
            backslashes = 0;
158
        }
159
    }
160
    false
161
}