///|
/// Single activation frame in the incremental grammar automaton.
priv struct StackFrame {
  rule_id : Int32
  alt_idx : Int32
  elem_idx : Int32
}

///|
/// Shared empty-stack sentinel stored in unused `StackSet` slots to avoid `Option` boxing.
let empty_stack_sentinel : Array[StackFrame] = []

///|
/// Reusable open-addressed hash set of `Array[StackFrame]` with O(1) generation clearing.
priv struct StackSet {
  mut capacity : Int32
  mut mask : Int32
  mut size : Int32
  mut grow_at : Int32
  mut cur_gen : Int32
  mut gen : FixedArray[Int32]
  mut hashes : FixedArray[Int32]
  mut keys : FixedArray[Array[StackFrame]]
}

///|
/// Reusable scratch buffers for `expand_work` / `step_stacks_with` across multiple steps.
priv struct ExpandScratch {
  work : Array[Array[StackFrame]]
  seen : StackSet
}

///|
/// Incremental stack-based constrained decoding state machine.
pub struct GrammarState {
  grammar : CompiledGrammar
  priv mut stacks : Array[Array[StackFrame]]
  priv mut cached_allowed : Array[CharRange]?
  priv mut cached_ascii_map : FixedArray[Bool]?
  priv scratch : ExpandScratch
}

///|
/// Compute a fast, allocation-free 32-bit FNV-1a + Murmur3 avalanche hash of a parse stack.
fn hash_stack(stack : Array[StackFrame]) -> Int32 {
  let mut h : UInt32 = 2166136261U
  let len = stack.length()
  for i = 0; i < len; i = i + 1 {
    let f = stack[i]
    h = (h ^ f.rule_id.reinterpret_as_uint()) * 16777619U
    h = (h ^ f.alt_idx.reinterpret_as_uint()) * 16777619U
    h = (h ^ f.elem_idx.reinterpret_as_uint()) * 16777619U
  }
  h = h ^ (h >> 16)
  h = h * 0x85EBCA6BU
  h = h ^ (h >> 13)
  h = h * 0xC2B2AE35U
  h = h ^ (h >> 16)
  h.reinterpret_as_int()
}

///|
/// Structural equality on two `Array[StackFrame]` without virtual dispatch.
fn stack_frames_equal(a : Array[StackFrame], b : Array[StackFrame]) -> Bool {
  let len = a.length()
  if len != b.length() {
    return false
  }
  for i = 0; i < len; i = i + 1 {
    let fa = a[i]
    let fb = b[i]
    if fa.rule_id != fb.rule_id ||
      fa.alt_idx != fb.alt_idx ||
      fa.elem_idx != fb.elem_idx {
      return false
    }
  }
  true
}

///|
/// Compute an allocation-free 32-bit hash of a deterministic list of active stacks.
fn hash_stack_list(stacks : Array[Array[StackFrame]]) -> Int32 {
  let mut h : UInt32 = 2166136261U
  let len = stacks.length()
  h = (h ^ len.reinterpret_as_uint()) * 16777619U
  for i = 0; i < len; i = i + 1 {
    let sh = hash_stack(stacks[i]).reinterpret_as_uint()
    h = (h ^ sh) * 16777619U
  }
  h = h ^ (h >> 16)
  h = h * 0x85EBCA6BU
  h = h ^ (h >> 13)
  h = h * 0xC2B2AE35U
  h = h ^ (h >> 16)
  h.reinterpret_as_int()
}

///|
/// Structural equality on two active stack lists.
fn stack_lists_equal(
  a : Array[Array[StackFrame]],
  b : Array[Array[StackFrame]],
) -> Bool {
  let len = a.length()
  if len != b.length() {
    return false
  }
  for i = 0; i < len; i = i + 1 {
    if !stack_frames_equal(a[i], b[i]) {
      return false
    }
  }
  true
}

///|
fn StackSet::new(initial_cap~ : Int32 = 16) -> StackSet {
  let cap = if initial_cap < 16 { 16 } else { initial_cap }
  {
    capacity: cap,
    mask: cap - 1,
    size: 0,
    grow_at: cap / 2,
    cur_gen: 1,
    gen: FixedArray::make(cap, 0),
    hashes: FixedArray::make(cap, 0),
    keys: FixedArray::make(cap, empty_stack_sentinel),
  }
}

