///|
/// Formal Value Lattice Unification Engine (`unify(a, b)`) and Subsumption (`subsumes(a, b)`).
///
/// Implements CUE's meet-semilattice laws:
/// - Identity: `unify(VTop, x) == x`
/// - Absorbing bottom: `unify(VBottom(e), x) == VBottom(e)`
/// - Commutativity, associativity, idempotence
/// - Numeric & string bound simplification, integer gap contradiction (`int & >1 & <2 == _|_`)
/// - Disjunction distribution & default propagation/pruning
/// - Closed struct enforcement & pattern constraint application

///|
/// Unify two CUE lattice values `a & b`.
pub fn unify(a : Value, b : Value) -> Value {
  // 1. Top identity
  if a.is_top() {
    return b
  }
  if b.is_top() {
    return a
  }

  // 2. Bottom absorption (preserving both diagnostics if both are bottom)
  match (a, b) {
    (VBottom(e1), VBottom(e2)) => {
      let merged = e1.copy()
      for e in e2 {
        if !merged.contains(e) {
          merged.push(e)
        }
      }
      return VBottom(merged)
    }
    (VBottom(_), _) => return a
    (_, VBottom(_)) => return b
    _ => ()
  }

  // 3. Disjunction distribution: (d1 | d2) & x == (d1 & x) | (d2 & x)
  match (a, b) {
    (VDisjunction(da), VDisjunction(db)) => return unify_disj_disj(da, db)
    (VDisjunction(da), other) => return unify_disj_val(da, other)
    (other, VDisjunction(db)) => return unify_disj_val(db, other)
    _ => ()
  }

  // 4. Conjunction flattening & normalization
  match (a, b) {
    (VConjunction(_), _) | (_, VConjunction(_)) =>
      return unify_conjunction(a, b)
    _ => ()
  }

  // 5. Concrete scalars
  match (a.as_scalar(), b.as_scalar()) {
    (Some(sa), Some(sb)) => return unify_scalars(sa, sb)
    _ => ()
  }

  // 6. Basic types
  match (a, b) {
    (VBasic(ka), VBasic(kb)) => return unify_basic_kinds(ka, kb)
    (VBasic(k), other) => return unify_basic_and_value(k, other)
    (other, VBasic(k)) => return unify_basic_and_value(k, other)
    _ => ()
  }

  // 7. Bounds
  match (a, b) {
    (VBound(ba), VBound(bb)) =>
      return simplify_constraints([VBound(ba), VBound(bb)])
    (VBound(ba), other) => return unify_bound_and_value(ba, other)
    (other, VBound(bb)) => return unify_bound_and_value(bb, other)
    _ => ()
  }

  // 8. Structs
  match (a, b) {
    (VStruct(sa), VStruct(sb)) => return unify_structs(sa, sb)
    (VStruct(s), other) => return unify_struct_and_non_struct(s, other)
    (other, VStruct(s)) => return unify_struct_and_non_struct(s, other)
    _ => ()
  }

  // 9. Lists
  match (a, b) {
    (VList(la), VList(lb)) => return unify_lists(la, lb)
    _ => ()
  }

  // 10. Incompatible kinds -> Bottom
  Value::bottom(
    ConflictError,
    "conflicting values \{format_value(a)} and \{format_value(b)}",
  )
}

