///|
/// Bounded resource limits for safe CUE parsing, evaluation, and export.
///
/// The defaults are chosen to protect against pathological inputs such as
/// disjunction explosion, deep nesting (safe on Windows 1 MB native debug
/// stacks), huge ASTs, and unbounded output expansion.
#derive(Eq, Debug)
pub(all) struct EvalLimits {
  max_source_bytes : Int32
  max_ast_nodes : Int32
  max_eval_steps : Int32
  max_depth : Int32
  max_disjunction_branches : Int32
  max_output_bytes : Int32
}

///|
/// Returns the default safe `EvalLimits` configuration.
pub fn EvalLimits::default() -> EvalLimits {
  {
    max_source_bytes: 1_048_576,
    max_ast_nodes: 100_000,
    max_eval_steps: 200_000,
    max_depth: 128,
    max_disjunction_branches: 256,
    max_output_bytes: 4_194_304,
  }
}

///|
/// Diagnostic error returned when an `EvalLimits` guardrail is exceeded.
///
/// Each variant stores `(actual, limit)`.
#derive(Eq, Debug)
pub(all) enum LimitError {
  SourceBytesExceeded(Int32, Int32)
  AstNodesExceeded(Int32, Int32)
  EvalStepsExceeded(Int32, Int32)
  MaxDepthExceeded(Int32, Int32)
  DisjunctionBranchesExceeded(Int32, Int32)
  OutputBytesExceeded(Int32, Int32)
}

///|
/// Formats a `LimitError` as a human-readable diagnostic message.
pub fn LimitError::message(self : LimitError) -> String {
  match self {
    SourceBytesExceeded(actual, limit) =>
      "source size (\{actual} bytes) exceeds limit (\{limit} bytes)"
    AstNodesExceeded(actual, limit) =>
      "AST node count (\{actual}) exceeds limit (\{limit})"
    EvalStepsExceeded(actual, limit) =>
      "evaluation steps (\{actual}) exceeds limit (\{limit})"
    MaxDepthExceeded(actual, limit) =>
      "maximum evaluation depth (\{actual}) exceeds limit (\{limit})"
    DisjunctionBranchesExceeded(actual, limit) =>
      "disjunction branches (\{actual}) exceeds limit (\{limit})"
    OutputBytesExceeded(actual, limit) =>
      "output size (\{actual} bytes) exceeds limit (\{limit})"
  }
}

///|
priv struct ActiveEvalContext {
  unify_fn : (Value, Value) -> Value
  validator : ((String, String, Array[Value], Value, EvalBudget) -> BuiltinValidationResult)?
}

///|
#derive(Debug)
priv struct EvalBudgetDebugRepr {
  limits : EvalLimits
  steps : Int32
  depth : Int32
}

///|
/// Mutable runtime budget tracker enforcing `EvalLimits` during evaluation.
pub struct EvalBudget {
  priv limits : EvalLimits
  priv mut steps : Int32
  priv mut depth : Int32
  priv mut active_ctx : ActiveEvalContext?
  priv mut matcher_fatal_trap : Array[CueError]?
  priv deferred_matcher_fatals : Array[(Array[CueError], Array[CueError])]
}

///|
pub impl Eq for EvalBudget with fn equal(self, other) {
  self.limits == other.limits &&
  self.steps == other.steps &&
  self.depth == other.depth
}

///|
pub impl @debug.Debug for EvalBudget with fn to_repr(self) {
  let repr_val : EvalBudgetDebugRepr = {
    limits: self.limits,
    steps: self.steps,
    depth: self.depth,
  }
  @debug.Repr(repr_val)
}

///|
/// Creates a fresh `EvalBudget` with the provided `EvalLimits`.
pub fn EvalBudget::new(limits : EvalLimits) -> EvalBudget {
  {
    limits,
    steps: 0,
    depth: 0,
    active_ctx: None,
    matcher_fatal_trap: None,
    deferred_matcher_fatals: [],
  }
}

///|
fn[T] EvalBudget::with_eval_context(
  self : EvalBudget,
  ctx : ActiveEvalContext?,
  body : () -> T,
) -> T {
  let prev = self.active_ctx
  self.active_ctx = ctx
  let out = body()
  self.active_ctx = prev
  out
}