///|
fn StackSet::clear(self : StackSet) -> Unit {
  if self.size == 0 {
    return
  }
  self.size = 0
  if self.capacity > 256 {
    let cap = 64
    self.capacity = cap
    self.mask = cap - 1
    self.grow_at = cap / 2
    self.cur_gen = 1
    self.gen = FixedArray::make(cap, 0)
    self.hashes = FixedArray::make(cap, 0)
    self.keys = FixedArray::make(cap, empty_stack_sentinel)
  } else if self.cur_gen >= 0x7FFF_FFFE {
    self.gen.fill(0)
    self.keys.fill(empty_stack_sentinel)
    self.cur_gen = 1
  } else {
    self.cur_gen += 1
  }
}

///|
fn StackSet::grow(self : StackSet) -> Unit {
  if self.capacity >= 0x4000_0000 {
    return
  }
  let old_cap = self.capacity
  let old_gen = self.gen
  let old_hashes = self.hashes
  let old_keys = self.keys
  let g = self.cur_gen
  let new_cap = old_cap * 2
  let new_mask = new_cap - 1
  let new_gen = FixedArray::make(new_cap, 0)
  let new_hashes = FixedArray::make(new_cap, 0)
  let new_keys = FixedArray::make(new_cap, empty_stack_sentinel)
  for i = 0; i < old_cap; i = i + 1 {
    if old_gen[i] == g {
      let h = old_hashes[i]
      let mut idx = h & new_mask
      while new_gen[idx] == 1 {
        idx = (idx + 1) & new_mask
      }
      new_gen[idx] = 1
      new_hashes[idx] = h
      new_keys[idx] = old_keys[i]
    }
  }
  self.capacity = new_cap
  self.mask = new_mask
  self.grow_at = new_cap / 2
  self.cur_gen = 1
  self.gen = new_gen
  self.hashes = new_hashes
  self.keys = new_keys
}

///|
fn StackSet::insert_with_hash(
  self : StackSet,
  key : Array[StackFrame],
  h : Int32,
) -> Bool {
  if self.size >= self.grow_at {
    self.grow()
  }
  let g = self.cur_gen
  let m = self.mask
  let mut idx = h & m
  while self.gen[idx] == g {
    if self.hashes[idx] == h && stack_frames_equal(self.keys[idx], key) {
      return false
    }
    idx = (idx + 1) & m
  }
  self.gen[idx] = g
  self.hashes[idx] = h
  self.keys[idx] = key
  self.size += 1
  true
}

///|
fn ExpandScratch::new() -> ExpandScratch {
  { work: [], seen: StackSet::new(), }
}

///|
fn clone_stacks(stacks : Array[Array[StackFrame]]) -> Array[Array[StackFrame]] {
  let out : Array[Array[StackFrame]] = Array(capacity=stacks.length())
  for s in stacks {
    out.push(s.copy())
  }
  out
}

///|
fn copy_with_replaced_top(
  stack : Array[StackFrame],
  frame : StackFrame,
) -> Array[StackFrame] {
  let out = stack.copy()
  out[out.length() - 1] = frame
  out
}

///|
fn copy_pop_top(stack : Array[StackFrame]) -> Array[StackFrame] {
  let len = stack.length()
  if len <= 1 {
    return []
  }
  let out : Array[StackFrame] = Array(capacity=len - 1)
  for i = 0; i < len - 1; i = i + 1 {
    out.push(stack[i])
  }
  out
}

///|
fn copy_and_push(
  stack : Array[StackFrame],
  frame : StackFrame,
) -> Array[StackFrame] {
  let len = stack.length()
  let out : Array[StackFrame] = Array(capacity=len + 1)
  for i = 0; i < len; i = i + 1 {
    out.push(stack[i])
  }
  out.push(frame)
  out
}

///|
/// Fast membership check on a normalized `Array[CharRange]` avoiding binary search setup for 0/1-element lists.
fn fast_ranges_contains(ranges : Array[CharRange], cp : Int32) -> Bool {
  let len = ranges.length()
  if len == 0 {
    return false
  }
  if len == 1 {
    let r = ranges[0]
    return cp >= r.start && cp <= r.end
  }
  let mut lo : Int32 = 0
  let mut hi : Int32 = len - 1
  while lo <= hi {
    let mid = lo + (hi - lo) / 2
    let r = ranges[mid]
    if cp < r.start {
      hi = mid - 1
    } else if cp > r.end {
      lo = mid + 1
    } else {
      return true
    }
  }
  false
}