///|
fn unify_scalars(a : Scalar, b : Scalar) -> Value {
  match (a, b) {
    (SNull, SNull) => VNull
    (SBool(x), SBool(y)) =>
      if x == y {
        VBool(x)
      } else {
        Value::bottom(ConflictError, "conflicting values \{x} and \{y}")
      }
    (SInt(x), SInt(y)) =>
      if x == y {
        VInt(x)
      } else {
        Value::bottom(ConflictError, "conflicting values \{x} and \{y}")
      }
    (SFloat(x), SFloat(y)) =>
      if x == y {
        VFloat(x)
      } else {
        Value::bottom(ConflictError, "conflicting values \{x} and \{y}")
      }
    // In CUE spec: `int` (3) and `float` (3.0) are distinct types: `3 & 3.0 == _|_`!
    (SInt(x), SFloat(y)) =>
      Value::bottom(
        ConflictError,
        "conflicting values \{x} (int) and \{y} (float)",
      )
    (SFloat(x), SInt(y)) =>
      Value::bottom(
        ConflictError,
        "conflicting values \{x} (float) and \{y} (int)",
      )
    (SString(x), SString(y)) =>
      if x == y {
        VString(x)
      } else {
        Value::bottom(ConflictError, "conflicting values \"\{x}\" and \"\{y}\"")
      }
    (SBytes(x), SBytes(y)) =>
      if x == y {
        VBytes(x)
      } else {
        Value::bottom(ConflictError, "conflicting bytes values")
      }
    _ =>
      Value::bottom(
        ConflictError,
        "conflicting values \{a} and \{b} (mismatched types \{a.kind()} and \{b.kind()})",
      )
  }
}

///|
fn unify_basic_kinds(a : BasicKind, b : BasicKind) -> Value {
  if a == b {
    return VBasic(a)
  }
  match (a, b) {
    (NumberKind, IntKind) | (IntKind, NumberKind) => VBasic(IntKind)
    (NumberKind, FloatKind) | (FloatKind, NumberKind) => VBasic(FloatKind)
    _ => Value::bottom(ConflictError, "conflicting types \{a} and \{b}")
  }
}

///|
fn kind_accepts_scalar(k : BasicKind, s : Scalar) -> Bool {
  match (k, s) {
    (NullKind, SNull) => true
    (BoolKind, SBool(_)) => true
    (IntKind, SInt(_)) => true
    (FloatKind, SFloat(_)) => true
    (NumberKind, SInt(_)) | (NumberKind, SFloat(_)) => true
    (StringKind, SString(_)) => true
    (BytesKind, SBytes(_)) => true
    _ => false
  }
}

///|
fn bound_implied_kind(b : BoundVal) -> BasicKind? {
  match b.op {
    BMatch | BNotMatch => Some(StringKind)
    BNeq => None // `!=null` or `!=5` applies to any value; mismatching types satisfy `!=`!
    BLt | BLte | BGt | BGte =>
      match b.scalar {
        SInt(_) | SFloat(_) => Some(NumberKind)
        SString(_) => Some(StringKind)
        SBytes(_) => Some(BytesKind)
        _ => None
      }
  }
}

///|
fn unify_basic_and_value(k : BasicKind, v : Value) -> Value {
  match v.as_scalar() {
    Some(s) =>
      if kind_accepts_scalar(k, s) {
        v
      } else {
        Value::bottom(
          ConflictError,
          "conflicting values \{s} and \{k} (mismatched types \{s.kind()} and \{k})",
        )
      }
    None =>
      match v {
        VBound(b) => simplify_constraints([VBasic(k), VBound(b)])
        VStruct(st) =>
          // Only valid if struct embeds a compatible value
          match st.embed {
            Some(e) => {
              let unified = unify(VBasic(k), e)
              if unified.is_bottom() {
                unified
              } else {
                VStruct({ ..st, embed: Some(unified), })
              }
            }
            None =>
              Value::bottom(ConflictError, "conflicting values \{k} and struct")
          }
        _ =>
          Value::bottom(
            ConflictError,
            "conflicting values \{k} and \{format_value(v)}",
          )
      }
  }
}

///|
fn compare_scalars(a : Scalar, b : Scalar) -> Int32? {
  match (a, b) {
    (SInt(x), SInt(y)) => Some(if x < y { -1 } else if x > y { 1 } else { 0 })
    (SInt(x), SFloat(y)) => {
      let xd = x.to_double()
      Some(if xd < y { -1 } else if xd > y { 1 } else { 0 })
    }
    (SFloat(x), SInt(y)) => {
      let yd = y.to_double()
      Some(if x < yd { -1 } else if x > yd { 1 } else { 0 })
    }
    (SFloat(x), SFloat(y)) =>
      Some(if x < y { -1 } else if x > y { 1 } else { 0 })
    (SString(x), SString(y)) => Some(x.compare(y))
    (SBytes(x), SBytes(y)) => Some(compare_bytes(x, y))
    _ => None
  }
}

