///|
/// Local slot allocator for one compiled callable frame (rule clause, branch,
/// or query).
priv struct SlotAlloc {
  mut next_slot : Int32
  name_to_slot : Map[String, Int32]
  user_vars : Array[(String, Int32)]
}

///|
fn SlotAlloc::new() -> SlotAlloc {
  { next_slot: 0, name_to_slot: Map([]), user_vars: [], }
}

///|
fn SlotAlloc::fresh_temp(self : SlotAlloc) -> Int32 {
  let id = self.next_slot
  self.next_slot += 1
  id
}

///|
fn SlotAlloc::slot_for(self : SlotAlloc, name : String) -> Int32 {
  if name == "_" {
    return self.fresh_temp()
  }
  match self.name_to_slot.get(name) {
    Some(id) => id
    None => {
      let id = self.next_slot
      self.next_slot += 1
      self.name_to_slot.set(name, id)
      self.user_vars.push((name, id))
      id
    }
  }
}

///|
fn parse_builtin_name(
  raw : String,
  span : @syntax.SourceSpan,
) -> @builtins.BuiltinName raise CompileError {
  @builtins.BuiltinName(raw) catch {
    _ => raise UndefinedFunction(name=raw, span~)
  }
}

///|
fn binary_op_builtin_name(op : @ast.BinaryOp) -> String {
  match op {
    Equal => "equal"
    Neq => "neq"
    Lt => "lt"
    Gt => "gt"
    Lte => "lte"
    Gte => "gte"
    Or => "or"
    And => "and"
    Add => "plus"
    Sub => "minus"
    Mul => "mul"
    Quo => "div"
    Rem => "rem"
  }
}

///|
/// Resolves a `Ref` base (or bare `Var`) into its root (`Data`, `Input`, or
/// local/computed `Operand`) and any prepended static path segments from
/// imports or sibling package rules.
fn resolve_ref_base(
  base : @ast.Term,
  scope : ScopeCtx,
  alloc : SlotAlloc,
  grounded : Map[String, Unit],
  with_mods : ReadOnlyArray[@ast.WithModifier],
  out : Array[Stmt],
) -> (Operand, Array[String]) raise CompileError {
  match base.kind() {
    Var(id) => {
      let name = id.to_string()
      if name == "input" {
        return (Operand::Input, [])
      }
      if name == "data" {
        return (Operand::Data, [])
      }
      if !scope.is_local_var(name) {
        if scope.env is Some(e) {
          match e.imports.get(name) {
            Some(imp) => {
              let root : Operand = match imp.root {
                ImportData => Operand::Data
                ImportInput => Operand::Input
              }
              return (root, imp.path.copy())
            }
            None => {
              let sib = e.pkg_path.copy()
              sib.push(name)
              return (Operand::Data, sib)
            }
          }
        }
      }
      (Operand::Local(alloc.slot_for(name)), [])
    }
    _ => {
      let op = lower_term(base, scope, alloc, grounded, with_mods, out)
      (op, [])
    }
  }
}

