///|
/// Resolved target of a call expression `callee(args...)`.
priv enum ResolvedCallee {
  CalleeUserFunc(path~ : Array[String], arity~ : Int32)
  CalleeBuiltin(name~ : @builtins.BuiltinName, arity~ : @builtins.BuiltinArity)
  CalleeWalk
}

///|
/// Static lexical scope context used during safety analysis, scheduling, and
/// Plan IR lowering.
priv struct ScopeCtx {
  raw_root : RawNode?
  compiled_policy : CompiledPolicy?
  env : ModuleEnv?
  builtins : @builtins.BuiltinRegistry
  declared_locals : Map[String, Unit]
}

///|
fn ScopeCtx::has_node(self : ScopeCtx, path : ArrayView[String]) -> Bool {
  match (self.raw_root, self.compiled_policy) {
    (Some(r), _) => lookup_raw_node(r, path) is Some(_)
    (None, Some(p)) => p.lookup_node(path) is Some(_)
    (None, None) => false
  }
}

///|
fn ScopeCtx::function_arity(
  self : ScopeCtx,
  path : ArrayView[String],
) -> Int32? {
  match (self.raw_root, self.compiled_policy) {
    (Some(r), _) =>
      match lookup_raw_node(r, path) {
        Some(node) =>
          match node.kind {
            RawFunction(a) => Some(a)
            _ => None
          }
        None => None
      }
    (None, Some(p)) =>
      match p.lookup_node(path) {
        Some(Function(arity~, ..)) => Some(arity)
        _ => None
      }
    (None, None) => None
  }
}

///|
fn ScopeCtx::child_with_locals(
  self : ScopeCtx,
  extra : Map[String, Unit],
) -> ScopeCtx {
  let merged : Map[String, Unit] = Map([])
  for k, v in self.declared_locals {
    merged.set(k, v)
  }
  for k, v in extra {
    merged.set(k, v)
  }
  {
    raw_root: self.raw_root,
    compiled_policy: self.compiled_policy,
    env: self.env,
    builtins: self.builtins,
    declared_locals: merged,
  }
}

///|
/// Reports whether bare identifier `name` refers to a local variable rather
/// than `input`, `data`, an import alias, or a sibling rule/package.
fn ScopeCtx::is_local_var(self : ScopeCtx, name : String) -> Bool {
  if name == "_" {
    return true
  }
  if name == "input" || name == "data" {
    return false
  }
  if self.declared_locals.contains(name) {
    return true
  }
  match self.env {
    Some(e) => {
      if e.imports.contains(name) {
        return false
      }
      let cand = e.pkg_path.copy()
      cand.push(name)
      if self.has_node(cand) {
        return false
      }
    }
    None => ()
  }
  true
}

///|
/// Extracts a static dotted name from a callee term (`Var` or `Ref` of static
/// segments), or `None` if dynamic.
fn extract_dotted_name(term : @ast.Term) -> Array[String]? {
  match term.kind() {
    Var(id) => Some([id.to_string()])
    Ref(r) => {
      let out : Array[String] = []
      match r.base().kind() {
        Var(id) => out.push(id.to_string())
        _ => return None
      }
      for seg in r.segments() {
        match seg {
          Dot(k) => out.push(k.to_string())
          Bracket(t) =>
            match t.kind() {
              String(s) => out.push(s)
              _ => return None
            }
        }
      }
      Some(out)
    }
    _ => None
  }
}

