Sources/OrgCore/Compute/BabelCalc.swift

257 lines · 13585 bytes

16 symbols in this file
  1import Foundation
  2
  3// ob-calc (Org 9.8.7) on `Calc`: each line of the body goes onto a fresh Calc stack, as in a
  4// new Emacs, and the value is the top of the stack. Calc's own modes apply, not
  5// `org-calc-default-modes`: 12 digits shown in full.
  6
  7extension Babel {
  8    /// A calc block: its lines, trimmed, and its variables as Calc values.
  9    public struct CalcBlock: Sendable, Equatable {
 10        let lines: [String]
 11        let vars: [Variable]
 12        /// `org-babel-result-cond` takes the value as a string.
 13        let scalar: Bool
 14        /// Why the block can't run here, found when it was planned.
 15        let refusal: Calc.Unsupported?
 16
 17        struct Variable: Sendable, Equatable {
 18            let name: String
 19            let value: Calc.Value
 20        }
 21    }
 22
 23    /// `org-babel-execute:calc` with `emacs -Q` modes.
 24    static let calcModes: Calc.Modes = {
 25        var modes = Calc.Modes()
 26        modes.format = .float(0)
 27        return modes
 28    }()
 29
 30    /// Plans a calc block: natively through `job.calc`, and in Emacs through `job.input`.
 31    static func calcJob(body: String, vars: [(String, VarValue)], params: Params, finish: BabelJob.Finish, directory: String?,
 32                        block: Range<Int>, blockText: String, alwaysAsk: Bool) throws -> BabelJob {
 33        let prologue = params.single[":prologue"], epilogue = params.single[":epilogue"]
 34        let expanded = (prologue.map { $0 + "\n" } ?? "") + body + (epilogue.map { "\n" + $0 + "\n" } ?? "")
 35        var job = BabelJob(language: "calc", runner: .emacs, input: calcScript(body: body, vars: vars, params: params, finish: finish),
 36                           directory: directory, block: block, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish)
 37        let lines = expanded.components(separatedBy: CharacterSet(charactersIn: "\n\r")).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
 38        var values: [CalcBlock.Variable] = []
 39        var refusal: Calc.Unsupported?
 40        do {
 41            // `org-babel-read` makes a number of an unquoted `:prologue 2`, which `concat` refuses.
 42            if [":prologue", ":epilogue"].contains(where: { key in params.single[key].map { !params.quoted.contains(key) && number($0) != nil } ?? false }) {
 43                throw Calc.Unsupported("numeric :prologue or :epilogue")
 44            }
 45            values = try vars.map { try CalcBlock.Variable(name: $0.0, value: calcValue($0.1, name: $0.0)) }
 46        } catch let error as Calc.Unsupported {
 47            refusal = error
 48        }
 49        job.calc = CalcBlock(lines: lines, vars: values, scalar: resultCondScalar(finish.params), refusal: refusal)
 50        return job
 51    }
 52
 53    /// `org-babel-result-cond`: whether the value is taken as a string.
 54    public static func resultCondScalar(_ params: [String]) -> Bool {
 55        params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
 56            || params.contains("pp") || params.contains("file")
 57            || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
 58    }
 59
 60    /// A `:var` value as ob-calc pushes it: a number read by Calc, a list as a vector, a table as
 61    /// a matrix (one row as a vector). Strings, Lisp floats inside lists, and names Calc reads as
 62    /// something else are refused.
 63    static func calcValue(_ value: VarValue, name: String) throws -> Calc.Value {
 64        let refusal = Calc.Unsupported("value of :var \(name)")
 65        guard name.range(of: "^[A-Za-z][A-Za-z0-9]*$", options: .regularExpression) != nil, !Calc.constants.contains(name), !Calc.reserved.contains(name) else { throw refusal }
 66        func integer(_ cell: Cell) throws -> Calc.Value {
 67            guard case .number(let n) = cell, let i = Int(n) else { throw refusal }
 68            return .int(i)
 69        }
 70        switch value {
 71        case .number(let n):
 72            return try Calc.withModes(calcModes) {
 73                var parser = Calc.Parser(n.replacingOccurrences(of: "e+", with: "e"))
 74                return try Calc.Evaluator(modes: calcModes).eval(try parser.parse())
 75            }
 76        case .list(let items) where items.count > 1:
 77            return .vector(try items.map(integer))
 78        case .table(let rows) where !rows.isEmpty && !rows.contains(where: { $0 == nil || $0!.isEmpty }):
 79            let matrix = try rows.map { try $0!.map(integer) }
 80            return matrix.count == 1 ? .vector(matrix[0]) : .vector(matrix.map { .vector($0) })
 81        default:
 82            throw refusal
 83        }
 84    }
 85
 86    /// Runs `job.calc` as ob-calc does: the output `calcScript` prints. Throws `Calc.Unsupported`
 87    /// for what Calc here doesn't do as Emacs's does, and `Failure` for Emacs's errors.
 88    public static func evaluateCalc(_ job: BabelJob) throws -> BabelOutput {
 89        guard let block = job.calc else { throw Failure.message("Not a calc block.") }
 90        if let refusal = block.refusal { throw refusal }
 91        do {
 92            return try calc(block)
 93        } catch let error as Calc.Failure {
 94            // `math-read-number` of the error `calc-eval` returns.
 95            throw Failure.message("Wrong type argument: stringp, (\(error.position) \"\(error.reason)\")")
 96        }
 97    }
 98
 99    static func calc(_ block: CalcBlock) throws -> BabelOutput {
100        try Calc.withModes(calcModes) {
101            let evaluator = Calc.Evaluator(modes: calcModes)
102            let names = Set(block.vars.map(\.name))
103            var stored: [String: Calc.Value] = [:]
104            for variable in block.vars { stored[variable.name] = variable.value }
105            /// Stack entries: a number, or the string ob-calc pushes for any other value.
106            /// `known` is false when Calc here couldn't tell whether ob-calc pushed a number.
107            enum Entry { case number(Calc.Value), text(String, known: Bool) }
108            var stack: [Entry] = []
109            func pop() throws -> Calc.Value {
110                guard let top = stack.popLast() else { throw Failure.message("Too few elements on stack") }
111                switch top {
112                case .number(let v): return v
113                case .text(_, true): throw Failure.message("Invalid data object encountered")
114                case .text(_, false): throw Calc.Unsupported("symbolic arithmetic")
115                }
116            }
117            for line in block.lines where !line.isEmpty {
118                if names.contains(line) {
119                    stack.append(.number(stored[line]!))
120                } else if line.hasPrefix("'") {
121                    let key = String(line.dropFirst())
122                    let node: Calc.Node
123                    switch key {
124                    case "+", "-", "*", "/", "^", "%", "\\":
125                        guard stack.count >= 2 else { throw Failure.message("Too few elements on stack") }
126                        let b = try pop(), a = try pop()
127                        node = .binary(Character(key), .number(a), .number(b))
128                    case "n": node = .unary("-", .number(try pop()))
129                    case "&": node = .binary("/", .number(.int(1)), .number(try pop()))
130                    case "Q": node = .call("sqrt", [.number(try pop())])
131                    case "A": node = .call("abs", [.number(try pop())])
132                    default: throw Calc.Unsupported("stack command '\(key)")
133                    }
134                    stack.append(.number(try checked(try evaluator.eval(node))))
135                } else {
136                    var parser = Calc.Parser(line)
137                    let tree = try parser.parse()
138                    // Calc's default modes give `pi` and `e` their values, which Calc here keeps
139                    // as symbols for table formulas.
140                    if !tree.variables.isDisjoint(with: Calc.constants) { throw Calc.Unsupported("Calc constants") }
141                    // `calc-eval` of the line: a number is pushed as one.
142                    let first: Calc.Value?
143                    do {
144                        first = try checked(try evaluator.eval(tree))
145                    } catch is Calc.Unsupported where !tree.variables.isDisjoint(with: names) {
146                        // Calc here can't keep this formula of the block's variables, which
147                        // Emacs's Calc keeps as a formula unless it simplifies to a number.
148                        first = nil
149                    }
150                    if let first, isNumber(first) {
151                        stack.append(.number(first))
152                    } else {
153                        // The formula again with the block's variables put in, as text.
154                        let resolved = try checked(try evaluator.eval(tree.substituting(stored)))
155                        let text = try Calc.format(resolved, calcModes.format).replacingOccurrences(of: "'", with: "")
156                        stack.append(.text(text, known: first != nil))
157                    }
158                }
159            }
160            guard let top = stack.last else { throw Failure.message("Too few elements on stack") }
161            let result: Calc.Value
162            switch top {
163            case .number(let v): result = v
164            case .text(let s, _):
165                var parser = Calc.Parser(s)
166                result = try checked(try evaluator.eval(try parser.parse()))
167            }
168            let object: [String: Any]
169            if case .vector(let items) = result, !block.scalar {
170                let rows: [[Calc.Value]]
171                if case .vector(let first)? = items.first, !first.isEmpty,
172                   items.allSatisfy({ if case .vector(let row) = $0 { row.count == first.count } else { false } }) {
173                    rows = items.map { if case .vector(let row) = $0 { row } else { [] } }
174                } else {
175                    rows = [items]
176                }
177                guard !rows.contains(where: \.isEmpty) else { throw Calc.Unsupported("empty vector") }
178                object = ["rows": try rows.map { try $0.map { try Calc.format($0, calcModes.format) } }]
179            } else {
180                object = ["value": try Calc.format(result, calcModes.format)]
181            }
182            let data = try JSONSerialization.data(withJSONObject: object)
183            return BabelOutput(stdout: String(decoding: data, as: UTF8.self))
184        }
185    }
186
187    static func isNumber(_ value: Calc.Value) -> Bool {
188        switch value {
189        case .int, .float, .frac: true
190        default: false
191        }
192    }
193
194    /// Dates show in Calc's own format, not Org's.
195    static func checked(_ value: Calc.Value) throws -> Calc.Value {
196        func hasDate(_ v: Calc.Value) -> Bool {
197            switch v {
198            case .date: true
199            case .vector(let items): items.contains(where: hasDate)
200            default: false
201            }
202        }
203        if hasDate(value) { throw Calc.Unsupported("dates in calc blocks") }
204        return value
205    }
206
207    /// Emacs running `org-babel-execute:calc` on the block, printing the value as JSON.
208    static func calcScript(body: String, vars: [(String, VarValue)], params: Params, finish: BabelJob.Finish) -> String {
209        var entries = vars.map { "(:var . (\($0.0) . \(lispLiteral($0.1))))" }
210        for key in [":prologue", ":epilogue"] {
211            if let value = params.single[key] {
212                entries.append("(\(key) . \(!params.quoted.contains(key) && number(value) != nil ? value : lispString(value)))")
213            }
214        }
215        entries.append("(:result-params . (" + finish.params.map { lispString($0) }.joined(separator: " ") + "))")
216        return """
217            ;;; -*- lexical-binding: t -*-
218            (require 'ob-calc)
219            (require 'json)
220            (condition-case err
221                (let* ((inhibit-message t)
222                       (result (org-babel-execute:calc \(lispString(body)) '(\(entries.joined(separator: " "))))))
223                  (princ (json-encode
224                          (if (listp result)
225                              `((rows . ,(vconcat (mapcar (lambda (row) (vconcat (mapcar (lambda (c) (format "%s" c)) row))) result))))
226                            `((value . ,(format "%s" result)))))))
227              (error (let ((inhibit-message nil)) (message "%s" (error-message-string err)))
228                     (kill-emacs 1)))
229            """
230    }
231}
232
233extension Calc {
234    /// `body` with `modes`' precision, fractions and symbolic mode.
235    static func withModes<T>(_ modes: Modes, _ body: () throws -> T) throws -> T {
236        guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") }
237        return try $precision.withValue(modes.precision) {
238            try $fractions.withValue(modes.preferFractions) {
239                try $symbolicMode.withValue(modes.symbolic) { try $nesting.withValue(Nesting(), operation: body) }
240            }
241        }
242    }
243}
244
245extension Calc.Node {
246    /// `org-babel-calc-maybe-resolve-var`: the variables in `values` replaced by their values.
247    func substituting(_ values: [String: Calc.Value]) -> Calc.Node {
248        switch self {
249        case .number: self
250        case .variable(let name): values[name].map(Calc.Node.number) ?? self
251        case .vector(let items): .vector(items.map { $0.substituting(values) })
252        case .unary(let op, let a): .unary(op, a.substituting(values))
253        case .binary(let op, let a, let b): .binary(op, a.substituting(values), b.substituting(values))
254        case .call(let name, let args): .call(name, args.map { $0.substituting(values) })
255        }
256    }
257}