///|
fn EvalBudget::record_matcher_fatal(
  self : EvalBudget,
  errs : Array[CueError],
) -> Unit {
  match self.matcher_fatal_trap {
    Some(buf) =>
      for err in errs {
        buf.push(err)
      }
    None => ()
  }
}

///|
fn[T] EvalBudget::with_matcher_fatal_trap(
  self : EvalBudget,
  body : () -> T,
) -> (T, Array[CueError]) {
  let prev = self.matcher_fatal_trap
  let local_buf : Array[CueError] = []
  self.matcher_fatal_trap = Some(local_buf)
  let out = body()
  self.matcher_fatal_trap = prev
  (out, local_buf)
}

///|
fn EvalBudget::register_deferred_matcher_fatal(
  self : EvalBudget,
  errs : Array[CueError],
  fatal : Array[CueError],
) -> Unit {
  let mut scanned = 0
  let mut i = self.deferred_matcher_fatals.length() - 1
  while i >= 0 {
    if scanned >= 16 && scanned % 16 == 0 {
      match self.consume_step() {
        Err(e) => {
          self.deferred_matcher_fatals.push(
            (errs, [CueError::new(ResourceLimit, e.message())]),
          )
          return
        }
        Ok(_) => ()
      }
    }
    let entry = self.deferred_matcher_fatals[i]
    if physical_equal(entry.0, errs) {
      let merged = pick_trapped_fatal(merge_errors(entry.1, fatal))
      self.deferred_matcher_fatals[i] = (entry.0, merged)
      return
    }
    scanned += 1
    i -= 1
  }
  self.deferred_matcher_fatals.push((errs, fatal))
}

///|
fn EvalBudget::mark_deferred_matcher_fatal(
  self : EvalBudget,
  v : Value,
  trapped : Array[CueError],
) -> Value {
  if trapped.is_empty() {
    return v
  }
  let fatal = pick_trapped_fatal(trapped)
  match v {
    Bottom(errs) => {
      let norm = normalize_bottom_errors(errs)
      self.register_deferred_matcher_fatal(norm, fatal)
      Bottom(norm)
    }
    _ => {
      let copy = fatal.copy()
      self.register_deferred_matcher_fatal(copy, fatal)
      Bottom(copy)
    }
  }
}

///|
fn EvalBudget::lookup_deferred_matcher_fatal(
  self : EvalBudget,
  errs : Array[CueError],
) -> Array[CueError]? {
  if self.deferred_matcher_fatals.is_empty() {
    return None
  }
  let mut scanned = 0
  let mut i = self.deferred_matcher_fatals.length() - 1
  while i >= 0 {
    if scanned >= 16 && scanned % 16 == 0 {
      match self.consume_step() {
        Err(e) => return Some([CueError::new(ResourceLimit, e.message())])
        Ok(_) => ()
      }
    }
    let entry = self.deferred_matcher_fatals[i]
    if physical_equal(entry.0, errs) {
      return Some(entry.1)
    }
    scanned += 1
    i -= 1
  }
  None
}

///|
fn EvalBudget::propagate_deferred_matcher_fatal_pair(
  self : EvalBudget,
  ea : Array[CueError],
  eb : Array[CueError],
  merged : Array[CueError],
) -> Unit {
  if self.deferred_matcher_fatals.is_empty() {
    return
  }
  match
    (
      self.lookup_deferred_matcher_fatal(ea),
      self.lookup_deferred_matcher_fatal(eb),
    ) {
    (Some(fa), Some(fb)) =>
      self.register_deferred_matcher_fatal(
        merged,
        pick_trapped_fatal(merge_errors(fa, fb)),
      )
    (Some(fa), None) => self.register_deferred_matcher_fatal(merged, fa)
    (None, Some(fb)) => self.register_deferred_matcher_fatal(merged, fb)
    (None, None) => ()
  }
}

///|
fn EvalBudget::replay_deferred_matcher_fatal(
  self : EvalBudget,
  errs : Array[CueError],
) -> CueError? {
  match self.lookup_deferred_matcher_fatal(errs) {
    Some(fatal) => {
      self.record_matcher_fatal(fatal)
      first_resource_limit_error(fatal)
    }
    None => None
  }
}

///|
fn EvalBudget::replay_deferred_matcher_fatal_prefixed(
  self : EvalBudget,
  errs : Array[CueError],
  seg : String,
) -> CueError? {
  match self.lookup_deferred_matcher_fatal(errs) {
    Some(fatal) => {
      let prefixed = prefix_trapped_fatal(fatal, seg)
      self.record_matcher_fatal(prefixed)
      first_resource_limit_error(prefixed)
    }
    None => None
  }
}

