Repository Public
1import Foundation2import SheetCore34/// R1C1-relative normal form of a formula: two formulas that are copies of each other (filled5/// down or across) have the same shape, whatever cell they sit in.6///7/// Relative coordinates are written as offsets from the formula's own cell (`R[-1]C`, `RC[2]`),8/// absolute (`$`) coordinates as 1-based positions (`R3C1`). Whole-column and whole-row references9/// keep only the relevant part (`C[1]:C[1]`, `R2:R4`).10public struct FormulaShape: Hashable, Sendable, Codable {11 /// Flat token list; `tokens.joined()` equals `r1c1`.12 public let tokens: [String]13 /// The formula in R1C1 notation, without the leading "=".14 public let r1c1: String1516 /// Shape of `expr` as stored in the cell `anchor`.17 public init(expr: Expr, at anchor: CellRef) {18 tokens = FormulaIntel.tokens(expr, style: .r1c1(anchor))19 r1c1 = tokens.joined()20 }2122 /// Shape of formula text ("=A1+1" or "A1+1"); nil when the text does not parse.23 public init?(formula text: String, at anchor: CellRef, syntax: FormulaSyntax = .canonical) {24 guard let e = try? FormulaParser.parse(text, syntax: syntax) else { return nil }25 self.init(expr: e, at: anchor)26 }2728 /// Token-level difference between two shapes.29 public static func diff(_ a: FormulaShape, _ b: FormulaShape) -> FormulaDiff { FormulaDiff(old: a.tokens, new: b.tokens) }30}3132/// Token-level difference between two formulas (longest-common-subsequence alignment).33public struct FormulaDiff: Hashable, Sendable, Codable {34 public enum Kind: String, Sendable, Codable { case equal, removed, added }3536 public struct Segment: Hashable, Sendable, Codable {37 public var kind: Kind38 public var token: String39 }4041 /// A replaced run: the tokens of the first formula and what stands in their place in the second42 /// (either side may be empty for a pure insertion or deletion).43 public struct Change: Hashable, Sendable, Codable {44 public var old: String45 public var new: String46 }4748 /// Aligned tokens in reading order.49 public let segments: [Segment]5051 public init(old a: [String], new b: [String]) {52 let n = a.count, m = b.count53 // LCS table (formulas are short: a few hundred tokens at most)54 var lcs = [[Int]](repeating: [Int](repeating: 0, count: m + 1), count: n + 1)55 if n > 0 && m > 0 {56 for i in stride(from: n - 1, through: 0, by: -1) {57 for j in stride(from: m - 1, through: 0, by: -1) {58 lcs[i][j] = a[i] == b[j] ? lcs[i + 1][j + 1] + 1 : max(lcs[i + 1][j], lcs[i][j + 1])59 }60 }61 }62 var out = [Segment]()63 var i = 0, j = 064 while i < n && j < m {65 if a[i] == b[j] { out.append(Segment(kind: .equal, token: a[i])); i += 1; j += 1 }66 else if lcs[i + 1][j] >= lcs[i][j + 1] { out.append(Segment(kind: .removed, token: a[i])); i += 1 }67 else { out.append(Segment(kind: .added, token: b[j])); j += 1 }68 }69 while i < n { out.append(Segment(kind: .removed, token: a[i])); i += 1 }70 while j < m { out.append(Segment(kind: .added, token: b[j])); j += 1 }71 segments = out72 }7374 public var isIdentical: Bool { segments.allSatisfy { $0.kind == .equal } }7576 /// Maximal runs of non-equal tokens, paired as old → new.77 public var changes: [Change] {78 var out = [Change]()79 var old = "", new = "", open = false80 for s in segments {81 switch s.kind {82 case .equal:83 if open { out.append(Change(old: old, new: new)); old = ""; new = ""; open = false }84 case .removed: old += s.token; open = true85 case .added: new += s.token; open = true86 }87 }88 if open { out.append(Change(old: old, new: new)) }89 return out90 }9192 /// e.g. "R[-1]C → R[-2]C; +1 → (nothing)".93 public var summary: String {94 isIdentical ? "identical" : changes.map { ($0.old.isEmpty ? "(nothing)" : $0.old) + " → " + ($0.new.isEmpty ? "(nothing)" : $0.new) }.joined(separator: "; ")95 }96}9798/// Formula comparison entry points.99public enum FormulaComparison {100 /// Compares two formulas as written (A1 tokens). Returns nil when either text does not parse.101 public static func diff(_ a: String, _ b: String, syntax: FormulaSyntax = .canonical) -> FormulaDiff? {102 guard let ea = try? FormulaParser.parse(a, syntax: syntax), let eb = try? FormulaParser.parse(b, syntax: syntax) else { return nil }103 return FormulaDiff(old: FormulaIntel.tokens(ea, style: .a1), new: FormulaIntel.tokens(eb, style: .a1))104 }105106 /// Compares two formulas in R1C1-relative form, each relative to its own cell: copies of the107 /// same formula compare as identical. Returns nil when either text does not parse.108 public static func relativeDiff(_ a: String, at cellA: CellRef, _ b: String, at cellB: CellRef, syntax: FormulaSyntax = .canonical) -> FormulaDiff? {109 guard let sa = FormulaShape(formula: a, at: cellA, syntax: syntax), let sb = FormulaShape(formula: b, at: cellB, syntax: syntax) else { return nil }110 return FormulaShape.diff(sa, sb)111 }112113 public static func diff(_ a: Expr, _ b: Expr) -> FormulaDiff {114 FormulaDiff(old: FormulaIntel.tokens(a, style: .a1), new: FormulaIntel.tokens(b, style: .a1))115 }116}117