///|
/// Lowers an `@ast.Term` into an `Operand`, appending Plan VM statements to `out`.
fn lower_term(
  term : @ast.Term,
  scope : ScopeCtx,
  alloc : SlotAlloc,
  grounded : Map[String, Unit],
  with_mods : ReadOnlyArray[@ast.WithModifier],
  out : Array[Stmt],
) -> Operand raise CompileError {
  match term.kind() {
    Null => Operand::Const(@value.Value::Null)
    Bool(b) => Operand::Const(@value.Value::Bool(b))
    Number(num) => {
      let dec = @value.Decimal(num.raw()) catch {
        _ => raise InvalidNumber(text=num.raw(), span=term.span())
      }
      Operand::Const(@value.Value::Number(dec))
    }
    String(s) => Operand::Const(@value.Value::String(s))
    Var(id) => {
      let name = id.to_string()
      if name == "input" {
        return Operand::Input
      }
      if name == "data" {
        return Operand::Data
      }
      if !scope.is_local_var(name) {
        if scope.env is Some(e) {
          match e.imports.get(name) {
            Some(imp) => {
              let dst = alloc.fresh_temp()
              match imp.root {
                ImportData =>
                  if imp.path.is_empty() {
                    return Operand::Data
                  } else {
                    out.push(
                      Stmt::CallRule(
                        path=ReadOnlyArray::from_array(imp.path),
                        dst~,
                      ),
                    )
                    return Operand::Local(dst)
                  }
                ImportInput =>
                  if imp.path.is_empty() {
                    return Operand::Input
                  } else {
                    let keys : Array[RefKey] = []
                    for s in imp.path {
                      keys.push(RefKey::Static(s))
                    }
                    out.push(
                      Stmt::EvalRef(
                        dst~,
                        base=Operand::Input,
                        segments=ReadOnlyArray::from_array(keys),
                      ),
                    )
                    return Operand::Local(dst)
                  }
              }
            }
            None => {
              let sib = e.pkg_path.copy()
              sib.push(name)
              let dst = alloc.fresh_temp()
              out.push(
                Stmt::CallRule(path=ReadOnlyArray::from_array(sib), dst~),
              )
              return Operand::Local(dst)
            }
          }
        }
      }
      Operand::Local(alloc.slot_for(name))
    }
    Ref(r) => {
      let (base_op, prefix) = resolve_ref_base(
        r.base(),
        scope,
        alloc,
        grounded,
        with_mods,
        out,
      )
      // For `data` references, split leading static segments from remaining
      // dynamic segments so static virtual documents use `CallRule` cleanly.
      if base_op is Operand::Data {
        let static_path = prefix.copy()
        let tail_keys : Array[RefKey] = []
        let mut hit_dynamic = false
        for seg in r.segments() {
          if !hit_dynamic {
            match seg {
              Dot(k) => static_path.push(k.to_string())
              Bracket(idx) =>
                match idx.kind() {
                  String(s) => static_path.push(s)
                  _ => {
                    hit_dynamic = true
                    tail_keys.push(
                      lower_ref_bracket(
                        idx, scope, alloc, grounded, with_mods, out,
                      ),
                    )
                  }
                }
            }
          } else {
            match seg {
              Dot(k) => tail_keys.push(RefKey::Static(k.to_string()))
              Bracket(idx) =>
                tail_keys.push(
                  lower_ref_bracket(idx, scope, alloc, grounded, with_mods, out),
                )
            }
          }
        }
        if tail_keys.is_empty() {
          if static_path.is_empty() {
            return Operand::Data
          }
          let dst = alloc.fresh_temp()
          out.push(
            Stmt::CallRule(path=ReadOnlyArray::from_array(static_path), dst~),
          )
          return Operand::Local(dst)
        }
        // Keep `Operand::Data` as the `EvalRef` base with leading static
        // segments so the VM resolves `data.nested[2]` and dynamic tails uniformly.
        let all_keys : Array[RefKey] = []
        for s in static_path {
          all_keys.push(RefKey::Static(s))
        }
        for tk in tail_keys {
          all_keys.push(tk)
        }
        let dst = alloc.fresh_temp()
        out.push(
          Stmt::EvalRef(
            dst~,
            base=Operand::Data,
            segments=ReadOnlyArray::from_array(all_keys),
          ),
        )
        return Operand::Local(dst)
      }
      // Non-`data` base (`input`, local var, or computed term).
      let keys : Array[RefKey] = []
      for s in prefix {
        keys.push(RefKey::Static(s))
      }
      for seg in r.segments() {
        match seg {
          Dot(k) => keys.push(RefKey::Static(k.to_string()))
          Bracket(idx) =>
            keys.push(
              lower_ref_bracket(idx, scope, alloc, grounded, with_mods, out),
            )
        }
      }
      let dst = alloc.fresh_temp()
      out.push(
        Stmt::EvalRef(
          dst~,
          base=base_op,
          segments=ReadOnlyArray::from_array(keys),
        ),
      )
      Operand::Local(dst)
    }
    UnaryNeg(inner) => {
      let inner_op = lower_term(inner, scope, alloc, grounded, with_mods, out)
      let dst = alloc.fresh_temp()
      out.push(
        Stmt::CallBuiltin(
          name=parse_builtin_name("minus", term.span()),
          args=ReadOnlyArray::from_array([
            Operand::Const(@value.Value::int(0)),
            inner_op,
          ]),
          dst=Some(dst),
        ),
      )
      Operand::Local(dst)
    }
    Binary(op, lhs, rhs) => {
      let l_op = lower_term(lhs, scope, alloc, grounded, with_mods, out)
      let r_op = lower_term(rhs, scope, alloc, grounded, with_mods, out)
      let dst = alloc.fresh_temp()
      out.push(
        Stmt::CallBuiltin(
          name=parse_builtin_name(binary_op_builtin_name(op), term.span()),
          args=ReadOnlyArray::from_array([l_op, r_op]),
          dst=Some(dst),
        ),
      )
      Operand::Local(dst)
    }
    In(key~, value~, domain~) => {
      let v_op = lower_term(value, scope, alloc, grounded, with_mods, out)
      let d_op = lower_term(domain, scope, alloc, grounded, with_mods, out)
      let dst = alloc.fresh_temp()
      match key {
        Some(k) => {
          let k_op = lower_term(k, scope, alloc, grounded, with_mods, out)
          out.push(
            Stmt::CallBuiltin(
              name=parse_builtin_name("internal.member_3", term.span()),
              args=ReadOnlyArray::from_array([k_op, v_op, d_op]),
              dst=Some(dst),
            ),
          )
        }
        None =>
          out.push(
            Stmt::CallBuiltin(
              name=parse_builtin_name("internal.member_2", term.span()),
              args=ReadOnlyArray::from_array([v_op, d_op]),
              dst=Some(dst),
            ),
          )
      }
      Operand::Local(dst)
    }
    Call(callee~, args~) => {
      let resolved = scope.resolve_callee(callee, with_mods)
      let arg_ops : Array[Operand] = []
      for arg in args {
        arg_ops.push(lower_term(arg, scope, alloc, grounded, with_mods, out))
      }
      let dst = alloc.fresh_temp()
      match resolved {
        CalleeUserFunc(path~, arity~) => {
          if arity >= 0 && args.length() != arity {
            raise WrongArity(
              name=format_data_path(path),
              expected=arity,
              actual=args.length(),
              span=term.span(),
            )
          }
          out.push(
            Stmt::CallFunc(
              path=ReadOnlyArray::from_array(path),
              args=ReadOnlyArray::from_array(arg_ops),
              dst~,
            ),
          )
        }
        CalleeBuiltin(name~, arity~) => {
          if !arity.accepts(args.length()) {
            let exp = match arity {
              Fixed(n) => n
              Variadic => args.length()
            }
            raise WrongArity(
              name=name.to_string(),
              expected=exp,
              actual=args.length(),
              span=term.span(),
            )
          }
          out.push(
            Stmt::CallBuiltin(
              name~,
              args=ReadOnlyArray::from_array(arg_ops),
              dst=Some(dst),
            ),
          )
        }
        CalleeWalk => {
          if args.length() != 1 {
            raise WrongArity(
              name="walk",
              expected=1,
              actual=args.length(),
              span=term.span(),
            )
          }
          out.push(
            Stmt::CallBuiltin(
              name=parse_builtin_name("walk", term.span()),
              args=ReadOnlyArray::from_array(arg_ops),
              dst=Some(dst),
            ),
          )
        }
      }
      Operand::Local(dst)
    }
    Array(items) => {
      let dst = alloc.fresh_temp()
      out.push(Stmt::MakeArray(dst~))
      for item in items {
        let elem = lower_term(item, scope, alloc, grounded, with_mods, out)
        out.push(Stmt::ArrayPush(arr=dst, elem~))
      }
      Operand::Local(dst)
    }
    Set(items) => {
      let dst = alloc.fresh_temp()
      out.push(Stmt::MakeSet(dst~))
      for item in items {
        let elem = lower_term(item, scope, alloc, grounded, with_mods, out)
        out.push(Stmt::SetAdd(set=dst, elem~))
      }
      Operand::Local(dst)
    }
    Object(pairs) => {
      let dst = alloc.fresh_temp()
      out.push(Stmt::MakeObject(dst~))
      for pair in pairs {
        let k = lower_term(pair.0, scope, alloc, grounded, with_mods, out)
        let v = lower_term(pair.1, scope, alloc, grounded, with_mods, out)
        out.push(Stmt::ObjectInsert(obj=dst, key=k, val=v))
      }
      Operand::Local(dst)
    }
    ArrayComprehension(term=elem, body~) => {
      let (comp_stmts, elem_op) = lower_comprehension_single(
        elem,
        body.exprs(),
        scope,
        alloc,
        grounded,
      )
      let dst = alloc.fresh_temp()
      out.push(
        Stmt::BuildArrayComp(
          dst~,
          elem=elem_op,
          body=ReadOnlyArray::from_array(comp_stmts),
        ),
      )
      Operand::Local(dst)
    }
    SetComprehension(term=elem, body~) => {
      let (comp_stmts, elem_op) = lower_comprehension_single(
        elem,
        body.exprs(),
        scope,
        alloc,
        grounded,
      )
      let dst = alloc.fresh_temp()
      out.push(
        Stmt::BuildSetComp(
          dst~,
          elem=elem_op,
          body=ReadOnlyArray::from_array(comp_stmts),
        ),
      )
      Operand::Local(dst)
    }
    ObjectComprehension(key~, value~, body~) => {
      let inner_decls = collect_declared_locals(body.exprs(), true)
      let inner_scope = scope.child_with_locals(inner_decls)
      let (ordered, body_grounded) = schedule_exprs(
        body.exprs(),
        inner_scope,
        grounded,
      )
      verify_term_safe(key, inner_scope, body_grounded)
      verify_term_safe(value, inner_scope, body_grounded)
      let comp_stmts : Array[Stmt] = []
      let run_grounded = copy_grounded(grounded)
      for e in ordered {
        lower_expr(e, inner_scope, alloc, run_grounded, comp_stmts)
      }
      let k_op = lower_term(
        key,
        inner_scope,
        alloc,
        run_grounded,
        ReadOnlyArray::from_array([]),
        comp_stmts,
      )
      let v_op = lower_term(
        value,
        inner_scope,
        alloc,
        run_grounded,
        ReadOnlyArray::from_array([]),
        comp_stmts,
      )
      let dst = alloc.fresh_temp()
      out.push(
        Stmt::BuildObjectComp(
          dst~,
          key=k_op,
          val=v_op,
          body=ReadOnlyArray::from_array(comp_stmts),
        ),
      )
      Operand::Local(dst)
    }
    TemplateString(parts~, ..) => {
      let compiled_parts : Array[CompiledTemplatePart] = []
      for part in parts {
        match part {
          Literal(s) => compiled_parts.push(CompiledTemplatePart::Lit(s))
          Expr(e) => {
            let p_stmts : Array[Stmt] = []
            let slot = alloc.fresh_temp()
            let sub_grounded = copy_grounded(grounded)
            let p_op = lower_template_expr(
              e, scope, alloc, sub_grounded, p_stmts,
            )
            p_stmts.push(Stmt::Assign(dst=slot, src=p_op))
            compiled_parts.push(
              CompiledTemplatePart::Interp(
                stmts=ReadOnlyArray::from_array(p_stmts),
                slot~,
              ),
            )
          }
        }
      }
      let dst = alloc.fresh_temp()
      out.push(
        Stmt::FormatTemplate(
          dst~,
          parts=ReadOnlyArray::from_array(compiled_parts),
        ),
      )
      Operand::Local(dst)
    }
  }
}