///|
fn compare_bytes(a : Bytes, b : Bytes) -> Int32 {
  let min_len = if a.length() < b.length() { a.length() } else { b.length() }
  for i = 0; i < min_len; i = i + 1 {
    let ba = a[i].to_int()
    let bb = b[i].to_int()
    if ba < bb {
      return -1
    } else if ba > bb {
      return 1
    }
  }
  if a.length() < b.length() {
    -1
  } else if a.length() > b.length() {
    1
  } else {
    0
  }
}

///|
fn scalar_equals_cue(a : Scalar, b : Scalar) -> Bool {
  match (a, b) {
    (SNull, SNull) => true
    (SBool(x), SBool(y)) => x == y
    (SInt(x), SInt(y)) => x == y
    (SFloat(x), SFloat(y)) => x == y
    (SInt(x), SFloat(y)) => x.to_double() == y
    (SFloat(x), SInt(y)) => x == y.to_double()
    (SString(x), SString(y)) => x == y
    (SBytes(x), SBytes(y)) => x == y
    _ => false
  }
}

///|
/// Check whether concrete scalar `s` satisfies bound `b`.
fn check_bound_scalar(b : BoundVal, s : Scalar) -> Value {
  match b.op {
    BNeq =>
      if scalar_equals_cue(s, b.scalar) {
        Value::bottom(BoundError, "invalid value \{s} (out of bound \{b})")
      } else {
        s.to_value()
      }
    BMatch =>
      match (b.scalar, s) {
        (SString(pat), SString(text)) => {
          let matched : Result[Bool, CueError] = Ok(regex_match(pat, text)) catch {
            e => Err(e)
          }
          match matched {
            Ok(true) => VString(text)
            Ok(false) =>
              Value::bottom(
                BoundError,
                "invalid value \"\{text}\" (does not match =~\"\{pat}\")",
              )
            Err(e) => VBottom([e])
          }
        }
        _ =>
          Value::bottom(
            ConflictError,
            "conflicting values \{s} and \{b} (mismatched types)",
          )
      }
    BNotMatch =>
      match (b.scalar, s) {
        (SString(pat), SString(text)) => {
          let matched : Result[Bool, CueError] = Ok(regex_match(pat, text)) catch {
            e => Err(e)
          }
          match matched {
            Ok(false) => VString(text)
            Ok(true) =>
              Value::bottom(
                BoundError,
                "invalid value \"\{text}\" (matches forbidden !~\"\{pat}\")",
              )
            Err(e) => VBottom([e])
          }
        }
        _ =>
          Value::bottom(
            ConflictError,
            "conflicting values \{s} and \{b} (mismatched types)",
          )
      }
    BLt | BLte | BGt | BGte =>
      match compare_scalars(s, b.scalar) {
        None =>
          Value::bottom(
            ConflictError,
            "conflicting values \{s} and \{b} (incompatible types for bound)",
          )
        Some(cmp) => {
          let ok = match b.op {
            BLt => cmp < 0
            BLte => cmp <= 0
            BGt => cmp > 0
            BGte => cmp >= 0
            _ => false
          }
          if ok {
            s.to_value()
          } else {
            Value::bottom(BoundError, "invalid value \{s} (out of bound \{b})")
          }
        }
      }
  }
}

///|
fn unify_bound_and_value(b : BoundVal, v : Value) -> Value {
  match v.as_scalar() {
    Some(s) => check_bound_scalar(b, s)
    None =>
      match v {
        VStruct(st) =>
          match b.op {
            // `!=null` unifies cleanly with a struct!
            BNeq =>
              match b.scalar {
                SNull
                | SBool(_)
                | SInt(_)
                | SFloat(_)
                | SString(_)
                | SBytes(_) => v
              }
            _ =>
              match st.embed {
                Some(e) => {
                  let u = unify(VBound(b), e)
                  if u.is_bottom() {
                    u
                  } else {
                    VStruct({ ..st, embed: Some(u), })
                  }
                }
                None =>
                  Value::bottom(
                    ConflictError,
                    "conflicting values \{b} and struct",
                  )
              }
          }
        VList(_) =>
          match b.op {
            BNeq => v
            _ =>
              Value::bottom(ConflictError, "conflicting values \{b} and list")
          }
        _ =>
          Value::bottom(
            ConflictError,
            "conflicting values \{b} and \{format_value(v)}",
          )
      }
  }
}