///|
/// Resolves a call target `callee` to a user function, `walk`, or a registered
/// built-in.
fn ScopeCtx::resolve_callee(
  self : ScopeCtx,
  callee : @ast.Term,
  with_mods : ReadOnlyArray[@ast.WithModifier],
) -> ResolvedCallee raise CompileError {
  guard extract_dotted_name(callee) is Some(parts) else {
    raise UndefinedFunction(name="", span=callee.span())
  }
  let raw_dotted = parts.join(".")
  if raw_dotted == "walk" {
    return CalleeWalk
  }
  // 1. Resolve via `data.*`
  if parts[0] == "data" && parts.length() >= 2 {
    let data_path : Array[String] = []
    for i in 1.. Unit {
  match term.kind() {
    Var(id) => {
      let name = id.to_string()
      if name != "_" && !out.contains(name) {
        out.set(name, term.span())
      }
    }
    Array(items) | Set(items) =>
      for item in items {
        collect_param_vars(item, out)
      }
    Object(pairs) =>
      for pair in pairs {
        collect_param_vars(pair.0, out)
        collect_param_vars(pair.1, out)
      }
    _ => ()
  }
}

///|
/// Collects all variables appearing in a pattern term (`x`, `[a, b]`, `{k: v}`).
fn collect_pattern_vars(
  term : @ast.Term,
  scope : ScopeCtx,
  out : Map[String, @syntax.SourceSpan],
) -> Unit {
  match term.kind() {
    Var(id) => {
      let name = id.to_string()
      if name != "_" && scope.is_local_var(name) {
        if !out.contains(name) {
          out.set(name, term.span())
        }
      }
    }
    Array(items) | Set(items) =>
      for item in items {
        collect_pattern_vars(item, scope, out)
      }
    Object(pairs) =>
      for pair in pairs {
        collect_pattern_vars(pair.0, scope, out)
        collect_pattern_vars(pair.1, scope, out)
      }
    _ => ()
  }
}

///|
/// Collects explicitly declared local variables in a block (`some`, `:=`).
fn collect_declared_locals(
  exprs : ArrayView[@ast.Expr],
  check_duplicates : Bool,
) -> Map[String, Unit] raise CompileError {
  let decls : Map[String, Unit] = Map([])
  let assigned : Map[String, @syntax.SourceSpan] = Map([])
  fn add_assign_vars(term : @ast.Term) -> Unit raise CompileError {
    match term.kind() {
      Var(id) => {
        let name = id.to_string()
        if name != "_" {
          if check_duplicates && assigned.contains(name) {
            raise DuplicateLocalVar(name~, span=term.span())
          }
          assigned.set(name, term.span())
          decls.set(name, ())
        }
      }
      Array(items) | Set(items) =>
        for item in items {
          add_assign_vars(item)
        }
      Object(pairs) =>
        for pair in pairs {
          add_assign_vars(pair.0)
          add_assign_vars(pair.1)
        }
      _ => ()
    }
  }
  fn add_some_vars(term : @ast.Term) -> Unit {
    match term.kind() {
      Var(id) => {
        let name = id.to_string()
        if name != "_" {
          decls.set(name, ())
        }
      }
      Array(items) | Set(items) =>
        for item in items {
          add_some_vars(item)
        }
      Object(pairs) =>
        for pair in pairs {
          add_some_vars(pair.0)
          add_some_vars(pair.1)
        }
      _ => ()
    }
  }
  for expr in exprs {
    match expr.kind() {
      Assign(lhs, _) => add_assign_vars(lhs)
      SomeDecl(first~, rest~) => {
        if first.to_string() != "_" {
          decls.set(first.to_string(), ())
        }
        for id in rest {
          if id.to_string() != "_" {
            decls.set(id.to_string(), ())
          }
        }
      }
      SomeIn(key~, value~, ..) => {
        if key is Some(k) {
          add_some_vars(k)
        }
        add_some_vars(value)
      }
      _ => ()
    }
  }
  decls
}

///|
/// Collects free local variables in `term`:
/// - `req` receives variables that MUST be grounded before evaluating `term`.
/// - `ref_binds` receives bare local variables in ref bracket positions (`base[k]`)
///   which `term` itself can ground by scanning once `base` is grounded.
fn collect_term_vars(
  term : @ast.Term,
  scope : ScopeCtx,
  grounded : Map[String, Unit],
  req : Map[String, @syntax.SourceSpan],
  ref_binds : Map[String, @syntax.SourceSpan],
) -> Unit raise CompileError {
  match term.kind() {
    Null | Bool(_) | Number(_) | String(_) => ()
    Var(id) => {
      let name = id.to_string()
      if name != "_" && scope.is_local_var(name) && !grounded.contains(name) {
        if !req.contains(name) {
          req.set(name, term.span())
        }
      }
    }
    Ref(r) => {
      collect_term_vars(r.base(), scope, grounded, req, ref_binds)
      for seg in r.segments() {
        match seg {
          Dot(_) => ()
          Bracket(idx) =>
            match idx.kind() {
              Var(id) => {
                let name = id.to_string()
                if name != "_" &&
                  scope.is_local_var(name) &&
                  !grounded.contains(name) {
                  if !ref_binds.contains(name) {
                    ref_binds.set(name, idx.span())
                  }
                }
              }
              Array(_) | Object(_) => {
                let pvars : Map[String, @syntax.SourceSpan] = Map([])
                collect_pattern_vars(idx, scope, pvars)
                let sub_req : Map[String, @syntax.SourceSpan] = Map([])
                let sub_rb : Map[String, @syntax.SourceSpan] = Map([])
                collect_term_vars(idx, scope, grounded, sub_req, sub_rb)
                for name, sp in sub_req {
                  if pvars.contains(name) {
                    if !ref_binds.contains(name) {
                      ref_binds.set(name, sp)
                    }
                  } else if !req.contains(name) {
                    req.set(name, sp)
                  }
                }
                for name, sp in sub_rb {
                  if !ref_binds.contains(name) {
                    ref_binds.set(name, sp)
                  }
                }
              }
              _ => collect_term_vars(idx, scope, grounded, req, ref_binds)
            }
        }
      }
    }
    Call(callee~, args~) => {
      // Callee itself is static (function or builtin); inspect args.
      let _ = callee
      for arg in args {
        collect_term_vars(arg, scope, grounded, req, ref_binds)
      }
    }
    UnaryNeg(inner) => collect_term_vars(inner, scope, grounded, req, ref_binds)
    Binary(_, lhs, rhs) => {
      collect_term_vars(lhs, scope, grounded, req, ref_binds)
      collect_term_vars(rhs, scope, grounded, req, ref_binds)
    }
    In(key~, value~, domain~) => {
      if key is Some(k) {
        collect_term_vars(k, scope, grounded, req, ref_binds)
      }
      collect_term_vars(value, scope, grounded, req, ref_binds)
      collect_term_vars(domain, scope, grounded, req, ref_binds)
    }
    Array(items) | Set(items) =>
      for item in items {
        collect_term_vars(item, scope, grounded, req, ref_binds)
      }
    Object(pairs) =>
      for pair in pairs {
        collect_term_vars(pair.0, scope, grounded, req, ref_binds)
        collect_term_vars(pair.1, scope, grounded, req, ref_binds)
      }
    TemplateString(parts~, ..) =>
      for part in parts {
        match part {
          Literal(_) => ()
          Expr(e) => {
            let inner_req : Map[String, @syntax.SourceSpan] = Map([])
            let inner_binds : Map[String, @syntax.SourceSpan] = Map([])
            collect_expr_outer_deps(e, scope, grounded, inner_req, inner_binds)
            for k, sp in inner_req {
              if !grounded.contains(k) && !req.contains(k) {
                req.set(k, sp)
              }
            }
          }
        }
      }
    ArrayComprehension(term=elem, body~) | SetComprehension(term=elem, body~) => {
      let outer_deps = compute_body_outer_deps(
        body.exprs(),
        [elem],
        scope,
        grounded,
      )
      for k, sp in outer_deps {
        if !grounded.contains(k) && !req.contains(k) {
          req.set(k, sp)
        }
      }
    }
    ObjectComprehension(key~, value~, body~) => {
      let outer_deps = compute_body_outer_deps(
        body.exprs(),
        [key, value],
        scope,
        grounded,
      )
      for k, sp in outer_deps {
        if !grounded.contains(k) && !req.contains(k) {
          req.set(k, sp)
        }
      }
    }
  }
}

///|
/// Computes outer-scope variables referenced by a nested body (comprehension
/// or `every`) that are not locally bound by that body.
fn compute_body_outer_deps(
  exprs : ReadOnlyArray[@ast.Expr],
  head_terms : Array[@ast.Term],
  outer_scope : ScopeCtx,
  outer_grounded : Map[String, Unit],
) -> Map[String, @syntax.SourceSpan] raise CompileError {
  let inner_decls = collect_declared_locals(exprs, false)
  let inner_scope = outer_scope.child_with_locals(inner_decls)
  // Collect all variables that appear anywhere inside the body or head, minus
  // variables grounded inside the body itself.
  let mentioned : Map[String, @syntax.SourceSpan] = Map([])
  let bound_inside : Map[String, Unit] = Map([])
  for k, _ in inner_decls {
    bound_inside.set(k, ())
  }
  fn scan_term_all(t : @ast.Term) -> Unit raise CompileError {
    let r : Map[String, @syntax.SourceSpan] = Map([])
    let rb : Map[String, @syntax.SourceSpan] = Map([])
    collect_term_vars(t, inner_scope, Map([]), r, rb)
    for k, sp in r {
      if !mentioned.contains(k) {
        mentioned.set(k, sp)
      }
    }
    for k, _ in rb {
      bound_inside.set(k, ())
    }
  }
  for e in exprs {
    for wm in e.with_modifiers() {
      scan_term_all(wm.value())
    }
    match e.kind() {
      Term(t) =>
        if t.kind() is Call(callee~, args~) {
          let is_rel = try {
            match inner_scope.resolve_callee(callee, e.with_modifiers()) {
              CalleeWalk => args.length() == 2
              CalleeBuiltin(arity=Fixed(n), ..) => args.length() == n + 1
              CalleeUserFunc(arity~, ..) =>
                arity >= 0 && args.length() == arity + 1
              _ => false
            }
          } catch {
            _ => false
          }
          if is_rel {
            for i in 0..<(args.length() - 1) {
              scan_term_all(args[i])
            }
            let out_vars : Map[String, @syntax.SourceSpan] = Map([])
            collect_pattern_vars(args[args.length() - 1], inner_scope, out_vars)
            for k, _ in out_vars {
              bound_inside.set(k, ())
            }
          } else {
            scan_term_all(t)
          }
        } else {
          scan_term_all(t)
        }
      Assign(lhs, rhs) => {
        let pvars : Map[String, @syntax.SourceSpan] = Map([])
        collect_pattern_vars(lhs, inner_scope, pvars)
        for k, _ in pvars {
          bound_inside.set(k, ())
        }
        scan_term_all(rhs)
      }
      Unify(lhs, rhs) => {
        // Variables that are ONLY in outer_grounded or appear on one side:
        // treat any var mentioned in unify that isn't already outer_grounded
        // as potentially bound inside if the other side is ground/outer.
        let lv : Map[String, @syntax.SourceSpan] = Map([])
        let rv : Map[String, @syntax.SourceSpan] = Map([])
        collect_pattern_vars(lhs, inner_scope, lv)
        collect_pattern_vars(rhs, inner_scope, rv)
        for k, sp in lv {
          if outer_grounded.contains(k) {
            if !mentioned.contains(k) {
              mentioned.set(k, sp)
            }
          } else if rv.is_empty() {
            bound_inside.set(k, ())
          } else if !mentioned.contains(k) {
            mentioned.set(k, sp)
          }
        }
        for k, sp in rv {
          if outer_grounded.contains(k) {
            if !mentioned.contains(k) {
              mentioned.set(k, sp)
            }
          } else if lv.is_empty() {
            bound_inside.set(k, ())
          } else if !mentioned.contains(k) {
            mentioned.set(k, sp)
          }
        }
        scan_term_all(lhs)
        scan_term_all(rhs)
      }
      Not(inner) => {
        let r : Map[String, @syntax.SourceSpan] = Map([])
        let rb : Map[String, @syntax.SourceSpan] = Map([])
        collect_expr_outer_deps(
          @ast.Expr::Expr(kind=inner, with_modifiers=[], span=e.span()),
          inner_scope,
          {},
          r,
          rb,
        )
        for k, sp in r {
          if !mentioned.contains(k) {
            mentioned.set(k, sp)
          }
        }
      }
      SomeDecl(_) => ()
      SomeIn(key~, value~, domain~) => {
        if key is Some(k) {
          let kv : Map[String, @syntax.SourceSpan] = Map([])
          collect_pattern_vars(k, inner_scope, kv)
          for n, _ in kv {
            bound_inside.set(n, ())
          }
        }
        let vv : Map[String, @syntax.SourceSpan] = Map([])
        collect_pattern_vars(value, inner_scope, vv)
        for n, _ in vv {
          bound_inside.set(n, ())
        }
        scan_term_all(domain)
      }
      Every(key~, value~, domain~, body~) => {
        scan_term_all(domain)
        let extra : Map[String, Unit] = Map([])
        if key is Some(k) && k.to_string() != "_" {
          extra.set(k.to_string(), ())
        }
        if value.to_string() != "_" {
          extra.set(value.to_string(), ())
        }
        let every_deps = compute_body_outer_deps(
          body.exprs(),
          [],
          inner_scope.child_with_locals(extra),
          outer_grounded,
        )
        for k, sp in every_deps {
          if !extra.contains(k) && !mentioned.contains(k) {
            mentioned.set(k, sp)
          }
        }
      }
    }
  }
  for ht in head_terms {
    scan_term_all(ht)
  }
  // Run a fixpoint pass over all `Unify` expressions inside this body using
  // `outer_grounded U bound_inside` so chained unifications like
  // `i = [z | ...]; i = y` or `a = arr[_]; [a, b] = pair` accurately classify
  // locally-grounded variables.
  let sim_grounded : Map[String, Unit] = Map([])
  for k, _ in outer_grounded {
    sim_grounded.set(k, ())
  }
  for k, _ in bound_inside {
    sim_grounded.set(k, ())
  }
  let mut changed = true
  while changed {
    changed = false
    for e in exprs {
      match try_schedule_expr(e, inner_scope, sim_grounded) {
        Some(newly) =>
          for v in newly {
            if !sim_grounded.contains(v) {
              sim_grounded.set(v, ())
              if !outer_grounded.contains(v) {
                bound_inside.set(v, ())
              }
              changed = true
            }
          }
        None => ()
      }
    }
  }
  let deps : Map[String, @syntax.SourceSpan] = Map([])
  for k, sp in mentioned {
    if !bound_inside.contains(k) {
      deps.set(k, sp)
    }
  }
  deps
}

///|

///|
fn is_with_builtin_ref(term : @ast.Term, scope : ScopeCtx) -> Bool {
  match extract_dotted_name(term) {
    Some(parts) => {
      let dotted = parts.join(".")
      scope.builtins.lookup(dotted) is Some(_) || dotted == "walk"
    }
    None => false
  }
}

///|
fn collect_expr_outer_deps(
  expr : @ast.Expr,
  scope : ScopeCtx,
  grounded : Map[String, Unit],
  req : Map[String, @syntax.SourceSpan],
  ref_binds : Map[String, @syntax.SourceSpan],
) -> Unit raise CompileError {
  for wm in expr.with_modifiers() {
    if !is_with_builtin_ref(wm.value(), scope) {
      collect_term_vars(wm.value(), scope, grounded, req, ref_binds)
    }
  }
  match expr.kind() {
    Term(t) => collect_term_vars(t, scope, grounded, req, ref_binds)
    Assign(_, rhs) => collect_term_vars(rhs, scope, grounded, req, ref_binds)
    Unify(lhs, rhs) => {
      collect_term_vars(lhs, scope, grounded, req, ref_binds)
      collect_term_vars(rhs, scope, grounded, req, ref_binds)
    }
    Not(inner) =>
      collect_expr_outer_deps(
        @ast.Expr::Expr(kind=inner, with_modifiers=[], span=expr.span()),
        scope,
        grounded,
        req,
        ref_binds,
      )
    SomeDecl(_) => ()
    SomeIn(domain~, ..) =>
      collect_term_vars(domain, scope, grounded, req, ref_binds)
    Every(key~, value~, domain~, body~) => {
      collect_term_vars(domain, scope, grounded, req, ref_binds)
      let extra : Map[String, Unit] = Map([])
      if key is Some(k) && k.to_string() != "_" {
        extra.set(k.to_string(), ())
      }
      if value.to_string() != "_" {
        extra.set(value.to_string(), ())
      }
      let deps = compute_body_outer_deps(
        body.exprs(),
        [],
        scope.child_with_locals(extra),
        grounded,
      )
      for k, sp in deps {
        if !extra.contains(k) && !grounded.contains(k) && !req.contains(k) {
          req.set(k, sp)
        }
      }
    }
  }
}

///|
fn terms_same_literal_key(a : @ast.Term, b : @ast.Term) -> Bool {
  match (a.kind(), b.kind()) {
    (Null, Null) => true
    (Bool(x), Bool(y)) => x == y
    (Number(x), Number(y)) => x.raw() == y.raw()
    (String(x), String(y)) => x == y
    (Var(x), Var(y)) => x.to_string() == y.to_string()
    _ => false
  }
}

///|
/// Checks whether `lhs = rhs` can be scheduled given `grounded`, and if so
/// returns the newly grounded variable names (supporting pairwise structural
/// unification like `[a, 2] = [1, b]` and `[a, b] = [1, a]`).
fn try_schedule_unify(
  lhs : @ast.Term,
  rhs : @ast.Term,
  scope : ScopeCtx,
  grounded : Map[String, Unit],
) -> Array[String]? raise CompileError {
  let sim : Map[String, Unit] = Map([])
  for k, _ in grounded {
    sim.set(k, ())
  }
  let pairs : Array[(@ast.Term, @ast.Term)] = [(lhs, rhs)]
  fn flatten_pair(a : @ast.Term, b : @ast.Term) -> Unit {
    match (a.kind(), b.kind()) {
      (Array(xs), Array(ys)) if xs.length() == ys.length() =>
        for i in 0.. {
        // Match constant-key entries directly when possible (ignoring source spans).
        let mut all_matched = true
        let matched : Array[(@ast.Term, @ast.Term)] = []
        for x in xs {
          let mut found = false
          for y in ys {
            if terms_same_literal_key(x.0, y.0) {
              matched.push((x.1, y.1))
              found = true
              break
            }
          }
          if !found {
            all_matched = false
            break
          }
        }
        if all_matched {
          for m in matched {
            flatten_pair(m.0, m.1)
          }
        } else {
          pairs.push((a, b))
        }
      }
      _ => pairs.push((a, b))
    }
  }
  let _ = pairs.pop()
  flatten_pair(lhs, rhs)

  let mut progress = true
  while progress {
    progress = false
    for pair in pairs {
      let l_req : Map[String, @syntax.SourceSpan] = Map([])
      let l_rb : Map[String, @syntax.SourceSpan] = Map([])
      collect_term_vars(pair.0, scope, sim, l_req, l_rb)
      let r_req : Map[String, @syntax.SourceSpan] = Map([])
      let r_rb : Map[String, @syntax.SourceSpan] = Map([])
      collect_term_vars(pair.1, scope, sim, r_req, r_rb)
      if l_req.is_empty() {
        for k, _ in l_rb {
          if !sim.contains(k) {
            sim.set(k, ())
            progress = true
          }
        }
        let r_pat : Map[String, @syntax.SourceSpan] = Map([])
        collect_pattern_vars(pair.1, scope, r_pat)
        if r_req.length() <= r_pat.length() {
          let mut all_in_pat = true
          for k, _ in r_req {
            if !r_pat.contains(k) {
              all_in_pat = false
              break
            }
          }
          if all_in_pat {
            for k, _ in r_pat {
              if !sim.contains(k) {
                sim.set(k, ())
                progress = true
              }
            }
          }
        }
      }
      if r_req.is_empty() {
        for k, _ in r_rb {
          if !sim.contains(k) {
            sim.set(k, ())
            progress = true
          }
        }
        let l_pat : Map[String, @syntax.SourceSpan] = Map([])
        collect_pattern_vars(pair.0, scope, l_pat)
        if l_req.length() <= l_pat.length() {
          let mut all_in_pat = true
          for k, _ in l_req {
            if !l_pat.contains(k) {
              all_in_pat = false
              break
            }
          }
          if all_in_pat {
            for k, _ in l_pat {
              if !sim.contains(k) {
                sim.set(k, ())
                progress = true
              }
            }
          }
        }
      }
    }
  }

  // Verify every pair is now fully grounded.
  for pair in pairs {
    let l_req : Map[String, @syntax.SourceSpan] = Map([])
    let l_rb : Map[String, @syntax.SourceSpan] = Map([])
    collect_term_vars(pair.0, scope, sim, l_req, l_rb)
    let r_req : Map[String, @syntax.SourceSpan] = Map([])
    let r_rb : Map[String, @syntax.SourceSpan] = Map([])
    collect_term_vars(pair.1, scope, sim, r_req, r_rb)
    if !l_req.is_empty() || !r_req.is_empty() {
      return None
    }
    for k, _ in l_rb {
      sim.set(k, ())
    }
    for k, _ in r_rb {
      sim.set(k, ())
    }
  }

  let newly : Array[String] = []
  for k, _ in sim {
    if !grounded.contains(k) {
      newly.push(k)
    }
  }
  Some(newly)
}

///|
/// Checks whether `expr` can be scheduled given currently `grounded` variables.
/// If ready, returns `Some(newly_grounded_vars)`; otherwise `None`.
fn try_schedule_expr(
  expr : @ast.Expr,
  scope : ScopeCtx,
  grounded : Map[String, Unit],
) -> Array[String]? raise CompileError {
  // Check all `with` modifier value expressions are grounded first.
  for wm in expr.with_modifiers() {
    if !is_with_builtin_ref(wm.value(), scope) {
      let req : Map[String, @syntax.SourceSpan] = Map([])
      let rb : Map[String, @syntax.SourceSpan] = Map([])
      collect_term_vars(wm.value(), scope, grounded, req, rb)
      if !req.is_empty() {
        return None
      }
    }
  }
  match expr.kind() {
    SomeDecl(_) => Some([])
    Assign(lhs, rhs) => {
      let req : Map[String, @syntax.SourceSpan] = Map([])
      let rb : Map[String, @syntax.SourceSpan] = Map([])
      collect_term_vars(rhs, scope, grounded, req, rb)
      if !req.is_empty() {
        return None
      }
      let out : Array[String] = []
      for k, _ in rb {
        out.push(k)
      }
      let pvars : Map[String, @syntax.SourceSpan] = Map([])
      collect_pattern_vars(lhs, scope, pvars)
      for k, _ in pvars {
        out.push(k)
      }
      Some(out)
    }
    Unify(lhs, rhs) => try_schedule_unify(lhs, rhs, scope, grounded)
    SomeIn(key~, value~, domain~) => {
      let req : Map[String, @syntax.SourceSpan] = Map([])
      let rb : Map[String, @syntax.SourceSpan] = Map([])
      collect_term_vars(domain, scope, grounded, req, rb)
      if !req.is_empty() {
        return None
      }
      let out : Array[String] = []
      for k, _ in rb {
        out.push(k)
      }
      if key is Some(k) {
        let kv : Map[String, @syntax.SourceSpan] = Map([])
        collect_pattern_vars(k, scope, kv)
        for n, _ in kv {
          out.push(n)
        }
      }
      let vv : Map[String, @syntax.SourceSpan] = Map([])
      collect_pattern_vars(value, scope, vv)
      for n, _ in vv {
        out.push(n)
      }
      Some(out)
    }
    Every(key~, value~, domain~, body~) => {
      let req : Map[String, @syntax.SourceSpan] = Map([])
      let rb : Map[String, @syntax.SourceSpan] = Map([])
      collect_term_vars(domain, scope, grounded, req, rb)
      let extra : Map[String, Unit] = Map([])
      if key is Some(k) && k.to_string() != "_" {
        extra.set(k.to_string(), ())
      }
      if value.to_string() != "_" {
        extra.set(value.to_string(), ())
      }
      let deps = compute_body_outer_deps(
        body.exprs(),
        [],
        scope.child_with_locals(extra),
        grounded,
      )
      for k, sp in deps {
        if !extra.contains(k) && !grounded.contains(k) && !req.contains(k) {
          req.set(k, sp)
        }
      }
      if !req.is_empty() {
        return None
      }
      Some([])
    }
    Not(inner) => {
      let inner_expr = @ast.Expr::Expr(
        kind=inner,
        with_modifiers=[],
        span=expr.span(),
      )
      // Negated expression must have all non-ref-key vars grounded in outer scope.
      let req : Map[String, @syntax.SourceSpan] = Map([])
      let rb : Map[String, @syntax.SourceSpan] = Map([])
      collect_expr_outer_deps(inner_expr, scope, grounded, req, rb)
      if !req.is_empty() {
        return None
      }
      Some([])
    }
    Term(t) => {
      // Check relation-style call `walk(x, out)` or `f(a1, ..., aN, out)`.
      match t.kind() {
        Call(callee~, args~) => {
          let resolved = scope.resolve_callee(callee, expr.with_modifiers())
          let is_relation_call = match resolved {
            CalleeWalk => args.length() == 2
            CalleeBuiltin(arity~, ..) =>
              match arity {
                Fixed(n) => args.length() == n + 1
                Variadic => false
              }
            CalleeUserFunc(arity~, ..) =>
              arity >= 0 && args.length() == arity + 1
          }
          if is_relation_call {
            let req : Map[String, @syntax.SourceSpan] = Map([])
            let rb : Map[String, @syntax.SourceSpan] = Map([])
            for i in 0..<(args.length() - 1) {
              collect_term_vars(args[i], scope, grounded, req, rb)
            }
            if !req.is_empty() {
              return None
            }
            let out : Array[String] = []
            for k, _ in rb {
              out.push(k)
            }
            let out_vars : Map[String, @syntax.SourceSpan] = Map([])
            collect_pattern_vars(args[args.length() - 1], scope, out_vars)
            for k, _ in out_vars {
              out.push(k)
            }
            return Some(out)
          }
        }
        _ => ()
      }
      let req : Map[String, @syntax.SourceSpan] = Map([])
      let rb : Map[String, @syntax.SourceSpan] = Map([])
      collect_term_vars(t, scope, grounded, req, rb)
      if !req.is_empty() {
        return None
      }
      let out : Array[String] = []
      for k, _ in rb {
        out.push(k)
      }
      Some(out)
    }
  }
}

///|
/// Reorders `exprs` so producers run before consumers (preserving original
/// order among ready expressions) and verifies variable safety.
fn schedule_exprs(
  exprs : ArrayView[@ast.Expr],
  scope : ScopeCtx,
  initial_grounded : Map[String, Unit],
) -> (Array[@ast.Expr], Map[String, Unit]) raise CompileError {
  let grounded : Map[String, Unit] = Map([])
  for k, _ in initial_grounded {
    grounded.set(k, ())
  }
  let n = exprs.length()
  let used = Array::make(n, false)
  let ordered : Array[@ast.Expr] = []

  let mut remaining = n
  while remaining > 0 {
    let mut picked = false
    for i in 0.. {
          used[i] = true
          remaining -= 1
          ordered.push(exprs[i])
          for v in newly {
            grounded.set(v, ())
          }
          picked = true
          break
        }
        None => ()
      }
    }
    if !picked {
      // Find the first ungrounded variable in the first remaining expression
      // to report an accurate `CompileError::UnsafeVar`.
      for i in 0.. Unit raise CompileError {
  let req : Map[String, @syntax.SourceSpan] = Map([])
  let rb : Map[String, @syntax.SourceSpan] = Map([])
  collect_term_vars(term, scope, grounded, req, rb)
  for name, span in req {
    raise UnsafeVar(name~, span~)
  }
  // In a rule head, an unbound ref key like `arr[i]` is ALSO unsafe if `i` wasn't grounded.
  for name, span in rb {
    if !grounded.contains(name) {
      raise UnsafeVar(name~, span~)
    }
  }
}

///|
/// Call-graph edge from one rule path to another.
priv struct DepEdge {
  target : String
  negated : Bool
  span : @syntax.SourceSpan
}

///|
/// Collects static rule/function dependencies from a term.
fn collect_term_deps(
  term : @ast.Term,
  scope : ScopeCtx,
  negated : Bool,
  edges : Array[DepEdge],
) -> Unit {
  fn record_path(path : Array[String], span : @syntax.SourceSpan) -> Unit {
    // Walk prefixes from longest to shortest to find the matching rule node.
    for len = path.length(); len >= 1; len = len - 1 {
      let prefix : Array[String] = []
      for i in 0..
            // Depending on a package depends on its child rules too when
            // materialized, record exact package path if leaf.
            if len == path.length() {
              edges.push({ target: format_data_path(prefix), negated, span, })
            }
          _ => {
            edges.push({ target: format_data_path(prefix), negated, span, })
            return
          }
        }
      }
    }
  }

  match term.kind() {
    Null | Bool(_) | Number(_) | String(_) => ()
    Var(id) => {
      let name = id.to_string()
      if !scope.is_local_var(name) && name != "input" && name != "data" {
        if scope.env is Some(e) {
          match e.imports.get(name) {
            Some(imp) if imp.root is ImportData =>
              record_path(imp.path, term.span())
            _ => {
              let sib = e.pkg_path.copy()
              sib.push(name)
              record_path(sib, term.span())
            }
          }
        }
      }
    }
    Ref(r) => {
      if extract_dotted_name(term) is Some(parts) {
        if parts[0] == "data" && parts.length() >= 2 {
          let p : Array[String] = []
          for i in 1.. {
                let p = imp.path.copy()
                for i in 1.. {
                let p = e.pkg_path.copy()
                for s in parts {
                  p.push(s)
                }
                record_path(p, term.span())
              }
            }
          }
        }
      } else {
        collect_term_deps(r.base(), scope, negated, edges)
      }
      for seg in r.segments() {
        if seg is Bracket(idx) {
          collect_term_deps(idx, scope, negated, edges)
        }
      }
    }
    Call(callee~, args~) => {
      collect_term_deps(callee, scope, negated, edges)
      for arg in args {
        collect_term_deps(arg, scope, negated, edges)
      }
    }
    UnaryNeg(inner) => collect_term_deps(inner, scope, negated, edges)
    Binary(_, a, b) => {
      collect_term_deps(a, scope, negated, edges)
      collect_term_deps(b, scope, negated, edges)
    }
    In(key~, value~, domain~) => {
      if key is Some(k) {
        collect_term_deps(k, scope, negated, edges)
      }
      collect_term_deps(value, scope, negated, edges)
      collect_term_deps(domain, scope, negated, edges)
    }
    Array(xs) | Set(xs) =>
      for x in xs {
        collect_term_deps(x, scope, negated, edges)
      }
    Object(pairs) =>
      for pair in pairs {
        collect_term_deps(pair.0, scope, negated, edges)
        collect_term_deps(pair.1, scope, negated, edges)
      }
    TemplateString(parts~, ..) =>
      for part in parts {
        if part is Expr(e) {
          collect_expr_deps(e, scope, negated, edges)
        }
      }
    ArrayComprehension(term=elem, body~) | SetComprehension(term=elem, body~) => {
      collect_term_deps(elem, scope, negated, edges)
      for e in body.exprs() {
        collect_expr_deps(e, scope, negated, edges)
      }
    }
    ObjectComprehension(key~, value~, body~) => {
      collect_term_deps(key, scope, negated, edges)
      collect_term_deps(value, scope, negated, edges)
      for e in body.exprs() {
        collect_expr_deps(e, scope, negated, edges)
      }
    }
  }
}

