Skip to main content

glrmask/
lib.rs

1#![recursion_limit = "256"]
2
3//! <!-- Generated by scripts/sync-guide.py from docs/content. Do not edit this output. -->
4//!
5//! GLRMask is a grammar-constrained decoding library for high-throughput LLM serving. It is optimized for fast mask computation with extremely low tail latency, even for complex grammars.
6//!
7//! GLRMask supports general context-free grammars, including ambiguous ones. It accepts JSON Schema, Lark and [GLRM](https://github.com/IsaacBreen/glrmask/blob/v1.0.0-rc.1/docs/glrm-format.md).
8//!
9//! # Installation
10//!
11//! ```bash
12//! cargo add glrmask
13//! ```
14//!
15//! GLRMask needs Rust 1.89 or later. A minor release may raise the minimum Rust version; a patch release won't.
16//!
17//! # Usage
18//!
19//! GLRMask has four core types:
20//!
21//! - `Grammar`: a grammar, written as source text or built from an expression.
22//! - `Constraint`: a compiled grammar, ready to use.
23//! - `ConstraintState`: the state of one generated sequence.
24//! - `Module`: a partially compiled grammar ([see below](#composing-grammars)).
25//!
26//! In the quickstart, supply the tokenizer's exact token bytes and the model's EOS ID. The model produces logits; the sampling routine must apply the packed mask and permit EOS only when the state is accepting.
27//!
28//! # Quickstart
29//!
30//! ```rust
31//! # use glrmask::{Grammar, Vocab};
32//! # const EOS: u32 = 256;
33//! # fn model(output: &[u32]) -> Vec<f32> {
34//! #     // 256 byte tokens + EOS
35//! #     (0..=EOS as usize).map(|t| ((t * 7919 + output.len() * 104_729) % 1000) as f32).collect()
36//! # }
37//! # fn sample(logits: &[f32], mask: &[u32], accepting: bool) -> u32 {
38//! #     (0..=EOS).filter(|&id| if id == EOS { accepting } else { mask[id as usize / 32] >> (id % 32) & 1 == 1 })
39//! #         .max_by(|&a, &b| logits[a as usize].total_cmp(&logits[b as usize])).expect("no allowed token and cannot stop")
40//! # }
41//! # fn main() -> glrmask::Result<()> {
42//! # // Replace with your tokenizer's token bytes
43//! # let token_bytes = (0..256u32).map(|id| (id, vec![id as u8]));
44//! let grammar = Grammar::from_json_schema(r#"
45//!     {
46//!         "type": "object",
47//!         "properties": {
48//!             "color": {
49//!                 "enum": ["red", "green", "blue"]
50//!             }
51//!         },
52//!         "required": ["color"],
53//!         "additionalProperties": false
54//!     }
55//! "#)?;
56//!
57//! // Token ID -> exact bytes from tokenizer
58//! let vocab = Vocab::new(token_bytes)?;
59//! let constraint = grammar.compile(&vocab)?;
60//! let mut state = constraint.start();
61//!
62//! let mut output = Vec::new();
63//! loop {
64//!     let logits = model(&output);
65//!     let mask = state.mask();
66//!     let token = sample(&logits, &mask, state.is_accepting());
67//!     if token == EOS { break; }
68//!     assert!(state.commit_token(token));
69//!     output.push(token);
70//! }
71//! # assert!(state.is_accepting());
72//! # let bytes: Vec<u8> = output.into_iter().map(|t| t as u8).collect();
73//! # println!("{}", String::from_utf8_lossy(&bytes));
74//! # Ok(())
75//! # }
76//! ```
77//!
78//! # Composing grammars
79//!
80//! In a typical serving setup, a grammar constraint is one main grammar with smaller grammars nested inside it, some of which, like tool schemas, change from request to request. GLRMask is built to make this kind of composition cheap. Like modules in a program, grammars can be written and compiled as separate parts and combined later.
81//!
82//! A server compiles its main grammar once as a `Module` with named externs. Each tool's schema is compiled on its own, in parallel or on another machine. For each request, GLRMask composes the main grammar with the compiled schemas by filling in the externs.
83//!
84//! Resolving the interactions between them requires some extra *boundary* work. However, this work is usually small compared with compiling the grammars themselves, so composition remains cheap even when the grammars are large.
85//!
86//! ```rust
87//! # use glrmask::{Grammar, Module, Vocab};
88//! # fn main() -> glrmask::Result<()> {
89//! # // Replace with your tokenizer's token bytes
90//! # let token_bytes = (0..256u32).map(|id| (id, vec![id as u8]));
91//! // Token ID -> exact bytes from tokenizer
92//! let vocab = Vocab::new(token_bytes)?;
93//!
94//! let weather = Grammar::from_json_schema(r#"
95//!     {
96//!         "type": "object",
97//!         "properties": {
98//!             "city": {"type": "string"}
99//!         },
100//!         "required": ["city"],
101//!         "additionalProperties": false
102//!     }
103//! "#)?.compile(&vocab)?;
104//!
105//! let parent = Grammar::from_glrm(r#"
106//!     extern grammar ARGS
107//!     start call
108//!     nt call = "<weather>" ARGS "</weather>"
109//! "#)?;
110//! let mut call = Module::new(&parent);
111//! call.bind("ARGS", &weather)?;
112//! let constraint = call.compile(&vocab)?;
113//! # let mut state = constraint.start();
114//! # assert!(state.commit_bytes(b"<weather>{\"city\": \"Perth\"}</weather>"));
115//! # assert!(state.is_accepting());
116//! # Ok(())
117//! # }
118//! ```
119//!
120//! # Learn more
121//!
122//! [Full guide](https://github.com/IsaacBreen/glrmask/blob/v1.0.0-rc.1/GUIDE.md) ยท [API reference](https://docs.rs/glrmask/latest/glrmask/)
123//!
124#![deny(warnings)]
125#![allow(dead_code)]
126#![allow(unused_variables)]
127
128pub(crate) mod automata;
129pub(crate) mod compiler;
130pub(crate) mod ds;
131pub(crate) mod env;
132mod error;
133mod artifact_load;
134mod public_api;
135// Data-only parser construction remains an unstable tooling API.
136#[cfg(any(test, feature = "internal-api"))]
137#[doc(hidden)]
138pub mod template_parser;
139#[cfg(not(any(test, feature = "internal-api")))]
140#[allow(unused_imports)]
141pub(crate) mod template_parser;
142pub(crate) use glrmask_grammar::__private::grammar;
143pub(crate) mod import;
144pub(crate) mod programmatic_js;
145pub(crate) mod runtime;
146#[path = "runtime/dynamic_constraint.rs"]
147mod dynamic_constraint;
148pub(crate) use glrmask_vocab::__private as vocab;
149pub(crate) use public_api::with_deep_stack;
150
151pub use runtime::ConstraintState;
152mod constraint_handle;
153pub use constraint_handle::Constraint;
154#[cfg(any(test, feature = "internal-api"))]
155#[doc(hidden)]
156pub use runtime::ConstraintInner;
157#[cfg(any(test, feature = "internal-api"))]
158#[doc(hidden)]
159pub use runtime::markers::{MarkerEvent, MarkerId};
160pub use glrmask_vocab::{TokenSet, Vocab};
161pub use error::{Error, ErrorKind, Result};
162pub use public_api::{Grammar, Module, CompileOptions, Expr, MaskStrategy, Extern, Externs, ExternIter, ExternIntoIter};
163#[cfg(any(test, feature = "internal-api"))]
164#[doc(hidden)]
165pub use public_api::{InternalMaskStrategy, InternalBoundaryMaskStrategy, ParserBackend, TokenTrie};
166#[cfg(not(any(test, feature = "internal-api")))]
167pub(crate) use public_api::InternalMaskStrategy;
168#[cfg(any(test, feature = "internal-api"))]
169#[doc(hidden)]
170pub use public_api::{
171    BuildOptions, PreparedGrammar, UnlinkedConstraint, Requirement,
172};
173#[cfg(any(test, feature = "internal-api"))]
174#[doc(hidden)]
175pub use runtime::BoundaryTriggerDetail;
176pub use glrmask_grammar::ExternKind;
177
178/// Unstable compatibility surface for repository tooling and benchmark
179/// harnesses. It is deliberately absent from normal dependency builds.
180#[cfg(any(test, feature = "internal-api"))]
181#[doc(hidden)]
182pub use dynamic_constraint::{DynamicConstraint, DynamicConstraintState};
183#[cfg(any(test, feature = "internal-api"))]
184#[doc(hidden)]
185pub use public_api::{
186    BoundarySummaryPolicy, ConstraintSpec, ConstraintSpecBuilder, VocabPartition,
187    VocabPartitionStrategy,
188};
189
190#[cfg(test)]
191pub(crate) static TEST_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
192
193/// Run an environment-mutating test in its own process. A writers-only mutex
194/// cannot protect unrelated tests that legitimately read production flags.
195/// Call this from the libtest entry, before spawning any custom-stack worker.
196/// Returns true in the parent after the exact child test has passed.
197#[cfg(test)]
198pub(crate) fn isolate_environment_test(ignored: bool) -> bool {
199    const CHILD: &str = "GLRMASK_ISOLATED_ENVIRONMENT_TEST";
200    let current = std::thread::current();
201    let name = current.name().expect("libtest names each test thread");
202    if crate::env::var(CHILD).as_deref() == Ok(name) {
203        return false;
204    }
205    let mut command = std::process::Command::new(std::env::current_exe().unwrap());
206    command
207        .arg(name)
208        .arg("--exact")
209        .arg("--nocapture")
210        .arg("--test-threads=1")
211        .env(CHILD, name)
212        .env_remove("GLRMASK_STRICT_STATIC_TRAP_DYNAMIC");
213    if ignored {
214        command.arg("--ignored");
215    }
216    let output = command.output().expect("run isolated environment test");
217    let stdout = String::from_utf8_lossy(&output.stdout);
218    let stderr = String::from_utf8_lossy(&output.stderr);
219    assert!(
220        output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed"),
221        "isolated test {name} failed or did not run exactly one test: {}\n{stdout}\n{stderr}",
222        output.status,
223    );
224    true
225}
226
227#[cfg(test)]
228mod budget_fallback_tests;
229#[cfg(test)]
230mod characterization_cycle_tests;
231#[cfg(test)]
232mod grammar_cross_tests;
233#[cfg(test)]
234mod right_recursion_regression;
235#[cfg(test)]
236mod terminal_dwa_cross_tests;
237#[cfg(test)]
238mod tokentrie_nullable_ambiguity_tests;
239#[cfg(test)]
240mod terminal_ended_rescue_tests;
241#[cfg(test)]
242mod tokentrie_reduce_cycle_tests;
243
244pub(crate) use error::ErrorExt;
245
246/// Compile a Constraint from a serialized GrammarDef JSON + vocab.
247/// This runs the full compile pipeline (equivalence analysis, terminal DWA, parser DWA).
248pub(crate) fn compile_grammar_def_json(
249    grammar_def_json: &str,
250    vocab: &Vocab,
251) -> Result<runtime::Constraint> {
252    let gdef: grammar::flat::GrammarDef = serde_json::from_str(grammar_def_json)
253        .map_err(|e| Error::Syntax(format!("invalid GrammarDef JSON: {e}")))?;
254    error::catch_internal_invariant(|| {
255        compiler::stages::id_map_and_terminal_dwa::l2p::with_ti_pool(|| {
256            compiler::compile_owned(gdef, vocab)
257        })
258    })
259}
260
261/// Populate compile-time artifacts that are pure functions of the vocabulary.
262///
263/// This intentionally does not compile any grammar/schema-dependent artifact.
264pub(crate) fn prepare_vocab_for_compile(vocab: &Vocab) {
265    compiler::compile::prepare_vocab_for_compile(vocab);
266}
267
268/// Populate compile-time vocabulary artifacts needed specifically by dynamic mode.
269pub(crate) fn prepare_vocab_for_dynamic_compile(vocab: &Vocab) {
270    compiler::compile::prepare_vocab_for_dynamic_compile(vocab);
271}
272
273/// Build (and, if configured, start the keepalive for) the terminal
274/// interchangeability certification thread pool ahead of first use.
275///
276/// Calling this at Python module import warms the pool so discovery does not
277/// pay the first-use worker-wake handoff (a large latency on macOS).
278pub(crate) fn warm_ti_pool() {
279    compiler::stages::id_map_and_terminal_dwa::l2p::warm_ti_pool();
280}
281
282/// Dump the imported JSON Schema grammar in GLRM format.
283///
284/// This intentionally preserves exact subtraction syntax so dumps reflect the
285/// source-level structure. The compile/import pipeline may still apply exact
286/// subtraction lowering.
287pub(crate) fn dump_json_schema_grammar_glrm(schema_json: &str) -> Result<String> {
288    let schema: serde_json::Value = serde_json::from_str(schema_json)
289        .map_err(|e| Error::Syntax(format!("invalid JSON: {e}")))?;
290    let named = import::json_schema::schema_to_named_grammar(&schema).map_err(crate::error::from_grammar)?;
291    let mut factored = grammar::factoring::factor_named_grammar(named);
292    import::json_schema::prepare_named_grammar_for_dump(&mut factored).map_err(crate::error::from_grammar)?;
293    grammar::glrm::to_glrm_v1(&factored).map_err(crate::error::from_grammar)
294}
295
296pub(crate) fn set_test_compat_mode(enabled: bool) {
297    glrmask_json_schema::__private::set_test_compat_mode(enabled);
298}
299
300/// The five mask configurations the test suite exercises: `Auto`, `ParserDwa`,
301/// and TokenTrie with neither switch (A), template DFAs only (B), and both
302/// switches (C). Test scaffold only.
303#[cfg(any(test, feature = "internal-api"))]
304#[doc(hidden)]
305pub mod test_modes {
306    use crate::{BuildOptions, CompileOptions, InternalMaskStrategy, ParserBackend, TokenTrie};
307
308    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
309    pub enum MaskMode {
310        Auto,
311        ParserDwa,
312        A,
313        B,
314        C,
315        D,
316    }
317
318    impl MaskMode {
319        pub const ALL: [Self; 6] = [Self::Auto, Self::ParserDwa, Self::A, Self::B, Self::C, Self::D];
320
321        pub fn strategy(self) -> InternalMaskStrategy {
322            match self {
323                Self::Auto => InternalMaskStrategy::Auto,
324                Self::ParserDwa => InternalMaskStrategy::ParserDwa,
325                Self::A | Self::B | Self::C | Self::D => InternalMaskStrategy::TokenTrie(
326                    TokenTrie::new()
327                        .parser_backend(self.parser_backend())
328                        .merge_equivalent_tokens(self.merge_equivalent_tokens()),
329                ),
330            }
331        }
332
333        pub fn parser_backend(self) -> ParserBackend {
334            if matches!(self, Self::B | Self::C) {
335                ParserBackend::TemplateDfa
336            } else {
337                ParserBackend::LrTable
338            }
339        }
340
341        pub fn merge_equivalent_tokens(self) -> bool {
342            matches!(self, Self::C | Self::D)
343        }
344
345        pub fn build_options(self) -> BuildOptions {
346            BuildOptions::default()
347                .optimization(self.strategy())
348                .engine_backend(self.parser_backend())
349                .merge_equivalent_tokens(self.merge_equivalent_tokens())
350        }
351
352        pub fn compile_options(self) -> CompileOptions {
353            CompileOptions::default().internal_mask_strategy(self.strategy())
354        }
355    }
356}
357
358#[cfg(feature = "internal-api")]
359#[doc(hidden)]
360pub mod __private {
361    use crate::ErrorExt as _;
362    pub use glrmask_vocab::__private::{MAX_TOKEN_ID, TokenSetExt, VocabExt as VocabAccess};
363    pub use crate::error::compilation_error;
364    pub use crate::runtime::boundary_cpu_profile::{
365        begin as begin_boundary_cpu_profile, take as take_boundary_cpu_profile, BoundaryCpuReport,
366    };
367    #[derive(Debug, Clone, Copy, Default)]
368    pub struct CompilerCacheStats {
369        pub token_set_entries: usize,
370        pub live_token_set_entries: usize,
371        pub weight_buckets: usize,
372        pub weight_entries: usize,
373        pub live_weight_entries: usize,
374        pub current_thread_weight_ops: usize,
375        pub current_thread_token_set_ops: usize,
376        pub current_thread_public_intersections: usize,
377        pub current_thread_weight_hashes: usize,
378        pub weight_op_generation: u64,
379        pub weight_hash_generation: u64,
380        pub vocab_artifacts: usize,
381    }
382
383    pub fn compiler_cache_stats(vocab: Option<&crate::Vocab>) -> CompilerCacheStats {
384        let stats = crate::ds::weight::weight_cache_stats();
385        CompilerCacheStats {
386            token_set_entries: stats.token_set_entries,
387            live_token_set_entries: stats.live_token_set_entries,
388            weight_buckets: stats.weight_buckets,
389            weight_entries: stats.weight_entries,
390            live_weight_entries: stats.live_weight_entries,
391            current_thread_weight_ops: stats.current_thread_weight_ops,
392            current_thread_token_set_ops: stats.current_thread_token_set_ops,
393            current_thread_public_intersections: stats.current_thread_public_intersections,
394            current_thread_weight_hashes: stats.current_thread_weight_hashes,
395            weight_op_generation: stats.weight_op_generation,
396            weight_hash_generation: stats.weight_hash_generation,
397            vocab_artifacts: vocab.map_or(0, crate::Vocab::compiler_cache_entry_count),
398        }
399    }
400
401    pub use crate::compiler::glr::table::TableAmbiguity;
402    pub use crate::error::Error;
403    pub use crate::runtime::{
404        AdvanceTrace,
405        AdvanceTraceStep,
406        CommitProfile,
407        GssProfileSummary,
408        MaskProfile,
409        PerAdvanceEntry,
410    };
411
412    use crate::{ConstraintInner as Constraint, ConstraintState, DynamicConstraint, Vocab};
413
414    pub type Result<T> = std::result::Result<T, Error>;
415
416    /// Diagnostic upper bound for outgoing model tokens of ONE compiled
417    /// component. No caller, sibling, placeholder binding or link graph is
418    /// accepted here. An unavailable certificate is an error, never empty.
419    pub fn debug_component_boundary_candidate_ids(component:&Constraint,vocab:&Vocab)->Result<Vec<u32>>{
420        crate::compiler::boundary_candidates::boundary_candidate_ids(component,vocab).0
421            .ok_or_else(||Error::Compilation("component-only outgoing boundary summary unavailable".into()))
422    }
423
424    /// Internal debug bridge: compile an ordinary
425    /// [`crate::grammar::ast::NamedGrammar`] through the normal
426    /// (non-composition) compiler path, using the same default table
427    /// construction as the ordinary GLRM route
428    /// (`Constraint::from_glrm_grammar` -> `ExperimentalCoreMerged`).
429    pub fn compile_named_grammar(
430        named: crate::grammar::ast::NamedGrammar,
431        vocab: &Vocab,
432    ) -> Result<Constraint> {
433        crate::import::compile_from_named_grammar(
434            named,
435            vocab,
436            "named_grammar_internal",
437            crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,
438            &[],
439        )
440    }
441
442    /// Sets or removes an environment variable and makes GLRMask see the change.
443    ///
444    /// # Safety
445    /// Same contract as [`std::env::set_var`].
446    pub unsafe fn set_env_var(key: &str, value: Option<&str>) {
447        match value {
448            Some(value) => unsafe { std::env::set_var(key, value) },
449            None => unsafe { std::env::remove_var(key) },
450        }
451        crate::env::record_override(
452            std::ffi::OsStr::new(key),
453            value.map(std::ffi::OsString::from),
454        );
455    }
456
457    /// Experimental mandatory template backend. The LR table is dropped and
458    /// any accidental runtime table access fails loudly. Composed constraints
459    /// are converted recursively without retaining packed compiler tables.
460    pub fn into_template_parser(mut constraint: Constraint) -> Result<Constraint> {
461        // Internal conversion is also used by composition benchmarks and by
462        // callers that precompile a child before binding it. Preserve the same
463        // component-local boundary certificate as the public compiler does,
464        // before physical table/rule removal makes recomputation impossible.
465        let vocab = constraint.late_bind_vocab.get().cloned().unwrap_or_else(|| {
466            Vocab::from_entries_unchecked(
467                constraint
468                    .token_bytes_iter()
469                    .map(|(token_id, bytes)| (token_id, bytes.to_vec()))
470                    .collect(),
471            )
472        });
473        crate::compiler::boundary_candidates::persist_boundary_candidate_summary(
474            &mut constraint,
475            &vocab,
476        );
477        constraint.install_template_parser()?;
478        Ok(constraint)
479    }
480
481    pub fn into_dynamic_template_parser(mut constraint: DynamicConstraint) -> Result<DynamicConstraint> {
482        for alternative in constraint.constraints_mut() { alternative.install_template_parser()?; }
483        Ok(constraint)
484    }
485
486    /// Check derived packed final-weight indices and projections against the
487    /// original wire decoder and original-token fragments. Internal regression
488    /// support only; never called by compilation, loading, or timed execution.
489    pub fn assert_packed_final_mask_cache(constraint: &Constraint, rounds: usize) -> usize {
490        constraint.check_packed_final_cache_against_uncached(rounds)
491    }
492
493    /// Check every cached tokenizer state/byte against its canonical decoder.
494    /// Internal regression support only; do not call during a timing pass.
495    pub fn assert_tokenizer_transition_cache(constraint: &Constraint) -> usize {
496        constraint.check_tokenizer_fast_transitions_against_uncached()
497    }
498
499    pub fn parser_backend_report(constraint: &Constraint) -> serde_json::Value {
500        constraint.parser_backend_report()
501    }
502
503    #[cfg(feature = "internal-api")]
504    pub fn grammar_from_glrm_with_markers(source: &str) -> Result<crate::Grammar> {
505        crate::Grammar::from_glrm_with_markers(source)
506    }
507
508    /// Diagnostic artifact bytes; never used for runtime, linking or timing.
509    pub fn save_without_effect_metadata_for_diagnostic(constraint:&Constraint) -> Vec<u8> {
510        constraint.save_without_effect_metadata_for_diagnostic()
511    }
512
513    /// Native research gate for the bounded O2 frontend; compare against the
514    /// ordinary O2 parser independently before adopting as a public policy.
515    pub fn compile_bounded_template_o2_glrm(source: &str, vocab: &Vocab) -> Result<DynamicConstraint> {
516        DynamicConstraint::from_glrm_with_bounded_template_parser(source, vocab)
517    }
518
519    pub fn dynamic_parser_backend_report(constraint: &DynamicConstraint) -> serde_json::Value {
520        serde_json::Value::Array(constraint.clone_constraints().iter()
521            .map(Constraint::parser_backend_report).collect())
522    }
523
524    /// Bounded diagnostic only. This compares canonical stack languages and
525    /// accumulators, not pointer identity or incidental GSS sharing shape.
526    /// The reference is a separate oracle constraint, never retained inside
527    /// the table-free candidate. Do not call this inside performance intervals.
528    pub fn compare_parser_states_debug(
529        reference: &ConstraintState, candidate: &ConstraintState,
530    ) -> Option<serde_json::Value> {
531        use crate::compiler::glr::parser::ParserGSS;
532        use std::collections::BTreeMap;
533        fn canonical(state: &ConstraintState) -> BTreeMap<u32, ParserGSS> {
534            let mut map = BTreeMap::<u32, ParserGSS>::new();
535            for (&key, gss) in state.state.iter() {
536                map.entry(key).and_modify(|prior| *prior = prior.merge(gss)).or_insert_with(|| gss.clone());
537            }
538            map
539        }
540        let left = canonical(reference); let right = canonical(candidate);
541        let keys: std::collections::BTreeSet<_> = left.keys().chain(right.keys()).copied().collect();
542        for key in keys {
543            let a = left.get(&key).cloned().unwrap_or_else(ParserGSS::empty);
544            let b = right.get(&key).cloned().unwrap_or_else(ParserGSS::empty);
545            if a.semantically_eq(&b, 65_536) != Some(true) {
546                return Some(serde_json::json!({
547                    "tokenizer_state":key, "reference_keys":left.keys().collect::<Vec<_>>(),
548                    "candidate_keys":right.keys().collect::<Vec<_>>(),
549                    "reference_stacks":format!("{:?}",a.to_stacks(32)),
550                    "candidate_stacks":format!("{:?}",b.to_stacks(32)),
551                    "reference_stack_vectors":a.to_stacks(4096).map(|stacks|stacks.into_iter().map(|(stack,_)|stack).collect::<Vec<_>>()),
552                    "candidate_stack_vectors":b.to_stacks(4096).map(|stacks|stacks.into_iter().map(|(stack,_)|stack).collect::<Vec<_>>()),
553                    "reference_table":serde_json::to_value(&*reference.constraint.table).ok(),
554                    "candidate_templates":serde_json::to_value(&candidate.constraint.template_dfas_by_terminal).ok(),
555                    "ignore_terminal":reference.constraint.ignore_terminal,
556                }));
557            }
558        }
559        None
560    }
561
562    pub trait ConstraintStateReject {
563        fn reject(&mut self);
564    }
565
566    impl ConstraintStateReject for crate::runtime::ConstraintState {
567        fn reject(&mut self) { self.reject_after_failed_commit(); }
568    }
569
570    impl ConstraintStateReject for crate::dynamic_constraint::DynamicConstraintState {
571        fn reject(&mut self) { self.reject_after_failed_commit(); }
572    }
573
574    pub trait ConstraintExt: Sized {
575        fn compile_grammar_def_json(grammar_def_json: &str, vocab: &Vocab) -> Result<Self>;
576        fn dump_json_schema_grammar_glrm(schema_json: &str) -> Result<String>;
577        fn profile_json_schema_import(schema_json: &str) -> Result<()>;
578        fn warm_ti_pool();
579        fn clear_stale_weights();
580        fn clear_weight_interners();
581        fn clear_weight_op_caches();
582        fn set_test_compat_mode(enabled: bool);
583        fn prepare_composition_grammar_summary(&mut self) -> Result<()>;
584
585        fn bind_vocab_exact(&mut self, vocab: &Vocab) -> std::result::Result<(), String>;
586        fn prepare_for_composition(&mut self, vocab: &Vocab) -> Result<()>;
587        fn prepare_for_dynamic_composition(&mut self, vocab: &Vocab) -> Result<()>;
588
589        fn num_parser_states(&self) -> u32;
590        fn num_terminals(&self) -> u32;
591        fn num_tokenizer_states(&self) -> usize;
592        fn internal_tsid_count(&self) -> usize;
593        fn parser_dwa_num_states(&self) -> u32;
594        fn parser_dwa_num_transitions(&self) -> usize;
595        fn compute_forced_minimized_tokenizer_state_count(&self) -> usize;
596        fn max_original_token_id(&self) -> Option<u32>;
597        fn final_internal_token_count(&self) -> usize;
598        fn final_original_token_map(&self) -> Vec<u32>;
599        fn table_ambiguous_actions(&self) -> Vec<TableAmbiguity>;
600        fn table_has_ambiguity(&self) -> bool;
601        fn terminal_display_names(&self) -> &[String];
602        fn terminal_display_name(&self, terminal_id: u32) -> Option<&str>;
603        /// Internal benchmark/debug bridge for linking already-compiled
604        /// subgrammar artifacts after the legacy public composition API was
605        /// removed.  Production callers should express subgrammars in GLRM.
606        fn compose_compiled_subgrammars(
607            self,
608            children: &[(&str, &Constraint)],
609            vocab: &Vocab,
610        ) -> Result<Self>;
611        fn compose_compiled_subgrammars_shared(
612            self,
613            children: &[(&str, std::sync::Arc<Constraint>)],
614            vocab: &Vocab,
615        ) -> Result<Self>;
616        /// Measurement-only bridge: same placeholder-substitution composition
617        /// but with the DynamicDirect segmented boundary backend.
618        fn compose_compiled_subgrammars_dynamic(
619            self,
620            children: &[(&str, &Constraint)],
621            vocab: &Vocab,
622        ) -> Result<Self>;
623        fn compose_compiled_subgrammars_dynamic_shared(
624            self,
625            children: &[(&str, std::sync::Arc<Constraint>)],
626            vocab: &Vocab,
627        ) -> Result<Self>;
628        /// Measurement-only bridge: compile static boundary shards only for
629        /// the listed starting-component indices. Other components retain an
630        /// exact DynamicDirect shard with the static walk's candidate-token
631        /// domain, allowing direct static-B vs candidate-dynamic-B timing.
632        fn compose_compiled_subgrammars_hybrid(
633            self,
634            children: &[(&str, &Constraint)],
635            vocab: &Vocab,
636            static_components: &[usize],
637        ) -> Result<Self>;
638    }
639
640    pub trait DynamicConstraintExt: Sized {
641        fn compile_ebnf_serialized_profiled_with_end_tokens(
642            source: &str,
643            vocab: &Vocab,
644            end_token_ids: &[u32],
645            vocab_partition: bool,
646        ) -> Result<(Vec<u8>, u64, u64)>;
647        fn compile_lark_serialized_profiled_with_end_tokens(
648            source: &str,
649            vocab: &Vocab,
650            end_token_ids: &[u32],
651            vocab_partition: bool,
652        ) -> Result<(Vec<u8>, u64, u64)>;
653        fn compile_json_schema_serialized_profiled_with_end_tokens(
654            source: &str,
655            vocab: &Vocab,
656            end_token_ids: &[u32],
657            vocab_partition: bool,
658        ) -> Result<(Vec<u8>, u64, u64)>;
659        fn compile_glrm_serialized_profiled_with_end_tokens(
660            source: &str,
661            vocab: &Vocab,
662            end_token_ids: &[u32],
663            vocab_partition: bool,
664        ) -> Result<(Vec<u8>, u64, u64)>;
665        fn compile_ebnf_serialized_with_end_tokens(
666            source: &str,
667            vocab: &Vocab,
668            end_token_ids: &[u32],
669        ) -> Result<Vec<u8>>;
670        fn compile_lark_serialized_with_end_tokens(
671            source: &str,
672            vocab: &Vocab,
673            end_token_ids: &[u32],
674        ) -> Result<Vec<u8>>;
675        fn compile_json_schema_serialized_with_end_tokens(
676            source: &str,
677            vocab: &Vocab,
678            end_token_ids: &[u32],
679        ) -> Result<Vec<u8>>;
680        fn compile_glrm_serialized_with_end_tokens(
681            source: &str,
682            vocab: &Vocab,
683            end_token_ids: &[u32],
684        ) -> Result<Vec<u8>>;
685        fn load_with_vocab(bytes: &[u8], vocab: &Vocab) -> Result<Self>;
686        fn max_original_token_id(&self) -> Option<u32>;
687    }
688
689    impl ConstraintExt for Constraint {
690        fn compile_grammar_def_json(grammar_def_json: &str, vocab: &Vocab) -> Result<Self> {
691            crate::compile_grammar_def_json(grammar_def_json, vocab)
692        }
693
694        fn dump_json_schema_grammar_glrm(schema_json: &str) -> Result<String> {
695            crate::dump_json_schema_grammar_glrm(schema_json)
696        }
697
698        fn profile_json_schema_import(schema_json: &str) -> Result<()> {
699            crate::import::__profile_json_schema_import(schema_json)
700        }
701
702        fn warm_ti_pool() {
703            crate::warm_ti_pool();
704        }
705
706        fn bind_vocab_exact(&mut self, vocab: &Vocab) -> std::result::Result<(), String> {
707            Constraint::bind_vocab_exact(self, vocab)
708        }
709
710        fn prepare_for_composition(&mut self, vocab: &Vocab) -> Result<()> {
711            self.prepare_for_composition_internal(vocab)
712        }
713
714        fn prepare_for_dynamic_composition(&mut self, vocab: &Vocab) -> Result<()> {
715            Constraint::bind_vocab_exact(self, vocab).map_err(Error::Compilation)?;
716            self.materialize_composition_link_metadata_for_compilation()
717                .map_err(Error::Compilation)
718        }
719
720        fn compose_compiled_subgrammars(
721            self,
722            children: &[(&str, &Constraint)],
723            vocab: &Vocab,
724        ) -> Result<Self> {
725            use crate::compiler::constraint_compose::{
726                CompiledSubgrammarInput, SegmentedBoundaryBackend,
727                compose_constraints_owned_parent_segmented,
728            };
729            use std::collections::BTreeSet;
730
731            let mut inputs = Vec::with_capacity(children.len());
732            let mut seen = BTreeSet::new();
733            for &(name, child) in children {
734                let placeholder_terminal = self
735                    .terminal_display_names
736                    .iter()
737                    .position(|candidate| candidate == name)
738                    .ok_or_else(|| {
739                        Error::Compilation(format!(
740                            "parent has no subgrammar placeholder terminal {name:?}",
741                        ))
742                    })? as u32;
743                if !seen.insert(placeholder_terminal) {
744                    return Err(Error::Compilation(format!(
745                        "parent placeholder terminal {name:?} was supplied more than once",
746                    )));
747                }
748                inputs.push(CompiledSubgrammarInput {
749                    placeholder_terminal,
750                    additional_placeholder_terminals: &[],
751                    constraint: child,
752                });
753            }
754            compose_constraints_owned_parent_segmented(
755                self,
756                &inputs,
757                vocab,
758                SegmentedBoundaryBackend::StaticParserDwa,
759            )
760            .map(|composition| composition.constraint)
761            .map_err(Error::Compilation)
762        }
763
764        fn compose_compiled_subgrammars_shared(
765            self,
766            children: &[(&str, std::sync::Arc<Constraint>)],
767            vocab: &Vocab,
768        ) -> Result<Self> {
769            use crate::compiler::constraint_compose::{
770                CompiledSubgrammarInput, SegmentedBoundaryBackend,
771                compose_constraints_owned_parent_segmented_shared,
772            };
773            use std::collections::BTreeSet;
774            use std::sync::Arc;
775
776            let mut inputs = Vec::with_capacity(children.len());
777            let mut shared = Vec::with_capacity(children.len());
778            let mut seen = BTreeSet::new();
779            for (name, child) in children {
780                let placeholder_terminal = self
781                    .terminal_display_names
782                    .iter()
783                    .position(|candidate| candidate == name)
784                    .ok_or_else(|| {
785                        Error::Compilation(format!(
786                            "parent has no subgrammar placeholder terminal {name:?}",
787                        ))
788                    })? as u32;
789                if !seen.insert(placeholder_terminal) {
790                    return Err(Error::Compilation(format!(
791                        "parent placeholder terminal {name:?} was supplied more than once",
792                    )));
793                }
794                inputs.push(CompiledSubgrammarInput {
795                    placeholder_terminal,
796                    additional_placeholder_terminals: &[],
797                    constraint: child.as_ref(),
798                });
799                shared.push(Arc::clone(child));
800            }
801            compose_constraints_owned_parent_segmented_shared(
802                self,
803                &inputs,
804                &shared,
805                vocab,
806                SegmentedBoundaryBackend::StaticParserDwa,
807            )
808            .map(|composition| composition.constraint)
809            .map_err(Error::Compilation)
810        }
811
812        fn compose_compiled_subgrammars_dynamic(
813            self,
814            children: &[(&str, &Constraint)],
815            vocab: &Vocab,
816        ) -> Result<Self> {
817            use crate::compiler::constraint_compose::{
818                CompiledSubgrammarInput, SegmentedBoundaryBackend,
819                compose_constraints_owned_parent_segmented,
820            };
821            use std::collections::BTreeSet;
822
823            let mut inputs = Vec::with_capacity(children.len());
824            let mut seen = BTreeSet::new();
825            for &(name, child) in children {
826                let placeholder_terminal = self
827                    .terminal_display_names
828                    .iter()
829                    .position(|candidate| candidate == name)
830                    .ok_or_else(|| {
831                        Error::Compilation(format!(
832                            "parent has no subgrammar placeholder terminal {name:?}",
833                        ))
834                    })? as u32;
835                if !seen.insert(placeholder_terminal) {
836                    return Err(Error::Compilation(format!(
837                        "parent placeholder terminal {name:?} was supplied more than once",
838                    )));
839                }
840                inputs.push(CompiledSubgrammarInput {
841                    placeholder_terminal,
842                    additional_placeholder_terminals: &[],
843                    constraint: child,
844                });
845            }
846            compose_constraints_owned_parent_segmented(
847                self,
848                &inputs,
849                vocab,
850                SegmentedBoundaryBackend::Dynamic,
851            )
852            .map(|composition| composition.constraint)
853            .map_err(Error::Compilation)
854        }
855
856
857        fn compose_compiled_subgrammars_dynamic_shared(
858            self,
859            children: &[(&str, std::sync::Arc<Constraint>)],
860            vocab: &Vocab,
861        ) -> Result<Self> {
862            use crate::compiler::constraint_compose::{
863                CompiledSubgrammarInput, SegmentedBoundaryBackend,
864                compose_constraints_owned_parent_segmented_shared,
865            };
866            use std::collections::BTreeSet;
867            use std::sync::Arc;
868
869            let mut inputs = Vec::with_capacity(children.len());
870            let mut shared = Vec::with_capacity(children.len());
871            let mut seen = BTreeSet::new();
872            for (name, child) in children {
873                let placeholder_terminal = self
874                    .terminal_display_names
875                    .iter()
876                    .position(|candidate| candidate == name)
877                    .ok_or_else(|| {
878                        Error::Compilation(format!(
879                            "parent has no subgrammar placeholder terminal {name:?}",
880                        ))
881                    })? as u32;
882                if !seen.insert(placeholder_terminal) {
883                    return Err(Error::Compilation(format!(
884                        "parent placeholder terminal {name:?} was supplied more than once",
885                    )));
886                }
887                inputs.push(CompiledSubgrammarInput {
888                    placeholder_terminal,
889                    additional_placeholder_terminals: &[],
890                    constraint: child.as_ref(),
891                });
892                shared.push(Arc::clone(child));
893            }
894            compose_constraints_owned_parent_segmented_shared(
895                self,
896                &inputs,
897                &shared,
898                vocab,
899                SegmentedBoundaryBackend::Dynamic,
900            )
901            .map(|composition| composition.constraint)
902            .map_err(Error::Compilation)
903        }
904
905        fn compose_compiled_subgrammars_hybrid(
906            self,
907            children: &[(&str, &Constraint)],
908            vocab: &Vocab,
909            static_components: &[usize],
910        ) -> Result<Self> {
911            use crate::compiler::constraint_compose::{
912                CompiledSubgrammarInput, compose_constraints_owned_parent_segmented_hybrid,
913            };
914            use crate::ds::bitset::BitSet;
915            use std::collections::BTreeSet;
916
917            let mut inputs = Vec::with_capacity(children.len());
918            let mut seen = BTreeSet::new();
919            for &(name, child) in children {
920                let placeholder_terminal = self
921                    .terminal_display_names
922                    .iter()
923                    .position(|candidate| candidate == name)
924                    .ok_or_else(|| {
925                        Error::Compilation(format!(
926                            "parent has no subgrammar placeholder terminal {name:?}",
927                        ))
928                    })? as u32;
929                if !seen.insert(placeholder_terminal) {
930                    return Err(Error::Compilation(format!(
931                        "parent placeholder terminal {name:?} was supplied more than once",
932                    )));
933                }
934                inputs.push(CompiledSubgrammarInput {
935                    placeholder_terminal,
936                    additional_placeholder_terminals: &[],
937                    constraint: child,
938                });
939            }
940            let mut selected = BitSet::new(children.len() + 1);
941            for &component in static_components {
942                if component > children.len() {
943                    return Err(Error::Compilation(format!(
944                        "hybrid static component {component} out of range 0..{}",
945                        children.len() + 1,
946                    )));
947                }
948                selected.set(component);
949            }
950            compose_constraints_owned_parent_segmented_hybrid(
951                self,
952                &inputs,
953                vocab,
954                &selected,
955            )
956            .map(|composition| composition.constraint)
957            .map_err(Error::Compilation)
958        }
959
960        fn clear_stale_weights() {
961            crate::ds::weight::clear_stale_weights();
962        }
963
964        fn clear_weight_interners() {
965            crate::ds::weight::clear_weight_interners();
966        }
967
968        fn clear_weight_op_caches() {
969            crate::ds::weight::clear_weight_op_caches();
970        }
971
972        fn set_test_compat_mode(enabled: bool) {
973            crate::set_test_compat_mode(enabled);
974        }
975
976        fn prepare_composition_grammar_summary(&mut self) -> Result<()> {
977            if self.composition_grammar_summary.is_some() {
978                return Ok(());
979            }
980            let augmented_start = self
981                .table
982                .rules
983                .first()
984                .map(|rule| rule.lhs)
985                .ok_or_else(|| Error::Compilation("constraint table has no augmented-start rule".to_string()))?;
986            let analyzed = crate::compiler::glr::analysis::AnalyzedGrammar::from_composed_rules(
987                self.table.rules.clone(),
988                self.table.num_terminals,
989                self.terminal_display_names.clone(),
990                self.table.nonterminal_display_names.clone(),
991                augmented_start,
992            );
993            self.composition_grammar_summary = Some(
994                crate::compiler::pipeline::composition_grammar_summary_from_analysis(&analyzed),
995            );
996            Ok(())
997        }
998
999
1000        fn num_parser_states(&self) -> u32 {
1001            Constraint::num_parser_states(self)
1002        }
1003
1004        fn num_terminals(&self) -> u32 {
1005            self.parser_terminal_count()
1006        }
1007
1008        fn num_tokenizer_states(&self) -> usize {
1009            Constraint::num_tokenizer_states(self)
1010        }
1011
1012        fn internal_tsid_count(&self) -> usize {
1013            Constraint::internal_tsid_count(self)
1014        }
1015
1016        fn parser_dwa_num_states(&self) -> u32 {
1017            Constraint::parser_dwa(self).num_states()
1018        }
1019
1020        fn parser_dwa_num_transitions(&self) -> usize {
1021            Constraint::parser_dwa(self).num_transitions()
1022        }
1023
1024        fn compute_forced_minimized_tokenizer_state_count(&self) -> usize {
1025            Constraint::compute_forced_minimized_tokenizer_state_count(self)
1026        }
1027
1028        fn max_original_token_id(&self) -> Option<u32> {
1029            Constraint::max_original_token_id(self)
1030        }
1031
1032        fn final_internal_token_count(&self) -> usize {
1033            self.internal_token_count()
1034        }
1035
1036        fn final_original_token_map(&self) -> Vec<u32> {
1037            self.original_token_map().to_vec()
1038        }
1039
1040        fn table_ambiguous_actions(&self) -> Vec<TableAmbiguity> {
1041            Constraint::table_ambiguous_actions(self)
1042        }
1043
1044        fn table_has_ambiguity(&self) -> bool {
1045            Constraint::table_has_ambiguity(self)
1046        }
1047
1048        fn terminal_display_names(&self) -> &[String] {
1049            Constraint::terminal_display_names(self)
1050        }
1051
1052        fn terminal_display_name(&self, terminal_id: u32) -> Option<&str> {
1053            Constraint::terminal_display_name(self, terminal_id)
1054        }
1055
1056    }
1057
1058    impl DynamicConstraintExt for DynamicConstraint {
1059        fn compile_ebnf_serialized_profiled_with_end_tokens(
1060            source: &str,
1061            vocab: &Vocab,
1062            end_token_ids: &[u32],
1063            vocab_partition: bool,
1064        ) -> Result<(Vec<u8>, u64, u64)> {
1065            DynamicConstraint::compile_ebnf_serialized_profiled_with_end_tokens(
1066                source,
1067                vocab,
1068                end_token_ids,
1069                vocab_partition,
1070            )
1071        }
1072
1073        fn compile_lark_serialized_profiled_with_end_tokens(
1074            source: &str,
1075            vocab: &Vocab,
1076            end_token_ids: &[u32],
1077            vocab_partition: bool,
1078        ) -> Result<(Vec<u8>, u64, u64)> {
1079            DynamicConstraint::compile_lark_serialized_profiled_with_end_tokens(
1080                source,
1081                vocab,
1082                end_token_ids,
1083                vocab_partition,
1084            )
1085        }
1086
1087        fn compile_json_schema_serialized_profiled_with_end_tokens(
1088            source: &str,
1089            vocab: &Vocab,
1090            end_token_ids: &[u32],
1091            vocab_partition: bool,
1092        ) -> Result<(Vec<u8>, u64, u64)> {
1093            DynamicConstraint::compile_json_schema_serialized_profiled_with_end_tokens(
1094                source,
1095                vocab,
1096                end_token_ids,
1097                vocab_partition,
1098            )
1099        }
1100
1101        fn compile_glrm_serialized_profiled_with_end_tokens(
1102            source: &str,
1103            vocab: &Vocab,
1104            end_token_ids: &[u32],
1105            vocab_partition: bool,
1106        ) -> Result<(Vec<u8>, u64, u64)> {
1107            DynamicConstraint::compile_glrm_serialized_profiled_with_end_tokens(
1108                source,
1109                vocab,
1110                end_token_ids,
1111                vocab_partition,
1112            )
1113        }
1114
1115        fn compile_ebnf_serialized_with_end_tokens(
1116            source: &str,
1117            vocab: &Vocab,
1118            end_token_ids: &[u32],
1119        ) -> Result<Vec<u8>> {
1120            DynamicConstraint::compile_ebnf_serialized_with_end_tokens(source, vocab, end_token_ids)
1121        }
1122
1123        fn compile_lark_serialized_with_end_tokens(
1124            source: &str,
1125            vocab: &Vocab,
1126            end_token_ids: &[u32],
1127        ) -> Result<Vec<u8>> {
1128            DynamicConstraint::compile_lark_serialized_with_end_tokens(source, vocab, end_token_ids)
1129        }
1130
1131        fn compile_json_schema_serialized_with_end_tokens(
1132            source: &str,
1133            vocab: &Vocab,
1134            end_token_ids: &[u32],
1135        ) -> Result<Vec<u8>> {
1136            DynamicConstraint::compile_json_schema_serialized_with_end_tokens(
1137                source,
1138                vocab,
1139                end_token_ids,
1140            )
1141        }
1142
1143        fn compile_glrm_serialized_with_end_tokens(
1144            source: &str,
1145            vocab: &Vocab,
1146            end_token_ids: &[u32],
1147        ) -> Result<Vec<u8>> {
1148            DynamicConstraint::compile_glrm_serialized_with_end_tokens(source, vocab, end_token_ids)
1149        }
1150
1151        fn load_with_vocab(bytes: &[u8], vocab: &Vocab) -> Result<Self> {
1152            DynamicConstraint::load_with_vocab(bytes, vocab)
1153        }
1154
1155        fn max_original_token_id(&self) -> Option<u32> {
1156            DynamicConstraint::max_original_token_id(self)
1157        }
1158    }
1159
1160    pub trait ConstraintStateExt {
1161        fn copy_snapshot_from(&mut self, source: &ConstraintState);
1162        fn commit_token_timed_ns(&mut self, token_id: u32) -> std::result::Result<u64, String>;
1163        fn commit_token_profiled(
1164            &mut self,
1165            token_id: u32,
1166        ) -> std::result::Result<CommitProfile, String>;
1167        fn commit_token_per_advance(
1168            &mut self,
1169            token_id: u32,
1170        ) -> std::result::Result<
1171            (Vec<PerAdvanceEntry>, Vec<(u32, Vec<Vec<u32>>)>, CommitProfile),
1172            String,
1173        >;
1174        fn debug_parser_stacks(&self) -> Vec<(u32, Vec<(Vec<u32>, Vec<(u32, Vec<u32>)>)>)>;
1175        fn fill_mask_profiled(&self, buf: &mut [u32]) -> MaskProfile;
1176        fn fill_mask_timed_ns(&self, buf: &mut [u32]) -> u64;
1177        /// Measurement-only: exact dynamic-reference mask (no parser DWA).
1178        fn fill_mask_dynamic_vec(&self) -> Vec<u32>;
1179        fn has_parser_ambiguity(&self) -> bool;
1180        fn parser_path_count(&self, limit: usize) -> usize;
1181        fn parser_root_count(&self) -> usize;
1182        #[cfg(feature = "internal-api")]
1183        fn frontier_shape(&self) -> (usize, usize, usize, usize, Vec<u32>);
1184    }
1185
1186    impl ConstraintStateExt for ConstraintState {
1187        fn copy_snapshot_from(&mut self, source: &ConstraintState) {
1188            ConstraintState::copy_snapshot_from(self, source);
1189        }
1190
1191        fn commit_token_timed_ns(&mut self, token_id: u32) -> std::result::Result<u64, String> {
1192            ConstraintState::commit_token_timed_ns(self, token_id)
1193        }
1194
1195        fn commit_token_profiled(
1196            &mut self,
1197            token_id: u32,
1198        ) -> std::result::Result<CommitProfile, String> {
1199            ConstraintState::commit_token_profiled(self, token_id)
1200        }
1201
1202        fn commit_token_per_advance(
1203            &mut self,
1204            token_id: u32,
1205        ) -> std::result::Result<
1206            (Vec<PerAdvanceEntry>, Vec<(u32, Vec<Vec<u32>>)>, CommitProfile),
1207            String,
1208        > {
1209            ConstraintState::commit_token_per_advance(self, token_id)
1210        }
1211
1212        fn debug_parser_stacks(&self) -> Vec<(u32, Vec<(Vec<u32>, Vec<(u32, Vec<u32>)>)>)> {
1213            ConstraintState::debug_parser_stacks(self)
1214        }
1215
1216        fn fill_mask_profiled(&self, buf: &mut [u32]) -> MaskProfile {
1217            ConstraintState::fill_mask_profiled(self, buf)
1218        }
1219
1220        fn fill_mask_timed_ns(&self, buf: &mut [u32]) -> u64 {
1221            ConstraintState::fill_mask_timed_ns(self, buf)
1222        }
1223
1224        fn fill_mask_dynamic_vec(&self) -> Vec<u32> {
1225            let mut buf = vec![0u32; self.constraint.mask_bit_len().div_ceil(32)];
1226            ConstraintState::fill_mask_dynamic(self, &mut buf);
1227            buf
1228        }
1229
1230        fn has_parser_ambiguity(&self) -> bool {
1231            ConstraintState::has_parser_ambiguity(self)
1232        }
1233
1234        fn parser_path_count(&self, limit: usize) -> usize {
1235            ConstraintState::parser_path_count(self, limit)
1236        }
1237
1238        fn parser_root_count(&self) -> usize {
1239            ConstraintState::parser_root_count(self)
1240        }
1241        #[cfg(feature = "internal-api")]
1242        fn frontier_shape(&self) -> (usize, usize, usize, usize, Vec<u32>) {
1243            ConstraintState::frontier_shape(self)
1244        }
1245
1246    }
1247
1248    pub trait VocabExt {
1249        fn prepare_for_compile(&self);
1250        fn prepare_for_dynamic_compile(&self);
1251    }
1252
1253    impl VocabExt for Vocab {
1254        fn prepare_for_compile(&self) {
1255            crate::prepare_vocab_for_compile(self);
1256        }
1257
1258        fn prepare_for_dynamic_compile(&self) {
1259            crate::prepare_vocab_for_dynamic_compile(self);
1260        }
1261    }
1262}