Tests/OrgCoreTests/CalcTests.swift

560 lines · 43509 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        var generator = SystemRandomNumberGenerator()
273        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"]
274        let ops = ["+", "-", "*", "/"]
275        for _ in 0..<300 {
276            var e = numbers.randomElement(using: &generator)!
277            for _ in 0..<Int.random(in: 1...4, using: &generator) {
278                e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))"
279            }
280            cases.append((e, "(float 8)"))
281        }
282        // Only what Calc itself can't show as a number.
283        let skipped = try Self.compare(cases)
284        #expect(skipped == [], "\(skipped)")
285    }
286
287    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
288    func functionsMatchCalc() throws {
289        var cases = Self.functions.map { ($0, "(float 12)") }
290        let sample = ["vgmean([1,2,3])", "agmean(1,2)", "sinh(1)", "arctan2(1,2)", "frac(0.1)", "log(10,2)", "nroot(10,3)",
291                      "vcorr([1,2,3],[1,2,4])", "5%", "1:3*3", "rounde(2.45,1)", "hypot(1,1)", "rad(1)", "16#FF/7"]
292        for format in ["(float 8)", "(fix 2)", "(sci 3)", "(eng 2)"] {
293            for e in sample { cases.append((e, format)) }
294        }
295        // Generated: functions of random integers, fractions and floats. Arguments outside a
296        // function's domain are refused, so only what is computed is compared.
297        var generator = SystemRandomNumberGenerator()
298        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"]
299        let unary = ["sinh", "cosh", "tanh", "arcsinh", "rad", "deg", "frac", "sign", "rounde", "roundu", "float", "sqrt", "arctanh"]
300        let binary = ["log", "hypot", "arctan2", "agmean", "nroot", "gcd", "lcm", "fdiv"]
301        for _ in 0..<200 {
302            let x = numbers.randomElement(using: &generator)!
303            let y = numbers.randomElement(using: &generator)!
304            cases.append(("\(unary.randomElement(using: &generator)!)(\(x))", "(float 12)"))
305            cases.append(("\(binary.randomElement(using: &generator)!)(\(x),\(y))", "(float 12)"))
306            cases.append(("vgmean([\(x),\(y),\(numbers.randomElement(using: &generator)!)])", "(float 12)"))
307        }
308        let skipped = Set(try Self.compare(cases)).intersection(Self.functions + sample)
309        #expect(skipped == [], "\(skipped)")
310    }
311
312    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
313    func precisionMatchesCalc() throws {
314        var generator = SystemRandomNumberGenerator()
315        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",
316                       "1.23456789012345678", "123456789.987654321"]
317        let ops = ["+", "-", "*", "/"]
318        for precision in [3, 6, 15, 18] {
319            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",
320                         "5%", "fact(18)", "(0.3/3.14159)-100", "123456+0.5"].map { ($0, "(float 0)") }
321            // Two digits more must fit in 18.
322            if precision <= 16 {
323                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)") }
324            }
325            // Above 12 digits Calc keeps fractions of a second, which isn't supported.
326            if precision < 12 {
327                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>)",
328                          "badd(<2026-10-09 Fri 10:00>,2.5)", "date(2026,1,1,10,30,15)", "minute(<2026-10-05 Mon 10:30>)",
329                          "vsum([<2026-10-05 Mon 06:00>,0.1])"].map { ($0, "(float 0)") }
330            }
331            cases += ["vmax([1000., 1001])", "vmin([1001, 1000.])", "vmax([1234567890120., 1234567890123])", "1.1^10",
332                      "8^(1:3)", "1.5^3"].map { ($0, "(float 0)") }
333            if precision <= 14 {
334                cases += ["sqrt(2)", "sinh(1)", "log(10,2)", "nroot(10,3)", "vgmean([1,2,3])", "exp(1)", "sin(30)", "2^0.5",
335                          "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)") }
336                // exp, ln and powers round at two digits more first.
337                for _ in 0..<150 {
338                    let x = "\(Int.random(in: 1...999, using: &generator))e-2"
339                    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)!
340                    cases += [("exp(\(x))", "(float 0)"), ("ln(\(x))", "(float 0)"), ("(\(x))^(\(y))", "(float 0)")]
341                }
342            }
343            for _ in 0..<100 {
344                var e = numbers.randomElement(using: &generator)!
345                for _ in 0..<Int.random(in: 1...3, using: &generator) {
346                    e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))"
347                }
348                cases.append((e, "(float 0)"))
349            }
350            let skipped = try Self.compare(cases, precision: precision)
351            #expect(skipped == [], "p\(precision) \(skipped)")
352        }
353    }
354
355    /// Formulas Calc leaves unevaluated: variables, text from fields, quotients by zero and
356    /// infinities.
357    static let symbolic = [
358        "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",
359        "(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",
360        "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)",
361        "(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.",
362        "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",
363        "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",
364        "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",
365        "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",
366        "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)",
367        "(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",
368        "inf", "-inf", "uinf", "inf+1", "inf-inf", "inf*0", "1/inf", "inf*2", "x*inf", "inf*-2", "inf+x", "-inf-inf",
369        "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",
370        "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])",
371        "vsum([1/0, 2])", "vsum([5 kg,3])", "vsum([2 (3),1])",
372        // No comma: Calc separates elements by spaces, except inside parentheses and arguments.
373        "vsum([1 - 2])", "vsum([x - 1])", "vsum([2x])", "vsum([(1 2)])", "vsum([max(1 2,3)])", "vcount([x])",
374        "(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))",
375        "(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))",
376    ]
377
378    /// Products are right-associative, and a formula of integer-valued numbers is known to
379    /// be integer-valued.
380    @Test func symbolicOrder() throws {
381        var modes = Calc.Modes()
382        modes.format = .float(8)
383        for (e, expected) in [("(1/x) * 2 x", "2 x / x"), ("(1/x) * 2 * x", "2 x / x"), ("2 x * (1/x)", "2"),
384                              ("(1/(2 x)) * 2 x", "1"), ("x^-1 * 2 x", "2 x / x"),
385                              ("((x)^2)^((0.0)^(0.0))", "x^(2 0.^0.)"), ("(x*y)^(0.0^0.0)", "x^0.^0. y^0.^0."),
386                              ("(y^2)^(2*(0.0^0.0))", "y^(4 0.^0.)"), ("(x^2)^(0.0^0.0 + 1)", "x^(2 0.^0. + 2)"),
387                              ("(x^2)^(-(0.0^0.0))", "x^(-2 0.^0.)"), ("(x^2)^(2^(0.0^0.0))", "(x^2)^2^0.^0.")] {
388            #expect(try Calc.evaluate(e, modes: modes) == expected, "\(e)")
389        }
390        modes.format = .sci(11)
391        #expect(try Calc.evaluate("9.48205255399 * 7.65908717266 9.30092496999", modes: modes) == "6.7546913880e2")
392    }
393
394    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
395    func symbolicMatchesCalc() throws {
396        var cases = Self.symbolic.map { ($0, "(float 8)") }
397        for format in ["(fix 2)", "(sci 3)"] {
398            for e in ["x/3 + 1/3", "vmean([x,2,3])", "2.5 x - 1:3"] { cases.append((e, format)) }
399        }
400        // Generated: a variable or two mixed with numbers. What Calc would decide from more
401        // than this arithmetic is refused, so only what is computed is compared.
402        var generator = SystemRandomNumberGenerator()
403        let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "10", "inf", "a b"]
404        let ops = ["+", "-", "*", "/", "^"]
405        func expression(_ depth: Int) -> String {
406            if depth == 0 || Int.random(in: 0..<3, using: &generator) == 0 { return leaves.randomElement(using: &generator)! }
407            let op = ops.randomElement(using: &generator)!
408            let right = op == "^" ? ["2", "3", "-1", "0.5", "x", "-2"].randomElement(using: &generator)! : expression(depth - 1)
409            let e = "(\(expression(depth - 1)))\(op)(\(right))"
410            return Int.random(in: 0..<6, using: &generator) == 0 ? "-\(e)" : e
411        }
412        for _ in 0..<2000 { cases.append((expression(4), "(float 8)")) }
413        let skipped = try Self.compare(cases)
414        #expect(Set(skipped).intersection(Self.symbolic) == [], "\(skipped)")
415        #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused")
416    }
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
493    @Test func unsupported() throws {
494        for e in ["vsum([5 kg])", "vsum([1 2])", "vcount([N A])", "vsum([2 3 4])", "vsum([1 1/2])", "vmin([3 4])",
495                  "vcount([f (x)])", "vcount([1 [2]])", "vcount([(1) 2])", "vcount([1 sin (2)])", "1.2.3e5",
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",
497                  "x+<2026-10-05 Mon>", "[x,1]", "vcount([x -1])", "(1/0)+1", "vmean([])", "(-8)^(1/3)", "vvar([5])", "1<2<3",
498                  "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
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)",
500                  "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",
501                  "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!",
502                  "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)",
503                  "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "ln(0)", "ln(-1)",
504                  // Calc leaves these date expressions unevaluated.
505                  "<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",
506                  "vmedian([<2026-10-05 Mon>,<2026-10-07 Wed>])", "vmean([<2026-10-05 Mon>,1])", "vmean([<2026-10-05 Mon>])",
507                  "vmean([<2026-10-05 Mon>,<2026-10-06 Tue>,<2026-10-10 Sat>])", "vvar([<2026-10-05 Mon>,<2026-10-07 Wed>])",
508                  "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)",
509                  "date(2026,2,32)", "date(2026.5,1,1)", "date(2026,1,1,10,30,1.5)", "date([1,2])", "year([1,2])",
510                  "newweek(<2026-10-15 Thu>,7)", "newyear(<2026-10-15 Thu>,400)", "incmonth(<2026-10-05 Mon>,1.5)",
511                  "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>",
512                  // Outside the years 1 to 2737, Calc's holiday range.
513                  "badd(date(2737,12,31),1)", "badd(<2026-10-05 Mon>,200000)", "bsub(date(2738,1,10),date(2026,1,1))",
514                  "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)",
515                  // Calc leaves abs of day number 0 unevaluated.
516                  "abs(date(1,1,1)-1)", "abs(date(-1,12,31))"] {
517            #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) }
518        }
519        var modes = Calc.Modes()
520        // Calc's daylight saving rules aren't reproduced.
521        modes.timeZone = TimeZone(identifier: "America/New_York")!
522        #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("unixtime(<2026-10-05 Mon>)", modes: modes) }
523        #expect(try Calc.evaluate("julian(<2026-10-05 Mon>)", modes: modes) == "2461319")
524        modes.precision = 15
525        #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("sinh(1)", modes: modes) }
526        #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("<2026-10-05 Mon 10:00>+1", modes: modes) }
527        modes.precision = 19
528        #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1+1", modes: modes) }
529        // `calc-eval` with `num`: a formula is an error, unless Calc explains it.
530        #expect(throws: Calc.Failure("Number expected")) { try Calc.evaluate("x+1", numeric: true) }
531        #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1/0", numeric: true) }
532        // Calc explains what a quotient, power or function rejected, even when it cancels.
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"] {
534            #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, numeric: true) }
535        }
536        for e in ["-x", "x*2", "2 x", "x*y", "x+x", "x+2-2", "nan", "x<1", "x && 1", "!x"] {
537            #expect(throws: Calc.Failure("Number expected"), "\(e)") { try Calc.evaluate(e, numeric: true) }
538        }
539        #expect(try Calc.evaluate("x/x", numeric: true) == "1")
540        // Digits and points read as one number, at the position Calc gives.
541        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),
542                              ("192.168.1.1", 11), ("1.2.3x", 5), ("1.5.", 4)] {
543            #expect(throws: Calc.Failure("Bad format", position: position), "\(e)") { try Calc.evaluate(e) }
544        }
545        var symbolic = Calc.Modes()
546        symbolic.symbolic = true
547        for e in ["sqrt(2)", "2^0.5", "ln(2)", "x^0.5", "sqrt(x)", "exp(x)"] {
548            #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, modes: symbolic) }
549        }
550    }
551
552    /// `;S`: what is computed matches; functions and powers that may not be exact are refused.
553    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
554    func symbolicModeMatchesCalc() throws {
555        let cases = (Self.fixed + Self.functions + Self.symbolic + Self.symbolicFunctions).map { ($0, "(float 8)") }
556        let skipped = try Self.compare(cases, symbolic: true)
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)"]))
558        #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused")
559    }
560}