///|
/// Default maximum number of semantic equivalence probe evaluations performed
/// during a single `trim` invocation.
pub const DEFAULT_MAX_TRIM_PROBES : Int32 = 256

///|
/// Configuration options for CUE redundant-field trimming.
#derive(Eq, Debug)
pub(all) struct TrimOptions {
  max_probes : Int32
  limits : @eval.EvalLimits
}

///|
/// Returns the default `TrimOptions` (`max_probes: 256`, default `EvalLimits`).
pub fn TrimOptions::default() -> TrimOptions {
  { max_probes: DEFAULT_MAX_TRIM_PROBES, limits: @eval.EvalLimits::default(), }
}

///|
/// Diagnostic categories produced by the `trim` package.
#derive(Eq, Debug)
pub(all) enum TrimErrorKind {
  SyntaxError
  EvalError
  ModuleError
  EquivalenceProofFailed
  ResourceLimit
}

///|
/// Structured diagnostic error returned when trimming fails or cannot verify
/// semantic equivalence.
#derive(Eq, Debug)
pub(all) struct TrimError {
  kind : TrimErrorKind
  path : String
  message : String
  span : @syntax.Span?
}

///|
/// Formats `self` as a human-readable diagnostic string with optional path and
/// `line:column` location.
pub fn TrimError::format(self : TrimError) -> String {
  let loc = match self.span {
    Some(sp) =>
      if self.path.is_empty() {
        "\{sp.start.line}:\{sp.start.column}: "
      } else {
        "\{self.path}:\{sp.start.line}:\{sp.start.column}: "
      }
    None => if self.path.is_empty() { "" } else { "\{self.path}: " }
  }
  "\{loc}\{self.message}"
}

///|
/// Trimming outcome for a single writable CUE source file.
#derive(Eq, Debug)
pub(all) struct TrimFileResult {
  path : String
  original : String
  trimmed : String
  changed : Bool
  removed_paths : Array[String]
  proof_verified : Bool
}

///|
/// Aggregate trimming outcome across a package or file set.
#derive(Eq, Debug)
pub(all) struct TrimResult {
  files : Array[TrimFileResult]
  changed : Bool
  proof_verified : Bool
  probes_used : Int32
}

///|
fn trim_err(
  kind : TrimErrorKind,
  path : String,
  message : String,
  span? : @syntax.Span,
) -> TrimError {
  { kind, path, message, span, }
}

