Tests/OrgCoreTests/CalcTests.swift

design-themes-widgets
orgstar/Tests/OrgCoreTests/CalcTests.swift history · blame · raw

568 lines · 44034 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5/// Runs `calc-eval` with org's table modes over a list of expressions.
  6enum CalcOracle {
  7    static func run(_ cases: [(expression: String, format: String)], precision: Int = 12, zone: String = "UTC", symbolic: Bool = false,
  8                    radians: Bool = false, fractions: Bool = false) throws -> [String] {
  9        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)")
 10        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 11        defer { try? FileManager.default.removeItem(at: folder) }
 12        let input = folder.appendingPathComponent("input.json")
 13        let output = folder.appendingPathComponent("output.json")
 14        let script = folder.appendingPathComponent("calc.el")
 15        try JSONSerialization.data(withJSONObject: cases.map { [$0.expression, $0.format] }).write(to: input)
 16        try #"""
 17        ;;; -*- lexical-binding: t -*-
 18        (require 'calc)
 19        (require 'org-table)
 20        (require 'json)
 21        (let* ((cases (with-temp-buffer
 22                        (insert-file-contents (getenv "ORACLE_INPUT"))
 23                        (json-parse-buffer :array-type 'list)))
 24               (results
 25                (mapcar (lambda (c)
 26                          (let* ((modes (copy-sequence org-calc-default-modes))
 27                                 (format (car (read-from-string (nth 1 c)))))
 28                            (setq modes (plist-put modes 'calc-float-format format))
 29                            (setq modes (plist-put modes 'calc-internal-prec (string-to-number (getenv "ORACLE_PREC"))))
 30                            (when (getenv "ORACLE_SYMBOLIC") (setq modes (plist-put modes 'calc-symbolic-mode t)))
 31                            (when (getenv "ORACLE_RADIANS") (setq modes (plist-put modes 'calc-angle-mode 'rad)))
 32                            (when (getenv "ORACLE_FRACTIONS") (setq modes (plist-put modes 'calc-prefer-frac t)))
 33                            (let ((r (condition-case e (calc-eval (cons (car c) modes) nil)
 34                                       (error (format "LISP ERROR %S" e)))))
 35                              (if (stringp r) r (format "ERROR %S" r)))))
 36                        cases)))
 37          (with-temp-file (getenv "ORACLE_OUTPUT")
 38            (insert (json-encode (vconcat results)))))
 39        """#.write(to: script, atomically: true, encoding: .utf8)
 40        _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path, "ORACLE_PREC": String(precision), "TZ": zone]
 41            .merging(symbolic ? ["ORACLE_SYMBOLIC": "1"] : [:]) { $1 }
 42            .merging(radians ? ["ORACLE_RADIANS": "1"] : [:]) { $1 }
 43            .merging(fractions ? ["ORACLE_FRACTIONS": "1"] : [:]) { $1 })
 44        return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
 45    }
 46}
 47
 48struct CalcTests {
 49    static let fixed = [
 50        "1+2", "7/2", "6/3", "1/3", "2/3", "(2)^(0.5)", "sqrt(2)", "sqrt(4)", "sqrt(16.0)", "1.5*2", "3.0", "(3.0)", "2^-1",
 51        "10/4", "1e5", "1e20*1", "123456789*1000", "0.1+0.2", "1/7", "100/7", "1000000/7", "1e10/7", "1e-5/7", "0.001/7",
 52        "0.0001/3", "(1.23456789012345)", "vsum([1,2,3.5])", "vmean([1,2])", "vmean([1,2,4])", "vmax([1,5,3])", "vsum([])",
 53        "vcount([1,2])", "vmedian([1,3,2,4])", "sin(30)", "cos(60)", "tan(45)", "exp(1)", "ln(10)", "log10(1000)", "log10(2)",
 54        "-3", "(-3)*2", "--3", "(+3)", "2*(0)", "2^0.5*2^0.5", "99999999.5*1", "123456785*0.1", "0.5*1e-10", "1.5e3",
 55        "12345678.9*1", "123456789.1*1", "1.25*1", "0.000123*1", "1e100*1e100", "round(2.5)", "floor(2.7)", "abs(-3)",
 56        "max(1,2)", "1.05*3", "2.675*1", "8/2*2", "8/2/2", "2*3/4", "-2^2", "2^3^2", "2^-2", "(-2)^2", "sin(0)", "sin(90)",
 57        "cos(0)", "cos(90)", "tan(0)", "exp(0)", "ln(1)", "log10(1)", "log10(100.0)", "sqrt(2.25)", "sqrt(0)", "arcsin(1)",
 58        "arctan(1)", "arccos(0.5)", "1.5^2", "1.1^10", "0.1^3", "2.5*4", "10/2.5", "1/3*3", "1.0/3", "vmedian([1,3])",
 59        "vmedian([1,2,3])", "vmedian([1.5,2])", "vmean([1.5,2.5])", "vsum([0.1,0.2,0.3])", "vmax([1,2.5])", "vmin([3,1.0])",
 60        "round(-2.5)", "round(2.4)", "round(1.23456,2)", "floor(-2.5)", "ceil(2.1)", "trunc(-2.7)", "abs(-1.5)", "max(1,2.5)",
 61        "min(4,2)", "1e3", "1.e3", "007", "(0.5)", "(.5)", "(5.)", "123456789012*10", "1.23456789012345678", "exp(10)",
 62        "exp(100)", "ln(0.5)", "sqrt(1e-10)", "2.0^2", "0^0", "1-1.0", "0.0", "-0.0", "1.0-1.0", "(-1.5)*(-2)",
 63        "(12)+(3.5)*(2)", "vsum([12,3.5,7])/3", "(1.5)/(0.5)", "(100)*(1.07)^(5)", "(19.99)*(3)", "(0.07)*(19.99)",
 64        "vmean([10,20,25])", "(5)-(7.25)", "(-0.001)*(1000)", "1/(3)", "(2)/(3)*(3)",
 65        // Dates, nan, comparisons and logic, and the rest of the functions tables use.
 66        "<2026-10-05 Mon>+3", "<2026-10-12 Mon>-<2026-10-05 Mon>", "<2026-10-05 Mon 10:00>-<2026-10-05 Mon 08:30>",
 67        "<2026-10-05 Mon 08:30>+0.5", "<2026-10-05 Mon 10:00>+1", "<2026-10-05 Mon 08:30>-<2026-10-04 Sun>", "(<2026-12-31 Thu>)+(1)",
 68        "<2026-03-01 Sun>-30", "1+<2026-10-05 Mon>", "<2026-10-05 Mon 23:59>-<2026-10-05 Mon 00:01>", "<2026-10-05 Mon 12:00>-0.25",
 69        "vmax([<2026-10-05 Mon>,<2026-10-07 Wed>])", "<2026-10-05 Mon> < <2026-10-06 Tue>", "nan", "nan+1", "vsum([1,nan])", "2*nan",
 70        "3<4", "3>4", "3<=3", "4>=5", "2==2", "2!=2", "1 && 0", "1 || 0", "!0", "!2", "if(3>4, 1, 2)", "if($1, 7, 8)".replacingOccurrences(of: "$1", with: "0"),
 71        "if(1.5, 2.5, 3)", "7%3", "-7%3", "7%-3", "7.5%2", "7\\2", "-7\\2", "7.5\\2", "mod(10,4)", "idiv(-9,4)", "fact(5)", "fact(0)",
 72        "vsdev([1,2,3,4])", "vvar([1,2,3])", "vpvar([1,2,3,4])", "vpsdev([2,4,4,4,5,5,7,9])", "vsdev([1.5,2.5,4])",
 73        "2+3<4*2", "1<2 && 3<4", "!(1<2)", "(1<2)+(2<3)",
 74        // Date forms and date functions.
 75        "<2026-10-05 Mon 00:00>", "<2026-10-05 Mon 00:00>+1", "<2026-10-05 Mon 12:00>+0.5", "<2026-10-05 Mon>+1e-9",
 76        "<2026-10-05 Mon>+0.1", "<2026-10-05 Mon>+1:2", "<2026-10-05 Mon 10:00>-1:3", "<2026-10-05 Mon 23:59:59>+0",
 77        "<2026-10-05 Mon>+<2026-10-06 Tue>", "1+<2026-10-05 Mon>+<2026-10-06 Tue>", "<2026-10-05 Mon>+1-<2026-10-01 Thu>",
 78        "-(<2026-10-05 Mon>)+<2026-10-01 Thu>", "0-<2026-10-05 Mon>", "-<2026-10-05 Mon>", "<2026-10-05 Mon>-nan",
 79        "<2026-10-05 Mon>-<2026-10-04 Sun 12:00>", "<2026-10-05 Mon> == <2026-10-05 Mon 00:00>",
 80        "vsum([<2026-10-05 Mon>,1.5])", "vsum([<2026-10-05 Mon 06:00>,0.1])", "vsum([<2026-10-05 Mon>,<2026-10-06 Tue>])",
 81        "vsum([<2026-10-05 Mon>,<2026-10-06 Tue>,<2026-10-10 Sat>])", "vmean([<2026-10-05 Mon>,<2026-10-06 Tue>])",
 82        "vmean([<2026-10-05 Mon 06:00>,<2026-10-05 Mon 12:00>])", "vmin([<2026-10-05 Mon>,<2026-10-07 Wed>])",
 83        "vmax([<2026-10-05 Mon>],[<2026-10-06 Tue>])", "vmin([<2026-10-05 Mon 00:00>,<2026-10-05 Mon>])",
 84        "vcount([<2026-10-05 Mon>])", "max(<2026-10-05 Mon>,<2026-10-06 Tue>)", "abs(<2026-10-05 Mon>)",
 85        "floor(<2026-10-05 Mon 10:30>)", "ceil(<2026-10-05 Mon 13:00>)", "trunc(<2026-10-05 Mon 13:00>)",
 86        "round(<2026-10-05 Mon 13:00>)", "round(<2026-10-05 Mon 11:00>)", "floor(<2026-10-05 Mon>)",
 87        "year(<2026-10-05 Mon>)", "month(<2026-10-05 Mon 10:30>)", "day(<2026-10-05 Mon>)", "weekday(<2026-10-05 Mon>)",
 88        "weekday(<2026-10-05 Mon 10:00>)", "weekday(-1)", "weekday(5)", "hour(<2026-10-05 Mon 10:30>)",
 89        "minute(<2026-10-05 Mon 10:30>)", "second(<2026-10-05 Mon 10:30:45>)", "hour(<2026-10-05 Mon>)",
 90        "yearday(<2026-10-05 Mon>)", "yearday(<2024-12-31 Tue>)", "year(5)", "year(<2026-10-05 Mon>)+1",
 91        "date(2026,10,5)", "date(2026,10,5,10,30,0)", "date(2026,1,1,10)", "date(2026,1,1,10,30)", "date(2026,1,1,25,0,0)",
 92        "date(2026,1,1,10,70,0)", "date(2026,2,31)", "date(2026.,2.,3.)", "date(2026,10,5,0,0,0)", "date(10,5)",
 93        "date(<2026-10-05 Mon>)", "date(<2026-10-05 Mon 06:00>)", "date(<2026-10-05 Mon>)+1", "date(739000)",
 94        "date(739000.5)", "date(739000.)", "date(1:2)", "date(5)", "date(36524)", "date(36890)", "date(365250)",
 95        "date(-5)", "date(-400)", "date(0)", "date(-366)", "date(-367)",
 96        "incmonth(<2026-01-31 Sat>,1)", "incmonth(<2026-10-05 Mon 10:30>,-14)", "incmonth(<2026-10-05 Mon>)",
 97        "incmonth(<2026-10-05 Mon>,2.)", "incmonth(5,1)", "incmonth(<2024-02-29 Thu>,12)", "incmonth(<2026-03-31 Tue>,-1)",
 98        "incmonth(<2026-12-15 Tue>,1)", "incmonth(<2026-01-15 Thu>,-1)", "incmonth(<2026-01-15 Thu>,-25)",
 99        "incmonth(400,-24)", "incmonth(-400,24)", "incyear(<2024-02-29 Thu>,1)", "incyear(<2024-02-29 Thu>,4)",
100        "incyear(<2026-10-05 Mon>)", "incyear(<2026-10-05 Mon>,1.5)", "incyear(<2026-10-05 Mon 08:00>,-3)",
101        "newmonth(<2026-10-15 Thu>)", "newmonth(<2026-02-15 Sun>,31)", "newmonth(<2026-02-15 Sun>,0)",
102        "newmonth(<2026-02-15 Sun 10:00>,5)", "newmonth(<2024-02-15 Thu>,30)", "newmonth(<2026-10-15 Thu>,31)",
103        "newyear(<2026-10-15 Thu>)", "newyear(<2026-10-15 Thu>,0)", "newyear(<2026-10-15 Thu>,-3)",
104        "newyear(<2026-10-15 Thu 10:00>,40)", "newyear(<2024-10-15 Tue>,366)", "newyear(<2026-10-15 Thu>,366)",
105        "newyear(<2026-10-15 Thu>,-12)", "newweek(<2026-10-15 Thu>)", "newweek(<2026-10-15 Thu>,3)",
106        "newweek(<2026-10-15 Thu 10:00>)", "newweek(<2026-10-11 Sun>,1)", "newweek(<2026-10-17 Sat>,6)",
107        "badd(<2026-10-09 Fri>,1)", "badd(<2026-10-10 Sat>,1)", "badd(<2026-10-10 Sat>,-1)", "badd(<2026-10-10 Sat>,0)",
108        "badd(<2026-10-09 Fri 10:00>,2.5)", "badd(1,<2026-10-09 Fri>)", "badd(<2026-10-05 Mon>,10)", "badd(<2026-10-05 Mon>,-10)",
109        "badd(<2026-10-11 Sun>,1)", "badd(<2026-10-11 Sun>,-1)", "badd(<2026-10-05 Mon>,0.5)", "badd(<2026-10-05 Mon>,-0.5)",
110        "bsub(<2026-10-12 Mon>,1)", "bsub(<2026-10-12 Mon>,<2026-10-09 Fri>)", "bsub(<2026-10-11 Sun>,<2026-10-09 Fri>)",
111        "bsub(<2026-10-12 Mon>,<2026-10-10 Sat>)", "bsub(<2026-10-05 Mon>,<2026-10-12 Mon>)",
112        "bsub(<2026-10-12 Mon 12:00>,<2026-10-09 Fri 06:00>)", "bsub(<2026-12-31 Thu>,<2026-01-01 Thu>)",
113        "bsub(<2026-10-10 Sat>,<2026-10-11 Sun>)", "bsub(<2026-10-11 Sun>,<2026-10-10 Sat>)",
114        "julian(<2026-10-05 Mon>)", "julian(<2026-10-05 Mon 12:00>)", "julian(2461319)", "julian(2461319.5)", "julian(1:2)",
115        "unixtime(<2026-10-05 Mon>)", "unixtime(<2026-10-05 Mon 10:30>)", "unixtime(1791158400)", "unixtime(1.5)",
116        "unixtime(0)", "unixtime(-86400)", "unixtime(<1970-01-01 Thu>)",
117        "abs(-<2026-10-05 Mon>)", "abs(date(-1,1,1))", "abs(-<2026-10-05 Mon 06:00>)", "abs(date(1,1,1))",
118        "abs(date(1,1,1)-1.5)", "abs(date(1,1,1)-0.25)",
119        "badd(date(2737,12,30),1)", "badd(date(1,1,3),-1)", "bsub(date(2737,12,31),date(1,1,1))",
120        "<0070-01-01 Thu>", "<0001-01-01 Mon>", "<0010-01-01 Fri>", "<0000-01-01 Sat>", "<0039-12-31 Sat>", "<0040-01-01 Sun>",
121        "<0099-01-01 Fri>", "<0050-06-15 Thu 10:30>", "<0100-01-01 Fri>", "year(<0010-01-01 Fri>)", "unixtime(<0001-01-01 Mon>)",
122    ]
123
124    /// Zones without daylight saving time, as `TZ` names them for Emacs and their offsets.
125    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
126    func datesInFixedZonesMatchCalc() throws {
127        let cases = ["unixtime(<2026-10-05 Mon>)", "unixtime(<2026-10-05 Mon 10:30>)", "unixtime(1791158400)",
128                     "julian(<2026-10-05 Mon 12:00>)", "julian(2461319.5)", "julian(<2026-10-05 Mon>)"].map { ($0, "(float 8)") }
129        for zone in [("EST5", -5 * 3600), ("IST-5:30", 19800)] {
130            let skipped = try Self.compare(cases, zone: zone)
131            #expect(skipped == [], "\(zone.0) \(skipped)")
132        }
133    }
134
135    /// Every function and operator given dates where numbers go: what isn't refused must
136    /// match Calc.
137    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
138    func everythingOnDatesMatchesCalc() throws {
139        let functions = ["vsum", "vprod", "vcount", "vmean", "vmax", "vmin", "vmedian", "if", "vvar", "vpvar", "vsdev", "vpsdev",
140                         "mod", "idiv", "fact", "dfact", "max", "min", "abs", "floor", "ceil", "trunc", "round", "sqrt", "exp", "ln",
141                         "log10", "sin", "cos", "tan", "arcsin", "arccos", "arctan", "eq", "neq", "lt", "gt", "leq", "geq", "land",
142                         "lor", "lnot", "percent", "float", "pfloat", "sign", "rounde", "roundu", "frac", "fdiv", "gcd", "lcm",
143                         "choose", "perm", "pow", "exp10", "nroot", "hypot", "log", "sinh", "cosh", "tanh", "arcsinh", "arccosh",
144                         "arctanh", "arctan2", "deg", "rad", "vflat", "vgmean", "vhmean", "vcov", "vpcov", "vcorr", "agmean", "date",
145                         "year", "month", "day", "hour", "minute", "second", "yearday", "weekday", "newweek", "newmonth", "newyear",
146                         "incmonth", "incyear", "badd", "bsub", "julian", "unixtime"]
147        let (d, t) = ("<2026-10-05 Mon>", "<2026-10-07 Wed 10:30>")
148        var cases: [String] = []
149        for f in functions {
150            for args in [d, t, "\(d),2", "2,\(d)", "\(t),1.5", "\(d),\(t)", "\(t),\(d)", "[\(d),\(t)]", "[\(d),2]", "[\(t)],[\(d)]", "1,\(d),2"] {
151                cases.append("\(f)(\(args))")
152            }
153        }
154        for op in ["+", "-", "*", "/", "%", "\\", "^", "==", "!=", "<", ">", "<=", ">=", "&&", "||"] {
155            cases += ["\(d)\(op)2", "2\(op)\(d)", "\(d)\(op)\(t)", "\(t)\(op)0.5", "\(t)\(op)\(d)", "\(d)\(op)nan"]
156        }
157        cases += ["-\(t)", "!\(d)", "\(d)%", "\(d)!", "\(d) 2", "2 \(d)"]
158        let skipped = try Self.compare(cases.map { ($0, "(float 8)") })
159        #expect(skipped.count < cases.count)
160    }
161
162    @Test func now() throws {
163        var modes = Calc.Modes()
164        modes.timeZone = TimeZone(secondsFromGMT: 3600)!
165        modes.now = Date(timeIntervalSince1970: 1_791_196_245)
166        #expect(try Calc.evaluate("now()", modes: modes) == "<2026-10-05 Mon 11:30>")
167        #expect(try Calc.evaluate("second(now())", modes: modes) == "45")
168        #expect(try Calc.evaluate("date(10,6)-newyear(now())", modes: modes) == "278")
169        modes.now = Date(timeIntervalSince1970: 1_791_158_400 - 3600)
170        #expect(try Calc.evaluate("now()", modes: modes) == "<2026-10-05 Mon 00:00>")
171    }
172
173    /// Constants, functions and syntax that only some tables use.
174    static let functions = [
175        // Grammar: juxtaposition, percent, factorials, fractions and radix integers.
176        "2 3", "2 (3)", "(2)(3)", "2 3 4", "2 3+4", "2*3 4", "-2 3", "2 -3", "2 (3) + 1", "2 .5", "1.5 2", "2 nan", "6/2 3",
177        "5%", "50%*20", "5%+1", "5%3", "5% 3", "(5)%", "12.5%", "1:4%", "100%", "-5%", "2^50%", "5%-1", "5% (2)",
178        "5!", "5!+1", "-5!", "0!", "(3)!", "2^3!", "3!!", "6!!", "0!!", "1!!", "5.!", "20.!", "3! 2", "5! == 120", "5!=120",
179        "1:3", "2:4", "4:2", "-1:3", "1:2:3", "1:0:3", "0:5", "1:3+1", "1:3*0.5", "1:3*3", "2:3^2", "(1:3)",
180        "16#FF", "16#ff", "16#FF+1", "2#101", "8#17", "36#Z", "36#zz", "016#10", "10#99",
181        // Comparisons and logic as functions; `&&` and `||` give an argument.
182        "eq(2,2)", "eq(2,2.0)", "neq(1,2)", "lt(1,2)", "gt(1,2)", "leq(2,2)", "geq(1,2)", "lt(1:3,0.5)",
183        "land(2,3)", "land(0,3)", "lor(0,2.5)", "lor(3,0)", "lnot(0)", "lnot(2.5)", "2 && 3", "0 || 2.5", "1.5 && 0.",
184        "0. || 0", "if(1:2, 1, 2)",
185        // Statistics.
186        "vsum([1,2],[3,4])", "vsum(1,2,3)", "vsum([1,2],3)", "vsum()", "vsum([[1,2],[3]])", "vmax([1,2],[5,3])",
187        "vmax(1,7,3)", "vmin([1,2],[0,3])", "vmean([1,2],[3])", "vmean(1,2)", "vprod([1,2],[3])", "vcount([1,2],3)",
188        "vcount()", "vmedian([1,2],[5])", "vvar([1,2],[3])", "vsdev(1,2,3)", "vpsdev([1,2],[3,4])", "vmax(5)",
189        "vmean(5)", "vsum(vflat([1,[2,3]],4))", "vcount(vflat(1,2,3))", "vgmean([1,2,4])", "vgmean([2,8])",
190        "vgmean([1,2,3])", "vgmean([1.5,2.5])", "vgmean([1:2,2])", "vgmean([0,2])", "vgmean([5])", "vgmean([2,3,4,5])",
191        "vgmean([1,2,3,4,5,6,7,8,9,10,11,12])", "vgmean([1.5,2,2.5,3,3.5])", "vgmean([16,1,1,1])", "vgmean([1:8,1,1])",
192        "vhmean([1,2,4])", "vhmean([1,2])", "vhmean([1.5,2.5])", "vhmean([3])", "vhmean(1,2,3)",
193        "vcov([1,2,3],[1,2,4])", "vpcov([1,2,3],[1,2,4])", "vcorr([1,2,3],[1,2,4])", "vcorr([1,2,3],[3,2,1])",
194        "vcov([1.5,2.5,4],[2,3.5,1])", "vpcov([5],[7])", "vcorr([1,2,3,4],[2,4,5,9])", "vcov([1:2,1,2],[1,2,3])",
195        "agmean(1,2)", "agmean(1,4)", "agmean(2,2)", "agmean(1.5,2)", "agmean(0,3)", "agmean(-1,4)", "agmean(24,6)",
196        // Rounding and fractions.
197        "rounde(2.5)", "rounde(3.5)", "rounde(-2.5)", "rounde(-3.5)", "rounde(2.6)", "rounde(7)", "rounde(5:2)",
198        "rounde(7:2)", "rounde(2.45,1)", "rounde(2.55,1)", "rounde(1234,-2)", "rounde(1250,-2)", "rounde(1:8,2)",
199        "roundu(2.5)", "roundu(-2.5)", "roundu(-2.4)", "roundu(2.45,1)", "roundu(-2.45,1)", "roundu(-5:2)", "roundu(3.)",
200        "fdiv(7,2)", "fdiv(6,3)", "fdiv(1:2,3)", "fdiv(3,1:2)", "fdiv(2:3,4:5)", "fdiv(7.,2)", "fdiv(-7,2)",
201        "frac(2.75)", "frac(-2.75)", "frac(7)", "frac(7:2)", "frac(7.)", "frac(0.1)", "frac(0.333333333333)",
202        "frac(3.14159265359)", "frac(1.5e-3)", "frac(0.142857142857)", "frac(1.5e-11)",
203        "sign(-3)", "sign(0)", "sign(2.5)", "sign(-1:3)", "sign(0.)",
204        "gcd(12,18)", "gcd(-12,18)", "gcd(0,5)", "gcd(12.,18)", "gcd(1:2,1:3)", "gcd(2:3,4)", "gcd(-1:2,3:4)", "gcd(0,0)",
205        "lcm(4,6)", "lcm(-4,6)", "lcm(0,6)", "lcm(1:2,1:3)", "lcm(3,4)",
206        "choose(5,2)", "choose(5,0)", "choose(5,6)", "choose(-5,2)", "choose(-5,3)", "choose(-3,-5)", "choose(-5,-3)",
207        "choose(5,-1)", "choose(52,5)", "choose(60,30)", "perm(5,2)", "perm(5,0)", "perm(5,5)", "perm(20,10)",
208        // Powers, roots and logarithms.
209        "pow(2,10)", "pow(2,0.5)", "pow(2,-1)", "8^(1:3)", "pow(8,1:3)", "4^(3:2)", "pow(4,3:2)", "27^(2:3)", "8^(-1:3)",
210        "2^(1:3)", "2^(1:4)", "16^(3:4)", "2^(2:7)", "2^(1:11)", "1.5^(1:3)", "2^1.5", "2^2.5", "2^0.25", "2^-0.5", "2^2.",
211        "3^2.", "10^2.", "10.^3", "10.^-2.", "0^2", "0^2.", "0.^0", "1:4^(1:2)", "(1:8)^(2:3)", "2^1.1", "0.5^0.75", "exp10(2)", "exp10(-2)", "exp10(0)", "exp10(15)",
212        "nroot(8,3)", "nroot(27,3)", "nroot(10,3)", "nroot(16,4)", "nroot(2.5,2)", "nroot(1:8,3)", "nroot(-8,1)",
213        "nroot(2,4)", "nroot(2,5)", "nroot(100,7)", "nroot(1000,12)", "nroot(3.5,11)", "nroot(2:3,3)", "nroot(0,3)",
214        "nroot(1,5)", "nroot(1024,10)", "nroot(7,6)", "nroot(1e10,9)",
215        "hypot(3,4)", "hypot(1,1)", "hypot(1.5,2)", "hypot(-3,4)", "hypot(0,-2.5)", "hypot(1:3,1:4)", "hypot(5,12)",
216        "log(8,2)", "log(100,10)", "log(10,2)", "log(2.5,1.5)", "log(1,2)", "log(9,3)", "log(1:8,2)", "log(2,8)",
217        "log(8,1:2)", "log(1:4,1:2)", "log(1000,10.)", "log(1.,3)", "log(1,2.)", "log(27,1:3)", "log(10,3)", "log(5)",
218        "log(0.5,2)", "log(81,9)", "log(3,81)", "log(1.25,10)", "log10(1.25)", "log10(5:4)", "log10(1:100)", "log10(0.001)",
219        "log10(7.5e-8)", "log10(99)", "log10(2:3)",
220        // Hyperbolic and angle functions.
221        "sinh(1)", "sinh(0)", "sinh(-2.5)", "sinh(0.)", "sinh(1:2)", "cosh(1)", "cosh(0)", "cosh(-0.5)", "tanh(1)",
222        "tanh(0)", "tanh(-3)", "tanh(0.25)", "arcsinh(1)", "arcsinh(0)", "arcsinh(-2.5)", "arcsinh(1:2)",
223        "arccosh(2)", "arccosh(1)", "arccosh(1.)", "arccosh(10.5)", "arctanh(0.5)", "arctanh(0)", "arctanh(-0.25)",
224        "arctanh(1:3)", "arctan2(1,1)", "arctan2(1,0)", "arctan2(0,-1)", "arctan2(-1,-1)", "arctan2(0,0)",
225        "arctan2(1,2)", "arctan2(0,1)", "arctan2(-1,0)", "arctan2(3,-4)", "arctan2(-2.5,1)",
226        "deg(1)", "deg(3.14159)", "deg(1:2)", "rad(180)", "rad(90)", "rad(1)", "rad(-45.5)",
227        "float(7)", "float(7:2)", "float(2.5)", "pfloat(7)", "float(1:3)", "float(123456789012345)",
228        "sqrt(2)", "sqrt(1e6)", "sqrt(10)", "sqrt(2:9)", "sqrt(0.5)", "sqrt(99999999)",
229    ]
230
231    /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the
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,
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)
236        #expect(emacs.count == cases.count)
237        var skipped: [String] = []
238        for (c, expected) in zip(cases, emacs) {
239            var modes = Calc.Modes()
240            modes.precision = precision
241            modes.symbolic = symbolic
242            modes.degrees = !radians
243            modes.preferFractions = fractions
244            modes.timeZone = TimeZone(secondsFromGMT: zone.offset)!
245            let f = c.1.dropFirst().dropLast().split(separator: " ")
246            let n = Int(f[1])!
247            switch f[0] {
248            case "fix": modes.format = .fix(n)
249            case "sci": modes.format = .sci(n)
250            case "eng": modes.format = .eng(n)
251            default: modes.format = .float(n)
252            }
253            let ours: String
254            do { ours = try Calc.evaluate(c.0, modes: modes) } catch { ours = "unsupported: \(error)" }
255            if ours.hasPrefix("unsupported") {
256                // Calc can fail too, e.g. a root whose Newton steps never settle.
257                if !expected.hasPrefix("LISP ERROR") { skipped.append(c.0) }
258                continue
259            }
260            #expect(ours == expected, "\(c.0) \(c.1) p\(precision)\(note)")
261        }
262        return skipped
263    }
264
265    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
266    func matchesCalc() throws {
267        var cases = Self.fixed.map { ($0, "(float 8)") }
268        for format in ["(float 3)", "(fix 2)", "(fix 0)", "(sci 3)", "(eng 2)"] {
269            for e in ["2/3", "3", "1.5", "1234.5678", "0.000123", "1e20*1", "-2/3", "1/7*100"] { cases.append((e, format)) }
270        }
271        // Generated: random operands and operators.
272        let seed = testSeed(20261122)
273        var generator = SeededGenerator(state: seed)
274        let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "0.3", "1e3", "2.5e-2"]
275        let ops = ["+", "-", "*", "/"]
276        for _ in 0..<300 {
277            var e = numbers.randomElement(using: &generator)!
278            for _ in 0..<Int.random(in: 1...4, using: &generator) {
279                e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))"
280            }
281            cases.append((e, "(float 8)"))
282        }
283        // Only what Calc itself can't show as a number.
284        let skipped = try Self.compare(cases, note: " seed \(seed)")
285        #expect(skipped == [], "\(skipped) seed \(seed)")
286    }
287
288    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
289    func functionsMatchCalc() throws {
290        var cases = Self.functions.map { ($0, "(float 12)") }
291        let sample = ["vgmean([1,2,3])", "agmean(1,2)", "sinh(1)", "arctan2(1,2)", "frac(0.1)", "log(10,2)", "nroot(10,3)",
292                      "vcorr([1,2,3],[1,2,4])", "5%", "1:3*3", "rounde(2.45,1)", "hypot(1,1)", "rad(1)", "16#FF/7"]
293        for format in ["(float 8)", "(fix 2)", "(sci 3)", "(eng 2)"] {
294            for e in sample { cases.append((e, format)) }
295        }
296        // Generated: functions of random integers, fractions and floats. Arguments outside a
297        // function's domain are refused, so only what is computed is compared.
298        let seed = testSeed(20261122)
299        var generator = SeededGenerator(state: seed)
300        let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "1:3", "5:4", "2.5e-2"]
301        let unary = ["sinh", "cosh", "tanh", "arcsinh", "rad", "deg", "frac", "sign", "rounde", "roundu", "float", "sqrt", "arctanh"]
302        let binary = ["log", "hypot", "arctan2", "agmean", "nroot", "gcd", "lcm", "fdiv"]
303        for _ in 0..<200 {
304            let x = numbers.randomElement(using: &generator)!
305            let y = numbers.randomElement(using: &generator)!
306            cases.append(("\(unary.randomElement(using: &generator)!)(\(x))", "(float 12)"))
307            cases.append(("\(binary.randomElement(using: &generator)!)(\(x),\(y))", "(float 12)"))
308            cases.append(("vgmean([\(x),\(y),\(numbers.randomElement(using: &generator)!)])", "(float 12)"))
309        }
310        let skipped = Set(try Self.compare(cases, note: " seed \(seed)")).intersection(Self.functions + sample)
311        #expect(skipped == [], "\(skipped) seed \(seed)")
312    }
313
314    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
315    func precisionMatchesCalc() throws {
316        let seed = testSeed(20261122)
317        var generator = SeededGenerator(state: seed)
318        let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "0.3", "1e3", "2.5e-2",
319                       "1.23456789012345678", "123456789.987654321"]
320        let ops = ["+", "-", "*", "/"]
321        for precision in [3, 6, 15, 18] {
322            var cases = ["1/3", "2/3", "1/7", "1.23456789012345678", "round(2/3,2)", "rounde(2.45,1)", "frac(0.1)", "1:3+0.5",
323                         "5%", "fact(18)", "(0.3/3.14159)-100", "123456+0.5"].map { ($0, "(float 0)") }
324            // Two digits more must fit in 18.
325            if precision <= 16 {
326                cases += ["vsum([0.1,0.2,0.3])", "vmean([1,2,4])", "vsum([1e-13,1,-1])", "vsdev([1.5,2.25,3e-12])", "0.7^-3"].map { ($0, "(float 0)") }
327            }
328            // Above 12 digits Calc keeps fractions of a second, which isn't supported.
329            if precision < 12 {
330                cases += ["<2026-10-05 Mon 08:30>+1", "<2026-10-05 Mon>+0.5", "julian(<2026-10-05 Mon 12:00>)", "unixtime(<2026-10-05 Mon 10:30>)",
331                          "badd(<2026-10-09 Fri 10:00>,2.5)", "date(2026,1,1,10,30,15)", "minute(<2026-10-05 Mon 10:30>)",
332                          "vsum([<2026-10-05 Mon 06:00>,0.1])"].map { ($0, "(float 0)") }
333            }
334            cases += ["vmax([1000., 1001])", "vmin([1001, 1000.])", "vmax([1234567890120., 1234567890123])", "1.1^10",
335                      "8^(1:3)", "1.5^3"].map { ($0, "(float 0)") }
336            if precision <= 14 {
337                cases += ["sqrt(2)", "sinh(1)", "log(10,2)", "nroot(10,3)", "vgmean([1,2,3])", "exp(1)", "sin(30)", "2^0.5",
338                          "exp(1.58)", "ln(9.44)", "0.08^1.5", "0.11^1.5", "exp(8.44)", "pow(2.5,1:3)", "(599e-2)^(5:7)"].map { ($0, "(float 0)") }
339                // exp, ln and powers round at two digits more first.
340                for _ in 0..<150 {
341                    let x = "\(Int.random(in: 1...999, using: &generator))e-2"
342                    let y = ["1.5", "0.5", "2.5", "1:3", "0.25", "-1.5", "2.", "3.7", "1.1", "-0.75", "5:7", "1:12"].randomElement(using: &generator)!
343                    cases += [("exp(\(x))", "(float 0)"), ("ln(\(x))", "(float 0)"), ("(\(x))^(\(y))", "(float 0)")]
344                }
345            }
346            for _ in 0..<100 {
347                var e = numbers.randomElement(using: &generator)!
348                for _ in 0..<Int.random(in: 1...3, using: &generator) {
349                    e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))"
350                }
351                cases.append((e, "(float 0)"))
352            }
353            let skipped = try Self.compare(cases, precision: precision, note: " seed \(seed)")
354            #expect(skipped == [], "p\(precision) \(skipped) seed \(seed)")
355        }
356    }
357
358    /// Formulas Calc leaves unevaluated: variables, text from fields, quotients by zero and
359    /// infinities.
360    static let symbolic = [
361        "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",
362        "(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",
363        "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)",
364        "(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.",
365        "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",
366        "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",
367        "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",
368        "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",
369        "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)",
370        "(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",
371        "inf", "-inf", "uinf", "inf+1", "inf-inf", "inf*0", "1/inf", "inf*2", "x*inf", "inf*-2", "inf+x", "-inf-inf",
372        "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",
373        "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])",
374        "vsum([1/0, 2])", "vsum([5 kg,3])", "vsum([2 (3),1])",
375        // No comma: Calc separates elements by spaces, except inside parentheses and arguments.
376        "vsum([1 - 2])", "vsum([x - 1])", "vsum([2x])", "vsum([(1 2)])", "vsum([max(1 2,3)])", "vcount([x])",
377        "(1/x) * 2 x", "(1/x) * 2 * x", "2 x * (1/x)", "(1/(2 x)) * 2 x", "x^-1 * 2 x", "((x)^2)^((0.0)^(0.0))",
378        "(x*y)^(0.0^0.0)", "(y^2)^(2*(0.0^0.0))", "(x^2)^(0.0^0.0 + 1)", "(x^2)^(-(0.0^0.0))", "(x^2)^(2^(0.0^0.0))",
379    ]
380
381    /// Products are right-associative, and a formula of integer-valued numbers is known to
382    /// be integer-valued.
383    @Test func symbolicOrder() throws {
384        var modes = Calc.Modes()
385        modes.format = .float(8)
386        for (e, expected) in [("(1/x) * 2 x", "2 x / x"), ("(1/x) * 2 * x", "2 x / x"), ("2 x * (1/x)", "2"),
387                              ("(1/(2 x)) * 2 x", "1"), ("x^-1 * 2 x", "2 x / x"),
388                              ("((x)^2)^((0.0)^(0.0))", "x^(2 0.^0.)"), ("(x*y)^(0.0^0.0)", "x^0.^0. y^0.^0."),
389                              ("(y^2)^(2*(0.0^0.0))", "y^(4 0.^0.)"), ("(x^2)^(0.0^0.0 + 1)", "x^(2 0.^0. + 2)"),
390                              ("(x^2)^(-(0.0^0.0))", "x^(-2 0.^0.)"), ("(x^2)^(2^(0.0^0.0))", "(x^2)^2^0.^0.")] {
391            #expect(try Calc.evaluate(e, modes: modes) == expected, "\(e)")
392        }
393        modes.format = .sci(11)
394        #expect(try Calc.evaluate("9.48205255399 * 7.65908717266 9.30092496999", modes: modes) == "6.7546913880e2")
395    }
396
397    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
398    func symbolicMatchesCalc() throws {
399        var cases = Self.symbolic.map { ($0, "(float 8)") }
400        for format in ["(fix 2)", "(sci 3)"] {
401            for e in ["x/3 + 1/3", "vmean([x,2,3])", "2.5 x - 1:3"] { cases.append((e, format)) }
402        }
403        // Generated: a variable or two mixed with numbers. What Calc would decide from more
404        // than this arithmetic is refused, so only what is computed is compared.
405        let seed = testSeed(20261122)
406        var generator = SeededGenerator(state: seed)
407        let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "10", "inf", "a b"]
408        let ops = ["+", "-", "*", "/", "^"]
409        func expression(_ depth: Int) -> String {
410            if depth == 0 || Int.random(in: 0..<3, using: &generator) == 0 { return leaves.randomElement(using: &generator)! }
411            let op = ops.randomElement(using: &generator)!
412            let right = op == "^" ? ["2", "3", "-1", "0.5", "x", "-2"].randomElement(using: &generator)! : expression(depth - 1)
413            let e = "(\(expression(depth - 1)))\(op)(\(right))"
414            return Int.random(in: 0..<6, using: &generator) == 0 ? "-\(e)" : e
415        }
416        for _ in 0..<2000 { cases.append((expression(4), "(float 8)")) }
417        let skipped = try Self.compare(cases, note: " seed \(seed)")
418        #expect(Set(skipped).intersection(Self.symbolic) == [], "\(skipped)")
419        #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused, seed \(seed)")
420    }
421
422    /// Functions of formulas Calc simplifies, or keeps with their arguments.
423    static let symbolicFunctions = [
424        "sqrt(x)", "sqrt(4 x)", "sqrt(2 x)", "sqrt(x/4)", "sqrt(4/x)", "sqrt(x^2)", "sqrt((-x)^2)", "sqrt(inf)", "sqrt(uinf)",
425        "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)",
426        "abs(-2 x)", "abs(abs(x))", "abs(x)^2", "abs(x) abs(x)", "abs(-inf)", "abs(x) - abs(x)", "exp(x)", "exp(-x)",
427        "exp(inf)", "exp(-inf)", "exp(x) exp(x)", "exp(x)/exp(x)", "ln(x)", "ln(e)", "ln(e^2)", "ln(inf)", "ln(-inf)",
428        "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)",
429        "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)",
430        "sqrt(x) == x^0.5", "exp(x) == e^x", "abs(x) < 0", "!x", "!(x<1)", "!(x+1)", "lnot(x>1)", "x && 1", "x || 0",
431        "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",
432        "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",
433        "2%inf", "x%inf", "x % y % z", "(x % y) * 2", "-x % y", "vmax([x,1])", "vmin([x,1,2])", "vmax([1,2,x])",
434        "vmax([x,y],[1,2])", "vmax([x,1.23456789012345])", "vmin([inf,x])", "vmax([N/A,3,5])", "vmin([2,TBD,1])",
435        // Prefix `!` binds tighter than `^`.
436        "!x+1", "!x<1", "!x*2", "2*!x", "!x^2", "!(x<1) + 1", "!-x+1", "-!x^2", "! !x", "!2+1", "!x && y", "x^!y",
437        // The reader negates numbers in a branch.
438        "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)",
439        "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)",
440        // An empty first vector starts from -inf.
441        "vmax([], [x])", "vmin([], [x])", "vmax([], [x, 1])", "vmax([], [2, x])", "vmax([[]], [x])", "vmax([x], [], [1])",
442        "vmin([], [], [x])",
443    ]
444
445    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
446    func symbolicFunctionsMatchCalc() throws {
447        var cases = Self.symbolicFunctions.map { ($0, "(float 8)") }
448        for format in ["(fix 2)", "(fix 0)", "(sci 3)", "(eng 2)"] {
449            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.)"] {
450                cases.append((e, format))
451            }
452        }
453        // Generated: the functions applied to formulas of a variable or two and numbers, and
454        // their results combined again. What is refused is left to Emacs.
455        let seed = testSeed(20261122)
456        var generator = SeededGenerator(state: seed)
457        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"]
458        let unary = ["sqrt", "abs", "exp", "ln", "!", "-"]
459        let binary = ["min", "max", "%", "<", ">", "<=", ">=", "==", "!=", "&&", "||", "+", "-", "*", "/", "^"]
460        func leaf() -> String { leaves.randomElement(using: &generator)! }
461        // Operands are left bare most of the time, so Calc's precedence decides.
462        func operand(_ e: String) -> String { Int.random(in: 0..<10, using: &generator) < 7 ? e : "(\(e))" }
463        func expression(_ depth: Int) -> String {
464            if depth == 0 || Int.random(in: 0..<4, using: &generator) == 0 { return leaf() }
465            switch Int.random(in: 0..<10, using: &generator) {
466            case 0..<4:
467                let f = unary.randomElement(using: &generator)!
468                return f == "!" || f == "-" ? f + operand(expression(depth - 1)) : "\(f)(\(expression(depth - 1)))"
469            case 4..<8:
470                let f = binary.randomElement(using: &generator)!
471                let (a, b) = (expression(depth - 1), f == "^" ? ["2", "3", "-1", "0.5", "x"].randomElement(using: &generator)! : expression(depth - 1))
472                return f.first!.isLetter ? "\(f)(\(a), \(b))" : "\(operand(a)) \(f) \(operand(b))"
473            case 8:
474                return "if(\(expression(depth - 1)), \(expression(depth - 1)), \(expression(depth - 1)))"
475            default:
476                let items = (0..<Int.random(in: 0...3, using: &generator)).map { _ in expression(depth - 1) }
477                return "\(["vmax", "vmin"].randomElement(using: &generator)!)([\(items.joined(separator: ", "))], [\(expression(depth - 1))])"
478            }
479        }
480        let formats = ["(float 8)", "(float 8)", "(fix 2)", "(fix 0)", "(eng 2)"]
481        for _ in 0..<4000 { cases.append((expression(4), formats.randomElement(using: &generator)!)) }
482        let skipped = try Self.compare(cases, note: " seed \(seed)")
483        #expect(Set(skipped).intersection(Self.symbolicFunctions) == [], "\(skipped)")
484        #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused, seed \(seed)")
485    }
486
487    /// Calc prints a float zero, in a formula too, under fix 0 as `0e0`.
488    @Test func floatZeroInFixZero() throws {
489        var modes = Calc.Modes()
490        modes.format = .fix(0)
491        for (e, expected) in [("max(x, 0.)", "max(x, 0e0)"), ("x < 0.", "x < 0e0"), ("if(x, 0., 1)", "x ? 0e0 : 1"),
492                              ("x / 0.", "x / 0e0"), ("0.", "0e0"), ("max(x, 0)", "max(x, 0)")] {
493            #expect(try Calc.evaluate(e, modes: modes) == expected, "\(e)")
494        }
495    }
496
497    @Test func unsupported() throws {
498        for e in ["vsum([5 kg])", "vsum([1 2])", "vcount([N A])", "vsum([2 3 4])", "vsum([1 1/2])", "vmin([3 4])",
499                  "vcount([f (x)])", "vcount([1 [2]])", "vcount([(1) 2])", "vcount([1 sin (2)])", "1.2.3e5",
500                  "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",
501                  "x+<2026-10-05 Mon>", "[x,1]", "vcount([x -1])", "(1/0)+1", "vmean([])", "(-8)^(1/3)", "vvar([5])", "1<2<3",
502                  "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
503                  "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
504                  "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",
505                  "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!",
506                  "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)",
507                  // Calc reads `<` after a space in a vector without commas as the start of a date.
508                  "abs(vmin([(3 - uinf) ^ (-1)], [0. < (-1 > 2.5)]))", "vmin([1], [0 < (1 > 2)])", "vcount([0 <(1 > 2)])",
509                  // Calc stops at `max-lisp-eval-depth`.
510                  "2*(((-1)/0+1.)*(-24))",
511                  "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "ln(0)", "ln(-1)",
512                  // Calc leaves these date expressions unevaluated.
513                  "<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",
514                  "vmedian([<2026-10-05 Mon>,<2026-10-07 Wed>])", "vmean([<2026-10-05 Mon>,1])", "vmean([<2026-10-05 Mon>])",
515                  "vmean([<2026-10-05 Mon>,<2026-10-06 Tue>,<2026-10-10 Sat>])", "vvar([<2026-10-05 Mon>,<2026-10-07 Wed>])",
516                  "max(<2026-10-05 Mon>,1)", "if(<2026-10-05 Mon>,1,2)", "round(<2026-10-05 Mon 13:00>,1)", "date(2026,13,1)",
517                  "date(2026,2,32)", "date(2026.5,1,1)", "date(2026,1,1,10,30,1.5)", "date([1,2])", "year([1,2])",
518                  "newweek(<2026-10-15 Thu>,7)", "newyear(<2026-10-15 Thu>,400)", "incmonth(<2026-10-05 Mon>,1.5)",
519                  "badd(<2026-10-09 Fri>,<2026-10-09 Fri>)", "bsub(5,1)", "now(5)", "julian(<2026-10-05 Mon>,5)", "1<<2026-10-05 Mon>",
520                  // Outside the years 1 to 2737, Calc's holiday range.
521                  "badd(date(2737,12,31),1)", "badd(<2026-10-05 Mon>,200000)", "bsub(date(2738,1,10),date(2026,1,1))",
522                  "badd(date(-100,1,3),1)", "badd(date(1,1,3),-3)", "bsub(date(1,1,10),date(-1,12,20))", "badd(date(10000,1,3),1)",
523                  // Calc leaves abs of day number 0 unevaluated.
524                  "abs(date(1,1,1)-1)", "abs(date(-1,12,31))"] {
525            #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) }
526        }
527        var modes = Calc.Modes()
528        // Calc's daylight saving rules aren't reproduced.
529        modes.timeZone = TimeZone(identifier: "America/New_York")!
530        #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("unixtime(<2026-10-05 Mon>)", modes: modes) }
531        #expect(try Calc.evaluate("julian(<2026-10-05 Mon>)", modes: modes) == "2461319")
532        modes.precision = 15
533        #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("sinh(1)", modes: modes) }
534        #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("<2026-10-05 Mon 10:00>+1", modes: modes) }
535        modes.precision = 19
536        #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1+1", modes: modes) }
537        // `calc-eval` with `num`: a formula is an error, unless Calc explains it.
538        #expect(throws: Calc.Failure("Number expected")) { try Calc.evaluate("x+1", numeric: true) }
539        #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1/0", numeric: true) }
540        // Calc explains what a quotient, power or function rejected, even when it cancels.
541        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"] {
542            #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, numeric: true) }
543        }
544        for e in ["-x", "x*2", "2 x", "x*y", "x+x", "x+2-2", "nan", "x<1", "x && 1", "!x"] {
545            #expect(throws: Calc.Failure("Number expected"), "\(e)") { try Calc.evaluate(e, numeric: true) }
546        }
547        #expect(try Calc.evaluate("x/x", numeric: true) == "1")
548        // Digits and points read as one number, at the position Calc gives.
549        for (e, position) in [("21.11.2026+1", 10), ("(21.11.2026)+1", 11), ("1.5.+1", 4), (".5.5", 4), ("3.14.15", 7),
550                              ("192.168.1.1", 11), ("1.2.3x", 5), ("1.5.", 4)] {
551            #expect(throws: Calc.Failure("Bad format", position: position), "\(e)") { try Calc.evaluate(e) }
552        }
553        var symbolic = Calc.Modes()
554        symbolic.symbolic = true
555        for e in ["sqrt(2)", "2^0.5", "ln(2)", "x^0.5", "sqrt(x)", "exp(x)"] {
556            #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, modes: symbolic) }
557        }
558    }
559
560    /// `;S`: what is computed matches; functions and powers that may not be exact are refused.
561    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
562    func symbolicModeMatchesCalc() throws {
563        let cases = (Self.fixed + Self.functions + Self.symbolic + Self.symbolicFunctions).map { ($0, "(float 8)") }
564        let skipped = try Self.compare(cases, symbolic: true)
565        #expect(Set(skipped).isDisjoint(with: ["1/3", "x+5", "1/0", "2 pi", "vmean([x,2,3])", "sin(30)", "x^2", "round(2.5)"]))
566        #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused")
567    }
568}