Tests/OrgCoreTests/CalcTests.swift
cmc Calc symbolic layer: variables, text fields, division by zero, infinities and the S flag
fb3b538d8b 5 days ago440 lines · 34359 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) throws -> [String] {
8 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)")
9 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
10 defer { try? FileManager.default.removeItem(at: folder) }
11 let input = folder.appendingPathComponent("input.json")
12 let output = folder.appendingPathComponent("output.json")
13 let script = folder.appendingPathComponent("calc.el")
14 try JSONSerialization.data(withJSONObject: cases.map { [$0.expression, $0.format] }).write(to: input)
15 try #"""
16 ;;; -*- lexical-binding: t -*-
17 (require 'calc)
18 (require 'org-table)
19 (require 'json)
20 (let* ((cases (with-temp-buffer
21 (insert-file-contents (getenv "ORACLE_INPUT"))
22 (json-parse-buffer :array-type 'list)))
23 (results
24 (mapcar (lambda (c)
25 (let* ((modes (copy-sequence org-calc-default-modes))
26 (format (car (read-from-string (nth 1 c)))))
27 (setq modes (plist-put modes 'calc-float-format format))
28 (setq modes (plist-put modes 'calc-internal-prec (string-to-number (getenv "ORACLE_PREC"))))
29 (when (getenv "ORACLE_SYMBOLIC") (setq modes (plist-put modes 'calc-symbolic-mode t)))
30 (let ((r (condition-case e (calc-eval (cons (car c) modes) nil)
31 (error (format "LISP ERROR %S" e)))))
32 (if (stringp r) r (format "ERROR %S" r)))))
33 cases)))
34 (with-temp-file (getenv "ORACLE_OUTPUT")
35 (insert (json-encode (vconcat results)))))
36 """#.write(to: script, atomically: true, encoding: .utf8)
37 _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path, "ORACLE_PREC": String(precision), "TZ": zone].merging(symbolic ? ["ORACLE_SYMBOLIC": "1"] : [:]) { $1 })
38 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
39 }
40}
41
42struct CalcTests {
43 static let fixed = [
44 "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",
45 "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",
46 "0.0001/3", "(1.23456789012345)", "vsum([1,2,3.5])", "vmean([1,2])", "vmean([1,2,4])", "vmax([1,5,3])", "vsum([])",
47 "vcount([1,2])", "vmedian([1,3,2,4])", "sin(30)", "cos(60)", "tan(45)", "exp(1)", "ln(10)", "log10(1000)", "log10(2)",
48 "-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",
49 "12345678.9*1", "123456789.1*1", "1.25*1", "0.000123*1", "1e100*1e100", "round(2.5)", "floor(2.7)", "abs(-3)",
50 "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)",
51 "cos(0)", "cos(90)", "tan(0)", "exp(0)", "ln(1)", "log10(1)", "log10(100.0)", "sqrt(2.25)", "sqrt(0)", "arcsin(1)",
52 "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])",
53 "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])",
54 "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)",
55 "min(4,2)", "1e3", "1.e3", "007", "(0.5)", "(.5)", "(5.)", "123456789012*10", "1.23456789012345678", "exp(10)",
56 "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)",
57 "(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)",
58 "vmean([10,20,25])", "(5)-(7.25)", "(-0.001)*(1000)", "1/(3)", "(2)/(3)*(3)",
59 // Dates, nan, comparisons and logic, and the rest of the functions tables use.
60 "<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>",
61 "<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)",
62 "<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",
63 "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",
64 "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"),
65 "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)",
66 "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])",
67 "2+3<4*2", "1<2 && 3<4", "!(1<2)", "(1<2)+(2<3)",
68 // Date forms and date functions.
69 "<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",
70 "<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",
71 "<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>",
72 "-(<2026-10-05 Mon>)+<2026-10-01 Thu>", "0-<2026-10-05 Mon>", "-<2026-10-05 Mon>", "<2026-10-05 Mon>-nan",
73 "<2026-10-05 Mon>-<2026-10-04 Sun 12:00>", "<2026-10-05 Mon> == <2026-10-05 Mon 00:00>",
74 "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>])",
75 "vsum([<2026-10-05 Mon>,<2026-10-06 Tue>,<2026-10-10 Sat>])", "vmean([<2026-10-05 Mon>,<2026-10-06 Tue>])",
76 "vmean([<2026-10-05 Mon 06:00>,<2026-10-05 Mon 12:00>])", "vmin([<2026-10-05 Mon>,<2026-10-07 Wed>])",
77 "vmax([<2026-10-05 Mon>],[<2026-10-06 Tue>])", "vmin([<2026-10-05 Mon 00:00>,<2026-10-05 Mon>])",
78 "vcount([<2026-10-05 Mon>])", "max(<2026-10-05 Mon>,<2026-10-06 Tue>)", "abs(<2026-10-05 Mon>)",
79 "floor(<2026-10-05 Mon 10:30>)", "ceil(<2026-10-05 Mon 13:00>)", "trunc(<2026-10-05 Mon 13:00>)",
80 "round(<2026-10-05 Mon 13:00>)", "round(<2026-10-05 Mon 11:00>)", "floor(<2026-10-05 Mon>)",
81 "year(<2026-10-05 Mon>)", "month(<2026-10-05 Mon 10:30>)", "day(<2026-10-05 Mon>)", "weekday(<2026-10-05 Mon>)",
82 "weekday(<2026-10-05 Mon 10:00>)", "weekday(-1)", "weekday(5)", "hour(<2026-10-05 Mon 10:30>)",
83 "minute(<2026-10-05 Mon 10:30>)", "second(<2026-10-05 Mon 10:30:45>)", "hour(<2026-10-05 Mon>)",
84 "yearday(<2026-10-05 Mon>)", "yearday(<2024-12-31 Tue>)", "year(5)", "year(<2026-10-05 Mon>)+1",
85 "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)",
86 "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)",
87 "date(<2026-10-05 Mon>)", "date(<2026-10-05 Mon 06:00>)", "date(<2026-10-05 Mon>)+1", "date(739000)",
88 "date(739000.5)", "date(739000.)", "date(1:2)", "date(5)", "date(36524)", "date(36890)", "date(365250)",
89 "date(-5)", "date(-400)", "date(0)", "date(-366)", "date(-367)",
90 "incmonth(<2026-01-31 Sat>,1)", "incmonth(<2026-10-05 Mon 10:30>,-14)", "incmonth(<2026-10-05 Mon>)",
91 "incmonth(<2026-10-05 Mon>,2.)", "incmonth(5,1)", "incmonth(<2024-02-29 Thu>,12)", "incmonth(<2026-03-31 Tue>,-1)",
92 "incmonth(<2026-12-15 Tue>,1)", "incmonth(<2026-01-15 Thu>,-1)", "incmonth(<2026-01-15 Thu>,-25)",
93 "incmonth(400,-24)", "incmonth(-400,24)", "incyear(<2024-02-29 Thu>,1)", "incyear(<2024-02-29 Thu>,4)",
94 "incyear(<2026-10-05 Mon>)", "incyear(<2026-10-05 Mon>,1.5)", "incyear(<2026-10-05 Mon 08:00>,-3)",
95 "newmonth(<2026-10-15 Thu>)", "newmonth(<2026-02-15 Sun>,31)", "newmonth(<2026-02-15 Sun>,0)",
96 "newmonth(<2026-02-15 Sun 10:00>,5)", "newmonth(<2024-02-15 Thu>,30)", "newmonth(<2026-10-15 Thu>,31)",
97 "newyear(<2026-10-15 Thu>)", "newyear(<2026-10-15 Thu>,0)", "newyear(<2026-10-15 Thu>,-3)",
98 "newyear(<2026-10-15 Thu 10:00>,40)", "newyear(<2024-10-15 Tue>,366)", "newyear(<2026-10-15 Thu>,366)",
99 "newyear(<2026-10-15 Thu>,-12)", "newweek(<2026-10-15 Thu>)", "newweek(<2026-10-15 Thu>,3)",
100 "newweek(<2026-10-15 Thu 10:00>)", "newweek(<2026-10-11 Sun>,1)", "newweek(<2026-10-17 Sat>,6)",
101 "badd(<2026-10-09 Fri>,1)", "badd(<2026-10-10 Sat>,1)", "badd(<2026-10-10 Sat>,-1)", "badd(<2026-10-10 Sat>,0)",
102 "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)",
103 "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)",
104 "bsub(<2026-10-12 Mon>,1)", "bsub(<2026-10-12 Mon>,<2026-10-09 Fri>)", "bsub(<2026-10-11 Sun>,<2026-10-09 Fri>)",
105 "bsub(<2026-10-12 Mon>,<2026-10-10 Sat>)", "bsub(<2026-10-05 Mon>,<2026-10-12 Mon>)",
106 "bsub(<2026-10-12 Mon 12:00>,<2026-10-09 Fri 06:00>)", "bsub(<2026-12-31 Thu>,<2026-01-01 Thu>)",
107 "bsub(<2026-10-10 Sat>,<2026-10-11 Sun>)", "bsub(<2026-10-11 Sun>,<2026-10-10 Sat>)",
108 "julian(<2026-10-05 Mon>)", "julian(<2026-10-05 Mon 12:00>)", "julian(2461319)", "julian(2461319.5)", "julian(1:2)",
109 "unixtime(<2026-10-05 Mon>)", "unixtime(<2026-10-05 Mon 10:30>)", "unixtime(1791158400)", "unixtime(1.5)",
110 "unixtime(0)", "unixtime(-86400)", "unixtime(<1970-01-01 Thu>)",
111 "abs(-<2026-10-05 Mon>)", "abs(date(-1,1,1))", "abs(-<2026-10-05 Mon 06:00>)", "abs(date(1,1,1))",
112 "abs(date(1,1,1)-1.5)", "abs(date(1,1,1)-0.25)",
113 "badd(date(2737,12,30),1)", "badd(date(1,1,3),-1)", "bsub(date(2737,12,31),date(1,1,1))",
114 "<0070-01-01 Thu>", "<0001-01-01 Mon>", "<0010-01-01 Fri>", "<0000-01-01 Sat>", "<0039-12-31 Sat>", "<0040-01-01 Sun>",
115 "<0099-01-01 Fri>", "<0050-06-15 Thu 10:30>", "<0100-01-01 Fri>", "year(<0010-01-01 Fri>)", "unixtime(<0001-01-01 Mon>)",
116 ]
117
118 /// Zones without daylight saving time, as `TZ` names them for Emacs and their offsets.
119 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
120 func datesInFixedZonesMatchCalc() throws {
121 let cases = ["unixtime(<2026-10-05 Mon>)", "unixtime(<2026-10-05 Mon 10:30>)", "unixtime(1791158400)",
122 "julian(<2026-10-05 Mon 12:00>)", "julian(2461319.5)", "julian(<2026-10-05 Mon>)"].map { ($0, "(float 8)") }
123 for zone in [("EST5", -5 * 3600), ("IST-5:30", 19800)] {
124 let skipped = try Self.compare(cases, zone: zone)
125 #expect(skipped == [], "\(zone.0) \(skipped)")
126 }
127 }
128
129 /// Every function and operator given dates where numbers go: what isn't refused must
130 /// match Calc.
131 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
132 func everythingOnDatesMatchesCalc() throws {
133 let functions = ["vsum", "vprod", "vcount", "vmean", "vmax", "vmin", "vmedian", "if", "vvar", "vpvar", "vsdev", "vpsdev",
134 "mod", "idiv", "fact", "dfact", "max", "min", "abs", "floor", "ceil", "trunc", "round", "sqrt", "exp", "ln",
135 "log10", "sin", "cos", "tan", "arcsin", "arccos", "arctan", "eq", "neq", "lt", "gt", "leq", "geq", "land",
136 "lor", "lnot", "percent", "float", "pfloat", "sign", "rounde", "roundu", "frac", "fdiv", "gcd", "lcm",
137 "choose", "perm", "pow", "exp10", "nroot", "hypot", "log", "sinh", "cosh", "tanh", "arcsinh", "arccosh",
138 "arctanh", "arctan2", "deg", "rad", "vflat", "vgmean", "vhmean", "vcov", "vpcov", "vcorr", "agmean", "date",
139 "year", "month", "day", "hour", "minute", "second", "yearday", "weekday", "newweek", "newmonth", "newyear",
140 "incmonth", "incyear", "badd", "bsub", "julian", "unixtime"]
141 let (d, t) = ("<2026-10-05 Mon>", "<2026-10-07 Wed 10:30>")
142 var cases: [String] = []
143 for f in functions {
144 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"] {
145 cases.append("\(f)(\(args))")
146 }
147 }
148 for op in ["+", "-", "*", "/", "%", "\\", "^", "==", "!=", "<", ">", "<=", ">=", "&&", "||"] {
149 cases += ["\(d)\(op)2", "2\(op)\(d)", "\(d)\(op)\(t)", "\(t)\(op)0.5", "\(t)\(op)\(d)", "\(d)\(op)nan"]
150 }
151 cases += ["-\(t)", "!\(d)", "\(d)%", "\(d)!", "\(d) 2", "2 \(d)"]
152 let skipped = try Self.compare(cases.map { ($0, "(float 8)") })
153 #expect(skipped.count < cases.count)
154 }
155
156 @Test func now() throws {
157 var modes = Calc.Modes()
158 modes.timeZone = TimeZone(secondsFromGMT: 3600)!
159 modes.now = Date(timeIntervalSince1970: 1_791_196_245)
160 #expect(try Calc.evaluate("now()", modes: modes) == "<2026-10-05 Mon 11:30>")
161 #expect(try Calc.evaluate("second(now())", modes: modes) == "45")
162 #expect(try Calc.evaluate("date(10,6)-newyear(now())", modes: modes) == "278")
163 modes.now = Date(timeIntervalSince1970: 1_791_158_400 - 3600)
164 #expect(try Calc.evaluate("now()", modes: modes) == "<2026-10-05 Mon 00:00>")
165 }
166
167 /// Constants, functions and syntax that only some tables use.
168 static let functions = [
169 // Grammar: juxtaposition, percent, factorials, fractions and radix integers.
170 "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",
171 "5%", "50%*20", "5%+1", "5%3", "5% 3", "(5)%", "12.5%", "1:4%", "100%", "-5%", "2^50%", "5%-1", "5% (2)",
172 "5!", "5!+1", "-5!", "0!", "(3)!", "2^3!", "3!!", "6!!", "0!!", "1!!", "5.!", "20.!", "3! 2", "5! == 120", "5!=120",
173 "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)",
174 "16#FF", "16#ff", "16#FF+1", "2#101", "8#17", "36#Z", "36#zz", "016#10", "10#99",
175 // Comparisons and logic as functions; `&&` and `||` give an argument.
176 "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)",
177 "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.",
178 "0. || 0", "if(1:2, 1, 2)",
179 // Statistics.
180 "vsum([1,2],[3,4])", "vsum(1,2,3)", "vsum([1,2],3)", "vsum()", "vsum([[1,2],[3]])", "vmax([1,2],[5,3])",
181 "vmax(1,7,3)", "vmin([1,2],[0,3])", "vmean([1,2],[3])", "vmean(1,2)", "vprod([1,2],[3])", "vcount([1,2],3)",
182 "vcount()", "vmedian([1,2],[5])", "vvar([1,2],[3])", "vsdev(1,2,3)", "vpsdev([1,2],[3,4])", "vmax(5)",
183 "vmean(5)", "vsum(vflat([1,[2,3]],4))", "vcount(vflat(1,2,3))", "vgmean([1,2,4])", "vgmean([2,8])",
184 "vgmean([1,2,3])", "vgmean([1.5,2.5])", "vgmean([1:2,2])", "vgmean([0,2])", "vgmean([5])", "vgmean([2,3,4,5])",
185 "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])",
186 "vhmean([1,2,4])", "vhmean([1,2])", "vhmean([1.5,2.5])", "vhmean([3])", "vhmean(1,2,3)",
187 "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])",
188 "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])",
189 "agmean(1,2)", "agmean(1,4)", "agmean(2,2)", "agmean(1.5,2)", "agmean(0,3)", "agmean(-1,4)", "agmean(24,6)",
190 // Rounding and fractions.
191 "rounde(2.5)", "rounde(3.5)", "rounde(-2.5)", "rounde(-3.5)", "rounde(2.6)", "rounde(7)", "rounde(5:2)",
192 "rounde(7:2)", "rounde(2.45,1)", "rounde(2.55,1)", "rounde(1234,-2)", "rounde(1250,-2)", "rounde(1:8,2)",
193 "roundu(2.5)", "roundu(-2.5)", "roundu(-2.4)", "roundu(2.45,1)", "roundu(-2.45,1)", "roundu(-5:2)", "roundu(3.)",
194 "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)",
195 "frac(2.75)", "frac(-2.75)", "frac(7)", "frac(7:2)", "frac(7.)", "frac(0.1)", "frac(0.333333333333)",
196 "frac(3.14159265359)", "frac(1.5e-3)", "frac(0.142857142857)", "frac(1.5e-11)",
197 "sign(-3)", "sign(0)", "sign(2.5)", "sign(-1:3)", "sign(0.)",
198 "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)",
199 "lcm(4,6)", "lcm(-4,6)", "lcm(0,6)", "lcm(1:2,1:3)", "lcm(3,4)",
200 "choose(5,2)", "choose(5,0)", "choose(5,6)", "choose(-5,2)", "choose(-5,3)", "choose(-3,-5)", "choose(-5,-3)",
201 "choose(5,-1)", "choose(52,5)", "choose(60,30)", "perm(5,2)", "perm(5,0)", "perm(5,5)", "perm(20,10)",
202 // Powers, roots and logarithms.
203 "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)",
204 "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.",
205 "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)",
206 "nroot(8,3)", "nroot(27,3)", "nroot(10,3)", "nroot(16,4)", "nroot(2.5,2)", "nroot(1:8,3)", "nroot(-8,1)",
207 "nroot(2,4)", "nroot(2,5)", "nroot(100,7)", "nroot(1000,12)", "nroot(3.5,11)", "nroot(2:3,3)", "nroot(0,3)",
208 "nroot(1,5)", "nroot(1024,10)", "nroot(7,6)", "nroot(1e10,9)",
209 "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)",
210 "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)",
211 "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)",
212 "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)",
213 "log10(7.5e-8)", "log10(99)", "log10(2:3)",
214 // Hyperbolic and angle functions.
215 "sinh(1)", "sinh(0)", "sinh(-2.5)", "sinh(0.)", "sinh(1:2)", "cosh(1)", "cosh(0)", "cosh(-0.5)", "tanh(1)",
216 "tanh(0)", "tanh(-3)", "tanh(0.25)", "arcsinh(1)", "arcsinh(0)", "arcsinh(-2.5)", "arcsinh(1:2)",
217 "arccosh(2)", "arccosh(1)", "arccosh(1.)", "arccosh(10.5)", "arctanh(0.5)", "arctanh(0)", "arctanh(-0.25)",
218 "arctanh(1:3)", "arctan2(1,1)", "arctan2(1,0)", "arctan2(0,-1)", "arctan2(-1,-1)", "arctan2(0,0)",
219 "arctan2(1,2)", "arctan2(0,1)", "arctan2(-1,0)", "arctan2(3,-4)", "arctan2(-2.5,1)",
220 "deg(1)", "deg(3.14159)", "deg(1:2)", "rad(180)", "rad(90)", "rad(1)", "rad(-45.5)",
221 "float(7)", "float(7:2)", "float(2.5)", "pfloat(7)", "float(1:3)", "float(123456789012345)",
222 "sqrt(2)", "sqrt(1e6)", "sqrt(10)", "sqrt(2:9)", "sqrt(0.5)", "sqrt(99999999)",
223 ]
224
225 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the
226 /// cases `Calc.evaluate` doesn't support.
227 static func compare(_ cases: [(String, String)], precision: Int = 12, zone: (name: String, offset: Int) = ("UTC", 0), symbolic: Bool = false) throws -> [String] {
228 let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name, symbolic: symbolic)
229 #expect(emacs.count == cases.count)
230 var skipped: [String] = []
231 for (c, expected) in zip(cases, emacs) {
232 var modes = Calc.Modes()
233 modes.precision = precision
234 modes.symbolic = symbolic
235 modes.timeZone = TimeZone(secondsFromGMT: zone.offset)!
236 let f = c.1.dropFirst().dropLast().split(separator: " ")
237 let n = Int(f[1])!
238 switch f[0] {
239 case "fix": modes.format = .fix(n)
240 case "sci": modes.format = .sci(n)
241 case "eng": modes.format = .eng(n)
242 default: modes.format = .float(n)
243 }
244 let ours: String
245 do { ours = try Calc.evaluate(c.0, modes: modes) } catch { ours = "unsupported: \(error)" }
246 if ours.hasPrefix("unsupported") {
247 skipped.append(c.0)
248 continue
249 }
250 #expect(ours == expected, "\(c.0) \(c.1) p\(precision)")
251 }
252 return skipped
253 }
254
255 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
256 func matchesCalc() throws {
257 var cases = Self.fixed.map { ($0, "(float 8)") }
258 for format in ["(float 3)", "(fix 2)", "(fix 0)", "(sci 3)", "(eng 2)"] {
259 for e in ["2/3", "3", "1.5", "1234.5678", "0.000123", "1e20*1", "-2/3", "1/7*100"] { cases.append((e, format)) }
260 }
261 // Generated: random operands and operators.
262 var generator = SystemRandomNumberGenerator()
263 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"]
264 let ops = ["+", "-", "*", "/"]
265 for _ in 0..<300 {
266 var e = numbers.randomElement(using: &generator)!
267 for _ in 0..<Int.random(in: 1...4, using: &generator) {
268 e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))"
269 }
270 cases.append((e, "(float 8)"))
271 }
272 // Only what Calc itself can't show as a number.
273 let skipped = try Self.compare(cases)
274 #expect(skipped == [], "\(skipped)")
275 }
276
277 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
278 func functionsMatchCalc() throws {
279 var cases = Self.functions.map { ($0, "(float 12)") }
280 let sample = ["vgmean([1,2,3])", "agmean(1,2)", "sinh(1)", "arctan2(1,2)", "frac(0.1)", "log(10,2)", "nroot(10,3)",
281 "vcorr([1,2,3],[1,2,4])", "5%", "1:3*3", "rounde(2.45,1)", "hypot(1,1)", "rad(1)", "16#FF/7"]
282 for format in ["(float 8)", "(fix 2)", "(sci 3)", "(eng 2)"] {
283 for e in sample { cases.append((e, format)) }
284 }
285 // Generated: functions of random integers, fractions and floats. Arguments outside a
286 // function's domain are refused, so only what is computed is compared.
287 var generator = SystemRandomNumberGenerator()
288 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"]
289 let unary = ["sinh", "cosh", "tanh", "arcsinh", "rad", "deg", "frac", "sign", "rounde", "roundu", "float", "sqrt", "arctanh"]
290 let binary = ["log", "hypot", "arctan2", "agmean", "nroot", "gcd", "lcm", "fdiv"]
291 for _ in 0..<200 {
292 let x = numbers.randomElement(using: &generator)!
293 let y = numbers.randomElement(using: &generator)!
294 cases.append(("\(unary.randomElement(using: &generator)!)(\(x))", "(float 12)"))
295 cases.append(("\(binary.randomElement(using: &generator)!)(\(x),\(y))", "(float 12)"))
296 cases.append(("vgmean([\(x),\(y),\(numbers.randomElement(using: &generator)!)])", "(float 12)"))
297 }
298 let skipped = Set(try Self.compare(cases)).intersection(Self.functions + sample)
299 #expect(skipped == [], "\(skipped)")
300 }
301
302 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
303 func precisionMatchesCalc() throws {
304 var generator = SystemRandomNumberGenerator()
305 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",
306 "1.23456789012345678", "123456789.987654321"]
307 let ops = ["+", "-", "*", "/"]
308 for precision in [3, 6, 15, 18] {
309 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",
310 "5%", "fact(18)", "(0.3/3.14159)-100", "123456+0.5"].map { ($0, "(float 0)") }
311 // Two digits more must fit in 18.
312 if precision <= 16 {
313 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)") }
314 }
315 // Above 12 digits Calc keeps fractions of a second, which isn't supported.
316 if precision < 12 {
317 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>)",
318 "badd(<2026-10-09 Fri 10:00>,2.5)", "date(2026,1,1,10,30,15)", "minute(<2026-10-05 Mon 10:30>)",
319 "vsum([<2026-10-05 Mon 06:00>,0.1])"].map { ($0, "(float 0)") }
320 }
321 cases += ["vmax([1000., 1001])", "vmin([1001, 1000.])", "vmax([1234567890120., 1234567890123])", "1.1^10",
322 "8^(1:3)", "1.5^3"].map { ($0, "(float 0)") }
323 if precision <= 14 {
324 cases += ["sqrt(2)", "sinh(1)", "log(10,2)", "nroot(10,3)", "vgmean([1,2,3])", "exp(1)", "sin(30)", "2^0.5",
325 "exp(1.58)", "ln(9.44)", "0.08^1.5", "0.11^1.5", "exp(8.44)", "pow(2.5,1:3)"].map { ($0, "(float 0)") }
326 // exp, ln and powers round at two digits more first.
327 for _ in 0..<150 {
328 let x = "\(Int.random(in: 1...999, using: &generator))e-2"
329 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)!
330 cases += [("exp(\(x))", "(float 0)"), ("ln(\(x))", "(float 0)"), ("(\(x))^(\(y))", "(float 0)")]
331 }
332 }
333 for _ in 0..<100 {
334 var e = numbers.randomElement(using: &generator)!
335 for _ in 0..<Int.random(in: 1...3, using: &generator) {
336 e = "(\(e))\(ops.randomElement(using: &generator)!)(\(numbers.randomElement(using: &generator)!))"
337 }
338 cases.append((e, "(float 0)"))
339 }
340 let skipped = try Self.compare(cases, precision: precision)
341 #expect(skipped == [], "p\(precision) \(skipped)")
342 }
343 }
344
345 /// Formulas Calc leaves unevaluated: variables, text from fields, quotients by zero and
346 /// infinities.
347 static let symbolic = [
348 "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",
349 "(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",
350 "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)",
351 "(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.",
352 "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",
353 "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",
354 "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",
355 "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",
356 "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)",
357 "(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",
358 "inf", "-inf", "uinf", "inf+1", "inf-inf", "inf*0", "1/inf", "inf*2", "x*inf", "inf*-2", "inf+x", "-inf-inf",
359 "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",
360 "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])",
361 "vsum([1/0, 2])", "vsum([5 kg,3])", "vsum([2 (3),1])",
362 ]
363
364 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
365 func symbolicMatchesCalc() throws {
366 var cases = Self.symbolic.map { ($0, "(float 8)") }
367 for format in ["(fix 2)", "(sci 3)"] {
368 for e in ["x/3 + 1/3", "vmean([x,2,3])", "2.5 x - 1:3"] { cases.append((e, format)) }
369 }
370 // Generated: a variable or two mixed with numbers. What Calc would decide from more
371 // than this arithmetic is refused, so only what is computed is compared.
372 var generator = SystemRandomNumberGenerator()
373 let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "10", "inf", "a b"]
374 let ops = ["+", "-", "*", "/", "^"]
375 func expression(_ depth: Int) -> String {
376 if depth == 0 || Int.random(in: 0..<3, using: &generator) == 0 { return leaves.randomElement(using: &generator)! }
377 let op = ops.randomElement(using: &generator)!
378 let right = op == "^" ? ["2", "3", "-1", "0.5", "x", "-2"].randomElement(using: &generator)! : expression(depth - 1)
379 let e = "(\(expression(depth - 1)))\(op)(\(right))"
380 return Int.random(in: 0..<6, using: &generator) == 0 ? "-\(e)" : e
381 }
382 for _ in 0..<2000 { cases.append((expression(4), "(float 8)")) }
383 let skipped = try Self.compare(cases)
384 #expect(Set(skipped).intersection(Self.symbolic) == [], "\(skipped)")
385 #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused")
386 }
387
388 @Test func unsupported() throws {
389 for e in ["sqrt(x)", "vmax([x,1])", "vsum(x,1)", "x<1", "if(x,1,2)", "x%2", "x_1", "x'", "Holidays+1", "café+1",
390 "x+<2026-10-05 Mon>", "[x,1]", "vcount([x -1])", "(1/0)+1", "vmean([])", "(-8)^(1/3)", "vvar([5])", "1<2<3",
391 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
392 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
393 "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",
394 "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!",
395 "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)",
396 "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "ln(0)", "ln(-1)",
397 // Calc leaves these date expressions unevaluated.
398 "<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",
399 "vmedian([<2026-10-05 Mon>,<2026-10-07 Wed>])", "vmean([<2026-10-05 Mon>,1])", "vmean([<2026-10-05 Mon>])",
400 "vmean([<2026-10-05 Mon>,<2026-10-06 Tue>,<2026-10-10 Sat>])", "vvar([<2026-10-05 Mon>,<2026-10-07 Wed>])",
401 "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)",
402 "date(2026,2,32)", "date(2026.5,1,1)", "date(2026,1,1,10,30,1.5)", "date([1,2])", "year([1,2])",
403 "newweek(<2026-10-15 Thu>,7)", "newyear(<2026-10-15 Thu>,400)", "incmonth(<2026-10-05 Mon>,1.5)",
404 "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>",
405 // Outside the years 1 to 2737, Calc's holiday range.
406 "badd(date(2737,12,31),1)", "badd(<2026-10-05 Mon>,200000)", "bsub(date(2738,1,10),date(2026,1,1))",
407 "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)",
408 // Calc leaves abs of day number 0 unevaluated.
409 "abs(date(1,1,1)-1)", "abs(date(-1,12,31))"] {
410 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) }
411 }
412 var modes = Calc.Modes()
413 // Calc's daylight saving rules aren't reproduced.
414 modes.timeZone = TimeZone(identifier: "America/New_York")!
415 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("unixtime(<2026-10-05 Mon>)", modes: modes) }
416 #expect(try Calc.evaluate("julian(<2026-10-05 Mon>)", modes: modes) == "2461319")
417 modes.precision = 15
418 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("sinh(1)", modes: modes) }
419 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("<2026-10-05 Mon 10:00>+1", modes: modes) }
420 modes.precision = 19
421 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1+1", modes: modes) }
422 // `calc-eval` with `num`: a formula is an error, unless Calc explains it.
423 #expect(throws: Calc.Failure("Number expected")) { try Calc.evaluate("x+1", numeric: true) }
424 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1/0", numeric: true) }
425 var symbolic = Calc.Modes()
426 symbolic.symbolic = true
427 for e in ["sqrt(2)", "2^0.5", "ln(2)", "x^0.5"] {
428 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e, modes: symbolic) }
429 }
430 }
431
432 /// `;S`: what is computed matches; functions and powers that may not be exact are refused.
433 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
434 func symbolicModeMatchesCalc() throws {
435 let cases = (Self.fixed + Self.functions + Self.symbolic).map { ($0, "(float 8)") }
436 let skipped = try Self.compare(cases, symbolic: true)
437 #expect(Set(skipped).isDisjoint(with: ["1/3", "x+5", "1/0", "2 pi", "vmean([x,2,3])", "sin(30)", "x^2", "round(2.5)"]))
438 #expect(skipped.count < cases.count / 3, "\(skipped.count) of \(cases.count) refused")
439 }
440}