///|
/// Check whether the top terminal element of `stack` matches `cp`.
fn stack_top_matches(
  grammar : CompiledGrammar,
  stack : Array[StackFrame],
  cp : Int32,
) -> Bool {
  if stack.length() == 0 {
    return false
  }
  let top = stack[stack.length() - 1]
  let seq = grammar.rules[top.rule_id].alts[top.alt_idx]
  match seq[top.elem_idx] {
    CharRanges(ranges) => fast_ranges_contains(ranges, cp)
    RuleRef(_) => false
  }
}

///|
/// Decode one Unicode scalar value (or unpaired UTF-16 code unit) at `idx`,
/// matching `String::iter()` / `for c in s` semantics bit-for-bit.
fn decode_cp_at(s : String, idx : Int32, len : Int32) -> (Int32, Int32) {
  let cu1 = s[idx]
  let u1 = cu1.to_int()
  if u1 < 0x80 {
    return (u1, idx + 1)
  }
  if cu1.is_leading_surrogate() && idx + 1 < len {
    let cu2 = s[idx + 1]
    if cu2.is_trailing_surrogate() {
      let cp = ((u1 - 0xD800) << 10) + (cu2.to_int() - 0xDC00) + 0x10000
      return (cp, idx + 2)
    }
  }
  (u1, idx + 1)
}

///|
/// Build a 128-entry ASCII lookup bitmap from a sorted, normalized `Array[CharRange]`.
fn build_ascii_bitmap(ranges : Array[CharRange]) -> FixedArray[Bool] {
  let map = FixedArray::make(128, false)
  for r in ranges {
    if r.start > 127 {
      break
    }
    let s = if r.start < 0 { 0 } else { r.start }
    let e = if r.end > 127 { 127 } else { r.end }
    for cp = s; cp <= e; cp = cp + 1 {
      map[cp] = true
    }
  }
  map
}

///|
/// Compute the normalized union of allowed `CharRange`s across `stacks`.
fn stacks_allowed_ranges(
  grammar : CompiledGrammar,
  stacks : Array[Array[StackFrame]],
) -> Array[CharRange] {
  let len = stacks.length()
  if len == 0 {
    return []
  }
  if len == 1 {
    let stack = stacks[0]
    if stack.length() == 0 {
      return []
    }
    let top = stack[stack.length() - 1]
    let seq = grammar.rules[top.rule_id].alts[top.alt_idx]
    match seq[top.elem_idx] {
      CharRanges(ranges) =>
        if ranges.length() == 1 {
          let r = ranges[0]
          if r.start >= 0 && r.end <= 0x10FFFF && r.start <= r.end {
            return ranges.copy()
          }
          return normalize_ranges(ranges)
        } else {
          return normalize_ranges(ranges)
        }
      RuleRef(_) => return []
    }
  }
  let raw : Array[CharRange] = []
  for stack in stacks {
    if stack.length() == 0 {
      continue
    }
    let top = stack[stack.length() - 1]
    let seq = grammar.rules[top.rule_id].alts[top.alt_idx]
    match seq[top.elem_idx] {
      CharRanges(ranges) =>
        for r in ranges {
          raw.push(r)
        }
      RuleRef(_) => ()
    }
  }
  normalize_ranges(raw)
}

