Sources/OrgCore/Compute/TableSbe.swift

7fee8f1214931d1d034bc40d1155a605813239cc
orgstar/Sources/OrgCore/Compute/TableSbe.swift

216 lines · 11853 bytes

  1import Foundation
  2
  3// `org-sbe` (ob-table.el, Org 9.8.7) in Lisp table formulas. The named block runs in `Elisp`,
  4// or for js through `TableBlocks.javaScript`, and named tables and lists are read from the
  5// file. Other languages, and references this can't follow, throw `Elisp.Unsupported`, so the
  6// table goes to Emacs.
  7
  8/// How `org-sbe` runs js blocks.
  9public enum TableBlocks {
 10    /// Runs a js job to the end on the calling thread; nil when it can't. The app sets it.
 11    nonisolated(unsafe) public static var javaScript: ((BabelJob) throws -> BabelOutput?)?
 12}
 13
 14extension Babel {
 15    /// Defines `org-sbe` for formulas in the file whose text `text` gives.
 16    static func defineSbe(_ lisp: Elisp, text: @escaping () -> String) {
 17        lisp.defineForm("org-sbe") { _, args in .string(try sbe(args, text: text())) }
 18    }
 19
 20    /// The macro's value: `(org-trim (format "%S" result))`, or the result when it is a string.
 21    static func sbe(_ args: [Sexp], text: String) throws -> String {
 22        guard let first = args.first else { throw Elisp.Signal(message: "Wrong number of arguments: org-sbe, 0") }
 23        let name: String
 24        switch first {
 25        case .string(let s): name = s
 26        case .symbol(let s): name = s
 27        default: throw Elisp.Unsupported(what: "org-sbe with a block name that isn't a symbol")
 28        }
 29        var variables = Array(args.dropFirst())
 30        var header = ""
 31        if case .string(let s)? = variables.first {
 32            header = s
 33            variables.removeFirst()
 34        }
 35        var specs: [String] = []
 36        for variable in variables {
 37            guard case .list(let items) = variable, case .symbol(let variableName)? = items.first else {
 38                throw Elisp.Unsupported(what: "org-sbe with an argument that isn't (NAME VALUE)")
 39            }
 40            // A value after `$` is written as Lisp, so a string stays a string.
 41            var quote = false
 42            var values: [Sexp] = []
 43            for item in items.dropFirst() {
 44                if item == .symbol("$") {
 45                    quote = true
 46                    continue
 47                }
 48                if quote {
 49                    values.append(.string(Elisp.printed(item, escape: true)))
 50                } else if !Elisp.isNil(item) {
 51                    values.append(item)
 52                }
 53                quote = false
 54            }
 55            if values.count > 1 {
 56                let read = try values.map { value -> Sexp in
 57                    guard case .string(let s) = value else { throw Elisp.Unsupported(what: "org-sbe with values that aren't text") }
 58                    do { return try LispReader.readFirst(s).sexp } catch { throw Elisp.Signal(message: "End of file during parsing") }
 59                }
 60                specs.append(variableName + "='" + Elisp.printed(.list(read), escape: true))
 61            } else {
 62                specs.append(variableName + "=" + (try Elisp.format([.string("%s"), values.first ?? .nil])))
 63            }
 64        }
 65        guard !name.isEmpty else { return "" }
 66        guard !name.contains(where: { "[]():\"".contains($0) }) else { throw Elisp.Unsupported(what: "org-sbe with the reference \(name)") }
 67        var value = try sbeReference(name, header: header, arguments: splitArguments(specs.joined(separator: ", ")), text: text)
 68        // `org-babel-ref-resolve` gives a symbol's name.
 69        if case .symbol(let s) = value, !Elisp.isNil(value) { value = .string(s) }
 70        // `:var results=` takes off a first row followed by a rule, as column names.
 71        if case .list(let rows) = value, rows.count > 1, rows[0] != .symbol("hline"), rows[1] == .symbol("hline"),
 72           !rows.dropFirst(2).contains(.symbol("hline")) {
 73            value = rows.count > 2 ? .list(Array(rows.dropFirst(2))) : .nil
 74        }
 75        let printed = value.string ?? Elisp.printed(value, escape: true)
 76        return printed.trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
 77    }
 78
 79    /// `org-babel-ref-resolve` for `name[header](arguments)`: a src block's value, or a named
 80    /// table or list.
 81    static func sbeReference(_ name: String, header: String, arguments: [String], text: String) throws -> Sexp {
 82        let ns = text as NSString
 83        let model = DocumentModel(tree: OrgParser.parse(text))
 84        let options = Options()
 85        // The first `#+NAME:` line with the name: a src block's, or another element's.
 86        let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
 87        guard let named = text.range(of: pattern, options: .regularExpression) else { throw notFound(name, text: text) }
 88        let start = NSRange(named, in: text).location
 89        let block = model.srcBlocks.first { block in
 90            guard block.name == name, block.range.lowerBound > start else { return false }
 91            let between = ns.substring(with: NSRange(location: start, length: block.range.lowerBound - start))
 92            return between.split(separator: "\n").allSatisfy { $0.trimmingCharacters(in: .whitespaces).hasPrefix("#+") }
 93        }
 94        guard let block else {
 95            do {
 96                return try sbeSexp(resolve(name, model: model, text: ns, refs: References(resolved: [:], options: options)))
 97            } catch let failure as Failure {
 98                throw sbeError(failure, text: text)
 99            }
100        }
101        let params: Params
102        do {
103            params = try Params(block: block, model: model, text: ns, extra: [Params.parse(header) + arguments.map { (":var", $0) }])
104        } catch let failure as Failure {
105            throw sbeError(failure, text: text)
106        }
107        if params.single[":cache"] == "yes" { throw Elisp.Unsupported(what: "org-sbe with :cache") }
108        var refs = References(resolved: [:], options: options)
109        refs.visiting = [name]
110        // The blocks its `:var`s refer to run first, as `DocumentSession.runBabel` runs them.
111        while true {
112            switch plan(block, params: params, model: model, text: ns, options: options, location: block.range, name: name, refs: refs, useCache: false) {
113            case .failure(let failure):
114                throw sbeError(failure, text: text)
115            case .success(let job):
116                if job.needsFile { throw Elisp.Unsupported(what: "org-sbe with Lisp that needs the file's name") }
117                if let need = job.needs.first {
118                    refs.resolved[need.reference] = varValue(need.job.finish, try sbeRun(need.job))
119                    continue
120                }
121                return try sbeValue(job, lexical: params.single[":lexical"] == "yes")
122            }
123        }
124    }
125
126    /// A block a reference needs, run as `Babel.evaluateNatively` or in JavaScriptCore.
127    static func sbeRun(_ job: BabelJob) throws -> BabelOutput {
128        if job.lispForm != nil {
129            do {
130                guard let output = try evaluateNatively(job) else { throw Elisp.Unsupported(what: "org-sbe with Lisp only Emacs runs") }
131                return output
132            } catch let Failure.message(message) {
133                // An error in the block.
134                throw Elisp.Signal(message: message)
135            }
136        }
137        guard job.language == "js" || job.language == "javascript" else { throw Elisp.Unsupported(what: "org-sbe with \(job.language) blocks") }
138        guard let output = try? TableBlocks.javaScript?(job), output.status == 0 else { throw Elisp.Unsupported(what: "org-sbe with js blocks") }
139        return output
140    }
141
142    /// The block's value as `org-babel-execute-src-block` returns it.
143    static func sbeValue(_ job: BabelJob, lexical: Bool) throws -> Sexp {
144        let params = job.finish.params
145        if params.contains("file") || job.finish.colnames != nil || job.finish.rownames != nil {
146            throw Elisp.Unsupported(what: "org-sbe with this block's results")
147        }
148        let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
149            || params.contains("pp") || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
150        var result: Sexp
151        if let form = job.lispForm {
152            // `org-babel-execute:emacs-lisp`: dynamic binding unless `:lexical yes`.
153            let lisp = Elisp()
154            lisp.lexical = lexical
155            lisp.syntax = .emacsLisp
156            lisp.standardTime()
157            result = try lisp.eval(try LispReader.readFirst(form).sexp)
158            if Elisp.containsClosure(result) { throw Elisp.Unsupported(what: "org-sbe with a closure") }
159            if scalar {
160                result = .string(params.contains("scalar") || params.contains("verbatim") ? Elisp.printed(result, escape: true) : try Elisp.format([.string("%s"), result]))
161            }
162        } else {
163            // `org-babel-js-read`: a number, a string, or the symbol a quoted word reads as.
164            let raw = rawResult(job.finish, try sbeRun(job))
165            if scalar {
166                result = .string(raw)
167            } else if raw.hasPrefix("(") || raw.hasPrefix("[") || raw.hasPrefix("`") || raw.contains("\\") {
168                throw Elisp.Unsupported(what: "org-sbe with this js value")
169            } else if raw.hasPrefix("'") {
170                guard let m = raw.firstMatch(of: /^'([A-Za-z0-9_-]+)(?:'|\s)/) else { throw Elisp.Unsupported(what: "org-sbe with this js value") }
171                result = try number(String(m.1)).map { try LispReader.readFirst($0).sexp } ?? .symbol(String(m.1))
172            } else if raw.hasPrefix("\""), raw.hasSuffix("\""), raw.count >= 2 {
173                result = .string(String(raw.dropFirst().dropLast()))
174            } else {
175                result = try number(raw).map { try LispReader.readFirst($0).sexp } ?? .string(raw)
176            }
177        }
178        if params.contains("discard") { return .nil }
179        if !job.finish.output, params.contains("vector") || params.contains("table") {
180            if case .list = result {} else if !Elisp.isNil(result) { result = .list([.list([result])]) }
181        }
182        return result
183    }
184
185    /// A named table or list as `org-babel-read-element` reads it.
186    static func sbeSexp(_ value: VarValue) throws -> Sexp {
187        func cell(_ c: Cell) throws -> Sexp {
188            switch c {
189            case .text(let s): return .string(s)
190            case .number(let n): return try LispReader.readFirst(n).sexp
191            }
192        }
193        switch value {
194        case .scalar(let s): return .string(s)
195        case .number(let n): return try LispReader.readFirst(n).sexp
196        case .list(let items): return .list(try items.map(cell))
197        case .table(let rows): return .list(try rows.map { row in try row.map { .list(try $0.map(cell)) } ?? .symbol("hline") })
198        }
199    }
200
201    /// A reference to nothing is an error; to an ID, which only Emacs looks up, unsupported.
202    static func notFound(_ name: String, text: String) -> Error {
203        let pattern = "(?im)^[ \\t]*:(custom_)?id:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
204        if text.range(of: pattern, options: .regularExpression) != nil { return Elisp.Unsupported(what: "org-sbe with an ID reference") }
205        return Elisp.Signal(message: "Reference ‘\(name)’ not found in this buffer")
206    }
207
208    /// What a planning failure is in Emacs: a reference to nothing is an error, the rest
209    /// unsupported here.
210    static func sbeError(_ failure: Failure, text: String) -> Error {
211        guard case .message(let message) = failure, let m = message.firstMatch(of: /^Can't find (.+) for :var\.$/) else {
212            return Elisp.Unsupported(what: "org-sbe with a block orgstar can't run")
213        }
214        return notFound(String(m.1), text: text)
215    }
216}
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