1use crate::automata::lexer::Lexer;
2use std::sync::{Arc, Mutex, Weak};
3use std::cell::RefCell;
4use std::marker::PhantomData;
5use std::ops::{Deref, DerefMut};
6use std::rc::Rc;
7use std::thread::LocalKey;
8use super::ConstraintData;
9
10use crate::compiler::glr::accumulator::TerminalsDisallowed;
11use crate::compiler::glr::parser::{
12 ParserGSS, stacks_finished, stacks_finished_control_closed,
13};
14use crate::ds::bitset::BitSet;
15use crate::ds::leveled_gss::GssSemanticKeyInterner;
16use rustc_hash::{FxHashMap, FxHashSet};
17use smallvec::SmallVec;
18
19use super::constraint::Constraint;
20
21pub(crate) const LINEAR_STACK_RESERVE: usize = 64;
22pub(crate) const INLINE_PARSER_STATE_CAPACITY: usize = 64;
24pub(crate) const LIVE_FRONTIER_CAPACITY: usize = 4;
25pub(crate) type FrontierEntries = SmallVec<[(u32, ParserGSS); LIVE_FRONTIER_CAPACITY]>;
26
27#[derive(Clone, Default, PartialEq, Eq)]
33pub(crate) struct ParserStateMap {
34 pub(crate) entries: FrontierEntries,
35}
36
37impl std::fmt::Debug for ParserStateMap {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 f.debug_map().entries(self.entries.iter().map(|(k, v)| (k, v))).finish()
40 }
41}
42
43impl ParserStateMap {
44 pub(crate) fn singleton(key: u32, value: ParserGSS) -> Self {
45 let mut entries = SmallVec::new();
46 entries.push((key, value));
47 Self { entries }
48 }
49
50 #[inline]
51 pub(crate) fn len(&self) -> usize { self.entries.len() }
52
53 #[inline]
54 pub(crate) fn is_empty(&self) -> bool { self.entries.is_empty() }
55
56 #[inline]
57 pub(crate) fn clear(&mut self) { self.entries.clear(); }
58
59 #[inline]
60 pub(crate) fn iter(&self) -> impl Iterator<Item = (&u32, &ParserGSS)> {
61 self.entries.iter().map(|(key, value)| (key, value))
62 }
63
64 #[inline]
65 pub(crate) fn values(&self) -> impl Iterator<Item = &ParserGSS> {
66 self.entries.iter().map(|(_, value)| value)
67 }
68
69 #[inline]
70 pub(crate) fn values_mut(&mut self) -> impl Iterator<Item = &mut ParserGSS> {
71 self.entries.iter_mut().map(|(_, value)| value)
72 }
73
74 #[inline]
75 pub(crate) fn keys(&self) -> impl Iterator<Item = &u32> {
76 self.entries.iter().map(|(key, _)| key)
77 }
78
79 fn equal_range(&self, key: u32) -> std::ops::Range<usize> {
80 let start = self.entries.partition_point(|(entry_key, _)| *entry_key < key);
81 let end = self.entries.partition_point(|(entry_key, _)| *entry_key <= key);
82 start..end
83 }
84
85 pub(crate) fn get(&self, key: &u32) -> Option<&ParserGSS> {
89 let range = self.equal_range(*key);
90 (range.len() == 1).then(|| &self.entries[range.start].1)
91 }
92
93 pub(crate) fn get_mut(&mut self, key: &u32) -> Option<&mut ParserGSS> {
94 let range = self.equal_range(*key);
95 if range.len() != 1 {
96 return None;
97 }
98 Some(&mut self.entries[range.start].1)
99 }
100
101 pub(crate) fn values_for_key(&self, key: u32) -> impl Iterator<Item = &ParserGSS> {
102 let range = self.equal_range(key);
103 self.entries[range].iter().map(|(_, value)| value)
104 }
105
106 pub(crate) fn has_duplicate_keys(&self) -> bool {
107 self.entries.windows(2).any(|pair| pair[0].0 == pair[1].0)
108 }
109
110 pub(crate) fn normalize_duplicate_keys(&mut self) {
114 if !self.has_duplicate_keys() {
115 return;
116 }
117 let old = std::mem::take(&mut self.entries);
118 for (key, value) in old {
119 self.merge_insert(key, value);
120 }
121 }
122
123 pub(crate) fn insert(&mut self, key: u32, value: ParserGSS) -> Option<ParserGSS> {
126 let range = self.equal_range(key);
127 if range.is_empty() {
128 self.entries.insert(range.start, (key, value));
129 return None;
130 }
131
132 let mut old = std::mem::replace(&mut self.entries[range.start].1, value);
133 for _ in range.start + 1..range.end {
134 let (_, duplicate) = self.entries.remove(range.start + 1);
135 old = old.merge(&duplicate);
136 }
137 Some(old)
138 }
139
140 pub(crate) fn pop_first(&mut self) -> Option<(u32, ParserGSS)> {
141 (!self.entries.is_empty()).then(|| self.entries.remove(0))
142 }
143
144 pub(crate) fn merge_insert(&mut self, key: u32, mut value: ParserGSS) {
145 let range = self.equal_range(key);
146 if range.is_empty() {
147 self.entries.insert(range.start, (key, value));
148 return;
149 }
150 for _ in range.clone() {
151 let (_, existing) = self.entries.remove(range.start);
152 value = value.merge(&existing);
153 }
154 self.entries.insert(range.start, (key, value));
155 }
156
157 pub(crate) fn insert_flat_alternative(&mut self, key: u32, value: ParserGSS) {
163 let index = self.entries.partition_point(|(entry_key, _)| *entry_key <= key);
164 self.entries.insert(index, (key, value));
165 }
166
167 pub(crate) fn retain(&mut self, mut keep: impl FnMut(&u32, &mut ParserGSS) -> bool) {
168 let mut index = 0;
169 while index < self.entries.len() {
170 let should_keep = {
171 let (key, value) = &mut self.entries[index];
172 keep(key, value)
173 };
174 if should_keep {
175 index += 1;
176 } else {
177 self.entries.remove(index);
178 }
179 }
180 }
181
182 pub(crate) fn replace_single_key(&mut self, key: u32) -> bool {
184 self.replace_single_keys(std::slice::from_ref(&key))
185 }
186
187 pub(crate) fn replace_single_keys(&mut self, keys: &[u32]) -> bool {
190 if self.entries.len() != 1 || keys.is_empty() {
191 return false;
192 }
193 if keys.windows(2).any(|pair| pair[0] >= pair[1]) {
194 return false;
195 }
196 let (_, gss) = self.entries.pop().unwrap();
197 self.entries.reserve(keys.len());
198 for &key in &keys[..keys.len() - 1] {
199 self.entries.push((key, gss.clone()));
200 }
201 self.entries.push((*keys.last().unwrap(), gss));
202 true
203 }
204
205
206 pub(crate) fn replace_uniform_gss_keys(&mut self, keys: &[u32]) -> bool {
209 if self.entries.is_empty()
210 || keys.is_empty()
211 || keys.windows(2).any(|pair| pair[0] >= pair[1])
212 {
213 return false;
214 }
215 let representative = &self.entries[0].1;
216 if self
217 .entries
218 .iter()
219 .skip(1)
220 .any(|(_, gss)| !representative.ptr_eq(gss) && representative != gss)
221 {
222 return false;
223 }
224
225 let (_, gss) = self.entries.swap_remove(0);
226 self.entries.clear();
227 self.entries.reserve(keys.len());
228 for &key in &keys[..keys.len() - 1] {
229 self.entries.push((key, gss.clone()));
230 }
231 self.entries.push((*keys.last().unwrap(), gss));
232 true
233 }
234}
235
236impl FromIterator<(u32, ParserGSS)> for ParserStateMap {
237 fn from_iter<T: IntoIterator<Item = (u32, ParserGSS)>>(iter: T) -> Self {
238 let mut result = Self::default();
239 for (key, value) in iter {
240 if let Some(existing) = result.insert(key, value) {
241 let current = result.get_mut(&key).unwrap();
242 *current = existing.merge(current);
243 }
244 }
245 result
246 }
247}
248
249impl IntoIterator for ParserStateMap {
250 type Item = (u32, ParserGSS);
251 type IntoIter = smallvec::IntoIter<[(u32, ParserGSS); LIVE_FRONTIER_CAPACITY]>;
252
253 fn into_iter(self) -> Self::IntoIter { self.entries.into_iter() }
254}
255
256impl<'a> IntoIterator for &'a ParserStateMap {
257 type Item = (&'a u32, &'a ParserGSS);
258 type IntoIter = std::iter::Map<
259 std::slice::Iter<'a, (u32, ParserGSS)>,
260 fn(&(u32, ParserGSS)) -> (&u32, &ParserGSS),
261 >;
262
263 fn into_iter(self) -> Self::IntoIter {
264 fn pair_refs(pair: &(u32, ParserGSS)) -> (&u32, &ParserGSS) { (&pair.0, &pair.1) }
265 self.entries.iter().map(pair_refs)
266 }
267}
268
269
270type ScratchSlot<T> = (Weak<ConstraintData>, Box<T>);
278type ScratchPool<T> = RefCell<Vec<ScratchSlot<T>>>;
279const SCRATCH_POOL_LIMIT: usize = 8;
280
281thread_local! {
282 static COMMIT_SCRATCH: ScratchPool<CommitBuffers> = const { RefCell::new(Vec::new()) };
283 static MASK_SCRATCH: ScratchPool<MaskScratch> = const { RefCell::new(Vec::new()) };
284}
285
286pub(crate) struct ScratchLease<T: 'static> {
287 slot: Option<ScratchSlot<T>>,
288 pool: &'static LocalKey<ScratchPool<T>>,
289 _thread_bound: PhantomData<Rc<()>>,
290}
291
292impl<T: 'static> Deref for ScratchLease<T> {
293 type Target = T;
294 #[inline]
295 fn deref(&self) -> &T { &self.slot.as_ref().expect("live scratch lease").1 }
296}
297
298impl<T: 'static> DerefMut for ScratchLease<T> {
299 #[inline]
300 fn deref_mut(&mut self) -> &mut T { &mut self.slot.as_mut().expect("live scratch lease").1 }
301}
302
303impl<T: 'static> Drop for ScratchLease<T> {
304 fn drop(&mut self) {
305 if std::thread::panicking() { return; }
306 let mut slot = self.slot.take();
307 let mut displaced = None;
310 let _ = self.pool.try_with(|cell| {
311 let Ok(mut slots) = cell.try_borrow_mut() else { return; };
312 if slots.len() >= SCRATCH_POOL_LIMIT {
315 displaced = Some(slots.remove(0));
316 }
317 slots.push(slot.take().expect("live scratch lease"));
318 });
319 drop(displaced);
320 }
321}
322
323#[inline]
324fn checkout_scratch<T: 'static>(
325 pool: &'static LocalKey<ScratchPool<T>>,
326 constraint: &Constraint,
327 make: impl FnOnce(&Constraint) -> T,
328) -> ScratchLease<T> {
329 let ptr = Arc::as_ptr(&constraint.data);
330 let slot = pool.try_with(|cell| {
331 let mut slots = cell.try_borrow_mut().ok()?;
332 let index = slots.iter().rposition(|(key, _)| key.as_ptr() == ptr)?;
333 Some(slots.remove(index))
334 }).ok().flatten().unwrap_or_else(|| (Arc::downgrade(&constraint.data), Box::new(make(constraint))));
335 ScratchLease { slot: Some(slot), pool, _thread_bound: PhantomData }
336}
337
338#[inline]
339pub(crate) fn commit_scratch(constraint: &Constraint) -> ScratchLease<CommitBuffers> {
340 checkout_scratch(&COMMIT_SCRATCH, constraint, CommitBuffers::for_constraint)
341}
342
343#[inline]
344pub(crate) fn mask_scratch(constraint: &Constraint) -> ScratchLease<MaskScratch> {
345 checkout_scratch(&MASK_SCRATCH, constraint, MaskScratch::for_constraint)
346}
347
348pub(crate) fn warm_scratch(constraint: &Constraint) {
349 drop(commit_scratch(constraint));
350 drop(mask_scratch(constraint));
351}
352
353pub(crate) struct MaskCacheData {
355 pub generation: u64,
356 pub mask: Vec<u32>,
357 pub merged_dense: Vec<u64>,
360}
361
362pub(crate) struct StateMaskCache {
366 ptr: std::sync::atomic::AtomicPtr<Mutex<MaskCacheData>>,
367}
368
369impl StateMaskCache {
370 pub(crate) const fn new() -> Self {
371 Self { ptr: std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }
372 }
373
374 #[inline]
375 fn cell(&self) -> Option<&Mutex<MaskCacheData>> {
376 unsafe { self.ptr.load(std::sync::atomic::Ordering::Acquire).as_ref() }
380 }
381
382 #[inline]
383 pub(crate) fn lock(&self) -> std::sync::LockResult<Option<std::sync::MutexGuard<'_, MaskCacheData>>> {
384 match self.cell() {
385 None => Ok(None),
386 Some(cell) => cell.lock().map(Some)
387 .map_err(|e| std::sync::PoisonError::new(Some(e.into_inner()))),
388 }
389 }
390
391 #[inline]
392 pub(crate) fn get_mut(&mut self) -> std::sync::LockResult<Option<&mut MaskCacheData>> {
393 match unsafe { self.ptr.get_mut().as_mut() } {
396 None => Ok(None),
397 Some(cell) => cell.get_mut().map(Some)
398 .map_err(|e| std::sync::PoisonError::new(Some(e.into_inner()))),
399 }
400 }
401
402 pub(crate) fn store(&self, generation: u64, mask: &[u32], dense: &[u64]) {
403 use std::sync::atomic::Ordering::{Acquire, AcqRel};
404 let cell = match self.cell() {
405 Some(cell) => cell,
406 None => {
407 let candidate = Box::into_raw(Box::new(Mutex::new(MaskCacheData {
408 generation, mask: mask.to_vec(), merged_dense: dense.to_vec(),
409 })));
410 match self.ptr.compare_exchange(std::ptr::null_mut(), candidate, AcqRel, Acquire) {
411 Ok(_) => return,
412 Err(existing) => {
413 unsafe {
417 drop(Box::from_raw(candidate));
418 &*existing
419 }
420 }
421 }
422 }
423 };
424 let mut data = cell.lock().unwrap();
425 data.generation = generation;
426 data.mask.clear();
427 data.mask.extend_from_slice(mask);
428 data.merged_dense.clear();
429 data.merged_dense.extend_from_slice(dense);
430 }
431
432 #[inline]
433 pub(crate) fn clear(&mut self) {
434 let ptr = std::mem::replace(self.ptr.get_mut(), std::ptr::null_mut());
435 if !ptr.is_null() {
436 unsafe { drop(Box::from_raw(ptr)); }
439 }
440 }
441}
442
443impl Drop for StateMaskCache {
444 fn drop(&mut self) { self.clear(); }
445}
446
447
448#[derive(Default)]
449pub(crate) struct MaskScratch {
450 pub merged_dense: Vec<u64>,
451 pub chain_merged_dense: Vec<u64>,
452 pub output_buf: Vec<u32>,
453 pub single_path_aux_dense: Vec<u64>,
456 pub single_path_acc_dense: Vec<u64>,
458 pub indexed_dag_mask: crate::runtime::mask::IndexedDagMaskRuntime,
461 pub segmented_component_initial_states: Vec<ParserStateMap>,
466 pub segmented_component_initial_masks: Vec<Vec<u32>>,
467}
468
469impl MaskScratch {
470 pub(crate) fn for_constraint(constraint: &Constraint) -> Self {
471 let dense_words = constraint.internal_token_dense_words;
472 let mut segmented_component_initial_states = Vec::new();
473 let mut segmented_component_initial_masks = Vec::new();
474 if let Some(overlay) = constraint.static_dynamic_overlay.as_ref() {
475 let authoritative_dynamic_direct = overlay.segmented_mask_authoritative
476 && !overlay.segmented_parser_components.is_empty()
477 && overlay.segmented_parser_components.iter().all(|component| {
478 component.boundary.as_ref().is_some_and(|shard| {
479 matches!(
480 shard.backend,
481 crate::runtime::SegmentedBoundaryShardBackend::DynamicDirect
482 )
483 })
484 });
485 if !authoritative_dynamic_direct {
486 segmented_component_initial_states.reserve(overlay.segmented_parser_components.len());
487 segmented_component_initial_masks.reserve(overlay.segmented_parser_components.len());
488 for component in &overlay.segmented_parser_components {
489 let source = component.constraint.as_ref();
490 segmented_component_initial_states.push(source.initial_state_map());
491 segmented_component_initial_masks.push(source.start().mask());
492 }
493 }
494 }
495 Self {
496 merged_dense: Vec::with_capacity(dense_words),
497 chain_merged_dense: Vec::with_capacity(dense_words),
498 output_buf: Vec::with_capacity(constraint.body_mask_len()),
499 single_path_aux_dense: vec![0; dense_words],
502 single_path_acc_dense: vec![0; dense_words],
503 indexed_dag_mask: crate::runtime::mask::IndexedDagMaskRuntime::default(),
504 segmented_component_initial_states,
505 segmented_component_initial_masks,
506 }
507 }
508}
509
510#[derive(Debug, Clone)]
517pub(crate) struct ParserAdmissionCacheEntry {
518 pub(crate) gss: ParserGSS,
519 pub(crate) tested: BitSet,
520 pub(crate) admitted: BitSet,
521 pub(crate) boolean_queries: SmallVec<[(BitSet, bool); 8]>,
522}
523
524#[derive(Debug, Clone)]
531pub(crate) struct ParserRelativeMaskEqCacheEntry {
532 pub(crate) left: u32,
533 pub(crate) right: u32,
534 pub(crate) admitted: BitSet,
535}
536
537#[derive(Debug)]
540pub(crate) struct CommitBuffers {
541 pub advance_result_cache: FxHashMap<(usize, u32), (ParserGSS, ParserGSS)>,
542 pub semantic_frontier_keys: GssSemanticKeyInterner<u32, TerminalsDisallowed>,
543 pub admission_cache: SmallVec<[ParserAdmissionCacheEntry; 8]>,
544 pub parser_relative_mask_eq_cache: SmallVec<[ParserRelativeMaskEqCacheEntry; 8]>,
545 pub pending_state: FxHashMap<u32, ParserGSS>,
546 pub seen_matches: FxHashSet<(usize, u32)>,
547 pub terminal_result_cache: FxHashMap<u32, ParserGSS>,
548 pub exec_results: FxHashMap<u32, crate::automata::lexer::tokenizer::TokenizerExecResult>,
549 pub small_exec_result: crate::automata::lexer::tokenizer::TokenizerExecResult,
550 pub reusable_tokenizer_exec:
551 crate::runtime::commit::tokenizer_scan::ReusableTokenizerExecScratch,
552 pub prune_tokenizer_exec:
553 crate::runtime::commit::tokenizer_scan::ReusableTokenizerExecScratch,
554 pub small_queue: Option<Box<crate::runtime::commit::SmallCommitQueueScratch>>,
558 pub flat_frontier: Option<Box<crate::runtime::commit::FlatFrontierScratch>>,
562 pub linear_stack_original: Vec<u32>,
563 pub linear_stack_work: Vec<u32>,
564 pub processing_queue: Vec<FxHashMap<u32, ParserGSS>>,
565 pub template_advance_runtime: crate::runtime::commit::TemplateAdvanceRuntime,
566}
567
568impl Default for CommitBuffers {
569 fn default() -> Self {
570 Self::with_flat_frontier_preallocation(256)
571 }
572}
573
574impl CommitBuffers {
575 pub(crate) fn for_mask_only_shadow() -> Self {
579 Self::with_allocation_policy::<true>(0)
580 }
581
582 pub(crate) fn for_finite_recursive_mask() -> Self {
585 Self::with_flat_frontier_preallocation(0)
586 }
587
588 fn with_flat_frontier_preallocation(preallocated_gss: usize) -> Self {
589 Self::with_allocation_policy::<false>(preallocated_gss)
590 }
591
592 fn with_allocation_policy<const MASK_ONLY: bool>(preallocated_gss: usize) -> Self {
593 Self {
594 advance_result_cache: FxHashMap::default(),
595 semantic_frontier_keys: GssSemanticKeyInterner::with_capacity(if MASK_ONLY { 0 } else { 256 }),
596 admission_cache: SmallVec::new(),
597 parser_relative_mask_eq_cache: SmallVec::new(),
598 pending_state: FxHashMap::default(),
599 seen_matches: FxHashSet::default(),
600 terminal_result_cache: FxHashMap::default(),
601 exec_results: FxHashMap::default(),
602 small_exec_result: crate::automata::lexer::tokenizer::TokenizerExecResult {
603 end_state: crate::automata::lexer::tokenizer::TokenizerStateSet::new(),
604 matches: Vec::with_capacity(if MASK_ONLY { 0 } else { 8 }),
605 },
606 reusable_tokenizer_exec:
607 crate::runtime::commit::tokenizer_scan::ReusableTokenizerExecScratch::with_capacity(if MASK_ONLY { 0 } else { 512 }),
608 prune_tokenizer_exec:
609 crate::runtime::commit::tokenizer_scan::ReusableTokenizerExecScratch::with_capacity(if MASK_ONLY { 0 } else { 512 }),
610 small_queue: if MASK_ONLY { None } else {
611 Some(crate::runtime::commit::SmallCommitQueueScratch::boxed())
612 },
613 flat_frontier: {
614 static LAZY_MASK_STACKS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
615 if MASK_ONLY && *LAZY_MASK_STACKS.get_or_init(|| {
616 crate::env::var("GLRMASK_LAZY_MASK_COMMIT_SCRATCH")
617 .map_or(true, |v| matches!(v.as_str(), "1" | "true"))
618 }) {
619 None
620 } else {
621 Some(crate::runtime::commit::FlatFrontierScratch::boxed_with_preallocated_gss(preallocated_gss))
622 }
623 },
624 linear_stack_original: Vec::with_capacity(if MASK_ONLY { 0 } else { LINEAR_STACK_RESERVE }),
625 linear_stack_work: Vec::with_capacity(if MASK_ONLY { 0 } else { LINEAR_STACK_RESERVE }),
626 processing_queue: Vec::new(),
627 template_advance_runtime:
628 if MASK_ONLY { crate::runtime::commit::TemplateAdvanceRuntime::for_mask_only_shadow() }
629 else { crate::runtime::commit::TemplateAdvanceRuntime::default() },
630 }
631 }
632
633 pub(crate) fn for_constraint(constraint: &Constraint) -> Self {
634 const ORDINARY_DYNAMIC_PREALLOCATED_GSS: usize = 32;
635 let ordinary_dynamic = constraint.uses_dynamic_runtime()
636 && constraint.static_dynamic_overlay.is_none()
637 && !constraint.table_has_ambiguity()
638 && !constraint.tokenizer_has_epsilon_transitions;
639 if ordinary_dynamic {
640 Self::with_flat_frontier_preallocation(ORDINARY_DYNAMIC_PREALLOCATED_GSS)
641 } else {
642 Self::default()
643 }
644 }
645}
646
647impl Clone for CommitBuffers {
648 fn clone(&self) -> Self {
649 Self::default()
651 }
652}
653
654impl CommitBuffers {
655 pub fn clear_all(&mut self) {
656 self.advance_result_cache.clear();
657 self.semantic_frontier_keys.clear();
658 self.pending_state.clear();
659 self.seen_matches.clear();
660 self.terminal_result_cache.clear();
661 self.exec_results.clear();
662 self.small_exec_result.end_state.clear();
663 self.small_exec_result.matches.clear();
664 self.reusable_tokenizer_exec.states.clear();
665 self.reusable_tokenizer_exec.matches.clear();
666 self.prune_tokenizer_exec.states.clear();
667 self.prune_tokenizer_exec.matches.clear();
668 if let Some(queue) = self.small_queue.as_mut() { queue.clear(); }
669 if let Some(frontier) = self.flat_frontier.as_mut() { frontier.clear(); }
670 self.linear_stack_original.clear();
671 self.linear_stack_work.clear();
672 for bucket in &mut self.processing_queue {
673 bucket.clear();
674 }
675 }
676
677 pub(crate) fn reset_all(&mut self) {
678 self.clear_all();
679 self.admission_cache.clear();
680 self.parser_relative_mask_eq_cache.clear();
681 self.template_advance_runtime.reset_all();
682 }
683}
684
685pub struct ConstraintState {
686 pub(crate) markers: Option<Arc<crate::runtime::markers::MarkerState>>,
687 pub(crate) constraint: Constraint,
688 pub(crate) state: ParserStateMap,
690 pub(crate) epoch: u64,
693 pub(crate) mask_cache: StateMaskCache,
696}
697
698impl Clone for ConstraintState {
699
700 fn clone(&self) -> Self {
701 ConstraintState {
702 markers: self.markers.clone(),
703 constraint: self.constraint.clone(),
704 state: self.state.clone(),
705 epoch: self.epoch,
706 mask_cache: StateMaskCache::new(),
707 }
708 }
709}
710
711impl std::fmt::Debug for ConstraintState {
712 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
713 f.debug_struct("ConstraintState")
714 .field("terminated", &self.terminated())
715 .field("state_len", &self.state.len())
716 .field("mask_cached", &self.mask_cache.lock().unwrap().is_some())
717 .finish()
718 }
719}
720
721impl ConstraintState {
722 const TERMINATED_BIT: u64 = 1 << 63;
723 const GENERATION_MASK: u64 = Self::TERMINATED_BIT - 1;
724
725 #[inline]
726 pub(crate) fn generation(&self) -> u64 {
727 self.epoch & Self::GENERATION_MASK
728 }
729
730 #[inline]
731 pub(crate) fn terminated(&self) -> bool {
732 self.epoch & Self::TERMINATED_BIT != 0
733 }
734
735 #[inline]
736 pub(crate) fn advance_generation(&mut self, terminated: bool) {
737 let next = self.epoch.wrapping_add(1) & Self::GENERATION_MASK;
738 if next == 0 { self.mask_cache.clear(); }
740 self.epoch = next | (u64::from(terminated) << 63);
741 }
742
743 pub(crate) fn copy_snapshot_from(&mut self, source: &ConstraintState) {
744 assert!(Arc::ptr_eq(&self.constraint.data, &source.constraint.data));
745 self.markers = source.markers.clone();
746 self.state = source.state.clone();
747 self.epoch = source.epoch;
748 self.mask_cache.clear();
749 }
750
751 pub(crate) fn reserve_linear_stack_hot_path(&mut self) {
752 for gss in self.state.values_mut() {
757 let _ = gss.reserve_single_segment_capacity(LINEAR_STACK_RESERVE);
758 }
759 }
760
761
762 pub fn forced_bytes(&self) -> Vec<u8> {
764 crate::runtime::forced_bytes_for_states(std::slice::from_ref(self))
765 }
766
767 pub fn is_accepting(&self) -> bool {
769 if !self.constraint.end_tokens.is_empty() {
770 return self.terminated();
771 }
772 frontier_is_accepting(&self.constraint, &self.state, self.terminated())
773 }
774
775 pub(crate) fn frontier_complete(&self) -> bool {
778 frontier_is_accepting(&self.constraint, &self.state, false)
779 }
780
781 #[cfg(feature = "internal-api")]
782 pub(crate) fn frontier_shape(&self) -> (usize, usize, usize, usize, Vec<u32>) {
783 let entries = &self.state.entries;
784 let mut keys = Vec::new();
785 let mut ptr_duplicates = 0;
786 let mut equal_duplicates = 0;
787 for (i, (key, gss)) in entries.iter().enumerate() {
788 if keys.last() != Some(key) { keys.push(*key); }
789 let previous = &entries[..i];
790 if previous.iter().any(|(k, g)| k == key && gss.ptr_eq(g)) {
791 ptr_duplicates += 1;
792 } else if previous.iter().any(|(k, g)| k == key && gss == g) {
793 equal_duplicates += 1;
794 }
795 }
796 (entries.len(), keys.len(), ptr_duplicates, equal_duplicates,
797 entries.iter().map(|(k, _)| *k).collect())
798 }
799
800 pub(crate) fn parser_root_count(&self) -> usize {
801 self.state.values().map(|gss| gss.peek_values().len()).sum()
802 }
803
804 pub(crate) fn parser_path_count(&self, limit: usize) -> usize {
805 self.state.values().map(|gss| gss.path_count_at_most(limit)).sum::<usize>().min(limit)
806 }
807
808 pub(crate) fn has_parser_ambiguity(&self) -> bool {
809 self.parser_path_count(2) > 1
810 }
811
812 pub(crate) fn debug_parser_stacks(&self) -> Vec<(u32, Vec<(Vec<u32>, Vec<(u32, Vec<u32>)>)>)> {
815 let mut grouped = std::collections::BTreeMap::<
816 u32,
817 Vec<(Vec<u32>, Vec<(u32, Vec<u32>)>)>,
818 >::new();
819 for (&ts, gss) in self.state.iter() {
820 let stacks = gss
821 .to_stacks(4_096)
822 .expect("stack enumeration exceeded explicit limit");
823 let out = grouped.entry(ts).or_default();
824 out.extend(stacks.into_iter().map(|(stack, acc)| {
825 let disallowed = acc
826 .iter()
827 .map(|(key, values)| (*key, values.iter().copied().collect()))
828 .collect();
829 (stack, disallowed)
830 }));
831 }
832 for stacks in grouped.values_mut() {
833 stacks.sort();
834 stacks.dedup();
835 }
836 grouped.into_iter().collect()
837 }
838
839 #[must_use]
841 pub fn is_terminated(&self) -> bool {
842 if self.terminated() {
843 return true;
844 }
845 if self.state.is_empty() {
846 return true;
847 }
848 if !self.constraint.end_tokens.is_empty() && self.frontier_complete() {
850 return false;
851 }
852 !self.state.iter().any(|(&tokenizer_state, gss)| {
853 super::commit::entry_can_continue(&self.constraint, tokenizer_state, gss)
854 })
855 }
856
857 #[cfg(any(test,feature="internal-api"))]
858 #[doc(hidden)]
859 pub fn forced_canonical_reference(&self)->Vec<u32> {
860 super::commit::forcing_reference::force(std::slice::from_ref(self),None)
861 }
862 #[cfg(any(test,feature="internal-api"))]
863 #[doc(hidden)]
864 pub fn forced_token_ids_reference(&self)->Vec<u32> {
865 super::commit::forcing_reference::force_token_ids(std::slice::from_ref(self),None)
866 }
867
868 #[cfg(any(test, feature="internal-api"))]
869 pub(super) fn mask_for_forced(&self, dynamic: bool) -> Vec<u32> {
870 if !self.constraint.end_tokens.is_empty() { return self.mask(); }
871 if dynamic {
872 let mut mask = vec![0u32; self.constraint.body_mask_len()];
873 self.fill_mask_dynamic(&mut mask);
874 mask
875 } else { self.mask() }
876 }
877
878}
879
880pub(super) fn frontier_is_accepting(constraint: &Constraint, state: &ParserStateMap, terminated: bool) -> bool {
882 if terminated { return true; }
883 if constraint.uses_compact_segmented_parser_runtime() {
884 let Some(root_reset) = constraint.recursive_tokenizer_reset_state(0) else {
885 return false;
886 };
887 return state.values_for_key(root_reset).any(|stack| {
888 !stack.is_empty()
889 && constraint
890 .compact_segmented_parser_is_finished(stack)
891 .unwrap_or(false)
892 });
893 }
894 let product_initial = constraint.tokenizer.initial_state();
895 let commit_initial = constraint.runtime_commit_initial_state();
896 state
897 .values_for_key(product_initial)
898 .chain(
899 (commit_initial != product_initial)
900 .then(|| state.values_for_key(commit_initial))
901 .into_iter()
902 .flatten(),
903 )
904 .any(|stack| {
905 if let Some(parser) = &constraint.template_parser {
906 return parser.finished(stack);
907 }
908 !stack.is_empty()
909 && constraint
910 .sparse_direct_regular_gss_is_complete(stack)
911 .unwrap_or_else(|| {
912 if let Some(finished) =
913 constraint.compact_segmented_parser_is_finished(stack)
914 {
915 finished
916 } else if !constraint.parser_has_controls() {
917 stacks_finished(&constraint.table, stack)
918 } else {
919 stacks_finished_control_closed(&constraint.table, stack)
920 }
921 })
922 })
923 }
924
925
926#[cfg(test)]
927mod clone_and_scratch_tests {
928 use super::*;
929 use crate::{Grammar, Vocab};
930
931 fn constraint(source: &str) -> Constraint {
932 let vocab = Vocab::new(vec![(0, b"a".to_vec()), (1, b"b".to_vec()), (2, b"c".to_vec())]).unwrap();
933 Constraint::compile(Grammar::glrm(source), &vocab).unwrap()
934 }
935
936 #[test]
937 fn sequence_state_layout() {
938 eprintln!("state={} frontier={} entry={} constraint={} markers={} cache={}",
939 std::mem::size_of::<ConstraintState>(), std::mem::size_of::<ParserStateMap>(),
940 std::mem::size_of::<(u32, ParserGSS)>(), std::mem::size_of::<Constraint>(),
941 std::mem::size_of::<Option<Arc<crate::runtime::markers::MarkerState>>>(),
942 std::mem::size_of::<StateMaskCache>());
943 }
944
945 #[test]
946 fn packed_epoch_preserves_termination_and_invalidates_rollover() {
947 let c = constraint("start root; nt root = 'a'+;");
948 let mut state = c.start();
949 state.epoch = ConstraintState::GENERATION_MASK;
950 state.mask_cache.store(0, &[1], &[]);
951 state.advance_generation(true);
952 assert_eq!(state.generation(), 0);
953 assert!(state.terminated());
954 assert!(state.mask_cache.lock().unwrap().is_none());
955 let mut clone = state.clone();
956 assert!(clone.terminated());
957 clone.advance_generation(false);
958 assert_eq!(clone.generation(), 1);
959 assert!(!clone.terminated());
960 assert!(state.terminated());
961 state.copy_snapshot_from(&clone);
962 assert_eq!(state.generation(), 1);
963 assert!(!state.terminated());
964 #[cfg(target_pointer_width = "64")]
965 assert!(std::mem::size_of::<ConstraintState>() <= 112);
966 }
967
968 #[test]
969 fn compact_mask_cache_is_lazy_and_concurrent() {
970 let mut cache = StateMaskCache::new();
971 assert_eq!(std::mem::size_of::<StateMaskCache>(), std::mem::size_of::<*const ()>());
972 assert!(cache.lock().unwrap().is_none());
973 let start = std::sync::Barrier::new(8);
974 std::thread::scope(|scope| {
975 for _ in 0..8 {
976 let (cache, start) = (&cache, &start);
977 scope.spawn(move || {
978 start.wait();
979 cache.store(7, &[1, 2], &[3, 4]);
980 let guard = cache.lock().unwrap().unwrap();
981 assert_eq!((guard.generation, guard.mask.as_slice(), guard.merged_dense.as_slice()),
982 (7, &[1, 2][..], &[3, 4][..]));
983 });
984 }
985 });
986 cache.get_mut().unwrap().unwrap().generation = 8;
987 cache.store(9, &[5], &[]);
988 let guard = cache.lock().unwrap().unwrap();
989 assert_eq!(guard.generation, 9);
990 assert_eq!(guard.mask, [5]);
991 assert!(guard.merged_dense.is_empty());
992 drop(guard);
993 cache.clear();
994 assert!(cache.lock().unwrap().is_none());
995 cache.store(10, &[6], &[]);
996 assert_eq!(cache.lock().unwrap().unwrap().generation, 10);
997 }
998
999 #[test]
1000 fn constraint_mask_length_cache_is_shared_and_cow_invalidated() {
1001 let original = constraint("start root; nt root = 'a'+;");
1002 assert_eq!(std::mem::size_of::<Constraint>(), std::mem::size_of::<*const ()>());
1003 let old_len = original.mask_bit_len();
1004 let mut changed = original.clone();
1005 assert_eq!(changed.cached_mask_bit_len.get(), Some(&old_len));
1006 changed.end_tokens = Arc::from([99u32]);
1007 assert_eq!(changed.cached_mask_bit_len.get(), None);
1008 assert_eq!(changed.mask_bit_len(), 100);
1009 assert_eq!(original.mask_bit_len(), old_len);
1010 assert!(!Arc::ptr_eq(&original.data, &changed.data));
1011 }
1012
1013
1014 #[test]
1017 #[ignore = "developer profile; set GLRMASK_FRONTIER_PROFILE_VOCAB to a token-hex file"]
1018 fn frontier_width_profile() {
1019 let path = std::env::var_os("GLRMASK_FRONTIER_PROFILE_VOCAB").expect("token-hex path");
1020 let text = std::fs::read_to_string(path).unwrap();
1021 let entries: Vec<_> = text.lines().enumerate().map(|(id,line)| {
1022 let bytes = line.as_bytes().as_chunks::<2>().0.iter()
1023 .map(|p| u8::from_str_radix(std::str::from_utf8(p).unwrap(),16).unwrap())
1024 .collect::<Vec<_>>();
1025 (id as u32, bytes)
1026 }).collect();
1027 let mut byte_ids = [u32::MAX;256];
1028 for (id,bytes) in &entries {
1029 if let [b] = bytes.as_slice() {
1030 let slot = &mut byte_ids[*b as usize];
1031 if *slot == u32::MAX { *slot = *id; }
1032 }
1033 }
1034 assert!(byte_ids.iter().all(|&id| id != u32::MAX));
1035 let vocab = Vocab::new(entries).unwrap();
1036 let opts = crate::CompileOptions::default().mask_strategy(crate::MaskStrategy::FAST_COMPILE);
1037 let profile = |name: &str, compiled: &crate::Constraint, bytes: &[u8]| {
1038 let mut s = compiled.start();
1039 let mut histogram = std::collections::BTreeMap::new();
1040 *histogram.entry(s.state.len()).or_insert(0usize) += 1;
1041 for (i,b) in bytes.iter().enumerate().take(512) {
1042 assert!(s.commit_token(byte_ids[*b as usize]), "{name}: byte {i}");
1043 *histogram.entry(s.state.len()).or_insert(0) += 1;
1044 }
1045 eprintln!("FRONTIER {name} {histogram:?}");
1046 };
1047 let js = Grammar::from_glrm(include_str!("../programmatic_js/javascript.glrm")).unwrap()
1048 .compile_with(&vocab,opts.clone()).unwrap();
1049 for (name,bytes) in [
1050 ("js-dangling",include_bytes!("../../tests/data/javascript/16_dangling_else_and_nested_prefixes.js").as_slice()),
1051 ("js-deep",include_bytes!("../../tests/data/javascript/19_deep_nesting.js").as_slice()),
1052 ("js-comprehensive",include_bytes!("../../tests/data/javascript/22_comprehensive_integration.js").as_slice()),
1053 ] { profile(name,&js,bytes); }
1054 let nested = Grammar::from_json_schema(r#"{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer"},"name":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}}},"required":["id","name","tags"],"additionalProperties":false}}},"required":["items"],"additionalProperties":false}"#).unwrap()
1055 .compile_with(&vocab,opts.clone()).unwrap();
1056 profile("json-nested",&nested,br#"{"items": [{"id": 123, "name": "alpha", "tags": ["x", "y"]}, {"id": 456, "name": "beta", "tags": ["z"]}]}"#);
1057 let union = Grammar::from_json_schema(r#"{"type":"array","items":{"anyOf":[{"type":"string","pattern":"^ab[0-9]+$"},{"type":"string","pattern":"^abc.*$"},{"type":"object","properties":{"key":{"type":"string"},"value":{"type":"integer"}},"required":["key","value"],"additionalProperties":false},{"type":"integer"}]}}"#).unwrap()
1058 .compile_with(&vocab,opts).unwrap();
1059 profile("json-union",&union,br#"["ab123", "abcxyz", {"key": "word", "value": -12}, 42, "ab456"]"#);
1060 }
1061
1062
1063 #[test]
1064 fn scratch_checkout_is_reentrant_constraint_scoped_and_reusable() {
1065 let c = constraint("start root; nt root = 'a'+;");
1066 let other = constraint("start root; nt root = 'b'+;");
1067 let mut outer = commit_scratch(&c);
1068 outer.linear_stack_original.push(98765);
1069 let outer_ptr = &*outer as *const CommitBuffers;
1070 let inner = commit_scratch(&c);
1071 assert_ne!(outer_ptr, &*inner as *const CommitBuffers);
1072 assert!(inner.linear_stack_original.is_empty());
1073 let different = commit_scratch(&other);
1074 assert!(different.linear_stack_original.is_empty());
1075 drop(different);
1076 drop(inner);
1077 drop(outer);
1078 let mut reused = commit_scratch(&c);
1079 assert_eq!(outer_ptr, &*reused as *const CommitBuffers);
1080 assert_eq!(reused.linear_stack_original.pop(), Some(98765));
1081 drop(reused);
1082 let a = mask_scratch(&c);
1083 let b = mask_scratch(&c);
1084 assert!(!std::ptr::eq(&*a, &*b));
1085 }
1086
1087 #[test]
1088 fn scratch_is_not_reused_after_unwind() {
1089 let c = constraint("start root; nt root = 'a'+;");
1090 let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1091 let mut scratch = commit_scratch(&c);
1092 scratch.linear_stack_original.push(98765);
1093 panic!("simulated runtime unwind");
1094 }));
1095 assert!(failed.is_err());
1096 assert!(!commit_scratch(&c).linear_stack_original.contains(&98765));
1097 }
1098
1099 #[test]
1100 fn bulk_rekey_reuses_spilled_frontier_storage() {
1101 let c = constraint("start root; nt root = 'a'+;");
1102 let initial = c.start();
1103 let gss = initial.state.values().next().unwrap().clone();
1104 let mut frontier = ParserStateMap::singleton(0, gss.clone());
1105 let keys: Vec<u32> = (0..65).collect();
1106 assert!(frontier.replace_single_keys(&keys));
1107 assert!(frontier.entries.spilled());
1108 assert!(frontier.values().all(|value| value.ptr_eq(&gss)));
1109 let storage = frontier.entries.as_ptr();
1110 assert!(frontier.replace_uniform_gss_keys(&[100]));
1111 assert_eq!(frontier.entries.as_ptr(), storage);
1112 assert!(frontier.replace_single_keys(&keys));
1113 assert_eq!(frontier.entries.as_ptr(), storage);
1114 assert_eq!(frontier.keys().copied().collect::<Vec<_>>(), keys);
1115 assert!(frontier.values().all(|value| value.ptr_eq(&gss)));
1116 assert!(!frontier.replace_uniform_gss_keys(&[2, 1]));
1117 assert_eq!(frontier.keys().copied().collect::<Vec<_>>(), keys);
1118 }
1119
1120 #[test]
1121 fn sequence_clone_shares_gss_nodes_but_not_frontier_storage() {
1122 let c = constraint("start root; nt root = 'a' ('b' | 'c');");
1123 let mut original = c.start();
1124 assert!(original.commit_token(0));
1125 let expected = original.mask();
1126 let mut accepted = original.clone();
1127 let mut rejected = original.clone();
1128 for ((a, b), d) in original.state.values().zip(accepted.state.values()).zip(rejected.state.values()) {
1129 assert!(a.ptr_eq(b) && a.ptr_eq(d));
1130 }
1131 assert!(!std::ptr::eq(&original.state, &accepted.state));
1132 assert!(accepted.commit_token(1));
1133 assert!(accepted.is_accepting());
1134 assert!(!rejected.commit_token(0));
1135 assert!(!rejected.is_accepting());
1136 assert!(rejected.is_terminated());
1137 assert!(rejected.mask().iter().all(|&word| word == 0));
1138 assert_eq!(original.mask(), expected);
1139 assert!(!original.is_accepting());
1140 assert!(original.commit_token(2));
1141 assert!(original.is_accepting());
1142 }
1143}