///|
fn merge_deferred_validator_constraint_pair_inner(
  a : ValidatorConstraint,
  b : ValidatorConstraint,
  budget : EvalBudget,
) -> Result[(ValidatorConstraint, Bool), CueError] {
  if budget.deferred_matcher_fatals.is_empty() {
    return Ok((a, false))
  }
  match budget.consume_step() {
    Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
    Ok(_) => ()
  }
  match budget.enter_depth() {
    Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
    Ok(_) => ()
  }
  let res : Result[(ValidatorConstraint, Bool), CueError] = match (a, b) {
    (MatchN(ca, pa), MatchN(cb, pb)) =>
      if pa.length() != pb.length() {
        Ok((a, false))
      } else {
        let mut changed = false
        match merge_deferred_value_pair_inner(ca, cb, budget) {
          Err(e) => Err(e)
          Ok((mc, c_changed)) => {
            if c_changed {
              changed = true
            }
            let new_pats : Array[Value] = []
            let mut err_opt : CueError? = None
            for i in 0.. {
                  err_opt = Some(e)
                  break
                }
                Ok((mp, p_changed)) => {
                  if p_changed {
                    changed = true
                  }
                  new_pats.push(mp)
                }
              }
            }
            match err_opt {
              Some(e) => Err(e)
              None =>
                if changed {
                  Ok((MatchN(mc, new_pats), true))
                } else {
                  Ok((a, false))
                }
            }
          }
        }
      }
    (Builtin(pkga, na, aa), Builtin(pkgb, nb, ab)) =>
      if pkga != pkgb || na != nb || aa.length() != ab.length() {
        Ok((a, false))
      } else {
        let mut changed = false
        let new_args : Array[Value] = []
        let mut err_opt : CueError? = None
        for i in 0.. {
              err_opt = Some(e)
              break
            }
            Ok((ma, a_changed)) => {
              if a_changed {
                changed = true
              }
              new_args.push(ma)
            }
          }
        }
        match err_opt {
          Some(e) => Err(e)
          None =>
            if changed {
              Ok((Builtin(pkga, na, new_args), true))
            } else {
              Ok((a, false))
            }
        }
      }
    _ => Ok((a, false))
  }
  budget.leave_depth()
  res
}

