Calc symbolic layer for table formulas !418

merged merged by cmc on 2026-11-21 14:08 UTC · krz/orgstar:parity-symbolic into main

10 files changed, +1134 −79

Layout: unified · split

Sources/OrgApp/TableReason.swift +2 −1
@@ -17,7 +17,6 @@ public enum TableReason {
1717 func value(_ prefix: String) -> String? { reason.hasPrefix(prefix) ? String(reason.dropFirst(prefix.count)) : nil }
1818 if let name = value("function ") { return String(localized: "function \(name)", comment: "Why a table needs Emacs: a Calc function") }
1919 if let name = value("variable ") { return String(localized: "variable \(name)", comment: "Why a table needs Emacs: a Calc variable") }
20 if let text = value("non-numeric field ") { return String(localized: "non-numeric field \(text)", comment: "Why a table needs Emacs") }
2120 if let number = value("number size ") { return String(localized: "number size \(number)", comment: "Why a table needs Emacs: a number too large") }
2221 if let flag = value("format flag ") { return String(localized: "format flag \(flag)", comment: "Why a table needs Emacs: a format specifier flag") }
2322 return nil
@@ -118,6 +117,8 @@ public enum TableReason {
118117 case "reference outside table": return String(localized: "reference outside table", comment: comment)
119118 case "remote table name from a range": return String(localized: "remote table name from a range", comment: comment)
120119 case "row out of range": return String(localized: "row out of range", comment: comment)
120 case "symbolic arithmetic": return String(localized: "symbolic arithmetic", comment: comment)
121 case "symbolic mode": return String(localized: "symbolic mode", comment: comment)
121122 case "table position": return String(localized: "table position", comment: comment)
122123 case "variance of one value": return String(localized: "variance of one value", comment: comment)
123124 case "vector argument": return String(localized: "vector argument", comment: comment)
Sources/OrgCore/Compute/Calc.swift +170 −27
@@ -16,8 +16,10 @@ public enum Calc {
1616 /// An error Calc reports, which a table shows as `#ERROR`.
1717 public struct Failure: Error, Equatable, CustomStringConvertible {
1818 public let reason: String
19 /// Where in the expression Calc reports the error.
20 public let position: Int
1921 public var description: String { reason }
20 init(_ reason: String) { self.reason = reason }
22 init(_ reason: String, position: Int = 0) { (self.reason, self.position) = (reason, position) }
2123 }
2224
2325 public indirect enum Value: Equatable, Sendable {
@@ -30,6 +32,8 @@ public enum Calc {
3032 case nan
3133 /// An exact fraction, reduced, the denominator above 1 (`calc-prefer-frac`).
3234 case frac(Int, Int)
35 /// A formula Calc leaves unevaluated, with variables or a quotient by zero.
36 case symbolic(Term)
3337 }
3438
3539 public enum FloatFormat: Equatable, Sendable {
@@ -42,6 +46,8 @@ public enum Calc {
4246 public var degrees = true
4347 /// `calc-prefer-frac`: dividing integers gives a fraction.
4448 public var preferFractions = false
49 /// `calc-symbolic-mode`: functions whose result isn't exact stay unevaluated.
50 public var symbolic = false
4551 /// The clock `now()` reads; nil is the system clock.
4652 public var now: Date?
4753 /// The local time zone, for `now()`, `julian` and `unixtime`.
@@ -55,16 +61,24 @@ public enum Calc {
5561 // Mantissas live in an Int, so 18 digits at most.
5662 guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") }
5763 return try $precision.withValue(modes.precision) {
58 var parser = Parser(expression)
59 let tree = try parser.parse()
60 let value = try Evaluator(modes: modes).eval(tree)
61 if numeric {
62 switch value {
63 case .int, .float, .frac: break
64 default: throw Failure("Number expected")
64 try $fractions.withValue(modes.preferFractions) {
65 try $symbolicMode.withValue(modes.symbolic) {
66 var parser = Parser(expression)
67 let tree = try parser.parse()
68 let value = try Evaluator(modes: modes).eval(tree)
69 if numeric {
70 switch value {
71 case .int, .float, .frac: break
72 default:
73 // Calc explains the first argument a quotient, power or function
74 // rejected along the way, which isn't tracked here.
75 if tree.mayExplain { throw Unsupported("symbolic arithmetic") }
76 throw Failure("Number expected")
77 }
78 }
79 return try format(value, modes.format)
6580 }
6681 }
67 return try format(value, modes.format)
6882 }
6983 }
7084
@@ -78,6 +92,7 @@ public enum Calc {
7892 let v = try $precision.withValue(precision + n, operation: body)
7993 if case .float(let m, let e) = v { return try makeFloat(Int128(m), e) }
8094 if case .date(.float(let m, let e)) = v { return .date(try makeFloat(Int128(m), e)) }
95 if case .symbolic(let t) = v { return value(try Symbolic.normalize(t)) }
8196 return v
8297 }
8398
@@ -216,6 +231,7 @@ public enum Calc {
216231 case .frac(let n, let d): return try parts(try divide(.int(n), .int(d)))
217232 case .vector: throw Unsupported("vector arithmetic")
218233 case .date, .nan: throw Unsupported("date arithmetic")
234 case .symbolic: throw Unsupported("symbolic arithmetic")
219235 }
220236 }
221237
@@ -257,6 +273,7 @@ public enum Calc {
257273 case .frac(let n, let d): return Double(n) / Double(d)
258274 case .vector: throw Unsupported("vector arithmetic")
259275 case .date, .nan: throw Unsupported("date arithmetic")
276 case .symbolic: throw Unsupported("symbolic arithmetic")
260277 }
261278 }
262279
@@ -273,7 +290,12 @@ public enum Calc {
273290 return try makeFloat(mantissa, exponent - 16)
274291 }
275292
293 static func isSymbolic(_ vs: Value...) -> Bool {
294 vs.contains { if case .symbolic = $0 { true } else { false } }
295 }
296
276297 static func add(_ a: Value, _ b: Value) throws -> Value {
298 if isSymbolic(a, b) { return value(try Symbolic.add(try term(a), try term(b))) }
277299 switch (a, b) {
278300 case (.nan, .vector), (.vector, .nan): throw Unsupported("vector arithmetic")
279301 case (.nan, _), (_, .nan): return .nan
@@ -310,6 +332,7 @@ public enum Calc {
310332
311333 static func negate(_ a: Value) throws -> Value {
312334 switch a {
335 case .symbolic(let t): return value(try Symbolic.neg(t))
313336 case .int(let i):
314337 guard i != .min else { throw Unsupported("integer size") }
315338 return .int(-i)
@@ -333,6 +356,7 @@ public enum Calc {
333356 }
334357
335358 static func multiply(_ a: Value, _ b: Value) throws -> Value {
359 if isSymbolic(a, b) { return value(try Symbolic.mul(try term(a), try term(b))) }
336360 if isNaN(a, b) { return .nan }
337361 if case .int(let x) = a, case .int(let y) = b {
338362 let (product, overflow) = x.multipliedReportingOverflow(by: y)
@@ -352,6 +376,10 @@ public enum Calc {
352376 }
353377
354378 static func divide(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value {
379 // `math-div-by-zero` leaves the quotient alone.
380 if isSymbolic(a, b) || (isZero(b) && (try? sign(a)) != nil) {
381 return try $fractions.withValue(fractions) { value(try Symbolic.div(try term(a), try term(b))) }
382 }
355383 if isNaN(a, b) { return .nan }
356384 if fractions || { if case .frac = a { return true }; if case .frac = b { return true }; return false }(),
357385 let (n1, d1) = rational(a), let (n2, d2) = rational(b) {
@@ -391,15 +419,17 @@ public enum Calc {
391419
392420 /// `math-pow` of real numbers.
393421 static func power(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value {
422 // In symbolic mode Calc keeps a power that isn't exact, which isn't reproduced.
423 if symbolicMode, !isInteger(b) { throw Unsupported("symbolic mode") }
424 if isSymbolic(a, b) { return try $fractions.withValue(fractions) { value(try Symbolic.pow(try term(a), try term(b))) } }
394425 if isNaN(a, b) { return .nan }
395426 _ = (try sign(a), try sign(b))
396427 var floatB = false
397428 if case .float = b { floatB = true }
398429 if isZero(a) {
399 // `math-pow-of-zero`.
430 // `math-pow-of-zero`: an indeterminate form, or a division by zero, stays alone.
400431 if b == .int(0) { return .int(1) }
401 if isZero(b) { throw Unsupported("arguments") }
402 guard try sign(b) > 0 else { throw Unsupported("division by zero") }
432 guard try sign(b) > 0 else { throw Rejected() }
403433 return floatB ? try float(a) : a
404434 }
405435 if a == .int(1) || b == .int(1) || a == .float(1, 0) || b == .float(1, 0) { return a }
@@ -713,6 +743,7 @@ public enum Calc {
713743 case .int(let i): return String(i)
714744 case .frac(let n, let d): return "\(n):\(d)"
715745 case .vector: throw Unsupported("vector result")
746 case .symbolic(let t): return try Symbolic.format(t, floatFormat)
716747 case .nan: return "nan"
717748 case .date(let d): return "<" + (try formatDate(d)) + ">"
718749 case .float(let m, _) where m < 0:
@@ -900,11 +931,39 @@ public enum Calc {
900931 case unary(Character, Node)
901932 case binary(Character, Node, Node)
902933 case call(String, [Node])
934 case variable(String)
935
936 /// Whether the formula has a quotient, a power, a function call, or a product
937 /// whose factors share a variable, which Calc simplifies to a power.
938 var mayExplain: Bool {
939 switch self {
940 case .number, .variable: false
941 case .call: true
942 case .vector(let items): items.contains { $0.mayExplain }
943 case .unary(_, let a): a.mayExplain
944 case .binary("*", let a, let b) where !a.variables.isDisjoint(with: b.variables): true
945 case .binary(let op, let a, let b): "/%\\^".contains(op) || a.mayExplain || b.mayExplain
946 }
947 }
948
949 var variables: Set<String> {
950 switch self {
951 case .number: []
952 case .variable(let name): [name]
953 case .call(_, let items), .vector(let items): items.reduce(into: []) { $0.formUnion($1.variables) }
954 case .unary(_, let a): a.variables
955 case .binary(_, let a, let b): a.variables.union(b.variables)
956 }
957 }
903958 }
904959
905960 struct Parser {
906961 let chars: [Character]
907962 var i = 0
963 /// Inside `[...]`, where Calc reads `x -1` as two elements.
964 var inVector = false
965 /// Inside `[...]` with no comma, where Calc reads `1 2` as two elements.
966 var spaceSeparated = false
908967
909968 init(_ s: String) { chars = Array(s) }
910969
@@ -968,6 +1027,9 @@ public enum Calc {
9681027 mutating func sum() throws -> Node {
9691028 var left = try quotient()
9701029 while let c = peek(), c == "+" || c == "-" {
1030 if inVector, i > 0, chars[i - 1] == " " || chars[i - 1] == "\t", i + 1 < chars.count, chars[i + 1] != " ", chars[i + 1] != "\t" {
1031 throw Unsupported("formula syntax")
1032 }
9711033 i += 1
9721034 left = .binary(c, left, try quotient())
9731035 }
@@ -983,19 +1045,22 @@ public enum Calc {
9831045 return left
9841046 }
9851047
986 /// `*`, and juxtaposition `2 3` or `2 (x)`, which Calc reads as `*`.
1048 /// `*`, and juxtaposition `2 3` or `2 (x)`, which Calc reads as `*`. With
1049 /// `calc-multiplication-has-precedence` both are right-associative: `a * b c` and
1050 /// `a * b * c` are `a * (b * c)`.
9871051 mutating func product() throws -> Node {
988 var left = try unary()
989 while let c = peek() {
990 if c == "*" {
991 i += 1
992 } else if !(c.isASCII && c.isNumber) && !c.isLetter && c != "(" && c != "["
993 && !(c == "." && i + 1 < chars.count && chars[i + 1].isASCII && chars[i + 1].isNumber) {
994 break
995 }
996 left = .binary("*", left, try unary())
1052 let left = try unary()
1053 guard let c = peek() else { return left }
1054 if c == "*" {
1055 i += 1
1056 } else if !(c.isASCII && c.isNumber) && !c.isLetter && c != "(" && c != "["
1057 && !(c == "." && i + 1 < chars.count && chars[i + 1].isASCII && chars[i + 1].isNumber) {
1058 return left
1059 } else if spaceSeparated, chars[i - 1] == " " || chars[i - 1] == "\t" {
1060 // Calc reads `[1 2]` as two elements and `[1 2 * 3]` as one; not reproduced.
1061 throw Unsupported("formula syntax")
9971062 }
998 return left
1063 return .binary("*", left, try product())
9991064 }
10001065
10011066 /// `math-factor-after`: whether what follows can start an operand, which makes `%`
@@ -1052,13 +1117,19 @@ public enum Calc {
10521117 guard let c = peek() else { throw Unsupported("formula syntax") }
10531118 if c == "(" {
10541119 i += 1
1120 let outer = (inVector, spaceSeparated)
1121 (inVector, spaceSeparated) = (false, false)
10551122 let inner = try or()
1123 (inVector, spaceSeparated) = outer
10561124 guard peek() == ")" else { throw Unsupported("formula syntax") }
10571125 i += 1
10581126 return inner
10591127 }
10601128 if c == "[" {
10611129 i += 1
1130 let outer = (inVector, spaceSeparated)
1131 (inVector, spaceSeparated) = (true, !hasComma())
1132 defer { (inVector, spaceSeparated) = outer }
10621133 var items: [Node] = []
10631134 if peek() != "]" {
10641135 items.append(try or())
@@ -1084,11 +1155,20 @@ public enum Calc {
10841155 name.append(chars[i])
10851156 i += 1
10861157 }
1158 // `[f (x)]` is two elements.
1159 if spaceSeparated, i < chars.count, chars[i] != "(", peek() == "(" { throw Unsupported("formula syntax") }
10871160 guard peek() == "(" else {
10881161 if name == "nan" { return .number(.nan) }
1089 throw Unsupported("variable \(name)")
1162 // Calc's names are letters and digits; `_` is a subscript, and `'` and `#`
1163 // belong to the name.
1164 guard name.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber) }), !reserved.contains(name),
1165 i >= chars.count || !"'#".contains(chars[i]) else { throw Unsupported("variable \(name)") }
1166 return .variable(name)
10901167 }
10911168 i += 1
1169 let outer = (inVector, spaceSeparated)
1170 (inVector, spaceSeparated) = (false, false)
1171 defer { (inVector, spaceSeparated) = outer }
10921172 var args: [Node] = []
10931173 if peek() != ")" {
10941174 args.append(try or())
@@ -1104,6 +1184,18 @@ public enum Calc {
11041184 throw Unsupported("formula syntax")
11051185 }
11061186
1187 /// `math-check-for-commas`: whether a comma follows before the bracket that closes.
1188 func hasComma() -> Bool {
1189 var depth = 0
1190 for c in chars[i...] {
1191 if "[{(".contains(c) { depth += 1 }
1192 if "]})".contains(c) { depth -= 1 }
1193 if depth < 0 { return false }
1194 if c == ",", depth == 0 { return true }
1195 }
1196 return false
1197 }
1198
11071199 /// Calc's number syntax: `7`, `007`, `1.5`, `.5`, `5.`, `1e3`, `1.5e-3`, fractions `1:3`
11081200 /// and `1:2:3`, and integers in a radix, `16#FF`.
11091201 mutating func number() throws -> Value {
@@ -1149,6 +1241,17 @@ public enum Calc {
11491241 i += 1
11501242 }
11511243 fraction = f
1244 // Calc reads digits and points as one number: `21.11.2026` is a bad format.
1245 if i < chars.count, chars[i] == ".", i + 1 >= chars.count || chars[i + 1] != "." {
1246 while i < chars.count, (chars[i].isASCII && chars[i].isNumber)
1247 || (chars[i] == "." && (i + 1 >= chars.count || chars[i + 1] != ".")) { i += 1 }
1248 // The position is in the string Calc reads, after it rewrites `..` and
1249 // characters such as `²`; an exponent belongs to the number.
1250 let before = String(chars[..<i])
1251 guard before.allSatisfy(\.isASCII), !before.contains(".."),
1252 i >= chars.count || !"eE".contains(chars[i]) else { throw Unsupported("formula syntax") }
1253 throw Failure("Bad format", position: i)
1254 }
11521255 }
11531256 var exponent: Int?
11541257 if i < chars.count, chars[i] == "e" || chars[i] == "E" {
@@ -1190,11 +1293,51 @@ public enum Calc {
11901293 case .number(let v): return v
11911294 case .vector(let items): return .vector(try items.map(eval))
11921295 case .unary("!", let operand): return .int(try truth(try eval(operand)) ? 0 : 1)
1193 case .unary(_, let operand): return try negate(try eval(operand))
1296 case .unary(_, let operand):
1297 let a = try eval(operand)
1298 do { return try negate(a) } catch is Rejected { return .symbolic(.op("neg", [try term(a)])) }
11941299 case .binary(let op, let l, let r):
1195 return try binary(op, try eval(l), try eval(r))
1300 let (a, b) = (try eval(l), try eval(r))
1301 do {
1302 return try binary(op, a, b)
1303 } catch is Rejected {
1304 // `math-normalize` keeps the operation, its arguments evaluated.
1305 guard let name = ["+": "+", "-": "-", "*": "*", "/": "/", "^": "^"][op] else { throw Unsupported("division by zero") }
1306 return .symbolic(.op(name, [try term(a), try term(b)]))
1307 }
11961308 case .call(let name, let args):
1197 return try call(name, try args.map(eval))
1309 let values = try args.map(eval)
1310 // In symbolic mode Calc keeps these unevaluated when the result isn't exact,
1311 // which isn't reproduced.
1312 if modes.symbolic, Self.inexact.contains(name) || (!modes.degrees && ["sin", "cos", "tan"].contains(name)) {
1313 throw Unsupported("function \(name) in symbolic mode")
1314 }
1315 if values.contains(where: Self.hasSymbol) {
1316 // Calc leaves most functions of a formula alone, and simplifies some.
1317 guard ["vsum", "vprod", "vmean", "vcount"].contains(name),
1318 values.allSatisfy({ if case .vector = $0 { true } else { !Self.hasSymbol($0) } }) else {
1319 throw Unsupported("function \(name) of a formula")
1320 }
1321 }
1322 do {
1323 return try call(name, values)
1324 } catch is Rejected {
1325 throw Unsupported("division by zero")
1326 }
1327 case .variable(let name):
1328 return .symbolic(.variable(name))
1329 }
1330 }
1331
1332 static let inexact: Set<String> = ["sqrt", "exp", "ln", "log10", "log", "vsdev", "vpsdev", "vgmean", "vhmean", "vcorr",
1333 "vcov", "vpcov", "agmean", "pow", "nroot", "hypot", "sinh", "cosh", "tanh", "arcsinh",
1334 "arccosh", "arctanh", "arcsin", "arccos", "arctan", "arctan2", "fact", "dfact"]
1335
1336 static func hasSymbol(_ v: Value) -> Bool {
1337 switch v {
1338 case .symbolic: true
1339 case .vector(let items): items.contains(where: hasSymbol)
1340 default: false
11981341 }
11991342 }
12001343
Sources/OrgCore/Compute/CalcSymbolic.swift added +694
@@ -0,0 +1,694 @@
1import Foundation
2
3/// Calc's arithmetic on formulas it can't reduce to a number: variables, `inf`, `uinf`, and
4/// quotients by zero. This ports `math-add`, `math-mul`, `math-div`, `math-pow` and `math-neg`
5/// with their `-symb-fancy` helpers from calc.el and calc-arith.el, as `calc-eval` runs them
6/// with `calc-simplify-mode` nil, and Calc's flat formula printer from calccomp.el. Anything
7/// those functions would decide from declarations, units, matrices or intervals throws
8/// `Calc.Unsupported`.
9extension Calc {
10 /// A formula, as Calc's Lisp form: a number, a variable, or an operator or function with
11 /// its arguments (`+ - * / ^ neg`, or a function name).
12 public indirect enum Term: Equatable, Sendable {
13 case number(Value)
14 case variable(String)
15 case op(String, [Term])
16 }
17
18 /// `math-reject-arg`: the operation stays unevaluated.
19 struct Rejected: Error {}
20
21 /// `calc-symbolic-mode`.
22 @TaskLocal static var symbolicMode = false
23
24 /// `calc-prefer-frac`, for the division the arithmetic does.
25 @TaskLocal static var fractions = false
26
27 /// Variables Calc gives a value or a declaration, which would change the arithmetic.
28 static let reserved: Set<String> = ["CommuteRules", "Decls", "DistribRules", "EvalRules", "FactorRules", "FitRules",
29 "Holidays", "IntegAfterRules", "InvertRules", "JumpRules", "MergeRules", "Modes",
30 "NegateRules"]
31
32 /// The special constants and infinities, whose sign or type Calc knows.
33 static let constants: Set<String> = ["pi", "e", "phi", "gamma", "i", "inf", "uinf", "nan"]
34
35 static func term(_ v: Value) throws -> Term {
36 switch v {
37 case .symbolic(let t): return t
38 case .nan: return .variable("nan")
39 case .int, .float, .frac: return .number(v)
40 case .vector, .date: throw Unsupported("symbolic arithmetic")
41 }
42 }
43
44 static func value(_ t: Term) -> Value {
45 switch t {
46 case .number(let v): return v
47 case .variable("nan"): return .nan
48 default: return .symbolic(t)
49 }
50 }
51
52 enum Symbolic {
53 static let inf = Term.variable("inf")
54 static let uinf = Term.variable("uinf")
55 static let nan = Term.variable("nan")
56
57 // MARK: Predicates
58
59 static func number(_ t: Term) -> Value? {
60 if case .number(let v) = t { return v }
61 return nil
62 }
63
64 static func head(_ t: Term) -> String? {
65 if case .op(let f, _) = t { return f }
66 return nil
67 }
68
69 /// `(nth n a)`, from 1.
70 static func arg(_ t: Term, _ n: Int) -> Term {
71 guard case .op(_, let args) = t, n - 1 < args.count else { return .number(.int(0)) }
72 return args[n - 1]
73 }
74
75 static func objectp(_ t: Term) -> Bool { number(t) != nil }
76 static func zerop(_ t: Term) -> Bool { number(t).map(isZero) ?? false }
77 static func floatp(_ t: Term) -> Bool {
78 if case .number(.float) = t { return true }
79 return false
80 }
81 static func ratp(_ t: Term) -> Bool { number(t).map { rational($0) != nil } ?? false }
82 static func integerp(_ t: Term) -> Bool {
83 if case .number(.int) = t { return true }
84 return false
85 }
86
87 /// `math-negp`.
88 static func negp(_ t: Term) -> Bool {
89 if let v = number(t) { return (try? sign(v)) == -1 }
90 return t == .op("neg", [inf])
91 }
92
93 /// `math-posp`.
94 static func posp(_ t: Term) -> Bool {
95 if let v = number(t) { return (try? sign(v)) == 1 }
96 return t == inf
97 }
98
99 /// `Math-equal-int`.
100 static func equalInt(_ t: Term, _ n: Int) -> Bool {
101 t == .number(.int(n)) || t == .number(.float(n, 0))
102 }
103
104 /// `math-looks-negp`; `loose` false is the `Math-looks-negp` macro, which doesn't
105 /// look inside a difference.
106 static func looksNeg(_ t: Term, loose: Bool = true) -> Bool {
107 if negp(t) { return true }
108 switch head(t) {
109 case "neg": return true
110 case "*", "/": return looksNeg(arg(t, 1)) || looksNeg(arg(t, 2))
111 case "-": return loose && looksNeg(arg(t, 1))
112 default: return false
113 }
114 }
115
116 /// `math-infinitep`: the infinity a product, quotient or negation is made of.
117 static func infinitep(_ t: Term) -> Term? {
118 var a = t
119 while let f = head(a), ["*", "/", "neg"].contains(f) {
120 a = f != "*" || infinitep(arg(a, 1)) != nil ? arg(a, 1) : arg(a, 2)
121 }
122 return [inf, uinf, nan].contains(a) ? a : nil
123 }
124
125 static func containsConstant(_ t: Term) -> Bool {
126 switch t {
127 case .number: false
128 case .variable(let name): constants.contains(name)
129 case .op(_, let args): args.contains(where: containsConstant)
130 }
131 }
132
133 /// `math-possible-signs`: the bits 1 negative, 2 zero, 4 positive and 8 not real,
134 /// relative to `origin`. Nothing is declared, so a variable may be anything.
135 static func signs(_ a: Term, _ origin: Term? = nil) throws -> Int {
136 func negSigns(_ s: Int) -> Int {
137 s >= 8 ? 8 + negSigns(s - 8) : (s & 1 != 0 ? 4 : 0) | (s & 2) | (s & 4 != 0 ? 1 : 0)
138 }
139 if objectp(a) {
140 let x = try origin.map { try sub(a, $0) } ?? a
141 return posp(x) ? 4 : negp(x) ? 1 : 2
142 }
143 let (a1, a2) = (arg(a, 1), arg(a, 2))
144 let f = head(a)
145 if f == "+" || f == "-" {
146 if objectp(a1) {
147 if f == "-" { return negSigns(try signs(a2, try origin.map { try add($0, a1) } ?? a1)) }
148 return try signs(a2, try origin.map { try sub($0, a1) } ?? (try neg(a1)))
149 }
150 if objectp(a2) {
151 let org = f == "-" ? a2 : try neg(a2)
152 return try signs(a1, try origin.map { try add($0, org) } ?? org)
153 }
154 let s1 = try signs(a1, origin)
155 var s2 = try signs(a2)
156 if f == "-" { s2 = negSigns(s2) }
157 if s1 == s2 { return s1 }
158 if s1 == 2 { return s2 }
159 if s2 == 2 { return s1 }
160 if s1 >= 8 || s2 >= 8 { return 15 }
161 if (s1, s2) == (4, 6) || (s1, s2) == (6, 4) { return 4 }
162 if (s1, s2) == (1, 3) || (s1, s2) == (3, 1) { return 1 }
163 return 7
164 }
165 if f == "neg" { return negSigns(try signs(a1, try origin.map(neg))) }
166 let origin = origin.flatMap { zerop($0) ? nil : $0 }
167 let zero = Term.number(.int(0))
168 if f == "*" || (f == "/" && origin != nil), objectp(a1) {
169 let s = f == "*"
170 ? (zerop(a1) ? try signs(zero, origin) : try signs(a2, try div(origin ?? zero, a1)))
171 : negSigns(try signs(a2, try div(a1, origin!)))
172 return negp(a1) ? negSigns(s) : s
173 }
174 if f == "*" || f == "/", objectp(a2) {
175 let s = try signs(a1, f == "*" ? try mul(origin ?? zero, a2) : try div(origin ?? zero, a2))
176 return negp(a2) ? negSigns(s) : s
177 }
178 let sign: Int
179 switch a {
180 case .op("*", _), .op("/", _):
181 let (s1, s2) = (try signs(a1), try signs(a2))
182 if s1 >= 8 || s2 >= 8 || (f == "/" && [2, 3, 6, 7].contains(s2)) {
183 sign = 15
184 } else {
185 sign = (s1 & 4 != 0 ? s2 : 0) | (s1 & 2) | (s1 & 1 != 0 ? negSigns(s2) : 0)
186 }
187 case .op("^", _):
188 let (s1, s2) = (try signs(a1), try signs(a2))
189 if s1 >= 8 || s2 >= 8 {
190 sign = 15
191 } else if s1 == 4 {
192 sign = 4
193 } else if s1 == 2 {
194 sign = s2 == 4 ? 2 : 15
195 } else if s2 == 2 {
196 sign = [1, 5].contains(s1) ? 2 : 15
197 } else if case .number(.int(let n)) = a2 {
198 sign = n % 2 == 0 ? ([3, 6, 7].contains(s1) ? 6 : 4) : s1
199 } else if s1 == 6 {
200 sign = s2 == 4 ? 6 : 15
201 } else {
202 sign = 7
203 }
204 case .variable(let name):
205 switch name {
206 case "pi", "e":
207 guard origin == nil else { throw Unsupported("symbolic arithmetic") }
208 return 4
209 case "inf": return 4
210 case "uinf": return 13
211 case "i": return 8
212 default: return 15
213 }
214 default: throw Unsupported("function \(f ?? "")")
215 }
216 guard let origin else { return sign }
217 if posp(origin) { return (sign & 8) + ([1, 2, 3, 8, 9, 10, 11].contains(sign) ? 1 : 7) }
218 return (sign & 8) + ([2, 4, 6, 8, 10, 12, 14].contains(sign) ? 4 : 7)
219 }
220
221 static func knownNonneg(_ t: Term) throws -> Bool { [2, 4, 6].contains(try signs(t)) }
222
223 /// `math-known-num-integerp`.
224 static func knownNumInteger(_ t: Term) throws -> Bool {
225 if let v = number(t) { return isWhole(v) }
226 guard !containsConstant(t) else { throw Unsupported("symbolic arithmetic") }
227 return try possibleTypes(t, num: true) <= 3
228 }
229
230 /// `math-possible-types`: the bits 1 integer, 2 integer-valued float, 4 fraction and
231 /// 8 float, with `num` merging 1 and 2 and merging 4 and 8. Nothing is declared, so a
232 /// variable may be anything (63). Results above 15 are all 63 here: only whether a
233 /// result is at most 3 is used, and no larger operand can make it so.
234 static func possibleTypes(_ a: Term, num: Bool = false) throws -> Int {
235 func merge(_ t1: Int, _ t2: Int, _ mask: Int) -> Int {
236 if num { return mask * 3 }
237 return (t1 & 5 > 0 && t2 & 5 > 0 ? mask : 0) | ((t1 | t2) & 10 > 0 ? mask * 2 : 0)
238 }
239 switch a {
240 case .number(.int): return num ? 3 : 1
241 case .number(.float(_, let e)) where e >= 0: return num ? 3 : 2
242 case .number(.frac): return num ? 12 : 4
243 case .number(.float): return num ? 12 : 8
244 case .number: throw Unsupported("symbolic arithmetic")
245 case .variable: return 63
246 case .op("neg", let args): return try possibleTypes(args[0])
247 case .op(let f, let args) where args.count == 2 && ["+", "-", "*", "/", "^"].contains(f):
248 let (t1, t2) = (try possibleTypes(args[0], num: num), try possibleTypes(args[1], num: num))
249 let t12 = t1 | t2
250 if f == "^" {
251 guard t2 <= 3, try knownNonneg(args[1]), t1 < 16 else {
252 return try knownNonneg(args[0]) && signs(args[1]) == 4 ? 15 : 63
253 }
254 let mask = (t1 & 3 > 0 ? 1 : 0) | (t1 & 4) | (t1 & 12 > 0 ? 5 : 0)
255 return merge(t1, t2, mask)
256 }
257 guard t12 < 16 else { return 63 }
258 if f == "/" {
259 if t12 & 10 > 0 { return 10 }
260 return t1 == 4 || t2 == 4 || fractions ? 5 : 15
261 }
262 let mask = t12 <= 3 ? 1
263 : ((t1 <= 3 && t2 & 3 == 0) || (t2 <= 3 && t1 & 3 == 0)) && f != "*" ? 4 : 5
264 return merge(t1, t2, mask)
265 default: throw Unsupported("function \(head(a) ?? "")")
266 }
267 }
268
269 // MARK: Arithmetic
270
271 /// `math-normalize`: the operations applied again from the leaves, floats rounded
272 /// to the precision.
273 static func normalize(_ t: Term) throws -> Term {
274 switch t {
275 case .number(.float(let m, let e)): return .number(try makeFloat(Int128(m), e))
276 case .number, .variable: return t
277 case .op(let f, let args):
278 let args = try args.map(normalize)
279 do { return try apply(f, args) } catch is Rejected { return .op(f, args) }
280 }
281 }
282
283 static func apply(_ f: String, _ args: [Term]) throws -> Term {
284 switch (f, args.count) {
285 case ("+", 2): return try add(args[0], args[1])
286 case ("-", 2): return try sub(args[0], args[1])
287 case ("*", 2): return try mul(args[0], args[1])
288 case ("/", 2): return try div(args[0], args[1])
289 case ("^", 2): return try pow(args[0], args[1])
290 case ("neg", 1): return try neg(args[0])
291 default: throw Unsupported("function \(f)")
292 }
293 }
294
295 static func numeric(_ a: Term, _ b: Term, _ op: (Value, Value) throws -> Value) throws -> Term? {
296 guard let x = number(a), let y = number(b) else { return nil }
297 return try term(try op(x, y))
298 }
299
300 /// `math-float` of a rational number.
301 static func float(_ t: Term) throws -> Term {
302 guard let v = number(t) else { return t }
303 return .number(try Calc.float(v))
304 }
305
306 /// `math-neg`.
307 static func neg(_ a: Term) throws -> Term {
308 if let v = number(a) { return .number(try negate(v)) }
309 func okayNeg(_ t: Term) -> Bool { looksNeg(t) || head(t) == "-" }
310 let (a1, a2) = (arg(a, 1), arg(a, 2))
311 switch head(a) {
312 case "+": return try sub(try neg(a1), a2)
313 case "-": return try sub(a2, a1)
314 case "*", "/":
315 let f = head(a)!
316 if okayNeg(a1) { return .op(f, [try neg(a1), a2]) }
317 if okayNeg(a2) { return .op(f, [a1, try neg(a2)]) }
318 if objectp(a1) || (head(a1) == "*" && objectp(arg(a1, 1))) { return .op(f, [try neg(a1), a2]) }
319 if f == "/", objectp(a2) || (head(a2) == "*" && objectp(arg(a2, 1))) { return .op(f, [a1, try neg(a2)]) }
320 case "neg": return a1
321 default: if a == uinf || a == nan { return a }
322 }
323 return .op("neg", [a])
324 }
325
326 /// `math-add`.
327 static func add(_ a: Term, _ b: Term) throws -> Term {
328 if let sum = try numeric(a, b, { try Calc.add($0, $1) }) { return sum }
329 if zerop(a) { return b }
330 if zerop(b) { return a }
331 return try addFancy(a, b)
332 }
333
334 /// `math-sub`.
335 static func sub(_ a: Term, _ b: Term) throws -> Term { try add(a, try neg(b)) }
336
337 /// `math-add-symb-fancy`.
338 static func addFancy(_ a: Term, _ b: Term) throws -> Term {
339 switch head(b) {
340 case "+": return try add(try add(a, arg(b, 1)), arg(b, 2))
341 case "-": return try sub(try add(a, arg(b, 1)), arg(b, 2))
342 case "neg" where head(arg(b, 1)) == "+":
343 return try sub(try sub(a, arg(arg(b, 1), 1)), arg(arg(b, 1), 2))
344 default: break
345 }
346 if let result = try combineSums(a, b) { return result }
347 if looksNeg(b, loose: false) { return .op("-", [a, try neg(b)]) }
348 if looksNeg(a, loose: false) { return .op("-", [b, try neg(a)]) }
349 return .op("+", [a, b])
350 }
351
352 /// The `cond` in `math-add-symb-fancy` that handles infinities and like terms.
353 static func combineSums(_ a: Term, _ b: Term) throws -> Term? {
354 if let infA = infinitep(a) {
355 guard let infB = infinitep(b) else { return a }
356 if [uinf, nan].contains(infA) || [uinf, nan].contains(infB) { return nan }
357 let dirA = try infiniteDirection(a, infA)
358 let dirB = try infiniteDirection(b, infB)
359 guard let x = number(dirA), let y = number(dirB) else { return nil }
360 return try compare(x, y) == 0 ? a : nan
361 }
362 if infinitep(b) != nil { return b }
363 if head(a) == "+" {
364 return try combineSum(arg(a, 2), b, negA: false, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) }
365 }
366 if head(a) == "-" {
367 return try combineSum(arg(a, 2), b, negA: true, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) }
368 }
369 if objectp(a), objectp(b) { return nil }
370 return try combineSum(a, b, negA: false, negB: false, scalarOkay: false)
371 }
372
373 /// `math-infinite-dir`: the formula with its infinity replaced by 1.
374 static func infiniteDirection(_ a: Term, _ infinity: Term) throws -> Term {
375 func substitute(_ t: Term) -> Term {
376 if t == infinity { return .number(.int(1)) }
377 if case .op(let f, let args) = t { return .op(f, args.map(substitute)) }
378 return t
379 }
380 return try normalize(substitute(a))
381 }
382
383 /// `math-combine-sum`: two terms that are multiples of the same thing, added.
384 static func combineSum(_ a: Term, _ b: Term, negA: Bool, negB: Bool, scalarOkay: Bool) throws -> Term? {
385 if scalarOkay, objectp(a), objectp(b) {
386 return try add(negA ? try neg(a) : a, negB ? try neg(b) : b)
387 }
388 /// The coefficient and the rest; a nil coefficient is Calc's `(frac 1 0)`.
389 func split(_ t: Term) throws -> (Term?, Term) {
390 switch head(t) {
391 case "*" where objectp(arg(t, 1)): return (arg(t, 1), arg(t, 2))
392 case "/" where objectp(arg(t, 2)):
393 let d = arg(t, 2)
394 if case .number(.int(let n)) = d { return (n == 0 ? nil : .number(try fraction(1, n)), arg(t, 1)) }
395 return (try div(.number(.int(1)), d), arg(t, 1))
396 case "neg": return (.number(.int(-1)), arg(t, 1))
397 default: return (.number(.int(1)), t)
398 }
399 }
400 let (multA, restA) = try split(a)
401 let (multB, restB) = try split(b)
402 guard restA == restB else { return nil }
403 // `math-make-frac` of two such coefficients divides by zero.
404 if multA == nil, multB == nil { throw Rejected() }
405 guard var ma = multA, var mb = multB else { throw Unsupported("division by zero") }
406 if negA { ma = try neg(ma) }
407 if negB { mb = try neg(mb) }
408 return try mul(try add(ma, mb), restA)
409 }
410
411 /// `math-mul`.
412 static func mul(_ a: Term, _ b: Term) throws -> Term {
413 if let product = try numeric(a, b, { try multiply($0, $1) }) { return product }
414 if zerop(a) { return try mulZero(a, b) }
415 if zerop(b) { return try mulZero(b, a) }
416 return try mulFancy(a, b)
417 }
418
419 /// `math-mul-zero`, `a` zero and `b` a formula.
420 static func mulZero(_ a: Term, _ b: Term) throws -> Term {
421 if infinitep(b) != nil { return nan }
422 return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0))
423 }
424
425 /// `math-mul-symb-fancy`.
426 static func mulFancy(_ a: Term, _ b: Term) throws -> Term {
427 if equalInt(a, 1) { return b }
428 if equalInt(a, -1) { return try neg(b) }
429 if objectp(b), !objectp(a) { return try mul(b, a) }
430 if head(a) == "neg" { return try neg(try mul(arg(a, 1), b)) }
431 if head(b) == "neg" { return try neg(try mul(a, arg(b, 1))) }
432 if head(a) == "*" { return try mul(arg(a, 1), try mul(arg(a, 2), b)) }
433 let negativePower = { (t: Term) in head(t) == "^" && looksNeg(arg(t, 2), loose: false) }
434 if negativePower(a), !negativePower(b) {
435 return try div(b, try normalize(.op("^", [arg(a, 1), try neg(arg(a, 2))])))
436 }
437 if negativePower(b), !negativePower(a) {
438 return try div(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))])))
439 }
440 if head(a) == "/" {
441 if let c = try combineProd(arg(a, 2), b, invA: true, invB: false, scalarOkay: true) { return try mul(arg(a, 1), c) }
442 return try div(try mul(arg(a, 1), b), arg(a, 2))
443 }
444 if head(b) == "/" { return try div(try mul(a, arg(b, 1)), arg(b, 2)) }
445 if let f = head(b), f == "+" || f == "-", objectp(a), objectp(arg(b, 1)) || objectp(arg(b, 2)) {
446 let (x, y) = (try mul(a, arg(b, 1)), try mul(a, arg(b, 2)))
447 return f == "+" ? try add(x, y) : try sub(x, y)
448 }
449 if head(b) == "*", objectp(arg(b, 1)), !objectp(a) { return try mul(arg(b, 1), try mul(a, arg(b, 2))) }
450 if looksNeg(b) || (head(b) == "-" && looksNeg(a)) { return try mul(try neg(a), try neg(b)) }
451 if head(b) == "*" {
452 if let c = try combineProd(a, arg(b, 1), invA: false, invB: false, scalarOkay: true) { return try mul(c, arg(b, 2)) }
453 } else if let c = try combineProd(a, b, invA: false, invB: false, scalarOkay: false) {
454 return c
455 }
456 for special in [nan, uinf] {
457 if a == special { return a }
458 if b == special { return b }
459 }
460 if b == inf {
461 switch try signs(a) {
462 case 4: return b
463 case 1: return try neg(b)
464 case 3, 6: throw Unsupported("symbolic arithmetic")
465 default: break
466 }
467 }
468 if a == inf { return try mul(b, a) }
469 return .op("*", [a, b])
470 }
471
472 /// `math-div`.
473 static func div(_ a: Term, _ b: Term) throws -> Term {
474 if zerop(b) {
475 // `math-div-by-zero`.
476 guard let infinity = infinitep(a) else { throw Rejected() }
477 return infinity == nan ? a : uinf
478 }
479 if let quotient = try numeric(a, b, { try divide($0, $1, fractions: fractions) }) { return quotient }
480 // `math-div-zero`.
481 if zerop(a) { return b == nan ? b : a }
482 return try divFancy(a, b)
483 }
484
485 /// `math-div-symb-fancy`.
486 static func divFancy(_ a: Term, _ b: Term) throws -> Term {
487 if equalInt(b, 1) { return a }
488 if equalInt(b, -1) { return try neg(a) }
489 if head(b) == "^", looksNeg(arg(b, 2), loose: false) || equalInt(a, 1) {
490 return try mul(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))])))
491 }
492 if head(a) == "neg" { return try neg(try div(arg(a, 1), b)) }
493 if head(b) == "neg" { return try neg(try div(a, arg(b, 1))) }
494 if head(a) == "/" { return try div(arg(a, 1), try mul(arg(a, 2), b)) }
495 if head(b) == "/" { return try div(try mul(a, arg(b, 2)), arg(b, 1)) }
496 if case .number(.frac(let n, let d)) = b { return try mul(.number(try fraction(d, n)), a) }
497 if let f = head(a), f == "+" || f == "-", objectp(arg(a, 1)) || objectp(arg(a, 2)), objectp(b) {
498 let (x, y) = (try div(arg(a, 1), b), try div(arg(a, 2), b))
499 return f == "+" ? try add(x, y) : try sub(x, y)
500 }
501 if head(a) == "-" || looksNeg(a), looksNeg(b) { return try div(try neg(a), try neg(b)) }
502 if head(b) == "-", looksNeg(a) { return try div(try neg(a), try neg(b)) }
503 if head(a) == "*" {
504 if head(b) == "*" {
505 if let c = try combineProd(arg(a, 1), arg(b, 1), invA: false, invB: true, scalarOkay: true) {
506 return try div(try mul(c, arg(a, 2)), arg(b, 2))
507 }
508 } else if let c = try combineProd(arg(a, 1), b, invA: false, invB: true, scalarOkay: true) {
509 return try mul(c, arg(a, 2))
510 }
511 } else if head(b) == "*" {
512 if let c = try combineProd(a, arg(b, 1), invA: false, invB: true, scalarOkay: true) { return try div(c, arg(b, 2)) }
513 } else if let c = try combineProd(a, b, invA: false, invB: true, scalarOkay: false) {
514 return c
515 }
516 if infinitep(a) != nil {
517 if infinitep(b) != nil { return nan }
518 if a == nan || a == uinf { return a }
519 if a == inf {
520 if posp(b) { return a }
521 if negp(b) { return try neg(a) }
522 if objectp(b) { throw Unsupported("symbolic arithmetic") }
523 }
524 }
525 if infinitep(b) != nil {
526 if b == nan { return b }
527 return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0))
528 }
529 return .op("/", [a, b])
530 }
531
532 /// `math-mul-or-div`.
533 static func mulOrDiv(_ a: Term, _ b: Term, invA: Bool, invB: Bool) throws -> Term {
534 if invA { return invB ? try div(try div(.number(.int(1)), a), b) : try div(b, a) }
535 return invB ? try div(a, b) : try mul(a, b)
536 }
537
538 /// `math-combine-prod`: two factors that are powers of the same thing, multiplied.
539 static func combineProd(_ a: Term, _ b: Term, invA: Bool, invB: Bool, scalarOkay: Bool) throws -> Term? {
540 if (invA && zerop(a)) || (invB && zerop(b)) { return nil }
541 if scalarOkay, objectp(a), objectp(b) {
542 let r = try mulOrDiv(a, b, invA: invA, invB: invB)
543 return objectp(r) ? r : nil
544 }
545 if head(a) == "^", invA, looksNeg(arg(a, 2)) { return try mul(try pow(arg(a, 1), try neg(arg(a, 2))), b) }
546 if head(b) == "^", invB, looksNeg(arg(b, 2)) { return try mul(a, try pow(arg(b, 1), try neg(arg(b, 2)))) }
547 func split(_ t: Term) throws -> (Term, Term) {
548 var (base, power) = (t, Term.number(.int(1)))
549 if head(t) == "^", objectp(arg(t, 2)) { (base, power) = (arg(t, 1), arg(t, 2)) }
550 if head(t) == "sqrt" || head(t) == "exp" { throw Unsupported("symbolic arithmetic") }
551 if case .number(.frac(let n, let d)) = base, n < d {
552 (base, power) = (try div(.number(.int(1)), base), try neg(power))
553 }
554 return (base, power)
555 }
556 var (baseA, powA) = try split(a)
557 var (baseB, powB) = try split(b)
558 if invA { powA = try neg(powA) }
559 if invB { powB = try neg(powB) }
560 func isFrac(_ t: Term) -> Bool {
561 if case .number(.frac) = t { return true }
562 return false
563 }
564 if baseA == baseB {
565 var sum = try add(powA, powB)
566 if !integerp(baseA) || zerop(sum) || isFrac(powA) == isFrac(powB) {
567 if looksNeg(sum), ratp(baseA), posp(baseA) {
568 (baseA, sum) = (try div(.number(.int(1)), baseA), try neg(sum))
569 }
570 if sum == .number(.frac(1, 2)) || sum == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") }
571 return try pow(baseA, sum)
572 }
573 }
574 if powA == powB, case .number(.int(let x)) = baseA, case .number(.int(let y)) = baseB, x >= 0, y >= 0 {
575 if powA == .number(.frac(1, 2)) || powA == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") }
576 return try pow(try mul(baseA, baseB), powA)
577 }
578 return nil
579 }
580
581 /// `math-pow`.
582 static func pow(_ a: Term, _ b: Term) throws -> Term {
583 if b == nan { return b }
584 if zerop(a) {
585 if let y = number(b) {
586 if try sign(y) > 0 { return floatp(b) ? try float(a) : a }
587 return .number(try power(number(a)!, y, fractions: fractions))
588 }
589 // `math-pow-of-zero` with a formula.
590 switch try signs(b) {
591 case 4: return a
592 case 1: return try div(.number(.int(1)), a)
593 default: return infinitep(b) != nil ? nan : .op("^", [a, b])
594 }
595 }
596 if a == .number(.int(1)) || b == .number(.int(1)) { return a }
597 if a == .number(.float(1, 0)) || b == .number(.float(1, 0)) { return a }
598 if zerop(b) {
599 if let x = number(a) { return .number(try power(x, number(b)!, fractions: fractions)) }
600 // `math-pow-zero`.
601 if infinitep(a) != nil { return nan }
602 return floatp(b) ? .number(.float(1, 0)) : .number(.int(1))
603 }
604 if let x = number(a), let y = number(b) { return .number(try power(x, y, fractions: fractions)) }
605 return try powFancy(a, b)
606 }
607
608 /// `math-pow-fancy` with a formula.
609 static func powFancy(_ a: Term, _ b: Term) throws -> Term {
610 let (a1, a2) = (arg(a, 1), arg(a, 2))
611 switch head(a) {
612 case "*" where try knownNumInteger(b) || knownNonneg(a1) || knownNonneg(a2):
613 return try mul(try pow(a1, b), try pow(a2, b))
614 case "/" where try knownNumInteger(b) || knownNonneg(a2):
615 return try div(try pow(a1, b), try pow(a2, b))
616 case "/" where try knownNonneg(a1) && !equalInt(a1, 1):
617 return try mul(try pow(a1, b), try pow(try div(.number(.int(1)), a2), b))
618 case "^" where try knownNumInteger(b) || knownNonneg(a1):
619 return try pow(a1, try mul(a2, b))
620 case "^":
621 // `math-known-evenp` of an exponent with a variable is false.
622 if case .number(let n) = a2, isWhole(n), try trunc(n) % 2 == 0, let y = number(b), let q = quarter(y),
623 (1...3).contains(q), try signs(a1) < 8 { throw Unsupported("symbolic arithmetic") }
624 default: break
625 }
626 if looksNeg(a), case .number(.int(let n)) = b {
627 let p = try pow(try neg(a), b)
628 return n % 2 == 0 ? p : try neg(p)
629 }
630 if let infinity = infinitep(a) {
631 if infinity == nan { return infinity }
632 if head(a) == "neg" { return try mul(try pow(.number(.int(-1)), b), try pow(a1, b)) }
633 if posp(b) { return a }
634 if negp(b) { return floatp(b) ? .number(.float(0, 0)) : .number(.int(0)) }
635 if objectp(b) || infinitep(b) != nil { return nan }
636 throw Unsupported("symbolic arithmetic")
637 }
638 if infinitep(b) != nil {
639 guard let x = number(a), b == inf else { throw Unsupported("symbolic arithmetic") }
640 // `calcFunc-abssqr` of a real number is its square.
641 let scale = try multiply(x, x)
642 if scale == .int(1) || scale == .float(1, 0) { return nan }
643 if try compare(scale, .int(1)) < 0 { return floatp(a) ? .number(.float(0, 0)) : .number(.int(0)) }
644 if try compare(.int(1), x) < 0 { return b }
645 return uinf
646 }
647 return .op("^", [a, b])
648 }
649
650 // MARK: Display
651
652 /// `math-format-value`: `math-compose-expr` in the flat language.
653 static func format(_ t: Term, _ floatFormat: FloatFormat) throws -> String {
654 let text = try compose(t, 0, floatFormat)
655 // Past its width of 1000, `calc-eval` breaks the line.
656 guard text.count < 1000 else { throw Unsupported("symbolic arithmetic") }
657 return text
658 }
659
660 /// Left and right precedence, from `math-standard-ops` with
661 /// `calc-multiplication-has-precedence`.
662 static let operators: [String: (Int, Int)] = ["+": (180, 181), "-": (180, 181), "*": (196, 195), "/": (190, 191), "^": (201, 200)]
663
664 static func compose(_ t: Term, _ prec: Int, _ floatFormat: FloatFormat, div: Bool = false) throws -> String {
665 switch t {
666 case .number(let v): return try Calc.format(v, floatFormat)
667 case .variable(let name): return name
668 case .op("neg", let args):
669 if prec > 197 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
670 return "-" + (try compose(args[0], 197, floatFormat))
671 case .op(let f, let args):
672 guard let (left, right) = operators[f], args.count == 2 else {
673 return f + "(" + (try args.map { try compose($0, 0, floatFormat) }).joined(separator: ", ") + ")"
674 }
675 if prec > min(left, right) || (div && f == "*") { return "(" + (try compose(t, 0, floatFormat)) + ")" }
676 var lhs = try compose(args[0], left, floatFormat)
677 let rhs = try compose(args[1], right, floatFormat, div: f == "/")
678 if f == "^", lhs.first == "-" { lhs = "(" + lhs + ")" }
679 if f == "*", let next = rhs.first {
680 var lastFactor = args[0]
681 while head(lastFactor) == "*" { lastFactor = arg(lastFactor, 2) }
682 let isVariable = if case .variable = lastFactor { true } else { false }
683 if (next.isASCII && (next.isLetter || next.isNumber)) || ".#_([{".contains(next), !(isVariable && next == "(") {
684 return lhs + " " + rhs
685 }
686 return lhs + "*" + rhs
687 }
688 if f == "^" { return lhs + "^" + rhs }
689 if f == "/", let x = number(args[0]), isWhole(x), case .number(.int) = args[1] { return lhs + "/" + rhs }
690 return lhs + " " + f + " " + rhs
691 }
692 }
693 }
694}
Sources/OrgCore/Compute/TableFormulas.swift +9 −17
@@ -1,8 +1,8 @@
11import Foundation
22
33// Table formulas (org-table.el, Org 9.8.7): `org-table-recalculate` and
4// `org-table-eval-formula` with Calc and Lisp evaluated natively. Symbolic results, Calc
5// features beyond `Calc` and Lisp beyond `Elisp` throw `Calc.Unsupported`; the caller then
4// `org-table-eval-formula` with Calc and Lisp evaluated natively. Calc features beyond
5// `Calc` and Lisp beyond `Elisp` throw `Calc.Unsupported`; the caller then
66// recalculates the table in Emacs. `remote()` finds tables by name in the file, and by ID
77// here or, through `RemoteTables`, in other files.
88
@@ -306,7 +306,6 @@ extension EmacsBuffer {
306306 case list([String])
307307 }
308308
309 static let calcNumber = "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?$"
310309 /// `org-ts-regexp-both`.
311310 static let timestampBoth = "[\\[<]([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)[\\]>]"
312311
@@ -321,8 +320,8 @@ extension EmacsBuffer {
321320 /// `number-to-string` of `string-to-number`.
322321 static func numberText(_ s: String) -> String { Elisp.printed(Elisp.stringToNumber(s)) }
323322
324 /// `org-table-make-reference`. For Calc, a field that isn't a number, a date or `nan`
325 /// would be a symbol, which isn't supported.
323 /// `org-table-make-reference`. For Calc, a field's text goes in as it is, so text that
324 /// isn't a number reads as variables.
326325 static func makeReference(_ value: TableRangeValue, _ mode: ReferenceMode) throws -> String {
327326 func blank(_ s: String) -> Bool { !s.contains { !$0.isWhitespace } }
328327 func lisp(_ s: String) -> String {
@@ -331,24 +330,16 @@ extension EmacsBuffer {
331330 default: mode.numbers ? numberText(s) : Elisp.printed(.string(s), escape: true)
332331 }
333332 }
334 func calc(_ s: String) throws -> String {
335 let text = mode.numbers ? numberText(s) : s
336 guard text.range(of: calcNumber, options: .regularExpression) != nil || text == "nan"
337 || text.range(of: "^[-+]?[0-9]+:[0-9:]+$", options: .regularExpression) != nil
338 || text.range(of: "^" + timestampBoth + "$", options: .regularExpression) != nil else {
339 throw Calc.Unsupported("non-numeric field \(text)")
340 }
341 return text
342 }
333 func calc(_ s: String) -> String { mode.numbers ? numberText(s) : s }
343334 let empty = !mode.keepEmpty || mode.numbers ? "0" : "nan"
344335 switch value {
345336 case .field(let s):
346337 if mode.lisp != .none { return lisp(s) }
347 return blank(s) ? (empty == "0" ? "(0)" : "nan") : "(" + (try calc(s)) + ")"
338 return blank(s) ? (empty == "0" ? "(0)" : "nan") : "(" + calc(s) + ")"
348339 case .list(var items):
349340 if !mode.keepEmpty { items = items.filter { !blank($0) } }
350341 if mode.lisp != .none { return items.map(lisp).joined(separator: " ") }
351 return "[" + (try items.map { blank($0) ? empty : try calc($0) }).joined(separator: ",") + "]"
342 return "[" + items.map { blank($0) ? empty : calc($0) }.joined(separator: ",") + "]"
352343 }
353344 }
354345
@@ -543,6 +534,7 @@ extension EmacsBuffer {
543534 case "F": modes.preferFractions = true
544535 case "D": modes.degrees = true
545536 case "R": modes.degrees = false
537 case "S": modes.symbolic = true
546538 default: throw Calc.Unsupported("format flag \(ns.substring(with: m.range))")
547539 }
548540 flags = ns.replacingCharacters(in: m.range, with: "")
@@ -634,7 +626,7 @@ extension EmacsBuffer {
634626 result = try Calc.evaluate(form, modes: modes, numeric: !mode.keepEmpty && mode.numbers)
635627 } catch let failure as Calc.Failure {
636628 // A duration formula takes Calc's error for a string, as org does.
637 if duration != nil { throw UserError(message: "Wrong type argument: stringp, (0 \"\(failure.reason)\")") }
629 if duration != nil { throw UserError(message: "Wrong type argument: stringp, (\(failure.position) \"\(failure.reason)\")") }
638630 (result, fmt) = ("#ERROR", nil)
639631 }
640632 }
Tests/OrgCoreTests/CalcTests.swift +104 −6
@@ -4,7 +4,7 @@ import Testing
44
55/// Runs `calc-eval` with org's table modes over a list of expressions.
66enum CalcOracle {
7 static func run(_ cases: [(expression: String, format: String)], precision: Int = 12, zone: String = "UTC") throws -> [String] {
7 static func run(_ cases: [(expression: String, format: String)], precision: Int = 12, zone: String = "UTC", symbolic: Bool = false) throws -> [String] {
88 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)")
99 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
1010 defer { try? FileManager.default.removeItem(at: folder) }
@@ -26,6 +26,7 @@ enum CalcOracle {
2626 (format (car (read-from-string (nth 1 c)))))
2727 (setq modes (plist-put modes 'calc-float-format format))
2828 (setq modes (plist-put modes 'calc-internal-prec (string-to-number (getenv "ORACLE_PREC"))))
29 (when (getenv "ORACLE_SYMBOLIC") (setq modes (plist-put modes 'calc-symbolic-mode t)))
2930 (let ((r (condition-case e (calc-eval (cons (car c) modes) nil)
3031 (error (format "LISP ERROR %S" e)))))
3132 (if (stringp r) r (format "ERROR %S" r)))))
@@ -33,7 +34,7 @@ enum CalcOracle {
3334 (with-temp-file (getenv "ORACLE_OUTPUT")
3435 (insert (json-encode (vconcat results)))))
3536 """#.write(to: script, atomically: true, encoding: .utf8)
36 _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path, "ORACLE_PREC": String(precision), "TZ": zone])
37 _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path, "ORACLE_PREC": String(precision), "TZ": zone].merging(symbolic ? ["ORACLE_SYMBOLIC": "1"] : [:]) { $1 })
3738 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
3839 }
3940}
@@ -223,13 +224,14 @@ struct CalcTests {
223224
224225 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the
225226 /// cases `Calc.evaluate` doesn't support.
226 static func compare(_ cases: [(String, String)], precision: Int = 12, zone: (name: String, offset: Int) = ("UTC", 0)) throws -> [String] {
227 let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name)
227 static func compare(_ cases: [(String, String)], precision: Int = 12, zone: (name: String, offset: Int) = ("UTC", 0), symbolic: Bool = false) throws -> [String] {
228 let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name, symbolic: symbolic)
228229 #expect(emacs.count == cases.count)
229230 var skipped: [String] = []
230231 for (c, expected) in zip(cases, emacs) {
231232 var modes = Calc.Modes()
232233 modes.precision = precision
234 modes.symbolic = symbolic
233235 modes.timeZone = TimeZone(secondsFromGMT: zone.offset)!
234236 let f = c.1.dropFirst().dropLast().split(separator: " ")
235237 let n = Int(f[1])!
@@ -340,14 +342,80 @@ struct CalcTests {
340342 }
341343 }
342344
345 /// Formulas Calc leaves unevaluated: variables, text from fields, quotients by zero and
346 /// infinities.
347 static let symbolic = [
348 "x", "pi", "e", "phi", "gamma", "2 pi", "pi*2", "pi+pi", "pi*pi", "e^2", "i*i", "abc*2", "x+5", "5 + x", "y + x",
349 "(N/A)+5", "(N/A)*(2)", "(N/A)+(N/A)", "(TBD)-(3)", "(5 kg)+(3)", "(5 kg)+(3 kg)", "a b c", "x2", "2x", "2e", ".5x",
350 "x+x", "x*2", "x+1+2", "x-x", "x/x", "x^2", "x*x", "(x)*(3)+(x)", "2 x + 3 y", "x - 5", "5 - x", "-x + 5", "-(x)",
351 "(x+1)*2", "(x+1)/2", "2/x", "x*y", "y*x", "x*x*x", "x + 2.5", "x * 2.5", "x * 1:3", "x*0", "x*0.", "x+0.",
352 "x - 0.5 x", "x / -2", "2^x", "x^0", "x^1", "x^-1", "x*(y+1)", "(y+1)*x", "x/(2 y)", "x/2 + x", "x/2 + x/3",
353 "a-(b-c)", "-(a+b)", "-(a/2)", "(a b)^2", "(a/b)^2", "(-a)^3", "a^2^3", "(a^2)^3", "1/a^2", "a^2/a", "2^x*2^x",
354 "x/1:2", "0/x", "0./x", "(2 x)^0.5", "(x/2)^0.5", "(2/x)^0.5", "(x^2)^0.5", "(-x)^2.", "(-x)^-3", "x^2*x^-3",
355 "2^x*3^x", "x/y/z", "(x/y)/(z/w)", "2/(3/x)", "-x*y", "x+2y-x", "(x+1)-(x+1)", "x^0.", "1^x", "0^x", "0.^x", "0^-x",
356 "1/0", "x/0", "0/0", "(5)/(0)", "(5.5)/(0)", "(0.)/(0)", "5/0.", "1:2/0", "x/0+1", "2*(1/0)", "(1/0)*2", "-(1/0)",
357 "(1/0)+(1/0)", "(1/0)^2", "2^(1/0)", "x/0 - x/0", "2*x/0", "0^-1", "0^0.", "2^(0^-1)", "x+0^-1",
358 "inf", "-inf", "uinf", "inf+1", "inf-inf", "inf*0", "1/inf", "inf*2", "x*inf", "inf*-2", "inf+x", "-inf-inf",
359 "uinf+1", "inf/0", "uinf/0", "inf^-1", "x/inf", "2^inf", "0.5^inf", "(-2)^inf", "inf^0", "nan*x", "x+nan", "x/nan",
360 "vsum([x,1,2])", "vmean([x,1])", "vmean([x,2,3])", "vsum([x,y,1])", "vprod([x,2,3])", "vmean([a,b])", "vcount([x,1])",
361 "vsum([1/0, 2])", "vsum([5 kg,3])", "vsum([2 (3),1])",
362 // No comma: Calc separates elements by spaces, except inside parentheses and arguments.
363 "vsum([1 - 2])", "vsum([x - 1])", "vsum([2x])", "vsum([(1 2)])", "vsum([max(1 2,3)])", "vcount([x])",
364 "(1/x) * 2 x", "(1/x) * 2 * x", "2 x * (1/x)", "(1/(2 x)) * 2 x", "x^-1 * 2 x", "((x)^2)^((0.0)^(0.0))",
365 "(x*y)^(0.0^0.0)", "(y^2)^(2*(0.0^0.0))", "(x^2)^(0.0^0.0 + 1)", "(x^2)^(-(0.0^0.0))", "(x^2)^(2^(0.0^0.0))",
366 ]
367
368 /// Products are right-associative, and a formula of integer-valued numbers is known to
369 /// be integer-valued.
370 @Test func symbolicOrder() throws {
371 var modes = Calc.Modes()
372 modes.format = .float(8)
373 for (e, expected) in [("(1/x) * 2 x", "2 x / x"), ("(1/x) * 2 * x", "2 x / x"), ("2 x * (1/x)", "2"),
374 ("(1/(2 x)) * 2 x", "1"), ("x^-1 * 2 x", "2 x / x"),
375 ("((x)^2)^((0.0)^(0.0))", "x^(2 0.^0.)"), ("(x*y)^(0.0^0.0)", "x^0.^0. y^0.^0."),
376 ("(y^2)^(2*(0.0^0.0))", "y^(4 0.^0.)"), ("(x^2)^(0.0^0.0 + 1)", "x^(2 0.^0. + 2)"),
377 ("(x^2)^(-(0.0^0.0))", "x^(-2 0.^0.)"), ("(x^2)^(2^(0.0^0.0))", "(x^2)^2^0.^0.")] {
378 #expect(try Calc.evaluate(e, modes: modes) == expected, "\(e)")
379 }
380 modes.format = .sci(11)
381 #expect(try Calc.evaluate("9.48205255399 * 7.65908717266 9.30092496999", modes: modes) == "6.7546913880e2")
382 }
383
384 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
385 func symbolicMatchesCalc() throws {
386 var cases = Self.symbolic.map { ($0, "(float 8)") }
387 for format in ["(fix 2)", "(sci 3)"] {
388 for e in ["x/3 + 1/3", "vmean([x,2,3])", "2.5 x - 1:3"] { cases.append((e, format)) }
389 }
390 // Generated: a variable or two mixed with numbers. What Calc would decide from more
391 // than this arithmetic is refused, so only what is computed is compared.
392 var generator = SystemRandomNumberGenerator()
393 let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "10", "inf", "a b"]
394 let ops = ["+", "-", "*", "/", "^"]
395 func expression(_ depth: Int) -> String {
396 if depth == 0 || Int.random(in: 0..<3, using: &generator) == 0 { return leaves.randomElement(using: &generator)! }
397 let op = ops.randomElement(using: &generator)!
398 let right = op == "^" ? ["2", "3", "-1", "0.5", "x", "-2"].randomElement(using: &generator)! : expression(depth - 1)
399 let e = "(\(expression(depth - 1)))\(op)(\(right))"
400 return Int.random(in: 0..<6, using: &generator) == 0 ? "-\(e)" : e
401 }
402 for _ in 0..<2000 { cases.append((expression(4), "(float 8)")) }
403 let skipped = try Self.compare(cases)
404 #expect(Set(skipped).intersection(Self.symbolic) == [], "\(skipped)")
405 #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused")
406 }
407
343408 @Test func unsupported() throws {
344 for e in ["abc*2", "1/0", "vmean([])", "pi", "e", "phi", "gamma", "2 pi", "(-8)^(1/3)", "vvar([5])", "1<2<3",
409 for e in ["vsum([5 kg])", "vsum([1 2])", "vcount([N A])", "vsum([2 3 4])", "vsum([1 1/2])", "vmin([3 4])",
410 "vcount([f (x)])", "vcount([1 [2]])", "vcount([(1) 2])", "vcount([1 sin (2)])", "1.2.3e5",
411 "sqrt(x)", "vmax([x,1])", "vsum(x,1)", "x<1", "if(x,1,2)", "x%2", "x_1", "x'", "Holidays+1", "café+1",
412 "x+<2026-10-05 Mon>", "[x,1]", "vcount([x -1])", "(1/0)+1", "vmean([])", "(-8)^(1/3)", "vvar([5])", "1<2<3",
345413 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
346414 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
347415 "nroot(-8,3)", "vgmean([-1,2])", "vhmean([0,1])", "gcd(1.5,3)", "gcd(12,18,4)", "5%%3", "1:0", "1:2:3:4",
348416 "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!",
349417 "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)",
350 "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "0^-1", "0^0.", "ln(0)", "ln(-1)",
418 "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "ln(0)", "ln(-1)",
351419 // Calc leaves these date expressions unevaluated.
352420 "<2026-10-05 Mon>*2", "2*<2026-10-05 Mon>", "<2026-10-05 Mon>/2", "<2026-10-05 Mon>*0", "<2026-10-05 Mon> < 5",
353421 "vmedian([<2026-10-05 Mon>,<2026-10-07 Wed>])", "vmean([<2026-10-05 Mon>,1])", "vmean([<2026-10-05 Mon>])",
@@ -373,5 +441,35 @@ struct CalcTests {
373441 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("<2026-10-05 Mon 10:00>+1", modes: modes) }
374442 modes.precision = 19
375443 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1+1", modes: modes) }
444 // `calc-eval` with `num`: a formula is an error, unless Calc explains it.
445 #expect(throws: Calc.Failure("Number expected")) { try Calc.evaluate("x+1", numeric: true) }
446 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1/0", numeric: true) }
447 // Calc explains what a quotient, power or function rejected, even when it cancels.
448 for e in ["x^2/x", "x*x/x", "inf+(1/0)", "x/2", "abs(x)", "x%2", "x*x", "x x", "x*y*x"] {
449 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, numeric: true) }
450 }
451 for e in ["-x", "x*2", "2 x", "x*y", "x+x", "x+2-2", "nan"] {
452 #expect(throws: Calc.Failure("Number expected"), "\(e)") { try Calc.evaluate(e, numeric: true) }
453 }
454 #expect(try Calc.evaluate("x/x", numeric: true) == "1")
455 // Digits and points read as one number, at the position Calc gives.
456 for (e, position) in [("21.11.2026+1", 10), ("(21.11.2026)+1", 11), ("1.5.+1", 4), (".5.5", 4), ("3.14.15", 7),
457 ("192.168.1.1", 11), ("1.2.3x", 5), ("1.5.", 4)] {
458 #expect(throws: Calc.Failure("Bad format", position: position), "\(e)") { try Calc.evaluate(e) }
459 }
460 var symbolic = Calc.Modes()
461 symbolic.symbolic = true
462 for e in ["sqrt(2)", "2^0.5", "ln(2)", "x^0.5"] {
463 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, modes: symbolic) }
464 }
465 }
466
467 /// `;S`: what is computed matches; functions and powers that may not be exact are refused.
468 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
469 func symbolicModeMatchesCalc() throws {
470 let cases = (Self.fixed + Self.functions + Self.symbolic).map { ($0, "(float 8)") }
471 let skipped = try Self.compare(cases, symbolic: true)
472 #expect(Set(skipped).isDisjoint(with: ["1/3", "x+5", "1/0", "2 pi", "vmean([x,2,3])", "sin(30)", "x^2", "round(2.5)"]))
473 #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused")
376474 }
377475}
Tests/OrgCoreTests/TableFormulaEntryTests.swift +6 −6
@@ -92,14 +92,14 @@ extension TableFormulaEntryTests {
9292 let text = "| a | b |\n|---+---|\n| 1 | 2 |\n#+TBLFM: $2=$1*2\n"
9393 let removed = try #require(committed(TableEvalFormula(named: false), text, after: "| 1 | 2", answers: ["formula": ""]))
9494 #expect(removed.text == "| a | b |\n|---+---|\n| 1 | 2 |\n#+TBLFM: \n" && removed.message == "Formula removed", "\(removed)")
95 // Text in a field is a Calc symbol, which needs Emacs: the formula is stored and TAB
95 // A function of a field holding text needs Emacs: the formula is stored and TAB
9696 // still moves on.
97 let symbolic = "| a | b |\n| x | =$1*2 |\n| y | |\n"
98 let tab = try #require(committed(TableCommand(.nextField), symbolic, after: "*2"))
99 #expect(tab.text == "| a | b |\n| x | =$1*2 |\n| y | |\n#+TBLFM: $2=$1*2\n", "\(tab.text.debugDescription)")
97 let symbolic = "| a | b |\n| x | =sqrt($1) |\n| y | |\n"
98 let tab = try #require(committed(TableCommand(.nextField), symbolic, after: "($1)"))
99 #expect(tab.text == "| a | b |\n| x | =sqrt($1) |\n| y | |\n#+TBLFM: $2=sqrt($1)\n", "\(tab.text.debugDescription)")
100100 #expect(tab.caret == (tab.text as NSString).range(of: "| y").location + 2)
101101 #expect(tab.message?.hasPrefix("The formula was stored; recalculating it needs Emacs") == true)
102 let prompted = try #require(committed(TableEvalFormula(named: false), symbolic, after: "| x", answers: ["formula": "$1+1"]))
103 #expect(prompted.text.hasSuffix("#+TBLFM: $1=$1+1\n") && prompted.message != nil, "\(prompted)")
102 let prompted = try #require(committed(TableEvalFormula(named: false), symbolic, after: "| x", answers: ["formula": "sqrt($1)"]))
103 #expect(prompted.text.hasSuffix("#+TBLFM: $1=sqrt($1)\n") && prompted.message != nil, "\(prompted)")
104104 }
105105}
Tests/OrgCoreTests/TableFormulaTests.swift +41 −5
@@ -89,6 +89,42 @@ struct TableFormulaTests {
8989 "| a | b |\n|---+---|\n| <2026-01-01 Thu> | |\n#+TBLFM: $2=<2026-12-25 Fri>-$1;U\n",
9090 ]
9191
92 /// Text and blank fields, which Calc reads as variables and zero, and the `S` flag.
93 static let symbolic = [
94 "| item | cost |\n|------+------|\n| a | 5 |\n| b | N/A |\n| c | 3 |\n|------+------|\n| total | |\n| mean | |\n#+TBLFM: @>>$2=vsum(@I..@II)::@>$2=vmean(@I..@II)\n",
95 "| a | b | ratio | twice |\n|---+---+-------+-------|\n| 6 | 0 | | |\n| 6 | | | |\n| 4.5 | 2 | | |\n| TBD | 4 | | |\n| 5 kg | 2 | | |\n#+TBLFM: $3=$1/$2::$4=2*$1+$2\n",
96 "| r | area | half |\n|---+------+------|\n| 3 | | |\n| x | | |\n#+TBLFM: $2=$1^2*pi::$3=$2/2;S\n",
97 "| a | b | c | d |\n|---+---+---+---|\n| 1 | | n/a | |\n| 2 | 3 | | |\n#+TBLFM: $4=vsum($1..$3)::@2$2=$1 + inf;S\n",
98 "| a | b | c |\n|---+---+---|\n| x | 1 | |\n| | 2 | |\n#+TBLFM: $3=$1*$2;E\n",
99 // Calc rejects a number with two points.
100 "| a | b |\n|---+---|\n| 21.11.2026 | |\n| 192.168.1.1 | |\n| 1.5 | |\n#+TBLFM: $2=$1+1\n",
101 "| a | b |\n|---+---|\n| 21.11.2026 | |\n#+TBLFM: $2=$1+1;T\n",
102 "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x;T\n",
103 "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x*y;T\n",
104 ]
105
106 /// A range of one field with a space is a vector without commas, which Calc splits at the
107 /// space; a power or quotient left symbolic under a duration flag has Calc's explanation.
108 @Test func refusesWhatCalcReadsOrExplainsDifferently() {
109 for text in [
110 "| a | b | c |\n|---+---+---|\n| 5 kg | | |\n#+TBLFM: $3=vsum($1..$2)\n",
111 "| a | b | c |\n|---+---+---|\n| 1 2 | | |\n#+TBLFM: $3=vsum($1..$2)\n",
112 "| a | b |\n|---+---|\n| N A | |\n| | |\n#+TBLFM: @2$2=vmean(@2$1..@3$1)\n",
113 "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x^2/x;T\n",
114 "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x*x;T\n",
115 "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x x;T\n",
116 ] {
117 let caret = (text as NSString).range(of: "#+TBLFM").location + 3
118 let failure = Self.recalculate(TableRecalculate(all: true), text, caret: caret).failure ?? ""
119 #expect(failure.hasPrefix("external:"), "\(failure) in\n\(text)")
120 }
121 }
122
123 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
124 func textAndBlankFieldsMatchEmacsNatively() throws {
125 try compare(Self.symbolic, fallbacksAllowed: false, headerFallbacksAllowed: false)
126 }
127
92128 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
93129 func datesMatchEmacs() throws {
94130 try compare(Self.dates + Self.numericResults, fallbacksAllowed: false)
@@ -150,7 +186,9 @@ struct TableFormulaTests {
150186 try compare(Self.lisp, fallbacksAllowed: false)
151187 }
152188
153 func compare(_ tables: [String], fallbacksAllowed: Bool) throws {
189 /// With `headerFallbacksAllowed`, a formula Calc would leave symbolic over a header's
190 /// text may go to Emacs even when other fallbacks aren't allowed.
191 func compare(_ tables: [String], fallbacksAllowed: Bool, headerFallbacksAllowed: Bool = true) throws {
154192 var cases: [EmacsOracle.Case] = []
155193 var ours: [(text: String, caret: Int, failure: String?)] = []
156194 for text in tables {
@@ -170,10 +208,8 @@ struct TableFormulaTests {
170208 for (i, (mine, theirs)) in zip(ours, emacs).enumerated() {
171209 if let failure = mine.failure, failure.hasPrefix("external:") {
172210 fallbacks += 1
173 // Calc keeps text as symbols, which goes to Emacs.
174 #expect(fallbacksAllowed || failure.contains("non-numeric field"), "\(failure) in\n\(cases[i].text)")
175 // Emacs gives symbolic results for text and division by zero.
176 #expect(failure.contains("non-numeric field") || failure.contains("division by zero"), "\(failure)")
211 let header = failure.contains("symbolic") || failure.contains("of a formula")
212 #expect(fallbacksAllowed || (headerFallbacksAllowed && header), "\(failure) in\n\(cases[i].text)")
177213 continue
178214 }
179215 let expected = (theirs.text, EmacsOracle.offset(theirs.point, in: theirs.text), theirs.error.isEmpty ? nil : theirs.error)
Tests/OrgProgramsTests/ProgramsTests.swift +4 −4
@@ -23,7 +23,7 @@ struct EmacsFallbackTests {
2323 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
2424 func recalculatesTablesNativeCodeCannot() async throws {
2525 let notes = try Folder()
26 let file = try notes.write("t.org", "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | |\n| y | 2 | |\n#+TBLFM: $3=$2*2\n")
26 let file = try notes.write("t.org", "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | |\n| y | 2 | |\n#+TBLFM: $3=sqrt($2)\n")
2727 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
2828 session.open(file.path)
2929 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil)
@@ -31,17 +31,17 @@ struct EmacsFallbackTests {
3131 Issue.record("\(step)")
3232 return
3333 }
34 #expect(reason == "non-numeric field a")
34 #expect(reason == "function sqrt of a formula")
3535 #expect(!lisp)
3636 let message = await session.recalculateInEmacs(table: table, point: point, form: form)
3737 #expect(message == "Recalculated in Emacs")
38 #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | 2 a |\n| y | 2 | 4 |\n#+TBLFM: $3=$2*2\n")
38 #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-----------|\n| x | a | sqrt(a) |\n| y | 2 | 1.4142136 |\n#+TBLFM: $3=sqrt($2)\n")
3939 }
4040
4141 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
4242 func cancelingARecalculationLeavesTheTable() async throws {
4343 let notes = try Folder()
44 let text = "| n | twice |\n|---+-------|\n| a | |\n#+TBLFM: $2=$1*2\n"
44 let text = "| n | twice |\n|---+-------|\n| a | |\n#+TBLFM: $2=sqrt($1)\n"
4545 let file = try notes.write("t.org", text)
4646 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
4747 session.open(file.path)
docs/manual/guide/10-tables.org +36 −13
@@ -231,9 +231,13 @@ In a Calc formula a single field becomes a number in parentheses, and a range be
231231a vector such as =[1,2,3]=. Without the =E= flag, empty fields count as 0 on their own
232232and are left out of ranges.
233233
234Fields in a Calc formula must hold numbers, fractions such as =1:30=, timestamps or
235=nan=, unless the =N= flag reads every field as a number. A reference to a field with
236other text needs Emacs, because Calc would treat the text as a symbol.
234A field's text goes into the formula as it is, so a field holding text such as =N/A= or
235=TBD= becomes Calc variables and the result is a formula: =$1+5= with =N/A= in =$1=
236gives =N / A + 5=. The =N= flag reads every field as a number instead, with text as 0.
237A field such as =21.11.2026= or =192.168.1.1=, with more than one decimal point, is
238=#ERROR=, as Calc can't read it as a number. A range whose only non-empty field holds
239text with a space, such as =5 kg=, needs Emacs: Calc reads a vector without commas as
240elements separated by spaces.
237241
238242** Names, parameters and constants
239243
@@ -321,7 +325,7 @@ side if it is nonzero, else the right side):
321325| ~==~, ~!=~, =<=, =>=, ~<=~, ~>=~ | Comparisons, giving 1 or 0. They can't be chained. |
322326| =+=, =-= | Addition and subtraction. |
323327| =/=, =%=, =\= | Division, modulo (sign of the divisor), integer division rounding down. |
324| =*= | Multiplication. Values side by side also multiply: =2 3=, =2 (x)=. |
328| =*= | Multiplication. Values side by side also multiply: =2 3=, =2 (x)=. It groups from the right: =a * b c= is =a * (b c)=. |
325329| unary =-= | Negation. |
326330| =^= | Power. |
327331| =!=, =!!= after a value | Factorial, double factorial. |
@@ -372,8 +376,21 @@ Functions:
372376| =land=, =lor=, =lnot= | As =&&=, ~||~ and =!=. |
373377
374378The statistics functions take any number of vectors and numbers, as in
375=vmean($2..$4, $6)=. Other Calc functions, variables such as =pi= or =e= (which Calc
376keeps as symbols), symbolic results, complex results and division by zero need Emacs.
379=vmean($2..$4, $6)=.
380
381Calc leaves what it can't reduce to a number as a formula, and so does orgstar for
382sums, differences, products, quotients and powers:
383
384- A name is a variable: =2*x + x= is =3 x=. Calc's constants =pi=, =e=, =phi= and =gamma=
385 stay names too: =$1^2*pi= gives =9 pi= for 3.
386- Division by zero stays unevaluated: =$1/$2= with 6 and an empty field gives =6/0=,
387 and =x/0 + 1= gives =x / 0 + 1=.
388- =inf=, =-inf= and =uinf= (infinity of unknown sign) follow Calc's rules: =inf - inf= is
389 =nan=, =1/inf= is =0=, =2^inf= is =inf=.
390- =vsum=, =vprod=, =vmean= and =vcount= take vectors holding such formulas.
391
392Other functions of a formula, comparisons and conditions on one, and complex results
393need Emacs.
377394
378395** Mode flags and formats
379396
@@ -389,6 +406,7 @@ After the formula, a =;= starts its flags, as in ~$3=$1/$2;%.2f~ or ~$4=$1*2;f2~
389406| =D=, =R= | Angles in degrees (the default) or radians. |
390407| =F= | Prefer fractions: =1/3= stays =1:3=. |
391408| =N= | Treat every field as a number; text counts as 0. |
409| =S= | Symbolic: results that aren't exact stay as formulas, such as =sqrt(2)=. |
392410| =E= | Keep empty fields: in ranges they stay in, and count as =nan= in Calc. |
393411| =L= | Literal: in Lisp formulas, insert fields as they are written. |
394412| =T= | Durations: read =H:MM= and =H:MM:SS= fields as times, show the result as =HH:MM:SS=. |
@@ -399,7 +417,13 @@ Above =p14=, functions worked out from decimal approximations (=sqrt= of a non-s
399417=exp=, =ln=, =log=, non-integer powers, trigonometric and hyperbolic functions) may need
400418Emacs, and above =p16= so may the statistics functions and powers of decimal numbers.
401419
402The flags =S= (symbolic) and =u= need Emacs. Any other text after the flags is a
420With =S=, the functions that may give an inexact result (=sqrt=, =exp=, =ln=, =log=,
421=log10=, =pow=, =nroot=, =hypot=, the inverse trigonometric and hyperbolic functions,
422=fact=, =dfact=, the standard deviations, =vgmean=, =vhmean=, the covariances and
423=agmean=), powers other than integer powers, and =sin=, =cos= and =tan= in radians need
424Emacs.
425
426The flag =u= needs Emacs. Any other text after the flags is a
403427=format= string applied to the result, such as =%.2f= or =%d=; =format= supports
404428=%s=, =%S=, =%d=, =%o=, =%x=, =%X=, =%c=, =%e=, =%f= and =%g=.
405429
@@ -621,12 +645,11 @@ time, which gives the same result unless a formula depends on its own value.
621645When a formula uses something the native evaluator doesn't have, the command reports
622646what it was and the Mac recalculates the table in Emacs instead. This happens for:
623647
624- references to fields holding text in a Calc formula, and symbolic results;
625- Calc functions and variables not listed above, intervals such as =[1..5]=,
626 precisions beyond those given under /Mode flags and formats/, and the =S= and =u=
627 flags;
628- division by zero, complex results, vector results, and numbers too large for
629 64-bit integers;
648- symbolic results beyond those under /Calc expressions/, such as a function of a field
649 holding text;
650- Calc functions not listed above, intervals such as =[1..5]=, precisions beyond those
651 given under /Mode flags and formats/, parts of the =S= flag, and the =u= flag;
652- complex results, vector results, and numbers too large for 64-bit integers;
630653- Lisp functions not listed above.
631654
632655The echo area shows =Recalculating in Emacs (reason)…=, then =Recalculated in Emacs=.
l10n/Localizable.xcstrings +68
@@ -35556,6 +35556,74 @@
3555635556 }
3555735557 }
3555835558 },
35559 "symbolic arithmetic": {
35560 "localizations": {
35561 "de": {
35562 "stringUnit": {
35563 "state": "translated",
35564 "value": "symbolische Arithmetik"
35565 }
35566 },
35567 "es": {
35568 "stringUnit": {
35569 "state": "translated",
35570 "value": "aritmética simbólica"
35571 }
35572 },
35573 "fr": {
35574 "stringUnit": {
35575 "state": "translated",
35576 "value": "arithmétique symbolique"
35577 }
35578 },
35579 "ja": {
35580 "stringUnit": {
35581 "state": "translated",
35582 "value": "記号演算"
35583 }
35584 },
35585 "pt-BR": {
35586 "stringUnit": {
35587 "state": "translated",
35588 "value": "aritmética simbólica"
35589 }
35590 }
35591 }
35592 },
35593 "symbolic mode": {
35594 "localizations": {
35595 "de": {
35596 "stringUnit": {
35597 "state": "translated",
35598 "value": "symbolischer Modus"
35599 }
35600 },
35601 "es": {
35602 "stringUnit": {
35603 "state": "translated",
35604 "value": "modo simbólico"
35605 }
35606 },
35607 "fr": {
35608 "stringUnit": {
35609 "state": "translated",
35610 "value": "mode symbolique"
35611 }
35612 },
35613 "ja": {
35614 "stringUnit": {
35615 "state": "translated",
35616 "value": "記号モード"
35617 }
35618 },
35619 "pt-BR": {
35620 "stringUnit": {
35621 "state": "translated",
35622 "value": "modo simbólico"
35623 }
35624 }
35625 }
35626 },
3555935627 "table position": {
3556035628 "localizations": {
3556135629 "de": {