Commit 537216e8fd
Verified · cmc
Layout: unified · split
Sources/OrgCore/Compute/Calc.swift +41 −17
| @@ -479,6 +479,15 @@ public enum Calc { | ||
| 479 | 479 | static func compare(_ a: Value, _ b: Value) throws -> Int { |
| 480 | 480 | if case .date(let x) = a, case .date(let y) = b { return try compare(x, y) } |
| 481 | 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 | 491 | let difference = try add(a, try negate(b)) |
| 483 | 492 | let (m, _) = try parts(difference) |
| 484 | 493 | return m == 0 ? 0 : (m < 0 ? -1 : 1) |
| @@ -1116,7 +1125,7 @@ public enum Calc { | ||
| 1116 | 1125 | return true |
| 1117 | 1126 | } |
| 1118 | 1127 | |
| 1119 | // `||` < `&&` < `!` < comparisons < sums. | |
| 1128 | // `||` < `&&` < comparisons < sums. | |
| 1120 | 1129 | mutating func or() throws -> Node { |
| 1121 | 1130 | var left = try and() |
| 1122 | 1131 | while take("||") { left = .binary("|", left, try and()) } |
| @@ -1124,21 +1133,11 @@ public enum Calc { | ||
| 1124 | 1133 | } |
| 1125 | 1134 | |
| 1126 | 1135 | 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()) } | |
| 1129 | 1138 | return left |
| 1130 | 1139 | } |
| 1131 | 1140 | |
| 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 | ||
| 1142 | 1141 | mutating func comparison() throws -> Node { |
| 1143 | 1142 | let left = try sum() |
| 1144 | 1143 | // Calc reads `<<` and `>>` as one token, so `1<<2026-10-05 Mon>` is a syntax error. |
| @@ -1211,8 +1210,25 @@ public enum Calc { | ||
| 1211 | 1210 | return try powerNode() |
| 1212 | 1211 | } |
| 1213 | 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 | ||
| 1214 | 1230 | mutating func powerNode() throws -> Node { |
| 1215 | var base = try primary() | |
| 1231 | var base = try not() ?? primary() | |
| 1216 | 1232 | // Postfix `%` (percent), `!` and `!!`, which bind tighter than `^`. |
| 1217 | 1233 | while let c = peek() { |
| 1218 | 1234 | let next = i + 1 < chars.count ? chars[i + 1] : nil |
| @@ -1460,9 +1476,13 @@ public enum Calc { | ||
| 1460 | 1476 | if Symbolic.functions.contains(name), !values.contains(where: isVector) { |
| 1461 | 1477 | return value(try Symbolic.function(name, try values.map(term))) |
| 1462 | 1478 | } |
| 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. | |
| 1464 | 1481 | 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 | } | |
| 1466 | 1486 | return try extra(2) { |
| 1467 | 1487 | value(try items.dropFirst().reduce(items[0]) { try Symbolic.function(name == "vmax" ? "max" : "min", [$0, $1]) }) |
| 1468 | 1488 | } |
| @@ -1489,7 +1509,11 @@ public enum Calc { | ||
| 1489 | 1509 | func literal(_ node: Node) throws -> Term { |
| 1490 | 1510 | switch node { |
| 1491 | 1511 | 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]) | |
| 1493 | 1517 | case .binary(let op, let a, let b) where "+-*/^".contains(op): return .op(String(op), [try literal(a), try literal(b)]) |
| 1494 | 1518 | default: throw Unsupported("condition") |
| 1495 | 1519 | } |
Tests/OrgCoreTests/CalcTests.swift +38 −14
| @@ -231,7 +231,7 @@ struct CalcTests { | ||
| 231 | 231 | /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the |
| 232 | 232 | /// cases `Calc.evaluate` doesn't support. |
| 233 | 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 | 235 | let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name, symbolic: symbolic, radians: radians, fractions: fractions) |
| 236 | 236 | #expect(emacs.count == cases.count) |
| 237 | 237 | var skipped: [String] = [] |
| @@ -257,7 +257,7 @@ struct CalcTests { | ||
| 257 | 257 | if !expected.hasPrefix("LISP ERROR") { skipped.append(c.0) } |
| 258 | 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 | 262 | return skipped |
| 263 | 263 | } |
| @@ -428,42 +428,66 @@ struct CalcTests { | ||
| 428 | 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 | 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 | 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])", | |
| 431 | 439 | ] |
| 432 | 440 | |
| 433 | 441 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) |
| 434 | 442 | func symbolicFunctionsMatchCalc() throws { |
| 435 | 443 | 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 | } | |
| 438 | 448 | } |
| 439 | 449 | // Generated: the functions applied to formulas of a variable or two and numbers, and |
| 440 | 450 | // 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) | |
| 442 | 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"] |
| 443 | let unary = ["sqrt", "abs", "exp", "ln", "!"] | |
| 454 | let unary = ["sqrt", "abs", "exp", "ln", "!", "-"] | |
| 444 | 455 | let binary = ["min", "max", "%", "<", ">", "<=", ">=", "==", "!=", "&&", "||", "+", "-", "*", "/", "^"] |
| 445 | 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))" } | |
| 446 | 459 | func expression(_ depth: Int) -> String { |
| 447 | 460 | if depth == 0 || Int.random(in: 0..<4, using: &generator) == 0 { return leaf() } |
| 448 | 461 | switch Int.random(in: 0..<10, using: &generator) { |
| 449 | 462 | case 0..<4: |
| 450 | 463 | 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)))" | |
| 452 | 465 | case 4..<8: |
| 453 | 466 | let f = binary.randomElement(using: &generator)! |
| 454 | 467 | 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))" | |
| 456 | 469 | case 8: |
| 457 | return "if(\(expression(depth - 1)), \(leaf()), \(leaf()))" | |
| 470 | return "if(\(expression(depth - 1)), \(expression(depth - 1)), \(expression(depth - 1)))" | |
| 458 | 471 | 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))])" | |
| 461 | 474 | } |
| 462 | 475 | } |
| 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)") | |
| 465 | 479 | #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 | } | |
| 467 | 491 | } |
| 468 | 492 | |
| 469 | 493 | @Test func unsupported() throws { |
Tests/OrgCoreTests/TableFormulaTests.swift +3
| @@ -102,6 +102,9 @@ struct TableFormulaTests { | ||
| 102 | 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 | 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 | 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", | |
| 105 | 108 | // Calc rejects a number with two points. |
| 106 | 109 | "| a | b |\n|---+---|\n| 21.11.2026 | |\n| 192.168.1.1 | |\n| 1.5 | |\n#+TBLFM: $2=$1+1\n", |
| 107 | 110 | "| 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): | ||
| 321 | 321 | | Operator | Meaning | |
| 322 | 322 | |------------------------------------+-----------------------------------------------------------| |
| 323 | 323 | | =&&= | Logical and: the left side if it is zero, else the right side. | |
| 324 | | =!= | Logical not. | | |
| 325 | 324 | | ~==~, ~!=~, =<=, =>=, ~<=~, ~>=~ | Comparisons, giving 1 or 0. They can't be chained. | |
| 326 | 325 | | =+=, =-= | Addition and subtraction. | |
| 327 | 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 | 328 | | unary =-= | Negation. | |
| 330 | 329 | | =^= | Power. | |
| 331 | 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 | 332 | | =%= after a value | Percent: =5%= is =0.05=. Followed by a value, =%= is modulo instead. | |
| 333 | 333 | |
| 334 | 334 | Parentheses group, =[a, b, c]= writes a vector, =<2026-10-05 Mon>= writes a date, and |