///|
/// Expand all non-terminals in `scratch.work` until every resulting stack
/// is either complete (empty) or paused at a terminal `CharRanges` element.
/// Applies tail-call optimization so right-recursive rules run in O(1) stack depth.
fn expand_work(
  grammar : CompiledGrammar,
  scratch : ExpandScratch,
) -> Array[Array[StackFrame]] {
  let work = scratch.work
  let seen = scratch.seen
  seen.clear()
  let out : Array[Array[StackFrame]] = []
  let mut has_empty = false
  let mut head = 0
  while head < work.length() {
    let cur = work[head]
    head += 1
    // Pop completed frames.
    while cur.length() > 0 {
      let top = cur[cur.length() - 1]
      let seq = grammar.rules[top.rule_id].alts[top.alt_idx]
      if top.elem_idx >= seq.length() {
        let _ = cur.pop()
      } else {
        break
      }
    }
    if cur.length() == 0 {
      if !has_empty {
        has_empty = true
        out.push([])
      }
      continue
    }
    let h = hash_stack(cur)
    if !seen.insert_with_hash(cur, h) {
      continue
    }
    let top = cur[cur.length() - 1]
    let seq = grammar.rules[top.rule_id].alts[top.alt_idx]
    match seq[top.elem_idx] {
      CharRanges(_) => out.push(cur)
      RuleRef(target_id) => {
        // Prepare continuation stack with tail-call optimization.
        let next_idx = top.elem_idx + 1
        let cont = if next_idx >= seq.length() {
          copy_pop_top(cur)
        } else {
          copy_with_replaced_top(cur, {
            rule_id: top.rule_id,
            alt_idx: top.alt_idx,
            elem_idx: next_idx,
          })
        }
        let target_alts = grammar.rules[target_id].alts
        let n_alts = target_alts.length()
        for alt_i = 0; alt_i < n_alts; alt_i = alt_i + 1 {
          let is_last = alt_i == n_alts - 1
          if target_alts[alt_i].length() == 0 {
            if cont.length() == 0 {
              if !has_empty {
                has_empty = true
                out.push([])
              }
            } else if is_last {
              work.push(cont)
            } else {
              work.push(cont.copy())
            }
          } else {
            let frame : StackFrame = {
              rule_id: target_id,
              alt_idx: alt_i,
              elem_idx: 0,
            }
            if is_last {
              cont.push(frame)
              work.push(cont)
            } else {
              work.push(copy_and_push(cont, frame))
            }
          }
        }
      }
    }
  }
  work.clear()
  out
}

///|
/// Advance `stacks` by one code point `cp` using reusable `scratch`.
fn step_stacks_with(
  grammar : CompiledGrammar,
  stacks : Array[Array[StackFrame]],
  cp : Int32,
  scratch : ExpandScratch,
) -> Array[Array[StackFrame]] {
  let len = stacks.length()
  if len == 0 {
    return []
  }
  if len == 1 {
    let stack = stacks[0]
    if stack.length() == 0 {
      return []
    }
    let top = stack[stack.length() - 1]
    let seq = grammar.rules[top.rule_id].alts[top.alt_idx]
    match seq[top.elem_idx] {
      CharRanges(ranges) => {
        if !fast_ranges_contains(ranges, cp) {
          return []
        }
        let next_idx = top.elem_idx + 1
        if next_idx < seq.length() {
          match seq[next_idx] {
            CharRanges(_) =>
              return [
                copy_with_replaced_top(stack, {
                  rule_id: top.rule_id,
                  alt_idx: top.alt_idx,
                  elem_idx: next_idx,
                }),
              ]
            RuleRef(_) => ()
          }
        }
        scratch.work.clear()
        let advanced = if next_idx >= seq.length() {
          copy_pop_top(stack)
        } else {
          copy_with_replaced_top(stack, {
            rule_id: top.rule_id,
            alt_idx: top.alt_idx,
            elem_idx: next_idx,
          })
        }
        scratch.work.push(advanced)
        return expand_work(grammar, scratch)
      }
      RuleRef(_) => return []
    }
  }
  scratch.work.clear()
  for stack in stacks {
    if stack.length() == 0 {
      continue
    }
    let top = stack[stack.length() - 1]
    let seq = grammar.rules[top.rule_id].alts[top.alt_idx]
    match seq[top.elem_idx] {
      CharRanges(ranges) =>
        if fast_ranges_contains(ranges, cp) {
          let next_idx = top.elem_idx + 1
          let advanced = if next_idx >= seq.length() {
            copy_pop_top(stack)
          } else {
            copy_with_replaced_top(stack, {
              rule_id: top.rule_id,
              alt_idx: top.alt_idx,
              elem_idx: next_idx,
            })
          }
          scratch.work.push(advanced)
        }
      RuleRef(_) => ()
    }
  }
  if scratch.work.length() == 0 {
    return []
  }
  expand_work(grammar, scratch)
}

///|
/// Step `start` stacks through UTF-16 string `s` starting at code-unit index `from_cu`.
fn step_str_stacks(
  grammar : CompiledGrammar,
  start : Array[Array[StackFrame]],
  s : String,
  from_cu~ : Int32 = 0,
  scratch~ : ExpandScratch,
) -> Array[Array[StackFrame]]? {
  let len = s.length()
  let mut cur = start
  let mut idx = from_cu
  while idx < len {
    let (cp, next_idx) = decode_cp_at(s, idx, len)
    let next = step_stacks_with(grammar, cur, cp, scratch)
    if next.length() == 0 {
      return None
    }
    cur = next
    idx = next_idx
  }
  Some(cur)
}

