Sources/OrgCore/Compute/CalcSymbolic.swift

988 lines · 49333 bytes

  1import Foundation
  2
  3/// Calc's arithmetic on formulas it can't reduce to a number: variables, `inf`, `uinf`, and
  4/// quotients by zero. This ports `math-add`, `math-mul`, `math-div`, `math-pow` and `math-neg`
  5/// with their `-symb-fancy` helpers from calc.el and calc-arith.el, as `calc-eval` runs them
  6/// with `calc-simplify-mode` nil; `math-sqrt`, `math-abs`, `math-mod`, `calcFunc-exp`, `calcFunc-ln`,
  7/// `calcFunc-min`, `calcFunc-max` and the comparisons and logical functions of calc-prog.el on
  8/// formulas; and Calc's flat formula printer from calccomp.el. Anything
  9/// those functions would decide from declarations, units, matrices or intervals throws
 10/// `Calc.Unsupported`.
 11extension Calc {
 12    /// A formula, as Calc's Lisp form: a number, a variable, or an operator or function with
 13    /// its arguments (`+ - * / ^ neg`, or a function name).
 14    public indirect enum Term: Equatable, Sendable {
 15        case number(Value)
 16        case variable(String)
 17        case op(String, [Term])
 18    }
 19
 20    /// `math-reject-arg`: the operation stays unevaluated.
 21    struct Rejected: Error {}
 22
 23    /// `calc-symbolic-mode`.
 24    @TaskLocal static var symbolicMode = false
 25
 26    /// `calc-prefer-frac`, for the division the arithmetic does.
 27    @TaskLocal static var fractions = false
 28
 29    /// Variables Calc gives a value or a declaration, which would change the arithmetic.
 30    static let reserved: Set<String> = ["CommuteRules", "Decls", "DistribRules", "EvalRules", "FactorRules", "FitRules",
 31                                        "Holidays", "IntegAfterRules", "InvertRules", "JumpRules", "MergeRules", "Modes",
 32                                        "NegateRules"]
 33
 34    /// The special constants and infinities, whose sign or type Calc knows.
 35    static let constants: Set<String> = ["pi", "e", "phi", "gamma", "i", "inf", "uinf", "nan"]
 36
 37    static func term(_ v: Value) throws -> Term {
 38        switch v {
 39        case .symbolic(let t): return t
 40        case .nan: return .variable("nan")
 41        case .int, .float, .frac: return .number(v)
 42        case .vector, .date: throw Unsupported("symbolic arithmetic")
 43        }
 44    }
 45
 46    static func value(_ t: Term) -> Value {
 47        switch t {
 48        case .number(let v): return v
 49        case .variable("nan"): return .nan
 50        default: return .symbolic(t)
 51        }
 52    }
 53
 54    enum Symbolic {
 55        static let inf = Term.variable("inf")
 56        static let uinf = Term.variable("uinf")
 57        static let nan = Term.variable("nan")
 58
 59        // MARK: Predicates
 60
 61        static func number(_ t: Term) -> Value? {
 62            if case .number(let v) = t { return v }
 63            return nil
 64        }
 65
 66        static func head(_ t: Term) -> String? {
 67            if case .op(let f, _) = t { return f }
 68            return nil
 69        }
 70
 71        /// `(nth n a)`, from 1.
 72        static func arg(_ t: Term, _ n: Int) -> Term {
 73            guard case .op(_, let args) = t, n - 1 < args.count else { return .number(.int(0)) }
 74            return args[n - 1]
 75        }
 76
 77        static func objectp(_ t: Term) -> Bool { number(t) != nil }
 78        static func zerop(_ t: Term) -> Bool { number(t).map(isZero) ?? false }
 79        static func floatp(_ t: Term) -> Bool {
 80            if case .number(.float) = t { return true }
 81            return false
 82        }
 83        static func ratp(_ t: Term) -> Bool { number(t).map { rational($0) != nil } ?? false }
 84        static func integerp(_ t: Term) -> Bool {
 85            if case .number(.int) = t { return true }
 86            return false
 87        }
 88
 89        /// `math-negp`.
 90        static func negp(_ t: Term) -> Bool {
 91            if let v = number(t) { return (try? sign(v)) == -1 }
 92            return t == .op("neg", [inf])
 93        }
 94
 95        /// `math-posp`.
 96        static func posp(_ t: Term) -> Bool {
 97            if let v = number(t) { return (try? sign(v)) == 1 }
 98            return t == inf
 99        }
100
101        /// `Math-equal-int`.
102        static func equalInt(_ t: Term, _ n: Int) -> Bool {
103            t == .number(.int(n)) || t == .number(.float(n, 0))
104        }
105
106        /// `math-looks-negp`; `loose` false is the `Math-looks-negp` macro, which doesn't
107        /// look inside a difference.
108        static func looksNeg(_ t: Term, loose: Bool = true) -> Bool {
109            if negp(t) { return true }
110            switch head(t) {
111            case "neg": return true
112            case "*", "/": return looksNeg(arg(t, 1)) || looksNeg(arg(t, 2))
113            case "-": return loose && looksNeg(arg(t, 1))
114            default: return false
115            }
116        }
117
118        /// `math-infinitep`: the infinity a product, quotient or negation is made of.
119        static func infinitep(_ t: Term) -> Term? {
120            var a = t
121            while let f = head(a), ["*", "/", "neg"].contains(f) {
122                a = f != "*" || infinitep(arg(a, 1)) != nil ? arg(a, 1) : arg(a, 2)
123            }
124            return [inf, uinf, nan].contains(a) ? a : nil
125        }
126
127        static func containsConstant(_ t: Term) -> Bool {
128            switch t {
129            case .number: false
130            case .variable(let name): constants.contains(name)
131            case .op(_, let args): args.contains(where: containsConstant)
132            }
133        }
134
135        /// `math-possible-signs`: the bits 1 negative, 2 zero, 4 positive and 8 not real,
136        /// relative to `origin`. Nothing is declared, so a variable may be anything.
137        static func signs(_ a: Term, _ origin: Term? = nil) throws -> Int {
138            func negSigns(_ s: Int) -> Int {
139                s >= 8 ? 8 + negSigns(s - 8) : (s & 1 != 0 ? 4 : 0) | (s & 2) | (s & 4 != 0 ? 1 : 0)
140            }
141            if objectp(a) {
142                let x = try origin.map { try sub(a, $0) } ?? a
143                return posp(x) ? 4 : negp(x) ? 1 : 2
144            }
145            let (a1, a2) = (arg(a, 1), arg(a, 2))
146            let f = head(a)
147            if f == "+" || f == "-" {
148                if objectp(a1) {
149                    if f == "-" { return negSigns(try signs(a2, try origin.map { try add($0, a1) } ?? a1)) }
150                    return try signs(a2, try origin.map { try sub($0, a1) } ?? (try neg(a1)))
151                }
152                if objectp(a2) {
153                    let org = f == "-" ? a2 : try neg(a2)
154                    return try signs(a1, try origin.map { try add($0, org) } ?? org)
155                }
156                let s1 = try signs(a1, origin)
157                var s2 = try signs(a2)
158                if f == "-" { s2 = negSigns(s2) }
159                if s1 == s2 { return s1 }
160                if s1 == 2 { return s2 }
161                if s2 == 2 { return s1 }
162                if s1 >= 8 || s2 >= 8 { return 15 }
163                if (s1, s2) == (4, 6) || (s1, s2) == (6, 4) { return 4 }
164                if (s1, s2) == (1, 3) || (s1, s2) == (3, 1) { return 1 }
165                return 7
166            }
167            if f == "neg" { return negSigns(try signs(a1, try origin.map(neg))) }
168            var origin = origin.flatMap { zerop($0) ? nil : $0 }
169            let zero = Term.number(.int(0))
170            if f == "*" || (f == "/" && origin != nil), objectp(a1) {
171                let s = f == "*"
172                    ? (zerop(a1) ? try signs(zero, origin) : try signs(a2, try div(origin ?? zero, a1)))
173                    : negSigns(try signs(a2, try div(a1, origin!)))
174                return negp(a1) ? negSigns(s) : s
175            }
176            if f == "*" || f == "/", objectp(a2) {
177                let s = try signs(a1, f == "*" ? try mul(origin ?? zero, a2) : try div(origin ?? zero, a2))
178                return negp(a2) ? negSigns(s) : s
179            }
180            let sign: Int
181            switch a {
182            case .op("*", _), .op("/", _):
183                let (s1, s2) = (try signs(a1), try signs(a2))
184                if s1 >= 8 || s2 >= 8 || (f == "/" && [2, 3, 6, 7].contains(s2)) {
185                    sign = 15
186                } else {
187                    sign = (s1 & 4 != 0 ? s2 : 0) | (s1 & 2) | (s1 & 1 != 0 ? negSigns(s2) : 0)
188                }
189            case .op("^", _):
190                let (s1, s2) = (try signs(a1), try signs(a2))
191                if s1 >= 8 || s2 >= 8 {
192                    sign = 15
193                } else if s1 == 4 {
194                    sign = 4
195                } else if s1 == 2 {
196                    sign = s2 == 4 ? 2 : 15
197                } else if s2 == 2 {
198                    sign = [1, 5].contains(s1) ? 2 : 15
199                } else if case .number(.int(let n)) = a2 {
200                    sign = n % 2 == 0 ? ([3, 6, 7].contains(s1) ? 6 : 4) : s1
201                } else if s1 == 6 {
202                    sign = s2 == 4 ? 6 : 15
203                } else {
204                    sign = 7
205                }
206            case .variable(let name):
207                switch name {
208                case "pi", "e":
209                    guard origin == nil else { throw Unsupported("symbolic arithmetic") }
210                    return 4
211                case "inf": return 4
212                case "uinf": return 13
213                case "i": return 8
214                default: return 15
215                }
216            case .op("%", let args):
217                let s2 = try signs(args[1])
218                sign = s2 >= 8 ? 7 : s2 == 2 ? 2 : [4, 6].contains(s2) ? 6 : [1, 3].contains(s2) ? 3 : 7
219            case .op("abs", let args):
220                let s1 = try signs(args[0])
221                sign = s1 == 2 ? 2 : [1, 4, 5].contains(s1) ? 4 : 6
222            case .op("exp", let args):
223                let s1 = try signs(args[0])
224                if s1 >= 8 {
225                    sign = 15
226                } else if origin == nil || negp(origin!) {
227                    sign = 4
228                } else {
229                    origin = try sub(origin!, .number(.int(1)))
230                    if zerop(origin!) { origin = nil }
231                    sign = s1
232                }
233            case .op("ln", let args):
234                sign = try knownNonneg(args[0]) ? try signs(args[0], .number(.int(1))) : 15
235            case .op("sqrt", let args):
236                let s1 = try signs(args[0])
237                sign = [2, 4, 6].contains(s1) ? s1 : 15
238            case .op(let f, _) where ["eq", "neq", "lt", "gt", "leq", "geq", "lnot", "max", "min"].contains(f):
239                sign = 7
240            // Nothing is declared about the other functions.
241            case .op(let f, _) where functions.contains(f) || f == "if": return 15
242            default: throw Unsupported("function \(f ?? "")")
243            }
244            guard let origin else { return sign }
245            if posp(origin) { return (sign & 8) + ([1, 2, 3, 8, 9, 10, 11].contains(sign) ? 1 : 7) }
246            return (sign & 8) + ([2, 4, 6, 8, 10, 12, 14].contains(sign) ? 4 : 7)
247        }
248
249        static func knownNonneg(_ t: Term) throws -> Bool { [2, 4, 6].contains(try signs(t)) }
250
251        static func knownReal(_ t: Term) throws -> Bool { try signs(t) < 8 }
252
253        /// `math-known-evenp`.
254        static func knownEven(_ t: Term) throws -> Bool {
255            switch t {
256            case .number(.int(let n)): return n % 2 == 0
257            case .number(.float(let m, let e)) where e >= 0: return e > 0 || m % 2 == 0
258            case .op("*", let args):
259                if try knownEven(args[0]) { return try knownNumInteger(args[1]) }
260                return try knownNumInteger(args[0]) && knownEven(args[1])
261            case .op("+", let args), .op("-", let args):
262                return try (knownEven(args[0]) && knownEven(args[1])) || (knownOdd(args[0]) && knownOdd(args[1]))
263            case .op("neg", let args): return try knownEven(args[0])
264            default: return false
265            }
266        }
267
268        /// `math-known-oddp`.
269        static func knownOdd(_ t: Term) throws -> Bool {
270            switch t {
271            case .number(.int(let n)): return n % 2 != 0
272            case .number(.float(let m, let e)) where e >= 0: return e == 0 && m % 2 != 0
273            case .op("+", let args), .op("-", let args):
274                return try (knownEven(args[0]) && knownOdd(args[1])) || (knownOdd(args[0]) && knownEven(args[1]))
275            case .op("neg", let args): return try knownOdd(args[0])
276            default: return false
277            }
278        }
279
280        /// `math-known-num-integerp`.
281        static func knownNumInteger(_ t: Term) throws -> Bool {
282            if let v = number(t) { return isWhole(v) }
283            guard !containsConstant(t) else { throw Unsupported("symbolic arithmetic") }
284            return try possibleTypes(t, num: true) <= 3
285        }
286
287        /// `math-possible-types`: the bits 1 integer, 2 integer-valued float, 4 fraction and
288        /// 8 float, with `num` merging 1 and 2 and merging 4 and 8. Nothing is declared, so a
289        /// variable may be anything (63). Results above 15 are all 63 here: only whether a
290        /// result is at most 3 is used, and no larger operand can make it so.
291        static func possibleTypes(_ a: Term, num: Bool = false) throws -> Int {
292            func merge(_ t1: Int, _ t2: Int, _ mask: Int) -> Int {
293                if num { return mask * 3 }
294                return (t1 & 5 > 0 && t2 & 5 > 0 ? mask : 0) | ((t1 | t2) & 10 > 0 ? mask * 2 : 0)
295            }
296            switch a {
297            case .number(.int): return num ? 3 : 1
298            case .number(.float(_, let e)) where e >= 0: return num ? 3 : 2
299            case .number(.frac): return num ? 12 : 4
300            case .number(.float): return num ? 12 : 8
301            case .number: throw Unsupported("symbolic arithmetic")
302            case .variable: return 63
303            case .op("neg", let args): return try possibleTypes(args[0])
304            case .op("sqrt", let args):
305                let s1 = try signs(args[0])
306                let t = (s1 & 2 > 0 ? 3 : 0) | (s1 & 1 > 0 ? 16 : 0) | (s1 & 4 > 0 ? 15 : 0) | (s1 & 8 > 0 ? 32 : 0)
307                return t < 16 ? t : 63
308            case .op("abs", let args):
309                let t1 = try possibleTypes(args[0])
310                return t1 >= 16 ? 15 : t1
311            case .op(let f, let args) where args.count == 2 && ["+", "-", "*", "/", "^", "%"].contains(f):
312                // `%` keeps only the real bits, which the merged values above 15 don't give.
313                if f == "%", args.contains(where: { containsHead($0, "sqrt") }) { throw Unsupported("symbolic arithmetic") }
314                var (t1, t2) = (try possibleTypes(args[0], num: num), try possibleTypes(args[1], num: num))
315                if f == "%" { (t1, t2) = (t1 & 15, t2 & 15) }
316                let t12 = t1 | t2
317                if f == "^" {
318                    guard t2 <= 3, try knownNonneg(args[1]), t1 < 16 else {
319                        return try knownNonneg(args[0]) && signs(args[1]) == 4 ? 15 : 63
320                    }
321                    let mask = (t1 & 3 > 0 ? 1 : 0) | (t1 & 4) | (t1 & 12 > 0 ? 5 : 0)
322                    return merge(t1, t2, mask)
323                }
324                guard t12 < 16 else { return 63 }
325                if f == "/" {
326                    if t12 & 10 > 0 { return 10 }
327                    return t1 == 4 || t2 == 4 || fractions ? 5 : 15
328                }
329                let mask = t12 <= 3 ? 1
330                    : ((t1 <= 3 && t2 & 3 == 0) || (t2 <= 3 && t1 & 3 == 0)) && (f == "+" || f == "-") ? 4 : 5
331                return merge(t1, t2, mask)
332            case .op(let f, _) where functions.contains(f) || f == "if": return 63
333            default: throw Unsupported("function \(head(a) ?? "")")
334            }
335        }
336
337        static func containsHead(_ t: Term, _ f: String) -> Bool {
338            guard case .op(let g, let args) = t else { return false }
339            return g == f || args.contains { containsHead($0, f) }
340        }
341
342        // MARK: Arithmetic
343
344        /// `math-normalize`: the operations applied again from the leaves, floats rounded
345        /// to the precision.
346        static func normalize(_ t: Term) throws -> Term {
347            switch t {
348            case .number(.float(let m, let e)): return .number(try makeFloat(Int128(m), e))
349            case .number, .variable: return t
350            // `math-normalize-logical-op`: the branches stay as written unless the condition
351            // is a number.
352            case .op("if", let args) where args.count == 3:
353                let c = try normalize(args[0])
354                guard let v = number(c) else { return .op("if", [c, args[1], args[2]]) }
355                return try normalize(isZero(v) ? args[2] : args[1])
356            case .op(let f, let args):
357                let args = try args.map(normalize)
358                do { return try apply(f, args) } catch is Rejected { return .op(f, args) }
359            }
360        }
361
362        static func apply(_ f: String, _ args: [Term]) throws -> Term {
363            switch (f, args.count) {
364            case ("+", 2): return try add(args[0], args[1])
365            case ("-", 2): return try sub(args[0], args[1])
366            case ("*", 2): return try mul(args[0], args[1])
367            case ("/", 2): return try div(args[0], args[1])
368            case ("^", 2): return try pow(args[0], args[1])
369            case ("neg", 1): return try neg(args[0])
370            default:
371                guard functions.contains(f) else { throw Unsupported("function \(f)") }
372                return try function(f, args)
373            }
374        }
375
376        static func numeric(_ a: Term, _ b: Term, _ op: (Value, Value) throws -> Value) throws -> Term? {
377            guard let x = number(a), let y = number(b) else { return nil }
378            return try term(try op(x, y))
379        }
380
381        /// `math-float` of a rational number.
382        static func float(_ t: Term) throws -> Term {
383            guard let v = number(t) else { return t }
384            return .number(try Calc.float(v))
385        }
386
387        /// `math-neg`.
388        static func neg(_ a: Term) throws -> Term {
389            if let v = number(a) { return .number(try negate(v)) }
390            func okayNeg(_ t: Term) -> Bool { looksNeg(t) || head(t) == "-" }
391            let (a1, a2) = (arg(a, 1), arg(a, 2))
392            switch head(a) {
393            case "+": return try sub(try neg(a1), a2)
394            case "-": return try sub(a2, a1)
395            case "*", "/":
396                let f = head(a)!
397                if okayNeg(a1) { return .op(f, [try neg(a1), a2]) }
398                if okayNeg(a2) { return .op(f, [a1, try neg(a2)]) }
399                if objectp(a1) || (head(a1) == "*" && objectp(arg(a1, 1))) { return .op(f, [try neg(a1), a2]) }
400                if f == "/", objectp(a2) || (head(a2) == "*" && objectp(arg(a2, 1))) { return .op(f, [a1, try neg(a2)]) }
401            case "neg": return a1
402            default: if a == uinf || a == nan { return a }
403            }
404            return .op("neg", [a])
405        }
406
407        /// `math-add`.
408        static func add(_ a: Term, _ b: Term) throws -> Term {
409            if let sum = try numeric(a, b, { try Calc.add($0, $1) }) { return sum }
410            if zerop(a) { return b }
411            if zerop(b) { return a }
412            return try addFancy(a, b)
413        }
414
415        /// `math-sub`.
416        static func sub(_ a: Term, _ b: Term) throws -> Term { try add(a, try neg(b)) }
417
418        /// `math-add-symb-fancy`.
419        static func addFancy(_ a: Term, _ b: Term) throws -> Term {
420            switch head(b) {
421            case "+": return try add(try add(a, arg(b, 1)), arg(b, 2))
422            case "-": return try sub(try add(a, arg(b, 1)), arg(b, 2))
423            case "neg" where head(arg(b, 1)) == "+":
424                return try sub(try sub(a, arg(arg(b, 1), 1)), arg(arg(b, 1), 2))
425            default: break
426            }
427            if let result = try combineSums(a, b) { return result }
428            if looksNeg(b, loose: false) { return .op("-", [a, try neg(b)]) }
429            if looksNeg(a, loose: false) { return .op("-", [b, try neg(a)]) }
430            return .op("+", [a, b])
431        }
432
433        /// The `cond` in `math-add-symb-fancy` that handles infinities and like terms.
434        static func combineSums(_ a: Term, _ b: Term) throws -> Term? {
435            if let infA = infinitep(a) {
436                guard let infB = infinitep(b) else { return a }
437                if [uinf, nan].contains(infA) || [uinf, nan].contains(infB) { return nan }
438                let dirA = try infiniteDirection(a, infA)
439                let dirB = try infiniteDirection(b, infB)
440                guard let x = number(dirA), let y = number(dirB) else { return nil }
441                return try compare(x, y) == 0 ? a : nan
442            }
443            if infinitep(b) != nil { return b }
444            if head(a) == "+" {
445                return try combineSum(arg(a, 2), b, negA: false, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) }
446            }
447            if head(a) == "-" {
448                return try combineSum(arg(a, 2), b, negA: true, negB: false, scalarOkay: true).map { try add(arg(a, 1), $0) }
449            }
450            if objectp(a), objectp(b) { return nil }
451            return try combineSum(a, b, negA: false, negB: false, scalarOkay: false)
452        }
453
454        /// `math-infinite-dir`: the formula with its infinity replaced by 1.
455        static func infiniteDirection(_ a: Term, _ infinity: Term) throws -> Term {
456            func substitute(_ t: Term) -> Term {
457                if t == infinity { return .number(.int(1)) }
458                if case .op(let f, let args) = t { return .op(f, args.map(substitute)) }
459                return t
460            }
461            return try normalize(substitute(a))
462        }
463
464        /// `math-combine-sum`: two terms that are multiples of the same thing, added.
465        static func combineSum(_ a: Term, _ b: Term, negA: Bool, negB: Bool, scalarOkay: Bool) throws -> Term? {
466            if scalarOkay, objectp(a), objectp(b) {
467                return try add(negA ? try neg(a) : a, negB ? try neg(b) : b)
468            }
469            /// The coefficient and the rest; a nil coefficient is Calc's `(frac 1 0)`.
470            func split(_ t: Term) throws -> (Term?, Term) {
471                switch head(t) {
472                case "*" where objectp(arg(t, 1)): return (arg(t, 1), arg(t, 2))
473                case "/" where objectp(arg(t, 2)):
474                    let d = arg(t, 2)
475                    if case .number(.int(let n)) = d { return (n == 0 ? nil : .number(try fraction(1, n)), arg(t, 1)) }
476                    return (try div(.number(.int(1)), d), arg(t, 1))
477                case "neg": return (.number(.int(-1)), arg(t, 1))
478                default: return (.number(.int(1)), t)
479                }
480            }
481            let (multA, restA) = try split(a)
482            let (multB, restB) = try split(b)
483            guard restA == restB else { return nil }
484            // `math-make-frac` of two such coefficients divides by zero.
485            if multA == nil, multB == nil { throw Rejected() }
486            guard var ma = multA, var mb = multB else { throw Unsupported("division by zero") }
487            if negA { ma = try neg(ma) }
488            if negB { mb = try neg(mb) }
489            return try mul(try add(ma, mb), restA)
490        }
491
492        /// `math-mul`.
493        static func mul(_ a: Term, _ b: Term) throws -> Term {
494            if let product = try numeric(a, b, { try multiply($0, $1) }) { return product }
495            if zerop(a) { return try mulZero(a, b) }
496            if zerop(b) { return try mulZero(b, a) }
497            return try mulFancy(a, b)
498        }
499
500        /// `math-mul-zero`, `a` zero and `b` a formula.
501        static func mulZero(_ a: Term, _ b: Term) throws -> Term {
502            if infinitep(b) != nil { return nan }
503            return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0))
504        }
505
506        /// `math-mul-symb-fancy`.
507        static func mulFancy(_ a: Term, _ b: Term) throws -> Term {
508            if equalInt(a, 1) { return b }
509            if equalInt(a, -1) { return try neg(b) }
510            if objectp(b), !objectp(a) { return try mul(b, a) }
511            if head(a) == "neg" { return try neg(try mul(arg(a, 1), b)) }
512            if head(b) == "neg" { return try neg(try mul(a, arg(b, 1))) }
513            if head(a) == "*" { return try mul(arg(a, 1), try mul(arg(a, 2), b)) }
514            let negativePower = { (t: Term) in head(t) == "^" && looksNeg(arg(t, 2), loose: false) }
515            if negativePower(a), !negativePower(b) {
516                return try div(b, try normalize(.op("^", [arg(a, 1), try neg(arg(a, 2))])))
517            }
518            if negativePower(b), !negativePower(a) {
519                return try div(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))])))
520            }
521            if head(a) == "/" {
522                if let c = try combineProd(arg(a, 2), b, invA: true, invB: false, scalarOkay: true) { return try mul(arg(a, 1), c) }
523                return try div(try mul(arg(a, 1), b), arg(a, 2))
524            }
525            if head(b) == "/" { return try div(try mul(a, arg(b, 1)), arg(b, 2)) }
526            if let f = head(b), f == "+" || f == "-", objectp(a), objectp(arg(b, 1)) || objectp(arg(b, 2)) {
527                let (x, y) = (try mul(a, arg(b, 1)), try mul(a, arg(b, 2)))
528                return f == "+" ? try add(x, y) : try sub(x, y)
529            }
530            if head(b) == "*", objectp(arg(b, 1)), !objectp(a) { return try mul(arg(b, 1), try mul(a, arg(b, 2))) }
531            if looksNeg(b) || (head(b) == "-" && looksNeg(a)) { return try mul(try neg(a), try neg(b)) }
532            if head(b) == "*" {
533                if let c = try combineProd(a, arg(b, 1), invA: false, invB: false, scalarOkay: true) { return try mul(c, arg(b, 2)) }
534            } else if let c = try combineProd(a, b, invA: false, invB: false, scalarOkay: false) {
535                return c
536            }
537            for special in [nan, uinf] {
538                if a == special { return a }
539                if b == special { return b }
540            }
541            if b == inf {
542                switch try signs(a) {
543                case 4: return b
544                case 1: return try neg(b)
545                case 3, 6: throw Unsupported("symbolic arithmetic")
546                default: break
547                }
548            }
549            if a == inf { return try mul(b, a) }
550            return .op("*", [a, b])
551        }
552
553        /// `math-div`.
554        static func div(_ a: Term, _ b: Term) throws -> Term {
555            if zerop(b) {
556                // `math-div-by-zero`.
557                guard let infinity = infinitep(a) else { throw Rejected() }
558                return infinity == nan ? a : uinf
559            }
560            if let quotient = try numeric(a, b, { try divide($0, $1, fractions: fractions) }) { return quotient }
561            // `math-div-zero`.
562            if zerop(a) { return b == nan ? b : a }
563            return try divFancy(a, b)
564        }
565
566        /// `math-div-symb-fancy`.
567        static func divFancy(_ a: Term, _ b: Term) throws -> Term {
568            if equalInt(b, 1) { return a }
569            if equalInt(b, -1) { return try neg(a) }
570            if head(b) == "^", looksNeg(arg(b, 2), loose: false) || equalInt(a, 1) {
571                return try mul(a, try normalize(.op("^", [arg(b, 1), try neg(arg(b, 2))])))
572            }
573            if head(a) == "neg" { return try neg(try div(arg(a, 1), b)) }
574            if head(b) == "neg" { return try neg(try div(a, arg(b, 1))) }
575            if head(a) == "/" { return try div(arg(a, 1), try mul(arg(a, 2), b)) }
576            if head(b) == "/" { return try div(try mul(a, arg(b, 2)), arg(b, 1)) }
577            if case .number(.frac(let n, let d)) = b { return try mul(.number(try fraction(d, n)), a) }
578            if let f = head(a), f == "+" || f == "-", objectp(arg(a, 1)) || objectp(arg(a, 2)), objectp(b) {
579                let (x, y) = (try div(arg(a, 1), b), try div(arg(a, 2), b))
580                return f == "+" ? try add(x, y) : try sub(x, y)
581            }
582            if head(a) == "-" || looksNeg(a), looksNeg(b) { return try div(try neg(a), try neg(b)) }
583            if head(b) == "-", looksNeg(a) { return try div(try neg(a), try neg(b)) }
584            if head(a) == "*" {
585                if head(b) == "*" {
586                    if let c = try combineProd(arg(a, 1), arg(b, 1), invA: false, invB: true, scalarOkay: true) {
587                        return try div(try mul(c, arg(a, 2)), arg(b, 2))
588                    }
589                } else if let c = try combineProd(arg(a, 1), b, invA: false, invB: true, scalarOkay: true) {
590                    return try mul(c, arg(a, 2))
591                }
592            } else if head(b) == "*" {
593                if let c = try combineProd(a, arg(b, 1), invA: false, invB: true, scalarOkay: true) { return try div(c, arg(b, 2)) }
594            } else if let c = try combineProd(a, b, invA: false, invB: true, scalarOkay: false) {
595                return c
596            }
597            if infinitep(a) != nil {
598                if infinitep(b) != nil { return nan }
599                if a == nan || a == uinf { return a }
600                if a == inf {
601                    if posp(b) { return a }
602                    if negp(b) { return try neg(a) }
603                    if objectp(b) { throw Unsupported("symbolic arithmetic") }
604                }
605            }
606            if infinitep(b) != nil {
607                if b == nan { return b }
608                return floatp(a) || floatp(b) ? .number(.float(0, 0)) : .number(.int(0))
609            }
610            return .op("/", [a, b])
611        }
612
613        /// `math-mul-or-div`.
614        static func mulOrDiv(_ a: Term, _ b: Term, invA: Bool, invB: Bool) throws -> Term {
615            if invA { return invB ? try div(try div(.number(.int(1)), a), b) : try div(b, a) }
616            return invB ? try div(a, b) : try mul(a, b)
617        }
618
619        /// `math-combine-prod`: two factors that are powers of the same thing, multiplied.
620        static func combineProd(_ a: Term, _ b: Term, invA: Bool, invB: Bool, scalarOkay: Bool) throws -> Term? {
621            if (invA && zerop(a)) || (invB && zerop(b)) { return nil }
622            if scalarOkay, objectp(a), objectp(b) {
623                let r = try mulOrDiv(a, b, invA: invA, invB: invB)
624                return objectp(r) ? r : nil
625            }
626            if head(a) == "^", invA, looksNeg(arg(a, 2)) { return try mul(try pow(arg(a, 1), try neg(arg(a, 2))), b) }
627            if head(b) == "^", invB, looksNeg(arg(b, 2)) { return try mul(a, try pow(arg(b, 1), try neg(arg(b, 2)))) }
628            func split(_ t: Term) throws -> (Term, Term) {
629                var (base, power) = (t, Term.number(.int(1)))
630                if head(t) == "^", objectp(arg(t, 2)) { (base, power) = (arg(t, 1), arg(t, 2)) }
631                if head(t) == "sqrt" { (base, power) = (arg(t, 1), .number(.frac(1, 2))) }
632                // Only in symbolic mode does `exp` of a number stay.
633                if head(t) == "exp", objectp(arg(t, 1)) { throw Unsupported("symbolic arithmetic") }
634                if case .number(.frac(let n, let d)) = base, n < d {
635                    (base, power) = (try div(.number(.int(1)), base), try neg(power))
636                }
637                return (base, power)
638            }
639            var (baseA, powA) = try split(a)
640            var (baseB, powB) = try split(b)
641            if invA { powA = try neg(powA) }
642            if invB { powB = try neg(powB) }
643            func isFrac(_ t: Term) -> Bool {
644                if case .number(.frac) = t { return true }
645                return false
646            }
647            if baseA == baseB {
648                var sum = try add(powA, powB)
649                if !integerp(baseA) || zerop(sum) || isFrac(powA) == isFrac(powB) {
650                    if looksNeg(sum), ratp(baseA), posp(baseA) {
651                        (baseA, sum) = (try div(.number(.int(1)), baseA), try neg(sum))
652                    }
653                    return try root(baseA, sum)
654                }
655            }
656            if powA == powB, case .number(.int(let x)) = baseA, case .number(.int(let y)) = baseB, x >= 0, y >= 0 {
657                return try root(try mul(baseA, baseB), powA)
658            }
659            return nil
660        }
661
662        /// `a^p`, with Calc's square root form for a half.
663        static func root(_ a: Term, _ p: Term) throws -> Term {
664            if p == .number(.frac(1, 2)) { return .op("sqrt", [a]) }
665            if p == .number(.frac(-1, 2)) { return try div(.number(.int(1)), .op("sqrt", [a])) }
666            return try pow(a, p)
667        }
668
669        /// `math-pow`.
670        static func pow(_ a: Term, _ b: Term) throws -> Term {
671            if b == nan { return b }
672            if zerop(a) {
673                if let y = number(b) {
674                    if try sign(y) > 0 { return floatp(b) ? try float(a) : a }
675                    return .number(try power(number(a)!, y, fractions: fractions))
676                }
677                // `math-pow-of-zero` with a formula.
678                switch try signs(b) {
679                case 4: return a
680                case 1: return try div(.number(.int(1)), a)
681                default: return infinitep(b) != nil ? nan : .op("^", [a, b])
682                }
683            }
684            if a == .number(.int(1)) || b == .number(.int(1)) { return a }
685            if a == .number(.float(1, 0)) || b == .number(.float(1, 0)) { return a }
686            if zerop(b) {
687                if let x = number(a) { return .number(try power(x, number(b)!, fractions: fractions)) }
688                // `math-pow-zero`.
689                if infinitep(a) != nil { return nan }
690                return floatp(b) ? .number(.float(1, 0)) : .number(.int(1))
691            }
692            if let x = number(a), let y = number(b) { return .number(try power(x, y, fractions: fractions)) }
693            return try powFancy(a, b)
694        }
695
696        /// `math-pow-fancy` with a formula.
697        static func powFancy(_ a: Term, _ b: Term) throws -> Term {
698            let (a1, a2) = (arg(a, 1), arg(a, 2))
699            switch head(a) {
700            case "*" where try knownNumInteger(b) || knownNonneg(a1) || knownNonneg(a2):
701                return try mul(try pow(a1, b), try pow(a2, b))
702            case "/" where try knownNumInteger(b) || knownNonneg(a2):
703                return try div(try pow(a1, b), try pow(a2, b))
704            case "/" where try knownNonneg(a1) && !equalInt(a1, 1):
705                return try mul(try pow(a1, b), try pow(try div(.number(.int(1)), a2), b))
706            case "^" where try knownNumInteger(b) || knownNonneg(a1):
707                return try pow(a1, try mul(a2, b))
708            case "sqrt" where try knownNumInteger(b) || knownNonneg(a1):
709                return try pow(a1, try div(b, .number(.int(2))))
710            case "^":
711                if let y = number(b), let q = quarter(y), (1...3).contains(q), try knownEven(a2), try knownReal(a1) {
712                    return try absTerm(try pow(a1, try mul(a2, b)))
713                }
714            default: break
715            }
716            if looksNeg(a), case .number(.int(let n)) = b {
717                let p = try pow(try neg(a), b)
718                return n % 2 == 0 ? p : try neg(p)
719            }
720            if head(a) == "abs", try knownReal(a1), try knownEven(b) { return try pow(a1, b) }
721            if let infinity = infinitep(a) {
722                if infinity == nan { return infinity }
723                if head(a) == "neg" { return try mul(try pow(.number(.int(-1)), b), try pow(a1, b)) }
724                if posp(b) { return a }
725                if negp(b) { return floatp(b) ? .number(.float(0, 0)) : .number(.int(0)) }
726                if objectp(b) || infinitep(b) != nil { return nan }
727                throw Unsupported("symbolic arithmetic")
728            }
729            if infinitep(b) != nil {
730                guard let x = number(a), b == inf else { throw Unsupported("symbolic arithmetic") }
731                // `calcFunc-abssqr` of a real number is its square.
732                let scale = try multiply(x, x)
733                if scale == .int(1) || scale == .float(1, 0) { return nan }
734                if try compare(scale, .int(1)) < 0 { return floatp(a) ? .number(.float(0, 0)) : .number(.int(0)) }
735                if try compare(.int(1), x) < 0 { return b }
736                return uinf
737            }
738            return .op("^", [a, b])
739        }
740
741        // MARK: Functions
742
743        /// The functions `function` applies to formulas; `%` is `math-mod`.
744        static let functions: Set<String> = ["sqrt", "abs", "exp", "ln", "min", "max", "eq", "neq", "lt", "gt", "leq", "geq",
745                                             "land", "lor", "lnot", "%"]
746
747        /// `name` of `args`, at least one a formula, as `math-normalize` calls it: simplified,
748        /// or kept with its arguments when the function rejects them.
749        static func function(_ name: String, _ args: [Term]) throws -> Term {
750            do { return try simplify(name, args) } catch is Rejected { return .op(name, args) }
751        }
752
753        static func simplify(_ name: String, _ args: [Term]) throws -> Term {
754            let kept = Term.op(name, args)
755            switch (name, args.count) {
756            case ("sqrt", 1), ("exp", 1), ("ln", 1):
757                // In symbolic mode these keep a result that isn't exact, which isn't reproduced.
758                guard !symbolicMode else { throw Unsupported("function \(name) in symbolic mode") }
759                switch name {
760                case "sqrt": return try sqrtTerm(args[0])
761                case "exp": return try expTerm(args[0])
762                default: return try lnTerm(args[0])
763                }
764            case ("abs", 1): return try absTerm(args[0])
765            case ("min", _), ("max", _):
766                // `calcFunc-min` rejects an argument that isn't a real number or an infinity.
767                guard !args.isEmpty else { throw Unsupported("arguments") }
768                guard args.allSatisfy({ objectp($0) || infinitep($0) != nil }) else { return kept }
769                return try args.dropFirst().reduce(args[0]) { best, item in
770                    switch try compareTerms(best, item) {
771                    case 2: return nan
772                    case let order: return order == (name == "max" ? -1 : 1) ? item : best
773                    }
774                }
775            case ("eq", 2), ("neq", 2), ("lt", 2), ("gt", 2), ("leq", 2), ("geq", 2):
776                let (a, b) = (args[0], args[1])
777                let order = try compareTerms(a, b)
778                if order == 2 {
779                    // Both sides negative, or zero, flip.
780                    if looksNeg(a) || zerop(a), looksNeg(b) || zerop(b) {
781                        return .op(flipped[name]!, [try neg(a), try neg(b)])
782                    }
783                    return kept
784                }
785                let holds = switch name {
786                case "eq": order == 0
787                case "neq": order != 0
788                case "lt": order == -1
789                case "gt": order == 1
790                case "leq": order != 1
791                default: order != -1
792                }
793                return .number(.int(holds ? 1 : 0))
794            case ("land", 2):
795                let (a, b) = (args[0], args[1])
796                if zerop(a) { return a }
797                if zerop(b) { return b }
798                if try isTrue(a) { return b }
799                if try isTrue(b) { return a }
800                return kept
801            case ("lor", 2):
802                let (a, b) = (args[0], args[1])
803                if zerop(a) { return b }
804                if zerop(b) { return a }
805                if try isTrue(a) { return a }
806                if try isTrue(b) { return b }
807                return kept
808            case ("lnot", 1):
809                let a = args[0]
810                if zerop(a) { return .number(.int(1)) }
811                if try isTrue(a) { return .number(.int(0)) }
812                if case .op(let f, let xs) = a, xs.count == 2, let opposite = negated[f] { return .op(opposite, xs) }
813                return kept
814            case ("%", 2): return try modTerm(args[0], args[1])
815            default: throw Unsupported("function \(name) of a formula")
816            }
817        }
818
819        /// The comparison with its sides negated, and its negation (`calc-tweak-eqn-table`).
820        static let flipped = ["eq": "eq", "neq": "neq", "lt": "gt", "gt": "lt", "leq": "geq", "geq": "leq"]
821        static let negated = ["eq": "neq", "neq": "eq", "lt": "geq", "gt": "leq", "leq": "gt", "geq": "lt"]
822
823        /// `math-is-true`.
824        static func isTrue(_ t: Term) throws -> Bool {
825            if let v = number(t) { return !isZero(v) }
826            return [1, 4, 5, 8, 9, 12, 13].contains(try signs(t))
827        }
828
829        /// `math-compare`: -1, 0 or 1, or 2 when the order isn't known.
830        static func compareTerms(_ a: Term, _ b: Term) throws -> Int {
831            if a == b {
832                switch a {
833                case .number: return 0
834                case .variable, .op("neg", _), .op("*", _), .op("/", _): return infinitep(a) != nil ? 2 : 0
835                default: return 0
836                }
837            }
838            if let x = number(a), let y = number(b) { return try Calc.compare(x, y) }
839            if case .number(.frac(let n, let d)) = a { return try compareTerms(.number(.int(n)), try mul(b, .number(.int(d)))) }
840            if case .number(.frac(let n, let d)) = b { return try compareTerms(try mul(a, .number(.int(d))), .number(.int(n))) }
841            let one = Term.number(.int(1)), minusOne = Term.number(.int(-1))
842            if let infA = infinitep(a) {
843                if a == uinf || a == nan { return 2 }
844                let dirA = try infiniteDirection(a, infA)
845                if let infB = infinitep(b) {
846                    if b == uinf || b == nan { return 2 }
847                    let dirB = try infiniteDirection(b, infB)
848                    return dirA == one && dirB == minusOne ? 1 : dirA == minusOne && dirB == one ? -1 : 2
849                }
850                return dirA == one ? 1 : dirA == minusOne ? -1 : 2
851            }
852            if let infB = infinitep(b) {
853                if b == uinf || b == nan { return 2 }
854                let dirB = try infiniteDirection(b, infB)
855                return dirB == one ? -1 : dirB == minusOne ? 1 : 2
856            }
857            let e = Term.variable("e")
858            if head(a) == "exp", head(b) == "^", arg(b, 1) == e { return try compareTerms(arg(a, 1), arg(b, 2)) }
859            if head(b) == "exp", head(a) == "^", arg(a, 1) == e { return try compareTerms(arg(a, 2), arg(b, 1)) }
860            let half: [Term] = [.number(.frac(1, 2)), .number(.float(5, -1))]
861            if (head(a) == "sqrt" && head(b) == "^" && half.contains(arg(b, 2)))
862                || (head(b) == "sqrt" && head(a) == "^" && half.contains(arg(a, 2))) {
863                return try compareTerms(arg(a, 1), arg(b, 1))
864            }
865            if case .variable = a { return 2 }
866            if case .op(let f, let xs) = a, case .op(let g, let ys) = b, f == g, xs.count == ys.count,
867               try zip(xs, ys).allSatisfy({ try compareTerms($0, $1) == 0 }) { return 0 }
868            return 2
869        }
870
871        /// `math-sqrt` of a formula.
872        static func sqrtTerm(_ a: Term) throws -> Term {
873            if let v = number(a) { return .number(try squareRoot(v)) }
874            // An imaginary result.
875            if [1, 2, 3].contains(try signs(a)) { throw Unsupported("complex result") }
876            let (a1, a2) = (arg(a, 1), arg(a, 2))
877            switch head(a) {
878            case "*" where try knownNonneg(a1) || knownNonneg(a2):
879                return try mul(try sqrtTerm(a1), try sqrtTerm(a2))
880            case "/" where try knownNonneg(a2):
881                return try div(try sqrtTerm(a1), try sqrtTerm(a2))
882            case "/" where try knownNonneg(a1) && !equalInt(a1, 1):
883                return try mul(try sqrtTerm(a1), try sqrtTerm(try div(.number(.int(1)), a2)))
884            case "^" where try knownEven(a2) && knownReal(a1):
885                return try absTerm(try pow(a1, try div(a2, .number(.int(2)))))
886            default: break
887            }
888            if let infinity = infinitep(a) { return try mul(try sqrtTerm(try infiniteDirection(a, infinity)), infinity) }
889            return .op("sqrt", [a])
890        }
891
892        /// `math-abs` of a formula.
893        static func absTerm(_ a: Term) throws -> Term {
894            if let v = number(a) { return .number(try absolute(v)) }
895            if negp(a) { return try neg(a) }
896            if looksNeg(a) { return .op("abs", [try neg(a)]) }
897            let s = try signs(a)
898            if [2, 4, 6].contains(s) { return a }
899            if [1, 3].contains(s) { return try neg(a) }
900            if let infinity = infinitep(a) { return infinity == nan ? nan : inf }
901            return .op("abs", [a])
902        }
903
904        /// `calcFunc-exp` of a formula.
905        static func expTerm(_ a: Term) throws -> Term {
906            if objectp(a) { throw Unsupported("symbolic arithmetic") }
907            if a == inf || a == nan { return a }
908            if a == .op("neg", [inf]) { return .number(.int(0)) }
909            return .op("exp", [a])
910        }
911
912        /// `calcFunc-ln` of a formula.
913        static func lnTerm(_ a: Term) throws -> Term {
914            if objectp(a) { throw Unsupported("symbolic arithmetic") }
915            if a == .variable("e") { return .number(.int(1)) }
916            if head(a) == "^", arg(a, 1) == .variable("e"), try knownReal(arg(a, 2)) { return arg(a, 2) }
917            if infinitep(a) != nil { return a == nan ? nan : inf }
918            return .op("ln", [a])
919        }
920
921        /// `math-mod` with a formula.
922        static func modTerm(_ a: Term, _ b: Term) throws -> Term {
923            if zerop(a) { return a }
924            if objectp(a), objectp(b) { throw Unsupported("symbolic arithmetic") }
925            if b == inf {
926                if posp(a) || zerop(a) { return a }
927                if negp(a) { return b }
928            }
929            return .op("%", [a, b])
930        }
931
932        // MARK: Display
933
934        /// `math-format-value`: `math-compose-expr` in the flat language.
935        static func format(_ t: Term, _ floatFormat: FloatFormat) throws -> String {
936            let text = try compose(t, 0, floatFormat)
937            // Past its width of 1000, `calc-eval` breaks the line.
938            guard text.count < 1000 else { throw Unsupported("symbolic arithmetic") }
939            return text
940        }
941
942        /// Left and right precedence, from `math-standard-ops` with
943        /// `calc-multiplication-has-precedence`.
944        static let operators: [String: (Int, Int)] = ["+": (180, 181), "-": (180, 181), "*": (196, 195), "/": (190, 191), "^": (201, 200),
945                                                      "%": (190, 191), "eq": (160, 161), "neq": (160, 161), "lt": (160, 161),
946                                                      "gt": (160, 161), "leq": (160, 161), "geq": (160, 161), "land": (110, 111),
947                                                      "lor": (100, 101)]
948
949        static let symbols = ["eq": "=", "neq": "!=", "lt": "<", "gt": ">", "leq": "<=", "geq": ">=", "land": "&&", "lor": "||"]
950
951        static func compose(_ t: Term, _ prec: Int, _ floatFormat: FloatFormat, div: Bool = false) throws -> String {
952            switch t {
953            case .number(let v): return try Calc.format(v, floatFormat)
954            case .variable(let name): return name
955            case .op("neg", let args):
956                if prec > 197 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
957                return "-" + (try compose(args[0], 197, floatFormat))
958            case .op("lnot", let args) where args.count == 1:
959                if prec > 1000 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
960                return "!" + (try compose(args[0], 1000, floatFormat))
961            case .op("if", let args) where args.count == 3:
962                if prec > 90 { return "(" + (try compose(t, 0, floatFormat)) + ")" }
963                return try compose(args[0], 91, floatFormat) + " ? " + compose(args[1], 0, floatFormat) + " : "
964                    + compose(args[2], 90, floatFormat)
965            case .op(let f, let args):
966                guard let (left, right) = operators[f], args.count == 2 else {
967                    return f + "(" + (try args.map { try compose($0, 0, floatFormat) }).joined(separator: ", ") + ")"
968                }
969                if prec > min(left, right) || (div && f == "*") { return "(" + (try compose(t, 0, floatFormat)) + ")" }
970                var lhs = try compose(args[0], left, floatFormat)
971                let rhs = try compose(args[1], right, floatFormat, div: f == "/")
972                if f == "^", lhs.first == "-" { lhs = "(" + lhs + ")" }
973                if f == "*", let next = rhs.first {
974                    var lastFactor = args[0]
975                    while head(lastFactor) == "*" { lastFactor = arg(lastFactor, 2) }
976                    let isVariable = if case .variable = lastFactor { true } else { false }
977                    if (next.isASCII && (next.isLetter || next.isNumber)) || ".#_([{".contains(next), !(isVariable && next == "(") {
978                        return lhs + " " + rhs
979                    }
980                    return lhs + "*" + rhs
981                }
982                if f == "^" { return lhs + "^" + rhs }
983                if f == "/", let x = number(args[0]), isWhole(x), case .number(.int) = args[1] { return lhs + "/" + rhs }
984                return lhs + " " + (symbols[f] ?? f) + " " + rhs
985            }
986        }
987    }
988}