Sources/OrgCore/Compute/BabelVars.swift
334 lines · 17283 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 a `:var` value.
115 static func varValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> VarValue {
116 switch value(finish, output) {
117 case .none: return .scalar("")
118 case .string(let s): return number(s).map(VarValue.number) ?? .scalar(s)
119 case .table(let rows): return .table(rows.map { $0?.map(cell) })
120 }
121 }
122
123 enum VarValue: Equatable, Sendable {
124 case scalar(String)
125 case number(String)
126 /// Rows; nil is a rule (`hline`).
127 case table([[Cell]?])
128 case list([Cell])
129 }
130
131 enum Cell: Equatable, Sendable {
132 case text(String)
133 case number(String)
134 }
135
136 /// `org-babel--string-to-number`, keeping Emacs's printed form.
137 static func number(_ s: String) -> String? {
138 let t = s.trimmingCharacters(in: .whitespaces)
139 guard !t.isEmpty, !t.contains(where: \.isWhitespace), t.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil else { return nil }
140 if t.range(of: "^[-+]?[0-9]+\\.?$", options: .regularExpression) != nil {
141 var digits = t.hasSuffix(".") ? String(t.dropLast()) : t
142 let negative = digits.hasPrefix("-")
143 if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() }
144 digits = String(digits.drop { $0 == "0" })
145 if digits.isEmpty { return "0" }
146 return (negative ? "-" : "") + digits
147 }
148 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,
149 let d = Double(t) else { return nil }
150 return emacsFloat(d)
151 }
152
153 /// How Emacs prints a float.
154 static func emacsFloat(_ d: Double) -> String {
155 if d == d.rounded(), abs(d) < 1e16 { return String(format: "%.1f", d) }
156 return "\(d)"
157 }
158
159 static func cell(_ s: String) -> Cell {
160 var t = s
161 if let m = s.firstMatch(of: /^\s*"(.+)"\s*$/) { t = String(m.1) }
162 return number(t).map(Cell.number) ?? .text(t)
163 }
164
165 /// `name` or `name(args)` naming a src block in the file: the block and its call arguments.
166 static func referencedBlock(_ value: String, model: DocumentModel) -> (block: SrcBlockInfo, arguments: String?)? {
167 guard let m = value.firstMatch(of: /^([^\s()\[\]"]+)(?:\((.*)\))?$/),
168 let block = model.srcBlocks.first(where: { $0.name == String(m.1) }) else { return nil }
169 return (block, m.2.map(String.init))
170 }
171
172 /// The blocks `params`' references run, directly or through theirs.
173 static func referencedBlocks(_ params: Params, model: DocumentModel, text: NSString, seen: Set<String>) -> [SrcBlockInfo] {
174 var found: [SrcBlockInfo] = []
175 var seen = seen
176 for value in params.vars.map(\.value) + [params.single[":stdin"]].compactMap({ $0 }) {
177 guard let (block, arguments) = referencedBlock(value, model: model), let name = block.name, seen.insert(name).inserted else { continue }
178 found.append(block)
179 let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
180 if let inner = try? Params(block: block, model: model, text: text, extra: extra) {
181 found += referencedBlocks(inner, model: model, text: text, seen: seen)
182 }
183 }
184 return found
185 }
186
187 /// `org-babel-ref-resolve` for literals, named tables and lists in the file, and named src
188 /// blocks, which run first (`Needed`) and give their result.
189 static func resolve(_ value: String, model: DocumentModel, text: NSString, refs: References) throws -> VarValue {
190 if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(Params.unescape(String(value.dropFirst().dropLast()))) }
191 if let n = number(value) { return .number(n) }
192 if let first = value.first, "('`[".contains(first) { return try lispValue(value) }
193 if let known = refs.resolved[value] { return known }
194 if let (block, arguments) = referencedBlock(value, model: model), let name = block.name {
195 guard !refs.visiting.contains(name) else { throw Failure.message("\(name) refers to itself through :var") }
196 let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
197 var inner = refs
198 inner.visiting.insert(name)
199 var params = try Params(block: block, model: model, text: text, extra: extra)
200 params.evaluateLisp(file: refs.options.file)
201 // A cached block gives its result without running, as `org-babel-execute-src-block` does.
202 var useCache = true
203 if params.single[":cache"] == "yes", let language = block.language {
204 let tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: text, refs: inner)) }, params: params)
205 let body = nowebEvaluates(params.single[":noweb"]) ? try expandNoweb(block, params: params, model: model, text: text) : normalizedBody(block)
206 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)
207 if state.current {
208 if let value = state.value { return value }
209 useCache = false
210 }
211 }
212 switch plan(block, params: params, model: model, text: text,
213 options: refs.options, location: block.range, name: name, refs: inner, useCache: useCache) {
214 case .failure(let failure): throw failure
215 case .success(let job):
216 throw Needed(need: job.needs.first ?? BabelJob.Need(reference: value, job: job))
217 }
218 }
219 if value.contains("(") || value.contains("[") { throw Failure.message("References like \(value) aren't supported yet.") }
220 // A named element: `#+NAME: value` above a table or list.
221 let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$"
222 guard let r = (text as String).range(of: pattern, options: .regularExpression) else {
223 throw Failure.message("Can't find \(value) for :var.")
224 }
225 let start = NSMaxRange(text.lineRange(for: NSRange(r, in: text as String)))
226 var location = start
227 var rows: [[Cell]?] = []
228 var items: [Cell] = []
229 while location < text.length {
230 let lineRange = text.lineRange(for: NSRange(location: location, length: 0))
231 let line = text.substring(with: lineRange).trimmingCharacters(in: .newlines)
232 let trimmed = line.trimmingCharacters(in: .whitespaces)
233 if trimmed.hasPrefix("|") {
234 if trimmed.hasPrefix("|-") {
235 rows.append(nil)
236 location = NSMaxRange(lineRange)
237 continue
238 }
239 let cells = trimmed.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
240 rows.append((trimmed.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell))
241 } else if let m = trimmed.firstMatch(of: /^[-+*] (.*)$/), rows.isEmpty {
242 items.append(cell(String(m.1)))
243 } else if trimmed.hasPrefix("#+") || (!rows.isEmpty || !items.isEmpty) {
244 if rows.isEmpty, items.isEmpty, trimmed.lowercased().hasPrefix("#+begin_src") {
245 throw Failure.message("Using a src block's result in :var isn't supported yet.")
246 }
247 break
248 } else {
249 break
250 }
251 location = NSMaxRange(lineRange)
252 }
253 if !rows.isEmpty { return .table(rows) }
254 if !items.isEmpty { return .list(items) }
255 throw Failure.message("\(value) isn't a table or list.")
256 }
257
258 /// `org-babel-sh-var-to-string`: a table's rows as tab-separated lines, a list's items as
259 /// lines.
260 static func shellString(_ value: VarValue, separator: String? = nil, hline: String? = nil) -> String {
261 switch value {
262 case .scalar(let s), .number(let s): return s
263 case .list(let items): return items.map(cellText).joined(separator: "\n")
264 case .table(let rows): return rows.compactMap { $0?.map(cellText).joined(separator: separator ?? "\t") ?? hline }.joined(separator: "\n")
265 }
266 }
267
268 /// `org-babel-variable-assignments:shell`, by the shell's name: for bash, an array for a
269 /// list and an associative array for a table of two or more columns; `set` for fish; a
270 /// quoted string otherwise.
271 static func shellAssignments(_ vars: [(String, VarValue)], shell: String, params: Params) -> [String] {
272 let separator = params.single[":separator"]
273 let hline = params.single[":hlines"] == "yes" ? params.single[":hline-string"] ?? "hline" : nil
274 func quoted(_ value: VarValue) -> String {
275 "'" + shellString(value, separator: separator, hline: hline).replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
276 }
277 return vars.map { name, value in
278 if shell.hasSuffix("bash") {
279 switch value {
280 case .table(let rows) where (rows.first ?? nil).map({ $0.count >= 2 }) ?? false:
281 let entries = rows.compactMap { $0 }.map { row in
282 "\(name)[\(quoted(.scalar(cellText(row[0]))))]=\(quoted(.list(Array(row.dropFirst()))))"
283 }
284 return (["unset \(name)", "declare -A \(name)"] + entries).joined(separator: "\n")
285 case .table(let rows):
286 let items = rows.map { $0.map { quoted(.list($0)) } ?? quoted(.scalar("hline")) }
287 return "unset \(name)\ndeclare -a \(name)=( \(items.joined(separator: " ")) )"
288 case .list(let items):
289 return "unset \(name)\ndeclare -a \(name)=( \(items.map { quoted(.scalar(cellText($0))) }.joined(separator: " ")) )"
290 case .scalar, .number:
291 break
292 }
293 }
294 return (shell.hasSuffix("fish") ? "set \(name) " : "\(name)=") + quoted(value)
295 }
296 }
297
298 /// `org-babel-python-var-to-python`.
299 static func pythonLiteral(_ value: VarValue) -> String {
300 func cell(_ c: Cell) -> String {
301 switch c {
302 case .number(let n): return n
303 case .text(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
304 }
305 }
306 switch value {
307 case .scalar(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
308 case .number(let n): return n
309 case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]"
310 case .table(let rows): return "[" + rows.map { $0.map { "[" + $0.map(cell).joined(separator: ", ") + "]" } ?? "None" }.joined(separator: ", ") + "]"
311 }
312 }
313
314 /// `prin1` of a string.
315 static func lispString(_ s: String, triple: Bool = false) -> String {
316 let quoted = "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
317 return triple ? "\"\"" + quoted + "\"\"" : quoted
318 }
319
320 static func lispLiteral(_ value: VarValue) -> String {
321 func cell(_ c: Cell) -> String {
322 switch c {
323 case .number(let n): return n
324 case .text(let s): return lispString(s)
325 }
326 }
327 switch value {
328 case .scalar(let s): return lispString(s)
329 case .number(let n): return n
330 case .list(let items): return "(" + items.map(cell).joined(separator: " ") + ")"
331 case .table(let rows): return "(" + rows.map { $0.map { "(" + $0.map(cell).joined(separator: " ") + ")" } ?? "hline" }.joined(separator: " ") + ")"
332 }
333 }
334}