Sources/OrgCore/Compute/BabelLanguages.swift
135 lines · 6001 bytes
6 symbols in this file
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 // As `emacs -Q --batch -l` runs `emacsScript`: lexical binding, in `*scratch*`.
96 let lisp = Elisp()
97 lisp.lexical = true
98 lisp.syntax = .emacsLisp
99 lisp.standardTime()
100 let result: Sexp
101 do {
102 result = try lisp.eval(sexp)
103 // Emacs prints closures as `#[ARGS BODY ENV]`.
104 if Elisp.containsClosure(result) { return nil }
105 } catch is Elisp.Unsupported {
106 return nil
107 } catch {
108 throw .message("\(error)")
109 }
110 func cell(_ c: Sexp) -> String { Elisp.printed(c) }
111 func isProper(_ v: Sexp) -> Bool {
112 if case .list = v { return true }
113 return Elisp.isNil(v)
114 }
115 func isAtom(_ v: Sexp) -> Bool {
116 switch v {
117 case .list(let items): items.isEmpty
118 case .dotted: false
119 default: true
120 }
121 }
122 var rows: [Any] = []
123 if case .list(let items) = result, items.allSatisfy({ isAtom($0) || isProper($0) }) {
124 if items.allSatisfy({ $0 == .symbol("hline") || isProper($0) }) {
125 rows = items.map { $0 == .symbol("hline") ? "hline" as Any : ((try? Elisp.elements($0)) ?? []).map(cell) as Any }
126 } else {
127 rows = [items.map(cell)]
128 }
129 }
130 var object: [String: Any] = ["s": Elisp.printed(result), "S": Elisp.printed(result, escape: true), "string": result.string != nil]
131 object["rows"] = rows.isEmpty ? NSNull() : rows
132 guard let data = try? JSONSerialization.data(withJSONObject: object), let json = String(data: data, encoding: .utf8) else { return nil }
133 return BabelOutput(stdout: lisp.standardOutput + json, stderr: lisp.messages)
134 }
135}