///|
fn split_diff_line_spans(s : String) -> (Array[(Int32, Int32)], Bool) {
  if s.is_empty() {
    return ([], false)
  }
  let spans : Array[(Int32, Int32)] = []
  let len = s.length()
  let mut start : Int32 = 0
  let mut ends_with_nl = false
  for i in 0.. StringView {
  s.clamped_view(start=span.0, end=span.1)
}

///|
priv enum DiffOpKind {
  Equal
  Delete
  Insert
}

///|
priv struct DiffOp {
  kind : DiffOpKind
  old_idx : Int32
  new_idx : Int32
  span : (Int32, Int32)
}

///|
fn compute_line_diff_ops(
  original : String,
  old_spans : Array[(Int32, Int32)],
  trimmed : String,
  new_spans : Array[(Int32, Int32)],
) -> Array[DiffOp] {
  let old_len = old_spans.length()
  let new_len = new_spans.length()
  let mut prefix : Int32 = 0
  while prefix < old_len &&
        prefix < new_len &&
        line_view(original, old_spans[prefix]) ==
        line_view(trimmed, new_spans[prefix]) {
    prefix += 1
  }
  let mut suffix : Int32 = 0
  while suffix < old_len - prefix &&
        suffix < new_len - prefix &&
        line_view(original, old_spans[old_len - 1 - suffix]) ==
        line_view(trimmed, new_spans[new_len - 1 - suffix]) {
    suffix += 1
  }
  let ops : Array[DiffOp] = []
  for i in 0..= 0; i = i - 1 {
      let oi = prefix + i
      let old_v = line_view(original, old_spans[oi])
      for j = mid_new - 1; j >= 0; j = j - 1 {
        let nj = prefix + j
        let idx = i * cols + j
        if old_v == line_view(trimmed, new_spans[nj]) {
          dp[idx] = dp[(i + 1) * cols + (j + 1)] + 1
        } else {
          let down = dp[(i + 1) * cols + j]
          let right = dp[i * cols + (j + 1)]
          dp[idx] = if down >= right { down } else { right }
        }
      }
    }
    let mut i : Int32 = 0
    let mut j : Int32 = 0
    while i < mid_old && j < mid_new {
      let oi = prefix + i
      let nj = prefix + j
      if line_view(original, old_spans[oi]) == line_view(trimmed, new_spans[nj]) {
        ops.push({ kind: Equal, old_idx: oi, new_idx: nj, span: old_spans[oi], })
        i += 1
        j += 1
      } else if dp[(i + 1) * cols + j] >= dp[i * cols + (j + 1)] {
        ops.push({
          kind: Delete,
          old_idx: oi,
          new_idx: nj,
          span: old_spans[oi],
        })
        i += 1
      } else {
        ops.push({
          kind: Insert,
          old_idx: oi,
          new_idx: nj,
          span: new_spans[nj],
        })
        j += 1
      }
    }
    while i < mid_old {
      let oi = prefix + i
      ops.push({
        kind: Delete,
        old_idx: oi,
        new_idx: prefix + j,
        span: old_spans[oi],
      })
      i += 1
    }
    while j < mid_new {
      let nj = prefix + j
      ops.push({
        kind: Insert,
        old_idx: prefix + i,
        new_idx: nj,
        span: new_spans[nj],
      })
      j += 1
    }
  } else {
    // Bounded fallback for gigantic files: emit one contiguous delete/insert block.
    for i in 0.. TrimDiffWriter {
  let exceeded = match max_bytes {
    Some(m) => m < 0L
    None => false
  }
  { buf: StringBuilder(), bytes: 0L, max_bytes, exceeded, }
}

///|
fn trim_char_utf8_len(ch : Char) -> Int64 {
  let cp = ch.to_int()
  if cp <= 0x7F {
    1L
  } else if cp <= 0x7FF {
    2L
  } else if cp <= 0xFFFF {
    3L
  } else {
    4L
  }
}

///|
fn TrimDiffWriter::write_char(self : TrimDiffWriter, ch : Char) -> Unit {
  if self.exceeded {
    return
  }
  let next = self.bytes + trim_char_utf8_len(ch)
  match self.max_bytes {
    Some(m) if next > m => {
      self.bytes = next
      self.exceeded = true
    }
    _ => {
      self.bytes = next
      self.buf.write_char(ch)
    }
  }
}

///|
fn TrimDiffWriter::write_string(self : TrimDiffWriter, s : String) -> Unit {
  if self.exceeded {
    return
  }
  match self.max_bytes {
    Some(m) => {
      let next = add_utf8_bytes_bounded(self.bytes, s, m)
      if next > m {
        self.bytes = next
        self.exceeded = true
        return
      }
      self.bytes = next
      self.buf.write_string(s)
    }
    None => self.buf.write_string(s)
  }
}

///|
fn TrimDiffWriter::write_span(
  self : TrimDiffWriter,
  src : String,
  span : (Int32, Int32),
) -> Unit {
  if self.exceeded {
    return
  }
  let v = line_view(src, span)
  match self.max_bytes {
    Some(m) => {
      let mut total = self.bytes
      for ch in v {
        total += trim_char_utf8_len(ch)
        if total > m {
          self.bytes = total
          self.exceeded = true
          return
        }
      }
      self.bytes = total
      self.buf.write_view(v)
    }
    None => self.buf.write_view(v)
  }
}

///|
fn unified_diff_impl(
  buf : TrimDiffWriter,
  path : String,
  original : String,
  trimmed : String,
) -> Unit {
  if original == trimmed {
    return
  }
  buf.write_string("--- a/")
  buf.write_string(path)
  buf.write_string("\n+++ b/")
  buf.write_string(path)
  buf.write_char('\n')
  if buf.exceeded {
    return
  }
  let (old_spans, old_nl) = split_diff_line_spans(original)
  let (new_spans, new_nl) = split_diff_line_spans(trimmed)
  let ops = compute_line_diff_ops(original, old_spans, trimmed, new_spans)
  let context : Int32 = 3
  let change_indices : Array[Int32] = []
  for i, op in ops {
    if !(op.kind is Equal) {
      change_indices.push(i)
    }
  }
  if change_indices.is_empty() {
    // Only trailing newline presence changed.
    if !old_spans.is_empty() {
      let last_idx = old_spans.length() - 1
      let start_idx = if last_idx >= context { last_idx - context } else { 0 }
      let count = last_idx - start_idx + 1
      let line_num = start_idx + 1
      buf.write_string("@@ -\{line_num},\{count} +\{line_num},\{count} @@\n")
      if buf.exceeded {
        return
      }
      for i in start_idx..= context {
    change_indices[0] - context
  } else {
    0
  }
  let mut cur_end = if change_indices[0] + context < ops.length() {
    change_indices[0] + context
  } else {
    ops.length() - 1
  }
  for k in 1..= context { ci - context } else { 0 }
    let next_end = if ci + context < ops.length() {
      ci + context
    } else {
      ops.length() - 1
    }
    if next_start <= cur_end + 1 {
      cur_end = next_end
    } else {
      hunks.push((cur_start, cur_end))
      cur_start = next_start
      cur_end = next_end
    }
  }
  hunks.push((cur_start, cur_end))
  for hunk in hunks {
    if buf.exceeded {
      return
    }
    let (hs, he) = hunk
    let mut old_count : Int32 = 0
    let mut new_count : Int32 = 0
    let mut first_old : Int32 = -1
    let mut first_new : Int32 = -1
    for i in hs..<=he {
      let op = ops[i]
      match op.kind {
        Equal => {
          if first_old < 0 {
            first_old = op.old_idx
          }
          if first_new < 0 {
            first_new = op.new_idx
          }
          old_count += 1
          new_count += 1
        }
        Delete => {
          if first_old < 0 {
            first_old = op.old_idx
          }
          if first_new < 0 {
            first_new = op.new_idx
          }
          old_count += 1
        }
        Insert => {
          if first_old < 0 {
            first_old = op.old_idx
          }
          if first_new < 0 {
            first_new = op.new_idx
          }
          new_count += 1
        }
      }
    }
    let old_start_hdr = if old_count == 0 { first_old } else { first_old + 1 }
    let new_start_hdr = if new_count == 0 { first_new } else { first_new + 1 }
    buf.write_string(
      "@@ -\{old_start_hdr},\{old_count} +\{new_start_hdr},\{new_count} @@\n",
    )
    if buf.exceeded {
      return
    }
    for i in hs..<=he {
      if buf.exceeded {
        return
      }
      let op = ops[i]
      match op.kind {
        Equal => {
          buf.write_char(' ')
          buf.write_span(original, op.span)
          buf.write_char('\n')
          if !old_nl && op.old_idx + 1 == old_spans.length() && new_nl {
            buf.write_string("\\ No newline at end of file\n")
          }
        }
        Delete => {
          buf.write_char('-')
          buf.write_span(original, op.span)
          buf.write_char('\n')
          if !old_nl && op.old_idx + 1 == old_spans.length() {
            buf.write_string("\\ No newline at end of file\n")
          }
        }
        Insert => {
          buf.write_char('+')
          buf.write_span(trimmed, op.span)
          buf.write_char('\n')
          if !new_nl && op.new_idx + 1 == new_spans.length() {
            buf.write_string("\\ No newline at end of file\n")
          }
        }
      }
    }
  }
}

///|
/// Computes a deterministic unified diff between `original` and `trimmed` for
/// `path`. Returns `""` when `original == trimmed`.
pub fn unified_diff(
  path : String,
  original : String,
  trimmed : String,
) -> String {
  let w = TrimDiffWriter::new(None)
  unified_diff_impl(w, path, original, trimmed)
  w.buf.to_string()
}

///|
/// Computes a deterministic unified diff between `original` and `trimmed` for
/// `path` while aborting early once UTF-8 output exceeds `max_output_bytes`.
pub fn unified_diff_bounded(
  path : String,
  original : String,
  trimmed : String,
  max_output_bytes : Int32,
) -> Result[String, @eval.LimitError] {
  if original == trimmed {
    return if max_output_bytes < 0 {
      Err(@eval.LimitError::OutputBytesExceeded(0, max_output_bytes))
    } else {
      Ok("")
    }
  }
  let w = TrimDiffWriter::new(Some(max_output_bytes.to_int64()))
  unified_diff_impl(w, path, original, trimmed)
  if w.exceeded {
    let actual = if w.bytes > 2147483647L {
      2147483647
    } else {
      w.bytes.to_int()
    }
    Err(@eval.LimitError::OutputBytesExceeded(actual, max_output_bytes))
  } else {
    Ok(w.buf.to_string())
  }
}

///|
fn add_utf8_bytes_bounded(acc : Int64, s : String, max_bytes : Int64) -> Int64 {
  let mut total = acc
  for ch in s {
    let cp = ch.to_int()
    let n : Int64 = if cp <= 0x7F {
      1L
    } else if cp <= 0x7FF {
      2L
    } else if cp <= 0xFFFF {
      3L
    } else {
      4L
    }
    total += n
    if max_bytes >= 0L && total > max_bytes {
      return total
    }
  }
  total
}

///|
fn check_cumulative_source_bytes(
  total : Int64,
  max_bytes : Int32,
  path : String,
) -> TrimError? {
  let max_i64 = max_bytes.to_int64()
  if max_i64 < 0L || total > max_i64 {
    let msg = if total <= 2147483647L {
      @eval.LimitError::SourceBytesExceeded(total.to_int(), max_bytes).message()
    } else {
      "source size (>2147483647 bytes) exceeds limit (\{max_bytes} bytes)"
    }
    Some(trim_err(ResourceLimit, path, msg))
  } else {
    None
  }
}

///|
fn cue_errors_to_trim_errors(
  errs : Array[@eval.CueError],
  default_path : String,
) -> Array[TrimError] {
  errs.map(fn(e) {
    let kind : TrimErrorKind = if e.kind == ResourceLimit {
      ResourceLimit
    } else {
      EvalError
    }
    trim_err(kind, default_path, e.format(), span?=e.span)
  })
}

///|
fn eval_and_validate_package(
  asts : Array[@syntax.File],
  cfg : @eval.EvalConfig,
  limits : @eval.EvalLimits,
) -> @eval.Value {
  let raw = @eval.eval_files_with_config(asts, cfg)
  let budget = @eval.EvalBudget::new(limits)
  @eval.validate_determined_constraints(
    raw,
    budget,
    validator?=cfg.validator_resolver,
  )
}

///|
fn values_semantically_equivalent(
  orig_val : @eval.Value,
  trial_val : @eval.Value,
  cfg : @eval.EvalConfig,
  limits : @eval.EvalLimits,
) -> Bool {
  if !@eval.collect_errors(trial_val).is_empty() {
    return false
  }
  let raw_opts : @eval.SubsumesOptions = {
    final_mode: false,
    ignore_closed: false,
  }
  let b1 = @eval.EvalBudget::new(limits)
  match
    @eval.subsumes_with_options(
      trial_val,
      orig_val,
      b1,
      options=raw_opts,
      validator?=cfg.validator_resolver,
    ) {
    Ok(true) => ()
    _ => return false
  }
  let final_opts : @eval.SubsumesOptions = {
    final_mode: true,
    ignore_closed: false,
  }
  let b2 = @eval.EvalBudget::new(limits)
  match
    @eval.subsumes_with_options(
      orig_val,
      trial_val,
      b2,
      options=final_opts,
      validator?=cfg.validator_resolver,
    ) {
    Ok(true) => ()
    _ => return false
  }
  let b3 = @eval.EvalBudget::new(limits)
  match
    @eval.subsumes_with_options(
      trial_val,
      orig_val,
      b3,
      options=final_opts,
      validator?=cfg.validator_resolver,
    ) {
    Ok(true) => true
    _ => false
  }
}

///|
/// Extracts the static regular path segments of a `FieldLabel` list if and only
/// if every label is eligible for pruning (Normal constraint, no alias, and a
/// Regular identifier or StringLit).
fn static_regular_labels(labels : Array[@syntax.FieldLabel]) -> Array[String]? {
  if labels.is_empty() {
    return None
  }
  let segs : Array[String] = []
  for fl in labels {
    if fl.constraint != Normal || fl.alias_name is Some(_) {
      return None
    }
    match fl.label {
      Ident(name, Regular, _) => segs.push(name)
      StringLit(name, _) => segs.push(name)
      _ => return None
    }
  }
  Some(segs)
}

///|
fn is_predeclared_type_name(name : String) -> Bool {
  match name {
    "_"
    | "null"
    | "bool"
    | "int"
    | "float"
    | "number"
    | "string"
    | "bytes"
    | "uint"
    | "uint8"
    | "uint16"
    | "uint32"
    | "uint64"
    | "uint128"
    | "int8"
    | "int16"
    | "int32"
    | "int64"
    | "int128"
    | "float32"
    | "float64"
    | "rune" => true
    _ => false
  }
}

///|
fn unwrap_expr_parens(expr : @syntax.Expr) -> @syntax.Expr {
  let mut cur = expr
  while true {
    match cur {
      Paren(inner, _) => cur = inner
      _ => break
    }
  }
  cur
}

///|
/// Returns `true` when `expr` is strictly a plain concrete literal, pure
/// constant arithmetic over plain concrete literals, a closed concrete list, or
/// a plain struct tree containing only plain concrete regular fields.
fn is_plain_concrete_expr(expr : @syntax.Expr) -> Bool {
  match unwrap_expr_parens(expr) {
    Null(_)
    | Bool(_, _)
    | Int(_, _)
    | Float(_, _)
    | String(_, _)
    | Bytes(_, _)
    | Bottom(_) => true
    Unary(Plus | Minus, inner, _) => is_plain_concrete_expr(inner)
    Binary(Add | Sub | Mul | QuoSlash | Div | Mod | Quo | Rem, lhs, rhs, _) =>
      is_plain_concrete_expr(lhs) && is_plain_concrete_expr(rhs)
    Binary(And, lhs, rhs, _) =>
      is_plain_concrete_expr(lhs) && is_plain_concrete_expr(rhs)
    List(elems, ellipsis_type, has_ellipsis, _) => {
      if has_ellipsis || ellipsis_type is Some(_) {
        return false
      }
      for elem in elems {
        match elem {
          Expr(e) => if !is_plain_concrete_expr(e) { return false }
          Comprehension(_, _, _) => return false
        }
      }
      true
    }
    Struct(decls, _) => {
      for d in decls {
        match d {
          Field(labels, val, _, _) => {
            if static_regular_labels(labels) is None {
              return false
            }
            if !is_plain_concrete_expr(val) {
              return false
            }
          }
          _ => return false
        }
      }
      true
    }
    _ => false
  }
}

///|
/// Returns `true` if `expr` is an explicit schema/type/constraint expression
/// (such as `int`, `#Def`, `*8080 | int`, `>0`, `[...int]`, or `lhs & { ... }`)
/// that must never be pruned away as redundant concrete data.
fn is_non_prunable_value_expr(expr : @syntax.Expr) -> Bool {
  match unwrap_expr_parens(expr) {
    Ident(name, kind, _) => kind != Regular || is_predeclared_type_name(name)
    Unary(Default | Lt | Le | Gt | Ge | Neq | Match | NotMatch, _, _) => true
    Binary(Or, _, _, _) => true
    Binary(And, lhs, rhs, _) =>
      expr_contains_struct(lhs) ||
      expr_contains_struct(rhs) ||
      is_non_prunable_value_expr(lhs) ||
      is_non_prunable_value_expr(rhs)
    List(_, ellipsis_type, has_ellipsis, _) =>
      has_ellipsis || ellipsis_type is Some(_)
    Struct(decls, _) => !decls.is_empty()
    _ => false
  }
}

///|
fn expr_contains_struct(expr : @syntax.Expr) -> Bool {
  match unwrap_expr_parens(expr) {
    Struct(_, _) => true
    Binary(And, lhs, rhs, _) =>
      expr_contains_struct(lhs) || expr_contains_struct(rhs)
    _ => false
  }
}

///|
/// Tracks field paths and prefix scopes that receive at least one schema,
/// constraint, comprehension, pattern, embedding, or readonly source
/// contribution so concrete duplicate siblings in writable peer files are never
/// arbitrarily deleted.
priv struct SchemaContributors {
  exact_paths : Map[String, Bool]
  prefix_paths : Map[String, Bool]
  mut root_prefix : Bool
}

///|
fn SchemaContributors::new() -> SchemaContributors {
  { exact_paths: Map([]), prefix_paths: Map([]), root_prefix: false, }
}

///|
fn encode_path_key(segs : Array[String]) -> String {
  let buf = StringBuilder()
  for i, seg in segs {
    if i > 0 {
      buf.write_char('\u{0000}')
    }
    buf.write_string(seg)
  }
  buf.to_string()
}

///|
fn format_dot_path(segs : Array[String]) -> String {
  segs.join(".")
}

///|
fn SchemaContributors::add_exact(
  self : SchemaContributors,
  segs : Array[String],
) -> Unit {
  if !segs.is_empty() {
    self.exact_paths.set(encode_path_key(segs), true)
  }
}

///|
fn SchemaContributors::add_prefix(
  self : SchemaContributors,
  segs : Array[String],
) -> Unit {
  if segs.is_empty() {
    self.root_prefix = true
  } else {
    self.prefix_paths.set(encode_path_key(segs), true)
  }
}

///|
/// Returns `true` if `segs` has a schema/constraint/readonly contributor.
/// `strict_ancestor_only` requires a contributor strictly above `segs` when
/// pruning a non-plain-concrete expression? Wait: for plain concrete fields at
/// `segs`, either an ancestor prefix contributor OR a non-plain-concrete exact
/// contributor at `segs` (such as `x: *1 | int` alongside `x: 1`) permits
/// pruning `x: 1`.
fn SchemaContributors::allows_pruning(
  self : SchemaContributors,
  segs : Array[String],
) -> Bool {
  if segs.is_empty() {
    return false
  }
  if self.root_prefix {
    return true
  }
  if self.exact_paths.contains(encode_path_key(segs)) {
    return true
  }
  let prefix : Array[String] = []
  for seg in segs {
    prefix.push(seg)
    if self.prefix_paths.contains(encode_path_key(prefix)) {
      return true
    }
  }
  false
}

///|
fn extend_path(base : Array[String], extra : Array[String]) -> Array[String] {
  let out = base.copy()
  for seg in extra {
    out.push(seg)
  }
  out
}

///|
fn SchemaContributors::collect_expr(
  self : SchemaContributors,
  expr : @syntax.Expr,
  prefix : Array[String],
  is_readonly : Bool,
) -> Unit {
  match unwrap_expr_parens(expr) {
    Struct(decls, _) => self.collect_decls(decls, prefix, is_readonly)
    Binary(And, lhs, rhs, _) => {
      if !is_plain_concrete_expr(lhs) || !is_plain_concrete_expr(rhs) {
        self.add_prefix(prefix)
      }
      self.collect_expr(lhs, prefix, is_readonly)
      self.collect_expr(rhs, prefix, is_readonly)
    }
    _ =>
      if is_readonly || !is_plain_concrete_expr(expr) {
        self.add_prefix(prefix)
      }
  }
}

///|
fn SchemaContributors::collect_decls(
  self : SchemaContributors,
  decls : Array[@syntax.Decl],
  prefix : Array[String],
  is_readonly : Bool,
) -> Unit {
  for decl in decls {
    match decl {
      Field(labels, value, _, _) => {
        let cur = prefix.copy()
        let mut hit_dynamic = false
        for fl in labels {
          match fl.label {
            Ident(name, Regular, _) | StringLit(name, _) =>
              if fl.constraint == Normal && fl.alias_name is None {
                cur.push(name)
                if is_readonly {
                  self.add_exact(cur)
                }
              } else {
                // Optional/Required/Aliased fields can supply schema constraints
                // for the field path; Def/Hidden/HiddenDef stay isolated.
                match fl.label {
                  Ident(_, Def | Hidden | HiddenDef, _) => ()
                  _ => {
                    cur.push(name)
                    self.add_prefix(cur)
                  }
                }
                hit_dynamic = true
                break
              }
            Ident(_, Def | Hidden | HiddenDef, _) => {
              hit_dynamic = true
              break
            }
            Pattern(_, _, _) | DynamicExpr(_, _) | DynamicInterp(_, _) => {
              self.add_prefix(cur)
              hit_dynamic = true
              break
            }
          }
        }
        if !hit_dynamic {
          self.collect_expr(value, cur, is_readonly)
        }
      }
      Embed(_, _, _) | Comprehension(_, _, _) => self.add_prefix(prefix)
      Let(_, _, _) | Ellipsis(_) | Attribute(_) => ()
    }
  }
}

///|
fn build_contributors(
  writable_asts : Array[@syntax.File],
  readonly_asts : Array[@syntax.File],
) -> SchemaContributors {
  let contribs = SchemaContributors::new()
  for f in readonly_asts {
    contribs.collect_decls(f.decls, [], true)
  }
  for f in writable_asts {
    contribs.collect_decls(f.decls, [], false)
  }
  contribs
}

///|
priv struct WritableFileState {
  path : String
  original : String
  tokens : Array[@syntax.Token]
  comments : Array[@syntax.Comment]
  slot : Int32
  mut ast : @syntax.File
  removed_paths : Array[String]
  removed_spans : Array[@syntax.Span]
}

///|
priv struct TrimState {
  writable : Array[WritableFileState]
  eval_asts : Array[@syntax.File]
  orig_val : @eval.Value
  cfg : @eval.EvalConfig
  options : TrimOptions
  contributors : SchemaContributors
  mut probes_used : Int32
}

///|
fn TrimState::probe_file_replacement(
  self : TrimState,
  file_idx : Int32,
  trial_file : @syntax.File,
) -> Bool {
  if self.probes_used >= self.options.max_probes {
    return false
  }
  self.probes_used += 1
  let slot = self.writable[file_idx].slot
  let trial_asts = self.eval_asts.copy()
  trial_asts[slot] = trial_file
  let trial_val = eval_and_validate_package(
    trial_asts,
    self.cfg,
    self.options.limits,
  )
  values_semantically_equivalent(
    self.orig_val,
    trial_val,
    self.cfg,
    self.options.limits,
  )
}

///|
fn TrimState::commit_file_ast(
  self : TrimState,
  file_idx : Int32,
  new_file : @syntax.File,
) -> Unit {
  self.writable[file_idx].ast = new_file
  let slot = self.writable[file_idx].slot
  self.eval_asts[slot] = new_file
}

///|
fn TrimState::prune_expr(
  self : TrimState,
  file_idx : Int32,
  expr : @syntax.Expr,
  path_prefix : Array[String],
  rebuild_expr : (@syntax.Expr) -> @syntax.File,
) -> @syntax.Expr {
  if self.probes_used >= self.options.max_probes {
    return expr
  }
  match expr {
    Struct(decls, span) => {
      let new_decls = self.prune_decls(file_idx, decls, path_prefix, fn(ds) {
        rebuild_expr(Struct(ds, span))
      })
      Struct(new_decls, span)
    }
    Binary(And, lhs, rhs, span) => {
      let new_lhs = self.prune_expr(file_idx, lhs, path_prefix, fn(l) {
        rebuild_expr(Binary(And, l, rhs, span))
      })
      let new_rhs = self.prune_expr(file_idx, rhs, path_prefix, fn(r) {
        rebuild_expr(Binary(And, new_lhs, r, span))
      })
      Binary(And, new_lhs, new_rhs, span)
    }
    Paren(inner, span) => {
      let new_inner = self.prune_expr(file_idx, inner, path_prefix, fn(e) {
        rebuild_expr(Paren(e, span))
      })
      Paren(new_inner, span)
    }
    _ => expr
  }
}

///|
fn build_trial_decls(
  kept : Array[@syntax.Decl],
  mid : @syntax.Decl?,
  rest : Array[@syntax.Decl],
  rest_start : Int32,
) -> Array[@syntax.Decl] {
  let out : Array[@syntax.Decl] = []
  for d in kept {
    out.push(d)
  }
  match mid {
    Some(m) => out.push(m)
    None => ()
  }
  for i in rest_start.. @syntax.File,
) -> Array[@syntax.Decl] {
  let kept : Array[@syntax.Decl] = []
  for i, decl in decls {
    if self.probes_used >= self.options.max_probes {
      for k in i..
        match static_regular_labels(labels) {
          None => kept.push(decl)
          Some(label_segs) => {
            let full_path = extend_path(path_prefix, label_segs)
            let updated_value = self.prune_expr(file_idx, value, full_path, fn(
              v,
            ) {
              let d = @syntax.Decl::Field(labels, v, attrs, span)
              rebuild_decls(build_trial_decls(kept, Some(d), decls, i + 1))
            })
            let updated_decl = @syntax.Decl::Field(
              labels, updated_value, attrs, span,
            )
            let can_remove = attrs.is_empty() &&
              !is_non_prunable_value_expr(updated_value) &&
              self.contributors.allows_pruning(full_path) &&
              self.probes_used < self.options.max_probes
            if can_remove {
              let trial_decls = build_trial_decls(kept, None, decls, i + 1)
              let trial_file = rebuild_decls(trial_decls)
              if self.probe_file_replacement(file_idx, trial_file) {
                self.commit_file_ast(file_idx, trial_file)
                self.writable[file_idx].removed_paths.push(
                  format_dot_path(full_path),
                )
                self.writable[file_idx].removed_spans.push(span)
                continue
              }
            }
            kept.push(updated_decl)
          }
        }
      _ => kept.push(decl)
    }
  }
  kept
}

///|
fn span_contains_span(outer : @syntax.Span, inner : @syntax.Span) -> Bool {
  inner.start.offset >= outer.start.offset &&
  inner.end.offset <= outer.end.offset
}

///|
fn token_inside_any_span(
  tok : @syntax.Token,
  spans : Array[@syntax.Span],
) -> Bool {
  for sp in spans {
    if span_contains_span(sp, tok.span) {
      return true
    }
  }
  false
}

///|
fn has_kept_token_on_line_before(
  kept_tokens : Array[@syntax.Token],
  line : Int32,
  before_offset : Int32,
) -> Bool {
  for tok in kept_tokens {
    if tok.span.start.line > line {
      break
    }
    if tok.span.start.line == line && tok.span.start.offset < before_offset {
      return true
    }
  }
  false
}

///|
fn has_kept_non_comma_token_between(
  kept_tokens : Array[@syntax.Token],
  after_offset : Int32,
  before_offset : Int32,
) -> Bool {
  for tok in kept_tokens {
    if tok.span.start.offset >= before_offset {
      break
    }
    if tok.kind != Comma && tok.span.start.offset >= after_offset {
      return true
    }
  }
  false
}

///|
/// Filters out comments belonging exclusively to removed declarations:
/// 1. Comments strictly inside a removed decl's span;
/// 2. Inline trailing comments on a removed decl's closing line before any
///    kept non-comma token;
/// 3. Contiguous doc comments directly above a removed decl (with no blank
///    lines in between and no kept token on the same line).
fn filter_comments_for_removed_spans(
  tokens : Array[@syntax.Token],
  comments : Array[@syntax.Comment],
  removed_spans : Array[@syntax.Span],
) -> Array[@syntax.Comment] {
  if comments.is_empty() || removed_spans.is_empty() {
    return comments
  }
  let kept_tokens : Array[@syntax.Token] = []
  for tok in tokens {
    if tok.kind != Eof && !token_inside_any_span(tok, removed_spans) {
      kept_tokens.push(tok)
    }
  }
  let remove_flags = Array::make(comments.length(), false)
  // Pass 1 & 2: inside removed spans and inline trailing comments.
  for i, c in comments {
    for sp in removed_spans {
      if span_contains_span(sp, c.span) {
        remove_flags[i] = true
        break
      }
      if c.span.start.line == sp.end.line &&
        c.span.start.offset >= sp.end.offset &&
        !has_kept_non_comma_token_between(
          kept_tokens,
          sp.end.offset,
          c.span.start.offset,
        ) {
        remove_flags[i] = true
        break
      }
    }
  }
  // Pass 3: contiguous doc comments directly above each removed decl.
  for sp in removed_spans {
    if has_kept_token_on_line_before(
        kept_tokens,
        sp.start.line,
        sp.start.offset,
      ) {
      continue
    }
    let mut expected_line = sp.start.line - 1
    for i = comments.length() - 1; i >= 0; i = i - 1 {
      let c = comments[i]
      if c.span.end.offset > sp.start.offset {
        continue
      }
      if c.span.end.line < expected_line {
        break
      }
      if c.span.end.line == expected_line &&
        !has_kept_token_on_line_before(
          kept_tokens,
          c.span.start.line,
          c.span.start.offset,
        ) {
        remove_flags[i] = true
        expected_line = c.span.start.line - 1
      } else {
        break
      }
    }
  }
  let out : Array[@syntax.Comment] = []
  for i, c in comments {
    if !remove_flags[i] {
      out.push(c)
    }
  }
  out
}

///|
/// Trims redundant concrete fields across `sources` (writable `(path, source)`
/// pairs) in the presence of optional `readonly_sources` and pre-resolved
/// `package_deps`, verifying full semantic equivalence both during pruning and
/// via a mandatory post-trim re-parse + re-evaluation self-proof.
pub fn trim_sources(
  sources : Array[(String, String)],
  readonly_sources~ : Array[(String, String)] = [],
  package_deps~ : Array[@eval.PackageUnit] = [],
  options~ : TrimOptions = TrimOptions::default(),
) -> Result[TrimResult, Array[TrimError]] {
  if options.max_probes < 0 {
    return Err([
      trim_err(
        ResourceLimit,
        "",
        "max_probes (\{options.max_probes}) must be non-negative",
      ),
    ])
  }
  let max_bytes = options.limits.max_source_bytes
  let max_i64 = max_bytes.to_int64()
  let mut total_bytes : Int64 = 0L
  for pair in sources {
    let (path, src) = pair
    total_bytes = add_utf8_bytes_bounded(total_bytes, src, max_i64)
    match check_cumulative_source_bytes(total_bytes, max_bytes, path) {
      Some(err) => return Err([err])
      None => ()
    }
  }
  for pair in readonly_sources {
    let (path, src) = pair
    total_bytes = add_utf8_bytes_bounded(total_bytes, src, max_i64)
    match check_cumulative_source_bytes(total_bytes, max_bytes, path) {
      Some(err) => return Err([err])
      None => ()
    }
  }
  let writable : Array[WritableFileState] = []
  let eval_asts : Array[@syntax.File] = []
  let writable_asts : Array[@syntax.File] = []
  for pair in sources {
    let (path, src) = pair
    let (tokens, comments) = match @syntax.tokenize_with_comments(src) {
      Ok(res) => res
      Err(err) => {
        let se = @syntax.SyntaxError::Lex(err)
        return Err([trim_err(SyntaxError, path, se.message(), span=se.span())])
      }
    }
    let ast = match @syntax.parse_file(src) {
      Ok(f) => f
      Err(err) =>
        return Err([trim_err(SyntaxError, path, err.message(), span=err.span())])
    }
    let slot = eval_asts.length()
    eval_asts.push(ast)
    writable_asts.push(ast)
    writable.push({
      path,
      original: src,
      tokens,
      comments,
      slot,
      ast,
      removed_paths: [],
      removed_spans: [],
    })
  }
  let readonly_asts : Array[@syntax.File] = []
  for pair in readonly_sources {
    let (path, src) = pair
    match @syntax.tokenize_with_comments(src) {
      Ok(_) => ()
      Err(err) => {
        let se = @syntax.SyntaxError::Lex(err)
        return Err([trim_err(SyntaxError, path, se.message(), span=se.span())])
      }
    }
    let ast = match @syntax.parse_file(src) {
      Ok(f) => f
      Err(err) =>
        return Err([trim_err(SyntaxError, path, err.message(), span=err.span())])
    }
    eval_asts.push(ast)
    readonly_asts.push(ast)
  }
  let cfg = @builtins.default_eval_config(limits=options.limits).with_package_deps(
    package_deps,
  )
  let orig_val = eval_and_validate_package(eval_asts, cfg, options.limits)
  let init_errs = @eval.collect_errors(orig_val)
  if !init_errs.is_empty() {
    let fallback_path = if writable.is_empty() {
      if readonly_sources.is_empty() {
        ""
      } else {
        readonly_sources[0].0
      }
    } else {
      writable[0].path
    }
    return Err(cue_errors_to_trim_errors(init_errs, fallback_path))
  }
  let contributors = build_contributors(writable_asts, readonly_asts)
  let state : TrimState = {
    writable,
    eval_asts,
    orig_val,
    cfg,
    options,
    contributors,
    probes_used: 0,
  }
  for file_idx in 0..= state.options.max_probes {
      break
    }
    let base_file = state.writable[file_idx].ast
    let _ = state.prune_decls(file_idx, base_file.decls, [], fn(new_decls) {
      { ..base_file, decls: new_decls, }
    })
  }
  // Format each writable file preserving non-removed comments, keeping
  // untouched files verbatim.
  let file_results : Array[TrimFileResult] = []
  let proof_asts : Array[@syntax.File] = state.eval_asts.copy()
  let mut any_changed = false
  for wf in state.writable {
    let trimmed = if wf.removed_spans.is_empty() {
      wf.original
    } else {
      let kept_comments = filter_comments_for_removed_spans(
        wf.tokens,
        wf.comments,
        wf.removed_spans,
      )
      match
        @syntax.format_file_with_comments_bounded(
          wf.ast,
          kept_comments,
          options.limits.max_output_bytes,
        ) {
        Ok(s) => s
        Err(msg) => return Err([trim_err(ResourceLimit, wf.path, msg)])
      }
    }
    let reparsed = match @syntax.parse_file(trimmed) {
      Ok(f) => f
      Err(err) =>
        return Err([
          trim_err(
            EquivalenceProofFailed,
            wf.path,
            "post-trim re-parse failed: \{err.message()}",
            span=err.span(),
          ),
        ])
    }
    proof_asts[wf.slot] = reparsed
    let changed = trimmed != wf.original
    if changed {
      any_changed = true
    }
    file_results.push({
      path: wf.path,
      original: wf.original,
      trimmed,
      changed,
      removed_paths: wf.removed_paths,
      proof_verified: true,
    })
  }
  // Mandatory final post-trim semantic equivalence self-proof (fail-closed).
  let proof_val = eval_and_validate_package(proof_asts, cfg, options.limits)
  let proof_errs = @eval.collect_errors(proof_val)
  if !proof_errs.is_empty() {
    return Err([
      trim_err(
        EquivalenceProofFailed,
        "",
        "post-trim evaluation failed: \{proof_errs[0].format()}",
        span?=proof_errs[0].span,
      ),
    ])
  }
  if !values_semantically_equivalent(orig_val, proof_val, cfg, options.limits) {
    return Err([
      trim_err(
        EquivalenceProofFailed,
        "",
        "post-trim semantic equivalence proof failed",
      ),
    ])
  }
  Ok({
    files: file_results,
    changed: any_changed,
    proof_verified: true,
    probes_used: state.probes_used,
  })
}

///|
/// Trims redundant fields from a single CUE source string.
pub fn trim_source(
  source : String,
  path~ : String = "",
  options~ : TrimOptions = TrimOptions::default(),
) -> Result[TrimFileResult, Array[TrimError]] {
  match trim_sources([(path, source)], options~) {
    Ok(res) => Ok(res.files[0])
    Err(errs) => Err(errs)
  }
}

///|
/// Trims redundant fields from `data` given a read-only `schema` source in the
/// same package scope.
pub fn trim_against_schema(
  schema : String,
  data : String,
  data_path~ : String = "",
  options~ : TrimOptions = TrimOptions::default(),
) -> Result[TrimFileResult, Array[TrimError]] {
  match
    trim_sources(
      [(data_path, data)],
      readonly_sources=[("", schema)],
      options~,
    ) {
    Ok(res) => Ok(res.files[0])
    Err(errs) => Err(errs)
  }
}

///|
fn dir_of_normalized_path(path : String) -> String {
  let chars = path.to_array()
  let mut last_sep = -1
  for i, ch in chars {
    if ch == '/' || ch == '\\' {
      last_sep = i
    }
  }
  if last_sep < 0 {
    return "."
  }
  if last_sep == 0 {
    return "/"
  }
  if last_sep == 2 && chars.length() >= 3 && chars[1] == ':' {
    let buf = StringBuilder()
    buf.write_char(chars[0])
    buf.write_string(":/")
    return buf.to_string()
  }
  let buf = StringBuilder()
  for i in 0.. Array[TrimError] {
  errs.map(fn(e) {
    let kind : TrimErrorKind = match e.kind {
      ParseError => SyntaxError
      ResourceLimit => ResourceLimit
      EvalError => EvalError
      _ => ModuleError
    }
    trim_err(kind, e.path, e.message, span?=e.span)
  })
}

///|
/// Resolves a CUE package via `@modsys.resolve_package` and trims redundant
/// fields in the package's target-directory files while treating ancestor
/// inherited files and imported dependency packages as read-only context.
pub fn trim_package(
  fs : @modsys.ModuleFs,
  target_dir : String,
  pkg_name? : String,
  cwd~ : String = ".",
  options~ : TrimOptions = TrimOptions::default(),
  mod_limits? : @modsys.ModLimits,
) -> Result[TrimResult, Array[TrimError]] {
  let eff_mod_limits = match mod_limits {
    Some(ml) => ml
    None => { ..@modsys.ModLimits::default(), eval_limits: options.limits, }
  }
  let graph = match
    @modsys.resolve_package(
      fs,
      target_dir,
      pkg_name?,
      cwd~,
      limits=eff_mod_limits,
    ) {
    Ok(g) => g
    Err(errs) => return Err(mod_errors_to_trim_errors(errs))
  }
  let writable_sources : Array[(String, String)] = []
  let readonly_sources : Array[(String, String)] = []
  for lf in graph.root.files {
    if dir_of_normalized_path(lf.path) == graph.root.dir {
      writable_sources.push((lf.path, lf.source))
    } else {
      readonly_sources.push((lf.path, lf.source))
    }
  }
  trim_sources(
    writable_sources,
    readonly_sources~,
    package_deps=graph.deps,
    options~,
  )
}