///|
/// Lazy Vertex / Closure-based CUE Evaluator.
///
/// Key architectural properties matching CUE's official ADT model:
/// 1. Structural conjuncts (`#Def & { ... }`, nested overrides across layers) are
///    merged into a single `StructVertex` BEFORE resolving sibling references,
///    so `#Base & { port: 9090 }` computes `url: "http://\(host):\(port)"` with 9090.
/// 2. Order-independent forward references with memoized `FieldCell`s and cycle detection.
/// 3. Faithful closedness semantics distinguishing `#Def & { extra: 1 }` (rejected)
///    from `{ #Def, extra: 1 }` (allowed embedding) and `...` (explicitly open).
/// 4. Field & list comprehensions (`for`, `if`, `let`), dynamic labels `(expr): v`,
///    pattern constraints `[pattern]: v`, string interpolation, and core stdlib imports.

///|
priv enum EvalState {
  Unevaluated
  Evaluating
  Evaluated(Value)
}

///|
priv struct FieldExprEntry {
  expr : Expr
  scope : Scope
  in_definition : Bool
}

///|
priv struct FieldCell {
  name : String
  is_definition : Bool
  is_hidden : Bool
  mut constraint : FieldConstraint
  entries : Array[FieldExprEntry]
  mut state : EvalState
}

///|
priv struct LetCell {
  expr : Expr
  scope : Scope
  mut state : EvalState
}

///|
priv struct Scope {
  parent : Scope?
  imports : Map[String, String] // alias -> stdlib path
  lets : Map[String, LetCell]
  fields : Map[String, FieldCell]
  field_order : Array[String]
}

///|
fn Scope::new(parent : Scope?, imports : Map[String, String]) -> Scope {
  { parent, imports, lets: Map([]), fields: Map([]), field_order: [], }
}

///|
fn Scope::lookup_import(self : Scope, alias_name : String) -> String? {
  match self.imports.get(alias_name) {
    Some(p) => Some(p)
    None =>
      match self.parent {
        Some(par) => par.lookup_import(alias_name)
        None => None
      }
  }
}

///|
priv struct RawStructSource {
  decls : Array[Decl]
  scope : Scope
  is_closed : Bool
}

///|
priv struct ClosedRule {
  allowed_names : Array[String]
  allowed_patterns : Array[PatternConstraint]
}

///|
fn ClosedRule::allows(self : ClosedRule, name : String) -> Bool {
  if self.allowed_names.contains(name) {
    return true
  }
  field_matches_any_pattern(name, self.allowed_patterns)
}

///|
/// Evaluate a single parsed CUE `File` into a `Value`.
pub fn eval_file(file : File) -> Value {
  eval_files([file])
}

///|
/// Evaluate and unify multiple parsed CUE `File`s in a shared root vertex.
pub fn eval_files(files : Array[File]) -> Value {
  let imports : Map[String, String] = Map([])
  for f in files {
    for imp in f.imports {
      let alias_name = match imp.alias_name {
        Some(a) => a
        None => default_import_alias(imp.path)
      }
      imports.set(alias_name, imp.path)
    }
  }
  let root_parent = Scope::new(None, imports)
  let sources : Array[RawStructSource] = []
  for f in files {
    sources.push({ decls: f.decls, scope: root_parent, is_closed: false, })
  }
  eval_struct_sources(sources, false)
}

///|
fn default_import_alias(path : String) -> String {
  let parts = path.split("/").collect()
  if parts.is_empty() {
    path
  } else {
    parts[parts.length() - 1].to_owned()
  }
}

///|
/// Try to decompose an expression into lazy struct conjuncts (without eagerly
/// resolving sibling references inside `#Definitions` or `{ ... }`).
fn try_collect_struct_sources(
  expr : Expr,
  scope : Scope,
  in_definition : Bool,
  out : Array[RawStructSource],
) -> Bool {
  match expr {
    StructExpr(decls, _) => {
      out.push({ decls, scope, is_closed: in_definition, })
      true
    }
    IdentExpr(name, _) =>
      match lookup_field_cell_in_scope(scope, name) {
        Some((cell, _owner)) => {
          // Only lazily inline if ALL entries of the target cell are struct-producing
          // and we aren't currently in a cycle on this cell!
          if cell.state is Evaluating || cell.entries.is_empty() {
            return false
          }
          let sub : Array[RawStructSource] = []
          let def_flag = in_definition || cell.is_definition
          for entry in cell.entries {
            if !try_collect_struct_sources(
                entry.expr,
                entry.scope,
                def_flag || entry.in_definition,
                sub,
              ) {
              return false
            }
          }
          for s in sub {
            out.push(s)
          }
          true
        }
        None => false
      }
    CallExpr(IdentExpr("close", _), [arg], _) => {
      let sub : Array[RawStructSource] = []
      if try_collect_struct_sources(arg, scope, true, sub) {
        for s in sub {
          out.push({ ..s, is_closed: true, })
        }
        true
      } else {
        false
      }
    }
    BinaryExpr(And, lhs, rhs, _) => {
      let sub : Array[RawStructSource] = []
      if try_collect_struct_sources(lhs, scope, in_definition, sub) &&
        try_collect_struct_sources(rhs, scope, in_definition, sub) {
        for s in sub {
          out.push(s)
        }
        true
      } else {
        false
      }
    }
    _ => false
  }
}

///|
fn lookup_field_cell_in_scope(
  scope : Scope,
  name : String,
) -> (FieldCell, Scope)? {
  match scope.fields.get(name) {
    Some(cell) => Some((cell, scope))
    None =>
      match scope.parent {
        Some(par) => lookup_field_cell_in_scope(par, name)
        None => None
      }
  }
}

