Commit 537216e8fd

537216e8fd5223a2a3620d16b08e418a649daffc

parent: e012e27afe

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 19:51 UTC

Match Calc's prefix !, negated branch numbers and empty vmax vectors

Also print zero in fix 0 as 0e0, compare fractions with floats as
math-compare does, and seed the generated Calc cases with bare operands,
expression branches and fix 0 and eng formats.

Layout: unified · split

Sources/OrgCore/Compute/Calc.swift +41 −17
@@ -479,6 +479,15 @@ public enum Calc {
479479 static func compare(_ a: Value, _ b: Value) throws -> Int {
480480 if case .date(let x) = a, case .date(let y) = b { return try compare(x, y) }
481481 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 }
482491 let difference = try add(a, try negate(b))
483492 let (m, _) = try parts(difference)
484493 return m == 0 ? 0 : (m < 0 ? -1 : 1)
@@ -1116,7 +1125,7 @@ public enum Calc {
11161125 return true
11171126 }
11181127
1119 // `||` < `&&` < `!` < comparisons < sums.
1128 // `||` < `&&` < comparisons < sums.
11201129 mutating func or() throws -> Node {
11211130 var left = try and()
11221131 while take("||") { left = .binary("|", left, try and()) }
@@ -1124,21 +1133,11 @@ public enum Calc {
11241133 }
11251134
11261135 mutating func and() throws -> Node {
1127 var left = try not()
1128 while take("&&") { left = .binary("&", left, try not()) }
1136 var left = try comparison()
1137 while take("&&") { left = .binary("&", left, try comparison()) }
11291138 return left
11301139 }
11311140
1132 mutating func not() throws -> Node {
1133 if peek() == "!", i + 1 >= chars.count || chars[i + 1] != "=" {
1134 // Calc reads `!!` as one token.
1135 if i + 1 < chars.count, chars[i + 1] == "!" { throw Unsupported("formula syntax") }
1136 i += 1
1137 return .unary("!", try not())
1138 }
1139 return try comparison()
1140 }
1141
11421141 mutating func comparison() throws -> Node {
11431142 let left = try sum()
11441143 // Calc reads `<<` and `>>` as one token, so `1<<2026-10-05 Mon>` is a syntax error.
@@ -1211,8 +1210,25 @@ public enum Calc {
12111210 return try powerNode()
12121211 }
12131212
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
12141230 mutating func powerNode() throws -> Node {
1215 var base = try primary()
1231 var base = try not() ?? primary()
12161232 // Postfix `%` (percent), `!` and `!!`, which bind tighter than `^`.
12171233 while let c = peek() {
12181234 let next = i + 1 < chars.count ? chars[i + 1] : nil
@@ -1460,9 +1476,13 @@ public enum Calc {
14601476 if Symbolic.functions.contains(name), !values.contains(where: isVector) {
14611477 return value(try Symbolic.function(name, try values.map(term)))
14621478 }
1463 // `math-reduce-many-vecs`: `max` of the elements in turn.
1479 // `math-reduce-many-vecs`: `max` of the elements in turn, starting from
1480 // -inf (`inf` for `min`) when the first vector is empty.
14641481 if name == "vmax" || name == "vmin", values.allSatisfy(isVector) {
1465 let items = try elements(values).map(term)
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 }
14661486 return try extra(2) {
14671487 value(try items.dropFirst().reduce(items[0]) { try Symbolic.function(name == "vmax" ? "max" : "min", [$0, $1]) })
14681488 }
@@ -1489,7 +1509,11 @@ public enum Calc {
14891509 func literal(_ node: Node) throws -> Term {
14901510 switch node {
14911511 case .number, .variable: return try term(try eval(node))
1492 case .unary("-", let a): return .op("neg", [try literal(a)])
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])
14931517 case .binary(let op, let a, let b) where "+-*/^".contains(op): return .op(String(op), [try literal(a), try literal(b)])
14941518 default: throw Unsupported("condition")
14951519 }
Tests/OrgCoreTests/CalcTests.swift +38 −14
@@ -231,7 +231,7 @@ struct CalcTests {
231231 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the
232232 /// cases `Calc.evaluate` doesn't support.
233233 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] {
235235 let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name, symbolic: symbolic, radians: radians, fractions: fractions)
236236 #expect(emacs.count == cases.count)
237237 var skipped: [String] = []
@@ -257,7 +257,7 @@ struct CalcTests {
257257 if !expected.hasPrefix("LISP ERROR") { skipped.append(c.0) }
258258 continue
259259 }
260 #expect(ours == expected, "\(c.0) \(c.1) p\(precision)")
260 #expect(ours == expected, "\(c.0) \(c.1) p\(precision)\(note)")
261261 }
262262 return skipped
263263 }
@@ -428,42 +428,66 @@ struct CalcTests {
428428 "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",
429429 "2%inf", "x%inf", "x % y % z", "(x % y) * 2", "-x % y", "vmax([x,1])", "vmin([x,1,2])", "vmax([1,2,x])",
430430 "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])",
431439 ]
432440
433441 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
434442 func symbolicFunctionsMatchCalc() throws {
435443 var cases = Self.symbolicFunctions.map { ($0, "(float 8)") }
436 for format in ["(fix 2)", "(sci 3)"] {
437 for e in ["sqrt(2 x)", "max(x, 2.5)", "if(x, 1.5, 2)", "x % 0.5", "vmin([x, 1:3, 0.25])"] { cases.append((e, format)) }
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 }
438448 }
439449 // Generated: the functions applied to formulas of a variable or two and numbers, and
440450 // their results combined again. What is refused is left to Emacs.
441 var generator = SystemRandomNumberGenerator()
451 let seed = ProcessInfo.processInfo.environment["ORGSTAR_SEED"].flatMap { UInt64($0) } ?? UInt64.random(in: 0...UInt64.max)
452 var generator = SeededGenerator(state: seed)
442453 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"]
443 let unary = ["sqrt", "abs", "exp", "ln", "!"]
454 let unary = ["sqrt", "abs", "exp", "ln", "!", "-"]
444455 let binary = ["min", "max", "%", "<", ">", "<=", ">=", "==", "!=", "&&", "||", "+", "-", "*", "/", "^"]
445456 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))" }
446459 func expression(_ depth: Int) -> String {
447460 if depth == 0 || Int.random(in: 0..<4, using: &generator) == 0 { return leaf() }
448461 switch Int.random(in: 0..<10, using: &generator) {
449462 case 0..<4:
450463 let f = unary.randomElement(using: &generator)!
451 return f == "!" ? "!(\(expression(depth - 1)))" : "\(f)(\(expression(depth - 1)))"
464 return f == "!" || f == "-" ? f + operand(expression(depth - 1)) : "\(f)(\(expression(depth - 1)))"
452465 case 4..<8:
453466 let f = binary.randomElement(using: &generator)!
454467 let (a, b) = (expression(depth - 1), f == "^" ? ["2", "3", "-1", "0.5", "x"].randomElement(using: &generator)! : expression(depth - 1))
455 return f.first!.isLetter ? "\(f)(\(a), \(b))" : "(\(a)) \(f) (\(b))"
468 return f.first!.isLetter ? "\(f)(\(a), \(b))" : "\(operand(a)) \(f) \(operand(b))"
456469 case 8:
457 return "if(\(expression(depth - 1)), \(leaf()), \(leaf()))"
470 return "if(\(expression(depth - 1)), \(expression(depth - 1)), \(expression(depth - 1)))"
458471 default:
459 let items = (0..<Int.random(in: 1...3, using: &generator)).map { _ in expression(depth - 1) }
460 return "\(["vmax", "vmin"].randomElement(using: &generator)!)([\(items.joined(separator: ", "))])"
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))])"
461474 }
462475 }
463 for _ in 0..<4000 { cases.append((expression(4), "(float 8)")) }
464 let skipped = try Self.compare(cases)
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)")
465479 #expect(Set(skipped).intersection(Self.symbolicFunctions) == [], "\(skipped)")
466 #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused")
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 }
467491 }
468492
469493 @Test func unsupported() throws {
Tests/OrgCoreTests/TableFormulaTests.swift +3
@@ -102,6 +102,9 @@ struct TableFormulaTests {
102102 "| 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",
103103 "| 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",
104104 "| 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",
105108 // Calc rejects a number with two points.
106109 "| a | b |\n|---+---|\n| 21.11.2026 | |\n| 192.168.1.1 | |\n| 1.5 | |\n#+TBLFM: $2=$1+1\n",
107110 "| a | b |\n|---+---|\n| 21.11.2026 | |\n#+TBLFM: $2=$1+1;T\n",
docs/manual/guide/10-tables.org +1 −1
@@ -321,7 +321,6 @@ side if it is nonzero, else the right side):
321321| Operator | Meaning |
322322|------------------------------------+-----------------------------------------------------------|
323323| =&&= | Logical and: the left side if it is zero, else the right side. |
324| =!= | Logical not. |
325324| ~==~, ~!=~, =<=, =>=, ~<=~, ~>=~ | Comparisons, giving 1 or 0. They can't be chained. |
326325| =+=, =-= | Addition and subtraction. |
327326| =/=, =%=, =\= | Division, modulo (sign of the divisor), integer division rounding down. |
@@ -329,6 +328,7 @@ side if it is nonzero, else the right side):
329328| unary =-= | Negation. |
330329| =^= | Power. |
331330| =!=, =!!= after a value | Factorial, double factorial. |
331| =!= before a value | Logical not: =!x^2= is =(!x)^2= and =!x + 1= is =(!x) + 1=. |
332332| =%= after a value | Percent: =5%= is =0.05=. Followed by a value, =%= is modulo instead. |
333333
334334Parentheses group, =[a, b, c]= writes a vector, =<2026-10-05 Mon>= writes a date, and