///|
fn merge_deferred_value_pair_inner(
  a : Value,
  b : Value,
  budget : EvalBudget,
) -> Result[(Value, Bool), CueError] {
  if budget.deferred_matcher_fatals.is_empty() {
    return Ok((a, false))
  }
  match budget.consume_step() {
    Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
    Ok(_) => ()
  }
  match budget.enter_depth() {
    Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
    Ok(_) => ()
  }
  let res : Result[(Value, Bool), CueError] = match (a, b) {
    (Bottom(ea), Bottom(eb)) =>
      match
        (
          budget.lookup_deferred_matcher_fatal(ea),
          budget.lookup_deferred_matcher_fatal(eb),
        ) {
        (Some(fa), Some(fb)) =>
          match first_resource_limit_error(fa) {
            Some(rl) => Err(rl)
            None =>
              match first_resource_limit_error(fb) {
                Some(rl) => Err(rl)
                None =>
                  if physical_equal(ea, eb) || fa == fb {
                    Ok((a, false))
                  } else {
                    let fresh = ea.copy()
                    budget.register_deferred_matcher_fatal(
                      fresh,
                      pick_trapped_fatal(merge_errors(fa, fb)),
                    )
                    Ok((Bottom(fresh), true))
                  }
              }
          }
        (Some(fa), None) =>
          match first_resource_limit_error(fa) {
            Some(rl) => Err(rl)
            None => Ok((a, false))
          }
        (None, Some(fb)) =>
          match first_resource_limit_error(fb) {
            Some(rl) => Err(rl)
            None => Ok((b, true))
          }
        (None, None) => Ok((a, false))
      }
    (List(la), List(lb)) =>
      if la.elems.length() != lb.elems.length() {
        Ok((a, false))
      } else {
        let mut changed = false
        let new_elems : Array[Value] = []
        let mut err_opt : CueError? = None
        for i in 0.. {
              err_opt = Some(e)
              break
            }
            Ok((me, e_changed)) => {
              if e_changed {
                changed = true
              }
              new_elems.push(me)
            }
          }
        }
        match err_opt {
          Some(e) => Err(e)
          None => {
            let new_tail = match (la.tail, lb.tail) {
              (Some(ta), Some(tb)) =>
                match merge_deferred_value_pair_inner(ta, tb, budget) {
                  Err(e) => {
                    err_opt = Some(e)
                    None
                  }
                  Ok((mt, t_changed)) => {
                    if t_changed {
                      changed = true
                    }
                    Some(mt)
                  }
                }
              (ta, _) => ta
            }
            match err_opt {
              Some(e) => Err(e)
              None =>
                if changed {
                  Ok((List({ elems: new_elems, tail: new_tail, }), true))
                } else {
                  Ok((a, false))
                }
            }
          }
        }
      }
    (Struct(sa), Struct(sb)) =>
      if sa.fields.length() != sb.fields.length() ||
        sa.patterns.length() != sb.patterns.length() ||
        sa.closed_rules.length() != sb.closed_rules.length() {
        Ok((a, false))
      } else {
        let mut changed = false
        let new_fields : Array[StructField] = []
        let mut err_opt : CueError? = None
        for i in 0.. {
              err_opt = Some(e)
              break
            }
            Ok((mv, f_changed)) => {
              if f_changed {
                changed = true
              }
              new_fields.push({ ..fa, value: mv, })
            }
          }
        }
        let new_patterns : Array[PatternConstraint] = []
        if err_opt is None {
          for i in 0.. {
                err_opt = Some(e)
                break
              }
              Ok((mk, k_changed)) =>
                match
                  merge_deferred_value_pair_inner(
                    pa.value_constraint,
                    pb.value_constraint,
                    budget,
                  ) {
                  Err(e) => {
                    err_opt = Some(e)
                    break
                  }
                  Ok((mv, v_changed)) => {
                    if k_changed || v_changed {
                      changed = true
                    }
                    new_patterns.push({
                      ..pa,
                      key_constraint: mk,
                      value_constraint: mv,
                    })
                  }
                }
            }
          }
        }
        let new_rules : Array[AllowedSet] = []
        if err_opt is None {
          for i in 0.. {
                  err_opt = Some(e)
                  break
                }
                Ok((mp, p_changed)) => {
                  if p_changed {
                    r_changed = true
                    changed = true
                  }
                  new_rpats.push(mp)
                }
              }
            }
            if err_opt is Some(_) {
              break
            }
            if r_changed {
              new_rules.push({ ..ra, patterns: new_rpats, })
            } else {
              new_rules.push(ra)
            }
          }
        }
        match err_opt {
          Some(e) => Err(e)
          None =>
            if changed {
              Ok(
                (
                  Struct({
                    ..sa,
                    fields: new_fields,
                    patterns: new_patterns,
                    closed_rules: new_rules,
                  }),
                  true,
                ),
              )
            } else {
              Ok((a, false))
            }
        }
      }
    (Disjunction(da), Disjunction(db)) =>
      if da.items.length() != db.items.length() {
        Ok((a, false))
      } else {
        let mut changed = false
        let new_items : Array[Disjunct] = []
        let mut err_opt : CueError? = None
        for i in 0.. {
              err_opt = Some(e)
              break
            }
            Ok((mv, i_changed)) => {
              if i_changed {
                changed = true
              }
              new_items.push({ ..ia, value: mv, })
            }
          }
        }
        match err_opt {
          Some(e) => Err(e)
          None =>
            if changed {
              Ok((Disjunction({ ..da, items: new_items, }), true))
            } else {
              Ok((a, false))
            }
        }
      }
    (Constrained(va, ca), Constrained(vb, cb)) =>
      if ca.length() != cb.length() {
        Ok((a, false))
      } else {
        let mut changed = false
        match merge_deferred_value_pair_inner(va, vb, budget) {
          Err(e) => Err(e)
          Ok((mv, v_changed)) => {
            if v_changed {
              changed = true
            }
            let new_cs : Array[ValidatorConstraint] = []
            let mut err_opt : CueError? = None
            for i in 0.. {
                  err_opt = Some(e)
                  break
                }
                Ok((mc, c_changed)) => {
                  if c_changed {
                    changed = true
                  }
                  new_cs.push(mc)
                }
              }
            }
            match err_opt {
              Some(e) => Err(e)
              None =>
                if changed {
                  Ok((Constrained(mv, new_cs), true))
                } else {
                  Ok((a, false))
                }
            }
          }
        }
      }
    _ => Ok((a, false))
  }
  budget.leave_depth()
  res
}

