SPB Git

Repository Public MIT

Calculator.swift 25.2 KB 558 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraAgents/Sources/Calculator.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import AstraCore9091public enum CalculatorError: Error, LocalizedError, Sendable, Hashable {92    case syntax(String)93    case unknownName(String)94    case arity(String)95    case domain(String)96    case divisionByZero97    case overflow98    case tooComplex(String)99100    public var errorDescription: String? {101        switch self {102        case .syntax(let m): "Syntax error: \(m)."103        case .unknownName(let n): "Unknown name “\(n)”. Constants: pi, e, tau. Functions: \(Calculator.functionNames.joined(separator: ", "))."104        case .arity(let m): m105        case .domain(let m): "Math error: \(m)."106        case .divisionByZero: "Math error: division by zero."107        case .overflow: "Math error: the result is too large to represent."108        case .tooComplex(let m): "The expression is \(m)."109        }110    }111}112113public enum AngleUnit: String, Sendable, Codable, Hashable, CaseIterable { case radians, degrees }114115/// A calculator result: an exact integer while the arithmetic stays inside 64 bits, otherwise a double.116public enum CalcValue: Sendable, Hashable {117    case integer(Int)118    case real(Double)119120    public var double: Double {121        switch self { case .integer(let i): Double(i); case .real(let d): d }122    }123}124125/// A recursive-descent arithmetic evaluator with a fixed grammar and a fixed function list. It evaluates numbers only:126/// there are no variables, no assignments, no loops and no way to reach anything outside the expression.127///128///     expr    := term (('+' | '-') term)*129///     term    := unary (('*' | '/' | '%') unary)*130///     unary   := ('-' | '+') unary | power131///     power   := postfix ('^' unary)?            right associative, binds tighter than unary minus132///     postfix := primary '!'*133///     primary := number | constant | name '(' expr (',' expr)* ')' | '(' expr ')'134public struct Calculator {135    public static let maxLength = 1_000136    public static let maxDepth = 64137    public static let functionNames = ["sqrt", "cbrt", "abs", "ln", "log10", "log2", "log", "exp", "sin", "cos", "tan", "asin", "acos", "atan",138                                       "atan2", "sinh", "cosh", "tanh", "floor", "ceil", "round", "trunc", "min", "max", "factorial", "nCr", "nPr",139                                       "mod", "gcd", "lcm"]140141    private let chars: [Character]142    private var i = 0143    private var depth = 0144    private let angle: AngleUnit145146    private init(_ text: String, angle: AngleUnit) { chars = Array(text); self.angle = angle }147148    public static func evaluate(_ expression: String, angle: AngleUnit = .radians) throws -> CalcValue {149        guard expression.count <= maxLength else { throw CalculatorError.tooComplex("too long (the limit is \(maxLength) characters)") }150        let normalised = expression.replacingOccurrences(of: "×", with: "*").replacingOccurrences(of: "·", with: "*")151            .replacingOccurrences(of: "÷", with: "/").replacingOccurrences(of: "−", with: "-").replacingOccurrences(of: "–", with: "-")152            .replacingOccurrences(of: "**", with: "^").replacingOccurrences(of: "π", with: "pi").replacingOccurrences(of: "√", with: "sqrt")153        var parser = Calculator(normalised, angle: angle)154        guard parser.peek() != nil else { throw CalculatorError.syntax("the expression is empty") }155        let value = try parser.expr()156        if let extra = parser.peek() { throw CalculatorError.syntax("unexpected “\(extra)” at position \(parser.i + 1)") }157        return try checked(value)158    }159160    /// Evaluates and formats in one step.161    public static func compute(_ expression: String, angle: AngleUnit = .radians) throws -> String {162        format(try evaluate(expression, angle: angle))163    }164165    /// Integers print exactly; other values print with up to 15 significant digits and no trailing zeros.166    public static func format(_ value: CalcValue) -> String {167        switch value {168        case .integer(let n): return String(n)169        case .real(let x):170            if x == 0 { return "0" }171            if x.rounded() == x, abs(x) < 1e15 { return String(Int64(x)) }172            return String(format: "%.15g", x)173        }174    }175176    // MARK: Lexing177178    private mutating func peek() -> Character? {179        while i < chars.count, chars[i].isWhitespace { i += 1 }180        return i < chars.count ? chars[i] : nil181    }182    private mutating func eat(_ c: Character) -> Bool { if peek() == c { i += 1; return true }; return false }183184    private mutating func enter() throws {185        depth += 1186        guard depth <= Self.maxDepth else { throw CalculatorError.tooComplex("nested too deeply (the limit is \(Self.maxDepth) levels)") }187    }188189    // MARK: Grammar190191    private mutating func expr() throws -> CalcValue {192        try enter(); defer { depth -= 1 }193        var v = try term()194        while true {195            if eat("+") { v = Self.add(v, try term()) }196            else if eat("-") { v = Self.subtract(v, try term()) }197            else { return v }198        }199    }200201    private mutating func term() throws -> CalcValue {202        var v = try unary()203        while true {204            if eat("*") { v = Self.multiply(v, try unary()) }205            else if eat("/") { v = try Self.divide(v, try unary()) }206            else if eat("%") { v = try Self.remainder(v, try unary()) }207            else { return v }208        }209    }210211    private mutating func unary() throws -> CalcValue {212        try enter(); defer { depth -= 1 }213        if eat("-") { return Self.negate(try unary()) }214        if eat("+") { return try unary() }215        return try power()216    }217218    private mutating func power() throws -> CalcValue {219        let base = try postfix()220        if eat("^") { return try Self.power(base, try unary()) }221        return base222    }223224    private mutating func postfix() throws -> CalcValue {225        var v = try primary()226        while eat("!") { v = try Self.factorial(v) }227        return v228    }229230    private mutating func primary() throws -> CalcValue {231        guard let c = peek() else { throw CalculatorError.syntax("the expression ends too early") }232        if eat("(") {233            let v = try expr()234            guard eat(")") else { throw CalculatorError.syntax("a closing parenthesis is missing") }235            return v236        }237        if c.isASCII, c.isNumber || c == "." { return try number() }238        if c.isLetter {239            let start = i240            while i < chars.count, chars[i].isLetter || (chars[i].isASCII && chars[i].isNumber) || chars[i] == "_" { i += 1 }241            let name = String(chars[start..<i]).lowercased()242            if eat("(") {243                var args: [CalcValue] = []244                if !eat(")") {245                    repeat {246                        args.append(try expr())247                        guard args.count <= 64 else { throw CalculatorError.tooComplex("calling \(name) with too many arguments") }248                    } while eat(",")249                    guard eat(")") else { throw CalculatorError.syntax("a closing parenthesis is missing after the arguments of \(name)") }250                }251                return try Self.checked(try call(name, args))252            }253            switch name {254            case "pi": return .real(.pi)255            case "e": return .real(M_E)256            case "tau": return .real(2 * .pi)257            default: throw CalculatorError.unknownName(name)258            }259        }260        throw CalculatorError.syntax("unexpected “\(c)” at position \(i + 1)")261    }262263    private mutating func number() throws -> CalcValue {264        let start = i265        func digit(_ k: Int) -> Bool { k < chars.count && chars[k].isASCII && chars[k].isNumber }266        while digit(i) { i += 1 }267        var isInteger = true268        if i < chars.count, chars[i] == "." { isInteger = false; i += 1; while digit(i) { i += 1 } }269        if i < chars.count, chars[i] == "e" || chars[i] == "E" {270            var j = i + 1271            if j < chars.count, chars[j] == "+" || chars[j] == "-" { j += 1 }272            if digit(j) { isInteger = false; i = j; while digit(i) { i += 1 } }273        }274        let text = String(chars[start..<i])275        if isInteger, let n = Int(text) { return .integer(n) }276        guard text != ".", let d = Double(text), d.isFinite else { throw CalculatorError.syntax("“\(text)” is not a valid number") }277        return .real(d)278    }279280    // MARK: Arithmetic281282    private static func checked(_ v: CalcValue) throws -> CalcValue {283        if case .real(let d) = v {284            if d.isNaN { throw CalculatorError.domain("the result is undefined") }285            if d.isInfinite { throw CalculatorError.overflow }286        }287        return v288    }289290    static func add(_ a: CalcValue, _ b: CalcValue) -> CalcValue {291        if case .integer(let x) = a, case .integer(let y) = b {292            let (r, o) = x.addingReportingOverflow(y)293            if !o { return .integer(r) }294        }295        return .real(a.double + b.double)296    }297298    static func subtract(_ a: CalcValue, _ b: CalcValue) -> CalcValue {299        if case .integer(let x) = a, case .integer(let y) = b {300            let (r, o) = x.subtractingReportingOverflow(y)301            if !o { return .integer(r) }302        }303        return .real(a.double - b.double)304    }305306    static func multiply(_ a: CalcValue, _ b: CalcValue) -> CalcValue {307        if case .integer(let x) = a, case .integer(let y) = b {308            let (r, o) = x.multipliedReportingOverflow(by: y)309            if !o { return .integer(r) }310        }311        return .real(a.double * b.double)312    }313314    static func negate(_ a: CalcValue) -> CalcValue {315        if case .integer(let x) = a, x != .min { return .integer(-x) }316        return .real(-a.double)317    }318319    static func divide(_ a: CalcValue, _ b: CalcValue) throws -> CalcValue {320        guard b.double != 0 else { throw CalculatorError.divisionByZero }321        if case .integer(let x) = a, case .integer(let y) = b, y != -1 || x != .min, x % y == 0 { return .integer(x / y) }322        return try checked(.real(a.double / b.double))323    }324325    /// `%`: remainder with the sign of the dividend (truncated division), as in C and Swift.326    static func remainder(_ a: CalcValue, _ b: CalcValue) throws -> CalcValue {327        guard b.double != 0 else { throw CalculatorError.divisionByZero }328        if case .integer(let x) = a, case .integer(let y) = b { return .integer(y == -1 ? 0 : x % y) }329        return .real(a.double.truncatingRemainder(dividingBy: b.double))330    }331332    static func power(_ a: CalcValue, _ b: CalcValue) throws -> CalcValue {333        if case .integer(let base) = a, case .integer(let exponent) = b {334            if exponent < 0, base == 0 { throw CalculatorError.divisionByZero }335            if exponent >= 0 {336                var result = 1, factor = base, n = exponent, exact = true337                while n > 0 {338                    if n & 1 == 1 {339                        let (r, o) = result.multipliedReportingOverflow(by: factor)340                        if o { exact = false; break }341                        result = r342                    }343                    n >>= 1344                    if n > 0 {345                        let (f, o) = factor.multipliedReportingOverflow(by: factor)346                        if o { exact = false; break }347                        factor = f348                    }349                }350                if exact { return .integer(result) }351            }352        }353        let x = a.double, y = b.double354        if x == 0, y < 0 { throw CalculatorError.divisionByZero }355        let r = pow(x, y)356        if r.isNaN { throw CalculatorError.domain("a negative number cannot be raised to a fractional power") }357        return try checked(.real(r))358    }359360    static func factorial(_ v: CalcValue) throws -> CalcValue {361        let n = try integer(v, "factorial")362        guard n >= 0 else { throw CalculatorError.domain("the factorial of a negative number is undefined") }363        guard n <= 170 else { throw CalculatorError.overflow }364        if n <= 20 { return .integer((1...max(1, n)).reduce(1, *)) }365        return .real((1...n).reduce(1.0) { $0 * Double($1) })366    }367368    private static func integer(_ v: CalcValue, _ function: String) throws -> Int {369        switch v {370        case .integer(let n): return n371        case .real(let d):372            guard d.rounded() == d, abs(d) < 9_007_199_254_740_992 else { throw CalculatorError.domain("\(function) needs whole numbers") }373            return Int(d)374        }375    }376377    private static func whole(_ d: Double) -> CalcValue { abs(d) < 9_007_199_254_740_992 ? .integer(Int(d)) : .real(d) }378379    private static func gcd(_ a: Int, _ b: Int) -> Int {380        var x = a.magnitude, y = b.magnitude381        while y != 0 { (x, y) = (y, x % y) }382        return Int(clamping: x)383    }384385    /// Falling product n·(n−1)…(n−k+1), divided step by step by 1…k when `choose` is set. Exact while it fits in 64 bits.386    private static func arrangements(_ n: Int, _ k: Int, choose: Bool, name: String) throws -> CalcValue {387        guard n >= 0, k >= 0 else { throw CalculatorError.domain("\(name) needs non-negative whole numbers") }388        guard k <= n else { return .integer(0) }389        let count = choose ? min(k, n - k) : k390        guard count <= 100_000 else { throw CalculatorError.overflow }391        var exact = 1, isExact = true392        var approximate = 1.0393        for step in 0..<count {394            let factor = n - step395            approximate *= Double(factor)396            if choose { approximate /= Double(step + 1) }397            if isExact {398                let (r, o) = exact.multipliedReportingOverflow(by: factor)399                if o { isExact = false } else { exact = choose ? r / (step + 1) : r }400            }401            if approximate.isInfinite { throw CalculatorError.overflow }402        }403        return isExact ? .integer(exact) : .real(approximate.rounded())404    }405406    // MARK: Functions407408    private func toRadians(_ x: Double) -> Double { angle == .degrees ? x * .pi / 180 : x }409    private func fromRadians(_ x: Double) -> Double { angle == .degrees ? x * 180 / .pi : x }410    /// Removes the last-bit noise of trigonometry so that sin(pi) is 0 and cos(60°) is 0.5.411    private static func clean(_ x: Double) -> Double { (x * 1e15).rounded() / 1e15 }412413    private func call(_ name: String, _ a: [CalcValue]) throws -> CalcValue {414        func arity(_ range: ClosedRange<Int>) throws {415            guard range.contains(a.count) else {416                let expected = range.lowerBound == range.upperBound ? "exactly \(range.lowerBound)" : "\(range.lowerBound) or \(range.upperBound)"417                throw CalculatorError.arity("\(name) takes \(expected) argument\(range.upperBound == 1 ? "" : "s"), got \(a.count).")418            }419        }420        func atLeast(_ n: Int) throws {421            guard a.count >= n else { throw CalculatorError.arity("\(name) needs at least \(n) argument\(n == 1 ? "" : "s"), got \(a.count).") }422        }423        func x() throws -> Double { try arity(1...1); return a[0].double }424425        switch name {426        case "sqrt":427            let v = try x()428            guard v >= 0 else { throw CalculatorError.domain("the square root of a negative number is not a real number") }429            let root = v.squareRoot()430            if case .integer(let n) = a[0], root.rounded() == root {431                let r = Int(root), (square, overflow) = r.multipliedReportingOverflow(by: r)432                if !overflow, square == n { return .integer(r) }433            }434            return .real(root)435        case "cbrt":436            let root = cbrt(try x())437            if case .integer(let n) = a[0], root.rounded() == root, abs(root) < 2_000_000, Int(root) * Int(root) * Int(root) == n { return .integer(Int(root)) }438            return .real(root)439        case "abs":440            try arity(1...1)441            if case .integer(let n) = a[0], n != .min { return .integer(abs(n)) }442            return .real(abs(a[0].double))443        case "ln":444            let v = try x()445            guard v > 0 else { throw CalculatorError.domain("the logarithm of a number that is not positive is undefined") }446            return .real(log(v))447        case "log10", "log2", "log":448            try arity(name == "log" ? 1...2 : 1...1)449            let v = a[0].double450            guard v > 0 else { throw CalculatorError.domain("the logarithm of a number that is not positive is undefined") }451            if name == "log2" { return .real(Self.clean(log2(v))) }452            if a.count == 2 {453                let base = a[1].double454                guard base > 0, base != 1 else { throw CalculatorError.domain("a logarithm base must be positive and different from 1") }455                return .real(Self.clean(log(v) / log(base)))456            }457            return .real(Self.clean(log10(v)))458        case "exp": return .real(exp(try x()))459        case "sin": return .real(Self.clean(sin(toRadians(try x()))))460        case "cos": return .real(Self.clean(cos(toRadians(try x()))))461        case "tan":462            let r = toRadians(try x())463            guard Self.clean(cos(r)) != 0 else { throw CalculatorError.domain("the tangent is undefined at this angle") }464            return .real(Self.clean(tan(r)))465        case "asin", "acos":466            let v = try x()467            guard (-1...1).contains(v) else { throw CalculatorError.domain("\(name) is only defined between -1 and 1") }468            return .real(Self.clean(fromRadians(name == "asin" ? asin(v) : acos(v))))469        case "atan": return .real(Self.clean(fromRadians(atan(try x()))))470        case "atan2":471            try arity(2...2)472            return .real(Self.clean(fromRadians(atan2(a[0].double, a[1].double))))473        case "sinh": return .real(sinh(try x()))474        case "cosh": return .real(cosh(try x()))475        case "tanh": return .real(tanh(try x()))476        case "floor", "ceil", "trunc":477            try arity(1...1)478            if case .integer = a[0] { return a[0] }479            let v = a[0].double480            return Self.whole(name == "floor" ? floor(v) : name == "ceil" ? ceil(v) : trunc(v))481        case "round":482            try arity(1...2)483            if a.count == 1 {484                if case .integer = a[0] { return a[0] }485                return Self.whole(a[0].double.rounded(.toNearestOrAwayFromZero))486            }487            let digits = try Self.integer(a[1], "round")488            guard (-15...15).contains(digits) else { throw CalculatorError.domain("round accepts between -15 and 15 decimal places") }489            if case .integer = a[0], digits >= 0 { return a[0] }490            let scale = pow(10, Double(digits))491            let rounded = (a[0].double * scale).rounded(.toNearestOrAwayFromZero) / scale492            return rounded.rounded() == rounded ? Self.whole(rounded) : .real(rounded)493        case "min", "max":494            try atLeast(1)495            return a.dropFirst().reduce(a[0]) { best, next in496                (name == "min" ? next.double < best.double : next.double > best.double) ? next : best497            }498        case "factorial":499            try arity(1...1)500            return try Self.factorial(a[0])501        case "ncr", "npr":502            try arity(2...2)503            let label = name == "ncr" ? "nCr" : "nPr"504            return try Self.arrangements(try Self.integer(a[0], label), try Self.integer(a[1], label), choose: name == "ncr", name: label)505        case "mod":506            // Floored modulo: the result has the sign of the divisor.507            try arity(2...2)508            guard a[1].double != 0 else { throw CalculatorError.divisionByZero }509            if case .integer(let p) = a[0], case .integer(let q) = a[1] {510                if q == -1 { return .integer(0) }511                let r = p % q512                return .integer(r != 0 && (r < 0) != (q < 0) ? r + q : r)513            }514            let p = a[0].double, q = a[1].double515            return .real(p - q * floor(p / q))516        case "gcd", "lcm":517            try atLeast(2)518            var acc = try Self.integer(a[0], name)519            for v in a.dropFirst() {520                let n = try Self.integer(v, name)521                if name == "gcd" { acc = Self.gcd(acc, n); continue }522                if acc == 0 || n == 0 { acc = 0; continue }523                let (r, o) = (acc / Self.gcd(acc, n)).multipliedReportingOverflow(by: n)524                guard !o, r != .min else { throw CalculatorError.overflow }525                acc = abs(r)526            }527            return .integer(abs(acc))528        default: throw CalculatorError.unknownName(name)529        }530    }531}532533public struct CalculatorTool: AgentTool {534    public let risk: ToolRisk = .safe535    public let definition = ToolDefinition(536        name: "calculator",537        summary: "Evaluates one arithmetic expression exactly. Operators: + - * / ^ % (remainder) and ! (factorial), with parentheses. "538            + "Constants: pi, e, tau. Functions: sqrt cbrt abs ln log10 log2 log(x, base) exp sin cos tan asin acos atan atan2 sinh cosh tanh "539            + "floor ceil round(x, digits) trunc min max factorial nCr nPr mod gcd lcm. Numbers only: no variables, no code.",540        parameters: [541            "type": "object",542            "properties": [543                "expression": ["type": "string", "minLength": 1, "maxLength": .number(Double(Calculator.maxLength)), "description": "For example (3 + 4) * 2 ^ 3 or nCr(52, 5)"],544                "angle_unit": ["type": "string", "enum": ["radians", "degrees"], "description": "Unit for trigonometric functions. Default: radians."],545            ],546            "required": ["expression"],547            "additionalProperties": false,548        ])549    public init() {}550551    public func run(_ arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {552        let expression = arguments["expression"]?.stringValue ?? ""553        let angle = arguments["angle_unit"]?.stringValue.flatMap(AngleUnit.init(rawValue:)) ?? .radians554        do { return ToolOutput(try Calculator.compute(expression, angle: angle)) }555        catch let error as CalculatorError { throw ToolError(error.errorDescription ?? "The expression could not be evaluated.") }556    }557}558
Files main
Menu

Theme