Repository Public
1import Foundation2import SheetCore34/// Internal helpers shared by the formula-intelligence and auditing code (namespaced so that5/// nothing leaks into the module's top level).6enum FormulaIntel {7 /// How references are rendered when a formula is flattened to tokens.8 enum RefStyle {9 /// As written (A1 with `$` markers).10 case a111 /// Relative to the cell holding the formula: `R[-1]C`, `R3C[2]`…12 case r1c1(CellRef)13 /// Absolute location, `$` markers dropped, sheet always spelled out.14 case absolute(defaultSheet: String)15 }1617 // MARK: Reference text1819 static func r1c1(_ a: CellAddr, anchor: CellRef) -> String {20 let r = a.absRow ? "R\(a.row + 1)" : (a.row == anchor.row ? "R" : "R[\(a.row - anchor.row)]")21 let c = a.absCol ? "C\(a.col + 1)" : (a.col == anchor.col ? "C" : "C[\(a.col - anchor.col)]")22 return r + c23 }24 private static func r1c1Row(_ a: CellAddr, _ anchor: CellRef) -> String {25 a.absRow ? "R\(a.row + 1)" : (a.row == anchor.row ? "R" : "R[\(a.row - anchor.row)]")26 }27 private static func r1c1Col(_ a: CellAddr, _ anchor: CellRef) -> String {28 a.absCol ? "C\(a.col + 1)" : (a.col == anchor.col ? "C" : "C[\(a.col - anchor.col)]")29 }3031 static func refText(sheet: String?, _ a: CellAddr, style: RefStyle) -> String {32 switch style {33 case .a1: return Expr.cell(sheet: sheet, a).formulaText()34 case .r1c1(let anchor): return prefix(sheet) + r1c1(a, anchor: anchor)35 case .absolute(let def): return prefix(sheet ?? def) + a.ref.a136 }37 }3839 static func rangeText(_ r: RangeExpr, style: RefStyle) -> String {40 switch style {41 case .a1: return Expr.range(r).formulaText()42 case .absolute(let def): return prefix(r.sheet ?? def) + r.rangeRef.a143 case .r1c1(let anchor):44 switch r.kind {45 case .cells: return prefix(r.sheet) + r1c1(r.a, anchor: anchor) + ":" + r1c1(r.b, anchor: anchor)46 case .columns: return prefix(r.sheet) + r1c1Col(r.a, anchor) + ":" + r1c1Col(r.b, anchor)47 case .rows: return prefix(r.sheet) + r1c1Row(r.a, anchor) + ":" + r1c1Row(r.b, anchor)48 }49 }50 }5152 static func prefix(_ sheet: String?) -> String { sheet.map { FormulaPrinter.quoteSheet($0) + "!" } ?? "" }5354 /// "Sheet1!B3" (sheet quoted when needed).55 static func address(_ sheet: String, _ cell: CellRef) -> String { prefix(sheet) + cell.a1 }56 static func address(_ sheet: String, _ range: RangeRef) -> String { prefix(sheet) + range.a1 }5758 // MARK: Flattening5960 /// Flattens an expression into display tokens; `tokens.joined()` is the formula text in the chosen style.61 static func tokens(_ e: Expr, style: RefStyle) -> [String] {62 var out = [String]()63 flatten(e, style, &out)64 return out65 }6667 private static func flatten(_ e: Expr, _ style: RefStyle, _ out: inout [String]) {68 switch e {69 case .missing: break70 case .number, .text, .bool, .error, .array, .name, .structured: out.append(e.formulaText())71 case .cell(let sheet, let a): out.append(refText(sheet: sheet, a, style: style))72 case .range(let r): out.append(rangeText(r, style: style))73 case .unary(let op, let x):74 out.append(op == .neg ? "-" : "+")75 flatten(x, style, &out)76 case .percent(let x):77 flatten(x, style, &out)78 out.append("%")79 case .binary(let op, let a, let b):80 flatten(a, style, &out)81 out.append(op.symbol)82 flatten(b, style, &out)83 case .call(let name, let args):84 out.append(name)85 out.append("(")86 for (k, a) in args.enumerated() {87 if k > 0 { out.append(",") }88 flatten(a, style, &out)89 }90 out.append(")")91 case .invoke(let f, let args):92 flatten(f, style, &out)93 out.append("(")94 for (k, a) in args.enumerated() {95 if k > 0 { out.append(",") }96 flatten(a, style, &out)97 }98 out.append(")")99 case .spill(let x):100 flatten(x, style, &out)101 out.append("#")102 case .implicit(let x):103 out.append("@")104 flatten(x, style, &out)105 case .paren(let x):106 out.append("(")107 flatten(x, style, &out)108 out.append(")")109 }110 }111112 // MARK: Values113114 /// Short display form of a value: numbers in General format, text in quotes, arrays as `{1,2;3,4}` (truncated).115 static func preview(_ v: Value, limit: Int = 60) -> String {116 func scalar(_ x: Value) -> String {117 switch x {118 case .blank: return "(blank)"119 case .number(let n): return Value.generalString(n)120 case .text(let s): return "\"" + s + "\""121 case .bool(let b): return b ? "TRUE" : "FALSE"122 case .error(let e): return e.rawValue123 case .array(let a): return a.items.first.map(scalar) ?? "{}"124 case .lambda: return "LAMBDA"125 }126 }127 var s: String128 if case .array(let a) = v {129 var parts = [String]()130 var shown = 0131 outer: for r in 0..<a.rows {132 var row = [String]()133 for c in 0..<a.cols {134 if shown >= 8 { row.append("…"); parts.append(row.joined(separator: ",")); break outer }135 row.append(scalar(a[r, c])); shown += 1136 }137 parts.append(row.joined(separator: ","))138 }139 s = "{" + parts.joined(separator: ";") + "}"140 if a.count > 8 { s += " (\(a.rows)×\(a.cols))" }141 } else {142 s = scalar(v)143 }144 if s.count > limit { s = String(s.prefix(limit - 1)) + "…" }145 return s146 }147148 static func typeName(_ v: Value) -> String {149 switch v {150 case .blank: "blank"151 case .number: "number"152 case .text: "text"153 case .bool: "boolean"154 case .error: "error"155 case .array: "array"156 case .lambda: "lambda"157 }158 }159160 // MARK: Reference collection161162 /// A direct reference found in an expression, resolved to a sheet index.163 struct ResolvedRef: Hashable {164 var sheet: Int165 var range: RangeRef166 var text: String167 }168169 /// Direct cell and range references of an expression (names and structured references are not expanded).170 /// References to sheets that do not exist are skipped.171 static func directRefs(_ e: Expr, workbook: Workbook, sheet si: Int) -> [ResolvedRef] {172 var out = [ResolvedRef]()173 var seen = Set<ResolvedRef>()174 e.walk { node in175 var found: ResolvedRef?176 switch node {177 case .cell(let s, let a):178 if let i = s.map({ workbook.sheetIndex(named: $0) }) ?? si {179 found = ResolvedRef(sheet: i, range: RangeRef(a.ref), text: node.formulaText())180 }181 case .range(let r):182 if let i = r.sheet.map({ workbook.sheetIndex(named: $0) }) ?? si {183 found = ResolvedRef(sheet: i, range: r.rangeRef, text: node.formulaText())184 }185 default: break186 }187 if let f = found, seen.insert(f).inserted { out.append(f) }188 }189 return out190 }191192 /// Groups cells into maximal vertical runs (then merges equal adjacent runs horizontally) for compact reporting.193 static func compress(_ cells: [CellRef]) -> [RangeRef] {194 var byCol = [Int: [Int]]()195 for c in Set(cells) { byCol[c.col, default: []].append(c.row) }196 var runs = [RangeRef]()197 for col in byCol.keys.sorted() {198 let rows = byCol[col]!.sorted()199 var start = rows[0], prev = rows[0]200 for r in rows.dropFirst() {201 if r == prev + 1 { prev = r; continue }202 runs.append(RangeRef(r0: start, c0: col, r1: prev, c1: col))203 start = r; prev = r204 }205 runs.append(RangeRef(r0: start, c0: col, r1: prev, c1: col))206 }207 // merge horizontally adjacent runs with identical row spans208 runs.sort { ($0.r0, $0.r1, $0.c0) < ($1.r0, $1.r1, $1.c0) }209 var merged = [RangeRef]()210 for r in runs {211 if let last = merged.last, last.r0 == r.r0, last.r1 == r.r1, last.c1 + 1 == r.c0 {212 merged[merged.count - 1] = RangeRef(r0: last.r0, c0: last.c0, r1: last.r1, c1: r.c1)213 } else {214 merged.append(r)215 }216 }217 return merged.sorted { ($0.r0, $0.c0) < ($1.r0, $1.c0) }218 }219}220