///|
fn merge_deferred_value_pair(
  a : Value,
  b : Value,
  budget : EvalBudget,
) -> Result[Value, CueError] {
  if budget.deferred_matcher_fatals.is_empty() {
    return Ok(a)
  }
  match merge_deferred_value_pair_inner(a, b, budget) {
    Ok((v, _)) => Ok(v)
    Err(e) => Err(e)
  }
}

///|
fn merge_deferred_validator_constraint_pair(
  a : ValidatorConstraint,
  b : ValidatorConstraint,
  budget : EvalBudget,
) -> Result[ValidatorConstraint, CueError] {
  if budget.deferred_matcher_fatals.is_empty() {
    return Ok(a)
  }
  match merge_deferred_validator_constraint_pair_inner(a, b, budget) {
    Ok((c, _)) => Ok(c)
    Err(e) => Err(e)
  }
}

///|
fn pattern_sort_key_checked(
  p : PatternConstraint,
  budget : EvalBudget,
) -> Result[String, CueError] {
  let buf = StringBuilder()
  match write_pattern_key_checked(p, buf, budget) {
    Ok(_) => Ok(buf.to_string())
    Err(e) => Err(e)
  }
}

///|
fn dedup_patterns_preserving_deferred(
  patterns : Array[PatternConstraint],
  budget : EvalBudget,
) -> Result[Array[PatternConstraint], CueError] {
  if budget.deferred_matcher_fatals.is_empty() || patterns.length() <= 1 {
    return Ok(patterns)
  }
  let out : Array[PatternConstraint] = []
  let key_to_idx : Map[String, Int32] = Map([])
  for p in patterns {
    let key = match pattern_sort_key_checked(p, budget) {
      Ok(k) => k
      Err(rl) => return Err(rl)
    }
    match key_to_idx.get(key) {
      Some(idx) => {
        let prev = out[idx]
        let merged_k = match
          merge_deferred_value_pair(
            prev.key_constraint,
            p.key_constraint,
            budget,
          ) {
          Ok(v) => v
          Err(rl) => return Err(rl)
        }
        let merged_v = match
          merge_deferred_value_pair(
            prev.value_constraint,
            p.value_constraint,
            budget,
          ) {
          Ok(v) => v
          Err(rl) => return Err(rl)
        }
        out[idx] = {
          ..prev,
          key_constraint: merged_k,
          value_constraint: merged_v,
        }
      }
      None => {
        key_to_idx.set(key, out.length())
        out.push(p)
      }
    }
  }
  Ok(out)
}

///|
/// Returns the `EvalLimits` configured for this budget.
pub fn EvalBudget::limits(self : EvalBudget) -> EvalLimits {
  self.limits
}

///|
/// Returns the number of evaluation steps consumed so far.
pub fn EvalBudget::steps_used(self : EvalBudget) -> Int32 {
  self.steps
}

///|
/// Returns the current nesting depth tracked by this budget.
pub fn EvalBudget::current_depth(self : EvalBudget) -> Int32 {
  self.depth
}

///|
/// Checks whether an input source byte length fits within `max_source_bytes`.
pub fn EvalBudget::check_source_bytes(
  self : EvalBudget,
  byte_len : Int32,
) -> Result[Unit, LimitError] {
  if byte_len > self.limits.max_source_bytes {
    Err(SourceBytesExceeded(byte_len, self.limits.max_source_bytes))
  } else {
    Ok(())
  }
}

///|
/// Consumes one evaluation step, failing if `max_eval_steps` would be exceeded.
pub fn EvalBudget::consume_step(self : EvalBudget) -> Result[Unit, LimitError] {
  if self.steps >= self.limits.max_eval_steps {
    let attempted = if self.steps < 0 {
      1
    } else if self.steps == 2147483647 {
      2147483647
    } else {
      self.steps + 1
    }
    Err(EvalStepsExceeded(attempted, self.limits.max_eval_steps))
  } else {
    self.steps += 1
    Ok(())
  }
}

