1pub(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
6pub(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
30pub(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#[allow(non_snake_case)]
46pub(crate) trait ErrorExt: Sized {
47 fn Syntax(message: String) -> Self;
49 fn InvalidInput(message: String) -> Self;
51 fn Compilation(message: String) -> Self;
53 fn Internal(message: String) -> Self;
55 fn ResourceLimit(message: String) -> Self;
57 fn StrategyUnsupported(message: String) -> Self;
59 fn Serialization(message: String) -> Self;
61 fn VocabMismatch(message: String) -> Self;
62 fn message(&self) -> &str;
64 fn with_source_span(self, span: Option<glrmask_grammar::SourceSpan>) -> Self;
66 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 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
153pub(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
164pub(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#[cfg(feature = "internal-api")]
174pub fn compilation_error(message: String) -> Error {
175 Error::Compilation(message)
176}
177
178pub(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
188pub(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
196pub(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
212pub(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
221pub 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}