///|
fn lookup_let_cell_in_scope(scope : Scope, name : String) -> LetCell? {
  match scope.lets.get(name) {
    Some(cell) => Some(cell)
    None =>
      match scope.parent {
        Some(par) => lookup_let_cell_in_scope(par, name)
        None => None
      }
  }
}

///|
fn ensure_field_cell(
  scope : Scope,
  name : String,
  constraint : FieldConstraint,
) -> FieldCell {
  match scope.fields.get(name) {
    Some(cell) => {
      cell.constraint = unify_field_constraint(cell.constraint, constraint)
      cell
    }
    None => {
      let cell : FieldCell = {
        name,
        is_definition: is_definition_name(name),
        is_hidden: is_hidden_name(name),
        constraint,
        entries: [],
        state: Unevaluated,
      }
      scope.fields.set(name, cell)
      scope.field_order.push(name)
      cell
    }
  }
}

///|
/// Core Vertex evaluator: merges a set of `RawStructSource` conjuncts into one
/// lexical scope, evaluates fields lazily with cycle detection, expands
/// embeddings & comprehensions, applies pattern constraints, and checks closedness.
fn eval_struct_sources(
  sources : Array[RawStructSource],
  force_closed : Bool,
) -> Value {
  let parent_scope : Scope? = if sources.is_empty() {
    None
  } else {
    Some(sources[0].scope)
  }
  let vscope = Scope::new(parent_scope, Map([]))

  let pending_embeds : Array[(Expr, Scope, Bool)] = []
  let pending_patterns : Array[(Expr, Expr, Scope, Int32)] = [] // (label_pat, val_expr, scope, group_idx)
  let pending_dynamic : Array[(Expr, FieldConstraint, Expr, Scope, Bool)] = []
  let pending_comps : Array[(Array[Clause], Array[Decl], Scope, Bool)] = []

  let group_allowed_names : Array[Array[String]] = []
  let group_is_closed : Array[Bool] = []
  let group_has_ellipsis : Array[Bool] = []
  let group_patterns : Array[Array[PatternConstraint]] = []

  // Pass 1: Register all static fields, let bindings, embeds, patterns, and comprehensions
  for g_idx = 0; g_idx < sources.length(); g_idx = g_idx + 1 {
    let src = sources[g_idx]
    let allowed : Array[String] = []
    let mut has_ell = false
    let mut embedded_closed = false
    group_allowed_names.push(allowed)
    group_is_closed.push(src.is_closed || force_closed)
    group_has_ellipsis.push(false)
    group_patterns.push([])

    // Collect declarations (including flattened struct embeddings inside this source!)
    register_decls_into_vertex(
      src.decls,
      src.scope,
      vscope,
      src.is_closed || force_closed,
      g_idx,
      allowed,
      pending_embeds,
      pending_patterns,
      pending_dynamic,
      pending_comps,
      fn() { has_ell = true },
      fn() { embedded_closed = true },
    )
    if embedded_closed {
      group_is_closed[g_idx] = true
    }
    group_has_ellipsis[g_idx] = has_ell
  }

  // Pass 2: Evaluate non-struct embeddings (or dynamic struct embeddings)
  let mut embedded_non_struct : Value? = None
  let extra_embedded_structs : Array[StructVal] = []
  for emb in pending_embeds {
    let (expr, emb_scope, _in_def) = emb
    let eval_scope = make_child_scope(vscope, emb_scope)
    let ev = eval_expr(expr, eval_scope)
    match ev {
      VBottom(_) => return ev
      VStruct(sv) => extra_embedded_structs.push(sv)
      VTop => ()
      other =>
        embedded_non_struct = match embedded_non_struct {
          None => Some(other)
          Some(prev) => {
            let u = unify(prev, other)
            if u.is_bottom() {
              return u
            }
            Some(u)
          }
        }
    }
  }

  // Pass 3: Evaluate dynamic labels `(expr): val`
  for dyn_entry in pending_dynamic {
    let (lbl_expr, constraint, val_expr, decl_scope, in_def) = dyn_entry
    let eval_scope = make_child_scope(vscope, decl_scope)
    let lbl_val = resolve_default_shallow(eval_expr(lbl_expr, eval_scope))
    match lbl_val {
      VString(name) => {
        let cell = ensure_field_cell(vscope, name, constraint)
        cell.entries.push({
          expr: val_expr,
          scope: decl_scope,
          in_definition: in_def || cell.is_definition,
        })
      }
      VBottom(_) => return lbl_val
      other =>
        return Value::bottom(
          EvalError,
          "dynamic field label must evaluate to string, got \{format_value(other)}",
          span=Some(lbl_expr.span()),
        )
    }
  }

  // Pass 4: Expand field comprehensions (`for ... { ... }`, `if ... { ... }`)
  for comp in pending_comps {
    let (clauses, body_decls, decl_scope, in_def) = comp
    let comp_scope = make_child_scope(vscope, decl_scope)
    let err = expand_field_comprehension(
      clauses, 0, comp_scope, body_decls, vscope, in_def, group_allowed_names,
    )
    match err {
      Some(b) => return b
      None => ()
    }
  }

  // Pass 5: Evaluate pattern constraints `[pat]: val`
  let all_patterns : Array[PatternConstraint] = []
  for pat_entry in pending_patterns {
    let (pat_expr, val_expr, decl_scope, g_idx) = pat_entry
    let eval_scope = make_child_scope(vscope, decl_scope)
    let pat_val = eval_expr(pat_expr, eval_scope)
    let rhs_val = eval_expr(val_expr, eval_scope)
    let pc : PatternConstraint = { label_pattern: pat_val, value: rhs_val, }
    all_patterns.push(pc)
    if g_idx >= 0 && g_idx < group_patterns.length() {
      group_patterns[g_idx].push(pc)
    }
  }

  // Pass 6: Evaluate all FieldCells in deterministic order
  let out_fields : Array[StructField] = []
  for name in vscope.field_order {
    let cell = vscope.fields.get(name).unwrap()
    let mut val = eval_field_cell(cell, vscope)
    // Apply pattern constraints to regular (non-definition, non-hidden) fields
    if !cell.is_definition && !cell.is_hidden {
      for pc in all_patterns {
        if !unify(pc.label_pattern, VString(name)).is_bottom() {
          val = unify(val, pc.value)
        }
      }
    }
    out_fields.push({
      name,
      value: val,
      constraint: cell.constraint,
      is_definition: cell.is_definition,
      is_hidden: cell.is_hidden,
    })
  }

  // Build closed rules for each closed conjunct group (excluding groups with `...`)
  let closed_rules : Array[ClosedRule] = []
  let mut any_closed = force_closed
  for g_idx = 0; g_idx < group_is_closed.length(); g_idx = g_idx + 1 {
    if group_is_closed[g_idx] && !group_has_ellipsis[g_idx] {
      any_closed = true
      closed_rules.push({
        allowed_names: group_allowed_names[g_idx],
        allowed_patterns: group_patterns[g_idx],
      })
    }
  }

  // Enforce closedness across all closed conjunct groups
  for f in out_fields {
    if f.is_definition || f.is_hidden || f.constraint == Optional {
      continue
    }
    for rule in closed_rules {
      if !rule.allows(f.name) {
        return Value::bottom(
          ClosedStructError,
          "field '\{f.name}' not allowed in closed struct",
          path=[f.name],
        )
      }
    }
  }

  // Verify no regular field mixes with non-struct embed
  match embedded_non_struct {
    Some(e) =>
      for f in out_fields {
        if !f.is_definition && !f.is_hidden && f.constraint == Regular {
          return Value::bottom(
            ConflictError,
            "cannot mix embedded value \{format_value(e)} with regular field '\{f.name}'",
          )
        }
      }
    None => ()
  }

  let mut result : Value = VStruct({
    fields: out_fields,
    patterns: all_patterns,
    is_closed: any_closed,
    embed: embedded_non_struct,
  })

  // Unify any dynamic struct embeddings that weren't statically inlined
  for sv in extra_embedded_structs {
    result = unify(result, VStruct(sv))
  }

  result
}

