Commit fb3b538d8b
Verified · cmc
Layout: unified · split
Sources/OrgApp/TableReason.swift +2 −1
| @@ -17,7 +17,6 @@ public enum TableReason { | ||
| 17 | 17 | func value(_ prefix: String) -> String? { reason.hasPrefix(prefix) ? String(reason.dropFirst(prefix.count)) : nil } |
| 18 | 18 | if let name = value("function ") { return String(localized: "function \(name)", comment: "Why a table needs Emacs: a Calc function") } |
| 19 | 19 | 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") } | |
| 21 | 20 | if let number = value("number size ") { return String(localized: "number size \(number)", comment: "Why a table needs Emacs: a number too large") } |
| 22 | 21 | if let flag = value("format flag ") { return String(localized: "format flag \(flag)", comment: "Why a table needs Emacs: a format specifier flag") } |
| 23 | 22 | return nil |
| @@ -118,6 +117,8 @@ public enum TableReason { | ||
| 118 | 117 | case "reference outside table": return String(localized: "reference outside table", comment: comment) |
| 119 | 118 | case "remote table name from a range": return String(localized: "remote table name from a range", comment: comment) |
| 120 | 119 | 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) | |
| 121 | 122 | case "table position": return String(localized: "table position", comment: comment) |
| 122 | 123 | case "variance of one value": return String(localized: "variance of one value", comment: comment) |
| 123 | 124 | case "vector argument": return String(localized: "vector argument", comment: comment) |
Sources/OrgCore/Compute/Calc.swift +99 −15
| @@ -30,6 +30,8 @@ public enum Calc { | ||
| 30 | 30 | case nan |
| 31 | 31 | /// An exact fraction, reduced, the denominator above 1 (`calc-prefer-frac`). |
| 32 | 32 | case frac(Int, Int) |
| 33 | /// A formula Calc leaves unevaluated, with variables or a quotient by zero. | |
| 34 | case symbolic(Term) | |
| 33 | 35 | } |
| 34 | 36 | |
| 35 | 37 | public enum FloatFormat: Equatable, Sendable { |
| @@ -42,6 +44,8 @@ public enum Calc { | ||
| 42 | 44 | public var degrees = true |
| 43 | 45 | /// `calc-prefer-frac`: dividing integers gives a fraction. |
| 44 | 46 | public var preferFractions = false |
| 47 | /// `calc-symbolic-mode`: functions whose result isn't exact stay unevaluated. | |
| 48 | public var symbolic = false | |
| 45 | 49 | /// The clock `now()` reads; nil is the system clock. |
| 46 | 50 | public var now: Date? |
| 47 | 51 | /// The local time zone, for `now()`, `julian` and `unixtime`. |
| @@ -55,16 +59,23 @@ public enum Calc { | ||
| 55 | 59 | // Mantissas live in an Int, so 18 digits at most. |
| 56 | 60 | guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") } |
| 57 | 61 | 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") | |
| 62 | try $fractions.withValue(modes.preferFractions) { | |
| 63 | try $symbolicMode.withValue(modes.symbolic) { | |
| 64 | var parser = Parser(expression) | |
| 65 | let tree = try parser.parse() | |
| 66 | let value = try Evaluator(modes: modes).eval(tree) | |
| 67 | if numeric { | |
| 68 | switch value { | |
| 69 | case .int, .float, .frac: break | |
| 70 | // Calc explains a division by zero or a power it left alone. | |
| 71 | case .symbolic(let t) where t.contains(where: { ["/", "^"].contains($0) }): | |
| 72 | throw Unsupported("symbolic arithmetic") | |
| 73 | default: throw Failure("Number expected") | |
| 74 | } | |
| 75 | } | |
| 76 | return try format(value, modes.format) | |
| 65 | 77 | } |
| 66 | 78 | } |
| 67 | return try format(value, modes.format) | |
| 68 | 79 | } |
| 69 | 80 | } |
| 70 | 81 | |
| @@ -78,6 +89,7 @@ public enum Calc { | ||
| 78 | 89 | let v = try $precision.withValue(precision + n, operation: body) |
| 79 | 90 | if case .float(let m, let e) = v { return try makeFloat(Int128(m), e) } |
| 80 | 91 | if case .date(.float(let m, let e)) = v { return .date(try makeFloat(Int128(m), e)) } |
| 92 | if case .symbolic(let t) = v { return value(try Symbolic.normalize(t)) } | |
| 81 | 93 | return v |
| 82 | 94 | } |
| 83 | 95 | |
| @@ -216,6 +228,7 @@ public enum Calc { | ||
| 216 | 228 | case .frac(let n, let d): return try parts(try divide(.int(n), .int(d))) |
| 217 | 229 | case .vector: throw Unsupported("vector arithmetic") |
| 218 | 230 | case .date, .nan: throw Unsupported("date arithmetic") |
| 231 | case .symbolic: throw Unsupported("symbolic arithmetic") | |
| 219 | 232 | } |
| 220 | 233 | } |
| 221 | 234 | |
| @@ -257,6 +270,7 @@ public enum Calc { | ||
| 257 | 270 | case .frac(let n, let d): return Double(n) / Double(d) |
| 258 | 271 | case .vector: throw Unsupported("vector arithmetic") |
| 259 | 272 | case .date, .nan: throw Unsupported("date arithmetic") |
| 273 | case .symbolic: throw Unsupported("symbolic arithmetic") | |
| 260 | 274 | } |
| 261 | 275 | } |
| 262 | 276 | |
| @@ -273,7 +287,12 @@ public enum Calc { | ||
| 273 | 287 | return try makeFloat(mantissa, exponent - 16) |
| 274 | 288 | } |
| 275 | 289 | |
| 290 | static func isSymbolic(_ vs: Value...) -> Bool { | |
| 291 | vs.contains { if case .symbolic = $0 { true } else { false } } | |
| 292 | } | |
| 293 | ||
| 276 | 294 | static func add(_ a: Value, _ b: Value) throws -> Value { |
| 295 | if isSymbolic(a, b) { return value(try Symbolic.add(try term(a), try term(b))) } | |
| 277 | 296 | switch (a, b) { |
| 278 | 297 | case (.nan, .vector), (.vector, .nan): throw Unsupported("vector arithmetic") |
| 279 | 298 | case (.nan, _), (_, .nan): return .nan |
| @@ -310,6 +329,7 @@ public enum Calc { | ||
| 310 | 329 | |
| 311 | 330 | static func negate(_ a: Value) throws -> Value { |
| 312 | 331 | switch a { |
| 332 | case .symbolic(let t): return value(try Symbolic.neg(t)) | |
| 313 | 333 | case .int(let i): |
| 314 | 334 | guard i != .min else { throw Unsupported("integer size") } |
| 315 | 335 | return .int(-i) |
| @@ -333,6 +353,7 @@ public enum Calc { | ||
| 333 | 353 | } |
| 334 | 354 | |
| 335 | 355 | static func multiply(_ a: Value, _ b: Value) throws -> Value { |
| 356 | if isSymbolic(a, b) { return value(try Symbolic.mul(try term(a), try term(b))) } | |
| 336 | 357 | if isNaN(a, b) { return .nan } |
| 337 | 358 | if case .int(let x) = a, case .int(let y) = b { |
| 338 | 359 | let (product, overflow) = x.multipliedReportingOverflow(by: y) |
| @@ -352,6 +373,10 @@ public enum Calc { | ||
| 352 | 373 | } |
| 353 | 374 | |
| 354 | 375 | static func divide(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value { |
| 376 | // `math-div-by-zero` leaves the quotient alone. | |
| 377 | if isSymbolic(a, b) || (isZero(b) && (try? sign(a)) != nil) { | |
| 378 | return try $fractions.withValue(fractions) { value(try Symbolic.div(try term(a), try term(b))) } | |
| 379 | } | |
| 355 | 380 | if isNaN(a, b) { return .nan } |
| 356 | 381 | if fractions || { if case .frac = a { return true }; if case .frac = b { return true }; return false }(), |
| 357 | 382 | let (n1, d1) = rational(a), let (n2, d2) = rational(b) { |
| @@ -391,15 +416,17 @@ public enum Calc { | ||
| 391 | 416 | |
| 392 | 417 | /// `math-pow` of real numbers. |
| 393 | 418 | static func power(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value { |
| 419 | // In symbolic mode Calc keeps a power that isn't exact, which isn't reproduced. | |
| 420 | if symbolicMode, !isInteger(b) { throw Unsupported("symbolic mode") } | |
| 421 | if isSymbolic(a, b) { return try $fractions.withValue(fractions) { value(try Symbolic.pow(try term(a), try term(b))) } } | |
| 394 | 422 | if isNaN(a, b) { return .nan } |
| 395 | 423 | _ = (try sign(a), try sign(b)) |
| 396 | 424 | var floatB = false |
| 397 | 425 | if case .float = b { floatB = true } |
| 398 | 426 | if isZero(a) { |
| 399 | // `math-pow-of-zero`. | |
| 427 | // `math-pow-of-zero`: an indeterminate form, or a division by zero, stays alone. | |
| 400 | 428 | 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") } | |
| 429 | guard try sign(b) > 0 else { throw Rejected() } | |
| 403 | 430 | return floatB ? try float(a) : a |
| 404 | 431 | } |
| 405 | 432 | if a == .int(1) || b == .int(1) || a == .float(1, 0) || b == .float(1, 0) { return a } |
| @@ -713,6 +740,7 @@ public enum Calc { | ||
| 713 | 740 | case .int(let i): return String(i) |
| 714 | 741 | case .frac(let n, let d): return "\(n):\(d)" |
| 715 | 742 | case .vector: throw Unsupported("vector result") |
| 743 | case .symbolic(let t): return try Symbolic.format(t, floatFormat) | |
| 716 | 744 | case .nan: return "nan" |
| 717 | 745 | case .date(let d): return "<" + (try formatDate(d)) + ">" |
| 718 | 746 | case .float(let m, _) where m < 0: |
| @@ -900,11 +928,14 @@ public enum Calc { | ||
| 900 | 928 | case unary(Character, Node) |
| 901 | 929 | case binary(Character, Node, Node) |
| 902 | 930 | case call(String, [Node]) |
| 931 | case variable(String) | |
| 903 | 932 | } |
| 904 | 933 | |
| 905 | 934 | struct Parser { |
| 906 | 935 | let chars: [Character] |
| 907 | 936 | var i = 0 |
| 937 | /// Inside `[...]`, where Calc reads `x -1` as two elements. | |
| 938 | var inVector = false | |
| 908 | 939 | |
| 909 | 940 | init(_ s: String) { chars = Array(s) } |
| 910 | 941 | |
| @@ -968,6 +999,9 @@ public enum Calc { | ||
| 968 | 999 | mutating func sum() throws -> Node { |
| 969 | 1000 | var left = try quotient() |
| 970 | 1001 | while let c = peek(), c == "+" || c == "-" { |
| 1002 | if inVector, i > 0, chars[i - 1] == " " || chars[i - 1] == "\t", i + 1 < chars.count, chars[i + 1] != " ", chars[i + 1] != "\t" { | |
| 1003 | throw Unsupported("formula syntax") | |
| 1004 | } | |
| 971 | 1005 | i += 1 |
| 972 | 1006 | left = .binary(c, left, try quotient()) |
| 973 | 1007 | } |
| @@ -1052,13 +1086,19 @@ public enum Calc { | ||
| 1052 | 1086 | guard let c = peek() else { throw Unsupported("formula syntax") } |
| 1053 | 1087 | if c == "(" { |
| 1054 | 1088 | i += 1 |
| 1089 | let outer = inVector | |
| 1090 | inVector = false | |
| 1055 | 1091 | let inner = try or() |
| 1092 | inVector = outer | |
| 1056 | 1093 | guard peek() == ")" else { throw Unsupported("formula syntax") } |
| 1057 | 1094 | i += 1 |
| 1058 | 1095 | return inner |
| 1059 | 1096 | } |
| 1060 | 1097 | if c == "[" { |
| 1061 | 1098 | i += 1 |
| 1099 | let outer = inVector | |
| 1100 | inVector = true | |
| 1101 | defer { inVector = outer } | |
| 1062 | 1102 | var items: [Node] = [] |
| 1063 | 1103 | if peek() != "]" { |
| 1064 | 1104 | items.append(try or()) |
| @@ -1086,7 +1126,11 @@ public enum Calc { | ||
| 1086 | 1126 | } |
| 1087 | 1127 | guard peek() == "(" else { |
| 1088 | 1128 | if name == "nan" { return .number(.nan) } |
| 1089 | throw Unsupported("variable \(name)") | |
| 1129 | // Calc's names are letters and digits; `_` is a subscript, and `'` and `#` | |
| 1130 | // belong to the name. | |
| 1131 | guard name.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber) }), !reserved.contains(name), | |
| 1132 | i >= chars.count || !"'#".contains(chars[i]) else { throw Unsupported("variable \(name)") } | |
| 1133 | return .variable(name) | |
| 1090 | 1134 | } |
| 1091 | 1135 | i += 1 |
| 1092 | 1136 | var args: [Node] = [] |
| @@ -1190,11 +1234,51 @@ public enum Calc { | ||
| 1190 | 1234 | case .number(let v): return v |
| 1191 | 1235 | case .vector(let items): return .vector(try items.map(eval)) |
| 1192 | 1236 | case .unary("!", let operand): return .int(try truth(try eval(operand)) ? 0 : 1) |
| 1193 | case .unary(_, let operand): return try negate(try eval(operand)) | |
| 1237 | case .unary(_, let operand): | |
| 1238 | let a = try eval(operand) | |
| 1239 | do { return try negate(a) } catch is Rejected { return .symbolic(.op("neg", [try term(a)])) } | |
| 1194 | 1240 | case .binary(let op, let l, let r): |
| 1195 | return try binary(op, try eval(l), try eval(r)) | |
| 1241 | let (a, b) = (try eval(l), try eval(r)) | |
| 1242 | do { | |
| 1243 | return try binary(op, a, b) | |
| 1244 | } catch is Rejected { | |
| 1245 | // `math-normalize` keeps the operation, its arguments evaluated. | |
| 1246 | guard let name = ["+": "+", "-": "-", "*": "*", "/": "/", "^": "^"][op] else { throw Unsupported("division by zero") } | |
| 1247 | return .symbolic(.op(name, [try term(a), try term(b)])) | |
| 1248 | } | |
| 1196 | 1249 | case .call(let name, let args): |
| 1197 | return try call(name, try args.map(eval)) | |
| 1250 | let values = try args.map(eval) | |
| 1251 | // In symbolic mode Calc keeps these unevaluated when the result isn't exact, | |
| 1252 | // which isn't reproduced. | |
| 1253 | if modes.symbolic, Self.inexact.contains(name) || (!modes.degrees && ["sin", "cos", "tan"].contains(name)) { | |
| 1254 | throw Unsupported("function \(name) in symbolic mode") | |
| 1255 | } | |
| 1256 | if values.contains(where: Self.hasSymbol) { | |
| 1257 | // Calc leaves most functions of a formula alone, and simplifies some. | |
| 1258 | guard ["vsum", "vprod", "vmean", "vcount"].contains(name), | |
| 1259 | values.allSatisfy({ if case .vector = $0 { true } else { !Self.hasSymbol($0) } }) else { | |
| 1260 | throw Unsupported("function \(name) of a formula") | |
| 1261 | } | |
| 1262 | } | |
| 1263 | do { | |
| 1264 | return try call(name, values) | |
| 1265 | } catch is Rejected { | |
| 1266 | throw Unsupported("division by zero") | |
| 1267 | } | |
| 1268 | case .variable(let name): | |
| 1269 | return .symbolic(.variable(name)) | |
| 1270 | } | |
| 1271 | } | |
| 1272 | ||
| 1273 | static let inexact: Set<String> = ["sqrt", "exp", "ln", "log10", "log", "vsdev", "vpsdev", "vgmean", "vhmean", "vcorr", | |
| 1274 | "vcov", "vpcov", "agmean", "pow", "nroot", "hypot", "sinh", "cosh", "tanh", "arcsinh", | |
| 1275 | "arccosh", "arctanh", "arcsin", "arccos", "arctan", "arctan2", "fact", "dfact"] | |
| 1276 | ||
| 1277 | static func hasSymbol(_ v: Value) -> Bool { | |
| 1278 | switch v { | |
| 1279 | case .symbolic: true | |
| 1280 | case .vector(let items): items.contains(where: hasSymbol) | |
| 1281 | default: false | |
| 1198 | 1282 | } |
| 1199 | 1283 | } |
| 1200 | 1284 | |
Sources/OrgCore/Compute/CalcSymbolic.swift added +664
| @@ -0,0 +1,664 @@ | ||
| 1 | import 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`. | |
| 9 | extension 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` and `math-known-integerp`: only numbers are known to be | |
| 224 | /// integers, as nothing is declared. | |
| 225 | static func knownNumInteger(_ t: Term) throws -> Bool { | |
| 226 | if let v = number(t) { return isWhole(v) } | |
| 227 | guard !containsConstant(t) else { throw Unsupported("symbolic arithmetic") } | |
| 228 | return false | |
| 229 | } | |
| 230 | ||
| 231 | // MARK: Arithmetic | |
| 232 | ||
| 233 | /// `math-normalize`: the operations applied again from the leaves, floats rounded | |
| 234 | /// to the precision. | |
| 235 | static func normalize(_ t: Term) throws -> Term { | |
| 236 | switch t { | |
| 237 | case .number(.float(let m, let e)): return .number(try makeFloat(Int128(m), e)) | |
| 238 | case .number, .variable: return t | |
| 239 | case .op(let f, let args): | |
| 240 | let args = try args.map(normalize) | |
| 241 | do { return try apply(f, args) } catch is Rejected { return .op(f, args) } | |
| 242 | } | |
| 243 | } | |
| 244 | ||
| 245 | static func apply(_ f: String, _ args: [Term]) throws -> Term { | |
| 246 | switch (f, args.count) { | |
| 247 | case ("+", 2): return try add(args[0], args[1]) | |
| 248 | case ("-", 2): return try sub(args[0], args[1]) | |
| 249 | case ("*", 2): return try mul(args[0], args[1]) | |
| 250 | case ("/", 2): return try div(args[0], args[1]) | |
| 251 | case ("^", 2): return try pow(args[0], args[1]) | |
| 252 | case ("neg", 1): return try neg(args[0]) | |
| 253 | default: throw Unsupported("function \(f)") | |
| 254 | } | |
| 255 | } | |
| 256 | ||
| 257 | static func numeric(_ a: Term, _ b: Term, _ op: (Value, Value) throws -> Value) throws -> Term? { | |
| 258 | guard let x = number(a), let y = number(b) else { return nil } | |
| 259 | return try term(try op(x, y)) | |
| 260 | } | |
| 261 | ||
| 262 | /// `math-float` of a rational number. | |
| 263 | static func float(_ t: Term) throws -> Term { | |
| 264 | guard let v = number(t) else { return t } | |
| 265 | return .number(try Calc.float(v)) | |
| 266 | } | |
| 267 | ||
| 268 | /// `math-neg`. | |
| 269 | static func neg(_ a: Term) throws -> Term { | |
| 270 | if let v = number(a) { return .number(try negate(v)) } | |
| 271 | func okayNeg(_ t: Term) -> Bool { looksNeg(t) || head(t) == "-" } | |
| 272 | let (a1, a2) = (arg(a, 1), arg(a, 2)) | |
| 273 | switch head(a) { | |
| 274 | case "+": return try sub(try neg(a1), a2) | |
| 275 | case "-": return try sub(a2, a1) | |
| 276 | case "*", "/": | |
| 277 | let f = head(a)! | |
| 278 | if okayNeg(a1) { return .op(f, [try neg(a1), a2]) } | |
| 279 | if okayNeg(a2) { return .op(f, [a1, try neg(a2)]) } | |
| 280 | if objectp(a1) || (head(a1) == "*" && objectp(arg(a1, 1))) { return .op(f, [try neg(a1), a2]) } | |
| 281 | if f == "/", objectp(a2) || (head(a2) == "*" && objectp(arg(a2, 1))) { return .op(f, [a1, try neg(a2)]) } | |
| 282 | case "neg": return a1 | |
| 283 | default: if a == uinf || a == nan { return a } | |
| 284 | } | |
| 285 | return .op("neg", [a]) | |
| 286 | } | |
| 287 | ||
| 288 | /// `math-add`. | |
| 289 | static func add(_ a: Term, _ b: Term) throws -> Term { | |
| 290 | if let sum = try numeric(a, b, { try Calc.add($0, $1) }) { return sum } | |
| 291 | if zerop(a) { return b } | |
| 292 | if zerop(b) { return a } | |
| 293 | return try addFancy(a, b) | |
| 294 | } | |
| 295 | ||
| 296 | /// `math-sub`. | |
| 297 | static func sub(_ a: Term, _ b: Term) throws -> Term { try add(a, try neg(b)) } | |
| 298 | ||
| 299 | /// `math-add-symb-fancy`. | |
| 300 | static func addFancy(_ a: Term, _ b: Term) throws -> Term { | |
| 301 | switch head(b) { | |
| 302 | case "+": return try add(try add(a, arg(b, 1)), arg(b, 2)) | |
| 303 | case "-": return try sub(try add(a, arg(b, 1)), arg(b, 2)) | |
| 304 | case "neg" where head(arg(b, 1)) == "+": | |
| 305 | return try sub(try sub(a, arg(arg(b, 1), 1)), arg(arg(b, 1), 2)) | |
| 306 | default: break | |
| 307 | } | |
| 308 | if let result = try combineSums(a, b) { return result } | |
| 309 | if looksNeg(b, loose: false) { return .op("-", [a, try neg(b)]) } | |
| 310 | if looksNeg(a, loose: false) { return .op("-", [b, try neg(a)]) } | |
| 311 | return .op("+", [a, b]) | |
| 312 | } | |
| 313 | ||
| 314 | /// The `cond` in `math-add-symb-fancy` that handles infinities and like terms. | |
| 315 | static func combineSums(_ a: Term, _ b: Term) throws -> Term? { | |
| 316 | if let infA = infinitep(a) { | |
| 317 | guard let infB = infinitep(b) else { return a } | |
| 318 | if [uinf, nan].contains(infA) || [uinf, nan].contains(infB) { return nan } | |
| 319 | let dirA = try infiniteDirection(a, infA) | |
| 320 | let dirB = try infiniteDirection(b, infB) | |
| 321 | guard let x = number(dirA), let y = number(dirB) else { return nil } | |
| 322 | return try compare(x, y) == 0 ? a : nan | |
| 323 | } | |
| 324 | if infinitep(b) != nil { return b } | |
| 325 | if head(a) == "+" { | |
| 326 | return try combineSum(arg(a, 2), b, negA: false, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) } | |
| 327 | } | |
| 328 | if head(a) == "-" { | |
| 329 | return try combineSum(arg(a, 2), b, negA: true, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) } | |
| 330 | } | |
| 331 | if objectp(a), objectp(b) { return nil } | |
| 332 | return try combineSum(a, b, negA: false, negB: false, scalarOkay: false) | |
| 333 | } | |
| 334 | ||
| 335 | /// `math-infinite-dir`: the formula with its infinity replaced by 1. | |
| 336 | static func infiniteDirection(_ a: Term, _ infinity: Term) throws -> Term { | |
| 337 | func substitute(_ t: Term) -> Term { | |
| 338 | if t == infinity { return .number(.int(1)) } | |
| 339 | if case .op(let f, let args) = t { return .op(f, args.map(substitute)) } | |
| 340 | return t | |
| 341 | } | |
| 342 | return try normalize(substitute(a)) | |
| 343 | } | |
| 344 | ||
| 345 | /// `math-combine-sum`: two terms that are multiples of the same thing, added. | |
| 346 | static func combineSum(_ a: Term, _ b: Term, negA: Bool, negB: Bool, scalarOkay: Bool) throws -> Term? { | |
| 347 | if scalarOkay, objectp(a), objectp(b) { | |
| 348 | return try add(negA ? try neg(a) : a, negB ? try neg(b) : b) | |
| 349 | } | |
| 350 | /// The coefficient and the rest; a nil coefficient is Calc's `(frac 1 0)`. | |
| 351 | func split(_ t: Term) throws -> (Term?, Term) { | |
| 352 | switch head(t) { | |
| 353 | case "*" where objectp(arg(t, 1)): return (arg(t, 1), arg(t, 2)) | |
| 354 | case "/" where objectp(arg(t, 2)): | |
| 355 | let d = arg(t, 2) | |
| 356 | if case .number(.int(let n)) = d { return (n == 0 ? nil : .number(try fraction(1, n)), arg(t, 1)) } | |
| 357 | return (try div(.number(.int(1)), d), arg(t, 1)) | |
| 358 | case "neg": return (.number(.int(-1)), arg(t, 1)) | |
| 359 | default: return (.number(.int(1)), t) | |
| 360 | } | |
| 361 | } | |
| 362 | let (multA, restA) = try split(a) | |
| 363 | let (multB, restB) = try split(b) | |
| 364 | guard restA == restB else { return nil } | |
| 365 | // `math-make-frac` of two such coefficients divides by zero. | |
| 366 | if multA == nil, multB == nil { throw Rejected() } | |
| 367 | guard var ma = multA, var mb = multB else { throw Unsupported("division by zero") } | |
| 368 | if negA { ma = try neg(ma) } | |
| 369 | if negB { mb = try neg(mb) } | |
| 370 | return try mul(try add(ma, mb), restA) | |
| 371 | } | |
| 372 | ||
| 373 | /// `math-mul`. | |
| 374 | static func mul(_ a: Term, _ b: Term) throws -> Term { | |
| 375 | if let product = try numeric(a, b, { try multiply($0, $1) }) { return product } | |
| 376 | if zerop(a) { return try mulZero(a, b) } | |
| 377 | if zerop(b) { return try mulZero(b, a) } | |
| 378 | return try mulFancy(a, b) | |
| 379 | } | |
| 380 | ||
| 381 | /// `math-mul-zero`, `a` zero and `b` a formula. | |
| 382 | static func mulZero(_ a: Term, _ b: Term) throws -> Term { | |
| 383 | if infinitep(b) != nil { return nan } | |
| 384 | return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0)) | |
| 385 | } | |
| 386 | ||
| 387 | /// `math-mul-symb-fancy`. | |
| 388 | static func mulFancy(_ a: Term, _ b: Term) throws -> Term { | |
| 389 | if equalInt(a, 1) { return b } | |
| 390 | if equalInt(a, -1) { return try neg(b) } | |
| 391 | if objectp(b), !objectp(a) { return try mul(b, a) } | |
| 392 | if head(a) == "neg" { return try neg(try mul(arg(a, 1), b)) } | |
| 393 | if head(b) == "neg" { return try neg(try mul(a, arg(b, 1))) } | |
| 394 | if head(a) == "*" { return try mul(arg(a, 1), try mul(arg(a, 2), b)) } | |
| 395 | let negativePower = { (t: Term) in head(t) == "^" && looksNeg(arg(t, 2), loose: false) } | |
| 396 | if negativePower(a), !negativePower(b) { | |
| 397 | return try div(b, try normalize(.op("^", [arg(a, 1), try neg(arg(a, 2))]))) | |
| 398 | } | |
| 399 | if negativePower(b), !negativePower(a) { | |
| 400 | return try div(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))]))) | |
| 401 | } | |
| 402 | if head(a) == "/" { | |
| 403 | if let c = try combineProd(arg(a, 2), b, invA: true, invB: false, scalarOkay: true) { return try mul(arg(a, 1), c) } | |
| 404 | return try div(try mul(arg(a, 1), b), arg(a, 2)) | |
| 405 | } | |
| 406 | if head(b) == "/" { return try div(try mul(a, arg(b, 1)), arg(b, 2)) } | |
| 407 | if let f = head(b), f == "+" || f == "-", objectp(a), objectp(arg(b, 1)) || objectp(arg(b, 2)) { | |
| 408 | let (x, y) = (try mul(a, arg(b, 1)), try mul(a, arg(b, 2))) | |
| 409 | return f == "+" ? try add(x, y) : try sub(x, y) | |
| 410 | } | |
| 411 | if head(b) == "*", objectp(arg(b, 1)), !objectp(a) { return try mul(arg(b, 1), try mul(a, arg(b, 2))) } | |
| 412 | if looksNeg(b) || (head(b) == "-" && looksNeg(a)) { return try mul(try neg(a), try neg(b)) } | |
| 413 | if head(b) == "*" { | |
| 414 | if let c = try combineProd(a, arg(b, 1), invA: false, invB: false, scalarOkay: true) { return try mul(c, arg(b, 2)) } | |
| 415 | } else if let c = try combineProd(a, b, invA: false, invB: false, scalarOkay: false) { | |
| 416 | return c | |
| 417 | } | |
| 418 | for special in [nan, uinf] { | |
| 419 | if a == special { return a } | |
| 420 | if b == special { return b } | |
| 421 | } | |
| 422 | if b == inf { | |
| 423 | switch try signs(a) { | |
| 424 | case 4: return b | |
| 425 | case 1: return try neg(b) | |
| 426 | case 3, 6: throw Unsupported("symbolic arithmetic") | |
| 427 | default: break | |
| 428 | } | |
| 429 | } | |
| 430 | if a == inf { return try mul(b, a) } | |
| 431 | return .op("*", [a, b]) | |
| 432 | } | |
| 433 | ||
| 434 | /// `math-div`. | |
| 435 | static func div(_ a: Term, _ b: Term) throws -> Term { | |
| 436 | if zerop(b) { | |
| 437 | // `math-div-by-zero`. | |
| 438 | guard let infinity = infinitep(a) else { throw Rejected() } | |
| 439 | return infinity == nan ? a : uinf | |
| 440 | } | |
| 441 | if let quotient = try numeric(a, b, { try divide($0, $1, fractions: fractions) }) { return quotient } | |
| 442 | // `math-div-zero`. | |
| 443 | if zerop(a) { return b == nan ? b : a } | |
| 444 | return try divFancy(a, b) | |
| 445 | } | |
| 446 | ||
| 447 | /// `math-div-symb-fancy`. | |
| 448 | static func divFancy(_ a: Term, _ b: Term) throws -> Term { | |
| 449 | if equalInt(b, 1) { return a } | |
| 450 | if equalInt(b, -1) { return try neg(a) } | |
| 451 | if head(b) == "^", looksNeg(arg(b, 2), loose: false) || equalInt(a, 1) { | |
| 452 | return try mul(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))]))) | |
| 453 | } | |
| 454 | if head(a) == "neg" { return try neg(try div(arg(a, 1), b)) } | |
| 455 | if head(b) == "neg" { return try neg(try div(a, arg(b, 1))) } | |
| 456 | if head(a) == "/" { return try div(arg(a, 1), try mul(arg(a, 2), b)) } | |
| 457 | if head(b) == "/" { return try div(try mul(a, arg(b, 2)), arg(b, 1)) } | |
| 458 | if case .number(.frac(let n, let d)) = b { return try mul(.number(try fraction(d, n)), a) } | |
| 459 | if let f = head(a), f == "+" || f == "-", objectp(arg(a, 1)) || objectp(arg(a, 2)), objectp(b) { | |
| 460 | let (x, y) = (try div(arg(a, 1), b), try div(arg(a, 2), b)) | |
| 461 | return f == "+" ? try add(x, y) : try sub(x, y) | |
| 462 | } | |
| 463 | if head(a) == "-" || looksNeg(a), looksNeg(b) { return try div(try neg(a), try neg(b)) } | |
| 464 | if head(b) == "-", looksNeg(a) { return try div(try neg(a), try neg(b)) } | |
| 465 | if head(a) == "*" { | |
| 466 | if head(b) == "*" { | |
| 467 | if let c = try combineProd(arg(a, 1), arg(b, 1), invA: false, invB: true, scalarOkay: true) { | |
| 468 | return try div(try mul(c, arg(a, 2)), arg(b, 2)) | |
| 469 | } | |
| 470 | } else if let c = try combineProd(arg(a, 1), b, invA: false, invB: true, scalarOkay: true) { | |
| 471 | return try mul(c, arg(a, 2)) | |
| 472 | } | |
| 473 | } else if head(b) == "*" { | |
| 474 | if let c = try combineProd(a, arg(b, 1), invA: false, invB: true, scalarOkay: true) { return try div(c, arg(b, 2)) } | |
| 475 | } else if let c = try combineProd(a, b, invA: false, invB: true, scalarOkay: false) { | |
| 476 | return c | |
| 477 | } | |
| 478 | if infinitep(a) != nil { | |
| 479 | if infinitep(b) != nil { return nan } | |
| 480 | if a == nan || a == uinf { return a } | |
| 481 | if a == inf { | |
| 482 | if posp(b) { return a } | |
| 483 | if negp(b) { return try neg(a) } | |
| 484 | if objectp(b) { throw Unsupported("symbolic arithmetic") } | |
| 485 | } | |
| 486 | } | |
| 487 | if infinitep(b) != nil { | |
| 488 | if b == nan { return b } | |
| 489 | return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0)) | |
| 490 | } | |
| 491 | return .op("/", [a, b]) | |
| 492 | } | |
| 493 | ||
| 494 | /// `math-mul-or-div`. | |
| 495 | static func mulOrDiv(_ a: Term, _ b: Term, invA: Bool, invB: Bool) throws -> Term { | |
| 496 | if invA { return invB ? try div(try div(.number(.int(1)), a), b) : try div(b, a) } | |
| 497 | return invB ? try div(a, b) : try mul(a, b) | |
| 498 | } | |
| 499 | ||
| 500 | /// `math-combine-prod`: two factors that are powers of the same thing, multiplied. | |
| 501 | static func combineProd(_ a: Term, _ b: Term, invA: Bool, invB: Bool, scalarOkay: Bool) throws -> Term? { | |
| 502 | if (invA && zerop(a)) || (invB && zerop(b)) { return nil } | |
| 503 | if scalarOkay, objectp(a), objectp(b) { | |
| 504 | let r = try mulOrDiv(a, b, invA: invA, invB: invB) | |
| 505 | return objectp(r) ? r : nil | |
| 506 | } | |
| 507 | if head(a) == "^", invA, looksNeg(arg(a, 2)) { return try mul(try pow(arg(a, 1), try neg(arg(a, 2))), b) } | |
| 508 | if head(b) == "^", invB, looksNeg(arg(b, 2)) { return try mul(a, try pow(arg(b, 1), try neg(arg(b, 2)))) } | |
| 509 | func split(_ t: Term) throws -> (Term, Term) { | |
| 510 | var (base, power) = (t, Term.number(.int(1))) | |
| 511 | if head(t) == "^", objectp(arg(t, 2)) { (base, power) = (arg(t, 1), arg(t, 2)) } | |
| 512 | if head(t) == "sqrt" || head(t) == "exp" { throw Unsupported("symbolic arithmetic") } | |
| 513 | if case .number(.frac(let n, let d)) = base, n < d { | |
| 514 | (base, power) = (try div(.number(.int(1)), base), try neg(power)) | |
| 515 | } | |
| 516 | return (base, power) | |
| 517 | } | |
| 518 | var (baseA, powA) = try split(a) | |
| 519 | var (baseB, powB) = try split(b) | |
| 520 | if invA { powA = try neg(powA) } | |
| 521 | if invB { powB = try neg(powB) } | |
| 522 | func isFrac(_ t: Term) -> Bool { | |
| 523 | if case .number(.frac) = t { return true } | |
| 524 | return false | |
| 525 | } | |
| 526 | if baseA == baseB { | |
| 527 | var sum = try add(powA, powB) | |
| 528 | if !integerp(baseA) || zerop(sum) || isFrac(powA) == isFrac(powB) { | |
| 529 | if looksNeg(sum), ratp(baseA), posp(baseA) { | |
| 530 | (baseA, sum) = (try div(.number(.int(1)), baseA), try neg(sum)) | |
| 531 | } | |
| 532 | if sum == .number(.frac(1, 2)) || sum == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") } | |
| 533 | return try pow(baseA, sum) | |
| 534 | } | |
| 535 | } | |
| 536 | if powA == powB, case .number(.int(let x)) = baseA, case .number(.int(let y)) = baseB, x >= 0, y >= 0 { | |
| 537 | if powA == .number(.frac(1, 2)) || powA == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") } | |
| 538 | return try pow(try mul(baseA, baseB), powA) | |
| 539 | } | |
| 540 | return nil | |
| 541 | } | |
| 542 | ||
| 543 | /// `math-pow`. | |
| 544 | static func pow(_ a: Term, _ b: Term) throws -> Term { | |
| 545 | if b == nan { return b } | |
| 546 | if zerop(a) { | |
| 547 | if let y = number(b) { | |
| 548 | if try sign(y) > 0 { return floatp(b) ? try float(a) : a } | |
| 549 | return .number(try power(number(a)!, y, fractions: fractions)) | |
| 550 | } | |
| 551 | // `math-pow-of-zero` with a formula. | |
| 552 | switch try signs(b) { | |
| 553 | case 4: return a | |
| 554 | case 1: return try div(.number(.int(1)), a) | |
| 555 | default: return infinitep(b) != nil ? nan : .op("^", [a, b]) | |
| 556 | } | |
| 557 | } | |
| 558 | if a == .number(.int(1)) || b == .number(.int(1)) { return a } | |
| 559 | if a == .number(.float(1, 0)) || b == .number(.float(1, 0)) { return a } | |
| 560 | if zerop(b) { | |
| 561 | if let x = number(a) { return .number(try power(x, number(b)!, fractions: fractions)) } | |
| 562 | // `math-pow-zero`. | |
| 563 | if infinitep(a) != nil { return nan } | |
| 564 | return floatp(b) ? .number(.float(1, 0)) : .number(.int(1)) | |
| 565 | } | |
| 566 | if let x = number(a), let y = number(b) { return .number(try power(x, y, fractions: fractions)) } | |
| 567 | return try powFancy(a, b) | |
| 568 | } | |
| 569 | ||
| 570 | /// `math-pow-fancy` with a formula. | |
| 571 | static func powFancy(_ a: Term, _ b: Term) throws -> Term { | |
| 572 | let (a1, a2) = (arg(a, 1), arg(a, 2)) | |
| 573 | switch head(a) { | |
| 574 | case "*" where try knownNumInteger(b) || knownNonneg(a1) || knownNonneg(a2): | |
| 575 | return try mul(try pow(a1, b), try pow(a2, b)) | |
| 576 | case "/" where try knownNumInteger(b) || knownNonneg(a2): | |
| 577 | return try div(try pow(a1, b), try pow(a2, b)) | |
| 578 | case "/" where try knownNonneg(a1) && !equalInt(a1, 1): | |
| 579 | return try mul(try pow(a1, b), try pow(try div(.number(.int(1)), a2), b)) | |
| 580 | case "^" where try knownNumInteger(b) || knownNonneg(a1): | |
| 581 | return try pow(a1, try mul(a2, b)) | |
| 582 | case "^": | |
| 583 | // `math-known-evenp` of an exponent with a variable is false. | |
| 584 | if case .number(let n) = a2, isWhole(n), try trunc(n) % 2 == 0, let y = number(b), let q = quarter(y), | |
| 585 | (1...3).contains(q), try signs(a1) < 8 { throw Unsupported("symbolic arithmetic") } | |
| 586 | default: break | |
| 587 | } | |
| 588 | if looksNeg(a), case .number(.int(let n)) = b { | |
| 589 | let p = try pow(try neg(a), b) | |
| 590 | return n % 2 == 0 ? p : try neg(p) | |
| 591 | } | |
| 592 | if let infinity = infinitep(a) { | |
| 593 | if infinity == nan { return infinity } | |
| 594 | if head(a) == "neg" { return try mul(try pow(.number(.int(-1)), b), try pow(a1, b)) } | |
| 595 | if posp(b) { return a } | |
| 596 | if negp(b) { return floatp(b) ? .number(.float(0, 0)) : .number(.int(0)) } | |
| 597 | if objectp(b) || infinitep(b) != nil { return nan } | |
| 598 | throw Unsupported("symbolic arithmetic") | |
| 599 | } | |
| 600 | if infinitep(b) != nil { | |
| 601 | guard let x = number(a), b == inf else { throw Unsupported("symbolic arithmetic") } | |
| 602 | // `calcFunc-abssqr` of a real number is its square. | |
| 603 | let scale = try multiply(x, x) | |
| 604 | if scale == .int(1) || scale == .float(1, 0) { return nan } | |
| 605 | if try compare(scale, .int(1)) < 0 { return floatp(a) ? .number(.float(0, 0)) : .number(.int(0)) } | |
| 606 | if try compare(.int(1), x) < 0 { return b } | |
| 607 | return uinf | |
| 608 | } | |
| 609 | return .op("^", [a, b]) | |
| 610 | } | |
| 611 | ||
| 612 | // MARK: Display | |
| 613 | ||
| 614 | /// `math-format-value`: `math-compose-expr` in the flat language. | |
| 615 | static func format(_ t: Term, _ floatFormat: FloatFormat) throws -> String { | |
| 616 | let text = try compose(t, 0, floatFormat) | |
| 617 | // Past its width of 1000, `calc-eval` breaks the line. | |
| 618 | guard text.count < 1000 else { throw Unsupported("symbolic arithmetic") } | |
| 619 | return text | |
| 620 | } | |
| 621 | ||
| 622 | /// Left and right precedence, from `math-standard-ops` with | |
| 623 | /// `calc-multiplication-has-precedence`. | |
| 624 | static let operators: [String: (Int, Int)] = ["+": (180, 181), "-": (180, 181), "*": (196, 195), "/": (190, 191), "^": (201, 200)] | |
| 625 | ||
| 626 | static func compose(_ t: Term, _ prec: Int, _ floatFormat: FloatFormat, div: Bool = false) throws -> String { | |
| 627 | switch t { | |
| 628 | case .number(let v): return try Calc.format(v, floatFormat) | |
| 629 | case .variable(let name): return name | |
| 630 | case .op("neg", let args): | |
| 631 | if prec > 197 { return "(" + (try compose(t, 0, floatFormat)) + ")" } | |
| 632 | return "-" + (try compose(args[0], 197, floatFormat)) | |
| 633 | case .op(let f, let args): | |
| 634 | guard let (left, right) = operators[f], args.count == 2 else { | |
| 635 | return f + "(" + (try args.map { try compose($0, 0, floatFormat) }).joined(separator: ", ") + ")" | |
| 636 | } | |
| 637 | if prec > min(left, right) || (div && f == "*") { return "(" + (try compose(t, 0, floatFormat)) + ")" } | |
| 638 | var lhs = try compose(args[0], left, floatFormat) | |
| 639 | let rhs = try compose(args[1], right, floatFormat, div: f == "/") | |
| 640 | if f == "^", lhs.first == "-" { lhs = "(" + lhs + ")" } | |
| 641 | if f == "*", let next = rhs.first { | |
| 642 | var lastFactor = args[0] | |
| 643 | while head(lastFactor) == "*" { lastFactor = arg(lastFactor, 2) } | |
| 644 | let isVariable = if case .variable = lastFactor { true } else { false } | |
| 645 | if (next.isASCII && (next.isLetter || next.isNumber)) || ".#_([{".contains(next), !(isVariable && next == "(") { | |
| 646 | return lhs + " " + rhs | |
| 647 | } | |
| 648 | return lhs + "*" + rhs | |
| 649 | } | |
| 650 | if f == "^" { return lhs + "^" + rhs } | |
| 651 | if f == "/", let x = number(args[0]), isWhole(x), case .number(.int) = args[1] { return lhs + "/" + rhs } | |
| 652 | return lhs + " " + f + " " + rhs | |
| 653 | } | |
| 654 | } | |
| 655 | } | |
| 656 | } | |
| 657 | ||
| 658 | extension Calc.Term { | |
| 659 | /// Whether an operator or function in the formula satisfies `predicate`. | |
| 660 | func contains(where predicate: (String) -> Bool) -> Bool { | |
| 661 | guard case .op(let f, let args) = self else { return false } | |
| 662 | return predicate(f) || args.contains { $0.contains(where: predicate) } | |
| 663 | } | |
| 664 | } | |
Sources/OrgCore/Compute/TableFormulas.swift +6 −14
| @@ -306,7 +306,6 @@ extension EmacsBuffer { | ||
| 306 | 306 | case list([String]) |
| 307 | 307 | } |
| 308 | 308 | |
| 309 | static let calcNumber = "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?$" | |
| 310 | 309 | /// `org-ts-regexp-both`. |
| 311 | 310 | static let timestampBoth = "[\\[<]([0-9]{4}-[0-9]{2}-[0-9]{2}(?: [^\\]>\\n]*)?)[\\]>]" |
| 312 | 311 | |
| @@ -321,8 +320,8 @@ extension EmacsBuffer { | ||
| 321 | 320 | /// `number-to-string` of `string-to-number`. |
| 322 | 321 | static func numberText(_ s: String) -> String { Elisp.printed(Elisp.stringToNumber(s)) } |
| 323 | 322 | |
| 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. | |
| 326 | 325 | static func makeReference(_ value: TableRangeValue, _ mode: ReferenceMode) throws -> String { |
| 327 | 326 | func blank(_ s: String) -> Bool { !s.contains { !$0.isWhitespace } } |
| 328 | 327 | func lisp(_ s: String) -> String { |
| @@ -331,24 +330,16 @@ extension EmacsBuffer { | ||
| 331 | 330 | default: mode.numbers ? numberText(s) : Elisp.printed(.string(s), escape: true) |
| 332 | 331 | } |
| 333 | 332 | } |
| 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 } | |
| 343 | 334 | let empty = !mode.keepEmpty || mode.numbers ? "0" : "nan" |
| 344 | 335 | switch value { |
| 345 | 336 | case .field(let s): |
| 346 | 337 | 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) + ")" | |
| 348 | 339 | case .list(var items): |
| 349 | 340 | if !mode.keepEmpty { items = items.filter { !blank($0) } } |
| 350 | 341 | 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: ",") + "]" | |
| 352 | 343 | } |
| 353 | 344 | } |
| 354 | 345 | |
| @@ -543,6 +534,7 @@ extension EmacsBuffer { | ||
| 543 | 534 | case "F": modes.preferFractions = true |
| 544 | 535 | case "D": modes.degrees = true |
| 545 | 536 | case "R": modes.degrees = false |
| 537 | case "S": modes.symbolic = true | |
| 546 | 538 | default: throw Calc.Unsupported("format flag \(ns.substring(with: m.range))") |
| 547 | 539 | } |
| 548 | 540 | flags = ns.replacingCharacters(in: m.range, with: "") |
Tests/OrgCoreTests/CalcTests.swift +69 −6
| @@ -4,7 +4,7 @@ import Testing | ||
| 4 | 4 | |
| 5 | 5 | /// Runs `calc-eval` with org's table modes over a list of expressions. |
| 6 | 6 | enum 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] { | |
| 8 | 8 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)") |
| 9 | 9 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
| 10 | 10 | defer { try? FileManager.default.removeItem(at: folder) } |
| @@ -26,6 +26,7 @@ enum CalcOracle { | ||
| 26 | 26 | (format (car (read-from-string (nth 1 c))))) |
| 27 | 27 | (setq modes (plist-put modes 'calc-float-format format)) |
| 28 | 28 | (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))) | |
| 29 | 30 | (let ((r (condition-case e (calc-eval (cons (car c) modes) nil) |
| 30 | 31 | (error (format "LISP ERROR %S" e))))) |
| 31 | 32 | (if (stringp r) r (format "ERROR %S" r))))) |
| @@ -33,7 +34,7 @@ enum CalcOracle { | ||
| 33 | 34 | (with-temp-file (getenv "ORACLE_OUTPUT") |
| 34 | 35 | (insert (json-encode (vconcat results))))) |
| 35 | 36 | """#.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 }) | |
| 37 | 38 | return try JSONDecoder().decode([String].self, from: Data(contentsOf: output)) |
| 38 | 39 | } |
| 39 | 40 | } |
| @@ -223,13 +224,14 @@ struct CalcTests { | ||
| 223 | 224 | |
| 224 | 225 | /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the |
| 225 | 226 | /// 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) | |
| 228 | 229 | #expect(emacs.count == cases.count) |
| 229 | 230 | var skipped: [String] = [] |
| 230 | 231 | for (c, expected) in zip(cases, emacs) { |
| 231 | 232 | var modes = Calc.Modes() |
| 232 | 233 | modes.precision = precision |
| 234 | modes.symbolic = symbolic | |
| 233 | 235 | modes.timeZone = TimeZone(secondsFromGMT: zone.offset)! |
| 234 | 236 | let f = c.1.dropFirst().dropLast().split(separator: " ") |
| 235 | 237 | let n = Int(f[1])! |
| @@ -340,14 +342,58 @@ struct CalcTests { | ||
| 340 | 342 | } |
| 341 | 343 | } |
| 342 | 344 | |
| 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 | ] | |
| 363 | ||
| 364 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 365 | func symbolicMatchesCalc() throws { | |
| 366 | var cases = Self.symbolic.map { ($0, "(float 8)") } | |
| 367 | for format in ["(fix 2)", "(sci 3)"] { | |
| 368 | for e in ["x/3 + 1/3", "vmean([x,2,3])", "2.5 x - 1:3"] { cases.append((e, format)) } | |
| 369 | } | |
| 370 | // Generated: a variable or two mixed with numbers. What Calc would decide from more | |
| 371 | // than this arithmetic is refused, so only what is computed is compared. | |
| 372 | var generator = SystemRandomNumberGenerator() | |
| 373 | let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "10", "inf", "a b"] | |
| 374 | let ops = ["+", "-", "*", "/", "^"] | |
| 375 | func expression(_ depth: Int) -> String { | |
| 376 | if depth == 0 || Int.random(in: 0..<3, using: &generator) == 0 { return leaves.randomElement(using: &generator)! } | |
| 377 | let op = ops.randomElement(using: &generator)! | |
| 378 | let right = op == "^" ? ["2", "3", "-1", "0.5", "x", "-2"].randomElement(using: &generator)! : expression(depth - 1) | |
| 379 | let e = "(\(expression(depth - 1)))\(op)(\(right))" | |
| 380 | return Int.random(in: 0..<6, using: &generator) == 0 ? "-\(e)" : e | |
| 381 | } | |
| 382 | for _ in 0..<2000 { cases.append((expression(4), "(float 8)")) } | |
| 383 | let skipped = try Self.compare(cases) | |
| 384 | #expect(Set(skipped).intersection(Self.symbolic) == [], "\(skipped)") | |
| 385 | #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused") | |
| 386 | } | |
| 387 | ||
| 343 | 388 | @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", | |
| 389 | for e in ["sqrt(x)", "vmax([x,1])", "vsum(x,1)", "x<1", "if(x,1,2)", "x%2", "x_1", "x'", "Holidays+1", "café+1", | |
| 390 | "x+<2026-10-05 Mon>", "[x,1]", "vcount([x -1])", "(1/0)+1", "vmean([])", "(-8)^(1/3)", "vvar([5])", "1<2<3", | |
| 345 | 391 | "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])", |
| 346 | 392 | "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)", |
| 347 | 393 | "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", |
| 348 | 394 | "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!", |
| 349 | 395 | "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)", | |
| 396 | "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "ln(0)", "ln(-1)", | |
| 351 | 397 | // Calc leaves these date expressions unevaluated. |
| 352 | 398 | "<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", |
| 353 | 399 | "vmedian([<2026-10-05 Mon>,<2026-10-07 Wed>])", "vmean([<2026-10-05 Mon>,1])", "vmean([<2026-10-05 Mon>])", |
| @@ -373,5 +419,22 @@ struct CalcTests { | ||
| 373 | 419 | #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("<2026-10-05 Mon 10:00>+1", modes: modes) } |
| 374 | 420 | modes.precision = 19 |
| 375 | 421 | #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1+1", modes: modes) } |
| 422 | // `calc-eval` with `num`: a formula is an error, unless Calc explains it. | |
| 423 | #expect(throws: Calc.Failure("Number expected")) { try Calc.evaluate("x+1", numeric: true) } | |
| 424 | #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1/0", numeric: true) } | |
| 425 | var symbolic = Calc.Modes() | |
| 426 | symbolic.symbolic = true | |
| 427 | for e in ["sqrt(2)", "2^0.5", "ln(2)", "x^0.5"] { | |
| 428 | #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, modes: symbolic) } | |
| 429 | } | |
| 430 | } | |
| 431 | ||
| 432 | /// `;S`: what is computed matches; functions and powers that may not be exact are refused. | |
| 433 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 434 | func symbolicModeMatchesCalc() throws { | |
| 435 | let cases = (Self.fixed + Self.functions + Self.symbolic).map { ($0, "(float 8)") } | |
| 436 | let skipped = try Self.compare(cases, symbolic: true) | |
| 437 | #expect(Set(skipped).isDisjoint(with: ["1/3", "x+5", "1/0", "2 pi", "vmean([x,2,3])", "sin(30)", "x^2", "round(2.5)"])) | |
| 438 | #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused") | |
| 376 | 439 | } |
| 377 | 440 | } |
Tests/OrgCoreTests/TableFormulaEntryTests.swift +6 −6
| @@ -92,14 +92,14 @@ extension TableFormulaEntryTests { | ||
| 92 | 92 | let text = "| a | b |\n|---+---|\n| 1 | 2 |\n#+TBLFM: $2=$1*2\n" |
| 93 | 93 | let removed = try #require(committed(TableEvalFormula(named: false), text, after: "| 1 | 2", answers: ["formula": ""])) |
| 94 | 94 | #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 | |
| 96 | 96 | // 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)") | |
| 100 | 100 | #expect(tab.caret == (tab.text as NSString).range(of: "| y").location + 2) |
| 101 | 101 | #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)") | |
| 104 | 104 | } |
| 105 | 105 | } |
Tests/OrgCoreTests/TableFormulaTests.swift +17 −4
| @@ -89,6 +89,20 @@ struct TableFormulaTests { | ||
| 89 | 89 | "| a | b |\n|---+---|\n| <2026-01-01 Thu> | |\n#+TBLFM: $2=<2026-12-25 Fri>-$1;U\n", |
| 90 | 90 | ] |
| 91 | 91 | |
| 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 | ] | |
| 100 | ||
| 101 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 102 | func textAndBlankFieldsMatchEmacsNatively() throws { | |
| 103 | try compare(Self.symbolic, fallbacksAllowed: false) | |
| 104 | } | |
| 105 | ||
| 92 | 106 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) |
| 93 | 107 | func datesMatchEmacs() throws { |
| 94 | 108 | try compare(Self.dates + Self.numericResults, fallbacksAllowed: false) |
| @@ -170,10 +184,9 @@ struct TableFormulaTests { | ||
| 170 | 184 | for (i, (mine, theirs)) in zip(ours, emacs).enumerated() { |
| 171 | 185 | if let failure = mine.failure, failure.hasPrefix("external:") { |
| 172 | 186 | 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)") | |
| 187 | // Formulas over a header's text that Calc would leave symbolic in ways not | |
| 188 | // reproduced go to Emacs. | |
| 189 | #expect(fallbacksAllowed || failure.contains("symbolic") || failure.contains("of a formula"), "\(failure) in\n\(cases[i].text)") | |
| 177 | 190 | continue |
| 178 | 191 | } |
| 179 | 192 | 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 { | ||
| 23 | 23 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) |
| 24 | 24 | func recalculatesTablesNativeCodeCannot() async throws { |
| 25 | 25 | 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") | |
| 27 | 27 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) |
| 28 | 28 | session.open(file.path) |
| 29 | 29 | let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil) |
| @@ -31,17 +31,17 @@ struct EmacsFallbackTests { | ||
| 31 | 31 | Issue.record("\(step)") |
| 32 | 32 | return |
| 33 | 33 | } |
| 34 | #expect(reason == "non-numeric field a") | |
| 34 | #expect(reason == "function sqrt of a formula") | |
| 35 | 35 | #expect(!lisp) |
| 36 | 36 | let message = await session.recalculateInEmacs(table: table, point: point, form: form) |
| 37 | 37 | #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") | |
| 39 | 39 | } |
| 40 | 40 | |
| 41 | 41 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) |
| 42 | 42 | func cancelingARecalculationLeavesTheTable() async throws { |
| 43 | 43 | 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" | |
| 45 | 45 | let file = try notes.write("t.org", text) |
| 46 | 46 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) |
| 47 | 47 | session.open(file.path) |
docs/manual/guide/10-tables.org +31 −12
| @@ -231,9 +231,9 @@ In a Calc formula a single field becomes a number in parentheses, and a range be | ||
| 231 | 231 | a vector such as =[1,2,3]=. Without the =E= flag, empty fields count as 0 on their own |
| 232 | 232 | and are left out of ranges. |
| 233 | 233 | |
| 234 | Fields 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 | |
| 236 | other text needs Emacs, because Calc would treat the text as a symbol. | |
| 234 | A 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= | |
| 236 | gives =N / A + 5=. The =N= flag reads every field as a number instead, with text as 0. | |
| 237 | 237 | |
| 238 | 238 | ** Names, parameters and constants |
| 239 | 239 | |
| @@ -372,8 +372,21 @@ Functions: | ||
| 372 | 372 | | =land=, =lor=, =lnot= | As =&&=, ~||~ and =!=. | |
| 373 | 373 | |
| 374 | 374 | The 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 | |
| 376 | keeps as symbols), symbolic results, complex results and division by zero need Emacs. | |
| 375 | =vmean($2..$4, $6)=. | |
| 376 | ||
| 377 | Calc leaves what it can't reduce to a number as a formula, and so does orgstar for | |
| 378 | sums, differences, products, quotients and powers: | |
| 379 | ||
| 380 | - A name is a variable: =2*x + x= is =3 x=. Calc's constants =pi=, =e=, =phi= and =gamma= | |
| 381 | stay names too: =$1^2*pi= gives =9 pi= for 3. | |
| 382 | - Division by zero stays unevaluated: =$1/$2= with 6 and an empty field gives =6/0=, | |
| 383 | and =x/0 + 1= gives =x / 0 + 1=. | |
| 384 | - =inf=, =-inf= and =uinf= (infinity of unknown sign) follow Calc's rules: =inf - inf= is | |
| 385 | =nan=, =1/inf= is =0=, =2^inf= is =inf=. | |
| 386 | - =vsum=, =vprod=, =vmean= and =vcount= take vectors holding such formulas. | |
| 387 | ||
| 388 | Other functions of a formula, comparisons and conditions on one, and complex results | |
| 389 | need Emacs. | |
| 377 | 390 | |
| 378 | 391 | ** Mode flags and formats |
| 379 | 392 | |
| @@ -389,6 +402,7 @@ After the formula, a =;= starts its flags, as in ~$3=$1/$2;%.2f~ or ~$4=$1*2;f2~ | ||
| 389 | 402 | | =D=, =R= | Angles in degrees (the default) or radians. | |
| 390 | 403 | | =F= | Prefer fractions: =1/3= stays =1:3=. | |
| 391 | 404 | | =N= | Treat every field as a number; text counts as 0. | |
| 405 | | =S= | Symbolic: results that aren't exact stay as formulas, such as =sqrt(2)=. | | |
| 392 | 406 | | =E= | Keep empty fields: in ranges they stay in, and count as =nan= in Calc. | |
| 393 | 407 | | =L= | Literal: in Lisp formulas, insert fields as they are written. | |
| 394 | 408 | | =T= | Durations: read =H:MM= and =H:MM:SS= fields as times, show the result as =HH:MM:SS=. | |
| @@ -399,7 +413,13 @@ Above =p14=, functions worked out from decimal approximations (=sqrt= of a non-s | ||
| 399 | 413 | =exp=, =ln=, =log=, non-integer powers, trigonometric and hyperbolic functions) may need |
| 400 | 414 | Emacs, and above =p16= so may the statistics functions and powers of decimal numbers. |
| 401 | 415 | |
| 402 | The flags =S= (symbolic) and =u= need Emacs. Any other text after the flags is a | |
| 416 | With =S=, the functions that may give an inexact result (=sqrt=, =exp=, =ln=, =log=, | |
| 417 | =log10=, =pow=, =nroot=, =hypot=, the inverse trigonometric and hyperbolic functions, | |
| 418 | =fact=, =dfact=, the standard deviations, =vgmean=, =vhmean=, the covariances and | |
| 419 | =agmean=), powers other than integer powers, and =sin=, =cos= and =tan= in radians need | |
| 420 | Emacs. | |
| 421 | ||
| 422 | The flag =u= needs Emacs. Any other text after the flags is a | |
| 403 | 423 | =format= string applied to the result, such as =%.2f= or =%d=; =format= supports |
| 404 | 424 | =%s=, =%S=, =%d=, =%o=, =%x=, =%X=, =%c=, =%e=, =%f= and =%g=. |
| 405 | 425 | |
| @@ -621,12 +641,11 @@ time, which gives the same result unless a formula depends on its own value. | ||
| 621 | 641 | When a formula uses something the native evaluator doesn't have, the command reports |
| 622 | 642 | what it was and the Mac recalculates the table in Emacs instead. This happens for: |
| 623 | 643 | |
| 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; | |
| 644 | - symbolic results beyond those under /Calc expressions/, such as a function of a field | |
| 645 | holding text; | |
| 646 | - Calc functions not listed above, intervals such as =[1..5]=, precisions beyond those | |
| 647 | given under /Mode flags and formats/, parts of the =S= flag, and the =u= flag; | |
| 648 | - complex results, vector results, and numbers too large for 64-bit integers; | |
| 630 | 649 | - Lisp functions not listed above. |
| 631 | 650 | |
| 632 | 651 | The echo area shows =Recalculating in Emacs (reason)…=, then =Recalculated in Emacs=. |
l10n/Localizable.xcstrings +68
| @@ -35556,6 +35556,74 @@ | ||
| 35556 | 35556 | } |
| 35557 | 35557 | } |
| 35558 | 35558 | }, |
| 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 | }, | |
| 35559 | 35627 | "table position": { |
| 35560 | 35628 | "localizations": { |
| 35561 | 35629 | "de": { |