///|
fn GrammarState::invalidate_cache(self : GrammarState) -> Unit {
  self.cached_allowed = None
  self.cached_ascii_map = None
}

///|
fn GrammarState::ensure_allowed_ranges(self : GrammarState) -> Array[CharRange] {
  match self.cached_allowed {
    Some(r) => r
    None => {
      let computed = stacks_allowed_ranges(self.grammar, self.stacks)
      self.cached_allowed = Some(computed)
      computed
    }
  }
}

///|
fn GrammarState::ensure_ascii_bitmap(self : GrammarState) -> FixedArray[Bool] {
  match self.cached_ascii_map {
    Some(m) => m
    None => {
      let m = build_ascii_bitmap(self.ensure_allowed_ranges())
      self.cached_ascii_map = Some(m)
      m
    }
  }
}

///|
/// Create a fresh incremental decoding state starting from the grammar's `root` rule.
pub fn GrammarState::new(grammar : CompiledGrammar) -> GrammarState {
  let scratch = ExpandScratch::new()
  let root_alts = grammar.rules[grammar.root_id].alts
  for alt_i = 0; alt_i < root_alts.length(); alt_i = alt_i + 1 {
    if root_alts[alt_i].length() == 0 {
      scratch.work.push([])
    } else {
      scratch.work.push([
        { rule_id: grammar.root_id, alt_idx: alt_i, elem_idx: 0, },
      ])
    }
  }
  let initial_stacks = expand_work(grammar, scratch)
  {
    grammar,
    stacks: initial_stacks,
    cached_allowed: None,
    cached_ascii_map: None,
    scratch,
  }
}

///|
/// Return true iff the input consumed so far constitutes a complete valid match.
pub fn GrammarState::is_complete(self : GrammarState) -> Bool {
  for s in self.stacks {
    if s.length() == 0 {
      return true
    }
  }
  false
}

///|
/// Return the number of currently active parse stacks (for diagnostics/debugging).
pub fn GrammarState::active_stack_count(self : GrammarState) -> Int32 {
  self.stacks.length()
}

///|
/// Transactionally feed one Unicode code point.
/// Returns `true` and advances the state if legal; returns `false` leaving state unchanged otherwise.
pub fn GrammarState::accept_codepoint(self : GrammarState, cp : Int32) -> Bool {
  let next = step_stacks_with(self.grammar, self.stacks, cp, self.scratch)
  if next.length() == 0 {
    false
  } else {
    self.stacks = next
    self.invalidate_cache()
    true
  }
}

///|
/// Transactionally feed one `Char`.
pub fn GrammarState::accept_char(self : GrammarState, c : Char) -> Bool {
  self.accept_codepoint(c.to_int())
}

///|
/// Transactionally feed an entire UTF-8 string (e.g., an LLM token).
/// If any character is illegal, returns `false` and rolls back to the prior state.
pub fn GrammarState::accept_str(self : GrammarState, s : String) -> Bool {
  if s.length() == 0 {
    return true
  }
  match step_str_stacks(self.grammar, self.stacks, s, scratch=self.scratch) {
    Some(next) => {
      self.stacks = next
      self.invalidate_cache()
      true
    }
    None => false
  }
}

///|
/// Reset this decoding state back to the initial `root` state, reusing internal scratch buffers.
pub fn GrammarState::reset(self : GrammarState) -> Unit {
  self.scratch.work.clear()
  let root_alts = self.grammar.rules[self.grammar.root_id].alts
  for alt_i = 0; alt_i < root_alts.length(); alt_i = alt_i + 1 {
    self.scratch.work.push([
      { rule_id: self.grammar.root_id, alt_idx: alt_i, elem_idx: 0, },
    ])
  }
  self.stacks = expand_work(self.grammar, self.scratch)
  self.invalidate_cache()
}

///|
/// Return true iff the entire string `s` is a complete valid sentence of this grammar.
pub fn CompiledGrammar::matches(self : CompiledGrammar, s : String) -> Bool {
  let state = GrammarState::new(self)
  if !state.accept_str(s) {
    return false
  }
  state.is_complete()
}