///|
fn register_decls_into_vertex(
  decls : Array[Decl],
  decl_scope : Scope,
  vscope : Scope,
  in_definition : Bool,
  g_idx : Int32,
  allowed : Array[String],
  pending_embeds : Array[(Expr, Scope, Bool)],
  pending_patterns : Array[(Expr, Expr, Scope, Int32)],
  pending_dynamic : Array[(Expr, FieldConstraint, Expr, Scope, Bool)],
  pending_comps : Array[(Array[Clause], Array[Decl], Scope, Bool)],
  on_ellipsis : () -> Unit,
  on_closed : () -> Unit,
) -> Unit {
  for decl in decls {
    match decl {
      EllipsisDecl(_) => on_ellipsis()
      LetDecl(name, expr, _) =>
        vscope.lets.set(name, { expr, scope: decl_scope, state: Unevaluated, })
      FieldDecl(field) =>
        match field.label {
          IdentLabel(name) | StringLabel(name) => {
            if !allowed.contains(name) {
              allowed.push(name)
            }
            let cell = ensure_field_cell(vscope, name, field.constraint)
            cell.entries.push({
              expr: field.value,
              scope: decl_scope,
              in_definition: in_definition || cell.is_definition,
            })
          }
          DynamicLabel(lbl_expr) =>
            pending_dynamic.push(
              (
                lbl_expr,
                field.constraint,
                field.value,
                decl_scope,
                in_definition,
              ),
            )
          PatternLabel(pat_expr) =>
            pending_patterns.push((pat_expr, field.value, decl_scope, g_idx))
        }
      ComprehensionDecl(clauses, body, _) =>
        pending_comps.push((clauses, body, decl_scope, in_definition))
      EmbedDecl(expr, _) => {
        // Try statically inlining embedded struct/definition into THIS conjunct group
        // so `{ #Def, extra: 1 }` unites `#Def`'s allowed fields with `extra`!
        let emb_sources : Array[RawStructSource] = []
        if try_collect_struct_sources(
            expr, decl_scope, in_definition, emb_sources,
          ) {
          for es in emb_sources {
            if es.is_closed {
              on_closed()
            }
            register_decls_into_vertex(
              es.decls,
              es.scope,
              vscope,
              es.is_closed || in_definition,
              g_idx,
              allowed,
              pending_embeds,
              pending_patterns,
              pending_dynamic,
              pending_comps,
              on_ellipsis,
              on_closed,
            )
          }
        } else {
          pending_embeds.push((expr, decl_scope, in_definition))
        }
      }
    }
  }
}

///|
/// Creates a lookup scope that checks `vscope` first, then falls back to `decl_scope`
/// (critical when a definition `#Def` defined in an outer/sibling scope is unified
/// into a different struct!).
fn make_child_scope(vscope : Scope, decl_scope : Scope) -> Scope {
  // Share vscope's fields/lets while linking to decl_scope as parent if different
  if physical_equal(vscope, decl_scope) {
    vscope
  } else {
    {
      parent: Some(decl_scope),
      imports: vscope.imports,
      lets: vscope.lets,
      fields: vscope.fields,
      field_order: vscope.field_order,
    }
  }
}