///|
/// Enters one level of nesting, failing if `max_depth` would be exceeded.
///
/// On `Err`, the recorded depth is not incremented.
pub fn EvalBudget::enter_depth(self : EvalBudget) -> Result[Unit, LimitError] {
  if self.depth >= self.limits.max_depth {
    let attempted = if self.depth < 0 {
      1
    } else if self.depth == 2147483647 {
      2147483647
    } else {
      self.depth + 1
    }
    Err(MaxDepthExceeded(attempted, self.limits.max_depth))
  } else {
    self.depth += 1
    Ok(())
  }
}

///|
/// Leaves one level of nesting, saturating at `0`.
pub fn EvalBudget::leave_depth(self : EvalBudget) -> Unit {
  if self.depth > 0 {
    self.depth -= 1
  }
}

///|
/// Checks whether a disjunction branch count fits within `max_disjunction_branches`.
pub fn EvalBudget::check_branches(
  self : EvalBudget,
  count : Int32,
) -> Result[Unit, LimitError] {
  if count > self.limits.max_disjunction_branches {
    Err(
      DisjunctionBranchesExceeded(count, self.limits.max_disjunction_branches),
    )
  } else {
    Ok(())
  }
}

///|
/// Checks whether an output byte length fits within `max_output_bytes`.
pub fn EvalBudget::check_output_bytes(
  self : EvalBudget,
  byte_len : Int32,
) -> Result[Unit, LimitError] {
  if byte_len > self.limits.max_output_bytes {
    Err(OutputBytesExceeded(byte_len, self.limits.max_output_bytes))
  } else {
    Ok(())
  }
}

///|
priv enum AstWorkItem {
  WorkDecl(@syntax.Decl)
  WorkExpr(@syntax.Expr)
  WorkLabel(@syntax.Label)
  WorkClause(@syntax.Clause)
  WorkListElem(@syntax.ListElem)
}

///|
fn bump_ast_count(
  count : Ref[Int32],
  max_nodes : Int32,
) -> Result[Unit, LimitError] {
  let next = count.val + 1
  if next > max_nodes {
    Err(AstNodesExceeded(next, max_nodes))
  } else {
    count.val = next
    Ok(())
  }
}

///|
fn check_worklist_quota(
  count : Ref[Int32],
  work_len : Int32,
  add_count : Int64,
  max_nodes : Int32,
) -> Result[Unit, LimitError] {
  if max_nodes < 0 {
    return Err(AstNodesExceeded(1, max_nodes))
  }
  let total = count.val.to_int64() + work_len.to_int64() + add_count
  if total > max_nodes.to_int64() {
    let exceeded = if max_nodes == 2147483647 {
      max_nodes
    } else {
      max_nodes + 1
    }
    Err(AstNodesExceeded(exceeded, max_nodes))
  } else {
    Ok(())
  }
}

