Sources/OrgCore/Compute/BabelCache.swift
157 lines · 9267 bytes
5 symbols in this file
1import CryptoKit
2import Foundation
3
4extension Babel {
5 // MARK: - Cache
6
7 /// `:cache yes` (`org-babel-execute-src-block`): the block's hash, and whether its results
8 /// already carry it, with their value when it can be read.
9 static func cacheState(language: String, params: Params, tables: Tables, body: String, location: Range<Int>, name: String?,
10 call: Bool, text: NSString, options: Options, model: DocumentModel) throws -> (hash: String, current: Bool, value: VarValue?) {
11 let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= location.lowerBound }
12 // ob-sqlite writes a table to a new temporary file each run, so Emacs's hash never matches.
13 if language == "sqlite", tables.vars.contains(where: { if case .table = $0.1 { true } else { false } }) {
14 throw Failure.message(":cache with a table :var isn't supported for sqlite blocks; nothing was run.")
15 }
16 // The hash is taken outside the shell's own binding of `shell-file-name`, so its
17 // variables are written for the user's shell whatever the block's language.
18 let expanded = try languageExpansion(body, language: language, tables: tables, params: params,
19 properties: { inheritedProperty($0, heading: heading, model: model) })
20 ?? expandedBody(language: language, vars: tables.vars, body: body, shell: options.shell, params: params)
21 let input = try cacheInput(language: language, params: params, tables: tables, expanded: expanded, call: call)
22 let hash = Insecure.SHA1.hash(data: Data(input.utf8)).map { String(format: "%02x", $0) }.joined()
23 guard let line = existingResults(name: name, block: location, text: text), resultsHash(at: line, text: text) == hash else {
24 return (hash, false, nil)
25 }
26 return (hash, true, readResult(after: line, text: text))
27 }
28
29 static func cachedMessage(_ value: VarValue?) -> String {
30 value.map { "Cached: " + lispLiteral($0) } ?? "Cached; nothing was run."
31 }
32
33 /// The body with its variables, as the language's `org-babel-expand-body:` writes it.
34 static func expandedBody(language: String, vars: [(String, VarValue)], body: String, shell: String, params: Params) -> String {
35 if shells.contains(language) {
36 return (shellAssignments(vars, shell: shell, params: params) + [body]).joined(separator: "\n")
37 }
38 if language == "python" {
39 return (vars.map { "\($0.0)=\(pythonLiteral($0.1))" } + [body]).joined(separator: "\n")
40 }
41 if language == "calc" {
42 // `org-babel-expand-body:calc`.
43 return (params.single[":prologue"].map { $0 + "\n" } ?? "") + body + (params.single[":epilogue"].map { "\n" + $0 + "\n" } ?? "")
44 }
45 if language == "sqlite" {
46 // `org-babel-expand-body:sqlite`, with no tables.
47 var expanded = body
48 for (name, value) in vars {
49 switch value {
50 case .scalar(let s): expanded = replacingCaseInsensitively("$" + name, in: expanded, with: s)
51 case .number(let n): expanded = replacingCaseInsensitively("$" + name, in: expanded, with: n)
52 default: break
53 }
54 }
55 return [params.single[":prologue"] ?? "", expanded, params.single[":epilogue"] ?? ""].joined(separator: "\n")
56 }
57 if language == "emacs-lisp" || language == "elisp" {
58 let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
59 return bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(body)\n)"
60 }
61 return body
62 }
63
64 /// What `org-babel-sha1-hash` hashes: the header arguments after `org-babel-process-params`,
65 /// sorted by key and printed with `%S`, then the expanded body.
66 static func cacheInput(language: String, params: Params, tables: Tables, expanded: String, call: Bool) throws -> String {
67 if let key = params.lisp.first(where: { params.evaluated[$0] == nil }) {
68 let setting = ":cache with \(key) \(params.single[key] ?? "")"
69 throw Failure.message(setting + EmacsFallback.wording(" needs Emacs to evaluate the Lisp; nothing was run.", " is Lisp that can't be evaluated here; nothing was run."))
70 }
71 let ignored: Set<String> = ["replace", "silent", "none", "discard", "append", "prepend"]
72 let drawsFile = language == "dot" || language == "plantuml"
73 // `org-babel-default-header-args`, the language's and `org-babel-default-lob-header-args`.
74 var defaults = [":session": "none", ":exports": call || drawsFile ? "results" : "code", ":cache": "no", ":noweb": "no", ":hlines": "no", ":tangle": "no"]
75 if language == "emacs-lisp" || language == "elisp" { defaults[":lexical"] = "no" }
76 var entries: [(key: String, printed: String)] = []
77 for (key, value) in defaults.merging(params.single, uniquingKeysWith: { $1 }) {
78 let printed: String
79 if let evaluated = params.evaluated[key] {
80 printed = Elisp.printed(evaluated, escape: true)
81 } else if value.isEmpty {
82 continue
83 } else if key == ":exports" {
84 printed = lispString(value.split(whereSeparator: \.isWhitespace).map(String.init).filter { !ignored.contains($0) }.sorted().joined(separator: " "))
85 } else if params.single[key] != nil, !params.quoted.contains(key), let n = number(value) {
86 printed = n
87 } else {
88 printed = lispString(value)
89 }
90 entries.append((key, printed))
91 }
92 var words = params.results
93 if drawsFile, !words.contains(where: { Params.resultGroups[0].contains($0) }) { words.append("file") }
94 let kept = words.filter { !ignored.contains($0) }.sorted()
95 if !kept.isEmpty { entries.append((":result-params", "(" + kept.map { lispString($0) }.joined(separator: " ") + ")")) }
96 entries.append((":result-type", words.contains("output") ? "output" : "value"))
97 entries.append((":results", lispString(kept.joined(separator: " "))))
98 if let wrap = params.wrap, !wrap.isEmpty { entries.append((":wrap", lispString(wrap))) }
99 for (key, names) in [(":colname-names", tables.colnames), (":rowname-names", tables.rownames)] where !names.isEmpty {
100 entries.append((key, "(" + names.map { "(\($0.name) " + lispLiteral(.list($0.names)).dropFirst() }.joined(separator: " ") + ")"))
101 }
102 for (name, value) in tables.vars {
103 switch value {
104 case .scalar, .number: entries.append((":var", "(\(name) . \(lispLiteral(value)))"))
105 case .list, .table: entries.append((":var", "(\(name) " + lispLiteral(value).dropFirst()))
106 }
107 }
108 let sorted = entries.enumerated().sorted { ($0.element.key, $0.offset) < ($1.element.key, $1.offset) }.map(\.element.printed)
109 return sorted.joined(separator: ":") + "-" + expanded
110 }
111
112 /// `org-babel-read-result` for fixed-width lines, a table or a plain list after the
113 /// `#+RESULTS` line at `line`; nil for anything else.
114 static func readResult(after line: Int, text ns: NSString) -> VarValue? {
115 var location = NSMaxRange(ns.lineRange(for: NSRange(location: line, length: 0)))
116 var lines: [String] = []
117 while location < ns.length {
118 let range = ns.lineRange(for: NSRange(location: location, length: 0))
119 let content = ns.substring(with: range).trimmingCharacters(in: .newlines)
120 if content.trimmingCharacters(in: .whitespaces).isEmpty { break }
121 lines.append(content.trimmingCharacters(in: .whitespaces))
122 location = NSMaxRange(range)
123 }
124 guard let first = lines.first else { return nil }
125 if first == ":" || first.hasPrefix(": ") {
126 var fixed: [String] = []
127 for l in lines {
128 guard l == ":" || l.hasPrefix(": ") else { break }
129 fixed.append(String(l.dropFirst(2)))
130 }
131 let value = fixed.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
132 return number(value).map(VarValue.number) ?? .scalar(value)
133 }
134 if first.hasPrefix("|") {
135 var rows: [[Cell]?] = []
136 for l in lines {
137 guard l.hasPrefix("|") else { break }
138 if l.hasPrefix("|-") {
139 rows.append(nil)
140 continue
141 }
142 let cells = l.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
143 rows.append((l.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell))
144 }
145 return .table(rows)
146 }
147 if first.firstMatch(of: #/^[-+*] /#) != nil {
148 var items: [Cell] = []
149 for l in lines {
150 guard let m = l.firstMatch(of: /^[-+*] (.*)$/) else { return nil }
151 items.append(cell(String(m.1)))
152 }
153 return .list(items)
154 }
155 return nil
156 }
157}