///|
fn flatten_conj(v : Value, out : Array[Value]) -> Unit {
  match v {
    VConjunction(items) =>
      for item in items {
        flatten_conj(item, out)
      }
    VTop => ()
    _ => out.push(v)
  }
}

///|
fn unify_conjunction(a : Value, b : Value) -> Value {
  let items : Array[Value] = []
  flatten_conj(a, items)
  flatten_conj(b, items)
  simplify_constraints(items)
}

///|
/// Normalize a list of conjuncts (basic types, bounds, concrete values, structs, lists).
/// Detects numeric/integer bound contradictions, tightens bounds, and collapses exact points.
fn simplify_constraints(items : Array[Value]) -> Value {
  let mut basic : BasicKind? = None
  let mut concrete : Value? = None
  let bounds : Array[BoundVal] = []

  for item in items {
    match item {
      VTop => ()
      VBottom(_) => return item
      VBasic(k) =>
        match basic {
          None => basic = Some(k)
          Some(prev) =>
            match unify_basic_kinds(prev, k) {
              VBasic(nk) => basic = Some(nk)
              err => return err
            }
        }
      VBound(b) => {
        match bound_implied_kind(b) {
          Some(bk) =>
            match basic {
              None => basic = Some(bk)
              Some(prev) =>
                match unify_basic_kinds(prev, bk) {
                  VBasic(nk) => basic = Some(nk)
                  err => return err
                }
            }
          None => ()
        }
        if !bounds.contains(b) {
          bounds.push(b)
        }
      }
      VConjunction(sub) => {
        let s = simplify_constraints(sub)
        if s.is_bottom() {
          return s
        }
        let next : Array[Value] = []
        match basic {
          Some(k) => next.push(VBasic(k))
          None => ()
        }
        match concrete {
          Some(c) => next.push(c)
          None => ()
        }
        for b in bounds {
          next.push(VBound(b))
        }
        next.push(s)
        return simplify_constraints(next)
      }
      _ =>
        match concrete {
          None => concrete = Some(item)
          Some(prev) => {
            let u = unify(prev, item)
            if u.is_bottom() {
              return u
            }
            concrete = Some(u)
          }
        }
    }
  }

  // If a concrete value (or struct/list) is present, validate it against basic type and all bounds!
  match concrete {
    Some(c) => {
      let mut res = c
      match basic {
        Some(k) => {
          res = unify(VBasic(k), res)
          if res.is_bottom() {
            return res
          }
        }
        None => ()
      }
      for b in bounds {
        res = unify(VBound(b), res)
        if res.is_bottom() {
          return res
        }
      }
      return res
    }
    None => ()
  }

  // Simplify ordering bounds (find tightest lower and upper bounds, check contradiction & point collapse!)
  let mut lower : BoundVal? = None // BGt or BGte
  let mut upper : BoundVal? = None // BLt or BLte
  let others : Array[BoundVal] = [] // BNeq, BMatch, BNotMatch

  for b in bounds {
    match b.op {
      BGt | BGte =>
        match lower {
          None => lower = Some(b)
          Some(prev) =>
            match compare_scalars(b.scalar, prev.scalar) {
              Some(cmp) =>
                if cmp > 0 || (cmp == 0 && b.op == BGt && prev.op == BGte) {
                  lower = Some(b)
                }
              None =>
                return Value::bottom(
                  ConflictError,
                  "incompatible bounds \{prev} and \{b}",
                )
            }
        }
      BLt | BLte =>
        match upper {
          None => upper = Some(b)
          Some(prev) =>
            match compare_scalars(b.scalar, prev.scalar) {
              Some(cmp) =>
                if cmp < 0 || (cmp == 0 && b.op == BLt && prev.op == BLte) {
                  upper = Some(b)
                }
              None =>
                return Value::bottom(
                  ConflictError,
                  "incompatible bounds \{prev} and \{b}",
                )
            }
        }
      _ => others.push(b)
    }
  }

  // Check lower vs upper compatibility!
  match (lower, upper) {
    (Some(lo), Some(hi)) =>
      match compare_scalars(lo.scalar, hi.scalar) {
        None =>
          return Value::bottom(
            ConflictError,
            "incompatible bounds \{lo} and \{hi}",
          )
        Some(cmp) => {
          if cmp > 0 {
            return Value::bottom(
              BoundError,
              "incompatible bounds \{lo} and \{hi}",
            )
          }
          if cmp == 0 {
            if lo.op == BGte && hi.op == BLte {
              // Per CUE v0.18 spec: `>=5 & <=5` remains a non-concrete bound conjunction
              // (valid, not bottom, unless contradicted by `!=5` or incompatible basic type).
              for ob in others {
                if ob.op == BNeq && scalar_equals_cue(lo.scalar, ob.scalar) {
                  return Value::bottom(
                    BoundError,
                    "incompatible bounds \{lo}, \{hi}, and \{ob}",
                  )
                }
              }
            } else {
              // e.g. `>5 & <=5`, `>=5 & <5`, `>5 & <5`
              return Value::bottom(
                BoundError,
                "incompatible bounds \{lo} and \{hi}",
              )
            }
          }
          // Integer domain contradiction check: e.g. `int & >1 & <2 == _|_`
          if basic == Some(IntKind) {
            match (lo.scalar, hi.scalar) {
              (SInt(lval), SInt(hval)) => {
                let eff_lo = if lo.op == BGt { lval + 1L } else { lval }
                let eff_hi = if hi.op == BLt { hval - 1L } else { hval }
                if eff_lo > eff_hi {
                  return Value::bottom(
                    BoundError,
                    "no integer satisfies \{lo} and \{hi}",
                  )
                }
              }
              _ => ()
            }
          }
        }
      }
    _ => ()
  }

  // Reconstruct canonical normalized value
  let final_items : Array[Value] = []
  match basic {
    Some(k) => final_items.push(VBasic(k))
    None => ()
  }
  match lower {
    Some(lo) => final_items.push(VBound(lo))
    None => ()
  }
  match upper {
    Some(hi) => final_items.push(VBound(hi))
    None => ()
  }
  for ob in others {
    final_items.push(VBound(ob))
  }

  match final_items.length() {
    0 => VTop
    1 => final_items[0]
    _ => VConjunction(final_items)
  }
}