///|
fn lower_ref_bracket(
  idx : @ast.Term,
  scope : ScopeCtx,
  alloc : SlotAlloc,
  grounded : Map[String, Unit],
  with_mods : ReadOnlyArray[@ast.WithModifier],
  out : Array[Stmt],
) -> RefKey raise CompileError {
  match idx.kind() {
    String(s) => RefKey::Static(s)
    Var(id) => {
      let name = id.to_string()
      if name == "_" {
        return RefKey::BindKey(alloc.fresh_temp())
      }
      if scope.is_local_var(name) && !grounded.contains(name) {
        let slot = alloc.slot_for(name)
        grounded.set(name, ())
        return RefKey::BindKey(slot)
      }
      RefKey::Dynamic(lower_term(idx, scope, alloc, grounded, with_mods, out))
    }
    Array(_) | Object(_) => {
      let pvars : Map[String, @syntax.SourceSpan] = Map([])
      collect_pattern_vars(idx, scope, pvars)
      let mut has_unbound = false
      for name, _ in pvars {
        if !grounded.contains(name) {
          has_unbound = true
          break
        }
      }
      if has_unbound {
        let pat = lower_pattern(idx, scope, alloc, grounded, with_mods, out)
        mark_pattern_grounded(idx, scope, grounded)
        RefKey::BindPattern(pat)
      } else {
        RefKey::Dynamic(lower_term(idx, scope, alloc, grounded, with_mods, out))
      }
    }
    _ =>
      RefKey::Dynamic(lower_term(idx, scope, alloc, grounded, with_mods, out))
  }
}

///|
fn lower_comprehension_single(
  elem : @ast.Term,
  exprs : ReadOnlyArray[@ast.Expr],
  scope : ScopeCtx,
  alloc : SlotAlloc,
  grounded : Map[String, Unit],
) -> (Array[Stmt], Operand) raise CompileError {
  let inner_decls = collect_declared_locals(exprs, true)
  let inner_scope = scope.child_with_locals(inner_decls)
  let (ordered, body_grounded) = schedule_exprs(exprs, inner_scope, grounded)
  verify_term_safe(elem, inner_scope, body_grounded)
  let comp_stmts : Array[Stmt] = []
  let run_grounded = copy_grounded(grounded)
  for e in ordered {
    lower_expr(e, inner_scope, alloc, run_grounded, comp_stmts)
  }
  let elem_op = lower_term(
    elem,
    inner_scope,
    alloc,
    run_grounded,
    ReadOnlyArray::from_array([]),
    comp_stmts,
  )
  (comp_stmts, elem_op)
}

///|
/// Lowers a template-string interpolation expression (which may carry `with`
/// modifiers) into an `Operand` without requiring truthiness (so `false`
/// renders as `"false"` rather than `""`).
fn lower_template_expr(
  expr : @ast.Expr,
  scope : ScopeCtx,
  alloc : SlotAlloc,
  grounded : Map[String, Unit],
  out : Array[Stmt],
) -> Operand raise CompileError {
  let wms = expr.with_modifiers()
  if !wms.is_empty() {
    let overlays = lower_with_modifiers(wms, scope, alloc, grounded, out)
    let inner_stmts : Array[Stmt] = []
    let inner_op = lower_template_expr(
      @ast.Expr::Expr(kind=expr.kind(), with_modifiers=[], span=expr.span()),
      scope,
      alloc,
      grounded,
      inner_stmts,
    )
    let dst = alloc.fresh_temp()
    inner_stmts.push(Stmt::Assign(dst~, src=inner_op))
    out.push(Stmt::With(overlays~, body=ReadOnlyArray::from_array(inner_stmts)))
    return Operand::Local(dst)
  }
  match expr.kind() {
    Term(t) => lower_term(t, scope, alloc, grounded, wms, out)
    _ => {
      // Fallback: execute expression as statement, yield `true` if it succeeds.
      lower_expr(expr, scope, alloc, grounded, out)
      Operand::Const(@value.Value::Bool(true))
    }
  }
}

