Sources/OrgCore/Compute/BabelLanguages.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgCore/Compute/BabelLanguages.swift history · blame · raw

129 lines · 5703 bytes

  1import Foundation
  2
  3extension Babel {
  4    // MARK: - Python
  5
  6    /// Writes the value of `main()` to the result file as org's Python wrapper does: `pprint`
  7    /// for `pp`, `key :: value` items for a dict as a list, dicts as rows for tables,
  8    /// otherwise `str`.
  9    static let pythonFormatter = """
 10    def __orgstar_format(value, path, params):
 11        def rows(v):
 12            if isinstance(v, dict):
 13                return [(k, rows(x)) for k, x in v.items()]
 14            if isinstance(v, (list, tuple)):
 15                return [rows(x) for x in v]
 16            return v
 17        with open(path, 'w') as out:
 18            if 'pp' in params:
 19                import pprint
 20                out.write(pprint.pformat(value))
 21            elif 'list' in params and isinstance(value, dict):
 22                out.write(str(['{} :: {}'.format(k, v) for k, v in value.items()]))
 23            else:
 24                if not set(params) & {'scalar', 'verbatim', 'raw'} and 'table' in params:
 25                    value = rows(value)
 26                out.write(str(value))
 27
 28    """
 29
 30    /// `org-babel-python--shift-right`: four spaces more on every line outside strings.
 31    static func shiftRight(_ body: String) -> String {
 32        var inString: String?
 33        var lines: [String] = []
 34        for line in body.components(separatedBy: "\n") {
 35            lines.append(inString == nil ? "    " + line : line)
 36            var i = line.startIndex
 37            while i < line.endIndex {
 38                if let delimiter = inString {
 39                    if line[i...].hasPrefix(delimiter) {
 40                        inString = nil
 41                        i = line.index(i, offsetBy: 3)
 42                        continue
 43                    }
 44                } else if line[i] == "#" {
 45                    break
 46                } else if line[i...].hasPrefix("\"\"\"") || line[i...].hasPrefix("'''") {
 47                    inString = String(line[i...].prefix(3))
 48                    i = line.index(i, offsetBy: 3)
 49                    continue
 50                } else if line[i] == "\"" || line[i] == "'" {
 51                    let quote = line[i]
 52                    i = line.index(after: i)
 53                    while i < line.endIndex, line[i] != quote {
 54                        if line[i] == "\\" { i = line.index(after: i) }
 55                        if i < line.endIndex { i = line.index(after: i) }
 56                    }
 57                }
 58                if i < line.endIndex { i = line.index(after: i) }
 59            }
 60        }
 61        return lines.joined(separator: "\n")
 62    }
 63
 64    // MARK: - Emacs Lisp
 65
 66    /// Evaluates `form` and prints the result as JSON: its `%s` and `%S` forms, and its rows
 67    /// when it is a table.
 68    static func emacsScript(form: String, params: [String]) -> String {
 69        """
 70        ;;; -*- lexical-binding: t -*-
 71        (require 'cl-lib)
 72        (require 'json)
 73        (let* ((result \(form))
 74               (print-level nil)
 75               (print-length nil)
 76               (cell (lambda (c) (if (stringp c) c (format "%s" c))))
 77               (tabulable (and (proper-list-p result)
 78                               (cl-every (lambda (e) (or (atom e) (proper-list-p e))) result)))
 79               (rows (and tabulable result
 80                          (if (cl-every (lambda (e) (or (eq e 'hline) (listp e))) result)
 81                              (mapcar (lambda (r) (if (eq r 'hline) "hline" (vconcat (mapcar cell r)))) result)
 82                            (list (vconcat (mapcar cell result)))))))
 83          (princ (json-encode `((s . ,(format "%s" result))
 84                                (S . ,(format "%S" result))
 85                                (string . ,(if (stringp result) t :json-false))
 86                                (rows . ,(if rows (vconcat rows) :json-null))))))
 87        """
 88    }
 89
 90    /// An Emacs Lisp job run by `Elisp` instead of Emacs: the output `emacsScript` would print.
 91    /// A Lisp error fails the run, as it does in Emacs; nil when the block uses what `Elisp`
 92    /// doesn't have.
 93    public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? {
 94        guard let form = job.lispForm, let sexp = try? LispReader.readFirst(form).sexp else { return nil }
 95        let lisp = Elisp()
 96        let result: Sexp
 97        do {
 98            result = try lisp.eval(sexp)
 99        } catch is Elisp.Unsupported {
100            return nil
101        } catch {
102            throw .message("\(error)")
103        }
104        func cell(_ c: Sexp) -> String { Elisp.printed(c) }
105        func isProper(_ v: Sexp) -> Bool {
106            if case .list = v { return true }
107            return Elisp.isNil(v)
108        }
109        func isAtom(_ v: Sexp) -> Bool {
110            switch v {
111            case .list(let items): items.isEmpty
112            case .dotted: false
113            default: true
114            }
115        }
116        var rows: [Any] = []
117        if case .list(let items) = result, items.allSatisfy({ isAtom($0) || isProper($0) }) {
118            if items.allSatisfy({ $0 == .symbol("hline") || isProper($0) }) {
119                rows = items.map { $0 == .symbol("hline") ? "hline" as Any : ((try? Elisp.elements($0)) ?? []).map(cell) as Any }
120            } else {
121                rows = [items.map(cell)]
122            }
123        }
124        var object: [String: Any] = ["s": Elisp.printed(result), "S": Elisp.printed(result, escape: true), "string": result.string != nil]
125        object["rows"] = rows.isEmpty ? NSNull() : rows
126        guard let data = try? JSONSerialization.data(withJSONObject: object), let json = String(data: data, encoding: .utf8) else { return nil }
127        return BabelOutput(stdout: lisp.standardOutput + json, stderr: lisp.messages)
128    }
129}