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