Skip to main content

glrmask\public_api/
module.rs

1//! Owned assembly snapshots. Local compilation is independent of occurrence bindings.
2#[cfg(test)]
3use crate::test_modes::MaskMode;
4use super::*;
5use super::expr::{check_expr_unbound, ExprNode, ExprLeaf};
6use std::collections::{HashMap, BTreeMap, BTreeSet};
7mod artifact;
8#[cfg(test)]
9mod mixed_validation;
10#[cfg(test)]
11thread_local! { static BIND_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }
12
13
14/// Options for compiling a grammar or module.
15#[derive(Debug, Clone, Default, PartialEq, Eq)]
16#[non_exhaustive]
17pub struct CompileOptions {
18    mask_strategy: MaskStrategy,
19    internal_mask: Option<InternalMaskStrategy>,
20    retry_mask: Option<InternalMaskStrategy>,
21    internal_boundary: Option<InternalBoundaryMaskStrategy>,
22}
23
24impl CompileOptions {
25
26    /// Defaults to `MaskStrategy::AUTO`.
27    pub fn mask_strategy(mut self, strategy: MaskStrategy) -> Self {
28        self.mask_strategy = strategy;
29        self.internal_mask = None;
30        self.retry_mask = None;
31        self
32    }
33
34    #[cfg(any(test, feature = "internal-api"))]
35    #[doc(hidden)]
36    pub fn internal_mask_strategy(mut self, strategy: impl Into<InternalMaskStrategy>) -> Self {
37        self.internal_mask = Some(strategy.into());
38        self.retry_mask = None;
39        self
40    }
41
42    #[cfg(any(test, feature = "internal-api"))]
43    #[doc(hidden)]
44    pub fn internal_boundary_mask_strategy(mut self, strategy: InternalBoundaryMaskStrategy) -> Self {
45        self.internal_boundary = Some(strategy);
46        self
47    }
48
49    fn selected_strategy(&self) -> InternalMaskStrategy {
50        self.internal_mask.or(self.retry_mask).unwrap_or_else(|| self.mask_strategy.clone().into())
51    }
52
53    fn selected_boundary(&self) -> InternalBoundaryMaskStrategy {
54        self.internal_boundary.unwrap_or(InternalBoundaryMaskStrategy::Auto)
55    }
56
57    fn can_fallback(&self, error: &Error) -> bool {
58        if self.soft() { crate::error::is_soft_strategy_decline(error) }
59        else { error.is_strategy_decline() }
60    }
61    fn soft(&self) -> bool { self.internal_mask.is_none() }
62    fn prefers_fast_masks(&self) -> bool { self.soft() && self.retry_mask.is_none() && self.mask_strategy == MaskStrategy::FAST_MASKS }
63    fn prefers_fast_compile(&self) -> bool { self.soft() && self.retry_mask.is_none() && self.mask_strategy == MaskStrategy::FAST_COMPILE }
64    fn retry_with(&self, engine: InternalMaskStrategy) -> Self {
65        let mut retry = self.clone();
66        retry.retry_mask = Some(engine);
67        retry
68    }
69    /// The internal engine for these options.
70    pub(crate) fn engine(&self) -> Result<Engine> {
71        Ok(engine_for(self.selected_strategy()))
72    }
73
74    pub(crate) fn parser_backend(&self) -> ParserBackend {
75        self.selected_strategy().token_trie_backend()
76    }
77
78    pub(crate) fn merge_equivalent_tokens(&self) -> bool {
79        self.selected_strategy().merges_tokens()
80    }
81
82    /// The TokenTrie parser backend for these options.
83    fn token_trie_backend(&self) -> crate::runtime::parser_backend::DynamicParserBackend {
84        token_trie_backend(self.selected_strategy().token_trie_backend())
85    }
86}
87
88impl InternalMaskStrategy {
89    pub(crate) fn token_trie_backend(self) -> ParserBackend {
90        match self {
91            Self::TokenTrie(settings) => settings.backend(),
92            _ => ParserBackend::LrTable,
93        }
94    }
95
96    pub(crate) fn merges_tokens(self) -> bool {
97        match self {
98            Self::TokenTrie(settings) => settings.merges(),
99            _ => false,
100        }
101    }
102}
103
104pub(super) enum Binding {
105    Module(Module),
106    Constraint(CompiledPart),
107    Grammar(Grammar),
108    Expr(Expr),
109    TokenSet(TokenSet),
110}
111
112#[derive(Debug, Clone)]
113pub(crate) enum BoundValue {
114    Module(Module),
115    Compiled(CompiledPart),
116    TokenSet(TokenSet),
117}
118
119#[derive(Debug, Clone)]
120pub enum CompiledPart {
121    Ready(Arc<dyn RetainedConstraint>),
122    Deferred { bytes: Arc<[u8]>, fingerprint: [u8; 32] },
123}
124// Hide recursive GSS internals from downstream auto-trait resolution, just
125// as RetainedPreparation does. The compiler checks Send + Sync here once.
126pub trait RetainedConstraint: Send + Sync + std::fmt::Debug {
127    fn constraint(&self) -> &Constraint;
128}
129impl RetainedConstraint for Constraint {
130    fn constraint(&self) -> &Constraint { self }
131}
132impl From<Constraint> for CompiledPart {
133    fn from(value: Constraint) -> Self { Self::Ready(Arc::new(value)) }
134}
135impl CompiledPart {
136    fn fingerprint(&self) -> [u8; 32] {
137        match self {
138            Self::Ready(c) => c.constraint().runtime().vocab_fingerprint(),
139            Self::Deferred { fingerprint, .. } => *fingerprint,
140        }
141    }
142    fn save(&self) -> Vec<u8> {
143        match self {
144            Self::Ready(c) => c.constraint().save(),
145            Self::Deferred { bytes, .. } => bytes.to_vec(),
146        }
147    }
148    fn materialize(&self, vocab: &Vocab, boundary_strategy: InternalBoundaryMaskStrategy) -> Result<RuntimeConstraint> {
149        let mut child = match self {
150            Self::Ready(c) => c.constraint().runtime().clone(),
151            Self::Deferred { bytes, .. } => Constraint::load(bytes, vocab)?.runtime().clone(),
152        };
153        child.materialize_composition_link_metadata_for_compilation().map_err(Error::Compilation)?;
154        if !child.has_template_parser() {
155            child.install_template_parser()?;
156        }
157        if child.end_tokens.is_empty() { return Ok(child); }
158        // Root end-token policy originated from an explicit trailing TokenSet.
159        // At an embedded boundary it must consume that token before returning.
160        let ids = child.end_tokens.to_vec();
161        child = child.with_end_tokens(&[])?;
162        let grammar = Grammar::from_glrm("extern grammar BODY extern token END start root nt root = BODY END")?;
163        let wrapper = Module::new(&grammar)
164            .bound("BODY", Binding::Constraint(Constraint::from_runtime(child).into()))?
165            .bound("END", Binding::TokenSet(TokenSet::new(ids)))?;
166        let options = CompileOptions::default().mask_strategy(MaskStrategy::FAST_COMPILE);
167        let mut wrapper = wrapper;
168        wrapper.precompile_for_compile(vocab, &options)?;
169        wrapper.materialize(vocab, &mut HashMap::new(), boundary_strategy)
170    }
171}
172
173/// A partially compiled grammar.
174#[derive(Debug, Clone)]
175pub struct Module {
176    pub(crate) node: Arc<Node>,
177}
178
179#[derive(Debug, Clone)]
180pub(crate) struct Node {
181    pub(crate) source: Arc<Grammar>,
182    pub(crate) prepared: BTreeMap<u8, Arc<dyn RetainedPreparation>>,
183    // The vocabulary identity survives even a precompile that retains no body.
184    pub(crate) precompiled_vocab: Option<[u8; 32]>,
185    pub(crate) bindings: OrdMap<String, BoundValue>,
186    pub(crate) certificate: Arc<OnceLock<Result<Arc<Certificate>>>>,
187    #[cfg(test)]
188    pub(crate) force_boundary_dwa_decline: std::sync::Arc<std::sync::atomic::AtomicBool>,
189    #[cfg(test)]
190    pub(crate) force_parser_dwa_decline: std::sync::Arc<std::sync::atomic::AtomicBool>,
191}
192
193pub(crate) trait RetainedPreparation: Send + Sync + std::fmt::Debug {
194    fn prepared(&self) -> &PreparedGrammar;
195    /// Rehydrates a vocabulary-free retained body, or returns an equivalent
196    /// already-bound preparation.
197    fn rehydrate_vocab(&self, vocab: &Vocab) -> Result<Arc<dyn RetainedPreparation>>;
198}
199impl RetainedPreparation for PreparedGrammar {
200    fn prepared(&self) -> &PreparedGrammar { self }
201    fn rehydrate_vocab(&self, vocab: &Vocab) -> Result<Arc<dyn RetainedPreparation>> {
202        let Some(wire) = self.retained_artifact.as_ref() else {
203            return Ok(Arc::new(self.clone()));
204        };
205        if self.retained_vocab_fingerprint != Some(crate::compiler::compile::vocab_fingerprint(vocab)) {
206            return Err(Error::VocabMismatch("the module was precompiled for a different vocabulary".to_owned()));
207        }
208        prepared_artifact::load(wire.as_ref(), Some(vocab))
209            .map(|prepared| Arc::new(prepared) as Arc<dyn RetainedPreparation>)
210    }
211}
212impl std::ops::Deref for dyn RetainedPreparation {
213    type Target = PreparedGrammar;
214    fn deref(&self) -> &Self::Target { self.prepared() }
215}
216pub(crate) fn retain_local(prepared: PreparedGrammar) -> Arc<dyn RetainedPreparation> {
217    Arc::new(prepared)
218}
219
220#[derive(Debug, Clone, Default)]
221pub(crate) struct Certificate {
222    height: usize,
223    instances: u128,
224    ports: u128,
225    target: Option<[u8; 32]>,
226    pending_sets: Vec<TokenSet>,
227}
228impl Certificate {
229    fn target(&mut self, vocab: &Vocab) -> Result<()> {
230        self.target_fingerprint(crate::compiler::compile::vocab_fingerprint(vocab))
231    }
232    fn target_fingerprint(&mut self, fingerprint: [u8; 32]) -> Result<()> {
233        if self.target.is_some_and(|v| v != fingerprint) {
234            return Err(Error::VocabMismatch("the bound modules were precompiled for different vocabularies".to_owned()));
235        }
236        if self.target.is_none() {
237            // The first supplied vocabulary must validate every pending token
238            // set. Set the target first so `tokens` checks rather than requeues.
239            self.target = Some(fingerprint);
240            for set in std::mem::take(&mut self.pending_sets) {
241                self.tokens(&set)?;
242            }
243        }
244        Ok(())
245    }
246    fn tokens(&mut self, _set: &TokenSet) -> Result<()> {
247        Ok(())
248    }
249    fn value(&mut self, value: &BoundValue) -> Result<()> {
250        match value {
251            BoundValue::TokenSet(set) => self.tokens(set)?,
252            BoundValue::Compiled(c) => self.target_fingerprint(c.fingerprint())?,
253            BoundValue::Module(m) => {
254                let child = m.certificate()?;
255                self.height = self.height.max(child.height + 1);
256                if let Some(v) = child.target { self.target_fingerprint(v)?; }
257                for set in &child.pending_sets { self.tokens(set)?; }
258            }
259        }
260        Ok(())
261    }
262}
263
264fn error(message: impl Into<String>) -> Error { Error::Compilation(message.into()) }
265fn invalid(message: impl Into<String>) -> Error { Error::InvalidInput(message.into()) }
266fn resource_limit(message: impl Into<String>) -> Error { Error::ResourceLimit(message.into()) }
267
268fn own_local(grammar: &Grammar) -> Grammar {
269    Grammar {
270        source: grammar.source.clone(),
271        module_snapshot: Arc::new(OnceLock::new()),
272        bindings: OrdMap::new(),
273        declarations_cache: grammar.declarations_cache.clone(),
274        analysis: graph::empty_cache(),
275        parsed_component: grammar.parsed_component.clone(),
276        exact_value: grammar.exact_value.clone(),
277        lark_document: grammar.lark_document.clone(),
278    }
279}
280
281/// The best retained preparation, in mask-speed order: `ParserDwa` (key 1),
282/// merged `TokenTrie` (key 3), then a retained template-DFA `TokenTrie` shell
283/// (key 2).
284fn best_retained(prepared: &BTreeMap<u8, Arc<dyn RetainedPreparation>>) -> Option<Engine> {
285    if prepared.contains_key(&Engine::ParserDwa.key()) {
286        Some(Engine::ParserDwa)
287    } else if prepared.contains_key(&Engine::MergedTokenTrie.key()) {
288        Some(Engine::MergedTokenTrie)
289    } else if prepared.contains_key(&Engine::TokenTrie.key()) {
290        Some(Engine::TokenTrie)
291    } else {
292        None
293    }
294}
295
296/// Compare reusable preparations by the same strength ordering as best_retained.
297fn preparation_strength(engine: Engine) -> u8 {
298    match engine {
299        Engine::Auto => 0,
300        Engine::TokenTrie => 1,
301        Engine::MergedTokenTrie => 2,
302        Engine::ParserDwa => 3,
303    }
304}
305
306/// Source-local work is shared between occurrences. Lark preparations with
307/// bound exact-token externs also contain the resolved bindings, so do not
308/// share them between distinct module snapshots.
309fn local_preparation_key(module: &Module) -> (usize, usize) {
310    let source = Arc::as_ptr(&module.node.source.parsed_component) as usize;
311    let instance = if matches!(module.node.source.source, GrammarSource::Lark(_))
312        && module.node.bindings.values().any(|value| matches!(value, BoundValue::TokenSet(_)))
313    {
314        Arc::as_ptr(&module.node) as usize
315    } else {
316        0
317    };
318    (source, instance)
319}
320
321/// How one node is compiled by the current call.
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323struct NodePlan {
324    /// The engine preparation this node uses or builds.
325    engine: Engine,
326    /// The parser backend for a `TokenTrie` build.
327    backend: ParserBackend,
328}
329
330/// Resolve one node's plan. `any_retained` is true when any node in the graph
331/// already owns compiled machinery; a `TokenTrie` built in that graph must be
332/// template-backed because it will be linked with template parts.
333fn plan_node(
334    requested: Engine,
335    prepared: &BTreeMap<u8, Arc<dyn RetainedPreparation>>,
336    any_retained: bool,
337    requested_backend: ParserBackend,
338) -> NodePlan {
339    let retained = best_retained(prepared);
340    match requested {
341        Engine::Auto => NodePlan {
342            engine: retained.unwrap_or(Engine::ParserDwa),
343            backend: ParserBackend::TemplateDfa,
344        },
345        Engine::ParserDwa => NodePlan {
346            engine: Engine::ParserDwa,
347            backend: ParserBackend::TemplateDfa,
348        },
349        Engine::MergedTokenTrie => NodePlan {
350            engine: match retained {
351                Some(Engine::ParserDwa) | Some(Engine::MergedTokenTrie) => retained.unwrap(),
352                _ => Engine::MergedTokenTrie,
353            },
354            backend: if any_retained {
355                ParserBackend::TemplateDfa
356            } else {
357                requested_backend
358            },
359        },
360        Engine::TokenTrie => match retained {
361            Some(engine) => NodePlan {
362                engine,
363                backend: ParserBackend::TemplateDfa,
364            },
365            None => NodePlan {
366                engine: Engine::TokenTrie,
367                backend: if any_retained {
368                    ParserBackend::TemplateDfa
369                } else {
370                    requested_backend
371                },
372            },
373        },
374    }
375}
376
377/// A node plan with an LR-table TokenTrie body retains nothing: an LR merged
378/// body is not kept either, exactly like an unmerged LR TokenTrie build.
379fn retains_nothing(plan: NodePlan) -> bool {
380    plan.backend == ParserBackend::LrTable
381        && matches!(plan.engine, Engine::TokenTrie | Engine::MergedTokenTrie)
382}
383
384pub(crate) fn target_boundary() -> BoundaryTriggerDetail {
385    // The public boundary trigger is always the LLM token set. InternalBoundaryMaskStrategy
386    // selects the boundary-parser wiring only.
387    BoundaryTriggerDetail::TokenSet
388}
389
390impl Module {
391    #[cfg(test)]
392    pub(crate) fn force_boundary_dwa_decline(&mut self) {
393        Arc::make_mut(&mut self.node)
394            .force_boundary_dwa_decline
395            .store(true, std::sync::atomic::Ordering::Relaxed);
396    }
397
398    #[cfg(test)]
399    pub(crate) fn force_parser_dwa_decline(&mut self) {
400        Arc::make_mut(&mut self.node)
401            .force_parser_dwa_decline
402            .store(true, std::sync::atomic::Ordering::Relaxed);
403    }
404}
405
406impl Grammar {
407    pub(crate) fn module(&self) -> Module { Module::new(self) }
408}
409
410impl Module {
411
412    /// Starts with the grammar and its unbound externs.
413    pub fn new(grammar: &Grammar) -> Self {
414        fn convert(grammar: &Grammar, cache: &mut HashMap<usize, Module>) -> Module {
415            if let Some(module) = grammar.module_snapshot.get() { return module.clone(); }
416            let id = graph::source_identity(grammar);
417            if let Some(module) = cache.get(&id) { return module.clone(); }
418            let mut bindings = OrdMap::new();
419            for (name, value) in &grammar.bindings {
420                let value = match value {
421                    GrammarValue::Source(child) => BoundValue::Module(convert(child, cache)),
422                    GrammarValue::TokenSet(t) => BoundValue::TokenSet(t.clone()),
423                };
424                bindings.insert(name.clone(), value);
425            }
426            let module = Module {
427                node: Arc::new(Node {
428                    source: Arc::new(own_local(grammar)),
429                    prepared: BTreeMap::new(),
430                    precompiled_vocab: None,
431                    bindings,
432                    certificate: Arc::new(OnceLock::new()),
433                    #[cfg(test)]
434                    force_boundary_dwa_decline: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
435                    #[cfg(test)]
436                    force_parser_dwa_decline: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
437                }),
438            };
439            let _ = grammar.module_snapshot.set(module.clone());
440            let module = grammar.module_snapshot.get().cloned().unwrap_or(module);
441            cache.insert(id, module.clone());
442            module
443        }
444        convert(grammar, &mut HashMap::new())
445    }
446
447    /// Binds an extern by name.
448    pub fn bind(&mut self, name: &str, value: impl Into<Expr>) -> Result<()> {
449        let expr = value.into();
450        let mut leaf = &expr;
451        while let ExprNode::Sequence(parts) = leaf.0.as_ref() {
452            if parts.len() != 1 { break; }
453            leaf = &parts[0];
454        }
455        let binding = match leaf.0.as_ref() {
456            ExprNode::Leaf(ExprLeaf::Grammar(g)) => Binding::Grammar(g.clone()),
457            ExprNode::Leaf(ExprLeaf::Module(m)) => Binding::Module(m.clone()),
458            ExprNode::Leaf(ExprLeaf::Constraint(c)) => Binding::Constraint(c.clone()),
459            ExprNode::Leaf(ExprLeaf::TokenSet(t)) => Binding::TokenSet(t.clone()),
460            _ => Binding::Expr(expr),
461        };
462        let next = self.bound(name, binding)?;
463        *self = next;
464        Ok(())
465    }
466
467    // Lets bindings surface a parse error where the Rust view must stay infallible.
468    #[cfg(any(test, feature = "internal-api"))]
469    #[doc(hidden)]
470    pub fn check_source(&self) -> Result<()> {
471        self.node.source.declarations().map(|_| ())
472    }
473
474    /// All extern declarations, including bound externs.
475    pub fn externs(&self) -> Externs { Externs::snapshot(ExternsSource::Module(self)) }
476
477    fn bound_module(
478        name: &str,
479        kind: ExternKind,
480        declared: &GlrmExternalDeclarations,
481        child: Module,
482    ) -> Result<BoundValue> {
483        check_binding_kind(name, kind, true)
484            .map_err(|e| e.with_source_span(declared.spans.get(name).copied()))?;
485        let unbound = child.externs().unbound();
486        if !unbound.is_empty() {
487            let names: Vec<String> = unbound.iter().map(|e| e.name().to_string()).collect();
488            return Err(invalid(format!("cannot bind {name:?} to a value with unbound externs: {}", names.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", "))));
489        }
490        Ok(BoundValue::Module(child))
491    }
492
493    fn bound(&self, name: &str, binding: Binding) -> Result<Self> {
494        if name.contains("::") {
495            return Err(invalid(format!("there is no extern named {name:?}")));
496        }
497        let declared = self.node.source.declarations()?;
498        let Some(&kind) = declared.kinds.get(name) else {
499            return Err(invalid(format!("there is no extern named {name:?}")));
500        };
501        if self.node.bindings.contains_key(name) {
502            return Err(invalid(format!("extern \"{name}\" is already bound")));
503        }
504        let value = match binding {
505            Binding::Grammar(grammar) => {
506                Self::bound_module(name, kind, declared, Module::new(&grammar))?
507            }
508            Binding::Module(child) => Self::bound_module(name, kind, declared, child)?,
509            Binding::Constraint(c) => {
510                check_binding_kind(name, kind, true).map_err(|e| e.with_source_span(declared.spans.get(name).copied()))?;
511                BoundValue::Compiled(c)
512            }
513            Binding::Expr(expr) => {
514                check_binding_kind(name, kind, true)
515                    .map_err(|e| e.with_source_span(declared.spans.get(name).copied()))?;
516                let unbound = check_expr_unbound(&expr);
517                if !unbound.is_empty() {
518                    return Err(invalid(format!("cannot bind {name:?} to a value with unbound externs: {}", unbound.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", "))));
519                }
520                let child = Module::from_expr(&expr, true)?;
521                BoundValue::Module(child)
522            }
523            Binding::TokenSet(tokens) => {
524                crate::error::check_token_set(&tokens)?;
525                check_binding_kind(name, kind, false)
526                    .map_err(|e| e.with_source_span(declared.spans.get(name).copied()))?;
527                BoundValue::TokenSet(tokens)
528            }
529        };
530
531        let previous = self.certificate()?;
532        let mut certificate = previous.as_ref().clone();
533        certificate.value(&value)?;
534        let counts = |v: Option<&BoundValue>| -> Result<(u128, u128)> {
535            if let Some(BoundValue::Module(m)) = v {
536                let c = m.certificate()?;
537                Ok((c.instances, c.ports))
538            } else {
539                Ok((0, 0))
540            }
541        };
542        let old = self.node.bindings.get(name);
543        let (old_nodes, old_ports) = counts(old)?;
544        let (new_nodes, new_ports) = counts(Some(&value))?;
545        certificate.instances = if certificate.instances == u128::MAX { u128::MAX } else { certificate.instances.saturating_sub(old_nodes).saturating_add(new_nodes) };
546        certificate.ports = if certificate.ports == u128::MAX { u128::MAX } else { certificate.ports.saturating_sub(old_ports).saturating_add(new_ports).saturating_add(u128::from(old.is_none())) };
547        let mut next = self.clone();
548        let node = Arc::make_mut(&mut next.node);
549        node.bindings.insert(name.to_owned(), value);
550        node.certificate = Arc::new(OnceLock::from(Ok(Arc::new(certificate))));
551        next.check_limits()?;
552        Ok(next)
553    }
554
555    pub(crate) fn from_expr(expr: &Expr, allow_modules: bool) -> Result<Self> {
556        let (grammar, leaves) = expr.skeleton(allow_modules)?;
557        let mut module = Module::new(&grammar);
558        for (name, leaf) in leaves {
559            module = module.bound(&name, leaf)?;
560        }
561        Ok(module)
562    }
563
564    pub(crate) fn certificate(&self) -> Result<Arc<Certificate>> {
565        self.node.certificate.get_or_init(|| {
566            #[cfg(test)]
567            BIND_WORK.with(|c| c.set(c.get() + 1));
568            let mut c = Certificate { instances: 1, ports: self.node.bindings.len() as u128, ..Certificate::default() };
569            if let Some(fingerprint) = self.node.precompiled_vocab {
570                c.target_fingerprint(fingerprint)?;
571            }
572            for p in self.node.prepared.values() {
573                // A loaded retained body may not have its vocabulary bytes yet.
574                c.target_fingerprint(p.retained_vocab_fingerprint
575                    .unwrap_or_else(|| p.inner.vocab_fingerprint()))?;
576            }
577            if let Some(t) = &self.node.source.exact_value { c.tokens(t)?; }
578            for value in self.node.bindings.values() {
579                c.value(value)?;
580                if let BoundValue::Module(m) = value {
581                    let child = m.certificate()?;
582                    c.instances = c.instances.saturating_add(child.instances);
583                    c.ports = c.ports.saturating_add(child.ports);
584                }
585            }
586            if c.height > graph::MAX_DEPTH { return Err(resource_limit("grammars are nested more than 64 levels deep")); }
587            Ok(Arc::new(c))
588        }).clone()
589    }
590
591    fn check_limits(&self) -> Result<()> {
592        let c = self.certificate()?;
593        if c.height > graph::MAX_DEPTH { return Err(resource_limit("grammars are nested more than 64 levels deep")); }
594        if c.instances > graph::MAX_NODES as u128 || c.ports > 1_048_576 { self.index()?; }
595        Ok(())
596    }
597
598    pub(crate) fn index(&self) -> Result<Vec<Module>> {
599        fn visit(module: &Module, active: &mut BTreeSet<usize>, done: &mut BTreeSet<usize>, out: &mut Vec<Module>, depth: usize) -> Result<()> {
600            if depth > graph::MAX_DEPTH { return Err(resource_limit("grammars are nested more than 64 levels deep")); }
601            #[cfg(test)]
602            BIND_WORK.with(|c| c.set(c.get() + 1));
603            let id = Arc::as_ptr(&module.node) as usize;
604            if active.contains(&id) { return Err(invalid("a module is bound inside itself")); }
605            if done.contains(&id) { return Ok(()); }
606            active.insert(id);
607            for value in module.node.bindings.values() {
608                if let BoundValue::Module(child) = value { visit(child, active, done, out, depth + 1)?; }
609            }
610            active.remove(&id);
611            done.insert(id);
612            out.push(module.clone());
613            if out.len() > graph::MAX_NODES { return Err(resource_limit("the composition has too many parts")); }
614            Ok(())
615        }
616        let mut out = Vec::new();
617        visit(self, &mut BTreeSet::new(), &mut BTreeSet::new(), &mut out, 0)?;
618        let mut summaries = HashMap::<usize, (usize, usize)>::new();
619        let mut ports = 0usize;
620        for module in &out {
621            let mut height = 0;
622            let mut expanded = 1usize;
623            ports = ports.saturating_add(module.node.bindings.len());
624            if ports > 1_048_576 { return Err(resource_limit("the composition has too many externs")); }
625            for value in module.node.bindings.values() {
626                if let BoundValue::Module(child) = value {
627                    let (h, e) = summaries[&(Arc::as_ptr(&child.node) as usize)];
628                    height = height.max(h + 1);
629                    expanded = expanded.saturating_add(e);
630                }
631            }
632            if height > graph::MAX_DEPTH { return Err(resource_limit("grammars are nested more than 64 levels deep")); }
633            summaries.insert(Arc::as_ptr(&module.node) as usize, (height, expanded));
634        }
635        Ok(out)
636    }
637
638    pub(crate) fn validate_targets(&self, supplied: Option<&Vocab>) -> Result<()> {
639        let mut c = self.certificate()?.as_ref().clone();
640        if let Some(v) = supplied { c.target(v)?; }
641        Ok(())
642    }
643
644    /// Retained precompiled work is vocabulary-specific. Verify it against the
645    /// vocabulary of the compile or precompile call that will use it.
646    fn validate_retained_vocab(&self, vocab: &Vocab) -> Result<()> {
647        let expected = crate::compiler::compile::vocab_fingerprint(vocab);
648        for module in &self.index()? {
649            for prepared in module.node.prepared.values() {
650                let prepared = prepared.prepared();
651                let recorded = prepared
652                    .retained_vocab_fingerprint
653                    .unwrap_or_else(|| prepared.inner.vocab_fingerprint());
654                if recorded != expected {
655                    return Err(Error::VocabMismatch("the module was precompiled for a different vocabulary".to_owned()));
656                }
657            }
658        }
659        Ok(())
660    }
661
662    /// Compiles what it can now, even with externs unbound. Further compilation must use the same `vocab`.
663    pub fn precompile(&mut self, vocab: &Vocab) -> Result<()> {
664        self.precompile_with(vocab, CompileOptions::default())
665    }
666
667    /// Like `precompile()`, with `options`.
668    pub fn precompile_with(&mut self, vocab: &Vocab, options: CompileOptions) -> Result<()> {
669        with_deep_stack(|| {
670            let run = |opts: &CompileOptions| -> Result<Module> {
671                let mut candidate = self.clone();
672                // Preserve the existing internal benchmark path. Public
673                // preparation has the same bounded attempt as final compile.
674                if opts.soft() && !opts.prefers_fast_compile() {
675                    let budget = crate::compiler::build_budget::BuildBudgetScope::enter();
676                    budget.install(|| crate::error::catch_template_attempt(|| {
677                        candidate.precompile_on_stack(vocab, opts, true)
678                    }))?;
679                } else {
680                    candidate.precompile_on_stack(vocab, opts, true)?;
681                }
682                Ok(candidate)
683            };
684            let result = match run(&options) {
685                Err(error) if options.can_fallback(&error) && (options.prefers_fast_masks() || (options.soft() && options.mask_strategy == MaskStrategy::AUTO)) =>
686                    run(&options.clone().mask_strategy(MaskStrategy::FAST_COMPILE)),
687                Err(error) if options.can_fallback(&error) && options.prefers_fast_compile() =>
688                    run(&options.clone().mask_strategy(MaskStrategy::FAST_MASKS)),
689                other => other,
690            }?;
691            *self = result;
692            Ok(())
693        })
694    }
695
696    /// Rehydrates vocabulary-free retained work loaded from a Module artifact.
697    ///
698    /// Deferred bodies are decoded once here, against the vocabulary that
699    /// `validate_retained_vocab` has already checked.
700    fn rehydrate_retained(&self, vocab: &Vocab) -> Result<Module> {
701        let modules = self.index()?;
702        let mut instances = HashMap::<usize, Module>::new();
703        for m in modules {
704            let mut next = m.clone();
705            let mut c = m.certificate()?.as_ref().clone();
706            c.target(vocab)?;
707            let node = Arc::make_mut(&mut next.node);
708            for (&engine, prepared) in &m.node.prepared {
709                node.prepared.insert(engine, prepared.rehydrate_vocab(vocab)?);
710            }
711            node.certificate = Arc::new(OnceLock::from(Ok(Arc::new(c))));
712            for (name, value) in &m.node.bindings {
713                if let BoundValue::Module(child) = value {
714                    node.bindings.insert(
715                        name.clone(),
716                        BoundValue::Module(instances[&(Arc::as_ptr(&child.node) as usize)].clone()),
717                    );
718                }
719            }
720            instances.insert(Arc::as_ptr(&m.node) as usize, next);
721        }
722        instances
723            .remove(&(Arc::as_ptr(&self.node) as usize))
724            .ok_or_else(|| error("missing rehydrated Module root"))
725    }
726
727    /// Internal compile preparation: retain compilation artifacts and the
728    /// default boundary token set.
729    fn precompile_for_compile(&mut self, vocab: &Vocab, options: &CompileOptions) -> Result<()> {
730        with_deep_stack(|| self.precompile_on_stack(vocab, options, true))
731    }
732
733    fn precompile_on_stack(&mut self, vocab: &Vocab, options: &CompileOptions, build_boundary: bool) -> Result<()> {
734        crate::error::check_vocab_token_ids(vocab)?;
735        self.validate_targets(Some(vocab))?;
736        self.validate_retained_vocab(vocab)?;
737        if self.index()?.iter().any(|module| module.node.prepared.values().any(|prepared| {
738            prepared.prepared().retained_artifact.is_some()
739        })) {
740            *self = self.rehydrate_retained(vocab)?;
741        }
742        let modules = self.index()?;
743        let requested = options.engine()?;
744        let any_retained = modules.iter().any(|m| best_retained(&m.node.prepared).is_some() || m.node.bindings.values().any(|v| matches!(v, BoundValue::Compiled(_))));
745        let target_b = target_boundary();
746        let plan_of = |m: &Module| plan_node(requested, &m.node.prepared, any_retained, options.parser_backend());
747        let backend_of = |plan: NodePlan| token_trie_backend(plan.backend);
748
749        // A source can occur in several module snapshots with different retained
750        // engines. Reuse the strongest compatible local work; a weaker
751        // occurrence must not hide it or suppress a requested upgrade.
752        let mut locals: HashMap<(usize, usize), (Engine, Arc<dyn RetainedPreparation>)> = HashMap::new();
753
754        for m in &modules {
755            let Some(engine) = best_retained(&m.node.prepared) else { continue; };
756            let p = &m.node.prepared[&engine.key()];
757            let source = local_preparation_key(m);
758            if p.prepared().boundary_trigger >= target_b
759                && locals.get(&source).is_none_or(|(old, _)| preparation_strength(engine) > preparation_strength(*old))
760            {
761                locals.insert(source, (engine, p.clone()));
762            }
763        }
764
765        // Keep source traversal order and build at most one missing strongest
766        // preparation per compatible source.
767        let mut job_indices = HashMap::<(usize, usize), usize>::new();
768        let mut jobs: Vec<(&Module, NodePlan)> = Vec::new();
769        for m in &modules {
770            let plan = plan_of(m);
771            if retains_nothing(plan) { continue; }
772            let source = local_preparation_key(m);
773            if locals.get(&source).is_some_and(|(engine, _)| preparation_strength(*engine) >= preparation_strength(plan.engine)) {
774                continue;
775            }
776            if let Some(&index) = job_indices.get(&source) {
777                if preparation_strength(plan.engine) > preparation_strength(jobs[index].1.engine) {
778                    jobs[index] = (m, plan);
779                }
780            } else {
781                job_indices.insert(source, jobs.len());
782                jobs.push((m, plan));
783            }
784        }
785
786        let results = jobs.par_iter().map(|&(m, plan)| {
787            #[cfg(test)]
788            let _probe = preparation_probe::enter(m);
789            let source = local_preparation_key(m);
790            let (engine, prepared) = match m.prepare_local_for(vocab, plan.engine, target_b, build_boundary, backend_of(plan)) {
791                Ok(p) => (plan.engine, retain_local(p)),
792                Err(error) if (requested == Engine::Auto || options.prefers_fast_masks())
793                    && plan.engine == Engine::ParserDwa
794                    && any_retained
795                    && options.can_fallback(&error) =>
796                {
797                    // If an attempted upgrade declines, retain the best
798                    // existing compatible preparation instead of rebuilding
799                    // a weaker trie shell.
800                    if let Some((engine, p)) = locals.get(&source) {
801                        (*engine, p.clone())
802                    } else {
803                        let fallback = NodePlan { engine: Engine::TokenTrie, backend: ParserBackend::TemplateDfa };
804                        let p = m.prepare_local_for(vocab, fallback.engine, target_b, build_boundary, backend_of(fallback))?;
805                        (fallback.engine, retain_local(p))
806                    }
807                }
808                Err(error) => return Err(error),
809            };
810            Ok((source, engine, prepared))
811        }).collect::<Result<Vec<_>>>()?;
812
813        for (source, engine, prepared) in results {
814            locals.insert(source, (engine, prepared));
815        }
816
817        let mut instances = HashMap::<usize, Module>::new();
818        let fingerprint = crate::compiler::compile::vocab_fingerprint(vocab);
819        for m in modules {
820            let mut next = m.clone();
821            let mut c = m.certificate()?.as_ref().clone();
822            c.target_fingerprint(fingerprint)?;
823            let source = local_preparation_key(&m);
824            let node = Arc::make_mut(&mut next.node);
825            node.precompiled_vocab = Some(fingerprint);
826            if let Some((engine, prepared)) = locals.get(&source)
827                && node.prepared.get(&engine.key()).is_none_or(|old| old.prepared().boundary_trigger < target_b)
828            {
829                node.prepared.insert(engine.key(), prepared.clone());
830            }
831            node.certificate = Arc::new(OnceLock::from(Ok(Arc::new(c))));
832            for (name, value) in &m.node.bindings {
833                if let BoundValue::Module(child) = value {
834                    node.bindings.insert(name.clone(), BoundValue::Module(instances[&(Arc::as_ptr(&child.node) as usize)].clone()));
835                }
836            }
837            instances.insert(Arc::as_ptr(&m.node) as usize, next);
838        }
839        *self = instances.remove(&(Arc::as_ptr(&self.node) as usize)).unwrap();
840        Ok(())
841    }
842
843    fn prepare_local_for(
844        &self,
845        vocab: &Vocab,
846        engine: Engine,
847        target_b: BoundaryTriggerDetail,
848        build_boundary: bool,
849        backend: crate::runtime::parser_backend::DynamicParserBackend,
850    ) -> Result<PreparedGrammar> {
851        if let Some(existing) = self.node.prepared.get(&engine.key()) {
852            let mut upgraded = existing.prepared().clone();
853            if build_boundary && upgraded.inner.boundary_trigger.detail() < target_b {
854                Arc::make_mut(&mut upgraded.inner)
855                    .build_boundary_trigger(target_b)
856                    .map_err(Error::Compilation)?;
857            }
858            upgraded.boundary_trigger = target_b;
859            return Ok(upgraded);
860        }
861        let source = &self.node.source;
862        if matches!(source.source, GrammarSource::Lark(_)) {
863            let mut resolved = source.resolve_lark(vocab)?;
864            // Token externs (named Lark atoms) must be bound before the local
865            // component is linked; grammar externs stay open for `materialize`.
866            for (name, value) in &self.node.bindings {
867                if resolved.bindings.contains_key(name) { continue; }
868                match value {
869                    BoundValue::TokenSet(t) => resolved = resolved.bind_value(name, GrammarValue::TokenSet(t.clone()))?,
870                    BoundValue::Module(_) | BoundValue::Compiled(_) => {}
871                }
872            }
873            let mut module = Module::new(&resolved);
874            let mut instances = HashMap::<usize, Module>::new();
875            for m in module.index()? {
876                let mut next = m.clone();
877                let p = m.prepare_local_for(vocab, engine, target_b, build_boundary, backend)?;
878                let node = Arc::make_mut(&mut next.node);
879                node.prepared.insert(engine.key(), retain_local(p));
880                node.certificate = Arc::new(OnceLock::new());
881                for (name, value) in &m.node.bindings {
882                    if let BoundValue::Module(child) = value {
883                        node.bindings.insert(name.clone(), BoundValue::Module(instances[&(Arc::as_ptr(&child.node) as usize)].clone()));
884                    }
885                }
886                instances.insert(Arc::as_ptr(&m.node) as usize, next);
887            }
888            module = instances.remove(&(Arc::as_ptr(&module.node) as usize)).unwrap();
889            let mut local = module.node.prepared.get(&engine.key()).ok_or_else(|| error("module is not prepared"))?.prepared().clone();
890            for (name, value) in &module.node.bindings {
891                match value {
892                    BoundValue::Module(child) => {
893                        let child_prep = child.node.prepared.get(&engine.key()).ok_or_else(|| error("child is not prepared"))?.prepared().clone();
894                        local.bind(name, child_prep)?;
895                    }
896                    BoundValue::TokenSet(t) => local.bind(name, t.clone())?,
897                    BoundValue::Compiled(_) => return Err(error("unexpected compiled source binding")),
898                }
899            }
900            #[cfg(test)]
901            static_build_probe::record(self, engine);
902            return Ok(local);
903        }
904
905        let declared = source.declarations()?;
906        source.validate_ebnf(vocab)?;
907        source.validate_exact_target(vocab)?;
908        // A typed template decline must survive so the public boundary can
909        // attempt the rescue; only real failures are rewrapped.
910        let token_class_error = |e: Error| {
911            if e.is_strategy_decline() {
912                e
913            } else {
914                Error::Compilation(format!("cannot merge equivalent tokens for this grammar: {e}"))
915            }
916        };
917        let mut inner = match engine {
918            // Only a mixed compile prepares a TOKEN_TRIE module: a dynamic shell
919            // on the table-free parser keeps its extern slots, so it composes
920            // with retained static components.
921            Engine::TokenTrie => crate::import::compile_component_shell_dynamic_with_backend(
922                source.component()?,
923                vocab,
924                backend,
925            )?,
926            Engine::MergedTokenTrie => match source.source {
927                GrammarSource::Glrm(_) | GrammarSource::Constructed | GrammarSource::Ebnf(_) => {
928                    if backend == crate::runtime::parser_backend::DynamicParserBackend::LrTable {
929                        crate::import::compile_component_shell_balanced_lr(source.component()?, vocab, &[])
930                            .map_err(token_class_error)?
931                    } else {
932                        crate::import::compile_component_shell_balanced(source.component()?, vocab, &[])
933                            .map_err(token_class_error)?
934                    }
935                }
936                _ => {
937                    let dynamic = if backend == crate::runtime::parser_backend::DynamicParserBackend::LrTable {
938                        match &source.source {
939                            GrammarSource::Lark(s) => DynamicConstraint::from_lark_with_vocab_partition(s, vocab),
940                            GrammarSource::JsonSchema(s) => DynamicConstraint::from_json_schema_with_vocab_partition(s, vocab),
941                            _ => unreachable!(),
942                        }
943                    } else {
944                        match &source.source {
945                            GrammarSource::Lark(s) => DynamicConstraint::from_lark_with_bounded_template_parser(s, vocab),
946                            GrammarSource::JsonSchema(s) => DynamicConstraint::from_json_schema_with_bounded_template_parser(s, vocab),
947                            _ => unreachable!(),
948                        }
949                    }.map_err(token_class_error)?;
950                    let mut components = dynamic.into_constraints();
951                    if components.len() != 1 {
952                        return Err(Error::Compilation("cannot merge equivalent tokens in a grammar made of several parts".into()));
953                    }
954                    components.pop().unwrap()
955                }
956            },
957            Engine::Auto | Engine::ParserDwa => {
958                #[cfg(test)]
959                if self
960                    .node
961                    .force_parser_dwa_decline
962                    .load(std::sync::atomic::Ordering::Relaxed)
963                {
964                    return Err(Error::ResourceLimit(
965                        "the grammar is too large to normalize".into(),
966                    ));
967                }
968                let mut p = source.prepare_unlinked(vocab, BuildOptions::default())?;
969                let inner = Arc::make_mut(&mut p.inner);
970                crate::compiler::boundary_candidates::persist_boundary_candidate_summary(inner, vocab);
971                let _ = inner.late_bind_vocab.set(vocab.clone());
972                inner.install_template_parser_from_compile()?;
973                if build_boundary {
974                    inner.build_boundary_trigger(target_b).map_err(Error::Compilation)?;
975                }
976                p.boundary_trigger = target_b;
977                #[cfg(test)]
978                static_build_probe::record(self, engine);
979                return Ok(p);
980            }
981        };
982
983        let _ = inner.late_bind_vocab.set(vocab.clone());
984        if engine == Engine::MergedTokenTrie
985            && backend != crate::runtime::parser_backend::DynamicParserBackend::LrTable
986        {
987            inner.install_template_parser_from_compile()?;
988        }
989        if build_boundary {
990            inner.build_boundary_trigger(target_b).map_err(Error::Compilation)?;
991        }
992        let prepared = PreparedGrammar {
993            inner: Arc::new(inner),
994            bindings: OrdMap::new(),
995            analysis: graph::empty_cache(),
996            event_adapters: Arc::new(event_cache::ExactAdapterCache::default()),
997            boundary_trigger: target_b,
998            slot_kinds: Arc::new(declared.kinds.clone()),
999            slot_spans: Arc::new(declared.spans.clone()),
1000            retained_artifact: None,
1001            retained_vocab_fingerprint: None,
1002        };
1003        prepared.validate_local_slot_manifest(vocab)?;
1004        prepared.validate_slot_manifest()?;
1005        #[cfg(test)]
1006        static_build_probe::record(self, engine);
1007        Ok(prepared)
1008    }
1009
1010    /// Recognizes the root shorthand `Sequence([body, end-token set])` and
1011    /// returns the body module with the sorted end-token IDs.
1012    fn end_token_root(&self) -> Result<Option<(Module, Vec<u32>)>> {
1013        self.end_token_root_at(0)
1014    }
1015
1016    fn end_token_root_at(&self, depth: usize) -> Result<Option<(Module, Vec<u32>)>> {
1017        if depth > 8 {
1018            return Ok(None);
1019        }
1020        let Some(body) = self.node.source.single_rule_body() else {
1021            return Ok(None);
1022        };
1023        match body {
1024            crate::grammar::ast::GrammarExpr::Sequence(parts) if parts.len() == 2 => {
1025                let (crate::grammar::ast::GrammarExpr::Ref(a), crate::grammar::ast::GrammarExpr::Ref(b)) =
1026                    (&parts[0], &parts[1])
1027                else {
1028                    return Ok(None);
1029                };
1030                let (Some(BoundValue::Module(body)), Some(BoundValue::TokenSet(tokens))) =
1031                    (self.node.bindings.get(a), self.node.bindings.get(b))
1032                else {
1033                    return Ok(None);
1034                };
1035                let mut ids: Vec<u32> = tokens
1036                    .range_pairs()
1037                    .iter()
1038                    .flat_map(|&(start, end)| start..=end)
1039                    .collect();
1040                ids.sort_unstable();
1041                if ids.is_empty() {
1042                    return Ok(None);
1043                }
1044                Ok(Some((body.clone(), ids)))
1045            }
1046            crate::grammar::ast::GrammarExpr::Ref(name) => {
1047                match self.node.bindings.get(name) {
1048                    Some(BoundValue::Module(body)) => body.end_token_root_at(depth + 1),
1049                    _ => Ok(None),
1050                }
1051            }
1052            _ => Ok(None),
1053        }
1054    }
1055
1056    /// Finishes compiling the module into a constraint.
1057    pub fn compile(&self, vocab: &Vocab) -> Result<Constraint> {
1058        self.compile_with(vocab, CompileOptions::default())
1059    }
1060
1061    /// Like `compile()`, with `options`.
1062    pub fn compile_with(&self, vocab: &Vocab, options: CompileOptions) -> Result<Constraint> {
1063        self.compile_inner_with(vocab, options).map(Constraint::from_runtime)
1064    }
1065
1066    pub(crate) fn compile_inner(&self, vocab: &Vocab) -> Result<RuntimeConstraint> {
1067        self.compile_inner_with(vocab, CompileOptions::default())
1068    }
1069
1070    pub(crate) fn compile_inner_with(&self, vocab: &Vocab, options: CompileOptions) -> Result<RuntimeConstraint> {
1071        let constraint = with_deep_stack(|| self.compile_with_on_stack(vocab, options, &[]))?;
1072        constraint.mask_bit_len();
1073        Ok(constraint)
1074    }
1075
1076    fn compile_with_on_stack(&self, vocab: &Vocab, options: CompileOptions, end_tokens: &[u32]) -> Result<RuntimeConstraint> {
1077        crate::error::check_vocab_token_ids(vocab)?;
1078        self.validate_targets(Some(vocab))?;
1079        self.validate_retained_vocab(vocab)?;
1080        if let Some(slot) = self.externs().unbound().iter().next() {
1081            return Err(invalid(format!("extern {:?} is unbound; bind it before compiling, or precompile to leave it open", slot.name())));
1082        }
1083        if end_tokens.is_empty()
1084            && let Some((body, ids)) = self.end_token_root()?
1085        {
1086            return body.compile_with_on_stack(vocab, options, &ids);
1087        }
1088        let modules = self.index()?;
1089        for module in &modules {
1090            module.node.source.validate_ebnf(vocab)?;
1091            module.node.source.validate_exact_target(vocab)?;
1092        }
1093        let mut expanded = HashMap::<usize, usize>::new();
1094        for module in &modules {
1095            let mut count = 1usize;
1096            for value in module.node.bindings.values() {
1097                if let BoundValue::Module(child) = value {
1098                    count = count.saturating_add(expanded[&(Arc::as_ptr(&child.node) as usize)]);
1099                }
1100            }
1101            expanded.insert(Arc::as_ptr(&module.node) as usize, count);
1102        }
1103        if expanded[&(Arc::as_ptr(&self.node) as usize)] > graph::MAX_NODES {
1104            return Err(resource_limit("the composition expands to too many parts"));
1105        }
1106        // TOKEN_TRIE without retained static work compiles the whole
1107        // composition as one ordinary Dynamic grammar, inlined at source level.
1108        // Merged requests take the same path so that a merged composition from
1109        // scratch computes one partition over the flattened grammar.
1110        // Over retained static work it is mixed: retained parts stay static and
1111        // every other module is compiled as its own dynamic component.
1112        let requested = options.engine()?;
1113        let any_retained = modules.iter().any(|m| best_retained(&m.node.prepared).is_some() || m.node.bindings.values().any(|v| matches!(v, BoundValue::Compiled(_))));
1114        // The whole-composition flatten path is only valid when the request is
1115        // a TokenTrie request and no part owns precompiled machinery.
1116        let whole = requested.is_token_trie() && !any_retained;
1117        // EXPERIMENT: one route report per top-level Module compile.
1118        let experiment = crate::compiler::terminal_ended_rescue::RescueExperiment::read();
1119        if whole {
1120            let result = self.flatten_source()?.compile_requested_token_trie(
1121                    vocab, BoundaryTriggerDetail::TokenSet,
1122                    options.parser_backend(), options.merge_equivalent_tokens(),
1123                ).and_then(|c| c.with_end_tokens(end_tokens));
1124            let result = match result {
1125                Err(error) if options.prefers_fast_compile() && options.can_fallback(&error) => {
1126                    return self.compile_with_on_stack(vocab, options.retry_with(InternalMaskStrategy::ParserDwa), end_tokens);
1127                }
1128                other => other?,
1129            };
1130            crate::compiler::terminal_ended_rescue::report_route(
1131                experiment.report_route,
1132                crate::compiler::terminal_ended_rescue::Route::Normal,
1133                requested,
1134                experiment,
1135                &crate::compiler::terminal_ended_rescue::RescueOutcome::NotTried,
1136            );
1137            return Ok(result);
1138        }
1139        let te_first = !any_retained && experiment.terminal_ended_rescue
1140            && experiment.terminal_ended_first
1141            && self.node.bindings.is_empty()
1142            && matches!(
1143                requested,
1144                Engine::ParserDwa | Engine::MergedTokenTrie | Engine::Auto
1145            );
1146        let mut route = crate::compiler::terminal_ended_rescue::Route::Normal;
1147        let mut outcome = crate::compiler::terminal_ended_rescue::RescueOutcome::NotTried;
1148        let result = (|| -> Result<RuntimeConstraint> {
1149            let try_rescue = || -> Result<RuntimeConstraint> {
1150                let grammar = self.flatten_source()?;
1151                let source = grammar.rescue_source_grammar(vocab)?;
1152                let mut constraint =
1153                    crate::compiler::terminal_ended_rescue::rescue(&source, vocab)?;
1154                apply_final_boundary_trigger(&mut constraint, target_boundary())?;
1155                constraint.with_end_tokens(end_tokens)
1156            };
1157            if te_first {
1158                match try_rescue() {
1159                    Ok(constraint) => {
1160                        route = crate::compiler::terminal_ended_rescue::Route::TerminalEnded;
1161                        outcome = crate::compiler::terminal_ended_rescue::RescueOutcome::Ok;
1162                        return Ok(constraint);
1163                    }
1164                    Err(rescue_error) => {
1165                        outcome = crate::compiler::terminal_ended_rescue::RescueOutcome::Declined(
1166                            rescue_error.to_string(),
1167                        );
1168                    }
1169                }
1170            }
1171            let build = || {
1172                let mut prepared = self.clone();
1173                let budget = crate::compiler::build_budget::BuildBudgetScope::enter();
1174                let end_tokens = end_tokens.to_vec();
1175                let compile_options = options.clone();
1176                budget.install(move || {
1177                    crate::error::catch_template_attempt(move || -> Result<RuntimeConstraint> {
1178                        prepared.precompile_for_compile(vocab, &compile_options)?;
1179                        let constraint = prepared.materialize(
1180                            vocab,
1181                            &mut HashMap::new(),
1182                            compile_options.selected_boundary(),
1183                        )?;
1184                        ensure_runnable_constraint(&constraint)?;
1185                        constraint.with_end_tokens(&end_tokens)
1186                    })
1187                })
1188            };
1189            let attempt = build();
1190            match attempt {
1191                Ok(constraint) => Ok(constraint),
1192                Err(error) if options.can_fallback(&error) => {
1193                    // Opt-in experiment: one terminal-ended rescue attempt from
1194                    // the original flattened source, restricted to plain single
1195                    // modules. Without the switch, the typed decline is returned
1196                    // unchanged.
1197                    if !any_retained && experiment.terminal_ended_rescue
1198                        && self.node.bindings.is_empty()
1199                        && !te_first
1200                    {
1201                        match try_rescue() {
1202                            Ok(constraint) => {
1203                                if crate::compiler::compile::compile_profile_enabled() {
1204                                    eprintln!(
1205                                        "[glrmask/profile][terminal_ended_rescue] strategy={requested:?} outcome=ok",
1206                                    );
1207                                }
1208                                route =
1209                                    crate::compiler::terminal_ended_rescue::Route::TerminalEnded;
1210                                outcome =
1211                                    crate::compiler::terminal_ended_rescue::RescueOutcome::Ok;
1212                                return Ok(constraint);
1213                            }
1214                            Err(rescue_error) => {
1215                                if crate::compiler::compile::compile_profile_enabled() {
1216                                    eprintln!(
1217                                        "[glrmask/profile][terminal_ended_rescue] strategy={requested:?} outcome=declined reason={rescue_error}",
1218                                    );
1219                                }
1220                                outcome =
1221                                    crate::compiler::terminal_ended_rescue::RescueOutcome::Declined(
1222                                        rescue_error.to_string(),
1223                                    );
1224                            }
1225                        }
1226                    }
1227                    if crate::compiler::compile::compile_profile_enabled() {
1228                        eprintln!(
1229                            "[glrmask/profile][template_decline] strategy={requested:?} stage={} reason={error}",
1230                            error.decline_stage(),
1231                        );
1232                    }
1233                    // Public Auto/FastMasks may fall back; strict internal
1234                    // selectors retain their original behavior. With retained
1235                    // work the per-part fallback above already kept it; the
1236                    // whole-composition retry is only allowed when nothing is
1237                    // retained.
1238                    if (requested == Engine::Auto || options.prefers_fast_masks()) && !any_retained && options.can_fallback(&error) {
1239                        // The fallback is exactly an explicit TokenTrie request
1240                        // with the same switches.
1241                        if let Ok(grammar) = self.flatten_source() {
1242                            let constraint = grammar
1243                                .compile_requested_token_trie(
1244                                    vocab,
1245                                    BoundaryTriggerDetail::TokenSet,
1246                                    options.parser_backend(),
1247                                    options.merge_equivalent_tokens(),
1248                                )?
1249                                .with_end_tokens(end_tokens)?;
1250                            route =
1251                                crate::compiler::terminal_ended_rescue::Route::TokenTrieFallback;
1252                            return Ok(constraint);
1253                        }
1254                    }
1255                    // Budget unwinds during parallel preparation can reach this outer
1256                    // handler instead of the per-node fallback. Retry with a fresh
1257                    // budget and a trie preference without discarding retained work.
1258                    if options.soft() && any_retained
1259                        && (requested == Engine::Auto || options.prefers_fast_masks()) {
1260                        return self.compile_with_on_stack(
1261                            vocab, options.retry_with(InternalMaskStrategy::FAST_COMPILE), end_tokens);
1262                    }
1263                    if options.prefers_fast_compile() {
1264                        return self.compile_with_on_stack(
1265                            vocab, options.retry_with(InternalMaskStrategy::ParserDwa), end_tokens);
1266                    }
1267                    Err(error)
1268                }
1269                Err(error) => Err(error),
1270            }
1271        })();
1272        crate::compiler::terminal_ended_rescue::report_route(
1273            experiment.report_route,
1274            route,
1275            requested,
1276            experiment,
1277            &outcome,
1278        );
1279        result
1280    }
1281
1282    fn materialize(
1283        &self,
1284        vocab: &Vocab,
1285        cache: &mut HashMap<usize, RuntimeConstraint>,
1286        boundary_strategy: InternalBoundaryMaskStrategy,
1287    ) -> Result<RuntimeConstraint> {
1288        let id = Arc::as_ptr(&self.node) as usize;
1289        if let Some(c) = cache.get(&id) { return Ok(c.clone()); }
1290        let engine = best_retained(&self.node.prepared)
1291            .ok_or_else(|| error("missing local compilation"))?;
1292        let local = self.node.prepared.get(&engine.key()).ok_or_else(|| error("missing local compilation"))?;
1293        // Rebuilding the pre-composition parent is only needed when the rare
1294        // `Auto` boundary decline has to redo composition, so keep it in a
1295        // closure instead of snapshotting the composed constraint.
1296        let build_base = || -> Result<RuntimeConstraint> {
1297            let mut base = if local.bindings.is_empty() {
1298                local.inner.as_ref().clone()
1299            } else {
1300                local.link_with(engine.build_options())?
1301            };
1302            base.materialize_composition_link_metadata_for_compilation().map_err(Error::Compilation)?;
1303            Ok(base)
1304        };
1305        let mut parent = build_base()?;
1306        let active = parent.late_grammar_slots.iter().map(|s| s.name.as_str()).collect::<BTreeSet<_>>();
1307        let children = self.node.bindings.iter().filter(|(name, _)| active.contains(name.as_str())).map(|(name, value)| {
1308            let child = match value {
1309                BoundValue::Module(child) => child.materialize(vocab, cache, boundary_strategy)?,
1310                BoundValue::Compiled(c) => c.materialize(vocab, boundary_strategy)?,
1311                BoundValue::TokenSet(t) => self.event_adapter(t.range_pairs(), vocab, parent.has_template_parser(), engine)?,
1312            };
1313            Ok((name.clone(), Arc::new(child)))
1314        }).collect::<Result<Vec<_>>>()?;
1315        let linked = !children.is_empty();
1316        let all_static = parent.has_template_parser()
1317            && children.iter().all(|(_, child)| child.has_template_parser());
1318        let mut child_token_union = Vec::new();
1319        for (_, child) in &children {
1320            if let crate::runtime::BoundaryTrigger::TokenSet(child_tokens) = &child.boundary_trigger {
1321                child_token_union.extend_from_slice(child_tokens);
1322            }
1323        }
1324        if linked {
1325            // Composition consumes the pre-composition parent. Factor it into
1326            // a closure so the rare `Auto` decline can redo composition from
1327            // the same inputs without a full `Constraint` snapshot per build.
1328            let compose = |parent: RuntimeConstraint| -> Result<RuntimeConstraint> {
1329                let composed = if all_static {
1330                    crate::error::catch_internal_invariant(|| {
1331                        crate::runtime::parser_backend::link::compose_owned(parent, children.clone(), vocab)
1332                    })??
1333                } else {
1334                    crate::error::catch_internal_invariant(|| {
1335                        compose_named_children(parent, &children, vocab, SegmentedBoundaryBackend::Dynamic)
1336                    })??
1337                };
1338                Ok(composed)
1339            };
1340            parent = compose(parent)?;
1341            // All-template compositions may still install the static boundary
1342            // parser; retained parts keep their own machinery.
1343            if boundary_strategy != InternalBoundaryMaskStrategy::TokenTrie
1344                && all_static
1345                && matches!(engine, Engine::ParserDwa | Engine::Auto)
1346            {
1347                // `Auto` mirrors `InternalMaskStrategy::Auto`: prefer the static
1348                // boundary parser, and fall back to the token-trie boundary
1349                // when it declines on budget instead of failing the build.
1350                let declined = {
1351                    #[cfg(test)]
1352                    let forced_decline = self
1353                        .node
1354                        .force_boundary_dwa_decline
1355                        .load(std::sync::atomic::Ordering::Relaxed);
1356                    #[cfg(not(test))]
1357                    let forced_decline = false;
1358                    if forced_decline {
1359                        true
1360                    } else {
1361                        match crate::compiler::template_boundary::install(&mut parent, vocab) {
1362                            Ok(()) => false,
1363                            Err(error) if crate::compiler::template_boundary::is_template_budget_decline(&error) => true,
1364                            Err(error) => return Err(error),
1365                        }
1366                    }
1367                };
1368                if declined && boundary_strategy == InternalBoundaryMaskStrategy::ParserDwa {
1369                    return Err(Error::ResourceLimit(
1370                        crate::error::BOUNDARY_DWA_DECLINE.into(),
1371                    ));
1372                }
1373                if declined {
1374                    parent = compose(build_base()?)?;
1375                }
1376            }
1377            let target_b = target_boundary();
1378            apply_final_boundary_trigger(&mut parent, target_b)?;
1379            // A composed trigger is the union of the parent's own set and the
1380            // precomputed sets of its children. Sorted merge keeps this cheap.
1381            let mut tokens = parent
1382                .boundary_trigger
1383                .token_summary()
1384                .map(|tokens| tokens.to_vec())
1385                .unwrap_or_else(|| child_token_union.clone());
1386            tokens.extend_from_slice(&child_token_union);
1387            tokens.sort_unstable();
1388            tokens.dedup();
1389            parent.boundary_trigger = crate::runtime::BoundaryTrigger::TokenSet(Arc::from(
1390                tokens.into_boxed_slice(),
1391            ));
1392        }
1393        cache.insert(id, parent.clone());
1394        Ok(parent)
1395    }
1396
1397    fn event_adapter(&self, ranges: &[(u32, u32)], vocab: &Vocab, native: bool, engine: Engine) -> Result<RuntimeConstraint> {
1398        let local = self.node.prepared.get(&engine.key()).ok_or_else(|| error("missing prepared event owner"))?;
1399        let leaf = local.event_adapters.leaf(ranges)?;
1400        Ok(leaf.compiled_for_representation(vocab, native)?.as_ref().clone())
1401    }
1402
1403    pub(super) fn to_source(&self) -> Result<Grammar> {
1404        if !self.node.prepared.is_empty() {
1405            return Err(error("a Grammar expression cannot contain a Module"));
1406        }
1407        self.flatten_source()
1408    }
1409
1410    // The whole composition as one source Grammar, with every bound child
1411    // inlined as a scoped source body. Retained work and settings are ignored.
1412    fn flatten_source(&self) -> Result<Grammar> {
1413        let mut grammar = self.node.source.as_ref().clone();
1414        for (name, value) in &self.node.bindings {
1415            let value = match value {
1416                BoundValue::Module(child) => GrammarValue::Source(Arc::new(child.flatten_source()?)),
1417                BoundValue::Compiled(_) => return Err(error("a compiled constraint cannot be flattened into source")),
1418                BoundValue::TokenSet(t) => GrammarValue::TokenSet(t.clone()),
1419            };
1420            grammar = grammar.bind_value(name, value)?;
1421        }
1422        Ok(grammar)
1423    }
1424
1425    /// Serializes the module, including any precompiled work.
1426    pub fn save(&self) -> Vec<u8> { with_deep_stack(|| artifact::save(self)) }
1427    /// May fail if saved by a different GLRMask version.
1428    pub fn load(bytes: &[u8]) -> Result<Self> {
1429        crate::artifact_load::guard(|| with_deep_stack(|| artifact::load(bytes, None)))
1430    }
1431}
1432
1433#[cfg(test)]
1434pub(crate) mod static_build_probe {
1435    use super::*;
1436    use std::sync::Mutex;
1437    // Each count keeps a liveness check for its grammar, because a dropped
1438    // grammar's address can be reused by a grammar in a parallel test.
1439    type Key = (usize, u8);
1440    type Entry = (Box<dyn Fn() -> bool + Send>, usize);
1441    fn counts() -> &'static Mutex<HashMap<Key, Entry>> {
1442        static COUNTS: OnceLock<Mutex<HashMap<Key, Entry>>> = OnceLock::new();
1443        COUNTS.get_or_init(|| Mutex::new(HashMap::new()))
1444    }
1445    fn key(m: &Module) -> usize { Arc::as_ptr(&m.node.source.parsed_component) as usize }
1446    pub(crate) fn record(m: &Module, engine: Engine) {
1447        let mut counts = counts().lock().unwrap();
1448        let entry = counts.entry((key(m), engine.key())).or_insert_with(|| (Box::new(|| false), 0));
1449        if !(entry.0)() {
1450            let weak = Arc::downgrade(&m.node.source.parsed_component);
1451            *entry = (Box::new(move || weak.strong_count() > 0), 0);
1452        }
1453        entry.1 += 1;
1454    }
1455    /// Static preparations (ParserDwa and merged) built so far for this
1456    /// module's grammar.
1457    pub(crate) fn builds(m: &Module) -> usize {
1458        let source = key(m);
1459        counts().lock().unwrap().iter().filter(|((candidate, engine), entry)| {
1460            *candidate == source && (*engine == 1 || *engine == 3) && (entry.0)()
1461        }).map(|(_, entry)| entry.1).sum()
1462    }
1463    /// Preparations built for one exact engine.
1464    pub(crate) fn builds_for(m: &Module, engine: Engine) -> usize {
1465        counts().lock().unwrap().get(&(key(m), engine.key())).filter(|e| (e.0)()).map_or(0, |e| e.1)
1466    }
1467}
1468
1469/// Records mixed-compile fallbacks on the calling test thread.
1470///
1471/// `build(mixed)` is matched on the caller, so a thread-local log attributes a
1472/// fallback to the compile that triggered it even when test threads run in
1473/// parallel.
1474#[cfg(test)]
1475pub(crate) mod mixed_compile_probe {
1476    use super::*;
1477    thread_local! {
1478        static FALLBACKS: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
1479    }
1480    pub(crate) fn record(error: &Error) {
1481        FALLBACKS.with(|log| log.borrow_mut().push(error.to_string()));
1482    }
1483    /// Drains the fallback reasons recorded since the last call.
1484    pub(crate) fn take() -> Vec<String> {
1485        FALLBACKS.with(|log| std::mem::take(&mut *log.borrow_mut()))
1486    }
1487}
1488
1489#[cfg(test)]
1490mod preparation_probe {
1491    use super::*;
1492    use std::sync::{Mutex, Condvar};
1493    use std::sync::atomic::{AtomicUsize, Ordering};
1494    pub(super) struct Probe {
1495        pub active: AtomicUsize,
1496        pub max: AtomicUsize,
1497        pub tasks: AtomicUsize,
1498        pub workers: usize,
1499        pub arrivals: Mutex<usize>,
1500        pub ready: Condvar,
1501        pub thread_ids: Mutex<BTreeSet<usize>>,
1502        pub pool_sizes: Mutex<BTreeSet<usize>>,
1503    }
1504    pub(super) fn registry() -> &'static Mutex<HashMap<usize, Arc<Probe>>> {
1505        static REGISTRY: OnceLock<Mutex<HashMap<usize, Arc<Probe>>>> = OnceLock::new();
1506        REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
1507    }
1508    pub(super) struct Guard(Option<Arc<Probe>>);
1509    pub(super) fn enter(m: &Module) -> Guard {
1510        let probe = registry().lock().unwrap().get(&(Arc::as_ptr(&m.node.source.parsed_component) as usize)).cloned();
1511        if let Some(p) = &probe {
1512            p.tasks.fetch_add(1, Ordering::SeqCst);
1513            let active = p.active.fetch_add(1, Ordering::SeqCst) + 1;
1514            p.max.fetch_max(active, Ordering::SeqCst);
1515            p.thread_ids.lock().unwrap().insert(rayon::current_thread_index().unwrap());
1516            p.pool_sizes.lock().unwrap().insert(rayon::current_num_threads());
1517            let mut arrivals = p.arrivals.lock().unwrap();
1518            *arrivals += 1;
1519            p.ready.notify_all();
1520            let (_arrivals, timeout) = p.ready.wait_timeout_while(arrivals, std::time::Duration::from_secs(10), |n| *n < p.workers).unwrap();
1521            assert!(!timeout.timed_out(), "independent definition tasks failed to enter concurrently");
1522        }
1523        Guard(probe)
1524    }
1525    impl Drop for Guard {
1526        fn drop(&mut self) {
1527            if let Some(p) = &self.0 {
1528                p.active.fetch_sub(1, Ordering::SeqCst);
1529            }
1530        }
1531    }
1532}
1533
1534#[cfg(test)]
1535mod precompile_boundary_tests {
1536    use super::*;
1537    use crate::__private::VocabExt as _;
1538
1539    fn vocab() -> Vocab {
1540        let vocab = Vocab::from_entries_unchecked(vec![
1541            (0, b"x".to_vec()),
1542            (1, b"y".to_vec()),
1543            (2, b"xy".to_vec()),
1544        ]);
1545        vocab.prepare_for_compile();
1546        vocab
1547    }
1548
1549    fn tokens(constraint: &RuntimeConstraint) -> Option<Arc<[u32]>> {
1550        match &constraint.boundary_trigger {
1551            crate::runtime::BoundaryTrigger::TokenSet(tokens) => Some(Arc::clone(tokens)),
1552            _ => None,
1553        }
1554    }
1555
1556    #[test]
1557    fn compiled_leaf_binding_does_not_prepare_a_wrapper() {
1558        let vocab = vocab();
1559        let child = Grammar::from_glrm(r#"start root; nt root = "x";"#).unwrap().compile(&vocab).unwrap();
1560        let mut parent = Module::new(&Grammar::from_glrm("extern grammar child start root nt root = child").unwrap());
1561        parent.precompile(&vocab).unwrap();
1562        let before = static_build_probe::builds(&parent);
1563        for expr in [Expr::from(&child), Expr::sequence([Expr::from(&child)])] {
1564            let mut request = parent.clone();
1565            request.bind("child", expr).unwrap();
1566            assert!(matches!(request.node.bindings.get("child"), Some(BoundValue::Compiled(_))));
1567            // The preparation traversal sees only the already-prepared parent.
1568            assert_eq!(request.index().unwrap().len(), 1);
1569            let result = request.compile(&vocab).unwrap();
1570            let mut state = result.start();
1571            assert!(state.commit_token(0));
1572            assert!(state.is_accepting());
1573            assert_eq!(static_build_probe::builds(&request), before);
1574        }
1575    }
1576
1577    #[test]
1578    fn precompile_builds_tokens_and_compile_reuses_the_same_arc() {
1579        let vocab = vocab();
1580        let grammar = Grammar::from_ebnf(r#"start ::= "x" "y" | "xy""#).unwrap();
1581
1582        let mut module = Module::new(&grammar);
1583        module.precompile(&vocab).expect("precompile");
1584        let prepared_trigger = module
1585            .node
1586            .prepared
1587            .values()
1588            .next()
1589            .and_then(|prepared| tokens(&prepared.prepared().inner))
1590            .expect("precompiled Module must carry a Tokens trigger");
1591        let compiled = module
1592            .compile_inner_with(&vocab, CompileOptions::default())
1593            .expect("compile after precompile");
1594        let compiled_trigger = tokens(&compiled).expect("compiled Module must carry Tokens");
1595        assert!(
1596            Arc::ptr_eq(&prepared_trigger, &compiled_trigger),
1597            "compile_with must reuse the precompiled Tokens Arc"
1598        );
1599        assert_eq!(prepared_trigger.as_ref(), compiled_trigger.as_ref());
1600
1601        let plain = Module::new(&grammar)
1602            .compile_inner_with(&vocab, CompileOptions::default())
1603            .expect("plain compile");
1604        assert!(tokens(&plain).is_some(), "plain compile must build the default trigger");
1605
1606        let bytes = module.save();
1607        let loaded = Module::load(&bytes).expect("Module artifact round-trip");
1608        let loaded_trigger = loaded
1609            .node
1610            .prepared
1611            .values()
1612            .next()
1613            .and_then(|prepared| tokens(&prepared.prepared().inner))
1614            .expect("loaded Module must keep its TokenSet");
1615        assert_eq!(loaded_trigger.as_ref(), prepared_trigger.as_ref());
1616
1617        let constraint_bytes = compiled.save();
1618        let mut loaded_constraint = RuntimeConstraint::load(&constraint_bytes, &vocab).expect("Constraint round-trip");
1619        loaded_constraint
1620            .materialize_composition_metadata_for_compilation()
1621            .expect("materialize loaded metadata");
1622        let loaded_constraint_trigger = tokens(&loaded_constraint).expect("loaded Constraint must keep its TokenSet");
1623        assert_eq!(loaded_constraint_trigger.as_ref(), prepared_trigger.as_ref());
1624
1625        let mut old = b"GLRASM01".to_vec();
1626        old.extend_from_slice(&bytes[8..]);
1627        let error = Module::load(&old).expect_err("old Module artifact must be rejected");
1628        assert!(error.to_string().contains("aren't a saved module"), "{error}");
1629    }
1630
1631    #[test]
1632    fn compile_after_precompile_never_downgrades_static_parts() {
1633        let vocab = vocab();
1634        let grammar = Grammar::from_ebnf(r#"start ::= "x" "y" | "xy""#).unwrap();
1635        let mut module = Module::new(&grammar);
1636        module
1637            .precompile_with(
1638                &vocab,
1639                CompileOptions::default().internal_mask_strategy(InternalMaskStrategy::ParserDwa),
1640            )
1641            .expect("precompile with ParserDwa");
1642        let prepared_trigger = module
1643            .node
1644            .prepared
1645            .get(&Engine::ParserDwa.key())
1646            .and_then(|prepared| tokens(&prepared.prepared().inner))
1647            .expect("ParserDwa preparation must carry a Tokens trigger");
1648
1649        let compiled = module
1650            .compile_inner_with(
1651                &vocab,
1652                CompileOptions::default().internal_mask_strategy(InternalMaskStrategy::FAST_COMPILE),
1653            )
1654            .expect("TokenTrie compile after ParserDwa precompile");
1655        assert!(
1656            !compiled.uses_dynamic_runtime(),
1657            "a TokenTrie request must not replace retained static parts with dynamic compilation"
1658        );
1659        let compiled_trigger = tokens(&compiled).expect("compiled Module must carry Tokens");
1660        assert!(
1661            Arc::ptr_eq(&prepared_trigger, &compiled_trigger),
1662            "compile must reuse the precompiled Tokens Arc"
1663        );
1664        assert!(
1665            module.node.prepared.contains_key(&Engine::ParserDwa.key()),
1666            "compile must not discard the retained static part"
1667        );
1668
1669        let expected = Module::new(&grammar)
1670            .compile_inner_with(&vocab, CompileOptions::default())
1671            .expect("plain ParserDwa compile");
1672        fn compare(a: &crate::ConstraintState, b: &crate::ConstraintState, depth: usize) {
1673            assert_eq!(a.mask(), b.mask(), "mask mismatch at depth {depth}");
1674            assert_eq!(a.is_accepting(), b.is_accepting(), "acceptance mismatch at depth {depth}");
1675            if depth == 0 { return; }
1676            for token in a.mask() {
1677                let mut next_a = a.clone();
1678                if !next_a.commit_token(token) { continue; }
1679                let mut next_b = b.clone();
1680                assert!(next_b.commit_token(token), "same masks accept the same token");
1681                compare(&next_a, &next_b, depth - 1);
1682            }
1683        }
1684        compare(&compiled.start(), &expected.start(), 3);
1685    }
1686
1687    #[test]
1688    fn strongest_compatible_shared_source_preparation_is_reused() {
1689        let vocab = vocab();
1690        let source = Grammar::from_ebnf(r#"start ::= "x" | "xy""#).unwrap();
1691        let mut strong = Module::new(&source);
1692        let mut merged = Module::new(&source);
1693        let fast = CompileOptions::default().mask_strategy(MaskStrategy::FAST_COMPILE);
1694        let masks = CompileOptions::default().mask_strategy(MaskStrategy::FAST_MASKS);
1695        strong.precompile_with(&vocab, masks.clone()).unwrap();
1696        merged.precompile_with(&vocab, MaskMode::C.compile_options()).unwrap();
1697        let strong_artifact = strong.node.prepared[&Engine::ParserDwa.key()].clone();
1698        let merged_artifact = merged.node.prepared[&Engine::MergedTokenTrie.key()].clone();
1699        let nstrong = static_build_probe::builds_for(&strong, Engine::ParserDwa);
1700        let nmerged = static_build_probe::builds_for(&merged, Engine::MergedTokenTrie);
1701        let host = Grammar::from_glrm("extern grammar A extern grammar B start s nt s = A B").unwrap();
1702        let mut parent = Module::new(&host);
1703        parent.bind("A", strong.clone()).unwrap();
1704        parent.bind("B", merged.clone()).unwrap();
1705        parent.precompile_with(&vocab, fast.clone()).unwrap();
1706        let BoundValue::Module(a) = parent.node.bindings.get("A").unwrap() else { panic!("A"); };
1707        let BoundValue::Module(b) = parent.node.bindings.get("B").unwrap() else { panic!("B"); };
1708        assert!(Arc::ptr_eq(&a.node.prepared[&Engine::ParserDwa.key()], &strong_artifact));
1709        assert!(Arc::ptr_eq(&b.node.prepared[&Engine::ParserDwa.key()], &strong_artifact));
1710        assert!(Arc::ptr_eq(&b.node.prepared[&Engine::MergedTokenTrie.key()], &merged_artifact));
1711        assert_eq!(static_build_probe::builds_for(&strong, Engine::ParserDwa), nstrong);
1712        assert_eq!(static_build_probe::builds_for(&merged, Engine::MergedTokenTrie), nmerged);
1713        let actual = parent.compile_inner_with(&vocab, fast).unwrap();
1714        let mut fresh = Module::new(&host);
1715        fresh.bind("A", Module::new(&source)).unwrap();
1716        fresh.bind("B", Module::new(&source)).unwrap();
1717        let expected = fresh.compile_inner_with(&vocab, masks).unwrap();
1718        same_language(&actual.start(), &expected.start(), 4);
1719    }
1720
1721    #[test]
1722    fn shared_weak_preparation_does_not_suppress_requested_upgrade() {
1723        let vocab = vocab();
1724        let source = Grammar::from_ebnf(r#"start ::= "x" | "xy""#).unwrap();
1725        let mut child = Module::new(&source);
1726        child.precompile_with(&vocab, MaskMode::C.compile_options()).unwrap();
1727        let artifact = child.node.prepared[&Engine::MergedTokenTrie.key()].clone();
1728        let host = Grammar::from_glrm("extern grammar A extern grammar B start s nt s = A B").unwrap();
1729        let mut parent = Module::new(&host);
1730        parent.bind("A", child.clone()).unwrap();
1731        parent.bind("B", Module::new(&source)).unwrap();
1732        let before = static_build_probe::builds_for(&child, Engine::ParserDwa);
1733        parent.precompile_with(&vocab, CompileOptions::default()).unwrap();
1734        let BoundValue::Module(a) = parent.node.bindings.get("A").unwrap() else { panic!("A"); };
1735        let BoundValue::Module(b) = parent.node.bindings.get("B").unwrap() else { panic!("B"); };
1736        assert!(Arc::ptr_eq(&a.node.prepared[&Engine::MergedTokenTrie.key()], &artifact));
1737        assert!(Arc::ptr_eq(&a.node.prepared[&Engine::ParserDwa.key()], &b.node.prepared[&Engine::ParserDwa.key()]));
1738        assert_eq!(static_build_probe::builds_for(&child, Engine::ParserDwa), before + 1);
1739    }
1740
1741    fn same_language(a: &crate::ConstraintState, b: &crate::ConstraintState, depth: usize) {
1742        let mask = a.mask();
1743        assert_eq!(mask, b.mask(), "mask mismatch at depth {depth}");
1744        assert_eq!(a.is_accepting(), b.is_accepting(), "acceptance mismatch at depth {depth}");
1745        if depth == 0 { return; }
1746        let tokens = mask.iter().enumerate().flat_map(|(word, bits)| {
1747            (0..32).filter(move |bit| bits & (1 << bit) != 0).map(move |bit| (word * 32 + bit) as u32)
1748        });
1749        for token in tokens {
1750            let mut next_a = a.clone();
1751            assert!(next_a.commit_token(token), "masked token commits");
1752            let mut next_b = b.clone();
1753            assert!(next_b.commit_token(token), "same masks accept the same token");
1754            same_language(&next_a, &next_b, depth - 1);
1755        }
1756    }
1757
1758    const PARENT: &str = r#"glrm 1; start start; extern grammar child; nt start = "x" child | "y" child "x";"#;
1759    const CHILD: &str = r#"start ::= "y" | "x" "y" | "xy""#;
1760
1761    fn assembly(precompile_parent: bool, precompile_child: bool) -> (Module, Module, Module) {
1762        let vocab = vocab();
1763        let static_options = CompileOptions::default().internal_mask_strategy(InternalMaskStrategy::ParserDwa);
1764        let mut child = Module::new(&Grammar::from_ebnf(CHILD).unwrap());
1765        if precompile_child {
1766            child.precompile_with(&vocab, static_options.clone()).expect("precompile child");
1767        }
1768        let mut parent = Module::new(&Grammar::from_glrm(PARENT).unwrap());
1769        if precompile_parent {
1770            parent.precompile_with(&vocab, static_options).expect("precompile unbound parent");
1771        }
1772        let mut assembly = parent.clone();
1773        assembly.bind("child", child.clone()).expect("bind child");
1774        if precompile_parent { (assembly, child, parent) } else { (assembly, parent, child) }
1775    }
1776
1777    fn reference(strategy: MaskMode) -> RuntimeConstraint {
1778        assembly(false, false)
1779            .0
1780            .compile_inner_with(&vocab(), strategy.compile_options())
1781            .expect("reference compile")
1782    }
1783
1784    #[test]
1785    fn token_trie_compile_keeps_a_precompiled_child_static_and_the_parent_dynamic() {
1786        let vocab = vocab();
1787        let (module, dynamic_part, static_part) = assembly(false, true);
1788        let before = static_build_probe::builds(&dynamic_part);
1789        let static_before = static_build_probe::builds(&static_part);
1790        let mixed = module
1791            .compile_inner_with(&vocab, CompileOptions::default().internal_mask_strategy(InternalMaskStrategy::FAST_COMPILE))
1792            .expect("mixed compile");
1793        assert_eq!(static_build_probe::builds(&dynamic_part), before, "the non-precompiled part must not be built statically");
1794        assert_eq!(static_build_probe::builds(&static_part), static_before, "the precompiled part must be reused, not rebuilt");
1795        same_language(&mixed.start(), &reference(MaskMode::ParserDwa).start(), 4);
1796        same_language(&mixed.start(), &reference(MaskMode::A).start(), 4);
1797    }
1798
1799    #[test]
1800    fn token_trie_compile_keeps_a_precompiled_parent_static_and_the_child_dynamic() {
1801        let vocab = vocab();
1802        let (module, dynamic_part, static_part) = assembly(true, false);
1803        let before = static_build_probe::builds(&dynamic_part);
1804        let static_before = static_build_probe::builds(&static_part);
1805        let mixed = module
1806            .compile_inner_with(&vocab, CompileOptions::default().internal_mask_strategy(InternalMaskStrategy::FAST_COMPILE))
1807            .expect("mixed compile");
1808        assert_eq!(static_build_probe::builds(&dynamic_part), before, "the non-precompiled part must not be built statically");
1809        assert_eq!(static_build_probe::builds(&static_part), static_before, "the precompiled part must be reused, not rebuilt");
1810        same_language(&mixed.start(), &reference(MaskMode::ParserDwa).start(), 4);
1811        same_language(&mixed.start(), &reference(MaskMode::A).start(), 4);
1812    }
1813}
1814
1815#[cfg(test)]
1816mod b_shell_tests {
1817    use super::*;
1818
1819    fn vocab() -> Vocab {
1820        Vocab::from_entries_unchecked(vec![
1821            (0, b"x".to_vec()),
1822            (1, b"a".to_vec()),
1823            (2, b"b".to_vec()),
1824            (3, b"y".to_vec()),
1825            (4, b"xay".to_vec()),
1826            (5, b"ab".to_vec()),
1827        ])
1828    }
1829
1830    #[test]
1831    fn b_shell_survives_save_and_is_reused_by_an_lr_request() {
1832        let vocab = vocab();
1833        let grammar = Grammar::from_ebnf(r#"start ::= "x" ("a" | "b") "y" | "xay""#).unwrap();
1834        let mut module = Module::new(&grammar);
1835        module
1836            .precompile_with(&vocab, MaskMode::B.compile_options())
1837            .expect("precompile the B shell");
1838        assert!(module.node.prepared.contains_key(&Engine::TokenTrie.key()));
1839
1840        let loaded = Module::load(&module.save()).expect("load the B shell");
1841        assert!(
1842            loaded.node.prepared.contains_key(&Engine::TokenTrie.key()),
1843            "the B shell must survive Module save/load",
1844        );
1845        let before = static_build_probe::builds_for(&loaded, Engine::TokenTrie);
1846        let compiled = loaded
1847            .compile_inner_with(&vocab, MaskMode::A.compile_options())
1848            .expect("compile an LR request over a B shell");
1849        assert!(compiled.uses_dynamic_runtime());
1850        assert_eq!(
1851            static_build_probe::builds_for(&loaded, Engine::TokenTrie),
1852            before,
1853            "the LR request rebuilt the retained B shell",
1854        );
1855        let reference = loaded
1856            .compile_inner_with(&vocab, MaskMode::ParserDwa.compile_options())
1857            .expect("ParserDwa reference");
1858        let mut left = reference.start();
1859        let mut right = compiled.start();
1860        assert_eq!(left.mask(), right.mask());
1861        for token in [0u32, 1, 3, 0] {
1862            assert_eq!(left.commit_token(token), right.commit_token(token));
1863            assert_eq!(left.mask(), right.mask());
1864            assert_eq!(left.is_accepting(), right.is_accepting());
1865        }
1866    }
1867}
1868
1869#[cfg(test)]
1870mod module_precompile_tests {
1871    use super::*;
1872
1873    fn vocab() -> Vocab {
1874        Vocab::from_entries_unchecked(vec![
1875            (0, b"x".to_vec()), (1, b"a".to_vec()), (2, b"b".to_vec()),
1876            (3, b"y".to_vec()), (4, b"xay".to_vec()), (5, b"ab".to_vec()),
1877        ])
1878    }
1879
1880    const HOST: &str = "glrm 1; start start; extern grammar child; nt start = \"x\" child \"y\";";
1881
1882    #[test]
1883    fn module_precompile_retains_its_work() {
1884        let vocab = vocab();
1885        let options = CompileOptions::default().internal_mask_strategy(InternalMaskStrategy::ParserDwa);
1886        let child = Grammar::from_ebnf(r#"start ::= "a""#).unwrap();
1887
1888        let mut module = Module::new(&child);
1889        module.precompile_with(&vocab, options).expect("module precompile");
1890        let builds = static_build_probe::builds(&module);
1891        assert_eq!(builds, 1, "precompiling the grammar must build and retain one static preparation");
1892
1893        let compiled = module
1894            .compile_inner_with(&vocab, CompileOptions::default().internal_mask_strategy(InternalMaskStrategy::FAST_COMPILE))
1895            .expect("TokenTrie compile after a ParserDwa grammar precompile");
1896        assert!(!compiled.uses_dynamic_runtime(), "the returned Module must keep its retained static work");
1897        assert_eq!(static_build_probe::builds(&module), builds, "the static preparation must be reused, not rebuilt");
1898        assert!(module.node.prepared.contains_key(&Engine::ParserDwa.key()));
1899
1900        // Composing through the returned Module still matches the explicit
1901        // Module::new + bind + precompile path.
1902        let mut parent = Module::new(&Grammar::from_glrm(HOST).unwrap());
1903        parent.precompile(&vocab).expect("open parent precompile");
1904        parent.bind("child", module).expect("bind child");
1905        let composed = parent.compile_inner(&vocab).expect("compile composed modules");
1906        let mut state = composed.start();
1907        assert!(state.commit_token(4));
1908        assert!(state.is_accepting());
1909
1910        let mut reference_parent = Module::new(&Grammar::from_glrm(HOST).unwrap());
1911        reference_parent.bind("child", Module::new(&child)).expect("bind reference child");
1912        reference_parent.precompile(&vocab).expect("precompile reference parent");
1913        let reference = reference_parent.compile_inner(&vocab).expect("compile reference");
1914        assert_eq!(composed.start().mask(), reference.start().mask());
1915        assert_eq!(composed.start().is_accepting(), reference.start().is_accepting());
1916    }
1917}
1918
1919#[cfg(test)]
1920mod boundary_gate_tests {
1921    use super::*;
1922    use crate::__private::VocabExt as _;
1923
1924    fn vocab() -> Vocab {
1925        let vocab = Vocab::from_entries_unchecked(
1926            [b"x".as_slice(), b"y", b"z", b"x!", b"ab!", b"a", b"b", b" "]
1927                .into_iter()
1928                .enumerate()
1929                .map(|(id, bytes)| (id as u32, bytes.to_vec()))
1930                .collect(),
1931        );
1932        vocab.prepare_for_compile();
1933        vocab
1934    }
1935
1936    fn compile_linked(parent: &str, child: Module, vocab: &Vocab) -> RuntimeConstraint {
1937        let mut module = Module::new(&Grammar::from_glrm(parent).unwrap());
1938        module.bind("child", child).expect("bind child");
1939        module
1940            .compile_inner_with(vocab, CompileOptions::default())
1941            .expect("compile linked")
1942    }
1943
1944    fn walk(
1945        gated: &mut crate::ConstraintState,
1946        ungated: &mut crate::ConstraintState,
1947        depth: usize,
1948    ) {
1949        assert_eq!(gated.mask(), ungated.mask(), "mask mismatch at depth {depth}");
1950        if depth == 0 {
1951            return;
1952        }
1953        let allowed = gated.mask();
1954        for token in allowed {
1955            if ungated.mask().binary_search(&token).is_err() {
1956                continue;
1957            }
1958            let mut next_gated = gated.clone();
1959            let mut next_ungated = ungated.clone();
1960            if !next_gated.commit_token(token) {
1961                continue;
1962            }
1963            assert!(next_ungated
1964                .commit_token(token), "ungated commit must accept a gated token");
1965            walk(&mut next_gated, &mut next_ungated, depth - 1);
1966        }
1967    }
1968
1969    fn assert_gate_agrees(composed: &RuntimeConstraint, label: &str) {
1970        assert!(
1971            matches!(composed.boundary_trigger, crate::runtime::BoundaryTrigger::TokenSet(_)),
1972            "{label}: expected a TokenSet gate"
1973        );
1974        let mut ungated = composed.clone();
1975        ungated.boundary_trigger = crate::runtime::BoundaryTrigger::None;
1976        let mut gated_state = composed.start();
1977        let mut ungated_state = ungated.start();
1978        walk(&mut gated_state, &mut ungated_state, 4);
1979    }
1980
1981    /// There is currently no runtime mask path that reads
1982    /// `BoundaryTrigger::TokenSet`; it is retained composition metadata today.
1983    /// This guard pins that future consumers never change observable masks.
1984    #[test]
1985    fn token_set_gate_never_changes_masks() {
1986        let vocab = vocab();
1987        let child = Module::new(&Grammar::from_lark("start: \"y\"?").unwrap());
1988        let simple = compile_linked(
1989            r#"glrm 1; start start; extern grammar child; nt start = "x" child;"#,
1990            child.clone(),
1991            &vocab,
1992        );
1993        assert_gate_agrees(&simple, "nullable child");
1994
1995        let postamble = compile_linked(
1996            r#"glrm 1; start start; extern grammar child; nt start = "x" child "y";"#,
1997            child.clone(),
1998            &vocab,
1999        );
2000        assert_gate_agrees(&postamble, "parent postamble");
2001
2002        let mid_token = compile_linked(
2003            r#"glrm 1; start start; extern grammar child; nt start = child;"#,
2004            Module::new(&Grammar::from_ebnf(r#"start ::= "x""#).unwrap()),
2005            &vocab,
2006        );
2007        assert_gate_agrees(&mid_token, "child ends mid-token");
2008
2009        let after_prefix = compile_linked(
2010            r#"glrm 1; start start; extern grammar child; nt start = "a" child;"#,
2011            Module::new(&Grammar::from_ebnf(r#"start ::= "b""#).unwrap()),
2012            &vocab,
2013        );
2014        assert_gate_agrees(&after_prefix, "bound slot after prefix");
2015
2016        let recursive = compile_linked(
2017            r#"glrm 1; start start; extern grammar child; nt start = list; nt list = "x" child list | "z";"#,
2018            child.clone(),
2019            &vocab,
2020        );
2021        assert_gate_agrees(&recursive, "recursive parent");
2022
2023        let nested_child = {
2024            let mut middle = Module::new(&Grammar::from_glrm(
2025                r#"glrm 1; start start; extern grammar child; nt start = "x" child;"#,
2026            ).unwrap());
2027            middle.bind("child", child).unwrap();
2028            middle
2029        };
2030        let nested = compile_linked(
2031            r#"glrm 1; start start; extern grammar child; nt start = "x" child;"#,
2032            nested_child,
2033            &vocab,
2034        );
2035        assert_gate_agrees(&nested, "two-level nested");
2036
2037        let ignored = Grammar::from_lark("start: \"x\" \"y\"\n%ignore WS\nWS: /[ \\t]+/").unwrap()
2038            .compile_with_build_options(
2039                &vocab,
2040                BuildOptions::default().optimization(InternalMaskStrategy::ParserDwa),
2041            )
2042            .expect("ignore grammar");
2043        assert_gate_agrees(&ignored, "ignore/whitespace");
2044    }
2045}
2046
2047#[cfg(test)]
2048mod boundary_strategy_tests {
2049    use super::*;
2050    use crate::__private::VocabExt as _;
2051
2052    fn vocab() -> Vocab {
2053        let vocab = Vocab::from_entries_unchecked(vec![
2054            (0, b"x".to_vec()),
2055            (1, b"y".to_vec()),
2056            (2, b"z".to_vec()),
2057            (3, b"xy".to_vec()),
2058        ]);
2059        vocab.prepare_for_compile();
2060        vocab
2061    }
2062
2063    #[test]
2064    fn token_trie_and_parser_dwa_boundaries_produce_identical_masks() {
2065        let vocab = vocab();
2066        let child = Module::new(&Grammar::from_ebnf(r#"start ::= "y" "z""#).unwrap());
2067        let compile = |strategy| {
2068            let mut parent = Module::new(&Grammar::from_glrm(
2069                r#"glrm 1; start start; extern grammar child; nt start = "x" child;"#,
2070            ).unwrap());
2071            parent.bind("child", child.clone()).unwrap();
2072            parent
2073                .compile_inner_with(
2074                    &vocab,
2075                    CompileOptions::default().internal_boundary_mask_strategy(strategy),
2076                )
2077                .unwrap()
2078        };
2079        let static_boundary = compile(InternalBoundaryMaskStrategy::ParserDwa);
2080        let token_trie = compile(InternalBoundaryMaskStrategy::TokenTrie);
2081        for prefix in [&[0u32][..0], &[0][..], &[0, 1][..]] {
2082            let mut a = static_boundary.start();
2083            let mut b = token_trie.start();
2084            for &token in prefix {
2085                assert!(a.commit_token(token));
2086                assert!(b.commit_token(token));
2087            }
2088            assert_eq!(a.mask(), b.mask(), "mask mismatch after {prefix:?}");
2089        }
2090    }
2091}
2092
2093#[cfg(test)]
2094mod boundary_error_tests {
2095    use super::*;
2096    use crate::__private::VocabExt as _;
2097
2098    #[test]
2099    fn parser_dwa_budget_decline_is_typed_and_token_trie_succeeds() {
2100        let vocab = {
2101            let vocab = Vocab::from_entries_unchecked(vec![(0, b"x".to_vec()), (1, b"y".to_vec())]);
2102            vocab.prepare_for_compile();
2103            vocab
2104        };
2105        let compile = |strategy| {
2106            let mut parent = Module::new(&Grammar::from_glrm(
2107                r#"glrm 1; start start; extern grammar child; nt start = "x" child;"#,
2108            ).unwrap());
2109            parent
2110                .bind("child", Module::new(&Grammar::from_ebnf(r#"start ::= "y""#).unwrap()))
2111                .unwrap();
2112            parent.force_boundary_dwa_decline();
2113            parent.compile_inner_with(
2114                &vocab,
2115                CompileOptions::default().internal_boundary_mask_strategy(strategy),
2116            )
2117        };
2118        let error = compile(InternalBoundaryMaskStrategy::ParserDwa).unwrap_err();
2119        match (error.kind(), error.message()) {
2120            (crate::ErrorKind::ResourceLimit, message) => {
2121                assert_eq!(message, crate::error::BOUNDARY_DWA_DECLINE);
2122                assert!(message.contains("FastCompile"));
2123            }
2124            other => panic!("expected ResourceLimit, got {other:?}"),
2125        }
2126        compile(InternalBoundaryMaskStrategy::TokenTrie).expect("TokenTrie must bypass the static boundary parser");
2127    }
2128
2129    #[test]
2130    fn auto_falls_back_to_token_trie_where_parser_dwa_errors() {
2131        let vocab = {
2132            let vocab = Vocab::from_entries_unchecked(vec![(0, b"x".to_vec()), (1, b"y".to_vec())]);
2133            vocab.prepare_for_compile();
2134            vocab
2135        };
2136        let compile = |strategy| {
2137            let mut parent = Module::new(&Grammar::from_glrm(
2138                r#"glrm 1; start start; extern grammar child; nt start = "x" child;"#,
2139            ).unwrap());
2140            parent
2141                .bind("child", Module::new(&Grammar::from_ebnf(r#"start ::= "y""#).unwrap()))
2142                .unwrap();
2143            parent.force_boundary_dwa_decline();
2144            parent.compile_inner_with(
2145                &vocab,
2146                CompileOptions::default().internal_boundary_mask_strategy(strategy),
2147            )
2148        };
2149        compile(InternalBoundaryMaskStrategy::ParserDwa).expect_err("explicit ParserDwa must report the budget decline");
2150        let auto = compile(InternalBoundaryMaskStrategy::Auto).expect("Auto must fall back to the token-trie boundary");
2151        let token_trie = compile(InternalBoundaryMaskStrategy::TokenTrie).expect("TokenTrie must build without the static boundary");
2152        let mut auto_state = auto.start();
2153        let mut trie_state = token_trie.start();
2154        assert_eq!(auto_state.mask(), trie_state.mask());
2155        assert!(auto_state.commit_token(0));
2156        assert!(trie_state.commit_token(0));
2157        assert_eq!(auto_state.mask(), trie_state.mask());
2158    }
2159}
2160
2161#[cfg(test)]
2162mod public_preference_tests {
2163    use super::*;
2164
2165    #[test]
2166    fn public_fast_masks_falls_back_on_deterministic_parser_decline() {
2167        let vocab = Vocab::new(vec![(0, b"a".to_vec()), (1, b"b".to_vec())]).unwrap();
2168        let source = Grammar::from_lark("start: \"a\"").unwrap();
2169        let mut module = Module::new(&source);
2170        module.force_parser_dwa_decline();
2171        let preferred = CompileOptions::default().mask_strategy(MaskStrategy::FAST_MASKS);
2172        let fast = CompileOptions::default().mask_strategy(MaskStrategy::FAST_COMPILE);
2173        let expected = module.compile_inner_with(&vocab, fast).unwrap().start().mask();
2174        assert_eq!(module.compile_inner_with(&vocab, preferred.clone()).unwrap().start().mask(), expected);
2175        module.precompile_with(&vocab, preferred.clone()).unwrap();
2176        assert_eq!(module.compile_inner_with(&vocab, preferred).unwrap().start().mask(), expected);
2177    }
2178}