///|
/// Numeric type kind in the CUE value lattice.
#derive(Eq, Debug)
pub(all) enum NumKind {
  Number
  Int
  Float
}

///|
/// Unifies two numeric kinds (`Number & Int = Int`, `Number & Float = Float`,
/// `Int & Float = None`).
pub fn NumKind::unify(self : NumKind, other : NumKind) -> NumKind? {
  match (self, other) {
    (Number, k) | (k, Number) => Some(k)
    (Int, Int) => Some(Int)
    (Float, Float) => Some(Float)
    (Int, Float) | (Float, Int) => None
  }
}

///|
/// Formats a `NumKind` as its canonical CUE keyword (`number`, `int`, `float`).
pub fn NumKind::format(self : NumKind) -> String {
  match self {
    Number => "number"
    Int => "int"
    Float => "float"
  }
}

///|
/// A concrete CUE numeric value preserving the distinction between exact
/// arbitrary-precision `Int(BigInt)` and arbitrary-precision decimal `Float(Decimal)`.
#derive(Debug)
pub(all) enum NumValue {
  Int(BigInt)
  Float(Decimal)
}

///|
/// Structural equality on `NumValue`: in CUE, `1` (`Int`) and `1.0` (`Float`)
/// have distinct types and are not equal under `Eq`, whereas numerically
/// `compare_num(Int(1), Float(1.0)) == 0`.
pub impl Eq for NumValue with fn equal(self, other) {
  match (self, other) {
    (Int(a), Int(b)) => a == b
    (Float(a), Float(b)) => a == b
    _ => false
  }
}

///|
/// Constructs a `NumValue::Int` from a `BigInt`.
pub fn NumValue::int(n : BigInt) -> NumValue {
  Int(n)
}

///|
/// Constructs a `NumValue::Float` directly from an exact normalized `Decimal`.
pub fn NumValue::decimal(d : Decimal) -> NumValue {
  Float(d)
}

///|
/// Constructs a validated finite `NumValue::Float` from a `Double`, rejecting
/// `NaN` and `±Inf` and normalizing `-0.0` to `0.0`.
pub fn NumValue::float(d : Double) -> Result[NumValue, String] {
  match Decimal::from_double(d) {
    Ok(dec) => Ok(Float(dec))
    Err(msg) => Err(msg)
  }
}

///|
/// Returns the concrete `NumKind` (`Int` or `Float`) of a `NumValue`.
pub fn NumValue::kind(self : NumValue) -> NumKind {
  match self {
    Int(_) => Int
    Float(_) => Float
  }
}

///|
fn validate_num_value(v : NumValue) -> Result[NumValue, String] {
  Ok(v)
}

///|
/// Formats a `NumValue` into valid CUE numeric syntax (`Float` always includes
/// a decimal point or exponent so it stays distinguishable from `Int`).
pub fn NumValue::format(self : NumValue) -> String {
  match self {
    Int(n) => n.to_string()
    Float(d) => d.format_cue()
  }
}

///|
fn is_dec_digit(ch : Char) -> Bool {
  ch >= '0' && ch <= '9'
}

///|
fn is_hex_digit(ch : Char) -> Bool {
  (ch >= '0' && ch <= '9') ||
  (ch >= 'a' && ch <= 'f') ||
  (ch >= 'A' && ch <= 'F')
}

///|
fn is_oct_digit(ch : Char) -> Bool {
  ch >= '0' && ch <= '7'
}

///|
fn is_bin_digit(ch : Char) -> Bool {
  ch == '0' || ch == '1'
}

///|
fn scan_validated_digits(
  chars : Array[Char],
  start : Int32,
  is_digit : (Char) -> Bool,
  out : StringBuilder,
) -> (Int32, Int32, Bool) {
  let mut i = start
  let mut digits = 0
  let mut prev_underscore = false
  let mut invalid = false
  while i < chars.length() {
    let ch = chars[i]
    if is_digit(ch) {
      out.write_char(ch)
      digits += 1
      prev_underscore = false
      i += 1
    } else if ch == '_' {
      if digits == 0 || prev_underscore {
        invalid = true
      }
      prev_underscore = true
      i += 1
    } else {
      break
    }
  }
  if prev_underscore {
    invalid = true
  }
  (i, digits, invalid)
}

///|
fn parse_multiplier_suffix(
  chars : Array[Char],
  start : Int32,
) -> (BigInt, Int32, Int32)? {
  if start >= chars.length() {
    return None
  }
  let ch = chars[start]
  let has_i = start + 1 < chars.length() && chars[start + 1] == 'i'
  let next_idx = if has_i { start + 2 } else { start + 1 }
  if next_idx != chars.length() {
    return None
  }
  if has_i {
    let shift = match ch {
      'K' => 10
      'M' => 20
      'G' => 30
      'T' => 40
      'P' => 50
      _ => return None
    }
    Some((BigInt::from_int(1) << shift, shift, next_idx))
  } else {
    let power = match ch {
      'K' => 3
      'M' => 6
      'G' => 9
      'T' => 12
      'P' => 15
      _ => return None
    }
    Some((pow10_bigint(power), power, next_idx))
  }
}