///|
fn collect_expr_deps(
  expr : @ast.Expr,
  scope : ScopeCtx,
  negated : Bool,
  edges : Array[DepEdge],
) -> Unit {
  for wm in expr.with_modifiers() {
    collect_term_deps(wm.value(), scope, negated, edges)
  }
  match expr.kind() {
    Term(t) => collect_term_deps(t, scope, negated, edges)
    Assign(_, rhs) => collect_term_deps(rhs, scope, negated, edges)
    Unify(lhs, rhs) => {
      collect_term_deps(lhs, scope, negated, edges)
      collect_term_deps(rhs, scope, negated, edges)
    }
    Not(inner) =>
      collect_expr_deps(
        @ast.Expr::Expr(kind=inner, with_modifiers=[], span=expr.span()),
        scope,
        true,
        edges,
      )
    SomeDecl(_) => ()
    SomeIn(domain~, ..) => collect_term_deps(domain, scope, negated, edges)
    Every(domain~, body~, ..) => {
      collect_term_deps(domain, scope, negated, edges)
      for e in body.exprs() {
        collect_expr_deps(e, scope, true, edges)
      }
    }
  }
}

///|
/// Builds the rule/function dependency graph and checks for direct/mutual
/// recursion (`CyclicRule`) and unstratified recursion through negation
/// (`UnstratifiedNegation`).
fn check_cycles(
  root : RawNode,
  builtins : @builtins.BuiltinRegistry,
) -> Unit raise CompileError {
  let graph : Map[String, Array[DepEdge]] = Map([])
  let all_nodes : Array[String] = []

  fn walk_tree(node : RawNode, path : Array[String]) -> Unit {
    let key = format_data_path(path)
    if !node.clauses.is_empty() {
      let edges : Array[DepEdge] = []
      for clause in node.clauses {
        let local_decls : 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 {
            local_decls.set(k, ())
          }
        }
        if clause.rule.body() is Some(b) {
          let b_decls = collect_declared_locals(b.exprs(), false) catch {
            _ => Map([])
          }
          for k, _ in b_decls {
            local_decls.set(k, ())
          }
        }
        let scope : ScopeCtx = {
          raw_root: Some(root),
          compiled_policy: None,
          env: Some(clause.module_env),
          builtins,
          declared_locals: local_decls,
        }
        for dk in clause.dynamic_keys {
          collect_term_deps(dk, scope, false, edges)
        }
        if clause.value_term is Some(vt) {
          collect_term_deps(vt, scope, false, edges)
        }
        if clause.rule.body() is Some(b) {
          for e in b.exprs() {
            collect_expr_deps(e, scope, false, edges)
          }
        }
        for eb in clause.rule.else_branches() {
          if eb.assigned() is Some(av) {
            collect_term_deps(av.value(), scope, false, edges)
          }
          if eb.body() is Some(b) {
            for e in b.exprs() {
              collect_expr_deps(e, scope, false, edges)
            }
          }
        }
      }
      graph.set(key, edges)
      all_nodes.push(key)
    }
    // Also link VirtualObject/Package to static children so a package cycle
    // through parent references is caught.
    let child_keys : Array[String] = []
    for k, _ in node.children {
      child_keys.push(k)
    }
    child_keys.sort()
    for ck in child_keys {
      match node.children.get(ck) {
        Some(child) => {
          let next_path = path.copy()
          next_path.push(ck)
          let child_key = format_data_path(next_path)
          if !path.is_empty() && !(child.kind is RawFunction(_)) {
            let parent_edges = match graph.get(key) {
              Some(e) => e
              None => {
                let fresh : Array[DepEdge] = []
                graph.set(key, fresh)
                all_nodes.push(key)
                fresh
              }
            }
            parent_edges.push({
              target: child_key,
              negated: false,
              span: child.span,
            })
          }
          walk_tree(child, next_path)
        }
        None => ()
      }
    }
  }
  walk_tree(root, [])

  // 3-color DFS: 0 = unvisited, 1 = visiting, 2 = done
  let color : Map[String, Int32] = Map([])
  let stack_nodes : Array[String] = []
  let stack_negated : Array[Bool] = []

  fn dfs(u : String) -> Unit raise CompileError {
    color.set(u, 1)
    stack_nodes.push(u)
    if graph.get(u) is Some(edges) {
      for edge in edges {
        let v = edge.target
        let st = match color.get(v) {
          Some(c) => c
          None => 0
        }
        if st == 1 {
          // Found cycle starting at `v` in `stack_nodes`.
          let mut start_idx = 0
          for i in 0..= start_idx && i < stack_negated.length() {
              if stack_negated[i] {
                has_neg = true
              }
            }
          }
          cycle.push(v)
          let ro = ReadOnlyArray::from_array(cycle)
          if has_neg {
            raise UnstratifiedNegation(cycle=ro, span=edge.span)
          } else {
            raise CyclicRule(cycle=ro, span=edge.span)
          }
        } else if st == 0 {
          stack_negated.push(edge.negated)
          dfs(v)
          let _ = stack_negated.pop()
        }
      }
    }
    let _ = stack_nodes.pop()
    color.set(u, 2)
  }

  for node in all_nodes {
    if !(color.get(node) is Some(2)) {
      dfs(node)
    }
  }
}