///|
fn run_ast_worklist(
  work : Array[AstWorkItem],
  count : Ref[Int32],
  max_nodes : Int32,
) -> Result[Int32, LimitError] {
  while !work.is_empty() {
    let item = work.pop().unwrap()
    match item {
      WorkDecl(decl) => {
        if bump_ast_count(count, max_nodes) is Err(e) {
          return Err(e)
        }
        match decl {
          Field(labels, value, attrs, _) => {
            let needed = attrs.length().to_int64() +
              1L +
              labels.length().to_int64() * 2L
            if check_worklist_quota(count, work.length(), needed, max_nodes)
              is Err(e) {
              return Err(e)
            }
            for attr in attrs {
              let _ = attr
              if bump_ast_count(count, max_nodes) is Err(e) {
                return Err(e)
              }
            }
            work.push(WorkExpr(value))
            for field_label in labels {
              if bump_ast_count(count, max_nodes) is Err(e) {
                return Err(e)
              }
              work.push(WorkLabel(field_label.label))
            }
          }
          Let(_, value, _) => {
            if check_worklist_quota(count, work.length(), 1L, max_nodes)
              is Err(e) {
              return Err(e)
            }
            work.push(WorkExpr(value))
          }
          Embed(expr, attrs, _) => {
            let needed = attrs.length().to_int64() + 1L
            if check_worklist_quota(count, work.length(), needed, max_nodes)
              is Err(e) {
              return Err(e)
            }
            for attr in attrs {
              let _ = attr
              if bump_ast_count(count, max_nodes) is Err(e) {
                return Err(e)
              }
            }
            work.push(WorkExpr(expr))
          }
          Ellipsis(_) | Attribute(_) => ()
          Comprehension(clauses, decls, _) => {
            let needed = decls.length().to_int64() + clauses.length().to_int64()
            if check_worklist_quota(count, work.length(), needed, max_nodes)
              is Err(e) {
              return Err(e)
            }
            for child in decls {
              work.push(WorkDecl(child))
            }
            for clause in clauses {
              work.push(WorkClause(clause))
            }
          }
        }
      }
      WorkLabel(label) => {
        if bump_ast_count(count, max_nodes) is Err(e) {
          return Err(e)
        }
        match label {
          Ident(_, _, _) | StringLit(_, _) => ()
          DynamicExpr(expr, _) | Pattern(_, expr, _) => {
            if check_worklist_quota(count, work.length(), 1L, max_nodes)
              is Err(e) {
              return Err(e)
            }
            work.push(WorkExpr(expr))
          }
          DynamicInterp(parts, _) => {
            if check_worklist_quota(
                count,
                work.length(),
                parts.length().to_int64(),
                max_nodes,
              )
              is Err(e) {
              return Err(e)
            }
            for part in parts {
              match part {
                Text(_) =>
                  if bump_ast_count(count, max_nodes) is Err(e) {
                    return Err(e)
                  }
                Expr(expr) => work.push(WorkExpr(expr))
              }
            }
          }
        }
      }
      WorkClause(clause) => {
        if bump_ast_count(count, max_nodes) is Err(e) {
          return Err(e)
        }
        if check_worklist_quota(count, work.length(), 1L, max_nodes) is Err(e) {
          return Err(e)
        }
        match clause {
          For(_, _, iter, _) => work.push(WorkExpr(iter))
          If(cond, _) => work.push(WorkExpr(cond))
          Let(_, value, _) => work.push(WorkExpr(value))
        }
      }
      WorkListElem(elem) =>
        match elem {
          Expr(expr) => {
            if check_worklist_quota(count, work.length(), 1L, max_nodes)
              is Err(e) {
              return Err(e)
            }
            work.push(WorkExpr(expr))
          }
          Comprehension(clauses, body, _) => {
            if bump_ast_count(count, max_nodes) is Err(e) {
              return Err(e)
            }
            let needed = 1L + clauses.length().to_int64()
            if check_worklist_quota(count, work.length(), needed, max_nodes)
              is Err(e) {
              return Err(e)
            }
            work.push(WorkExpr(body))
            for clause in clauses {
              work.push(WorkClause(clause))
            }
          }
        }
      WorkExpr(expr) => {
        if bump_ast_count(count, max_nodes) is Err(e) {
          return Err(e)
        }
        match expr {
          Null(_)
          | Bool(_, _)
          | Int(_, _)
          | Float(_, _)
          | String(_, _)
          | Bytes(_, _)
          | Bottom(_)
          | Ident(_, _, _) => ()
          StringInterp(parts, _) => {
            if check_worklist_quota(
                count,
                work.length(),
                parts.length().to_int64(),
                max_nodes,
              )
              is Err(e) {
              return Err(e)
            }
            for part in parts {
              match part {
                Text(_) =>
                  if bump_ast_count(count, max_nodes) is Err(e) {
                    return Err(e)
                  }
                Expr(inner) => work.push(WorkExpr(inner))
              }
            }
          }
          BytesInterp(parts, _) => {
            if check_worklist_quota(
                count,
                work.length(),
                parts.length().to_int64(),
                max_nodes,
              )
              is Err(e) {
              return Err(e)
            }
            for part in parts {
              match part {
                BytesChunk(_) =>
                  if bump_ast_count(count, max_nodes) is Err(e) {
                    return Err(e)
                  }
                Expr(inner) => work.push(WorkExpr(inner))
              }
            }
          }
          Unary(_, inner, _) | Paren(inner, _) | Alias(_, inner, _) => {
            if check_worklist_quota(count, work.length(), 1L, max_nodes)
              is Err(e) {
              return Err(e)
            }
            work.push(WorkExpr(inner))
          }
          Binary(_, left, right, _) => {
            if check_worklist_quota(count, work.length(), 2L, max_nodes)
              is Err(e) {
              return Err(e)
            }
            work.push(WorkExpr(right))
            work.push(WorkExpr(left))
          }
          Struct(decls, _) => {
            if check_worklist_quota(
                count,
                work.length(),
                decls.length().to_int64(),
                max_nodes,
              )
              is Err(e) {
              return Err(e)
            }
            for decl in decls {
              work.push(WorkDecl(decl))
            }
          }
          List(elems, ellipsis_type, _, _) => {
            let needed = elems.length().to_int64() +
              (if ellipsis_type is Some(_) { 1L } else { 0L })
            if check_worklist_quota(count, work.length(), needed, max_nodes)
              is Err(e) {
              return Err(e)
            }
            match ellipsis_type {
              Some(ty) => work.push(WorkExpr(ty))
              None => ()
            }
            for elem in elems {
              work.push(WorkListElem(elem))
            }
          }
          Selector(target, _, _) => {
            if check_worklist_quota(count, work.length(), 1L, max_nodes)
              is Err(e) {
              return Err(e)
            }
            work.push(WorkExpr(target))
          }
          Index(target, index, _) => {
            if check_worklist_quota(count, work.length(), 2L, max_nodes)
              is Err(e) {
              return Err(e)
            }
            work.push(WorkExpr(index))
            work.push(WorkExpr(target))
          }
          Slice(target, low, high, _) => {
            let needed = 1L +
              (if low is Some(_) { 1L } else { 0L }) +
              (if high is Some(_) { 1L } else { 0L })
            if check_worklist_quota(count, work.length(), needed, max_nodes)
              is Err(e) {
              return Err(e)
            }
            match high {
              Some(hi) => work.push(WorkExpr(hi))
              None => ()
            }
            match low {
              Some(lo) => work.push(WorkExpr(lo))
              None => ()
            }
            work.push(WorkExpr(target))
          }
          Call(callee, args, _) => {
            let needed = args.length().to_int64() + 1L
            if check_worklist_quota(count, work.length(), needed, max_nodes)
              is Err(e) {
              return Err(e)
            }
            for arg in args {
              work.push(WorkExpr(arg))
            }
            work.push(WorkExpr(callee))
          }
        }
      }
    }
  }
  Ok(count.val)
}