///|
fn eval_field_cell(cell : FieldCell, vscope : Scope) -> Value {
  match cell.state {
    Evaluated(v) => return v
    Evaluating =>
      return Value::bottom(
        CycleError,
        "cyclic reference to field '\{cell.name}'",
      )
    Unevaluated => ()
  }
  cell.state = Evaluating

  // Check if ALL entries are struct-producing so we can merge them into ONE unified StructVertex!
  let struct_sources : Array[RawStructSource] = []
  let mut all_structs = !cell.entries.is_empty()
  for entry in cell.entries {
    let eval_scope = make_child_scope(vscope, entry.scope)
    if !try_collect_struct_sources(
        entry.expr,
        eval_scope,
        entry.in_definition || cell.is_definition,
        struct_sources,
      ) {
      all_structs = false
      break
    }
  }

  let val : Value = if all_structs && !struct_sources.is_empty() {
    eval_struct_sources(struct_sources, cell.is_definition)
  } else {
    let mut acc : Value = VTop
    for entry in cell.entries {
      let eval_scope = make_child_scope(vscope, entry.scope)
      let v = eval_expr(entry.expr, eval_scope)
      let v2 = if entry.in_definition || cell.is_definition {
        close_value(v)
      } else {
        v
      }
      acc = unify(acc, v2)
    }
    acc
  }

  cell.state = Evaluated(val)
  val
}

///|
fn eval_let_cell(cell : LetCell, vscope : Scope) -> Value {
  match cell.state {
    Evaluated(v) => return v
    Evaluating =>
      return Value::bottom(CycleError, "cyclic reference in 'let' binding")
    Unevaluated => ()
  }
  cell.state = Evaluating
  let eval_scope = make_child_scope(vscope, cell.scope)
  let val = eval_expr(cell.expr, eval_scope)
  cell.state = Evaluated(val)
  val
}

///|
fn expand_field_comprehension(
  clauses : Array[Clause],
  idx : Int32,
  scope : Scope,
  body_decls : Array[Decl],
  target_vscope : Scope,
  in_def : Bool,
  group_allowed_names : Array[Array[String]],
) -> Value? {
  if idx >= clauses.length() {
    // Evaluate body declarations in current clause scope and merge into target_vscope!
    for decl in body_decls {
      match decl {
        FieldDecl(field) => {
          let name_res : Result[String, Value] = match field.label {
            IdentLabel(n) | StringLabel(n) => Ok(n)
            DynamicLabel(e) =>
              match resolve_default_shallow(eval_expr(e, scope)) {
                VString(s) => Ok(s)
                VBottom(_) as b => Err(b)
                other =>
                  Err(
                    Value::bottom(
                      EvalError,
                      "dynamic label must be string, got \{format_value(other)}",
                      span=Some(e.span()),
                    ),
                  )
              }
            PatternLabel(_) =>
              Err(
                Value::bottom(
                  EvalError,
                  "pattern labels are not supported inside comprehension body",
                  span=Some(field.span),
                ),
              )
          }
          match name_res {
            Err(b) => return Some(b)
            Ok(name) => {
              // Evaluate value eagerly with the loop variables currently bound in `scope`!
              let val = eval_expr(field.value, scope)
              if val.is_bottom() {
                // Still store bottom in the field so diagnostics carry the field path!
              }
              for g in group_allowed_names {
                if !g.contains(name) {
                  g.push(name)
                }
              }
              let cell = ensure_field_cell(
                target_vscope,
                name,
                field.constraint,
              )
              match cell.state {
                Evaluated(prev) => cell.state = Evaluated(unify(prev, val))
                _ =>
                  // Wrap evaluated value as a literal-like expression via direct pre-evaluation:
                  // evaluate existing entries first if needed, or store via closure
                  if cell.entries.is_empty() {
                    cell.state = Evaluated(val)
                  } else {
                    let prev = eval_field_cell(cell, target_vscope)
                    cell.state = Evaluated(unify(prev, val))
                  }
              }
            }
          }
        }
        ComprehensionDecl(inner_clauses, inner_body, _) =>
          match
            expand_field_comprehension(
              inner_clauses, 0, scope, inner_body, target_vscope, in_def, group_allowed_names,
            ) {
            Some(b) => return Some(b)
            None => ()
          }
        LetDecl(name, expr, _) => {
          let v = eval_expr(expr, scope)
          scope.lets.set(name, { expr, scope, state: Evaluated(v), })
        }
        _ => ()
      }
    }
    return None
  }

  match clauses[idx] {
    IfClause(cond~, span~) =>
      match resolve_default_shallow(eval_expr(cond, scope)) {
        VBool(true) =>
          expand_field_comprehension(
            clauses,
            idx + 1,
            scope,
            body_decls,
            target_vscope,
            in_def,
            group_allowed_names,
          )
        VBool(false) => None
        VBottom(_) as b => Some(b)
        other =>
          Some(
            Value::bottom(
              EvalError,
              "if condition must be bool, got \{format_value(other)}",
              span=Some(span),
            ),
          )
      }
    LetClause(name~, expr~, span=_) => {
      let next_scope = Scope::new(Some(scope), Map([]))
      let v = eval_expr(expr, scope)
      next_scope.lets.set(name, { expr, scope, state: Evaluated(v), })
      expand_field_comprehension(
        clauses,
        idx + 1,
        next_scope,
        body_decls,
        target_vscope,
        in_def,
        group_allowed_names,
      )
    }
    ForClause(key~, val~, source~, span~) => {
      let src_val = resolve_default_shallow(eval_expr(source, scope))
      match src_val {
        VList(l) => {
          for i = 0; i < l.elems.length(); i = i + 1 {
            let iter_scope = Scope::new(Some(scope), Map([]))
            match key {
              Some(k) =>
                if k != "_" {
                  iter_scope.lets.set(k, {
                    expr: IntLit(i.to_int64(), span),
                    scope,
                    state: Evaluated(VInt(i.to_int64())),
                  })
                }
              None => ()
            }
            if val != "_" {
              iter_scope.lets.set(val, {
                expr: TopLit(span),
                scope,
                state: Evaluated(l.elems[i]),
              })
            }
            match
              expand_field_comprehension(
                clauses,
                idx + 1,
                iter_scope,
                body_decls,
                target_vscope,
                in_def,
                group_allowed_names,
              ) {
              Some(b) => return Some(b)
              None => ()
            }
          }
          None
        }
        VStruct(s) => {
          for f in s.fields {
            if f.is_definition || f.is_hidden || f.constraint != Regular {
              continue
            }
            let iter_scope = Scope::new(Some(scope), Map([]))
            match key {
              Some(k) =>
                if k != "_" {
                  iter_scope.lets.set(k, {
                    expr: StringLit(f.name, span),
                    scope,
                    state: Evaluated(VString(f.name)),
                  })
                }
              None => ()
            }
            if val != "_" {
              iter_scope.lets.set(val, {
                expr: TopLit(span),
                scope,
                state: Evaluated(f.value),
              })
            }
            match
              expand_field_comprehension(
                clauses,
                idx + 1,
                iter_scope,
                body_decls,
                target_vscope,
                in_def,
                group_allowed_names,
              ) {
              Some(b) => return Some(b)
              None => ()
            }
          }
          None
        }
        VBottom(_) as b => Some(b)
        other =>
          Some(
            Value::bottom(
              EvalError,
              "cannot iterate over \{format_value(other)} in 'for' clause",
              span=Some(span),
            ),
          )
      }
    }
  }
}

