Sources/OrgCore/Compute/BabelVars.swift
350 lines · 18465 bytes
1import Foundation
2
3extension Babel {
4 // MARK: - Tables in variables
5
6 /// Variables after `org-babel-disassemble-tables`, with the names taken off their tables.
7 struct Tables {
8 var vars: [(String, VarValue)] = []
9 var colnames: [(name: String, names: [Cell])] = []
10 var rownames: [(name: String, names: [Cell])] = []
11
12 /// `org-babel-pick-name`: a Lisp list given as the header argument, or the last
13 /// variable's names, unless the header argument is absent, whose `nil` selects none.
14 func picked(_ names: [(name: String, names: [Cell])], _ key: String, _ params: Params) -> [String]? {
15 if let list = params.evaluated[key].flatMap(Babel.lispNames) { return list }
16 guard params.single[key] != nil, let last = names.last else { return nil }
17 return last.names.map(Babel.cellText)
18 }
19 }
20
21 /// A Lisp list of strings and numbers, as names.
22 static func lispNames(_ value: Sexp) -> [String]? {
23 guard case .list(let items) = value else { return nil }
24 return try? items.map { item in
25 if let s = item.string { return s }
26 let printed = Elisp.printed(item)
27 guard number(printed) == printed else { throw Failure.message(printed) }
28 return printed
29 }
30 }
31
32 static func cellText(_ c: Cell) -> String {
33 switch c {
34 case .number(let n): n
35 case .text(let s): s
36 }
37 }
38
39 /// `org-babel-disassemble-tables`: a table's header row comes off when `:colnames` asks, or
40 /// by default when only its second row is a rule; its first column with `:rownames`; its
41 /// rules unless `:hlines yes`.
42 static func disassemble(_ vars: [(String, VarValue)], params: Params) throws -> Tables {
43 for key in [":colnames", ":rownames"] where params.lisp.contains(key) && params.evaluated[key].flatMap(lispNames) == nil {
44 throw Failure.message("\(key) \(params.single[key] ?? "") is Lisp that only Emacs can evaluate; nothing was run.")
45 }
46 let colnames = params.single[":colnames"]
47 let rownames = params.single[":rownames"]
48 let hlines = params.single[":hlines"] ?? "no"
49 var tables = Tables()
50 for (name, value) in vars {
51 guard case .table(var rows) = value else {
52 tables.vars.append((name, value))
53 continue
54 }
55 let auto = rows.count > 1 && rows[0] != nil && rows[1] == nil && !rows.dropFirst(2).contains(where: { $0 == nil })
56 if colnames != "no", colnames != nil || auto {
57 while let first = rows.first, first == nil { rows.removeFirst() }
58 if let header = rows.first ?? nil {
59 rows.removeFirst(rows.count > 1 && rows[1] == nil ? 2 : 1)
60 tables.colnames.append((name, header))
61 }
62 }
63 if let rownames, rownames != "no" {
64 let kept = rows.compactMap { $0 }
65 tables.rownames.append((name, kept.map { $0.first ?? .text("") }))
66 rows = kept.map { Array($0.dropFirst()) }
67 }
68 if hlines != "yes" { rows = rows.filter { $0 != nil } }
69 tables.vars.append((name, .table(rows)))
70 }
71 return tables
72 }
73
74 /// `org-babel-reassemble-table` on a result.
75 static func reassemble(_ value: Value, _ finish: BabelJob.Finish) -> Value {
76 guard case .table(var rows) = value else { return value }
77 if let names = finish.rownames, names.count == rows.count {
78 var next = names.makeIterator()
79 rows = rows.map { row in row.map { [next.next() ?? ""] + $0 } }
80 }
81 if let names = finish.colnames, let first = rows.first ?? nil, first.count == names.count {
82 rows = [names, nil] + rows
83 }
84 return .table(rows)
85 }
86
87 /// A `:var` value that is Lisp (`org-babel-read`): evaluated, as a number, string, list or
88 /// table.
89 static func lispValue(_ value: String) throws -> VarValue {
90 let refusal = Failure.message(":var value \(value) is Lisp that only Emacs can evaluate.")
91 guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form), !Elisp.containsClosure(result) else { throw refusal }
92 func cell(_ v: Sexp) throws -> Cell {
93 if let s = v.string { return .text(s) }
94 if let n = number(Elisp.printed(v)), Elisp.printed(v) == n { return .number(n) }
95 throw refusal
96 }
97 if let s = result.string { return .scalar(s) }
98 if case .list(let items) = result, !items.isEmpty {
99 if items.allSatisfy({ if case .list = $0 { return true }; return $0 == .symbol("hline") }) {
100 return .table(try items.map { item in
101 if item == .symbol("hline") { return nil }
102 guard case .list(let cells) = item else { throw refusal }
103 return try cells.map(cell)
104 })
105 }
106 return .list(try items.map(cell))
107 }
108 if case .number(let n) = try? cell(result) { return .number(n) }
109 throw refusal
110 }
111
112 // MARK: - Variables
113
114 /// A referenced block's result as `org-babel-execute-src-block` returns it: with
115 /// `:results file`, the name of `:file`, or without one the result as the program left it.
116 /// `this` gives the value of `*this*`, where `:file` is a link.
117 static func varValue(_ finish: BabelJob.Finish, _ output: BabelOutput, this: Bool = false) -> VarValue {
118 if finish.params.contains("file") {
119 guard let file = finish.file else { return .scalar(rawResult(finish, output)) }
120 if !this { return .scalar(file) }
121 }
122 switch value(finish, output) {
123 case .none: return .scalar("")
124 case .string(let s): return number(s).map(VarValue.number) ?? .scalar(s)
125 case .table(let rows): return .table(rows.map { $0?.map(cell) })
126 }
127 }
128
129 enum VarValue: Equatable, Sendable {
130 case scalar(String)
131 case number(String)
132 /// Rows; nil is a rule (`hline`).
133 case table([[Cell]?])
134 case list([Cell])
135 }
136
137 enum Cell: Equatable, Sendable {
138 case text(String)
139 case number(String)
140 }
141
142 /// `org-babel--string-to-number`, keeping Emacs's printed form.
143 static func number(_ s: String) -> String? {
144 let t = s.trimmingCharacters(in: .whitespaces)
145 guard !t.isEmpty, !t.contains(where: \.isWhitespace), t.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil else { return nil }
146 if t.range(of: "^[-+]?[0-9]+\\.?$", options: .regularExpression) != nil {
147 var digits = t.hasSuffix(".") ? String(t.dropLast()) : t
148 let negative = digits.hasPrefix("-")
149 if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() }
150 digits = String(digits.drop { $0 == "0" })
151 if digits.isEmpty { return "0" }
152 return (negative ? "-" : "") + digits
153 }
154 guard t.range(of: "^[-+]?([0-9]+\\.[0-9]+|[0-9]*\\.[0-9]+|[0-9]+(\\.[0-9]*)?e[-+]?[0-9]+|[0-9]*\\.[0-9]+e[-+]?[0-9]+)$", options: .regularExpression) != nil,
155 let d = Double(t) else { return nil }
156 return emacsFloat(d)
157 }
158
159 /// How Emacs prints a float.
160 static func emacsFloat(_ d: Double) -> String {
161 if d == d.rounded(), abs(d) < 1e16 { return String(format: "%.1f", d) }
162 return "\(d)"
163 }
164
165 static func cell(_ s: String) -> Cell {
166 var t = s
167 if let m = s.firstMatch(of: /^\s*"(.+)"\s*$/) { t = String(m.1) }
168 return number(t).map(Cell.number) ?? .text(t)
169 }
170
171 /// `name` or `name(args)` naming a src block in the file: the block and its call arguments.
172 static func referencedBlock(_ value: String, model: DocumentModel) -> (block: SrcBlockInfo, arguments: String?)? {
173 guard let m = value.firstMatch(of: /^([^\s()\[\]"]+)(?:\((.*)\))?$/),
174 let block = model.srcBlocks.first(where: { $0.name == String(m.1) }) else { return nil }
175 return (block, m.2.map(String.init))
176 }
177
178 /// The blocks the references of `block` run, directly or through theirs: its `:var`,
179 /// `:stdin` and `:post`, and the noweb references that run a block.
180 static func referencedBlocks(_ block: SrcBlockInfo, _ params: Params, model: DocumentModel, text: NSString, seen: inout Set<Int>) -> [SrcBlockInfo] {
181 var found: [SrcBlockInfo] = []
182 var values = params.vars.map(\.value) + [params.single[":stdin"], params.single[":post"]].compactMap { $0 }
183 if nowebEvaluates(params.single[":noweb"]) {
184 var included: Set<Int> = []
185 values += nowebCalls(block, model: model, text: text, seen: &included)
186 }
187 for value in values {
188 guard let (other, arguments) = referencedBlock(value, model: model), seen.insert(other.range.lowerBound).inserted else { continue }
189 found.append(other)
190 let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
191 if let inner = try? Params(block: other, model: model, text: text, extra: extra) {
192 found += referencedBlocks(other, inner, model: model, text: text, seen: &seen)
193 }
194 }
195 return found
196 }
197
198 /// `org-babel-ref-resolve` for literals, named tables and lists in the file, and named src
199 /// blocks, which run first (`Needed`) and give their result.
200 /// `through` names the kind of reference when it leads back to its own block.
201 static func resolve(_ value: String, model: DocumentModel, text: NSString, refs: References, through: String = ":var") throws -> VarValue {
202 if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(Params.unescape(String(value.dropFirst().dropLast()))) }
203 if let n = number(value) { return .number(n) }
204 if let first = value.first, "('`[".contains(first) { return try lispValue(value) }
205 if value == "*this*", let this = refs.this { return this }
206 // A reference that passes `*this*` on has a value for each run `*this*` came from.
207 let key = value.contains("*this*") ? refs.thisKey + value : value
208 if let known = refs.resolved[key] { return known }
209 if let (block, arguments) = referencedBlock(value, model: model), let name = block.name {
210 guard !refs.visiting.contains(name) else { throw Failure.message("\(name) refers to itself through \(through)") }
211 let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
212 var inner = refs
213 inner.visiting.insert(name)
214 var params = try Params(block: block, model: model, text: text, extra: extra)
215 params.evaluateLisp(file: refs.options.file)
216 // A cached block gives its result without running, as `org-babel-execute-src-block` does.
217 var useCache = true
218 if params.single[":cache"] == "yes", let language = block.language {
219 let tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: text, refs: inner)) }, params: params)
220 let body = nowebEvaluates(params.single[":noweb"]) ? try expandNoweb(block, params: params, model: model, text: text, refs: inner) : normalizedBody(block)
221 let state = try cacheState(language: language, params: params, tables: tables, body: body, location: block.range, name: name, call: false, text: text, options: refs.options, model: model)
222 if state.current {
223 if let value = state.value { return value }
224 useCache = false
225 }
226 }
227 switch plan(block, params: params, model: model, text: text,
228 options: refs.options, location: block.range, name: name, refs: inner, useCache: useCache) {
229 case .failure(let failure): throw failure
230 case .success(let job):
231 if let posted = job.finish.post, job.needs.isEmpty { return posted }
232 throw Needed(need: job.needs.first ?? BabelJob.Need(reference: key, job: job))
233 }
234 }
235 if value.contains("(") || value.contains("[") { throw Failure.message("References like \(value) aren't supported yet.") }
236 // A named element: `#+NAME: value` above a table or list.
237 let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$"
238 guard let r = (text as String).range(of: pattern, options: .regularExpression) else {
239 throw Failure.message("Can't find \(value) for :var.")
240 }
241 let start = NSMaxRange(text.lineRange(for: NSRange(r, in: text as String)))
242 var location = start
243 var rows: [[Cell]?] = []
244 var items: [Cell] = []
245 while location < text.length {
246 let lineRange = text.lineRange(for: NSRange(location: location, length: 0))
247 let line = text.substring(with: lineRange).trimmingCharacters(in: .newlines)
248 let trimmed = line.trimmingCharacters(in: .whitespaces)
249 if trimmed.hasPrefix("|") {
250 if trimmed.hasPrefix("|-") {
251 rows.append(nil)
252 location = NSMaxRange(lineRange)
253 continue
254 }
255 let cells = trimmed.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
256 rows.append((trimmed.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell))
257 } else if let m = trimmed.firstMatch(of: /^[-+*] (.*)$/), rows.isEmpty {
258 items.append(cell(String(m.1)))
259 } else if trimmed.hasPrefix("#+") || (!rows.isEmpty || !items.isEmpty) {
260 if rows.isEmpty, items.isEmpty, trimmed.lowercased().hasPrefix("#+begin_src") {
261 throw Failure.message("Using a src block's result in :var isn't supported yet.")
262 }
263 break
264 } else {
265 break
266 }
267 location = NSMaxRange(lineRange)
268 }
269 if !rows.isEmpty { return .table(rows) }
270 if !items.isEmpty { return .list(items) }
271 throw Failure.message("\(value) isn't a table or list.")
272 }
273
274 /// `org-babel-sh-var-to-string`: a table's rows as tab-separated lines, a list's items as
275 /// lines.
276 static func shellString(_ value: VarValue, separator: String? = nil, hline: String? = nil) -> String {
277 switch value {
278 case .scalar(let s), .number(let s): return s
279 case .list(let items): return items.map(cellText).joined(separator: "\n")
280 case .table(let rows): return rows.compactMap { $0?.map(cellText).joined(separator: separator ?? "\t") ?? hline }.joined(separator: "\n")
281 }
282 }
283
284 /// `org-babel-variable-assignments:shell`, by the shell's name: for bash, an array for a
285 /// list and an associative array for a table of two or more columns; `set` for fish; a
286 /// quoted string otherwise.
287 static func shellAssignments(_ vars: [(String, VarValue)], shell: String, params: Params) -> [String] {
288 let separator = params.single[":separator"]
289 let hline = params.single[":hlines"] == "yes" ? params.single[":hline-string"] ?? "hline" : nil
290 func quoted(_ value: VarValue) -> String {
291 "'" + shellString(value, separator: separator, hline: hline).replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
292 }
293 return vars.map { name, value in
294 if shell.hasSuffix("bash") {
295 switch value {
296 case .table(let rows) where (rows.first ?? nil).map({ $0.count >= 2 }) ?? false:
297 let entries = rows.compactMap { $0 }.map { row in
298 "\(name)[\(quoted(.scalar(cellText(row[0]))))]=\(quoted(.list(Array(row.dropFirst()))))"
299 }
300 return (["unset \(name)", "declare -A \(name)"] + entries).joined(separator: "\n")
301 case .table(let rows):
302 let items = rows.map { $0.map { quoted(.list($0)) } ?? quoted(.scalar("hline")) }
303 return "unset \(name)\ndeclare -a \(name)=( \(items.joined(separator: " ")) )"
304 case .list(let items):
305 return "unset \(name)\ndeclare -a \(name)=( \(items.map { quoted(.scalar(cellText($0))) }.joined(separator: " ")) )"
306 case .scalar, .number:
307 break
308 }
309 }
310 return (shell.hasSuffix("fish") ? "set \(name) " : "\(name)=") + quoted(value)
311 }
312 }
313
314 /// `org-babel-python-var-to-python`.
315 static func pythonLiteral(_ value: VarValue) -> String {
316 func cell(_ c: Cell) -> String {
317 switch c {
318 case .number(let n): return n
319 case .text(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
320 }
321 }
322 switch value {
323 case .scalar(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
324 case .number(let n): return n
325 case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]"
326 case .table(let rows): return "[" + rows.map { $0.map { "[" + $0.map(cell).joined(separator: ", ") + "]" } ?? "None" }.joined(separator: ", ") + "]"
327 }
328 }
329
330 /// `prin1` of a string.
331 static func lispString(_ s: String, triple: Bool = false) -> String {
332 let quoted = "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
333 return triple ? "\"\"" + quoted + "\"\"" : quoted
334 }
335
336 static func lispLiteral(_ value: VarValue) -> String {
337 func cell(_ c: Cell) -> String {
338 switch c {
339 case .number(let n): return n
340 case .text(let s): return lispString(s)
341 }
342 }
343 switch value {
344 case .scalar(let s): return lispString(s)
345 case .number(let n): return n
346 case .list(let items): return "(" + items.map(cell).joined(separator: " ") + ")"
347 case .table(let rows): return "(" + rows.map { $0.map { "(" + $0.map(cell).joined(separator: " ") + ")" } ?? "hline" }.joined(separator: " ") + ")"
348 }
349 }
350}