///|
fn unify_disj_val(disjuncts : Array[Disjunct], other : Value) -> Value {
  let out : Array[Disjunct] = []
  let errs : Array[CueError] = []
  for d in disjuncts {
    let u = unify(d.value, other)
    match u {
      VBottom(es) =>
        for e in es {
          errs.push(e)
        }
      VDisjunction(nested) =>
        for nd in nested {
          push_disjunct(out, {
            value: nd.value,
            is_default: d.is_default || nd.is_default,
          })
        }
      _ => push_disjunct(out, { value: u, is_default: d.is_default, })
    }
  }
  finalize_disjunction(out, errs)
}

///|
fn unify_disj_disj(da : Array[Disjunct], db : Array[Disjunct]) -> Value {
  let out : Array[Disjunct] = []
  let errs : Array[CueError] = []
  for a in da {
    for b in db {
      let u = unify(a.value, b.value)
      let is_def = a.is_default && b.is_default
      match u {
        VBottom(es) =>
          for e in es {
            errs.push(e)
          }
        VDisjunction(nested) =>
          for nd in nested {
            push_disjunct(out, {
              value: nd.value,
              is_default: is_def && nd.is_default,
            })
          }
        _ => push_disjunct(out, { value: u, is_default: is_def, })
      }
    }
  }
  finalize_disjunction(out, errs)
}