///|
fn expand_list_comprehension(
  clauses : Array[Clause],
  idx : Int32,
  scope : Scope,
  body : Expr,
  out : Array[Value],
) -> Value? {
  if idx >= clauses.length() {
    out.push(eval_expr(body, scope))
    return None
  }
  match clauses[idx] {
    IfClause(cond~, span~) =>
      match resolve_default_shallow(eval_expr(cond, scope)) {
        VBool(true) =>
          expand_list_comprehension(clauses, idx + 1, scope, body, out)
        VBool(false) => None
        VBottom(_) as b => Some(b)
        other =>
          Some(
            Value::bottom(
              EvalError,
              "if condition must be bool, got \{format_value(other)}",
              span=Some(span),
            ),
          )
      }
    LetClause(name~, expr~, span=_) => {
      let next_scope = Scope::new(Some(scope), Map([]))
      let v = eval_expr(expr, scope)
      next_scope.lets.set(name, { expr, scope, state: Evaluated(v), })
      expand_list_comprehension(clauses, idx + 1, next_scope, body, out)
    }
    ForClause(key~, val~, source~, span~) => {
      let src_val = resolve_default_shallow(eval_expr(source, scope))
      match src_val {
        VList(l) => {
          for i = 0; i < l.elems.length(); i = i + 1 {
            let iter_scope = Scope::new(Some(scope), Map([]))
            match key {
              Some(k) =>
                if k != "_" {
                  iter_scope.lets.set(k, {
                    expr: IntLit(i.to_int64(), span),
                    scope,
                    state: Evaluated(VInt(i.to_int64())),
                  })
                }
              None => ()
            }
            if val != "_" {
              iter_scope.lets.set(val, {
                expr: TopLit(span),
                scope,
                state: Evaluated(l.elems[i]),
              })
            }
            match
              expand_list_comprehension(clauses, idx + 1, iter_scope, body, out) {
              Some(b) => return Some(b)
              None => ()
            }
          }
          None
        }
        VStruct(s) => {
          for f in s.fields {
            if f.is_definition || f.is_hidden || f.constraint != Regular {
              continue
            }
            let iter_scope = Scope::new(Some(scope), Map([]))
            match key {
              Some(k) =>
                if k != "_" {
                  iter_scope.lets.set(k, {
                    expr: StringLit(f.name, span),
                    scope,
                    state: Evaluated(VString(f.name)),
                  })
                }
              None => ()
            }
            if val != "_" {
              iter_scope.lets.set(val, {
                expr: TopLit(span),
                scope,
                state: Evaluated(f.value),
              })
            }
            match
              expand_list_comprehension(clauses, idx + 1, iter_scope, body, out) {
              Some(b) => return Some(b)
              None => ()
            }
          }
          None
        }
        VBottom(_) as b => Some(b)
        other =>
          Some(
            Value::bottom(
              EvalError,
              "cannot iterate over \{format_value(other)} in list comprehension",
              span=Some(span),
            ),
          )
      }
    }
  }
}