///|
/// Lowers an AST term into a structural `Pattern` for `Unify`, `SomeIn`,
/// `WalkScan`, or function parameter matching.
fn lower_pattern(
  term : @ast.Term,
  scope : ScopeCtx,
  alloc : SlotAlloc,
  grounded : Map[String, Unit],
  with_mods : ReadOnlyArray[@ast.WithModifier],
  out : Array[Stmt],
) -> Pattern raise CompileError {
  match term.kind() {
    Null => Pattern::PConst(@value.Value::Null)
    Bool(b) => Pattern::PConst(@value.Value::Bool(b))
    Number(num) => {
      let dec = @value.Decimal(num.raw()) catch {
        _ => raise InvalidNumber(text=num.raw(), span=term.span())
      }
      Pattern::PConst(@value.Value::Number(dec))
    }
    String(s) => Pattern::PConst(@value.Value::String(s))
    Var(id) => {
      let name = id.to_string()
      if name == "_" {
        return Pattern::PWildcard
      }
      if scope.is_local_var(name) {
        let slot = alloc.slot_for(name)
        return Pattern::PLocal(slot)
      }
      // Global/import/sibling ref inside pattern: evaluate to temp slot.
      let op = lower_term(term, scope, alloc, grounded, with_mods, out)
      match op {
        Const(v) => Pattern::PConst(v)
        Local(s) => Pattern::PLocal(s)
        _ => {
          let tmp = alloc.fresh_temp()
          out.push(Stmt::Assign(dst=tmp, src=op))
          Pattern::PLocal(tmp)
        }
      }
    }
    Array(items) => {
      let pats : Array[Pattern] = []
      for item in items {
        pats.push(lower_pattern(item, scope, alloc, grounded, with_mods, out))
      }
      Pattern::PArray(ReadOnlyArray::from_array(pats))
    }
    Set(items) => {
      let pats : Array[Pattern] = []
      for item in items {
        pats.push(lower_pattern(item, scope, alloc, grounded, with_mods, out))
      }
      Pattern::PSet(ReadOnlyArray::from_array(pats))
    }
    Object(pairs) => {
      let pats : Array[(Pattern, Pattern)] = []
      for pair in pairs {
        let kp = lower_pattern(pair.0, scope, alloc, grounded, with_mods, out)
        let vp = lower_pattern(pair.1, scope, alloc, grounded, with_mods, out)
        pats.push((kp, vp))
      }
      Pattern::PObject(ReadOnlyArray::from_array(pats))
    }
    _ => {
      let op = lower_term(term, scope, alloc, grounded, with_mods, out)
      match op {
        Const(v) => Pattern::PConst(v)
        Local(s) => Pattern::PLocal(s)
        _ => {
          let tmp = alloc.fresh_temp()
          out.push(Stmt::Assign(dst=tmp, src=op))
          Pattern::PLocal(tmp)
        }
      }
    }
  }
}

///|
/// Marks all pattern variable names as grounded in `grounded`.
fn mark_pattern_grounded(
  term : @ast.Term,
  scope : ScopeCtx,
  grounded : Map[String, Unit],
) -> Unit {
  let pvars : Map[String, @syntax.SourceSpan] = Map([])
  collect_pattern_vars(term, scope, pvars)
  for k, _ in pvars {
    grounded.set(k, ())
  }
}

///|
fn copy_grounded(m : Map[String, Unit]) -> Map[String, Unit] {
  let out : Map[String, Unit] = Map([])
  for k, _ in m {
    out.set(k, ())
  }
  out
}

///|
/// Resolves `with  as ` modifiers into compiled `WithOverlay`s.
fn lower_with_modifiers(
  wms : ReadOnlyArray[@ast.WithModifier],
  scope : ScopeCtx,
  alloc : SlotAlloc,
  grounded : Map[String, Unit],
  out : Array[Stmt],
) -> ReadOnlyArray[WithOverlay] raise CompileError {
  let overlays : Array[WithOverlay] = []
  let empty_wm : ReadOnlyArray[@ast.WithModifier] = ReadOnlyArray::from_array([])
  for wm in wms {
    let target_ref = wm.target()
    let target_term = @ast.Term::Term(
      kind=Ref(target_ref),
      span=target_ref.span(),
    )
    guard extract_dotted_name(target_term) is Some(parts) else {
      raise InvalidWithTarget(target="", span=target_ref.span())
    }
    let dotted = parts.join(".")
    let target : WithTarget = if parts[0] == "input" {
      let rest : Array[String] = []
      for i in 1.. {
          let full = imp.path.copy()
          for i in 1..
              WithTarget::WithInput(ReadOnlyArray::from_array(full))
            ImportData => WithTarget::WithData(ReadOnlyArray::from_array(full))
          }
        }
        None => {
          let sib = e.pkg_path.copy()
          for p in parts {
            sib.push(p)
          }
          WithTarget::WithData(ReadOnlyArray::from_array(sib))
        }
      }
    } else {
      raise InvalidWithTarget(target=dotted, span=target_ref.span())
    }

    // Determine whether replacement is a callable (user function or built-in)
    // or a runtime value expression.
    let val_term = wm.value()
    let mut with_val : WithValue? = None
    if extract_dotted_name(val_term) is Some(v_parts) {
      let v_dotted = v_parts.join(".")
      if v_parts[0] == "data" && v_parts.length() >= 2 {
        let dp : Array[String] = []
        for i in 1.. wv
      None => {
        let op = lower_term(val_term, scope, alloc, grounded, empty_wm, out)
        WithValue::WithOperand(op)
      }
    }
    overlays.push({ target, value: resolved_val, })
  }
  ReadOnlyArray::from_array(overlays)
}

