Skip to main content

glrmask/
error.rs

1/// The one typed decline that is a boundary request, not a mask strategy
2/// decline: `InternalBoundaryMaskStrategy::ParserDwa` refused the boundary parser DWA.
3pub(crate) const BOUNDARY_DWA_DECLINE: &str =
4    "the parser DWA for a grammar boundary would be too large; use the Auto or FastCompile boundary mask strategy";
5
6// Only deterministic plan-specific refusals qualify for the public soft
7// preferences. A general ResourceLimit (allocation failure, graph size,
8// parser control closure, etc.) is not a reason to conceal a real failure.
9pub(crate) fn is_soft_strategy_decline(error: &Error) -> bool {
10    match error.kind() {
11        ErrorKind::StrategyUnsupported => true,
12        ErrorKind::ResourceLimit => {
13            let m = error.message();
14            m.ends_with(" build budget exhausted")
15                || m == "the grammar is too large to normalize"
16                || (m.starts_with("projected L1 partition ") && m.contains("exceeding GLRMASK_L1_SINGLE_MAX_STATES="))
17        }
18        _ => false,
19    }
20}
21
22pub(crate) fn catch_internal_invariant<T>(f: impl FnOnce() -> T) -> Result<T> {
23    glrmask_invariant::__private::catch_compilation_resource_limit(|| {
24        glrmask_invariant::__private::catch_internal_invariant_message(f)
25    })
26    .map_err(Error::ResourceLimit)?
27    .map_err(Error::Internal)
28}
29
30/// Run a fallible template attempt while letting a deterministic resource-limit
31/// unwind become a typed decline. Public entry points use this so a declined
32/// template strategy can return that decline, or attempt the opt-in
33/// terminal-ended rescue when it is explicitly enabled.
34pub(crate) fn catch_template_attempt<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {
35    catch_internal_invariant(f).and_then(|result| result)
36}
37
38pub use glrmask_vocab::{Error, ErrorKind};
39use glrmask_vocab::__private::{VocabExt as _, TokenSetExt as _};
40use glrmask_vocab::__private as error_internal;
41
42/// Crate-internal constructors and helpers for [`Error`]. The type lives in
43/// glrmask-vocab (so `Vocab::new` can return it), so these are trait methods;
44/// bring the trait into scope to write `Error::Compilation(message)`.
45#[allow(non_snake_case)]
46pub(crate) trait ErrorExt: Sized {
47    /// The grammar source or JSON Schema could not be parsed.
48    fn Syntax(message: String) -> Self;
49    /// The caller passed something invalid.
50    fn InvalidInput(message: String) -> Self;
51    /// A valid grammar could not be compiled.
52    fn Compilation(message: String) -> Self;
53    /// A bug in GLRMask: an internal invariant was violated.
54    fn Internal(message: String) -> Self;
55    /// A build exceeded a resource budget.
56    fn ResourceLimit(message: String) -> Self;
57    /// The requested strategy cannot represent this grammar exactly.
58    fn StrategyUnsupported(message: String) -> Self;
59    /// An artifact could not be serialized or loaded.
60    fn Serialization(message: String) -> Self;
61    fn VocabMismatch(message: String) -> Self;
62    /// The message, without the kind prefix or source span.
63    fn message(&self) -> &str;
64    /// Sets the source span if it isn't set yet.
65    fn with_source_span(self, span: Option<glrmask_grammar::SourceSpan>) -> Self;
66    /// A template strategy declined deterministically. Public entry points
67    /// return this error unchanged, or attempt the opt-in terminal-ended
68    /// rescue when it is explicitly enabled.
69    fn is_strategy_decline(&self) -> bool;
70    fn decline_stage(&self) -> &'static str;
71    fn classify_template_compile_message(message: String) -> Self;
72}
73
74impl ErrorExt for Error {
75    fn Syntax(message: String) -> Self {
76        error_internal::new_error(ErrorKind::Syntax, message)
77    }
78    fn InvalidInput(message: String) -> Self {
79        error_internal::new_error(ErrorKind::InvalidInput, message)
80    }
81    fn Compilation(message: String) -> Self {
82        error_internal::new_error(ErrorKind::Compilation, message)
83    }
84    fn Internal(message: String) -> Self {
85        error_internal::new_error(ErrorKind::Internal, message)
86    }
87    fn ResourceLimit(message: String) -> Self {
88        error_internal::new_error(ErrorKind::ResourceLimit, message)
89    }
90    fn StrategyUnsupported(message: String) -> Self {
91        error_internal::new_error(ErrorKind::StrategyUnsupported, message)
92    }
93    fn Serialization(message: String) -> Self {
94        error_internal::new_error(ErrorKind::Serialization, message)
95    }
96    fn VocabMismatch(message: String) -> Self {
97        error_internal::new_error(ErrorKind::VocabMismatch, message)
98    }
99    fn message(&self) -> &str {
100        error_internal::error_message(self)
101    }
102    fn with_source_span(self, span: Option<glrmask_grammar::SourceSpan>) -> Self {
103        error_internal::with_source_span(self, span)
104    }
105    fn is_strategy_decline(&self) -> bool {
106        match self.kind() {
107            ErrorKind::ResourceLimit => self.message() != BOUNDARY_DWA_DECLINE,
108            ErrorKind::StrategyUnsupported => true,
109            _ => false,
110        }
111    }
112    fn decline_stage(&self) -> &'static str {
113        // Order matters: a longer stage name before its prefix.
114        const STAGES: [&str; 11] = [
115            "glr_table_lr1",
116            "glr_table_collapse",
117            "glr_table",
118            "o2_quotient_materialize",
119            "runtime_tokenizer_join",
120            "split_terminal_dwa_wall",
121            "template_determinization",
122            "template_specialization",
123            "grammar_normalization",
124            "single_use_inlining",
125            "bound_reduction_length",
126        ];
127        let message = self.message();
128        match self.kind() {
129            ErrorKind::ResourceLimit => {
130                if let Some(stage) = STAGES.into_iter().find(|stage| message.starts_with(stage)) {
131                    stage
132                } else if message == BOUNDARY_DWA_DECLINE {
133                    "boundary_parser_dwa"
134                } else if message.starts_with("parser_dwa") {
135                    "parser_dwa"
136                } else {
137                    "template"
138                }
139            }
140            ErrorKind::StrategyUnsupported if message.contains("right-recursive cycle") => "glr_table",
141            _ => "template",
142        }
143    }
144    fn classify_template_compile_message(message: String) -> Self {
145        if message.contains("right-recursive cycle") || message.contains("reduction cycle") {
146            Self::StrategyUnsupported(message)
147        } else {
148            Self::Compilation(message)
149        }
150    }
151}
152
153/// Converts a grammar front-end error. Not a `From` impl, so the internal
154/// crate's error type never becomes part of the public API.
155pub(crate) fn from_grammar(error: glrmask_grammar::Error) -> Error {
156    match error {
157        glrmask_grammar::Error::GrammarParse(message) => Error::Syntax(message),
158        glrmask_grammar::Error::GrammarParseAt { message, span } => {
159            Error::Syntax(message).with_source_span(Some(span))
160        }
161    }
162}
163
164/// Converts a weighted-automata error.
165pub(crate) fn from_automata(error: glrmask_weighted_automata::Error) -> Error {
166    match error {
167        glrmask_weighted_automata::Error::Compilation(message) => Error::Compilation(message),
168    }
169}
170
171/// A `Compilation` error, for integration tests and examples that implement
172/// `ParserCompiler`. Not part of the supported API.
173#[cfg(feature = "internal-api")]
174pub fn compilation_error(message: String) -> Error {
175    Error::Compilation(message)
176}
177
178/// Rejects a token ID above the maximum supported token ID.
179pub(crate) fn check_token_id(id: u32) -> Result<()> {
180    if id > glrmask_vocab::__private::MAX_TOKEN_ID {
181        return Err(Error::InvalidInput(format!(
182            "token ID {id} is outside the supported range"
183        )));
184    }
185    Ok(())
186}
187
188/// Rejects a token set with an ID above the maximum supported token ID.
189pub(crate) fn check_token_set(tokens: &glrmask_vocab::TokenSet) -> Result<()> {
190    match tokens.range_pairs().last() {
191        Some(&(_, end)) => check_token_id(end),
192        None => Ok(()),
193    }
194}
195
196/// Rejects a vocabulary with an ID above the maximum supported token ID,
197/// and checks that this machine can allocate the per-token-ID tables a compile
198/// builds, so a lack of memory is an error rather than an abort.
199pub(crate) fn check_vocab_token_ids(vocab: &glrmask_vocab::Vocab) -> Result<()> {
200    let Some(max) = vocab.max_event_token_id() else {
201        return Ok(());
202    };
203    check_token_id(max)?;
204    let len = max as usize + 1;
205    Vec::<u32>::new().try_reserve_exact(len).map_err(|_| token_table_error(len))
206}
207
208fn token_table_error(len: usize) -> Error {
209    Error::ResourceLimit(format!("not enough memory for a table of {len} token IDs"))
210}
211
212/// A vector of `len` copies of `value`, sized by a token ID. A failed
213/// allocation is a `ResourceLimit` error instead of an abort.
214pub(crate) fn try_token_table<T: Clone>(len: usize, value: T) -> Result<Vec<T>> {
215    let mut table = Vec::new();
216    table.try_reserve_exact(len).map_err(|_| token_table_error(len))?;
217    table.resize(len, value);
218    Ok(table)
219}
220
221/// A result with a GLRMask [`Error`].
222pub type Result<T> = std::result::Result<T, Error>;
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn internal_invariant_crossing_rayon_is_returned_as_a_normal_error() {
230        let error = catch_internal_invariant(|| {
231            let _: ((), usize) = rayon::join(
232                || glrmask_invariant::__private::fail_internal_invariant("analysis coordinate escaped its domain"),
233                || 1,
234            );
235        })
236        .expect_err("the internal invariant payload must cross the Rayon boundary");
237
238        assert_eq!(error.kind(), ErrorKind::Internal);
239        assert_eq!(
240            error.to_string(),
241            "internal error (a bug in GLRMask; please report it): analysis coordinate escaped its domain"
242        );
243    }
244
245    #[test]
246    fn unrelated_panics_are_not_reclassified_as_compiler_errors() {
247        let panic = std::panic::catch_unwind(|| {
248            let _ = catch_internal_invariant(|| {
249                std::panic::resume_unwind(Box::new("unrelated panic payload"))
250            });
251        });
252
253        assert!(panic.is_err());
254    }
255}
256
257#[cfg(test)]
258mod resource_limit_tests {
259    use super::*;
260
261    #[test]
262    fn compilation_resource_limit_crosses_rayon_as_a_normal_error() {
263        let error = catch_internal_invariant(|| {
264            let _: ((), usize) = rayon::join(
265                || glrmask_invariant::__private::fail_compilation_resource_limit("projected L1 state budget"),
266                || 1,
267            );
268        }).expect_err("resource-limit signal must cross the Rayon boundary");
269        assert_eq!(error.kind(), ErrorKind::ResourceLimit);
270        assert_eq!(error.to_string(), "resource limit exceeded: projected L1 state budget");
271        assert_eq!(catch_internal_invariant(|| 42).unwrap(), 42);
272    }
273}
274
275#[cfg(test)]
276#[test]
277fn soft_preference_fallback_distinguishes_resource_failures() {
278    assert!(is_soft_strategy_decline(&Error::ResourceLimit("the grammar is too large to normalize".into())));
279    assert!(!is_soft_strategy_decline(&Error::ResourceLimit("not enough memory for a table of 128 token IDs".into())));
280    assert!(!is_soft_strategy_decline(&Error::InvalidInput("bad input".into())));
281}