Sources/OrgCore/Compute/Calc.swift
1917 lines · 92103 bytes
1import Foundation
2
3/// The part of Emacs Calc that table formulas use, with Calc's number semantics: exact
4/// integers, decimal floats rounded to `calc-internal-prec` digits after every operation, and
5/// Calc's display formats. Anything outside this domain throws `Calc.Unsupported`, and the
6/// caller hands the work to Emacs.
7public enum Calc {
8 public struct Unsupported: Error, Equatable, CustomStringConvertible {
9 public let reason: String
10 /// The left-hand side of the table formula that threw, once recalculation knows it.
11 public var formula: String?
12 public var description: String { reason }
13 init(_ reason: String) { self.reason = reason }
14 }
15
16 /// An error Calc reports, which a table shows as `#ERROR`.
17 public struct Failure: Error, Equatable, CustomStringConvertible {
18 public let reason: String
19 /// Where in the expression Calc reports the error.
20 public let position: Int
21 public var description: String { reason }
22 init(_ reason: String, position: Int = 0) { (self.reason, self.position) = (reason, position) }
23 }
24
25 public indirect enum Value: Equatable, Sendable {
26 case int(Int)
27 /// Mantissa and exponent, normalized: at most `precision` digits, no trailing zeros.
28 case float(Int, Int)
29 case vector([Value])
30 /// A date form: the day number, with the time of day as a fraction.
31 case date(Value)
32 case nan
33 /// An exact fraction, reduced, the denominator above 1 (`calc-prefer-frac`).
34 case frac(Int, Int)
35 /// A formula Calc leaves unevaluated, with variables or a quotient by zero.
36 case symbolic(Term)
37 }
38
39 public enum FloatFormat: Equatable, Sendable {
40 case float(Int), fix(Int), sci(Int), eng(Int)
41 }
42
43 public struct Modes: Equatable, Sendable {
44 public var precision = 12
45 public var format = FloatFormat.float(8)
46 public var degrees = true
47 /// `calc-prefer-frac`: dividing integers gives a fraction.
48 public var preferFractions = false
49 /// `calc-symbolic-mode`: functions whose result isn't exact stay unevaluated.
50 public var symbolic = false
51 /// The clock `now()` reads; nil is the system clock.
52 public var now: Date?
53 /// The local time zone, for `now()`, `julian` and `unixtime`.
54 public var timeZone = TimeZone.current
55 public init() {}
56 }
57
58 /// `calc-eval` of `expression`, as the string Calc would return; with `numeric`, as
59 /// `calc-eval` with `num`, a result that isn't a number is an error.
60 public static func evaluate(_ expression: String, modes: Modes = Modes(), numeric: Bool = false) throws -> String {
61 // Mantissas live in an Int, so 18 digits at most.
62 guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") }
63 return try $precision.withValue(modes.precision) {
64 try $fractions.withValue(modes.preferFractions) {
65 try $symbolicMode.withValue(modes.symbolic) {
66 var parser = Parser(expression)
67 let tree = try parser.parse()
68 let value = try Evaluator(modes: modes).eval(tree)
69 if numeric {
70 switch value {
71 case .int, .float, .frac: break
72 default:
73 // Calc explains the first argument a quotient, power or function
74 // rejected along the way, which isn't tracked here.
75 if tree.mayExplain { throw Unsupported("symbolic arithmetic") }
76 throw Failure("Number expected")
77 }
78 }
79 return try format(value, modes.format)
80 }
81 }
82 }
83 }
84
85 // MARK: - Numbers
86
87 /// `calc-internal-prec`.
88 @TaskLocal static var precision = 12
89
90 /// `math-with-extra-prec`: `body` with `n` more digits, the result rounded back.
91 static func extra(_ n: Int, _ body: () throws -> Value) throws -> Value {
92 let v = try $precision.withValue(precision + n, operation: body)
93 if case .float(let m, let e) = v { return try makeFloat(Int128(m), e) }
94 if case .date(.float(let m, let e)) = v { return .date(try makeFloat(Int128(m), e)) }
95 if case .symbolic(let t) = v { return value(try Symbolic.normalize(t)) }
96 return v
97 }
98
99 /// `math-use-emacs-fn`: `f` on a double, as Calc does at up to 16 digits. Above that
100 /// Calc uses its own series, which isn't reproduced.
101 static func emacs(_ f: (Double) -> Double, _ x: Value) throws -> Value {
102 guard precision <= 16 else { throw Unsupported("calc precision") }
103 guard case .float(let m, let e) = x, (-300...300).contains(e + digits(Int128(m)) - 1),
104 let d = Double("\(m)e\(e)") else { throw Unsupported("number size") }
105 let r = f(d)
106 guard r.isFinite else { throw Unsupported("infinite result") }
107 // `number-to-string`: the shortest text that reads back as the same double.
108 let pieces = r.description.split(separator: "e")
109 let text = String(pieces[0])
110 let point = text.firstIndex(of: ".").map { text.distance(from: $0, to: text.endIndex) - 1 } ?? 0
111 guard let mantissa = Int128(text.replacingOccurrences(of: ".", with: "")),
112 let exponent = Int(pieces.count > 1 ? String(pieces[1]) : "0") else { throw Unsupported("number") }
113 return try makeFloat(mantissa, exponent - point)
114 }
115
116 // Constants to 36 digits, rounded to the precision, as `math-defcache` gives them.
117 static func pi() throws -> Value { try makeFloat(314159265358979323846264338327950288, -35) }
118 static func piOver2() throws -> Value { try makeFloat(157079632679489661923132169163975144, -35) }
119 static func piOver180() throws -> Value { try makeFloat(174532925199432957692369076848861271, -37) }
120
121 /// `math-float`.
122 static func float(_ v: Value) throws -> Value {
123 switch v {
124 case .int(let i): return try makeFloat(Int128(i), 0)
125 case .frac(let n, let d): return try divide(try makeFloat(Int128(n), 0), .int(d))
126 case .float: return v
127 default: throw Unsupported("arguments")
128 }
129 }
130
131 static func isZero(_ v: Value) -> Bool { v == .int(0) || v == .float(0, 0) }
132
133 /// The sign of a real number.
134 static func sign(_ v: Value) throws -> Int {
135 switch v {
136 case .int(let i): return i.signum()
137 case .float(let m, _): return m.signum()
138 case .frac(let n, _): return n.signum()
139 default: throw Unsupported("arguments")
140 }
141 }
142
143 /// `math-trunc` of a real number, as an integer.
144 static func trunc(_ v: Value) throws -> Int {
145 switch v {
146 case .int(let i): return i
147 case .frac(let n, let d): return n / d
148 case .float(let m, let e):
149 let t = e >= 0 ? try scaleRounding(Int128(m), e) : -e > 37 ? 0 : Int128(m) / (try power10(-e))
150 guard let i = Int(exactly: t) else { throw Unsupported("integer size") }
151 return i
152 default: throw Unsupported("arguments")
153 }
154 }
155
156 /// `Math-num-integerp`: an integer, or a float with an integer value.
157 static func isWhole(_ v: Value) -> Bool {
158 switch v {
159 case .int: true
160 case .float(_, let e): e >= 0
161 default: false
162 }
163 }
164
165 /// `math-nearly-equal-float`: equal but for the last digit of precision.
166 static func nearlyEqual(_ a: Value, _ b: Value) -> Bool {
167 guard case .float(let ma, let ea) = a, case .float(let mb, let eb) = b else { return false }
168 let (x, y) = (Int128(ma), Int128(mb))
169 switch ea - eb {
170 case 0: return x == y || (abs(y - x) < 10 && digits(x) == precision)
171 case 1: return abs(x * 10 - y) < 10 && digits(y) == precision
172 case -1: return abs(y * 10 - x) < 10 && digits(x) == precision
173 default: return false
174 }
175 }
176
177 static func digits(_ x: Int128) -> Int {
178 var n = x.magnitude
179 var count = 1
180 while n >= 10 {
181 n /= 10
182 count += 1
183 }
184 return count
185 }
186
187 static func power10(_ n: Int) throws -> Int128 {
188 guard n >= 0, n <= 37 else { throw Unsupported("number size") }
189 var result: Int128 = 1
190 for _ in 0..<n { result *= 10 }
191 return result
192 }
193
194 /// `math-scale-rounding`: `x` times 10^n, rounding half away from zero when n < 0.
195 static func scaleRounding(_ x: Int128, _ n: Int) throws -> Int128 {
196 if n >= 0 {
197 let (result, overflow) = x.multipliedReportingOverflow(by: try power10(n))
198 if overflow { throw Unsupported("number size") }
199 return result
200 }
201 if x < 0 { return -(try scaleRounding(-x, n)) }
202 if -n > 38 { return 0 }
203 let truncated = -n - 1 > 37 ? 0 : x / (try power10(-n - 1))
204 return (truncated + 5) / 10
205 }
206
207 /// `math-make-float`.
208 static func makeFloat(_ mantissa: Int128, _ exponent: Int) throws -> Value {
209 var m = mantissa
210 var e = exponent
211 if m == 0 { return .float(0, 0) }
212 let excess = digits(m) - precision
213 if excess > 0 {
214 m = try scaleRounding(m, -excess)
215 e += excess
216 }
217 if m == 0 { return .float(0, 0) }
218 while m % 10 == 0 {
219 m /= 10
220 e += 1
221 }
222 guard let i = Int(exactly: m) else { throw Unsupported("calc precision") }
223 return .float(i, e)
224 }
225
226 static func parts(_ v: Value) throws -> (Int128, Int) {
227 switch v {
228 // `math-float`: normalized and rounded, as Calc converts an integer to combine it with a float.
229 case .int(let i): return try parts(try makeFloat(Int128(i), 0))
230 case .float(let m, let e): return (Int128(m), e)
231 case .frac(let n, let d): return try parts(try divide(.int(n), .int(d)))
232 case .vector: throw Unsupported("vector arithmetic")
233 case .date, .nan: throw Unsupported("date arithmetic")
234 case .symbolic: throw Unsupported("symbolic arithmetic")
235 }
236 }
237
238 /// An integer or a fraction as numerator and denominator.
239 static func rational(_ v: Value) -> (Int, Int)? {
240 switch v {
241 case .int(let i): (i, 1)
242 case .frac(let n, let d): (n, d)
243 default: nil
244 }
245 }
246
247 /// `math-make-frac`: reduced, as an integer when it is one.
248 static func fraction(_ n: Int, _ d: Int) throws -> Value {
249 guard d != 0 else { throw Unsupported("division by zero") }
250 guard n != .min, d != .min else { throw Unsupported("integer size") }
251 func gcd(_ a: Int, _ b: Int) -> Int { b == 0 ? abs(a) : gcd(b, a % b) }
252 let g = gcd(n, d)
253 var (num, den) = (n / g, d / g)
254 if den < 0 { (num, den) = (-num, -den) }
255 return den == 1 ? .int(num) : .frac(num, den)
256 }
257
258 /// Two rationals, one of them a fraction, combined exactly; nil otherwise.
259 static func exact(_ a: Value, _ b: Value, _ op: (Int, Int, Int, Int) -> (Int, Int, Bool)) throws -> Value? {
260 var fraction = false
261 if case .frac = a { fraction = true }
262 if case .frac = b { fraction = true }
263 guard fraction, let (n1, d1) = rational(a), let (n2, d2) = rational(b) else { return nil }
264 let (n, d, overflow) = op(n1, d1, n2, d2)
265 if overflow { throw Unsupported("integer size") }
266 return try self.fraction(n, d)
267 }
268
269 static func double(_ v: Value) throws -> Double {
270 switch v {
271 case .int(let i): return Double(i)
272 case .float(let m, let e): return Double(m) * pow(10, Double(e))
273 case .frac(let n, let d): return Double(n) / Double(d)
274 case .vector: throw Unsupported("vector arithmetic")
275 case .date, .nan: throw Unsupported("date arithmetic")
276 case .symbolic: throw Unsupported("symbolic arithmetic")
277 }
278 }
279
280 static func fromDouble(_ d: Double) throws -> Value {
281 // Calc works these out at two digits more; past 16 it uses its own series.
282 guard precision <= 14 else { throw Unsupported("calc precision") }
283 guard d.isFinite else { throw Unsupported("infinite result") }
284 if d == 0 { return .float(0, 0) }
285 // Seventeen significant digits are exact for a Double; rounding to 12 follows.
286 let text = String(format: "%.16e", d)
287 let pieces = text.split(separator: "e")
288 let digitsText = pieces[0].replacingOccurrences(of: ".", with: "")
289 guard let mantissa = Int128(digitsText), let exponent = Int(pieces[1]) else { throw Unsupported("number") }
290 return try makeFloat(mantissa, exponent - 16)
291 }
292
293 static func isSymbolic(_ vs: Value...) -> Bool {
294 vs.contains { if case .symbolic = $0 { true } else { false } }
295 }
296
297 static func add(_ a: Value, _ b: Value) throws -> Value {
298 if isSymbolic(a, b) { return value(try Symbolic.add(try term(a), try term(b))) }
299 switch (a, b) {
300 case (.nan, .vector), (.vector, .nan): throw Unsupported("vector arithmetic")
301 case (.nan, _), (_, .nan): return .nan
302 // Two dates add as their day numbers.
303 case (.date(let x), .date(let y)): return try add(x, y)
304 case (.date(let d), _): return .date(try add(d, b))
305 case (_, .date(let d)): return .date(try add(a, d))
306 default: break
307 }
308 if case .int(let x) = a, case .int(let y) = b {
309 let (sum, overflow) = x.addingReportingOverflow(y)
310 if overflow { throw Unsupported("integer size") }
311 return .int(sum)
312 }
313 if let sum = try exact(a, b, { n1, d1, n2, d2 in
314 let (p, o1) = n1.multipliedReportingOverflow(by: d2)
315 let (q, o2) = n2.multipliedReportingOverflow(by: d1)
316 let (n, o3) = p.addingReportingOverflow(q)
317 let (d, o4) = d1.multipliedReportingOverflow(by: d2)
318 return (n, d, o1 || o2 || o3 || o4)
319 }) { return sum }
320 let (m1, e1) = try parts(a)
321 let (m2, e2) = try parts(b)
322 if m1 == 0 { return try makeFloat(m2, e2) }
323 if m2 == 0 { return try makeFloat(m1, e1) }
324 let ediff = e1 - e2
325 if ediff >= 0 {
326 if ediff >= 2 * precision { return try makeFloat(m1, e1) }
327 return try makeFloat(try scaleRounding(m1, ediff) + m2, e2)
328 }
329 if -ediff >= 2 * precision { return try makeFloat(m2, e2) }
330 return try makeFloat(m1 + (try scaleRounding(m2, -ediff)), e1)
331 }
332
333 static func negate(_ a: Value) throws -> Value {
334 switch a {
335 case .symbolic(let t): return value(try Symbolic.neg(t))
336 case .int(let i):
337 guard i != .min else { throw Unsupported("integer size") }
338 return .int(-i)
339 case .float(let m, let e): return .float(-m, e)
340 case .frac(let n, let d): return .frac(-n, d)
341 case .vector: throw Unsupported("vector arithmetic")
342 case .date(let d): return .date(try negate(d))
343 case .nan: return .nan
344 }
345 }
346
347 /// `a - b`: a date less a date is the days between them.
348 static func subtract(_ a: Value, _ b: Value) throws -> Value {
349 try add(a, try negate(b))
350 }
351
352 static func isNaN(_ a: Value, _ b: Value) -> Bool {
353 if case .vector = a { return false }
354 if case .vector = b { return false }
355 return a == .nan || b == .nan
356 }
357
358 static func multiply(_ a: Value, _ b: Value) throws -> Value {
359 if isSymbolic(a, b) { return value(try Symbolic.mul(try term(a), try term(b))) }
360 if isNaN(a, b) { return .nan }
361 if case .int(let x) = a, case .int(let y) = b {
362 let (product, overflow) = x.multipliedReportingOverflow(by: y)
363 if overflow { throw Unsupported("integer size") }
364 return .int(product)
365 }
366 if let product = try exact(a, b, { n1, d1, n2, d2 in
367 let (n, o1) = n1.multipliedReportingOverflow(by: n2)
368 let (d, o2) = d1.multipliedReportingOverflow(by: d2)
369 return (n, d, o1 || o2)
370 }) { return product }
371 let (m1, e1) = try parts(a)
372 let (m2, e2) = try parts(b)
373 let (product, overflow) = m1.multipliedReportingOverflow(by: m2)
374 if overflow { throw Unsupported("number size") }
375 return try makeFloat(product, e1 + e2)
376 }
377
378 static func divide(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value {
379 // `math-div-by-zero` leaves the quotient alone.
380 if isSymbolic(a, b) || (isZero(b) && (try? sign(a)) != nil) {
381 return try $fractions.withValue(fractions) { value(try Symbolic.div(try term(a), try term(b))) }
382 }
383 if isNaN(a, b) { return .nan }
384 if fractions || { if case .frac = a { return true }; if case .frac = b { return true }; return false }(),
385 let (n1, d1) = rational(a), let (n2, d2) = rational(b) {
386 guard n2 != 0 else { throw Unsupported("division by zero") }
387 let (n, o1) = n1.multipliedReportingOverflow(by: d2)
388 let (d, o2) = d1.multipliedReportingOverflow(by: n2)
389 if o1 || o2 { throw Unsupported("integer size") }
390 return try fraction(n, d)
391 }
392 if case .int(let x) = a, case .int(let y) = b {
393 guard y != 0 else { throw Unsupported("division by zero") }
394 if x % y == 0 { return .int(x / y) }
395 }
396 let (m1, e1) = try parts(a)
397 let (m2, e2) = try parts(b)
398 guard m2 != 0 else { throw Unsupported("division by zero") }
399 // `math-div-float`: scale so the truncated quotient has one digit more than needed.
400 let ldiff = max(precision + 1 - (digits(m1) - digits(m2)), 0)
401 let quotient = (try scaleRounding(m1, ldiff)) / m2
402 return try makeFloat(quotient, e1 - ldiff - e2)
403 }
404
405 static func isInteger(_ v: Value) -> Bool {
406 if case .int = v { return true }
407 return false
408 }
409
410 /// `math-ipow`.
411 static func integerPower(_ a: Value, _ n: Int, fractions: Bool = false) throws -> Value {
412 if n < 0 { return try integerPower(try divide(.int(1), a, fractions: fractions), -n) }
413 if n == 0 { return .int(1) }
414 if n == 1 { return a }
415 let square = try multiply(a, a)
416 if n % 2 == 0 { return try integerPower(square, n / 2) }
417 return try multiply(a, try integerPower(square, n / 2))
418 }
419
420 /// `math-pow` of real numbers.
421 static func power(_ a: Value, _ b: Value, fractions: Bool = false) throws -> Value {
422 // In symbolic mode Calc keeps a power that isn't exact, which isn't reproduced.
423 if symbolicMode, !isInteger(b) { throw Unsupported("symbolic mode") }
424 if isSymbolic(a, b) { return try $fractions.withValue(fractions) { value(try Symbolic.pow(try term(a), try term(b))) } }
425 if isNaN(a, b) { return .nan }
426 _ = (try sign(a), try sign(b))
427 var floatB = false
428 if case .float = b { floatB = true }
429 if isZero(a) {
430 // `math-pow-of-zero`: an indeterminate form, or a division by zero, stays alone.
431 if b == .int(0) { return .int(1) }
432 guard try sign(b) > 0 else { throw Rejected() }
433 return floatB ? try float(a) : a
434 }
435 if a == .int(1) || b == .int(1) || a == .float(1, 0) || b == .float(1, 0) { return a }
436 if isZero(b) {
437 if case .float = a { return .float(1, 0) }
438 return floatB ? .float(1, 0) : .int(1)
439 }
440 if case .int(let n) = b {
441 if a == .float(1, 1) { return try makeFloat(1, n) }
442 return try extra(2) { try integerPower(a, n, fractions: fractions) }
443 }
444 // `math-pow-fancy`.
445 if let q = quarter(b), (1...3).contains(q) {
446 let root = try squareRoot(floatB ? try float(a) : a)
447 return try power(root, try multiply(.int(2), b), fractions: fractions)
448 }
449 if case .frac(let num, let den) = b, den <= 10, try sign(a) > 0 {
450 return try integerPower(try nthRoot(a, den), num, fractions: fractions)
451 }
452 if a == .int(10) || a == .float(1, 1), isWhole(b) { return try makeFloat(1, try trunc(b)) }
453 guard try sign(a) > 0 else { throw Unsupported("complex result") }
454 return try extra(2) { try expRaw(try float(try multiply(b, try lnRaw(try float(a))))) }
455 }
456
457 /// `math-quarter-integer`: 0 for an integer, 1 to 3 for a number of quarters, else nil.
458 static func quarter(_ x: Value) -> Int? {
459 switch x {
460 case .int: return 0
461 case .frac(let n, let d):
462 if n < 0 { return quarter(.frac(-n, d)).map { 4 - $0 } }
463 return d == 2 ? 2 : d == 4 ? n % 4 : nil
464 case .float(let m, let e):
465 if m < 0 { return quarter(.float(-m, e)).map { 4 - $0 } }
466 if e >= 0 { return 0 }
467 if e == -1 { return m % 10 == 5 ? 2 : nil }
468 if e == -2 { return m % 100 == 25 ? 1 : m % 100 == 75 ? 3 : nil }
469 return nil
470 default: return nil
471 }
472 }
473
474 static func compare(_ a: Value, _ b: Value) throws -> Int {
475 if case .date(let x) = a, case .date(let y) = b { return try compare(x, y) }
476 if a == .nan || b == .nan { throw Unsupported("comparison with nan") }
477 let difference = try add(a, try negate(b))
478 let (m, _) = try parts(difference)
479 return m == 0 ? 0 : (m < 0 ? -1 : 1)
480 }
481
482 static func absolute(_ v: Value) throws -> Value { try sign(v) < 0 ? try negate(v) : v }
483
484 /// `math-floor` of a real number, as an integer.
485 static func floorInt(_ v: Value) throws -> Int {
486 let t = try trunc(v)
487 return try sign(v) < 0 && compare(v, .int(t)) != 0 ? t - 1 : t
488 }
489
490 // MARK: - Roots, logarithms and rounding
491
492 /// `math-sqrt` of a real number.
493 static func squareRoot(_ a: Value) throws -> Value {
494 if isZero(a) { return a }
495 guard try sign(a) > 0 else { throw Unsupported("complex result") }
496 func exact(_ i: Int) -> Int? {
497 let guess = Int(Double(i).squareRoot())
498 return [guess - 1, guess, guess + 1].first { $0 >= 0 && $0.multipliedReportingOverflow(by: $0) == (i, false) }
499 }
500 if case .int(let i) = a, let root = exact(i) { return .int(root) }
501 if case .frac(let n, let d) = a, let rn = exact(n), let rd = exact(d) { return .frac(rn, rd) }
502 let x = try float(a)
503 return try extra(1) { try squareRootRaw(x) }
504 }
505
506 /// `math-sqrt-raw` of a float.
507 static func squareRootRaw(_ a: Value) throws -> Value {
508 if isZero(a) { return a }
509 guard try sign(a) > 0 else { throw Unsupported("complex result") }
510 return try emacs({ $0.squareRoot() }, a)
511 }
512
513 /// `math-exp-raw` of a float.
514 static func expRaw(_ x: Value) throws -> Value {
515 isZero(x) ? .float(1, 0) : try emacs({ Foundation.exp($0) }, x)
516 }
517
518 /// `math-ln-raw` of a float.
519 static func lnRaw(_ x: Value) throws -> Value {
520 if x == .float(1, 0) { return .float(0, 0) }
521 guard try sign(x) > 0 else { throw Unsupported("logarithm domain") }
522 return try emacs({ Foundation.log($0) }, x)
523 }
524
525 /// `math-arctan-raw` of a float.
526 static func arctanRaw(_ x: Value) throws -> Value {
527 if try sign(x) < 0 { return try negate(try arctanRaw(try negate(x))) }
528 return isZero(x) ? x : try emacs({ Foundation.atan($0) }, x)
529 }
530
531 static func ln2() throws -> Value { try makeFloat(693147180559945309417232121458176568, -36) }
532 static func ln10() throws -> Value { try makeFloat(230258509299404568401799145468436421, -35) }
533
534 /// `math-ln-raw-2`: the logarithm of a positive float by Calc's series.
535 static func lnRaw2(_ x: Value) throws -> Value {
536 if try compare(.float(14, -1), x) < 0 { return try add(try lnRaw2(try multiply(x, .float(5, -1))), try ln2()) }
537 let y = try divide(try subtract(x, .float(1, 0)), try add(x, .float(1, 0)))
538 let square = try multiply(y, y)
539 var (sum, power, n) = (y, y, 3)
540 for _ in 0..<10000 {
541 power = try multiply(power, square)
542 let next = try add(sum, try divide(power, try float(.int(n))))
543 if nearlyEqual(sum, next) { return try multiply(sum, .float(2, 0)) }
544 (sum, n) = (next, n + 2)
545 }
546 throw Unsupported("number")
547 }
548
549 /// `math-nth-root-integer`: the integer root rounded down, and whether it is exact.
550 static func integerRoot(_ a: Int, _ n: Int) throws -> (Bool, Int) {
551 let a = Int128(a)
552 var guess = try power10((digits(a) + n - 1) / n)
553 while true {
554 var p: Int128 = 1
555 for _ in 0..<(n - 1) {
556 let (r, overflow) = p.multipliedReportingOverflow(by: guess)
557 if overflow { throw Unsupported("integer size") }
558 p = r
559 }
560 let (q, r) = a.quotientAndRemainder(dividingBy: p)
561 let (g2, r2) = (q + Int128(n - 1) * guess).quotientAndRemainder(dividingBy: Int128(n))
562 if g2 < guess {
563 guess = g2
564 continue
565 }
566 return (g2 == guess && r == 0 && r2 == 0, Int(guess))
567 }
568 }
569
570 /// `math-nth-root-float`: Newton's method at one digit more.
571 static func floatRoot(_ a: Value, _ n: Int, guess: Value? = nil) throws -> Value {
572 try extra(1) {
573 guard case .float(let m, let e) = a else { throw Unsupported("arguments") }
574 let nf = try makeFloat(Int128(n), 0)
575 let nfm1 = try makeFloat(Int128(n - 1), 0)
576 var g = try guess ?? makeFloat(1, (digits(Int128(m)) + e + n / 2) / n)
577 for _ in 0..<1000 {
578 let g2 = try divide(try add(try multiply(nfm1, g), try divide(a, try integerPower(g, n - 1))), nf)
579 if nearlyEqual(g2, g) { return g2 }
580 g = g2
581 }
582 throw Unsupported("number")
583 }
584 }
585
586 /// `math-nth-root` of a positive real number.
587 static func nthRoot(_ a: Value, _ n: Int) throws -> Value {
588 switch a {
589 case .int(let i):
590 let (exact, root) = try integerRoot(i, n)
591 return exact ? .int(root) : try floatRoot(try float(a), n, guess: try float(.int(root)))
592 case .frac(let num, let den):
593 let (e1, r1) = try integerRoot(num, n)
594 let (e2, r2) = try integerRoot(den, n)
595 if e1 && e2 { return .frac(r1, r2) }
596 return try floatRoot(try float(a), n, guess: try divide(try float(.int(r1)), try float(.int(r2))))
597 default:
598 return try floatRoot(a, n)
599 }
600 }
601
602 /// `math-pow` of a real number to the power `1:n`.
603 static func rootPower(_ a: Value, _ n: Int) throws -> Value {
604 if isZero(a) || a == .int(1) || a == .float(1, 0) { return a }
605 guard try sign(a) > 0 else { throw Unsupported("complex result") }
606 switch n {
607 case 1: return a
608 case 2: return try squareRoot(a)
609 case 4: return try squareRoot(try squareRoot(a))
610 case 3...10: return try nthRoot(a, n)
611 default: return try extra(2) { try expRaw(try float(try multiply(.frac(1, n), try lnRaw(try float(a))))) }
612 }
613 }
614
615 /// `math-integer-log`: the largest n with b^n at most x, and whether b^n is x.
616 static func integerLog(_ x: Value, _ b: Value) throws -> (Bool, Int) {
617 var pows = [b]
618 var pow = try multiply(b, b)
619 while try compare(x, pow) >= 0 {
620 pows.insert(pow, at: 0)
621 pow = try multiply(pow, pow)
622 }
623 var n = 1 << (pows.count - 1)
624 var sum = n
625 pow = pows[0]
626 var rest = pows.dropFirst()
627 while let next = rest.first, try compare(pow, x) < 0 {
628 rest = rest.dropFirst()
629 n /= 2
630 let candidate = try multiply(pow, next)
631 if try compare(x, candidate) >= 0 {
632 pow = candidate
633 sum += n
634 }
635 }
636 return (pow == x, sum)
637 }
638
639 /// `math-round` in `math-rounding-mode` `even` or `up`.
640 static func round(_ a: Value, even: Bool) throws -> Value {
641 if isWhole(a) { return .int(try trunc(a)) }
642 if try sign(a) < 0, even { return try negate(try round(try negate(a), even: even)) }
643 let b = try add(a, rational(a) != nil ? .frac(1, 2) : .float(5, -1))
644 var f = try floorInt(b)
645 if even, isWhole(b), f % 2 != 0 { f -= 1 }
646 return .int(f)
647 }
648
649 /// `calcFunc-scf`: `x` times 10^n.
650 static func scale(_ x: Value, _ n: Int, fractions: Bool) throws -> Value {
651 if n == 0 { return x }
652 guard abs(n) <= 18 else { throw Unsupported("number size") }
653 let p = Int(try power10(abs(n)))
654 switch x {
655 case .int: return n > 0 ? try multiply(x, .int(p)) : try divide(x, .int(p), fractions: fractions)
656 case .frac(let a, let b):
657 let (num, o1) = a.multipliedReportingOverflow(by: n > 0 ? p : 1)
658 let (den, o2) = b.multipliedReportingOverflow(by: n > 0 ? 1 : p)
659 if o1 || o2 { throw Unsupported("integer size") }
660 return try fraction(num, den)
661 case .float(let m, let e): return try makeFloat(Int128(m), e + n)
662 default: throw Unsupported("arguments")
663 }
664 }
665
666 /// `calcFunc-frac`: the fraction closest to a float within its precision.
667 static func toFraction(_ a: Value) throws -> Value {
668 if rational(a) != nil { return a }
669 if isWhole(a) { return .int(try trunc(a)) }
670 if try sign(a) < 0 { return try negate(try toFraction(try negate(a))) }
671 guard case .float(let m, let e) = a else { throw Unsupported("arguments") }
672 let tolerance = Value.float(5, digits(Int128(m)) + e - (1 + precision))
673 /// `math-eval-continued-fraction`.
674 func evaluate(_ terms: [Int], fractions: Bool) throws -> Value {
675 var n = Value.int(terms.last!)
676 var d = Value.int(1)
677 for c in terms.reversed().dropFirst() { (n, d) = (try add(try multiply(.int(c), n), d), n) }
678 return try divide(n, d, fractions: fractions)
679 }
680 let terms = try $precision.withValue(precision + 2) {
681 var terms: [Int] = []
682 var aa = a
683 while try terms.isEmpty || (!isZero(aa) && compare(try absolute(try subtract(a, try evaluate(terms, fractions: false))), tolerance) >= 0) {
684 guard terms.count < 100 else { throw Unsupported("number") }
685 let whole = try trunc(aa)
686 aa = try subtract(aa, .int(whole))
687 terms.append(whole)
688 if !isZero(aa) { aa = try divide(.int(1), aa) }
689 }
690 return terms
691 }
692 return try evaluate(terms, fractions: true)
693 }
694
695 /// `calcFunc-gcd`.
696 static func gcd(_ a: Value, _ b: Value) throws -> Value {
697 func gcd(_ a: Int, _ b: Int) -> Int { b == 0 ? abs(a) : gcd(b, a % b) }
698 let a = isWhole(a) ? .int(try trunc(a)) : a
699 let b = isWhole(b) ? .int(try trunc(b)) : b
700 if case .int(let x) = a, case .int(let y) = b {
701 guard x != .min, y != .min else { throw Unsupported("integer size") }
702 return .int(gcd(x, y))
703 }
704 if try sign(a) < 0 { return try Calc.gcd(try negate(a), b) }
705 if try sign(b) < 0 { return try Calc.gcd(a, try negate(b)) }
706 guard let (n1, d1) = rational(a), let (n2, d2) = rational(b) else { throw Unsupported("arguments") }
707 guard case .int(let g) = try Calc.gcd(.int(d1), .int(d2)) else { throw Unsupported("arguments") }
708 let (product, overflow) = d1.multipliedReportingOverflow(by: d2 / g)
709 if overflow { throw Unsupported("integer size") }
710 return try fraction(gcd(n1, n2), product)
711 }
712
713 /// `calcFunc-choose` of integers.
714 static func choose(_ n: Int, _ m: Int) throws -> Int {
715 if m >= 0, m <= n {
716 var c = 1
717 var top = n
718 for i in stride(from: 1, through: m > n / 2 ? n - m : m, by: 1) {
719 let (product, overflow) = c.multipliedReportingOverflow(by: top)
720 if overflow { throw Unsupported("integer size") }
721 c = product / i
722 top -= 1
723 }
724 return c
725 }
726 if n < 0, m >= 0 {
727 let v = try choose(m - n - 1, m)
728 return m % 2 == 0 ? v : -v
729 }
730 if n < 0 {
731 if n < m { return 0 }
732 let v = try choose(-m - 1, n - m)
733 return (n - m) % 2 == 0 ? v : -v
734 }
735 return 0
736 }
737
738 // MARK: - Display
739
740 /// `math-format-number`.
741 static func format(_ value: Value, _ floatFormat: FloatFormat) throws -> String {
742 switch value {
743 case .int(let i): return String(i)
744 case .frac(let n, let d): return "\(n):\(d)"
745 case .vector: throw Unsupported("vector result")
746 case .symbolic(let t): return try Symbolic.format(t, floatFormat)
747 case .nan: return "nan"
748 case .date(let d): return "<" + (try formatDate(d)) + ">"
749 case .float(let m, _) where m < 0:
750 guard case .float(let m, let e) = value else { fatalError() }
751 return "-" + (try format(.float(-m, e), floatFormat))
752 case .float(let m, var exp):
753 var mant = Int128(m)
754 var figs: Int
755 let kind: String
756 switch floatFormat {
757 case .float(let n): (figs, kind) = (n, "float")
758 case .fix(let n): (figs, kind) = (n, "fix")
759 case .sci(let n): (figs, kind) = (n, "sci")
760 case .eng(let n): (figs, kind) = (n, "eng")
761 }
762 if kind == "fix", figs < 0 || exp + digits(mant) > -figs {
763 if figs < 0 { figs = -figs }
764 mant = try scaleRounding(mant, exp + figs)
765 var str = String(mant)
766 if str.count <= figs { str = String(repeating: "0", count: figs + 1 - str.count) + str }
767 if figs > 0 {
768 return String(str.dropLast(figs)) + "." + String(str.suffix(figs))
769 }
770 return str + "."
771 }
772 if figs < 0 { figs += precision }
773 if figs > 0 {
774 let adj = figs - digits(mant)
775 if adj < 0 {
776 mant = try scaleRounding(mant, adj)
777 exp -= adj
778 }
779 }
780 var str = String(mant)
781 let len = str.count
782 let dpos = exp + len
783 // `calc-display-sci-high` 0, `calc-display-sci-low` -3.
784 if kind == "float", dpos <= precision, dpos >= -1 {
785 if dpos == 0 {
786 str = "0." + str
787 } else if exp <= 0, dpos > 0 {
788 str = String(str.prefix(dpos)) + "." + String(str.dropFirst(dpos))
789 } else if exp > 0 {
790 str += String(repeating: "0", count: exp) + "."
791 } else {
792 str = "0." + String(repeating: "0", count: -dpos) + str
793 }
794 return str
795 }
796 let eadj = exp + len
797 let scale = kind == "eng" ? 1 + ((eadj + 300002) % 3) : 1
798 if scale > str.count { str += String(repeating: "0", count: scale - str.count) }
799 if scale < str.count { str = String(str.prefix(scale)) + "." + String(str.dropFirst(scale)) }
800 return str + "e" + String(eadj - scale)
801 }
802 }
803
804 static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
805
806 /// `calc-date-format` as Org sets it: `YYYY-MM-DD Www`, then ` hh:mm` for a day number
807 /// that isn't an integer.
808 static func formatDate(_ value: Value) throws -> String {
809 let dt = try dateParts(value)
810 let year = dt.year > 0 && dt.year < 100 ? "+\(dt.year)" : String(dt.year)
811 var text = year + String(format: "-%02d-%02d ", dt.month, dt.day) + weekdays[Days.weekday(try floorInt(value))]
812 if let time = dt.time { text += String(format: " %02d:%02d", time.hour, time.minute) }
813 return text
814 }
815
816 /// A date form `<YYYY-MM-DD Www>` or `<YYYY-MM-DD Www hh:mm>`, from the text between
817 /// the brackets.
818 static func parseDate(_ text: String) throws -> Value {
819 guard let m = text.firstMatch(of: /^([0-9]{4})-([0-9]{2})-([0-9]{2})(?: +[A-Za-z]+)?(?: +([0-9]{1,2}):([0-9]{2})(?::([0-9]{2}))?)?$/) else {
820 throw Unsupported("date syntax")
821 }
822 // `math-parse-date-validate`: a year under 100 is 19xx or 20xx.
823 var year = Int(m.1)!
824 if year < 100 { year += year < 40 ? 2000 : 1900 }
825 let day = Days.absolute(year: year, month: Int(m.2)!, day: Int(m.3)!)
826 guard let hour = m.4.flatMap({ Int($0) }), let minute = m.5.flatMap({ Int($0) }) else { return .date(.int(day)) }
827 return try dateTime(day, hour * 3600 + minute * 60 + (m.6.flatMap { Int($0) } ?? 0))
828 }
829
830 // MARK: - Dates
831
832 /// Calc numbers years without a year 0: -1 comes before 1.
833 static func astronomical(_ year: Int) -> Int { year > 0 ? year : year == 0 ? 0 : year + 1 }
834
835 /// `math-absolute-from-gregorian-dt`.
836 static func absolute(_ year: Int, _ month: Int, _ day: Int) throws -> Int {
837 guard abs(year) < 1_000_000_000 else { throw Unsupported("number size") }
838 return Days.absolute(year: astronomical(year), month: month, day: day)
839 }
840
841 /// `math-days-in-month`.
842 static func daysInMonth(_ year: Int, _ month: Int) throws -> Int {
843 try absolute(year, month + 1, 1) - absolute(year, month, 1)
844 }
845
846 /// `math-dt-to-date` with a time of day: a float day number.
847 static func dateTime(_ day: Int, _ seconds: Int) throws -> Value {
848 .date(try add(try float(.int(day)), try divide(.int(seconds), .float(864, 2))))
849 }
850
851 /// `math-dt-to-date`.
852 static func dateValue(_ year: Int, _ month: Int, _ day: Int, _ time: (hour: Int, minute: Int, second: Int)? = nil) throws -> Value {
853 guard (1...12).contains(month), (1...31).contains(day) else { throw Unsupported("arguments") }
854 let n = try absolute(year, month, day)
855 guard let time else { return .date(.int(n)) }
856 guard [time.hour, time.minute, time.second].allSatisfy({ abs($0) < 1_000_000 }) else { throw Unsupported("arguments") }
857 return try dateTime(n, time.hour * 3600 + time.minute * 60 + time.second)
858 }
859
860 /// The day number of a date form, or a real number, which Calc's date functions also take.
861 static func dayNumber(_ v: Value) throws -> Value {
862 let x: Value = if case .date(let d) = v { d } else { v }
863 _ = try sign(x)
864 return x
865 }
866
867 /// `math-date-to-dt`: the day, with the time of day when the day number isn't an integer.
868 static func dateParts(_ v: Value) throws -> (year: Int, month: Int, day: Int, time: (hour: Int, minute: Int, second: Int)?) {
869 let x = try dayNumber(v)
870 let day = try floorInt(x)
871 guard abs(day) < 100_000_000_000 else { throw Unsupported("number size") }
872 let date = Days.date(day)
873 let year = date.year > 0 ? date.year : date.year - 1
874 if case .int = x { return (year, date.month, date.day, nil) }
875 // Above 12 digits Calc keeps fractions of a second.
876 guard precision <= 12 else { throw Unsupported("calc precision") }
877 let seconds = try trunc(try round(try multiply(try subtract(x, .int(day)), .int(86400)), even: false))
878 return (year, date.month, date.day, (seconds / 3600, seconds / 60 % 60, seconds % 60))
879 }
880
881 /// `math-to-business-day`, with Calc's default holidays: Saturdays and Sundays.
882 static func toBusinessDay(_ v: Value) throws -> (Value, holiday: Bool) {
883 let x = try dayNumber(v)
884 let day = try floorInt(x)
885 try checkHolidayRange(day)
886 let weekday = Days.weekday(day)
887 let delta = day / 7 * 2 + (weekday > 0 ? 1 : 0)
888 return (try add(.int(day - delta), try subtract(x, .int(day))), weekday == 0 || weekday == 6)
889 }
890
891 /// `math-setup-holidays` with a date: Calc's holidays cover the years 1 to 2737.
892 static func checkHolidayRange(_ day: Int) throws {
893 guard (try absolute(1, 1, 1)...absolute(2737, 12, 31)).contains(day) else { throw Unsupported("arguments") }
894 }
895
896 /// `math-from-business-day`.
897 static func fromBusinessDay(_ n: Value) throws -> Value {
898 var day = try floorInt(n)
899 let time = try subtract(n, .int(day))
900 var left = ((day % 5) + 5) % 5
901 day += day / 5 * 2
902 var weekday = 0
903 while true {
904 if weekday == 0 || weekday == 6 {
905 day += 1
906 } else {
907 left -= 1
908 if left < 0 { break }
909 }
910 weekday += 1
911 }
912 try checkHolidayRange(day)
913 return .date(try add(.int(day), time))
914 }
915
916 /// `calcFunc-tzone` for the local zone, in seconds. Calc applies the current year's
917 /// daylight saving rules to every date, which isn't reproduced, so only zones without
918 /// daylight saving time are supported.
919 static func zoneOffset(_ zone: TimeZone) throws -> Int {
920 guard !zone.isDaylightSavingTime(), zone.nextDaylightSavingTimeTransition == nil else {
921 throw Unsupported("daylight saving time")
922 }
923 return -zone.secondsFromGMT()
924 }
925
926 // MARK: - Parsing
927
928 indirect enum Node {
929 case number(Value)
930 case vector([Node])
931 case unary(Character, Node)
932 case binary(Character, Node, Node)
933 case call(String, [Node])
934 case variable(String)
935
936 /// Whether the formula has a quotient, a power, a function call, or a product
937 /// whose factors share a variable, which Calc simplifies to a power.
938 var mayExplain: Bool {
939 switch self {
940 case .number, .variable: false
941 case .call: true
942 case .vector(let items): items.contains { $0.mayExplain }
943 case .unary(_, let a): a.mayExplain
944 case .binary("*", let a, let b) where !a.variables.isDisjoint(with: b.variables): true
945 case .binary(let op, let a, let b): "/%\\^".contains(op) || a.mayExplain || b.mayExplain
946 }
947 }
948
949 var variables: Set<String> {
950 switch self {
951 case .number: []
952 case .variable(let name): [name]
953 case .call(_, let items), .vector(let items): items.reduce(into: []) { $0.formUnion($1.variables) }
954 case .unary(_, let a): a.variables
955 case .binary(_, let a, let b): a.variables.union(b.variables)
956 }
957 }
958 }
959
960 struct Parser {
961 let chars: [Character]
962 var i = 0
963 /// Inside `[...]`, where Calc reads `x -1` as two elements.
964 var inVector = false
965 /// Inside `[...]` with no comma, where Calc reads `1 2` as two elements.
966 var spaceSeparated = false
967
968 init(_ s: String) { chars = Array(s) }
969
970 mutating func skip() {
971 while i < chars.count, chars[i] == " " || chars[i] == "\t" { i += 1 }
972 }
973
974 mutating func peek() -> Character? {
975 skip()
976 return i < chars.count ? chars[i] : nil
977 }
978
979 mutating func parse() throws -> Node {
980 let node = try or()
981 guard peek() == nil else { throw Unsupported("formula syntax") }
982 return node
983 }
984
985 mutating func take(_ token: String) -> Bool {
986 guard peek() != nil else { return false }
987 let t = Array(token)
988 guard i + t.count <= chars.count, Array(chars[i..<(i + t.count)]) == t else { return false }
989 i += t.count
990 return true
991 }
992
993 // `||` < `&&` < `!` < comparisons < sums.
994 mutating func or() throws -> Node {
995 var left = try and()
996 while take("||") { left = .binary("|", left, try and()) }
997 return left
998 }
999
1000 mutating func and() throws -> Node {
1001 var left = try not()
1002 while take("&&") { left = .binary("&", left, try not()) }
1003 return left
1004 }
1005
1006 mutating func not() throws -> Node {
1007 if peek() == "!", i + 1 >= chars.count || chars[i + 1] != "=" {
1008 i += 1
1009 return .unary("!", try not())
1010 }
1011 return try comparison()
1012 }
1013
1014 mutating func comparison() throws -> Node {
1015 let left = try sum()
1016 // Calc reads `<<` and `>>` as one token, so `1<<2026-10-05 Mon>` is a syntax error.
1017 if take("<<") || take(">>") { throw Unsupported("formula syntax") }
1018 for (token, op) in [("==", "="), ("!=", "≠"), ("<=", "≤"), (">=", "≥"), ("<", "<"), (">", ">")] where take(token) {
1019 let right = try sum()
1020 if let next = peek(), "=!<>".contains(next) { throw Unsupported("chained comparison") }
1021 return .binary(Character(op), left, right)
1022 }
1023 return left
1024 }
1025
1026 // `+ -` < `/` < `*` < unary minus < `^`, as Calc's operator table orders them.
1027 mutating func sum() throws -> Node {
1028 var left = try quotient()
1029 while let c = peek(), c == "+" || c == "-" {
1030 if inVector, i > 0, chars[i - 1] == " " || chars[i - 1] == "\t", i + 1 < chars.count, chars[i + 1] != " ", chars[i + 1] != "\t" {
1031 throw Unsupported("formula syntax")
1032 }
1033 i += 1
1034 left = .binary(c, left, try quotient())
1035 }
1036 return left
1037 }
1038
1039 mutating func quotient() throws -> Node {
1040 var left = try product()
1041 while let c = peek(), c == "/" || c == "%" || c == "\\" {
1042 i += 1
1043 left = .binary(c, left, try product())
1044 }
1045 return left
1046 }
1047
1048 /// `*`, and juxtaposition `2 3` or `2 (x)`, which Calc reads as `*`. With
1049 /// `calc-multiplication-has-precedence` both are right-associative: `a * b c` and
1050 /// `a * b * c` are `a * (b * c)`.
1051 mutating func product() throws -> Node {
1052 let left = try unary()
1053 guard let c = peek() else { return left }
1054 if c == "*" {
1055 i += 1
1056 } else if !(c.isASCII && c.isNumber) && !c.isLetter && c != "(" && c != "["
1057 && !(c == "." && i + 1 < chars.count && chars[i + 1].isASCII && chars[i + 1].isNumber) {
1058 return left
1059 } else if spaceSeparated, chars[i - 1] == " " || chars[i - 1] == "\t" {
1060 // Calc reads `[1 2]` as two elements and `[1 2 * 3]` as one; not reproduced.
1061 throw Unsupported("formula syntax")
1062 }
1063 return .binary("*", left, try product())
1064 }
1065
1066 /// `math-factor-after`: whether what follows can start an operand, which makes `%`
1067 /// the modulo operator rather than percent.
1068 func factorAfter(_ j: Int) -> Bool {
1069 var j = j
1070 while j < chars.count, chars[j] == " " || chars[j] == "\t" { j += 1 }
1071 guard j < chars.count else { return false }
1072 let c = chars[j]
1073 if c == ".", j + 1 < chars.count { return chars[j + 1].isASCII && chars[j + 1].isNumber }
1074 return (c.isASCII && c.isNumber) || c.isLetter || "$#\"-+!([{".contains(c)
1075 }
1076
1077 mutating func unary() throws -> Node {
1078 if let c = peek(), c == "-" || c == "+" {
1079 i += 1
1080 let operand = try unary()
1081 return c == "-" ? .unary("-", operand) : operand
1082 }
1083 return try powerNode()
1084 }
1085
1086 mutating func powerNode() throws -> Node {
1087 var base = try primary()
1088 // Postfix `%` (percent), `!` and `!!`, which bind tighter than `^`.
1089 while let c = peek() {
1090 let next = i + 1 < chars.count ? chars[i + 1] : nil
1091 if c == "%", !factorAfter(i + 1) {
1092 // `%%` starts a comment.
1093 if next == "%" { throw Unsupported("formula syntax") }
1094 i += 1
1095 base = .call("percent", [base])
1096 } else if c == "!", next != "=" {
1097 if next == "!" {
1098 if i + 2 < chars.count, chars[i + 2] == "!" { throw Unsupported("formula syntax") }
1099 i += 2
1100 base = .call("dfact", [base])
1101 } else {
1102 i += 1
1103 base = .call("fact", [base])
1104 }
1105 } else {
1106 break
1107 }
1108 }
1109 if peek() == "^" {
1110 i += 1
1111 return .binary("^", base, try unary())
1112 }
1113 return base
1114 }
1115
1116 mutating func primary() throws -> Node {
1117 guard let c = peek() else { throw Unsupported("formula syntax") }
1118 if c == "(" {
1119 i += 1
1120 let outer = (inVector, spaceSeparated)
1121 (inVector, spaceSeparated) = (false, false)
1122 let inner = try or()
1123 (inVector, spaceSeparated) = outer
1124 guard peek() == ")" else { throw Unsupported("formula syntax") }
1125 i += 1
1126 return inner
1127 }
1128 if c == "[" {
1129 i += 1
1130 let outer = (inVector, spaceSeparated)
1131 (inVector, spaceSeparated) = (true, !hasComma())
1132 defer { (inVector, spaceSeparated) = outer }
1133 var items: [Node] = []
1134 if peek() != "]" {
1135 items.append(try or())
1136 while peek() == "," {
1137 i += 1
1138 items.append(try or())
1139 }
1140 }
1141 guard peek() == "]" else { throw Unsupported("formula syntax") }
1142 i += 1
1143 return .vector(items)
1144 }
1145 if c.isASCII, c.isNumber || c == "." { return .number(try number()) }
1146 if c == "<" {
1147 guard let close = chars[i...].firstIndex(of: ">") else { throw Unsupported("formula syntax") }
1148 let text = String(chars[(i + 1)..<close])
1149 i = close + 1
1150 return .number(try parseDate(text))
1151 }
1152 if c.isLetter {
1153 var name = ""
1154 while i < chars.count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
1155 name.append(chars[i])
1156 i += 1
1157 }
1158 // `[f (x)]` is two elements.
1159 if spaceSeparated, i < chars.count, chars[i] != "(", peek() == "(" { throw Unsupported("formula syntax") }
1160 guard peek() == "(" else {
1161 if name == "nan" { return .number(.nan) }
1162 // Calc's names are letters and digits; `_` is a subscript, and `'` and `#`
1163 // belong to the name.
1164 guard name.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber) }), !reserved.contains(name),
1165 i >= chars.count || !"'#".contains(chars[i]) else { throw Unsupported("variable \(name)") }
1166 return .variable(name)
1167 }
1168 i += 1
1169 let outer = (inVector, spaceSeparated)
1170 (inVector, spaceSeparated) = (false, false)
1171 defer { (inVector, spaceSeparated) = outer }
1172 var args: [Node] = []
1173 if peek() != ")" {
1174 args.append(try or())
1175 while peek() == "," {
1176 i += 1
1177 args.append(try or())
1178 }
1179 }
1180 guard peek() == ")" else { throw Unsupported("formula syntax") }
1181 i += 1
1182 return .call(name, args)
1183 }
1184 throw Unsupported("formula syntax")
1185 }
1186
1187 /// `math-check-for-commas`: whether a comma follows before the bracket that closes.
1188 func hasComma() -> Bool {
1189 var depth = 0
1190 for c in chars[i...] {
1191 if "[{(".contains(c) { depth += 1 }
1192 if "]})".contains(c) { depth -= 1 }
1193 if depth < 0 { return false }
1194 if c == ",", depth == 0 { return true }
1195 }
1196 return false
1197 }
1198
1199 /// Calc's number syntax: `7`, `007`, `1.5`, `.5`, `5.`, `1e3`, `1.5e-3`, fractions `1:3`
1200 /// and `1:2:3`, and integers in a radix, `16#FF`.
1201 mutating func number() throws -> Value {
1202 var whole = ""
1203 while i < chars.count, chars[i].isASCII, chars[i].isNumber {
1204 whole.append(chars[i])
1205 i += 1
1206 }
1207 if !whole.isEmpty, i + 1 < chars.count, chars[i] == ":", chars[i + 1].isASCII, chars[i + 1].isNumber {
1208 var text = whole
1209 while i < chars.count, chars[i] == ":" || (chars[i].isASCII && chars[i].isNumber) {
1210 text.append(chars[i])
1211 i += 1
1212 }
1213 let parts = text.split(separator: ":", omittingEmptySubsequences: false).map { Int($0) }
1214 guard parts.count <= 3, !parts.contains(nil) else { throw Unsupported("formula syntax") }
1215 let n = parts.map { $0! }
1216 guard n.last != 0 else { throw Unsupported("formula syntax") }
1217 if n.count == 2 { return try fraction(n[0], n[1]) }
1218 let (product, o1) = n[0].multipliedReportingOverflow(by: n[2])
1219 let (sum, o2) = product.addingReportingOverflow(n[1])
1220 if o1 || o2 { throw Unsupported("integer size") }
1221 return try fraction(sum, n[2])
1222 }
1223 if !whole.isEmpty, i < chars.count, chars[i] == "#" {
1224 i += 1
1225 var text = ""
1226 while i < chars.count, chars[i].isASCII, chars[i].isLetter || chars[i].isNumber || chars[i] == "." || chars[i] == ":" || chars[i] == "#" {
1227 text.append(chars[i])
1228 i += 1
1229 }
1230 guard let radix = Int(whole), (2...36).contains(radix), !text.isEmpty,
1231 let value = Int(text, radix: radix) else { throw Unsupported("formula syntax") }
1232 return .int(value)
1233 }
1234 var fraction: String?
1235 // `2..5` is an interval, not `2.` then `.5`.
1236 if i < chars.count, chars[i] == ".", i + 1 >= chars.count || chars[i + 1] != "." {
1237 i += 1
1238 var f = ""
1239 while i < chars.count, chars[i].isASCII, chars[i].isNumber {
1240 f.append(chars[i])
1241 i += 1
1242 }
1243 fraction = f
1244 // Calc reads digits and points as one number: `21.11.2026` is a bad format.
1245 if i < chars.count, chars[i] == ".", i + 1 >= chars.count || chars[i + 1] != "." {
1246 while i < chars.count, (chars[i].isASCII && chars[i].isNumber)
1247 || (chars[i] == "." && (i + 1 >= chars.count || chars[i + 1] != ".")) { i += 1 }
1248 // The position is in the string Calc reads, after it rewrites `..` and
1249 // characters such as `²`; an exponent belongs to the number.
1250 let before = String(chars[..<i])
1251 guard before.allSatisfy(\.isASCII), !before.contains(".."),
1252 i >= chars.count || !"eE".contains(chars[i]) else { throw Unsupported("formula syntax") }
1253 throw Failure("Bad format", position: i)
1254 }
1255 }
1256 var exponent: Int?
1257 if i < chars.count, chars[i] == "e" || chars[i] == "E" {
1258 var j = i + 1
1259 var e = ""
1260 if j < chars.count, chars[j] == "-" || chars[j] == "+" {
1261 e.append(chars[j])
1262 j += 1
1263 }
1264 var digitsSeen = false
1265 while j < chars.count, chars[j].isASCII, chars[j].isNumber {
1266 e.append(chars[j])
1267 j += 1
1268 digitsSeen = true
1269 }
1270 if digitsSeen {
1271 exponent = Int(e)
1272 i = j
1273 }
1274 }
1275 guard !whole.isEmpty || !(fraction ?? "").isEmpty else { throw Unsupported("formula syntax") }
1276 if fraction == nil, exponent == nil {
1277 guard let value = Int(whole) else { throw Unsupported("integer size") }
1278 return .int(value)
1279 }
1280 let digitsText = whole + (fraction ?? "")
1281 guard let mantissa = Int128(digitsText.isEmpty ? "0" : digitsText) else { throw Unsupported("number size") }
1282 return try makeFloat(mantissa, (exponent ?? 0) - (fraction?.count ?? 0))
1283 }
1284 }
1285
1286 // MARK: - Evaluation
1287
1288 struct Evaluator {
1289 let modes: Modes
1290
1291 func eval(_ node: Node) throws -> Value {
1292 switch node {
1293 case .number(let v): return v
1294 case .vector(let items): return .vector(try items.map(eval))
1295 case .unary("!", let operand): return .int(try truth(try eval(operand)) ? 0 : 1)
1296 case .unary(_, let operand):
1297 let a = try eval(operand)
1298 do { return try negate(a) } catch is Rejected { return .symbolic(.op("neg", [try term(a)])) }
1299 case .binary(let op, let l, let r):
1300 let (a, b) = (try eval(l), try eval(r))
1301 do {
1302 return try binary(op, a, b)
1303 } catch is Rejected {
1304 // `math-normalize` keeps the operation, its arguments evaluated.
1305 guard let name = ["+": "+", "-": "-", "*": "*", "/": "/", "^": "^"][op] else { throw Unsupported("division by zero") }
1306 return .symbolic(.op(name, [try term(a), try term(b)]))
1307 }
1308 case .call(let name, let args):
1309 let values = try args.map(eval)
1310 // In symbolic mode Calc keeps these unevaluated when the result isn't exact,
1311 // which isn't reproduced.
1312 if modes.symbolic, Self.inexact.contains(name) || (!modes.degrees && ["sin", "cos", "tan"].contains(name)) {
1313 throw Unsupported("function \(name) in symbolic mode")
1314 }
1315 if values.contains(where: Self.hasSymbol) {
1316 // Calc leaves most functions of a formula alone, and simplifies some.
1317 guard ["vsum", "vprod", "vmean", "vcount"].contains(name),
1318 values.allSatisfy({ if case .vector = $0 { true } else { !Self.hasSymbol($0) } }) else {
1319 throw Unsupported("function \(name) of a formula")
1320 }
1321 }
1322 do {
1323 return try call(name, values)
1324 } catch is Rejected {
1325 throw Unsupported("division by zero")
1326 }
1327 case .variable(let name):
1328 return .symbolic(.variable(name))
1329 }
1330 }
1331
1332 static let inexact: Set<String> = ["sqrt", "exp", "ln", "log10", "log", "vsdev", "vpsdev", "vgmean", "vhmean", "vcorr",
1333 "vcov", "vpcov", "agmean", "pow", "nroot", "hypot", "sinh", "cosh", "tanh", "arcsinh",
1334 "arccosh", "arctanh", "arcsin", "arccos", "arctan", "arctan2", "fact", "dfact"]
1335
1336 static func hasSymbol(_ v: Value) -> Bool {
1337 switch v {
1338 case .symbolic: true
1339 case .vector(let items): items.contains(where: hasSymbol)
1340 default: false
1341 }
1342 }
1343
1344 func binary(_ op: Character, _ a: Value, _ b: Value) throws -> Value {
1345 switch op {
1346 case "+": return try add(a, b)
1347 case "-": return try subtract(a, b)
1348 case "*": return try multiply(a, b)
1349 case "/": return try divide(a, b, fractions: modes.preferFractions)
1350 case "%": return try mod(a, b)
1351 case "\\": return try idiv(a, b)
1352 case "^": return try power(a, b, fractions: modes.preferFractions)
1353 // `calcFunc-lor` and `calcFunc-land` give one of their arguments.
1354 case "|": return try truth(a) ? a : b
1355 case "&": return try truth(a) ? b : a
1356 default:
1357 let order = try compare(a, b)
1358 let holds = switch op {
1359 case "=": order == 0
1360 case "≠": order != 0
1361 case "<": order < 0
1362 case ">": order > 0
1363 case "≤": order <= 0
1364 default: order >= 0
1365 }
1366 return .int(holds ? 1 : 0)
1367 }
1368 }
1369
1370 /// A condition's value: a number, nonzero for true.
1371 func truth(_ v: Value) throws -> Bool {
1372 switch v {
1373 case .int(let i): return i != 0
1374 case .float(let m, _): return m != 0
1375 case .frac: return true
1376 default: throw Unsupported("condition")
1377 }
1378 }
1379
1380 /// `math-mod`: the remainder with the divisor's sign.
1381 func mod(_ a: Value, _ b: Value) throws -> Value {
1382 if case .int(let x) = a, case .int(let y) = b {
1383 guard y != 0 else { throw Unsupported("division by zero") }
1384 let r = x % y
1385 return .int(r != 0 && (r < 0) != (y < 0) ? r + y : r)
1386 }
1387 let q = try floorOf(try divide(a, b))
1388 return try subtract(a, try multiply(b, q))
1389 }
1390
1391 /// `calcFunc-idiv`: the quotient rounded down.
1392 func idiv(_ a: Value, _ b: Value) throws -> Value {
1393 if case .int(let x) = a, case .int(let y) = b {
1394 guard y != 0 else { throw Unsupported("division by zero") }
1395 let q = x / y
1396 return .int(q * y != x && (x < 0) != (y < 0) ? q - 1 : q)
1397 }
1398 return try floorOf(try divide(a, b))
1399 }
1400
1401 func floorOf(_ v: Value) throws -> Value {
1402 if case .int = v { return v }
1403 guard let i = Int(exactly: try double(v).rounded(.down)) else { throw Unsupported("integer size") }
1404 return .int(i)
1405 }
1406
1407 /// `math-covariance` of numbers without error forms: the variance of `xs` without `ys`,
1408 /// with `correlation` the correlation coefficient.
1409 func covariance(_ xs: [Value], _ ys: [Value]? = nil, population: Bool, correlation: Bool = false) throws -> Value {
1410 let n = xs.count
1411 guard n > 0 else { throw Unsupported("empty vector") }
1412 guard population || n > 1 else { throw Unsupported(ys == nil ? "variance of one value" : "arguments") }
1413 guard (ys ?? xs).count == n else { throw Unsupported("arguments") }
1414 return try extra(2) {
1415 func sum(_ v: [Value]) throws -> Value { try v.dropFirst().reduce(v[0], add) }
1416 func deviations(_ v: [Value]) throws -> [Value] {
1417 let shift = try divide(try sum(v), .int(-n), fractions: modes.preferFractions)
1418 return try v.map { try add($0, shift) }
1419 }
1420 let dx = try deviations(xs)
1421 let dy = try ys.map(deviations) ?? dx
1422 let products = try sum(try zip(dx, dy).map(multiply))
1423 let divisor = correlation
1424 ? try squareRoot(try multiply(try sum(try dx.map { try multiply($0, $0) }), try sum(try dy.map { try multiply($0, $0) })))
1425 : .int(population ? n : n - 1)
1426 return try divide(products, divisor, fractions: modes.preferFractions)
1427 }
1428 }
1429
1430 /// `math-flatten-many-vecs`: the arguments, vectors flattened into their elements.
1431 func elements(_ args: [Value]) throws -> [Value] {
1432 var items: [Value] = []
1433 for arg in args {
1434 if case .vector(let inner) = arg { items += try elements(inner) } else { items.append(arg) }
1435 }
1436 return items
1437 }
1438
1439 func one(_ args: [Value]) throws -> Value {
1440 guard args.count == 1 else { throw Unsupported("arguments") }
1441 if case .vector = args[0] { throw Unsupported("vector argument") }
1442 return args[0]
1443 }
1444
1445 /// An integer argument, from an integer or a float with an integer value
1446 /// (`math-messy-integerp`).
1447 func integer(_ v: Value) throws -> Int {
1448 guard isWhole(v) else { throw Unsupported("arguments") }
1449 return try trunc(v)
1450 }
1451
1452 /// The local date and time `now()` reads.
1453 func clock() -> DateComponents {
1454 var calendar = Calendar(identifier: .gregorian)
1455 calendar.timeZone = modes.timeZone
1456 return calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: modes.now ?? Date())
1457 }
1458
1459 func radians(_ x: Double) -> Double { modes.degrees ? x * .pi / 180 : x }
1460 func angle(_ x: Double) -> Double { modes.degrees ? x * 180 / .pi : x }
1461
1462 func call(_ name: String, _ args: [Value]) throws -> Value {
1463 switch name {
1464 case "vsum":
1465 return try extra(2) { try elements(args).reduce(Value.int(0)) { try add($0, $1) } }
1466 case "vprod":
1467 return try extra(2) { try elements(args).reduce(Value.int(1)) { try multiply($0, $1) } }
1468 case "vcount":
1469 return .int(try elements(args).count)
1470 case "vmean":
1471 let items = try elements(args)
1472 guard !items.isEmpty else { throw Unsupported("empty vector") }
1473 return try extra(2) { try divide(try items.reduce(Value.int(0)) { try add($0, $1) }, .int(items.count), fractions: modes.preferFractions) }
1474 case "vmax", "vmin":
1475 // `math-reduce-many-vecs` compares at two digits more.
1476 let items = try elements(args)
1477 guard let first = items.first else { throw Unsupported("empty vector") }
1478 return try extra(2) {
1479 var best = first
1480 for item in items.dropFirst() {
1481 let order = try compare(item, best)
1482 if name == "vmax" ? order > 0 : order < 0 { best = item }
1483 }
1484 return best
1485 }
1486 case "vmedian":
1487 var items = try elements(args)
1488 guard !items.isEmpty else { throw Unsupported("empty vector") }
1489 // Calc leaves the median of dates unevaluated.
1490 if items.contains(where: { if case .date = $0 { true } else { false } }) { throw Unsupported("arguments") }
1491 try items.sort { try compare($0, $1) < 0 }
1492 if items.count % 2 == 1 { return items[items.count / 2] }
1493 return try divide(try add(items[items.count / 2 - 1], items[items.count / 2]), .int(2))
1494 case "if":
1495 guard args.count == 3 else { throw Unsupported("arguments") }
1496 return try truth(args[0]) ? args[1] : args[2]
1497 case "vvar", "vpvar", "vsdev", "vpsdev":
1498 let variance = try covariance(try elements(args), population: name == "vpvar" || name == "vpsdev")
1499 return name.hasSuffix("sdev") ? try squareRoot(variance) : variance
1500 case "mod":
1501 guard args.count == 2 else { throw Unsupported("arguments") }
1502 return try mod(args[0], args[1])
1503 case "idiv":
1504 guard args.count == 2 else { throw Unsupported("arguments") }
1505 return try idiv(args[0], args[1])
1506 case "fact", "dfact":
1507 // A float with an integer value gives a float, up to 20.
1508 let x = try one(args)
1509 guard isWhole(x), case let n = try trunc(x), n >= 0, x == .int(n) || (name == "fact" && n <= 20) else { throw Unsupported("arguments") }
1510 var result = Value.int(1)
1511 for k in stride(from: name == "fact" ? 2 : 2 + n % 2, through: n, by: name == "fact" ? 1 : 2) { result = try multiply(result, .int(k)) }
1512 return x == .int(n) ? result : try float(result)
1513 case "max", "min":
1514 guard !args.isEmpty else { throw Unsupported("arguments") }
1515 var best = args[0]
1516 for item in args.dropFirst() {
1517 let order = try compare(item, best)
1518 if name == "max" ? order > 0 : order < 0 { best = item }
1519 }
1520 return best
1521 case "abs":
1522 let x = try one(args)
1523 if case .date(let d) = x {
1524 // Calc leaves abs of day number 0 unevaluated.
1525 if d == .int(0) { throw Unsupported("date arithmetic") }
1526 return .date(try compare(d, .int(0)) < 0 ? try negate(d) : d)
1527 }
1528 return try compare(x, .int(0)) < 0 ? try negate(x) : x
1529 case "floor", "ceil", "trunc":
1530 if args.count == 1, case .date(let d) = args[0] { return .date(try call(name, [d])) }
1531 var x = try one(args)
1532 if case .frac(let n, let d) = x { x = try divide(.int(n), .int(d)) }
1533 if case .int = x { return x }
1534 let d = try double(x)
1535 let r = name == "floor" ? d.rounded(.down) : name == "ceil" ? d.rounded(.up) : d.rounded(.towardZero)
1536 guard let i = Int(exactly: r) else { throw Unsupported("integer size") }
1537 return .int(i)
1538 case "round":
1539 guard args.count == 1 || args.count == 2 else { throw Unsupported("arguments") }
1540 if case .date(let d) = args[0] {
1541 guard args.count == 1 else { throw Unsupported("arguments") }
1542 return .date(try call(name, [d]))
1543 }
1544 var x = args[0]
1545 if case .frac(let n, let d) = x { x = try divide(.int(n), .int(d)) }
1546 if args.count == 2 {
1547 guard case .int(let places) = args[1] else { throw Unsupported("arguments") }
1548 guard case .float(let m, let e) = x else { return x }
1549 return try makeFloat(try scaleRounding(Int128(m), e + places), -places)
1550 }
1551 guard case .float(let m, let e) = x else { return x }
1552 guard let i = Int(exactly: try scaleRounding(Int128(m), e)) else { throw Unsupported("integer size") }
1553 return .int(i)
1554 case "sqrt":
1555 return try squareRoot(try one(args))
1556 case "exp":
1557 let x = try one(args)
1558 if x == .int(0) { return .int(1) }
1559 return try extra(2) { try expRaw(try float(x)) }
1560 case "ln":
1561 let x = try one(args)
1562 if x == .int(1) { return .int(0) }
1563 guard try sign(x) > 0 else { throw Unsupported("logarithm domain") }
1564 return try extra(2) { try lnRaw(try float(x)) }
1565 case "log10":
1566 let x = try one(args)
1567 if case .int(let i) = x, i > 0 {
1568 var n = i
1569 var k = 0
1570 while n % 10 == 0 {
1571 n /= 10
1572 k += 1
1573 }
1574 if n == 1 { return .int(k) }
1575 }
1576 if case .frac(1, let d) = x, case (true, let k) = try integerLog(.int(d), .int(10)) { return .int(-k) }
1577 if isZero(x) { throw Unsupported("logarithm domain") }
1578 return try extra(2) {
1579 guard case .float(let m, let e) = try float(x), m > 0 else { throw Unsupported("logarithm domain") }
1580 if m == 1 { return try float(.int(e)) }
1581 let digits = digits(Int128(m)) - 1
1582 return try add(try divide(try lnRaw2(.float(m, -digits)), try ln10()), try float(.int(e + digits)))
1583 }
1584 case "sin", "cos", "tan":
1585 let x = try one(args)
1586 if modes.degrees, case .int(let i) = x, i % 90 == 0 {
1587 let quarter = ((i / 90) % 4 + 4) % 4
1588 switch name {
1589 case "sin": return .int([0, 1, 0, -1][quarter])
1590 case "cos": return .int([1, 0, -1, 0][quarter])
1591 default:
1592 guard quarter % 2 == 0 else { throw Unsupported("infinite result") }
1593 return .int(0)
1594 }
1595 }
1596 if !modes.degrees, x == .int(0) { return .int(name == "cos" ? 1 : 0) }
1597 let r = radians(try double(x))
1598 return try fromDouble(name == "sin" ? Foundation.sin(r) : name == "cos" ? Foundation.cos(r) : Foundation.tan(r))
1599 case "arcsin", "arccos", "arctan":
1600 let x = try one(args)
1601 if modes.degrees, case .int(let i) = x {
1602 switch (name, i) {
1603 case ("arcsin", -1), ("arcsin", 0), ("arcsin", 1): return .int(90 * i)
1604 case ("arccos", -1), ("arccos", 0), ("arccos", 1): return .int(90 - 90 * i)
1605 case ("arctan", -1), ("arctan", 0), ("arctan", 1): return .int(45 * i)
1606 default: break
1607 }
1608 }
1609 let d = try double(x)
1610 if name != "arctan", abs(d) > 1 { throw Unsupported("complex result") }
1611 let r = name == "arcsin" ? Foundation.asin(d) : name == "arccos" ? Foundation.acos(d) : Foundation.atan(d)
1612 return try fromDouble(angle(r))
1613 case "eq", "neq", "lt", "gt", "leq", "geq", "land", "lor":
1614 guard args.count == 2 else { throw Unsupported("arguments") }
1615 let ops: [String: Character] = ["eq": "=", "neq": "≠", "lt": "<", "gt": ">", "leq": "≤", "geq": "≥", "land": "&", "lor": "|"]
1616 return try binary(ops[name]!, args[0], args[1])
1617 case "lnot":
1618 return .int(try truth(try one(args)) ? 0 : 1)
1619 case "percent":
1620 let x = try one(args)
1621 _ = try sign(x)
1622 return try divide(x, .int(100))
1623 case "float", "pfloat":
1624 return try float(try one(args))
1625 case "sign":
1626 return .int(try sign(try one(args)))
1627 case "rounde", "roundu":
1628 guard args.count == 1 || args.count == 2 else { throw Unsupported("arguments") }
1629 let x = args[0]
1630 _ = try sign(x)
1631 guard args.count == 2 else { return try round(x, even: name == "rounde") }
1632 guard isWhole(args[1]), case let places = try trunc(args[1]) else { throw Unsupported("arguments") }
1633 if places <= 0, case .int = x { return x }
1634 let rounded = try round(try scale(x, places, fractions: true), even: name == "rounde")
1635 return try scale(rounded, -places, fractions: modes.preferFractions)
1636 case "frac":
1637 return try toFraction(try one(args))
1638 case "fdiv":
1639 guard args.count == 2 else { throw Unsupported("arguments") }
1640 func parts(_ v: Value) throws -> (Int, Int) {
1641 if isWhole(v) { return (try trunc(v), 1) }
1642 guard case .frac(let n, let d) = v else { throw Unsupported("arguments") }
1643 return (n, d)
1644 }
1645 let (n1, d1) = try parts(args[0])
1646 let (n2, d2) = try parts(args[1])
1647 guard n2 != 0 else { throw Unsupported("division by zero") }
1648 let (n, o1) = n1.multipliedReportingOverflow(by: d2)
1649 let (d, o2) = d1.multipliedReportingOverflow(by: n2)
1650 if o1 || o2 { throw Unsupported("integer size") }
1651 return try fraction(n, d)
1652 case "gcd":
1653 guard args.count == 2 else { throw Unsupported("arguments") }
1654 return try gcd(args[0], args[1])
1655 case "lcm":
1656 guard args.count == 2 else { throw Unsupported("arguments") }
1657 return try divide(try absolute(try multiply(args[0], args[1])), try gcd(args[0], args[1]), fractions: modes.preferFractions)
1658 case "choose", "perm":
1659 guard args.count == 2, case .int(let n) = args[0], case .int(let m) = args[1] else { throw Unsupported("arguments") }
1660 if name == "choose" { return .int(try choose(n, m)) }
1661 guard m >= 0, m <= n else { throw Unsupported("arguments") }
1662 var result = Value.int(1)
1663 for k in stride(from: n - m + 1, through: n, by: 1) { result = try multiply(result, .int(k)) }
1664 return result
1665 case "pow":
1666 guard args.count == 2 else { throw Unsupported("arguments") }
1667 return try power(args[0], args[1], fractions: modes.preferFractions)
1668 case "exp10":
1669 let x = try one(args)
1670 guard case .int(let n) = x else { throw Unsupported("arguments") }
1671 return n == 0 ? .int(1) : try makeFloat(1, n)
1672 case "nroot":
1673 guard args.count == 2, case .int(let n) = args[1], n >= 1 else { throw Unsupported("arguments") }
1674 _ = try sign(args[0])
1675 return n == 1 ? args[0] : try rootPower(args[0], n)
1676 case "hypot":
1677 guard args.count == 2 else { throw Unsupported("arguments") }
1678 let (a, b) = (args[0], args[1])
1679 _ = (try sign(a), try sign(b))
1680 if isZero(a) { return try absolute(b) }
1681 if isZero(b) { return try absolute(a) }
1682 return try extra(1) { try squareRoot(try add(try multiply(a, a), try multiply(b, b))) }
1683 case "log":
1684 guard args.count == 2 else {
1685 guard args.count == 1 else { throw Unsupported("arguments") }
1686 return try call("ln", args)
1687 }
1688 let (x, b) = (args[0], args[1])
1689 _ = (try sign(x), try sign(b))
1690 if b == .int(10) || b == .float(1, 1) { return try call("log10", [x]) }
1691 if isZero(x) || isZero(b) || b == .int(1) || b == .float(1, 0) { throw Unsupported("logarithm domain") }
1692 if x == .int(1) || x == .float(1, 0) {
1693 if case .float = b { return .float(0, 0) }
1694 return .int(0)
1695 }
1696 if rational(x) != nil, rational(b) != nil, try sign(x) > 0, try sign(b) > 0 {
1697 var sign = 1
1698 var (xx, bb) = (x, b)
1699 if try compare(.int(1), x) >= 0 {
1700 sign = -1
1701 xx = try divide(.int(1), x)
1702 }
1703 if try compare(.int(1), b) >= 0 {
1704 sign = -sign
1705 bb = try divide(.int(1), b)
1706 }
1707 let inverse = try compare(xx, bb) < 0
1708 let (exact, n) = inverse ? try integerLog(bb, xx) : try integerLog(xx, bb)
1709 if exact { return inverse ? try divide(.int(1), .int(sign * n), fractions: modes.preferFractions) : .int(sign * n) }
1710 }
1711 return try extra(2) { try divide(try lnRaw(try float(x)), try lnRaw(try float(b))) }
1712 case "sinh", "cosh":
1713 let x = try one(args)
1714 if x == .int(0) { return .int(name == "sinh" ? 0 : 1) }
1715 _ = try sign(x)
1716 return try extra(2) {
1717 let e = try expRaw(try float(x))
1718 return try multiply(try add(e, try divide(.int(name == "sinh" ? -1 : 1), e)), .float(5, -1))
1719 }
1720 case "tanh":
1721 let x = try one(args)
1722 if x == .int(0) { return x }
1723 _ = try sign(x)
1724 return try extra(2) {
1725 let e = try extra(2) { try expRaw(try float(x)) }
1726 let inverse = try divide(.int(1), e)
1727 return try divide(try subtract(e, inverse), try add(e, inverse))
1728 }
1729 case "arcsinh":
1730 let x = try one(args)
1731 if x == .int(0) { return x }
1732 _ = try sign(x)
1733 return try extra(2) { try lnRaw(try add(x, try squareRootRaw(try add(try multiply(x, x), .float(1, 0))))) }
1734 case "arccosh":
1735 let x = try one(args)
1736 if x == .int(1) { return .int(0) }
1737 guard try compare(x, .int(-1)) != 0 else { throw Unsupported("complex result") }
1738 return try extra(2) {
1739 let xp1 = try add(.int(1), x)
1740 return try lnRaw(try add(x, try multiply(xp1, try squareRootRaw(try divide(try subtract(x, .float(1, 0)), xp1)))))
1741 }
1742 case "arctanh":
1743 let x = try one(args)
1744 if x == .int(0) { return x }
1745 guard try compare(x, .int(1)) <= 0 else { throw Unsupported("complex result") }
1746 return try extra(2) {
1747 try multiply(try lnRaw(try divide(try add(.float(1, 0), x), try subtract(.int(1), x))), .float(5, -1))
1748 }
1749 case "arctan2":
1750 guard args.count == 2 else { throw Unsupported("arguments") }
1751 _ = (try sign(args[0]), try sign(args[1]))
1752 return try extra(2) {
1753 let (y, x) = (try float(args[0]), try float(args[1]))
1754 let r: Value
1755 if isZero(y) {
1756 r = try sign(x) < 0 ? try pi() : .float(0, 0)
1757 } else if isZero(x) {
1758 r = try sign(y) > 0 ? try piOver2() : try negate(try piOver2())
1759 } else if try sign(x) > 0 {
1760 r = try arctanRaw(try divide(y, x))
1761 } else if try sign(y) > 0 {
1762 r = try add(try arctanRaw(try divide(y, x)), try pi())
1763 } else {
1764 r = try subtract(try arctanRaw(try divide(y, x)), try pi())
1765 }
1766 return modes.degrees ? try divide(r, try piOver180()) : r
1767 }
1768 case "deg", "rad":
1769 let x = try one(args)
1770 _ = try sign(x)
1771 return try extra(2) { name == "deg" ? try divide(x, try piOver180()) : try multiply(x, try piOver180()) }
1772 case "vflat":
1773 return .vector(try elements(args))
1774 case "vgmean", "vhmean":
1775 let items = try elements(args)
1776 guard !items.isEmpty else { throw Unsupported("empty vector") }
1777 return try extra(2) {
1778 if name == "vhmean" {
1779 let inverses = try items.map { try divide(.int(1), $0, fractions: modes.preferFractions) }
1780 return try divide(.int(items.count), try inverses.dropFirst().reduce(inverses[0], add), fractions: modes.preferFractions)
1781 }
1782 let product = try items.dropFirst().reduce(items[0], multiply)
1783 return items.count == 2 ? try squareRoot(product) : try rootPower(product, items.count)
1784 }
1785 case "vcov", "vpcov", "vcorr":
1786 // Two vectors; one matrix argument isn't supported.
1787 guard args.count == 2 else { throw Unsupported("arguments") }
1788 return try covariance(try elements([args[0]]), try elements([args[1]]), population: name == "vpcov", correlation: name == "vcorr")
1789 case "agmean":
1790 guard args.count == 2 else { throw Unsupported("arguments") }
1791 let (a, b) = (args[0], args[1])
1792 _ = (try sign(a), try sign(b))
1793 if try compare(a, b) == 0 || isZero(a) { return a }
1794 if isZero(b) { return b }
1795 return try extra(2) {
1796 var (x, y) = (try float(try absolute(a)), try float(try absolute(b)))
1797 for _ in 0..<1000 {
1798 if nearlyEqual(x, y) { return x }
1799 let mean = try multiply(try add(x, y), .float(5, -1))
1800 y = try extra(1) { try squareRootRaw(try multiply(x, y)) }
1801 x = mean
1802 }
1803 throw Unsupported("number")
1804 }
1805 case "now":
1806 guard args.isEmpty else { throw Unsupported("arguments") }
1807 let c = clock()
1808 return try dateValue(c.year!, c.month!, c.day!, (c.hour!, c.minute!, c.second!))
1809 case "date":
1810 // `date(d)` converts between a date and its day number; otherwise the
1811 // arguments are [year,] month, day[, hour[, minute[, second]]].
1812 if args.count == 1 {
1813 if case .date(let d) = args[0] { return d }
1814 return .date(try dayNumber(args[0]))
1815 }
1816 guard (2...6).contains(args.count) else { throw Unsupported("arguments") }
1817 let n = try args.map(integer)
1818 if n.count == 2 { return try dateValue(clock().year!, n[0], n[1]) }
1819 return try dateValue(n[0], n[1], n[2], n.count > 3 ? (n[3], n.count > 4 ? n[4] : 0, n.count > 5 ? n[5] : 0) : nil)
1820 case "year", "month", "day", "hour", "minute", "second", "yearday":
1821 let dt = try dateParts(try one(args))
1822 switch name {
1823 case "year": return .int(dt.year)
1824 case "month": return .int(dt.month)
1825 case "day": return .int(dt.day)
1826 case "hour": return .int(dt.time?.hour ?? 0)
1827 case "minute": return .int(dt.time?.minute ?? 0)
1828 case "second": return .int(dt.time?.second ?? 0)
1829 default: return .int(try absolute(dt.year, dt.month, dt.day) - absolute(dt.year, 1, 1) + 1)
1830 }
1831 case "weekday":
1832 return .int(Days.weekday(try floorInt(try dayNumber(try one(args)))))
1833 case "newweek":
1834 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1835 let day = try floorInt(try dayNumber(args[0]))
1836 let weekday = args.count > 1 ? try integer(args[1]) : 0
1837 guard (0...6).contains(weekday) else { throw Unsupported("arguments") }
1838 return .date(.int(day - Days.weekday(day - weekday)))
1839 case "newmonth":
1840 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1841 var day = args.count > 1 ? try integer(args[1]) : 1
1842 guard (0...31).contains(day) else { throw Unsupported("arguments") }
1843 let dt = try dateParts(args[0])
1844 let days = try daysInMonth(dt.year, dt.month)
1845 day = day == 0 || day > days ? days - 1 : day - 1
1846 return .date(.int(try absolute(dt.year, dt.month, 1) + day))
1847 case "newyear":
1848 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1849 var day = args.count > 1 ? try integer(args[1]) : 1
1850 let dt = try dateParts(args[0])
1851 if (-12 ... -1).contains(day) { return .date(.int(try absolute(dt.year, -day, 1))) }
1852 guard (0...366).contains(day) else { throw Unsupported("arguments") }
1853 let days = try daysInMonth(dt.year, 2) == 29 ? 366 : 365
1854 if day == 0 || day > days { day = days }
1855 return .date(.int(try absolute(dt.year, 1, 1) + day - 1))
1856 case "incmonth", "incyear":
1857 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1858 let step = args.count > 1 ? args[1] : .int(1)
1859 let months = try integer(name == "incyear" ? try multiply(step, .int(12)) : step)
1860 guard abs(months) < 1_000_000_000 else { throw Unsupported("arguments") }
1861 let dt = try dateParts(args[0])
1862 let m = dt.month - 1 + months
1863 let extra = m >= 0 ? m / 12 : (m - 11) / 12
1864 let month = m - extra * 12 + 1
1865 var year = dt.year + extra
1866 let day = min(dt.day, try daysInMonth(year, month))
1867 // Past the year zero, which Calc doesn't have.
1868 if dt.year > 0, year <= 0 { year -= 1 }
1869 if dt.year < 0, year >= 0 { year += 1 }
1870 return try dateValue(year, month, day, dt.time)
1871 case "badd", "bsub":
1872 guard args.count == 2 else { throw Unsupported("arguments") }
1873 var (a, b) = (args[0], args[1])
1874 if name == "bsub" {
1875 guard case .date = a else { throw Unsupported("arguments") }
1876 if case .date = b {
1877 if try compare(a, b) < 0 { return try negate(try call(name, [b, a])) }
1878 let (x, xHoliday) = try toBusinessDay(a)
1879 let (y, yHoliday) = try toBusinessDay(b)
1880 return try add(try subtract(x, y), .int(yHoliday && !xHoliday ? 1 : 0))
1881 }
1882 b = try negate(b)
1883 }
1884 if case .date = b {
1885 if case .date = a { throw Unsupported("arguments") }
1886 (a, b) = (b, a)
1887 }
1888 guard case .date = a else { throw Unsupported("arguments") }
1889 if try sign(b) == 0 { return a }
1890 let (day, holiday) = try toBusinessDay(a)
1891 return try fromBusinessDay(try add(day, holiday && sign(b) > 0 ? try subtract(b, .int(1)) : b))
1892 case "julian":
1893 // `math-julian-date-beginning`: 1721424.5 days before day 0.
1894 let x = try one(args)
1895 if case .date(let d) = x {
1896 if case .int = d { return try add(d, .int(1721425)) }
1897 return try add(d, try add(.float(17214245, -1), try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
1898 }
1899 if case .int(let d) = x { return .date(try add(.int(d), .int(-1721425))) }
1900 let shifted = try subtract(try dayNumber(x), .float(17214245, -1))
1901 return .date(try subtract(shifted, try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
1902 case "unixtime":
1903 // `math-unix-epoch`: day 719163.
1904 let x = try one(args)
1905 if case .date(let d) = x {
1906 guard precision <= 12 else { throw Unsupported("calc precision") }
1907 let seconds = try round(try multiply(try subtract(d, .int(719163)), .int(86400)), even: false)
1908 return try add(seconds, .int(try zoneOffset(modes.timeZone)))
1909 }
1910 let day = try add(.int(719163), try divide(try dayNumber(x), .float(864, 2)))
1911 return .date(try subtract(day, try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
1912 default:
1913 throw Unsupported("function \(name)")
1914 }
1915 }
1916 }
1917}