///|
fn push_disjunct(out : Array[Disjunct], cand : Disjunct) -> Unit {
  for i = 0; i < out.length(); i = i + 1 {
    if out[i].value == cand.value {
      if cand.is_default && !out[i].is_default {
        out[i] = { value: out[i].value, is_default: true, }
      }
      return
    }
  }
  out.push(cand)
}

///|
fn finalize_disjunction(out : Array[Disjunct], errs : Array[CueError]) -> Value {
  match out.length() {
    0 =>
      if errs.is_empty() {
        Value::bottom(ConflictError, "empty disjunction")
      } else {
        VBottom([
          CueError::new(
            ConflictError,
            "no disjunct matched (first error: \{errs[0]})",
          ),
        ])
      }
    1 => out[0].value
    _ => VDisjunction(out)
  }
}

///|
/// Construct a normalized disjunction from raw disjunct branches.
pub fn make_disjunction(branches : Array[Disjunct]) -> Value {
  let out : Array[Disjunct] = []
  let errs : Array[CueError] = []
  for b in branches {
    match b.value {
      VBottom(es) =>
        for e in es {
          errs.push(e)
        }
      VDisjunction(inner) =>
        for id in inner {
          push_disjunct(out, {
            value: id.value,
            is_default: b.is_default || id.is_default,
          })
        }
      _ => push_disjunct(out, b)
    }
  }
  finalize_disjunction(out, errs)
}

///|
fn unify_field_constraint(
  a : FieldConstraint,
  b : FieldConstraint,
) -> FieldConstraint {
  match (a, b) {
    (Regular, _) | (_, Regular) => Regular
    (Required, _) | (_, Required) => Required
    (Optional, Optional) => Optional
  }
}

///|
fn field_matches_any_pattern(
  name : String,
  patterns : Array[PatternConstraint],
) -> Bool {
  for p in patterns {
    if !unify(p.label_pattern, VString(name)).is_bottom() {
      return true
    }
  }
  false
}

///|
fn unify_structs(sa : StructVal, sb : StructVal) -> Value {
  // Merge pattern constraints
  let merged_patterns : Array[PatternConstraint] = []
  for p in sa.patterns {
    merged_patterns.push(p)
  }
  for p in sb.patterns {
    merged_patterns.push(p)
  }

  // Merge fields preserving order, recording closed-struct violations per offending field
  // so diagnostics report ALL errors across the struct rather than stopping at the first one.
  let merged_fields : Array[StructField] = []
  for fa in sa.fields {
    match sb.get_field(fa.name) {
      Some(fb) => {
        let mut val = unify(fa.value, fb.value)
        if !fa.is_definition && !fa.is_hidden {
          for p in merged_patterns {
            if !unify(p.label_pattern, VString(fa.name)).is_bottom() {
              val = unify(val, p.value)
            }
          }
        }
        merged_fields.push({
          name: fa.name,
          value: val,
          constraint: unify_field_constraint(fa.constraint, fb.constraint),
          is_definition: fa.is_definition || fb.is_definition,
          is_hidden: fa.is_hidden || fb.is_hidden,
        })
      }
      None => {
        let mut val = fa.value
        if sb.is_closed &&
          !fa.is_definition &&
          !fa.is_hidden &&
          fa.constraint != Optional &&
          !field_matches_any_pattern(fa.name, sb.patterns) {
          val = Value::bottom(
            ClosedStructError,
            "field '\{fa.name}' not allowed in closed struct",
          )
        } else if !fa.is_definition && !fa.is_hidden {
          for p in sb.patterns {
            if !unify(p.label_pattern, VString(fa.name)).is_bottom() {
              val = unify(val, p.value)
            }
          }
        }
        merged_fields.push({ ..fa, value: val, })
      }
    }
  }
  for fb in sb.fields {
    if sa.get_field(fb.name) is None {
      let mut val = fb.value
      if sa.is_closed &&
        !fb.is_definition &&
        !fb.is_hidden &&
        fb.constraint != Optional &&
        !field_matches_any_pattern(fb.name, sa.patterns) {
        val = Value::bottom(
          ClosedStructError,
          "field '\{fb.name}' not allowed in closed struct",
        )
      } else if !fb.is_definition && !fb.is_hidden {
        for p in sa.patterns {
          if !unify(p.label_pattern, VString(fb.name)).is_bottom() {
            val = unify(val, p.value)
          }
        }
      }
      merged_fields.push({ ..fb, value: val, })
    }
  }

  // Merge embeds
  let merged_embed : Value? = match (sa.embed, sb.embed) {
    (None, None) => None
    (Some(e), None) | (None, Some(e)) => Some(e)
    (Some(ea), Some(eb)) => {
      let u = unify(ea, eb)
      if u.is_bottom() {
        return u
      }
      Some(u)
    }
  }

  // If struct has a non-struct embed AND regular fields, CUE treats that as conflict
  match merged_embed {
    Some(e) =>
      for f in merged_fields {
        if !f.is_definition && !f.is_hidden && f.constraint == Regular {
          return Value::bottom(
            ConflictError,
            "cannot mix scalar/list embedding \{format_value(e)} with regular field '\{f.name}'",
          )
        }
      }
    None => ()
  }

  VStruct({
    fields: merged_fields,
    patterns: merged_patterns,
    is_closed: sa.is_closed || sb.is_closed,
    embed: merged_embed,
  })
}

