Commit 57be8cb98f

57be8cb98f4ab4e40df93ff0c54d593b3b0d6f78

parent: 0aba84182e

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 23:36 UTC

Run calc and sqlite blocks in-process

Layout: unified · split

Sources/OrgApp/DocumentSession.swift +4
@@ -929,6 +929,10 @@ public final class DocumentSession {
929 #if canImport(JavaScriptCore) 929 #if canImport(JavaScriptCore)
930 if let output = try await JavaScriptBlocks.run(job, directory: directory) { return output } 930 if let output = try await JavaScriptBlocks.run(job, directory: directory) { return output }
931 #endif 931 #endif
932 if job.calc != nil { return try TableReason.calcBlock(job) }
933 #if canImport(SQLite3)
934 if let output = try SQLiteBlocks.run(job, directory: directory) { return output }
935 #endif
932 guard let output = try Babel.evaluateNatively(job) else { 936 guard let output = try Babel.evaluateNatively(job) else {
933 #if os(macOS) 937 #if os(macOS)
934 throw Babel.Failure.message(job.lispForm == nil 938 throw Babel.Failure.message(job.lispForm == nil
Sources/OrgApp/SQLiteBlocks.swift added +544
@@ -0,0 +1,544 @@
1#if canImport(SQLite3)
2import Foundation
3import OrgCore
4import SQLite3
5
6/// sqlite blocks with the SQLite library, as `sqlite3` (macOS's, 3.54.0) runs them for ob-sqlite,
7/// for builds that can't start it. The command-line options ob-sqlite writes and the dot-commands
8/// `.headers`, `.mode`, `.separator`, `.nullvalue` and `.import` into an existing table are
9/// emulated in the list, csv, column, html and line modes. Anything else, and values whose text
10/// `sqlite3` would escape or lay out by display width, is refused rather than shown differently.
11public enum SQLiteBlocks {
12 /// Runs `job` when it is an sqlite block, in `directory` or its `:dir`; nil for other jobs.
13 public static func run(_ job: BabelJob, directory: URL) throws -> BabelOutput? {
14 guard job.language == "sqlite", let command = job.sqlite else { return nil }
15 let folder = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
16 guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") }
17 do {
18 guard let arguments = command.arguments else { throw Refusal(.shell) }
19 var shell = try Shell(arguments: arguments)
20 var input = job.input
21 var temporary: URL?
22 if !job.dataFiles.isEmpty {
23 let files = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-sqlite-\(UUID().uuidString)")
24 try FileManager.default.createDirectory(at: files, withIntermediateDirectories: true)
25 temporary = files
26 for (token, contents) in job.dataFiles {
27 let file = files.appendingPathComponent("sql-data-\(token.filter(\.isNumber))")
28 try contents.write(to: file, atomically: true, encoding: .utf8)
29 input = input.replacingOccurrences(of: token, with: file.path)
30 }
31 }
32 defer { if let temporary { try? FileManager.default.removeItem(at: temporary) } }
33 return try shell.run(input, folder: folder)
34 } catch let refusal as Refusal {
35 throw Babel.Failure.message(refusal.message)
36 }
37 }
38
39 /// Why a block can't run as `sqlite3` would run it.
40 struct Refusal: Error, Equatable {
41 enum Reason: Equatable {
42 case shell, dotCommand(String), blob, control, width, explain, newTable, importRows, encoding
43 }
44 let reason: Reason
45 /// Statements before the refused one ran.
46 var partly = false
47 init(_ reason: Reason, partly: Bool = false) { (self.reason, self.partly) = (reason, partly) }
48
49 var message: String {
50 let what: String
51 switch reason {
52 case .shell: what = String(localized: "header arguments with shell syntax", comment: "Why an sqlite block can't run here")
53 case .dotCommand(let name): what = String(localized: "the dot-command \(name)", comment: "Why an sqlite block can't run here")
54 case .blob: what = String(localized: "BLOB values", comment: "Why an sqlite block can't run here")
55 case .control: what = String(localized: "control characters in values", comment: "Why an sqlite block can't run here")
56 case .width: what = String(localized: "text other than plain ASCII in column or line mode", comment: "Why an sqlite block can't run here")
57 case .explain: what = String(localized: "EXPLAIN statements", comment: "Why an sqlite block can't run here")
58 case .newTable: what = String(localized: ".import into a table that doesn't exist yet", comment: "Why an sqlite block can't run here")
59 case .importRows: what = String(localized: ".import of rows that don't fit the table", comment: "Why an sqlite block can't run here")
60 case .encoding: what = String(localized: "text that isn't UTF-8", comment: "Why an sqlite block can't run here")
61 }
62 return partly
63 ? String(localized: "This sqlite block can't run here: \(what). The statements before it ran.", comment: "An sqlite block refused partway")
64 : String(localized: "This sqlite block can't run here: \(what).", comment: "An sqlite block refused before it ran")
65 }
66 }
67
68 /// `sqlite3` reading the input as a script.
69 struct Shell {
70 enum Mode: String { case list, csv, column, html, line }
71 var mode = Mode.list
72 var header = false
73 /// Set by `.headers`, which outlasts a change of mode; the command-line options don't.
74 var headerFlag: Bool?
75 var separator = "|"
76 var rowSeparator = "\n"
77 var nullValue = ""
78 var echo = false
79 var bail = false
80 var readonly = false
81 var database: String?
82
83 init(arguments: [String]) throws {
84 var i = 0
85 while i < arguments.count {
86 let argument = arguments[i]
87 switch argument {
88 case "-header": header = true
89 case "-noheader": header = false
90 case "-separator", "-nullvalue":
91 guard i + 1 < arguments.count else { throw Refusal(.shell) }
92 i += 1
93 if argument == "-separator" { separator = arguments[i] } else { nullValue = arguments[i] }
94 case "-echo": echo = true
95 case "-bail": bail = true
96 case "-readonly": readonly = true
97 case "-csv", "-list", "-column", "-html", "-line": change(to: Mode(rawValue: String(argument.dropFirst()))!)
98 default:
99 guard !argument.hasPrefix("-"), database == nil else { throw Refusal(.shell) }
100 database = argument
101 }
102 i += 1
103 }
104 }
105
106 mutating func change(to new: Mode) {
107 mode = new
108 separator = ["csv": ",", "list": "|", "line": ": "][new.rawValue] ?? ""
109 rowSeparator = new == .csv ? "\r\n" : "\n"
110 nullValue = ""
111 header = headerFlag ?? (new == .column || new == .html)
112 }
113
114 /// What `process_input` reads: dot-commands, lines it only echoes, and SQL.
115 enum Item {
116 case echo(String)
117 case dot(String, [String])
118 case sql(String, line: Int)
119 }
120
121 static func isSpace(_ c: UInt8) -> Bool { c == 32 || (9...13).contains(c) }
122
123 /// `line_is_all_whitespace`: spaces and SQL comments.
124 static func isAllWhitespace(_ line: String) -> Bool {
125 let z = Array(line.utf8)
126 var i = 0
127 while i < z.count {
128 if isSpace(z[i]) { i += 1; continue }
129 if z[i] == UInt8(ascii: "/"), i + 1 < z.count, z[i + 1] == UInt8(ascii: "*") {
130 i += 2
131 while i < z.count, !(z[i] == UInt8(ascii: "*") && i + 1 < z.count && z[i + 1] == UInt8(ascii: "/")) { i += 1 }
132 if i >= z.count { return false }
133 i += 2
134 continue
135 }
136 if z[i] == UInt8(ascii: "-"), i + 1 < z.count, z[i + 1] == UInt8(ascii: "-") {
137 while i < z.count, z[i] != UInt8(ascii: "\n") { i += 1 }
138 if i >= z.count { return true }
139 continue
140 }
141 return false
142 }
143 return true
144 }
145
146 static func items(_ input: String) throws -> [Item] {
147 var lines = input.components(separatedBy: "\n")
148 if lines.last == "" { lines.removeLast() }
149 var items: [Item] = []
150 var sql = ""
151 var start = 0
152 for (n, line) in lines.enumerated() {
153 if sql.isEmpty, isAllWhitespace(line) {
154 items.append(.echo(line))
155 continue
156 }
157 if sql.isEmpty, line.hasPrefix(".") || line.hasPrefix("#") {
158 items.append(line.hasPrefix(".") ? .dot(line, try dotArguments(line)) : .echo(line))
159 continue
160 }
161 if sql.isEmpty {
162 sql = String(decoding: line.utf8.drop(while: isSpace), as: UTF8.self)
163 start = n + 1
164 } else {
165 sql += "\n" + line
166 }
167 if line.contains(";"), sqlite3_complete(sql) != 0 {
168 items.append(.sql(sql, line: start))
169 sql = ""
170 } else if !sql.isEmpty, isAllWhitespace(sql) {
171 items.append(.echo(sql))
172 sql = ""
173 }
174 }
175 if !sql.isEmpty { items.append(.sql(sql, line: start)) }
176 return items
177 }
178
179 /// A dot-command's words, refused unless it is one of those emulated, written plainly.
180 static func dotArguments(_ line: String) throws -> [String] {
181 let words = line.dropFirst().split(whereSeparator: { $0 == " " || $0 == "\t" }).map(String.init)
182 let name = words.first ?? ""
183 let refusal = Refusal(.dotCommand("." + name))
184 guard !line.contains(where: { "\"'\\\r;".contains($0) }) else { throw refusal }
185 switch name {
186 case "header", "headers":
187 guard words.count == 2, ["on", "off", "yes", "no", "1", "0", "true", "false"].contains(words[1]) else { throw refusal }
188 case "mode":
189 guard words.count == 2, Mode(rawValue: words[1]) != nil else { throw refusal }
190 case "separator", "nullvalue":
191 guard words.count == 2 else { throw refusal }
192 case "import":
193 let rest = words.dropFirst().filter { $0 != "--csv" && $0 != "-csv" }
194 guard rest.count == 2, !rest[rest.startIndex].hasPrefix("-"), !rest[rest.startIndex].hasPrefix("|"),
195 !rest[rest.startIndex].hasPrefix("<<"), !rest.last!.hasPrefix("-"), !rest.last!.contains(".") else { throw refusal }
196 default:
197 throw refusal
198 }
199 return words
200 }
201
202 mutating func run(_ input: String, folder: URL) throws -> BabelOutput {
203 let items = try Self.items(input)
204 var out = Data()
205 var err = ""
206 func write(_ s: String) { out.append(contentsOf: Array(s.utf8)) }
207 var db: OpaquePointer?
208 let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
209 let path = database.map { URL(fileURLWithPath: $0, relativeTo: folder).standardizedFileURL.path } ?? ":memory:"
210 defer { sqlite3_close(db) }
211 if sqlite3_open_v2(path, &db, flags, nil) != SQLITE_OK {
212 let reason = db.map { String(cString: sqlite3_errmsg($0)) } ?? "out of memory"
213 if Sandbox.isActive || !Self.onMac {
214 throw Babel.Failure.message(String(localized: "Can't open the database \(database ?? ""): \(reason). orgstar can open files only in the folders it has access to.", comment: "An sqlite block's database that can't be opened"))
215 }
216 return BabelOutput(stdout: "", stderr: "Error: unable to open database \"\(database ?? "")\": \(reason)\n", status: 1)
217 }
218 var errors = 0
219 var ran = false
220 for item in items {
221 if errors > 0, bail { break }
222 switch item {
223 case .echo(let line):
224 if echo { write(line + "\n") }
225 case .dot(let line, let words):
226 if echo { write(line + "\n") }
227 do {
228 if try dot(words, db: db!, error: &err) { errors += 1 }
229 } catch var refusal as Refusal {
230 refusal.partly = ran
231 throw refusal
232 }
233 ran = true
234 case .sql(let sql, let line):
235 if echo { write(sql + "\n") }
236 do {
237 if try execute(sql, line: line, db: db!, write: write, error: &err) { errors += 1 }
238 } catch var refusal as Refusal {
239 refusal.partly = refusal.partly || ran
240 throw refusal
241 }
242 ran = true
243 }
244 }
245 return BabelOutput(stdout: String(decoding: out, as: UTF8.self), stderr: err, status: errors > 0 ? 1 : 0)
246 }
247
248 static var onMac: Bool {
249 #if os(macOS)
250 true
251 #else
252 false
253 #endif
254 }
255
256 /// A dot-command; true when it failed.
257 mutating func dot(_ words: [String], db: OpaquePointer, error: inout String) throws -> Bool {
258 switch words[0] {
259 case "header", "headers":
260 headerFlag = ["on", "yes", "1", "true"].contains(words[1])
261 header = headerFlag!
262 case "mode":
263 change(to: Mode(rawValue: words[1])!)
264 case "separator":
265 separator = words[1]
266 case "nullvalue":
267 nullValue = words[1]
268 default:
269 return try importFile(words, db: db, error: &error)
270 }
271 return false
272 }
273
274 /// `.import FILE TABLE` into a table that exists, as CSV.
275 func importFile(_ words: [String], db: OpaquePointer, error: inout String) throws -> Bool {
276 let rest = words.dropFirst().filter { $0 != "--csv" && $0 != "-csv" }
277 let csvOption = words.count != rest.count + 1
278 let (file, table) = (rest[rest.startIndex], rest[rest.startIndex + 1])
279 var columnSeparator = csvOption ? UInt8(ascii: ",") : (separator.utf8.first ?? UInt8(ascii: ","))
280 if columnSeparator >= 0x80 { columnSeparator = UInt8(ascii: ",") }
281 var statement: OpaquePointer?
282 let quoted = "\"" + table.replacingOccurrences(of: "\"", with: "\"\"") + "\""
283 guard sqlite3_prepare_v2(db, "SELECT count(*) FROM pragma_table_info('\(table.replacingOccurrences(of: "'", with: "''"))')", -1, &statement, nil) == SQLITE_OK else {
284 throw Refusal(.newTable)
285 }
286 let columns = sqlite3_step(statement) == SQLITE_ROW ? Int(sqlite3_column_int(statement, 0)) : 0
287 sqlite3_finalize(statement)
288 guard columns > 0 else { throw Refusal(.newTable) }
289 guard let data = FileManager.default.contents(atPath: file) else {
290 error += "Error: cannot open \"\(file)\"\n"
291 return true
292 }
293 let rows = try Self.csvRows(Array(data), separator: columnSeparator)
294 guard rows.allSatisfy({ $0.count == columns }) else { throw Refusal(.importRows) }
295 let insert = "INSERT INTO \(quoted) VALUES(" + Array(repeating: "?", count: columns).joined(separator: ",") + ")"
296 guard sqlite3_prepare_v2(db, insert, -1, &statement, nil) == SQLITE_OK else { throw Refusal(.newTable) }
297 defer { sqlite3_finalize(statement) }
298 let commit = sqlite3_get_autocommit(db) != 0
299 if commit { sqlite3_exec(db, "BEGIN", nil, nil, nil) }
300 var failed = false
301 let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
302 for (n, row) in rows.enumerated() {
303 for (i, field) in row.enumerated() { sqlite3_bind_text(statement, Int32(i + 1), field, -1, transient) }
304 sqlite3_step(statement)
305 if sqlite3_reset(statement) != SQLITE_OK {
306 error += "\(file):\(n + 1): INSERT failed: \(String(cString: sqlite3_errmsg(db)))\n"
307 failed = true
308 if bail { break }
309 }
310 }
311 if commit { sqlite3_exec(db, "COMMIT", nil, nil, nil) }
312 return failed
313 }
314
315 /// `csv_read_one_field` over a file of well-formed CSV: rows of fields.
316 static func csvRows(_ bytes: [UInt8], separator: UInt8) throws -> [[String]] {
317 let quote = UInt8(ascii: "\""), newline = UInt8(ascii: "\n"), cr = UInt8(ascii: "\r")
318 var rows: [[String]] = []
319 var row: [String] = []
320 var i = 0
321 // Any quote must open a field and close it; else the reader's warnings and
322 // recovery would apply.
323 while i < bytes.count {
324 var field: [UInt8] = []
325 if bytes[i] == quote {
326 i += 1
327 while true {
328 guard i < bytes.count else { throw Refusal(.importRows) }
329 if bytes[i] == quote {
330 if i + 1 < bytes.count, bytes[i + 1] == quote {
331 field.append(quote)
332 i += 2
333 continue
334 }
335 i += 1
336 break
337 }
338 field.append(bytes[i])
339 i += 1
340 }
341 guard i == bytes.count || bytes[i] == separator || bytes[i] == newline else { throw Refusal(.importRows) }
342 } else {
343 while i < bytes.count, bytes[i] != separator, bytes[i] != newline {
344 guard bytes[i] != quote else { throw Refusal(.importRows) }
345 field.append(bytes[i])
346 i += 1
347 }
348 if i < bytes.count, bytes[i] == newline, field.last == cr { field.removeLast() }
349 }
350 guard let text = String(bytes: field, encoding: .utf8) else { throw Refusal(.encoding) }
351 row.append(text)
352 if i < bytes.count, bytes[i] == separator {
353 i += 1
354 if i == bytes.count { row.append("") }
355 } else {
356 rows.append(row)
357 row = []
358 if i < bytes.count { i += 1 }
359 }
360 }
361 if !row.isEmpty { rows.append(row) }
362 // The first-row byte-order mark the reader skips.
363 if let first = rows.first?.first, first.hasPrefix("\u{FEFF}") { throw Refusal(.encoding) }
364 return rows
365 }
366
367 /// `shell_exec` of one group of statements; true when one failed.
368 func execute(_ sql: String, line: Int, db: OpaquePointer, write: (String) -> Void, error: inout String) throws -> Bool {
369 var bytes = Array(sql.utf8CString)
370 return try bytes.withUnsafeMutableBufferPointer { buffer -> Bool in
371 var next: UnsafePointer<CChar>? = UnsafePointer(buffer.baseAddress!)
372 while let start = next, start.pointee != 0 {
373 var statement: OpaquePointer?
374 var tail: UnsafePointer<CChar>?
375 if sqlite3_prepare_v2(db, start, -1, &statement, &tail) != SQLITE_OK {
376 error += "Parse error near line \(line): \(String(cString: sqlite3_errmsg(db)))\n"
377 return true
378 }
379 next = tail
380 while let rest = next, rest.pointee != 0, Self.isSpace(UInt8(bitPattern: rest.pointee)) { next = rest + 1 }
381 guard let statement else { continue }
382 defer { sqlite3_finalize(statement) }
383 if sqlite3_stmt_isexplain(statement) != 0 { throw Refusal(.explain) }
384 let failed = try output(statement, db: db, write: write)
385 if failed {
386 error += "Error near line \(line): \(String(cString: sqlite3_errmsg(db)))\n"
387 return true
388 }
389 }
390 return false
391 }
392 }
393
394 /// A value as text, with its type; nil text for NULL.
395 struct Cell {
396 let text: String?
397 let numeric: Bool
398 }
399
400 func cell(_ statement: OpaquePointer, _ i: Int32) throws -> Cell {
401 switch sqlite3_column_type(statement, i) {
402 case SQLITE_NULL: return Cell(text: nil, numeric: false)
403 case SQLITE_BLOB: throw Refusal(.blob)
404 case let type:
405 guard let pointer = sqlite3_column_text(statement, i) else { return Cell(text: nil, numeric: false) }
406 let bytes = UnsafeBufferPointer(start: pointer, count: Int(sqlite3_column_bytes(statement, i)))
407 guard let text = String(bytes: bytes, encoding: .utf8) else { throw Refusal(.encoding) }
408 try Self.check(text)
409 return Cell(text: text, numeric: type == SQLITE_INTEGER || type == SQLITE_FLOAT)
410 }
411 }
412
413 /// Control characters other than tab and newline `sqlite3` escapes.
414 static func check(_ text: String) throws {
415 if text.unicodeScalars.contains(where: { ($0.value < 0x20 && $0 != "\t" && $0 != "\n") || $0.value == 0x7F }) {
416 throw Refusal(.control)
417 }
418 }
419
420 /// Writes the statement's rows in the mode; true when stepping failed.
421 func output(_ statement: OpaquePointer, db: OpaquePointer, write: (String) -> Void) throws -> Bool {
422 let count = sqlite3_column_count(statement)
423 let names = try (0..<count).map { i -> String in
424 let name = sqlite3_column_name(statement, i).map { String(cString: $0) } ?? ""
425 try Self.check(name)
426 return name
427 }
428 var rows: [[Cell]] = []
429 var failed = false
430 var buffered = ""
431 func emit(_ s: String) { if mode == .column { buffered += s } else { write(s) } }
432 while true {
433 let rc = sqlite3_step(statement)
434 if rc == SQLITE_DONE { break }
435 guard rc == SQLITE_ROW else {
436 failed = true
437 break
438 }
439 guard count > 0 else { continue }
440 let row = try (0..<count).map { try cell(statement, $0) }
441 switch mode {
442 case .column:
443 rows.append(row)
444 case .line:
445 let width = try names.map { name -> Int in
446 guard name.allSatisfy({ $0.isASCII }) else { throw Refusal(.width) }
447 return name.utf8.count
448 }.max() ?? 0
449 if !rows.isEmpty { emit("\n") }
450 rows.append([])
451 for (name, value) in zip(names, row) {
452 let pieces = (value.text ?? nullValue).components(separatedBy: "\n")
453 var lines = Array(pieces)
454 // A final newline ends the last line.
455 if lines.count > 1, lines.last == "" { lines.removeLast() }
456 emit(String(repeating: " ", count: width - name.utf8.count) + name + separator + lines[0] + "\n")
457 for more in lines.dropFirst() {
458 emit(String(repeating: " ", count: width + separator.utf8.count) + more + "\n")
459 }
460 }
461 case .html:
462 if rows.isEmpty, header {
463 emit("<TR>\n" + names.map { "<TH>" + Self.html($0) + "\n" }.joined() + "</TR>\n")
464 }
465 rows.append([])
466 emit("<TR>\n" + row.map { "<TD>" + ($0.text.map(Self.html) ?? "null") + "\n" }.joined() + "</TR>\n")
467 case .list, .csv:
468 if rows.isEmpty, header {
469 emit(names.map { mode == .csv ? csv($0) : $0 }.joined(separator: separator) + rowSeparator)
470 }
471 rows.append([])
472 emit(row.map { value in
473 guard let text = value.text else { return nullValue }
474 return mode == .csv && !value.numeric ? csv(text) : text
475 }.joined(separator: separator) + rowSeparator)
476 }
477 }
478 if mode == .column, !rows.isEmpty {
479 try column(names: names, rows: rows, emit: emit)
480 write(buffered)
481 }
482 return failed
483 }
484
485 /// CSV quoting: a field with a control character, space, quote, apostrophe, DEL or byte
486 /// above ASCII, or with the separator, is quoted.
487 func csv(_ text: String) -> String {
488 let special = text.isEmpty || text.utf8.contains { $0 < 0x20 || $0 == 0x20 || $0 == 0x22 || $0 == 0x27 || $0 >= 0x7F }
489 guard special || (!separator.isEmpty && text.contains(separator)) else { return text }
490 return "\"" + text.replacingOccurrences(of: "\"", with: "\"\"") + "\""
491 }
492
493 /// `sqlite3`'s HTML escaping, which writes `>` as `&lt;`.
494 static func html(_ text: String) -> String {
495 var out = ""
496 for c in text.unicodeScalars {
497 switch c {
498 case "<", ">": out += "&lt;"
499 case "&": out += "&amp;"
500 case "\"": out += "&quot;"
501 case "'": out += "&#39;"
502 default: out.unicodeScalars.append(c)
503 }
504 }
505 return out
506 }
507
508 /// Column mode: each column as wide as its widest text, the titles centered over a rule,
509 /// numbers to the right, two spaces between columns, no spaces at the ends of lines.
510 func column(names: [String], rows: [[Cell]], emit: (String) -> Void) throws {
511 func plain(_ s: String) throws -> String {
512 guard s.allSatisfy({ $0.isASCII && $0 != "\t" && $0 != "\n" }) else { throw Refusal(.width) }
513 return s
514 }
515 let texts = try rows.map { try $0.map { try plain($0.text ?? nullValue) } }
516 let titles = try names.map(plain)
517 var widths = Array(repeating: 0, count: names.count)
518 for (i, title) in titles.enumerated() where header { widths[i] = max(widths[i], title.count) }
519 for row in texts { for (i, text) in row.enumerated() { widths[i] = max(widths[i], text.count) } }
520 func line(_ cells: [String], _ align: (Int) -> Character) -> String {
521 var s = ""
522 for (i, text) in cells.enumerated() {
523 let space = widths[i] - text.count
524 switch align(i) {
525 case "c": s += String(repeating: " ", count: space / 2) + text + String(repeating: " ", count: space - space / 2)
526 case "r": s += String(repeating: " ", count: space) + text
527 default: s += text + String(repeating: " ", count: space)
528 }
529 if i < cells.count - 1 { s += " " }
530 }
531 while s.last == " " { s.removeLast() }
532 return s + "\n"
533 }
534 if header {
535 emit(line(titles) { _ in "c" })
536 emit(line(widths.map { String(repeating: "-", count: $0) }) { _ in "l" })
537 }
538 for (row, cells) in zip(texts, rows) {
539 emit(line(row) { cells[$0].numeric ? "r" : "l" })
540 }
541 }
542 }
543}
544#endif
Sources/OrgApp/TableReason.swift +18
@@ -6,6 +6,20 @@ public enum TableReason {
6 /// The reason translated, or as it is when it's one this doesn't know. 6 /// The reason translated, or as it is when it's one this doesn't know.
7 public static func localized(_ reason: String) -> String { translated(reason) ?? reason } 7 public static func localized(_ reason: String) -> String { translated(reason) ?? reason }
8 8
9 /// Why a calc block can't be calculated here, `Calc.Unsupported`'s reason, in the app's language.
10 public static func calcRefusal(_ reason: String) -> String {
11 String(localized: "This calc block can't be calculated here: \(localized(reason)).", comment: "A calc block orgstar can't calculate")
12 }
13
14 /// A calc block's result, or a refusal in the app's language.
15 public static func calcBlock(_ job: BabelJob) throws -> BabelOutput {
16 do {
17 return try Babel.evaluateCalc(job)
18 } catch let refusal as Calc.Unsupported {
19 throw Babel.Failure.message(calcRefusal(refusal.reason))
20 }
21 }
22
9 /// Nil for a reason not known here. 23 /// Nil for a reason not known here.
10 static func translated(_ reason: String) -> String? { 24 static func translated(_ reason: String) -> String? {
11 if reason.hasPrefix("Lisp ") { 25 if reason.hasPrefix("Lisp ") {
@@ -19,6 +33,8 @@ public enum TableReason {
19 if let name = value("variable ") { return String(localized: "variable \(name)", comment: "Why a table needs Emacs: a Calc variable") } 33 if let name = value("variable ") { return String(localized: "variable \(name)", comment: "Why a table needs Emacs: a Calc variable") }
20 if let number = value("number size ") { return String(localized: "number size \(number)", comment: "Why a table needs Emacs: a number too large") } 34 if let number = value("number size ") { return String(localized: "number size \(number)", comment: "Why a table needs Emacs: a number too large") }
21 if let flag = value("format flag ") { return String(localized: "format flag \(flag)", comment: "Why a table needs Emacs: a format specifier flag") } 35 if let flag = value("format flag ") { return String(localized: "format flag \(flag)", comment: "Why a table needs Emacs: a format specifier flag") }
36 if let key = value("stack command ") { return String(localized: "stack command \(key)", comment: "Why a calc block needs Emacs: a key it runs on the stack") }
37 if let name = value("value of :var ") { return String(localized: "value of :var \(name)", comment: "Why a calc block needs Emacs: a variable's value") }
22 return nil 38 return nil
23 } 39 }
24 40
@@ -103,6 +119,7 @@ public enum TableReason {
103 case "constants that refer to themselves": return String(localized: "constants that refer to themselves", comment: comment) 119 case "constants that refer to themselves": return String(localized: "constants that refer to themselves", comment: comment)
104 case "date arithmetic": return String(localized: "date arithmetic", comment: comment) 120 case "date arithmetic": return String(localized: "date arithmetic", comment: comment)
105 case "date syntax": return String(localized: "date syntax", comment: comment) 121 case "date syntax": return String(localized: "date syntax", comment: comment)
122 case "dates in calc blocks": return String(localized: "dates in calc blocks", comment: comment)
106 case "daylight saving time": return String(localized: "daylight saving time", comment: comment) 123 case "daylight saving time": return String(localized: "daylight saving time", comment: comment)
107 case "division by zero": return String(localized: "division by zero", comment: comment) 124 case "division by zero": return String(localized: "division by zero", comment: comment)
108 case "duration size": return String(localized: "duration size", comment: comment) 125 case "duration size": return String(localized: "duration size", comment: comment)
@@ -114,6 +131,7 @@ public enum TableReason {
114 case "logarithm domain": return String(localized: "logarithm domain", comment: comment) 131 case "logarithm domain": return String(localized: "logarithm domain", comment: comment)
115 case "number": return String(localized: "number", comment: comment) 132 case "number": return String(localized: "number", comment: comment)
116 case "number size": return String(localized: "number size", comment: comment) 133 case "number size": return String(localized: "number size", comment: comment)
134 case "numeric :prologue or :epilogue": return String(localized: "numeric :prologue or :epilogue", comment: comment)
117 case "range outside row": return String(localized: "range outside row", comment: comment) 135 case "range outside row": return String(localized: "range outside row", comment: comment)
118 case "reference outside table": return String(localized: "reference outside table", comment: comment) 136 case "reference outside table": return String(localized: "reference outside table", comment: comment)
119 case "remote table name from a range": return String(localized: "remote table name from a range", comment: comment) 137 case "remote table name from a range": return String(localized: "remote table name from a range", comment: comment)
Sources/OrgCore/Commands/Table.swift +2 −1
@@ -131,7 +131,8 @@ extension EmacsBuffer {
131 fixed = cookie.1.first 131 fixed = cookie.1.first
132 } else { 132 } else {
133 nonEmpty += 1 133 nonEmpty += 1
134 if numberRegex.firstMatch(in: cell, range: NSRange(location: 0, length: (cell as NSString).length)) != nil { numbers += 1 } 134 // `$` doesn't match before a CR in Emacs.
135 if !cell.unicodeScalars.contains("\r"), numberRegex.firstMatch(in: cell, range: NSRange(location: 0, length: (cell as NSString).length)) != nil { numbers += 1 }
135 } 136 }
136 } 137 }
137 widths.append(maxWidth) 138 widths.append(maxWidth)
Sources/OrgCore/Compute/Babel.swift +35 −2
@@ -53,6 +53,12 @@ public struct BabelJob: Sendable, Equatable {
53 /// A Lisp header value couldn't be evaluated without the file's path: plan again with 53 /// A Lisp header value couldn't be evaluated without the file's path: plan again with
54 /// `Babel.replan` before running. 54 /// `Babel.replan` before running.
55 public internal(set) var needsFile = false 55 public internal(set) var needsFile = false
56 /// A calc block, for `Babel.evaluateCalc`.
57 public internal(set) var calc: Babel.CalcBlock?
58 /// An sqlite block's `sqlite3` command line, for `SQLiteBlocks`.
59 public internal(set) var sqlite: Babel.SQLiteCommand?
60 /// Files the runner writes, each where its key stands in `input`: `:var` tables as CSV.
61 public internal(set) var dataFiles: [String: String] = [:]
56 62
57 public struct Need: Sendable, Equatable { 63 public struct Need: Sendable, Equatable {
58 /// The `:var` value, `name` or `name(args)`. 64 /// The `:var` value, `name` or `name(args)`.
@@ -64,7 +70,14 @@ public struct BabelJob: Sendable, Equatable {
64 /// `compiled`: C, C++, D, Java, Fortran and Clojure, by `language`. 70 /// `compiled`: C, C++, D, Java, Fortran and Clojure, by `language`.
65 /// `script`: ruby and js, whose value comes back as their `inspect` prints it, from 71 /// `script`: ruby and js, whose value comes back as their `inspect` prints it, from
66 /// the result file for ruby and the output for js. 72 /// the result file for ruby and the output for js.
67 enum Kind: Sendable, Equatable { case shell(valueIsExitStatus: Bool), python, generic, emacsLisp, compiled, script(js: Bool, session: Bool = false) } 73 /// `calc`: the value as JSON, `{"value": …}` or `{"rows": […]}`. `sqlite`: the output of
74 /// `sqlite3`, read as CSV when `csv`, with a rule after the first row when `headers`.
75 enum Kind: Sendable, Equatable {
76 case shell(valueIsExitStatus: Bool), python, generic, emacsLisp, compiled, script(js: Bool, session: Bool = false), calc
77 case sqlite(csv: Bool, headers: Bool)
78
79 var isSQLite: Bool { if case .sqlite = self { true } else { false } }
80 }
68 let kind: Kind 81 let kind: Kind
69 var language = "" 82 var language = ""
70 public internal(set) var params: [String] 83 public internal(set) var params: [String]
@@ -358,7 +371,7 @@ public enum Babel {
358 if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language), !shells.contains(language), !compiled { 371 if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language), !shells.contains(language), !compiled {
359 return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run.")) 372 return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run."))
360 } 373 }
361 let wraps = compiled || shells.contains(language) || ["python", "emacs-lisp", "elisp"].contains(language) || generic[language] != nil 374 let wraps = compiled || shells.contains(language) || ["python", "emacs-lisp", "elisp", "calc", "sqlite"].contains(language) || generic[language] != nil
362 for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil 375 for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil
363 && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) && !(wraps && [":prologue", ":epilogue"].contains(key)) { 376 && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) && !(wraps && [":prologue", ":epilogue"].contains(key)) {
364 return .failure(.message("\(key) isn't supported yet; nothing was run.")) 377 return .failure(.message("\(key) isn't supported yet; nothing was run."))
@@ -517,6 +530,26 @@ public enum Babel {
517 job.lispForm = form 530 job.lispForm = form
518 return .success(job) 531 return .success(job)
519 } 532 }
533 if language == "calc" {
534 do {
535 return .success(try calcJob(body: body, vars: vars, params: params, finish: finishBase(.calc), directory: dir, block: location,
536 blockText: blockText, alwaysAsk: alwaysAsk))
537 } catch let error as Failure {
538 return .failure(error)
539 } catch {
540 return .failure(.message("\(error)"))
541 }
542 }
543 if language == "sqlite" {
544 do {
545 return .success(try sqliteJob(body: body, vars: vars, params: params, finishBase: finishBase, directory: dir, block: location,
546 blockText: blockText, alwaysAsk: alwaysAsk))
547 } catch let error as Failure {
548 return .failure(error)
549 } catch {
550 return .failure(.message("\(error)"))
551 }
552 }
520 if ["dot", "plantuml", "mermaid"].contains(language) { 553 if ["dot", "plantuml", "mermaid"].contains(language) {
521 // ob-dot, ob-plantuml and ob-mermaid: the program draws into `:file`. 554 // ob-dot, ob-plantuml and ob-mermaid: the program draws into `:file`.
522 guard let file else { return .failure(.message("\(language) code blocks need a :file header argument")) } 555 guard let file else { return .failure(.message("\(language) code blocks need a :file header argument")) }
Sources/OrgCore/Compute/BabelCache.swift +20
@@ -9,6 +9,10 @@ extension Babel {
9 static func cacheState(language: String, params: Params, tables: Tables, body: String, location: Range<Int>, name: String?, 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?) { 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 } 11 let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= location.lowerBound }
12 // ob-sqlite writes a table to a new temporary file each run, so Emacs's hash never matches.
13 if language == "sqlite", tables.vars.contains(where: { if case .table = $0.1 { true } else { false } }) {
14 throw Failure.message(":cache with a table :var isn't supported for sqlite blocks; nothing was run.")
15 }
12 // The hash is taken outside the shell's own binding of `shell-file-name`, so its 16 // 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. 17 // 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, 18 let expanded = try languageExpansion(body, language: language, tables: tables, params: params,
@@ -34,6 +38,22 @@ extension Babel {
34 if language == "python" { 38 if language == "python" {
35 return (vars.map { "\($0.0)=\(pythonLiteral($0.1))" } + [body]).joined(separator: "\n") 39 return (vars.map { "\($0.0)=\(pythonLiteral($0.1))" } + [body]).joined(separator: "\n")
36 } 40 }
41 if language == "calc" {
42 // `org-babel-expand-body:calc`.
43 return (params.single[":prologue"].map { $0 + "\n" } ?? "") + body + (params.single[":epilogue"].map { "\n" + $0 + "\n" } ?? "")
44 }
45 if language == "sqlite" {
46 // `org-babel-expand-body:sqlite`, with no tables.
47 var expanded = body
48 for (name, value) in vars {
49 switch value {
50 case .scalar(let s): expanded = replacingCaseInsensitively("$" + name, in: expanded, with: s)
51 case .number(let n): expanded = replacingCaseInsensitively("$" + name, in: expanded, with: n)
52 default: break
53 }
54 }
55 return [params.single[":prologue"] ?? "", expanded, params.single[":epilogue"] ?? ""].joined(separator: "\n")
56 }
37 if language == "emacs-lisp" || language == "elisp" { 57 if language == "emacs-lisp" || language == "elisp" {
38 let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" } 58 let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
39 return bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(body)\n)" 59 return bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(body)\n)"
Sources/OrgCore/Compute/BabelCalc.swift added +254
@@ -0,0 +1,254 @@
1import Foundation
2
3// ob-calc (Org 9.8.7) on `Calc`: each line of the body goes onto a fresh Calc stack, as in a
4// new Emacs, and the value is the top of the stack. Calc's own modes apply, not
5// `org-calc-default-modes`: 12 digits shown in full.
6
7extension Babel {
8 /// A calc block: its lines, trimmed, and its variables as Calc values.
9 public struct CalcBlock: Sendable, Equatable {
10 let lines: [String]
11 let vars: [Variable]
12 /// `org-babel-result-cond` takes the value as a string.
13 let scalar: Bool
14 /// Why the block can't run here, found when it was planned.
15 let refusal: Calc.Unsupported?
16
17 struct Variable: Sendable, Equatable {
18 let name: String
19 let value: Calc.Value
20 }
21 }
22
23 /// `org-babel-execute:calc` with `emacs -Q` modes.
24 static let calcModes: Calc.Modes = {
25 var modes = Calc.Modes()
26 modes.format = .float(0)
27 return modes
28 }()
29
30 /// Plans a calc block: natively through `job.calc`, and in Emacs through `job.input`.
31 static func calcJob(body: String, vars: [(String, VarValue)], params: Params, finish: BabelJob.Finish, directory: String?,
32 block: Range<Int>, blockText: String, alwaysAsk: Bool) throws -> BabelJob {
33 let prologue = params.single[":prologue"], epilogue = params.single[":epilogue"]
34 let expanded = (prologue.map { $0 + "\n" } ?? "") + body + (epilogue.map { "\n" + $0 + "\n" } ?? "")
35 var job = BabelJob(language: "calc", runner: .emacs, input: calcScript(body: body, vars: vars, params: params, finish: finish),
36 directory: directory, block: block, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish)
37 let lines = expanded.components(separatedBy: CharacterSet(charactersIn: "\n\r")).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
38 var values: [CalcBlock.Variable] = []
39 var refusal: Calc.Unsupported?
40 do {
41 // `org-babel-read` makes a number of an unquoted `:prologue 2`, which `concat` refuses.
42 if [":prologue", ":epilogue"].contains(where: { key in params.single[key].map { !params.quoted.contains(key) && number($0) != nil } ?? false }) {
43 throw Calc.Unsupported("numeric :prologue or :epilogue")
44 }
45 values = try vars.map { try CalcBlock.Variable(name: $0.0, value: calcValue($0.1, name: $0.0)) }
46 } catch let error as Calc.Unsupported {
47 refusal = error
48 }
49 job.calc = CalcBlock(lines: lines, vars: values, scalar: resultCondScalar(finish.params), refusal: refusal)
50 return job
51 }
52
53 /// `org-babel-result-cond`: whether the value is taken as a string.
54 static func resultCondScalar(_ params: [String]) -> Bool {
55 params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
56 || params.contains("pp") || params.contains("file")
57 || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
58 }
59
60 /// A `:var` value as ob-calc pushes it: a number read by Calc, a list as a vector, a table as
61 /// a matrix (one row as a vector). Strings, Lisp floats inside lists, and names Calc reads as
62 /// something else are refused.
63 static func calcValue(_ value: VarValue, name: String) throws -> Calc.Value {
64 let refusal = Calc.Unsupported("value of :var \(name)")
65 guard name.range(of: "^[A-Za-z][A-Za-z0-9]*$", options: .regularExpression) != nil, !Calc.constants.contains(name), !Calc.reserved.contains(name) else { throw refusal }
66 func integer(_ cell: Cell) throws -> Calc.Value {
67 guard case .number(let n) = cell, let i = Int(n) else { throw refusal }
68 return .int(i)
69 }
70 switch value {
71 case .number(let n):
72 return try Calc.withModes(calcModes) {
73 var parser = Calc.Parser(n.replacingOccurrences(of: "e+", with: "e"))
74 return try Calc.Evaluator(modes: calcModes).eval(try parser.parse())
75 }
76 case .list(let items) where items.count > 1:
77 return .vector(try items.map(integer))
78 case .table(let rows) where !rows.isEmpty && !rows.contains(where: { $0 == nil || $0!.isEmpty }):
79 let matrix = try rows.map { try $0!.map(integer) }
80 return matrix.count == 1 ? .vector(matrix[0]) : .vector(matrix.map { .vector($0) })
81 default:
82 throw refusal
83 }
84 }
85
86 /// Runs `job.calc` as ob-calc does: the output `calcScript` prints. Throws `Calc.Unsupported`
87 /// for what Calc here doesn't do as Emacs's does, and `Failure` for Emacs's errors.
88 public static func evaluateCalc(_ job: BabelJob) throws -> BabelOutput {
89 guard let block = job.calc else { throw Failure.message("Not a calc block.") }
90 if let refusal = block.refusal { throw refusal }
91 do {
92 return try calc(block)
93 } catch let error as Calc.Failure {
94 // `math-read-number` of the error `calc-eval` returns.
95 throw Failure.message("Wrong type argument: stringp, (\(error.position) \"\(error.reason)\")")
96 }
97 }
98
99 static func calc(_ block: CalcBlock) throws -> BabelOutput {
100 try Calc.withModes(calcModes) {
101 let evaluator = Calc.Evaluator(modes: calcModes)
102 let names = Set(block.vars.map(\.name))
103 var stored: [String: Calc.Value] = [:]
104 for variable in block.vars { stored[variable.name] = variable.value }
105 /// Stack entries: a number, or the string ob-calc pushes for any other value.
106 /// `known` is false when Calc here couldn't tell whether ob-calc pushed a number.
107 enum Entry { case number(Calc.Value), text(String, known: Bool) }
108 var stack: [Entry] = []
109 func pop() throws -> Calc.Value {
110 guard let top = stack.popLast() else { throw Failure.message("Too few elements on stack") }
111 switch top {
112 case .number(let v): return v
113 case .text(_, true): throw Failure.message("Invalid data object encountered")
114 case .text(_, false): throw Calc.Unsupported("symbolic arithmetic")
115 }
116 }
117 for line in block.lines where !line.isEmpty {
118 if names.contains(line) {
119 stack.append(.number(stored[line]!))
120 } else if line.hasPrefix("'") {
121 let key = String(line.dropFirst())
122 let node: Calc.Node
123 switch key {
124 case "+", "-", "*", "/", "^", "%", "\\":
125 guard stack.count >= 2 else { throw Failure.message("Too few elements on stack") }
126 let b = try pop(), a = try pop()
127 node = .binary(Character(key), .number(a), .number(b))
128 case "n": node = .unary("-", .number(try pop()))
129 case "&": node = .binary("/", .number(.int(1)), .number(try pop()))
130 case "Q": node = .call("sqrt", [.number(try pop())])
131 case "A": node = .call("abs", [.number(try pop())])
132 default: throw Calc.Unsupported("stack command '\(key)")
133 }
134 stack.append(.number(try checked(try evaluator.eval(node))))
135 } else {
136 var parser = Calc.Parser(line)
137 let tree = try parser.parse()
138 // `calc-eval` of the line: a number is pushed as one.
139 let first: Calc.Value?
140 do {
141 first = try checked(try evaluator.eval(tree))
142 } catch is Calc.Unsupported where !tree.variables.isDisjoint(with: names) {
143 // Calc here can't keep this formula of the block's variables, which
144 // Emacs's Calc keeps as a formula unless it simplifies to a number.
145 first = nil
146 }
147 if let first, isNumber(first) {
148 stack.append(.number(first))
149 } else {
150 // The formula again with the block's variables put in, as text.
151 let resolved = try checked(try evaluator.eval(tree.substituting(stored)))
152 let text = try Calc.format(resolved, calcModes.format).replacingOccurrences(of: "'", with: "")
153 stack.append(.text(text, known: first != nil))
154 }
155 }
156 }
157 guard let top = stack.last else { throw Failure.message("Too few elements on stack") }
158 let result: Calc.Value
159 switch top {
160 case .number(let v): result = v
161 case .text(let s, _):
162 var parser = Calc.Parser(s)
163 result = try checked(try evaluator.eval(try parser.parse()))
164 }
165 let object: [String: Any]
166 if case .vector(let items) = result, !block.scalar {
167 let rows: [[Calc.Value]]
168 if case .vector(let first)? = items.first, !first.isEmpty,
169 items.allSatisfy({ if case .vector(let row) = $0 { row.count == first.count } else { false } }) {
170 rows = items.map { if case .vector(let row) = $0 { row } else { [] } }
171 } else {
172 rows = [items]
173 }
174 guard !rows.contains(where: \.isEmpty) else { throw Calc.Unsupported("empty vector") }
175 object = ["rows": try rows.map { try $0.map { try Calc.format($0, calcModes.format) } }]
176 } else {
177 object = ["value": try Calc.format(result, calcModes.format)]
178 }
179 let data = try JSONSerialization.data(withJSONObject: object)
180 return BabelOutput(stdout: String(decoding: data, as: UTF8.self))
181 }
182 }
183
184 static func isNumber(_ value: Calc.Value) -> Bool {
185 switch value {
186 case .int, .float, .frac: true
187 default: false
188 }
189 }
190
191 /// Dates show in Calc's own format, not Org's.
192 static func checked(_ value: Calc.Value) throws -> Calc.Value {
193 func hasDate(_ v: Calc.Value) -> Bool {
194 switch v {
195 case .date: true
196 case .vector(let items): items.contains(where: hasDate)
197 default: false
198 }
199 }
200 if hasDate(value) { throw Calc.Unsupported("dates in calc blocks") }
201 return value
202 }
203
204 /// Emacs running `org-babel-execute:calc` on the block, printing the value as JSON.
205 static func calcScript(body: String, vars: [(String, VarValue)], params: Params, finish: BabelJob.Finish) -> String {
206 var entries = vars.map { "(:var . (\($0.0) . \(lispLiteral($0.1))))" }
207 for key in [":prologue", ":epilogue"] {
208 if let value = params.single[key] {
209 entries.append("(\(key) . \(!params.quoted.contains(key) && number(value) != nil ? value : lispString(value)))")
210 }
211 }
212 entries.append("(:result-params . (" + finish.params.map { lispString($0) }.joined(separator: " ") + "))")
213 return """
214 ;;; -*- lexical-binding: t -*-
215 (require 'ob-calc)
216 (require 'json)
217 (condition-case err
218 (let* ((inhibit-message t)
219 (result (org-babel-execute:calc \(lispString(body)) '(\(entries.joined(separator: " "))))))
220 (princ (json-encode
221 (if (listp result)
222 `((rows . ,(vconcat (mapcar (lambda (row) (vconcat (mapcar (lambda (c) (format "%s" c)) row))) result))))
223 `((value . ,(format "%s" result)))))))
224 (error (let ((inhibit-message nil)) (message "%s" (error-message-string err)))
225 (kill-emacs 1)))
226 """
227 }
228}
229
230extension Calc {
231 /// `body` with `modes`' precision, fractions and symbolic mode.
232 static func withModes<T>(_ modes: Modes, _ body: () throws -> T) throws -> T {
233 guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") }
234 return try $precision.withValue(modes.precision) {
235 try $fractions.withValue(modes.preferFractions) {
236 try $symbolicMode.withValue(modes.symbolic, operation: body)
237 }
238 }
239 }
240}
241
242extension Calc.Node {
243 /// `org-babel-calc-maybe-resolve-var`: the variables in `values` replaced by their values.
244 func substituting(_ values: [String: Calc.Value]) -> Calc.Node {
245 switch self {
246 case .number: self
247 case .variable(let name): values[name].map(Calc.Node.number) ?? self
248 case .vector(let items): .vector(items.map { $0.substituting(values) })
249 case .unary(let op, let a): .unary(op, a.substituting(values))
250 case .binary(let op, let a, let b): .binary(op, a.substituting(values), b.substituting(values))
251 case .call(let name, let args): .call(name, args.map { $0.substituting(values) })
252 }
253 }
254}
Sources/OrgCore/Compute/BabelResults.swift +35 −6
@@ -42,7 +42,15 @@ extension Babel {
42 42
43 /// The language's result handling: `org-babel-result-cond` and the table import. 43 /// The language's result handling: `org-babel-result-cond` and the table import.
44 static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value { 44 static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
45 reassemble(rawValue(finish, output), finish) 45 let value = reassemble(rawValue(finish, output), finish)
46 switch (finish.kind, value) {
47 case (.calc, .string(let s)), (.sqlite, .string(let s)):
48 // `org-babel-execute-src-block` makes a table of a value that isn't a list.
49 if !finish.params.contains("output"), finish.params.contains("vector") || finish.params.contains("table") { return .table([[s]]) }
50 return value
51 default:
52 return value
53 }
46 } 54 }
47 55
48 static func rawValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value { 56 static func rawValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
@@ -54,10 +62,16 @@ extension Babel {
54 if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" } 62 if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" }
55 return .string(link + "]") 63 return .string(link + "]")
56 } 64 }
57 let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code") 65 let scalar = resultCondScalar(params)
58 || params.contains("pp") || params.contains("file")
59 || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
60 switch finish.kind { 66 switch finish.kind {
67 case .calc:
68 guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
69 return .string(output.stdout)
70 }
71 if let rows = object["rows"] as? [[String]] { return .table(rows) }
72 return .string(object["value"] as? String ?? "")
73 case .sqlite(let csv, let headers):
74 return sqliteValue(output.stdout, csv: csv, headers: headers, scalar: scalar)
61 case .shell(let valueIsExitStatus): 75 case .shell(let valueIsExitStatus):
62 var results = output.stdout 76 var results = output.stdout
63 if valueIsExitStatus { 77 if valueIsExitStatus {
@@ -103,6 +117,10 @@ extension Babel {
103 case .shell(let valueIsExitStatus): 117 case .shell(let valueIsExitStatus):
104 return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout 118 return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout
105 case .generic: return output.stdout 119 case .generic: return output.stdout
120 case .calc:
121 guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout }
122 return object["value"] as? String ?? ""
123 case .sqlite: return output.stdout
106 case .compiled: return compiledResult(finish, output) 124 case .compiled: return compiledResult(finish, output)
107 case .script(let js, let session): return finish.output || (js && !session) ? output.stdout : (output.resultFile ?? "") 125 case .script(let js, let session): return finish.output || (js && !session) ? output.stdout : (output.resultFile ?? "")
108 } 126 }
@@ -427,6 +445,16 @@ extension Babel {
427 if s.last != "\n" { s += "\n" } 445 if s.last != "\n" { s += "\n" }
428 let items = s.split(separator: "\n", omittingEmptySubsequences: true) 446 let items = s.split(separator: "\n", omittingEmptySubsequences: true)
429 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n") 447 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
448 case .table(let rows) where params.contains("list") && finish.kind.isSQLite:
449 // ob-sqlite's value is always rows: each an item, its first cell the text and the
450 // others lines under it.
451 listed = true
452 var items = rows.map { row in
453 guard let row else { return "- hline\n" }
454 return "- " + (row.first ?? "") + "\n" + row.dropFirst().map { " " + $0 + "\n" }.joined()
455 }.joined()
456 while let last = items.unicodeScalars.last, " \r\t\n".unicodeScalars.contains(last) { items.unicodeScalars.removeLast() }
457 buffer.insert(items + "\n")
430 case .table(let rows) where params.contains("list"): 458 case .table(let rows) where params.contains("list"):
431 listed = true 459 listed = true
432 let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") } 460 let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") }
@@ -440,7 +468,8 @@ extension Babel {
440 buffer.tableAlign() 468 buffer.tableAlign()
441 buffer.point = buffer.tableEnd() 469 buffer.point = buffer.tableEnd()
442 case .string(var s): 470 case .string(var s):
443 if !s.isEmpty, s.last != "\n" { s += "\n" } 471 // `org-string-nw-p`: a blank result gets no newline.
472 if s.unicodeScalars.contains(where: { !" \r\t\n".unicodeScalars.contains($0) }), s.unicodeScalars.last != "\n" { s += "\n" }
444 buffer.insert(s) 473 buffer.insert(s)
445 } 474 }
446 let end = buffer.marker(buffer.point, advances: true) 475 let end = buffer.marker(buffer.point, advances: true)
@@ -500,7 +529,7 @@ extension Babel {
500 /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block. 529 /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block.
501 static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) { 530 static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) {
502 let text = buffer.substring(beg, end) 531 let text = buffer.substring(beg, end)
503 var size = text.components(separatedBy: "\n").count - (text.hasSuffix("\n") ? 1 : 0) 532 var size = text.components(separatedBy: "\n").count - (text.utf16.last == 10 ? 1 : 0)
504 if text.isEmpty { size = 0 } 533 if text.isEmpty { size = 0 }
505 guard size > 0 else { return } 534 guard size > 0 else { return }
506 if size < 10 { 535 if size < 10 {
Sources/OrgCore/Compute/BabelSQLite.swift added +250
@@ -0,0 +1,250 @@
1import Foundation
2
3// ob-sqlite (Org 9.8.7): the body goes to `sqlite3` on standard input, with the options the
4// header arguments name, and the output becomes the result through `org-table-convert-region`.
5
6extension Babel {
7 /// An sqlite block's `sqlite3` command line.
8 public struct SQLiteCommand: Sendable, Equatable {
9 /// The command for the shell, as ob-sqlite writes it.
10 public let command: String
11 /// The command's words after `sqlite3` when they hold nothing the shell would change;
12 /// nil otherwise.
13 public let arguments: [String]?
14 }
15
16 /// Stands, in a job's input, for a data file the runner writes (`BabelJob.dataFiles`).
17 public static func dataFileToken(_ n: Int) -> String { "__ORGSTAR_DATA_FILE_\(n)__" }
18
19 static func sqliteJob(body: String, vars: [(String, VarValue)], params: Params, finishBase: (BabelJob.Finish.Kind) -> BabelJob.Finish,
20 directory: String?, block: Range<Int>, blockText: String, alwaysAsk: Bool) throws -> BabelJob {
21 let separator = params.single[":separator"], nullvalue = params.single[":nullvalue"], db = params.single[":db"]
22 let headers = params.single[":colnames"] == "yes"
23 let others = [":header", ":echo", ":bail", ":column", ":csv", ":html", ":line", ":list"].filter { params.single[$0] != nil }
24 let formatted = others.contains { [":csv", ":column", ":line", ":list", ":html"].contains($0) } || separator != nil
25 let fields: [(String, String)] = [
26 ("cmd", "sqlite3"),
27 ("header", headers ? "-header" : "-noheader"),
28 ("separator", separator.map { "-separator \($0)" } ?? ""),
29 ("nullvalue", nullvalue.map { "-nullvalue \($0)" } ?? ""),
30 ("others", others.map { "-" + $0.dropFirst() }.joined(separator: " ")),
31 ("csv", formatted ? "" : "-csv"),
32 ("readonly", params.single[":readonly"] == "yes" ? "-readonly" : ""),
33 ("db", db ?? ""),
34 ]
35 // `org-fill-template`.
36 var command = "%cmd %header %separator %nullvalue %others %csv %readonly %db "
37 for (key, value) in fields { command = command.replacingOccurrences(of: "%" + key, with: value) }
38 let words = command.split(separator: " ").dropFirst().map(String.init)
39 let plain = words.allSatisfy { $0.range(of: "^[A-Za-z0-9._/:@%+=,-]+$", options: .regularExpression) != nil }
40 && !(db?.hasPrefix("-") ?? false) && words.count == command.split(separator: " ").count - 1
41
42 // `org-babel-sql-expand-vars`: `$name` replaced, a table by a CSV file of it.
43 var expanded = body
44 var files: [String: String] = [:]
45 for (name, value) in vars {
46 guard name.range(of: "^[A-Za-z0-9_-]+$", options: .regularExpression) != nil else {
47 throw Failure.message(":var \(name) isn't supported for sqlite blocks; nothing was run.")
48 }
49 let replacement: String
50 switch value {
51 case .scalar(let s): replacement = s
52 case .number(let n): replacement = n
53 case .table(let rows):
54 let token = dataFileToken(files.count)
55 files[token] = try csvFile(rows, name: name)
56 replacement = token
57 case .list:
58 throw Failure.message(":var \(name) is a list, which sqlite blocks can't take; nothing was run.")
59 }
60 expanded = replacingCaseInsensitively("$" + name, in: expanded, with: replacement)
61 }
62 let input = [params.single[":prologue"] ?? "", expanded, params.single[":epilogue"] ?? ""].joined(separator: "\n") + "\n"
63 var finish = finishBase(.sqlite(csv: !formatted, headers: headers))
64 // ob-sqlite doesn't put back the names `:var` tables gave up.
65 (finish.colnames, finish.rownames) = (nil, nil)
66 var job = BabelJob(language: "sqlite", runner: .process(executable: command, arguments: []), input: input, directory: directory,
67 block: block, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish)
68 job.sqlite = SQLiteCommand(command: command, arguments: plain ? words : nil)
69 job.dataFiles = files
70 return job
71 }
72
73 /// `replace-regexp-in-string` of a literal with `case-fold-search`.
74 static func replacingCaseInsensitively(_ target: String, in text: String, with replacement: String) -> String {
75 let ns = text as NSString
76 var result = ""
77 var location = 0
78 while location <= ns.length {
79 let found = ns.range(of: target, options: [.caseInsensitive, .literal], range: NSRange(location: location, length: ns.length - location))
80 guard found.location != NSNotFound else { break }
81 result += ns.substring(with: NSRange(location: location, length: found.location - location)) + replacement
82 location = NSMaxRange(found)
83 }
84 return result + ns.substring(from: min(location, ns.length))
85 }
86
87 /// `orgtbl-to-csv` of a table: rules dropped, a field with `"` or `,` quoted, no final
88 /// newline. Cells the Org exporter could change are refused.
89 static func csvFile(_ rows: [[Cell]?], name: String) throws -> String {
90 try rows.compactMap { $0 }.map { row in
91 try row.map { cell in
92 let text = cellText(cell)
93 guard text.range(of: "[\\[\\]{}<>@\\\\\\n\\t]|src_|call_", options: .regularExpression) == nil,
94 text == text.trimmingCharacters(in: .whitespaces) else {
95 throw Failure.message(":var \(name) has a cell the Org exporter may change; nothing was run.")
96 }
97 return text.contains("\"") || text.contains(",") ? "\"" + text.replacingOccurrences(of: "\"", with: "\"\"") + "\"" : text
98 }.joined(separator: ",")
99 }.joined(separator: "\n")
100 }
101
102 // MARK: - Results
103
104 /// ob-sqlite's result from `sqlite3`'s output: the output
105 /// as a string or through `org-table-convert-region` as a table, a single cell alone.
106 static func sqliteValue(_ output: String, csv: Bool, headers: Bool, scalar: Bool) -> Value {
107 // csv mode ends lines with CRLF, and Emacs keeps the CR.
108 let text = output
109 if scalar { return .string(text) }
110 if text.isEmpty { return .string("") }
111 var rows: [[String]?] = convertRegion(text, csv: csv)
112 if headers, let first = rows.first {
113 rows = [first, nil] + rows.dropFirst()
114 }
115 // `org-babel-sqlite-table-or-scalar`.
116 if rows.count == 1, let only = rows[0], only.count == 1 { return .string(babelRead(only[0])) }
117 return .table(rows.map { $0?.map(babelRead) })
118 }
119
120 /// `org-babel-read` with Lisp evaluation inhibited: a number as Emacs prints it, a single
121 /// quoted string read, else the cell.
122 static func babelRead(_ cell: String) -> String {
123 guard cell.contains(where: { !$0.isWhitespace }) else { return cell }
124 if !cell.contains("\r"), let n = number(cell), cell.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil { return n }
125 let trimmed = cell.trimmingCharacters(in: .whitespacesAndNewlines)
126 if trimmed.hasPrefix("\""), trimmed.count >= 2, trimmed.hasSuffix("\""),
127 let (sexp, length) = try? LispReader.readFirst(trimmed), length == trimmed.count, let s = sexp.string {
128 return s
129 }
130 return cell
131 }
132
133 /// `org-table-convert-region` on the whole output, then `org-table-to-lisp` of the aligned
134 /// table: rows of cells, padded to the widest row.
135 static func convertRegion(_ text: String, csv: Bool) -> [[String]?] {
136 var b = Array(text.unicodeScalars)
137 let nl: Unicode.Scalar = "\n", tab: Unicode.Scalar = "\t", space: Unicode.Scalar = " ", comma: Unicode.Scalar = ",", quote: Unicode.Scalar = "\""
138 var end = b.last == nl ? b.count - 1 : b.count
139 var point = 0
140 func bol(_ i: Int) -> Bool { i == 0 || b[i - 1] == nl }
141 func replace(_ range: Range<Int>, _ s: [Unicode.Scalar]) {
142 b.replaceSubrange(range, with: s)
143 if end >= range.upperBound { end += s.count - range.count } else if end > range.lowerBound { end = range.lowerBound }
144 }
145 enum Separator { case comma, tab, spaces }
146 var separator = Separator.comma
147 if !csv {
148 let lines = String(String.UnicodeScalarView(b[0..<end])).components(separatedBy: "\n").filter { !$0.isEmpty }
149 if !lines.contains(where: { !$0.contains("\t") }) {
150 separator = .tab
151 } else if !lines.contains(where: { !$0.contains(",") }) {
152 separator = .comma
153 } else {
154 separator = .spaces
155 }
156 }
157 if separator == .comma {
158 while point < end {
159 if bol(point) {
160 replace(point..<point, ["|", " "])
161 point += 2
162 continue
163 }
164 var j = point
165 while j < b.count, b[j] == space || b[j] == tab { j += 1 }
166 if j == b.count || b[j] == nl {
167 // `[ \t]*$`, then the next line.
168 replace(point..<j, [" ", "|"])
169 point += 2
170 if let next = b[point...].firstIndex(of: nl) { point = next + 1 } else { point = b.count }
171 continue
172 }
173 if b[j] == quote, let close = b[(j + 1)...].firstIndex(of: quote) {
174 let content = b[(j + 1)..<close].map { $0 == nl ? space : $0 }
175 replace(point..<(close + 1), Array(content))
176 point += content.count
177 if point < b.count, b[point] == quote {
178 replace(point..<point, [quote])
179 point += 1
180 }
181 continue
182 }
183 if point < b.count, b[point] != comma, b[point] != nl {
184 while point < b.count, b[point] != comma, b[point] != nl { point += 1 }
185 continue
186 }
187 if j < b.count, b[j] == comma {
188 replace(point..<(j + 1), [" ", "|", " "])
189 point += 3
190 continue
191 }
192 if let next = b[point...].firstIndex(of: nl) { point = next + 1 } else { point = b.count }
193 }
194 } else {
195 // `re-search-forward` of "^\\|\t", or "^ *\\| *\t *\\| \\{1,\\}", each match
196 // replaced by "| ".
197 while point <= end {
198 var match: Range<Int>?
199 var i = point
200 while i <= end, match == nil {
201 if bol(i) {
202 var k = i
203 if separator == .spaces { while k < end, b[k] == space { k += 1 } }
204 match = i..<k
205 } else if i < end {
206 if separator == .tab {
207 if b[i] == tab { match = i..<(i + 1) }
208 } else {
209 var k = i
210 while k < end, b[k] == space { k += 1 }
211 if k < end, b[k] == tab {
212 var m = k + 1
213 while m < end, b[m] == space { m += 1 }
214 match = i..<m
215 } else if k > i {
216 match = i..<k
217 }
218 }
219 }
220 i += 1
221 }
222 guard let found = match else { break }
223 replace(found, ["|", " "])
224 point = found.lowerBound + 2
225 }
226 }
227 // The table: the lines from the start that begin with `|`.
228 var rows: [[String]] = []
229 for line in String(String.UnicodeScalarView(b)).components(separatedBy: "\n") {
230 var s = Substring(line)
231 s = s.drop { $0 == " " || $0 == "\t" }
232 guard s.first == "|" else { break }
233 s = s.dropFirst()
234 var cells: [String] = []
235 while true {
236 s = s.drop { $0 == " " || $0 == "\t" }
237 if s.isEmpty { break }
238 let field = s.prefix { $0 != "|" }
239 var cell = Substring(field)
240 while let last = cell.last, last == " " || last == "\t" { cell = cell.dropLast() }
241 cells.append(String(cell))
242 s = s.dropFirst(field.count)
243 if !s.isEmpty { s = s.dropFirst() }
244 }
245 rows.append(cells)
246 }
247 let width = rows.map(\.count).max() ?? 0
248 return rows.map { $0 + Array(repeating: "", count: width - $0.count) }
249 }
250}
Sources/OrgCore/Semantic/DisplayWidth.swift +3
@@ -8,6 +8,9 @@ func displayWidth(of character: Character) -> Int {
8 guard let scalar = character.unicodeScalars.first else { return 0 } 8 guard let scalar = character.unicodeScalars.first else { return 0 }
9 if scalar.properties.isEmojiPresentation { return 2 } 9 if scalar.properties.isEmojiPresentation { return 2 }
10 switch scalar.value { 10 switch scalar.value {
11 case 0x00...0x08, 0x0B...0x1F, 0x7F:
12 // Emacs shows a control character as `^M`.
13 return character.unicodeScalars.count == 1 ? 2 : 1
11 case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0xA4CF, 0xAC00...0xD7A3, 0xF900...0xFAFF, 14 case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0xA4CF, 0xAC00...0xD7A3, 0xF900...0xFAFF,
12 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x20000...0x3FFFD: 15 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x20000...0x3FFFD:
13 return 2 16 return 2
Sources/OrgPrograms/BabelRunner.swift +6 −1
@@ -51,7 +51,12 @@ public enum BabelRunner {
51 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 51 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
52 defer { try? FileManager.default.removeItem(at: folder) } 52 defer { try? FileManager.default.removeItem(at: folder) }
53 let resultFile = folder.appendingPathComponent("result") 53 let resultFile = folder.appendingPathComponent("result")
54 let input = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path) 54 var input = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path)
55 for (token, contents) in job.dataFiles {
56 let file = folder.appendingPathComponent("sql-data-\(token.filter(\.isNumber))")
57 try contents.write(to: file, atomically: true, encoding: .utf8)
58 input = input.replacingOccurrences(of: token, with: file.path)
59 }
55 if case .session(let name, let executable, let kind) = job.runner { 60 if case .session(let name, let executable, let kind) = job.runner {
56 let directory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: fileDirectory).standardizedFileURL } ?? fileDirectory 61 let directory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: fileDirectory).standardizedFileURL } ?? fileDirectory
57 return try await BabelSessions.shared.run(job, name: name, executable: executable, kind: kind, directory: directory, resultFile: resultFile) 62 return try await BabelSessions.shared.run(job, name: name, executable: executable, kind: kind, directory: directory, resultFile: resultFile)
Sources/OrgPrograms/Programs.swift +13
@@ -21,8 +21,21 @@ public struct Programs: ProgramRunning {
21 if words.count == 1, !BabelRunner.installed(words[0]), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output } 21 if words.count == 1, !BabelRunner.installed(words[0]), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output }
22 case .session(_, let executable, _): 22 case .session(_, let executable, _):
23 if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output } 23 if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output }
24 case .process where job.language == "sqlite":
25 // `sqlite3` when it's installed, as Emacs runs it; the SQLite library otherwise.
26 if !BabelRunner.installed("sqlite3"), let output = try SQLiteBlocks.run(job, directory: fileDirectory) { return output }
24 case .process: 27 case .process:
25 break 28 break
29 case .emacs where job.calc != nil:
30 // calc natively, and in Emacs what Calc here refuses.
31 do {
32 return try Babel.evaluateCalc(job)
33 } catch let refusal as Calc.Unsupported {
34 guard emacs() != nil else { throw BabelRunner.Failure(description: TableReason.calcRefusal(refusal.reason)) }
35 }
36 let output = try await BabelRunner.run(job, fileDirectory: fileDirectory)
37 if output.status != 0 { throw BabelRunner.Failure(description: output.stderr.trimmingCharacters(in: .whitespacesAndNewlines)) }
38 return output
26 case .emacs: 39 case .emacs:
27 // Emacs Lisp in `Elisp` when Emacs isn't installed. 40 // Emacs Lisp in `Elisp` when Emacs isn't installed.
28 if emacs() == nil { 41 if emacs() == nil {
Tests/OrgAppTests/SQLiteBlocksTests.swift added +221
@@ -0,0 +1,221 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// sqlite blocks with the SQLite library, compared with macOS's `sqlite3` and with Emacs
8/// running it.
9struct SQLiteBlocksTests {
10 static let sqlite3 = "/usr/bin/sqlite3"
11 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && FileManager.default.isExecutableFile(atPath: sqlite3)
12
13 static let values = """
14 select 1 as a, 'x y' as b, null as c, 2.50 as d, 'it''s' as e, '' as f, -7 as g, 0.1 + 0.2 as h
15 union all select 22, 'é,ü', 'q"t', 1e20, '<&>', ' lead', 3.0, 'tab\tin';
16 """
17
18 /// Options as ob-sqlite writes them, and scripts.
19 static let cli: [([String], String)] = [
20 (["-noheader", "-csv"], values),
21 (["-header", "-csv"], values),
22 (["-noheader", "-list"], values),
23 (["-noheader", "-header", "-list"], values),
24 (["-noheader", "-column"], "select 1 as a, 'xx' as long_name, 2.5 as mid union all select -10, null, 'text';\nselect 'second' as s;"),
25 (["-noheader", "-html"], values),
26 (["-noheader", "-line"], values + "\nselect 'a\nb\n' as multi, 'c' as longer_name;"),
27 (["-noheader", "-separator", "X"], values),
28 (["-header", "-separator", ";"], values),
29 (["-noheader", "-separator", "X", "-nullvalue", "N"], values),
30 (["-noheader", "-nullvalue", "N", "-csv"], values),
31 (["-noheader", "-csv"], "\nselect 1;\n\n select 2; select 3;\n# comment\nselect 4\n;\nselect 5"),
32 (["-noheader", "-echo", "-csv"], "\nselect 1;\n select 2; select 3;\n# c\n.mode list\n\nselect 4\n;\n"),
33 (["-noheader", "-csv"], ".headers on\nselect 1 as a;\n.mode column\nselect 2 as b;\n.mode list\nselect 3 as c;\n.mode csv\nselect 4 as d;\n"),
34 (["-noheader", "-csv"], ".mode column\n.headers off\nselect 1 as a, null as n;\n.headers on\n.mode html\n.nullvalue N\nselect 1 as a, null as n;"),
35 (["-noheader", "-csv"], ".mode line\n.separator X\nselect 1 as a, null as n;\n.mode csv\n.separator :\nselect 'a:b' as a, 'c,d';"),
36 (["-noheader", "-csv"], ".nullvalue N\nselect null;\n.mode list\nselect null;\n.nullvalue M\nselect null, 1;"),
37 (["-noheader", "-csv"], "create table t(a integer, b text, c real);\ninsert into t values (1, 'one', 1.5), (2, null, -0.25), (30, 'thirty', 1e100);\nselect * from t order by a;\nselect count(*) as n from t;\nselect a from t where 0;"),
38 (["-noheader", "-column"], "create table t(a, b);\ninsert into t values (1, 'xx'), (22, null), (3.5, 'y');\nselect * from t;\nselect a from t where 0;\n"),
39 (["-noheader", "-csv"], "select 1;\nselect * from nope;\nselect 2;\nselect 3; select * from nope; select 4;\nselect 5;"),
40 (["-noheader", "-bail", "-csv"], "select 1;\nselect * from nope;\nselect 2;"),
41 (["-noheader", "-csv"], "select 1 union all select abs(-9223372036854775808);\nselect 2;"),
42 (["-noheader", "-csv"], "create table t(a unique);\ninsert into t values (1);\ninsert into t values (1);\nselect count(*) from t;"),
43 (["-noheader", "-csv"], "select 1 -- a comment\n;\n/* c */ select 2;\n-- only a comment\nselect 3 /* trailing"),
44 (["-noheader", "-csv"], "select $x, ?, :y;"),
45 (["-noheader", "-html"], "select 'a''b\"c<d>e&f' as \"<h>\";"),
46 (["-noheader", "-csv"], "select 'line\ntwo', 'a,b', '\"', 'plain' as \"col name\", 'x' as \"q\"\"n\";"),
47 (["-noheader", "-csv"], ".mode list\n.separator ,\nselect 'a,b', 'c';\n.mode list\nselect 'a,b';"),
48 (["-noheader", "-header", "-csv"], "create table t(a, b);\n.headers on\nselect * from t;\ninsert into t values (1, 2);\nselect * from t;"),
49 ]
50
51 static func cliOutput(_ arguments: [String], _ input: String, folder: URL) throws -> (stdout: String, status: Int32) {
52 let process = Process()
53 process.executableURL = URL(fileURLWithPath: sqlite3)
54 process.arguments = arguments
55 process.currentDirectoryURL = folder
56 let stdin = Pipe(), stdout = Pipe()
57 process.standardInput = stdin
58 process.standardOutput = stdout
59 process.standardError = FileHandle.nullDevice
60 try process.run()
61 stdin.fileHandleForWriting.write(Data(input.utf8))
62 try stdin.fileHandleForWriting.close()
63 let data = stdout.fileHandleForReading.readDataToEndOfFile()
64 process.waitUntilExit()
65 return (String(decoding: data, as: UTF8.self), process.terminationStatus)
66 }
67
68 @Test(.enabled(if: oracle))
69 func shellMatchesSqlite3() throws {
70 for (arguments, script) in Self.cli {
71 let input = script + "\n"
72 let theirFolder = try Folder(), ourFolder = try Folder()
73 let theirs = try Self.cliOutput(arguments, input, folder: theirFolder.url)
74 var shell = try SQLiteBlocks.Shell(arguments: arguments)
75 let ours = try shell.run(input, folder: ourFolder.url)
76 #expect(ours.stdout == theirs.stdout, "\(arguments) \(script.debugDescription)\nours:\n\(ours.stdout.debugDescription)\nsqlite3:\n\(theirs.stdout.debugDescription)")
77 #expect(ours.status == theirs.status, "\(arguments) \(script.debugDescription)")
78 }
79 }
80
81 static let table = "#+NAME: tbl\n| id | name |\n|----+-------|\n| 1 | one |\n| 2 | two |\n| 3 | x, \"y\" |\n\n"
82
83 static let blocks: [String] = [
84 "#+begin_src sqlite\nselect 1 as a, 'x y' as b, null as c, 2.50 as d;\nselect 'q\"t', 'é', '007', '\"quoted\"';\n#+end_src\n",
85 "#+begin_src sqlite :colnames yes\nselect 1 as a, 2 as b;\nselect 3, 4;\n#+end_src\n",
86 "#+begin_src sqlite\nselect 42;\n#+end_src\n",
87 "#+begin_src sqlite\nselect 'line\ntwo', 'a,b';\n#+end_src\n",
88 "#+begin_src sqlite :list\nselect 1, 'x y';\n#+end_src\n",
89 "#+begin_src sqlite :column\nselect 1 as a, 'x y' as b;\n#+end_src\n",
90 "#+begin_src sqlite :html\nselect 1 as a, 'x' as b;\n#+end_src\n",
91 "#+begin_src sqlite :line\nselect 1 as a, 'x' as b;\n#+end_src\n",
92 "#+begin_src sqlite :separator X\nselect 1 as a, 'x y' as b;\n#+end_src\n",
93 "#+begin_src sqlite :separator , :nullvalue N\nselect 1, null, 'a b';\n#+end_src\n",
94 "#+begin_src sqlite :header\nselect 1 as a, 2 as b;\n#+end_src\n",
95 "#+begin_src sqlite :csv\nselect 1 as a, 'b c' as b;\n#+end_src\n",
96 "#+begin_src sqlite :results output\nselect 1, 2;\n#+end_src\n",
97 "#+begin_src sqlite :results output\nselect 'line\ntwo', 'a,b';\n#+end_src\n",
98 "#+begin_src sqlite :results verbatim\nselect 1, 2;\nselect 3, 4;\n#+end_src\n",
99 "#+begin_src sqlite :results raw\nselect '*bold*';\n#+end_src\n",
100 "#+begin_src sqlite :results table\nselect 7;\n#+end_src\n",
101 "#+begin_src sqlite :results list\nselect 1, 2;\nselect 3, 4;\n#+end_src\n",
102 "#+begin_src sqlite\ncreate table t(a);\n#+end_src\n",
103 "#+begin_src sqlite\nselect 1 where 0;\n#+end_src\n",
104 "#+begin_src sqlite :db test.db\ncreate table if not exists t(a, b);\ninsert into t values (1, 'one'), (2, 'two');\nselect * from t order by a;\n#+end_src\n",
105 "#+begin_src sqlite :db test2.db :readonly yes\nselect 1;\n#+end_src\n",
106 "#+begin_src sqlite :var x=3 name=\"two\"\nselect $x * 2, '$name', $X;\n#+end_src\n",
107 "#+begin_src sqlite :var x=2.50\nselect $x;\n#+end_src\n",
108 table + "#+begin_src sqlite :var t=tbl\ncreate table v(id integer, name text);\n.mode csv\n.import $t v\nselect name, id * 10 from v order by id;\n#+end_src\n",
109 table + "#+begin_src sqlite :var t=tbl :colnames yes\ncreate table v(id integer, name text);\n.import --csv $t v\n.headers on\nselect * from v;\n#+end_src\n",
110 "#+begin_src sqlite :prologue \"create table p(a);\" :epilogue \"select count(*) from p;\"\ninsert into p values (1), (2);\n#+end_src\n",
111 "#+begin_src sqlite\nselect 1;\nselect * from nope;\nselect 2;\n#+end_src\n",
112 "#+begin_src sqlite :bail\nselect 1;\nselect * from nope;\nselect 2;\n#+end_src\n",
113 "#+begin_src sqlite :echo\nselect 1;\nselect 2;\n#+end_src\n",
114 "#+begin_src sqlite\nselect ' a ', '\"b\"', 'c\"d', '-', '1e3', '+5', '.5', '1.';\n#+end_src\n",
115 "#+begin_src sqlite :list\nselect 'a b', 'c';\nselect 'single';\n#+end_src\n",
116 "#+begin_src sqlite :list\nselect 'a' || char(9) || 'b', 'c';\nselect 'd' || char(9) || 'e';\n#+end_src\n",
117 "#+begin_src sqlite :separator ,\nselect 1, 2;\nselect 3;\n#+end_src\n",
118 "#+begin_src sqlite\nselect '';\n#+end_src\n",
119 "#+begin_src sqlite\nselect 1, '';\nselect '', '';\n#+end_src\n",
120 ]
121
122 /// The results the app inserts, as Emacs inserts them running `sqlite3`.
123 @MainActor
124 @Test(.enabled(if: oracle))
125 func resultsMatchEmacs() async throws {
126 let ourFolder = try Folder(), theirFolder = try Folder()
127 var forms: [String] = []
128 var ours: [String] = []
129 for text in Self.blocks {
130 let caret = (text as NSString).range(of: "#+begin_src").location + 2
131 let file = try ourFolder.write("b.org", text)
132 let session = DocumentSession(recovery: FileRecoveryStore(directory: ourFolder.url.appendingPathComponent(".r")))
133 session.open(file.path)
134 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: caret, expect: nil) else {
135 Issue.record("not planned: \(text)")
136 return
137 }
138 _ = await session.runBabel(job)
139 ours.append(session.document?.text ?? "")
140 let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
141 forms.append("(with-temp-buffer (insert \(quoted)) (org-mode) (goto-char \(caret + 1)) (condition-case e (org-babel-execute-src-block) (error (insert (format \"ERROR: %S\" e)))) (princ (concat (buffer-string) \"\\f\")))")
142 }
143 let emacs = try Self.emacs("""
144 (progn (require 'org) (require 'ob-sqlite)
145 (setq org-confirm-babel-evaluate nil org-babel-sqlite3-command "\(Self.sqlite3)" default-directory "\(theirFolder.url.path)/")
146 \(forms.joined(separator: "\n")))
147 """).split(separator: "\u{0C}", omittingEmptySubsequences: false).map(String.init)
148 for (i, text) in Self.blocks.enumerated() {
149 #expect(ours[i] == emacs[i], "\(text)\nours:\n\(ours[i])\nemacs:\n\(emacs[i])")
150 }
151 }
152
153 /// Emacs in a UTF-8 locale, as it runs on the Mac.
154 static func emacs(_ form: String) throws -> String {
155 let process = Process()
156 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
157 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
158 process.environment = ProcessInfo.processInfo.environment.merging(["LANG": "en_US.UTF-8", "LC_ALL": "en_US.UTF-8"]) { $1 }
159 let pipe = Pipe()
160 process.standardOutput = pipe
161 process.standardError = FileHandle.nullDevice
162 try process.run()
163 let data = pipe.fileHandleForReading.readDataToEndOfFile()
164 process.waitUntilExit()
165 return String(decoding: data, as: UTF8.self)
166 }
167
168 static func plan(_ text: String) throws -> BabelJob {
169 let caret = (text as NSString).range(of: "#+begin_src").location + 2
170 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
171 guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned: \(text)") }
172 return job
173 }
174
175 /// What can't be shown as `sqlite3` shows it is refused, with nothing written.
176 @Test func refusals() throws {
177 let refused: [(String, SQLiteBlocks.Refusal)] = [
178 ("#+begin_src sqlite :db \"my file.db\"\nselect 1;\n#+end_src\n", .init(.shell)),
179 ("#+begin_src sqlite :separator |\nselect 1;\n#+end_src\n", .init(.shell)),
180 ("#+begin_src sqlite :header :separator ;\nselect 1;\n#+end_src\n", .init(.shell)),
181 ("#+begin_src sqlite\n.separator ;\nselect 1;\n#+end_src\n", .init(.dotCommand(".separator"))),
182 ("#+begin_src sqlite :db ~/x.db\nselect 1;\n#+end_src\n", .init(.shell)),
183 ("#+begin_src sqlite\n.tables\n#+end_src\n", .init(.dotCommand(".tables"))),
184 ("#+begin_src sqlite\n.mode box\nselect 1;\n#+end_src\n", .init(.dotCommand(".mode"))),
185 ("#+begin_src sqlite\n.separator \"\\t\"\nselect 1;\n#+end_src\n", .init(.dotCommand(".separator"))),
186 ("#+begin_src sqlite\nselect x'00';\n#+end_src\n", .init(.blob)),
187 ("#+begin_src sqlite\nselect 'a' || char(13) || 'b';\n#+end_src\n", .init(.control)),
188 ("#+begin_src sqlite :column\nselect 'é';\n#+end_src\n", .init(.width)),
189 ("#+begin_src sqlite :column\nselect 'a\nb';\n#+end_src\n", .init(.width)),
190 ("#+begin_src sqlite\nexplain select 1;\n#+end_src\n", .init(.explain)),
191 ("#+begin_src sqlite\ncreate table t(a);\nselect x'01';\n#+end_src\n", .init(.blob, partly: true)),
192 (Self.table + "#+begin_src sqlite :var t=tbl\n.import --csv $t v\n#+end_src\n", .init(.newTable)),
193 (Self.table + "#+begin_src sqlite :var t=tbl\ncreate table v(a);\n.import --csv $t v\n#+end_src\n", .init(.importRows, partly: true)),
194 ]
195 let folder = try Folder()
196 for (text, refusal) in refused {
197 #expect(throws: Babel.Failure.message(refusal.message), "\(text)") { try SQLiteBlocks.run(Self.plan(text), directory: folder.url) }
198 }
199 #expect(try SQLiteBlocks.run(Self.plan("#+begin_src js\n1\n#+end_src\n"), directory: folder.url) == nil)
200 }
201
202 /// The sandboxed builds run calc blocks natively, and say why they refuse one.
203 @MainActor
204 @Test func calcBlocksRunInTheSession() async throws {
205 let folder = try Folder()
206 for (text, message, result) in [
207 ("#+begin_src calc\n1/3\n#+end_src\n", "Code block evaluation complete.", "#+RESULTS:\n: 0.333333333333\n"),
208 ("#+begin_src calc\n1\n'x\n#+end_src\n", "This calc block can't be calculated here: stack command 'x.", ""),
209 ] {
210 let file = try folder.write("c.org", text)
211 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.url.appendingPathComponent(".r")))
212 session.open(file.path)
213 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 2, expect: nil) else {
214 Issue.record("not planned: \(text)")
215 return
216 }
217 #expect(await session.runBabel(job) == message)
218 #expect(session.document?.text == text + (result.isEmpty ? "" : "\n" + result))
219 }
220 }
221}
Tests/OrgCoreTests/BabelCalcTests.swift added +123
@@ -0,0 +1,123 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// calc blocks on `Calc`, compared with ob-calc in Emacs.
6struct BabelCalcTests {
7 static let table = "#+NAME: tb\n| 1 | 2 |\n| 3 | 4 |\n\n"
8
9 static let cases: [String] = [
10 "#+begin_src calc\n1+2\n#+end_src\n",
11 "#+begin_src calc\n1/3\n#+end_src\n",
12 "#+begin_src calc\n10 / 4\n#+end_src\n",
13 "#+begin_src calc\n7 % 3\n#+end_src\n",
14 "#+begin_src calc\n3.0\n#+end_src\n",
15 "#+begin_src calc\n1e3\n#+end_src\n",
16 "#+begin_src calc\n1.5e20 * 3\n#+end_src\n",
17 "#+begin_src calc\n1:3 + 1:6\n#+end_src\n",
18 "#+begin_src calc\nsqrt(2)\n#+end_src\n",
19 "#+begin_src calc\nsin(30)\n#+end_src\n",
20 "#+begin_src calc\n 5 \n\n#+end_src\n",
21 "#+begin_src calc\n3\n4\n'+\n#+end_src\n",
22 "#+begin_src calc\n1\n2\n'-\n#+end_src\n",
23 "#+begin_src calc\n1\n3\n'/\n#+end_src\n",
24 "#+begin_src calc\n2\n10\n'^\n#+end_src\n",
25 "#+begin_src calc\n7\n2\n'%\n#+end_src\n",
26 "#+begin_src calc\n7\n2\n'\\\n#+end_src\n",
27 "#+begin_src calc\n2\n'n\n#+end_src\n",
28 "#+begin_src calc\n4\n'&\n#+end_src\n",
29 "#+begin_src calc\n9\n'Q\n#+end_src\n",
30 "#+begin_src calc\n-3\n'A\n#+end_src\n",
31 "#+begin_src calc\n1.0\n2\n'+\n#+end_src\n",
32 "#+begin_src calc\n1\n2\n#+end_src\n",
33 "#+begin_src calc :var x=5 y=2.5\nx*y+1\n#+end_src\n",
34 "#+begin_src calc :var x=5\nx\n#+end_src\n",
35 "#+begin_src calc :var x=5\nx*2\n#+end_src\n",
36 "#+begin_src calc :var x=5\n2 x\n#+end_src\n",
37 "#+begin_src calc :var x=5\n[x, 2 x]\n#+end_src\n",
38 "#+begin_src calc :var x=5\nx\nx\n'*\n#+end_src\n",
39 "#+begin_src calc :var x=2.5\nx\n2\n'*\n#+end_src\n",
40 "#+begin_src calc :var x=0.1\nx * 3\n#+end_src\n",
41 "#+begin_src calc :var x=1e20\nx\n#+end_src\n",
42 "#+begin_src calc :var xy=5 x=2\nxy\n#+end_src\n",
43 "#+begin_src calc :var x=5 :results table\nx\n#+end_src\n",
44 "#+begin_src calc\nx + 1\n#+end_src\n",
45 "#+begin_src calc\n2 x + 3 x\n#+end_src\n",
46 "#+begin_src calc\n[1, 2, 3]\n#+end_src\n",
47 "#+begin_src calc\n[[1, 2], [3, 4]]\n#+end_src\n",
48 "#+begin_src calc\n[1, [2, 3]]\n#+end_src\n",
49 "#+begin_src calc\n[[1, 2], [3]]\n#+end_src\n",
50 "#+begin_src calc :results scalar\n[1, 2, 3]\n#+end_src\n",
51 "#+begin_src calc :results output\n1+1\n#+end_src\n",
52 "#+begin_src calc :results verbatim\n1/4\n#+end_src\n",
53 "#+begin_src calc :var v='(1 2 3)\nvsum(v)\n#+end_src\n",
54 "#+begin_src calc :var v='(1 2 3)\nv\n#+end_src\n",
55 table + "#+begin_src calc :var m=tb\nm\n#+end_src\n",
56 "#+begin_src calc :prologue \"2\" :epilogue \"'*\"\n3\n#+end_src\n",
57 "#+NAME: hd\n| a | b |\n|---+---|\n| 1 | 2 |\n| 3 | 4 |\n\n#+begin_src calc :var m=hd\nm\n#+end_src\n",
58 // Errors in Emacs: the result isn't written.
59 "#+begin_src calc :var x=5\n3\n'+\n#+end_src\n",
60 "#+begin_src calc :var x=5\nx*2\n3\n'+\n#+end_src\n",
61 "#+begin_src calc\n'+\n#+end_src\n",
62 "#+begin_src calc\n#+end_src\n",
63 ]
64
65 static func caret(_ text: String) -> Int { (text as NSString).range(of: "#+begin_src").location + 2 }
66
67 /// The block run with `Babel.evaluateCalc`.
68 static func native(_ text: String) throws -> (text: String, failure: String?) {
69 try TestBabelRunner.execute(text, caret: caret(text), directory: FileManager.default.temporaryDirectory, native: true)
70 }
71
72 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
73 func blocksMatchEmacs() throws {
74 let folder = FileManager.default.temporaryDirectory
75 var emacsCases: [EmacsOracle.Case] = []
76 var ours: [(text: String, failure: String?)] = []
77 var fallback: [(text: String, failure: String?)] = []
78 for text in Self.cases {
79 ours.append(try Self.native(text))
80 fallback.append(try TestBabelRunner.execute(text, caret: Self.caret(text), directory: folder))
81 emacsCases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(Self.caret(text), in: text), form: """
82 (progn (require 'ob-calc) (setq org-confirm-babel-evaluate nil)
83 ;; A new stack, as in a new Emacs.
84 (save-window-excursion (calc) (when (> (calc-stack-size) 0) (calc-pop (calc-stack-size))) (calc-quit))
85 (org-babel-execute-src-block))
86 """))
87 }
88 let emacs = try EmacsOracle.run(emacsCases)
89 for (i, theirs) in emacs.enumerated() {
90 #expect(ours[i].text == theirs.text, "case \(i):\n\(Self.cases[i])\nours (\(ours[i].failure ?? "")):\n\(ours[i].text)\nemacs (\(theirs.error)):\n\(theirs.text)")
91 #expect((ours[i].failure != nil) == !theirs.error.isEmpty, "case \(i): ours \(ours[i].failure ?? "ok"), emacs \(theirs.error)")
92 #expect(fallback[i].text == theirs.text, "case \(i) in Emacs:\n\(Self.cases[i])\nours:\n\(fallback[i].text)\nemacs:\n\(theirs.text)")
93 }
94 }
95
96 /// What Calc here doesn't do as Emacs's does is refused, with the reason.
97 @Test func refusals() throws {
98 let refused: [(String, String)] = [
99 ("#+begin_src calc\n1\n'x\n#+end_src\n", "stack command 'x"),
100 ("#+begin_src calc\n1\n2\n'TAB\n#+end_src\n", "stack command 'TAB"),
101 ("#+begin_src calc :var s=\"abc\"\ns\n#+end_src\n", "value of :var s"),
102 ("#+begin_src calc :var v='(1.5 2)\nv\n#+end_src\n", "value of :var v"),
103 ("#+begin_src calc :var v='(1)\nv\n#+end_src\n", "value of :var v"),
104 ("#+begin_src calc :var e=5\ne\n#+end_src\n", "value of :var e"),
105 ("#+begin_src calc :var my_x=5\nmy_x\n#+end_src\n", "value of :var my_x"),
106 ("#+begin_src calc :prologue 2\n3\n#+end_src\n", "numeric :prologue or :epilogue"),
107 ("#+begin_src calc\n2^100\n#+end_src\n", "integer size"),
108 ("#+begin_src calc\n[]\n#+end_src\n", "empty vector"),
109 (Self.table + "#+begin_src calc :var m=tb\ndet(m)\n#+end_src\n", "function det"),
110 ]
111 for (text, reason) in refused {
112 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [Self.caret(text)..<Self.caret(text)])
113 guard case .success(let job) = Babel.plan(context) else { Issue.record("not planned: \(text)"); continue }
114 #expect(job.runner == .emacs)
115 #expect(throws: Calc.Unsupported.self, "\(text)") { try Babel.evaluateCalc(job) }
116 do {
117 _ = try Babel.evaluateCalc(job)
118 } catch let error as Calc.Unsupported {
119 #expect(error.reason == reason, "\(text)")
120 }
121 }
122 }
123}
Tests/OrgCoreTests/BabelTests.swift +11 −2
@@ -11,7 +11,12 @@ enum TestBabelRunner {
11 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 11 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
12 defer { try? FileManager.default.removeItem(at: folder) } 12 defer { try? FileManager.default.removeItem(at: folder) }
13 let resultFile = folder.appendingPathComponent("result") 13 let resultFile = folder.appendingPathComponent("result")
14 let input = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path) 14 var input = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path)
15 for (token, contents) in job.dataFiles {
16 let file = folder.appendingPathComponent(token)
17 try contents.write(to: file, atomically: true, encoding: .utf8)
18 input = input.replacingOccurrences(of: token, with: file.path)
19 }
15 let process = Process() 20 let process = Process()
16 process.executableURL = URL(fileURLWithPath: "/usr/bin/env") 21 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
17 switch job.runner { 22 switch job.runner {
@@ -42,7 +47,8 @@ enum TestBabelRunner {
42 try stdin.fileHandleForWriting.close() 47 try stdin.fileHandleForWriting.close()
43 let data = stdout.fileHandleForReading.readDataToEndOfFile() 48 let data = stdout.fileHandleForReading.readDataToEndOfFile()
44 process.waitUntilExit() 49 process.waitUntilExit()
45 return BabelOutput(stdout: String(decoding: data, as: UTF8.self), resultFile: try? String(contentsOf: resultFile, encoding: .utf8)) 50 return BabelOutput(stdout: String(decoding: data, as: UTF8.self), resultFile: try? String(contentsOf: resultFile, encoding: .utf8),
51 status: process.terminationStatus)
46 } 52 }
47 53
48 /// Plans, runs and finishes the block at `caret`: the new text, or the failure. 54 /// Plans, runs and finishes the block at `caret`: the new text, or the failure.
@@ -50,6 +56,7 @@ enum TestBabelRunner {
50 static func execute(_ text: String, caret: Int, directory: URL, native: Bool = false) throws -> (text: String, failure: String?) { 56 static func execute(_ text: String, caret: Int, directory: URL, native: Bool = false) throws -> (text: String, failure: String?) {
51 func run(_ job: BabelJob, directory: URL) throws -> BabelOutput { 57 func run(_ job: BabelJob, directory: URL) throws -> BabelOutput {
52 guard native else { return try TestBabelRunner.run(job, directory: directory) } 58 guard native else { return try TestBabelRunner.run(job, directory: directory) }
59 if job.calc != nil { return try Babel.evaluateCalc(job) }
53 guard let output = try Babel.evaluateNatively(job) else { throw NativeUnsupported() } 60 guard let output = try Babel.evaluateNatively(job) else { throw NativeUnsupported() }
54 return output 61 return output
55 } 62 }
@@ -70,6 +77,8 @@ enum TestBabelRunner {
70 guard case .message(let message) = failure else { return (text, nil) } 77 guard case .message(let message) = failure else { return (text, nil) }
71 return (text, message) 78 return (text, message)
72 } 79 }
80 // A calc block's error in Emacs.
81 if job.calc != nil, output.status != 0 { return (text, "error") }
73 if let file = Babel.fileResult(job, output: output) { 82 if let file = Babel.fileResult(job, output: output) {
74 try file.contents.write(to: directory.appendingPathComponent(file.path), atomically: true, encoding: .utf8) 83 try file.contents.write(to: directory.appendingPathComponent(file.path), atomically: true, encoding: .utf8)
75 } 84 }