///|
fn pow10_bigint(exp : Int32) -> BigInt {
  let mut result = BigInt::from_int(1)
  let ten = BigInt::from_int(10)
  for _ in 0.. String {
  let chars = digits.to_array()
  let mut end = chars.length()
  while end > 0 && chars[end - 1] == '0' {
    end -= 1
  }
  if end == chars.length() {
    return digits
  }
  let sb = StringBuilder()
  for i in 0.. Result[BigInt, String] {
  if raw.is_empty() {
    return Err("invalid integer literal: empty input")
  }
  let chars = raw.to_array()
  // Base-prefixed integers: 0x/0X, 0o/0O, 0b/0B (no dot or SI/IEC multiplier).
  if chars.length() >= 2 && chars[0] == '0' {
    let base_info : (Int32, (Char) -> Bool)? = match chars[1] {
      'x' | 'X' => Some((16, is_hex_digit))
      'o' | 'O' => Some((8, is_oct_digit))
      'b' | 'B' => Some((2, is_bin_digit))
      _ => None
    }
    match base_info {
      Some((radix, pred)) => {
        let digits_buf = StringBuilder()
        let (next_idx, count, bad) = scan_validated_digits(
          chars, 2, pred, digits_buf,
        )
        if count == 0 || bad || next_idx != chars.length() {
          return Err("invalid integer literal '\{raw}'")
        }
        let parsed = @string.parse_bigint(digits_buf.to_string(), radix~) catch {
          _ => return Err("invalid integer literal '\{raw}'")
        }
        return Ok(parsed)
      }
      None => ()
    }
  }
  // Leading-dot SI/IEC literal such as `.5K` or `.5Ki`.
  let int_buf = StringBuilder()
  let frac_buf = StringBuilder()
  let mut idx = 0
  let mut int_count = 0
  let mut has_dot = false
  let mut frac_count = 0
  if chars[0] == '.' {
    has_dot = true
    idx = 1
    let (after_frac, fc, fbad) = scan_validated_digits(
      chars, idx, is_dec_digit, frac_buf,
    )
    if fc == 0 || fbad {
      return Err("invalid integer literal '\{raw}'")
    }
    frac_count = fc
    idx = after_frac
  } else {
    let (after_int, ic, ibad) = scan_validated_digits(
      chars, 0, is_dec_digit, int_buf,
    )
    if ic == 0 || ibad {
      return Err("invalid integer literal '\{raw}'")
    }
    int_count = ic
    idx = after_int
    if idx < chars.length() && chars[idx] == '.' {
      has_dot = true
      idx += 1
      let (after_frac, fc, fbad) = scan_validated_digits(
        chars, idx, is_dec_digit, frac_buf,
      )
      if fc == 0 || fbad {
        return Err("invalid integer literal '\{raw}'")
      }
      frac_count = fc
      idx = after_frac
    }
  }
  if idx == chars.length() {
    // Plain decimal integer (no multiplier).
    if has_dot {
      return Err("invalid integer literal '\{raw}': unexpected decimal point")
    }
    if chars[0] == '0' && chars.length() > 1 {
      return Err("invalid integer literal '\{raw}': leading zero not allowed")
    }
    let _ = int_count
    let _ = frac_count
    let parsed = @string.parse_bigint(int_buf.to_string(), radix=10) catch {
      _ => return Err("invalid integer literal '\{raw}'")
    }
    return Ok(parsed)
  }
  // Parse SI/IEC multiplier suffix.
  let (mult, max_frac_scale, end_idx) = match
    parse_multiplier_suffix(chars, idx) {
    Some(info) => info
    None => return Err("invalid integer literal '\{raw}'")
  }
  if end_idx != chars.length() {
    return Err("invalid integer literal '\{raw}'")
  }
  let int_digits = int_buf.to_string()
  if !has_dot {
    let base_val = @string.parse_bigint(int_digits, radix=10) catch {
      _ => return Err("invalid integer literal '\{raw}'")
    }
    return Ok(base_val * mult)
  }
  let trimmed_frac = trim_trailing_zeros(frac_buf.to_string())
  let scale = trimmed_frac.length()
  if scale == 0 {
    let base_val = if int_digits.is_empty() {
      BigInt::from_int(0)
    } else {
      @string.parse_bigint(int_digits, radix=10) catch {
        _ => return Err("invalid integer literal '\{raw}'")
      }
    }
    return Ok(base_val * mult)
  }
  // After stripping trailing zeros from the fractional part, the final digit is
  // non-zero. For SI (10^p) or IEC (2^p), digits_val * mult / 10^scale cannot
  // be an integer whenever scale > p.
  if scale > max_frac_scale {
    return Err(
      "invalid integer literal '\{raw}': fractional multiplier is not an exact integer",
    )
  }
  let combined = int_digits + trimmed_frac
  let digits_val = @string.parse_bigint(combined, radix=10) catch {
    _ => return Err("invalid integer literal '\{raw}'")
  }
  let numerator = digits_val * mult
  let denominator = pow10_bigint(scale)
  if !(numerator % denominator).is_zero() {
    return Err(
      "invalid integer literal '\{raw}': fractional multiplier is not an exact integer",
    )
  }
  Ok(numerator / denominator)
}

///|
/// Exact IEEE-754 binary64 round-to-nearest-even conversion from validated
/// unsigned decimal digits (`sig_digits`, no leading zeros) and base-10
/// exponent `exp10` representing `sig_digits * 10^exp10`.
fn decimal_to_finite_double(
  sig_digits : String,
  exp10 : Int32,
) -> Result[Double, String] {
  if sig_digits.is_empty() {
    return Ok(0.0)
  }
  // Truncate beyond 768 significant digits with a sticky '1' digit.
  // Every exact binary64 midpoint has at most 752 significant decimal digits,
  // so keeping 768 digits + 1 sticky digit is exact for round-to-nearest-even.
  let chars = sig_digits.to_array()
  let mut eff_digits = sig_digits
  let mut eff_exp10 = exp10
  if chars.length() > 768 {
    let sb = StringBuilder()
    for i in 0..<768 {
      sb.write_char(chars[i])
    }
    let mut sticky = false
    for i in 768..= 310 {
    return Err("float overflow")
  }
  if mag_hi <= -324 {
    return Ok(0.0)
  }
  let mantissa = @string.parse_bigint(trimmed, radix=10) catch {
    _ => return Err("invalid decimal mantissa '\{trimmed}'")
  }
  let (num_raw, den_raw) = if eff_exp10 >= 0 {
    (mantissa * pow10_bigint(eff_exp10), BigInt::from_int(1))
  } else {
    (mantissa, pow10_bigint(-eff_exp10))
  }
  // Compute exact k = floor(log2(num_raw / den_raw)).
  let mut k = num_raw.bit_length() - den_raw.bit_length()
  let less_than_pow2k = if k >= 0 {
    num_raw < den_raw << k
  } else {
    num_raw << -k < den_raw
  }
  if less_than_pow2k {
    k -= 1
  }
  if k > 1023 {
    return Err("float overflow")
  }
  if k < -1075 {
    return Ok(0.0)
  }
  // Scale to 53-bit significand (normal) or 2^-1074 quantum (subnormal).
  let scale = if k - 52 > -1074 { k - 52 } else { -1074 }
  let (num, den) = if scale >= 0 {
    (num_raw, den_raw << scale)
  } else {
    (num_raw << -scale, den_raw)
  }
  let mut q = num / den
  let rem = num % den
  let twice_rem = rem << 1
  let one = BigInt::from_int(1)
  if twice_rem > den || (twice_rem == den && !(q & one).is_zero()) {
    q = q + one
  }
  let q_u64 = q.to_uint64()
  if k <= -1023 {
    // Subnormal (or rounded up into smallest normal 2^-1022).
    if q_u64 == 1UL << 52 {
      Ok((1UL << 52).reinterpret_as_double())
    } else {
      Ok(q_u64.reinterpret_as_double())
    }
  } else {
    let mut final_k = k
    let mut final_q = q_u64
    if final_q == 1UL << 53 {
      final_q = final_q >> 1
      final_k += 1
    }
    if final_k > 1023 {
      return Err("float overflow")
    }
    let exp_bits = (final_k + 1023).to_uint64()
    let frac_bits = final_q & 0x000F_FFFF_FFFF_FFFFUL
    Ok(((exp_bits << 52) | frac_bits).reinterpret_as_double())
  }
}

///|
/// Parses a CUE floating-point literal into a finite `Double`.
///
/// Supports `_` separators, trailing dot (`0.`, `1.`, `1.e5`), leading dot
/// (`.5`, `.5e-3`), and exponents (`1e5`, `2.5e-3`). Rejects malformed literals
/// as well as `NaN` and `±Inf` overflow, normalizing `-0.0` to `0.0`.
pub fn parse_float_literal(raw : String) -> Result[Double, String] {
  if raw.is_empty() {
    return Err("invalid float literal: empty input")
  }
  let chars = raw.to_array()
  let int_buf = StringBuilder()
  let frac_buf = StringBuilder()
  let mut idx = 0
  let mut int_count = 0
  let mut frac_count = 0
  if chars[0] != '.' {
    let (after_int, ic, ibad) = scan_validated_digits(
      chars, 0, is_dec_digit, int_buf,
    )
    if ic == 0 || ibad {
      return Err("invalid float literal '\{raw}'")
    }
    int_count = ic
    idx = after_int
  }
  if idx < chars.length() && chars[idx] == '.' {
    idx += 1
    let (after_frac, fc, fbad) = scan_validated_digits(
      chars, idx, is_dec_digit, frac_buf,
    )
    if fbad {
      return Err("invalid float literal '\{raw}'")
    }
    frac_count = fc
    idx = after_frac
  }
  if int_count == 0 && frac_count == 0 {
    return Err("invalid float literal '\{raw}'")
  }
  let mut exp_neg = false
  let mut exp_abs = 0L
  let raw_len = chars.length().to_int64()
  let exp_sat = if raw_len + 10_000L > 1_000_000L {
    raw_len + 10_000L
  } else {
    1_000_000L
  }
  if idx < chars.length() && (chars[idx] == 'e' || chars[idx] == 'E') {
    idx += 1
    if idx < chars.length() {
      if chars[idx] == '+' {
        idx += 1
      } else if chars[idx] == '-' {
        exp_neg = true
        idx += 1
      }
    }
    let exp_buf = StringBuilder()
    let (after_exp, ec, ebad) = scan_validated_digits(
      chars, idx, is_dec_digit, exp_buf,
    )
    if ec == 0 || ebad {
      return Err("invalid float literal '\{raw}'")
    }
    idx = after_exp
    // Saturate exponent magnitude well beyond raw length + IEEE-754 range so
    // mantissa/fraction offsets can never be masked by premature saturation.
    for ch in exp_buf.to_string() {
      if exp_abs < exp_sat {
        exp_abs = exp_abs * 10L + (ch.to_int() - '0'.to_int()).to_int64()
        if exp_abs > exp_sat {
          exp_abs = exp_sat
        }
      }
    }
  }
  if idx != chars.length() {
    return Err("invalid float literal '\{raw}'")
  }
  // Collect significant digits (skipping leading zeros) and compute base-10 exponent.
  let combined = int_buf.to_string() + frac_buf.to_string()
  let sig_buf = StringBuilder()
  let mut seen_nonzero = false
  let mut sig_len = 0
  for ch in combined {
    if !seen_nonzero && ch == '0' {
      continue
    }
    seen_nonzero = true
    sig_len += 1
    sig_buf.write_char(ch)
  }
  if !seen_nonzero {
    return Ok(0.0)
  }
  // Compute net order of magnitude after accounting for mantissa and fraction digits
  // before short-circuiting overflow or underflow.
  let signed_exp = if exp_neg { -exp_abs } else { exp_abs }
  let total_exp10_64 = signed_exp - frac_count.to_int64()
  let net_exp = total_exp10_64 + (sig_len - 1).to_int64()
  if net_exp > 310L {
    return Err("invalid float literal '\{raw}': float overflow")
  }
  if net_exp < -330L {
    return Ok(0.0)
  }
  match decimal_to_finite_double(sig_buf.to_string(), total_exp10_64.to_int()) {
    Ok(d) => Ok(if d == 0.0 { 0.0 } else { d })
    Err(_) => Err("invalid float literal '\{raw}': float overflow")
  }
}

///|
/// Decodes a finite IEEE-754 binary64 `Double` into exact `(floor, ceil, is_exact_int)`.
///
/// Never casts arbitrary-size `BigInt` to `Double`: every finite subnormal,
/// normal, negative, and huge-exponent `Double` is decoded directly from its
/// 64-bit IEEE-754 representation.
fn double_int_bounds(d : Double) -> (BigInt, BigInt, Bool) {
  let bits = d.reinterpret_as_uint64()
  let neg = ((bits >> 63) & 1UL) != 0UL
  let exp_bits = ((bits >> 52) & 0x7FFUL).to_int()
  let frac_bits = bits & 0x000F_FFFF_FFFF_FFFFUL
  let zero = BigInt::from_int(0)
  let one = BigInt::from_int(1)
  // Non-finite fallback (callers validate finite doubles).
  if exp_bits == 0x7FF {
    return (zero, zero, false)
  }
  // +0.0 or -0.0
  if exp_bits == 0 && frac_bits == 0UL {
    return (zero, zero, true)
  }
  // Subnormal: 0 < |d| < 2^-1022 < 1
  if exp_bits == 0 {
    return if neg { (-one, zero, false) } else { (zero, one, false) }
  }
  // Normal: value = (-1)^neg * sig * 2^exp2, with 2^52 <= sig < 2^53.
  let sig = (1UL << 52) | frac_bits
  let exp2 = exp_bits - 1023 - 52
  if exp2 >= 0 {
    let mag = BigInt::from_uint64(sig) << exp2
    let exact = if neg { -mag } else { mag }
    return (exact, exact, true)
  }
  let shift = -exp2
  if shift >= 53 {
    // Since sig < 2^53 <= 2^shift, 0 < |d| < 1 strictly.
    return if neg { (-one, zero, false) } else { (zero, one, false) }
  }
  // 1 <= shift <= 52: exact split into integer quotient and remainder bits.
  let int_part = sig >> shift
  let rem_mask = (1UL << shift) - 1UL
  let has_frac = (sig & rem_mask) != 0UL
  let q = BigInt::from_uint64(int_part)
  if !has_frac {
    let exact = if neg { -q } else { q }
    (exact, exact, true)
  } else if neg {
    (-(q + one), -q, false)
  } else {
    (q, q + one, false)
  }
}

///|
/// Returns the exact mathematical floor of a finite `Double` as a `BigInt`.
pub fn floor_to_bigint(d : Double) -> BigInt {
  double_int_bounds(d).0
}

///|
/// Returns the exact mathematical ceiling of a finite `Double` as a `BigInt`.
pub fn ceil_to_bigint(d : Double) -> BigInt {
  double_int_bounds(d).1
}

///|
fn normalize_cmp(c : Int32) -> Int32 {
  if c < 0 {
    -1
  } else if c > 0 {
    1
  } else {
    0
  }
}

///|
/// Compares two `NumValue`s numerically, returning `-1`, `0`, or `+1`.
///
/// Cross-type comparison between `Int(BigInt)` and `Float(Decimal)` is exact
/// (never rounds through IEEE-754 `Double`), so `2^53 + 1 > Float(2^53)` and
/// `compare_num(Int(1), Float(Decimal("1.0"))) == 0`.
pub fn compare_num(a : NumValue, b : NumValue) -> Int32 {
  match (a, b) {
    (Int(x), Int(y)) => normalize_cmp(x.compare(y))
    (Float(x), Float(y)) => x.compare(y)
    (Int(x), Float(y)) => -y.compare_bigint(x)
    (Float(x), Int(y)) => x.compare_bigint(y)
  }
}

///|
/// Deterministic canonical tie-breaker when `compare_num(a, b) == 0`.
/// Always prefers `Int` over `Float` so lattice unification is commutative,
/// associative, and idempotent.
fn prefer_int(a : NumValue, b : NumValue) -> NumValue {
  match (a, b) {
    (Int(_), _) => a
    (_, Int(_)) => b
    (Float(_), Float(_)) => a
  }
}

///|
/// Ordering and inequality bound operators supported by CUE constraints.
#derive(Eq, Debug)
pub(all) enum BoundOp {
  Lt
  Le
  Gt
  Ge
  Neq
}

///|
/// Canonical normalized numeric constraint bounds in the CUE value lattice.
///
/// Invariants maintained by all constructors and `unify`:
/// - All stored `Float` values are finite and `-0.0` is normalized to `0.0`.
/// - When `kind == Int`, `lower` and `upper` (if present) are always inclusive
///   `Int(BigInt)` values, and `excluded` contains only strictly interior
///   sorted unique `Int(BigInt)` values (endpoints are tightened past excluded
///   boundary integers).
/// - When `kind` is `Number` or `Float`, `excluded` is sorted ascending by
///   `compare_num`, deduplicated (preferring `Int` on ties), and contains only
///   values strictly inside `(lower, upper)`; any excluded value equal to an
///   inclusive endpoint tightens that endpoint to exclusive.
#derive(Eq, Debug)
pub(all) struct NumBounds {
  kind : NumKind
  lower : (NumValue, Bool)?
  upper : (NumValue, Bool)?
  excluded : Array[NumValue]
}

///|
/// Constructs an unconstrained `NumBounds` of the given `NumKind`.
pub fn NumBounds::of_kind(kind : NumKind) -> NumBounds {
  { kind, lower: None, upper: None, excluded: [], }
}

///|
/// Constructs a `NumBounds` from a single unary bound operator and value.
///
/// The resulting `NumBounds` has `kind = Number` (per CUE semantics, numeric
/// bounds like `>=1` or `>=1.5` accept both `int` and `float` until narrowed).
pub fn NumBounds::from_bound(
  op : BoundOp,
  val : NumValue,
) -> Result[NumBounds, String] {
  let v = match validate_num_value(val) {
    Ok(clean) => clean
    Err(msg) => return Err(msg)
  }
  match op {
    Lt =>
      Ok({ kind: Number, lower: None, upper: Some((v, false)), excluded: [], })
    Le =>
      Ok({ kind: Number, lower: None, upper: Some((v, true)), excluded: [], })
    Gt =>
      Ok({ kind: Number, lower: Some((v, false)), upper: None, excluded: [], })
    Ge =>
      Ok({ kind: Number, lower: Some((v, true)), upper: None, excluded: [], })
    Neq => Ok({ kind: Number, lower: None, upper: None, excluded: [v], })
  }
}

///|
fn int_lower_bound(val : NumValue, inclusive : Bool) -> Result[BigInt, String] {
  let one = BigInt::from_int(1)
  match val {
    Int(n) => Ok(if inclusive { n } else { n + one })
    Float(d) =>
      if inclusive {
        d.ceil()
      } else {
        match d.floor() {
          Ok(fl) => Ok(fl + one)
          Err(msg) => Err(msg)
        }
      }
  }
}

///|
fn int_upper_bound(val : NumValue, inclusive : Bool) -> Result[BigInt, String] {
  let one = BigInt::from_int(1)
  match val {
    Int(n) => Ok(if inclusive { n } else { n - one })
    Float(d) =>
      if inclusive {
        d.floor()
      } else {
        match d.ceil() {
          Ok(ce) => Ok(ce - one)
          Err(msg) => Err(msg)
        }
      }
  }
}

///|
fn normalize_int_bounds(
  lower : (NumValue, Bool)?,
  upper : (NumValue, Bool)?,
  excluded : Array[NumValue],
) -> Result[NumBounds, String] {
  let one = BigInt::from_int(1)
  let mut lo_opt : BigInt? = match lower {
    Some((v, inc)) =>
      match int_lower_bound(v, inc) {
        Ok(b) => Some(b)
        Err(msg) => return Err(msg)
      }
    None => None
  }
  let mut hi_opt : BigInt? = match upper {
    Some((v, inc)) =>
      match int_upper_bound(v, inc) {
        Ok(b) => Some(b)
        Err(msg) => return Err(msg)
      }
    None => None
  }
  // Collect only exact integer exclusions (non-integral float != can never
  // match an integer).
  let int_excl : Array[BigInt] = []
  for item in excluded {
    match item {
      Int(n) => int_excl.push(n)
      Float(d) =>
        if d.is_exact_int() {
          match d.floor() {
            Ok(fl) => int_excl.push(fl)
            Err(msg) => return Err(msg)
          }
        }
    }
  }
  int_excl.sort_by(fn(a, b) { normalize_cmp(a.compare(b)) })
  // Deduplicate sorted integer exclusions.
  let unique_excl : Array[BigInt] = []
  for n in int_excl {
    if unique_excl.is_empty() || unique_excl[unique_excl.length() - 1] != n {
      unique_excl.push(n)
    }
  }
  // Linear tightening of lower and upper integer endpoints past excluded values.
  let mut start = 0
  let mut end_excl = unique_excl.length() - 1
  match lo_opt {
    Some(lo_init) => {
      let mut lo = lo_init
      while start <= end_excl && unique_excl[start] < lo {
        start += 1
      }
      while start <= end_excl && unique_excl[start] == lo {
        lo = lo + one
        start += 1
      }
      lo_opt = Some(lo)
    }
    None => ()
  }
  match hi_opt {
    Some(hi_init) => {
      let mut hi = hi_init
      while end_excl >= start && unique_excl[end_excl] > hi {
        end_excl -= 1
      }
      while end_excl >= start && unique_excl[end_excl] == hi {
        hi = hi - one
        end_excl -= 1
      }
      hi_opt = Some(hi)
    }
    None => ()
  }
  match (lo_opt, hi_opt) {
    (Some(lo), Some(hi)) =>
      if lo > hi {
        return Err(
          "conflicting integer bounds: >= \{lo.to_string()} and <= \{hi.to_string()} have no integer solution",
        )
      }
    _ => ()
  }
  let final_excl : Array[NumValue] = []
  let mut i = start
  while i <= end_excl {
    final_excl.push(Int(unique_excl[i]))
    i += 1
  }
  let final_lower : (NumValue, Bool)? = match lo_opt {
    Some(lo) => Some((NumValue::Int(lo), true))
    None => None
  }
  let final_upper : (NumValue, Bool)? = match hi_opt {
    Some(hi) => Some((NumValue::Int(hi), true))
    None => None
  }
  Ok({
    kind: Int,
    lower: final_lower,
    upper: final_upper,
    excluded: final_excl,
  })
}

///|
fn normalize_num_bounds(
  kind : NumKind,
  lower : (NumValue, Bool)?,
  upper : (NumValue, Bool)?,
  excluded : Array[NumValue],
) -> Result[NumBounds, String] {
  let clean_lower = match lower {
    Some((v, inc)) =>
      match validate_num_value(v) {
        Ok(cv) => Some((cv, inc))
        Err(msg) => return Err(msg)
      }
    None => None
  }
  let clean_upper = match upper {
    Some((v, inc)) =>
      match validate_num_value(v) {
        Ok(cv) => Some((cv, inc))
        Err(msg) => return Err(msg)
      }
    None => None
  }
  let clean_excl : Array[NumValue] = []
  for item in excluded {
    match validate_num_value(item) {
      Ok(cv) => clean_excl.push(cv)
      Err(msg) => return Err(msg)
    }
  }
  if kind == Int {
    return normalize_int_bounds(clean_lower, clean_upper, clean_excl)
  }
  // Sort and deduplicate exclusions for Number / Float, preferring Int on
  // numerically equal values.
  clean_excl.sort_by(compare_num)
  let unique_excl : Array[NumValue] = []
  for item in clean_excl {
    if unique_excl.is_empty() {
      unique_excl.push(item)
    } else {
      let last_idx = unique_excl.length() - 1
      let prev = unique_excl[last_idx]
      if compare_num(prev, item) == 0 {
        unique_excl[last_idx] = prefer_int(prev, item)
      } else {
        unique_excl.push(item)
      }
    }
  }
  // Tighten inclusive endpoints if the endpoint itself is excluded.
  // Keeping the endpoint's own NumValue representation preserves associativity
  // across mixed Int/Float endpoints and exclusions.
  let mut norm_lower = clean_lower
  let mut norm_upper = clean_upper
  match norm_lower {
    Some((lo_val, true)) =>
      for e in unique_excl {
        if compare_num(e, lo_val) == 0 {
          norm_lower = Some((lo_val, false))
          break
        }
      }
    _ => ()
  }
  match norm_upper {
    Some((hi_val, true)) =>
      for e in unique_excl {
        if compare_num(e, hi_val) == 0 {
          norm_upper = Some((hi_val, false))
          break
        }
      }
    _ => ()
  }
  // Check lower vs upper consistency.
  match (norm_lower, norm_upper) {
    (Some((lo_val, lo_inc)), Some((hi_val, hi_inc))) => {
      let cmp = compare_num(lo_val, hi_val)
      if cmp > 0 || (cmp == 0 && (!lo_inc || !hi_inc)) {
        let lo_op = if lo_inc { ">=" } else { ">" }
        let hi_op = if hi_inc { "<=" } else { "<" }
        return Err(
          "conflicting bounds: \{lo_op}\{lo_val.format()} and \{hi_op}\{hi_val.format()}",
        )
      }
    }
    _ => ()
  }
  // Keep only exclusions strictly inside (lower, upper).
  let final_excl : Array[NumValue] = []
  for e in unique_excl {
    let above_lo = match norm_lower {
      Some((lo_val, _)) => compare_num(e, lo_val) > 0
      None => true
    }
    let below_hi = match norm_upper {
      Some((hi_val, _)) => compare_num(e, hi_val) < 0
      None => true
    }
    if above_lo && below_hi {
      final_excl.push(e)
    }
  }
  Ok({ kind, lower: norm_lower, upper: norm_upper, excluded: final_excl, })
}

///|
fn merge_num_lower(
  a : (NumValue, Bool)?,
  b : (NumValue, Bool)?,
) -> (NumValue, Bool)? {
  match (a, b) {
    (None, x) | (x, None) => x
    (Some((va, ia)), Some((vb, ib))) => {
      let cmp = compare_num(va, vb)
      if cmp > 0 {
        Some((va, ia))
      } else if cmp < 0 {
        Some((vb, ib))
      } else {
        Some((prefer_int(va, vb), ia && ib))
      }
    }
  }
}

///|
fn merge_num_upper(
  a : (NumValue, Bool)?,
  b : (NumValue, Bool)?,
) -> (NumValue, Bool)? {
  match (a, b) {
    (None, x) | (x, None) => x
    (Some((va, ia)), Some((vb, ib))) => {
      let cmp = compare_num(va, vb)
      if cmp < 0 {
        Some((va, ia))
      } else if cmp > 0 {
        Some((vb, ib))
      } else {
        Some((prefer_int(va, vb), ia && ib))
      }
    }
  }
}

///|
fn validate_opt_bound(
  bound : (NumValue, Bool)?,
) -> Result[(NumValue, Bool)?, String] {
  match bound {
    Some((v, inc)) =>
      match validate_num_value(v) {
        Ok(clean) => Ok(Some((clean, inc)))
        Err(msg) => Err(msg)
      }
    None => Ok(None)
  }
}

///|
/// Unifies two `NumBounds`, returning the canonical tightened intersection or
/// an error if the bounds contradict each other.
pub fn NumBounds::unify(
  self : NumBounds,
  other : NumBounds,
) -> Result[NumBounds, String] {
  let self_lower = match validate_opt_bound(self.lower) {
    Ok(b) => b
    Err(msg) => return Err(msg)
  }
  let other_lower = match validate_opt_bound(other.lower) {
    Ok(b) => b
    Err(msg) => return Err(msg)
  }
  let self_upper = match validate_opt_bound(self.upper) {
    Ok(b) => b
    Err(msg) => return Err(msg)
  }
  let other_upper = match validate_opt_bound(other.upper) {
    Ok(b) => b
    Err(msg) => return Err(msg)
  }
  let kind = match self.kind.unify(other.kind) {
    Some(k) => k
    None => return Err("conflicting numeric types: int and float")
  }
  let merged_lower = merge_num_lower(self_lower, other_lower)
  let merged_upper = merge_num_upper(self_upper, other_upper)
  let combined_excl : Array[NumValue] = []
  for item in self.excluded {
    combined_excl.push(item)
  }
  for item in other.excluded {
    combined_excl.push(item)
  }
  normalize_num_bounds(kind, merged_lower, merged_upper, combined_excl)
}

///|
/// Checks whether a concrete `NumValue` satisfies all constraints in `self`.
pub fn NumBounds::matches(
  self : NumBounds,
  val : NumValue,
) -> Result[Unit, String] {
  let v = match validate_num_value(val) {
    Ok(clean) => clean
    Err(msg) => return Err(msg)
  }
  match (self.kind, v) {
    (Int, Float(_)) => return Err("type mismatch: expected int, got float")
    (Float, Int(_)) => return Err("type mismatch: expected float, got int")
    _ => ()
  }
  match self.lower {
    Some((lo, true)) =>
      if compare_num(v, lo) < 0 {
        return Err(
          "value \{v.format()} out of bounds: must be >=\{lo.format()}",
        )
      }
    Some((lo, false)) =>
      if compare_num(v, lo) <= 0 {
        return Err("value \{v.format()} out of bounds: must be >\{lo.format()}")
      }
    None => ()
  }
  match self.upper {
    Some((hi, true)) =>
      if compare_num(v, hi) > 0 {
        return Err(
          "value \{v.format()} out of bounds: must be <=\{hi.format()}",
        )
      }
    Some((hi, false)) =>
      if compare_num(v, hi) >= 0 {
        return Err("value \{v.format()} out of bounds: must be <\{hi.format()}")
      }
    None => ()
  }
  for e in self.excluded {
    if compare_num(v, e) == 0 {
      return Err("value \{v.format()} violates bound !=\{e.format()}")
    }
  }
  Ok(())
}

///|
/// Formats a `NumBounds` into canonical CUE display syntax (for example
/// `int & >=1 & <=65535`).
pub fn NumBounds::format(self : NumBounds) -> String {
  let parts : Array[String] = []
  match self.kind {
    Int => parts.push("int")
    Float => parts.push("float")
    Number =>
      if self.lower is None && self.upper is None && self.excluded.is_empty() {
        parts.push("number")
      }
  }
  match self.lower {
    Some((v, true)) => parts.push(">=\{v.format()}")
    Some((v, false)) => parts.push(">\{v.format()}")
    None => ()
  }
  match self.upper {
    Some((v, true)) => parts.push("<=\{v.format()}")
    Some((v, false)) => parts.push("<\{v.format()}")
    None => ()
  }
  for e in self.excluded {
    parts.push("!=\{e.format()}")
  }
  join_conjunction(parts)
}

///|
fn join_conjunction(parts : Array[String]) -> String {
  let sb = StringBuilder()
  for i, part in parts {
    if i > 0 {
      sb.write_string(" & ")
    }
    sb.write_string(part)
  }
  sb.to_string()
}

///|
fn int_range_bounds(lo : BigInt, hi : BigInt) -> NumBounds {
  {
    kind: Int,
    lower: Some((Int(lo), true)),
    upper: Some((Int(hi), true)),
    excluded: [],
  }
}

///|
/// Returns the predeclared CUE numeric constraint for standard built-in numeric
/// type identifiers (`number`, `int`, `float`, `uint`, `uint8`, `int8`,
/// `uint16`, `int16`, `uint32`, `int32`, `rune`, `uint64`, `int64`, `uint128`,
/// `int128`, `float32`, `float64`), or `None` for any other name.
pub fn predeclared_num_bounds(name : String) -> NumBounds? {
  let zero = BigInt::from_int(0)
  let one = BigInt::from_int(1)
  match name {
    "number" => Some(NumBounds::of_kind(Number))
    "int" => Some(NumBounds::of_kind(Int))
    "float" => Some(NumBounds::of_kind(Float))
    "uint" =>
      Some({
        kind: Int,
        lower: Some((Int(zero), true)),
        upper: None,
        excluded: [],
      })
    "uint8" => Some(int_range_bounds(zero, BigInt::from_int(255)))
    "int8" =>
      Some(int_range_bounds(BigInt::from_int(-128), BigInt::from_int(127)))
    "uint16" => Some(int_range_bounds(zero, BigInt::from_int(65535)))
    "int16" =>
      Some(int_range_bounds(BigInt::from_int(-32768), BigInt::from_int(32767)))
    "uint32" => Some(int_range_bounds(zero, (one << 32) - one))
    "int32" => Some(int_range_bounds(-(one << 31), (one << 31) - one))
    "rune" => Some(int_range_bounds(zero, BigInt::from_int(0x10FFFF)))
    "uint64" => Some(int_range_bounds(zero, (one << 64) - one))
    "int64" => Some(int_range_bounds(-(one << 63), (one << 63) - one))
    "uint128" => Some(int_range_bounds(zero, (one << 128) - one))
    "int128" => Some(int_range_bounds(-(one << 127), (one << 127) - one))
    "float32" => {
      // Exact IEEE-754 float32 max: (2^24 - 1) * 2^104.
      let f32_max_bi = ((one << 24) - one) << 104
      match Decimal::from_bigint(f32_max_bi) {
        Ok(f32_max) =>
          Some({
            kind: Number,
            lower: Some((Float(f32_max.neg()), true)),
            upper: Some((Float(f32_max), true)),
            excluded: [],
          })
        Err(_) => None
      }
    }
    "float64" => {
      // Exact IEEE-754 float64 max: (2^53 - 1) * 2^971.
      let f64_max_bi = ((one << 53) - one) << 971
      match Decimal::from_bigint(f64_max_bi) {
        Ok(f64_max) =>
          Some({
            kind: Number,
            lower: Some((Float(f64_max.neg()), true)),
            upper: Some((Float(f64_max), true)),
            excluded: [],
          })
        Err(_) => None
      }
    }
    _ => None
  }
}

///|
/// Compares two strings lexicographically by Unicode scalar value (identical to
/// UTF-8 byte lexicographical order as specified by CUE), returning `-1`, `0`,
/// or `+1`.
pub fn compare_cue_string(a : String, b : String) -> Int32 {
  let mut ia = 0
  let mut ib = 0
  let la = a.length()
  let lb = b.length()
  while ia < la && ib < lb {
    let (ca, step_a) = match a.get_char(ia) {
      Some(ch) => {
        let code = ch.to_int()
        (code, if code > 0xFFFF { 2 } else { 1 })
      }
      None => (a.code_unit_at(ia).to_int(), 1)
    }
    let (cb, step_b) = match b.get_char(ib) {
      Some(ch) => {
        let code = ch.to_int()
        (code, if code > 0xFFFF { 2 } else { 1 })
      }
      None => (b.code_unit_at(ib).to_int(), 1)
    }
    if ca < cb {
      return -1
    } else if ca > cb {
      return 1
    }
    ia += step_a
    ib += step_b
  }
  if ia < la {
    1
  } else if ib < lb {
    -1
  } else {
    0
  }
}

///|
/// Compares two byte sequences lexicographically byte-by-byte (unsigned),
/// returning `-1`, `0`, or `+1`.
pub fn compare_cue_bytes(a : Bytes, b : Bytes) -> Int32 {
  normalize_cmp(a.lexical_compare(b))
}

///|
fn dummy_syntax_span() -> @syntax.Span {
  let pos : @syntax.Position = { offset: 0, line: 1, column: 1, }
  { start: pos, end: pos, }
}

///|
fn format_cue_string_lit(s : String) -> String {
  @syntax.format_expr(@syntax.Expr::String(s, dummy_syntax_span()))
}

///|
fn format_cue_bytes_lit(b : Bytes) -> String {
  @syntax.format_expr(@syntax.Expr::Bytes(b, dummy_syntax_span()))
}

///|
/// Canonical normalized lexicographical constraint bounds on CUE `string` values.
#derive(Eq, Debug)
pub(all) struct StringBounds {
  lower : (String, Bool)?
  upper : (String, Bool)?
  excluded : Array[String]
}

///|
/// Constructs an unconstrained `StringBounds` representing `string`.
pub fn StringBounds::any() -> StringBounds {
  { lower: None, upper: None, excluded: [], }
}

///|
/// Constructs a `StringBounds` from a single bound operator and string literal.
pub fn StringBounds::from_bound(op : BoundOp, val : String) -> StringBounds {
  match op {
    Lt => { lower: None, upper: Some((val, false)), excluded: [], }
    Le => { lower: None, upper: Some((val, true)), excluded: [], }
    Gt => { lower: Some((val, false)), upper: None, excluded: [], }
    Ge => { lower: Some((val, true)), upper: None, excluded: [], }
    Neq => { lower: None, upper: None, excluded: [val], }
  }
}

///|
fn contains_sorted_string(sorted : Array[String], target : String) -> Bool {
  let mut lo = 0
  let mut hi = sorted.length()
  while lo < hi {
    let mid = lo + (hi - lo) / 2
    let cmp = compare_cue_string(sorted[mid], target)
    if cmp == 0 {
      return true
    } else if cmp < 0 {
      lo = mid + 1
    } else {
      hi = mid
    }
  }
  false
}

///|
fn normalize_string_bounds(
  lower : (String, Bool)?,
  upper : (String, Bool)?,
  excluded : Array[String],
) -> Result[StringBounds, String] {
  let sorted = excluded.copy()
  sorted.sort_by(compare_cue_string)
  let unique : Array[String] = []
  for item in sorted {
    if unique.is_empty() || unique[unique.length() - 1] != item {
      unique.push(item)
    }
  }
  let mut norm_lower = lower
  let mut norm_upper = upper
  match norm_lower {
    Some((lo, true)) =>
      for e in unique {
        if e == lo {
          norm_lower = Some((lo, false))
          break
        }
      }
    _ => ()
  }
  match norm_upper {
    Some((hi, true)) =>
      for e in unique {
        if e == hi {
          norm_upper = Some((hi, false))
          break
        }
      }
    _ => ()
  }
  match (norm_lower, norm_upper) {
    (Some((lo, lo_inc)), Some((hi, hi_inc))) => {
      let cmp = compare_cue_string(lo, hi)
      let mut min_valid = if lo_inc { lo } else { lo + "\u{00}" }
      while contains_sorted_string(unique, min_valid) {
        min_valid = min_valid + "\u{00}"
      }
      let min_cmp = compare_cue_string(min_valid, hi)
      if cmp > 0 ||
        (cmp == 0 && (!lo_inc || !hi_inc)) ||
        min_cmp > 0 ||
        (min_cmp == 0 && !hi_inc) {
        let lo_op = if lo_inc { ">=" } else { ">" }
        let hi_op = if hi_inc { "<=" } else { "<" }
        return Err(
          "conflicting string bounds: \{lo_op}\{format_cue_string_lit(lo)} and \{hi_op}\{format_cue_string_lit(hi)}",
        )
      }
    }
    (None, Some((hi, hi_inc))) => {
      let mut min_valid = ""
      while contains_sorted_string(unique, min_valid) {
        min_valid = min_valid + "\u{00}"
      }
      let min_cmp = compare_cue_string(min_valid, hi)
      if min_cmp > 0 || (min_cmp == 0 && !hi_inc) {
        let hi_op = if hi_inc { "<=" } else { "<" }
        return Err(
          "conflicting string bounds: empty range for \{hi_op}\{format_cue_string_lit(hi)}",
        )
      }
    }
    _ => ()
  }
  let final_excl : Array[String] = []
  for e in unique {
    let above_lo = match norm_lower {
      Some((lo, _)) => compare_cue_string(e, lo) > 0
      None => true
    }
    let below_hi = match norm_upper {
      Some((hi, _)) => compare_cue_string(e, hi) < 0
      None => true
    }
    if above_lo && below_hi {
      final_excl.push(e)
    }
  }
  Ok({ lower: norm_lower, upper: norm_upper, excluded: final_excl, })
}

///|
/// Unifies two `StringBounds`, returning the canonical intersection or an error
/// if the constraints are contradictory.
pub fn StringBounds::unify(
  self : StringBounds,
  other : StringBounds,
) -> Result[StringBounds, String] {
  let merged_lower = match (self.lower, other.lower) {
    (None, x) | (x, None) => x
    (Some((va, ia)), Some((vb, ib))) => {
      let cmp = compare_cue_string(va, vb)
      if cmp > 0 {
        Some((va, ia))
      } else if cmp < 0 {
        Some((vb, ib))
      } else {
        Some((va, ia && ib))
      }
    }
  }
  let merged_upper = match (self.upper, other.upper) {
    (None, x) | (x, None) => x
    (Some((va, ia)), Some((vb, ib))) => {
      let cmp = compare_cue_string(va, vb)
      if cmp < 0 {
        Some((va, ia))
      } else if cmp > 0 {
        Some((vb, ib))
      } else {
        Some((va, ia && ib))
      }
    }
  }
  let combined : Array[String] = []
  for item in self.excluded {
    combined.push(item)
  }
  for item in other.excluded {
    combined.push(item)
  }
  normalize_string_bounds(merged_lower, merged_upper, combined)
}

///|
/// Checks whether a concrete `String` satisfies all constraints in `self`.
pub fn StringBounds::matches(
  self : StringBounds,
  val : String,
) -> Result[Unit, String] {
  match self.lower {
    Some((lo, true)) =>
      if compare_cue_string(val, lo) < 0 {
        return Err(
          "string \{format_cue_string_lit(val)} out of bounds: must be >=\{format_cue_string_lit(lo)}",
        )
      }
    Some((lo, false)) =>
      if compare_cue_string(val, lo) <= 0 {
        return Err(
          "string \{format_cue_string_lit(val)} out of bounds: must be >\{format_cue_string_lit(lo)}",
        )
      }
    None => ()
  }
  match self.upper {
    Some((hi, true)) =>
      if compare_cue_string(val, hi) > 0 {
        return Err(
          "string \{format_cue_string_lit(val)} out of bounds: must be <=\{format_cue_string_lit(hi)}",
        )
      }
    Some((hi, false)) =>
      if compare_cue_string(val, hi) >= 0 {
        return Err(
          "string \{format_cue_string_lit(val)} out of bounds: must be <\{format_cue_string_lit(hi)}",
        )
      }
    None => ()
  }
  for e in self.excluded {
    if val == e {
      return Err(
        "string \{format_cue_string_lit(val)} violates bound !=\{format_cue_string_lit(e)}",
      )
    }
  }
  Ok(())
}

///|
/// Formats a `StringBounds` into canonical CUE display syntax.
pub fn StringBounds::format(self : StringBounds) -> String {
  if self.lower is None && self.upper is None && self.excluded.is_empty() {
    return "string"
  }
  let parts : Array[String] = []
  match self.lower {
    Some((lo, true)) => parts.push(">=\{format_cue_string_lit(lo)}")
    Some((lo, false)) => parts.push(">\{format_cue_string_lit(lo)}")
    None => ()
  }
  match self.upper {
    Some((hi, true)) => parts.push("<=\{format_cue_string_lit(hi)}")
    Some((hi, false)) => parts.push("<\{format_cue_string_lit(hi)}")
    None => ()
  }
  for e in self.excluded {
    parts.push("!=\{format_cue_string_lit(e)}")
  }
  join_conjunction(parts)
}

///|
/// Canonical normalized lexicographical constraint bounds on CUE `bytes` values.
#derive(Eq, Debug)
pub(all) struct BytesBounds {
  lower : (Bytes, Bool)?
  upper : (Bytes, Bool)?
  excluded : Array[Bytes]
}

///|
/// Constructs an unconstrained `BytesBounds` representing `bytes`.
pub fn BytesBounds::any() -> BytesBounds {
  { lower: None, upper: None, excluded: [], }
}

///|
/// Constructs a `BytesBounds` from a single bound operator and bytes literal.
pub fn BytesBounds::from_bound(op : BoundOp, val : Bytes) -> BytesBounds {
  match op {
    Lt => { lower: None, upper: Some((val, false)), excluded: [], }
    Le => { lower: None, upper: Some((val, true)), excluded: [], }
    Gt => { lower: Some((val, false)), upper: None, excluded: [], }
    Ge => { lower: Some((val, true)), upper: None, excluded: [], }
    Neq => { lower: None, upper: None, excluded: [val], }
  }
}

///|
fn append_zero_byte(b : Bytes) -> Bytes {
  let len = b.length()
  Bytes::makei(len + 1, fn(i) { if i < len { b[i] } else { b'\x00' } })
}

///|
fn contains_sorted_bytes(sorted : Array[Bytes], target : Bytes) -> Bool {
  let mut lo = 0
  let mut hi = sorted.length()
  while lo < hi {
    let mid = lo + (hi - lo) / 2
    let cmp = compare_cue_bytes(sorted[mid], target)
    if cmp == 0 {
      return true
    } else if cmp < 0 {
      lo = mid + 1
    } else {
      hi = mid
    }
  }
  false
}

///|
fn normalize_bytes_bounds(
  lower : (Bytes, Bool)?,
  upper : (Bytes, Bool)?,
  excluded : Array[Bytes],
) -> Result[BytesBounds, String] {
  let sorted = excluded.copy()
  sorted.sort_by(compare_cue_bytes)
  let unique : Array[Bytes] = []
  for item in sorted {
    if unique.is_empty() || unique[unique.length() - 1] != item {
      unique.push(item)
    }
  }
  let mut norm_lower = lower
  let mut norm_upper = upper
  match norm_lower {
    Some((lo, true)) =>
      for e in unique {
        if e == lo {
          norm_lower = Some((lo, false))
          break
        }
      }
    _ => ()
  }
  match norm_upper {
    Some((hi, true)) =>
      for e in unique {
        if e == hi {
          norm_upper = Some((hi, false))
          break
        }
      }
    _ => ()
  }
  match (norm_lower, norm_upper) {
    (Some((lo, lo_inc)), Some((hi, hi_inc))) => {
      let cmp = compare_cue_bytes(lo, hi)
      let mut min_valid = if lo_inc { lo } else { append_zero_byte(lo) }
      while contains_sorted_bytes(unique, min_valid) {
        min_valid = append_zero_byte(min_valid)
      }
      let min_cmp = compare_cue_bytes(min_valid, hi)
      if cmp > 0 ||
        (cmp == 0 && (!lo_inc || !hi_inc)) ||
        min_cmp > 0 ||
        (min_cmp == 0 && !hi_inc) {
        let lo_op = if lo_inc { ">=" } else { ">" }
        let hi_op = if hi_inc { "<=" } else { "<" }
        return Err(
          "conflicting bytes bounds: \{lo_op}\{format_cue_bytes_lit(lo)} and \{hi_op}\{format_cue_bytes_lit(hi)}",
        )
      }
    }
    (None, Some((hi, hi_inc))) => {
      let mut min_valid = Bytes::from_array([])
      while contains_sorted_bytes(unique, min_valid) {
        min_valid = append_zero_byte(min_valid)
      }
      let min_cmp = compare_cue_bytes(min_valid, hi)
      if min_cmp > 0 || (min_cmp == 0 && !hi_inc) {
        let hi_op = if hi_inc { "<=" } else { "<" }
        return Err(
          "conflicting bytes bounds: empty range for \{hi_op}\{format_cue_bytes_lit(hi)}",
        )
      }
    }
    _ => ()
  }
  let final_excl : Array[Bytes] = []
  for e in unique {
    let above_lo = match norm_lower {
      Some((lo, _)) => compare_cue_bytes(e, lo) > 0
      None => true
    }
    let below_hi = match norm_upper {
      Some((hi, _)) => compare_cue_bytes(e, hi) < 0
      None => true
    }
    if above_lo && below_hi {
      final_excl.push(e)
    }
  }
  Ok({ lower: norm_lower, upper: norm_upper, excluded: final_excl, })
}

///|
/// Unifies two `BytesBounds`, returning the canonical intersection or an error
/// if the constraints are contradictory.
pub fn BytesBounds::unify(
  self : BytesBounds,
  other : BytesBounds,
) -> Result[BytesBounds, String] {
  let merged_lower = match (self.lower, other.lower) {
    (None, x) | (x, None) => x
    (Some((va, ia)), Some((vb, ib))) => {
      let cmp = compare_cue_bytes(va, vb)
      if cmp > 0 {
        Some((va, ia))
      } else if cmp < 0 {
        Some((vb, ib))
      } else {
        Some((va, ia && ib))
      }
    }
  }
  let merged_upper = match (self.upper, other.upper) {
    (None, x) | (x, None) => x
    (Some((va, ia)), Some((vb, ib))) => {
      let cmp = compare_cue_bytes(va, vb)
      if cmp < 0 {
        Some((va, ia))
      } else if cmp > 0 {
        Some((vb, ib))
      } else {
        Some((va, ia && ib))
      }
    }
  }
  let combined : Array[Bytes] = []
  for item in self.excluded {
    combined.push(item)
  }
  for item in other.excluded {
    combined.push(item)
  }
  normalize_bytes_bounds(merged_lower, merged_upper, combined)
}

///|
/// Checks whether a concrete `Bytes` value satisfies all constraints in `self`.
pub fn BytesBounds::matches(
  self : BytesBounds,
  val : Bytes,
) -> Result[Unit, String] {
  match self.lower {
    Some((lo, true)) =>
      if compare_cue_bytes(val, lo) < 0 {
        return Err(
          "bytes \{format_cue_bytes_lit(val)} out of bounds: must be >=\{format_cue_bytes_lit(lo)}",
        )
      }
    Some((lo, false)) =>
      if compare_cue_bytes(val, lo) <= 0 {
        return Err(
          "bytes \{format_cue_bytes_lit(val)} out of bounds: must be >\{format_cue_bytes_lit(lo)}",
        )
      }
    None => ()
  }
  match self.upper {
    Some((hi, true)) =>
      if compare_cue_bytes(val, hi) > 0 {
        return Err(
          "bytes \{format_cue_bytes_lit(val)} out of bounds: must be <=\{format_cue_bytes_lit(hi)}",
        )
      }
    Some((hi, false)) =>
      if compare_cue_bytes(val, hi) >= 0 {
        return Err(
          "bytes \{format_cue_bytes_lit(val)} out of bounds: must be <\{format_cue_bytes_lit(hi)}",
        )
      }
    None => ()
  }
  for e in self.excluded {
    if val == e {
      return Err(
        "bytes \{format_cue_bytes_lit(val)} violates bound !=\{format_cue_bytes_lit(e)}",
      )
    }
  }
  Ok(())
}

///|
/// Formats a `BytesBounds` into canonical CUE display syntax.
pub fn BytesBounds::format(self : BytesBounds) -> String {
  if self.lower is None && self.upper is None && self.excluded.is_empty() {
    return "bytes"
  }
  let parts : Array[String] = []
  match self.lower {
    Some((lo, true)) => parts.push(">=\{format_cue_bytes_lit(lo)}")
    Some((lo, false)) => parts.push(">\{format_cue_bytes_lit(lo)}")
    None => ()
  }
  match self.upper {
    Some((hi, true)) => parts.push("<=\{format_cue_bytes_lit(hi)}")
    Some((hi, false)) => parts.push("<\{format_cue_bytes_lit(hi)}")
    None => ()
  }
  for e in self.excluded {
    parts.push("!=\{format_cue_bytes_lit(e)}")
  }
  join_conjunction(parts)
}