///|
/// Shared deterministic step counter enforcing `StepBudget`.
priv struct StepCounter {
  mut steps : Int32
  limit : Int32
}

///|
fn StepCounter::tick(self : StepCounter) -> Unit raise EvalError {
  self.steps += 1
  if self.steps > self.limit {
    raise BudgetExceeded(limit=self.limit)
  }
}

///|
fn StepCounter::remaining(self : StepCounter) -> Int32 {
  if self.steps >= self.limit {
    0
  } else {
    self.limit - self.steps
  }
}

///|
fn StepCounter::charge(self : StepCounter, n : Int32) -> Unit raise EvalError {
  if n <= 0 {
    return
  }
  if n > self.limit - self.steps {
    self.steps = self.limit + 1
    raise BudgetExceeded(limit=self.limit)
  }
  self.steps += n
}

///|
/// Replacement value stored in a `WithScope` overlay.
priv enum OverlayValue {
  OverlayVal(@value.Value)
  OverlayFunc(ReadOnlyArray[String])
  OverlayBuiltin(@builtins.BuiltinName)
}

///|
/// Scoped `with` environment carrying effective `input`, `data` overlays,
/// built-in overlays, and a per-scope virtual-document memoization cache.
priv struct WithScope {
  input_val : @value.Value?
  data_overlays : Array[(ReadOnlyArray[String], OverlayValue)]
  builtin_overlays : Map[@builtins.BuiltinName, OverlayValue]
  cache : Map[String, @value.Value?]
  in_progress : Map[String, Unit]
}

///|
fn WithScope::root(input_val : @value.Value?) -> WithScope {
  {
    input_val,
    data_overlays: [],
    builtin_overlays: Map([]),
    cache: Map([]),
    in_progress: Map([]),
  }
}

///|
/// Active VM execution context shared across frames.
priv struct VmState {
  policy : @compile.CompiledPolicy
  static_data : @value.Value
  options : EngineOptions
  counter : StepCounter
}

///|
/// One block frame on the explicit Plan VM stack.
priv struct BlockFrame {
  stmts : ReadOnlyArray[@compile.Stmt]
  mut pc : Int32
  scope : WithScope
}

///|
/// Continuation behavior for a backtracking choice point.
priv enum ChoiceKind {
  ScanChoice(
    items~ : Array[(@value.Value, @value.Value)],
    next_idx~ : Int32,
    key_slot~ : Int32?,
    val_slot~ : Int32,
  )
  WalkChoice(
    pairs~ : ReadOnlyArray[@value.Value],
    next_idx~ : Int32,
    out_pat~ : @compile.Pattern,
  )
  RefKeyChoice(
    items~ : Array[(@value.Value, @value.Value)],
    next_idx~ : Int32,
    dst~ : Int32,
    key_slot~ : Int32,
    rem_segs~ : ReadOnlyArray[@compile.RefKey],
    seg_start~ : Int32,
  )
  RefPatChoice(
    items~ : Array[(@value.Value, @value.Value)],
    next_idx~ : Int32,
    dst~ : Int32,
    key_pat~ : @compile.Pattern,
    rem_segs~ : ReadOnlyArray[@compile.RefKey],
    seg_start~ : Int32,
  )
}

///|
/// Explicit backtracking choice point (replaces host call-stack recursion).
priv struct ChoicePoint {
  mut kind : ChoiceKind
  saved_frames : Array[(ReadOnlyArray[@compile.Stmt], Int32, WithScope)]
  trail_mark : Int32
}

///|
fn path_cache_key(path : ArrayView[String]) -> String {
  if path.is_empty() {
    ""
  } else {
    let buf = StringBuilder()
    for i in 0.. 0 {
        buf.write_char('\u{0000}')
      }
      buf.write_string(path[i])
    }
    buf.to_string()
  }
}

///|
fn format_path(path : ArrayView[String]) -> String {
  if path.is_empty() {
    "data"
  } else {
    let buf = StringBuilder()
    buf.write_string("data")
    for s in path {
      buf.write_char('.')
      buf.write_string(s)
    }
    buf.to_string()
  }
}