///|
/// Lowers one scheduled `@ast.Expr` into Plan VM statements appended to `out`.
fn lower_expr(
  expr : @ast.Expr,
  scope : ScopeCtx,
  alloc : SlotAlloc,
  grounded : Map[String, Unit],
  out : Array[Stmt],
) -> Unit raise CompileError {
  let wms = expr.with_modifiers()
  if !wms.is_empty() {
    let overlays = lower_with_modifiers(wms, scope, alloc, grounded, out)
    let inner_stmts : Array[Stmt] = []
    lower_expr_inner(
      expr.kind(),
      expr.span(),
      wms,
      scope,
      alloc,
      grounded,
      inner_stmts,
    )
    out.push(Stmt::With(overlays~, body=ReadOnlyArray::from_array(inner_stmts)))
    return
  }
  lower_expr_inner(expr.kind(), expr.span(), wms, scope, alloc, grounded, out)
}

///|
fn lower_expr_inner(
  kind : @ast.ExprKind,
  span : @syntax.SourceSpan,
  wms : ReadOnlyArray[@ast.WithModifier],
  scope : ScopeCtx,
  alloc : SlotAlloc,
  grounded : Map[String, Unit],
  out : Array[Stmt],
) -> Unit raise CompileError {
  match kind {
    SomeDecl(_) => ()
    Assign(lhs, rhs) => {
      // `[path, val] := walk(x)` iterates `walk_pairs(x)` via `WalkScan`.
      if rhs.kind() is Call(callee~, args~) &&
        args.length() == 1 &&
        scope.resolve_callee(callee, wms) is CalleeWalk {
        let target_op = lower_term(args[0], scope, alloc, grounded, wms, out)
        let out_pat = lower_pattern(lhs, scope, alloc, grounded, wms, out)
        mark_pattern_grounded(lhs, scope, grounded)
        out.push(Stmt::WalkScan(target=target_op, out=out_pat))
        return
      }
      let rhs_op = lower_term(rhs, scope, alloc, grounded, wms, out)
      match lhs.kind() {
        Var(id) => {
          let name = id.to_string()
          if name != "_" {
            let slot = alloc.slot_for(name)
            grounded.set(name, ())
            out.push(Stmt::Assign(dst=slot, src=rhs_op))
          }
        }
        _ => {
          let lhs_pat = lower_pattern(lhs, scope, alloc, grounded, wms, out)
          let rhs_pat = match rhs_op {
            Const(v) => Pattern::PConst(v)
            Local(s) => Pattern::PLocal(s)
            _ => {
              let tmp = alloc.fresh_temp()
              out.push(Stmt::Assign(dst=tmp, src=rhs_op))
              Pattern::PLocal(tmp)
            }
          }
          mark_pattern_grounded(lhs, scope, grounded)
          out.push(Stmt::Unify(lhs=lhs_pat, rhs=rhs_pat))
        }
      }
    }
    Unify(lhs, rhs) => {
      // `[path, val] = walk(x)` or `walk(x) = [path, val]` iterates via `WalkScan`.
      if rhs.kind() is Call(callee~, args~) &&
        args.length() == 1 &&
        scope.resolve_callee(callee, wms) is CalleeWalk {
        let target_op = lower_term(args[0], scope, alloc, grounded, wms, out)
        let out_pat = lower_pattern(lhs, scope, alloc, grounded, wms, out)
        mark_pattern_grounded(lhs, scope, grounded)
        out.push(Stmt::WalkScan(target=target_op, out=out_pat))
        return
      }
      if lhs.kind() is Call(callee~, args~) &&
        args.length() == 1 &&
        scope.resolve_callee(callee, wms) is CalleeWalk {
        let target_op = lower_term(args[0], scope, alloc, grounded, wms, out)
        let out_pat = lower_pattern(rhs, scope, alloc, grounded, wms, out)
        mark_pattern_grounded(rhs, scope, grounded)
        out.push(Stmt::WalkScan(target=target_op, out=out_pat))
        return
      }
      let l_pat = lower_pattern(lhs, scope, alloc, grounded, wms, out)
      let r_pat = lower_pattern(rhs, scope, alloc, grounded, wms, out)
      mark_pattern_grounded(lhs, scope, grounded)
      mark_pattern_grounded(rhs, scope, grounded)
      out.push(Stmt::Unify(lhs=l_pat, rhs=r_pat))
    }
    SomeIn(key~, value~, domain~) => {
      let dom_op = lower_term(domain, scope, alloc, grounded, wms, out)
      let key_slot : Int32? = match key {
        Some(k) =>
          match k.kind() {
            Var(id) if id.to_string() != "_" &&
              scope.is_local_var(id.to_string()) =>
              if !grounded.contains(id.to_string()) {
                let s = alloc.slot_for(id.to_string())
                grounded.set(id.to_string(), ())
                Some(s)
              } else {
                Some(alloc.fresh_temp())
              }
            _ => Some(alloc.fresh_temp())
          }
        None => None
      }
      let val_direct_slot : (Int32, Bool) = match value.kind() {
        Var(id) if id.to_string() != "_" && scope.is_local_var(id.to_string()) =>
          if !grounded.contains(id.to_string()) {
            let s = alloc.slot_for(id.to_string())
            grounded.set(id.to_string(), ())
            (s, true)
          } else {
            (alloc.fresh_temp(), false)
          }
        _ => (alloc.fresh_temp(), false)
      }
      out.push(Stmt::Scan(domain=dom_op, key_slot~, val_slot=val_direct_slot.0))
      if key is Some(k) && key_slot is Some(ks) {
        let need_unify = match k.kind() {
          Var(id) if id.to_string() != "_" &&
            scope.is_local_var(id.to_string()) &&
            alloc.slot_for(id.to_string()) == ks => false
          Var(id) if id.to_string() == "_" => false
          _ => true
        }
        if need_unify {
          let kp = lower_pattern(k, scope, alloc, grounded, wms, out)
          mark_pattern_grounded(k, scope, grounded)
          out.push(Stmt::Unify(lhs=kp, rhs=Pattern::PLocal(ks)))
        }
      }
      if !val_direct_slot.1 {
        let need_unify = match value.kind() {
          Var(id) if id.to_string() == "_" => false
          _ => true
        }
        if need_unify {
          let vp = lower_pattern(value, scope, alloc, grounded, wms, out)
          mark_pattern_grounded(value, scope, grounded)
          out.push(Stmt::Unify(lhs=vp, rhs=Pattern::PLocal(val_direct_slot.0)))
        }
      }
    }
    Every(key~, value~, domain~, body~) => {
      let dom_op = lower_term(domain, scope, alloc, grounded, wms, out)
      let extra_locals : Map[String, Unit] = Map([])
      let inner_grounded = copy_grounded(grounded)
      let k_slot : Int32? = match key {
        Some(k) => {
          let kn = k.to_string()
          if kn != "_" {
            extra_locals.set(kn, ())
            inner_grounded.set(kn, ())
            Some(alloc.slot_for(kn))
          } else {
            Some(alloc.fresh_temp())
          }
        }
        None => None
      }
      let vn = value.to_string()
      let v_slot = if vn != "_" {
        extra_locals.set(vn, ())
        inner_grounded.set(vn, ())
        alloc.slot_for(vn)
      } else {
        alloc.fresh_temp()
      }
      let body_decls = collect_declared_locals(body.exprs(), true)
      for n, _ in body_decls {
        extra_locals.set(n, ())
      }
      let inner_scope = scope.child_with_locals(extra_locals)
      let (ordered, _) = schedule_exprs(
        body.exprs(),
        inner_scope,
        inner_grounded,
      )
      let body_stmts : Array[Stmt] = []
      for e in ordered {
        lower_expr(e, inner_scope, alloc, inner_grounded, body_stmts)
      }
      // `every k, v in dom { body }` == `Block([AssertCollection(dom), not (some k, v in dom; not body), Break(0)])`
      let not_inner : Array[Stmt] = [
        Stmt::Scan(domain=dom_op, key_slot=k_slot, val_slot=v_slot),
        Stmt::Not(ReadOnlyArray::from_array(body_stmts)),
      ]
      out.push(
        Stmt::Block(
          ReadOnlyArray::from_array([
            Stmt::AssertCollection(dom_op),
            Stmt::Not(ReadOnlyArray::from_array(not_inner)),
            Stmt::Break(0),
          ]),
        ),
      )
    }
    Not(inner) => {
      let inner_stmts : Array[Stmt] = []
      let sub_grounded = copy_grounded(grounded)
      lower_expr_inner(
        inner, span, wms, scope, alloc, sub_grounded, inner_stmts,
      )
      out.push(Stmt::Not(ReadOnlyArray::from_array(inner_stmts)))
    }
    Term(t) => {
      // Handle relation-style calls (`walk(x, out)` and `f(a1..aN, out)`).
      if t.kind() is Call(callee~, args~) {
        let resolved = scope.resolve_callee(callee, wms)
        match resolved {
          CalleeWalk => {
            if args.length() != 2 {
              raise WrongArity(
                name="walk",
                expected=2,
                actual=args.length(),
                span=t.span(),
              )
            }
            let target_op = lower_term(
              args[0],
              scope,
              alloc,
              grounded,
              wms,
              out,
            )
            let out_pat = lower_pattern(
              args[1],
              scope,
              alloc,
              grounded,
              wms,
              out,
            )
            mark_pattern_grounded(args[1], scope, grounded)
            out.push(Stmt::WalkScan(target=target_op, out=out_pat))
            return
          }
          CalleeBuiltin(name~, arity=Fixed(n)) if args.length() == n + 1 => {
            let arg_ops : Array[Operand] = []
            for i in 0..= 0 &&
            args.length() == arity + 1 => {
            let arg_ops : Array[Operand] = []
            for i in 0.. ()
        }
      }
      // Fast-path `a == b` at statement level into `Stmt::Equal`.
      if t.kind() is Binary(Equal, lhs, rhs) {
        let l_op = lower_term(lhs, scope, alloc, grounded, wms, out)
        let r_op = lower_term(rhs, scope, alloc, grounded, wms, out)
        out.push(Stmt::Equal(lhs=l_op, rhs=r_op))
        return
      }
      let op = lower_term(t, scope, alloc, grounded, wms, out)
      out.push(Stmt::AssertTruthy(op))
    }
  }
}

///|
fn build_clause_metadata(
  clause : RawClause,
  full_path : Array[String],
  doc_annotations : Array[@ast.Annotation],
  pkg_ann_map : Map[String, Array[@ast.Annotation]],
  subpkg_ann_map : Map[String, Array[@ast.Annotation]],
) -> (@value.Value?, @value.Value?) {
  let mut rule_meta : @value.Value? = None
  let chain : Array[@value.Value] = []
  let path_vals : Array[@value.Value] = []
  for s in full_path {
    path_vals.push(@value.Value::String(s))
  }
  let full_path_val = @value.Value::array(path_vals)

  let mut has_rule_or_doc = false
  for ann in clause.rule.annotations() {
    match ann.scope() {
      Rule => {
        let v = annotation_to_value(ann)
        rule_meta = Some(v)
        has_rule_or_doc = true
        chain.push(
          @value.Value::string_object([
            ("path", full_path_val),
            ("annotations", v),
          ]),
        )
      }
      Document => ()
      _ => ()
    }
  }
  for ann in doc_annotations {
    has_rule_or_doc = true
    chain.push(
      @value.Value::string_object([
        ("path", full_path_val),
        ("annotations", annotation_to_value(ann)),
      ]),
    )
  }
  let pkg_key = clause.module_env.pkg_path.join(".")
  let pkg_path_vals : Array[@value.Value] = []
  for s in clause.module_env.pkg_path {
    pkg_path_vals.push(@value.Value::String(s))
  }
  if pkg_ann_map.get(pkg_key) is Some(anns) {
    for ann in anns {
      chain.push(
        @value.Value::string_object([
          ("path", @value.Value::array(pkg_path_vals)),
          ("annotations", annotation_to_value(ann)),
        ]),
      )
    }
  }
  // Subpackages annotations from current package up through ancestor prefixes.
  for len = clause.module_env.pkg_path.length(); len >= 1; len = len - 1 {
    let prefix : Array[String] = []
    let p_vals : Array[@value.Value] = []
    for i in 0.. CompiledClause raise CompileError {
  let empty_wm : ReadOnlyArray[@ast.WithModifier] = ReadOnlyArray::from_array([])
  let alloc = SlotAlloc::new()
  let param_locals : Map[String, Unit] = Map([])
  let initial_grounded : Map[String, Unit] = Map([])

  for pt in clause.param_terms {
    let pv : Map[String, @syntax.SourceSpan] = Map([])
    collect_param_vars(pt, pv)
    for k, _ in pv {
      param_locals.set(k, ())
      initial_grounded.set(k, ())
    }
  }

  let body_exprs : ReadOnlyArray[@ast.Expr] = match clause.rule.body() {
    Some(b) => b.exprs()
    None => ReadOnlyArray::from_array([])
  }
  let body_decls = collect_declared_locals(body_exprs, true)
  for k, _ in param_locals {
    body_decls.set(k, ())
  }
  let scope : ScopeCtx = {
    raw_root: Some(root),
    compiled_policy: None,
    env: Some(clause.module_env),
    builtins,
    declared_locals: body_decls,
  }

  let param_pats : Array[Pattern] = []
  let dummy_stmts : Array[Stmt] = []
  for pt in clause.param_terms {
    param_pats.push(
      lower_pattern(pt, scope, alloc, initial_grounded, empty_wm, dummy_stmts),
    )
  }

  let (ordered, body_grounded) = schedule_exprs(
    body_exprs, scope, initial_grounded,
  )
  for dk in clause.dynamic_keys {
    verify_term_safe(dk, scope, body_grounded)
  }
  if clause.value_term is Some(vt) {
    verify_term_safe(vt, scope, body_grounded)
  }

  let stmts : Array[Stmt] = []
  let run_grounded = copy_grounded(initial_grounded)
  for e in ordered {
    lower_expr(e, scope, alloc, run_grounded, stmts)
  }

  let key_ops : Array[Operand] = []
  for dk in clause.dynamic_keys {
    key_ops.push(lower_term(dk, scope, alloc, run_grounded, empty_wm, stmts))
  }
  let val_op : Operand = match clause.value_term {
    Some(vt) => lower_term(vt, scope, alloc, run_grounded, empty_wm, stmts)
    None => Operand::Const(@value.Value::Bool(true))
  }

  // Compile any `else` branches (inheriting function parameters if present).
  let compiled_elses : Array[CompiledBranch] = []
  for eb in clause.rule.else_branches() {
    let eb_alloc = SlotAlloc::new()
    // Reserve the exact same leading slots for function parameters so the VM
    // can copy parameter bindings cleanly into an `else` branch frame.
    let eb_init : Map[String, Unit] = Map([])
    for pt in clause.param_terms {
      let pv : Map[String, @syntax.SourceSpan] = Map([])
      collect_param_vars(pt, pv)
      for k, _ in pv {
        let _ = eb_alloc.slot_for(k)
        eb_init.set(k, ())
      }
    }
    let eb_exprs : ReadOnlyArray[@ast.Expr] = match eb.body() {
      Some(b) => b.exprs()
      None => ReadOnlyArray::from_array([])
    }
    let eb_decls = collect_declared_locals(eb_exprs, true)
    for k, _ in param_locals {
      eb_decls.set(k, ())
    }
    let eb_scope : ScopeCtx = {
      raw_root: Some(root),
      compiled_policy: None,
      env: Some(clause.module_env),
      builtins,
      declared_locals: eb_decls,
    }
    let (eb_ordered, eb_grounded) = schedule_exprs(eb_exprs, eb_scope, eb_init)
    let eb_stmts : Array[Stmt] = []
    let eb_run = copy_grounded(eb_init)
    for e in eb_ordered {
      lower_expr(e, eb_scope, eb_alloc, eb_run, eb_stmts)
    }
    let eb_res : Operand = match eb.assigned() {
      Some(av) => {
        verify_term_safe(av.value(), eb_scope, eb_grounded)
        lower_term(av.value(), eb_scope, eb_alloc, eb_run, empty_wm, eb_stmts)
      }
      None => Operand::Const(@value.Value::Bool(true))
    }
    compiled_elses.push({
      num_slots: eb_alloc.next_slot,
      body: ReadOnlyArray::from_array(eb_stmts),
      result: eb_res,
    })
  }

  let (rule_metadata, chain_metadata) = build_clause_metadata(
    clause, full_path, doc_annotations, pkg_ann_map, subpkg_ann_map,
  )

  // For complete rules with `else` branches, lower the primary clause and its
  // `else` branches into a structured `Stmt::ElseChain` while retaining
  // `else_branches` metadata for inspection.
  let (final_num_slots, final_body, final_val_op) = if clause.param_terms.is_empty() &&
    !compiled_elses.is_empty() {
    let all_branches : Array[CompiledBranch] = [
      {
        num_slots: alloc.next_slot,
        body: ReadOnlyArray::from_array(stmts),
        result: val_op,
      },
    ]
    for eb in compiled_elses {
      all_branches.push(eb)
    }
    (
      1,
      ReadOnlyArray::from_array([
        Stmt::ElseChain(branches=ReadOnlyArray::from_array(all_branches), dst=0),
      ]),
      Operand::Local(0),
    )
  } else {
    (alloc.next_slot, ReadOnlyArray::from_array(stmts), val_op)
  }

  {
    num_slots: final_num_slots,
    param_patterns: ReadOnlyArray::from_array(param_pats),
    key_operands: ReadOnlyArray::from_array(key_ops),
    leaf_kind: clause.leaf_kind,
    value_operand: final_val_op,
    body: final_body,
    else_branches: ReadOnlyArray::from_array(compiled_elses),
    rule_metadata,
    chain_metadata,
  }
}

///|
fn freeze_node(
  node : RawNode,
  path : Array[String],
  root : RawNode,
  builtins : @builtins.BuiltinRegistry,
  pkg_ann_map : Map[String, Array[@ast.Annotation]],
  subpkg_ann_map : Map[String, Array[@ast.Annotation]],
  all_rule_paths : Array[ReadOnlyArray[String]],
) -> CompiledRuleNode raise CompileError {
  let child_keys : Array[String] = []
  for k, _ in node.children {
    child_keys.push(k)
  }
  child_keys.sort()
  let compiled_children : Array[(String, CompiledRuleNode)] = []
  for ck in child_keys {
    if node.children.get(ck) is Some(child) {
      let next_path = path.copy()
      next_path.push(ck)
      compiled_children.push(
        (
          ck,
          freeze_node(
            child, next_path, root, builtins, pkg_ann_map, subpkg_ann_map, all_rule_paths,
          ),
        ),
      )
    }
  }
  let compiled_clauses : Array[CompiledClause] = []
  for cl in node.clauses {
    compiled_clauses.push(
      compile_clause(
        cl,
        path,
        node.doc_annotations,
        root,
        builtins,
        pkg_ann_map,
        subpkg_ann_map,
      ),
    )
  }
  match node.kind {
    RawPackage =>
      CompiledRuleNode::Package(
        children=ReadOnlyArray::from_array(compiled_children),
      )
    RawComplete => {
      all_rule_paths.push(ReadOnlyArray::from_array(path.copy()))
      let default_branch : CompiledBranch? = match node.default_term {
        Some((def_env, def_term)) => {
          let def_alloc = SlotAlloc::new()
          let def_scope : ScopeCtx = {
            raw_root: Some(root),
            compiled_policy: None,
            env: Some(def_env),
            builtins,
            declared_locals: Map([]),
          }
          let def_stmts : Array[Stmt] = []
          let def_op = lower_term(
            def_term,
            def_scope,
            def_alloc,
            Map([]),
            ReadOnlyArray::from_array([]),
            def_stmts,
          )
          Some({
            num_slots: def_alloc.next_slot,
            body: ReadOnlyArray::from_array(def_stmts),
            result: def_op,
          })
        }
        None => None
      }
      CompiledRuleNode::Complete(
        clauses=ReadOnlyArray::from_array(compiled_clauses),
        default_value=node.default_val,
        default_branch~,
      )
    }
    RawPartialSet => {
      all_rule_paths.push(ReadOnlyArray::from_array(path.copy()))
      CompiledRuleNode::PartialSet(
        clauses=ReadOnlyArray::from_array(compiled_clauses),
      )
    }
    RawVirtualObject => {
      all_rule_paths.push(ReadOnlyArray::from_array(path.copy()))
      CompiledRuleNode::VirtualObject(
        static_children=ReadOnlyArray::from_array(compiled_children),
        dynamic_clauses=ReadOnlyArray::from_array(compiled_clauses),
      )
    }
    RawFunction(arity) => {
      all_rule_paths.push(ReadOnlyArray::from_array(path.copy()))
      CompiledRuleNode::Function(
        arity~,
        clauses=ReadOnlyArray::from_array(compiled_clauses),
        default_value=node.default_val,
      )
    }
  }
}

///|
/// Compiles a set of Rego v1 AST modules into an immutable `CompiledPolicy`
/// containing resolved virtual document rules, scheduled HIR, and structured
/// Plan VM instructions.
pub fn compile_modules(
  modules : ArrayView[@ast.Module],
  builtins : @builtins.BuiltinRegistry,
) -> CompiledPolicy raise CompileError {
  let (raw_root, _, pkg_ann_map, subpkg_ann_map) = build_raw_tree(modules)
  check_cycles(raw_root, builtins)
  let all_rule_paths : Array[ReadOnlyArray[String]] = []
  let root = freeze_node(
    raw_root,
    [],
    raw_root,
    builtins,
    pkg_ann_map,
    subpkg_ann_map,
    all_rule_paths,
  )
  { root, builtins, rule_paths: ReadOnlyArray::from_array(all_rule_paths), }
}

///|
/// Compiles a standalone Rego v1 query against a `CompiledPolicy` into an
/// immutable `CompiledQuery`.
pub fn compile_query(
  query : @ast.Query,
  policy : CompiledPolicy,
) -> CompiledQuery raise CompileError {
  let exprs = query.exprs()
  let decls = collect_declared_locals(exprs, true)
  let scope : ScopeCtx = {
    raw_root: None,
    compiled_policy: Some(policy),
    env: None,
    builtins: policy.builtins(),
    declared_locals: decls,
  }
  let init_grounded : Map[String, Unit] = Map([])
  let (ordered, _) = schedule_exprs(exprs, scope, init_grounded)
  let alloc = SlotAlloc::new()
  let stmts : Array[Stmt] = []
  let expr_slots : Array[Int32] = []
  let run_grounded : Map[String, Unit] = Map([])

  for e in ordered {
    // Capture each top-level Term expression's value into an output expr slot
    // so callers can inspect expression results as well as variable bindings.
    let wms = e.with_modifiers()
    match e.kind() {
      Term(t) if !is_relation_stmt(t, wms, scope) => {
        let slot = alloc.fresh_temp()
        if !wms.is_empty() {
          let overlays = lower_with_modifiers(
            wms, scope, alloc, run_grounded, stmts,
          )
          let inner : Array[Stmt] = []
          let op = lower_term(t, scope, alloc, run_grounded, wms, inner)
          inner.push(Stmt::Assign(dst=slot, src=op))
          inner.push(Stmt::AssertTruthy(Operand::Local(slot)))
          stmts.push(
            Stmt::With(overlays~, body=ReadOnlyArray::from_array(inner)),
          )
        } else {
          let op = lower_term(t, scope, alloc, run_grounded, wms, stmts)
          stmts.push(Stmt::Assign(dst=slot, src=op))
          stmts.push(Stmt::AssertTruthy(Operand::Local(slot)))
        }
        expr_slots.push(slot)
      }
      _ => {
        lower_expr(e, scope, alloc, run_grounded, stmts)
        let slot = alloc.fresh_temp()
        stmts.push(
          Stmt::Assign(dst=slot, src=Operand::Const(@value.Value::Bool(true))),
        )
        expr_slots.push(slot)
      }
    }
  }
  let bindings = ReadOnlyArray::from_array(alloc.user_vars)
  stmts.push(Stmt::ResultSetAdd(bindings~))
  {
    num_slots: alloc.next_slot,
    body: ReadOnlyArray::from_array(stmts),
    output_bindings: bindings,
    expr_slots: ReadOnlyArray::from_array(expr_slots),
  }
}

///|
fn is_relation_stmt(
  t : @ast.Term,
  wms : ReadOnlyArray[@ast.WithModifier],
  scope : ScopeCtx,
) -> Bool {
  match t.kind() {
    Call(callee~, args~) => {
      let resolved = scope.resolve_callee(callee, wms) catch {
        _ => return false
      }
      match resolved {
        CalleeWalk => args.length() == 2
        CalleeBuiltin(arity=Fixed(n), ..) => args.length() == n + 1
        CalleeUserFunc(arity~, ..) => arity >= 0 && args.length() == arity + 1
        _ => false
      }
    }
    _ => false
  }
}