Sources/OrgCore/Compute/BabelCalc.swift

0dbf01d3bc8b68b775dfc3a8385b84bd682b85dd
orgstar/Sources/OrgCore/Compute/BabelCalc.swift

254 lines · 13271 bytes

  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    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-eval` of the line: a number is pushed as one.
139                    let first: Calc.Value?
140                    do {
141                        first = try checked(try evaluator.eval(tree))
142                    } catch is Calc.Unsupported where !tree.variables.isDisjoint(with: names) {
143                        // Calc here can't keep this formula of the block's variables, which
144                        // Emacs's Calc keeps as a formula unless it simplifies to a number.
145                        first = nil
146                    }
147                    if let first, isNumber(first) {
148                        stack.append(.number(first))
149                    } else {
150                        // The formula again with the block's variables put in, as text.
151                        let resolved = try checked(try evaluator.eval(tree.substituting(stored)))
152                        let text = try Calc.format(resolved, calcModes.format).replacingOccurrences(of: "'", with: "")
153                        stack.append(.text(text, known: first != nil))
154                    }
155                }
156            }
157            guard let top = stack.last else { throw Failure.message("Too few elements on stack") }
158            let result: Calc.Value
159            switch top {
160            case .number(let v): result = v
161            case .text(let s, _):
162                var parser = Calc.Parser(s)
163                result = try checked(try evaluator.eval(try parser.parse()))
164            }
165            let object: [String: Any]
166            if case .vector(let items) = result, !block.scalar {
167                let rows: [[Calc.Value]]
168                if case .vector(let first)? = items.first, !first.isEmpty,
169                   items.allSatisfy({ if case .vector(let row) = $0 { row.count == first.count } else { false } }) {
170                    rows = items.map { if case .vector(let row) = $0 { row } else { [] } }
171                } else {
172                    rows = [items]
173                }
174                guard !rows.contains(where: \.isEmpty) else { throw Calc.Unsupported("empty vector") }
175                object = ["rows": try rows.map { try $0.map { try Calc.format($0, calcModes.format) } }]
176            } else {
177                object = ["value": try Calc.format(result, calcModes.format)]
178            }
179            let data = try JSONSerialization.data(withJSONObject: object)
180            return BabelOutput(stdout: String(decoding: data, as: UTF8.self))
181        }
182    }
183
184    static func isNumber(_ value: Calc.Value) -> Bool {
185        switch value {
186        case .int, .float, .frac: true
187        default: false
188        }
189    }
190
191    /// Dates show in Calc's own format, not Org's.
192    static func checked(_ value: Calc.Value) throws -> Calc.Value {
193        func hasDate(_ v: Calc.Value) -> Bool {
194            switch v {
195            case .date: true
196            case .vector(let items): items.contains(where: hasDate)
197            default: false
198            }
199        }
200        if hasDate(value) { throw Calc.Unsupported("dates in calc blocks") }
201        return value
202    }
203
204    /// Emacs running `org-babel-execute:calc` on the block, printing the value as JSON.
205    static func calcScript(body: String, vars: [(String, VarValue)], params: Params, finish: BabelJob.Finish) -> String {
206        var entries = vars.map { "(:var . (\($0.0) . \(lispLiteral($0.1))))" }
207        for key in [":prologue", ":epilogue"] {
208            if let value = params.single[key] {
209                entries.append("(\(key) . \(!params.quoted.contains(key) && number(value) != nil ? value : lispString(value)))")
210            }
211        }
212        entries.append("(:result-params . (" + finish.params.map { lispString($0) }.joined(separator: " ") + "))")
213        return """
214            ;;; -*- lexical-binding: t -*-
215            (require 'ob-calc)
216            (require 'json)
217            (condition-case err
218                (let* ((inhibit-message t)
219                       (result (org-babel-execute:calc \(lispString(body)) '(\(entries.joined(separator: " "))))))
220                  (princ (json-encode
221                          (if (listp result)
222                              `((rows . ,(vconcat (mapcar (lambda (row) (vconcat (mapcar (lambda (c) (format "%s" c)) row))) result))))
223                            `((value . ,(format "%s" result)))))))
224              (error (let ((inhibit-message nil)) (message "%s" (error-message-string err)))
225                     (kill-emacs 1)))
226            """
227    }
228}
229
230extension Calc {
231    /// `body` with `modes`' precision, fractions and symbolic mode.
232    static func withModes<T>(_ modes: Modes, _ body: () throws -> T) throws -> T {
233        guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") }
234        return try $precision.withValue(modes.precision) {
235            try $fractions.withValue(modes.preferFractions) {
236                try $symbolicMode.withValue(modes.symbolic, operation: body)
237            }
238        }
239    }
240}
241
242extension Calc.Node {
243    /// `org-babel-calc-maybe-resolve-var`: the variables in `values` replaced by their values.
244    func substituting(_ values: [String: Calc.Value]) -> Calc.Node {
245        switch self {
246        case .number: self
247        case .variable(let name): values[name].map(Calc.Node.number) ?? self
248        case .vector(let items): .vector(items.map { $0.substituting(values) })
249        case .unary(let op, let a): .unary(op, a.substituting(values))
250        case .binary(let op, let a, let b): .binary(op, a.substituting(values), b.substituting(values))
251        case .call(let name, let args): .call(name, args.map { $0.substituting(values) })
252        }
253    }
254}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form