Sources/OrgCore/Compute/BabelScripts.swift

133 lines · 6235 bytes

  1import Foundation
  2
  3// Variables, `:prologue` and `:epilogue` for the interpreted languages (ob-ruby, ob-js, ob-R,
  4// ob-awk, Org 9.8.7), and how ob-ruby and ob-js return a block's value.
  5
  6extension Babel {
  7    /// `org-babel-expand-body:generic`: the prologue, the variables, the body and the epilogue,
  8    /// a line apart.
  9    static func expandGeneric(_ body: String, _ lines: [String], _ params: Params) -> String {
 10        ((params.single[":prologue"].map { [$0] } ?? []) + lines + [body] + (params.single[":epilogue"].map { [$0] } ?? [])).joined(separator: "\n")
 11    }
 12
 13    /// `org-babel-ruby-var-to-ruby`: lists in brackets, a rule `nil`, the rest as `prin1`.
 14    static func rubyLiteral(_ value: VarValue) -> String {
 15        func cell(_ c: Cell) -> String {
 16            switch c {
 17            case .number(let n): n
 18            case .text(let s): lispString(s)
 19            }
 20        }
 21        switch value {
 22        case .scalar(let s): return lispString(s)
 23        case .number(let n): return n
 24        case .list(let items): return "[" + items.map(cell).joined(separator: ", \n") + "]"
 25        case .table(let rows): return "[" + rows.map { $0.map { "[" + $0.map(cell).joined(separator: ", \n") + "]" } ?? "nil" }.joined(separator: ", \n") + "]"
 26        }
 27    }
 28
 29    /// `org-babel-js-var-to-js`: lists in brackets, the rest as `prin1` with newlines as `\n`.
 30    static func jsLiteral(_ value: VarValue) -> String {
 31        func atom(_ printed: String) -> String { printed.replacingOccurrences(of: "\n", with: "\\n") }
 32        func cell(_ c: Cell) -> String {
 33            switch c {
 34            case .number(let n): n
 35            case .text(let s): atom(lispString(s))
 36            }
 37        }
 38        switch value {
 39        case .scalar(let s): return atom(lispString(s))
 40        case .number(let n): return n
 41        case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]"
 42        case .table(let rows): return "[" + rows.map { $0.map { "[" + $0.map(cell).joined(separator: ", ") + "]" } ?? "hline" }.joined(separator: ", ") + "]"
 43        }
 44    }
 45
 46    /// `org-babel-R-assign-elisp`: a table or list read from its TSV text, an integer with `L`,
 47    /// a float or a string as they print. `colnames` are the header row `:colnames` took off,
 48    /// which ob-R puts back.
 49    static func rAssignment(_ name: String, _ value: VarValue, colnames: [Cell]?, colnamesYes: Bool, rownamesYes: Bool) -> String {
 50        // `orgtbl-to-tsv` makes every field a string, which `org-babel-R-quote-tsv-field` quotes.
 51        func field(_ c: Cell) -> String { "\"" + cellText(c).replacingOccurrences(of: "\"", with: "\"\"") + "\"" }
 52        var rows: [[Cell]?]
 53        switch value {
 54        case .scalar(let s): return "\(name) <- \(lispString(s))"
 55        case .number(let n): return "\(name) <- " + (n.contains(where: { ".eE".contains($0) }) ? n : n + "L")
 56        case .list(let items): rows = items.map { [$0] }
 57        case .table(let table): rows = table
 58        }
 59        if let colnames { rows = [colnames, nil] + rows }
 60        let lengths = rows.compactMap { $0?.count }
 61        let tsv = rows.compactMap { $0.map { $0.map(field).joined(separator: "\t") } }.joined(separator: "\n")
 62        let header = (rows.count > 1 && rows[1] == nil) || colnamesYes ? "TRUE" : "FALSE"
 63        let rowNames = rownamesYes ? "1" : "NULL"
 64        let common = """
 65            \(name) <- local({
 66                 con <- textConnection(
 67                   \(lispString(tsv))
 68                 )
 69                 res <- utils::read.table(
 70                   con,
 71                   header    = \(header),
 72                   row.names = \(rowNames),
 73                   sep       = "\\t",
 74                   as.is     = TRUE
 75            """
 76        if lengths.max() == lengths.min() {
 77            return common + "\n     )\n     close(con)\n     res\n   })"
 78        }
 79        return common + ",\n       fill      = TRUE,\n       col.names = paste(\"V\", seq_len(\(lengths.max() ?? 0)), sep =\"\")\n     )\n     close(con)\n     res\n   })"
 80    }
 81
 82    /// `org-babel-ruby-wrapper-method` and `org-babel-ruby-pp-wrapper-method`: the body's
 83    /// value written to the result file.
 84    static func rubyWrapper(_ body: String, pp: Bool) -> String {
 85        pp ? """
 86
 87            require 'pp'
 88            results = (lambda do
 89            \(body)
 90            end).call
 91            File.open('\(resultFileToken)', 'w') do |f|
 92              $stdout = f
 93              pp results
 94            end
 95
 96            """ : """
 97
 98            results = (lambda do
 99            \(body)
100            end).call
101            File.open('\(resultFileToken)', 'w'){ |f| f.write((results.class == String) ? results : results.inspect) }
102
103            """
104    }
105
106    /// `org-babel-js-function-wrapper`: the body's value printed with `util.inspect`.
107    static func jsWrapper(_ body: String) -> String {
108        "require('process').stdout.write(require('util').inspect(function(){\(body)\n}()));"
109    }
110
111    /// `org-babel-awk-command`'s command line: the program in a file, `:cmd-line`, a `-v` for
112    /// each variable, and `:in-file`.
113    static func awkCommand(_ vars: [(String, VarValue)], params: Params) -> String {
114        var parts = ["awk", "-f", "\"$f\""]
115        if let cmdline = params.single[":cmd-line"] { parts.append(cmdline) }
116        parts += vars.map { "-v \($0.0)='\(shellString($0.1))'" }
117        if let file = params.single[":in-file"] { parts.append(file) }
118        return "f=$(mktemp); cat > \"$f\"; " + parts.joined(separator: " ") + " < /dev/null; s=$?; rm -f \"$f\"; exit $s"
119    }
120}
121
122extension Babel {
123    /// `org-babel-js-read`: an array read as a list once its quotes and commas are Lisp's;
124    /// otherwise `org-babel-read`, which takes a quoted word as the symbol it names.
125    static func jsValue(_ raw: String) -> Value {
126        if raw.hasPrefix("["), raw.hasSuffix("]") { return pythonValue(raw, none: "\u{0}") }
127        if raw.hasPrefix("'") {
128            return .string(String(raw.dropFirst().prefix { !$0.isWhitespace && !"()\"';".contains($0) }))
129        }
130        if raw.hasPrefix("\""), raw.hasSuffix("\""), raw.count >= 2 { return .string(String(raw.dropFirst().dropLast())) }
131        return .string(raw)
132    }
133}