///|
fn eval_expr(expr : Expr, scope : Scope) -> Value {
  match expr {
    TopLit(_) => VTop
    BottomLit(sp) =>
      Value::bottom(
        ExplicitBottom,
        "explicit error (_|_ literal)",
        span=Some(sp),
      )
    NullLit(_) => VNull
    BoolLit(b, _) => VBool(b)
    IntLit(i, _) => VInt(i)
    FloatLit(f, _) => VFloat(f)
    StringLit(s, _) => VString(s)
    BytesLit(b, _) => VBytes(b)
    InterpStringExpr(parts, sp) => {
      let buf = StringBuilder()
      for part in parts {
        match part {
          StrText(s) => buf.write_string(s)
          StrExpr(e) => {
            let v = resolve_default_shallow(eval_expr(e, scope))
            match v {
              VString(s) => buf.write_string(s)
              VInt(i) => buf.write_string("\{i}")
              VFloat(f) => buf.write_string("\{f}")
              VBool(b) => buf.write_string(if b { "true" } else { "false" })
              VNull => buf.write_string("null")
              VBottom(_) => return v
              other =>
                return Value::bottom(
                  IncompleteError,
                  "non-concrete value in string interpolation: \{format_value(other)}",
                  span=Some(sp),
                )
            }
          }
        }
      }
      VString(buf.to_string())
    }
    IdentExpr(name, sp) => eval_ident(name, scope, sp)
    StructExpr(decls, _) =>
      eval_struct_sources([{ decls, scope, is_closed: false, }], false)
    ListExpr(elems, _) => {
      let out : Array[Value] = []
      let mut open_tail : Value? = None
      for elem in elems {
        match elem {
          ListItem(e) => out.push(eval_expr(e, scope))
          ListEllipsis(tail_opt, _) =>
            open_tail = match tail_opt {
              None => Some(VTop)
              Some(te) => Some(eval_expr(te, scope))
            }
          ListComp(clauses, body, _) =>
            match expand_list_comprehension(clauses, 0, scope, body, out) {
              Some(b) => return b
              None => ()
            }
        }
      }
      VList({ elems: out, open_tail, })
    }
    UnaryExpr(op, operand, sp) => eval_unary(op, operand, scope, sp)
    BinaryExpr(op, lhs, rhs, sp) => eval_binary(op, lhs, rhs, scope, sp)
    SelectorExpr(recv, field_name, sp) => {
      let rv = resolve_default_shallow(eval_expr(recv, scope))
      match rv {
        VStruct(sv) =>
          match sv.get_field(field_name) {
            Some(f) => f.value
            None =>
              Value::bottom(
                EvalError,
                "field '\{field_name}' not found",
                span=Some(sp),
              )
          }
        VBottom(_) => rv
        other =>
          Value::bottom(
            EvalError,
            "cannot select field '\{field_name}' on \{format_value(other)}",
            span=Some(sp),
          )
      }
    }
    IndexExpr(recv, idx_expr, sp) => {
      let rv = resolve_default_shallow(eval_expr(recv, scope))
      let iv = resolve_default_shallow(eval_expr(idx_expr, scope))
      match (rv, iv) {
        (VBottom(_) as b, _) | (_, VBottom(_) as b) => b
        (VList(l), VInt(i)) => {
          let idx = i.to_int()
          if idx >= 0 && idx < l.elems.length() {
            l.elems[idx]
          } else {
            Value::bottom(
              EvalError,
              "list index \{i} out of bounds (len \{l.elems.length()})",
              span=Some(sp),
            )
          }
        }
        (VStruct(sv), VString(key)) =>
          match sv.get_field(key) {
            Some(f) => f.value
            None =>
              Value::bottom(
                EvalError,
                "field '\{key}' not found",
                span=Some(sp),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "invalid index operation \{format_value(rv)}[\{format_value(iv)}]",
            span=Some(sp),
          )
      }
    }
    SliceExpr(recv, lo_opt, hi_opt, sp) => {
      let rv = resolve_default_shallow(eval_expr(recv, scope))
      match rv {
        VList(l) => {
          let lo : Int32 = match lo_opt {
            None => 0
            Some(e) =>
              match resolve_default_shallow(eval_expr(e, scope)) {
                VInt(i) => i.to_int()
                VBottom(_) as b => return b
                _ =>
                  return Value::bottom(
                    EvalError,
                    "slice lower bound must be int",
                    span=Some(sp),
                  )
              }
          }
          let hi : Int32 = match hi_opt {
            None => l.elems.length()
            Some(e) =>
              match resolve_default_shallow(eval_expr(e, scope)) {
                VInt(i) => i.to_int()
                VBottom(_) as b => return b
                _ =>
                  return Value::bottom(
                    EvalError,
                    "slice upper bound must be int",
                    span=Some(sp),
                  )
              }
          }
          if lo < 0 || hi < lo || hi > l.elems.length() {
            return Value::bottom(
              EvalError,
              "slice bounds [\{lo}:\{hi}] out of range (len \{l.elems.length()})",
              span=Some(sp),
            )
          }
          let sliced : Array[Value] = []
          for i = lo; i < hi; i = i + 1 {
            sliced.push(l.elems[i])
          }
          VList({ elems: sliced, open_tail: None, })
        }
        VBottom(_) => rv
        other =>
          Value::bottom(
            EvalError,
            "cannot slice \{format_value(other)}",
            span=Some(sp),
          )
      }
    }
    CallExpr(callee, args, sp) => eval_call(callee, args, scope, sp)
  }
}

///|
fn eval_ident(name : String, scope : Scope, sp : Span) -> Value {
  // 1. Check lexical `let` bindings walking up scope chain
  match lookup_let_cell_in_scope(scope, name) {
    Some(lcell) => return eval_let_cell(lcell, scope)
    None => ()
  }
  // 2. Check struct fields walking up scope chain
  match lookup_field_cell_in_scope(scope, name) {
    Some((fcell, owner_scope)) => return eval_field_cell(fcell, owner_scope)
    None => ()
  }
  // 3. Check predeclared CUE types (`int`, `string`, `uint16`, etc.)
  match lookup_predeclared_type(name) {
    Some(v) => return v
    None => ()
  }
  Value::bottom(EvalError, "undefined reference '\{name}'", span=Some(sp))
}

///|
fn eval_call(
  callee : Expr,
  arg_exprs : Array[Expr],
  scope : Scope,
  sp : Span,
) -> Value {
  let args : Array[Value] = []
  for a in arg_exprs {
    args.push(eval_expr(a, scope))
  }
  match callee {
    IdentExpr(name, _) => eval_global_builtin(name, args, sp)
    SelectorExpr(IdentExpr(pkg_alias, _), func_name, _) =>
      match scope.lookup_import(pkg_alias) {
        Some(pkg_path) => eval_stdlib_call(pkg_path, func_name, args, sp)
        None =>
          Value::bottom(
            EvalError,
            "unimported package '\{pkg_alias}' (add `import \"\{pkg_alias}\"`)",
            span=Some(sp),
          )
      }
    _ =>
      Value::bottom(
        EvalError,
        "cannot call non-function expression",
        span=Some(sp),
      )
  }
}

///|
fn eval_unary(op : UnaryOp, operand : Expr, scope : Scope, sp : Span) -> Value {
  match op {
    Default => {
      let v = eval_expr(operand, scope)
      match v {
        VBottom(_) => v
        _ => VDisjunction([{ value: v, is_default: true, }])
      }
    }
    Pos => {
      let v = resolve_default_shallow(eval_expr(operand, scope))
      match v {
        VInt(_) | VFloat(_) | VBottom(_) => v
        other =>
          Value::bottom(
            EvalError,
            "invalid unary '+' on \{format_value(other)}",
            span=Some(sp),
          )
      }
    }
    Neg => {
      let v = resolve_default_shallow(eval_expr(operand, scope))
      match v {
        VInt(i) => VInt(-i)
        VFloat(f) => VFloat(-f)
        VBottom(_) => v
        other =>
          Value::bottom(
            EvalError,
            "invalid unary '-' on \{format_value(other)}",
            span=Some(sp),
          )
      }
    }
    Not => {
      let v = resolve_default_shallow(eval_expr(operand, scope))
      match v {
        VBool(b) => VBool(!b)
        VBottom(_) => v
        other =>
          Value::bottom(
            EvalError,
            "invalid unary '!' on \{format_value(other)}",
            span=Some(sp),
          )
      }
    }
    Lt | Lte | Gt | Gte | Neq | Match | NotMatch => {
      let v = resolve_default_shallow(eval_expr(operand, scope))
      match v {
        VBottom(_) => v
        _ =>
          match v.as_scalar() {
            Some(s) => {
              let bop : BoundOp = match op {
                Lt => BLt
                Lte => BLte
                Gt => BGt
                Gte => BGte
                Neq => BNeq
                Match => BMatch
                NotMatch => BNotMatch
                _ => BNeq
              }
              // Pre-validate regex syntax eagerly if Match/NotMatch
              if bop == BMatch || bop == BNotMatch {
                match s {
                  SString(pat) => {
                    let chk : Result[CompiledRegex, CueError] = Ok(
                      compile_regex(pat),
                    ) catch {
                      e => Err(e)
                    }
                    match chk {
                      Err(e) => return VBottom([e])
                      Ok(_) => ()
                    }
                  }
                  _ =>
                    return Value::bottom(
                      BoundError,
                      "regex bound requires string pattern",
                      span=Some(sp),
                    )
                }
              }
              VBound({ op: bop, scalar: s, })
            }
            None =>
              Value::bottom(
                BoundError,
                "bound operand must be a concrete scalar, got \{format_value(v)}",
                span=Some(sp),
              )
          }
      }
    }
  }
}

///|
fn flatten_disj_exprs(expr : Expr, out : Array[(Expr, Bool)]) -> Unit {
  match expr {
    BinaryExpr(Or, lhs, rhs, _) => {
      flatten_disj_exprs(lhs, out)
      flatten_disj_exprs(rhs, out)
    }
    UnaryExpr(Default, inner, _) => out.push((inner, true))
    _ => out.push((expr, false))
  }
}

///|
fn eval_binary(
  op : BinOp,
  lhs_expr : Expr,
  rhs_expr : Expr,
  scope : Scope,
  sp : Span,
) -> Value {
  match op {
    Or => {
      let raw : Array[(Expr, Bool)] = []
      flatten_disj_exprs(lhs_expr, raw)
      flatten_disj_exprs(rhs_expr, raw)
      let disjuncts : Array[Disjunct] = []
      for item in raw {
        let (e, is_def) = item
        let v = eval_expr(e, scope)
        disjuncts.push({ value: v, is_default: is_def, })
      }
      make_disjunction(disjuncts)
    }
    And => {
      // Crucial CUE semantics: if both sides are struct-producing conjuncts,
      // merge them into ONE StructVertex before resolving internal sibling references!
      let sources : Array[RawStructSource] = []
      if try_collect_struct_sources(lhs_expr, scope, false, sources) &&
        try_collect_struct_sources(rhs_expr, scope, false, sources) {
        eval_struct_sources(sources, false)
      } else {
        let lv = eval_expr(lhs_expr, scope)
        let rv = eval_expr(rhs_expr, scope)
        unify(lv, rv)
      }
    }
    Land => {
      let lv = resolve_default_shallow(eval_expr(lhs_expr, scope))
      match lv {
        VBool(false) => VBool(false)
        VBool(true) => {
          let rv = resolve_default_shallow(eval_expr(rhs_expr, scope))
          match rv {
            VBool(b) => VBool(b)
            VBottom(_) => rv
            other =>
              Value::bottom(
                EvalError,
                "invalid rhs for '&&': \{format_value(other)}",
                span=Some(sp),
              )
          }
        }
        VBottom(_) => lv
        other =>
          Value::bottom(
            EvalError,
            "invalid lhs for '&&': \{format_value(other)}",
            span=Some(sp),
          )
      }
    }
    Lor => {
      let lv = resolve_default_shallow(eval_expr(lhs_expr, scope))
      match lv {
        VBool(true) => VBool(true)
        VBool(false) => {
          let rv = resolve_default_shallow(eval_expr(rhs_expr, scope))
          match rv {
            VBool(b) => VBool(b)
            VBottom(_) => rv
            other =>
              Value::bottom(
                EvalError,
                "invalid rhs for '||': \{format_value(other)}",
                span=Some(sp),
              )
          }
        }
        VBottom(_) => lv
        other =>
          Value::bottom(
            EvalError,
            "invalid lhs for '||': \{format_value(other)}",
            span=Some(sp),
          )
      }
    }
    _ => {
      let lv = resolve_default_shallow(eval_expr(lhs_expr, scope))
      let rv = resolve_default_shallow(eval_expr(rhs_expr, scope))
      if lv.is_bottom() {
        return lv
      }
      if rv.is_bottom() {
        return rv
      }
      eval_concrete_binary(op, lv, rv, sp)
    }
  }
}

///|
fn eval_concrete_binary(op : BinOp, lv : Value, rv : Value, sp : Span) -> Value {
  match op {
    Add =>
      match (lv, rv) {
        (VInt(a), VInt(b)) => VInt(a + b)
        (VFloat(a), VFloat(b)) => VFloat(a + b)
        (VInt(a), VFloat(b)) => VFloat(a.to_double() + b)
        (VFloat(a), VInt(b)) => VFloat(a + b.to_double())
        (VString(a), VString(b)) => VString(a + b)
        (VList(_), VList(_)) =>
          Value::bottom(
            EvalError,
            "list addition '+' was removed in CUE v0.11+; use list.Concat([...]) instead",
            span=Some(sp),
          )
        _ =>
          Value::bottom(
            EvalError,
            "invalid '+' between \{format_value(lv)} and \{format_value(rv)}",
            span=Some(sp),
          )
      }
    Sub =>
      match (lv, rv) {
        (VInt(a), VInt(b)) => VInt(a - b)
        (VFloat(a), VFloat(b)) => VFloat(a - b)
        (VInt(a), VFloat(b)) => VFloat(a.to_double() - b)
        (VFloat(a), VInt(b)) => VFloat(a - b.to_double())
        _ =>
          Value::bottom(
            EvalError,
            "invalid '-' between \{format_value(lv)} and \{format_value(rv)}",
            span=Some(sp),
          )
      }
    Mul =>
      match (lv, rv) {
        (VInt(a), VInt(b)) => VInt(a * b)
        (VFloat(a), VFloat(b)) => VFloat(a * b)
        (VInt(a), VFloat(b)) => VFloat(a.to_double() * b)
        (VFloat(a), VInt(b)) => VFloat(a * b.to_double())
        // CUE string repetition: `"ab" * 3 == "ababab"`
        (VString(s), VInt(n)) | (VInt(n), VString(s)) => {
          if n < 0L {
            return Value::bottom(
              EvalError,
              "negative string repetition count \{n}",
              span=Some(sp),
            )
          }
          let buf = StringBuilder()
          for _i = 0L; _i < n; _i = _i + 1L {
            buf.write_string(s)
          }
          VString(buf.to_string())
        }
        (VList(_), VInt(_)) | (VInt(_), VList(_)) =>
          Value::bottom(
            EvalError,
            "list multiplication '*' was removed in CUE v0.11+; use list.Repeat(xs, n) instead",
            span=Some(sp),
          )
        _ =>
          Value::bottom(
            EvalError,
            "invalid '*' between \{format_value(lv)} and \{format_value(rv)}",
            span=Some(sp),
          )
      }
    Quo =>
      match (lv, rv) {
        (VInt(a), VInt(b)) =>
          if b == 0L {
            Value::bottom(EvalError, "division by zero", span=Some(sp))
          } else {
            VFloat(a.to_double() / b.to_double())
          }
        (VFloat(a), VFloat(b)) =>
          if b == 0.0 {
            Value::bottom(EvalError, "division by zero", span=Some(sp))
          } else {
            VFloat(a / b)
          }
        (VInt(a), VFloat(b)) =>
          if b == 0.0 {
            Value::bottom(EvalError, "division by zero", span=Some(sp))
          } else {
            VFloat(a.to_double() / b)
          }
        (VFloat(a), VInt(b)) =>
          if b == 0L {
            Value::bottom(EvalError, "division by zero", span=Some(sp))
          } else {
            VFloat(a / b.to_double())
          }
        _ =>
          Value::bottom(
            EvalError,
            "invalid '/' between \{format_value(lv)} and \{format_value(rv)}",
            span=Some(sp),
          )
      }
    IntDiv | IntMod | IntQuo | IntRem =>
      match (lv, rv) {
        (VInt(a), VInt(b)) => {
          let res : Result[(Int64, Int64), CueError] = Ok(
            if op == IntDiv || op == IntMod {
              cue_int_div(a, b)
            } else {
              cue_int_quo(a, b)
            },
          ) catch {
            e => Err(e)
          }
          match res {
            Ok((q, r)) =>
              if op == IntDiv || op == IntQuo {
                VInt(q)
              } else {
                VInt(r)
              }
            Err(e) => VBottom([e])
          }
        }
        _ =>
          Value::bottom(
            EvalError,
            "integer division/modulo requires two integers",
            span=Some(sp),
          )
      }
    Eq => VBool(values_equal_cue(lv, rv))
    Neq => VBool(!values_equal_cue(lv, rv))
    Lt | Lte | Gt | Gte =>
      match (lv.as_scalar(), rv.as_scalar()) {
        (Some(sa), Some(sb)) =>
          match compare_scalars(sa, sb) {
            Some(cmp) =>
              VBool(
                match op {
                  Lt => cmp < 0
                  Lte => cmp <= 0
                  Gt => cmp > 0
                  Gte => cmp >= 0
                  _ => false
                },
              )
            None =>
              Value::bottom(
                EvalError,
                "cannot compare \{sa} and \{sb}",
                span=Some(sp),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "comparison requires concrete scalars",
            span=Some(sp),
          )
      }
    Match | NotMatch =>
      match (lv, rv) {
        (VString(text), VString(pat)) => {
          let res : Result[Bool, CueError] = Ok(regex_match(pat, text)) catch {
            e => Err(e)
          }
          match res {
            Ok(m) => VBool(if op == Match { m } else { !m })
            Err(e) => VBottom([e])
          }
        }
        _ =>
          Value::bottom(
            EvalError,
            "regex match requires (string, string)",
            span=Some(sp),
          )
      }
    _ => Value::bottom(EvalError, "unexpected binary operator", span=Some(sp))
  }
}

///|
fn values_equal_cue(a : Value, b : Value) -> Bool {
  match (a.as_scalar(), b.as_scalar()) {
    (Some(sa), Some(sb)) => scalar_equals_cue(sa, sb)
    _ => a == b
  }
}