Simplify Calc functions, comparisons and if on formulas !425

merged merged by cmc on 2026-11-21 21:13 UTC · krz/orgstar:gaps-symfn into main

7 files changed, +506 −54

Layout: unified · split

Sources/OrgCore/Compute/Calc.swift +89 −20
@@ -479,6 +479,15 @@ public enum Calc {
479 static func compare(_ a: Value, _ b: Value) throws -> Int { 479 static func compare(_ a: Value, _ b: Value) throws -> Int {
480 if case .date(let x) = a, case .date(let y) = b { return try compare(x, y) } 480 if case .date(let x) = a, case .date(let y) = b { return try compare(x, y) }
481 if a == .nan || b == .nan { throw Unsupported("comparison with nan") } 481 if a == .nan || b == .nan { throw Unsupported("comparison with nan") }
482 // `math-compare` clears a fraction's denominator, so 0.333333333333 is less than 1:3.
483 let real = { (v: Value) in switch v { case .int, .float, .frac: true; default: false } }
484 if real(a), real(b) {
485 if case .frac(let n, let d) = a {
486 if case .frac(let n2, let d2) = b { return try compare(try multiply(.int(n), .int(d2)), try multiply(.int(n2), .int(d))) }
487 return try compare(.int(n), try multiply(b, .int(d)))
488 }
489 if case .frac(let n, let d) = b { return try compare(try multiply(a, .int(d)), .int(n)) }
490 }
482 let difference = try add(a, try negate(b)) 491 let difference = try add(a, try negate(b))
483 let (m, _) = try parts(difference) 492 let (m, _) = try parts(difference)
484 return m == 0 ? 0 : (m < 0 ? -1 : 1) 493 return m == 0 ? 0 : (m < 0 ? -1 : 1)
@@ -1116,7 +1125,7 @@ public enum Calc {
1116 return true 1125 return true
1117 } 1126 }
1118 1127
1119 // `||` < `&&` < `!` < comparisons < sums. 1128 // `||` < `&&` < comparisons < sums.
1120 mutating func or() throws -> Node { 1129 mutating func or() throws -> Node {
1121 var left = try and() 1130 var left = try and()
1122 while take("||") { left = .binary("|", left, try and()) } 1131 while take("||") { left = .binary("|", left, try and()) }
@@ -1124,19 +1133,11 @@ public enum Calc {
1124 } 1133 }
1125 1134
1126 mutating func and() throws -> Node { 1135 mutating func and() throws -> Node {
1127 var left = try not() 1136 var left = try comparison()
1128 while take("&&") { left = .binary("&", left, try not()) } 1137 while take("&&") { left = .binary("&", left, try comparison()) }
1129 return left 1138 return left
1130 } 1139 }
1131 1140
1132 mutating func not() throws -> Node {
1133 if peek() == "!", i + 1 >= chars.count || chars[i + 1] != "=" {
1134 i += 1
1135 return .unary("!", try not())
1136 }
1137 return try comparison()
1138 }
1139
1140 mutating func comparison() throws -> Node { 1141 mutating func comparison() throws -> Node {
1141 let left = try sum() 1142 let left = try sum()
1142 // Calc reads `<<` and `>>` as one token, so `1<<2026-10-05 Mon>` is a syntax error. 1143 // Calc reads `<<` and `>>` as one token, so `1<<2026-10-05 Mon>` is a syntax error.
@@ -1209,8 +1210,25 @@ public enum Calc {
1209 return try powerNode() 1210 return try powerNode()
1210 } 1211 }
1211 1212
1213 /// Prefix `!`, whose operand Calc reads at precedence 1000: `!x^2` is `(!x)^2`, and
1214 /// only a postfix `%` joins the operand. After `-` the operand is read as `-`'s.
1215 mutating func not() throws -> Node? {
1216 guard peek() == "!", i + 1 >= chars.count || chars[i + 1] != "=" else { return nil }
1217 // Calc reads `!!` as one token.
1218 if i + 1 < chars.count, chars[i + 1] == "!" { throw Unsupported("formula syntax") }
1219 i += 1
1220 if peek() == "-" { return .unary("!", try unary()) }
1221 var operand = try not() ?? primary()
1222 while peek() == "%", !factorAfter(i + 1) {
1223 if i + 1 < chars.count, chars[i + 1] == "%" { throw Unsupported("formula syntax") }
1224 i += 1
1225 operand = .call("percent", [operand])
1226 }
1227 return .unary("!", operand)
1228 }
1229
1212 mutating func powerNode() throws -> Node { 1230 mutating func powerNode() throws -> Node {
1213 var base = try primary() 1231 var base = try not() ?? primary()
1214 // Postfix `%` (percent), `!` and `!!`, which bind tighter than `^`. 1232 // Postfix `%` (percent), `!` and `!!`, which bind tighter than `^`.
1215 while let c = peek() { 1233 while let c = peek() {
1216 let next = i + 1 < chars.count ? chars[i + 1] : nil 1234 let next = i + 1 < chars.count ? chars[i + 1] : nil
@@ -1418,19 +1436,31 @@ public enum Calc {
1418 switch node { 1436 switch node {
1419 case .number(let v): return v 1437 case .number(let v): return v
1420 case .vector(let items): return .vector(try items.map(eval)) 1438 case .vector(let items): return .vector(try items.map(eval))
1421 case .unary("!", let operand): return .int(try truth(try eval(operand)) ? 0 : 1) 1439 case .unary("!", let operand):
1440 let a = try eval(operand)
1441 if isSymbolic(a) || a == .nan { return value(try Symbolic.function("lnot", [try term(a)])) }
1442 return .int(try truth(a) ? 0 : 1)
1422 case .unary(_, let operand): 1443 case .unary(_, let operand):
1423 let a = try eval(operand) 1444 let a = try eval(operand)
1424 do { return try negate(a) } catch is Rejected { return .symbolic(.op("neg", [try term(a)])) } 1445 do { return try negate(a) } catch is Rejected { return .symbolic(.op("neg", [try term(a)])) }
1425 case .binary(let op, let l, let r): 1446 case .binary(let op, let l, let r):
1426 let (a, b) = (try eval(l), try eval(r)) 1447 let (a, b) = (try eval(l), try eval(r))
1448 if isSymbolic(a, b) || a == .nan || b == .nan, let name = Self.symbolicOperators[op] {
1449 return value(try Symbolic.function(name, [try term(a), try term(b)]))
1450 }
1427 do { 1451 do {
1428 return try binary(op, a, b) 1452 return try binary(op, a, b)
1429 } catch is Rejected { 1453 } catch is Rejected {
1430 // `math-normalize` keeps the operation, its arguments evaluated. 1454 // `math-normalize` keeps the operation, its arguments evaluated.
1431 guard let name = ["+": "+", "-": "-", "*": "*", "/": "/", "^": "^"][op] else { throw Unsupported("division by zero") } 1455 guard let name = ["+": "+", "-": "-", "*": "*", "/": "/", "^": "^", "%": "%"][op] else { throw Unsupported("division by zero") }
1432 return .symbolic(.op(name, [try term(a), try term(b)])) 1456 return .symbolic(.op(name, [try term(a), try term(b)]))
1433 } 1457 }
1458 case .call("if", let args) where args.count == 3:
1459 let c = try eval(args[0])
1460 // Calc keeps the branches of a formula's condition as written, and evaluates
1461 // only the branch a number's condition picks.
1462 if isSymbolic(c) || c == .nan { return .symbolic(.op("if", [try term(c), try literal(args[1]), try literal(args[2])])) }
1463 return try eval(try truth(c) ? args[1] : args[2])
1434 case .call(let name, let args): 1464 case .call(let name, let args):
1435 let values = try args.map(eval) 1465 let values = try args.map(eval)
1436 // In symbolic mode Calc keeps these unevaluated when the result isn't exact, 1466 // In symbolic mode Calc keeps these unevaluated when the result isn't exact,
@@ -1438,8 +1468,25 @@ public enum Calc {
1438 if modes.symbolic, Self.inexact.contains(name) || (!modes.degrees && ["sin", "cos", "tan"].contains(name)) { 1468 if modes.symbolic, Self.inexact.contains(name) || (!modes.degrees && ["sin", "cos", "tan"].contains(name)) {
1439 throw Unsupported("function \(name) in symbolic mode") 1469 throw Unsupported("function \(name) in symbolic mode")
1440 } 1470 }
1441 if values.contains(where: Self.hasSymbol) { 1471 // `nan` is a formula to these functions.
1472 if values.contains(where: Self.hasSymbol)
1473 || ((Symbolic.functions.contains(name) || name == "vmax" || name == "vmin") && values.contains(where: Self.hasNaN)) {
1442 // Calc leaves most functions of a formula alone, and simplifies some. 1474 // Calc leaves most functions of a formula alone, and simplifies some.
1475 let isVector = { (v: Value) in if case .vector = v { true } else { false } }
1476 if Symbolic.functions.contains(name), !values.contains(where: isVector) {
1477 return value(try Symbolic.function(name, try values.map(term)))
1478 }
1479 // `math-reduce-many-vecs`: `max` of the elements in turn, starting from
1480 // -inf (`inf` for `min`) when the first vector is empty.
1481 if name == "vmax" || name == "vmin", values.allSatisfy(isVector) {
1482 var items = try elements(values).map(term)
1483 if try elements([values[0]]).isEmpty {
1484 items.insert(name == "vmax" ? .op("neg", [Symbolic.inf]) : Symbolic.inf, at: 0)
1485 }
1486 return try extra(2) {
1487 value(try items.dropFirst().reduce(items[0]) { try Symbolic.function(name == "vmax" ? "max" : "min", [$0, $1]) })
1488 }
1489 }
1443 guard ["vsum", "vprod", "vmean", "vcount"].contains(name), 1490 guard ["vsum", "vprod", "vmean", "vcount"].contains(name),
1444 values.allSatisfy({ if case .vector = $0 { true } else { !Self.hasSymbol($0) } }) else { 1491 values.allSatisfy({ if case .vector = $0 { true } else { !Self.hasSymbol($0) } }) else {
1445 throw Unsupported("function \(name) of a formula") 1492 throw Unsupported("function \(name) of a formula")
@@ -1455,10 +1502,35 @@ public enum Calc {
1455 } 1502 }
1456 } 1503 }
1457 1504
1505 static let symbolicOperators: [Character: String] = ["=": "eq", "≠": "neq", "<": "lt", ">": "gt", "≤": "leq", "≥": "geq",
1506 "&": "land", "|": "lor", "%": "%"]
1507
1508 /// A branch of `if` as Calc reads it, unevaluated.
1509 func literal(_ node: Node) throws -> Term {
1510 switch node {
1511 case .number, .variable: return try term(try eval(node))
1512 case .unary("-", let a):
1513 // The reader negates a number: `--3` is 3 and `-0.` is `0.`.
1514 let t = try literal(a)
1515 if case .number(let v) = t { return try term(try negate(v)) }
1516 return .op("neg", [t])
1517 case .binary(let op, let a, let b) where "+-*/^".contains(op): return .op(String(op), [try literal(a), try literal(b)])
1518 default: throw Unsupported("condition")
1519 }
1520 }
1521
1458 static let inexact: Set<String> = ["sqrt", "exp", "ln", "log10", "log", "vsdev", "vpsdev", "vgmean", "vhmean", "vcorr", 1522 static let inexact: Set<String> = ["sqrt", "exp", "ln", "log10", "log", "vsdev", "vpsdev", "vgmean", "vhmean", "vcorr",
1459 "vcov", "vpcov", "agmean", "pow", "nroot", "hypot", "sinh", "cosh", "tanh", "arcsinh", 1523 "vcov", "vpcov", "agmean", "pow", "nroot", "hypot", "sinh", "cosh", "tanh", "arcsinh",
1460 "arccosh", "arctanh", "arcsin", "arccos", "arctan", "arctan2", "fact", "dfact"] 1524 "arccosh", "arctanh", "arcsin", "arccos", "arctan", "arctan2", "fact", "dfact"]
1461 1525
1526 static func hasNaN(_ v: Value) -> Bool {
1527 switch v {
1528 case .nan: true
1529 case .vector(let items): items.contains(where: hasNaN)
1530 default: false
1531 }
1532 }
1533
1462 static func hasSymbol(_ v: Value) -> Bool { 1534 static func hasSymbol(_ v: Value) -> Bool {
1463 switch v { 1535 switch v {
1464 case .symbolic: true 1536 case .symbolic: true
@@ -1505,8 +1577,8 @@ public enum Calc {
1505 1577
1506 /// `math-mod`: the remainder with the divisor's sign. 1578 /// `math-mod`: the remainder with the divisor's sign.
1507 func mod(_ a: Value, _ b: Value) throws -> Value { 1579 func mod(_ a: Value, _ b: Value) throws -> Value {
1508 if isZero(a) { return a } 1580 if isZero(a), (try? sign(b)) != nil { return a }
1509 if isZero(b) { throw Unsupported("division by zero") } 1581 if isZero(b), (try? sign(a)) != nil { throw Rejected() }
1510 // `math-imod` only for natural numbers; otherwise the quotient is a float without F. 1582 // `math-imod` only for natural numbers; otherwise the quotient is a float without F.
1511 if case .int(let x) = a, case .int(let y) = b, x >= 0, y > 0 { return .int(x % y) } 1583 if case .int(let x) = a, case .int(let y) = b, x >= 0, y > 0 { return .int(x % y) }
1512 let q = try floorOf(try divide(a, b, fractions: modes.preferFractions)) 1584 let q = try floorOf(try divide(a, b, fractions: modes.preferFractions))
@@ -1626,9 +1698,6 @@ public enum Calc {
1626 try items.sort { try compare($0, $1) < 0 } 1698 try items.sort { try compare($0, $1) < 0 }
1627 if items.count % 2 == 1 { return items[items.count / 2] } 1699 if items.count % 2 == 1 { return items[items.count / 2] }
1628 return try divide(try add(items[items.count / 2 - 1], items[items.count / 2]), .int(2), fractions: modes.preferFractions) 1700 return try divide(try add(items[items.count / 2 - 1], items[items.count / 2]), .int(2), fractions: modes.preferFractions)
1629 case "if":
1630 guard args.count == 3 else { throw Unsupported("arguments") }
1631 return try truth(args[0]) ? args[1] : args[2]
1632 case "vvar", "vpvar", "vsdev", "vpsdev": 1701 case "vvar", "vpvar", "vsdev", "vpsdev":
1633 let variance = try covariance(try elements(args), population: name == "vpvar" || name == "vpsdev") 1702 let variance = try covariance(try elements(args), population: name == "vpvar" || name == "vpsdev")
1634 return name.hasSuffix("sdev") ? try squareRoot(variance) : variance 1703 return name.hasSuffix("sdev") ? try squareRoot(variance) : variance
Sources/OrgCore/Compute/CalcSymbolic.swift +310 −16
@@ -3,7 +3,9 @@ import Foundation
3/// Calc's arithmetic on formulas it can't reduce to a number: variables, `inf`, `uinf`, and 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` 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 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 6/// with `calc-simplify-mode` nil; `math-sqrt`, `math-abs`, `math-mod`, `calcFunc-exp`, `calcFunc-ln`,
7/// `calcFunc-min`, `calcFunc-max` and the comparisons and logical functions of calc-prog.el on
8/// formulas; and Calc's flat formula printer from calccomp.el. Anything
7/// those functions would decide from declarations, units, matrices or intervals throws 9/// those functions would decide from declarations, units, matrices or intervals throws
8/// `Calc.Unsupported`. 10/// `Calc.Unsupported`.
9extension Calc { 11extension Calc {
@@ -163,7 +165,7 @@ extension Calc {
163 return 7 165 return 7
164 } 166 }
165 if f == "neg" { return negSigns(try signs(a1, try origin.map(neg))) } 167 if f == "neg" { return negSigns(try signs(a1, try origin.map(neg))) }
166 let origin = origin.flatMap { zerop($0) ? nil : $0 } 168 var origin = origin.flatMap { zerop($0) ? nil : $0 }
167 let zero = Term.number(.int(0)) 169 let zero = Term.number(.int(0))
168 if f == "*" || (f == "/" && origin != nil), objectp(a1) { 170 if f == "*" || (f == "/" && origin != nil), objectp(a1) {
169 let s = f == "*" 171 let s = f == "*"
@@ -211,6 +213,32 @@ extension Calc {
211 case "i": return 8 213 case "i": return 8
212 default: return 15 214 default: return 15
213 } 215 }
216 case .op("%", let args):
217 let s2 = try signs(args[1])
218 sign = s2 >= 8 ? 7 : s2 == 2 ? 2 : [4, 6].contains(s2) ? 6 : [1, 3].contains(s2) ? 3 : 7
219 case .op("abs", let args):
220 let s1 = try signs(args[0])
221 sign = s1 == 2 ? 2 : [1, 4, 5].contains(s1) ? 4 : 6
222 case .op("exp", let args):
223 let s1 = try signs(args[0])
224 if s1 >= 8 {
225 sign = 15
226 } else if origin == nil || negp(origin!) {
227 sign = 4
228 } else {
229 origin = try sub(origin!, .number(.int(1)))
230 if zerop(origin!) { origin = nil }
231 sign = s1
232 }
233 case .op("ln", let args):
234 sign = try knownNonneg(args[0]) ? try signs(args[0], .number(.int(1))) : 15
235 case .op("sqrt", let args):
236 let s1 = try signs(args[0])
237 sign = [2, 4, 6].contains(s1) ? s1 : 15
238 case .op(let f, _) where ["eq", "neq", "lt", "gt", "leq", "geq", "lnot", "max", "min"].contains(f):
239 sign = 7
240 // Nothing is declared about the other functions.
241 case .op(let f, _) where functions.contains(f) || f == "if": return 15
214 default: throw Unsupported("function \(f ?? "")") 242 default: throw Unsupported("function \(f ?? "")")
215 } 243 }
216 guard let origin else { return sign } 244 guard let origin else { return sign }
@@ -220,6 +248,35 @@ extension Calc {
220 248
221 static func knownNonneg(_ t: Term) throws -> Bool { [2, 4, 6].contains(try signs(t)) } 249 static func knownNonneg(_ t: Term) throws -> Bool { [2, 4, 6].contains(try signs(t)) }
222 250
251 static func knownReal(_ t: Term) throws -> Bool { try signs(t) < 8 }
252
253 /// `math-known-evenp`.
254 static func knownEven(_ t: Term) throws -> Bool {
255 switch t {
256 case .number(.int(let n)): return n % 2 == 0
257 case .number(.float(let m, let e)) where e >= 0: return e > 0 || m % 2 == 0
258 case .op("*", let args):
259 if try knownEven(args[0]) { return try knownNumInteger(args[1]) }
260 return try knownNumInteger(args[0]) && knownEven(args[1])
261 case .op("+", let args), .op("-", let args):
262 return try (knownEven(args[0]) && knownEven(args[1])) || (knownOdd(args[0]) && knownOdd(args[1]))
263 case .op("neg", let args): return try knownEven(args[0])
264 default: return false
265 }
266 }
267
268 /// `math-known-oddp`.
269 static func knownOdd(_ t: Term) throws -> Bool {
270 switch t {
271 case .number(.int(let n)): return n % 2 != 0
272 case .number(.float(let m, let e)) where e >= 0: return e == 0 && m % 2 != 0
273 case .op("+", let args), .op("-", let args):
274 return try (knownEven(args[0]) && knownOdd(args[1])) || (knownOdd(args[0]) && knownEven(args[1]))
275 case .op("neg", let args): return try knownOdd(args[0])
276 default: return false
277 }
278 }
279
223 /// `math-known-num-integerp`. 280 /// `math-known-num-integerp`.
224 static func knownNumInteger(_ t: Term) throws -> Bool { 281 static func knownNumInteger(_ t: Term) throws -> Bool {
225 if let v = number(t) { return isWhole(v) } 282 if let v = number(t) { return isWhole(v) }
@@ -244,8 +301,18 @@ extension Calc {
244 case .number: throw Unsupported("symbolic arithmetic") 301 case .number: throw Unsupported("symbolic arithmetic")
245 case .variable: return 63 302 case .variable: return 63
246 case .op("neg", let args): return try possibleTypes(args[0]) 303 case .op("neg", let args): return try possibleTypes(args[0])
247 case .op(let f, let args) where args.count == 2 && ["+", "-", "*", "/", "^"].contains(f): 304 case .op("sqrt", let args):
248 let (t1, t2) = (try possibleTypes(args[0], num: num), try possibleTypes(args[1], num: num)) 305 let s1 = try signs(args[0])
306 let t = (s1 & 2 > 0 ? 3 : 0) | (s1 & 1 > 0 ? 16 : 0) | (s1 & 4 > 0 ? 15 : 0) | (s1 & 8 > 0 ? 32 : 0)
307 return t < 16 ? t : 63
308 case .op("abs", let args):
309 let t1 = try possibleTypes(args[0])
310 return t1 >= 16 ? 15 : t1
311 case .op(let f, let args) where args.count == 2 && ["+", "-", "*", "/", "^", "%"].contains(f):
312 // `%` keeps only the real bits, which the merged values above 15 don't give.
313 if f == "%", args.contains(where: { containsHead($0, "sqrt") }) { throw Unsupported("symbolic arithmetic") }
314 var (t1, t2) = (try possibleTypes(args[0], num: num), try possibleTypes(args[1], num: num))
315 if f == "%" { (t1, t2) = (t1 & 15, t2 & 15) }
249 let t12 = t1 | t2 316 let t12 = t1 | t2
250 if f == "^" { 317 if f == "^" {
251 guard t2 <= 3, try knownNonneg(args[1]), t1 < 16 else { 318 guard t2 <= 3, try knownNonneg(args[1]), t1 < 16 else {
@@ -260,12 +327,18 @@ extension Calc {
260 return t1 == 4 || t2 == 4 || fractions ? 5 : 15 327 return t1 == 4 || t2 == 4 || fractions ? 5 : 15
261 } 328 }
262 let mask = t12 <= 3 ? 1 329 let mask = t12 <= 3 ? 1
263 : ((t1 <= 3 && t2 & 3 == 0) || (t2 <= 3 && t1 & 3 == 0)) && f != "*" ? 4 : 5 330 : ((t1 <= 3 && t2 & 3 == 0) || (t2 <= 3 && t1 & 3 == 0)) && (f == "+" || f == "-") ? 4 : 5
264 return merge(t1, t2, mask) 331 return merge(t1, t2, mask)
332 case .op(let f, _) where functions.contains(f) || f == "if": return 63
265 default: throw Unsupported("function \(head(a) ?? "")") 333 default: throw Unsupported("function \(head(a) ?? "")")
266 } 334 }
267 } 335 }
268 336
337 static func containsHead(_ t: Term, _ f: String) -> Bool {
338 guard case .op(let g, let args) = t else { return false }
339 return g == f || args.contains { containsHead($0, f) }
340 }
341
269 // MARK: Arithmetic 342 // MARK: Arithmetic
270 343
271 /// `math-normalize`: the operations applied again from the leaves, floats rounded 344 /// `math-normalize`: the operations applied again from the leaves, floats rounded
@@ -274,6 +347,12 @@ extension Calc {
274 switch t { 347 switch t {
275 case .number(.float(let m, let e)): return .number(try makeFloat(Int128(m), e)) 348 case .number(.float(let m, let e)): return .number(try makeFloat(Int128(m), e))
276 case .number, .variable: return t 349 case .number, .variable: return t
350 // `math-normalize-logical-op`: the branches stay as written unless the condition
351 // is a number.
352 case .op("if", let args) where args.count == 3:
353 let c = try normalize(args[0])
354 guard let v = number(c) else { return .op("if", [c, args[1], args[2]]) }
355 return try normalize(isZero(v) ? args[2] : args[1])
277 case .op(let f, let args): 356 case .op(let f, let args):
278 let args = try args.map(normalize) 357 let args = try args.map(normalize)
279 do { return try apply(f, args) } catch is Rejected { return .op(f, args) } 358 do { return try apply(f, args) } catch is Rejected { return .op(f, args) }
@@ -288,7 +367,9 @@ extension Calc {
288 case ("/", 2): return try div(args[0], args[1]) 367 case ("/", 2): return try div(args[0], args[1])
289 case ("^", 2): return try pow(args[0], args[1]) 368 case ("^", 2): return try pow(args[0], args[1])
290 case ("neg", 1): return try neg(args[0]) 369 case ("neg", 1): return try neg(args[0])
291 default: throw Unsupported("function \(f)") 370 default:
371 guard functions.contains(f) else { throw Unsupported("function \(f)") }
372 return try function(f, args)
292 } 373 }
293 } 374 }
294 375
@@ -547,7 +628,9 @@ extension Calc {
547 func split(_ t: Term) throws -> (Term, Term) { 628 func split(_ t: Term) throws -> (Term, Term) {
548 var (base, power) = (t, Term.number(.int(1))) 629 var (base, power) = (t, Term.number(.int(1)))
549 if head(t) == "^", objectp(arg(t, 2)) { (base, power) = (arg(t, 1), arg(t, 2)) } 630 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") } 631 if head(t) == "sqrt" { (base, power) = (arg(t, 1), .number(.frac(1, 2))) }
632 // Only in symbolic mode does `exp` of a number stay.
633 if head(t) == "exp", objectp(arg(t, 1)) { throw Unsupported("symbolic arithmetic") }
551 if case .number(.frac(let n, let d)) = base, n < d { 634 if case .number(.frac(let n, let d)) = base, n < d {
552 (base, power) = (try div(.number(.int(1)), base), try neg(power)) 635 (base, power) = (try div(.number(.int(1)), base), try neg(power))
553 } 636 }
@@ -567,17 +650,22 @@ extension Calc {
567 if looksNeg(sum), ratp(baseA), posp(baseA) { 650 if looksNeg(sum), ratp(baseA), posp(baseA) {
568 (baseA, sum) = (try div(.number(.int(1)), baseA), try neg(sum)) 651 (baseA, sum) = (try div(.number(.int(1)), baseA), try neg(sum))
569 } 652 }
570 if sum == .number(.frac(1, 2)) || sum == .number(.frac(-1, 2)) { throw Unsupported("symbolic arithmetic") } 653 return try root(baseA, sum)
571 return try pow(baseA, sum)
572 } 654 }
573 } 655 }
574 if powA == powB, case .number(.int(let x)) = baseA, case .number(.int(let y)) = baseB, x >= 0, y >= 0 { 656 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") } 657 return try root(try mul(baseA, baseB), powA)
576 return try pow(try mul(baseA, baseB), powA)
577 } 658 }
578 return nil 659 return nil
579 } 660 }
580 661
662 /// `a^p`, with Calc's square root form for a half.
663 static func root(_ a: Term, _ p: Term) throws -> Term {
664 if p == .number(.frac(1, 2)) { return .op("sqrt", [a]) }
665 if p == .number(.frac(-1, 2)) { return try div(.number(.int(1)), .op("sqrt", [a])) }
666 return try pow(a, p)
667 }
668
581 /// `math-pow`. 669 /// `math-pow`.
582 static func pow(_ a: Term, _ b: Term) throws -> Term { 670 static func pow(_ a: Term, _ b: Term) throws -> Term {
583 if b == nan { return b } 671 if b == nan { return b }
@@ -617,16 +705,19 @@ extension Calc {
617 return try mul(try pow(a1, b), try pow(try div(.number(.int(1)), a2), b)) 705 return try mul(try pow(a1, b), try pow(try div(.number(.int(1)), a2), b))
618 case "^" where try knownNumInteger(b) || knownNonneg(a1): 706 case "^" where try knownNumInteger(b) || knownNonneg(a1):
619 return try pow(a1, try mul(a2, b)) 707 return try pow(a1, try mul(a2, b))
708 case "sqrt" where try knownNumInteger(b) || knownNonneg(a1):
709 return try pow(a1, try div(b, .number(.int(2))))
620 case "^": 710 case "^":
621 // `math-known-evenp` of an exponent with a variable is false. 711 if let y = number(b), let q = quarter(y), (1...3).contains(q), try knownEven(a2), try knownReal(a1) {
622 if case .number(let n) = a2, isWhole(n), try trunc(n) % 2 == 0, let y = number(b), let q = quarter(y), 712 return try absTerm(try pow(a1, try mul(a2, b)))
623 (1...3).contains(q), try signs(a1) < 8 { throw Unsupported("symbolic arithmetic") } 713 }
624 default: break 714 default: break
625 } 715 }
626 if looksNeg(a), case .number(.int(let n)) = b { 716 if looksNeg(a), case .number(.int(let n)) = b {
627 let p = try pow(try neg(a), b) 717 let p = try pow(try neg(a), b)
628 return n % 2 == 0 ? p : try neg(p) 718 return n % 2 == 0 ? p : try neg(p)
629 } 719 }
720 if head(a) == "abs", try knownReal(a1), try knownEven(b) { return try pow(a1, b) }
630 if let infinity = infinitep(a) { 721 if let infinity = infinitep(a) {
631 if infinity == nan { return infinity } 722 if infinity == nan { return infinity }
632 if head(a) == "neg" { return try mul(try pow(.number(.int(-1)), b), try pow(a1, b)) } 723 if head(a) == "neg" { return try mul(try pow(.number(.int(-1)), b), try pow(a1, b)) }
@@ -647,6 +738,197 @@ extension Calc {
647 return .op("^", [a, b]) 738 return .op("^", [a, b])
648 } 739 }
649 740
741 // MARK: Functions
742
743 /// The functions `function` applies to formulas; `%` is `math-mod`.
744 static let functions: Set<String> = ["sqrt", "abs", "exp", "ln", "min", "max", "eq", "neq", "lt", "gt", "leq", "geq",
745 "land", "lor", "lnot", "%"]
746
747 /// `name` of `args`, at least one a formula, as `math-normalize` calls it: simplified,
748 /// or kept with its arguments when the function rejects them.
749 static func function(_ name: String, _ args: [Term]) throws -> Term {
750 do { return try simplify(name, args) } catch is Rejected { return .op(name, args) }
751 }
752
753 static func simplify(_ name: String, _ args: [Term]) throws -> Term {
754 let kept = Term.op(name, args)
755 switch (name, args.count) {
756 case ("sqrt", 1), ("exp", 1), ("ln", 1):
757 // In symbolic mode these keep a result that isn't exact, which isn't reproduced.
758 guard !symbolicMode else { throw Unsupported("function \(name) in symbolic mode") }
759 switch name {
760 case "sqrt": return try sqrtTerm(args[0])
761 case "exp": return try expTerm(args[0])
762 default: return try lnTerm(args[0])
763 }
764 case ("abs", 1): return try absTerm(args[0])
765 case ("min", _), ("max", _):
766 // `calcFunc-min` rejects an argument that isn't a real number or an infinity.
767 guard !args.isEmpty else { throw Unsupported("arguments") }
768 guard args.allSatisfy({ objectp($0) || infinitep($0) != nil }) else { return kept }
769 return try args.dropFirst().reduce(args[0]) { best, item in
770 switch try compareTerms(best, item) {
771 case 2: return nan
772 case let order: return order == (name == "max" ? -1 : 1) ? item : best
773 }
774 }
775 case ("eq", 2), ("neq", 2), ("lt", 2), ("gt", 2), ("leq", 2), ("geq", 2):
776 let (a, b) = (args[0], args[1])
777 let order = try compareTerms(a, b)
778 if order == 2 {
779 // Both sides negative, or zero, flip.
780 if looksNeg(a) || zerop(a), looksNeg(b) || zerop(b) {
781 return .op(flipped[name]!, [try neg(a), try neg(b)])
782 }
783 return kept
784 }
785 let holds = switch name {
786 case "eq": order == 0
787 case "neq": order != 0
788 case "lt": order == -1
789 case "gt": order == 1
790 case "leq": order != 1
791 default: order != -1
792 }
793 return .number(.int(holds ? 1 : 0))
794 case ("land", 2):
795 let (a, b) = (args[0], args[1])
796 if zerop(a) { return a }
797 if zerop(b) { return b }
798 if try isTrue(a) { return b }
799 if try isTrue(b) { return a }
800 return kept
801 case ("lor", 2):
802 let (a, b) = (args[0], args[1])
803 if zerop(a) { return b }
804 if zerop(b) { return a }
805 if try isTrue(a) { return a }
806 if try isTrue(b) { return b }
807 return kept
808 case ("lnot", 1):
809 let a = args[0]
810 if zerop(a) { return .number(.int(1)) }
811 if try isTrue(a) { return .number(.int(0)) }
812 if case .op(let f, let xs) = a, xs.count == 2, let opposite = negated[f] { return .op(opposite, xs) }
813 return kept
814 case ("%", 2): return try modTerm(args[0], args[1])
815 default: throw Unsupported("function \(name) of a formula")
816 }
817 }
818
819 /// The comparison with its sides negated, and its negation (`calc-tweak-eqn-table`).
820 static let flipped = ["eq": "eq", "neq": "neq", "lt": "gt", "gt": "lt", "leq": "geq", "geq": "leq"]
821 static let negated = ["eq": "neq", "neq": "eq", "lt": "geq", "gt": "leq", "leq": "gt", "geq": "lt"]
822
823 /// `math-is-true`.
824 static func isTrue(_ t: Term) throws -> Bool {
825 if let v = number(t) { return !isZero(v) }
826 return [1, 4, 5, 8, 9, 12, 13].contains(try signs(t))
827 }
828
829 /// `math-compare`: -1, 0 or 1, or 2 when the order isn't known.
830 static func compareTerms(_ a: Term, _ b: Term) throws -> Int {
831 if a == b {
832 switch a {
833 case .number: return 0
834 case .variable, .op("neg", _), .op("*", _), .op("/", _): return infinitep(a) != nil ? 2 : 0
835 default: return 0
836 }
837 }
838 if let x = number(a), let y = number(b) { return try Calc.compare(x, y) }
839 if case .number(.frac(let n, let d)) = a { return try compareTerms(.number(.int(n)), try mul(b, .number(.int(d)))) }
840 if case .number(.frac(let n, let d)) = b { return try compareTerms(try mul(a, .number(.int(d))), .number(.int(n))) }
841 let one = Term.number(.int(1)), minusOne = Term.number(.int(-1))
842 if let infA = infinitep(a) {
843 if a == uinf || a == nan { return 2 }
844 let dirA = try infiniteDirection(a, infA)
845 if let infB = infinitep(b) {
846 if b == uinf || b == nan { return 2 }
847 let dirB = try infiniteDirection(b, infB)
848 return dirA == one && dirB == minusOne ? 1 : dirA == minusOne && dirB == one ? -1 : 2
849 }
850 return dirA == one ? 1 : dirA == minusOne ? -1 : 2
851 }
852 if let infB = infinitep(b) {
853 if b == uinf || b == nan { return 2 }
854 let dirB = try infiniteDirection(b, infB)
855 return dirB == one ? -1 : dirB == minusOne ? 1 : 2
856 }
857 let e = Term.variable("e")
858 if head(a) == "exp", head(b) == "^", arg(b, 1) == e { return try compareTerms(arg(a, 1), arg(b, 2)) }
859 if head(b) == "exp", head(a) == "^", arg(a, 1) == e { return try compareTerms(arg(a, 2), arg(b, 1)) }
860 let half: [Term] = [.number(.frac(1, 2)), .number(.float(5, -1))]
861 if (head(a) == "sqrt" && head(b) == "^" && half.contains(arg(b, 2)))
862 || (head(b) == "sqrt" && head(a) == "^" && half.contains(arg(a, 2))) {
863 return try compareTerms(arg(a, 1), arg(b, 1))
864 }
865 if case .variable = a { return 2 }
866 if case .op(let f, let xs) = a, case .op(let g, let ys) = b, f == g, xs.count == ys.count,
867 try zip(xs, ys).allSatisfy({ try compareTerms($0, $1) == 0 }) { return 0 }
868 return 2
869 }
870
871 /// `math-sqrt` of a formula.
872 static func sqrtTerm(_ a: Term) throws -> Term {
873 if let v = number(a) { return .number(try squareRoot(v)) }
874 // An imaginary result.
875 if [1, 2, 3].contains(try signs(a)) { throw Unsupported("complex result") }
876 let (a1, a2) = (arg(a, 1), arg(a, 2))
877 switch head(a) {
878 case "*" where try knownNonneg(a1) || knownNonneg(a2):
879 return try mul(try sqrtTerm(a1), try sqrtTerm(a2))
880 case "/" where try knownNonneg(a2):
881 return try div(try sqrtTerm(a1), try sqrtTerm(a2))
882 case "/" where try knownNonneg(a1) && !equalInt(a1, 1):
883 return try mul(try sqrtTerm(a1), try sqrtTerm(try div(.number(.int(1)), a2)))
884 case "^" where try knownEven(a2) && knownReal(a1):
885 return try absTerm(try pow(a1, try div(a2, .number(.int(2)))))
886 default: break
887 }
888 if let infinity = infinitep(a) { return try mul(try sqrtTerm(try infiniteDirection(a, infinity)), infinity) }
889 return .op("sqrt", [a])
890 }
891
892 /// `math-abs` of a formula.
893 static func absTerm(_ a: Term) throws -> Term {
894 if let v = number(a) { return .number(try absolute(v)) }
895 if negp(a) { return try neg(a) }
896 if looksNeg(a) { return .op("abs", [try neg(a)]) }
897 let s = try signs(a)
898 if [2, 4, 6].contains(s) { return a }
899 if [1, 3].contains(s) { return try neg(a) }
900 if let infinity = infinitep(a) { return infinity == nan ? nan : inf }
901 return .op("abs", [a])
902 }
903
904 /// `calcFunc-exp` of a formula.
905 static func expTerm(_ a: Term) throws -> Term {
906 if objectp(a) { throw Unsupported("symbolic arithmetic") }
907 if a == inf || a == nan { return a }
908 if a == .op("neg", [inf]) { return .number(.int(0)) }
909 return .op("exp", [a])
910 }
911
912 /// `calcFunc-ln` of a formula.
913 static func lnTerm(_ a: Term) throws -> Term {
914 if objectp(a) { throw Unsupported("symbolic arithmetic") }
915 if a == .variable("e") { return .number(.int(1)) }
916 if head(a) == "^", arg(a, 1) == .variable("e"), try knownReal(arg(a, 2)) { return arg(a, 2) }
917 if infinitep(a) != nil { return a == nan ? nan : inf }
918 return .op("ln", [a])
919 }
920
921 /// `math-mod` with a formula.
922 static func modTerm(_ a: Term, _ b: Term) throws -> Term {
923 if zerop(a) { return a }
924 if objectp(a), objectp(b) { throw Unsupported("symbolic arithmetic") }
925 if b == inf {
926 if posp(a) || zerop(a) { return a }
927 if negp(a) { return b }
928 }
929 return .op("%", [a, b])
930 }
931
650 // MARK: Display 932 // MARK: Display
651 933
652 /// `math-format-value`: `math-compose-expr` in the flat language. 934 /// `math-format-value`: `math-compose-expr` in the flat language.
@@ -659,7 +941,12 @@ extension Calc {
659 941
660 /// Left and right precedence, from `math-standard-ops` with 942 /// Left and right precedence, from `math-standard-ops` with
661 /// `calc-multiplication-has-precedence`. 943 /// `calc-multiplication-has-precedence`.
662 static let operators: [String: (Int, Int)] = ["+": (180, 181), "-": (180, 181), "*": (196, 195), "/": (190, 191), "^": (201, 200)] 944 static let operators: [String: (Int, Int)] = ["+": (180, 181), "-": (180, 181), "*": (196, 195), "/": (190, 191), "^": (201, 200),
945 "%": (190, 191), "eq": (160, 161), "neq": (160, 161), "lt": (160, 161),
946 "gt": (160, 161), "leq": (160, 161), "geq": (160, 161), "land": (110, 111),
947 "lor": (100, 101)]
948
949 static let symbols = ["eq": "=", "neq": "!=", "lt": "<", "gt": ">", "leq": "<=", "geq": ">=", "land": "&&", "lor": "||"]
663 950
664 static func compose(_ t: Term, _ prec: Int, _ floatFormat: FloatFormat, div: Bool = false) throws -> String { 951 static func compose(_ t: Term, _ prec: Int, _ floatFormat: FloatFormat, div: Bool = false) throws -> String {
665 switch t { 952 switch t {
@@ -668,6 +955,13 @@ extension Calc {
668 case .op("neg", let args): 955 case .op("neg", let args):
669 if prec > 197 { return "(" + (try compose(t, 0, floatFormat)) + ")" } 956 if prec > 197 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
670 return "-" + (try compose(args[0], 197, floatFormat)) 957 return "-" + (try compose(args[0], 197, floatFormat))
958 case .op("lnot", let args) where args.count == 1:
959 if prec > 1000 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
960 return "!" + (try compose(args[0], 1000, floatFormat))
961 case .op("if", let args) where args.count == 3:
962 if prec > 90 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
963 return try compose(args[0], 91, floatFormat) + " ? " + compose(args[1], 0, floatFormat) + " : "
964 + compose(args[2], 90, floatFormat)
671 case .op(let f, let args): 965 case .op(let f, let args):
672 guard let (left, right) = operators[f], args.count == 2 else { 966 guard let (left, right) = operators[f], args.count == 2 else {
673 return f + "(" + (try args.map { try compose($0, 0, floatFormat) }).joined(separator: ", ") + ")" 967 return f + "(" + (try args.map { try compose($0, 0, floatFormat) }).joined(separator: ", ") + ")"
@@ -687,7 +981,7 @@ extension Calc {
687 } 981 }
688 if f == "^" { return lhs + "^" + rhs } 982 if f == "^" { return lhs + "^" + rhs }
689 if f == "/", let x = number(args[0]), isWhole(x), case .number(.int) = args[1] { return lhs + "/" + rhs } 983 if f == "/", let x = number(args[0]), isWhole(x), case .number(.int) = args[1] { return lhs + "/" + rhs }
690 return lhs + " " + f + " " + rhs 984 return lhs + " " + (symbols[f] ?? f) + " " + rhs
691 } 985 }
692 } 986 }
693 } 987 }
Tests/OrgCoreTests/CalcTests.swift +81 −6
@@ -231,7 +231,7 @@ struct CalcTests {
231 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the 231 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the
232 /// cases `Calc.evaluate` doesn't support. 232 /// cases `Calc.evaluate` doesn't support.
233 static func compare(_ cases: [(String, String)], precision: Int = 12, zone: (name: String, offset: Int) = ("UTC", 0), symbolic: Bool = false, 233 static func compare(_ cases: [(String, String)], precision: Int = 12, zone: (name: String, offset: Int) = ("UTC", 0), symbolic: Bool = false,
234 radians: Bool = false, fractions: Bool = false) throws -> [String] { 234 radians: Bool = false, fractions: Bool = false, note: String = "") throws -> [String] {
235 let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name, symbolic: symbolic, radians: radians, fractions: fractions) 235 let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name, symbolic: symbolic, radians: radians, fractions: fractions)
236 #expect(emacs.count == cases.count) 236 #expect(emacs.count == cases.count)
237 var skipped: [String] = [] 237 var skipped: [String] = []
@@ -257,7 +257,7 @@ struct CalcTests {
257 if !expected.hasPrefix("LISP ERROR") { skipped.append(c.0) } 257 if !expected.hasPrefix("LISP ERROR") { skipped.append(c.0) }
258 continue 258 continue
259 } 259 }
260 #expect(ours == expected, "\(c.0) \(c.1) p\(precision)") 260 #expect(ours == expected, "\(c.0) \(c.1) p\(precision)\(note)")
261 } 261 }
262 return skipped 262 return skipped
263 } 263 }
@@ -415,10 +415,85 @@ struct CalcTests {
415 #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused") 415 #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused")
416 } 416 }
417 417
418 /// Functions of formulas Calc simplifies, or keeps with their arguments.
419 static let symbolicFunctions = [
420 "sqrt(x)", "sqrt(4 x)", "sqrt(2 x)", "sqrt(x/4)", "sqrt(4/x)", "sqrt(x^2)", "sqrt((-x)^2)", "sqrt(inf)", "sqrt(uinf)",
421 "sqrt(x)^2", "sqrt(x)*sqrt(x)", "sqrt(x)/sqrt(x)", "x sqrt(x)", "2 sqrt(x)", "sqrt(x) + sqrt(x)", "abs(x)", "abs(-x)",
422 "abs(-2 x)", "abs(abs(x))", "abs(x)^2", "abs(x) abs(x)", "abs(-inf)", "abs(x) - abs(x)", "exp(x)", "exp(-x)",
423 "exp(inf)", "exp(-inf)", "exp(x) exp(x)", "exp(x)/exp(x)", "ln(x)", "ln(e)", "ln(e^2)", "ln(inf)", "ln(-inf)",
424 "min(x,1)", "max(x,1)", "max(1,x,2)", "max(inf,1)", "max(inf,inf)", "max(x inf, 1)", "2 max(x,1)", "-max(x,1)",
425 "x<1", "x==x", "x==y", "-x==-1", "0 < -x", "-x < -1", "x<=x", "x != x", "x != y", "1 + (x<1)", "eq(x,y)", "lt(x,1)",
426 "sqrt(x) == x^0.5", "exp(x) == e^x", "abs(x) < 0", "!x", "!(x<1)", "!(x+1)", "lnot(x>1)", "x && 1", "x || 0",
427 "x<1 && y", "x || y", "if(x,1,2)", "if(x, -3, 2.50)", "if(x, -y, 1:2)", "if(x<1,x,1)", "if(x,1,2)+1",
428 "if(inf,1,2)", "if(1,x,y)", "if(0,x,y)", "if(1,2,ln(0))", "x%2", "x%x", "(2 x)%2", "0%x", "x%0", "-1%inf",
429 "2%inf", "x%inf", "x % y % z", "(x % y) * 2", "-x % y", "vmax([x,1])", "vmin([x,1,2])", "vmax([1,2,x])",
430 "vmax([x,y],[1,2])", "vmax([x,1.23456789012345])", "vmin([inf,x])", "vmax([N/A,3,5])", "vmin([2,TBD,1])",
431 // Prefix `!` binds tighter than `^`.
432 "!x+1", "!x<1", "!x*2", "2*!x", "!x^2", "!(x<1) + 1", "!-x+1", "-!x^2", "! !x", "!2+1", "!x && y", "x^!y",
433 // The reader negates numbers in a branch.
434 "if(x, --3, 1)", "if(x, -(-(2)), 1)", "if(x, -0, 1)", "if(x, -0.0, 1)", "if(x, 1/-2, 1)", "if(x, 2^-1, 1)",
435 "if(x, y * -2, 1)", "if(x, -(-x), 1)", "if(x, -2 * -3, 1)", "if(x, -x^-2, 1)", "if(x, 1/(-x), 1)", "if(x, -(1:2), 1)",
436 // An empty first vector starts from -inf.
437 "vmax([], [x])", "vmin([], [x])", "vmax([], [x, 1])", "vmax([], [2, x])", "vmax([[]], [x])", "vmax([x], [], [1])",
438 "vmin([], [], [x])",
439 ]
440
441 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
442 func symbolicFunctionsMatchCalc() throws {
443 var cases = Self.symbolicFunctions.map { ($0, "(float 8)") }
444 for format in ["(fix 2)", "(fix 0)", "(sci 3)", "(eng 2)"] {
445 for e in ["sqrt(2 x)", "max(x, 2.5)", "if(x, 1.5, 2)", "x % 0.5", "vmin([x, 1:3, 0.25])", "x + 0.4", "max(x, 0.)"] {
446 cases.append((e, format))
447 }
448 }
449 // Generated: the functions applied to formulas of a variable or two and numbers, and
450 // their results combined again. What is refused is left to Emacs.
451 let seed = ProcessInfo.processInfo.environment["ORGSTAR_SEED"].flatMap { UInt64($0) } ?? UInt64.random(in: 0...UInt64.max)
452 var generator = SeededGenerator(state: seed)
453 let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "-2", "4", "inf", "e", "a b", "-inf", "uinf", "nan", "0.", "1.5e3", "-x", "2 x", "pi"]
454 let unary = ["sqrt", "abs", "exp", "ln", "!", "-"]
455 let binary = ["min", "max", "%", "<", ">", "<=", ">=", "==", "!=", "&&", "||", "+", "-", "*", "/", "^"]
456 func leaf() -> String { leaves.randomElement(using: &generator)! }
457 // Operands are left bare most of the time, so Calc's precedence decides.
458 func operand(_ e: String) -> String { Int.random(in: 0..<10, using: &generator) < 7 ? e : "(\(e))" }
459 func expression(_ depth: Int) -> String {
460 if depth == 0 || Int.random(in: 0..<4, using: &generator) == 0 { return leaf() }
461 switch Int.random(in: 0..<10, using: &generator) {
462 case 0..<4:
463 let f = unary.randomElement(using: &generator)!
464 return f == "!" || f == "-" ? f + operand(expression(depth - 1)) : "\(f)(\(expression(depth - 1)))"
465 case 4..<8:
466 let f = binary.randomElement(using: &generator)!
467 let (a, b) = (expression(depth - 1), f == "^" ? ["2", "3", "-1", "0.5", "x"].randomElement(using: &generator)! : expression(depth - 1))
468 return f.first!.isLetter ? "\(f)(\(a), \(b))" : "\(operand(a)) \(f) \(operand(b))"
469 case 8:
470 return "if(\(expression(depth - 1)), \(expression(depth - 1)), \(expression(depth - 1)))"
471 default:
472 let items = (0..<Int.random(in: 0...3, using: &generator)).map { _ in expression(depth - 1) }
473 return "\(["vmax", "vmin"].randomElement(using: &generator)!)([\(items.joined(separator: ", "))], [\(expression(depth - 1))])"
474 }
475 }
476 let formats = ["(float 8)", "(float 8)", "(fix 2)", "(fix 0)", "(eng 2)"]
477 for _ in 0..<4000 { cases.append((expression(4), formats.randomElement(using: &generator)!)) }
478 let skipped = try Self.compare(cases, note: " seed \(seed)")
479 #expect(Set(skipped).intersection(Self.symbolicFunctions) == [], "\(skipped)")
480 #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused, seed \(seed)")
481 }
482
483 /// Calc prints a float zero, in a formula too, under fix 0 as `0e0`.
484 @Test func floatZeroInFixZero() throws {
485 var modes = Calc.Modes()
486 modes.format = .fix(0)
487 for (e, expected) in [("max(x, 0.)", "max(x, 0e0)"), ("x < 0.", "x < 0e0"), ("if(x, 0., 1)", "x ? 0e0 : 1"),
488 ("x / 0.", "x / 0e0"), ("0.", "0e0"), ("max(x, 0)", "max(x, 0)")] {
489 #expect(try Calc.evaluate(e, modes: modes) == expected, "\(e)")
490 }
491 }
492
418 @Test func unsupported() throws { 493 @Test func unsupported() throws {
419 for e in ["vsum([5 kg])", "vsum([1 2])", "vcount([N A])", "vsum([2 3 4])", "vsum([1 1/2])", "vmin([3 4])", 494 for e in ["vsum([5 kg])", "vsum([1 2])", "vcount([N A])", "vsum([2 3 4])", "vsum([1 1/2])", "vmin([3 4])",
420 "vcount([f (x)])", "vcount([1 [2]])", "vcount([(1) 2])", "vcount([1 sin (2)])", "1.2.3e5", 495 "vcount([f (x)])", "vcount([1 [2]])", "vcount([(1) 2])", "vcount([1 sin (2)])", "1.2.3e5",
421 "sqrt(x)", "vmax([x,1])", "vsum(x,1)", "x<1", "if(x,1,2)", "x%2", "x_1", "x'", "Holidays+1", "café+1", 496 "sqrt(-inf)", "vmax([x,1],2)", "!!x", "if(x,sqrt(4),1)", "eq(x,y,z)", "vsum(x,1)", "x_1", "x'", "Holidays+1", "café+1",
422 "x+<2026-10-05 Mon>", "[x,1]", "vcount([x -1])", "(1/0)+1", "vmean([])", "(-8)^(1/3)", "vvar([5])", "1<2<3", 497 "x+<2026-10-05 Mon>", "[x,1]", "vcount([x -1])", "(1/0)+1", "vmean([])", "(-8)^(1/3)", "vvar([5])", "1<2<3",
423 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])", 498 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
424 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)", 499 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
@@ -458,7 +533,7 @@ struct CalcTests {
458 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"] { 533 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"] {
459 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, numeric: true) } 534 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, numeric: true) }
460 } 535 }
461 for e in ["-x", "x*2", "2 x", "x*y", "x+x", "x+2-2", "nan"] { 536 for e in ["-x", "x*2", "2 x", "x*y", "x+x", "x+2-2", "nan", "x<1", "x && 1", "!x"] {
462 #expect(throws: Calc.Failure("Number expected"), "\(e)") { try Calc.evaluate(e, numeric: true) } 537 #expect(throws: Calc.Failure("Number expected"), "\(e)") { try Calc.evaluate(e, numeric: true) }
463 } 538 }
464 #expect(try Calc.evaluate("x/x", numeric: true) == "1") 539 #expect(try Calc.evaluate("x/x", numeric: true) == "1")
@@ -469,7 +544,7 @@ struct CalcTests {
469 } 544 }
470 var symbolic = Calc.Modes() 545 var symbolic = Calc.Modes()
471 symbolic.symbolic = true 546 symbolic.symbolic = true
472 for e in ["sqrt(2)", "2^0.5", "ln(2)", "x^0.5"] { 547 for e in ["sqrt(2)", "2^0.5", "ln(2)", "x^0.5", "sqrt(x)", "exp(x)"] {
473 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, modes: symbolic) } 548 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, modes: symbolic) }
474 } 549 }
475 } 550 }
@@ -477,7 +552,7 @@ struct CalcTests {
477 /// `;S`: what is computed matches; functions and powers that may not be exact are refused. 552 /// `;S`: what is computed matches; functions and powers that may not be exact are refused.
478 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 553 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
479 func symbolicModeMatchesCalc() throws { 554 func symbolicModeMatchesCalc() throws {
480 let cases = (Self.fixed + Self.functions + Self.symbolic).map { ($0, "(float 8)") } 555 let cases = (Self.fixed + Self.functions + Self.symbolic + Self.symbolicFunctions).map { ($0, "(float 8)") }
481 let skipped = try Self.compare(cases, symbolic: true) 556 let skipped = try Self.compare(cases, symbolic: true)
482 #expect(Set(skipped).isDisjoint(with: ["1/3", "x+5", "1/0", "2 pi", "vmean([x,2,3])", "sin(30)", "x^2", "round(2.5)"])) 557 #expect(Set(skipped).isDisjoint(with: ["1/3", "x+5", "1/0", "2 pi", "vmean([x,2,3])", "sin(30)", "x^2", "round(2.5)"]))
483 #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused") 558 #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused")
Tests/OrgCoreTests/TableFormulaEntryTests.swift +4 −4
@@ -94,12 +94,12 @@ extension TableFormulaEntryTests {
94 #expect(removed.text == "| a | b |\n|---+---|\n| 1 | 2 |\n#+TBLFM: \n" && removed.message == "Formula removed", "\(removed)") 94 #expect(removed.text == "| a | b |\n|---+---|\n| 1 | 2 |\n#+TBLFM: \n" && removed.message == "Formula removed", "\(removed)")
95 // A function of a field holding text 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 // still moves on. 96 // still moves on.
97 let symbolic = "| a | b |\n| x | =sqrt($1) |\n| y | |\n" 97 let symbolic = "| a | b |\n| x | =floor($1) |\n| y | |\n"
98 let tab = try #require(committed(TableCommand(.nextField), symbolic, after: "($1)")) 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)") 99 #expect(tab.text == "| a | b |\n| x | =floor($1) |\n| y | |\n#+TBLFM: $2=floor($1)\n", "\(tab.text.debugDescription)")
100 #expect(tab.caret == (tab.text as NSString).range(of: "| y").location + 2) 100 #expect(tab.caret == (tab.text as NSString).range(of: "| y").location + 2)
101 #expect(tab.message?.hasPrefix("The formula was stored; recalculating it needs Emacs") == true) 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": "sqrt($1)"])) 102 let prompted = try #require(committed(TableEvalFormula(named: false), symbolic, after: "| x", answers: ["formula": "floor($1)"]))
103 #expect(prompted.text.hasSuffix("#+TBLFM: $1=sqrt($1)\n") && prompted.message != nil, "\(prompted)") 103 #expect(prompted.text.hasSuffix("#+TBLFM: $1=floor($1)\n") && prompted.message != nil, "\(prompted)")
104 } 104 }
105} 105}
Tests/OrgCoreTests/TableFormulaTests.swift +8
@@ -97,6 +97,14 @@ struct TableFormulaTests {
97 "| r | area | half |\n|---+------+------|\n| 3 | | |\n| x | | |\n#+TBLFM: $2=$1^2*pi::$3=$2/2;S\n", 97 "| r | area | half |\n|---+------+------|\n| 3 | | |\n| x | | |\n#+TBLFM: $2=$1^2*pi::$3=$2/2;S\n",
98 "| 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 | d |\n|---+---+---+---|\n| 1 | | n/a | |\n| 2 | 3 | | |\n#+TBLFM: $4=vsum($1..$3)::@2$2=$1 + inf;S\n",
99 "| a | b | c |\n|---+---+---|\n| x | 1 | |\n| | 2 | |\n#+TBLFM: $3=$1*$2;E\n", 99 "| a | b | c |\n|---+---+---|\n| x | 1 | |\n| | 2 | |\n#+TBLFM: $3=$1*$2;E\n",
100 // Functions of text fields.
101 "| name | q1 | q2 | q3 | best | worst |\n|------+----+----+----+------+-------|\n| ann | 5 | 7 | 6 | | |\n| bob | 4 | absent | 8 | | |\n| cy | | 2.5 | 1 | | |\n#+TBLFM: $5=vmax($2..$4)::$6=vmin($2..$4)\n",
102 "| item | qty | status | flag |\n|------+-----+--------+------|\n| a | 12 | | |\n| b | n/a | | |\n| c | 3 | | |\n| d | TBD | | |\n#+TBLFM: $3=if($2 > 10, 1, 0)::$4=$2 >= 3 && $2 != 12\n",
103 "| x | abs | root | low | mod |\n|---+-----+------+-----+-----|\n| -4 | | | | |\n| TBD | | | | |\n| 9 | | | | |\n#+TBLFM: $2=abs($1)::$3=sqrt(abs($1))::$4=min($1, 5)::$5=$1 % 4\n",
104 "| a | b | same | e | ln |\n|---+---+------+---+----|\n| N/A | N/A | | | |\n| 1 | 2 | | | |\n| x | y | | | |\n#+TBLFM: $3=$1 == $2::$4=exp($1)::$5=ln($2)\n",
105 "| a | not | below |\n|---+-----+-------|\n| TBD | | |\n| 2 | | |\n#+TBLFM: $2=!$1 + 1::$3=!$1 < 1\n",
106 "| a | b | c |\n|---+---+---|\n| TBD | -3 | |\n#+TBLFM: $3=if($1 > 0, -$2, 0)\n",
107 "| a | b | c | d | max | min |\n|---+---+---+---+-----+-----|\n| | | TBD | 1 | | |\n#+TBLFM: $5=vmax($1..$2, $3..$4)::$6=vmin($1..$2, $3..$4)\n",
100 // Calc rejects a number with two points. 108 // Calc rejects a number with two points.
101 "| a | b |\n|---+---|\n| 21.11.2026 | |\n| 192.168.1.1 | |\n| 1.5 | |\n#+TBLFM: $2=$1+1\n", 109 "| a | b |\n|---+---|\n| 21.11.2026 | |\n| 192.168.1.1 | |\n| 1.5 | |\n#+TBLFM: $2=$1+1\n",
102 "| a | b |\n|---+---|\n| 21.11.2026 | |\n#+TBLFM: $2=$1+1;T\n", 110 "| a | b |\n|---+---|\n| 21.11.2026 | |\n#+TBLFM: $2=$1+1;T\n",
Tests/OrgProgramsTests/ProgramsTests.swift +4 −4
@@ -23,7 +23,7 @@ struct EmacsFallbackTests {
23 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 23 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
24 func recalculatesTablesNativeCodeCannot() async throws { 24 func recalculatesTablesNativeCodeCannot() async throws {
25 let notes = try Folder() 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=sqrt($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=floor($2)\n")
27 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) 27 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
28 session.open(file.path) 28 session.open(file.path)
29 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil) 29 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil)
@@ -31,11 +31,11 @@ struct EmacsFallbackTests {
31 Issue.record("\(step)") 31 Issue.record("\(step)")
32 return 32 return
33 } 33 }
34 #expect(reason == "function sqrt of a formula") 34 #expect(reason == "function floor of a formula")
35 #expect(!lisp) 35 #expect(!lisp)
36 let message = await session.recalculateInEmacs(table: table, point: point, form: form) 36 let message = await session.recalculateInEmacs(table: table, point: point, form: form)
37 #expect(message == "Recalculated in Emacs") 37 #expect(message == "Recalculated in Emacs")
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") 38 #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+----------|\n| x | a | floor(a) |\n| y | 2 | 2 |\n#+TBLFM: $3=floor($2)\n")
39 } 39 }
40 40
41 /// `elisp:` links run in Emacs, in a copy of the file with point at the caret; in 41 /// `elisp:` links run in Emacs, in a copy of the file with point at the caret; in
@@ -96,7 +96,7 @@ struct EmacsFallbackTests {
96 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 96 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
97 func cancelingARecalculationLeavesTheTable() async throws { 97 func cancelingARecalculationLeavesTheTable() async throws {
98 let notes = try Folder() 98 let notes = try Folder()
99 let text = "| n | twice |\n|---+-------|\n| a | |\n#+TBLFM: $2=sqrt($1)\n" 99 let text = "| n | twice |\n|---+-------|\n| a | |\n#+TBLFM: $2=floor($1)\n"
100 let file = try notes.write("t.org", text) 100 let file = try notes.write("t.org", text)
101 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) 101 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
102 session.open(file.path) 102 session.open(file.path)
docs/manual/guide/10-tables.org +10 −4
@@ -321,7 +321,6 @@ side if it is nonzero, else the right side):
321| Operator | Meaning | 321| Operator | Meaning |
322|------------------------------------+-----------------------------------------------------------| 322|------------------------------------+-----------------------------------------------------------|
323| =&&= | Logical and: the left side if it is zero, else the right side. | 323| =&&= | Logical and: the left side if it is zero, else the right side. |
324| =!= | Logical not. |
325| ~==~, ~!=~, =<=, =>=, ~<=~, ~>=~ | Comparisons, giving 1 or 0. They can't be chained. | 324| ~==~, ~!=~, =<=, =>=, ~<=~, ~>=~ | Comparisons, giving 1 or 0. They can't be chained. |
326| =+=, =-= | Addition and subtraction. | 325| =+=, =-= | Addition and subtraction. |
327| =/=, =%=, =\= | Division, modulo (sign of the divisor), integer division rounding down. | 326| =/=, =%=, =\= | Division, modulo (sign of the divisor), integer division rounding down. |
@@ -329,6 +328,7 @@ side if it is nonzero, else the right side):
329| unary =-= | Negation. | 328| unary =-= | Negation. |
330| =^= | Power. | 329| =^= | Power. |
331| =!=, =!!= after a value | Factorial, double factorial. | 330| =!=, =!!= after a value | Factorial, double factorial. |
331| =!= before a value | Logical not: =!x^2= is =(!x)^2= and =!x + 1= is =(!x) + 1=. |
332| =%= after a value | Percent: =5%= is =0.05=. Followed by a value, =%= is modulo instead. | 332| =%= after a value | Percent: =5%= is =0.05=. Followed by a value, =%= is modulo instead. |
333 333
334Parentheses group, =[a, b, c]= writes a vector, =<2026-10-05 Mon>= writes a date, and 334Parentheses group, =[a, b, c]= writes a vector, =<2026-10-05 Mon>= writes a date, and
@@ -388,9 +388,15 @@ sums, differences, products, quotients and powers:
388- =inf=, =-inf= and =uinf= (infinity of unknown sign) follow Calc's rules: =inf - inf= is 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=. 389 =nan=, =1/inf= is =0=, =2^inf= is =inf=.
390- =vsum=, =vprod=, =vmean= and =vcount= take vectors holding such formulas. 390- =vsum=, =vprod=, =vmean= and =vcount= take vectors holding such formulas.
391 391- =sqrt=, =abs=, =exp=, =ln=, =min=, =max=, =vmax=, =vmin= and =%= simplify a formula
392Other functions of a formula, comparisons and conditions on one, and complex results 392 as Calc does, or keep it: =abs(-x)= is =abs(x)=, =sqrt(4 x)= is =2 sqrt(x)=,
393need Emacs. 393 =vmax($2..$4)= over 4, =absent= and 8 is =max(max(4, absent), 8)=, and =x % 3= stays.
394- Comparisons, =&&=, =||=, =!= and =if= on a formula give a formula unless Calc can
395 decide them: =x == x= is 1, =$2 > 10= with =TBD= in =$2= is =TBD > 10=, and
396 =if($2 > 10, 1, 0)= is =TBD > 10 ? 1 : 0=.
397
398Other functions of a formula, =sqrt=, =exp= and =ln= of one under the =S= flag, and
399complex results such as =sqrt(-inf)= need Emacs.
394 400
395** Mode flags and formats 401** Mode flags and formats
396 402