Skip to main content

glrmask/
public_api.rs

1use glrmask_vocab::__private::{VocabExt as _, TokenSetExt as _};
2use crate::ErrorExt as _;
3#[cfg(test)]
4use crate::test_modes::MaskMode;
5use std::collections::{BTreeMap, BTreeSet};
6use std::sync::{Arc, OnceLock};
7use snapshot_map::SnapshotMap as OrdMap;
8use crate::grammar::glrm::{ExternKind, GlrmExternalDeclarations, ParsedComponent};
9use glrmask_grammar::{LarkDocument,LarkExternKind,LarkTokenSet};
10use std::time::Instant;
11
12use rayon::prelude::*;
13
14use crate::compiler::constraint_compose::{
15    CompiledSubgrammarInput, SegmentedBoundaryBackend,
16    compose_constraints_owned_parent_segmented_shared,
17};
18use crate::runtime::Constraint as RuntimeConstraint;
19use crate::dynamic_constraint::DynamicConstraint;
20use crate::runtime::BoundaryTriggerDetail;
21use crate::{Constraint, Error, TokenSet, Result, Vocab};
22
23mod graph;
24mod snapshot_map;
25mod event_cache;
26mod prepared_artifact;
27mod artifact_limits;
28pub(crate) mod module;
29mod expr;
30mod stack;
31pub use module::{Module, CompileOptions};
32pub use expr::Expr;
33pub(crate) use stack::with_deep_stack;
34#[allow(unused_imports)]
35pub(crate) use stack::{DEEP_STACK_RED_ZONE, DEEP_STACK_SIZE};
36
37/// Controls how the constraint is compiled.
38#[derive(Clone, PartialEq, Eq, Hash)]
39pub struct MaskStrategy(MaskPreference);
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42enum MaskPreference { Auto, FastCompile, FastMasks }
43
44impl MaskStrategy {
45    /// The default; currently `FAST_MASKS`.
46    pub const AUTO: Self = Self(MaskPreference::Auto);
47    /// Faster compilation, slower masks.
48    pub const FAST_COMPILE: Self = Self(MaskPreference::FastCompile);
49    /// Faster masks, slower compilation.
50    pub const FAST_MASKS: Self = Self(MaskPreference::FastMasks);
51}
52
53impl Default for MaskStrategy {
54    fn default() -> Self { Self::AUTO }
55}
56
57impl std::fmt::Debug for MaskStrategy {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        f.write_str(match self.0 {
60            MaskPreference::Auto => "MaskStrategy::AUTO",
61            MaskPreference::FastCompile => "MaskStrategy::FAST_COMPILE",
62            MaskPreference::FastMasks => "MaskStrategy::FAST_MASKS",
63        })
64    }
65}
66
67/// How masks are computed.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
69#[non_exhaustive]
70#[doc(hidden)]
71pub enum InternalMaskStrategy {
72    /// Reuses any precompiled work; otherwise [`ParserDwa`](Self::ParserDwa), or
73    /// [`TokenTrie`](Self::TokenTrie) when that would be too large. The default.
74    #[default]
75    Auto,
76    /// Builds a parser DWA for the grammar. Slowest to compile, with the fastest
77    /// masks.
78    ParserDwa,
79    /// Computes each mask by walking the vocabulary. Fastest to compile, with
80    /// slower masks. See [`TokenTrie`](crate::TokenTrie) for its settings.
81    TokenTrie(TokenTrie),
82}
83
84impl InternalMaskStrategy {
85    /// Same as [`TokenTrie`](Self::TokenTrie) with the default settings.
86    pub const FAST_COMPILE: Self = Self::TokenTrie(TokenTrie::new());
87    /// Same as [`ParserDwa`](Self::ParserDwa).
88    pub const FAST_MASKS: Self = Self::ParserDwa;
89}
90
91impl From<MaskStrategy> for InternalMaskStrategy {
92    fn from(value: MaskStrategy) -> Self { match value {
93        MaskStrategy::AUTO => Self::Auto,
94        MaskStrategy::FAST_COMPILE => Self::FAST_COMPILE,
95        MaskStrategy::FAST_MASKS => Self::ParserDwa,
96    } }
97}
98
99impl From<TokenTrie> for InternalMaskStrategy {
100    fn from(settings: TokenTrie) -> Self {
101        Self::TokenTrie(settings)
102    }
103}
104
105/// Internal token-trie settings, not part of the stable API.
106#[doc(hidden)]
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
108pub struct TokenTrie {
109    parser_backend: ParserBackend,
110    merge_equivalent_tokens: bool,
111}
112
113impl TokenTrie {
114    /// The default settings: an LR table, with tokens not merged.
115    pub const fn new() -> Self {
116        Self {
117            parser_backend: ParserBackend::LrTable,
118            merge_equivalent_tokens: false,
119        }
120    }
121
122    /// Sets how the parser is represented. Defaults to [`ParserBackend::LrTable`].
123    pub const fn parser_backend(mut self, backend: ParserBackend) -> Self {
124        self.parser_backend = backend;
125        self
126    }
127
128    /// Sets whether tokens that the grammar treats the same are merged, so masks
129    /// walk fewer tokens. Off by default.
130    ///
131    /// Tokens are not merged in a composition that includes precompiled parts.
132    pub const fn merge_equivalent_tokens(mut self, enable: bool) -> Self {
133        self.merge_equivalent_tokens = enable;
134        self
135    }
136
137    pub(crate) const fn backend(&self) -> ParserBackend {
138        self.parser_backend
139    }
140
141    pub(crate) const fn merges(&self) -> bool {
142        self.merge_equivalent_tokens
143    }
144}
145
146/// How masks are computed at grammar boundaries.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
148#[non_exhaustive]
149#[doc(hidden)]
150pub enum InternalBoundaryMaskStrategy {
151    /// [`ParserDwa`](Self::ParserDwa), or [`TokenTrie`](Self::TokenTrie) when that
152    /// would be too large. The default.
153    #[default]
154    Auto,
155    /// Builds a parser DWA across each boundary. Slower to compile, with faster
156    /// masks. Fails with [`ErrorKind::ResourceLimit`](crate::ErrorKind::ResourceLimit)
157    /// if it would be too large.
158    ParserDwa,
159    /// Walks the vocabulary at each boundary as needed. Faster to compile, with
160    /// slower masks.
161    TokenTrie,
162}
163
164impl InternalBoundaryMaskStrategy {
165    /// Same as [`TokenTrie`](Self::TokenTrie).
166    pub const FAST_COMPILE: Self = Self::TokenTrie;
167    /// Same as [`ParserDwa`](Self::ParserDwa).
168    pub const FAST_MASKS: Self = Self::ParserDwa;
169}
170
171/// Internal mask engine. The wire tags are stable within the module artifact format.
172#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
173pub(crate) enum Engine {
174    /// Reuses retained work; otherwise [`ParserDwa`](Self::ParserDwa).
175    #[default]
176    Auto,
177    ParserDwa,
178    /// A retained [`TokenTrie`](Self::TokenTrie) template-DFA shell ("B shell").
179    /// An LR-table TokenTrie build retains nothing, so it has no key.
180    TokenTrie,
181    /// [`TokenTrie`](Self::TokenTrie) over the merged vocabulary. Key 3 is
182    /// retained only for a template-DFA body (combination C); an LR-table
183    /// merged body (combination D) retains nothing, exactly like an unmerged
184    /// LR TokenTrie build.
185    MergedTokenTrie,
186}
187
188impl Engine {
189    pub(crate) fn key(self) -> u8 {
190        match self {
191            Self::Auto => 0,
192            Self::ParserDwa => 1,
193            Self::TokenTrie => 2,
194            Self::MergedTokenTrie => 3,
195        }
196    }
197
198    pub(crate) fn is_token_trie(self) -> bool {
199        matches!(self, Self::TokenTrie | Self::MergedTokenTrie)
200    }
201}
202
203/// A named placeholder in a grammar.
204#[derive(Debug, Clone, PartialEq, Eq, Hash)]
205pub struct Extern {
206    pub(crate) name: String,
207    pub(crate) kind: ExternKind,
208}
209
210impl Extern {
211    pub fn name(&self) -> &str {
212        &self.name
213    }
214    pub fn kind(&self) -> ExternKind {
215        self.kind
216    }
217}
218
219/// A read-only collection of extern names and their `Extern` values.
220#[derive(Clone, PartialEq, Eq)]
221pub struct Externs {
222    entries: Vec<Extern>,
223    unbound: Vec<Extern>,
224}
225
226impl std::fmt::Debug for Externs {
227    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228        f.debug_struct("Externs")
229            .field("entries", &self.entries)
230            .field("unbound", &self.unbound.iter().map(Extern::name).collect::<Vec<_>>())
231            .finish()
232    }
233}
234
235#[derive(Debug, Clone)]
236pub(crate) enum ExternsSource<'a> {
237    Module(&'a Module),
238    Grammar(&'a Grammar),
239}
240
241impl ExternsSource<'_> {
242    fn declarations(&self) -> Option<&GlrmExternalDeclarations> {
243        match self {
244            Self::Module(module) => module.node.source.declarations().ok(),
245            Self::Grammar(grammar) => grammar.declarations().ok(),
246        }
247    }
248    fn bound(&self, name: &str) -> bool {
249        match self {
250            Self::Module(module) => module.node.bindings.contains_key(name),
251            Self::Grammar(grammar) => grammar.bindings.contains_key(name),
252        }
253    }
254}
255
256impl Externs {
257    pub(crate) fn snapshot(source: ExternsSource<'_>) -> Self {
258        let mut entries = Vec::new();
259        if let Some(declared) = source.declarations() {
260            entries.extend(declared.names.iter().filter_map(|name| {
261                Some(Extern { name: name.clone(), kind: *declared.kinds.get(name)? })
262            }));
263        }
264        entries.sort_by(|a, b| a.name.cmp(&b.name));
265        let unbound = entries.iter().filter(|e| !source.bound(&e.name)).cloned().collect();
266        Self { entries, unbound }
267    }
268
269    pub fn get(&self, name: &str) -> Option<&Extern> {
270        self.entries.binary_search_by(|e| e.name.as_str().cmp(name)).ok().map(|i| &self.entries[i])
271    }
272
273    pub fn len(&self) -> usize { self.entries.len() }
274    pub fn is_empty(&self) -> bool { self.entries.is_empty() }
275
276    /// Only externs that still need bindings.
277    pub fn unbound(&self) -> Self {
278        Self { entries: self.unbound.clone(), unbound: self.unbound.clone() }
279    }
280
281    pub fn iter(&self) -> ExternIter<'_> { ExternIter(self.entries.iter()) }
282}
283
284/// A borrowed iterator over externs.
285#[derive(Clone, Debug)]
286pub struct ExternIter<'a>(std::slice::Iter<'a, Extern>);
287
288impl<'a> Iterator for ExternIter<'a> {
289    type Item = &'a Extern;
290    fn next(&mut self) -> Option<Self::Item> { self.0.next() }
291    fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
292}
293impl DoubleEndedIterator for ExternIter<'_> {
294    fn next_back(&mut self) -> Option<Self::Item> { self.0.next_back() }
295}
296impl ExactSizeIterator for ExternIter<'_> {}
297impl std::iter::FusedIterator for ExternIter<'_> {}
298
299/// An owning iterator over externs.
300#[derive(Clone, Debug)]
301pub struct ExternIntoIter(std::vec::IntoIter<Extern>);
302
303impl Iterator for ExternIntoIter {
304    type Item = Extern;
305    fn next(&mut self) -> Option<Self::Item> { self.0.next() }
306    fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
307}
308impl DoubleEndedIterator for ExternIntoIter {
309    fn next_back(&mut self) -> Option<Self::Item> { self.0.next_back() }
310}
311impl ExactSizeIterator for ExternIntoIter {}
312impl std::iter::FusedIterator for ExternIntoIter {}
313
314impl IntoIterator for Externs {
315    type Item = Extern;
316    type IntoIter = ExternIntoIter;
317    fn into_iter(self) -> Self::IntoIter { ExternIntoIter(self.entries.into_iter()) }
318}
319
320impl<'a> IntoIterator for &'a Externs {
321    type Item = &'a Extern;
322    type IntoIter = ExternIter<'a>;
323    fn into_iter(self) -> Self::IntoIter { self.iter() }
324}
325
326/// How the parser is represented and run when masks are computed with
327/// [`InternalMaskStrategy::TokenTrie`].
328#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
329#[non_exhaustive]
330#[doc(hidden)]
331pub enum ParserBackend {
332    /// An LR table. Faster to compile, with slower masks. The default.
333    #[default]
334    LrTable,
335    /// Template DFAs. Slower to compile, with faster masks.
336    TemplateDfa,
337}
338
339/// Final compile/link options. `prepare_with` retains only the boundary metadata request; choose optimization and end tokens at final link.
340#[derive(Debug, Clone)]
341pub struct BuildOptions {
342    end_tokens: Vec<u32>,
343    optimization: InternalMaskStrategy,
344    engine_backend: ParserBackend,
345    merge_equivalent_tokens: bool,
346    parser_backend: ParserBackend,
347    boundary_trigger: Option<BoundaryTriggerDetail>,
348}
349
350impl Default for BuildOptions {
351    fn default() -> Self {
352        Self {
353            end_tokens: Vec::new(),
354            optimization: InternalMaskStrategy::default(),
355            engine_backend: ParserBackend::LrTable,
356            merge_equivalent_tokens: false,
357            parser_backend: ParserBackend::TemplateDfa,
358            boundary_trigger: None,
359        }
360    }
361}
362
363impl BuildOptions {
364    /// Root stopping controls, allowed only at acceptance. Commit the selected end token before stopping; the policy is not inherited by embedded children.
365    pub fn end_tokens(mut self, ids: impl IntoIterator<Item = u32>) -> Self {
366        self.end_tokens = ids.into_iter().collect();
367        self
368    }
369
370    /// Defaults to [`InternalMaskStrategy::Auto`].
371    pub fn optimization(mut self, optimization: InternalMaskStrategy) -> Self {
372        self.optimization = optimization;
373        self
374    }
375
376    /// Parses with the requested parser backend.
377    #[cfg(any(test, feature = "internal-api"))]
378    #[doc(hidden)]
379    pub fn engine_backend(mut self, backend: ParserBackend) -> Self {
380        self.engine_backend = backend;
381        self
382    }
383
384    /// Merges tokens that the grammar treats the same, so masks walk fewer
385    /// tokens. Off by default.
386    pub fn merge_equivalent_tokens(mut self, enable: bool) -> Self {
387        self.merge_equivalent_tokens = enable;
388        self
389    }
390
391    /// Optional composition metadata. At final link an explicit request, including `None`, overrides the prepared request.
392    pub fn boundary_trigger(mut self, detail: BoundaryTriggerDetail) -> Self {
393        self.boundary_trigger = Some(detail);
394        self
395    }
396
397    #[cfg(any(test, feature = "internal-api"))]
398    #[doc(hidden)]
399    pub fn parser_backend(mut self, backend: ParserBackend) -> Self {
400        assert!(backend != ParserBackend::LrTable,
401            "LR-BACKED CONSTRAINT REQUEST IS FORBIDDEN: only native template Constraints may be materialized");
402        self.parser_backend = backend; self
403    }
404
405    pub(crate) fn end_token_ids(&self) -> &[u32] {
406        &self.end_tokens
407    }
408
409    /// The internal engine for these options.
410    pub(crate) fn engine(&self) -> Result<Engine> {
411        Ok(engine_for(self.optimization))
412    }
413
414    /// The TokenTrie parser backend for these options.
415    pub(crate) fn token_trie_backend(&self) -> crate::runtime::parser_backend::DynamicParserBackend {
416        token_trie_backend(self.engine_backend)
417    }
418}
419
420/// Derive the internal engine from the public strategy.
421pub(crate) fn engine_for(strategy: InternalMaskStrategy) -> Engine {
422    match strategy {
423        InternalMaskStrategy::Auto => Engine::Auto,
424        InternalMaskStrategy::ParserDwa => Engine::ParserDwa,
425        InternalMaskStrategy::TokenTrie(settings) if settings.merges() => Engine::MergedTokenTrie,
426        InternalMaskStrategy::TokenTrie(_) => Engine::TokenTrie,
427    }
428}
429
430pub(crate) fn token_trie_backend(
431    parser_backend: ParserBackend,
432) -> crate::runtime::parser_backend::DynamicParserBackend {
433    use crate::runtime::parser_backend::DynamicParserBackend;
434    if parser_backend == ParserBackend::TemplateDfa {
435        DynamicParserBackend::Native
436    } else {
437        DynamicParserBackend::LrTable
438    }
439}
440
441impl Engine {
442    /// Link options that reproduce this engine for an already prepared body.
443    pub(crate) fn build_options(self) -> BuildOptions {
444        let (optimization, engine_backend, merge_equivalent_tokens) = match self {
445            Self::Auto => (InternalMaskStrategy::Auto, ParserBackend::LrTable, false),
446            Self::ParserDwa => (InternalMaskStrategy::ParserDwa, ParserBackend::LrTable, false),
447            Self::TokenTrie => (InternalMaskStrategy::FAST_COMPILE, ParserBackend::LrTable, false),
448            Self::MergedTokenTrie => (
449                InternalMaskStrategy::TokenTrie(
450                    TokenTrie::new()
451                        .parser_backend(ParserBackend::TemplateDfa)
452                        .merge_equivalent_tokens(true),
453                ),
454                ParserBackend::TemplateDfa,
455                true,
456            ),
457        };
458        BuildOptions {
459            optimization,
460            engine_backend,
461            merge_equivalent_tokens,
462            parser_backend: ParserBackend::TemplateDfa,
463            ..BuildOptions::default()
464        }
465    }
466}
467
468/// Vocabulary-specific compiled machinery, possibly with unresolved externs.
469///
470/// Binding changes only this handle; clones and attached children retain independent snapshots.
471#[derive(Debug, Clone)]
472pub struct PreparedGrammar {
473    inner: Arc<RuntimeConstraint>,
474    /// Compiled-only immutable attachments. Delaying composition is what lets
475    /// the terminal link call choose the boundary/runtime trade-off.
476    bindings: OrdMap<String, ModuleBinding>,
477    /// Immutable-instance certificate; clones share it until a binding changes.
478    analysis: graph::SummaryCache,
479    event_adapters: Arc<event_cache::ExactAdapterCache>,
480    boundary_trigger: BoundaryTriggerDetail,
481    /// Authored interface, independent of optimization and runtime reachability.
482    slot_kinds: Arc<BTreeMap<String, ExternKind>>,
483    slot_spans: Arc<BTreeMap<String,glrmask_grammar::SourceSpan>>,
484    /// Vocabulary-free artifact bytes retained by a deferred Module load.
485    /// `compile`/`precompile` rehydrates from these with the supplied vocabulary.
486    pub(crate) retained_artifact: Option<Arc<[u8]>>,
487    /// Fingerprint recorded by `retained_artifact`.
488    pub(crate) retained_vocab_fingerprint: Option<[u8; 32]>,
489}
490
491/// Unstable spelling retained only for repository tooling. The public type is
492/// PreparedGrammar; normal dependency builds expose no compatibility alias.
493#[cfg(any(test,feature="internal-api"))]
494#[doc(hidden)]
495pub type UnlinkedConstraint = PreparedGrammar;
496
497#[derive(Debug, Clone, PartialEq, Eq)]
498pub struct Requirement {
499    pub path: Vec<String>,
500    pub kind: ExternKind,
501    pub source_span: Option<glrmask_grammar::SourceSpan>,
502}
503impl Requirement {
504    pub fn name(&self) -> String { self.path.join("::") }
505}
506
507#[derive(Debug, Clone)]
508enum ModuleBinding {
509    Module(Arc<PreparedGrammar>),
510    Constraint(Arc<RuntimeConstraint>),
511    TokenSet(Arc<event_cache::ExactEvent>),
512}
513
514#[derive(Debug, Clone)]
515pub(crate) enum GrammarValue {
516    Source(Arc<Grammar>),
517    TokenSet(TokenSet),
518}
519
520
521#[doc(hidden)]
522pub(crate) trait IntoGrammarValue {
523    fn into_grammar_value(self) -> Result<GrammarValue>;
524}
525
526#[derive(Debug, Clone)]
527pub(crate) enum UnlinkedValue<'a> {
528    Prepared(Arc<PreparedGrammar>),
529    StaticBorrowed(&'a RuntimeConstraint),
530    StaticOwned(Arc<RuntimeConstraint>),
531    TokenSet(TokenSet),
532}
533
534#[doc(hidden)]
535pub(crate) trait IntoUnlinkedValue<'a> {
536    fn into_unlinked_value(self) -> UnlinkedValue<'a>;
537}
538
539fn lark_declarations(document:&LarkDocument)->impl Iterator<Item=(String,ExternKind)>+'_ {
540    document.externs.iter().map(|e|(e.name.clone(),match e.kind {
541        LarkExternKind::Token=>ExternKind::Token,
542        LarkExternKind::Grammar=>ExternKind::Grammar,
543    }))
544}
545
546fn attached_path<'n,T:Clone>(name:&'n str, bindings:&OrdMap<String,T>) -> Option<(&'n str,&'n str)> {
547    // Look up only the qualified prefixes, never scan every unrelated binding.
548    name.rmatch_indices("::").find_map(|(index,_)| {
549        let head=&name[..index]; let tail=&name[index+2..];
550        (!tail.is_empty() && bindings.contains_key(head)).then_some((head,tail))
551    })
552}
553fn check_binding_kind(name:&str,kind:ExternKind,grammar:bool)->Result<()> {
554    if matches!((kind,grammar),(ExternKind::Token,true)) {
555        return Err(Error::InvalidInput(format!("extern {name:?} is a token extern; bind it to a token set")));
556    }
557    Ok(())
558}
559
560#[derive(Debug, Clone)]
561pub struct Grammar {
562    source: GrammarSource,
563    module_snapshot: Arc<OnceLock<Module>>,
564    bindings: OrdMap<String, GrammarValue>,
565    declarations_cache: Arc<OnceLock<Result<GlrmExternalDeclarations>>>,
566    analysis: graph::SummaryCache,
567    parsed_component: Arc<OnceLock<std::result::Result<ParsedComponent, Error>>>,
568    exact_value: Option<TokenSet>,
569    lark_document:Arc<OnceLock<std::result::Result<LarkDocument,Error>>>,
570}
571
572#[derive(Debug, Clone, PartialEq, Eq)]
573enum GrammarSource {
574    Ebnf(Arc<str>),
575    Lark(Arc<str>),
576    JsonSchema(Arc<str>),
577    Glrm(Arc<str>),
578    Constructed,
579}
580
581#[derive(Default)]
582struct SourcePreparation {
583    prepared: std::collections::HashMap<usize,Arc<PreparedGrammar>>,
584    retained: Vec<Arc<Grammar>>,
585    visited: usize,
586}
587
588impl Grammar {
589
590    /// Resolve the parser-facing expression graph without selecting an LR
591    /// normal form. Source bindings are not part of this constructor boundary;
592    /// use a closed grammar or the ordinary compiled-component linker.
593    #[cfg(any(test, feature = "internal-api"))]
594    #[doc(hidden)]
595    pub fn prepare_parser_grammar(&self) -> Result<crate::template_parser::PreparedParserGrammar> {
596        if !self.bindings.is_empty() {
597            return Err(Error::Compilation("custom parser construction requires a source without external bindings".into()));
598        }
599        let (source, parse): (&str, fn(&str) -> Result<glrmask_grammar::NamedGrammar>) = match &self.source {
600            GrammarSource::Ebnf(source) => (source, crate::import::parse_ebnf_to_named),
601            GrammarSource::Lark(source) => (source, crate::import::parse_lark_to_named),
602            GrammarSource::JsonSchema(source) => (source, crate::import::parse_json_schema_to_named),
603            GrammarSource::Glrm(source) => (source, crate::import::parse_glrm_to_named),
604            GrammarSource::Constructed => return crate::template_parser::PreparedParserGrammar::from_named(&self.component()?.lower_closed().map_err(crate::error::from_grammar)?),
605        };
606        crate::import::with_large_import_stack(source.len(), || {
607            crate::template_parser::PreparedParserGrammar::from_named(&parse(source)?)
608        })
609    }
610
611    /// Resolve this grammar, invoke a compile-time parser constructor once, and
612    /// assemble its template relations using the ordinary masking machinery.
613    /// For repeated experiments, retain `prepare_parser_grammar()` instead.
614    #[cfg(any(test, feature = "internal-api"))]
615    #[doc(hidden)]
616    pub fn compile_with_parser(&self, vocab: &Vocab,
617        compiler: &(impl crate::template_parser::ParserCompiler + ?Sized),
618        options: crate::template_parser::TemplateBuildOptions) -> Result<RuntimeConstraint> {
619        self.prepare_parser_grammar()?.compile_parser(compiler)?.compile_with(vocab, options)
620    }
621
622    #[cfg(any(test, feature = "internal-api"))]
623    #[doc(hidden)]
624    pub fn ebnf(source: &str) -> Self { Self::new(GrammarSource::Ebnf(Arc::from(source))) }
625    #[cfg(any(test, feature = "internal-api"))]
626    #[doc(hidden)]
627    pub fn lark(source: &str) -> Self { Self::new(GrammarSource::Lark(Arc::from(source))) }
628    #[cfg(any(test, feature = "internal-api"))]
629    #[doc(hidden)]
630    pub fn json_schema(source: &str) -> Self { Self::new(GrammarSource::JsonSchema(Arc::from(source))) }
631    #[cfg(any(test, feature = "internal-api"))]
632    #[doc(hidden)]
633    pub fn glrm(source: &str) -> Self {
634        let grammar=Self::new(GrammarSource::Glrm(Arc::from(source)));
635        let _=grammar.parsed_component.set(ParsedComponent::parse_glrm(source).map_err(crate::error::from_grammar));
636        grammar
637    }
638
639    #[cfg(any(test, feature = "internal-api"))]
640    #[doc(hidden)]
641    pub fn from_ebnf(source: impl AsRef<str>) -> Result<Self> {
642        let grammar = Self::new(GrammarSource::Ebnf(Arc::from(source.as_ref())));
643        grammar.component()?;
644        Ok(grammar)
645    }
646
647    /// Parses [GLRM](https://github.com/IsaacBreen/glrmask/blob/v1.0.0-rc.1/docs/glrm-format.md) source.
648    pub fn from_glrm(source: &str) -> Result<Self> {
649        let grammar = Self::new(GrammarSource::Glrm(Arc::from(source)));
650        grammar.component()?;
651        Ok(grammar)
652    }
653
654
655    /// Parses [Lark](https://github.com/IsaacBreen/glrmask/blob/v1.0.0-rc.1/GUIDE.md#grammar-formats) source.
656    pub fn from_lark(source: &str) -> Result<Self> {
657        let grammar = Self::new(GrammarSource::Lark(Arc::from(source)));
658        grammar.lark_document()?;
659        grammar.declarations()?;
660        Ok(grammar)
661    }
662
663    /// Parses a [JSON Schema](https://github.com/IsaacBreen/glrmask/blob/v1.0.0-rc.1/GUIDE.md#grammar-formats), given as JSON text.
664    pub fn from_json_schema(source: &str) -> Result<Self> {
665        crate::import::parse_json_schema_to_named(source)?;
666        Ok(Self::new(GrammarSource::JsonSchema(Arc::from(source))))
667    }
668
669    #[cfg(feature = "internal-api")]
670    pub(crate) fn from_glrm_with_markers(source: &str) -> Result<Self> {
671        let grammar = Self::new(GrammarSource::Glrm(Arc::from(source)));
672        let _ = grammar.parsed_component.set(
673            ParsedComponent::parse_glrm_with_markers(source).map_err(crate::error::from_grammar),
674        );
675        grammar.component()?;
676        Ok(grammar)
677    }
678
679    fn new(source: GrammarSource) -> Self {
680        Self { source, module_snapshot: Arc::new(OnceLock::new()), bindings: OrdMap::new(), declarations_cache: Arc::new(OnceLock::new()), analysis: graph::empty_cache(), parsed_component: Arc::new(OnceLock::new()), exact_value: None, lark_document:Arc::new(OnceLock::new()) }
681    }
682
683    pub(crate) fn single_rule_body(&self) -> Option<&crate::grammar::ast::GrammarExpr> {
684        self.component().ok()?.single_rule_body()
685    }
686
687    fn component(&self) -> Result<&ParsedComponent> {
688        self.parsed_component.get_or_init(|| match &self.source {
689            GrammarSource::Glrm(source) => ParsedComponent::parse_glrm(source).map_err(crate::error::from_grammar),
690            GrammarSource::Ebnf(source) => crate::import::parse_ebnf_to_named(source)
691                .and_then(|n|ParsedComponent::from_named(n,&[]).map_err(crate::error::from_grammar)),
692            GrammarSource::Lark(source) => crate::import::parse_lark_to_named(source)
693                .and_then(|n|ParsedComponent::from_named(n,&[]).map_err(crate::error::from_grammar)),
694            // JSON Schema lowers to an ordinary named grammar, so it can join a
695            // mixed compile as a dynamic component shell. The schema pipeline
696            // prepares it exactly as the static schema route does, including
697            // lexer partitioning for the generated terminal classes.
698            GrammarSource::JsonSchema(source) => crate::import::prepare_json_schema_named_for_component(source)
699                .and_then(|n|ParsedComponent::from_named(n,&[]).map_err(crate::error::from_grammar)),
700            GrammarSource::Constructed => Err(Error::Compilation("constructed grammar has no semantic description".into())),
701        }).as_ref().map_err(Clone::clone)
702    }
703
704    fn lark_document(&self)->Result<&LarkDocument> {
705        let GrammarSource::Lark(source)=&self.source else{return Err(Error::Compilation("not a Lark description".into()));};
706        self.lark_document.get_or_init(||glrmask_grammar::parse_lark_document(source).map_err(crate::error::from_grammar))
707            .as_ref().map_err(Clone::clone)
708    }
709
710    fn resolve_lark(&self,_vocab:&Vocab)->Result<Self> {
711        let GrammarSource::Lark(source)=&self.source else{return Err(Error::Compilation("not a Lark description".into()));};
712        let document=self.lark_document()?;
713        let mut values=std::collections::HashMap::new();
714        for (name,LarkTokenSet::Named(external)) in &document.events {
715            values.insert(name.clone(),glrmask_grammar::GrammarExpr::Ref(external.clone()));
716        }
717        let named=document.resolve_events(&values);
718        let externs=lark_declarations(document)
719            .chain(document.schemas.iter().map(|(name,_)|(name.clone(),ExternKind::Grammar))).collect::<Vec<_>>();
720        let mut resolved=Self::new(GrammarSource::Constructed);
721        let spans=externs.iter().filter_map(|(name,_)|document.source_spans.get(name).map(|span|(name.clone(),*span))).collect();
722        let _=resolved.parsed_component.set(ParsedComponent::from_named_with_ignores(named,&externs,&document.resolved_additional_ignores())
723            .and_then(|component|component.with_source_spans(&spans)).map_err(crate::error::from_grammar));
724        let _=resolved.component()?;
725        resolved.bindings=self.bindings.clone();
726        for (name,range) in &document.schemas {
727            // Preserve a real child boundary and the JSON frontend's own whitespace
728            // rules. The source span borrows the original Lark document safely.
729            let child=Self::new(GrammarSource::JsonSchema(Arc::from(&source[range.clone()])));
730            resolved.bindings.insert(name.clone(),GrammarValue::Source(Arc::new(child)));
731        }
732        Ok(resolved)
733    }
734
735    fn declarations(&self) -> Result<&GlrmExternalDeclarations> {
736        self.declarations_cache.get_or_init(|| match &self.source {
737            GrammarSource::Glrm(_) | GrammarSource::Constructed => Ok(self.component()?.declarations().clone()),
738            GrammarSource::Lark(_)=>{
739                let document=self.lark_document()?;
740                let declared=lark_declarations(document).collect::<Vec<_>>();
741                let kinds=declared.iter().cloned().collect::<BTreeMap<_,_>>();
742                let spans=declared.iter().filter_map(|(name,_)|document.source_spans.get(name).map(|span|(name.clone(),*span))).collect();
743                Ok(GlrmExternalDeclarations{names:declared.into_iter().map(|(name,_)|name).collect(),kinds,spans})
744            }
745            _ => Ok(GlrmExternalDeclarations::default()),
746        }).as_ref().map_err(Clone::clone)
747    }
748
749    fn validate_exact_target(&self, vocab: &Vocab) -> Result<()> {
750        if matches!(self.source, GrammarSource::Glrm(_)) {
751            let comp = self.component()?;
752            let ranges = comp.inline_token_ranges();
753            for &(start, end) in &ranges {
754                if !vocab.contains_token_range(start, end) {
755                    return Err(Error::InvalidInput(format!(
756                        "token range {start}..={end} includes IDs that are not in the vocabulary"
757                    )));
758                }
759            }
760            let selected = range_set_blaze::RangeSetBlaze::from_iter(
761                ranges.iter().map(|&(a, b)| a..=b),
762            );
763            crate::import::reject_special_token_ids(&selected, vocab)?;
764        }
765        Ok(())
766    }
767
768    fn validate_ebnf(&self, vocab: &Vocab) -> Result<()> {
769        if let GrammarSource::Ebnf(source) = &self.source {
770            crate::import::validate_ebnf_source(source, vocab)?;
771        }
772        Ok(())
773    }
774
775    #[cfg(any(test, feature = "internal-api"))]
776    #[doc(hidden)]
777    pub fn exact(tokens: TokenSet) -> Self { Self::from_token_set(tokens) }
778
779    pub(crate) fn from_token_set(tokens: TokenSet) -> Self {
780        let exprs=tokens.range_pairs().iter().map(|&(a,b)|if a==b {
781            glrmask_grammar::GrammarExpr::SpecialToken(a)
782        } else {glrmask_grammar::GrammarExpr::SpecialTokenRange(a,b)}).collect::<Vec<_>>();
783        let expr=if exprs.len()==1 {exprs.into_iter().next().unwrap()}
784            else {glrmask_grammar::GrammarExpr::Choice(exprs)};
785        let named=glrmask_grammar::NamedGrammar {
786            start:"__exact_event".into(),
787            rules:vec![glrmask_grammar::NamedRule {name:"__exact_event".into(),expr,is_terminal:false,is_internal:false}],
788            ignore:None,lexer_partitions:Default::default(),lexer_literal_partitions:Default::default(),default_lexer_partition:None,
789        };
790        let mut grammar=Self::new(GrammarSource::Constructed);
791        let _=grammar.parsed_component.set(ParsedComponent::from_named(named,&[]).map_err(crate::error::from_grammar));
792        grammar.exact_value=Some(tokens);grammar
793    }
794
795    /// Includes unresolved externs in attached open children. Diagnostic expansion is bounded and may return an error for very large shared graphs.
796    #[cfg(any(test,feature="internal-api"))]
797    #[doc(hidden)]
798    pub fn requirements(&self) -> Result<Vec<Requirement>> {
799        graph::source_requirements(self)
800    }
801
802    /// Builds a grammar from an `Expr`.
803    pub fn from_expr(expr: &Expr) -> Result<Grammar> {
804        Self::from_expr_ref(expr)
805    }
806
807    // Keep the large historical differential fixture corpus readable while it
808    // exercises the same mutable operation. Not part of the normal public API.
809    #[cfg(any(test, feature = "internal-api"))]
810    #[doc(hidden)]
811    #[allow(private_bounds)]
812    pub fn bind_snapshot<T>(&self, name: impl AsRef<str>, value: T) -> Result<Self>
813    where T: IntoGrammarValue {
814        self.bind_value(name.as_ref(), value.into_grammar_value()?)
815    }
816
817    fn bind_value(&self, name:&str, mut value:GrammarValue) -> Result<Self> {
818        if let GrammarValue::TokenSet(tokens)=&value { crate::error::check_token_set(tokens)?; }
819        let declared = self.declarations()?;
820        let previous = graph::source_summary(self)?;
821        if !declared.kinds.contains_key(name) {
822            if let Some((head,tail))=attached_path(name,&self.bindings) {
823                let Some(GrammarValue::Source(child))=self.bindings.get(head) else {
824                    return Err(Error::InvalidInput(format!("{head:?} is not a source component")));
825                };
826                let child=child.bind_value(tail,value)?;
827                let summary=graph::source_summary(&child)?;
828                let mut next=self.clone();
829                next.bindings.insert(head.to_owned(),GrammarValue::Source(Arc::new(child)));
830                next.analysis=graph::filled_cache(previous.changed(head,Some(summary)));
831                next.module_snapshot=Arc::new(OnceLock::new());
832                graph::check_source_limits(&next)?;
833                return Ok(next);
834            }
835            return Err(Error::InvalidInput(format!("there is no extern named {name:?}")));
836        }
837        if self.bindings.contains_key(name) {
838            return Err(Error::InvalidInput(format!("extern {name:?} is already bound")));
839        }
840        check_binding_kind(name,declared.kinds[name],matches!(value,GrammarValue::Source(_)))
841            .map_err(|e|e.with_source_span(declared.spans.get(name).copied()))?;
842        // A one-event value is a lossless grammar-fragment widening. Preserve
843        // the independently scoped child boundary, not a decoded-byte alias.
844        if declared.kinds[name]==ExternKind::Grammar {
845            value=match value {
846                GrammarValue::TokenSet(tokens)=>GrammarValue::Source(Arc::new(Self::from_token_set(tokens))),
847                other=>other,
848            };
849        }
850        let child_summary=match &value {
851            GrammarValue::Source(child)=>Some(graph::source_summary(child)?),
852            _=>None,
853        };
854        let mut next=self.clone();next.bindings.insert(name.to_owned(),value);
855        next.analysis=graph::filled_cache(previous.changed(name,child_summary));
856        next.module_snapshot=Arc::new(OnceLock::new());
857        graph::check_source_limits(&next)?;
858        Ok(next)
859    }
860
861    /// Compatibility spelling for source-only grammar binding.
862    #[cfg(any(test, feature = "internal-api"))]
863    #[doc(hidden)]
864    pub fn bind_grammar(self, name: impl AsRef<str>, grammar: Grammar) -> Result<Self> {
865        self.bind_value(name.as_ref(), GrammarValue::Source(Arc::new(grammar)))
866    }
867
868    /// All extern declarations.
869    pub fn externs(&self) -> Externs { Externs::snapshot(ExternsSource::Grammar(self)) }
870
871    /// Compiles the grammar into a constraint.
872    pub fn compile(&self, vocab: &Vocab) -> Result<Constraint> {
873        Module::new(self).compile(vocab)
874    }
875
876    /// Like `compile()`, with `options`.
877    pub fn compile_with(
878        &self,
879        vocab: &Vocab,
880        options: CompileOptions,
881    ) -> Result<Constraint> {
882        Module::new(self).compile_with(vocab, options)
883    }
884
885    pub(crate) fn compile_inner(&self, vocab: &Vocab) -> Result<RuntimeConstraint> {
886        Module::new(self).compile_inner(vocab)
887    }
888
889    pub(crate) fn compile_inner_with(&self, vocab: &Vocab, options: CompileOptions) -> Result<RuntimeConstraint> {
890        Module::new(self).compile_inner_with(vocab, options)
891    }
892
893    #[cfg(any(test, feature = "internal-api"))]
894    #[doc(hidden)]
895    pub fn compile_with_build_options(
896        &self,
897        vocab: &Vocab,
898        options: BuildOptions,
899    ) -> Result<RuntimeConstraint> {
900        crate::error::check_vocab_token_ids(vocab)?;
901        graph::source_preflight(self)?;
902        let engine = options.engine()?;
903        if matches!(self.source,GrammarSource::Lark(_)){return self.resolve_lark(vocab)?.compile_with_build_options(vocab,options);}
904        self.validate_exact_target(vocab)?;
905        self.validate_ebnf(vocab)?;
906        if let Some(name) = self.unresolved_external_names()?.first() {
907            return Err(Error::InvalidInput(format!(
908                "extern {name:?} is unbound; bind it before compiling, or precompile to leave it open",
909            )));
910        }
911        if engine == Engine::TokenTrie {
912            let constraint = self.compile_token_trie(
913                vocab,
914                options.boundary_trigger.unwrap_or_default(),
915                options.token_trie_backend(),
916            )?;
917            return constraint.with_end_tokens(options.end_token_ids());
918        }
919        if engine == Engine::MergedTokenTrie && options.engine_backend == ParserBackend::LrTable {
920            let constraint = self.compile_merged_token_trie(
921                vocab,
922                options.boundary_trigger.unwrap_or_default(),
923                ParserBackend::LrTable,
924            )?;
925            return constraint.with_end_tokens(options.end_token_ids());
926        }
927        if options.parser_backend == ParserBackend::TemplateDfa
928            && engine == Engine::MergedTokenTrie && self.bindings.is_empty() {
929                return self.finish_template_attempt(vocab, &options, || {
930                    let budget = crate::compiler::build_budget::BuildBudgetScope::enter();
931                    // A partial template build must not leave prepared caches on
932                    // the source reused by the rescue attempt.
933                    let attempt_grammar = self.clone();
934                    let attempt_options = options.clone();
935                    budget.install(move || {
936                        crate::error::catch_template_attempt(move || -> Result<RuntimeConstraint> {
937                            // Use the existing O2 runtime with the bounded grammar normal
938                            // form required by finite templates. Ordinary dynamic grammar
939                            // preparation intentionally allows recursive action closures.
940                            let dynamic = match &attempt_grammar.source {
941                                GrammarSource::Glrm(_) | GrammarSource::Constructed => crate::import::compile_bounded_template_from_named(attempt_grammar.resolve_dynamic_source(vocab,false)?,vocab,crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,None),
942                                GrammarSource::Ebnf(source) => DynamicConstraint::from_ebnf_with_bounded_template_parser(source, vocab),
943                                GrammarSource::Lark(source) => DynamicConstraint::from_lark_with_bounded_template_parser(source, vocab),
944                                GrammarSource::JsonSchema(source) => DynamicConstraint::from_json_schema_with_bounded_template_parser(source, vocab),
945                            }?;
946                            let mut components = dynamic.into_constraints();
947                            if components.len() != 1 {
948                                return Err(Error::Compilation("the TemplateDfa parser backend doesn't support a choice of several grammars yet; use the LrTable backend".into()));
949                            }
950                            let mut constraint = components.pop().unwrap();
951                            ensure_runnable_constraint(&constraint)?;
952                            apply_final_boundary_trigger(&mut constraint, attempt_options.boundary_trigger.unwrap_or_default())?;
953                            constraint.with_end_tokens(attempt_options.end_token_ids())
954                        })
955                    })
956                });
957            }
958        if !self.bindings.is_empty() {
959            return self.finish_template_attempt(vocab, &options, || {
960                let budget = crate::compiler::build_budget::BuildBudgetScope::enter();
961                let attempt_grammar = self.clone();
962                let attempt_options = options.clone();
963                budget.install(move || {
964                    crate::error::catch_template_attempt(move || {
965                        attempt_grammar.prepare(vocab)?.link_with(attempt_options)
966                    })
967                })
968            });
969        }
970        self.finish_template_attempt(vocab, &options, || {
971            let budget = crate::compiler::build_budget::BuildBudgetScope::enter();
972            let attempt_grammar = self.clone();
973            let attempt_options = options.clone();
974            budget.install(move || {
975                crate::error::catch_template_attempt(move || -> Result<RuntimeConstraint> {
976                    let mut spec = ConstraintSpec::builder(attempt_grammar.clone(), vocab)?.build()?;
977                    spec.automatic_boundary_selection = true;
978                    if let Some(name) = spec.unbound_grammar_names.first() {
979                        return Err(Error::InvalidInput(format!(
980                            "extern {name:?} is unbound; bind it before compiling, or precompile to leave it open",
981                        )));
982                    }
983                    let mut constraint = spec.compile_final(engine)?;
984                    ensure_runnable_constraint(&constraint)?;
985                    let detail = attempt_options.boundary_trigger.unwrap_or_default();
986                    if attempt_options.parser_backend == ParserBackend::TemplateDfa {
987                        // Preserve the component-only proper-prefix certificate while the
988                        // LR/rule metadata still exists. A table-free constraint can be
989                        // bound later as a compiled child and must not widen that boundary
990                        // query back to the full model vocabulary merely because its table
991                        // was intentionally removed.
992                        crate::compiler::boundary_candidates::persist_boundary_candidate_summary(
993                            &mut constraint,
994                            vocab,
995                        );
996                        constraint.install_template_parser_from_compile()?;
997                    }
998                    let _ = constraint.late_bind_vocab.set(vocab.clone());
999                    apply_final_boundary_trigger(&mut constraint, detail)?;
1000                    constraint.with_end_tokens(attempt_options.end_token_ids())
1001                })
1002            })
1003        })
1004    }
1005
1006    /// Give a template-strategy decline one terminal-ended rescue attempt with
1007    /// the same strategy. If that also fails, the original typed decline is
1008    /// returned; the requested strategy is never silently replaced.
1009    ///
1010    /// The terminal-ended rescue is opt-in:
1011    /// `GLRMASK_EXPERIMENT_TERMINAL_ENDED_RESCUE=1` enables it after a typed
1012    /// template decline. `GLRMASK_EXPERIMENT_TERMINAL_ENDED_FIRST=1`
1013    /// additionally tries it before the ordinary template attempt.
1014    /// `GLRMASK_REPORT_ROUTE=1` emits one route line for this top-level compile.
1015    fn finish_template_attempt<F>(
1016        &self,
1017        vocab: &Vocab,
1018        options: &BuildOptions,
1019        attempt: F,
1020    ) -> Result<RuntimeConstraint>
1021    where
1022        F: FnOnce() -> Result<RuntimeConstraint>,
1023    {
1024        use crate::compiler::terminal_ended_rescue::{
1025            report_route, RescueExperiment, RescueOutcome, Route,
1026        };
1027        let experiment = RescueExperiment::read();
1028        let strategy = options.engine()?;
1029        let template = options.parser_backend == ParserBackend::TemplateDfa;
1030        let te_first = experiment.terminal_ended_rescue
1031            && experiment.terminal_ended_first
1032            && template
1033            && self.bindings.is_empty()
1034            && matches!(
1035                strategy,
1036                Engine::ParserDwa | Engine::MergedTokenTrie | Engine::Auto
1037            );
1038        let mut route = Route::Normal;
1039        let mut outcome = RescueOutcome::NotTried;
1040        let result = (|| -> Result<RuntimeConstraint> {
1041            // EXPERIMENT: terminal-ended first.
1042            if te_first {
1043                match self.try_terminal_ended_rescue(vocab, options) {
1044                    Ok(constraint) => {
1045                        route = Route::TerminalEnded;
1046                        outcome = RescueOutcome::Ok;
1047                        return Ok(constraint);
1048                    }
1049                    Err(rescue_error) => {
1050                        outcome = RescueOutcome::Declined(rescue_error.to_string());
1051                    }
1052                }
1053            }
1054            match attempt() {
1055                Ok(constraint) => Ok(constraint),
1056                Err(error) if error.is_strategy_decline() => {
1057                    // Opt-in experiment: give the original source one
1058                    // terminal-ended rescue attempt with the same strategy.
1059                    // Without the switch, the typed decline above is returned
1060                    // unchanged.
1061                    if template && experiment.terminal_ended_rescue && !te_first {
1062                        match self.try_terminal_ended_rescue(vocab, options) {
1063                            Ok(constraint) => {
1064                                if crate::compiler::compile::compile_profile_enabled() {
1065                                    eprintln!(
1066                                        "[glrmask/profile][terminal_ended_rescue] strategy={:?} outcome=ok",
1067                                        strategy,
1068                                    );
1069                                }
1070                                route = Route::TerminalEnded;
1071                                outcome = RescueOutcome::Ok;
1072                                return Ok(constraint);
1073                            }
1074                            Err(rescue_error) => {
1075                                if crate::compiler::compile::compile_profile_enabled() {
1076                                    eprintln!(
1077                                        "[glrmask/profile][terminal_ended_rescue] strategy={:?} outcome=declined reason={rescue_error}",
1078                                        strategy,
1079                                    );
1080                                }
1081                                outcome = RescueOutcome::Declined(rescue_error.to_string());
1082                            }
1083                        }
1084                    }
1085                    if crate::compiler::compile::compile_profile_enabled() {
1086                        eprintln!(
1087                            "[glrmask/profile][template_decline] strategy={:?} stage={} reason={error}",
1088                            strategy,
1089                            error.decline_stage(),
1090                        );
1091                    }
1092                    // Only Auto may pick a different exact strategy; an explicit
1093                    // strategy request is never silently replaced.
1094                    if strategy == Engine::Auto {
1095                        // The fallback is exactly an explicit TokenTrie request
1096                        // with the same two switches.
1097                        let constraint = self
1098                            .compile_requested_token_trie(
1099                                vocab,
1100                                options.boundary_trigger.unwrap_or_default(),
1101                                options.engine_backend,
1102                                options.merge_equivalent_tokens,
1103                            )?
1104                            .with_end_tokens(options.end_token_ids())?;
1105                        route = Route::TokenTrieFallback;
1106                        return Ok(constraint);
1107                    }
1108                    Err(error)
1109                }
1110                Err(error) => Err(error),
1111            }
1112        })();
1113        report_route(experiment.report_route, route, strategy, experiment, &outcome);
1114        result
1115    }
1116
1117    #[cfg(any(test, feature = "internal-api"))]
1118    #[doc(hidden)]
1119    pub fn prepare(&self, vocab: &Vocab) -> Result<PreparedGrammar> {
1120        self.prepare_with(vocab, BuildOptions::default())
1121    }
1122
1123    #[cfg(any(test, feature = "internal-api"))]
1124    #[doc(hidden)]
1125    pub fn prepare_with(&self, vocab: &Vocab, options: BuildOptions) -> Result<PreparedGrammar> {
1126        self.prepare_unlinked(vocab, options)
1127    }
1128
1129    // The public preparation entry points are internal-api only, but composition
1130    // and artifact loading prepare children in every build.
1131    pub(crate) fn prepare_unlinked(&self, vocab: &Vocab, options: BuildOptions) -> Result<PreparedGrammar> {
1132        with_deep_stack(|| {
1133            let _ = graph::source_first(self)?;
1134            let module = self.prepare_cached(vocab, options, &mut SourcePreparation::default(), 0)?;
1135            module.validate_slot_manifest()?;
1136            Ok(module.as_ref().clone())
1137        })
1138    }
1139
1140    #[cfg(any(test,feature="internal-api"))]
1141    #[doc(hidden)]
1142    pub fn compile_unlinked(&self,vocab:&Vocab)->Result<PreparedGrammar> {self.prepare(vocab)}
1143    #[cfg(any(test,feature="internal-api"))]
1144    #[doc(hidden)]
1145    pub fn compile_unlinked_with(&self,vocab:&Vocab,options:BuildOptions)->Result<PreparedGrammar> {self.prepare_with(vocab,options)}
1146
1147    fn prepare_cached(&self,vocab:&Vocab,options:BuildOptions,cache:&mut SourcePreparation,depth:usize)
1148        -> Result<Arc<PreparedGrammar>> {
1149        if depth>graph::MAX_DEPTH {return Err(Error::ResourceLimit("grammars are nested more than 64 levels deep".into()));}
1150        let identity=graph::source_identity(self);
1151        if let Some(module)=cache.prepared.get(&identity){return Ok(module.clone());}
1152        cache.visited+=1;
1153        if cache.visited>graph::MAX_NODES {return Err(Error::ResourceLimit("the composition has too many parts".into()));}
1154
1155        if matches!(self.source,GrammarSource::Lark(_)) {
1156            let resolved=Arc::new(self.resolve_lark(vocab)?);
1157            cache.retained.push(resolved.clone());
1158            let module=resolved.prepare_cached(vocab,options,cache,depth)?;
1159            cache.prepared.insert(identity,module.clone());return Ok(module);
1160        }
1161        self.validate_exact_target(vocab)?;
1162        self.validate_ebnf(vocab)?;
1163        let declarations=self.declarations()?;
1164        let slot_kinds=Arc::new(declarations.kinds.clone());
1165        let slot_spans=Arc::new(declarations.spans.clone());
1166        // Compile this component locally. Grammar-child attachments remain
1167        // compiled values in the unlinked graph and are linked only by link_with,
1168        // where the caller's InternalMaskStrategy choice is finally known.
1169        let (local_grammar, source_bindings) = self.clone().into_source_only_and_bindings();
1170        let mut builder = ConstraintSpec::builder(local_grammar, vocab)?;
1171        let event_adapters=Arc::new(event_cache::ExactAdapterCache::default());
1172        let mut bindings = OrdMap::<String, ModuleBinding>::new();
1173        let mut source_children = Vec::<(String, Arc<Grammar>)>::new();
1174        for (name, value) in source_bindings {
1175            match value {
1176                GrammarValue::TokenSet(tokens) => {
1177                    bindings.insert(name.clone(),ModuleBinding::TokenSet(event_adapters.leaf(tokens.range_pairs())?));
1178                    builder.token_bindings.insert(name, tokens.range_pairs().to_vec());
1179                }
1180                GrammarValue::Source(child) => {
1181                    source_children.push((name, child));
1182                }
1183            }
1184        }
1185        let mut spec = builder.build()?;
1186        spec.allow_open_source_tokens = true;
1187        spec.automatic_boundary_selection = true;
1188        // A leaf has no independent child work. Entering the global Rayon pool
1189        // here lets a worker waiting on a compiler-local pool re-enter another
1190        // unrelated compilation while retaining its heavy compiler stack.
1191        let (constraint, source_modules) = if source_children.is_empty() {
1192            (spec.compile_boxed(), Ok(Vec::new()))
1193        } else {
1194            rayon::join(
1195                || spec.compile_boxed(),
1196                || {
1197                    source_children
1198                        .into_iter()
1199                        .map(|(name, child)| {
1200                            cache.retained.push(child.clone());
1201                            Ok((name, ModuleBinding::Module(child.prepare_cached(vocab,BuildOptions::default(),cache,depth+1)?)))
1202                        })
1203                        .collect::<Result<Vec<_>>>()
1204                },
1205            )
1206        };
1207        let constraint = constraint?;
1208        for (name, binding) in source_modules? {
1209            bindings.insert(name, binding);
1210        }
1211        let module = PreparedGrammar {
1212            inner: Arc::from(constraint),
1213            bindings,
1214            analysis: graph::empty_cache(),
1215            event_adapters,
1216            boundary_trigger: options.boundary_trigger.unwrap_or_default(),
1217            slot_kinds,
1218            slot_spans,
1219            retained_artifact: None,
1220            retained_vocab_fingerprint: None,
1221        };
1222        module.validate_local_slot_manifest(vocab)?;
1223        let module=Arc::new(module);
1224        cache.prepared.insert(identity,module.clone());
1225        Ok(module)
1226    }
1227
1228    // Resolve source bindings as typed AST scopes before ordinary Dynamic
1229    // compilation. No compiled component is converted into a parser table.
1230    fn resolve_dynamic_source(&self, vocab: &Vocab, embedded: bool) -> Result<glrmask_grammar::NamedGrammar> {
1231        match &self.source {
1232            GrammarSource::Ebnf(source) => {
1233                crate::import::validate_ebnf_source(source, vocab)?;
1234                crate::import::parse_ebnf_to_named(source)
1235            }
1236            GrammarSource::Lark(_) => self.resolve_lark(vocab)?.resolve_dynamic_source(vocab,embedded),
1237            GrammarSource::JsonSchema(source) => {
1238                let mut named = crate::import::parse_json_schema_to_named_dynamic(source)?;
1239                if embedded {
1240                    named = crate::grammar::factoring::factor_named_grammar(named);
1241                    crate::import::prepare_dynamic_json_schema_named(&mut named)?;
1242                }
1243                Ok(named)
1244            }
1245            GrammarSource::Glrm(_) | GrammarSource::Constructed => {
1246                self.validate_exact_target(vocab)?;
1247                let mut children=Vec::new();let mut tokens=Vec::new();
1248                for (name,value) in &self.bindings {
1249                    match value {
1250                        GrammarValue::Source(child)=>children.push((name.as_str(),ParsedComponent::from_named(child.resolve_dynamic_source(vocab,true)?,&[]).map_err(crate::error::from_grammar)?)),
1251                        GrammarValue::TokenSet(ids)=>{
1252                            tokens.push((name.as_str(),ids.range_pairs().to_vec()));
1253                        },
1254                    }
1255                }
1256                let token_refs=tokens.iter().map(|(n,ids)|(*n,ids.as_slice())).collect::<Vec<_>>();
1257                Ok(self.component()?.with_tokens(&token_refs).map_err(crate::error::from_grammar)?.with_children(&children).map_err(crate::error::from_grammar)?.lower_closed().map_err(crate::error::from_grammar)?)
1258            }
1259        }
1260    }
1261
1262    /// Lower this source exactly as the ordinary static template route does,
1263    /// stopping at the pre-normalization `GrammarDef`. The normal route and the
1264    /// terminal-ended rescue share this function so their inputs cannot drift.
1265    pub(crate) fn lower_static_template_input(
1266        &self,
1267        vocab: &Vocab,
1268    ) -> Result<crate::grammar::flat::GrammarDef> {
1269        match &self.source {
1270            GrammarSource::Ebnf(source) => crate::import::lower_static_ebnf(source),
1271            GrammarSource::Lark(_) => {
1272                // The normal route resolves Lark into a Constructed component
1273                // first; raw parse_lark_to_named cannot express events,
1274                // imports or schemas.
1275                let resolved = self.resolve_lark(vocab)?;
1276                resolved.lower_static_template_input(vocab)
1277            }
1278            GrammarSource::JsonSchema(source) => crate::import::lower_static_json_schema(source),
1279            GrammarSource::Glrm(_) | GrammarSource::Constructed => {
1280                self.validate_exact_target(vocab)?;
1281                let named = crate::import::lower_static_component(self.component()?, vocab)?;
1282                crate::import::lower_static_named_grammar(named, &[])
1283            }
1284        }
1285    }
1286
1287    /// Lower the original source to the flat grammar consumed by the
1288    /// terminal-ended construction. Stage 1 remains restricted to plain single
1289    /// grammars: bindings and extern declarations decline the rescue. Lark is
1290    /// resolved first so events (and, until composed-unit support lands, the
1291    /// declarations produced by imports/schemas) take the normal route.
1292    fn rescue_source_grammar(
1293        &self,
1294        vocab: &Vocab,
1295    ) -> Result<crate::grammar::flat::GrammarDef> {
1296        let resolved;
1297        let source = if matches!(self.source, GrammarSource::Lark(_)) {
1298            resolved = self.resolve_lark(vocab)?;
1299            &resolved
1300        } else {
1301            self
1302        };
1303        if !source.bindings.is_empty() {
1304            return Err(Error::StrategyUnsupported(
1305                "terminal-ended rescue is limited to plain single grammars".into(),
1306            ));
1307        }
1308        if !source.declarations()?.names.is_empty() {
1309            return Err(Error::StrategyUnsupported(
1310                "terminal-ended rescue does not accept extern declarations".into(),
1311            ));
1312        }
1313        let grammar = source.lower_static_template_input(vocab)?;
1314        crate::compiler::terminal_ended_rescue::check_rescue_scope(&grammar)?;
1315        Ok(grammar)
1316    }
1317
1318    fn try_terminal_ended_rescue(
1319        &self,
1320        vocab: &Vocab,
1321        options: &BuildOptions,
1322    ) -> Result<RuntimeConstraint> {
1323        let source = self.rescue_source_grammar(vocab)?;
1324        let mut constraint = crate::compiler::terminal_ended_rescue::rescue(&source, vocab)?;
1325        apply_final_boundary_trigger(&mut constraint, options.boundary_trigger.unwrap_or_default())?;
1326        constraint.with_end_tokens(options.end_token_ids())
1327    }
1328
1329    // Use the ordinary Dynamic compiler with one complete, unsplit source
1330    // body. Resolve bindings as typed nodes before compilation, without
1331    // rebuilding the resulting Constraint through the native/O2 path.
1332    pub(crate) fn compile_token_trie(
1333        &self,
1334        vocab: &Vocab,
1335        boundary: BoundaryTriggerDetail,
1336        backend: crate::runtime::parser_backend::DynamicParserBackend,
1337    ) -> Result<RuntimeConstraint> {
1338        graph::source_preflight(self)?;
1339        if matches!(self.source, GrammarSource::Lark(_)) {
1340            return self.resolve_lark(vocab)?.compile_token_trie(vocab, boundary, backend);
1341        }
1342        self.validate_exact_target(vocab)?;
1343        self.validate_ebnf(vocab)?;
1344        let named = self.resolve_dynamic_source(vocab, false)?;
1345        let construction = match &self.source {
1346            GrammarSource::JsonSchema(_) => crate::compiler::glr::table::GlrTableConstruction::Lalr,
1347            _ => crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,
1348        };
1349        let mut constraint = crate::import::compile_dynamic_named_single_with_backend(
1350            named,
1351            vocab,
1352            construction,
1353            matches!(self.source, GrammarSource::JsonSchema(_)),
1354            backend,
1355        )?;
1356        let _ = constraint.late_bind_vocab.set(vocab.clone());
1357        ensure_runnable_constraint(&constraint)?;
1358        apply_final_boundary_trigger(&mut constraint, boundary)?;
1359        Ok(constraint)
1360    }
1361
1362    /// Compile the whole grammar as TokenTrie over the merged vocabulary
1363    /// (combinations C and D). `TemplateDfa` installs a template parser; `LrTable`
1364    /// keeps an LR table and never installs one.
1365    pub(crate) fn compile_merged_token_trie(
1366        &self,
1367        vocab: &Vocab,
1368        boundary: BoundaryTriggerDetail,
1369        backend: ParserBackend,
1370    ) -> Result<RuntimeConstraint> {
1371        graph::source_preflight(self)?;
1372        if matches!(self.source, GrammarSource::Lark(_)) {
1373            return self
1374                .resolve_lark(vocab)?
1375                .compile_merged_token_trie(vocab, boundary, backend);
1376        }
1377        self.validate_exact_target(vocab)?;
1378        self.validate_ebnf(vocab)?;
1379        let merge_error = |e: Error| {
1380            if e.is_strategy_decline() {
1381                e
1382            } else {
1383                Error::Compilation(format!(
1384                    "cannot merge equivalent tokens for this grammar: {e}"
1385                ))
1386            }
1387        };
1388        let backend = token_trie_backend(backend);
1389        let has_bindings = !self.bindings.is_empty();
1390        let mut inner = match self.source {
1391            GrammarSource::Glrm(_) | GrammarSource::Constructed | GrammarSource::Ebnf(_) => {
1392                if has_bindings {
1393                    self.compile_merged_from_resolved_source(vocab, backend)?
1394                } else if backend == crate::runtime::parser_backend::DynamicParserBackend::LrTable {
1395                    crate::import::compile_component_shell_balanced_lr(
1396                        self.component()?,
1397                        vocab,
1398                        &[],
1399                    )
1400                    .map_err(merge_error)?
1401                } else {
1402                    crate::import::compile_component_shell_balanced(
1403                        self.component()?,
1404                        vocab,
1405                        &[],
1406                    )
1407                    .map_err(merge_error)?
1408                }
1409            }
1410            _ => {
1411                if has_bindings || backend == crate::runtime::parser_backend::DynamicParserBackend::LrTable {
1412                    self.compile_merged_from_resolved_source(vocab, backend)?
1413                } else {
1414                    let dynamic = match &self.source {
1415                        GrammarSource::Lark(source) => {
1416                            DynamicConstraint::from_lark_with_bounded_template_parser(source, vocab)
1417                        }
1418                        GrammarSource::JsonSchema(source) => {
1419                            DynamicConstraint::from_json_schema_with_bounded_template_parser(
1420                                source, vocab,
1421                            )
1422                        }
1423                        _ => unreachable!(),
1424                    }
1425                    .map_err(merge_error)?;
1426                    let mut components = dynamic.into_constraints();
1427                    if components.len() != 1 {
1428                        return Err(Error::Compilation(
1429                            "cannot merge equivalent tokens in a grammar made of several parts".into(),
1430                        ));
1431                    }
1432                    components.pop().unwrap()
1433                }
1434            }
1435        };
1436        let _ = inner.late_bind_vocab.set(vocab.clone());
1437        if backend != crate::runtime::parser_backend::DynamicParserBackend::LrTable {
1438            inner.install_template_parser_from_compile()?;
1439        }
1440        ensure_runnable_constraint(&inner)?;
1441        apply_final_boundary_trigger(&mut inner, boundary)?;
1442        Ok(inner)
1443    }
1444
1445    /// Resolve bindings exactly as the unmerged flatten path does, then compile
1446    /// the whole resolved grammar through the merged-vocabulary lane.
1447    fn compile_merged_from_resolved_source(
1448        &self,
1449        vocab: &Vocab,
1450        backend: crate::runtime::parser_backend::DynamicParserBackend,
1451    ) -> Result<RuntimeConstraint> {
1452        let named = self.resolve_dynamic_source(vocab, false)?;
1453        let construction = match &self.source {
1454            GrammarSource::JsonSchema(_) => crate::compiler::glr::table::GlrTableConstruction::Lalr,
1455            _ => crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,
1456        };
1457        let merge_error = |e: Error| {
1458            if e.is_strategy_decline() {
1459                e
1460            } else {
1461                Error::Compilation(format!(
1462                    "cannot merge equivalent tokens for this grammar: {e}"
1463                ))
1464            }
1465        };
1466        crate::import::compile_dynamic_named_single_merged(
1467            named,
1468            vocab,
1469            construction,
1470            matches!(self.source, GrammarSource::JsonSchema(_)),
1471            backend,
1472        )
1473        .map_err(merge_error)
1474    }
1475
1476    /// Compile a TokenTrie request with the supplied switches, whether they
1477    /// were explicit or reached through `Auto`'s decline fallback.
1478    fn compile_requested_token_trie(
1479        &self,
1480        vocab: &Vocab,
1481        boundary: BoundaryTriggerDetail,
1482        parser_backend: ParserBackend,
1483        merge_equivalent_tokens: bool,
1484    ) -> Result<RuntimeConstraint> {
1485        if merge_equivalent_tokens {
1486            self.compile_merged_token_trie(vocab, boundary, parser_backend)
1487        } else {
1488            self.compile_token_trie(vocab, boundary, token_trie_backend(parser_backend))
1489        }
1490    }
1491
1492    pub(crate) fn from_expr_ref(expr: &Expr) -> Result<Grammar> {
1493        let module = Module::from_expr(expr, false)?;
1494        module.to_source()
1495    }
1496
1497    fn unresolved_external_names(&self) -> Result<BTreeSet<String>> {
1498        Ok(graph::source_first(self)?.map(|r|r.name()).into_iter().collect())
1499    }
1500
1501    fn glrm_source(&self) -> Option<&str> {
1502        match &self.source {
1503            GrammarSource::Glrm(source) => Some(source),
1504            _ => None,
1505        }
1506    }
1507
1508    fn into_source_only_and_bindings(self) -> (Self, OrdMap<String, GrammarValue>) {
1509        let mut source=self;
1510        let bindings=std::mem::take(&mut source.bindings);
1511        source.analysis=graph::empty_cache();
1512        source.module_snapshot=Arc::new(OnceLock::new());
1513        (source,bindings)
1514    }
1515}
1516
1517impl IntoGrammarValue for Grammar {
1518    fn into_grammar_value(self) -> Result<GrammarValue> {
1519        Ok(GrammarValue::Source(Arc::new(self)))
1520    }
1521}
1522
1523impl IntoGrammarValue for &Grammar {
1524    fn into_grammar_value(self) -> Result<GrammarValue> {
1525        Ok(GrammarValue::Source(Arc::new(self.clone())))
1526    }
1527}
1528
1529impl IntoGrammarValue for TokenSet {
1530    fn into_grammar_value(self) -> Result<GrammarValue> {
1531        Ok(GrammarValue::TokenSet(self))
1532    }
1533}
1534
1535impl IntoGrammarValue for u32 {
1536    fn into_grammar_value(self) -> Result<GrammarValue> {
1537        Ok(GrammarValue::TokenSet(TokenSet::new([self])))
1538    }
1539}
1540
1541impl IntoGrammarValue for Expr {
1542    fn into_grammar_value(self)->Result<GrammarValue> {
1543        Ok(GrammarValue::Source(Arc::new(Grammar::from_expr_ref(&self)?)))
1544    }
1545}
1546impl IntoGrammarValue for &Expr {
1547    fn into_grammar_value(self)->Result<GrammarValue> {
1548        Ok(GrammarValue::Source(Arc::new(Grammar::from_expr_ref(self)?)))
1549    }
1550}
1551
1552#[cfg(any(test,feature="internal-api"))]
1553impl<'a> IntoUnlinkedValue<'a> for &'a RuntimeConstraint {
1554    fn into_unlinked_value(self) -> UnlinkedValue<'a> {
1555        UnlinkedValue::StaticBorrowed(self)
1556    }
1557}
1558
1559#[cfg(any(test,feature="internal-api"))]
1560impl<'a> IntoUnlinkedValue<'a> for RuntimeConstraint {
1561    fn into_unlinked_value(self) -> UnlinkedValue<'a> {
1562        UnlinkedValue::StaticOwned(Arc::new(self))
1563    }
1564}
1565
1566#[cfg(any(test,feature="internal-api"))]
1567impl<'a> IntoUnlinkedValue<'a> for Arc<RuntimeConstraint> {
1568    fn into_unlinked_value(self) -> UnlinkedValue<'a> {
1569        UnlinkedValue::StaticOwned(self)
1570    }
1571}
1572
1573impl<'a> IntoUnlinkedValue<'a> for &'a PreparedGrammar {
1574    fn into_unlinked_value(self)->UnlinkedValue<'a>{UnlinkedValue::Prepared(Arc::new(self.clone()))}
1575}
1576impl<'a> IntoUnlinkedValue<'a> for PreparedGrammar {
1577    fn into_unlinked_value(self)->UnlinkedValue<'a>{UnlinkedValue::Prepared(Arc::new(self))}
1578}
1579
1580impl<'a> IntoUnlinkedValue<'a> for TokenSet {
1581    fn into_unlinked_value(self) -> UnlinkedValue<'a> {
1582        UnlinkedValue::TokenSet(self)
1583    }
1584}
1585
1586impl<'a> IntoUnlinkedValue<'a> for u32 {
1587    fn into_unlinked_value(self) -> UnlinkedValue<'a> {
1588        UnlinkedValue::TokenSet(TokenSet::new([self]))
1589    }
1590}
1591
1592
1593/// Strategy used to build a [`VocabPartition`].
1594///
1595/// All strategies are conservative: they may keep tokens separate when a more
1596/// expensive proof could merge them, but they never intentionally merge tokens
1597/// whose grammar-visible behavior differs.
1598#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1599pub enum VocabPartitionStrategy {
1600    /// Choose automatically from the observable lexer topology.
1601    #[default]
1602    Automatic,
1603    /// Prefer the Static-derived quotient, which is usually more compact but may
1604    /// spend more time proving multi-token equivalences on small lexers.
1605    Compact,
1606    /// Use the dedicated vocabulary-only relation. This often compiles faster on
1607    /// small lexers but may return a finer partition with more classes.
1608    Dedicated,
1609}
1610
1611/// A conservative grammar-specific equivalence partition of model vocabulary tokens.
1612///
1613/// Tokens in the same class have been proved interchangeable by the fast
1614/// vocabulary analysis. The partition may be finer than the token partition of
1615/// a fully compiled [`Constraint`](crate::Constraint): expensive proof steps may
1616/// deliberately be skipped, in which case affected tokens remain separated.
1617#[derive(Debug, Clone)]
1618pub struct VocabPartition {
1619    original_to_class: Vec<u32>,
1620    classes: Vec<Vec<u32>>,
1621    representatives: Vec<u32>,
1622    class_output_masks: Vec<Vec<(u32, u32)>>,
1623}
1624
1625impl VocabPartition {
1626    /// Analyze `grammar` for `vocab` without constructing terminal/parser DWAs.
1627    pub fn compile(grammar: Grammar, vocab: &Vocab) -> Result<Self> {
1628        Self::compile_with_strategy(grammar, vocab, VocabPartitionStrategy::Automatic)
1629    }
1630
1631    /// Analyze `grammar` for `vocab` using an explicit partition strategy.
1632    pub fn compile_with_strategy(
1633        grammar: Grammar,
1634        vocab: &Vocab,
1635        strategy: VocabPartitionStrategy,
1636    ) -> Result<Self> {
1637        let profile = crate::compiler::pipeline::compile_top_profile_enabled();
1638        let total_started = profile.then(Instant::now);
1639        if !grammar.bindings.is_empty() {
1640            return Err(Error::Compilation(
1641                "vocabulary partition analysis does not yet support bound grammar values".to_owned(),
1642            ));
1643        }
1644        let source_kind = match &grammar.source {
1645            GrammarSource::Ebnf(_) => "ebnf",
1646            GrammarSource::Lark(_) => "lark",
1647            GrammarSource::JsonSchema(_) => "json_schema",
1648            GrammarSource::Glrm(_) => "glrm",
1649            GrammarSource::Constructed => return Err(Error::Compilation("use normal preparation for constructed event grammars".into())),
1650        };
1651        let source = match &grammar.source {
1652            GrammarSource::Ebnf(source)
1653            | GrammarSource::Lark(source)
1654            | GrammarSource::JsonSchema(source)
1655            | GrammarSource::Glrm(source) => source,
1656            GrammarSource::Constructed => unreachable!("handled before source lookup"),
1657        };
1658        let lower_started = profile.then(Instant::now);
1659        let grammar_def = crate::import::lower_source_for_vocab_partition(source_kind, source)?;
1660        let lower_ms = lower_started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1000.0);
1661        let compile_started = profile.then(Instant::now);
1662        let map = crate::error::catch_internal_invariant(|| {
1663            crate::compiler::vocab_partition::compile_vocab_partition_owned(grammar_def, vocab, strategy)
1664        })?;
1665        if profile {
1666            eprintln!(
1667                "[glrmask/profile][vocab_partition_compile] source={} lower_ms={:.3} compile_ms={:.3} total_ms={:.3}",
1668                source_kind,
1669                lower_ms,
1670                compile_started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1000.0),
1671                total_started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1000.0),
1672            );
1673        }
1674        let classes = map.internal_to_originals;
1675        // Internal O2/vocab-only compilation is allowed to carry only grouped
1676        // class membership and deliberately omit the model-vocab-sized dense
1677        // original-token -> class vector. `VocabPartition` is a public API,
1678        // however, and explicitly exposes that dense coordinate through
1679        // `class_of()` / `original_to_class()`. Materialize it once at this
1680        // boundary rather than forcing every internal fast path to carry it.
1681        let original_to_class = if map.original_to_internal.is_empty() && !classes.is_empty() {
1682            let mut dense = crate::error::try_token_table(vocab.max_token_id() as usize + 1, u32::MAX)?;
1683            for (class_id, class) in classes.iter().enumerate() {
1684                for &token_id in class {
1685                    dense[token_id as usize] = class_id as u32;
1686                }
1687            }
1688            dense
1689        } else {
1690            map.original_to_internal
1691        };
1692        let class_output_masks = classes
1693            .iter()
1694            .map(|class| {
1695                let mut words = Vec::<(u32, u32)>::new();
1696                for &token_id in class {
1697                    let word = token_id / 32;
1698                    let bit = 1u32 << (token_id % 32);
1699                    if let Some((last_word, last_bits)) = words.last_mut()
1700                        && *last_word == word
1701                    {
1702                        *last_bits |= bit;
1703                    } else {
1704                        words.push((word, bit));
1705                    }
1706                }
1707                words
1708            })
1709            .collect();
1710        Ok(Self {
1711            original_to_class,
1712            classes,
1713            representatives: map.representative_original_ids,
1714            class_output_masks,
1715        })
1716    }
1717
1718    /// Number of equivalence classes.
1719    pub fn num_classes(&self) -> usize { self.classes.len() }
1720
1721    /// Class containing `token_id`, or `None` if that token ID was not in the vocabulary.
1722    pub fn class_of(&self, token_id: u32) -> Option<u32> {
1723        self.original_to_class
1724            .get(token_id as usize)
1725            .copied()
1726            .filter(|&class| class != u32::MAX)
1727    }
1728
1729    /// Original model token IDs grouped by equivalence class.
1730    pub fn classes(&self) -> &[Vec<u32>] { &self.classes }
1731
1732    /// A stable original-token representative for `class_id`.
1733    pub fn representative(&self, class_id: u32) -> Option<u32> {
1734        self.representatives
1735            .get(class_id as usize)
1736            .copied()
1737            .filter(|&token| token != u32::MAX)
1738    }
1739
1740    /// Dense original-token-ID to class-ID map. Missing token IDs contain `u32::MAX`.
1741    pub fn original_to_class(&self) -> &[u32] { &self.original_to_class }
1742
1743    /// Number of packed `u64` words needed for a class-space mask.
1744    pub fn internal_mask_len(&self) -> usize { self.num_classes().div_ceil(64) }
1745
1746    /// Number of packed `u32` words needed for an original-token-space mask.
1747    pub fn original_mask_len(&self) -> usize { self.original_to_class.len().div_ceil(32) }
1748
1749    /// Expand a packed class-space mask into the original model-token ID space.
1750    ///
1751    /// Bit `i` in `internal_mask` selects equivalence class `i`. Every original
1752    /// token in each selected class is set in the returned packed `u32` mask.
1753    /// Bits beyond [`Self::num_classes`] are ignored.
1754    pub fn expand_mask(&self, internal_mask: &[u64]) -> Vec<u32> {
1755        let mut out = vec![0u32; self.original_mask_len()];
1756        self.fill_expanded_mask(internal_mask, &mut out);
1757        out
1758    }
1759
1760    /// Expand a packed class-space mask into an existing original-token mask buffer.
1761    ///
1762    /// `out` must contain at least [`Self::original_mask_len`] `u32` words. The
1763    /// entire supplied buffer is cleared before expansion, matching the overwrite
1764    /// semantics of [`ConstraintState::fill_mask`](crate::ConstraintState::fill_mask).
1765    pub fn fill_expanded_mask(&self, internal_mask: &[u64], out: &mut [u32]) {
1766        let required = self.original_mask_len();
1767        assert!(
1768            out.len() >= required,
1769            "expanded mask buffer is smaller than original vocabulary mask"
1770        );
1771        out.fill(0);
1772
1773        for (word_index, &word) in internal_mask.iter().enumerate() {
1774            let class_base = word_index * 64;
1775            if class_base >= self.num_classes() {
1776                break;
1777            }
1778            let mut selected = word;
1779            while selected != 0 {
1780                let bit = selected.trailing_zeros() as usize;
1781                let class_id = class_base + bit;
1782                if class_id >= self.num_classes() {
1783                    break;
1784                }
1785                for &(output_word, output_bits) in &self.class_output_masks[class_id] {
1786                    out[output_word as usize] |= output_bits;
1787                }
1788                selected &= selected - 1;
1789            }
1790        }
1791    }
1792}
1793
1794/// A grammar, vocabulary, and complete set of extern bindings.
1795#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1796pub enum BoundarySummaryPolicy {
1797    /// Do not prepare or persist the static-composition candidate summary.
1798    Disabled,
1799    /// Prepare the summary only when a later static composition actually needs
1800    /// it. This is the default so ordinary standalone compilation pays no tax.
1801    #[default]
1802    LazyOnCompose,
1803    /// Prepare the bounded conservative summary during component compilation so
1804    /// later composition can consume it without first-touch analysis.
1805    BoundedPrepare,
1806}
1807
1808/// A grammar, vocabulary, and complete set of extern bindings.
1809#[derive(Debug, Clone)]
1810pub struct ConstraintSpec<'a> {
1811    grammar: Grammar,
1812    vocab: &'a Vocab,
1813    token_bindings: BTreeMap<String, Vec<(u32, u32)>>,
1814    grammar_bindings: BTreeMap<String, SpecGrammarBinding<'a>>,
1815    unbound_grammar_names: Vec<String>,
1816    // Only explicit module compilation may preserve unbound source token
1817    // slots. Legacy specification compilation keeps its validation contract.
1818    allow_open_source_tokens: bool,
1819    automatic_boundary_selection: bool,
1820    // These belong to this source component. Register their terminal identity
1821    // before linking: another component may independently use the same hidden
1822    // token ID, which is not a globally unique linker coordinate.
1823    open_token_placeholders: BTreeMap<String, u32>,
1824    boundary_trigger_detail: BoundaryTriggerDetail,
1825    boundary_summary_policy: BoundarySummaryPolicy,
1826}
1827
1828/// Builder for [`ConstraintSpec`].
1829#[derive(Debug)]
1830pub struct ConstraintSpecBuilder<'a> {
1831    grammar: Grammar,
1832    vocab: &'a Vocab,
1833    declared_externals: BTreeSet<String>,
1834    token_bindings: BTreeMap<String, Vec<(u32, u32)>>,
1835    grammar_bindings: BTreeMap<String, SpecGrammarBinding<'a>>,
1836    boundary_trigger_detail: BoundaryTriggerDetail,
1837    boundary_summary_policy: BoundarySummaryPolicy,
1838}
1839
1840/// Internal input accepted by [`ConstraintSpecBuilder::bind_grammar`].
1841#[doc(hidden)]
1842#[non_exhaustive]
1843#[derive(Debug, Clone)]
1844pub(crate) enum SpecGrammarBinding<'a> {
1845    Source(Grammar),
1846    Spec(Box<ConstraintSpec<'a>>),
1847    #[doc(hidden)]
1848    StaticBorrowed(&'a RuntimeConstraint),
1849    #[doc(hidden)]
1850    StaticOwned(Arc<RuntimeConstraint>),
1851    #[doc(hidden)]
1852    DynamicBorrowed(&'a DynamicConstraint),
1853    #[doc(hidden)]
1854    DynamicOwned(Arc<DynamicConstraint>),
1855}
1856
1857/// Converts a supported child grammar into an internal binding.
1858#[doc(hidden)]
1859pub(crate) trait IntoSpecGrammarBinding<'a> {
1860    #[doc(hidden)]
1861    fn into_grammar_binding(self) -> SpecGrammarBinding<'a>;
1862}
1863
1864impl<'a> IntoSpecGrammarBinding<'a> for Grammar {
1865    fn into_grammar_binding(self) -> SpecGrammarBinding<'a> { SpecGrammarBinding::Source(self) }
1866}
1867
1868impl<'a> IntoSpecGrammarBinding<'a> for ConstraintSpec<'a> {
1869    fn into_grammar_binding(self) -> SpecGrammarBinding<'a> {
1870        SpecGrammarBinding::Spec(Box::new(self))
1871    }
1872}
1873
1874impl<'a> IntoSpecGrammarBinding<'a> for &ConstraintSpec<'a> {
1875    fn into_grammar_binding(self) -> SpecGrammarBinding<'a> {
1876        SpecGrammarBinding::Spec(Box::new(self.clone()))
1877    }
1878}
1879
1880impl<'a> IntoSpecGrammarBinding<'a> for RuntimeConstraint {
1881    fn into_grammar_binding(self) -> SpecGrammarBinding<'a> {
1882        SpecGrammarBinding::StaticOwned(Arc::new(self))
1883    }
1884}
1885
1886impl<'a> IntoSpecGrammarBinding<'a> for &'a RuntimeConstraint {
1887    fn into_grammar_binding(self) -> SpecGrammarBinding<'a> {
1888        SpecGrammarBinding::StaticBorrowed(self)
1889    }
1890}
1891
1892impl<'a> IntoSpecGrammarBinding<'a> for Arc<RuntimeConstraint> {
1893    fn into_grammar_binding(self) -> SpecGrammarBinding<'a> {
1894        SpecGrammarBinding::StaticOwned(self)
1895    }
1896}
1897
1898impl<'a> IntoSpecGrammarBinding<'a> for DynamicConstraint {
1899    fn into_grammar_binding(self) -> SpecGrammarBinding<'a> {
1900        SpecGrammarBinding::DynamicOwned(Arc::new(self))
1901    }
1902}
1903
1904impl<'a> IntoSpecGrammarBinding<'a> for &'a DynamicConstraint {
1905    fn into_grammar_binding(self) -> SpecGrammarBinding<'a> {
1906        SpecGrammarBinding::DynamicBorrowed(self)
1907    }
1908}
1909
1910impl<'a> IntoSpecGrammarBinding<'a> for Arc<DynamicConstraint> {
1911    fn into_grammar_binding(self) -> SpecGrammarBinding<'a> {
1912        SpecGrammarBinding::DynamicOwned(self)
1913    }
1914}
1915
1916impl<'a> ConstraintSpec<'a> {
1917    /// Start a specification for `grammar` and `vocab`.
1918    pub fn builder(
1919        grammar: Grammar,
1920        vocab: &'a Vocab,
1921    ) -> Result<ConstraintSpecBuilder<'a>> {
1922        ConstraintSpecBuilder::new(grammar, vocab)
1923    }
1924
1925    /// Compile this specification into a [`Constraint`](crate::Constraint).
1926    pub fn compile(&self) -> Result<RuntimeConstraint> {
1927        Ok(*self.compile_boxed()?)
1928    }
1929
1930    // Keep the large native value off compiler/join frames that can remain
1931    // live while Rayon executes another source compilation on this worker.
1932    fn compile_boxed(&self) -> Result<Box<RuntimeConstraint>> {
1933        with_deep_stack(|| {
1934            let mut constraint = self.compile_static_with_trigger_boxed()?;
1935            // A constraint with unresolved external grammars is explicitly a
1936            // reusable late-bind parent.  Cache its exact tokenizer-reset
1937            // terminal -> model-token relation now, while compilation already owns
1938            // the vocabulary, instead of rescanning the vocabulary on every later
1939            // bind.  The cache is part of composition metadata and therefore
1940            // survives ordinary save/load.
1941            if !constraint.late_grammar_slots.is_empty() {
1942                constraint.ensure_composition_reset_tokens_by_terminal();
1943            }
1944            match self.boundary_summary_policy {
1945                BoundarySummaryPolicy::Disabled => {
1946                    let _ = constraint.boundary_candidate_summary.set(
1947                        crate::runtime::BoundaryCandidateSummary::Unknown {
1948                            reason: crate::runtime::SummaryUnavailable::Disabled,
1949                        },
1950                    );
1951                }
1952                BoundarySummaryPolicy::LazyOnCompose => {}
1953                BoundarySummaryPolicy::BoundedPrepare => {
1954                    crate::compiler::boundary_candidates::prepare_boundary_candidate_summary(
1955                        &constraint,
1956                        self.vocab,
1957                    );
1958                }
1959            }
1960            // Keep first-save latency bounded without charging serialization to
1961            // every ordinary compile. Static virtual-residual constraints can carry
1962            // very large runtime sections, while exceptionally large parser-template
1963            // caches are expensive to encode on demand. Prime only those structural
1964            // tails; ordinary constraints serialize when save() is actually called.
1965            if should_prime_first_save_artifact(&constraint) {
1966                constraint.cache_serialized_artifact_for_save();
1967            }
1968            Ok(constraint)
1969        })
1970    }
1971
1972    fn compile_final(&self, optimization: Engine) -> Result<RuntimeConstraint> {
1973        match optimization {
1974            Engine::TokenTrie => Ok(self.compile_dynamic()?.into_constraint()),
1975            Engine::MergedTokenTrie => {
1976                let dynamic = self.compile_dynamic()?;
1977                collapse_dynamic_alternatives(
1978                    dynamic.into_constraints(),
1979                    self.vocab,
1980                    SegmentedBoundaryBackend::Dynamic,
1981                )
1982            }
1983            Engine::Auto | Engine::ParserDwa => self.compile(),
1984        }
1985    }
1986
1987    fn compile_static_with_trigger_boxed(&self) -> Result<Box<RuntimeConstraint>> {
1988        let mut constraint = self.compile_static_uncached()?;
1989        constraint
1990            .build_boundary_trigger(self.boundary_trigger_detail)
1991            .map_err(Error::Compilation)?;
1992        Ok(constraint)
1993    }
1994
1995    fn register_open_token_placeholders(&self, parent: &mut RuntimeConstraint) -> Result<()> {
1996        for (name, &placeholder_id) in &self.open_token_placeholders {
1997            let terminals = parent.special_token_terminals.iter()
1998                .filter(|special| special.token_id == placeholder_id)
1999                .map(|special| special.terminal_id).collect::<BTreeSet<_>>();
2000            if terminals.len() != 1 {
2001                return Err(Error::Compilation(format!(
2002                    "compiled external token {name:?} did not resolve to exactly one component-local terminal",
2003                )));
2004            }
2005            parent.late_grammar_slots.push(crate::runtime::LateGrammarSlot {
2006                name: name.clone(),
2007                terminal_id: *terminals.iter().next().expect("length checked"),
2008            });
2009        }
2010        if !self.open_token_placeholders.is_empty() {
2011            parent.serialized_artifact_cache = None;
2012            if parent.sanitize_late_grammar_placeholder_token_domain() {
2013                parent.rebuild_runtime_caches();
2014            }
2015        }
2016        Ok(())
2017    }
2018
2019    #[inline(never)]
2020    fn compile_static_parent_boxed(&self) -> Result<Box<RuntimeConstraint>> {
2021        let token_bindings = self.token_binding_refs();
2022        let parent=compile_static_source(&self.grammar,self.vocab,&token_bindings)?;
2023        Ok(Box::new(parent))
2024    }
2025
2026    fn compile_static_uncached(&self) -> Result<Box<RuntimeConstraint>> {
2027        let compile_parent = || self.compile_static_parent_boxed();
2028        if self.grammar_bindings.is_empty() {
2029            let mut parent = compile_parent()?;
2030            self.register_open_token_placeholders(&mut parent)?;
2031            return Ok(parent);
2032        }
2033
2034        // Parent-local compilation and child-local compilation have no
2035        // semantic dependency. Run them in the same Rayon pool and join only
2036        // before boundary construction, which genuinely needs both artifacts.
2037        let (parent, children) = rayon::join(
2038            compile_parent,
2039            || self.compile_children(ChildCompileMode::Static),
2040        );
2041        let mut parent = parent?;
2042        self.register_open_token_placeholders(&mut parent)?;
2043        let children = children?;
2044        let children = prepare_compiled_children(
2045            children, self.vocab, SegmentedBoundaryBackend::StaticParserDwa,
2046        )?;
2047        let boundary_backend = if self.automatic_boundary_selection {
2048            select_supported_boundary(&parent, &children)?
2049        } else {
2050            SegmentedBoundaryBackend::StaticParserDwa
2051        };
2052        compose_boxed_parent(parent, &children, self.vocab, boundary_backend)
2053    }
2054
2055    /// Compile this specification into a [`DynamicConstraint`].
2056    pub fn compile_dynamic(&self) -> Result<DynamicConstraint> {
2057        Ok(*self.compile_dynamic_boxed()?)
2058    }
2059
2060    fn compile_dynamic_boxed(&self) -> Result<Box<DynamicConstraint>> {
2061        let mut constraint = self.compile_dynamic_uncached()?;
2062        for component in constraint.constraints_mut() {
2063            // Retain the supplied shared vocabulary, just as static compilation
2064            // does. Reconstructing it from every token's bytes on the first bind
2065            // costs more than compiling many small dynamic components.
2066            let _ = component.late_bind_vocab.set(self.vocab.clone());
2067            component
2068                .build_boundary_trigger(self.boundary_trigger_detail)
2069                .map_err(Error::Compilation)?;
2070            match self.boundary_summary_policy {
2071                BoundarySummaryPolicy::Disabled => {
2072                    let _ = component.boundary_candidate_summary.set(
2073                        crate::runtime::BoundaryCandidateSummary::Unknown {
2074                            reason: crate::runtime::SummaryUnavailable::Disabled,
2075                        },
2076                    );
2077                }
2078                BoundarySummaryPolicy::LazyOnCompose => {}
2079                BoundarySummaryPolicy::BoundedPrepare => {
2080                    crate::compiler::boundary_candidates::prepare_boundary_candidate_summary(
2081                        component,
2082                        self.vocab,
2083                    );
2084                }
2085            }
2086        }
2087        Ok(constraint)
2088    }
2089
2090    #[inline(never)]
2091    fn compile_dynamic_parent_boxed(&self) -> Result<Box<DynamicConstraint>> {
2092        let token_bindings = self.token_binding_refs();
2093        let parent=compile_dynamic_source(&self.grammar,self.vocab,&token_bindings)?;
2094        Ok(Box::new(parent))
2095    }
2096
2097    fn compile_dynamic_uncached(&self) -> Result<Box<DynamicConstraint>> {
2098        if self.grammar_bindings.is_empty() {
2099            return self.compile_dynamic_parent_boxed();
2100        }
2101        if !matches!(self.grammar.source,GrammarSource::Glrm(_)|GrammarSource::Constructed) {
2102            return Err(Error::Compilation(
2103                "external grammar bindings require a GLRM grammar".to_owned(),
2104            ));
2105        }
2106        let (parents, children) = rayon::join(
2107            || self.compile_dynamic_parent_boxed(),
2108            || self.compile_children(ChildCompileMode::Dynamic),
2109        );
2110        let parents = parents?;
2111        let children = prepare_compiled_children(
2112            children?, self.vocab, SegmentedBoundaryBackend::Dynamic,
2113        )?;
2114        compose_boxed_dynamic_parents(parents, &children, self.vocab)
2115    }
2116
2117    fn token_binding_refs(&self) -> Vec<(&str, &[(u32, u32)])> {
2118        self.token_bindings
2119            .iter()
2120            .map(|(name, ids)| (name.as_str(), ids.as_slice()))
2121            .collect()
2122    }
2123
2124    fn compile_children(
2125        &self,
2126        mode: ChildCompileMode,
2127    ) -> Result<Vec<(String, CompiledChild<'_>)>> {
2128        let bindings = self.grammar_bindings.iter().collect::<Vec<_>>();
2129        bindings
2130            .par_iter()
2131            .map(|(name, binding)| {
2132                Ok((
2133                    (*name).clone(),
2134                    binding.compile(self.vocab, mode, self.allow_open_source_tokens)?,
2135                ))
2136            })
2137            .collect()
2138    }
2139
2140    fn targets(&self, vocab: &Vocab) -> bool {
2141        self.vocab.same_model_vocab(vocab)
2142    }
2143}
2144
2145impl<'a> ConstraintSpecBuilder<'a> {
2146    fn new(grammar: Grammar, vocab: &'a Vocab) -> Result<Self> {
2147        let (grammar, source_bindings) = grammar.into_source_only_and_bindings();
2148        grammar.validate_ebnf(vocab)?;
2149        let declarations = grammar.declarations()?;
2150        let declared_externals = declarations.names.iter().cloned().collect::<BTreeSet<_>>();
2151        let mut token_bindings = BTreeMap::new();
2152        let mut grammar_bindings = BTreeMap::new();
2153        for (name, value) in source_bindings {
2154            match value {
2155                GrammarValue::TokenSet(tokens) => {
2156                    if !declared_externals.contains(&name) {
2157                        return Err(Error::Compilation(format!(
2158                            "there is no token extern named {name:?}",
2159                        )));
2160                    }
2161                    token_bindings.insert(name, tokens.range_pairs().to_vec());
2162                }
2163                GrammarValue::Source(child) => {
2164                    if !declared_externals.contains(&name) {
2165                        return Err(Error::Compilation(format!(
2166                            "there is no grammar extern named {name:?}",
2167                        )));
2168                    }
2169                    grammar_bindings.insert(name, SpecGrammarBinding::Source(child.as_ref().clone()));
2170                }
2171            }
2172        }
2173        for (name, binding) in &mut grammar_bindings {
2174            binding.bind_target(vocab, name)?;
2175        }
2176        Ok(Self {
2177            grammar,
2178            vocab,
2179            declared_externals,
2180            token_bindings,
2181            grammar_bindings,
2182            boundary_trigger_detail: BoundaryTriggerDetail::None,
2183            boundary_summary_policy: BoundarySummaryPolicy::LazyOnCompose,
2184        })
2185    }
2186
2187    /// Request reusable dynamic-boundary trigger metadata for this component.
2188    ///
2189    /// The default is [`BoundaryTriggerDetail::None`], which adds no trigger
2190    /// construction cost. This setting is independent of static vs dynamic
2191    /// ordinary masking.
2192    pub fn boundary_trigger_detail(mut self, detail: BoundaryTriggerDetail) -> Self {
2193        self.boundary_trigger_detail = detail;
2194        self
2195    }
2196
2197    /// Configure preparation of the grammar-aware static composition boundary
2198    /// candidate summary. This is independent of [`BoundaryTriggerDetail`],
2199    /// which controls dynamic-runtime trigger metadata.
2200    pub fn boundary_summary_policy(mut self, policy: BoundarySummaryPolicy) -> Self {
2201        self.boundary_summary_policy = policy;
2202        self
2203    }
2204
2205    /// Bind an `extern NAME;` declaration to token IDs.
2206    pub fn bind_token(
2207        mut self,
2208        name: impl AsRef<str>,
2209        token_ids: impl IntoIterator<Item = u32>,
2210    ) -> Result<Self> {
2211        let name = name.as_ref();
2212        self.require_declared(name)?;
2213        check_binding_kind(name,self.grammar.declarations()?.kinds[name],false)?;
2214        if self.token_bindings.contains_key(name) || self.grammar_bindings.contains_key(name) {
2215            return Err(Error::InvalidInput(format!(
2216                "extern {name:?} is already bound",
2217            )));
2218        }
2219        let token_ids = token_ids.into_iter().collect::<Vec<_>>();
2220        let unique = token_ids.iter().copied().collect::<BTreeSet<_>>();
2221        if unique.len() != token_ids.len() {
2222            return Err(Error::Compilation(format!(
2223                "the token IDs bound to extern {name:?} contain a duplicate",
2224            )));
2225        }
2226        self.token_bindings
2227            .insert(name.to_owned(), range_set_blaze::RangeSetBlaze::from_iter(unique)
2228                .ranges().map(|range| (*range.start(), *range.end())).collect());
2229        Ok(self)
2230    }
2231
2232    /// Bind an `extern NAME;` to a source, spec, or compiled constraint.
2233    #[allow(private_bounds)]
2234    pub fn bind_grammar<T>(mut self, name: impl AsRef<str>, realization: T) -> Result<Self>
2235    where
2236        T: IntoSpecGrammarBinding<'a>,
2237    {
2238        let name = name.as_ref();
2239        self.require_declared(name)?;
2240        check_binding_kind(name,self.grammar.declarations()?.kinds[name],true)?;
2241        if self.grammar_bindings.contains_key(name) || self.token_bindings.contains_key(name) {
2242            return Err(Error::InvalidInput(format!(
2243                "extern {name:?} is already bound",
2244            )));
2245        }
2246        let mut realization = realization.into_grammar_binding();
2247        realization.bind_target(self.vocab, name)?;
2248        self.grammar_bindings.insert(name.to_owned(), realization);
2249        Ok(self)
2250    }
2251
2252    /// Finish the specification, retaining any unresolved externs.
2253    ///
2254    /// Externs may remain unresolved. Their names are retained in
2255    /// the compiled constraint and can be supplied later with
2256    /// [`RuntimeConstraint::bind_grammar`] or [`DynamicConstraint::bind_grammar`].
2257    pub fn build(self) -> Result<ConstraintSpec<'a>> {
2258        let unbound_grammar_names = self
2259            .declared_externals
2260            .iter()
2261            .filter(|name| !self.grammar_bindings.contains_key(*name) && !self.token_bindings.contains_key(*name))
2262            .cloned()
2263            .collect::<Vec<_>>();
2264        Ok(ConstraintSpec {
2265            grammar: self.grammar,
2266            vocab: self.vocab,
2267            token_bindings: self.token_bindings,
2268            grammar_bindings: self.grammar_bindings,
2269            unbound_grammar_names,
2270            allow_open_source_tokens: false,
2271            automatic_boundary_selection: false,
2272            open_token_placeholders: BTreeMap::new(),
2273            boundary_trigger_detail: self.boundary_trigger_detail,
2274            boundary_summary_policy: self.boundary_summary_policy,
2275        })
2276    }
2277
2278    fn require_declared(&self, name: &str) -> Result<()> {
2279        if self.declared_externals.contains(name) {
2280            return Ok(());
2281        }
2282        Err(Error::InvalidInput(format!("there is no extern named {name:?}")))
2283    }
2284}
2285
2286#[derive(Clone, Copy)]
2287enum ChildCompileMode {
2288    Static,
2289    Dynamic,
2290}
2291
2292enum CompiledChild<'a> {
2293    StaticBorrowed(&'a RuntimeConstraint),
2294    StaticOwned(Box<RuntimeConstraint>),
2295    DynamicBorrowed(&'a DynamicConstraint),
2296    DynamicOwned(Box<DynamicConstraint>),
2297}
2298
2299impl CompiledChild<'_> {
2300    fn into_constraints(self) -> Vec<RuntimeConstraint> {
2301        match self {
2302            Self::StaticBorrowed(constraint) => vec![constraint.clone()],
2303            Self::StaticOwned(constraint) => vec![*constraint],
2304            Self::DynamicBorrowed(constraint) => constraint.clone_constraints(),
2305            Self::DynamicOwned(constraint) => constraint.clone_constraints(),
2306        }
2307    }
2308}
2309
2310fn static_constraint_targets(constraint: &RuntimeConstraint, vocab: &Vocab) -> bool {
2311    constraint
2312        .late_bind_vocab
2313        .get()
2314        .map_or_else(
2315            || constraint.token_bytes_match_vocab(vocab),
2316            |compiled_vocab| compiled_vocab.same_model_vocab(vocab),
2317        )
2318}
2319
2320impl SpecGrammarBinding<'_> {
2321    fn bind_target(&mut self, vocab: &Vocab, name: &str) -> Result<()> {
2322        let compatible = match self {
2323            Self::Source(_) => return Ok(()),
2324            Self::Spec(spec) => spec.targets(vocab),
2325            Self::StaticBorrowed(constraint) => static_constraint_targets(constraint, vocab),
2326            Self::StaticOwned(constraint) => static_constraint_targets(constraint, vocab),
2327            Self::DynamicBorrowed(constraint) => constraint.targets_vocab(vocab),
2328            Self::DynamicOwned(constraint) => constraint.targets_vocab(vocab),
2329        };
2330        if compatible {
2331            Ok(())
2332        } else {
2333            Err(Error::VocabMismatch(format!(
2334                "the module bound to extern {name:?} was precompiled for a different vocabulary",
2335            )))
2336        }
2337    }
2338
2339    fn compile<'a>(
2340        &'a self,
2341        vocab: &Vocab,
2342        mode: ChildCompileMode,
2343        allow_open_source_tokens: bool,
2344    ) -> Result<CompiledChild<'a>> {
2345        match self {
2346            Self::Source(grammar) => match mode {
2347                ChildCompileMode::Static => {
2348                    if !allow_open_source_tokens
2349                        && let Some(name) = grammar.unresolved_external_names()?.first() {
2350                            return Err(Error::InvalidInput(format!(
2351                                "extern {name:?} is unbound; bind it before compiling, or precompile to leave it open",
2352                            )));
2353                        }
2354                    let module = grammar.prepare_unlinked(vocab, BuildOptions::default())?;
2355                    Ok(CompiledChild::StaticOwned(Box::new(module.materialize_template_components(Engine::Auto)?)))
2356                }
2357                ChildCompileMode::Dynamic => {
2358                    let spec = ConstraintSpec::builder(grammar.clone(), vocab)?.build()?;
2359                    Ok(CompiledChild::DynamicOwned(spec.compile_dynamic_boxed()?))
2360                }
2361            },
2362            Self::Spec(spec) => match mode {
2363                ChildCompileMode::Static => {
2364                    Ok(CompiledChild::StaticOwned(spec.compile_static_with_trigger_boxed()?))
2365                }
2366                ChildCompileMode::Dynamic => {
2367                    Ok(CompiledChild::DynamicOwned(spec.compile_dynamic_boxed()?))
2368                }
2369            },
2370            Self::StaticBorrowed(constraint) => Ok(CompiledChild::StaticBorrowed(constraint)),
2371            Self::StaticOwned(constraint) => Ok(CompiledChild::StaticBorrowed(constraint)),
2372            Self::DynamicBorrowed(constraint) => Ok(CompiledChild::DynamicBorrowed(constraint)),
2373            Self::DynamicOwned(constraint) => Ok(CompiledChild::DynamicBorrowed(constraint)),
2374        }
2375    }
2376
2377    /// One-shot late binding can consume the user's binding. Preserve that
2378    /// ownership instead of immediately downgrading an owned/Arc constraint to
2379    /// a borrowed child and deep-cloning it again during preparation.
2380    fn into_compiled<'a>(
2381        self,
2382        vocab: &Vocab,
2383        mode: ChildCompileMode,
2384    ) -> Result<CompiledChild<'a>>
2385    where
2386        Self: 'a,
2387    {
2388        match self {
2389            Self::Source(grammar) => match mode {
2390                ChildCompileMode::Static => {
2391                    if let Some(name) = grammar.unresolved_external_names()?.first() {
2392                        return Err(Error::InvalidInput(format!(
2393                            "extern {name:?} is unbound; bind it before compiling, or precompile to leave it open",
2394                        )));
2395                    }
2396                    let module = grammar.prepare_unlinked(vocab, BuildOptions::default())?;
2397                    Ok(CompiledChild::StaticOwned(Box::new(module.materialize_template_components(Engine::Auto)?)))
2398                }
2399                ChildCompileMode::Dynamic => {
2400                    let spec = ConstraintSpec::builder(grammar, vocab)?.build()?;
2401                    Ok(CompiledChild::DynamicOwned(spec.compile_dynamic_boxed()?))
2402                }
2403            },
2404            Self::Spec(spec) => match mode {
2405                ChildCompileMode::Static => {
2406                    Ok(CompiledChild::StaticOwned(spec.compile_static_with_trigger_boxed()?))
2407                }
2408                ChildCompileMode::Dynamic => {
2409                    Ok(CompiledChild::DynamicOwned(spec.compile_dynamic_boxed()?))
2410                }
2411            },
2412            Self::StaticBorrowed(constraint) => Ok(CompiledChild::StaticBorrowed(constraint)),
2413            Self::StaticOwned(constraint) => Ok(CompiledChild::StaticOwned(Box::new(
2414                Arc::try_unwrap(constraint).unwrap_or_else(|shared| (*shared).clone()),
2415            ))),
2416            Self::DynamicBorrowed(constraint) => Ok(CompiledChild::DynamicBorrowed(constraint)),
2417            Self::DynamicOwned(constraint) => Ok(CompiledChild::DynamicOwned(Box::new(
2418                Arc::try_unwrap(constraint).unwrap_or_else(|shared| (*shared).clone()),
2419            ))),
2420        }
2421    }
2422}
2423
2424/// Every compiled component must already own its native parser; linking
2425/// cannot materialize an LR-backed Constraint as an intermediate.
2426fn require_composable_parser(constraint: &RuntimeConstraint) -> Result<()> {
2427    if !constraint.has_template_parser() || constraint.table.is_present() {
2428        return Err(Error::Compilation(
2429            "a composition can't mix parts precompiled with the LrTable and TemplateDfa parser backends".into(),
2430        ));
2431    }
2432    Ok(())
2433}
2434
2435fn prepare_compiled_children(
2436    children: Vec<(String, CompiledChild<'_>)>,
2437    vocab: &Vocab,
2438    boundary_backend: SegmentedBoundaryBackend,
2439) -> Result<Vec<(String, Arc<RuntimeConstraint>)>> {
2440    children
2441        .into_iter()
2442        .map(|(name, child)| {
2443            let alternatives = child.into_constraints();
2444            for alternative in &alternatives { require_composable_parser(alternative)?; }
2445            let mut constraint = collapse_dynamic_alternatives(
2446                alternatives, vocab, boundary_backend,
2447            )?;
2448            // Root termination is policy, not an embedded grammar terminal.
2449            // The native artifact cache already contains body-only bytes.
2450            constraint.end_tokens = Arc::from([]);
2451            // `compose_named_children` always uses the segmented linker. Decode
2452            // composition-only metadata on this first owned child copy so the
2453            // linker does not clone the whole compiled child a second time
2454            // merely to materialize the same cold metadata.
2455            match boundary_backend {
2456                SegmentedBoundaryBackend::StaticParserDwa => constraint
2457                    .materialize_composition_metadata_for_compilation()
2458                    .map_err(Error::Compilation)?,
2459                SegmentedBoundaryBackend::Dynamic => constraint
2460                    .materialize_composition_link_metadata_for_compilation()
2461                    .map_err(Error::Compilation)?,
2462            }
2463            Ok((name, Arc::new(constraint)))
2464        })
2465        .collect()
2466}
2467
2468fn collapse_dynamic_alternatives(
2469    mut alternatives: Vec<RuntimeConstraint>,
2470    vocab: &Vocab,
2471    boundary_backend: SegmentedBoundaryBackend,
2472) -> Result<RuntimeConstraint> {
2473    if alternatives.len() == 1 {
2474        return Ok(alternatives.pop().expect("length checked"));
2475    }
2476    if alternatives.is_empty() {
2477        return Err(Error::Compilation(
2478            "external grammar realization has no alternatives".to_owned(),
2479        ));
2480    }
2481
2482    let mut source = String::from("glrm 1;\nstart start;\n");
2483    for index in 0..alternatives.len() {
2484        source.push_str(&format!("extern alternative_{index};\n"));
2485    }
2486    source.push_str("nt start = ");
2487    for index in 0..alternatives.len() {
2488        if index != 0 {
2489            source.push_str(" | ");
2490        }
2491        source.push_str(&format!("alternative_{index}"));
2492    }
2493    source.push_str(";\n");
2494
2495    let names = (0..alternatives.len())
2496        .map(|index| format!("alternative_{index}"))
2497        .collect::<Vec<_>>();
2498    let children = names
2499        .iter()
2500        .cloned()
2501        .zip(alternatives.into_iter().map(Arc::new))
2502        .collect::<Vec<_>>();
2503    let parent = RuntimeConstraint::from_glrm_grammar_with_subgrammars(&source, &[], vocab)?;
2504    let mut union = compose_named_children(parent, &children, vocab, boundary_backend)?;
2505    for slot in &mut union.late_grammar_slots {
2506        if let Some((alternative, nested)) = slot.name.split_once('.')
2507            && alternative.starts_with("alternative_")
2508        {
2509            slot.name = nested.to_owned();
2510        }
2511    }
2512    Ok(union)
2513}
2514
2515#[inline(never)]
2516#[allow(clippy::boxed_local)] // Keep the large parent boxed until this separate frame.
2517fn compose_boxed_dynamic_parents(
2518    parents: Box<DynamicConstraint>,
2519    children: &[(String, Arc<RuntimeConstraint>)],
2520    vocab: &Vocab,
2521) -> Result<Box<DynamicConstraint>> {
2522    let alternatives = parents.clone_constraints().into_iter()
2523        .map(|parent| compose_named_children(
2524            parent, children, vocab, SegmentedBoundaryBackend::Dynamic,
2525        ))
2526        .collect::<Result<Vec<_>>>()?;
2527    Ok(Box::new(DynamicConstraint::from_constraints(alternatives)))
2528}
2529
2530// Unbox only after the independent compiler jobs have completed. Keeping this
2531// in a separate frame prevents the by-value linker slots from occupying every
2532// suspended source-compiler frame in unoptimized builds.
2533#[inline(never)]
2534#[allow(clippy::boxed_local)] // Keep the large parent boxed until this separate frame.
2535fn compose_boxed_parent(
2536    parent: Box<RuntimeConstraint>,
2537    children: &[(String, Arc<RuntimeConstraint>)],
2538    vocab: &Vocab,
2539    boundary_backend: SegmentedBoundaryBackend,
2540) -> Result<Box<RuntimeConstraint>> {
2541    compose_named_children(*parent, children, vocab, boundary_backend).map(Box::new)
2542}
2543
2544fn compose_named_children(
2545    parent: RuntimeConstraint,
2546    children: &[(String, Arc<RuntimeConstraint>)],
2547    vocab: &Vocab,
2548    boundary_backend: SegmentedBoundaryBackend,
2549) -> Result<RuntimeConstraint> {
2550    if parent.has_template_parser() {
2551        let mut linked = crate::runtime::parser_backend::link::compose(parent, children, vocab)?;
2552        if matches!(boundary_backend, SegmentedBoundaryBackend::StaticParserDwa) {
2553            match crate::compiler::template_boundary::install(&mut linked, vocab) {
2554                Ok(()) => {}
2555                // The backend was selected heuristically. When the exact static
2556                // constructor declines a shard for a resource budget, the
2557                // segmented dynamic boundary that `compose` already installed
2558                // is the exact fallback; it supports the same nested shape.
2559                Err(error) if crate::compiler::template_boundary::is_template_budget_decline(&error) => {
2560                    if crate::env::var_os("GLRMASK_PROFILE_COMPILE_SUMMARY").is_some() {
2561                        eprintln!("[glrmask/profile][static_template_boundary] fallback=dynamic reason=budget_decline");
2562                    }
2563                }
2564                Err(error) => return Err(error),
2565            }
2566        }
2567        return Ok(linked);
2568    }
2569    let bound_names = children
2570        .iter()
2571        .map(|(name, _)| name.as_str())
2572        .collect::<BTreeSet<_>>();
2573    let mut present = Vec::new();
2574    let mut matching_terminals = Vec::new();
2575    for (child_index, (name, _)) in children.iter().enumerate() {
2576        let terminals = parent
2577            .late_grammar_slots
2578            .iter()
2579            .filter(|slot| slot.name == *name)
2580            .map(|slot| slot.terminal_id)
2581            .collect::<Vec<_>>();
2582        if !terminals.is_empty() {
2583            present.push(child_index);
2584            matching_terminals.push(terminals);
2585        }
2586    }
2587    if present.is_empty() {
2588        return Ok(parent);
2589    }
2590    // This branch is only for ordinary retained-LR Dynamic components.
2591    // Native components were dispatched above and may never enter LR machinery.
2592    if !parent.table.is_present() || present.iter().any(|&i|
2593        children[i].1.has_template_parser() || !children[i].1.table.is_present()) {
2594        return Err(Error::Compilation("a composition can't mix parts precompiled with the LrTable and TemplateDfa parser backends".into()));
2595    }
2596
2597    let remaining_parent_slots = parent
2598        .late_grammar_slots
2599        .iter()
2600        .filter(|slot| !bound_names.contains(slot.name.as_str()))
2601        .cloned()
2602        .collect::<Vec<_>>();
2603    let inputs = present
2604        .iter()
2605        .zip(&matching_terminals)
2606        .map(|(&child_index, terminals)| CompiledSubgrammarInput {
2607            placeholder_terminal: terminals[0],
2608            additional_placeholder_terminals: &terminals[1..],
2609            constraint: children[child_index].1.as_ref(),
2610        })
2611        .collect::<Vec<_>>();
2612    let shared_children = present
2613        .iter()
2614        .map(|&child_index| Arc::clone(&children[child_index].1))
2615        .collect::<Vec<_>>();
2616    let mut composition = compose_constraints_owned_parent_segmented_shared(
2617        parent,
2618        &inputs,
2619        &shared_children,
2620        vocab,
2621        boundary_backend,
2622    )
2623    .map_err(Error::Compilation)?;
2624    composition.constraint.late_grammar_slots = remaining_parent_slots;
2625    for (component_index, &child_index) in present.iter().enumerate() {
2626        let terminal_offset = composition.terminal_offsets[component_index + 1];
2627        let (binding_name, child) = &children[child_index];
2628        composition.constraint.late_grammar_slots.extend(
2629            child.late_grammar_slots.iter().map(|slot| crate::runtime::LateGrammarSlot {
2630                name: format!("{binding_name}.{}", slot.name),
2631                terminal_id: terminal_offset + slot.terminal_id,
2632            }),
2633        );
2634    }
2635    if composition
2636        .constraint
2637        .sanitize_late_grammar_placeholder_token_domain()
2638    {
2639        composition.constraint.rebuild_runtime_caches();
2640    }
2641    Ok(composition.constraint)
2642}
2643
2644fn compile_static_source(
2645    grammar: &Grammar,
2646    vocab: &Vocab,
2647    token_bindings: &[(&str, &[(u32, u32)])],
2648) -> Result<RuntimeConstraint> {
2649    match &grammar.source {
2650        GrammarSource::Ebnf(source) => RuntimeConstraint::from_ebnf(source, vocab),
2651        GrammarSource::Lark(source) => RuntimeConstraint::from_lark(source, vocab),
2652        GrammarSource::JsonSchema(source) => RuntimeConstraint::from_json_schema(source, vocab),
2653        GrammarSource::Glrm(_) | GrammarSource::Constructed => {
2654            grammar.validate_exact_target(vocab)?;
2655            crate::import::compile_component_shell(grammar.component()?,vocab,token_bindings,false)
2656        },
2657    }
2658}
2659
2660fn compile_dynamic_source(
2661    grammar: &Grammar,
2662    vocab: &Vocab,
2663    token_bindings: &[(&str, &[(u32, u32)])],
2664) -> Result<DynamicConstraint> {
2665    match &grammar.source {
2666        GrammarSource::Ebnf(source) => DynamicConstraint::from_ebnf(source, vocab),
2667        GrammarSource::Lark(source) => DynamicConstraint::from_lark(source, vocab),
2668        GrammarSource::JsonSchema(source) => DynamicConstraint::from_json_schema(source, vocab),
2669        GrammarSource::Glrm(_) | GrammarSource::Constructed => {
2670            grammar.validate_exact_target(vocab)?;
2671            Ok(DynamicConstraint::from_constraints(vec![crate::import::compile_component_shell(grammar.component()?,vocab,token_bindings,true)?]))
2672        },
2673    }
2674}
2675
2676#[cfg(any(test, feature = "internal-api"))]
2677impl RuntimeConstraint {
2678    /// Compile `grammar` into a [`Constraint`](crate::Constraint) for `vocab`.
2679    pub fn compile(grammar: Grammar, vocab: &Vocab) -> Result<Self> {
2680        ConstraintSpec::builder(grammar, vocab)?.build()?.compile()
2681    }
2682
2683    /// Bind one retained `extern NAME;` declaration using a fully compiled boundary.
2684    ///
2685    /// Other named externs remain unresolved and may be bound by later calls.
2686    /// The compiled parent and the supplied child's masking backends are reused;
2687    /// only their cross-boundary behavior is compiled here.
2688    #[allow(private_bounds)]
2689    pub fn bind_grammar<'a, T>(&self, name: impl AsRef<str>, child: T) -> Result<Self>
2690    where
2691        T: IntoSpecGrammarBinding<'a>,
2692    {
2693        bind_static_parent_grammar(
2694            self,
2695            name.as_ref(),
2696            child,
2697            SegmentedBoundaryBackend::StaticParserDwa,
2698        )
2699    }
2700
2701    /// Bind one retained `extern NAME;` declaration using the dynamic boundary walker.
2702    ///
2703    /// Component-local masking remains independently static or dynamic according
2704    /// to the backend with which each component was supplied.
2705    #[allow(private_bounds)]
2706    pub fn bind_grammar_dynamic_boundary<'a, T>(
2707        &self,
2708        name: impl AsRef<str>,
2709        child: T,
2710    ) -> Result<Self>
2711    where
2712        T: IntoSpecGrammarBinding<'a>,
2713    {
2714        bind_static_parent_grammar(
2715            self,
2716            name.as_ref(),
2717            child,
2718            SegmentedBoundaryBackend::Dynamic,
2719        )
2720    }
2721
2722    /// Private compatibility hook for internal benchmark/composition callers.
2723    /// Public late binding no longer requires the caller to resupply `Vocab`,
2724    /// but old internal cached-parent probes still use this to eagerly prepare
2725    /// only the small compiler-facing composition metadata while leaving the
2726    /// packed runtime automata untouched.
2727    pub(crate) fn prepare_for_composition_internal(&mut self, vocab: &Vocab) -> Result<()> {
2728        self.bind_vocab_exact(vocab).map_err(Error::Compilation)?;
2729        self.materialize_composition_metadata_for_compilation()
2730            .map_err(Error::Compilation)?;
2731        crate::compiler::boundary_candidates::persist_boundary_candidate_summary(self, vocab);
2732        if crate::env::var_os("GLRMASK_PREPARE_BOUNDARY_COMPLETION").is_some() {
2733            crate::compiler::boundary_precomputed_completion::prepare_component(self, vocab)
2734                .map_err(crate::Error::Compilation)?;
2735        }
2736        Ok(())
2737    }
2738}
2739
2740#[cfg(any(test, feature = "internal-api"))]
2741impl DynamicConstraint {
2742    /// Compile `grammar` into a [`DynamicConstraint`] for `vocab`.
2743    pub fn compile(grammar: Grammar, vocab: &Vocab) -> Result<Self> {
2744        ConstraintSpec::builder(grammar, vocab)?.build()?.compile_dynamic()
2745    }
2746
2747
2748    /// Compile `grammar` into a dynamic constraint whose local mask walk uses
2749    /// one representative per proven vocabulary-equivalence class.
2750    ///
2751    /// The complete original vocabulary is still retained for commits,
2752    /// composition compatibility, and boundary triggers. Consequently a
2753    /// partition-optimized constraint can be composed with ordinary static or
2754    /// dynamic constraints without changing the public token coordinate.
2755    pub fn compile_with_vocab_partition(grammar: Grammar, vocab: &Vocab) -> Result<Self> {
2756        if !grammar.bindings.is_empty() {
2757            return Err(Error::Compilation(
2758                "compile_with_vocab_partition does not yet compile source-level bound subgrammars; compile the components first and bind the compiled constraints"
2759                    .to_owned(),
2760            ));
2761        }
2762        match &grammar.source {
2763            GrammarSource::Ebnf(source) => Self::from_ebnf_with_vocab_partition(source, vocab),
2764            GrammarSource::Lark(source) => Self::from_lark_with_vocab_partition(source, vocab),
2765            GrammarSource::JsonSchema(source) => {
2766                Self::from_json_schema_with_vocab_partition(source, vocab)
2767            }
2768            GrammarSource::Glrm(source) => {
2769                Self::from_glrm_grammar_with_vocab_partition(source, vocab)
2770            }
2771            GrammarSource::Constructed=>crate::import::compile_bounded_template_from_named(grammar.component()?.lower_closed().map_err(crate::error::from_grammar)?,vocab,crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,None),
2772        }
2773    }
2774
2775    /// Bind one retained `extern NAME;` declaration using a fully compiled boundary.
2776    ///
2777    /// Dynamic parent alternatives and dynamic component-local masking remain
2778    /// dynamic; the boundary choice is independent of component backends.
2779    #[allow(private_bounds)]
2780    pub fn bind_grammar<'a, T>(&self, name: impl AsRef<str>, child: T) -> Result<Self>
2781    where
2782        T: IntoSpecGrammarBinding<'a>,
2783    {
2784        bind_dynamic_parent_grammar(
2785            self,
2786            name.as_ref(),
2787            child,
2788            SegmentedBoundaryBackend::StaticParserDwa,
2789        )
2790    }
2791
2792    /// Bind one retained `extern NAME;` declaration using the dynamic boundary walker.
2793    #[allow(private_bounds)]
2794    pub fn bind_grammar_dynamic_boundary<'a, T>(
2795        &self,
2796        name: impl AsRef<str>,
2797        child: T,
2798    ) -> Result<Self>
2799    where
2800        T: IntoSpecGrammarBinding<'a>,
2801    {
2802        bind_dynamic_parent_grammar(
2803            self,
2804            name.as_ref(),
2805            child,
2806            SegmentedBoundaryBackend::Dynamic,
2807        )
2808    }
2809}
2810
2811pub(crate) fn constraint_vocab(constraint: &RuntimeConstraint) -> Vocab {
2812    constraint
2813        .late_bind_vocab
2814        .get_or_init(|| {
2815            Vocab::from_entries_unchecked(
2816                constraint
2817                    .token_bytes_iter()
2818                    .map(|(token_id, bytes)| (token_id, bytes.to_vec()))
2819                    .collect(),
2820            )
2821        })
2822        .clone()
2823}
2824
2825// Native precompiled components are immutable across this materialization.
2826// Revalidate the persisted certificate in the same coordinate as the linker;
2827// recompute unavailable/stale certificates before installing any parser view.
2828fn prepare_immutable_template_component_boundary_summary(
2829    constraint: &mut RuntimeConstraint,
2830    vocab: &Vocab,
2831) {
2832    if matches!(
2833        crate::compiler::boundary_candidates::persisted_boundary_candidate_ids(constraint, vocab),
2834        Ok(Some(_)),
2835    ) {
2836        constraint.serialized_artifact_cache = None;
2837        return;
2838    }
2839    crate::compiler::boundary_candidates::persist_boundary_candidate_summary(constraint, vocab);
2840}
2841
2842fn apply_final_boundary_trigger(constraint: &mut RuntimeConstraint, detail: BoundaryTriggerDetail) -> Result<()> {
2843    if detail == BoundaryTriggerDetail::None {
2844        constraint.boundary_trigger = crate::runtime::BoundaryTrigger::None;
2845        constraint.serialized_artifact_cache = None;
2846        return Ok(());
2847    }
2848    if detail == BoundaryTriggerDetail::Exact && !constraint.has_template_parser() {
2849        return Err(Error::Compilation("Exact boundary triggers require native template components; retained-LR Dynamic is unsupported".into()));
2850    }
2851    constraint.build_boundary_trigger(detail).map_err(Error::Compilation)
2852}
2853
2854fn ensure_runnable_constraint(constraint: &RuntimeConstraint) -> Result<()> {
2855    if let Some(slot) = constraint.late_grammar_slots.first() {
2856        return Err(Error::InvalidInput(format!(
2857            "extern {:?} is unbound; bind it before compiling, or precompile to leave it open",
2858            slot.name,
2859        )));
2860    }
2861    Ok(())
2862}
2863
2864/// The current bounded static linker requires nonnullable child links. Decide
2865/// from retained semantic metadata before construction, never by catching a
2866/// compiler error or silently falling back during mask generation.
2867fn select_supported_boundary(
2868    parent: &RuntimeConstraint,
2869    children: &[(String, Arc<RuntimeConstraint>)],
2870) -> Result<SegmentedBoundaryBackend> {
2871    fn requires_dynamic_boundary(constraint: &RuntimeConstraint) -> bool {
2872        // A FastBuild child can carry exact virtual lexer residuals. Static
2873        // boundary shards cannot execute those coordinates, even when the
2874        // child is non-nullable. Select the supported backend from metadata
2875        // before linking rather than asking callers to know internal engines.
2876        constraint.tokenizer.has_virtual_residual_runtime()
2877            || constraint.static_dynamic_overlay.as_ref().is_some_and(|overlay| {
2878                overlay.segmented_parser_links.iter().any(|link| link.child_start_nullable)
2879                    || overlay.segmented_parser_components.iter()
2880                        .any(|component| requires_dynamic_boundary(&component.constraint))
2881            })
2882    }
2883    require_composable_parser(parent)?;
2884    for (_, child) in children { require_composable_parser(child)?; }
2885    if requires_dynamic_boundary(parent) {
2886        return Ok(SegmentedBoundaryBackend::Dynamic);
2887    }
2888    for (_, child) in children {
2889        if child.composition_start_nullable().map_err(Error::Compilation)?
2890            || requires_dynamic_boundary(child)
2891        {
2892            return Ok(SegmentedBoundaryBackend::Dynamic);
2893        }
2894    }
2895    Ok(SegmentedBoundaryBackend::StaticParserDwa)
2896}
2897
2898fn compile_exact_token_adapter(vocab: &Vocab, token_ids: &[(u32, u32)]) -> Result<RuntimeConstraint> {
2899    use crate::grammar::ast::{GrammarExpr, NamedGrammar, NamedRule};
2900    let named = NamedGrammar {
2901        start: "__exact_tokens".to_owned(),
2902        rules: vec![NamedRule {
2903            name: "__exact_tokens".to_owned(),
2904            expr: crate::import::choice_or_single(
2905                token_ids.iter().map(|&(start, end)| {
2906                    if start == end { GrammarExpr::SpecialToken(start) }
2907                    else { GrammarExpr::SpecialTokenRange(start, end) }
2908                }).collect(),
2909            ),
2910            is_terminal: false,
2911            is_internal: false,
2912        }],
2913        ignore: None,
2914        lexer_partitions: BTreeMap::new(),
2915        lexer_literal_partitions: BTreeMap::new(),
2916        default_lexer_partition: None,
2917    };
2918    crate::import::compile_from_named_grammar(
2919        named,
2920        vocab,
2921        "exact_token_binding",
2922        crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,
2923        &[],
2924    )
2925}
2926
2927fn boundary_for_optimization(
2928    parent: &RuntimeConstraint,
2929    children: &[(String, Arc<RuntimeConstraint>)],
2930    optimization: Engine,
2931) -> Result<SegmentedBoundaryBackend> {
2932    match optimization {
2933        Engine::TokenTrie | Engine::MergedTokenTrie => Ok(SegmentedBoundaryBackend::Dynamic),
2934        Engine::Auto | Engine::ParserDwa => {
2935            select_supported_boundary(parent, children)
2936        }
2937    }
2938}
2939
2940impl PreparedGrammar {
2941    #[cfg(test)]
2942    pub(crate) fn boundary_test_inner(&self) -> &RuntimeConstraint {
2943        &self.inner
2944    }
2945
2946    fn direct_slot_names(&self) -> BTreeSet<&str> {
2947        self.inner
2948            .late_grammar_slots
2949            .iter()
2950            .map(|slot| slot.name.as_str())
2951            .collect()
2952    }
2953
2954    fn first_open_slot(&self) -> Result<Option<String>> {
2955        Ok(graph::prepared_first(self)?.map(|r|r.name()))
2956    }
2957
2958    fn targets_vocab(&self, vocab: &Vocab) -> bool {
2959        graph::prepared_targets(self,vocab)
2960    }
2961
2962    fn validate_slot_manifest(&self) -> Result<()> {
2963        graph::prepared_summary(self).map(|_|())
2964    }
2965
2966    fn validate_local_slot_manifest(&self, vocab: &Vocab) -> Result<()> {
2967        if self.slot_spans.iter().any(|(name,span)|!self.slot_kinds.contains_key(name)
2968            || span.start()>span.end() || { let (line, column) = glrmask_vocab::__private::source_span_line_column(span); line==0 || column==0 }) {
2969            return Err(Error::Serialization("invalid prepared requirement source coordinates".into()));
2970        }
2971        if !self.inner.end_tokens.is_empty() {
2972            return Err(Error::Serialization(
2973                "unlinked-constraint artifact contains final-root policy".to_owned(),
2974            ));
2975        }
2976        let direct_slots = self.direct_slot_names();
2977        if direct_slots.iter().any(|name|!self.slot_kinds.contains_key(*name)) {
2978            return Err(Error::Serialization("compiled extern missing from authored interface".into()));
2979        }
2980        if !static_constraint_targets(self.inner.as_ref(),vocab) {
2981            return Err(Error::Serialization("prepared component targets an incompatible vocabulary".into()));
2982        }
2983        for (name, binding) in &self.bindings {
2984            if name.is_empty() || !self.slot_kinds.contains_key(name) {
2985                return Err(Error::Serialization(format!(
2986                    "unlinked-constraint binding {name:?} has no compiled linker extern",
2987                )));
2988            }
2989            check_binding_kind(name,self.slot_kinds[name],!matches!(binding,ModuleBinding::TokenSet(_)))?;
2990            match binding {
2991                ModuleBinding::TokenSet(ids) => {
2992                    let mut previous = None;
2993                    for &(start, end) in ids.iter() {
2994                        if previous.is_some_and(|value| u64::from(value) + 1 >= u64::from(start)) {
2995                            return Err(Error::Serialization(format!(
2996                                "unlinked-constraint token-set binding {name:?} is invalid for its vocabulary",
2997                            )));
2998                        }
2999                        previous = Some(end);
3000                    }
3001                }
3002                ModuleBinding::Module(_) => {} // Validated once by the graph traversal.
3003                ModuleBinding::Constraint(child) => {
3004                    if !static_constraint_targets(child.as_ref(), vocab) {
3005                        return Err(Error::Serialization(format!(
3006                            "unlinked-constraint grammar binding {name:?} has incompatible vocabulary",
3007                        )));
3008                    }
3009                }
3010            }
3011        }
3012        Ok(())
3013    }
3014
3015    fn require_direct_slot(&self,name:&str)->Result<()> {
3016        if !self.slot_kinds.contains_key(name){return Err(Error::InvalidInput(format!("there is no unbound extern named {name:?}")));}
3017        if self.bindings.contains_key(name){return Err(Error::InvalidInput(format!("extern {name:?} is already bound")));}
3018        Ok(())
3019    }
3020
3021    /// Unresolved paths, including externs inside attached children. Diagnostic expansion is bounded.
3022    #[cfg(any(test,feature="internal-api"))]
3023    #[doc(hidden)]
3024    pub fn requirements(&self)->Result<Vec<Requirement>> {
3025        graph::prepared_requirements(self)
3026    }
3027
3028    pub fn unbound(&self)->Result<Vec<Requirement>> {graph::prepared_requirements(self)}
3029
3030    /// Authored externs, including bound externs and distinct attached occurrences.
3031    pub fn externs(&self)->Result<Vec<Requirement>> {
3032        self.validate_slot_manifest()?;
3033        let mut pending=vec![(self,Vec::<String>::new())];let mut out=Vec::new();let mut visits=0;
3034        while let Some((module,prefix))=pending.pop() {
3035            visits+=1;if visits>131_072 {return Err(Error::ResourceLimit("the composition expands to too many parts".into()));}
3036            for (name,&kind) in module.slot_kinds.iter() {
3037                let mut path=prefix.clone();path.extend(name.split("::").map(str::to_owned));
3038                out.push(Requirement {path,kind,source_span:module.slot_spans.get(name).copied()});
3039                if out.len()>65_536 {return Err(Error::ResourceLimit("the composition expands to too many parts".into()));}
3040            }
3041            for (name,binding) in &module.bindings {if let ModuleBinding::Module(child)=binding {
3042                let mut path=prefix.clone();path.extend(name.split("::").map(str::to_owned));pending.push((child,path));
3043            }}
3044        }
3045        out.sort_by(|a,b|a.path.cmp(&b.path));Ok(out)
3046    }
3047
3048
3049    fn bind_value(&self, name: &str, value: UnlinkedValue<'_>) -> Result<Self> {
3050        let previous=graph::prepared_summary(self)?;
3051        if !self.slot_kinds.contains_key(name)
3052            && let Some((head,tail))=attached_path(name,&self.bindings) {
3053                let Some(ModuleBinding::Module(child))=self.bindings.get(head) else {
3054                    return Err(Error::Compilation(format!("external grammar {head:?} is not a prepared component")));
3055                };
3056                let child=child.bind_value(tail,value)?;
3057                let summary=graph::prepared_summary(&child)?;
3058                let mut next=self.clone();next.bindings.insert(head.to_owned(),ModuleBinding::Module(Arc::new(child)));
3059                next.analysis=graph::filled_cache(previous.changed(head,Some(summary)));
3060                graph::check_prepared_limits(&next)?;return Ok(next);
3061            }
3062        self.require_direct_slot(name)?;
3063        check_binding_kind(name,self.slot_kinds[name],matches!(value,UnlinkedValue::Prepared(_)|UnlinkedValue::StaticBorrowed(_)|UnlinkedValue::StaticOwned(_)))
3064            .map_err(|e|e.with_source_span(self.slot_spans.get(name).copied()))?;
3065        let vocab = constraint_vocab(self.inner.as_ref());
3066        let binding = match value {
3067            UnlinkedValue::Prepared(child) => {
3068                if !child.targets_vocab(&vocab){return Err(Error::VocabMismatch("the bound modules were precompiled for different vocabularies".into()));}
3069                let _=graph::prepared_first(&child)?;
3070                ModuleBinding::Module(child)
3071            }
3072            UnlinkedValue::TokenSet(tokens) => {
3073                self.require_direct_slot(name)?;
3074                ModuleBinding::TokenSet(self.event_adapters.leaf(tokens.range_pairs())?)
3075            }
3076            UnlinkedValue::StaticBorrowed(child) => {
3077                self.require_direct_slot(name)?;
3078                if !static_constraint_targets(child, &vocab) {
3079                    return Err(Error::VocabMismatch(format!(
3080                        "the module bound to extern {name:?} was precompiled for a different vocabulary",
3081                    )));
3082                }
3083                ModuleBinding::Constraint(Arc::new(child.clone()))
3084            }
3085            UnlinkedValue::StaticOwned(child) => {
3086                self.require_direct_slot(name)?;
3087                if !static_constraint_targets(child.as_ref(), &vocab) {
3088                    return Err(Error::VocabMismatch(format!(
3089                        "the module bound to extern {name:?} was precompiled for a different vocabulary",
3090                    )));
3091                }
3092                ModuleBinding::Constraint(child)
3093            }
3094        };
3095        let child_summary=match &binding { ModuleBinding::Module(child)=>Some(graph::prepared_summary(child)?),_=>None };
3096        let mut next = self.clone();
3097        next.bindings.insert(name.to_owned(), binding);
3098        next.analysis=graph::filled_cache(previous.changed(name,child_summary));
3099        graph::check_prepared_limits(&next)?;
3100        Ok(next)
3101    }
3102
3103    /// Fill a declared extern once with `PreparedGrammar` or `TokenSet`. Attach a parent before binding descendants. Prepared children must use the same byte mapping and special-token IDs. Attached children are snapshots; failed binds leave this handle unchanged.
3104    #[allow(private_bounds)]
3105    pub fn bind<'a, T>(&mut self, name: impl AsRef<str>, value: T) -> Result<()>
3106    where T: IntoUnlinkedValue<'a> {
3107        let next=self.bind_value(name.as_ref(),value.into_unlinked_value())?;
3108        *self=next;
3109        Ok(())
3110    }
3111
3112    #[cfg(any(test, feature = "internal-api"))]
3113    #[doc(hidden)]
3114    #[allow(private_bounds)]
3115    pub fn bind_snapshot<'a, T>(&self,name:impl AsRef<str>,value:T)->Result<Self>
3116    where T:IntoUnlinkedValue<'a> {
3117        let mut next=self.clone();next.bind(name,value)?;Ok(next)
3118    }
3119
3120    fn materialize(&self, optimization: Engine) -> Result<RuntimeConstraint> {
3121        self.validate_slot_manifest()?;
3122        if self.bindings.is_empty() {
3123            return Ok(self.inner.as_ref().clone());
3124        }
3125        let vocab = constraint_vocab(self.inner.as_ref());
3126        let active=self.direct_slot_names();
3127        let binding_entries = self.bindings.iter().filter(|(name,_)|active.contains(name.as_str())).collect::<Vec<_>>();
3128        if binding_entries.is_empty(){return Ok(self.inner.as_ref().clone());}
3129        let raw_children = binding_entries
3130            .par_iter()
3131            .map(|(name, binding)| {
3132                let mut child = match binding {
3133                    ModuleBinding::Module(module) => {
3134                        let mut child = module.materialize(optimization)?;
3135                        child.build_boundary_trigger(module.boundary_trigger).map_err(Error::Compilation)?;
3136                        child
3137                    },
3138                    ModuleBinding::Constraint(constraint) => constraint.as_ref().clone(),
3139                    ModuleBinding::TokenSet(ids) => {
3140                        ids.compiled(&vocab)?.as_ref().clone()
3141                    }
3142                };
3143                // Standalone termination is root policy, never an embedded body.
3144                child.end_tokens = Arc::from([]);
3145                Ok(((*name).clone(), child))
3146            })
3147            .collect::<Result<Vec<_>>>()?;
3148        let probe_children = raw_children
3149            .iter()
3150            .map(|(name, child)| (name.clone(), Arc::new(child.clone())))
3151            .collect::<Vec<_>>();
3152        let backend = boundary_for_optimization(
3153            self.inner.as_ref(),
3154            &probe_children,
3155            optimization,
3156        )?;
3157        let prepared = prepare_compiled_children(
3158            raw_children
3159                .into_iter()
3160                .map(|(name, child)| (name, CompiledChild::StaticOwned(Box::new(child))))
3161                .collect(),
3162            &vocab,
3163            backend,
3164        )?;
3165        compose_named_children(
3166            self.inner.as_ref().clone(),
3167            &prepared,
3168            &vocab,
3169            backend,
3170        )
3171    }
3172
3173    /// Requires every extern to be bound. Uses default build options and inherits the prepared boundary request.
3174    pub fn link(&self) -> Result<RuntimeConstraint> {
3175        self.link_with(BuildOptions::default())
3176    }
3177
3178    fn requires_template_linker(&self) -> bool {
3179        // Sparse regular frontends also have no LR action/rule inventory.
3180        // An explicit template request converts their finite depth-one
3181        // programs directly instead of sending them through the LR splicer.
3182        let needs_native = |constraint: &RuntimeConstraint| {
3183            constraint.has_template_parser() || constraint.uses_sparse_direct_regular_runtime()
3184        };
3185        needs_native(self.inner.as_ref()) || self.bindings.values().any(|binding| match binding {
3186            ModuleBinding::Module(module) => module.requires_template_linker(),
3187            ModuleBinding::Constraint(constraint) => needs_native(constraint.as_ref()),
3188            ModuleBinding::TokenSet(_) => false,
3189        })
3190    }
3191
3192    fn materialize_template_components(&self, optimization: Engine) -> Result<RuntimeConstraint> {
3193        self.validate_slot_manifest()?;
3194        let vocab = constraint_vocab(self.inner.as_ref());
3195        let mut parent = self.inner.as_ref().clone();
3196        if parent.has_template_parser() {
3197            prepare_immutable_template_component_boundary_summary(
3198                &mut parent,
3199                &vocab,
3200            );
3201        }
3202        parent.install_template_parser()?;
3203        if self.bindings.is_empty() { return Ok(parent); }
3204        let active=self.direct_slot_names();
3205        let children = self.bindings.iter().filter(|(name,_)|active.contains(name.as_str())).map(|(name, binding)| {
3206            let mut child = match binding {
3207                ModuleBinding::Module(module) => module.materialize_template_components(optimization)?,
3208                ModuleBinding::Constraint(constraint) => constraint.as_ref().clone(),
3209                ModuleBinding::TokenSet(ids) => ids.compiled(&vocab)?.as_ref().clone(),
3210            };
3211            child.end_tokens = Arc::from([]);
3212            if child.has_template_parser() {
3213                prepare_immutable_template_component_boundary_summary(
3214                    &mut child,
3215                    &vocab,
3216                );
3217            }
3218            child.install_template_parser()?;
3219            if let ModuleBinding::Module(module) = binding {
3220                child.build_boundary_trigger(module.boundary_trigger).map_err(Error::Compilation)?;
3221            }
3222            Ok((name.clone(), Arc::new(child)))
3223        }).collect::<Result<Vec<_>>>()?;
3224        if children.is_empty(){return Ok(parent);}
3225        crate::error::catch_internal_invariant(|| {
3226            let mut linked = crate::runtime::parser_backend::link::compose_owned(parent, children, &vocab)?;
3227            if optimization == Engine::ParserDwa {
3228                crate::compiler::template_boundary::install(&mut linked, &vocab)?;
3229            }
3230            Ok(linked)
3231        })?
3232    }
3233
3234    /// Requires all externs to be bound. Selects final optimization and root end tokens; an explicit boundary request overrides the prepared request. End tokens become allowed only at acceptance and must be committed before stopping.
3235    pub fn link_with(&self, options: BuildOptions) -> Result<RuntimeConstraint> {
3236        graph::prepared_preflight(self)?;
3237        if let Some(name) = self.first_open_slot()? {
3238            return Err(Error::InvalidInput(format!(
3239                "extern {name:?} is unbound; bind it before compiling, or precompile to leave it open",
3240            )));
3241        }
3242        let engine = options.engine()?;
3243        let mut constraint = if options.parser_backend == ParserBackend::TemplateDfa && self.requires_template_linker() {
3244            self.materialize_template_components(engine)?
3245        } else { self.materialize(engine)? };
3246        ensure_runnable_constraint(&constraint)?;
3247        if options.parser_backend == ParserBackend::TemplateDfa {
3248            constraint.install_template_parser()?;
3249        }
3250        apply_final_boundary_trigger(&mut constraint, options.boundary_trigger.unwrap_or(self.boundary_trigger))?;
3251        constraint.with_end_tokens(options.end_token_ids())
3252    }
3253
3254    /// Preserves compiled machinery, vocabulary and unresolved externs. Shared definitions are serialized once. Artifact compatibility across GLRMask releases is not guaranteed.
3255    pub fn save(&self) -> Vec<u8> {
3256        with_deep_stack(|| prepared_artifact::save(self))
3257    }
3258
3259    /// Rejects malformed or incompatible prepared artifacts. The supplied
3260    /// vocabulary must match the saved token-ID/byte fingerprint; loaded
3261    /// definitions share its caches. Open externs and shared definitions are
3262    /// preserved.
3263    pub fn load<'b>(bytes: impl Into<std::borrow::Cow<'b, [u8]>>, vocab: &Vocab) -> Result<Self> {
3264        with_deep_stack(|| prepared_artifact::load(bytes.into().as_ref(), Some(vocab)))
3265    }
3266
3267}
3268
3269const FIRST_SAVE_TEMPLATE_STATE_PRIME_THRESHOLD: usize = 100_000;
3270
3271fn should_prime_first_save_artifact(constraint: &RuntimeConstraint) -> bool {
3272    if retains_dynamic_component(constraint) {
3273        return false;
3274    }
3275    if constraint.tokenizer.has_virtual_residual_runtime() {
3276        return true;
3277    }
3278    let mut template_states = 0usize;
3279    for template in constraint
3280        .composition_parser_templates_by_terminal
3281        .iter()
3282        .flatten()
3283    {
3284        template_states = template_states.saturating_add(template.states.len());
3285        if template_states >= FIRST_SAVE_TEMPLATE_STATE_PRIME_THRESHOLD {
3286            return true;
3287        }
3288    }
3289    false
3290}
3291
3292fn retains_dynamic_component(constraint: &RuntimeConstraint) -> bool {
3293    if constraint.uses_dynamic_runtime() {
3294        return true;
3295    }
3296    constraint
3297        .static_dynamic_overlay
3298        .as_ref()
3299        .is_some_and(|overlay| {
3300            overlay
3301                .segmented_parser_components
3302                .iter()
3303                .any(|component| retains_dynamic_component(component.constraint.as_ref()))
3304        })
3305}
3306
3307fn require_late_grammar_slot(
3308    parents: &[RuntimeConstraint],
3309    name: &str,
3310) -> Result<()> {
3311    if parents.iter().any(|parent| {
3312        parent
3313            .late_grammar_slots
3314            .iter()
3315            .any(|slot| slot.name == name)
3316    }) {
3317        return Ok(());
3318    }
3319    Err(Error::Compilation(format!(
3320        "there is no unbound grammar extern named {name:?}",
3321    )))
3322}
3323
3324fn prepare_late_child<'a, T>(
3325    name: &str,
3326    child: T,
3327    vocab: &Vocab,
3328    boundary_backend: SegmentedBoundaryBackend,
3329) -> Result<Vec<(String, Arc<RuntimeConstraint>)>>
3330where
3331    T: IntoSpecGrammarBinding<'a>,
3332{
3333    let mut binding = child.into_grammar_binding();
3334    binding.bind_target(vocab, name)?;
3335    let mode = match boundary_backend {
3336        SegmentedBoundaryBackend::StaticParserDwa => ChildCompileMode::Static,
3337        SegmentedBoundaryBackend::Dynamic => ChildCompileMode::Dynamic,
3338    };
3339    let compiled = binding.into_compiled(vocab, mode)?;
3340    prepare_compiled_children(
3341        vec![(name.to_owned(), compiled)],
3342        vocab,
3343        boundary_backend,
3344    )
3345}
3346
3347fn bind_static_parent_grammar<'a, T>(
3348    parent: &RuntimeConstraint,
3349    name: &str,
3350    child: T,
3351    boundary_backend: SegmentedBoundaryBackend,
3352) -> Result<RuntimeConstraint>
3353where
3354    T: IntoSpecGrammarBinding<'a>,
3355{
3356    let profile = crate::env::var_os("GLRMASK_PROFILE_PUBLIC_BIND").is_some();
3357    let total_started = Instant::now();
3358    let phase = Instant::now();
3359    require_late_grammar_slot(std::slice::from_ref(parent), name)?;
3360    let require_ms = phase.elapsed().as_secs_f64() * 1000.0;
3361
3362    let phase = Instant::now();
3363    let vocab = constraint_vocab(parent);
3364    let vocab_ms = phase.elapsed().as_secs_f64() * 1000.0;
3365
3366    let phase = Instant::now();
3367    let children = prepare_late_child(name, child, &vocab, boundary_backend)?;
3368    let child_ms = phase.elapsed().as_secs_f64() * 1000.0;
3369
3370    let phase = Instant::now();
3371    let parent = parent.clone();
3372    let parent_clone_ms = phase.elapsed().as_secs_f64() * 1000.0;
3373
3374    let phase = Instant::now();
3375    let result = compose_named_children(parent, &children, &vocab, boundary_backend)?;
3376    let compose_ms = phase.elapsed().as_secs_f64() * 1000.0;
3377
3378    // Late binding is a construction operation, not an implicit persistence
3379    // request. Serializing an all-static result here made bind latency include
3380    // the full first-save cost even when the caller never saves the result.
3381    // `Constraint::save()` still installs/reuses the serialized artifact cache
3382    // when persistence is actually requested; ordinary `Constraint::compile()`
3383    // keeps its existing eager first-save priming policy.
3384    let cache_save_ms = 0.0;
3385    if profile {
3386        eprintln!(
3387            "[glrmask/profile][public_bind_static_parent] require_ms={require_ms:.3} vocab_ms={vocab_ms:.3} child_ms={child_ms:.3} parent_clone_ms={parent_clone_ms:.3} compose_ms={compose_ms:.3} cache_save_ms={cache_save_ms:.3} total_ms={:.3}",
3388            total_started.elapsed().as_secs_f64() * 1000.0,
3389        );
3390    }
3391    Ok(result)
3392}
3393
3394fn bind_dynamic_parent_grammar<'a, T>(
3395    parent: &DynamicConstraint,
3396    name: &str,
3397    child: T,
3398    boundary_backend: SegmentedBoundaryBackend,
3399) -> Result<DynamicConstraint>
3400where
3401    T: IntoSpecGrammarBinding<'a>,
3402{
3403    let parents = parent.clone_constraints();
3404    require_late_grammar_slot(&parents, name)?;
3405    parents.first().ok_or_else(|| {
3406        Error::Compilation("dynamic parent has no alternatives".to_owned())
3407    })?;
3408    // Cache on the retained parent, not a temporary clone discarded after this
3409    // bind. Loaded constraints must reconstruct the vocabulary at most once.
3410    let vocab = constraint_vocab(&parent.inner);
3411    if !parents
3412        .iter()
3413        .all(|alternative| static_constraint_targets(alternative, &vocab))
3414    {
3415        return Err(Error::Compilation(
3416            "dynamic parent alternatives target incompatible vocabularies".to_owned(),
3417        ));
3418    }
3419    let children = prepare_late_child(name, child, &vocab, boundary_backend)?;
3420    let alternatives = parents
3421        .into_iter()
3422        .map(|alternative| {
3423            compose_named_children(alternative, &children, &vocab, boundary_backend)
3424        })
3425        .collect::<Result<Vec<_>>>()?;
3426    Ok(DynamicConstraint::from_constraints(alternatives))
3427}
3428
3429#[cfg(test)]
3430fn native_dynamic_fixture(grammar: Grammar, vocab: &Vocab) -> Result<DynamicConstraint> {
3431    assert!(grammar.bindings.is_empty(), "fixture supplies compiled bindings separately");
3432    let constraint = match &grammar.source {
3433        // Keep the ordinary full-vocabulary lane in EBNF comparison fixtures,
3434        // while selecting its parser representation explicitly.
3435        GrammarSource::Ebnf(source) => {
3436            let named = crate::import::parse_ebnf_to_named(source)?;
3437            let factored = crate::grammar::factoring::factor_named_grammar(named);
3438            crate::compiler::pipeline::compile_dynamic_owned_with_backend(
3439                crate::grammar::ast::lower(&factored).map_err(crate::error::from_grammar)?, vocab,
3440                crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,
3441                crate::runtime::parser_backend::DynamicParserBackend::Native,
3442            )?
3443        }
3444        GrammarSource::Glrm(source) => crate::import::compile_dynamic_glrm_fixture(
3445            source, vocab, crate::runtime::parser_backend::DynamicParserBackend::Native,
3446        )?,
3447        GrammarSource::Lark(source) => DynamicConstraint::from_lark_with_bounded_template_parser(source, vocab)?,
3448        GrammarSource::JsonSchema(source) => DynamicConstraint::from_json_schema_with_bounded_template_parser(source, vocab)?,
3449        GrammarSource::Constructed=>crate::import::compile_bounded_template_from_named(grammar.component()?.lower_closed().map_err(crate::error::from_grammar)?,vocab,crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,None)?,
3450    };
3451    assert!(constraint.clone_constraints().iter().all(|body|
3452        body.has_template_parser() && !body.table.is_present() && body.uses_dynamic_runtime()));
3453    Ok(constraint)
3454}
3455
3456#[cfg(test)]
3457impl ConstraintSpec<'_> {
3458    /// These fixtures exercise native composition, independent of the ordinary
3459    /// Dynamic development override. Children must already be compiled native
3460    /// fixtures; source-child compilation is covered by the public API gates.
3461    fn compile_native_dynamic_fixture(&self) -> Result<DynamicConstraint> {
3462        assert!(self.token_bindings.is_empty());
3463        let parents = native_dynamic_fixture(self.grammar.clone(), self.vocab)?;
3464        let mut constraint = if self.grammar_bindings.is_empty() {
3465            parents
3466        } else {
3467            let children = prepare_compiled_children(
3468                self.compile_children(ChildCompileMode::Dynamic)?, self.vocab,
3469                SegmentedBoundaryBackend::Dynamic,
3470            )?;
3471            *compose_boxed_dynamic_parents(Box::new(parents), &children, self.vocab)?
3472        };
3473        for body in constraint.constraints_mut() {
3474            let _ = body.late_bind_vocab.set(self.vocab.clone());
3475            body.build_boundary_trigger(self.boundary_trigger_detail).map_err(Error::Compilation)?;
3476        }
3477        Ok(constraint)
3478    }
3479}
3480
3481#[cfg(test)]
3482mod tests {
3483    use super::*;
3484    use crate::automata::lexer::tokenizer::Lexer;
3485
3486    fn compose_owned_test_fixture() -> (Vocab, PreparedGrammar, RuntimeConstraint) {
3487        let vocab = Vocab::from_entries_unchecked(vec![
3488            (0, b"<".to_vec()), (1, b"a".to_vec()), (2, b">".to_vec()),
3489            (3, b"<a>".to_vec()), (4, b"a>".to_vec()), (5, b"<a".to_vec()),
3490            (6, b"b".to_vec()), (7, b"ab".to_vec()), (8, b"<ab>".to_vec()),
3491        ]);
3492        let parent = Grammar::glrm("glrm 1; start root; extern grammar child; nt root = \"<\" child \">\";")
3493            .prepare(&vocab).unwrap();
3494        let child = Grammar::glrm("glrm 1; start value; nt value = \"a\" | \"ab\";")
3495            .compile_inner(&vocab).unwrap().with_end_tokens(&[99]).unwrap();
3496        let parent = PreparedGrammar::load(parent.save(), &vocab).unwrap();
3497        let child = RuntimeConstraint::load(child.save(), &vocab).unwrap();
3498        assert!(child.deferred_composition_metadata_blob.is_some());
3499        assert!(!child.composition_link_metadata_materialized);
3500        (vocab, parent, child)
3501    }
3502
3503    fn assert_compose_owned_behavior_equal(left: &RuntimeConstraint, right: &RuntimeConstraint) {
3504        let mut prefixes = vec![Vec::<u32>::new()];
3505        let mut saw_eof = false;
3506        for depth in 0..=4 {
3507            let mut next = Vec::new();
3508            for prefix in prefixes {
3509                let mut a = left.start(); let mut b = right.start();
3510                for &token in &prefix { assert!(a.commit_token(token)); assert!(b.commit_token(token)); }
3511                let before_a = a.mask(); let before_b = b.mask();
3512                assert_eq!(before_a, before_b, "mask at {prefix:?}");
3513                assert_eq!(a.is_accepting(), b.is_accepting());
3514                // The end token is admitted exactly when the grammar is
3515                // complete, and committing it makes the state accepting.
3516                let mut eof = a.clone();
3517                let allowed_eof = token_allowed(&before_a, 99);
3518                assert_eq!(eof.commit_token(99), allowed_eof, "root EOF policy");
3519                if allowed_eof { assert!(eof.is_accepting()); }
3520                for token in (0..=8).chain([99]) {
3521                    let mut trial_a = a.clone(); let mut trial_b = b.clone();
3522                    let ok_a = trial_a.commit_token(token);
3523                    let ok_b = trial_b.commit_token(token);
3524                    assert_eq!(ok_a, ok_b, "commit {token} at {prefix:?}");
3525                    assert_eq!(trial_a.mask(), trial_b.mask());
3526                    assert_eq!(trial_a.is_accepting(), trial_b.is_accepting());
3527                    if token == 99 && token_allowed(&before_a, token) { assert!(ok_a); saw_eof = true; }
3528                    if depth < 4 && token != 99 && token_allowed(&before_a, token) && ok_a {
3529                        let mut path = prefix.clone(); path.push(token); next.push(path);
3530                    }
3531                }
3532                assert_eq!(a.mask(), before_a, "cloned trial mutated original matcher");
3533                assert_eq!(b.mask(), before_b);
3534            }
3535            prefixes = next;
3536        }
3537        assert!(saw_eof, "fixture must exercise accepting EOF commit");
3538    }
3539
3540    #[test]
3541    fn compose_owned_loaded_private_and_shared_children_preserve_inputs() {
3542        let (vocab, parent, child) = compose_owned_test_fixture();
3543        let parent_bytes = parent.save(); let parent_mask = parent.inner.start().mask();
3544        let child_bytes = child.save(); let child_mask = child.start().mask();
3545        let prepare = || {
3546            let mut p = parent.inner.as_ref().clone();
3547            prepare_immutable_template_component_boundary_summary(&mut p, &vocab);
3548            p.install_template_parser().unwrap();
3549            let mut c = child.clone(); c.end_tokens = Arc::from([]);
3550            prepare_immutable_template_component_boundary_summary(&mut c, &vocab);
3551            c.install_template_parser().unwrap();
3552            (p, Arc::new(c))
3553        };
3554        let (p, c) = prepare(); let private_pointer = Arc::as_ptr(&c);
3555        let owned = crate::runtime::parser_backend::link::compose_owned(p, vec![("child".into(), c)], &vocab)
3556            .unwrap().with_end_tokens(&[99]).unwrap();
3557        let retained = &owned.static_dynamic_overlay.as_ref().unwrap().segmented_parser_components[1].constraint;
3558        assert_eq!(Arc::as_ptr(retained), private_pointer, "private child was copied unnecessarily");
3559        let (p, c) = prepare(); let borrowed_pointer = Arc::as_ptr(&c);
3560        let borrowed = crate::runtime::parser_backend::link::compose(p, &[("child".into(), c.clone())], &vocab)
3561            .unwrap().with_end_tokens(&[99]).unwrap();
3562        assert_ne!(Arc::as_ptr(&borrowed.static_dynamic_overlay.as_ref().unwrap().segmented_parser_components[1].constraint), borrowed_pointer);
3563        let (p, c) = prepare(); let shared_bytes = c.save(); let shared_mask = c.start().mask();
3564        let shared = crate::runtime::parser_backend::link::compose_owned(p, vec![("child".into(), c.clone())], &vocab)
3565            .unwrap().with_end_tokens(&[99]).unwrap();
3566        assert_ne!(Arc::as_ptr(&shared.static_dynamic_overlay.as_ref().unwrap().segmented_parser_components[1].constraint), Arc::as_ptr(&c));
3567        assert!(!c.composition_link_metadata_materialized, "shared child mutated in place");
3568        assert_eq!(c.save(), shared_bytes); assert_eq!(c.start().mask(), shared_mask);
3569        assert_eq!(owned.save(), borrowed.save()); assert_eq!(owned.save(), shared.save());
3570        assert_compose_owned_behavior_equal(&owned, &borrowed);
3571        assert_compose_owned_behavior_equal(&owned, &shared);
3572        let reloaded = RuntimeConstraint::load(owned.save(), &vocab).unwrap();
3573        assert_compose_owned_behavior_equal(&owned, &reloaded);
3574        assert_eq!(parent.save(), parent_bytes); assert_eq!(parent.inner.start().mask(), parent_mask);
3575        assert_eq!(child.save(), child_bytes); assert_eq!(child.start().mask(), child_mask);
3576    }
3577
3578    #[test]
3579    fn compose_owned_repeated_public_links_preserve_retained_inputs() {
3580        let (vocab, parent, child) = compose_owned_test_fixture();
3581        let parent_bytes = parent.save(); let parent_mask = parent.inner.start().mask();
3582        let child = Arc::new(child); let child_bytes = child.save(); let child_mask = child.start().mask();
3583        let options = MaskMode::C.build_options().parser_backend(ParserBackend::TemplateDfa).end_tokens([99]);
3584        let borrowed_bound = parent.bind_snapshot("child", child.as_ref()).unwrap();
3585        let owned_bound = parent.bind_snapshot("child", Arc::clone(&child)).unwrap();
3586        let borrowed_bytes = borrowed_bound.save(); let owned_bytes = owned_bound.save();
3587        let mut first = None;
3588        for _ in 0..3 {
3589            let a = borrowed_bound.link_with(options.clone()).unwrap();
3590            let b = owned_bound.link_with(options.clone()).unwrap();
3591            assert_compose_owned_behavior_equal(&a, &b);
3592            let bytes = a.save(); assert_eq!(bytes, b.save());
3593            if let Some(previous) = first.as_ref() { assert_eq!(&bytes, previous); } else { first = Some(bytes); }
3594            assert_eq!(borrowed_bound.save(), borrowed_bytes); assert_eq!(owned_bound.save(), owned_bytes);
3595            assert_eq!(parent.save(), parent_bytes); assert_eq!(parent.inner.start().mask(), parent_mask);
3596            assert_eq!(child.save(), child_bytes); assert_eq!(child.start().mask(), child_mask);
3597        }
3598        assert_eq!(RuntimeConstraint::load(first.unwrap(), &vocab).unwrap().parser_backend(), ParserBackend::TemplateDfa);
3599    }
3600
3601    fn token_allowed(mask: &[u32], token_id: u32) -> bool {
3602        let word = token_id as usize / 32;
3603        let bit = token_id % 32;
3604        mask.get(word)
3605            .is_some_and(|bits| bits & (1u32 << bit) != 0)
3606    }
3607
3608    #[test]
3609    fn immutable_template_certificate_reuse_recomputes_stale_versions_and_preserves_disabled() {
3610        use crate::runtime::{BoundaryCandidateSummary, OriginalTokenSet, SummaryUnavailable};
3611        let vocab = Vocab::from_entries_unchecked(vec![
3612            (0, b"[a]tail".to_vec()), (1, b"[]tail".to_vec()),
3613            (2, b"[".to_vec()), (3, b"a".to_vec()), (4, b"]".to_vec()),
3614        ]);
3615        let mut component = Grammar::glrm(
3616            r#"glrm 1; start value; nt value = "[" "a"? "]";"#,
3617        ).compile_inner(&vocab).unwrap();
3618        crate::compiler::boundary_candidates::persist_boundary_candidate_summary(&mut component, &vocab);
3619        let expected = crate::compiler::boundary_candidates::persisted_boundary_candidate_ids(&component, &vocab)
3620            .unwrap().expect("fresh component must carry a checked certificate");
3621        assert!(!expected.is_empty());
3622        let mut stale = component.boundary_candidate_summary.take().unwrap();
3623        let BoundaryCandidateSummary::Known { fingerprint, tokens, .. } = &mut stale else {
3624            panic!("expected known certificate");
3625        };
3626        fingerprint.algorithm_version -= 1;
3627        *tokens = OriginalTokenSet::from_sorted_unique(Vec::new(), vocab.max_token_id());
3628        component.boundary_candidate_summary.set(stale).unwrap();
3629        assert!(crate::compiler::boundary_candidates::persisted_boundary_candidate_ids(&component, &vocab)
3630            .unwrap().is_none());
3631        prepare_immutable_template_component_boundary_summary(&mut component, &vocab);
3632        assert_eq!(crate::compiler::boundary_candidates::persisted_boundary_candidate_ids(&component, &vocab)
3633            .unwrap(), Some(expected));
3634        component.boundary_candidate_summary.take();
3635        component.boundary_candidate_summary.set(BoundaryCandidateSummary::Unknown {
3636            reason: SummaryUnavailable::Disabled,
3637        }).unwrap();
3638        prepare_immutable_template_component_boundary_summary(&mut component, &vocab);
3639        assert!(matches!(component.boundary_candidate_summary.get(),
3640            Some(BoundaryCandidateSummary::Unknown { reason: SummaryUnavailable::Disabled })));
3641    }
3642
3643    #[test]
3644    fn immutable_template_certificate_reuse_invalidates_unchanged_resave_cache() {
3645        let vocab = Vocab::from_entries_unchecked(vec![(0, b"a".to_vec()), (1, b"ab".to_vec())]);
3646        let component = Grammar::glrm(r#"glrm 1; start value; nt value = "a";"#)
3647            .compile_inner(&vocab).unwrap();
3648        let mut loaded = RuntimeConstraint::load(component.save(), &vocab).unwrap();
3649        let expected = crate::compiler::boundary_candidates::persisted_boundary_candidate_ids(&loaded, &vocab)
3650            .unwrap().expect("loaded native component must carry a checked certificate");
3651        assert!(loaded.serialized_artifact_cache.is_some());
3652        prepare_immutable_template_component_boundary_summary(&mut loaded, &vocab);
3653        assert!(loaded.serialized_artifact_cache.is_none());
3654        assert_eq!(crate::compiler::boundary_candidates::persisted_boundary_candidate_ids(&loaded, &vocab)
3655            .unwrap(), Some(expected));
3656    }
3657
3658    #[test]
3659    fn vocab_partition_covers_sparse_vocab_and_merges_identical_tokens() {
3660        let vocab = Vocab::from_entries_unchecked(vec![
3661            (0, b"a".to_vec()),
3662            (3, b"a".to_vec()),
3663            (7, b"b".to_vec()),
3664            (11, b"ab".to_vec()),
3665            (67, b"a".to_vec()),
3666        ]);
3667        let partition = VocabPartition::compile(Grammar::ebnf(r#"start ::= "a"+"#), &vocab)
3668            .unwrap();
3669
3670        assert_eq!(partition.class_of(1), None);
3671        for token in [0, 3, 7, 11, 67] {
3672            assert!(partition.class_of(token).is_some(), "token {token} is unmapped");
3673        }
3674        assert_eq!(partition.class_of(0), partition.class_of(3));
3675        assert_eq!(partition.class_of(0), partition.class_of(67));
3676        let mut covered = partition.classes().iter().flatten().copied().collect::<Vec<_>>();
3677        covered.sort_unstable();
3678        assert_eq!(covered, vec![0, 3, 7, 11, 67]);
3679        for class in 0..partition.num_classes() as u32 {
3680            let representative = partition.representative(class).unwrap();
3681            assert_eq!(partition.class_of(representative), Some(class));
3682        }
3683
3684        assert_eq!(partition.internal_mask_len(), partition.num_classes().div_ceil(64));
3685        assert_eq!(partition.original_mask_len(), 3);
3686
3687        let class = partition.class_of(0).unwrap() as usize;
3688        let mut internal = vec![0u64; partition.internal_mask_len()];
3689        internal[class / 64] |= 1u64 << (class % 64);
3690        let expanded = partition.expand_mask(&internal);
3691        assert_ne!(expanded[0] & (1u32 << 0), 0);
3692        assert_ne!(expanded[0] & (1u32 << 3), 0);
3693        assert_eq!(expanded[0] & (1u32 << 1), 0);
3694        assert_ne!(expanded[2] & (1u32 << 3), 0);
3695
3696        let mut reused = vec![u32::MAX; partition.original_mask_len() + 2];
3697        partition.fill_expanded_mask(&internal, &mut reused);
3698        assert_eq!(&reused[..partition.original_mask_len()], expanded.as_slice());
3699        assert_eq!(&reused[partition.original_mask_len()..], &[0, 0]);
3700    }
3701
3702    #[test]
3703    fn vocab_partition_expands_multiple_classes_and_ignores_high_internal_bits() {
3704        let partition = VocabPartition {
3705            original_to_class: vec![0, u32::MAX, 1, 0, u32::MAX, 2, 2, u32::MAX, 1],
3706            classes: vec![vec![0, 3], vec![2, 8], vec![5, 6]],
3707            representatives: vec![0, 2, 5],
3708            class_output_masks: vec![
3709                vec![(0, (1u32 << 0) | (1u32 << 3))],
3710                vec![(0, (1u32 << 2) | (1u32 << 8))],
3711                vec![(0, (1u32 << 5) | (1u32 << 6))],
3712            ],
3713        };
3714
3715        let expanded = partition.expand_mask(&[(1u64 << 0) | (1u64 << 2) | (1u64 << 63)]);
3716        assert_eq!(expanded, vec![(1u32 << 0) | (1u32 << 3) | (1u32 << 5) | (1u32 << 6)]);
3717    }
3718
3719    #[test]
3720    fn vocab_partition_supports_json_schema_frontend() {
3721        let vocab = Vocab::from_entries_unchecked(vec![
3722            (0, b"null".to_vec()),
3723            (1, b"true".to_vec()),
3724            (2, b"false".to_vec()),
3725            (3, b"0".to_vec()),
3726            (4, b"x".to_vec()),
3727        ]);
3728        let partition = VocabPartition::compile(
3729            Grammar::json_schema(r#"{"type":["null","boolean"]}"#),
3730            &vocab,
3731        )
3732        .unwrap();
3733        assert!(partition.num_classes() > 0);
3734        assert!(partition.num_classes() <= vocab.len());
3735    }
3736
3737    #[test]
3738    fn explicit_vocab_partition_strategies_are_conservative() {
3739        let vocab = Vocab::from_entries_unchecked(vec![
3740            (0, b"a".to_vec()),
3741            (1, b"b".to_vec()),
3742            (2, b"ab".to_vec()),
3743            (3, b"ba".to_vec()),
3744            (4, b"aa".to_vec()),
3745            (5, b"bb".to_vec()),
3746        ]);
3747        let source = r#"start ::= ("a" | "b")+"#;
3748        let compact = VocabPartition::compile_with_strategy(
3749            Grammar::ebnf(source),
3750            &vocab,
3751            VocabPartitionStrategy::Compact,
3752        )
3753        .unwrap();
3754        let dedicated = VocabPartition::compile_with_strategy(
3755            Grammar::ebnf(source),
3756            &vocab,
3757            VocabPartitionStrategy::Dedicated,
3758        )
3759        .unwrap();
3760
3761        for class in dedicated.classes() {
3762            let mut compact_class = None;
3763            for &token_id in class {
3764                let current = compact.class_of(token_id).unwrap();
3765                assert!(compact_class.is_none_or(|expected| expected == current));
3766                compact_class = Some(current);
3767            }
3768        }
3769    }
3770    #[test]
3771    fn vocab_partition_rejects_bound_subgrammar_instead_of_ignoring_it() {
3772        let vocab = Vocab::from_entries_unchecked(vec![(0, b"a".to_vec())]);
3773        let grammar = Grammar::glrm(
3774            "glrm 1; extern grammar child; start root; nt root = child;",
3775        )
3776        .bind_grammar("child", Grammar::ebnf(r#"start ::= "a""#))
3777        .unwrap();
3778        let error = VocabPartition::compile(grammar, &vocab).unwrap_err();
3779        assert!(error.to_string().contains("bound grammar values"));
3780    }
3781
3782    #[test]
3783    fn partition_optimized_dynamic_mask_matches_ordinary_dynamic() {
3784        let vocab = Vocab::from_entries_unchecked(vec![
3785            (0, b"a".to_vec()),
3786            (1, b"b".to_vec()),
3787            (2, b"aa".to_vec()),
3788            (3, b"bb".to_vec()),
3789            (4, b"ab".to_vec()),
3790            (5, b"ba".to_vec()),
3791            (6, b"x".to_vec()),
3792        ]);
3793        let grammar_source = "start ::= [ab]+".to_owned();
3794        let grammar = Grammar::ebnf(&grammar_source);
3795        let partition = VocabPartition::compile(grammar.clone(), &vocab).unwrap();
3796        assert_eq!(partition.class_of(0), partition.class_of(1));
3797        assert!(partition.num_classes() < vocab.len());
3798
3799        let ordinary = DynamicConstraint::compile(grammar.clone(), &vocab).unwrap();
3800        let optimized =
3801            DynamicConstraint::compile_with_vocab_partition(grammar, &vocab).unwrap();
3802
3803        assert_eq!(optimized.inner.token_bytes_count(), vocab.len());
3804        assert!(
3805            optimized
3806                .inner
3807                .dynamic_mask_vocab_for_runtime()
3808                .is_grammar_quotiented(),
3809            "O2 must not silently fall back to ordinary dynamic for tiny grammars",
3810        );
3811        assert!(
3812            optimized
3813                .inner
3814                .dynamic_mask_vocab_for_runtime()
3815                .canonical_token_count()
3816                < ordinary
3817                    .inner
3818                    .dynamic_mask_vocab_for_runtime()
3819                    .canonical_token_count(),
3820            "optimized dynamic runtime did not reduce the mask vocabulary",
3821        );
3822
3823        let ordinary_start = ordinary.start();
3824        let optimized_start = optimized.start();
3825        assert_eq!(ordinary_start.mask(), optimized_start.mask());
3826
3827        for token in [0u32, 1, 2, 3, 4, 5] {
3828            let mut ordinary_state = ordinary.start();
3829            let mut optimized_state = optimized.start();
3830            assert!(ordinary_state.commit_token(token));
3831            assert!(optimized_state.commit_token(token));
3832            assert_eq!(ordinary_state.is_accepting(), optimized_state.is_accepting());
3833            assert_eq!(ordinary_state.mask(), optimized_state.mask(), "token {token}");
3834        }
3835    }
3836
3837    #[test]
3838    fn singleton_literal_partition_matches_dynamic_masks_exactly() {
3839        let vocab = Vocab::from_entries_unchecked(vec![
3840            (0, b"x".to_vec()),
3841            (1, b"{".to_vec()),
3842            (2, b"}".to_vec()),
3843            (3, b"{}".to_vec()),
3844            (4, b"{}x".to_vec()),
3845            (5, b"{".to_vec()),
3846            (6, b"x{}".to_vec()),
3847        ]);
3848        let grammar_source = r#"start ::= "{" "}""#.to_owned();
3849        let grammar = Grammar::ebnf(&grammar_source);
3850        let partition = VocabPartition::compile(grammar.clone(), &vocab).unwrap();
3851
3852        assert_eq!(partition.num_classes(), 4);
3853        assert_eq!(partition.class_of(0), partition.class_of(4));
3854        assert_eq!(partition.class_of(0), partition.class_of(6));
3855        assert_eq!(partition.class_of(1), partition.class_of(5));
3856        assert_ne!(partition.class_of(1), partition.class_of(2));
3857        assert_ne!(partition.class_of(1), partition.class_of(3));
3858        assert_ne!(partition.class_of(2), partition.class_of(3));
3859
3860        let ordinary = DynamicConstraint::compile(grammar.clone(), &vocab).unwrap();
3861        let optimized =
3862            DynamicConstraint::compile_with_vocab_partition(grammar, &vocab).unwrap();
3863
3864        let ordinary_start = ordinary.start();
3865        let optimized_start = optimized.start();
3866        assert_eq!(ordinary_start.mask(), optimized_start.mask());
3867        for token in [0u32, 1, 2, 3, 4, 5, 6] {
3868            assert_eq!(
3869                token_allowed(&ordinary_start.mask(), token),
3870                token_allowed(&optimized_start.mask(), token),
3871                "start mask differs for token {token}",
3872            );
3873        }
3874
3875        for open in [1u32, 5] {
3876            let mut ordinary_state = ordinary.start();
3877            let mut optimized_state = optimized.start();
3878            assert!(ordinary_state.commit_token(open));
3879            assert!(optimized_state.commit_token(open));
3880            assert_eq!(ordinary_state.is_accepting(), optimized_state.is_accepting());
3881            assert_eq!(ordinary_state.mask(), optimized_state.mask());
3882        }
3883
3884        let mut ordinary_done = ordinary.start();
3885        let mut optimized_done = optimized.start();
3886        assert!(ordinary_done.commit_token(3));
3887        assert!(optimized_done.commit_token(3));
3888        assert!(ordinary_done.is_accepting());
3889        assert!(optimized_done.is_accepting());
3890        assert_eq!(ordinary_done.mask(), optimized_done.mask());
3891
3892        // The production singleton path uses the flat alias representation and
3893        // deliberately defers its first transfer-artifact serialization. Verify
3894        // that both survive the real external-vocab save/load boundary.
3895        let saved = optimized.save_without_vocab();
3896        let loaded = DynamicConstraint::load_with_vocab(&saved, &vocab).unwrap();
3897        assert_eq!(loaded.start().mask(), optimized.start().mask());
3898        let mut loaded_done = loaded.start();
3899        assert!(loaded_done.commit_token(3));
3900        assert!(loaded_done.is_accepting());
3901    }
3902
3903    #[test]
3904    fn singleton_literal_partition_matches_all_reachable_cross_terminal_prefixes() {
3905        let vocab = Vocab::from_entries_unchecked(vec![
3906            (0, b"a".to_vec()),
3907            (2, b"b".to_vec()),
3908            (5, b"c".to_vec()),
3909            (9, b"d".to_vec()),
3910            (12, b"ab".to_vec()),
3911            (18, b"bc".to_vec()),
3912            (24, b"cd".to_vec()),
3913            (31, b"abc".to_vec()),
3914            (37, b"bcd".to_vec()),
3915            (44, b"abcd".to_vec()),
3916            (51, b"x".to_vec()),
3917            (58, b"bd".to_vec()),
3918            (63, b"abcx".to_vec()),
3919            (71, b"bc".to_vec()),
3920        ]);
3921        let token_ids = vocab.iter().map(|(token_id, _)| token_id).collect::<Vec<_>>();
3922        let grammar_source = r#"start ::= "ab" "cd""#.to_owned();
3923        let grammar = Grammar::ebnf(&grammar_source);
3924
3925        // Compile ordinary first so the optimized compile also exercises the
3926        // cached byte-order lookup used by prepared production vocabularies.
3927        let ordinary = DynamicConstraint::compile(grammar.clone(), &vocab).unwrap();
3928        let optimized =
3929            DynamicConstraint::compile_with_vocab_partition(grammar, &vocab).unwrap();
3930
3931        let mut pending = vec![Vec::<u32>::new()];
3932        let mut seen = std::collections::BTreeSet::<Vec<u32>>::new();
3933        seen.insert(Vec::new());
3934        while let Some(prefix) = pending.pop() {
3935            let mut ordinary_state = ordinary.start();
3936            let mut optimized_state = optimized.start();
3937            for &token in &prefix {
3938                assert!(ordinary_state.commit_token(token));
3939                assert!(optimized_state.commit_token(token));
3940            }
3941
3942            assert_eq!(
3943                ordinary_state.is_accepting(),
3944                optimized_state.is_accepting(),
3945                "acceptance differs after token prefix {prefix:?}",
3946            );
3947            let ordinary_mask = ordinary_state.mask();
3948            let optimized_mask = optimized_state.mask();
3949            assert_eq!(
3950                ordinary_mask, optimized_mask,
3951                "mask differs after token prefix {prefix:?}",
3952            );
3953
3954            for &token in &token_ids {
3955                let ordinary_allowed = token_allowed(&ordinary_mask, token);
3956                let optimized_allowed = token_allowed(&optimized_mask, token);
3957                assert_eq!(
3958                    ordinary_allowed, optimized_allowed,
3959                    "token {token} differs after token prefix {prefix:?}",
3960                );
3961                if ordinary_allowed {
3962                    let mut next = prefix.clone();
3963                    next.push(token);
3964                    // Four one-byte tokens can consume the complete language;
3965                    // no valid path can require a deeper token prefix.
3966                    if next.len() <= 4 && seen.insert(next.clone()) {
3967                        pending.push(next);
3968                    }
3969                }
3970            }
3971        }
3972    }
3973
3974    #[test]
3975    fn partition_optimized_dynamic_save_load_preserves_quotient_mask() {
3976        let vocab = Vocab::from_entries_unchecked(vec![
3977            (0, b"a".to_vec()),
3978            (1, b"b".to_vec()),
3979            (2, b"aa".to_vec()),
3980            (3, b"bb".to_vec()),
3981            (4, b"x".to_vec()),
3982        ]);
3983        let grammar_source = format!(
3984            "start ::= [ab]+{}",
3985            (0..17)
3986                .map(|index| format!(r#" | "unused_{index}""#))
3987                .collect::<String>()
3988        );
3989        let optimized =
3990            DynamicConstraint::compile_with_vocab_partition(Grammar::ebnf(&grammar_source), &vocab)
3991                .unwrap();
3992        let original_canonical = optimized
3993            .inner
3994            .dynamic_mask_vocab_for_runtime()
3995            .canonical_token_count();
3996        assert!(original_canonical < vocab.len());
3997        let bytes = optimized.save_without_vocab();
3998        let loaded = DynamicConstraint::load_with_vocab(&bytes, &vocab).unwrap();
3999        assert_eq!(loaded.start().mask(), optimized.start().mask());
4000        assert_eq!(
4001            loaded
4002                .inner
4003                .dynamic_mask_vocab_for_runtime()
4004                .canonical_token_count(),
4005            original_canonical,
4006            "save/load must retain the representative vocabulary rather than rebuilding the full vocabulary",
4007        );
4008    }
4009
4010    #[test]
4011    fn partition_optimized_bounded_string_schema_does_not_fall_back_to_ordinary_dynamic() {
4012        let vocab = Vocab::from_entries_unchecked(vec![
4013            (0, b"\"abcdefgh\"".to_vec()),
4014            (1, b"\"ijklmnop\"".to_vec()),
4015            (2, b"true".to_vec()),
4016            (3, b"false".to_vec()),
4017            (4, b"{".to_vec()),
4018            (5, b"}".to_vec()),
4019            (6, b":".to_vec()),
4020            (7, b",".to_vec()),
4021            (8, b" ".to_vec()),
4022        ]);
4023        let mut properties = serde_json::Map::new();
4024        properties.insert(
4025            "bounded".to_owned(),
4026            serde_json::json!({"type":"string", "minLength":8, "maxLength":8}),
4027        );
4028        for index in 0..20 {
4029            properties.insert(format!("flag_{index}"), serde_json::json!({"type":"boolean"}));
4030        }
4031        let schema = serde_json::json!({
4032            "type":"object",
4033            "properties": properties,
4034            "additionalProperties": false
4035        })
4036        .to_string();
4037
4038        let optimized = DynamicConstraint::compile_with_vocab_partition(
4039            Grammar::json_schema(&schema),
4040            &vocab,
4041        )
4042        .unwrap();
4043        assert!(
4044            optimized
4045                .inner
4046                .dynamic_mask_vocab_for_runtime()
4047                .is_grammar_quotiented(),
4048            "O2 must retain its grammar quotient for bounded-string residual schemas",
4049        );
4050
4051        let bytes = optimized.save_without_vocab();
4052        let loaded = DynamicConstraint::load_with_vocab(&bytes, &vocab).unwrap();
4053        assert!(
4054            loaded
4055                .inner
4056                .dynamic_mask_vocab_for_runtime()
4057                .is_grammar_quotiented(),
4058            "external-vocab transfer must preserve the O2 grammar quotient",
4059        );
4060        assert_eq!(loaded.start().mask(), optimized.start().mask());
4061    }
4062
4063    #[test]
4064    fn partition_optimized_plain_bounded_string_builds_a_real_quotient() {
4065        let vocab = Vocab::from_entries_unchecked(vec![
4066            (0, b"\"".to_vec()),
4067            (1, b"a".to_vec()),
4068            (2, b"b".to_vec()),
4069            (3, b"aa".to_vec()),
4070            (4, b"bb".to_vec()),
4071            (5, b"ab".to_vec()),
4072            (6, b"ba".to_vec()),
4073            (7, b"\"a".to_vec()),
4074            (8, b"\"b".to_vec()),
4075            (9, b"x".to_vec()),
4076        ]);
4077        let schema = r#"{"type":"string","maxLength":100}"#;
4078
4079        let ordinary =
4080            DynamicConstraint::compile(Grammar::json_schema(schema), &vocab).unwrap();
4081        let optimized = DynamicConstraint::compile_with_vocab_partition(
4082            Grammar::json_schema(schema),
4083            &vocab,
4084        )
4085        .unwrap();
4086
4087        let optimized_vocab = optimized.inner.dynamic_mask_vocab_for_runtime();
4088        assert!(optimized_vocab.is_grammar_quotiented());
4089        assert!(
4090            optimized_vocab.canonical_token_count() < vocab.len(),
4091            "bounded-string O2 must not degrade to the identity vocabulary quotient",
4092        );
4093        assert_eq!(ordinary.start().mask(), optimized.start().mask());
4094
4095        let mut ordinary_state = ordinary.start();
4096        let mut optimized_state = optimized.start();
4097        assert!(ordinary_state.commit_token(0));
4098        assert!(optimized_state.commit_token(0));
4099        assert_eq!(ordinary_state.mask(), optimized_state.mask());
4100    }
4101
4102    #[test]
4103    fn partition_optimized_multi_alternative_roundtrips_without_sharing_one_quotient() {
4104        let vocab = Vocab::from_entries_unchecked(vec![
4105            (0, b"a".to_vec()),
4106            (1, b"b".to_vec()),
4107            (2, b"aa".to_vec()),
4108            (3, b"bb".to_vec()),
4109            (4, b"ab".to_vec()),
4110            (5, b"ba".to_vec()),
4111            (6, b"x".to_vec()),
4112        ]);
4113        let first = DynamicConstraint::compile_with_vocab_partition(
4114            Grammar::ebnf(r#"start ::= [ab]+"#),
4115            &vocab,
4116        )
4117        .unwrap();
4118        let second = DynamicConstraint::compile_with_vocab_partition(
4119            Grammar::ebnf(r#"start ::= "a"+"#),
4120            &vocab,
4121        )
4122        .unwrap();
4123        let optimized = DynamicConstraint::from_alternatives(vec![first, second]);
4124        assert_eq!(optimized.clone_constraints().len(), 2);
4125        let expected_mask = optimized.start().mask();
4126
4127        // The self-contained wire has one shared vocab accelerator, so this
4128        // case intentionally drops the per-alternative quotients and rebuilds
4129        // the full vocab lazily after load rather than applying one quotient to
4130        // every alternative.
4131        let loaded = DynamicConstraint::load(&optimized.save(), &vocab).unwrap();
4132        assert_eq!(loaded.start().mask(), expected_mask);
4133
4134        // The external-vocab transfer has per-alternative metadata and can keep
4135        // each quotient independently.
4136        let transferred = DynamicConstraint::load_with_vocab(
4137            &optimized.save_without_vocab(),
4138            &vocab,
4139        )
4140        .unwrap();
4141        assert_eq!(transferred.start().mask(), expected_mask);
4142    }
4143
4144    #[test]
4145    fn partition_optimized_component_keeps_boundary_token_distinctions() {
4146        let vocab = Vocab::from_entries_unchecked(vec![
4147            (0, b"a".to_vec()),
4148            (1, b"b".to_vec()),
4149            (2, b"ax".to_vec()),
4150            (3, b"ay".to_vec()),
4151            (4, b"bx".to_vec()),
4152            (5, b"by".to_vec()),
4153            (6, b"x".to_vec()),
4154            (7, b"y".to_vec()),
4155        ]);
4156        let child_grammar = Grammar::ebnf(r#"start ::= [ab]"#);
4157        let child_partition = VocabPartition::compile(child_grammar.clone(), &vocab).unwrap();
4158        assert_eq!(child_partition.class_of(2), child_partition.class_of(3));
4159        assert_eq!(child_partition.class_of(4), child_partition.class_of(5));
4160
4161        let ordinary_child = native_dynamic_fixture(child_grammar.clone(), &vocab).unwrap();
4162        let optimized_child =
4163            DynamicConstraint::from_ebnf_with_bounded_template_parser(
4164                r#"start ::= [ab]"#, &vocab,
4165            ).unwrap();
4166        assert_eq!(optimized_child.inner.token_bytes_count(), vocab.len());
4167
4168        let parent = Grammar::glrm(
4169            "glrm 1; start start; extern grammar child; nt start = child \"x\";",
4170        );
4171        let ordinary = ConstraintSpec::builder(parent.clone(), &vocab)
4172            .unwrap()
4173            .bind_grammar("child", &ordinary_child)
4174            .unwrap()
4175            .build()
4176            .unwrap()
4177            .compile_native_dynamic_fixture()
4178            .unwrap();
4179        let optimized = ConstraintSpec::builder(parent, &vocab)
4180            .unwrap()
4181            .bind_grammar("child", &optimized_child)
4182            .unwrap()
4183            .build()
4184            .unwrap()
4185            .compile_native_dynamic_fixture()
4186            .unwrap();
4187
4188        let ordinary_mask = ordinary.start().mask();
4189        let optimized_mask = optimized.start().mask();
4190        assert_eq!(ordinary_mask, optimized_mask);
4191        assert!(token_allowed(&optimized_mask, 2), "ax must cross child -> parent boundary");
4192        assert!(!token_allowed(&optimized_mask, 3), "ay must remain rejected by the parent boundary");
4193        assert!(token_allowed(&optimized_mask, 4), "bx must cross child -> parent boundary");
4194        assert!(!token_allowed(&optimized_mask, 5), "by must remain rejected by the parent boundary");
4195    }
4196
4197    #[test]
4198    fn first_save_priming_threshold_tracks_large_composition_cache() {
4199        let vocab = Vocab::from_entries_unchecked(vec![(0, b"a".to_vec())]);
4200        let mut constraint = RuntimeConstraint::compile(
4201            Grammar::glrm("glrm 1;\nstart start;\nt A = \"a\";\nnt start = A;\n"),
4202            &vocab,
4203        )
4204        .unwrap();
4205        assert!(!should_prime_first_save_artifact(&constraint));
4206
4207        let mut large = crate::automata::unweighted_u32::dfa::DFA::new();
4208        large
4209            .states
4210            .resize_with(FIRST_SAVE_TEMPLATE_STATE_PRIME_THRESHOLD, Default::default);
4211        constraint.composition_parser_templates_by_terminal = vec![Some(large)];
4212        assert!(should_prime_first_save_artifact(&constraint));
4213    }
4214
4215    fn component_backend_flags(constraint: &RuntimeConstraint) -> Vec<bool> {
4216        constraint
4217            .static_dynamic_overlay
4218            .as_ref()
4219            .expect("bound constraint must use the explicit segmented runtime")
4220            .segmented_parser_components
4221            .iter()
4222            .map(|component| component.constraint.uses_dynamic_runtime())
4223            .collect()
4224    }
4225
4226    fn leaf_backend_flags(constraint: &RuntimeConstraint) -> Vec<bool> {
4227        match constraint.static_dynamic_overlay.as_ref() {
4228            Some(overlay) if !overlay.segmented_parser_components.is_empty() => overlay
4229                .segmented_parser_components
4230                .iter()
4231                .flat_map(|component| leaf_backend_flags(&component.constraint))
4232                .collect(),
4233            _ => vec![constraint.uses_dynamic_runtime()],
4234        }
4235    }
4236
4237    fn assert_recursive_compiler_views_detached(constraint: &RuntimeConstraint) {
4238        assert!(constraint.has_template_parser());
4239        assert!(!constraint.table.is_present(), "native parser retained an LR table");
4240        if !constraint.uses_compact_segmented_parser_runtime() {
4241            return;
4242        }
4243        let overlay = constraint.static_dynamic_overlay.as_ref().unwrap();
4244        assert!(
4245            constraint.template_parser.as_ref().unwrap().link_grammar.is_some(),
4246            "recursive coordinator lost its pure composition grammar metadata",
4247        );
4248        for component in &overlay.segmented_parser_components {
4249            assert_recursive_compiler_views_detached(&component.constraint);
4250        }
4251    }
4252
4253    fn assert_no_materialized_outer_table(constraint: &mut RuntimeConstraint) {
4254        constraint.recursive_parser_layout().unwrap().unwrap();
4255        // Native constraints have no table to poison, including at leaves.
4256        // Keep exercising the cloned/loaded instance after proving absence.
4257        assert_recursive_compiler_views_detached(constraint);
4258    }
4259
4260    fn assert_static_boundary(constraint: &RuntimeConstraint) {
4261        let overlay = constraint
4262            .static_dynamic_overlay
4263            .as_ref()
4264            .expect("bound constraint must use the explicit segmented runtime");
4265        assert!(overlay.segmented_boundary_parser.is_none());
4266        assert!(overlay.segmented_boundary_terminal_trie.is_none());
4267        assert!(
4268            !overlay.segmented_boundary_shards.is_empty(),
4269            "static boundary policy must publish component-owned shards",
4270        );
4271        assert!(overlay.segmented_boundary_shards.iter().all(|shard| matches!(
4272            shard.backend,
4273            crate::runtime::SegmentedBoundaryShardBackend::StaticParser(_)
4274        )));
4275    }
4276
4277    fn assert_dynamic_boundary(constraint: &RuntimeConstraint) {
4278        let overlay = constraint
4279            .static_dynamic_overlay
4280            .as_ref()
4281            .expect("bound constraint must use the explicit segmented runtime");
4282        assert!(overlay.segmented_boundary_parser.is_none());
4283        assert!(overlay.segmented_boundary_terminal_trie.is_none());
4284        assert!(overlay.segmented_boundary_shards.iter().all(|shard| matches!(
4285            shard.backend,
4286            crate::runtime::SegmentedBoundaryShardBackend::DynamicDirect
4287        )));
4288    }
4289
4290    #[test]
4291    fn mixed_native_lr_component_composition_returns_compilation_error() {
4292        let vocab = Vocab::from_entries_unchecked(vec![(0, b"x".to_vec()), (1, b"y".to_vec()), (2, b"xy".to_vec())]);
4293        let lr = |source: &str| crate::import::compile_dynamic_glrm_fixture(
4294            source, &vocab, crate::runtime::parser_backend::DynamicParserBackend::LrTable,
4295        ).unwrap();
4296        let source = "start start; extern grammar child; nt start = 'x' child;";
4297        let parent = RuntimeConstraint::compile(Grammar::glrm(source), &vocab).unwrap();
4298        let child = lr("start start; nt start = 'y';");
4299        assert!(child.inner.table.is_present());
4300        assert!(!child.inner.has_template_parser());
4301        let spec = ConstraintSpec::builder(Grammar::glrm(source), &vocab).unwrap()
4302            .bind_grammar("child", &child).unwrap().build().unwrap();
4303        for error in [spec.compile().unwrap_err(), spec.compile_dynamic().unwrap_err(),
4304            parent.bind_grammar("child", &child).unwrap_err(),
4305            parent.bind_grammar_dynamic_boundary("child", &child).unwrap_err()] {
4306            assert_eq!(error.kind(), crate::ErrorKind::Compilation);
4307            let message=error.to_string();
4308            assert!(message.contains("a composition can't mix parts precompiled with the LrTable and TemplateDfa parser backends"), "{message}");
4309        }
4310        let lr_parent = lr(source);
4311        let native_child = RuntimeConstraint::compile(Grammar::ebnf("start ::= 'y'"), &vocab).unwrap();
4312        for error in [lr_parent.bind_grammar("child", &native_child).unwrap_err(),
4313            lr_parent.bind_grammar_dynamic_boundary("child", &native_child).unwrap_err()] {
4314            assert_eq!(error.kind(), crate::ErrorKind::Compilation);
4315            let message=error.to_string();
4316            assert!(message.contains("a composition can't mix parts precompiled with the LrTable and TemplateDfa parser backends"), "{message}");
4317        }
4318        // Failed linking must leave the retained LR object usable.
4319        assert_eq!(child.start().mask()[0] & 2, 2);
4320        assert!(child.inner.table.is_present());
4321    }
4322
4323    #[test]
4324    fn segmented_composition_preserves_supplied_component_backends() {
4325        let vocab = Vocab::from_entries_unchecked(vec![
4326            (0, b"x".to_vec()),
4327            (1, b"y".to_vec()),
4328            // Forces B to carry a strictly internal parent -> child crossing.
4329            (2, b"xy".to_vec()),
4330        ]);
4331        let parent = Grammar::glrm(
4332            "glrm 1; start start; extern grammar child; nt start = \"x\" child;",
4333        );
4334        let static_child = RuntimeConstraint::compile(Grammar::ebnf(r#"start ::= "y""#), &vocab)
4335            .unwrap();
4336        let dynamic_child =
4337            native_dynamic_fixture(Grammar::ebnf(r#"start ::= "y""#), &vocab).unwrap();
4338
4339        let static_with_dynamic = ConstraintSpec::builder(parent.clone(), &vocab)
4340            .unwrap()
4341            .bind_grammar("child", &dynamic_child)
4342            .unwrap()
4343            .build()
4344            .unwrap()
4345            .compile()
4346            .unwrap();
4347        assert_eq!(component_backend_flags(&static_with_dynamic), vec![false, true]);
4348        assert!(
4349            static_with_dynamic.serialized_artifact_cache.is_none(),
4350            "compiling a hybrid must not eagerly staticify its dynamic leaf for serialization",
4351        );
4352        assert_static_boundary(&static_with_dynamic);
4353
4354        let dynamic_with_static = ConstraintSpec::builder(parent.clone(), &vocab)
4355            .unwrap()
4356            .bind_grammar("child", &static_child)
4357            .unwrap()
4358            .build()
4359            .unwrap()
4360            .compile_native_dynamic_fixture()
4361            .unwrap();
4362        for alternative in dynamic_with_static.clone_constraints() {
4363            assert_eq!(component_backend_flags(&alternative), vec![true, false]);
4364            let overlay = alternative.static_dynamic_overlay.as_ref().unwrap();
4365            assert!(overlay.segmented_boundary_parser.is_none());
4366            assert!(overlay.segmented_boundary_terminal_trie.is_none());
4367            assert!(overlay.segmented_boundary_shards.iter().all(|shard| matches!(
4368                shard.backend,
4369                crate::runtime::SegmentedBoundaryShardBackend::DynamicDirect
4370            )));
4371        }
4372
4373        let dynamic_with_dynamic = ConstraintSpec::builder(parent, &vocab)
4374            .unwrap()
4375            .bind_grammar("child", &dynamic_child)
4376            .unwrap()
4377            .build()
4378            .unwrap()
4379            .compile_native_dynamic_fixture()
4380            .unwrap();
4381        for alternative in dynamic_with_dynamic.clone_constraints() {
4382            assert_eq!(component_backend_flags(&alternative), vec![true, true]);
4383        }
4384    }
4385
4386    #[test]
4387    fn compiled_parent_late_binding_preserves_leaf_backends_and_boundary_choice() {
4388        let vocab = Vocab::from_entries_unchecked(vec![
4389            (0, b"x".to_vec()),
4390            (1, b"y".to_vec()),
4391            (2, b"xy".to_vec()),
4392            (3, b"z".to_vec()),
4393            (4, b"yz".to_vec()),
4394            (5, b"xyz".to_vec()),
4395        ]);
4396        let one_slot = Grammar::glrm(
4397            "glrm 1; start start; extern grammar child; nt start = \"x\" child;",
4398        );
4399        let static_parent = RuntimeConstraint::compile(one_slot.clone(), &vocab).unwrap();
4400        let dynamic_parent = native_dynamic_fixture(one_slot, &vocab).unwrap();
4401        let static_child = RuntimeConstraint::compile(Grammar::ebnf(r#"start ::= "y""#), &vocab)
4402            .unwrap();
4403        let dynamic_child =
4404            native_dynamic_fixture(Grammar::ebnf(r#"start ::= "y""#), &vocab).unwrap();
4405
4406        let bound = static_parent.bind_grammar("child", &static_child).unwrap();
4407        assert_eq!(leaf_backend_flags(&bound), vec![false, false]);
4408        assert_static_boundary(&bound);
4409        assert!(
4410            bound.serialized_artifact_cache.is_none(),
4411            "late binding must not pay first-save serialization eagerly",
4412        );
4413
4414        let bound = static_parent
4415            .bind_grammar_dynamic_boundary("child", &static_child)
4416            .unwrap();
4417        assert_eq!(leaf_backend_flags(&bound), vec![false, false]);
4418        assert_dynamic_boundary(&bound);
4419
4420        let bound = static_parent.bind_grammar("child", &dynamic_child).unwrap();
4421        assert_eq!(leaf_backend_flags(&bound), vec![false, true]);
4422        assert_static_boundary(&bound);
4423        assert!(
4424            bound.serialized_artifact_cache.is_none(),
4425            "late binding a dynamic child must not trigger serialization-time staticification",
4426        );
4427
4428        let bound = static_parent
4429            .bind_grammar_dynamic_boundary("child", &dynamic_child)
4430            .unwrap();
4431        assert_eq!(leaf_backend_flags(&bound), vec![false, true]);
4432        assert_dynamic_boundary(&bound);
4433
4434        let bound = dynamic_parent.bind_grammar("child", &static_child).unwrap();
4435        for alternative in bound.clone_constraints() {
4436            assert_eq!(leaf_backend_flags(&alternative), vec![true, false]);
4437            assert_static_boundary(&alternative);
4438        }
4439
4440        let bound = dynamic_parent
4441            .bind_grammar_dynamic_boundary("child", &static_child)
4442            .unwrap();
4443        for alternative in bound.clone_constraints() {
4444            assert_eq!(leaf_backend_flags(&alternative), vec![true, false]);
4445            assert_dynamic_boundary(&alternative);
4446        }
4447
4448        let bound = dynamic_parent.bind_grammar("child", &dynamic_child).unwrap();
4449        for alternative in bound.clone_constraints() {
4450            assert_eq!(leaf_backend_flags(&alternative), vec![true, true]);
4451            assert_static_boundary(&alternative);
4452        }
4453
4454        let bound = dynamic_parent
4455            .bind_grammar_dynamic_boundary("child", &dynamic_child)
4456            .unwrap();
4457        for alternative in bound.clone_constraints() {
4458            assert_eq!(leaf_backend_flags(&alternative), vec![true, true]);
4459            assert_dynamic_boundary(&alternative);
4460        }
4461
4462        let two_slots = Grammar::glrm(
4463            "glrm 1; start start; extern grammar left; extern grammar right; \
4464             nt start = \"x\" left right;",
4465        );
4466        let open = RuntimeConstraint::compile(two_slots, &vocab).unwrap();
4467        let partially_bound = open.bind_grammar("left", &static_child).unwrap();
4468        assert!(
4469            partially_bound.late_bind_vocab.get().is_some(),
4470            "partially bound constraints should carry the shared vocabulary cache into the next bind",
4471        );
4472        assert!(partially_bound
4473            .late_grammar_slots
4474            .iter()
4475            .any(|slot| slot.name == "right"));
4476        let fully_bound = partially_bound
4477            .bind_grammar(
4478                "right",
4479                native_dynamic_fixture(Grammar::ebnf(r#"start ::= "z""#), &vocab).unwrap(),
4480            )
4481            .unwrap();
4482        assert!(fully_bound.late_grammar_slots.is_empty());
4483        assert_eq!(leaf_backend_flags(&fully_bound), vec![false, false, true]);
4484        assert_static_boundary(&fully_bound);
4485
4486        let fully_bound = partially_bound
4487            .bind_grammar_dynamic_boundary(
4488                "right",
4489                native_dynamic_fixture(Grammar::ebnf(r#"start ::= "z""#), &vocab).unwrap(),
4490            )
4491            .unwrap();
4492        assert!(fully_bound.late_grammar_slots.is_empty());
4493        assert_eq!(leaf_backend_flags(&fully_bound), vec![false, false, true]);
4494        assert_dynamic_boundary(&fully_bound);
4495
4496        let open = native_dynamic_fixture(
4497            Grammar::glrm(
4498                "glrm 1; start start; extern grammar left; extern grammar right; \
4499                 nt start = \"x\" left right;",
4500            ),
4501            &vocab,
4502        )
4503        .unwrap();
4504        let partially_bound = open.bind_grammar("left", &static_child).unwrap();
4505        let dynamic_right =
4506            native_dynamic_fixture(Grammar::ebnf(r#"start ::= "z""#), &vocab).unwrap();
4507        let fully_bound = partially_bound.bind_grammar("right", &dynamic_right).unwrap();
4508        for alternative in fully_bound.clone_constraints() {
4509            assert_eq!(leaf_backend_flags(&alternative), vec![true, false, true]);
4510            assert_static_boundary(&alternative);
4511        }
4512        let fully_bound = partially_bound
4513            .bind_grammar_dynamic_boundary("right", &dynamic_right)
4514            .unwrap();
4515        for alternative in fully_bound.clone_constraints() {
4516            assert_eq!(leaf_backend_flags(&alternative), vec![true, false, true]);
4517            assert_dynamic_boundary(&alternative);
4518        }
4519    }
4520
4521    #[test]
4522    fn all_static_late_bound_segmented_roundtrip_preserves_fused_boundary_tokens() {
4523        let vocab = Vocab::from_entries_unchecked(vec![
4524            (0, b"x".to_vec()),
4525            (1, b"y".to_vec()),
4526            (2, b"xy".to_vec()),
4527        ]);
4528        let parent = RuntimeConstraint::compile(
4529            Grammar::glrm(
4530                "glrm 1; start start; extern grammar child; nt start = \"x\" child;",
4531            ),
4532            &vocab,
4533        )
4534        .unwrap();
4535        let child = RuntimeConstraint::compile(Grammar::ebnf(r#"start ::= "y""#), &vocab)
4536            .unwrap();
4537
4538        for dynamic_boundary in [false, true] {
4539            let bound = if dynamic_boundary {
4540                parent
4541                    .bind_grammar_dynamic_boundary("child", child.clone())
4542                    .unwrap()
4543            } else {
4544                parent.bind_grammar("child", child.clone()).unwrap()
4545            };
4546            let live_mask = bound.start().mask();
4547            assert_ne!(
4548                live_mask[0] & (1 << 2),
4549                0,
4550                "fused parent/child token must be live before serialization",
4551            );
4552
4553            let loaded = RuntimeConstraint::load(bound.save(), &vocab).unwrap();
4554            let overlay = loaded
4555                .static_dynamic_overlay
4556                .as_ref()
4557                .expect("round-tripped segmented runtime must retain A/B metadata");
4558            assert!(
4559                !overlay.segmented_static_baseline,
4560                "new segmented saves must not synthesize a flattened static parser baseline",
4561            );
4562            assert!(
4563                overlay.segmented_parser_components.len() == 2,
4564                "new segmented saves must retain the parent and child A components exactly",
4565            );
4566            assert!(overlay
4567                .segmented_parser_components
4568                .iter()
4569                .all(|component| component.root_disallowed_terminal.is_none()));
4570            assert_eq!(
4571                loaded.start().mask(),
4572                live_mask,
4573                "all-static segmented A+B changed across save/load (dynamic_boundary={dynamic_boundary})",
4574            );
4575
4576            let mut state = loaded.start();
4577            assert!(state.commit_token(2));
4578            assert!(state.is_accepting());
4579
4580            let mut live_state = bound.start();
4581            let mut loaded_state = loaded.start();
4582            for token in [0, 1] {
4583                assert_eq!(
4584                    loaded_state.mask(),
4585                    live_state.mask(),
4586                    "all-static segmented state changed after round-trip before token {token} (dynamic_boundary={dynamic_boundary})",
4587                );
4588                assert!(live_state.commit_token(token));
4589                assert!(loaded_state.commit_token(token));
4590            }
4591            assert_eq!(loaded_state.is_accepting(), live_state.is_accepting());
4592            assert!(loaded_state.is_accepting());
4593        }
4594    }
4595
4596    #[test]
4597    fn composed_dynamic_constraint_transfer_roundtrip_preserves_recursive_runtime() {
4598        let vocab = Vocab::from_entries_unchecked(vec![
4599            (0, b"x".to_vec()),
4600            (1, b"y".to_vec()),
4601            (2, b"xy".to_vec()),
4602            (3, b"xyz".to_vec()),
4603        ]);
4604        let reference = RuntimeConstraint::compile(
4605            Grammar::ebnf(r#"start ::= "x" "y""#),
4606            &vocab,
4607        )
4608        .unwrap();
4609        let parent = native_dynamic_fixture(
4610            Grammar::glrm(
4611                "glrm 1; start start; extern grammar child; nt start = \"x\" child;",
4612            ),
4613            &vocab,
4614        )
4615        .unwrap();
4616        let child = native_dynamic_fixture(Grammar::ebnf(r#"start ::= "y""#), &vocab)
4617            .unwrap();
4618
4619        for dynamic_boundary in [false, true] {
4620            let bound = if dynamic_boundary {
4621                parent
4622                    .bind_grammar_dynamic_boundary("child", &child)
4623                    .unwrap()
4624            } else {
4625                parent.bind_grammar("child", &child).unwrap()
4626            };
4627            assert_eq!(bound.start().mask(), reference.start().mask());
4628
4629            let transfer = bound.clone().into_saved();
4630            let loaded = DynamicConstraint::load_with_vocab(&transfer, &vocab).unwrap();
4631            assert_eq!(
4632                loaded.start().mask(),
4633                bound.start().mask(),
4634                "composed dynamic transfer changed initial mask (dynamic_boundary={dynamic_boundary})",
4635            );
4636            let mut state = loaded.start();
4637            assert!(state.commit_token(2));
4638            assert!(state.is_accepting());
4639        }
4640    }
4641
4642    #[test]
4643    fn dynamic_boundary_token_triggers_survive_component_roundtrip() {
4644        let vocab = Vocab::from_entries_unchecked(vec![
4645            (0, b"x".to_vec()),
4646            (1, b"y".to_vec()),
4647            (2, b"xy".to_vec()),
4648            (3, b"z".to_vec()),
4649        ]);
4650        let reference = RuntimeConstraint::compile(
4651            Grammar::ebnf(r#"start ::= "x" "y""#),
4652            &vocab,
4653        )
4654        .unwrap();
4655        let mut parent = RuntimeConstraint::compile(
4656            Grammar::glrm(
4657                "glrm 1; start start; extern grammar child; nt start = \"x\" child;",
4658            ),
4659            &vocab,
4660        )
4661        .unwrap();
4662        let mut child = RuntimeConstraint::compile(
4663            Grammar::ebnf(r#"start ::= "y""#),
4664            &vocab,
4665        )
4666        .unwrap();
4667
4668        parent.build_boundary_token_trigger().unwrap();
4669        child.build_boundary_token_trigger().unwrap();
4670        assert!(parent
4671            .boundary_trigger
4672            .token_summary()
4673            .expect("parent token trigger must be built")
4674            .contains(&2));
4675
4676        let loaded_parent = RuntimeConstraint::load_body_external_artifact(parent.save(), &vocab).unwrap();
4677        let loaded_child = RuntimeConstraint::load(child.save(), &vocab).unwrap();
4678        let bound = loaded_parent
4679            .bind_grammar_dynamic_boundary("child", loaded_child)
4680            .unwrap();
4681        assert_eq!(bound.start().mask(), reference.start().mask());
4682
4683        let overlay = bound
4684            .static_dynamic_overlay
4685            .as_ref()
4686            .expect("dynamic composition must retain component runtime metadata");
4687        let parent_tokens = overlay.segmented_parser_components[0]
4688            .constraint
4689            .boundary_trigger
4690            .token_summary()
4691            .expect("parent Tokens trigger must survive save/load");
4692        let child_tokens = overlay.segmented_parser_components[1]
4693            .constraint
4694            .boundary_trigger
4695            .token_summary()
4696            .expect("child Tokens trigger must survive save/load");
4697        assert!(parent_tokens.contains(&2));
4698        assert!(child_tokens.iter().all(|&token| token < 4));
4699    }
4700
4701    #[test]
4702    fn exact_boundary_triggers_roundtrip_and_gate_entry_and_finish() {
4703        let vocab = Vocab::from_entries_unchecked(vec![
4704            (0, b"x".to_vec()),
4705            (1, b"y".to_vec()),
4706            (2, b"z".to_vec()),
4707            (3, b"xy".to_vec()),
4708            (4, b"yz".to_vec()),
4709            (5, b"xyz".to_vec()),
4710        ]);
4711        let reference = RuntimeConstraint::compile(
4712            Grammar::ebnf(r#"start ::= "x" "y" "z""#),
4713            &vocab,
4714        )
4715        .unwrap();
4716        let mut parent = RuntimeConstraint::compile(
4717            Grammar::glrm(
4718                "glrm 1; start start; extern grammar child; nt start = \"x\" child \"z\";",
4719            ),
4720            &vocab,
4721        )
4722        .unwrap();
4723        let mut child = RuntimeConstraint::compile(
4724            Grammar::ebnf(r#"start ::= "y""#),
4725            &vocab,
4726        )
4727        .unwrap();
4728
4729        parent.build_exact_boundary_trigger().unwrap();
4730        child.build_exact_boundary_trigger().unwrap();
4731        assert!(matches!(
4732            parent.boundary_trigger,
4733            crate::runtime::BoundaryTrigger::Exact(_)
4734        ));
4735        assert!(matches!(
4736            child.boundary_trigger,
4737            crate::runtime::BoundaryTrigger::Exact(_)
4738        ));
4739
4740        let loaded_parent = RuntimeConstraint::load_body_external_artifact(parent.save(), &vocab).unwrap();
4741        let loaded_child = RuntimeConstraint::load(child.save(), &vocab).unwrap();
4742        let bound = loaded_parent
4743            .bind_grammar_dynamic_boundary("child", loaded_child)
4744            .unwrap();
4745        let overlay = bound
4746            .static_dynamic_overlay
4747            .as_ref()
4748            .expect("dynamic composition must retain component runtime metadata");
4749        assert!(overlay.segmented_parser_components.iter().all(|component| {
4750            matches!(
4751                component.constraint.boundary_trigger,
4752                crate::runtime::BoundaryTrigger::Exact(_)
4753            )
4754        }));
4755
4756        for tokens in [&[5][..], &[0, 4][..], &[3, 2][..], &[0, 1, 2][..]] {
4757            let mut actual = bound.start();
4758            let mut expected = reference.start();
4759            for &token in tokens {
4760                assert_eq!(
4761                    actual.mask(),
4762                    expected.mask(),
4763                    "Exact-trigger dynamic boundary mismatch before {tokens:?} token {token}",
4764                );
4765                assert!(actual.commit_token(token));
4766                assert!(expected.commit_token(token));
4767            }
4768            assert_eq!(actual.is_accepting(), expected.is_accepting(), "{tokens:?}");
4769            assert!(actual.is_accepting(), "{tokens:?}");
4770        }
4771    }
4772
4773    #[test]
4774    fn exact_trigger_supports_control_bearing_composed_component() {
4775        let vocab = Vocab::from_entries_unchecked(vec![
4776            (0, b"<".to_vec()),
4777            (1, b"a".to_vec()),
4778            (2, b">".to_vec()),
4779            (3, b"!".to_vec()),
4780            (4, b"<a>!".to_vec()),
4781            (5, b"a>!".to_vec()),
4782            (6, b">!".to_vec()),
4783        ]);
4784
4785        let inner_parent = RuntimeConstraint::compile(
4786            Grammar::glrm(
4787                r#"glrm 1; start inner; extern grammar leaf; nt inner = "<" leaf ">";"#,
4788            ),
4789            &vocab,
4790        )
4791        .unwrap();
4792        let leaf = RuntimeConstraint::compile(Grammar::ebnf(r#"start ::= "a""#), &vocab)
4793            .unwrap();
4794        let mut inner = inner_parent
4795            .bind_grammar_dynamic_boundary("leaf", leaf)
4796            .unwrap();
4797        assert_recursive_compiler_views_detached(&inner);
4798        assert!(
4799            inner.parser_has_controls(),
4800            "fixture must exercise Exact construction over explicit native linker controls",
4801        );
4802        inner.build_exact_boundary_trigger().unwrap();
4803        assert_recursive_compiler_views_detached(&inner);
4804        assert!(matches!(
4805            inner.boundary_trigger,
4806            crate::runtime::BoundaryTrigger::Exact(_)
4807        ));
4808
4809        let outer = RuntimeConstraint::compile(
4810            Grammar::glrm(
4811                r#"glrm 1; start document; extern grammar inner; nt document = inner "!";"#,
4812            ),
4813            &vocab,
4814        )
4815        .unwrap();
4816        let composed = outer
4817            .bind_grammar_dynamic_boundary("inner", RuntimeConstraint::load(inner.save(), &vocab).unwrap())
4818            .unwrap();
4819        let reference = RuntimeConstraint::compile(
4820            Grammar::ebnf(r#"start ::= "<" "a" ">" "!""#),
4821            &vocab,
4822        )
4823        .unwrap();
4824
4825        let overlay = composed.static_dynamic_overlay.as_ref().unwrap();
4826        assert!(matches!(
4827            overlay.segmented_parser_components[1]
4828                .constraint
4829                .boundary_trigger,
4830            crate::runtime::BoundaryTrigger::Exact(_)
4831        ));
4832
4833        for tokens in [&[4][..], &[0, 5][..], &[0, 1, 6][..], &[0, 1, 2, 3][..]] {
4834            let mut actual = composed.start();
4835            let mut expected = reference.start();
4836            for &token in tokens {
4837                assert_eq!(
4838                    actual.mask(),
4839                    expected.mask(),
4840                    "control-bearing Exact trigger mismatch before {tokens:?} token {token}",
4841                );
4842                assert!(actual.commit_token(token));
4843                assert!(expected.commit_token(token));
4844            }
4845            assert_eq!(actual.is_accepting(), expected.is_accepting(), "{tokens:?}");
4846            assert!(actual.is_accepting(), "{tokens:?}");
4847        }
4848    }
4849
4850    #[test]
4851    fn loaded_constraint_trigger_upgrade_resaves_updated_link_metadata() {
4852        let vocab = Vocab::from_entries_unchecked(vec![
4853            (0, b"x".to_vec()),
4854            (1, b"y".to_vec()),
4855            (2, b"xy".to_vec()),
4856        ]);
4857        let parent = RuntimeConstraint::compile(
4858            Grammar::glrm(
4859                "glrm 1; start start; extern grammar child; nt start = \"x\" child;",
4860            ),
4861            &vocab,
4862        )
4863        .unwrap();
4864        let child = RuntimeConstraint::compile(Grammar::ebnf(r#"start ::= "y""#), &vocab)
4865            .unwrap();
4866
4867        let mut loaded = RuntimeConstraint::load_body_external_artifact(parent.save(), &vocab).unwrap();
4868        assert!(loaded.deferred_composition_metadata_blob.is_some());
4869        loaded.build_exact_boundary_trigger().unwrap();
4870        assert!(matches!(
4871            loaded.boundary_trigger,
4872            crate::runtime::BoundaryTrigger::Exact(_)
4873        ));
4874        assert!(
4875            loaded.deferred_composition_metadata_blob.is_some(),
4876            "trigger upgrade should not force materialization of the heavy parser-cache section",
4877        );
4878
4879        let reloaded = RuntimeConstraint::load_body_external_artifact(loaded.save(), &vocab).unwrap();
4880        let bound = reloaded
4881            .bind_grammar_dynamic_boundary("child", child)
4882            .unwrap();
4883        let overlay = bound.static_dynamic_overlay.as_ref().unwrap();
4884        assert!(matches!(
4885            overlay.segmented_parser_components[0]
4886                .constraint
4887                .boundary_trigger,
4888            crate::runtime::BoundaryTrigger::Exact(_)
4889        ));
4890        assert_ne!(bound.start().mask()[0] & (1 << 2), 0);
4891    }
4892
4893    #[test]
4894    fn exact_triggers_survive_outer_runtime_lexer_product_multi_source_states() {
4895        let vocab = Vocab::from_entries_unchecked(vec![
4896            (0, b"a".to_vec()),
4897            (1, b"b".to_vec()),
4898            (2, b"c".to_vec()),
4899            (3, b"!".to_vec()),
4900            (4, b"?".to_vec()),
4901            (5, b"c!".to_vec()),
4902            (6, b"c?".to_vec()),
4903        ]);
4904        let child_spec = ConstraintSpec::builder(
4905            Grammar::ebnf(r#"start ::= "a" "b" "c""#),
4906            &vocab,
4907        )
4908        .unwrap()
4909        .boundary_trigger_detail(crate::BoundaryTriggerDetail::Exact)
4910        .build()
4911        .unwrap();
4912        let child = child_spec.compile_native_dynamic_fixture().unwrap();
4913        // Keep one child component so its local-LR -> composed-LR relation is
4914        // functional, while the parent also has an equivalent local lexical
4915        // lane. The outer lexer product can then coalesce parent + child lanes
4916        // after `a`/`b` without relying on duplicate child call sites.
4917        let parent = Grammar::glrm(
4918            "glrm 1; start document; extern grammar child; \
4919             nt document = child \"!\" | \"a\" \"b\" \"c\" \"?\";",
4920        );
4921        let composed = ConstraintSpec::builder(parent, &vocab)
4922            .unwrap()
4923            .bind_grammar("child", &child)
4924            .unwrap()
4925            .build()
4926            .unwrap()
4927            .compile_native_dynamic_fixture()
4928            .unwrap();
4929        let alternatives = composed.clone_constraints();
4930        assert_eq!(alternatives.len(), 1);
4931        let composed = &alternatives[0];
4932        let reference = RuntimeConstraint::compile(
4933            Grammar::ebnf(r#"start ::= "a" "b" "c" "!" | "a" "b" "c" "?""#),
4934            &vocab,
4935        )
4936        .unwrap();
4937
4938        let explicitly_disabled = crate::env::var("GLRMASK_COMPOSE_RUNTIME_LEXER_PRODUCT")
4939            .ok()
4940            .is_some_and(|value| {
4941                matches!(
4942                    value.trim().to_ascii_lowercase().as_str(),
4943                    "" | "0" | "false" | "no" | "off"
4944                )
4945            });
4946
4947        let mut actual = composed.start();
4948        let mut expected = reference.start();
4949        for token in [0, 1] {
4950            assert_eq!(actual.mask(), expected.mask());
4951            assert!(actual.commit_token(token));
4952            assert!(expected.commit_token(token));
4953        }
4954
4955        if !explicitly_disabled
4956            && let Some(source_offset) = composed.runtime_source_state_offset()
4957        {
4958            let product_state = *actual.state.keys().next().unwrap();
4959            assert!(product_state < source_offset);
4960            assert!(
4961                composed
4962                    .runtime_product_source_states(product_state)
4963                    .is_some_and(|sources| sources.len() >= 2),
4964                "a selected outer product state must preserve every represented lexer lane",
4965            );
4966        }
4967
4968        let mask = actual.mask();
4969        let reference_mask = expected.mask();
4970        assert_eq!(mask, reference_mask);
4971        assert_ne!(mask[0] & (1 << 5), 0, "c! must cross child -> parent internally");
4972        assert_ne!(mask[0] & (1 << 6), 0, "c? must remain valid on the parent-local branch");
4973    }
4974
4975    #[test]
4976    fn exact_trigger_detail_is_independent_of_dynamic_component_compilation() {
4977        let vocab = Vocab::from_entries_unchecked(vec![
4978            (0, b"y".to_vec()),
4979            (1, b"z".to_vec()),
4980            (2, b"yz".to_vec()),
4981        ]);
4982        let spec = ConstraintSpec::builder(Grammar::ebnf(r#"start ::= "y""#), &vocab)
4983            .unwrap()
4984            .boundary_trigger_detail(crate::BoundaryTriggerDetail::Exact)
4985            .build()
4986            .unwrap();
4987
4988        let static_constraint = spec.compile().unwrap();
4989        assert!(matches!(
4990            static_constraint.boundary_trigger,
4991            crate::runtime::BoundaryTrigger::Exact(_)
4992        ));
4993
4994        let dynamic_constraint = spec.compile_native_dynamic_fixture().unwrap();
4995        assert!(dynamic_constraint.clone_constraints().iter().all(|constraint| {
4996            matches!(constraint.boundary_trigger, crate::runtime::BoundaryTrigger::Exact(_))
4997        }));
4998
4999        let loaded_dynamic = DynamicConstraint::load(&dynamic_constraint.save(), &vocab).unwrap();
5000        assert!(loaded_dynamic.clone_constraints().iter_mut().all(|constraint| {
5001            constraint.materialize_composition_link_metadata_for_compilation().unwrap();
5002            matches!(constraint.boundary_trigger, crate::runtime::BoundaryTrigger::Exact(_))
5003        }));
5004
5005        let transfer = dynamic_constraint.clone().into_saved();
5006        let loaded_transfer = DynamicConstraint::load_with_vocab(&transfer, &vocab).unwrap();
5007        assert!(loaded_transfer.clone_constraints().iter_mut().all(|constraint| {
5008            constraint.materialize_composition_link_metadata_for_compilation().unwrap();
5009            matches!(constraint.boundary_trigger, crate::runtime::BoundaryTrigger::Exact(_))
5010        }));
5011    }
5012
5013    #[test]
5014    fn boundary_token_trigger_follows_lexeme_resets_inside_model_token() {
5015        let vocab = Vocab::from_entries_unchecked(vec![
5016            (0, b"x".to_vec()),
5017            (1, b"q".to_vec()),
5018            (2, b"y".to_vec()),
5019            (3, b"xqy".to_vec()),
5020        ]);
5021        let mut parent = RuntimeConstraint::compile(
5022            Grammar::glrm(
5023                "glrm 1; start start; extern grammar child; nt start = \"x\" \"q\" child;",
5024            ),
5025            &vocab,
5026        )
5027        .unwrap();
5028        parent.build_boundary_token_trigger().unwrap();
5029        assert!(
5030            parent
5031                .boundary_trigger
5032                .token_summary()
5033                .expect("Tokens trigger must be built")
5034                .contains(&3),
5035            "a token that reaches the child only after multiple local lexemes must remain boundary-relevant",
5036        );
5037
5038        let child = RuntimeConstraint::compile(Grammar::ebnf(r#"start ::= "y""#), &vocab)
5039            .unwrap();
5040        let bound = parent
5041            .bind_grammar_dynamic_boundary("child", child)
5042            .unwrap();
5043        assert_ne!(bound.start().mask()[0] & (1 << 3), 0);
5044    }
5045
5046    #[test]
5047    fn nested_dynamic_boundaries_preserve_token_crossing_leaf_middle_and_outer() {
5048        let vocab = Vocab::from_entries_unchecked(vec![
5049            (0, b"X".to_vec()),
5050            (1, b"[".to_vec()),
5051            (2, b"a".to_vec()),
5052            (3, b"]".to_vec()),
5053            (4, b"!".to_vec()),
5054            (5, b"a]!".to_vec()),
5055            (6, b"[a]!".to_vec()),
5056            (7, b"X[a]!".to_vec()),
5057        ]);
5058        let leaf = RuntimeConstraint::compile(
5059            Grammar::glrm("glrm 1; start leaf; nt leaf = \"a\";"),
5060            &vocab,
5061        )
5062        .unwrap();
5063        let middle_parent = RuntimeConstraint::compile(
5064            Grammar::glrm(
5065                "glrm 1; start middle; extern grammar leaf; nt middle = \"[\" leaf \"]\";",
5066            ),
5067            &vocab,
5068        )
5069        .unwrap();
5070        let middle = middle_parent
5071            .bind_grammar_dynamic_boundary("leaf", leaf)
5072            .unwrap();
5073        let outer_parent = RuntimeConstraint::compile(
5074            Grammar::glrm(
5075                "glrm 1; start document; extern grammar middle; nt document = \"X\" middle \"!\";",
5076            ),
5077            &vocab,
5078        )
5079        .unwrap();
5080        let bound = outer_parent
5081            .bind_grammar_dynamic_boundary("middle", middle)
5082            .unwrap();
5083        let monolithic = RuntimeConstraint::compile(
5084            Grammar::glrm("glrm 1; start document; nt document = \"X\" \"[\" \"a\" \"]\" \"!\";"),
5085            &vocab,
5086        )
5087        .unwrap();
5088
5089        let loaded = RuntimeConstraint::load(bound.save(), &vocab).unwrap();
5090        assert_recursive_compiler_views_detached(&bound);
5091        assert_recursive_compiler_views_detached(&loaded);
5092        let mut no_trigger = bound.clone();
5093        {
5094            let overlay = no_trigger.static_dynamic_overlay.as_mut().unwrap();
5095            for component in &mut overlay.segmented_parser_components {
5096                let Some(shard) = component.boundary.as_mut() else {
5097                    continue;
5098                };
5099                if !matches!(
5100                    shard.backend,
5101                    crate::runtime::SegmentedBoundaryShardBackend::DynamicDirect
5102                ) {
5103                    continue;
5104                }
5105                shard.candidate_tokens = None;
5106                std::sync::Arc::make_mut(&mut component.constraint).boundary_trigger =
5107                    crate::runtime::BoundaryTrigger::None;
5108            }
5109        }
5110        let mut no_outer_tokenizer = loaded.clone();
5111        {
5112            let root = no_outer_tokenizer
5113                .static_dynamic_overlay
5114                .as_ref()
5115                .unwrap()
5116                .segmented_parser_components[0]
5117                .constraint
5118                .clone();
5119            no_outer_tokenizer.tokenizer = root.tokenizer.clone();
5120            no_outer_tokenizer.tokenizer_fast_transitions =
5121                root.tokenizer_fast_transitions.clone();
5122            no_outer_tokenizer.tokenizer_has_epsilon_transitions =
5123                root.tokenizer_has_epsilon_transitions;
5124        }
5125        let mut no_outer_table = loaded.clone();
5126        assert_no_materialized_outer_table(&mut no_outer_table);
5127        for constraint in [
5128            &bound,
5129            &loaded,
5130            &no_trigger,
5131            &no_outer_tokenizer,
5132            &no_outer_table,
5133        ] {
5134            let mut pending = vec![Vec::<u32>::new()];
5135            while let Some(path) = pending.pop() {
5136                let mut actual = constraint.start();
5137                let mut expected = monolithic.start();
5138                for &token in &path {
5139                    assert!(actual.commit_token(token));
5140                    assert!(expected.commit_token(token));
5141                }
5142                let actual_mask = actual.mask();
5143                let expected_mask = expected.mask();
5144                assert_eq!(actual_mask, expected_mask, "mask mismatch at {path:?}");
5145                assert_eq!(
5146                    actual.is_accepting(),
5147                    expected.is_accepting(),
5148                    "acceptance mismatch at {path:?}",
5149                );
5150                if path.len() == 5 {
5151                    continue;
5152                }
5153                for token in 0..8u32 {
5154                    if actual_mask
5155                        .get(token as usize / 32)
5156                        .is_none_or(|word| *word & (1u32 << (token % 32)) == 0)
5157                    {
5158                        continue;
5159                    }
5160                    let mut next = path.clone();
5161                    next.push(token);
5162                    pending.push(next);
5163                }
5164            }
5165        }
5166
5167        for tokens in [
5168            &[7][..],
5169            &[0, 6][..],
5170            &[0, 1, 5][..],
5171            &[0, 1, 2, 3, 4][..],
5172        ] {
5173            let mut actual = bound.start();
5174            let mut expected = monolithic.start();
5175            for &token in tokens {
5176                assert_eq!(actual.mask(), expected.mask(), "before {tokens:?} token {token}");
5177                assert!(actual.commit_token(token));
5178                assert!(expected.commit_token(token));
5179            }
5180            assert_eq!(actual.is_accepting(), expected.is_accepting(), "{tokens:?}");
5181            assert!(actual.is_accepting(), "{tokens:?}");
5182        }
5183    }
5184
5185    #[test]
5186    fn recursive_live_parser_expands_static_nested_component_with_native_boundary() {
5187        let vocab = Vocab::from_entries_unchecked(vec![
5188            (0, b"X".to_vec()),
5189            (1, b"[".to_vec()),
5190            (2, b"a".to_vec()),
5191            (3, b"]".to_vec()),
5192            (4, b"!".to_vec()),
5193            (5, b"a]!".to_vec()),
5194            (6, b"[a]!".to_vec()),
5195            (7, b"X[a]!".to_vec()),
5196        ]);
5197        let leaf = RuntimeConstraint::compile(
5198            Grammar::glrm("glrm 1; start leaf; nt leaf = \"a\";"),
5199            &vocab,
5200        )
5201        .unwrap();
5202        let middle_parent = RuntimeConstraint::compile(
5203            Grammar::glrm(
5204                "glrm 1; start middle; extern grammar leaf; nt middle = \"[\" leaf \"]\";",
5205            ),
5206            &vocab,
5207        )
5208        .unwrap();
5209        // Static B is transported exactly onto the recursive parser coordinate,
5210        // so the middle wrapper can expose its intact parent/child leaves.
5211        let middle = middle_parent.bind_grammar("leaf", leaf).unwrap();
5212        assert!(middle.uses_compact_segmented_parser_runtime());
5213        let outer_parent = RuntimeConstraint::compile(
5214            Grammar::glrm(
5215                "glrm 1; start document; extern grammar middle; nt document = \"X\" middle \"!\";",
5216            ),
5217            &vocab,
5218        )
5219        .unwrap();
5220        let bound = outer_parent
5221            .bind_grammar_dynamic_boundary("middle", middle)
5222            .unwrap();
5223        let layout = bound.recursive_parser_layout().unwrap().unwrap();
5224        assert_eq!(layout.leaves.len(), 3);
5225        let monolithic = RuntimeConstraint::compile(
5226            Grammar::glrm("glrm 1; start document; nt document = \"X\" \"[\" \"a\" \"]\" \"!\";"),
5227            &vocab,
5228        )
5229        .unwrap();
5230
5231        for constraint in [&bound, &RuntimeConstraint::load(bound.save(), &vocab).unwrap()] {
5232            for tokens in [
5233                &[7][..],
5234                &[0, 6][..],
5235                &[0, 1, 5][..],
5236                &[0, 1, 2, 3, 4][..],
5237            ] {
5238                let mut actual = constraint.start();
5239                let mut expected = monolithic.start();
5240                for &token in tokens {
5241                    assert_eq!(actual.mask(), expected.mask(), "before {tokens:?} token {token}");
5242                    assert!(actual.commit_token(token));
5243                    assert!(expected.commit_token(token));
5244                }
5245                assert_eq!(actual.is_accepting(), expected.is_accepting(), "{tokens:?}");
5246                assert!(actual.is_accepting(), "{tokens:?}");
5247            }
5248        }
5249    }
5250
5251    #[test]
5252    fn recursive_special_token_routes_through_active_child_leaf_and_returns_to_parent() {
5253        let vocab = Vocab::from_entries_unchecked(vec![(0, b"X".to_vec()), (1, b"!".to_vec()), (100, b"[100]".to_vec())]);
5254        let child = RuntimeConstraint::compile(
5255            Grammar::from_glrm("start child; extern token CHILD_TOKEN; nt child = CHILD_TOKEN;")
5256                .unwrap()
5257                .bind_snapshot("CHILD_TOKEN", crate::TokenSet::new([100]))
5258                .unwrap(),
5259            &vocab,
5260        )
5261        .unwrap();
5262        let parent = RuntimeConstraint::compile(
5263            Grammar::glrm(
5264                "glrm 1; start document; extern grammar child; nt document = \"X\" child \"!\";",
5265            ),
5266            &vocab,
5267        )
5268        .unwrap();
5269        let bound = parent.bind_grammar("child", child).unwrap();
5270        assert!(bound.uses_compact_segmented_parser_runtime());
5271
5272        let loaded = RuntimeConstraint::load(bound.save(), &vocab).unwrap();
5273        let mut no_outer_table = loaded.clone();
5274        assert_no_materialized_outer_table(&mut no_outer_table);
5275        for constraint in [&bound, &loaded, &no_outer_table] {
5276            let mut state = constraint.start();
5277            assert!(state.commit_token(0));
5278            let mask = state.mask();
5279            assert_ne!(mask[100 / 32] & (1u32 << (100 % 32)), 0);
5280
5281            assert!(state.commit_token(100));
5282            let mask = state.mask();
5283            assert_ne!(mask[1 / 32] & (1u32 << 1), 0);
5284
5285            assert!(state.commit_token(1));
5286            assert!(state.is_accepting());
5287        }
5288    }
5289
5290    #[test]
5291    fn recursive_static_virtual_residual_child_handles_fused_boundaries_and_roundtrip() {
5292        let vocab = Vocab::from_entries_unchecked(vec![
5293            (0, b"X".to_vec()),
5294            (1, b"!".to_vec()),
5295            (2, b"\"".to_vec()),
5296            (3, b"x:".to_vec()),
5297            (4, b"a".to_vec()),
5298            (5, b"X\"".to_vec()),
5299            (6, b"\"!".to_vec()),
5300            (7, b"xa".to_vec()),
5301            (8, b":".to_vec()),
5302            (9, b"X\"x:".to_vec()),
5303            (10, b"a\"!".to_vec()),
5304            (11, b"aa".to_vec()),
5305            (12, b"a\"".to_vec()),
5306        ]);
5307        let schema = r#"{"type":"string","format":"uri","pattern":"^[a-z][a-z0-9+.-]*:[a-z]*$","minLength":1,"maxLength":5000}"#;
5308        let child = RuntimeConstraint::from_json_schema(
5309            schema,
5310            &vocab,
5311        )
5312        .unwrap();
5313        assert!(child.tokenizer.has_virtual_residual_runtime());
5314
5315        let parent = RuntimeConstraint::compile(
5316            Grammar::glrm(
5317                "glrm 1; start document; extern grammar payload; nt document = \"X\" payload \"!\";",
5318            ),
5319            &vocab,
5320        )
5321        .unwrap();
5322        let static_bound = parent.bind_grammar("payload", &child).unwrap();
5323        assert!(static_bound.static_dynamic_overlay.as_ref().unwrap()
5324            .segmented_boundary_shards.iter().all(|shard| !matches!(
5325                shard.backend, crate::runtime::SegmentedBoundaryShardBackend::DynamicDirect)));
5326        let static_loaded = RuntimeConstraint::load(static_bound.save(), &vocab).unwrap();
5327        let bound = parent
5328            .bind_grammar_dynamic_boundary("payload", child)
5329            .unwrap();
5330        let loaded = RuntimeConstraint::load(bound.save(), &vocab).unwrap();
5331        // Keep the schema's exact internal regular nodes; source serialization
5332        // is not the composition protocol and may intentionally have a narrower
5333        // syntax than the JSON frontend's already constructed representation.
5334        let child_named = crate::import::parse_json_schema_to_named(schema).unwrap();
5335        let named = crate::grammar::glrm::from_glrm_with_named_subgrammars_and_external_terminals(
5336            r#"start document extern grammar payload nt document = "X" payload "!""#,
5337            &[("payload", child_named)], &[],
5338        ).unwrap();
5339        let inline = crate::import::compile_from_named_grammar(named, &vocab,
5340            "virtual_uri_inline_reference", crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,
5341            &[]).unwrap();
5342
5343        let token_allowed = |mask: &[u32], token: u32| {
5344            mask[token as usize / 32] & (1u32 << (token % 32)) != 0
5345        };
5346        for constraint in [&static_bound, &static_loaded, &bound, &loaded] {
5347            let mut state = constraint.start();
5348            let mut reference = inline.start();
5349            assert_eq!(state.mask(), reference.mask());
5350            assert!(token_allowed(&state.mask(), 9));
5351            assert!(state.commit_token(9));
5352            assert!(reference.commit_token(9));
5353            assert_eq!(state.mask(), reference.mask());
5354            assert!(token_allowed(&state.mask(), 10));
5355            assert!(state.commit_token(10));
5356            assert!(reference.commit_token(10));
5357            assert_eq!(state.mask(), reference.mask());
5358            assert_eq!(state.is_accepting(), reference.is_accepting());
5359            assert!(state.is_accepting());
5360
5361            let mut exact = constraint.start();
5362            let mut exact_bytes = b"X\"x:".to_vec();
5363            exact_bytes.extend(std::iter::repeat_n(b'a', 4998));
5364            exact_bytes.extend_from_slice(b"\"!");
5365            assert!(exact.commit_bytes(&exact_bytes));
5366            assert!(exact.is_accepting());
5367
5368            let mut over = constraint.start();
5369            let mut over_bytes = b"X\"x:".to_vec();
5370            over_bytes.extend(std::iter::repeat_n(b'a', 4999));
5371            over_bytes.extend_from_slice(b"\"!");
5372            assert!(!over.commit_bytes(&over_bytes));
5373        }
5374    }
5375
5376    #[test]
5377    fn nested_boundaries_use_recursive_parser_coordinate_live_and_loaded() {
5378        let vocab = Vocab::from_entries_unchecked(vec![
5379            (0, b"X".to_vec()),
5380            (1, b"[".to_vec()),
5381            (2, b"a".to_vec()),
5382            (3, b"]".to_vec()),
5383            (4, b"!".to_vec()),
5384            (5, b"a]!".to_vec()),
5385            (6, b"[a]!".to_vec()),
5386            (7, b"X[a]!".to_vec()),
5387        ]);
5388        let leaf = RuntimeConstraint::compile(
5389            Grammar::glrm("glrm 1; start leaf; nt leaf = \"a\";"),
5390            &vocab,
5391        )
5392        .unwrap();
5393        let middle_parent = RuntimeConstraint::compile(
5394            Grammar::glrm(
5395                "glrm 1; start middle; extern grammar leaf; nt middle = \"[\" leaf \"]\";",
5396            ),
5397            &vocab,
5398        )
5399        .unwrap();
5400        let middle = middle_parent.bind_grammar("leaf", leaf).unwrap();
5401        assert!(middle.uses_compact_segmented_parser_runtime());
5402
5403        let outer_parent = RuntimeConstraint::compile(
5404            Grammar::glrm(
5405                "glrm 1; start document; extern grammar middle; nt document = \"X\" middle \"!\";",
5406            ),
5407            &vocab,
5408        )
5409        .unwrap();
5410        let bound = outer_parent
5411            .bind_grammar_dynamic_boundary("middle", middle)
5412            .unwrap();
5413        assert!(bound.uses_compact_segmented_parser_runtime());
5414        assert!(
5415            bound
5416                .static_dynamic_overlay
5417                .as_ref()
5418                .unwrap()
5419                .segmented_component_union_root_dispatch
5420                .is_empty(),
5421            "recursive runtime must not retain materialized-state component dispatch",
5422        );
5423        assert!(
5424            bound
5425                .static_dynamic_overlay
5426                .as_ref()
5427                .unwrap()
5428                .segmented_parser_state_offsets
5429                .is_empty(),
5430            "recursive runtime must derive state intervals from its component tree",
5431        );
5432        let bound_overlay = bound.static_dynamic_overlay.as_ref().unwrap();
5433        assert!(bound_overlay.segmented_boundary_shards.iter().all(|shard| {
5434            shard.start_parser_states.is_empty()
5435        }));
5436        assert!(bound_overlay.segmented_parser_components.iter().all(|component| {
5437            component
5438                .boundary
5439                .as_ref()
5440                .is_none_or(|shard| shard.start_parser_states.is_empty())
5441        }));
5442        let layout = bound.recursive_parser_layout().unwrap().unwrap();
5443        assert_eq!(layout.leaves.len(), 3);
5444
5445        let loaded = RuntimeConstraint::load(bound.save(), &vocab).unwrap();
5446        assert!(loaded.uses_compact_segmented_parser_runtime());
5447        assert!(
5448            loaded
5449                .static_dynamic_overlay
5450                .as_ref()
5451                .unwrap()
5452                .segmented_component_union_root_dispatch
5453                .is_empty(),
5454        );
5455        assert!(
5456            loaded
5457                .static_dynamic_overlay
5458                .as_ref()
5459                .unwrap()
5460                .segmented_parser_state_offsets
5461                .is_empty(),
5462        );
5463        let loaded_overlay = loaded.static_dynamic_overlay.as_ref().unwrap();
5464        assert!(loaded_overlay.segmented_boundary_shards.iter().all(|shard| {
5465            shard.start_parser_states.is_empty()
5466        }));
5467        assert!(loaded_overlay.segmented_parser_components.iter().all(|component| {
5468            component
5469                .boundary
5470                .as_ref()
5471                .is_none_or(|shard| shard.start_parser_states.is_empty())
5472        }));
5473        assert_eq!(loaded.recursive_parser_layout().unwrap().unwrap().leaves.len(), 3);
5474
5475        let monolithic = RuntimeConstraint::compile(
5476            Grammar::glrm("glrm 1; start document; nt document = \"X\" \"[\" \"a\" \"]\" \"!\";"),
5477            &vocab,
5478        )
5479        .unwrap();
5480        let mut no_outer_table = loaded.clone();
5481        assert_no_materialized_outer_table(&mut no_outer_table);
5482        fn compare_reachable_prefix_tree(
5483            actual_constraint: &RuntimeConstraint,
5484            expected_constraint: &RuntimeConstraint,
5485            max_depth: usize,
5486        ) {
5487            let mut pending = vec![Vec::<u32>::new()];
5488            while let Some(path) = pending.pop() {
5489                let mut actual = actual_constraint.start();
5490                let mut expected = expected_constraint.start();
5491                for &token in &path {
5492                    assert!(actual.commit_token(token));
5493                    assert!(expected.commit_token(token));
5494                }
5495                let actual_mask = actual.mask();
5496                let expected_mask = expected.mask();
5497                assert_eq!(actual_mask, expected_mask, "mask mismatch at {path:?}");
5498                assert_eq!(
5499                    actual.is_accepting(),
5500                    expected.is_accepting(),
5501                    "acceptance mismatch at {path:?}",
5502                );
5503                if path.len() == max_depth {
5504                    continue;
5505                }
5506                for token in 0..8u32 {
5507                    let word = token as usize / 32;
5508                    let bit = token % 32;
5509                    if actual_mask
5510                        .get(word)
5511                        .is_none_or(|word| *word & (1u32 << bit) == 0)
5512                    {
5513                        continue;
5514                    }
5515                    let mut next = path.clone();
5516                    next.push(token);
5517                    pending.push(next);
5518                }
5519            }
5520        }
5521        for constraint in [&bound, &loaded, &no_outer_table] {
5522            compare_reachable_prefix_tree(constraint, &monolithic, 5);
5523            for tokens in [
5524                &[7][..],
5525                &[0, 6][..],
5526                &[0, 1, 5][..],
5527                &[0, 1, 2, 3, 4][..],
5528            ] {
5529                let mut actual = constraint.start();
5530                let mut expected = monolithic.start();
5531                for &token in tokens {
5532                    assert_eq!(actual.mask(), expected.mask(), "before {tokens:?} token {token}");
5533                    assert!(actual.commit_token(token));
5534                    assert!(expected.commit_token(token));
5535                }
5536                assert_eq!(actual.is_accepting(), expected.is_accepting(), "{tokens:?}");
5537                assert!(actual.is_accepting(), "{tokens:?}");
5538            }
5539        }
5540    }
5541
5542    #[test]
5543    fn nested_static_nullable_wrapper_returns_in_recursive_live_runtime() {
5544        let vocab = Vocab::from_entries_unchecked(vec![
5545            (0, b"X".to_vec()),
5546            (1, b"a".to_vec()),
5547            (2, b"!".to_vec()),
5548            (3, b"X!".to_vec()),
5549            (4, b"Xa!".to_vec()),
5550            (5, b"a!".to_vec()),
5551        ]);
5552        let leaf = RuntimeConstraint::compile(
5553            Grammar::glrm("glrm 1; start leaf; nt leaf = \"a\";"),
5554            &vocab,
5555        )
5556        .unwrap();
5557        let middle_parent = RuntimeConstraint::compile(
5558            Grammar::glrm("glrm 1; start middle; extern grammar leaf; nt middle = leaf?;"),
5559            &vocab,
5560        )
5561        .unwrap();
5562        assert!(middle_parent.composition_start_nullable().unwrap());
5563        let middle = middle_parent.bind_grammar("leaf", leaf).unwrap();
5564        assert!(middle.composition_start_nullable().unwrap());
5565        assert!(middle.uses_compact_segmented_parser_runtime());
5566
5567        let outer_parent = RuntimeConstraint::compile(
5568            Grammar::glrm(
5569                "glrm 1; start document; extern grammar middle; nt document = \"X\" middle \"!\";",
5570            ),
5571            &vocab,
5572        )
5573        .unwrap();
5574        let bound = outer_parent
5575            .bind_grammar_dynamic_boundary("middle", middle)
5576            .unwrap();
5577        assert!(bound.uses_compact_segmented_parser_runtime());
5578        let loaded = RuntimeConstraint::load(bound.save(), &vocab).unwrap();
5579        assert!(loaded.uses_compact_segmented_parser_runtime());
5580        let monolithic = RuntimeConstraint::compile(
5581            Grammar::glrm("glrm 1; start document; nt document = \"X\" \"a\"? \"!\";"),
5582            &vocab,
5583        )
5584        .unwrap();
5585        let mut no_outer_table = loaded.clone();
5586        assert_no_materialized_outer_table(&mut no_outer_table);
5587
5588        for constraint in [&bound, &loaded, &no_outer_table] {
5589            for tokens in [&[3][..], &[4][..], &[0, 2][..], &[0, 5][..], &[0, 1, 2][..]] {
5590                let mut actual = constraint.start();
5591                let mut expected = monolithic.start();
5592                for &token in tokens {
5593                    assert_eq!(actual.mask(), expected.mask(), "before {tokens:?} token {token}");
5594                    assert!(actual.commit_token(token));
5595                    assert!(expected.commit_token(token));
5596                }
5597                assert_eq!(actual.is_accepting(), expected.is_accepting(), "{tokens:?}");
5598                assert!(actual.is_accepting(), "{tokens:?}");
5599            }
5600        }
5601    }
5602
5603    #[test]
5604    fn recursive_parser_layout_flattens_state_coordinate_but_preserves_outer_wrapper_owner() {
5605        let vocab = Vocab::from_entries_unchecked(vec![
5606            (0, b"X".to_vec()),
5607            (1, b"[".to_vec()),
5608            (2, b"a".to_vec()),
5609            (3, b"]".to_vec()),
5610            (4, b"!".to_vec()),
5611        ]);
5612        let leaf = RuntimeConstraint::compile(
5613            Grammar::glrm("glrm 1; start leaf; nt leaf = \"a\";"),
5614            &vocab,
5615        )
5616        .unwrap();
5617        let leaf_states = leaf.parser_symbol_count();
5618        let leaf_tokenizer_states = leaf.tokenizer.num_states();
5619        let leaf_tokenizer_reset = leaf.runtime_commit_initial_state();
5620        let middle_parent = RuntimeConstraint::compile(
5621            Grammar::glrm(
5622                "glrm 1; start middle; extern grammar leaf; nt middle = \"[\" leaf \"]\";",
5623            ),
5624            &vocab,
5625        )
5626        .unwrap();
5627        let middle_parent_states = middle_parent.parser_symbol_count();
5628        let middle_parent_tokenizer_states = middle_parent.tokenizer.num_states();
5629        let middle_parent_tokenizer_reset = middle_parent.runtime_commit_initial_state();
5630        let middle = middle_parent
5631            .bind_grammar_dynamic_boundary("leaf", leaf)
5632            .unwrap();
5633        let outer_parent = RuntimeConstraint::compile(
5634            Grammar::glrm(
5635                "glrm 1; start document; extern grammar middle; nt document = \"X\" middle \"!\";",
5636            ),
5637            &vocab,
5638        )
5639        .unwrap();
5640        let outer_parent_states = outer_parent.parser_symbol_count();
5641        let outer_parent_tokenizer_states = outer_parent.tokenizer.num_states();
5642        let outer_parent_tokenizer_reset = outer_parent.runtime_commit_initial_state();
5643        let bound = outer_parent
5644            .bind_grammar_dynamic_boundary("middle", middle)
5645            .unwrap();
5646
5647        for constraint in [&bound, &RuntimeConstraint::load(bound.save(), &vocab).unwrap()] {
5648            let layout = constraint
5649                .recursive_parser_layout()
5650                .unwrap()
5651                .expect("nested composition must expose a recursive parser layout");
5652            assert_eq!(layout.component_offsets, vec![0, outer_parent_states]);
5653            assert_eq!(layout.leaves.len(), 3);
5654            assert_eq!(
5655                layout
5656                    .leaves
5657                    .iter()
5658                    .map(|leaf| leaf.component_path.clone())
5659                    .collect::<Vec<_>>(),
5660                vec![vec![0], vec![1, 0], vec![1, 1]],
5661            );
5662            assert_eq!(
5663                layout
5664                    .leaves
5665                    .iter()
5666                    .map(|leaf| (leaf.state_offset, leaf.state_count, leaf.top_component))
5667                    .collect::<Vec<_>>(),
5668                vec![
5669                    (0, outer_parent_states, 0),
5670                    (outer_parent_states, middle_parent_states, 1),
5671                    (
5672                        outer_parent_states + middle_parent_states,
5673                        leaf_states,
5674                        1,
5675                    ),
5676                ],
5677            );
5678            assert_eq!(
5679                layout.total_states,
5680                outer_parent_states + middle_parent_states + leaf_states,
5681            );
5682            assert_eq!(
5683                layout.leaf_tokenizer_state_offsets,
5684                vec![
5685                    0,
5686                    outer_parent_tokenizer_states,
5687                    outer_parent_tokenizer_states + middle_parent_tokenizer_states,
5688                ],
5689            );
5690            assert_eq!(
5691                layout.total_tokenizer_states,
5692                outer_parent_tokenizer_states
5693                    + middle_parent_tokenizer_states
5694                    + leaf_tokenizer_states,
5695            );
5696            for (global_terminal, targets) in layout.terminal_targets.iter().enumerate() {
5697                for &(leaf_index, local_terminal) in targets {
5698                    let scoped = constraint
5699                        .recursive_terminal_scoped_id(leaf_index as usize, local_terminal)
5700                        .unwrap();
5701                    assert_eq!(
5702                        constraint.recursive_terminal_leaf_local(scoped),
5703                        Some((leaf_index as usize, local_terminal)),
5704                        "terminal routing lost global={global_terminal} leaf={leaf_index} local={local_terminal}",
5705                    );
5706                }
5707            }
5708            let tokenizer_counts = [
5709                outer_parent_tokenizer_states,
5710                middle_parent_tokenizer_states,
5711                leaf_tokenizer_states,
5712            ];
5713            let tokenizer_resets = [
5714                outer_parent_tokenizer_reset,
5715                middle_parent_tokenizer_reset,
5716                leaf_tokenizer_reset,
5717            ];
5718            for leaf_index in 0..layout.leaves.len() {
5719                for local_state in 0..tokenizer_counts[leaf_index] {
5720                    let scoped = constraint
5721                        .recursive_tokenizer_scoped_state(leaf_index, local_state)
5722                        .unwrap();
5723                    assert_eq!(
5724                        constraint.recursive_tokenizer_leaf_state(scoped),
5725                        Some((leaf_index, local_state)),
5726                    );
5727                }
5728                assert_eq!(
5729                    constraint.recursive_tokenizer_reset_state(leaf_index),
5730                    constraint.recursive_tokenizer_scoped_state(
5731                        leaf_index,
5732                        tokenizer_resets[leaf_index],
5733                    ),
5734                );
5735            }
5736            assert!(layout.leaves[1].state_count >= 2);
5737            let root_top = layout.leaves[0].state_offset;
5738            let middle_top_a = layout.leaves[1].state_offset;
5739            let middle_top_b = middle_top_a + 1;
5740            let leaf_top = layout.leaves[2].state_offset;
5741            let acc0 = crate::compiler::glr::accumulator::TerminalsDisallowed::new()
5742                .with_insert(10, 20);
5743            let acc1 = crate::compiler::glr::accumulator::TerminalsDisallowed::new()
5744                .with_insert(11, 21);
5745            let acc2 = crate::compiler::glr::accumulator::TerminalsDisallowed::new()
5746                .with_insert(12, 22);
5747            let acc3 = crate::compiler::glr::accumulator::TerminalsDisallowed::new()
5748                .with_insert(13, 23);
5749            let mixed = crate::compiler::glr::parser::ParserGSS::from_stacks(&[
5750                (vec![root_top], acc0.clone()),
5751                (vec![root_top, middle_top_a], acc1.clone()),
5752                (vec![root_top, middle_top_b], acc2.clone()),
5753                (vec![root_top, leaf_top], acc3.clone()),
5754            ]);
5755            let partitions = constraint
5756                .partition_recursive_parser_gss_by_active_leaf(&mixed)
5757                .expect("recursive GSS must partition by active tokenizer leaf");
5758            assert_eq!(
5759                partitions.iter().map(|(leaf, _)| *leaf).collect::<Vec<_>>(),
5760                vec![0, 1, 2],
5761            );
5762            let mut middle_stacks = partitions[1].1.to_stacks(16).unwrap();
5763            middle_stacks.sort_by_key(|(stack, _)| *stack.last().unwrap());
5764            assert_eq!(
5765                middle_stacks,
5766                vec![
5767                    (vec![root_top, middle_top_a], acc1),
5768                    (vec![root_top, middle_top_b], acc2),
5769                ],
5770            );
5771            assert_eq!(
5772                partitions[0].1.to_stacks(16).unwrap(),
5773                vec![(vec![root_top], acc0)],
5774            );
5775            assert_eq!(
5776                partitions[2].1.to_stacks(16).unwrap(),
5777                vec![(vec![root_top, leaf_top], acc3)],
5778            );
5779            assert_eq!(constraint.recursive_parser_state_span().unwrap(), layout.total_states);
5780            assert_eq!(layout.links.len(), 2);
5781            assert!(layout
5782                .links
5783                .iter()
5784                .any(|link| link.parent_component == 1 && link.child_component == 2));
5785            assert!(layout
5786                .links
5787                .iter()
5788                .any(|link| link.parent_component == 0 && link.child_component == 1));
5789        }
5790    }
5791
5792    #[test]
5793    fn recursive_parser_reference_executes_nested_calls_without_materialized_child_table() {
5794        let vocab = Vocab::from_entries_unchecked(vec![
5795            (0, b"X".to_vec()),
5796            (1, b"[".to_vec()),
5797            (2, b"a".to_vec()),
5798            (3, b"]".to_vec()),
5799            (4, b"!".to_vec()),
5800        ]);
5801        let terminal = |constraint: &RuntimeConstraint, name: &str| {
5802            constraint
5803                .terminal_display_names
5804                .iter()
5805                .position(|candidate| candidate == name)
5806                .unwrap() as u32
5807        };
5808        let leaf = RuntimeConstraint::compile(
5809            Grammar::glrm("glrm 1; start leaf; t A = \"a\"; nt leaf = A;"),
5810            &vocab,
5811        )
5812        .unwrap();
5813        let middle_parent = RuntimeConstraint::compile(
5814            Grammar::glrm(
5815                "glrm 1; start middle; extern grammar leaf; t L = \"[\"; t R = \"]\"; nt middle = L leaf R;",
5816            ),
5817            &vocab,
5818        )
5819        .unwrap();
5820        let middle = middle_parent
5821            .bind_grammar_dynamic_boundary("leaf", &leaf)
5822            .unwrap();
5823        let outer_parent = RuntimeConstraint::compile(
5824            Grammar::glrm(
5825                "glrm 1; start document; extern grammar middle; t X = \"X\"; t BANG = \"!\"; nt document = X middle BANG;",
5826            ),
5827            &vocab,
5828        )
5829        .unwrap();
5830        let bound = outer_parent
5831            .bind_grammar_dynamic_boundary("middle", &middle)
5832            .unwrap();
5833
5834        let outer_overlay = bound.static_dynamic_overlay.as_ref().unwrap();
5835        let middle_outer_offset = outer_overlay.segmented_parser_components[1].terminal_offset;
5836        let middle_overlay = middle.static_dynamic_overlay.as_ref().unwrap();
5837        let middle_parent_offset = middle_overlay.segmented_parser_components[0].terminal_offset;
5838        let leaf_offset = middle_overlay.segmented_parser_components[1].terminal_offset;
5839        let terminals = [
5840            outer_overlay.segmented_parser_components[0].terminal_offset
5841                + terminal(&outer_parent, "X"),
5842            middle_outer_offset + middle_parent_offset + terminal(&middle_parent, "L"),
5843            middle_outer_offset + leaf_offset + terminal(&leaf, "A"),
5844            middle_outer_offset + middle_parent_offset + terminal(&middle_parent, "R"),
5845            outer_overlay.segmented_parser_components[0].terminal_offset
5846                + terminal(&outer_parent, "BANG"),
5847        ];
5848
5849        for constraint in [&bound, &RuntimeConstraint::load(bound.save(), &vocab).unwrap()] {
5850            let start = crate::compiler::glr::parser::ParserGSS::from_single_stack(
5851                vec![0],
5852                crate::compiler::glr::accumulator::TerminalsDisallowed::new(),
5853            );
5854            let mut parser = constraint
5855                .close_recursive_segmented_parser_reference(&start)
5856                .unwrap()
5857                .unwrap();
5858            for &terminal in &terminals {
5859                parser = constraint
5860                    .advance_recursive_segmented_parser_reference(&parser, terminal)
5861                    .unwrap()
5862                    .unwrap();
5863                assert!(
5864                    !parser.is_empty(),
5865                    "recursive parser rejected terminal {terminal}",
5866                );
5867            }
5868            assert_eq!(
5869                constraint
5870                    .recursive_segmented_parser_is_finished_reference(&parser)
5871                    .unwrap(),
5872                Some(true),
5873            );
5874
5875            let mut invalid = constraint
5876                .close_recursive_segmented_parser_reference(&start)
5877                .unwrap()
5878                .unwrap();
5879            for &terminal in &[terminals[0], terminals[1], terminals[3]] {
5880                invalid = constraint
5881                    .advance_recursive_segmented_parser_reference(&invalid, terminal)
5882                    .unwrap()
5883                    .unwrap();
5884            }
5885            assert!(invalid.is_empty(), "recursive parser accepted a missing leaf token");
5886        }
5887    }
5888
5889    #[test]
5890    fn recursive_parser_reference_resolves_new_link_through_precomposed_parent() {
5891        let vocab = Vocab::from_entries_unchecked(vec![
5892            (0, b"<".to_vec()),
5893            (1, b"a".to_vec()),
5894            (2, b"b".to_vec()),
5895            (3, b">".to_vec()),
5896        ]);
5897        let terminal = |constraint: &RuntimeConstraint, name: &str| {
5898            constraint
5899                .terminal_display_names
5900                .iter()
5901                .position(|candidate| candidate == name)
5902                .unwrap() as u32
5903        };
5904        let parent = RuntimeConstraint::compile(
5905            Grammar::glrm(
5906                "glrm 1; start document; extern grammar left; extern grammar right; t LT = \"<\"; t GT = \">\"; nt document = LT left right GT;",
5907            ),
5908            &vocab,
5909        )
5910        .unwrap();
5911        let left = RuntimeConstraint::compile(
5912            Grammar::glrm("glrm 1; start left; t A = \"a\"; nt left = A;"),
5913            &vocab,
5914        )
5915        .unwrap();
5916        let right = RuntimeConstraint::compile(
5917            Grammar::glrm("glrm 1; start right; t B = \"b\"; nt right = B;"),
5918            &vocab,
5919        )
5920        .unwrap();
5921        let half = parent
5922            .bind_grammar_dynamic_boundary("left", &left)
5923            .unwrap();
5924        let full = half
5925            .bind_grammar_dynamic_boundary("right", &right)
5926            .unwrap();
5927
5928        let full_overlay = full.static_dynamic_overlay.as_ref().unwrap();
5929        let half_offset = full_overlay.segmented_parser_components[0].terminal_offset;
5930        let right_offset = full_overlay.segmented_parser_components[1].terminal_offset;
5931        let half_overlay = half.static_dynamic_overlay.as_ref().unwrap();
5932        let original_parent_offset = half_overlay.segmented_parser_components[0].terminal_offset;
5933        let left_offset = half_overlay.segmented_parser_components[1].terminal_offset;
5934        let terminals = [
5935            half_offset + original_parent_offset + terminal(&parent, "LT"),
5936            half_offset + left_offset + terminal(&left, "A"),
5937            right_offset + terminal(&right, "B"),
5938            half_offset + original_parent_offset + terminal(&parent, "GT"),
5939        ];
5940
5941        for constraint in [&full, &RuntimeConstraint::load(full.save(), &vocab).unwrap()] {
5942            let layout = constraint.recursive_parser_layout().unwrap().unwrap();
5943            assert_eq!(
5944                layout
5945                    .leaves
5946                    .iter()
5947                    .map(|leaf| leaf.component_path.clone())
5948                    .collect::<Vec<_>>(),
5949                vec![vec![0, 0], vec![0, 1], vec![1]],
5950            );
5951            assert_eq!(layout.links.len(), 2);
5952            assert!(layout
5953                .links
5954                .iter()
5955                .any(|link| link.parent_component == 0 && link.child_component == 1));
5956            assert!(layout
5957                .links
5958                .iter()
5959                .any(|link| link.parent_component == 0 && link.child_component == 2));
5960
5961            let start = crate::compiler::glr::parser::ParserGSS::from_single_stack(
5962                vec![0],
5963                crate::compiler::glr::accumulator::TerminalsDisallowed::new(),
5964            );
5965            let mut parser = constraint
5966                .close_recursive_segmented_parser_reference(&start)
5967                .unwrap()
5968                .unwrap();
5969            for &terminal in &terminals {
5970                parser = constraint
5971                    .advance_recursive_segmented_parser_reference(&parser, terminal)
5972                    .unwrap()
5973                    .unwrap();
5974                assert!(!parser.is_empty(), "recursive parser rejected terminal {terminal}");
5975            }
5976            assert_eq!(
5977                constraint
5978                    .recursive_segmented_parser_is_finished_reference(&parser)
5979                    .unwrap(),
5980                Some(true),
5981            );
5982        }
5983    }
5984
5985    #[test]
5986    fn loaded_recursive_composition_rebinds_from_lazy_compiler_views() {
5987        let vocab = Vocab::from_entries_unchecked(vec![
5988            (0, b"<".to_vec()),
5989            (1, b"a".to_vec()),
5990            (2, b"b".to_vec()),
5991            (3, b">".to_vec()),
5992            (4, b"<ab>".to_vec()),
5993        ]);
5994        let parent = RuntimeConstraint::compile(
5995            Grammar::glrm(
5996                "glrm 1; start document; extern grammar left; extern grammar right; nt document = \"<\" left right \">\";",
5997            ),
5998            &vocab,
5999        )
6000        .unwrap();
6001        let left = RuntimeConstraint::compile(
6002            Grammar::glrm("glrm 1; start left; nt left = \"a\";"),
6003            &vocab,
6004        )
6005        .unwrap();
6006        let right = RuntimeConstraint::compile(
6007            Grammar::glrm("glrm 1; start right; nt right = \"b\";"),
6008            &vocab,
6009        )
6010        .unwrap();
6011
6012        let half = parent
6013            .bind_grammar_dynamic_boundary("left", &left)
6014            .unwrap();
6015        let half_overlay = half.static_dynamic_overlay.as_ref().unwrap();
6016        let half_layout = half.recursive_parser_layout().unwrap().unwrap();
6017        assert_eq!(
6018            half.tokenizer.num_states(),
6019            half_overlay.segmented_parser_components[0]
6020                .constraint
6021                .tokenizer
6022                .num_states(),
6023            "recursive coordinator must retain only the root-leaf tokenizer",
6024        );
6025        assert!(
6026            half.tokenizer.num_states() < half_layout.total_tokenizer_states,
6027            "test fixture must actually contain more than one tokenizer leaf",
6028        );
6029        assert_recursive_compiler_views_detached(&half);
6030        assert!(half_overlay
6031            .segmented_parser_components
6032            .iter()
6033            .all(|component| component.global_to_local_parser_state.is_empty()));
6034
6035        let loaded_half = RuntimeConstraint::load_body_external_artifact(half.save(), &vocab).unwrap();
6036        let loaded_half_overlay = loaded_half.static_dynamic_overlay.as_ref().unwrap();
6037        let loaded_half_layout = loaded_half.recursive_parser_layout().unwrap().unwrap();
6038        assert_eq!(
6039            loaded_half.tokenizer.num_states(),
6040            loaded_half_overlay.segmented_parser_components[0]
6041                .constraint
6042                .tokenizer
6043                .num_states(),
6044            "loaded recursive coordinator must not reconstruct the outer union tokenizer eagerly",
6045        );
6046        assert!(loaded_half.tokenizer.num_states() < loaded_half_layout.total_tokenizer_states);
6047        assert_recursive_compiler_views_detached(&loaded_half);
6048        assert!(loaded_half_overlay
6049            .segmented_parser_components
6050            .iter()
6051            .all(|component| component.global_to_local_parser_state.is_empty()));
6052
6053        let fresh_full = half
6054            .bind_grammar_dynamic_boundary("right", &right)
6055            .unwrap();
6056        let loaded_full = loaded_half
6057            .bind_grammar_dynamic_boundary("right", &right)
6058            .unwrap();
6059        for constraint in [&fresh_full, &loaded_full] {
6060            assert_recursive_compiler_views_detached(constraint);
6061        }
6062        let fresh_start = crate::compiler::glr::parser::ParserGSS::from_single_stack(
6063            vec![0],
6064            crate::compiler::glr::accumulator::TerminalsDisallowed::new(),
6065        );
6066        let loaded_start = fresh_start.clone();
6067        let fresh_closed = fresh_full
6068            .close_compact_segmented_parser(&fresh_start)
6069            .unwrap();
6070        let loaded_closed = loaded_full
6071            .close_compact_segmented_parser(&loaded_start)
6072            .unwrap();
6073        assert!(fresh_closed.semantically_eq(&loaded_closed, 4096).unwrap());
6074        for terminal in 0..fresh_full.parser_terminal_count() {
6075            let fresh_advanced = fresh_full
6076                .advance_compact_segmented_parser(&fresh_closed, terminal)
6077                .unwrap();
6078            let loaded_advanced = loaded_full
6079                .advance_compact_segmented_parser(&loaded_closed, terminal)
6080                .unwrap();
6081            assert!(
6082                fresh_advanced
6083                    .semantically_eq(&loaded_advanced, 4096)
6084                    .unwrap(),
6085                "recursive parser advance differs for terminal {terminal}",
6086            );
6087        }
6088        for constraint in [&fresh_full, &loaded_full] {
6089            let overlay = constraint.static_dynamic_overlay.as_ref().unwrap();
6090            assert!(overlay
6091                .segmented_parser_components
6092                .iter()
6093                .all(|component| component.global_to_local_parser_state.is_empty()));
6094            let mut split = constraint.start();
6095            for token in [0, 1, 2, 3] {
6096                assert_ne!(split.mask()[0] & (1 << token), 0);
6097                assert!(split.commit_token(token));
6098            }
6099            assert!(split.is_accepting());
6100
6101            let mut fused = constraint.start();
6102            assert_ne!(fused.mask()[0] & (1 << 4), 0);
6103            assert!(fused.commit_token(4));
6104            assert!(fused.is_accepting());
6105        }
6106    }
6107
6108    #[test]
6109    fn recursive_parser_reference_preserves_nested_nullable_wrapper_return() {
6110        let vocab = Vocab::from_entries_unchecked(vec![
6111            (0, b"X".to_vec()),
6112            (1, b"a".to_vec()),
6113            (2, b"!".to_vec()),
6114        ]);
6115        let terminal = |constraint: &RuntimeConstraint, name: &str| {
6116            constraint
6117                .terminal_display_names
6118                .iter()
6119                .position(|candidate| candidate == name)
6120                .unwrap() as u32
6121        };
6122        let leaf = RuntimeConstraint::compile(
6123            Grammar::glrm("glrm 1; start leaf; t A = \"a\"; nt leaf = A?;"),
6124            &vocab,
6125        )
6126        .unwrap();
6127        let middle_parent = RuntimeConstraint::compile(
6128            Grammar::glrm("glrm 1; start middle; extern grammar leaf; nt middle = leaf;"),
6129            &vocab,
6130        )
6131        .unwrap();
6132        assert!(!middle_parent.composition_start_nullable().unwrap());
6133        let middle = middle_parent
6134            .bind_grammar_dynamic_boundary("leaf", &leaf)
6135            .unwrap();
6136        assert!(middle.composition_start_nullable().unwrap());
6137        let outer_parent = RuntimeConstraint::compile(
6138            Grammar::glrm(
6139                "glrm 1; start document; extern grammar middle; t X = \"X\"; t BANG = \"!\"; nt document = X middle BANG;",
6140            ),
6141            &vocab,
6142        )
6143        .unwrap();
6144        let bound = outer_parent
6145            .bind_grammar_dynamic_boundary("middle", &middle)
6146            .unwrap();
6147
6148        let outer_overlay = bound.static_dynamic_overlay.as_ref().unwrap();
6149        let middle_outer_offset = outer_overlay.segmented_parser_components[1].terminal_offset;
6150        let middle_overlay = middle.static_dynamic_overlay.as_ref().unwrap();
6151        let leaf_offset = middle_overlay.segmented_parser_components[1].terminal_offset;
6152        let x = outer_overlay.segmented_parser_components[0].terminal_offset
6153            + terminal(&outer_parent, "X");
6154        let a = middle_outer_offset + leaf_offset + terminal(&leaf, "A");
6155        let bang = outer_overlay.segmented_parser_components[0].terminal_offset
6156            + terminal(&outer_parent, "BANG");
6157
6158        for constraint in [&bound, &RuntimeConstraint::load(bound.save(), &vocab).unwrap()] {
6159            let layout = constraint.recursive_parser_layout().unwrap().unwrap();
6160            let outer_link = layout
6161                .links
6162                .iter()
6163                .find(|link| link.parent_component == 0 && link.child_component == 1)
6164                .expect("outer link must target the middle wrapper root leaf");
6165            assert!(outer_link.child_start_nullable);
6166
6167            for terminals in [&[x, bang][..], &[x, a, bang][..]] {
6168                let start = crate::compiler::glr::parser::ParserGSS::from_single_stack(
6169                    vec![0],
6170                    crate::compiler::glr::accumulator::TerminalsDisallowed::new(),
6171                );
6172                let mut parser = constraint
6173                    .close_recursive_segmented_parser_reference(&start)
6174                    .unwrap()
6175                    .unwrap();
6176                for &terminal in terminals {
6177                    parser = constraint
6178                        .advance_recursive_segmented_parser_reference(&parser, terminal)
6179                        .unwrap()
6180                        .unwrap();
6181                    assert!(!parser.is_empty(), "recursive nullable parser rejected {terminals:?}");
6182                }
6183                assert_eq!(
6184                    constraint
6185                        .recursive_segmented_parser_is_finished_reference(&parser)
6186                        .unwrap(),
6187                    Some(true),
6188                    "{terminals:?}",
6189                );
6190            }
6191        }
6192    }
6193
6194    #[test]
6195    fn static_boundary_shards_are_authoritative_across_multiple_internal_crossings() {
6196        let vocab = Vocab::from_entries_unchecked(vec![
6197            (0, b"x".to_vec()),
6198            (1, b"y".to_vec()),
6199            (2, b"z".to_vec()),
6200            (3, b"xy".to_vec()),
6201            (4, b"yz".to_vec()),
6202            (5, b"xyz".to_vec()),
6203        ]);
6204        let parent = RuntimeConstraint::compile(
6205            Grammar::glrm(
6206                "glrm 1; start start; extern grammar left; extern grammar right; \
6207                 nt start = \"x\" left right;",
6208            ),
6209            &vocab,
6210        )
6211        .unwrap();
6212        let left = RuntimeConstraint::compile(Grammar::ebnf(r#"start ::= "y""#), &vocab)
6213            .unwrap();
6214        let right = RuntimeConstraint::compile(Grammar::ebnf(r#"start ::= "z""#), &vocab)
6215            .unwrap();
6216        let bound = parent
6217            .bind_grammar("left", left)
6218            .unwrap()
6219            .bind_grammar("right", right)
6220            .unwrap();
6221
6222        let overlay = bound
6223            .static_dynamic_overlay
6224            .as_ref()
6225            .expect("static composition must retain segmented A+B metadata");
6226        assert!(
6227            !overlay.segmented_boundary_shards.is_empty(),
6228            "static composition must publish component-scoped B shards",
6229        );
6230        assert!(
6231            overlay.segmented_boundary_parser.is_none(),
6232            "partitioned static B must not retain a redundant global boundary parser",
6233        );
6234        assert!(overlay.segmented_boundary_terminal_trie.is_none());
6235
6236        let loaded = RuntimeConstraint::load(bound.save(), &vocab).unwrap();
6237        let loaded_overlay = loaded.static_dynamic_overlay.as_ref().unwrap();
6238        assert!(loaded_overlay.segmented_boundary_parser.is_none());
6239        assert!(loaded_overlay.segmented_boundary_terminal_trie.is_none());
6240        assert!(!loaded_overlay.segmented_boundary_shards.is_empty());
6241        let reference = RuntimeConstraint::compile(
6242            Grammar::ebnf(r#"start ::= "x" "y" "z""#),
6243            &vocab,
6244        )
6245        .unwrap();
6246
6247        for tokens in [&[5][..], &[0, 4][..], &[0, 1, 2][..]] {
6248            let mut sharded = bound.start();
6249            let mut restored = loaded.start();
6250            let mut expected = reference.start();
6251            for &token in tokens {
6252                assert_eq!(
6253                    sharded.mask(),
6254                    expected.mask(),
6255                    "partitioned static B mismatch before {tokens:?} token {token}",
6256                );
6257                assert_eq!(
6258                    restored.mask(),
6259                    expected.mask(),
6260                    "restored static shards differ before {tokens:?} token {token}",
6261                );
6262                assert!(sharded.commit_token(token));
6263                assert!(restored.commit_token(token));
6264                assert!(expected.commit_token(token));
6265            }
6266            assert_eq!(sharded.is_accepting(), expected.is_accepting(), "{tokens:?}");
6267            assert_eq!(restored.is_accepting(), expected.is_accepting(), "{tokens:?}");
6268            assert!(sharded.is_accepting(), "{tokens:?}");
6269        }
6270    }
6271
6272    #[test]
6273    fn authoritative_ab_keeps_component_parser_dwas_unchanged_across_scoped_ignores() {
6274        let vocab = Vocab::from_entries_unchecked(vec![
6275            (0, b"X".to_vec()),
6276            (1, b" ".to_vec()),
6277            (2, b"\t".to_vec()),
6278            (3, b"a".to_vec()),
6279            (4, b"!".to_vec()),
6280            (5, b"X \ta!".to_vec()),
6281            (6, b"X\t a!".to_vec()),
6282            (7, b"Xa\t !".to_vec()),
6283            (8, b"Xa \t!".to_vec()),
6284        ]);
6285        let parent = RuntimeConstraint::compile(
6286            Grammar::glrm(
6287                r#"
6288                    glrm 1;
6289                    start document;
6290                    ignore PARENT_WS;
6291                    t PARENT_WS = " "+;
6292                    extern grammar child;
6293                    nt document = "X" child "!";
6294                "#,
6295            ),
6296            &vocab,
6297        )
6298        .unwrap();
6299        let child = RuntimeConstraint::compile(
6300            Grammar::glrm(
6301                r#"
6302                    glrm 1;
6303                    start child;
6304                    ignore CHILD_WS;
6305                    t CHILD_WS = "\t"+;
6306                    nt child = "a";
6307                "#,
6308            ),
6309            &vocab,
6310        )
6311        .unwrap();
6312        assert!(
6313            !parent.composition_reset_tokens_by_terminal.is_empty(),
6314            "late-bind parent compilation should precompute reset-token composition metadata",
6315        );
6316        let mut cached_parent = RuntimeConstraint::load_body_external_artifact(parent.save(), &vocab).unwrap();
6317        cached_parent
6318            .materialize_composition_metadata_for_compilation()
6319            .unwrap();
6320        assert_eq!(
6321            cached_parent.composition_reset_tokens_by_terminal,
6322            parent.composition_reset_tokens_by_terminal,
6323            "late-bind reset-token cache must survive save/load",
6324        );
6325        let monolithic = RuntimeConstraint::compile(
6326            Grammar::glrm(
6327                r#"
6328                    glrm 1;
6329                    start document;
6330                    ignore PARENT_WS;
6331                    t PARENT_WS = " "+;
6332                    grammar child {
6333                        start child;
6334                        ignore CHILD_WS;
6335                        t CHILD_WS = "\t"+;
6336                        nt child = "a";
6337                    };
6338                    nt document = "X" child "!";
6339                "#,
6340            ),
6341            &vocab,
6342        )
6343        .unwrap();
6344
6345        let parent_dwa = parent.parser_dwa.clone();
6346        let child_dwa = child.parser_dwa.clone();
6347        let bound = parent
6348            .bind_grammar_dynamic_boundary("child", child.clone())
6349            .unwrap();
6350        let overlay = bound
6351            .static_dynamic_overlay
6352            .as_ref()
6353            .expect("authoritative A+B metadata");
6354        assert!(overlay.segmented_mask_authoritative);
6355        assert!(!overlay.segmented_static_baseline);
6356        assert_eq!(overlay.segmented_parser_components.len(), 2);
6357        assert_eq!(overlay.segmented_parser_components[0].constraint.parser_dwa, parent_dwa);
6358        assert_eq!(overlay.segmented_parser_components[1].constraint.parser_dwa, child_dwa);
6359        assert!(overlay
6360            .segmented_parser_components
6361            .iter()
6362            .all(|component| component.root_disallowed_terminal.is_none()));
6363
6364        let loaded = RuntimeConstraint::load(bound.save(), &vocab).unwrap();
6365        assert!(bound.uses_compact_segmented_parser_runtime());
6366        assert!(loaded.uses_compact_segmented_parser_runtime());
6367        let loaded_overlay = loaded
6368            .static_dynamic_overlay
6369            .as_ref()
6370            .expect("round-tripped authoritative A+B metadata");
6371        assert_eq!(loaded_overlay.segmented_parser_components.len(), 2);
6372        let mut loaded_parent = loaded_overlay.segmented_parser_components[0]
6373            .constraint
6374            .as_ref()
6375            .clone();
6376        let mut loaded_child = loaded_overlay.segmented_parser_components[1]
6377            .constraint
6378            .as_ref()
6379            .clone();
6380        loaded_parent.materialize_parser_dwa_for_compilation().unwrap();
6381        loaded_child.materialize_parser_dwa_for_compilation().unwrap();
6382        assert_eq!(loaded_parent.parser_dwa, parent_dwa);
6383        assert_eq!(loaded_child.parser_dwa, child_dwa);
6384        for (kind, constraint) in [("source", &bound), ("loaded", &loaded)] {
6385            let mut actual = constraint.start();
6386            let mut expected = monolithic.start();
6387            assert_eq!(actual.mask(), expected.mask(), "{kind} initial mask");
6388            for token in [1, 0, 2, 3, 1, 4] {
6389                assert!(actual.commit_token(token));
6390                assert!(expected.commit_token(token));
6391                assert_eq!(actual.mask(), expected.mask(), "after token {token}");
6392            }
6393            assert!(actual.is_accepting());
6394            assert!(expected.is_accepting());
6395
6396            for token in [5, 6, 7, 8] {
6397                let mut actual = constraint.start();
6398                let mut expected = monolithic.start();
6399                assert_eq!(
6400                    actual.commit_token(token),
6401                    expected.commit_token(token),
6402                    "fused token {token}",
6403                );
6404                assert_eq!(actual.is_accepting(), expected.is_accepting());
6405            }
6406        }
6407    }
6408
6409    #[test]
6410    fn authoritative_ab_handles_multi_terminal_parent_token_after_zero_width_return() {
6411        let vocab = Vocab::from_entries_unchecked(vec![
6412            (0, b"X".to_vec()),
6413            (1, b"a".to_vec()),
6414            (2, b"!".to_vec()),
6415            (3, b"?".to_vec()),
6416            (4, b"!?".to_vec()),
6417        ]);
6418        let parent = RuntimeConstraint::compile(
6419            Grammar::glrm(
6420                r#"
6421                    glrm 1;
6422                    start document;
6423                    extern grammar child;
6424                    nt document = "X" child "!" "?";
6425                "#,
6426            ),
6427            &vocab,
6428        )
6429        .unwrap();
6430        let child = RuntimeConstraint::compile(
6431            Grammar::glrm("glrm 1; start child; nt child = \"a\";"),
6432            &vocab,
6433        )
6434        .unwrap();
6435        let monolithic = RuntimeConstraint::compile(
6436            Grammar::glrm(
6437                r#"
6438                    glrm 1;
6439                    start document;
6440                    grammar child { start child; nt child = "a"; };
6441                    nt document = "X" child "!" "?";
6442                "#,
6443            ),
6444            &vocab,
6445        )
6446        .unwrap();
6447
6448        let bound = parent
6449            .bind_grammar_dynamic_boundary("child", child)
6450            .unwrap();
6451        for constraint in [&bound, &RuntimeConstraint::load(bound.save(), &vocab).unwrap()] {
6452            let mut actual = constraint.start();
6453            let mut expected = monolithic.start();
6454            for token in [0, 1] {
6455                assert_eq!(actual.mask(), expected.mask(), "before token {token}");
6456                assert!(actual.commit_token(token));
6457                assert!(expected.commit_token(token));
6458            }
6459            let actual_mask = actual.mask();
6460            let expected_mask = expected.mask();
6461            assert_eq!(actual_mask, expected_mask, "after child completion");
6462            assert_ne!(actual_mask[0] & (1 << 4), 0, "fused parent token !? must be allowed");
6463            assert!(actual.commit_token(4));
6464            assert!(expected.commit_token(4));
6465            assert!(actual.is_accepting());
6466            assert!(expected.is_accepting());
6467        }
6468    }
6469
6470    #[test]
6471    fn dynamic_late_bind_vocab_cache_is_shared_reused_and_not_serialized() {
6472        let vocab = Vocab::from_entries_unchecked(vec![
6473            (0, b"x".to_vec()), (1, b"y".to_vec()), (2, b"xy".to_vec()),
6474        ]);
6475        let parent = native_dynamic_fixture(
6476            Grammar::glrm("glrm 1; start start; extern grammar child; nt start = \"x\" child;"),
6477            &vocab,
6478        ).unwrap();
6479        let child = native_dynamic_fixture(Grammar::ebnf(r#"start ::= "y""#), &vocab).unwrap();
6480        let retained = parent.inner.late_bind_vocab.get().expect("retain supplied vocabulary");
6481        assert!(Arc::ptr_eq(&retained.entries_arc(), &vocab.entries_arc()));
6482
6483        let loaded = DynamicConstraint::from_constraints(vec![
6484            RuntimeConstraint::load_body_external_artifact(parent.inner.save(), &vocab).unwrap(),
6485        ]);
6486        assert!(loaded.inner.late_bind_vocab.get().is_some());
6487        let first = loaded.bind_grammar_dynamic_boundary("child", &child).unwrap();
6488        let first_backing = loaded.inner.late_bind_vocab.get()
6489            .expect("prime retained loaded parent, not a throwaway clone").entries_arc();
6490        let second = loaded.bind_grammar_dynamic_boundary("child", &child).unwrap();
6491        assert!(Arc::ptr_eq(
6492            &first_backing, &loaded.inner.late_bind_vocab.get().unwrap().entries_arc(),
6493        ));
6494        assert_eq!(first.start().mask(), second.start().mask());
6495        let reloaded = DynamicConstraint::from_constraints(vec![
6496            RuntimeConstraint::load_body_external_artifact(loaded.inner.save(), &vocab).unwrap(),
6497        ]);
6498        assert!(reloaded.inner.late_bind_vocab.get().is_some(), "loaded vocab is runtime-only, never serialized");
6499        let rebound = reloaded.bind_grammar_dynamic_boundary("child", &child).unwrap();
6500        assert_eq!(first.start().mask(), rebound.start().mask());
6501    }
6502
6503    #[test]
6504    fn late_bind_vocab_cache_is_reused_and_not_serialized() {
6505        let vocab = Vocab::from_entries_unchecked(vec![
6506            (0, b"x".to_vec()),
6507            (1, b"y".to_vec()),
6508            (2, b"xy".to_vec()),
6509        ]);
6510        let parent = RuntimeConstraint::compile(
6511            Grammar::glrm(
6512                "glrm 1; start start; extern grammar child; nt start = \"x\" child;",
6513            ),
6514            &vocab,
6515        )
6516        .unwrap();
6517        let child =
6518            native_dynamic_fixture(Grammar::ebnf(r#"start ::= "y""#), &vocab).unwrap();
6519
6520        assert!(
6521            parent.late_bind_vocab.get().is_some(),
6522            "fresh compilation should retain the supplied vocabulary for later binds",
6523        );
6524
6525        let loaded_parent = RuntimeConstraint::load_body_external_artifact(parent.save(), &vocab).unwrap();
6526        assert!(
6527            loaded_parent.late_bind_vocab.get().is_some(),
6528            "the loader supplies the vocabulary; it is runtime-only and never serialized",
6529        );
6530        let first = loaded_parent
6531            .bind_grammar_dynamic_boundary("child", &child)
6532            .unwrap();
6533        assert!(loaded_parent.late_bind_vocab.get().is_some());
6534        let second = loaded_parent
6535            .bind_grammar_dynamic_boundary("child", &child)
6536            .unwrap();
6537        assert_eq!(first.start().mask(), second.start().mask());
6538
6539        let loaded = RuntimeConstraint::load_body_external_artifact(loaded_parent.save(), &vocab).unwrap();
6540        assert!(
6541            loaded.late_bind_vocab.get().is_some(),
6542            "the loader supplies the vocabulary; it is runtime-only and never serialized",
6543        );
6544        let rebound = loaded
6545            .bind_grammar_dynamic_boundary("child", &child)
6546            .unwrap();
6547        assert_eq!(first.start().mask(), rebound.start().mask());
6548    }
6549}
6550
6551
6552#[cfg(test)]
6553mod final_unlinked_optimization_tests {
6554    use super::*;
6555
6556    fn assert_static_boundary(constraint: &RuntimeConstraint) {
6557        let overlay = constraint.static_dynamic_overlay.as_ref().unwrap();
6558        assert!(!overlay.segmented_boundary_shards.is_empty());
6559        assert!(overlay.segmented_boundary_shards.iter().all(|shard| matches!(
6560            shard.backend,
6561            crate::runtime::SegmentedBoundaryShardBackend::StaticParser(_)
6562        )));
6563    }
6564
6565    fn assert_dynamic_boundary(constraint: &RuntimeConstraint) {
6566        let overlay = constraint.static_dynamic_overlay.as_ref().unwrap();
6567        assert!(!overlay.segmented_boundary_shards.is_empty());
6568        assert!(overlay.segmented_boundary_shards.iter().all(|shard| matches!(
6569            shard.backend,
6570            crate::runtime::SegmentedBoundaryShardBackend::DynamicDirect
6571        )));
6572    }
6573
6574    #[test]
6575    fn unlinked_bind_defers_composition_until_link_and_link_optimization_selects_boundary() {
6576        let vocab = Vocab::from_entries_unchecked(vec![
6577            (0, b"x".to_vec()),
6578            (1, b"y".to_vec()),
6579            (2, b"xy".to_vec()),
6580        ]);
6581        let host = Grammar::glrm(
6582            r#"glrm 1; start start; extern grammar child; nt start = "x" child;"#,
6583        )
6584        .prepare(&vocab)
6585        .unwrap();
6586        let child = Grammar::ebnf(r#"start ::= "y""#)
6587            .compile_inner(&vocab)
6588            .unwrap();
6589
6590        let bound = host.bind_snapshot("child", &child).unwrap();
6591        assert!(bound.inner.late_grammar_slots.iter().any(|slot| slot.name == "child"));
6592        assert!(bound.inner.static_dynamic_overlay.is_none(), "bind must not compile a boundary eagerly");
6593
6594        let fast_build = bound.link_with(
6595            MaskMode::C.build_options(),
6596        ).unwrap();
6597        let fast_runtime = bound.link_with(
6598            BuildOptions::default().optimization(InternalMaskStrategy::ParserDwa),
6599        ).unwrap();
6600        assert_dynamic_boundary(&fast_build);
6601        assert_static_boundary(&fast_runtime);
6602        assert_eq!(fast_build.start().mask(), fast_runtime.start().mask());
6603
6604        let loaded = PreparedGrammar::load(bound.save(), &vocab).unwrap();
6605        assert!(loaded.inner.late_grammar_slots.iter().any(|slot| slot.name == "child"));
6606        assert_dynamic_boundary(&loaded.link_with(
6607            MaskMode::C.build_options(),
6608        ).unwrap());
6609        assert_static_boundary(&loaded.link_with(
6610            BuildOptions::default().optimization(InternalMaskStrategy::ParserDwa),
6611        ).unwrap());
6612    }
6613}
6614
6615#[cfg(test)]
6616mod cached_parent_main_tests {
6617    use super::*;
6618
6619    fn vocab() -> Vocab {
6620        Vocab::from_entries_unchecked(vec![
6621            (0, b"<".to_vec()),
6622            (1, b">".to_vec()),
6623            (2, b"[".to_vec()),
6624            (3, b"]".to_vec()),
6625            (4, b"a".to_vec()),
6626            (5, b"b".to_vec()),
6627            (6, b"x".to_vec()),
6628            (7, b"<a>".to_vec()),
6629            (8, b"<b>".to_vec()),
6630            (9, b"<[a]>".to_vec()),
6631        ])
6632    }
6633
6634    fn accepts(constraint: &RuntimeConstraint, bytes: &[u8]) -> bool {
6635        let mut state = constraint.start();
6636        state.commit_bytes(bytes) && state.is_accepting()
6637    }
6638
6639    #[test]
6640    fn compiled_parent_can_bind_external_grammar_after_compile_and_load() {
6641        let vocab = vocab();
6642        let parent = RuntimeConstraint::compile(
6643            Grammar::glrm(
6644                r#"
6645                    glrm 1;
6646                    extern grammar payload;
6647                    start document;
6648                    nt document = "x" | "<" payload ">";
6649                "#,
6650            ),
6651            &vocab,
6652        )
6653        .unwrap();
6654        assert_eq!(
6655            parent
6656                .late_grammar_slots
6657                .iter()
6658                .map(|slot| slot.name.as_str())
6659                .collect::<Vec<_>>(),
6660            vec!["payload"],
6661        );
6662        assert!(accepts(&parent, b"x"));
6663        assert!(!accepts(&parent, b"<a>"));
6664
6665        let child_a = RuntimeConstraint::compile(
6666            Grammar::glrm("glrm 1; start value; nt value = \"a\";"),
6667            &vocab,
6668        )
6669        .unwrap();
6670        let child_b = RuntimeConstraint::compile(
6671            Grammar::glrm("glrm 1; start value; nt value = \"b\";"),
6672            &vocab,
6673        )
6674        .unwrap();
6675
6676        let with_a = parent.bind_grammar("payload", &child_a).unwrap();
6677        let with_b = parent.bind_grammar("payload", &child_b).unwrap();
6678        assert!(accepts(&with_a, b"x"));
6679        assert!(accepts(&with_a, b"<a>"));
6680        assert!(!accepts(&with_a, b"<b>"));
6681        assert!(accepts(&with_b, b"<b>"));
6682        assert!(!accepts(&with_b, b"<a>"));
6683        assert!(parent
6684            .late_grammar_slots
6685            .iter()
6686            .any(|slot| slot.name == "payload"));
6687
6688        let saved = parent.save();
6689        let loaded = RuntimeConstraint::load_body_external_artifact(&saved, &vocab).unwrap();
6690        let loaded_with_a = loaded.bind_grammar("payload", &child_a).unwrap();
6691        assert!(accepts(&loaded_with_a, b"<a>"));
6692        assert!(!accepts(&loaded_with_a, b"<b>"));
6693    }
6694
6695    #[test]
6696    fn compiled_parent_can_fill_multiple_slots_incrementally() {
6697        let vocab = vocab();
6698        let parent = RuntimeConstraint::compile(
6699            Grammar::glrm(
6700                r#"
6701                    glrm 1;
6702                    extern grammar left;
6703                    extern grammar right;
6704                    start document;
6705                    nt document = "<" left right ">";
6706                "#,
6707            ),
6708            &vocab,
6709        )
6710        .unwrap();
6711        let a = RuntimeConstraint::compile(
6712            Grammar::glrm(r#"glrm 1; start value; nt value = "a";"#),
6713            &vocab,
6714        )
6715        .unwrap();
6716        let b = RuntimeConstraint::compile(
6717            Grammar::glrm(r#"glrm 1; start value; nt value = "b";"#),
6718            &vocab,
6719        )
6720        .unwrap();
6721        let half = parent.bind_grammar_dynamic_boundary("left", &a).unwrap();
6722        assert!(half
6723            .late_grammar_slots
6724            .iter()
6725            .any(|slot| slot.name == "right"));
6726        let full = half.bind_grammar_dynamic_boundary("right", &b).unwrap();
6727        assert!(full.late_grammar_slots.is_empty());
6728        assert!(accepts(&full, b"<ab>"));
6729
6730        let unresolved_child = RuntimeConstraint::compile(
6731            Grammar::glrm(
6732                "glrm 1; extern grammar leaf; start value; nt value = leaf;",
6733            ),
6734            &vocab,
6735        )
6736        .unwrap();
6737        // Main used to reject this because independently compiled unresolved
6738        // children could collide in the private placeholder-token namespace.
6739        // The successor architecture transports those slots by qualified name
6740        // and sanitizes the private linker token from the public token domain.
6741        let open_left = parent
6742            .bind_grammar_dynamic_boundary("left", &unresolved_child)
6743            .unwrap();
6744        assert!(open_left
6745            .late_grammar_slots
6746            .iter()
6747            .any(|slot| slot.name == "left.leaf"));
6748        let left = open_left.bind_grammar_dynamic_boundary("left.leaf", &a).unwrap();
6749        let nested_full = left.bind_grammar_dynamic_boundary("right", &b).unwrap();
6750        assert!(nested_full.late_grammar_slots.is_empty());
6751        assert!(accepts(&nested_full, b"<ab>"));
6752    }
6753
6754    #[test]
6755    fn dynamic_compile_preserves_unbound_external_grammar() {
6756        let vocab = vocab();
6757        let open = native_dynamic_fixture(
6758            Grammar::glrm(
6759                "glrm 1; extern grammar payload; start document; nt document = payload;",
6760            ),
6761            &vocab,
6762        )
6763        .unwrap();
6764        assert!(open
6765            .clone_constraints()
6766            .iter()
6767            .all(|alternative| alternative
6768                .late_grammar_slots
6769                .iter()
6770                .any(|slot| slot.name == "payload")));
6771        let child = RuntimeConstraint::compile(
6772            Grammar::glrm("glrm 1; start value; nt value = \"a\";"),
6773            &vocab,
6774        )
6775        .unwrap();
6776        let bound = open.bind_grammar("payload", &child).unwrap();
6777        let mut state = bound.start();
6778        assert!(state.commit_bytes(b"a"));
6779        assert!(state.is_accepting());
6780    }
6781
6782    #[test]
6783    fn final_optimization_dispatch_selects_dynamic_build_and_static_runtime_paths() {
6784        let vocab = Vocab::from_entries_unchecked(vec![
6785            (0, b"a".to_vec()),
6786            (1, b"b".to_vec()),
6787            (2, b"ab".to_vec()),
6788        ]);
6789        let grammar = Grammar::ebnf(r#"start ::= "a" "b""#);
6790        let fast_build = grammar
6791            .compile_with_build_options(
6792                &vocab,
6793                MaskMode::C.build_options(),
6794            )
6795            .unwrap();
6796        let fast_runtime = grammar
6797            .compile_with_build_options(
6798                &vocab,
6799                BuildOptions::default().optimization(InternalMaskStrategy::ParserDwa),
6800            )
6801            .unwrap();
6802        assert!(fast_build.uses_dynamic_runtime());
6803        assert!(!fast_runtime.uses_dynamic_runtime());
6804
6805        let mut build_state = fast_build.start();
6806        let mut runtime_state = fast_runtime.start();
6807        assert_eq!(build_state.mask(), runtime_state.mask());
6808        assert!(build_state.commit_token(2));
6809        assert!(runtime_state.commit_token(2));
6810        assert_eq!(build_state.is_accepting(), runtime_state.is_accepting());
6811
6812        let loaded = RuntimeConstraint::load(fast_build.save(), &vocab).unwrap();
6813        assert!(loaded.uses_dynamic_runtime());
6814        assert_eq!(loaded.start().mask(), fast_runtime.start().mask());
6815    }
6816}
6817
6818impl RuntimeConstraint {
6819    /// Inspect the actual stored parser backend, not a process-wide switch.
6820    #[cfg(any(test, feature = "internal-api"))]
6821    #[doc(hidden)]
6822    pub fn parser_backend(&self) -> ParserBackend {
6823        if self.has_template_parser() {
6824            assert!(!self.table.is_present(), "template parser retained LR storage");
6825            ParserBackend::TemplateDfa
6826        } else { ParserBackend::LrTable }
6827    }
6828
6829    /// Diagnostic: whether this body retains an LR table.
6830    #[cfg(any(test, feature = "internal-api"))]
6831    #[doc(hidden)]
6832    pub fn runtime_has_lr_table(&self) -> bool {
6833        self.table.is_present()
6834    }
6835
6836    /// Diagnostic: whether this body retains a template parser.
6837    #[cfg(any(test, feature = "internal-api"))]
6838    #[doc(hidden)]
6839    pub fn runtime_has_template_parser(&self) -> bool {
6840        self.has_template_parser()
6841    }
6842
6843    /// Diagnostic: whether the mask vocabulary is grammar-quotiented.
6844    #[cfg(any(test, feature = "internal-api"))]
6845    #[doc(hidden)]
6846    pub fn runtime_is_grammar_quotiented(&self) -> bool {
6847        self.dynamic_mask_vocab.is_grammar_quotiented()
6848    }
6849}
6850
6851
6852#[cfg(test)]
6853mod final_boundary_option_tests {
6854    use super::*;
6855
6856    fn vocab() -> Vocab {
6857        Vocab::from_entries_unchecked(vec![(0, b"x".to_vec()), (1, b"y".to_vec()), (2, b"xy".to_vec())])
6858    }
6859
6860    #[test]
6861    fn trigger_metadata_exists_before_first_use_in_every_public_mode() {
6862        let v = vocab();
6863        let grammar = Grammar::from_ebnf(r#"start ::= "x" "y""#).unwrap();
6864        for mode in MaskMode::ALL {
6865            for detail in [BoundaryTriggerDetail::None, BoundaryTriggerDetail::TokenSet, BoundaryTriggerDetail::Exact] {
6866                let result = grammar.compile_with_build_options(&v,
6867                    mode.build_options().boundary_trigger(detail));
6868                if (mode == MaskMode::A || mode == MaskMode::D) && detail == BoundaryTriggerDetail::Exact {
6869                    assert!(result.unwrap_err().to_string().contains("retained-LR Dynamic"));
6870                    continue;
6871                }
6872                let constraint = result.unwrap();
6873                assert!(matches!((&constraint.boundary_trigger, detail),
6874                    (crate::runtime::BoundaryTrigger::None, BoundaryTriggerDetail::None) |
6875                    (crate::runtime::BoundaryTrigger::TokenSet(_), BoundaryTriggerDetail::TokenSet) |
6876                    (crate::runtime::BoundaryTrigger::Exact(_), BoundaryTriggerDetail::Exact)));
6877            }
6878        }
6879    }
6880
6881    #[test]
6882    fn deferred_trigger_metadata_is_built_at_link_and_explicit_none_overrides() {
6883        let v = vocab();
6884        let parent = Grammar::from_glrm(r#"glrm 1; start start; extern grammar child; nt start = "x" child;"#).unwrap()
6885            .prepare_with(&v, BuildOptions::default().boundary_trigger(BoundaryTriggerDetail::Exact)).unwrap();
6886        assert!(matches!(parent.inner.boundary_trigger, crate::runtime::BoundaryTrigger::None));
6887        let parent = PreparedGrammar::load(parent.save(), &v).unwrap();
6888        let child = Grammar::from_ebnf(r#"start ::= "y""#).unwrap().prepare(&v).unwrap();
6889        let bound = parent.bind_snapshot("child", &child).unwrap();
6890        assert!(matches!(bound.inner.boundary_trigger, crate::runtime::BoundaryTrigger::None));
6891        let exact = bound.link().unwrap();
6892        assert!(matches!(exact.boundary_trigger, crate::runtime::BoundaryTrigger::Exact(_)));
6893        let none = bound.link_with(BuildOptions::default().boundary_trigger(BoundaryTriggerDetail::None)).unwrap();
6894        assert!(matches!(none.boundary_trigger, crate::runtime::BoundaryTrigger::None));
6895        assert_eq!(exact.start().mask(), none.start().mask());
6896    }
6897
6898    #[test]
6899    fn persisted_child_request_is_scoped_to_the_child() {
6900        let v = vocab();
6901        let mut parent = Grammar::from_glrm(r#"glrm 1; start start; extern grammar child; nt start = "x" child;"#).unwrap()
6902            .prepare(&v).unwrap();
6903        let child = Grammar::from_ebnf(r#"start ::= "y""#).unwrap().prepare_with(&v,
6904            BuildOptions::default().boundary_trigger(BoundaryTriggerDetail::TokenSet)).unwrap();
6905        parent.bindings.insert("child".to_owned(), ModuleBinding::Module(Arc::new(child)));
6906        let parent = PreparedGrammar::load(parent.save(), &v).unwrap();
6907        let linked = parent.clone().link_with(
6908            BuildOptions::default().boundary_trigger(BoundaryTriggerDetail::None),
6909        ).unwrap();
6910        assert!(matches!(linked.boundary_trigger, crate::runtime::BoundaryTrigger::None));
6911        let gated = parent.link_with(BuildOptions::default()).unwrap();
6912        assert!(matches!(gated.boundary_trigger, crate::runtime::BoundaryTrigger::TokenSet(_)));
6913    }
6914}
6915
6916
6917#[cfg(test)]
6918mod final_ordinary_dynamic_selection_tests {
6919    use super::*;
6920    #[test]
6921    fn fast_build_uses_the_actual_dynamic_compiler_and_preserves_loaded_representation() {
6922        let v=Vocab::from_entries_unchecked(vec![(0,b"(".to_vec()),(1,b")".to_vec()),(2,b"()".to_vec()),(3,b"x".to_vec())]);
6923        let g=Grammar::from_ebnf(r#"start ::= "(" start ")" start | """#).unwrap();
6924        let actual=g.compile_with_build_options(&v,BuildOptions::default().optimization(InternalMaskStrategy::FAST_COMPILE)).unwrap();
6925        let oracle=DynamicConstraint::compile(g.clone(),&v).unwrap().into_constraint();
6926        assert!(actual.uses_dynamic_runtime());
6927        assert!(!actual.has_template_parser()); assert!(actual.table.is_present());
6928        assert_eq!(actual.dynamic_mask_vocab.is_grammar_quotiented(),oracle.dynamic_mask_vocab.is_grammar_quotiented());
6929        for bytes in [actual.save(),actual.save()] {
6930            let restored=RuntimeConstraint::load(bytes,&v).unwrap();
6931            assert!(restored.uses_dynamic_runtime());
6932            assert!(!restored.has_template_parser()); assert!(restored.table.is_present());
6933            for prefix in [b"".as_slice(),b"(",b"()",b"()("] {
6934                let mut a=restored.start();let mut b=oracle.start_dynamic();
6935                assert!(a.commit_bytes(prefix));assert!(b.commit_bytes(prefix));
6936                assert_eq!(a.mask(),b.mask());assert_eq!(a.is_accepting(),b.is_accepting());
6937            }
6938        }
6939        let balanced=g.compile_with_build_options(&v,MaskMode::C.build_options()).unwrap();
6940        assert!(balanced.uses_dynamic_runtime()); assert!(balanced.has_template_parser());
6941        assert!(!balanced.table.is_present());
6942        for mode in [MaskMode::Auto,MaskMode::ParserDwa] {
6943            assert!(!g.compile_with_build_options(&v,mode.build_options()).unwrap().uses_dynamic_runtime());
6944        }
6945    }
6946}
6947
6948#[cfg(test)]
6949mod final_unsplit_dynamic_tests {
6950    use super::*;
6951    use crate::grammar::ast::{GrammarExpr, NamedGrammar, NamedRule};
6952    use crate::grammar::expr_nfa::ExprNFA;
6953    use crate::automata::unweighted_u32::nfa::NFA;
6954
6955    #[test]
6956    fn unsplit_embedded_regions_match_existing_multiple_root_union() {
6957        fn region(byte: u8) -> GrammarExpr {
6958            let mut nfa=NFA::new_empty();let start=nfa.add_state();let end=nfa.add_state();
6959            nfa.start_states.push(start);nfa.set_accepting(end);
6960            nfa.add_transition(start,0,end);nfa.add_transition(end,0,end);
6961            let mut expr=ExprNFA::new(nfa,vec![GrammarExpr::Literal(vec![byte])]);
6962            expr.prefer_direct_nfa_emission=true;
6963            GrammarExpr::ExprNFA(Box::new(expr))
6964        }
6965        let named=NamedGrammar {
6966            start:"root".into(),ignore:None,lexer_partitions:BTreeMap::new(),
6967            lexer_literal_partitions:BTreeMap::new(),default_lexer_partition:None,
6968            rules:vec![
6969                NamedRule {name:"root".into(),expr:GrammarExpr::Choice(vec![GrammarExpr::Sequence(vec![GrammarExpr::Ref("a".into()),GrammarExpr::Literal(b"x".to_vec())]),GrammarExpr::Sequence(vec![GrammarExpr::Ref("b".into()),GrammarExpr::Literal(b"x".to_vec())])]),is_terminal:false,is_internal:false},
6970                NamedRule {name:"a".into(),expr:region(b'a'),is_terminal:false,is_internal:false},
6971                NamedRule {name:"b".into(),expr:region(b'b'),is_terminal:false,is_internal:false},
6972            ],
6973        };
6974        let v=Vocab::from_entries_unchecked(vec![(0,b"a".to_vec()),(1,b"b".to_vec()),(2,b"aa".to_vec()),(3,b"bb".to_vec()),(4,b"ab".to_vec()),(5,b"x".to_vec()),(6,b"ax".to_vec()),(7,b"a".to_vec()),(8,b"bx".to_vec())]);
6975        let oracle=crate::import::compile_dynamic_named_union_for_test(named.clone(),&v).unwrap();
6976        assert!(oracle.clone_constraints().len()>1,"oracle must exercise the existing splitter");
6977        let c=crate::import::compile_dynamic_named_single(named,&v,
6978            crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,false).unwrap();
6979        assert!(c.uses_dynamic_runtime());assert!(!c.has_template_parser());
6980        for actual in [c.clone(),RuntimeConstraint::load(c.save(), &v).unwrap(),
6981            RuntimeConstraint::load(c.save(),&v).unwrap()] {
6982            for prefix in [b"".as_slice(),b"a",b"aa",b"b",b"bb",b"ax",b"bx",b"ab",b"ba"] {
6983                let mut a=actual.start();let mut o=oracle.start();
6984                let _=a.commit_bytes(prefix);let _=o.commit_bytes(prefix);
6985                assert_eq!(a.mask(),o.mask(),"after {prefix:?}");
6986                assert_eq!(a.is_accepting(),o.is_accepting());
6987                assert_eq!((a.mask().iter().all(|word| *word == 0)),(o.mask().iter().all(|word| *word == 0)));
6988                assert_eq!(a.forced_canonical_reference(),o.forced_canonical_reference());
6989            }
6990        }
6991    }
6992}
6993
6994#[cfg(test)]
6995mod bare_direct_region_regression_tests {
6996    use super::*;
6997    use crate::grammar::ast::{GrammarExpr, NamedGrammar, NamedRule};
6998    use crate::grammar::expr_nfa::ExprNFA;
6999    use crate::automata::unweighted_u32::nfa::NFA;
7000
7001    #[test]
7002    fn bare_region_union_and_unsplit_lr_preserve_the_complete_language() {
7003        fn region(byte:u8)->GrammarExpr {
7004            let mut nfa=NFA::new_empty();let start=nfa.add_state();let end=nfa.add_state();
7005            nfa.start_states.push(start);nfa.set_accepting(end);
7006            nfa.add_transition(start,0,end);nfa.add_transition(end,0,end);
7007            GrammarExpr::ExprNFA(Box::new(ExprNFA::new(nfa,vec![GrammarExpr::Literal(vec![byte])])
7008                .with_embedded_direct_nfa_emission()))
7009        }
7010        let named=NamedGrammar { start:"root".into(),ignore:None,lexer_partitions:BTreeMap::new(),
7011            lexer_literal_partitions:BTreeMap::new(),default_lexer_partition:None,
7012            rules:vec![
7013                NamedRule{name:"root".into(),expr:GrammarExpr::Choice(vec![GrammarExpr::Ref("a".into()),GrammarExpr::Ref("b".into())]),is_terminal:false,is_internal:false},
7014                NamedRule{name:"a".into(),expr:region(b'a'),is_terminal:false,is_internal:false},
7015                NamedRule{name:"b".into(),expr:region(b'b'),is_terminal:false,is_internal:false}] };
7016        let v=Vocab::from_entries_unchecked(vec![(0,b"a".to_vec()),(1,b"b".to_vec()),(2,b"aa".to_vec()),
7017            (3,b"bb".to_vec()),(4,b"ab".to_vec()),(7,b"a".to_vec())]);
7018        let union=crate::import::compile_dynamic_named_union_for_test(named.clone(),&v).unwrap();
7019        let single=crate::import::compile_dynamic_named_single(named,&v,
7020            crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,false).unwrap();
7021        assert_eq!(union.clone_constraints().len(),2);
7022        for c in union.clone_constraints() {
7023            assert!(c.table.is_present()); assert!(!c.table.action.is_empty());
7024            assert!(c.direct_regular_automaton.is_none()); assert!(!c.has_template_parser());
7025        }
7026        assert_eq!(union.start().mask(),vec![143]);
7027        for actual in [single.clone(),RuntimeConstraint::load(single.save(), &v).unwrap(),
7028            RuntimeConstraint::load(single.save(),&v).unwrap()] {
7029            for (prefix,mask,accept,reject) in [(b"".as_slice(),143,false,false),(b"a",133,true,false),
7030                (b"aa",133,true,false),(b"b",10,true,false),(b"bb",10,true,false),
7031                (b"ab",0,false,true),(b"ba",0,false,true)] {
7032                let mut a=actual.start();let mut o=union.start();
7033                let ae= a.commit_bytes(prefix);let oe= o.commit_bytes(prefix);
7034                assert_eq!(!ae,!oe,"after {prefix:?}");
7035                assert_eq!(a.mask(),vec![mask],"unsplit after {prefix:?}");
7036                assert_eq!(o.mask(),vec![mask],"union after {prefix:?}");
7037                assert_eq!((a.is_accepting(),(a.mask().iter().all(|word| *word == 0))),(accept,reject));
7038                assert_eq!((o.is_accepting(),(o.mask().iter().all(|word| *word == 0))),(accept,reject));
7039                assert_eq!(a.forced_canonical_reference(),o.forced_canonical_reference());
7040            }
7041        }
7042    }
7043}
7044
7045#[cfg(test)]
7046mod static_whole_token_regression_tests {
7047    use super::*;
7048    #[test]
7049    fn compressed_whole_word_is_allowed_before_and_after_reload() {
7050        let mut source=String::from("start: r0\n");for i in 0..30 {source.push_str(&format!("r{i}: \"a\" r{}\n",i+1));}source.push_str("r30: \"b\"\n");
7051        let mut word=vec![b'a';30];word.push(b'b');
7052        for entries in [vec![(3,word.clone())],vec![(0,b"a".to_vec()),(1,b"b".to_vec()),(2,b"aa".to_vec()),(3,word.clone())]] {
7053            let singleton=entries.len()==1;let v=Vocab::from_entries_unchecked(entries);
7054            for mode in [MaskMode::Auto,MaskMode::ParserDwa] {
7055                let c=Grammar::from_lark(&source).unwrap().compile_with_build_options(&v,mode.build_options()).unwrap();
7056                assert!(c.direct_regular_automaton.is_some());
7057                for c in [c.clone(),RuntimeConstraint::load(c.save(), &v).unwrap(),RuntimeConstraint::load(c.save(),&v).unwrap()] {
7058                    let mut state=c.start();assert_eq!(state.mask(),vec![if singleton {8} else {13}]);
7059                    assert!(state.commit_token(3));assert!(state.is_accepting());assert!(state.mask().iter().all(|word| *word == 0));
7060                }
7061            }
7062        }
7063    }
7064}
7065
7066#[cfg(test)]
7067mod tiny_cfg_compile_blowup_tests {
7068    use super::*;
7069
7070    // Random tiny CFGs reduced from the compile-time blow-up repro. Symbols
7071    // >= 0 are nonterminals; symbol < 0 is byte b'a' + (-symbol - 1).
7072    struct Case {
7073        start: usize,
7074        bound: usize,
7075        rules: &'static [(usize, &'static [isize])],
7076    }
7077
7078    // Minimised from case 296 by deleting rules and symbols while the
7079    // compile stayed above the timeout. It keeps the nullable left-recursive
7080    // core that produced the template blow-up.
7081    const COMPACT: Case = Case {
7082        start: 1,
7083        bound: 3,
7084        rules: &[
7085            (1, &[-3]),
7086            (0, &[1, -2]),
7087            (1, &[1, 0, 1]),
7088            (1, &[]),
7089        ],
7090    };
7091
7092    fn lark(case: &Case) -> String {
7093        let mut by_lhs: BTreeMap<usize, Vec<String>> = BTreeMap::new();
7094        let mut defined = BTreeSet::new();
7095        for (lhs, rhs) in case.rules {
7096            defined.insert(*lhs);
7097            let mut alternatives = Vec::new();
7098            let mut text = String::new();
7099            for symbol in *rhs {
7100                if !text.is_empty() {
7101                    text.push(' ');
7102                }
7103                if *symbol >= 0 {
7104                    text.push_str(&format!("n{symbol}"));
7105                } else {
7106                    let byte = (b'a' + ((-*symbol - 1) as u8)) as char;
7107                    text.push('"');
7108                    text.push(byte);
7109                    text.push('"');
7110                }
7111            }
7112            if text.is_empty() {
7113                text.push_str("\"\"");
7114            }
7115            alternatives.push(text);
7116            by_lhs.entry(*lhs).or_default().extend(alternatives);
7117        }
7118        for (lhs, rhs) in case.rules {
7119            for symbol in *rhs {
7120                assert!(
7121                    *symbol < 0 || defined.contains(&(*symbol as usize)),
7122                    "referenced nonterminal must have a production",
7123                );
7124            }
7125        }
7126        let mut source = String::new();
7127        source.push_str(&format!("start: n{}\n", case.start));
7128        for (lhs, alternatives) in &by_lhs {
7129            source.push_str(&format!("n{lhs}: {}\n", alternatives.join(" | ")));
7130        }
7131        source
7132    }
7133
7134    fn vocabulary() -> Vocab {
7135        Vocab::from_entries_unchecked(vec![(0, vec![b'a']), (1, vec![b'b']), (2, vec![b'c'])])
7136    }
7137
7138    fn bounded_language(case: &Case) -> BTreeSet<Vec<u8>> {
7139        // Prefix validity is a property of the unbounded language: e.g. the
7140        // prefix "bcc" is witnessed only by the four-byte word "bccb". Derive
7141        // a generous margin beyond the checked word length so every prefix of
7142        // a checked word has a witness; membership of the short words
7143        // themselves is unaffected.
7144        let limit = case.bound + 2;
7145        let mut sets: BTreeMap<usize, BTreeSet<Vec<u8>>> = BTreeMap::new();
7146        for (lhs, _) in case.rules {
7147            sets.entry(*lhs).or_default();
7148        }
7149        loop {
7150            let mut changed = false;
7151            for (lhs, rhs) in case.rules {
7152                let mut words: BTreeSet<Vec<u8>> = std::iter::once(Vec::new()).collect();
7153                for symbol in *rhs {
7154                    let next = if *symbol >= 0 {
7155                        sets.get(&(*symbol as usize)).cloned().unwrap_or_default()
7156                    } else {
7157                        std::iter::once(vec![b'a' + ((-*symbol - 1) as u8)]).collect()
7158                    };
7159                    let mut product = BTreeSet::new();
7160                    for prefix in &words {
7161                        for suffix in &next {
7162                            if prefix.len() + suffix.len() <= limit {
7163                                let mut word = prefix.clone();
7164                                word.extend_from_slice(suffix);
7165                                product.insert(word);
7166                            }
7167                        }
7168                    }
7169                    words = product;
7170                }
7171                let target = sets.get_mut(lhs).expect("defined above");
7172                for word in words {
7173                    changed |= target.insert(word);
7174                }
7175            }
7176            if !changed {
7177                break;
7178            }
7179        }
7180        sets.remove(&case.start).unwrap_or_default()
7181    }
7182
7183    fn all_words(case: &Case) -> Vec<Vec<u8>> {
7184        let mut words = vec![Vec::new()];
7185        let mut level = vec![Vec::new()];
7186        for _ in 0..case.bound {
7187            let mut next = Vec::new();
7188            for word in &level {
7189                for byte in *b"abc" {
7190                    let mut extended = word.clone();
7191                    extended.push(byte);
7192                    next.push(extended);
7193                }
7194            }
7195            words.extend(next.iter().cloned());
7196            level = next;
7197        }
7198        words
7199    }
7200
7201    fn assert_exact(constraint: &RuntimeConstraint, case: &Case) {
7202        let language = bounded_language(case);
7203        let words = all_words(case);
7204        for word in &words {
7205            let mut state = constraint.start();
7206            let mut alive = true;
7207            for (position, byte) in word.iter().enumerate() {
7208                let mask = state.mask();
7209                for candidate in 0..3u8 {
7210                    let mut prefix = word[..position].to_vec();
7211                    prefix.push(b'a' + candidate);
7212                    let expected = language
7213                        .iter()
7214                        .any(|word| word.starts_with(&prefix));
7215                    let id = candidate as usize;
7216                    let allowed = mask[id / 32] & (1 << (id % 32)) != 0;
7217                    assert_eq!(
7218                        allowed, expected,
7219                        "mask mismatch at {:?}[{position}] for token {candidate}",
7220                        String::from_utf8_lossy(word),
7221                    );
7222                }
7223                for id in 3..(mask.len() * 32) {
7224                    assert_eq!(
7225                        mask[id / 32] & (1 << (id % 32)),
7226                        0,
7227                        "unexpected token id {id} at {:?}[{position}]",
7228                        String::from_utf8_lossy(word),
7229                    );
7230                }
7231                let id = (byte - b'a') as usize;
7232                if mask[id / 32] & (1 << (id % 32)) == 0 {
7233                    // The prefix is already outside the language; the exact
7234                    // mask assertion above is the check for this word.
7235                    alive = false;
7236                    break;
7237                }
7238                assert!(state
7239                    .commit_token((byte - b'a') as u32));
7240            }
7241            if alive {
7242                assert_eq!(
7243                    state.is_accepting(),
7244                    language.contains(word),
7245                    "acceptance mismatch for {:?}",
7246                    String::from_utf8_lossy(word),
7247                );
7248            } else {
7249                assert!(
7250                    !language.contains(word),
7251                    "mask rejected an in-language word {:?}",
7252                    String::from_utf8_lossy(word),
7253                );
7254            }
7255        }
7256    }
7257
7258    fn compile(case: &Case, strategy: MaskMode) -> RuntimeConstraint {
7259        let source = lark(case);
7260        let grammar = Grammar::from_lark(&source).unwrap();
7261        let module = Module::new(&grammar);
7262        module
7263            .compile_inner_with(&vocabulary(), strategy.compile_options())
7264            .unwrap()
7265    }
7266
7267    #[test]
7268    fn compact_nullable_left_recursive_grammar_builds_minimal_templates() {
7269        for strategy in [MaskMode::C, MaskMode::ParserDwa] {
7270            let constraint = compile(&COMPACT, strategy);
7271            assert!(
7272                !constraint.table.is_present(),
7273                "the compact grammar must keep its finite templates",
7274            );
7275            assert!(constraint.template_parser.is_some());
7276            assert_exact(&constraint, &COMPACT);
7277        }
7278    }
7279}
7280
7281#[cfg(test)]
7282mod module_build_overhead_tests {
7283    use super::*;
7284    use crate::__private::VocabExt as _;
7285    use std::time::Instant;
7286
7287    fn jsb_like_schema(properties: usize) -> String {
7288        let props = (0..properties)
7289            .map(|i| (format!("p{i}"), serde_json::json!({"type": "integer"})))
7290            .collect::<serde_json::Map<_, _>>();
7291        serde_json::json!({
7292            "type": "object",
7293            "additionalProperties": false,
7294            "properties": props,
7295        })
7296        .to_string()
7297    }
7298
7299    fn jsb_like_vocab(tokens: u32) -> Vocab {
7300        let vocab = Vocab::from_entries_unchecked((0..tokens).map(|id| (id, format!("t{id}").into_bytes())).collect());
7301        vocab.prepare_for_compile();
7302        vocab
7303    }
7304
7305    fn minimum(values: &[f64]) -> f64 {
7306        values.iter().copied().fold(f64::INFINITY, f64::min)
7307    }
7308
7309    /// A standalone Module builds the same default TokenSet trigger as the
7310    /// direct Grammar path, and must stay close to it in build time.
7311    #[test]
7312    fn module_standalone_build_stays_close_to_grammar_build() {
7313        let vocab = jsb_like_vocab(16_384);
7314        let source = jsb_like_schema(80);
7315
7316        let grammar = Grammar::from_json_schema(&source).unwrap();
7317        let direct = grammar
7318            .compile_with_build_options(
7319                &vocab,
7320                BuildOptions::default()
7321                    .optimization(InternalMaskStrategy::ParserDwa)
7322                    .end_tokens([0u32]),
7323            )
7324            .expect("direct build");
7325        let standalone = Module::from_expr(&Expr::sequence([
7326            Expr::from(grammar.clone()),
7327            Expr::from(TokenSet::new([0u32])),
7328        ]), true)
7329        .expect("root expression")
7330        .compile_inner(&vocab)
7331        .expect("module build");
7332        assert!(
7333            matches!(standalone.boundary_trigger, crate::runtime::BoundaryTrigger::TokenSet(_)),
7334            "standalone Module must carry the default TokenSet trigger"
7335        );
7336        assert_eq!(
7337            standalone.boundary_trigger.token_summary(),
7338            direct.boundary_trigger.token_summary(),
7339            "Module and Grammar must agree on the standalone token set"
7340        );
7341
7342        // One untimed warm-up pair: the first compile of each shape pays lazy
7343        // pool and cache initialization that neither steady-state path should
7344        // be charged for.
7345        {
7346            let grammar = Grammar::from_json_schema(&source).unwrap();
7347            grammar
7348                .compile_with_build_options(
7349                    &vocab,
7350                    BuildOptions::default()
7351                        .optimization(InternalMaskStrategy::ParserDwa)
7352                        .end_tokens([0u32]),
7353                )
7354                .expect("warmup direct build");
7355            let grammar = Grammar::from_json_schema(&source).unwrap();
7356            Module::from_expr(&Expr::sequence([
7357                Expr::from(grammar.clone()),
7358                Expr::from(TokenSet::new([0u32])),
7359            ]), true)
7360            .expect("root expression")
7361            .compile_inner(&vocab)
7362            .expect("warmup module build");
7363        }
7364
7365        let mut grammar_ms = Vec::new();
7366        let mut module_ms = Vec::new();
7367        for _ in 0..7 {
7368            let grammar = Grammar::from_json_schema(&source).unwrap();
7369            let started = Instant::now();
7370            grammar
7371                .compile_with_build_options(
7372                    &vocab,
7373                    BuildOptions::default()
7374                        .optimization(InternalMaskStrategy::ParserDwa)
7375                        .end_tokens([0u32]),
7376                )
7377                .expect("direct build");
7378            grammar_ms.push(started.elapsed().as_secs_f64() * 1000.0);
7379
7380            let grammar = Grammar::from_json_schema(&source).unwrap();
7381            let started = Instant::now();
7382            Module::from_expr(&Expr::sequence([
7383                Expr::from(grammar.clone()),
7384                Expr::from(TokenSet::new([0u32])),
7385            ]), true)
7386            .expect("root expression")
7387            .compile_inner(&vocab)
7388            .expect("module build");
7389            module_ms.push(started.elapsed().as_secs_f64() * 1000.0);
7390        }
7391        // Uncontended work time: noise only ever adds time, so the minimum is
7392        // the robust estimator for these single-shot compiles.
7393        let grammar_min = minimum(&grammar_ms);
7394        let module_min = minimum(&module_ms);
7395        eprintln!(
7396            "[module-build-overhead] grammar_min={grammar_min:.3}ms module_min={module_min:.3}ms ratio={:.2} grammar_ms={grammar_ms:?} module_ms={module_ms:?}",
7397            module_min / grammar_min
7398        );
7399        assert!(
7400            module_min <= grammar_min * 1.5,
7401            "Module build minimum {module_min:.3}ms is more than 1.5x the direct Grammar build minimum {grammar_min:.3}ms; grammar samples {grammar_ms:?}, module samples {module_ms:?}",
7402        );
7403    }
7404}
7405
7406#[cfg(test)]
7407mod mask_strategy_configuration_tests {
7408    use super::*;
7409    use crate::__private::VocabExt as _;
7410    use crate::test_modes::MaskMode;
7411
7412    fn merged_vocab() -> Vocab {
7413        let vocab = Vocab::from_entries_unchecked(vec![
7414            (0, b"a".to_vec()),
7415            (1, b"b".to_vec()),
7416            (2, b"ab".to_vec()),
7417            (3, b"x".to_vec()),
7418            (4, b"y".to_vec()),
7419        ]);
7420        vocab.prepare_for_compile();
7421        vocab
7422    }
7423
7424    fn composed_module(child: &Grammar) -> Module {
7425        let mut parent = Module::new(
7426            &Grammar::from_glrm(
7427                r#"glrm 1; start start; extern grammar child; nt start = "x" child "y";"#,
7428            )
7429            .unwrap(),
7430        );
7431        parent.bind("child", child).unwrap();
7432        parent
7433    }
7434
7435    fn assert_same_language(
7436        reference: &crate::ConstraintState,
7437        candidate: &crate::ConstraintState,
7438        depth: usize,
7439    ) -> usize {
7440        let mask = reference.mask();
7441        assert_eq!(mask, candidate.mask(), "mask mismatch at depth {depth}");
7442        assert_eq!(
7443            reference.is_accepting(),
7444            candidate.is_accepting(),
7445            "acceptance mismatch at depth {depth}",
7446        );
7447        if depth == 0 {
7448            return 1;
7449        }
7450        let mut visited = 1;
7451        for (word, bits) in mask.iter().enumerate() {
7452            for bit in 0..32 {
7453                if bits & (1 << bit) == 0 {
7454                    continue;
7455                }
7456                let token = (word * 32 + bit) as u32;
7457                let mut next_reference = reference.clone();
7458                assert!(next_reference.commit_token(token));
7459                let mut next_candidate = candidate.clone();
7460                assert!(next_candidate.commit_token(token));
7461                visited += assert_same_language(&next_reference, &next_candidate, depth - 1);
7462            }
7463        }
7464        visited
7465    }
7466
7467    fn assert_inputs_match(
7468        merged: &RuntimeConstraint,
7469        unmerged: &RuntimeConstraint,
7470        inputs: &[&[u32]],
7471    ) {
7472        for input in inputs {
7473            let mut merged_state = merged.start();
7474            let mut unmerged_state = unmerged.start();
7475            for &token in *input {
7476                assert_eq!(
7477                    merged_state.mask(),
7478                    unmerged_state.mask(),
7479                    "mask mismatch before token {token} in {input:?}",
7480                );
7481                assert_eq!(
7482                    merged_state.is_accepting(),
7483                    unmerged_state.is_accepting(),
7484                    "acceptance mismatch before token {token} in {input:?}",
7485                );
7486                let merged_commit = merged_state.commit_token(token);
7487                let unmerged_commit = unmerged_state.commit_token(token);
7488                assert_eq!(merged_commit, unmerged_commit, "commit mismatch for {input:?}");
7489                if !merged_commit {
7490                    break;
7491                }
7492            }
7493            assert_eq!(merged_state.mask(), unmerged_state.mask(), "final mask {input:?}");
7494            assert_eq!(
7495                merged_state.is_accepting(),
7496                unmerged_state.is_accepting(),
7497                "final acceptance {input:?}",
7498            );
7499        }
7500    }
7501
7502    #[test]
7503    fn merged_compositions_match_unmerged_masks() {
7504        // Regression for byte-spanning child boundaries: "xay" can be one
7505        // token spanning x + child(a) + y, while "ay" cannot.
7506        let tokens: [(u32, Vec<u8>); 9] = [
7507            (0, b"x".to_vec()),
7508            (1, b"a".to_vec()),
7509            (2, b"y".to_vec()),
7510            (3, b"xay".to_vec()),
7511            (4, b"xy".to_vec()),
7512            (5, b"ay".to_vec()),
7513            (6, b"aa".to_vec()),
7514            (7, b"yx".to_vec()),
7515            (8, b"".to_vec()),
7516        ];
7517        let vocab = Vocab::from_entries_unchecked(tokens.to_vec());
7518        let child = Grammar::from_glrm("start root t A = /a?/ nt root = A").unwrap();
7519        let mut parent = Module::new(
7520            &Grammar::from_glrm(
7521                r#"glrm 1; start root; extern grammar C; nt root = "x" C "y";"#,
7522            )
7523            .unwrap(),
7524        );
7525        parent.bind("C", child).unwrap();
7526        let unmerged = parent
7527            .compile_inner_with(&vocab, MaskMode::A.compile_options())
7528            .expect("unmerged TokenTrie compile");
7529        let merged = parent
7530            .compile_inner_with(&vocab, MaskMode::C.compile_options())
7531            .expect("merged compile");
7532        let merged_lr = parent
7533            .compile_inner_with(&vocab, MaskMode::D.compile_options())
7534            .expect("merged LR compile");
7535        assert!(merged.runtime_is_grammar_quotiented(), "C flattened composition must be quotiented");
7536        assert!(merged_lr.runtime_is_grammar_quotiented(), "D flattened composition must be quotiented");
7537        assert_eq!(merged_lr.parser_backend(), ParserBackend::LrTable);
7538        assert!(merged_lr.runtime_has_lr_table());
7539        assert!(!merged_lr.runtime_has_template_parser());
7540        assert_inputs_match(
7541            &merged,
7542            &unmerged,
7543            &[
7544                &[],
7545                &[3],
7546                &[4],
7547                &[5],
7548                &[0],
7549                &[0, 1],
7550                &[0, 1, 2],
7551                &[3, 3],
7552                &[4, 3],
7553            ],
7554        );
7555        assert_inputs_match(
7556            &merged_lr,
7557            &unmerged,
7558            &[
7559                &[],
7560                &[3],
7561                &[4],
7562                &[5],
7563                &[0],
7564                &[0, 1],
7565                &[0, 1, 2],
7566                &[3, 3],
7567                &[4, 3],
7568            ],
7569        );
7570
7571        // A second composition, with an ordinary child grammar.
7572        let vocab = merged_vocab();
7573        let child = Grammar::from_ebnf(r#"start ::= "a" | "b""#).unwrap();
7574        let parent = composed_module(&child);
7575        let unmerged = parent
7576            .compile_inner_with(&vocab, MaskMode::A.compile_options())
7577            .expect("unmerged TokenTrie compile");
7578        let merged = parent
7579            .compile_inner_with(&vocab, MaskMode::C.compile_options())
7580            .expect("merged compile");
7581        let merged_lr = parent
7582            .compile_inner_with(&vocab, MaskMode::D.compile_options())
7583            .expect("merged LR compile");
7584        assert!(merged.runtime_is_grammar_quotiented());
7585        assert!(merged_lr.runtime_is_grammar_quotiented());
7586        assert_inputs_match(&merged, &unmerged, &[&[], &[0], &[0, 1], &[0, 3], &[3, 0], &[4, 0]]);
7587        assert_inputs_match(&merged_lr, &unmerged, &[&[], &[0], &[0, 1], &[0, 3], &[3, 0], &[4, 0]]);
7588
7589        // Two levels of composition flatten into one partition.
7590        let nested_vocab = Vocab::from_entries_unchecked(vec![
7591            (0, b"a".to_vec()),
7592            (3, b"x".to_vec()),
7593            (4, b"y".to_vec()),
7594            (5, b"(".to_vec()),
7595            (6, b")".to_vec()),
7596            (7, b"(a)".to_vec()),
7597            (8, Vec::new()),
7598        ]);
7599        let leaf = Grammar::from_ebnf(r#"start ::= "a"?"#).unwrap();
7600        let mut middle = Module::new(
7601            &Grammar::from_glrm(r#"glrm 1; start root; extern grammar leaf; nt root = "(" leaf ")";"#)
7602                .unwrap(),
7603        );
7604        middle.bind("leaf", leaf).unwrap();
7605        let mut top = Module::new(
7606            &Grammar::from_glrm(r#"glrm 1; start root; extern grammar middle; nt root = "x" middle "y";"#)
7607                .unwrap(),
7608        );
7609        top.bind("middle", middle).unwrap();
7610        let unmerged = top
7611            .compile_inner_with(&nested_vocab, MaskMode::A.compile_options())
7612            .unwrap();
7613        let merged_lr = top
7614            .compile_inner_with(&nested_vocab, MaskMode::D.compile_options())
7615            .unwrap();
7616        assert!(merged_lr.runtime_is_grammar_quotiented());
7617        assert_inputs_match(&merged_lr, &unmerged, &[&[], &[0], &[0, 5], &[4, 0], &[0, 7, 3]]);
7618
7619        // A local C compile still uses its own quotient.
7620        let local = Grammar::from_ebnf(r#"start ::= "a" "b" | "ab""#)
7621            .unwrap()
7622            .compile_inner_with(&merged_vocab(), MaskMode::C.compile_options())
7623            .unwrap();
7624        assert!(local.dynamic_mask_vocab.is_grammar_quotiented());
7625    }
7626
7627    #[test]
7628    fn merged_request_over_retained_parts_keeps_them_and_matches_unmerged() {
7629        let vocab = merged_vocab();
7630        let child = Grammar::from_ebnf(r#"start ::= "a" | "b""#).unwrap();
7631        let mut parent = composed_module(&child);
7632        parent
7633            .precompile_with(&vocab, MaskMode::ParserDwa.compile_options())
7634            .unwrap();
7635        let unmerged = parent
7636            .compile_inner_with(&vocab, MaskMode::A.compile_options())
7637            .unwrap();
7638        for mode in [MaskMode::C, MaskMode::D] {
7639            let merged = parent
7640                .compile_inner_with(&vocab, mode.compile_options())
7641                .unwrap();
7642            assert_inputs_match(&merged, &unmerged, &[&[], &[0], &[0, 1], &[0, 3], &[3, 0], &[4, 0]]);
7643        }
7644    }
7645
7646    #[test]
7647    fn merged_flatten_resolves_lark_and_json_schema_children() {
7648        let vocab = Vocab::from_entries_unchecked(vec![
7649            (0, b"x".to_vec()),
7650            (1, b"y".to_vec()),
7651            (2, b"a".to_vec()),
7652            (3, b"\"a\"".to_vec()),
7653            (4, Vec::new()),
7654        ]);
7655        let lark = Grammar::from_lark(r#"start: "a""#).unwrap();
7656        let json = Grammar::from_json_schema(r#"{"type":"string","maxLength":1}"#).unwrap();
7657        let build = || {
7658            let mut parent = Module::new(
7659                &Grammar::from_glrm(
7660                    r#"glrm 1; start root; extern grammar L; extern grammar J; nt root = "x" L "y" | J;"#,
7661                )
7662                .unwrap(),
7663            );
7664            parent.bind("L", lark.clone()).unwrap();
7665            parent.bind("J", json.clone()).unwrap();
7666            parent
7667        };
7668        let unmerged = build()
7669            .compile_inner_with(&vocab, MaskMode::A.compile_options())
7670            .unwrap();
7671        for mode in [MaskMode::C, MaskMode::D] {
7672            let merged = build()
7673                .compile_inner_with(&vocab, mode.compile_options())
7674                .unwrap();
7675            assert!(
7676                merged.runtime_is_grammar_quotiented(),
7677                "{mode:?}: flattened composition must be quotiented",
7678            );
7679            assert_inputs_match(&merged, &unmerged, &[&[], &[0], &[0, 2], &[0, 2, 1], &[3], &[0, 3]]);
7680        }
7681    }
7682}