///|
fn unify_struct_and_non_struct(s : StructVal, other : Value) -> Value {
  match s.embed {
    Some(e) => {
      let u = unify(e, other)
      if u.is_bottom() {
        u
      } else {
        VStruct({ ..s, embed: Some(u), })
      }
    }
    None =>
      // A struct with only definitions/hidden fields and an embed can unify,
      // otherwise a regular struct conflicts with a non-struct value.
      Value::bottom(
        ConflictError,
        "conflicting values struct and \{format_value(other)}",
      )
  }
}

///|
fn unify_lists(la : ListVal, lb : ListVal) -> Value {
  let len_a = la.elems.length()
  let len_b = lb.elems.length()
  let max_len = if len_a > len_b { len_a } else { len_b }
  let merged : Array[Value] = []

  for i = 0; i < max_len; i = i + 1 {
    let elem_a : Value = if i < len_a {
      la.elems[i]
    } else {
      match la.open_tail {
        Some(t) => t
        None =>
          return Value::bottom(
            ConflictError,
            "incompatible list lengths (\{len_a} and \{len_b})",
          )
      }
    }
    let elem_b : Value = if i < len_b {
      lb.elems[i]
    } else {
      match lb.open_tail {
        Some(t) => t
        None =>
          return Value::bottom(
            ConflictError,
            "incompatible list lengths (\{len_a} and \{len_b})",
          )
      }
    }
    let u = unify(elem_a, elem_b)
    if u.is_bottom() {
      // Attach index path to diagnostics
      match u {
        VBottom(es) => {
          let prefixed : Array[CueError] = []
          for e in es {
            prefixed.push(e.with_path_prefix("[\{i}]"))
          }
          return VBottom(prefixed)
        }
        _ => return u
      }
    }
    merged.push(u)
  }

  let tail : Value? = match (la.open_tail, lb.open_tail) {
    (Some(ta), Some(tb)) => Some(unify(ta, tb))
    _ => None
  }

  VList({ elems: merged, open_tail: tail, })
}

///|
/// Returns true iff `a` subsumes `b` in the CUE value lattice (`a ⊒ b`),
/// meaning every concrete instance of `b` is also a valid instance of `a`.
pub fn subsumes(a : Value, b : Value) -> Bool {
  if a.is_top() || b.is_bottom() {
    return true
  }
  if a.is_bottom() {
    return false
  }
  match (a, b) {
    (VDisjunction(da), _) => {
      for d in da {
        if subsumes(d.value, b) {
          return true
        }
      }
      false
    }
    (_, VDisjunction(db)) => {
      for d in db {
        if !subsumes(a, d.value) {
          return false
        }
      }
      true
    }
    _ => {
      let u = unify(a, b)
      !u.has_error() && u == b
    }
  }
}

