Sources/OrgCore/Compute/TableSbe.swift
259 lines · 14693 bytes
12 symbols in this file
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 /// Whether `org-sbe` may run; the app ties it to running source blocks.
13 nonisolated(unsafe) public static var allowed: () -> Bool = { true }
14 /// The reason a table goes to the app when `allowed` is false.
15 public static let lockedReason = "Lisp org-sbe with source blocks locked"
16}
17
18extension Babel {
19 /// Defines `org-sbe` for formulas in the file whose text `text` gives.
20 static func defineSbe(_ lisp: Elisp, text: @escaping () -> String) {
21 lisp.defineForm("org-sbe") { _, args in
22 guard TableBlocks.allowed() else { throw Elisp.Unsupported(what: "org-sbe with source blocks locked") }
23 return .string(try sbe(args, text: text()))
24 }
25 }
26
27 /// The macro's value: `(org-trim (format "%S" result))`, or the result when it is a string.
28 static func sbe(_ args: [Sexp], text: String) throws -> String {
29 guard let first = args.first else { throw Elisp.Signal(message: "Wrong number of arguments: org-sbe, 0") }
30 let name: String
31 switch first {
32 case .string(let s): name = s
33 case .symbol(let s): name = s
34 default: throw Elisp.Unsupported(what: "org-sbe with a block name that isn't a symbol")
35 }
36 var variables = Array(args.dropFirst())
37 var header = ""
38 if case .string(let s)? = variables.first {
39 header = s
40 variables.removeFirst()
41 }
42 var specs: [String] = []
43 for variable in variables {
44 guard case .list(let items) = variable, case .symbol(let variableName)? = items.first else {
45 throw Elisp.Unsupported(what: "org-sbe with an argument that isn't (NAME VALUE)")
46 }
47 // A value after `$` is written as Lisp, so a string stays a string.
48 var quote = false
49 var values: [Sexp] = []
50 for item in items.dropFirst() {
51 if item == .symbol("$") {
52 quote = true
53 continue
54 }
55 if quote {
56 values.append(.string(Elisp.printed(item, escape: true)))
57 } else if !Elisp.isNil(item) {
58 values.append(item)
59 }
60 quote = false
61 }
62 if values.count > 1 {
63 let read = try values.map { value -> Sexp in
64 guard case .string(let s) = value else { throw Elisp.Unsupported(what: "org-sbe with values that aren't text") }
65 do { return try LispReader.readFirst(s).sexp } catch { throw Elisp.Signal(message: "End of file during parsing") }
66 }
67 specs.append(variableName + "='" + Elisp.printed(.list(read), escape: true))
68 } else {
69 specs.append(variableName + "=" + (try Elisp.format([.string("%s"), values.first ?? .nil])))
70 }
71 }
72 guard !name.isEmpty else { return "" }
73 guard !name.contains(where: { "[]():\"".contains($0) }) else { throw Elisp.Unsupported(what: "org-sbe with the reference \(name)") }
74 var value = try sbeReference(name, header: header, arguments: splitArguments(specs.joined(separator: ", ")), text: text)
75 // `org-babel-ref-resolve` gives a symbol's name.
76 if case .symbol(let s) = value, !Elisp.isNil(value) { value = .string(s) }
77 // `:var results=` takes off a first row followed by a rule, as column names.
78 if case .list(let rows) = value, rows.count > 1, rows[0] != .symbol("hline"), rows[1] == .symbol("hline"),
79 !rows.dropFirst(2).contains(.symbol("hline")) {
80 value = rows.count > 2 ? .list(Array(rows.dropFirst(2))) : .nil
81 }
82 let printed = value.string ?? Elisp.printed(value, escape: true)
83 return printed.trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r"))
84 }
85
86 /// `org-babel-ref-resolve` for `name[header](arguments)`: a src block's value, or a named
87 /// table or list.
88 static func sbeReference(_ name: String, header: String, arguments: [String], text: String) throws -> Sexp {
89 let ns = text as NSString
90 let model = DocumentModel(tree: OrgParser.parse(text))
91 let options = Options()
92 // The first `#+NAME:` line with the name outside COMMENTed headings that names an
93 // element: a src block's, or another element's. The keyword's case doesn't matter; the
94 // name's does.
95 let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*(" + NSRegularExpression.escapedPattern(for: name) + ")[ \\t]*$"
96 let found = try NSRegularExpression(pattern: pattern).matches(in: text, range: NSRange(location: 0, length: ns.length))
97 let matches = found.filter { ns.substring(with: $0.range(at: 1)) == name }.map(\.range)
98 let headingStarts = model.headings.map(\.headingRange.lowerBound)
99 func commented(_ location: Int) -> Bool {
100 guard let h = headingStarts.lastIndex(where: { $0 <= location }) else { return false }
101 return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") }
102 }
103 // A keyword followed by a blank line, after any other affiliated keywords, names nothing.
104 func orphaned(_ match: NSRange) -> Bool {
105 var location = NSMaxRange(ns.lineRange(for: match))
106 while location < ns.length {
107 let line = ns.lineRange(for: NSRange(location: location, length: 0))
108 let content = ns.substring(with: line)
109 if content.range(of: "(?i)^[ \\t]*#\\+(name|caption|header|plot|results|attr_[-\\w]+)(\\[.*\\])?:", options: .regularExpression) == nil {
110 return content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
111 }
112 location = NSMaxRange(line)
113 }
114 return true
115 }
116 guard let named = matches.first(where: { !commented($0.location) && !orphaned($0) }) else { throw notFound(name, text: text) }
117 let start = named.location
118 let block = model.srcBlocks.first { block in
119 guard block.name == name, block.range.lowerBound > start else { return false }
120 let between = ns.substring(with: NSRange(location: start, length: block.range.lowerBound - start))
121 return between.split(separator: "\n").allSatisfy { $0.trimmingCharacters(in: .whitespaces).hasPrefix("#+") }
122 }
123 guard let block else {
124 // `resolve` reads the first element with the name in any case, and runs a src block
125 // before it.
126 guard named == found.first?.range, !model.srcBlocks.contains(where: { $0.name == name }) else {
127 throw Elisp.Unsupported(what: "org-sbe with a name used more than once")
128 }
129 do {
130 return try sbeSexp(resolve(name, model: model, text: ns, refs: References(resolved: [:], options: options)))
131 } catch let failure as Failure {
132 throw sbeError(failure, text: text)
133 }
134 }
135 let params: Params
136 do {
137 params = try Params(block: block, model: model, text: ns, extra: [Params.parse(header) + arguments.map { (":var", $0) }])
138 } catch let failure as Failure {
139 throw sbeError(failure, text: text)
140 }
141 if params.single[":cache"] == "yes" { throw Elisp.Unsupported(what: "org-sbe with :cache") }
142 if params.single[":post"] != nil { throw Elisp.Unsupported(what: "org-sbe with :post") }
143 var refs = References(resolved: [:], options: options)
144 refs.visiting = [name]
145 // The blocks its `:var`s refer to run first, as `DocumentSession.runBabel` runs them.
146 while true {
147 switch plan(block, params: params, model: model, text: ns, options: options, location: block.range, name: name, refs: refs, useCache: false) {
148 case .failure(let failure):
149 throw sbeError(failure, text: text)
150 case .success(let job):
151 if job.needsFile { throw Elisp.Unsupported(what: "org-sbe with Lisp that needs the file's name") }
152 if let need = job.needs.first {
153 if need.reference.hasPrefix(thisPrefix) { throw Elisp.Unsupported(what: "org-sbe with :post") }
154 refs.resolved[need.reference] = varValue(need.job.finish, try sbeRun(need.job))
155 continue
156 }
157 // `org-babel-emacs-lisp-lexical`: "yes" and "t" are lexical; other Lisp is read.
158 let lexical: Bool
159 switch params.single[":lexical"] {
160 case "yes", "t": lexical = true
161 case nil, "no", "nil": lexical = false
162 default: throw Elisp.Unsupported(what: "org-sbe with this :lexical")
163 }
164 return try sbeValue(job, lexical: lexical)
165 }
166 }
167 }
168
169 /// A block a reference needs, run as `Babel.evaluateNatively` or in JavaScriptCore.
170 static func sbeRun(_ job: BabelJob) throws -> BabelOutput {
171 if job.lispForm != nil {
172 do {
173 guard let output = try evaluateNatively(job) else { throw Elisp.Unsupported(what: "org-sbe with Lisp only Emacs runs") }
174 return output
175 } catch let Failure.message(message) {
176 // An error in the block.
177 throw Elisp.Signal(message: message)
178 }
179 }
180 guard job.language == "js" || job.language == "javascript" else { throw Elisp.Unsupported(what: "org-sbe with \(job.language) blocks") }
181 guard let output = try? TableBlocks.javaScript?(job), output.status == 0 else { throw Elisp.Unsupported(what: "org-sbe with js blocks") }
182 return output
183 }
184
185 /// The block's value as `org-babel-execute-src-block` returns it.
186 static func sbeValue(_ job: BabelJob, lexical: Bool) throws -> Sexp {
187 let params = job.finish.params
188 if params.contains("file") || job.finish.colnames != nil || job.finish.rownames != nil {
189 throw Elisp.Unsupported(what: "org-sbe with this block's results")
190 }
191 let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
192 || params.contains("pp") || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
193 var result: Sexp
194 if let form = job.lispForm {
195 // `org-babel-execute:emacs-lisp`: dynamic binding unless `:lexical` is yes or t.
196 let lisp = Elisp()
197 lisp.lexical = lexical
198 lisp.syntax = .emacsLisp
199 lisp.standardTime()
200 result = try lisp.eval(try LispReader.readFirst(form).sexp)
201 if Elisp.containsClosure(result) { throw Elisp.Unsupported(what: "org-sbe with a function value") }
202 if scalar {
203 result = .string(params.contains("scalar") || params.contains("verbatim") ? Elisp.printed(result, escape: true) : try Elisp.format([.string("%s"), result]))
204 }
205 } else {
206 // `org-babel-js-read`: a number, a string, or the symbol a quoted word reads as.
207 let raw = rawResult(job.finish, try sbeRun(job))
208 if scalar {
209 result = .string(raw)
210 } else if raw.hasPrefix("(") || raw.hasPrefix("[") || raw.hasPrefix("`") || raw.contains("\\") {
211 throw Elisp.Unsupported(what: "org-sbe with this js value")
212 } else if raw.hasPrefix("'") {
213 guard let m = raw.firstMatch(of: /^'([A-Za-z0-9_-]+)(?:'|\s)/) else { throw Elisp.Unsupported(what: "org-sbe with this js value") }
214 result = try number(String(m.1)).map { try LispReader.readFirst($0).sexp } ?? .symbol(String(m.1))
215 } else if raw.hasPrefix("\""), raw.hasSuffix("\""), raw.count >= 2 {
216 result = .string(String(raw.dropFirst().dropLast()))
217 } else {
218 result = try number(raw).map { try LispReader.readFirst($0).sexp } ?? .string(raw)
219 }
220 }
221 if params.contains("discard") { return .nil }
222 if !job.finish.output, params.contains("vector") || params.contains("table") {
223 if case .list = result {} else if !Elisp.isNil(result) { result = .list([.list([result])]) }
224 }
225 return result
226 }
227
228 /// A named table or list as `org-babel-read-element` reads it.
229 static func sbeSexp(_ value: VarValue) throws -> Sexp {
230 func cell(_ c: Cell) throws -> Sexp {
231 switch c {
232 case .text(let s): return .string(s)
233 case .number(let n): return try LispReader.readFirst(n).sexp
234 }
235 }
236 switch value {
237 case .scalar(let s): return .string(s)
238 case .number(let n): return try LispReader.readFirst(n).sexp
239 case .list(let items): return .list(try items.map(cell))
240 case .table(let rows): return .list(try rows.map { row in try row.map { .list(try $0.map(cell)) } ?? .symbol("hline") })
241 }
242 }
243
244 /// A reference to nothing is an error; to an ID, which only Emacs looks up, unsupported.
245 static func notFound(_ name: String, text: String) -> Error {
246 let pattern = "(?im)^[ \\t]*:(custom_)?id:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
247 if text.range(of: pattern, options: .regularExpression) != nil { return Elisp.Unsupported(what: "org-sbe with an ID reference") }
248 return Elisp.Signal(message: "Reference ‘\(name)’ not found in this buffer")
249 }
250
251 /// What a planning failure is in Emacs: a reference to nothing is an error, the rest
252 /// unsupported here.
253 static func sbeError(_ failure: Failure, text: String) -> Error {
254 guard case .message(let message) = failure, let m = message.firstMatch(of: /^Can't find (.+) for :var\.$/) else {
255 return Elisp.Unsupported(what: "org-sbe with a block orgstar can't run")
256 }
257 return notFound(String(m.1), text: text)
258 }
259}