Sources/OrgCore/Compute/BabelCache.swift
136 lines · 7964 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 throw Failure.message(":cache with \(key) \(params.single[key] ?? "") needs Emacs to evaluate the Lisp; nothing was run.")
49 }
50 let ignored: Set<String> = ["replace", "silent", "none", "discard", "append", "prepend"]
51 let drawsFile = language == "dot" || language == "plantuml"
52 // `org-babel-default-header-args`, the language's and `org-babel-default-lob-header-args`.
53 var defaults = [":session": "none", ":exports": call || drawsFile ? "results" : "code", ":cache": "no", ":noweb": "no", ":hlines": "no", ":tangle": "no"]
54 if language == "emacs-lisp" || language == "elisp" { defaults[":lexical"] = "no" }
55 var entries: [(key: String, printed: String)] = []
56 for (key, value) in defaults.merging(params.single, uniquingKeysWith: { $1 }) {
57 let printed: String
58 if let evaluated = params.evaluated[key] {
59 printed = Elisp.printed(evaluated, escape: true)
60 } else if value.isEmpty {
61 continue
62 } else if key == ":exports" {
63 printed = lispString(value.split(whereSeparator: \.isWhitespace).map(String.init).filter { !ignored.contains($0) }.sorted().joined(separator: " "))
64 } else if params.single[key] != nil, !params.quoted.contains(key), let n = number(value) {
65 printed = n
66 } else {
67 printed = lispString(value)
68 }
69 entries.append((key, printed))
70 }
71 var words = params.results
72 if drawsFile, !words.contains(where: { Params.resultGroups[0].contains($0) }) { words.append("file") }
73 let kept = words.filter { !ignored.contains($0) }.sorted()
74 if !kept.isEmpty { entries.append((":result-params", "(" + kept.map { lispString($0) }.joined(separator: " ") + ")")) }
75 entries.append((":result-type", words.contains("output") ? "output" : "value"))
76 entries.append((":results", lispString(kept.joined(separator: " "))))
77 if let wrap = params.wrap, !wrap.isEmpty { entries.append((":wrap", lispString(wrap))) }
78 for (key, names) in [(":colname-names", tables.colnames), (":rowname-names", tables.rownames)] where !names.isEmpty {
79 entries.append((key, "(" + names.map { "(\($0.name) " + lispLiteral(.list($0.names)).dropFirst() }.joined(separator: " ") + ")"))
80 }
81 for (name, value) in tables.vars {
82 switch value {
83 case .scalar, .number: entries.append((":var", "(\(name) . \(lispLiteral(value)))"))
84 case .list, .table: entries.append((":var", "(\(name) " + lispLiteral(value).dropFirst()))
85 }
86 }
87 let sorted = entries.enumerated().sorted { ($0.element.key, $0.offset) < ($1.element.key, $1.offset) }.map(\.element.printed)
88 return sorted.joined(separator: ":") + "-" + expanded
89 }
90
91 /// `org-babel-read-result` for fixed-width lines, a table or a plain list after the
92 /// `#+RESULTS` line at `line`; nil for anything else.
93 static func readResult(after line: Int, text ns: NSString) -> VarValue? {
94 var location = NSMaxRange(ns.lineRange(for: NSRange(location: line, length: 0)))
95 var lines: [String] = []
96 while location < ns.length {
97 let range = ns.lineRange(for: NSRange(location: location, length: 0))
98 let content = ns.substring(with: range).trimmingCharacters(in: .newlines)
99 if content.trimmingCharacters(in: .whitespaces).isEmpty { break }
100 lines.append(content.trimmingCharacters(in: .whitespaces))
101 location = NSMaxRange(range)
102 }
103 guard let first = lines.first else { return nil }
104 if first == ":" || first.hasPrefix(": ") {
105 var fixed: [String] = []
106 for l in lines {
107 guard l == ":" || l.hasPrefix(": ") else { break }
108 fixed.append(String(l.dropFirst(2)))
109 }
110 let value = fixed.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
111 return number(value).map(VarValue.number) ?? .scalar(value)
112 }
113 if first.hasPrefix("|") {
114 var rows: [[Cell]?] = []
115 for l in lines {
116 guard l.hasPrefix("|") else { break }
117 if l.hasPrefix("|-") {
118 rows.append(nil)
119 continue
120 }
121 let cells = l.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
122 rows.append((l.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell))
123 }
124 return .table(rows)
125 }
126 if first.firstMatch(of: #/^[-+*] /#) != nil {
127 var items: [Cell] = []
128 for l in lines {
129 guard let m = l.firstMatch(of: /^[-+*] (.*)$/) else { return nil }
130 items.append(cell(String(m.1)))
131 }
132 return .list(items)
133 }
134 return nil
135 }
136}