///|
/// Format any CUE `Value` into readable CUE syntax (matching `cue eval`).
pub fn format_value(val : Value) -> String {
  format_value_indent(val, 0)
}

///|
fn write_indent(buf : StringBuilder, depth : Int32) -> Unit {
  for _i = 0; _i < depth; _i = _i + 1 {
    buf.write_string("  ")
  }
}

///|
fn format_value_indent(val : Value, depth : Int32) -> String {
  match val {
    VTop => "_"
    VBottom(errs) => if errs.is_empty() { "_|_" } else { "_|_ // \{errs[0]}" }
    VNull => "null"
    VBool(b) => if b { "true" } else { "false" }
    VInt(i) => "\{i}"
    VFloat(f) => "\{f}"
    VString(s) => escape_cue_string(s)
    VBytes(b) => "'\\x...(\{b.length()} bytes)'"
    VBasic(k) => "\{k}"
    VBound(b) => "\{b}"
    VConjunction(items) => {
      let buf = StringBuilder()
      for i = 0; i < items.length(); i = i + 1 {
        if i > 0 {
          buf.write_string(" & ")
        }
        buf.write_string(format_value_indent(items[i], depth))
      }
      buf.to_string()
    }
    VDisjunction(ds) => {
      let buf = StringBuilder()
      for i = 0; i < ds.length(); i = i + 1 {
        if i > 0 {
          buf.write_string(" | ")
        }
        if ds[i].is_default {
          buf.write_char('*')
        }
        buf.write_string(format_value_indent(ds[i].value, depth))
      }
      buf.to_string()
    }
    VList(l) => {
      let buf = StringBuilder()
      buf.write_char('[')
      for i = 0; i < l.elems.length(); i = i + 1 {
        if i > 0 {
          buf.write_string(", ")
        }
        buf.write_string(format_value_indent(l.elems[i], depth))
      }
      match l.open_tail {
        Some(t) => {
          if !l.elems.is_empty() {
            buf.write_string(", ")
          }
          buf.write_string("...")
          if !t.is_top() {
            buf.write_string(format_value_indent(t, depth))
          }
        }
        None => ()
      }
      buf.write_char(']')
      buf.to_string()
    }
    VStruct(s) => {
      if s.fields.is_empty() && s.patterns.is_empty() {
        return "{}"
      }
      let buf = StringBuilder()
      buf.write_string("{\n")
      for f in s.fields {
        write_indent(buf, depth + 1)
        if is_valid_cue_ident(f.name) {
          buf.write_string(f.name)
        } else {
          buf.write_string(escape_cue_string(f.name))
        }
        match f.constraint {
          Regular => ()
          Optional => buf.write_char('?')
          Required => buf.write_char('!')
        }
        buf.write_string(": ")
        buf.write_string(format_value_indent(f.value, depth + 1))
        buf.write_char('\n')
      }
      for p in s.patterns {
        write_indent(buf, depth + 1)
        buf.write_char('[')
        buf.write_string(format_value_indent(p.label_pattern, depth + 1))
        buf.write_string("]: ")
        buf.write_string(format_value_indent(p.value, depth + 1))
        buf.write_char('\n')
      }
      write_indent(buf, depth)
      buf.write_char('}')
      buf.to_string()
    }
  }
}

///|
fn is_valid_cue_ident(name : String) -> Bool {
  let chars = name.to_array()
  if chars.is_empty() {
    return false
  }
  if !is_ident_start(chars[0]) {
    return false
  }
  for i = 1; i < chars.length(); i = i + 1 {
    if !is_ident_continue(chars[i]) {
      return false
    }
  }
  true
}

///|
fn escape_cue_string(s : String) -> String {
  let buf = StringBuilder()
  buf.write_char('"')
  for ch in s {
    match ch {
      '"' => buf.write_string("\\\"")
      '\\' => buf.write_string("\\\\")
      '\n' => buf.write_string("\\n")
      '\r' => buf.write_string("\\r")
      '\t' => buf.write_string("\\t")
      _ => buf.write_char(ch)
    }
  }
  buf.write_char('"')
  buf.to_string()
}