///|
/// Counts all AST nodes in a `@syntax.File`, short-circuiting as soon as
/// `max_nodes` is exceeded. Uses an explicit worklist so deeply nested ASTs
/// cannot overflow the call stack.
pub fn count_file_ast_nodes(
  file : @syntax.File,
  max_nodes : Int32,
) -> Result[Int32, LimitError] {
  let count : Ref[Int32] = { val: 0, }
  if bump_ast_count(count, max_nodes) is Err(e) {
    return Err(e)
  }
  if check_worklist_quota(
      count,
      0,
      file.pre_package_attrs.length().to_int64(),
      max_nodes,
    )
    is Err(e) {
    return Err(e)
  }
  for attr in file.pre_package_attrs {
    let _ = attr
    if bump_ast_count(count, max_nodes) is Err(e) {
      return Err(e)
    }
  }
  match file.package_clause {
    Some(_) => if bump_ast_count(count, max_nodes) is Err(e) { return Err(e) }
    None => ()
  }
  if check_worklist_quota(count, 0, file.imports.length().to_int64(), max_nodes)
    is Err(e) {
    return Err(e)
  }
  for imp in file.imports {
    if bump_ast_count(count, max_nodes) is Err(e) {
      return Err(e)
    }
    if check_worklist_quota(count, 0, imp.specs.length().to_int64(), max_nodes)
      is Err(e) {
      return Err(e)
    }
    for spec in imp.specs {
      let _ = spec
      if bump_ast_count(count, max_nodes) is Err(e) {
        return Err(e)
      }
    }
  }
  if check_worklist_quota(count, 0, file.decls.length().to_int64(), max_nodes)
    is Err(e) {
    return Err(e)
  }
  let work : Array[AstWorkItem] = []
  for decl in file.decls {
    work.push(WorkDecl(decl))
  }
  run_ast_worklist(work, count, max_nodes)
}

///|
/// Counts all AST nodes in a `@syntax.Expr`, short-circuiting as soon as
/// `max_nodes` is exceeded. Uses an explicit worklist so deeply nested ASTs
/// cannot overflow the call stack.
pub fn count_expr_ast_nodes(
  expr : @syntax.Expr,
  max_nodes : Int32,
) -> Result[Int32, LimitError] {
  let count : Ref[Int32] = { val: 0, }
  let work : Array[AstWorkItem] = [WorkExpr(expr)]
  run_ast_worklist(work, count, max_nodes)
}