///|
fn paths_equal(a : ReadOnlyArray[String], b : ArrayView[String]) -> Bool {
  if a.length() != b.length() {
    return false
  }
  for i in 0.. Bool {
  if prefix.length() >= full.length() {
    return false
  }
  for i in 0.. Bool {
  if prefix.length() >= full.length() {
    return false
  }
  for i in 0.. @value.Value {
  if segs.is_empty() {
    return replacement
  }
  let key = @value.Value::String(segs[0])
  let existing_obj = match base {
    Some(Object(o)) => o
    _ => @value.RegoObject::empty()
  }
  let child_base = existing_obj.get(key)
  let updated_child = patch_value_at(child_base, segs[1:], replacement)
  @value.Value::Object(existing_obj.insert(key, updated_child))
}

///|
/// Traverses static string segments inside a `@value.Value` (objects and sets).
fn lookup_static_value(
  base : @value.Value,
  segs : ArrayView[String],
) -> @value.Value? {
  let mut cur = base
  for s in segs {
    match lookup_single_key(cur, @value.Value::String(s)) {
      Some(next) => cur = next
      None => return None
    }
  }
  Some(cur)
}

///|
/// Collects `(key, value)` pairs from an iterable Rego collection (`Array`,
/// `Object`, or `Set`), or `None` if `v` is not a collection.
fn collection_entries(v : @value.Value) -> Array[(@value.Value, @value.Value)]? {
  match v {
    Array(items) => {
      let out : Array[(@value.Value, @value.Value)] = []
      for i in 0.. {
      let out : Array[(@value.Value, @value.Value)] = []
      for e in obj.entries() {
        out.push(e)
      }
      Some(out)
    }
    Set(s) => {
      let out : Array[(@value.Value, @value.Value)] = []
      for item in s.items() {
        out.push((item, item))
      }
      Some(out)
    }
    _ => None
  }
}

///|
/// Single-step runtime indexing of `base[key]`.
fn lookup_single_key(base : @value.Value, key : @value.Value) -> @value.Value? {
  match base {
    Object(obj) => obj.get(key)
    Array(items) =>
      match key {
        Number(d) =>
          match d.to_int() {
            Some(idx) if idx >= 0 && idx < items.length() => Some(items[idx])
            _ => None
          }
        _ => None
      }
    Set(s) => if s.contains(key) { Some(key) } else { None }
    _ => None
  }
}

///|
/// Binds `slots[idx] = Some(val)` while recording the prior state on `trail`.
fn bind_slot(
  slots : Array[@value.Value?],
  trail : Array[(Int32, @value.Value?)],
  idx : Int32,
  val : @value.Value,
) -> Unit {
  let prev = slots[idx]
  trail.push((idx, prev))
  slots[idx] = Some(val)
}

///|
/// Unwinds `trail` back to `mark`, restoring previous slot bindings.
fn unwind_trail(
  slots : Array[@value.Value?],
  trail : Array[(Int32, @value.Value?)],
  mark : Int32,
) -> Unit {
  while trail.length() > mark {
    match trail.pop() {
      Some((idx, prev)) => slots[idx] = prev
      None => break
    }
  }
}

///|
/// Evaluates a `@compile.Operand` in the current frame & scope.
fn VmState::eval_operand(
  self : VmState,
  op : @compile.Operand,
  slots : Array[@value.Value?],
  scope : WithScope,
) -> @value.Value? raise EvalError {
  match op {
    Const(v) => Some(v)
    Local(idx) => slots[idx]
    Input => scope.input_val
    Data => self.eval_data_path([], scope)
  }
}

///|
/// Attempts to materialize a pattern into a ground `@value.Value` if every slot
/// inside it is currently bound.
fn pattern_to_value(
  pat : @compile.Pattern,
  slots : Array[@value.Value?],
) -> @value.Value? {
  match pat {
    PConst(v) => Some(v)
    PLocal(idx) => slots[idx]
    PWildcard => None
    PArray(items) => {
      let vals : Array[@value.Value] = []
      for item in items {
        guard pattern_to_value(item, slots) is Some(v) else { return None }
        vals.push(v)
      }
      Some(@value.Value::array(vals))
    }
    PSet(items) => {
      let vals : Array[@value.Value] = []
      for item in items {
        guard pattern_to_value(item, slots) is Some(v) else { return None }
        vals.push(v)
      }
      Some(@value.Value::set(vals))
    }
    PObject(pairs) => {
      let entries : Array[(@value.Value, @value.Value)] = []
      for pair in pairs {
        guard pattern_to_value(pair.0, slots) is Some(k) else { return None }
        guard pattern_to_value(pair.1, slots) is Some(v) else { return None }
        entries.push((k, v))
      }
      Some(@value.Value::object(entries))
    }
  }
}

///|
/// Unifies a concrete `@value.Value` against a `@compile.Pattern`.
fn unify_value_pattern(
  val : @value.Value,
  pat : @compile.Pattern,
  slots : Array[@value.Value?],
  trail : Array[(Int32, @value.Value?)],
  counter : StepCounter,
) -> Bool raise EvalError {
  counter.tick()
  match pat {
    PWildcard => true
    PConst(c) => val == c
    PLocal(idx) =>
      match slots[idx] {
        Some(existing) => existing == val
        None => {
          bind_slot(slots, trail, idx, val)
          true
        }
      }
    PArray(pats) =>
      match val {
        Array(items) if items.length() == pats.length() => {
          for i in 0.. false
      }
    PSet(_) =>
      match val {
        Set(s) => {
          guard pattern_to_value(pat, slots) is Some(Set(ps)) else {
            return false
          }
          s == ps
        }
        _ => false
      }
    PObject(pairs) =>
      match val {
        Object(obj) if obj.length() == pairs.length() => {
          for pair in pairs {
            guard pattern_to_value(pair.0, slots) is Some(k) else {
              return false
            }
            guard obj.get(k) is Some(v) else { return false }
            if !unify_value_pattern(v, pair.1, slots, trail, counter) {
              return false
            }
          }
          true
        }
        _ => false
      }
  }
}

///|
/// Structural Rego unification `lhs = rhs` supporting bidirectional binding
/// (for example `[a, 2] = [1, b]` and `[a, b] = [1, a]`).
fn unify_patterns(
  lhs : @compile.Pattern,
  rhs : @compile.Pattern,
  slots : Array[@value.Value?],
  trail : Array[(Int32, @value.Value?)],
  counter : StepCounter,
) -> Bool raise EvalError {
  counter.tick()
  // Fast paths when either side is already a concrete value.
  if pattern_to_value(lhs, slots) is Some(lv) {
    return unify_value_pattern(lv, rhs, slots, trail, counter)
  }
  if pattern_to_value(rhs, slots) is Some(rv) {
    return unify_value_pattern(rv, lhs, slots, trail, counter)
  }
  match (lhs, rhs) {
    (PWildcard, _) | (_, PWildcard) => true
    (PLocal(i), PLocal(j)) =>
      match (slots[i], slots[j]) {
        (Some(a), Some(b)) => a == b
        (Some(a), None) => {
          bind_slot(slots, trail, j, a)
          true
        }
        (None, Some(b)) => {
          bind_slot(slots, trail, i, b)
          true
        }
        (None, None) => i == j
      }
    (PArray(xs), PArray(ys)) if xs.length() == ys.length() => {
      for i in 0.. {
      // Match keys between the two object patterns and unify their value patterns.
      let used = Array::make(ys.length(), false)
      for x in xs {
        guard pattern_to_value(x.0, slots) is Some(xk) else { return false }
        let mut matched = false
        for j in 0.. false
  }
}

///|
/// Builds a child `WithScope` by applying `overlays` in left-to-right order.
fn VmState::apply_with_overlays(
  self : VmState,
  parent : WithScope,
  overlays : ReadOnlyArray[@compile.WithOverlay],
  slots : Array[@value.Value?],
) -> WithScope? raise EvalError {
  let mut next_input = parent.input_val
  let next_data = parent.data_overlays.copy()
  let next_builtins : Map[@builtins.BuiltinName, OverlayValue] = Map([])
  for k, v in parent.builtin_overlays {
    next_builtins.set(k, v)
  }
  for ov in overlays {
    let ov_val : OverlayValue = match ov.value {
      WithOperand(op) => {
        guard self.eval_operand(op, slots, parent) is Some(v) else {
          // If a `with` replacement value evaluates to undefined, the whole
          // `with` expression is undefined (fails this branch).
          return None
        }
        OverlayVal(v)
      }
      WithFuncPath(p) => OverlayFunc(p)
      WithBuiltinName(b) => OverlayBuiltin(b)
    }
    match ov.target {
      WithInput(segs) =>
        match ov_val {
          OverlayVal(v) =>
            next_input = Some(patch_value_at(next_input, segs, v))
          _ => return None
        }
      WithData(segs) => next_data.push((segs, ov_val))
      WithBuiltin(name) => next_builtins.set(name, ov_val)
    }
  }
  // Fresh empty memoization cache guarantees zero leakage across `with` scopes!
  Some({
    input_val: next_input,
    data_overlays: next_data,
    builtin_overlays: next_builtins,
    cache: Map([]),
    in_progress: Map([]),
  })
}

///|
/// Merges a dynamic ref-head contribution `keys -> val` into `obj`, enforcing
/// OPA conflict checks for complete leaves and set accumulation for set leaves.
fn merge_dynamic_entry(
  obj : @value.RegoObject,
  keys : ArrayView[@value.Value],
  leaf_kind : @compile.DynamicLeafKind,
  val : @value.Value,
  path_label : String,
) -> @value.RegoObject raise EvalError {
  if keys.is_empty() {
    return obj
  }
  let k = keys[0]
  if keys.length() == 1 {
    match leaf_kind {
      DynamicValue =>
        match obj.get(k) {
          Some(existing) =>
            if existing != val {
              raise Conflict(
                path=path_label,
                message="object key produced conflicting values",
              )
            } else {
              obj
            }
          None => obj.insert(k, val)
        }
      DynamicSetElem =>
        match obj.get(k) {
          Some(Set(s)) => obj.insert(k, @value.Value::Set(s.insert(val)))
          Some(_) =>
            raise Conflict(
              path=path_label,
              message="set leaf conflicts with non-set value",
            )
          None => obj.insert(k, @value.Value::set([val]))
        }
    }
  } else {
    let sub_obj = match obj.get(k) {
      Some(Object(o)) => o
      Some(_) =>
        raise Conflict(
          path=path_label,
          message="nested ref-head key conflicts with non-object value",
        )
      None => @value.RegoObject::empty()
    }
    let updated = merge_dynamic_entry(
      sub_obj,
      keys[1:],
      leaf_kind,
      val,
      path_label,
    )
    obj.insert(k, @value.Value::Object(updated))
  }
}

///|
/// Deep-merges virtual document entries over static base data entries.
/// In OPA, static base data takes precedence on scalar collisions while
/// nested objects merge recursively.
fn merge_objects(
  base : @value.RegoObject,
  overlay : @value.RegoObject,
  path_label : String,
) -> @value.RegoObject raise EvalError {
  let mut acc = base
  for entry in overlay.entries() {
    let k = entry.0
    let v = entry.1
    match (acc.get(k), v) {
      (Some(Object(a)), Object(b)) =>
        acc = acc.insert(
          k,
          @value.Value::Object(merge_objects(a, b, path_label)),
        )
      (Some(_), _) => ()
      (None, _) => acc = acc.insert(k, v)
    }
  }
  acc
}

///|
/// Applies any descendant `WithData` overlays that target paths strictly inside
/// `base_path` onto `base_val`.
fn apply_descendant_data_overlays(
  base_path : ArrayView[String],
  base_val : @value.Value?,
  scope : WithScope,
) -> @value.Value? {
  let mut cur = base_val
  for pair in scope.data_overlays {
    let ov_path = pair.0
    let ov_val = pair.1
    if is_prefix_of_ro(base_path, ov_path) {
      if ov_val is OverlayVal(v) {
        let rel : Array[String] = []
        for i in base_path.length()..` document (unifying static `data`, compiled
/// virtual rules, `with` overlays, and per-scope memoization).
fn VmState::eval_data_path(
  self : VmState,
  path : ArrayView[String],
  scope : WithScope,
) -> @value.Value? raise EvalError {
  self.counter.tick()
  let cache_key = path_cache_key(path)
  if scope.cache.get(cache_key) is Some(cached) {
    return cached
  }
  if scope.in_progress.contains(cache_key) {
    return None
  }

  // Check exact or ancestor `WithData` overlays (latest wins).
  let mut exact_or_prefix : @value.Value?? = None
  for pair in scope.data_overlays {
    let ov_path = pair.0
    let ov_val = pair.1
    if paths_equal(ov_path, path) {
      match ov_val {
        OverlayVal(v) => exact_or_prefix = Some(Some(v))
        _ => exact_or_prefix = Some(None)
      }
    } else if is_strict_prefix(ov_path, path) {
      match ov_val {
        OverlayVal(v) => {
          let tail : Array[String] = []
          for i in ov_path.length().. exact_or_prefix = Some(None)
      }
    }
  }
  if exact_or_prefix is Some(overridden) {
    let final_val = apply_descendant_data_overlays(path, overridden, scope)
    scope.cache.set(cache_key, final_val)
    return final_val
  }

  // Before marking `cache_key` in-progress, check whether an ancestor prefix
  // is a `VirtualObject` with dynamic clauses that is NOT already in-progress.
  // Evaluating the merged ancestor first ensures static children AND dynamic
  // clauses combine cleanly without `cache_key` blocking its own evaluation.
  for len = path.length() - 1; len >= 1; len = len - 1 {
    if self.policy.lookup_node(path[:len])
      is Some(VirtualObject(dynamic_clauses~, ..)) &&
      !dynamic_clauses.is_empty() {
      let anc_key = path_cache_key(path[:len])
      if !scope.in_progress.contains(anc_key) {
        let mut resolved : @value.Value? = None
        if self.eval_data_path(path[:len], scope) is Some(anc_val) {
          let mut cur = anc_val
          let mut ok = true
          for j in len.. cur = next
              None => {
                ok = false
                break
              }
            }
          }
          if ok {
            resolved = Some(cur)
          }
        }
        let final_val = apply_descendant_data_overlays(path, resolved, scope)
        scope.cache.set(cache_key, final_val)
        return final_val
      }
    }
  }

  scope.in_progress.set(cache_key, ())
  let path_label = format_path(path)
  errdefer scope.in_progress.remove(cache_key)
  let result : @value.Value? = match self.policy.lookup_node(path) {
    Some(Complete(clauses~, default_value~, default_branch~)) => {
      let mut found : @value.Value? = None
      for clause in clauses {
        let val = self.eval_complete_clause(clause, scope, path_label)
        if val is Some(v) {
          match found {
            Some(prev) =>
              if prev != v {
                raise Conflict(
                  path=path_label,
                  message="complete rule produced conflicting values",
                )
              }
            None => found = Some(v)
          }
        }
      }
      match found {
        Some(v) => Some(v)
        None =>
          match default_value {
            Some(dv) => Some(dv)
            None =>
              match default_branch {
                Some(br) => {
                  let br_slots : Array[@value.Value?] = Array::make(
                    br.num_slots,
                    None,
                  )
                  let mut br_val : @value.Value? = None
                  self.exec_stmts(
                    br.body,
                    br_slots,
                    scope,
                    self.make_builtin_context(),
                    true,
                    fn(sol_slots, sol_scope) raise EvalError {
                      br_val = self.eval_operand(
                        br.result,
                        sol_slots,
                        sol_scope,
                      )
                    },
                  )
                  br_val
                }
                None => None
              }
          }
      }
    }
    Some(PartialSet(clauses~)) => {
      let mut acc = @value.RegoSet::empty()
      for clause in clauses {
        let slots : Array[@value.Value?] = Array::make(clause.num_slots, None)
        let meta = self.make_builtin_context(
          rule_metadata=clause.rule_metadata,
          chain_metadata=clause.chain_metadata,
        )
        self.exec_stmts(clause.body, slots, scope, meta, false, fn(
          sol_slots,
          sol_scope,
        ) raise EvalError {
          if self.eval_operand(clause.value_operand, sol_slots, sol_scope)
            is Some(v) {
            acc = acc.insert(v)
          }
        })
      }
      Some(@value.Value::Set(acc))
    }
    Some(VirtualObject(static_children~, dynamic_clauses~)) => {
      let mut obj = match lookup_static_value(self.static_data, path) {
        Some(Object(o)) => o
        _ => @value.RegoObject::empty()
      }
      for child in static_children {
        let child_name = child.0
        if child.1 is Function(..) {
          continue
        }
        let child_path : Array[String] = []
        for s in path {
          child_path.push(s)
        }
        child_path.push(child_name)
        if self.eval_data_path(child_path, scope) is Some(cv) {
          let sub = @value.RegoObject::from_strings([(child_name, cv)])
          obj = merge_objects(obj, sub, path_label)
        }
      }
      for clause in dynamic_clauses {
        let slots : Array[@value.Value?] = Array::make(clause.num_slots, None)
        let meta = self.make_builtin_context(
          rule_metadata=clause.rule_metadata,
          chain_metadata=clause.chain_metadata,
        )
        self.exec_stmts(clause.body, slots, scope, meta, false, fn(
          sol_slots,
          sol_scope,
        ) raise EvalError {
          let ks : Array[@value.Value] = []
          for kop in clause.key_operands {
            guard self.eval_operand(kop, sol_slots, sol_scope) is Some(kv) else {
              return
            }
            ks.push(kv)
          }
          guard self.eval_operand(clause.value_operand, sol_slots, sol_scope)
            is Some(v) else {
            return
          }
          obj = merge_dynamic_entry(obj, ks, clause.leaf_kind, v, path_label)
        })
      }
      Some(@value.Value::Object(obj))
    }
    Some(Package(children~)) => {
      let mut obj = match lookup_static_value(self.static_data, path) {
        Some(Object(o)) => o
        _ => @value.RegoObject::empty()
      }
      for child in children {
        let child_name = child.0
        if child.1 is Function(..) {
          continue
        }
        let child_path : Array[String] = []
        for s in path {
          child_path.push(s)
        }
        child_path.push(child_name)
        if self.eval_data_path(child_path, scope) is Some(cv) {
          let sub = @value.RegoObject::from_strings([(child_name, cv)])
          obj = merge_objects(obj, sub, path_label)
        }
      }
      Some(@value.Value::Object(obj))
    }
    Some(Function(..)) => None
    None => {
      // Check if an ancestor prefix is a compiled rule (`Complete`,
      // `PartialSet`, or `VirtualObject`), such as `data.pkg.obj.k` or
      // `data.pkg.myset.member`, before falling back to static data.
      let mut resolved : @value.Value? = None
      let mut hit_virtual = false
      for len = path.length() - 1; len >= 1; len = len - 1 {
        match self.policy.lookup_node(path[:len]) {
          Some(Complete(..)) | Some(PartialSet(..)) | Some(VirtualObject(..)) => {
            hit_virtual = true
            if self.eval_data_path(path[:len], scope) is Some(anc_val) {
              let mut cur = anc_val
              let mut ok = true
              for j in len.. cur = next
                  None => {
                    ok = false
                    break
                  }
                }
              }
              if ok {
                resolved = Some(cur)
              }
            }
            break
          }
          _ => ()
        }
      }
      if hit_virtual {
        resolved
      } else {
        lookup_static_value(self.static_data, path)
      }
    }
  }

  let final_val = apply_descendant_data_overlays(path, result, scope)
  scope.in_progress.remove(cache_key)
  scope.cache.set(cache_key, final_val)
  final_val
}

///|
fn VmState::make_builtin_context(
  self : VmState,
  rule_metadata~ : @value.Value? = None,
  chain_metadata~ : @value.Value? = None,
) -> @builtins.BuiltinContext {
  @builtins.BuiltinContext::with_metadata(rule_metadata~, chain_metadata~)
  .with_clock(self.options.clock())
  .with_random_seed(self.options.random_seed())
}

///|
/// Evaluates a single complete rule clause and its `else` branches.
fn VmState::eval_complete_clause(
  self : VmState,
  clause : @compile.CompiledClause,
  scope : WithScope,
  path_label : String,
) -> @value.Value? raise EvalError {
  let slots : Array[@value.Value?] = Array::make(clause.num_slots, None)
  let meta = self.make_builtin_context(
    rule_metadata=clause.rule_metadata,
    chain_metadata=clause.chain_metadata,
  )
  let mut found : @value.Value? = None
  self.exec_stmts(clause.body, slots, scope, meta, false, fn(
    sol_slots,
    sol_scope,
  ) raise EvalError {
    if self.eval_operand(clause.value_operand, sol_slots, sol_scope) is Some(v) {
      match found {
        Some(prev) =>
          if prev != v {
            raise Conflict(
              path=path_label,
              message="rule produced conflicting values across bindings",
            )
          }
        None => found = Some(v)
      }
    }
  })
  if found is Some(_) {
    return found
  }
  // Try `else` branches in order.
  for br in clause.else_branches {
    let br_slots : Array[@value.Value?] = Array::make(br.num_slots, None)
    let mut br_found : @value.Value? = None
    self.exec_stmts(br.body, br_slots, scope, meta, false, fn(
      sol_slots,
      sol_scope,
    ) raise EvalError {
      if self.eval_operand(br.result, sol_slots, sol_scope) is Some(v) {
        match br_found {
          Some(prev) =>
            if prev != v {
              raise Conflict(
                path=path_label,
                message="else branch produced conflicting values",
              )
            }
          None => br_found = Some(v)
        }
      }
    })
    if br_found is Some(_) {
      return br_found
    }
  }
  None
}

///|
/// Evaluates a user-defined Rego function at `path` with `args`.
fn VmState::eval_func(
  self : VmState,
  path : ReadOnlyArray[String],
  args : Array[@value.Value],
  scope : WithScope,
  caller_meta : @builtins.BuiltinContext,
) -> @value.Value? raise EvalError {
  self.counter.tick()
  // Check `WithData` overlay on this function path (latest wins).
  let mut ov_found : OverlayValue? = None
  for pair in scope.data_overlays {
    if paths_equal(pair.0, path[:]) {
      ov_found = Some(pair.1)
    }
  }
  if ov_found is Some(ov) {
    // When invoking a `with` replacement, remove the dispatched overlay from
    // the callee scope so a mock function can safely delegate to the original
    // function without recursing into itself (matching OPA v1.23.0 semantics).
    let stripped_data : Array[(ReadOnlyArray[String], OverlayValue)] = []
    for pair in scope.data_overlays {
      if !paths_equal(pair.0, path[:]) {
        stripped_data.push(pair)
      }
    }
    let callee_scope : WithScope = {
      input_val: scope.input_val,
      data_overlays: stripped_data,
      builtin_overlays: scope.builtin_overlays,
      cache: Map([]),
      in_progress: Map([]),
    }
    match ov {
      OverlayVal(v) => return Some(v)
      OverlayFunc(target_path) =>
        return self.eval_func(target_path, args, callee_scope, caller_meta)
      OverlayBuiltin(bname) =>
        return self.eval_builtin(bname, args, callee_scope, caller_meta)
    }
  }

  let path_label = format_path(path[:])
  guard self.policy.lookup_node(path[:])
    is Some(Function(arity~, clauses~, default_value~)) else {
    return None
  }
  if args.length() != arity {
    return None
  }
  let mut found : @value.Value? = None
  for clause in clauses {
    let slots : Array[@value.Value?] = Array::make(clause.num_slots, None)
    let trail : Array[(Int32, @value.Value?)] = []
    let mut matched = true
    for i in 0..
            if prev != v {
              raise Conflict(
                path=path_label,
                message="function produced conflicting values",
              )
            }
          None => clause_found = Some(v)
        }
      }
    })
    if clause_found is None {
      for br in clause.else_branches {
        let br_slots : Array[@value.Value?] = Array::make(br.num_slots, None)
        // Copy bound parameter slots into the else branch frame.
        let copy_len = if slots.length() < br_slots.length() {
          slots.length()
        } else {
          br_slots.length()
        }
        for i in 0..
                if prev != v {
                  raise Conflict(
                    path=path_label,
                    message="function else branch produced conflicting values",
                  )
                }
              None => br_found = Some(v)
            }
          }
        })
        if br_found is Some(_) {
          clause_found = br_found
          break
        }
      }
    }
    if clause_found is Some(v) {
      match found {
        Some(prev) =>
          if prev != v {
            raise Conflict(
              path=path_label,
              message="function clauses produced conflicting values",
            )
          }
        None => found = Some(v)
      }
    }
  }
  match found {
    Some(v) => Some(v)
    None => default_value
  }
}

///|
/// Evaluates a registered built-in function, honoring `with` overrides.
fn VmState::eval_builtin(
  self : VmState,
  name : @builtins.BuiltinName,
  args : Array[@value.Value],
  scope : WithScope,
  meta : @builtins.BuiltinContext,
) -> @value.Value? raise EvalError {
  self.counter.tick()
  if scope.builtin_overlays.get(name) is Some(ov) {
    let stripped_builtins : Map[@builtins.BuiltinName, OverlayValue] = Map([])
    let callee_scope : WithScope = {
      input_val: scope.input_val,
      data_overlays: scope.data_overlays,
      builtin_overlays: stripped_builtins,
      cache: Map([]),
      in_progress: Map([]),
    }
    match ov {
      OverlayVal(v) => return Some(v)
      OverlayFunc(target_path) =>
        return self.eval_func(target_path, args, callee_scope, meta)
      OverlayBuiltin(bname) =>
        return self.eval_builtin(bname, args, callee_scope, meta)
    }
  }
  guard self.policy.builtins().get(name) is Some(entry) else { return None }
  let call_meta = meta.with_remaining_steps(self.counter.remaining())
  let res = entry.call(args, call_meta) catch {
    @builtins.BudgetExceeded(..) =>
      raise BudgetExceeded(limit=self.counter.limit)
    @builtins.EvalFailure(name=bn, message~) =>
      if self.options.strict_builtin_errors {
        raise BuiltinFailure(name=bn, message~)
      } else {
        return None
      }
    @builtins.WrongArity(..) => return None
    _ => return None
  }
  let name_text = name.to_string()
  if (name_text == "numbers.range" || name_text == "numbers.range_step") &&
    res is Some(@value.Array(items)) {
    self.counter.charge(items.length())
  }
  res
}

///|
fn snapshot_frames(
  frames : Array[BlockFrame],
) -> Array[(ReadOnlyArray[@compile.Stmt], Int32, WithScope)] {
  let out : Array[(ReadOnlyArray[@compile.Stmt], Int32, WithScope)] = []
  for f in frames {
    out.push((f.stmts, f.pc, f.scope))
  }
  out
}

///|
fn restore_frames(
  saved : Array[(ReadOnlyArray[@compile.Stmt], Int32, WithScope)],
) -> Array[BlockFrame] {
  let out : Array[BlockFrame] = []
  for s in saved {
    out.push({ stmts: s.0, pc: s.1, scope: s.2, })
  }
  out
}

///|
/// Core explicit-stack Plan VM execution loop with trail-based backtracking.
fn VmState::exec_stmts(
  self : VmState,
  entry_stmts : ReadOnlyArray[@compile.Stmt],
  slots : Array[@value.Value?],
  entry_scope : WithScope,
  meta : @builtins.BuiltinContext,
  stop_after_first : Bool,
  on_solution : (Array[@value.Value?], WithScope) -> Unit raise EvalError,
) -> Unit raise EvalError {
  let trail : Array[(Int32, @value.Value?)] = []
  let mut frames : Array[BlockFrame] = [
    { stmts: entry_stmts, pc: 0, scope: entry_scope, },
  ]
  let choices : Array[ChoicePoint] = []
  let mut current_scope = entry_scope

  fn backtrack() -> Bool raise EvalError {
    while !choices.is_empty() {
      self.counter.tick()
      let top_idx = choices.length() - 1
      let cp = choices[top_idx]
      unwind_trail(slots, trail, cp.trail_mark)
      match cp.kind {
        ScanChoice(items~, next_idx~, key_slot~, val_slot~) =>
          if next_idx < items.length() {
            let pair = items[next_idx]
            cp.kind = ScanChoice(
              items~,
              next_idx=next_idx + 1,
              key_slot~,
              val_slot~,
            )
            if key_slot is Some(ks) {
              bind_slot(slots, trail, ks, pair.0)
            }
            bind_slot(slots, trail, val_slot, pair.1)
            frames = restore_frames(cp.saved_frames)
            return true
          } else {
            let _ = choices.pop()
          }
        WalkChoice(pairs~, next_idx~, out_pat~) =>
          if next_idx < pairs.length() {
            let pair_val = pairs[next_idx]
            cp.kind = WalkChoice(pairs~, next_idx=next_idx + 1, out_pat~)
            if unify_value_pattern(
                pair_val,
                out_pat,
                slots,
                trail,
                self.counter,
              ) {
              frames = restore_frames(cp.saved_frames)
              return true
            }
            // Otherwise loop to try the next walk pair!
          } else {
            let _ = choices.pop()
          }
        RefKeyChoice(items~, next_idx~, dst~, key_slot~, rem_segs~, seg_start~) =>
          if next_idx < items.length() {
            let pair = items[next_idx]
            cp.kind = RefKeyChoice(
              items~,
              next_idx=next_idx + 1,
              dst~,
              key_slot~,
              rem_segs~,
              seg_start~,
            )
            frames = restore_frames(cp.saved_frames)
            let active_scope = if frames.is_empty() {
              entry_scope
            } else {
              frames[frames.length() - 1].scope
            }
            bind_slot(slots, trail, key_slot, pair.0)
            if self.eval_ref_segments(
                pair.1,
                rem_segs,
                seg_start,
                dst,
                slots,
                trail,
                frames,
                choices,
                active_scope,
              ) {
              return true
            }
            // Otherwise loop to try the next key!
          } else {
            let _ = choices.pop()
          }
        RefPatChoice(items~, next_idx~, dst~, key_pat~, rem_segs~, seg_start~) =>
          if next_idx < items.length() {
            let pair = items[next_idx]
            cp.kind = RefPatChoice(
              items~,
              next_idx=next_idx + 1,
              dst~,
              key_pat~,
              rem_segs~,
              seg_start~,
            )
            frames = restore_frames(cp.saved_frames)
            let active_scope = if frames.is_empty() {
              entry_scope
            } else {
              frames[frames.length() - 1].scope
            }
            if unify_value_pattern(pair.0, key_pat, slots, trail, self.counter) &&
              self.eval_ref_segments(
                pair.1,
                rem_segs,
                seg_start,
                dst,
                slots,
                trail,
                frames,
                choices,
                active_scope,
              ) {
              return true
            }
          } else {
            let _ = choices.pop()
          }
      }
    }
    unwind_trail(slots, trail, 0)
    false
  }

  while true {
    self.counter.tick()
    if frames.is_empty() {
      on_solution(slots, current_scope)
      if stop_after_first {
        unwind_trail(slots, trail, 0)
        return
      }
      if !backtrack() {
        return
      }
      continue
    }
    let f_idx = frames.length() - 1
    let frame = frames[f_idx]
    current_scope = frame.scope
    if frame.pc >= frame.stmts.length() {
      let _ = frames.pop()
      continue
    }
    let stmt = frame.stmts[frame.pc]
    frame.pc += 1

    match stmt {
      Block(inner) => frames.push({ stmts: inner, pc: 0, scope: frame.scope, })
      Break(depth) => {
        let mut to_pop = depth + 1
        while to_pop > 0 && !frames.is_empty() {
          let _ = frames.pop()
          to_pop -= 1
        }
      }
      AssertTruthy(op) =>
        match self.eval_operand(op, slots, frame.scope) {
          Some(Bool(false)) | None => if !backtrack() { return }
          Some(_) => ()
        }
      AssertCollection(op) =>
        match self.eval_operand(op, slots, frame.scope) {
          Some(Array(_)) | Some(Object(_)) | Some(Set(_)) => ()
          _ => if !backtrack() { return }
        }
      Assign(dst~, src~) =>
        match self.eval_operand(src, slots, frame.scope) {
          Some(v) => bind_slot(slots, trail, dst, v)
          None => if !backtrack() { return }
        }
      Equal(lhs~, rhs~) =>
        match
          (
            self.eval_operand(lhs, slots, frame.scope),
            self.eval_operand(rhs, slots, frame.scope),
          ) {
          (Some(a), Some(b)) if a == b => ()
          _ => if !backtrack() { return }
        }
      Unify(lhs~, rhs~) => {
        let mark = trail.length()
        if !unify_patterns(lhs, rhs, slots, trail, self.counter) {
          unwind_trail(slots, trail, mark)
          if !backtrack() {
            return
          }
        }
      }
      EvalRef(dst~, base~, segments~) =>
        if base is @compile.Operand::Data {
          let data_prefix : Array[String] = []
          let mut consumed = 0
          let mut failed_prefix = false
          for i in 0.. {
                data_prefix.push(s)
                consumed = i + 1
              }
              Dynamic(op) =>
                match self.eval_operand(op, slots, frame.scope) {
                  Some(String(s)) => {
                    data_prefix.push(s)
                    consumed = i + 1
                  }
                  Some(Number(d)) if d.to_bigint() is Some(_) =>
                    // OPA `data` ref dereference: if `data.` is an
                    // Object (not an Array) and has string key `"2"`, index
                    // `data[2]` / `data.nested[2]` resolves to `"2"`.
                    match self.eval_data_path(data_prefix, frame.scope) {
                      Some(Object(o)) if o.get_string(d.to_string()) is Some(_) => {
                        data_prefix.push(d.to_string())
                        consumed = i + 1
                      }
                      _ => break
                    }
                  Some(_) => break
                  None => {
                    failed_prefix = true
                    break
                  }
                }
              BindKey(k_slot) =>
                match slots[k_slot] {
                  Some(String(s)) => {
                    data_prefix.push(s)
                    consumed = i + 1
                  }
                  _ => break
                }
              BindPattern(_) => break
            }
          }
          if failed_prefix {
            if !backtrack() {
              return
            }
          } else {
            match self.eval_data_path(data_prefix, frame.scope) {
              Some(base_val) =>
                if !self.eval_ref_segments(
                    base_val,
                    segments,
                    consumed,
                    dst,
                    slots,
                    trail,
                    frames,
                    choices,
                    frame.scope,
                  ) {
                  if !backtrack() {
                    return
                  }
                }
              None => if !backtrack() { return }
            }
          }
        } else {
          match self.eval_operand(base, slots, frame.scope) {
            Some(base_val) =>
              if !self.eval_ref_segments(
                  base_val,
                  segments,
                  0,
                  dst,
                  slots,
                  trail,
                  frames,
                  choices,
                  frame.scope,
                ) {
                if !backtrack() {
                  return
                }
              }
            None => if !backtrack() { return }
          }
        }
      Scan(domain~, key_slot~, val_slot~) =>
        match self.eval_operand(domain, slots, frame.scope) {
          Some(dom_val) =>
            match collection_entries(dom_val) {
              Some(items) if !items.is_empty() => {
                if items.length() > 1 {
                  choices.push({
                    kind: ScanChoice(items~, next_idx=1, key_slot~, val_slot~),
                    saved_frames: snapshot_frames(frames),
                    trail_mark: trail.length(),
                  })
                }
                if key_slot is Some(ks) {
                  bind_slot(slots, trail, ks, items[0].0)
                }
                bind_slot(slots, trail, val_slot, items[0].1)
              }
              _ => if !backtrack() { return }
            }
          None => if !backtrack() { return }
        }
      WalkScan(target~, out~) =>
        match self.eval_operand(target, slots, frame.scope) {
          Some(t_val) => {
            let pairs = @builtins.walk_pairs(t_val)
            let mut matched_first = false
            let mut idx = 0
            while idx < pairs.length() {
              let mark = trail.length()
              if unify_value_pattern(
                  pairs[idx],
                  out,
                  slots,
                  trail,
                  self.counter,
                ) {
                if idx + 1 < pairs.length() {
                  choices.push({
                    kind: WalkChoice(pairs~, next_idx=idx + 1, out_pat=out),
                    saved_frames: snapshot_frames(frames),
                    trail_mark: mark,
                  })
                }
                matched_first = true
                break
              }
              unwind_trail(slots, trail, mark)
              idx += 1
            }
            if !matched_first {
              if !backtrack() {
                return
              }
            }
          }
          None => if !backtrack() { return }
        }
      Not(body) => {
        let mut any_sol = false
        let sub_slots = slots.copy()
        self.exec_stmts(body, sub_slots, frame.scope, meta, true, fn(_, _) {
          any_sol = true
        })
        if any_sol {
          if !backtrack() {
            return
          }
        }
      }
      CallBuiltin(name~, args~, dst~) => {
        let arg_vals : Array[@value.Value] = []
        let mut all_ok = true
        for a in args {
          match self.eval_operand(a, slots, frame.scope) {
            Some(v) => arg_vals.push(v)
            None => {
              all_ok = false
              break
            }
          }
        }
        if !all_ok {
          if !backtrack() {
            return
          }
          continue
        }
        match self.eval_builtin(name, arg_vals, frame.scope, meta) {
          Some(res) => if dst is Some(d) { bind_slot(slots, trail, d, res) }
          None => if !backtrack() { return }
        }
      }
      CallRule(path~, dst~) =>
        match self.eval_data_path(path[:], frame.scope) {
          Some(v) => bind_slot(slots, trail, dst, v)
          None => if !backtrack() { return }
        }
      CallFunc(path~, args~, dst~) => {
        let arg_vals : Array[@value.Value] = []
        let mut all_ok = true
        for a in args {
          match self.eval_operand(a, slots, frame.scope) {
            Some(v) => arg_vals.push(v)
            None => {
              all_ok = false
              break
            }
          }
        }
        if !all_ok {
          if !backtrack() {
            return
          }
          continue
        }
        match self.eval_func(path, arg_vals, frame.scope, meta) {
          Some(res) => bind_slot(slots, trail, dst, res)
          None => if !backtrack() { return }
        }
      }
      With(overlays~, body~) =>
        match self.apply_with_overlays(frame.scope, overlays, slots) {
          Some(child_scope) =>
            frames.push({ stmts: body, pc: 0, scope: child_scope, })
          None => if !backtrack() { return }
        }
      ElseChain(branches~, dst~) => {
        let mut chosen : @value.Value? = None
        for br in branches {
          let br_slots : Array[@value.Value?] = Array::make(br.num_slots, None)
          let mut br_found : @value.Value? = None
          self.exec_stmts(br.body, br_slots, frame.scope, meta, false, fn(
            sol_slots,
            sol_scope,
          ) raise EvalError {
            if self.eval_operand(br.result, sol_slots, sol_scope) is Some(v) {
              match br_found {
                Some(prev) =>
                  if prev != v {
                    raise Conflict(
                      path="",
                      message="else branch produced conflicting values",
                    )
                  }
                None => br_found = Some(v)
              }
            }
          })
          if br_found is Some(_) {
            chosen = br_found
            break
          }
        }
        match chosen {
          Some(v) => bind_slot(slots, trail, dst, v)
          None => if !backtrack() { return }
        }
      }
      MakeArray(dst~) => bind_slot(slots, trail, dst, @value.Value::array([]))
      ArrayPush(arr~, elem~) =>
        match (slots[arr], self.eval_operand(elem, slots, frame.scope)) {
          (Some(Array(items)), Some(v)) => {
            let next : Array[@value.Value] = []
            for x in items {
              next.push(x)
            }
            next.push(v)
            bind_slot(slots, trail, arr, @value.Value::array(next))
          }
          _ => if !backtrack() { return }
        }
      MakeSet(dst~) =>
        bind_slot(slots, trail, dst, @value.Value::Set(@value.RegoSet::empty()))
      SetAdd(set~, elem~) =>
        match (slots[set], self.eval_operand(elem, slots, frame.scope)) {
          (Some(Set(s)), Some(v)) =>
            bind_slot(slots, trail, set, @value.Value::Set(s.insert(v)))
          _ => if !backtrack() { return }
        }
      MakeObject(dst~) =>
        bind_slot(
          slots,
          trail,
          dst,
          @value.Value::Object(@value.RegoObject::empty()),
        )
      ObjectInsert(obj~, key~, val~) =>
        match
          (
            slots[obj],
            self.eval_operand(key, slots, frame.scope),
            self.eval_operand(val, slots, frame.scope),
          ) {
          (Some(Object(o)), Some(k), Some(v)) =>
            bind_slot(slots, trail, obj, @value.Value::Object(o.insert(k, v)))
          _ => if !backtrack() { return }
        }
      BuildArrayComp(dst~, elem~, body~) => {
        let collected : Array[@value.Value] = []
        let sub_slots = slots.copy()
        self.exec_stmts(body, sub_slots, frame.scope, meta, false, fn(
          sol_slots,
          sol_scope,
        ) raise EvalError {
          if self.eval_operand(elem, sol_slots, sol_scope) is Some(v) {
            collected.push(v)
          }
        })
        bind_slot(slots, trail, dst, @value.Value::array(collected))
      }
      BuildSetComp(dst~, elem~, body~) => {
        let mut acc = @value.RegoSet::empty()
        let sub_slots = slots.copy()
        self.exec_stmts(body, sub_slots, frame.scope, meta, false, fn(
          sol_slots,
          sol_scope,
        ) raise EvalError {
          if self.eval_operand(elem, sol_slots, sol_scope) is Some(v) {
            acc = acc.insert(v)
          }
        })
        bind_slot(slots, trail, dst, @value.Value::Set(acc))
      }
      BuildObjectComp(dst~, key~, val~, body~) => {
        let mut acc = @value.RegoObject::empty()
        let sub_slots = slots.copy()
        self.exec_stmts(body, sub_slots, frame.scope, meta, false, fn(
          sol_slots,
          sol_scope,
        ) raise EvalError {
          if (
              self.eval_operand(key, sol_slots, sol_scope),
              self.eval_operand(val, sol_slots, sol_scope),
            )
            is (Some(k), Some(v)) {
            match acc.get(k) {
              Some(existing) if existing != v =>
                raise Conflict(
                  path="",
                  message="object comprehension keys must not conflict",
                )
              _ => acc = acc.insert(k, v)
            }
          }
        })
        bind_slot(slots, trail, dst, @value.Value::Object(acc))
      }
      FormatTemplate(dst~, parts~) => {
        let buf = StringBuilder()
        for part in parts {
          match part {
            Lit(s) => buf.write_string(s)
            Interp(stmts~, slot~) => {
              let mut rendered : @value.Value? = None
              let sub_slots = slots.copy()
              self.exec_stmts(stmts, sub_slots, frame.scope, meta, true, fn(
                sol_slots,
                _,
              ) {
                rendered = sol_slots[slot]
              })
              match rendered {
                Some(v) => buf.write_string(v.format_template())
                None => buf.write_string("")
              }
            }
          }
        }
        bind_slot(slots, trail, dst, @value.Value::String(buf.to_string()))
      }
      ResultSetAdd(_) => ()
    }
  }
}

///|
/// Traverses reference segments `segments[start..]` starting from `start_val`,
/// pushing backtracking `RefKeyChoice` points whenever a `BindKey` segment
/// encounters a collection.
fn VmState::eval_ref_segments(
  self : VmState,
  start_val : @value.Value,
  segments : ReadOnlyArray[@compile.RefKey],
  start : Int32,
  dst : Int32,
  slots : Array[@value.Value?],
  trail : Array[(Int32, @value.Value?)],
  frames : Array[BlockFrame],
  choices : Array[ChoicePoint],
  scope : WithScope,
) -> Bool raise EvalError {
  let mut cur = start_val
  for i in start..
        match lookup_single_key(cur, @value.Value::String(s)) {
          Some(next) => cur = next
          None => return false
        }
      Dynamic(op) =>
        match self.eval_operand(op, slots, scope) {
          Some(k) =>
            match lookup_single_key(cur, k) {
              Some(next) => cur = next
              None => return false
            }
          None => return false
        }
      BindKey(k_slot) =>
        match slots[k_slot] {
          // If already bound in an earlier expression, treat as ground lookup.
          Some(k) =>
            match lookup_single_key(cur, k) {
              Some(next) => cur = next
              None => return false
            }
          None =>
            match collection_entries(cur) {
              Some(items) if !items.is_empty() => {
                if items.length() > 1 {
                  choices.push({
                    kind: RefKeyChoice(
                      items~,
                      next_idx=1,
                      dst~,
                      key_slot=k_slot,
                      rem_segs=segments,
                      seg_start=i + 1,
                    ),
                    saved_frames: snapshot_frames(frames),
                    trail_mark: trail.length(),
                  })
                }
                bind_slot(slots, trail, k_slot, items[0].0)
                cur = items[0].1
              }
              _ => return false
            }
        }
      BindPattern(key_pat) =>
        match collection_entries(cur) {
          Some(items) if !items.is_empty() => {
            let mut matched_idx = -1
            for j in 0.. return false
        }
    }
  }
  bind_slot(slots, trail, dst, cur)
  true
}

///|
/// Evaluates a compiled Rego v1 query against a `CompiledPolicy`, optional
/// `input` document, static `data` document, and `EngineOptions`.
pub fn eval_query(
  policy : @compile.CompiledPolicy,
  query : @compile.CompiledQuery,
  input~ : @value.Value? = None,
  data~ : @value.Value = @value.Value::Object(@value.RegoObject::empty()),
  options~ : EngineOptions = EngineOptions::default(),
) -> EvalResult raise EvalError {
  let state : VmState = {
    policy,
    static_data: data,
    options,
    counter: { steps: 0, limit: options.step_budget().limit(), },
  }
  let slots : Array[@value.Value?] = Array::make(query.num_slots(), None)
  let root_scope = WithScope::root(input)
  let rows : Array[BindingSet] = []

  state.exec_stmts(
    query.body(),
    slots,
    root_scope,
    state.make_builtin_context(),
    false,
    fn(sol_slots, _) {
      let b_pairs : Array[(String, @value.Value)] = []
      for b in query.output_bindings() {
        if sol_slots[b.1] is Some(v) {
          b_pairs.push((b.0, v))
        }
      }
      let expr_vals : Array[@value.Value] = []
      for s in query.expr_slots() {
        if sol_slots[s] is Some(v) {
          expr_vals.push(v)
        }
      }
      rows.push({
        bindings: ReadOnlyArray::from_array(b_pairs),
        expressions: ReadOnlyArray::from_array(expr_vals),
      })
    },
  )
  { rows: ReadOnlyArray::from_array(rows), }
}

///|
/// Directly evaluates a `data.` rule or package document in `policy`.
/// `path` holds arbitrary `data` object keys (`ArrayView[String]`), which have
/// no character-set restrictions in Rego or JSON.
pub fn eval_rule(
  policy : @compile.CompiledPolicy,
  path : ArrayView[String],
  input~ : @value.Value? = None,
  data~ : @value.Value = @value.Value::Object(@value.RegoObject::empty()),
  options~ : EngineOptions = EngineOptions::default(),
) -> @value.Value? raise EvalError {
  let state : VmState = {
    policy,
    static_data: data,
    options,
    counter: { steps: 0, limit: options.step_budget().limit(), },
  }
  state.eval_data_path(path, WithScope::root(input))
}