Grow the Emacs Lisp evaluator; run it when Emacs is missing !414
22 files changed, +2211 −153
Layout: unified · split
Sources/OrgApp/TableReason.swift +55 −1
| @@ -25,15 +25,69 @@ public enum TableReason { | |||
| 25 | 25 | ||
| 26 | /// `Elisp.Unsupported`'s reasons. | 26 | /// `Elisp.Unsupported`'s reasons. |
| 27 | static func lisp(_ what: String) -> String? { | 27 | static func lisp(_ what: String) -> String? { |
| 28 | if what == "integer size" { return fixed(what) } | 28 | let comment: StaticString = "Why a table needs Emacs: something a Lisp formula does" |
| 29 | switch what { | ||
| 30 | case "integer size": return fixed(what) | ||
| 31 | case "a closure as a list": return String(localized: "a closure as a list", comment: comment) | ||
| 32 | case "capitalize past ASCII": return String(localized: "capitalize past ASCII", comment: comment) | ||
| 33 | case "case folding past ASCII": return String(localized: "case folding past ASCII", comment: comment) | ||
| 34 | case "cl-loop destructuring": return String(localized: "cl-loop destructuring", comment: comment) | ||
| 35 | case "cl-loop with collect and sum": return String(localized: "cl-loop with collect and sum", comment: comment) | ||
| 36 | case "cl-loop without for": return String(localized: "cl-loop without for", comment: comment) | ||
| 37 | case "float times": return String(localized: "float times", comment: comment) | ||
| 38 | case "float-time of picoseconds": return String(localized: "float-time of picoseconds", comment: comment) | ||
| 39 | case "org-time-string-to-absolute with a day": return String(localized: "org-time-string-to-absolute with a day", comment: comment) | ||
| 40 | case "random with a seed": return String(localized: "random with a seed", comment: comment) | ||
| 41 | case "regexp classes on text past ASCII": return String(localized: "regexp classes on text past ASCII", comment: comment) | ||
| 42 | case "replace-match case past ASCII": return String(localized: "replace-match case past ASCII", comment: comment) | ||
| 43 | case "replace-match in a buffer": return String(localized: "replace-match in a buffer", comment: comment) | ||
| 44 | case "replace-regexp-in-string from the end": return String(localized: "replace-regexp-in-string from the end", comment: comment) | ||
| 45 | case "seq-uniq with a test": return String(localized: "seq-uniq with a test", comment: comment) | ||
| 46 | case "sort on a string": return String(localized: "sort on a string", comment: comment) | ||
| 47 | case "the data of this error": return String(localized: "the data of this error", comment: comment) | ||
| 48 | default: break | ||
| 49 | } | ||
| 29 | func value(_ prefix: String) -> String? { what.hasPrefix(prefix) ? String(what.dropFirst(prefix.count)) : nil } | 50 | func value(_ prefix: String) -> String? { what.hasPrefix(prefix) ? String(what.dropFirst(prefix.count)) : nil } |
| 51 | func split(_ text: String, _ separator: String) -> (String, String)? { | ||
| 52 | guard let range = text.range(of: separator) else { return nil } | ||
| 53 | return (String(text[..<range.lowerBound]), String(text[range.upperBound...])) | ||
| 54 | } | ||
| 30 | if let name = value("function ") { return String(localized: "function \(name)", comment: "Why a table needs Emacs: a Calc function") } | 55 | if let name = value("function ") { return String(localized: "function \(name)", comment: "Why a table needs Emacs: a Calc function") } |
| 31 | if let time = value("time value ") { return String(localized: "time value \(time)", comment: "Why a table needs Emacs: a Lisp time value") } | 56 | if let time = value("time value ") { return String(localized: "time value \(time)", comment: "Why a table needs Emacs: a Lisp time value") } |
| 32 | if let number = value("date number ") { return String(localized: "date number \(number)", comment: "Why a table needs Emacs: a Lisp date number") } | 57 | if let number = value("date number ") { return String(localized: "date number \(number)", comment: "Why a table needs Emacs: a Lisp date number") } |
| 58 | if let text = value("date-to-time of ") { return String(localized: "date-to-time of \(text)", comment: comment) } | ||
| 59 | if let parts = value("date ") { return String(localized: "date \(parts)", comment: comment) } | ||
| 60 | if let text = value("time string ") { return String(localized: "time string \(text)", comment: comment) } | ||
| 61 | if let zone = value("format-time-string zone ") { return String(localized: "format-time-string zone \(zone)", comment: comment) } | ||
| 62 | if let code = value("format-time-string ") { return String(localized: "format-time-string \(code)", comment: comment) } | ||
| 63 | if let clause = value("cl-loop ") { return String(localized: "cl-loop \(clause)", comment: comment) } | ||
| 64 | if let names = value("condition-case on ") { return String(localized: "condition-case on \(names)", comment: comment) } | ||
| 65 | if let pattern = value("pcase pattern ") { return String(localized: "pcase pattern \(pattern)", comment: comment) } | ||
| 66 | if let name = value("let-alist ") { return String(localized: "let-alist \(name)", comment: comment) } | ||
| 67 | if let text = value("string-width of ") { return String(localized: "string-width of \(text)", comment: comment) } | ||
| 68 | if let rest = value("regexp "), let parts = split(rest, " in ") { | ||
| 69 | return String(localized: "regexp \(parts.0) in \(parts.1)", comment: "Why a table needs Emacs: part of a Lisp regular expression") | ||
| 70 | } | ||
| 71 | if let rest = value("value< on "), let parts = split(rest, " and ") { | ||
| 72 | return String(localized: "value< on \(parts.0) and \(parts.1)", comment: comment) | ||
| 73 | } | ||
| 33 | if what.hasSuffix(" on a place") { | 74 | if what.hasSuffix(" on a place") { |
| 34 | let name = String(what.dropLast(" on a place".count)) | 75 | let name = String(what.dropLast(" on a place".count)) |
| 35 | return String(localized: "\(name) on a place", comment: "Why a table needs Emacs: a Lisp function used on a variable") | 76 | return String(localized: "\(name) on a place", comment: "Why a table needs Emacs: a Lisp function used on a variable") |
| 36 | } | 77 | } |
| 78 | if what.hasSuffix(" on a closure") { | ||
| 79 | let name = String(what.dropLast(" on a closure".count)) | ||
| 80 | return String(localized: "\(name) on a closure", comment: "Why a table needs Emacs: a Lisp function that looks inside a closure") | ||
| 81 | } | ||
| 82 | if what.hasSuffix(" on a list another value shares") { | ||
| 83 | let name = String(what.dropLast(" on a list another value shares".count)) | ||
| 84 | return String(localized: "\(name) on a list another value shares", comment: "Why a table needs Emacs: a Lisp function that changes a shared list") | ||
| 85 | } | ||
| 86 | if what.hasSuffix(" in a buffer") { | ||
| 87 | let name = String(what.dropLast(" in a buffer".count)) | ||
| 88 | return String(localized: "\(name) in a buffer", comment: comment) | ||
| 89 | } | ||
| 90 | if let parts = split(what, " with ") { return String(localized: "\(parts.0) with \(parts.1)", comment: comment) } | ||
| 37 | return nil | 91 | return nil |
| 38 | } | 92 | } |
| 39 | 93 | ||
Sources/OrgCore/Agenda/DiarySexp.swift +15 −7
| @@ -125,9 +125,8 @@ public enum DiarySexp { | |||
| 125 | 125 | ||
| 126 | static func optional(_ args: [Sexp], _ i: Int) -> Sexp { i < args.count ? args[i] : .nil } | 126 | static func optional(_ args: [Sexp], _ i: Int) -> Sexp { i < args.count ? args[i] : .nil } |
| 127 | 127 | ||
| 128 | static func define(_ lisp: Elisp) { | 128 | /// The calendar functions, which don't depend on the diary entry. |
| 129 | func date() throws -> Sexp { try lisp.value("date") } | 129 | static func defineCalendar(_ lisp: Elisp) { |
| 130 | func entry() throws -> Sexp { try lisp.value("entry") } | ||
| 131 | func arity(_ args: [Sexp], _ range: ClosedRange<Int>, _ name: String) throws { | 130 | func arity(_ args: [Sexp], _ range: ClosedRange<Int>, _ name: String) throws { |
| 132 | try Elisp.arity(args, range, name) | 131 | try Elisp.arity(args, range, name) |
| 133 | } | 132 | } |
| @@ -180,7 +179,20 @@ public enum DiarySexp { | |||
| 180 | let thursday = day - (Days.weekday(day) + 6) % 7 + 3 | 179 | let thursday = day - (Days.weekday(day) + 6) % 7 + 3 |
| 181 | return .list([.integer(Days.isoWeek(day)), .integer(Days.weekday(day)), .integer(Days.date(thursday).year)]) | 180 | return .list([.integer(Days.isoWeek(day)), .integer(Days.weekday(day)), .integer(Days.date(thursday).year)]) |
| 182 | } | 181 | } |
| 182 | lisp.define("calendar-check-holidays") { _, args in | ||
| 183 | try arity(args, 1...1, "calendar-check-holidays") | ||
| 184 | return Elisp.list(holidays(try absolute(args[0])).map(Sexp.string)) | ||
| 185 | } | ||
| 186 | } | ||
| 183 | 187 | ||
| 188 | static func define(_ lisp: Elisp) { | ||
| 189 | func date() throws -> Sexp { try lisp.value("date") } | ||
| 190 | func entry() throws -> Sexp { try lisp.value("entry") } | ||
| 191 | func arity(_ args: [Sexp], _ range: ClosedRange<Int>, _ name: String) throws { | ||
| 192 | try Elisp.arity(args, range, name) | ||
| 193 | } | ||
| 194 | |||
| 195 | defineCalendar(lisp) | ||
| 184 | lisp.define("diary-ordinal-suffix") { _, args in | 196 | lisp.define("diary-ordinal-suffix") { _, args in |
| 185 | try arity(args, 1...1, "diary-ordinal-suffix") | 197 | try arity(args, 1...1, "diary-ordinal-suffix") |
| 186 | return .string(try ordinalSuffix(try Elisp.int(args[0]))) | 198 | return .string(try ordinalSuffix(try Elisp.int(args[0]))) |
| @@ -299,10 +311,6 @@ public enum DiarySexp { | |||
| 299 | lisp.define("org-cyclic") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-cyclic", args) } } | 311 | lisp.define("org-cyclic") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-cyclic", args) } } |
| 300 | lisp.define("org-block") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-block", args) } } | 312 | lisp.define("org-block") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-block", args) } } |
| 301 | lisp.define("org-date") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-date", args) } } | 313 | lisp.define("org-date") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-date", args) } } |
| 302 | lisp.define("calendar-check-holidays") { _, args in | ||
| 303 | try arity(args, 1...1, "calendar-check-holidays") | ||
| 304 | return Elisp.list(holidays(try absolute(args[0])).map(Sexp.string)) | ||
| 305 | } | ||
| 306 | lisp.define("org-calendar-holiday") { _, _ in | 314 | lisp.define("org-calendar-holiday") { _, _ in |
| 307 | let names = holidays(try absolute(try date())) | 315 | let names = holidays(try absolute(try date())) |
| 308 | return names.isEmpty ? .nil : .string(names.joined(separator: "; ")) | 316 | return names.isEmpty ? .nil : .string(names.joined(separator: "; ")) |
Sources/OrgCore/Capture/CaptureLisp.swift +1 −24
| @@ -82,14 +82,7 @@ extension Capture { | |||
| 82 | self.answers = answers[...] | 82 | self.answers = answers[...] |
| 83 | lisp.set("user-full-name", .string(context.userName)) | 83 | lisp.set("user-full-name", .string(context.userName)) |
| 84 | lisp.define("user-full-name") { [context] _, _ in .string(context.userName) } | 84 | lisp.define("user-full-name") { [context] _, _ in .string(context.userName) } |
| 85 | lisp.define("current-time") { [context] _, _ in Self.time(context.now) } | 85 | lisp.standardTime(now: { [context] in context.now }, calendar: context.calendar) |
| 86 | lisp.define("format-time-string") { [context] _, args in | ||
| 87 | guard let format = args.first?.string else { throw Elisp.Signal(message: "Wrong type argument: stringp, \(args.first?.description ?? "nil")") } | ||
| 88 | let date = try args.count > 1 && !Elisp.isNil(args[1]) ? Self.date(args[1]) : context.now | ||
| 89 | var at = context | ||
| 90 | at.now = date | ||
| 91 | return .string(Capture.strftime(format, at)) | ||
| 92 | } | ||
| 93 | lisp.define("read-string") { [unowned self] _, args in | 86 | lisp.define("read-string") { [unowned self] _, args in |
| 94 | let prompt = args.first?.string ?? "" | 87 | let prompt = args.first?.string ?? "" |
| 95 | let initial = args.count > 1 ? args[1].string : nil | 88 | let initial = args.count > 1 ? args[1].string : nil |
| @@ -102,22 +95,6 @@ extension Capture { | |||
| 102 | } | 95 | } |
| 103 | } | 96 | } |
| 104 | 97 | ||
| 105 | /// `(HIGH LOW USEC PSEC)`. | ||
| 106 | static func time(_ date: Date) -> Sexp { | ||
| 107 | let seconds = Int(date.timeIntervalSince1970.rounded(.down)) | ||
| 108 | let micro = Int((date.timeIntervalSince1970 - Double(seconds)) * 1_000_000) | ||
| 109 | return .list([.integer(seconds >> 16), .integer(seconds & 0xFFFF), .integer(micro), .integer(0)]) | ||
| 110 | } | ||
| 111 | |||
| 112 | static func date(_ time: Sexp) throws -> Date { | ||
| 113 | if let seconds = time.integer { return Date(timeIntervalSince1970: Double(seconds)) } | ||
| 114 | guard let parts = time.elements, parts.count >= 2, let high = parts[0].integer, let low = parts[1].integer else { | ||
| 115 | throw Elisp.Unsupported(what: "time value \(time.description)") | ||
| 116 | } | ||
| 117 | let micro = parts.count > 2 ? Double(parts[2].integer ?? 0) / 1_000_000 : 0 | ||
| 118 | return Date(timeIntervalSince1970: Double(high << 16 + low) + micro) | ||
| 119 | } | ||
| 120 | |||
| 121 | /// The value to insert for the form `text`: a string, or "" for nil. | 98 | /// The value to insert for the form `text`: a string, or "" for nil. |
| 122 | func evaluate(_ text: String) -> Result<String, Failure> { | 99 | func evaluate(_ text: String) -> Result<String, Failure> { |
| 123 | let form: Sexp | 100 | let form: Sexp |
Sources/OrgCore/Compute/BabelLanguages.swift +6
| @@ -92,10 +92,16 @@ extension Babel { | |||
| 92 | /// doesn't have. | 92 | /// doesn't have. |
| 93 | public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? { | 93 | public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? { |
| 94 | guard let form = job.lispForm, let sexp = try? LispReader.readFirst(form).sexp else { return nil } | 94 | guard let form = job.lispForm, let sexp = try? LispReader.readFirst(form).sexp else { return nil } |
| 95 | // As `emacs -Q --batch -l` runs `emacsScript`: lexical binding, in `*scratch*`. | ||
| 95 | let lisp = Elisp() | 96 | let lisp = Elisp() |
| 97 | lisp.lexical = true | ||
| 98 | lisp.syntax = .emacsLisp | ||
| 99 | lisp.standardTime() | ||
| 96 | let result: Sexp | 100 | let result: Sexp |
| 97 | do { | 101 | do { |
| 98 | result = try lisp.eval(sexp) | 102 | result = try lisp.eval(sexp) |
| 103 | // Emacs prints closures as `#[ARGS BODY ENV]`. | ||
| 104 | if Elisp.containsClosure(result) { return nil } | ||
| 99 | } catch is Elisp.Unsupported { | 105 | } catch is Elisp.Unsupported { |
| 100 | return nil | 106 | return nil |
| 101 | } catch { | 107 | } catch { |
Sources/OrgCore/Compute/TableFormulas.swift +1
| @@ -656,6 +656,7 @@ extension EmacsBuffer { | |||
| 656 | /// `(eval (eval (read form)))` for a Lisp formula; an error is `#ERROR`. | 656 | /// `(eval (eval (read form)))` for a Lisp formula; an error is `#ERROR`. |
| 657 | func evalLisp(_ form: String, duration: DurationFormat?) throws -> String { | 657 | func evalLisp(_ form: String, duration: DurationFormat?) throws -> String { |
| 658 | let lisp = Elisp() | 658 | let lisp = Elisp() |
| 659 | lisp.standardTime() | ||
| 659 | Self.defineLookups(lisp) | 660 | Self.defineLookups(lisp) |
| 660 | let value: Sexp | 661 | let value: Sexp |
| 661 | do { | 662 | do { |
Sources/OrgCore/Config/Elisp.swift +331 −96
| @@ -1,8 +1,8 @@ | |||
| 1 | import Foundation | 1 | import Foundation |
| 2 | 2 | ||
| 3 | /// A small Emacs Lisp evaluator over `Sexp` values: the special forms and functions diary | 3 | /// A small Emacs Lisp evaluator over `Sexp` values: the special forms and functions diary |
| 4 | /// sexps and table formulas use, with dynamic binding. A function or form it doesn't have | 4 | /// sexps and table formulas use, with dynamic binding unless `lexical` is set. A function or |
| 5 | /// throws `Unsupported`; errors Emacs would signal throw `Signal`. | 5 | /// form it doesn't have throws `Unsupported`; errors Emacs would signal throw `Signal`. |
| 6 | public final class Elisp { | 6 | public final class Elisp { |
| 7 | public struct Unsupported: Error, Equatable, CustomStringConvertible { | 7 | public struct Unsupported: Error, Equatable, CustomStringConvertible { |
| 8 | public let what: String | 8 | public let what: String |
| @@ -11,14 +11,64 @@ public final class Elisp { | |||
| 11 | 11 | ||
| 12 | public struct Signal: Error, Equatable, CustomStringConvertible { | 12 | public struct Signal: Error, Equatable, CustomStringConvertible { |
| 13 | public let message: String | 13 | public let message: String |
| 14 | /// The error symbol, by default from the message, and its data when known: what | ||
| 15 | /// `condition-case` binds. | ||
| 16 | public let symbol: String? | ||
| 17 | public let data: [Sexp]? | ||
| 14 | public var description: String { message } | 18 | public var description: String { message } |
| 19 | |||
| 20 | public init(message: String, symbol: String? = nil, data: [Sexp]? = nil) { | ||
| 21 | self.message = message | ||
| 22 | self.symbol = symbol ?? Self.symbols.first(where: { message.hasPrefix($0.prefix) })?.symbol | ||
| 23 | self.data = data ?? (message == "Arithmetic error" ? [] : nil) | ||
| 24 | } | ||
| 25 | |||
| 26 | static let symbols: [(prefix: String, symbol: String)] = [ | ||
| 27 | ("Arithmetic error", "arith-error"), ("Args out of range", "args-out-of-range"), ("Invalid function", "invalid-function"), | ||
| 28 | ("Symbol’s value as variable is void", "void-variable"), ("Wrong number of arguments", "wrong-number-of-arguments"), | ||
| 29 | ("Wrong type argument", "wrong-type-argument"), | ||
| 30 | ] | ||
| 15 | } | 31 | } |
| 16 | 32 | ||
| 33 | /// What `condition-case` binds its variable to for an error whose data isn't known. | ||
| 34 | static let unknownError = Sexp.symbol("\u{0}error") | ||
| 35 | |||
| 17 | public typealias Builtin = (Elisp, [Sexp]) throws -> Sexp | 36 | public typealias Builtin = (Elisp, [Sexp]) throws -> Sexp |
| 18 | 37 | ||
| 19 | private var scopes: [[String: Sexp]] = [[:]] | 38 | /// A set of bindings, shared by the closures created while it is in scope. |
| 39 | final class Frame { | ||
| 40 | var vars: [String: Sexp] | ||
| 41 | init(_ vars: [String: Sexp] = [:]) { self.vars = vars } | ||
| 42 | } | ||
| 43 | |||
| 44 | /// The global frame, then the visible local ones, innermost last. | ||
| 45 | var scopes: [Frame] = [Frame()] | ||
| 46 | /// `lexical-binding`: lambdas close over the local frames, and only special variables | ||
| 47 | /// (the host's and `defvar`'s) are bound dynamically. | ||
| 48 | public var lexical = false | ||
| 49 | /// Variables bound dynamically when `lexical` is set. | ||
| 50 | var specials: Set<String> = [] | ||
| 51 | /// Under lexical binding, running a lambda list, which Emacs evaluates with dynamic binding: | ||
| 52 | /// every variable is bound dynamically and lambdas aren't closures. | ||
| 53 | private var dynamicOnly = false | ||
| 54 | /// The functions `defun` defined, which may take closures. | ||
| 55 | var defined: Set<String> = [] | ||
| 56 | /// Each closure's captured frames, by the id in its `(closure ID ARGS . BODY)` value. | ||
| 57 | var closures: [[Frame]] = [] | ||
| 58 | /// The scopes of the callers of running closures, and the global values that dynamic | ||
| 59 | /// bindings of special variables hide. | ||
| 60 | private var hiddenScopes: [[Frame]] = [] | ||
| 61 | private var hiddenValues: [Sexp] = [] | ||
| 62 | /// Values held while a form evaluates: each call's evaluated arguments, innermost last. | ||
| 63 | private var pending: [[Sexp]] = [] | ||
| 64 | /// The variable an in-place function's first argument named, for that function to read. | ||
| 65 | private var inPlaceVariable: String? | ||
| 66 | /// The syntax table regexps and case conversion use. | ||
| 67 | var syntax = ElispSyntax.org { | ||
| 68 | didSet { regexes = [:] } | ||
| 69 | } | ||
| 20 | private var functions: [String: Builtin] = [:] | 70 | private var functions: [String: Builtin] = [:] |
| 21 | private var steps = 0 | 71 | var steps = 0 |
| 22 | static let stepLimit = 1_000_000 | 72 | static let stepLimit = 1_000_000 |
| 23 | /// Nested evaluations, as `max-lisp-eval-depth` limits them. | 73 | /// Nested evaluations, as `max-lisp-eval-depth` limits them. |
| 24 | private var depth = 0 | 74 | private var depth = 0 |
| @@ -32,35 +82,154 @@ public final class Elisp { | |||
| 32 | public var standardOutput: String { outputs[0] } | 82 | public var standardOutput: String { outputs[0] } |
| 33 | /// What `message` wrote. | 83 | /// What `message` wrote. |
| 34 | public private(set) var messages = "" | 84 | public private(set) var messages = "" |
| 85 | /// What the last `string-match` matched: each group's range in characters. | ||
| 86 | var matchData: [Range<Int>?] = [] | ||
| 87 | var regexes: [String: ElispRegex] = [:] | ||
| 35 | 88 | ||
| 36 | public init() { | 89 | public init() { |
| 37 | Self.core(self) | 90 | Self.core(self) |
| 91 | Self.library(self) | ||
| 92 | Self.regexFunctions(self) | ||
| 38 | } | 93 | } |
| 39 | 94 | ||
| 40 | /// Defines or replaces a function. | 95 | /// Defines or replaces a function. |
| 41 | public func define(_ name: String, _ function: @escaping Builtin) { functions[name] = function } | 96 | public func define(_ name: String, _ function: @escaping Builtin) { functions[name] = function } |
| 42 | 97 | ||
| 43 | /// Sets a global variable. | 98 | /// Sets a global variable, which is special. |
| 44 | public func set(_ name: String, _ value: Sexp) { scopes[0][name] = value } | 99 | public func set(_ name: String, _ value: Sexp) { |
| 100 | scopes[0].vars[name] = value | ||
| 101 | specials.insert(name) | ||
| 102 | } | ||
| 45 | 103 | ||
| 46 | public func value(_ name: String) throws -> Sexp { | 104 | public func value(_ name: String) throws -> Sexp { |
| 47 | for scope in scopes.reversed() { if let v = scope[name] { return v } } | 105 | for scope in scopes.reversed() { |
| 48 | throw Signal(message: "Symbol’s value as variable is void: \(name)") | 106 | guard let v = scope.vars[name] else { continue } |
| 107 | if v == Self.unknownError { throw Unsupported(what: "the data of this error") } | ||
| 108 | return v | ||
| 109 | } | ||
| 110 | throw Signal(message: "Symbol’s value as variable is void: \(name)", data: [.symbol(name)]) | ||
| 49 | } | 111 | } |
| 50 | 112 | ||
| 51 | /// Evaluates `body` with `bindings` added. | 113 | /// Evaluates `body` with `bindings` added: in a new frame, or for special variables under |
| 114 | /// lexical binding, as their global values until `body` returns. | ||
| 52 | public func binding<T>(_ bindings: [String: Sexp], _ body: () throws -> T) rethrows -> T { | 115 | public func binding<T>(_ bindings: [String: Sexp], _ body: () throws -> T) rethrows -> T { |
| 53 | scopes.append(bindings) | 116 | try binding(Frame(bindings), body) |
| 54 | defer { scopes.removeLast() } | 117 | } |
| 118 | |||
| 119 | func binding<T>(_ frame: Frame, _ body: () throws -> T) rethrows -> T { | ||
| 120 | let dynamic = dynamicOnly ? Array(frame.vars.keys) : lexical ? frame.vars.keys.filter(specials.contains) : [] | ||
| 121 | var saved: [(String, Sexp?)] = [] | ||
| 122 | for name in dynamic { | ||
| 123 | saved.append((name, scopes[0].vars[name])) | ||
| 124 | if let old = scopes[0].vars[name] { hiddenValues.append(old) } | ||
| 125 | scopes[0].vars[name] = frame.vars.removeValue(forKey: name) | ||
| 126 | } | ||
| 127 | scopes.append(frame) | ||
| 128 | defer { | ||
| 129 | scopes.removeLast() | ||
| 130 | for (name, old) in saved.reversed() { | ||
| 131 | scopes[0].vars[name] = old | ||
| 132 | if old != nil { hiddenValues.removeLast() } | ||
| 133 | } | ||
| 134 | } | ||
| 55 | return try body() | 135 | return try body() |
| 56 | } | 136 | } |
| 57 | 137 | ||
| 58 | private func assign(_ name: String, _ v: Sexp) { | 138 | func assign(_ name: String, _ v: Sexp) { |
| 59 | for i in scopes.indices.reversed() where scopes[i][name] != nil { | 139 | for scope in scopes.reversed() where scope.vars[name] != nil { |
| 60 | scopes[i][name] = v | 140 | scope.vars[name] = v |
| 141 | return | ||
| 142 | } | ||
| 143 | scopes[0].vars[name] = v | ||
| 144 | } | ||
| 145 | |||
| 146 | /// A lambda as `function` makes it: a closure over the local frames under lexical | ||
| 147 | /// binding, else the list itself. | ||
| 148 | func closure(_ lambda: Sexp) -> Sexp { | ||
| 149 | guard lexical, !dynamicOnly, case .list(let items) = lambda, items.first == .symbol("lambda"), items.count >= 2 else { return lambda } | ||
| 150 | closures.append(Array(scopes.dropFirst())) | ||
| 151 | return .list([.symbol("closure"), .integer(closures.count - 1)] + items.dropFirst()) | ||
| 152 | } | ||
| 153 | |||
| 154 | static func isClosure(_ v: Sexp) -> Bool { | ||
| 155 | if case .list(let items) = v, items.count >= 3, items[0] == .symbol("closure"), items[1].integer != nil { return true } | ||
| 156 | return false | ||
| 157 | } | ||
| 158 | |||
| 159 | /// Builtins that may take closures as arguments, from the given position on: those that | ||
| 160 | /// call them or only hold them. Emacs's closures aren't lists, as they are here. | ||
| 161 | static let closureArguments: [String: Int] = [ | ||
| 162 | "funcall": 0, "apply": 0, "mapcar": 0, "mapc": 0, "mapconcat": 0, "seq-map": 0, "seq-filter": 0, "seq-remove": 0, | ||
| 163 | "seq-reduce": 0, "cl-reduce": 0, "cl-remove-if": 0, "cl-remove-if-not": 0, "cl-find": 1, "cl-position": 1, "sort": 0, | ||
| 164 | "replace-regexp-in-string": 1, "list": 0, "identity": 0, "ignore": 0, "null": 0, "not": 0, | ||
| 165 | ] | ||
| 166 | /// Builtins that compare or print what lists hold. | ||
| 167 | static let closureInspectors: Set<String> = [ | ||
| 168 | "equal", "eq", "eql", "member", "memq", "memql", "assoc", "assq", "delete", "delq", "delete-dups", "seq-uniq", | ||
| 169 | "format", "format-message", "message", "error", "user-error", "prin1-to-string", "princ", "prin1", "print", | ||
| 170 | ] | ||
| 171 | |||
| 172 | /// Refuses a builtin call that would look inside a closure. | ||
| 173 | func refuseClosures(_ name: String, _ args: [Sexp]) throws { | ||
| 174 | guard !closures.isEmpty, !defined.contains(name) else { return } | ||
| 175 | for (i, arg) in args.enumerated() { | ||
| 176 | if Self.isClosure(arg) ? i < Self.closureArguments[name] ?? .max : Self.closureInspectors.contains(name) && Self.containsClosure(arg) { | ||
| 177 | throw Unsupported(what: "\(name) on a closure") | ||
| 178 | } | ||
| 179 | } | ||
| 180 | } | ||
| 181 | |||
| 182 | /// Whether `v` contains a closure, which Emacs prints in a form this evaluator doesn't. | ||
| 183 | static func containsClosure(_ v: Sexp) -> Bool { | ||
| 184 | switch v { | ||
| 185 | case .list(let items): isClosure(v) || items.contains(where: containsClosure) | ||
| 186 | case .dotted(let items, let last): items.contains(where: containsClosure) || containsClosure(last) | ||
| 187 | case .vector(let items): items.contains(where: containsClosure) | ||
| 188 | default: false | ||
| 189 | } | ||
| 190 | } | ||
| 191 | |||
| 192 | /// The variable named by the first argument of the function being called from `eval`, read | ||
| 193 | /// once. | ||
| 194 | func takeInPlaceVariable() -> String? { | ||
| 195 | defer { inPlaceVariable = nil } | ||
| 196 | return inPlaceVariable | ||
| 197 | } | ||
| 198 | |||
| 199 | /// Refuses an in-place change to `v` when another binding, list or pending argument may | ||
| 200 | /// share its cells, which Emacs would change too: any value holding a list that ends like | ||
| 201 | /// `v`, or an equal vector or string. `variable`'s innermost binding is the one `eval` | ||
| 202 | /// updates after the call. | ||
| 203 | func refuseShared(_ v: Sexp, variable: String?, _ name: String) throws { | ||
| 204 | let matches: (Sexp) -> Bool | ||
| 205 | switch v { | ||
| 206 | case .list(let items): | ||
| 207 | guard let last = items.last.map(Self.normalized) else { return } | ||
| 208 | matches = { if case .list(let xs) = $0, let l = xs.last { Self.normalized(l) == last } else { false } } | ||
| 209 | case .dotted(let items, let tail): | ||
| 210 | let last = Self.normalized(items.last!) | ||
| 211 | matches = { if case .dotted(let xs, let t) = $0 { t == tail && Self.normalized(xs.last!) == last } else { false } } | ||
| 212 | case .vector, .string: | ||
| 213 | matches = { $0 == v } | ||
| 214 | default: | ||
| 61 | return | 215 | return |
| 62 | } | 216 | } |
| 63 | scopes[0][name] = v | 217 | func contains(_ x: Sexp) -> Bool { |
| 218 | if matches(x) { return true } | ||
| 219 | switch x { | ||
| 220 | case .list(let items), .vector(let items): return items.contains(where: contains) | ||
| 221 | case .dotted(let items, let last): return items.contains(where: contains) || contains(last) | ||
| 222 | default: return false | ||
| 223 | } | ||
| 224 | } | ||
| 225 | let owner = variable.flatMap { name in scopes.last { $0.vars[name] != nil } } | ||
| 226 | var seen: Set<ObjectIdentifier> = [] | ||
| 227 | for frame in (hiddenScopes + [scopes] + closures).joined() where seen.insert(ObjectIdentifier(frame)).inserted { | ||
| 228 | for (key, value) in frame.vars where !(frame === owner && key == variable) && contains(value) { | ||
| 229 | throw Unsupported(what: "\(name) on a list another value shares") | ||
| 230 | } | ||
| 231 | } | ||
| 232 | if (hiddenValues + pending.dropLast().joined()).contains(where: contains) { throw Unsupported(what: "\(name) on a list another value shares") } | ||
| 64 | } | 233 | } |
| 65 | 234 | ||
| 66 | // MARK: - Values | 235 | // MARK: - Values |
| @@ -81,25 +250,28 @@ public final class Elisp { | |||
| 81 | } | 250 | } |
| 82 | 251 | ||
| 83 | static func car(_ v: Sexp) throws -> Sexp { | 252 | static func car(_ v: Sexp) throws -> Sexp { |
| 84 | switch v { | 253 | if isClosure(v) { throw Unsupported(what: "car on a closure") } |
| 254 | return switch v { | ||
| 85 | case .list(let items): items.first ?? .nil | 255 | case .list(let items): items.first ?? .nil |
| 86 | case .dotted(let items, _): items[0] | 256 | case .dotted(let items, _): items[0] |
| 87 | case _ where isNil(v): .nil | 257 | case _ where isNil(v): .nil |
| 88 | default: throw Signal(message: "Wrong type argument: listp, \(v.description)") | 258 | default: throw Signal(message: "Wrong type argument: listp, \(v.description)", data: [.symbol("listp"), v]) |
| 89 | } | 259 | } |
| 90 | } | 260 | } |
| 91 | 261 | ||
| 92 | static func cdr(_ v: Sexp) throws -> Sexp { | 262 | static func cdr(_ v: Sexp) throws -> Sexp { |
| 93 | switch v { | 263 | if isClosure(v) { throw Unsupported(what: "cdr on a closure") } |
| 264 | return switch v { | ||
| 94 | case .list(let items): list(Array(items.dropFirst())) | 265 | case .list(let items): list(Array(items.dropFirst())) |
| 95 | case .dotted(let items, let last): items.count == 1 ? last : .dotted(Array(items.dropFirst()), last) | 266 | case .dotted(let items, let last): items.count == 1 ? last : .dotted(Array(items.dropFirst()), last) |
| 96 | case _ where isNil(v): .nil | 267 | case _ where isNil(v): .nil |
| 97 | default: throw Signal(message: "Wrong type argument: listp, \(v.description)") | 268 | default: throw Signal(message: "Wrong type argument: listp, \(v.description)", data: [.symbol("listp"), v]) |
| 98 | } | 269 | } |
| 99 | } | 270 | } |
| 100 | 271 | ||
| 101 | /// A proper list's elements. | 272 | /// A proper list's elements. |
| 102 | static func elements(_ v: Sexp) throws -> [Sexp] { | 273 | static func elements(_ v: Sexp) throws -> [Sexp] { |
| 274 | if isClosure(v) { throw Unsupported(what: "a closure as a list") } | ||
| 103 | if case .list(let items) = v { return items } | 275 | if case .list(let items) = v { return items } |
| 104 | if isNil(v) { return [] } | 276 | if isNil(v) { return [] } |
| 105 | throw Signal(message: "Wrong type argument: listp, \(v.description)") | 277 | throw Signal(message: "Wrong type argument: listp, \(v.description)") |
| @@ -197,16 +369,40 @@ public final class Elisp { | |||
| 197 | guard let head = items.first else { return .nil } | 369 | guard let head = items.first else { return .nil } |
| 198 | guard case .symbol(let name) = head else { | 370 | guard case .symbol(let name) = head else { |
| 199 | if case .list(let lambda) = head, lambda.first == .symbol("lambda") { | 371 | if case .list(let lambda) = head, lambda.first == .symbol("lambda") { |
| 200 | return try call(head, try items.dropFirst().map(eval)) | 372 | return try call(closure(head), try evaluated(items.dropFirst())) |
| 201 | } | 373 | } |
| 202 | throw Signal(message: "Invalid function: \(head.description)") | 374 | throw Signal(message: "Invalid function: \(head.description)") |
| 203 | } | 375 | } |
| 204 | return try special(name, Array(items.dropFirst())) ?? callNamed(name, try items.dropFirst().map(eval)) | 376 | let args = Array(items.dropFirst()) |
| 377 | if let value = try special(name, args) { return value } | ||
| 378 | // The function first, so an unknown one, or a macro this evaluator lacks, is | ||
| 379 | // unsupported rather than an error from its arguments. | ||
| 380 | guard let function = functions[name] else { throw Unsupported(what: "function \(name)") } | ||
| 381 | pending.append([]) | ||
| 382 | defer { pending.removeLast() } | ||
| 383 | for arg in args { pending[pending.count - 1].append(try eval(arg)) } | ||
| 384 | let values = pending[pending.count - 1] | ||
| 385 | try refuseClosures(name, values) | ||
| 386 | var variable: String? | ||
| 387 | if case .symbol(let s)? = args.first, s != "nil", s != "t", !s.hasPrefix(":") { variable = s } | ||
| 388 | inPlaceVariable = variable | ||
| 389 | let result = try function(self, values) | ||
| 390 | inPlaceVariable = nil | ||
| 391 | if let variable, let after = Self.afterInPlace(name, values, result) { assign(variable, after) } | ||
| 392 | return result | ||
| 205 | case .dotted: throw Signal(message: "Invalid function") | 393 | case .dotted: throw Signal(message: "Invalid function") |
| 206 | default: return form | 394 | default: return form |
| 207 | } | 395 | } |
| 208 | } | 396 | } |
| 209 | 397 | ||
| 398 | /// `forms`' values, held as pending while the later ones evaluate. | ||
| 399 | func evaluated(_ forms: some Collection<Sexp>) throws -> [Sexp] { | ||
| 400 | pending.append([]) | ||
| 401 | defer { pending.removeLast() } | ||
| 402 | for form in forms { pending[pending.count - 1].append(try eval(form)) } | ||
| 403 | return pending[pending.count - 1] | ||
| 404 | } | ||
| 405 | |||
| 210 | func progn(_ body: some Collection<Sexp>) throws -> Sexp { | 406 | func progn(_ body: some Collection<Sexp>) throws -> Sexp { |
| 211 | var result = Sexp.nil | 407 | var result = Sexp.nil |
| 212 | for form in body { result = try eval(form) } | 408 | for form in body { result = try eval(form) } |
| @@ -219,16 +415,17 @@ public final class Elisp { | |||
| 219 | case "quote": | 415 | case "quote": |
| 220 | return args.first ?? .nil | 416 | return args.first ?? .nil |
| 221 | case "function": | 417 | case "function": |
| 222 | return args.first ?? .nil | 418 | return closure(args.first ?? .nil) |
| 223 | case "lambda": | 419 | case "lambda": |
| 224 | return .list([.symbol("lambda")] + args) | 420 | return closure(.list([.symbol("lambda")] + args)) |
| 225 | case "progn": | 421 | case "progn": |
| 226 | return try progn(args) | 422 | return try progn(args) |
| 227 | case "prog1": | 423 | case "prog1": |
| 228 | guard let first = args.first else { return .nil } | 424 | guard let first = args.first else { return .nil } |
| 229 | let value = try eval(first) | 425 | pending.append([try eval(first)]) |
| 426 | defer { pending.removeLast() } | ||
| 230 | _ = try progn(args.dropFirst()) | 427 | _ = try progn(args.dropFirst()) |
| 231 | return value | 428 | return pending[pending.count - 1][0] |
| 232 | case "if": | 429 | case "if": |
| 233 | guard args.count >= 2 else { throw Signal(message: "Wrong number of arguments: if") } | 430 | guard args.count >= 2 else { throw Signal(message: "Wrong number of arguments: if") } |
| 234 | return Self.isNil(try eval(args[0])) ? try progn(args.dropFirst(2)) : try eval(args[1]) | 431 | return Self.isNil(try eval(args[0])) ? try progn(args.dropFirst(2)) : try eval(args[1]) |
| @@ -258,22 +455,29 @@ public final class Elisp { | |||
| 258 | return .nil | 455 | return .nil |
| 259 | case "let", "let*": | 456 | case "let", "let*": |
| 260 | guard let first = args.first else { return .nil } | 457 | guard let first = args.first else { return .nil } |
| 261 | var bindings: [String: Sexp] = [:] | 458 | var specs: [(String, Sexp?)] = [] |
| 262 | scopes.append([:]) | ||
| 263 | defer { scopes.removeLast() } | ||
| 264 | for binding in try Self.elements(first) { | 459 | for binding in try Self.elements(first) { |
| 265 | let (variable, value): (String, Sexp) | ||
| 266 | if case .symbol(let s) = binding { | 460 | if case .symbol(let s) = binding { |
| 267 | (variable, value) = (s, .nil) | 461 | specs.append((s, nil)) |
| 268 | } else { | 462 | } else { |
| 269 | let parts = try Self.elements(binding) | 463 | let parts = try Self.elements(binding) |
| 270 | guard case .symbol(let s)? = parts.first else { throw Signal(message: "Bad binding") } | 464 | guard case .symbol(let s)? = parts.first else { throw Signal(message: "Bad binding") } |
| 271 | (variable, value) = (s, parts.count > 1 ? try eval(parts[1]) : .nil) | 465 | specs.append((s, parts.count > 1 ? parts[1] : nil)) |
| 272 | } | 466 | } |
| 273 | if name == "let*" { scopes[scopes.count - 1][variable] = value } else { bindings[variable] = value } | ||
| 274 | } | 467 | } |
| 275 | if name == "let" { scopes[scopes.count - 1] = bindings } | 468 | if name == "let" { |
| 276 | return try progn(args.dropFirst()) | 469 | let values = try evaluated(specs.map { $0.1 ?? .nil }) |
| 470 | var bindings: [String: Sexp] = [:] | ||
| 471 | for ((variable, _), value) in zip(specs, values) { bindings[variable] = value } | ||
| 472 | return try binding(bindings) { try progn(args.dropFirst()) } | ||
| 473 | } | ||
| 474 | // `let*` nests a binding per variable, so a closure sees the ones before it. | ||
| 475 | func bind(_ rest: ArraySlice<(String, Sexp?)>) throws -> Sexp { | ||
| 476 | guard let (variable, form) = rest.first else { return try progn(args.dropFirst()) } | ||
| 477 | let value = try form.map(eval) ?? .nil | ||
| 478 | return try binding([variable: value]) { try bind(rest.dropFirst()) } | ||
| 479 | } | ||
| 480 | return try bind(specs[...]) | ||
| 277 | case "setq": | 481 | case "setq": |
| 278 | var value = Sexp.nil | 482 | var value = Sexp.nil |
| 279 | var i = 0 | 483 | var i = 0 |
| @@ -291,6 +495,7 @@ public final class Elisp { | |||
| 291 | assign(variable, try Self.cdr(list)) | 495 | assign(variable, try Self.cdr(list)) |
| 292 | return try Self.car(list) | 496 | return try Self.car(list) |
| 293 | } | 497 | } |
| 498 | if Self.isClosure(list) { throw Unsupported(what: "push on a closure") } | ||
| 294 | let pushed = Self.cons(try eval(args[0]), list) | 499 | let pushed = Self.cons(try eval(args[0]), list) |
| 295 | assign(variable, pushed) | 500 | assign(variable, pushed) |
| 296 | return pushed | 501 | return pushed |
| @@ -304,17 +509,16 @@ public final class Elisp { | |||
| 304 | let source = try eval(spec[1]) | 509 | let source = try eval(spec[1]) |
| 305 | let items = name == "dolist" ? try Self.elements(source) : [] | 510 | let items = name == "dolist" ? try Self.elements(source) : [] |
| 306 | let count = name == "dolist" ? items.count : max(0, try Self.int(source)) | 511 | let count = name == "dolist" ? items.count : max(0, try Self.int(source)) |
| 307 | scopes.append([:]) | 512 | pending.append([source]) |
| 308 | defer { scopes.removeLast() } | 513 | defer { pending.removeLast() } |
| 514 | // A new binding each time round, as closures over the variable see it. | ||
| 309 | for i in 0..<count { | 515 | for i in 0..<count { |
| 310 | steps += 1 | 516 | steps += 1 |
| 311 | if steps > Self.stepLimit { throw Signal(message: "Evaluation took too long") } | 517 | if steps > Self.stepLimit { throw Signal(message: "Evaluation took too long") } |
| 312 | scopes[scopes.count - 1][variable] = name == "dolist" ? items[i] : .integer(i) | 518 | _ = try binding([variable: name == "dolist" ? items[i] : .integer(i)]) { try progn(args.dropFirst()) } |
| 313 | _ = try progn(args.dropFirst()) | ||
| 314 | } | 519 | } |
| 315 | if spec.count > 2 { | 520 | if spec.count > 2 { |
| 316 | scopes[scopes.count - 1][variable] = name == "dotimes" ? .integer(count) : .nil | 521 | return try binding([variable: name == "dotimes" ? .integer(count) : .nil]) { try eval(spec[2]) } |
| 317 | return try eval(spec[2]) | ||
| 318 | } | 522 | } |
| 319 | return .nil | 523 | return .nil |
| 320 | case "with-output-to-string": | 524 | case "with-output-to-string": |
| @@ -333,18 +537,26 @@ public final class Elisp { | |||
| 333 | do { | 537 | do { |
| 334 | return try eval(args[1]) | 538 | return try eval(args[1]) |
| 335 | } catch let signal as Signal { | 539 | } catch let signal as Signal { |
| 540 | // Every error has the `error` condition as well as its own. | ||
| 541 | let conditions = ["error", "t"] + (signal.symbol.map { [$0] } ?? []) | ||
| 336 | for handler in args.dropFirst(2) { | 542 | for handler in args.dropFirst(2) { |
| 337 | let parts = try Self.elements(handler) | 543 | let parts = try Self.elements(handler) |
| 338 | guard let condition = parts.first else { continue } | 544 | guard let condition = parts.first else { continue } |
| 339 | let names = (try? Self.elements(condition)) ?? [condition] | 545 | let names = ((try? Self.elements(condition)) ?? [condition]).compactMap(\.symbol) |
| 340 | guard names.contains(.symbol("error")) || names.contains(.symbol("t")) else { continue } | 546 | guard names.contains(where: conditions.contains) else { |
| 341 | let bindings: [String: Sexp] = args[0].symbol.map { $0 == "nil" ? [:] : [$0: .list([.symbol("error"), .string(signal.message)])] } ?? [:] | 547 | if signal.symbol == nil, !names.isEmpty { throw Unsupported(what: "condition-case on \(names.joined(separator: " "))") } |
| 548 | continue | ||
| 549 | } | ||
| 550 | var bindings: [String: Sexp] = [:] | ||
| 551 | if let variable = args[0].symbol, variable != "nil" { | ||
| 552 | bindings[variable] = signal.symbol.flatMap { symbol in signal.data.map { .list([.symbol(symbol)] + $0) } } ?? Self.unknownError | ||
| 553 | } | ||
| 342 | return try binding(bindings) { try progn(parts.dropFirst()) } | 554 | return try binding(bindings) { try progn(parts.dropFirst()) } |
| 343 | } | 555 | } |
| 344 | throw signal | 556 | throw signal |
| 345 | } | 557 | } |
| 346 | default: | 558 | default: |
| 347 | return nil | 559 | return try moreSpecial(name, args) |
| 348 | } | 560 | } |
| 349 | } | 561 | } |
| 350 | 562 | ||
| @@ -352,37 +564,65 @@ public final class Elisp { | |||
| 352 | public func call(_ function: Sexp, _ args: [Sexp]) throws -> Sexp { | 564 | public func call(_ function: Sexp, _ args: [Sexp]) throws -> Sexp { |
| 353 | switch function { | 565 | switch function { |
| 354 | case .symbol(let name): return try callNamed(name, args) | 566 | case .symbol(let name): return try callNamed(name, args) |
| 567 | case .list(let items) where Self.isClosure(function): | ||
| 568 | guard closures.indices.contains(items[1].integer!) else { throw Unsupported(what: "a closure as a list") } | ||
| 569 | let saved = dynamicOnly | ||
| 570 | dynamicOnly = false | ||
| 571 | defer { dynamicOnly = saved } | ||
| 572 | return try apply(parameters: items[2], body: items.dropFirst(3), args, scope: closures[items[1].integer!]) | ||
| 355 | case .list(let items) where items.first == .symbol("lambda") && items.count >= 2: | 573 | case .list(let items) where items.first == .symbol("lambda") && items.count >= 2: |
| 356 | var bindings: [String: Sexp] = [:] | 574 | guard lexical else { return try apply(parameters: items[1], body: items.dropFirst(2), args, scope: nil) } |
| 357 | var mode = "required" | 575 | // Under lexical binding, a lambda list runs outside the caller's local frames, with |
| 358 | var i = 0 | 576 | // dynamic binding. |
| 359 | for parameter in try Self.elements(items[1]) { | 577 | let saved = dynamicOnly |
| 360 | guard case .symbol(let p) = parameter else { throw Signal(message: "Bad lambda list") } | 578 | dynamicOnly = true |
| 361 | if p == "&optional" || p == "&rest" { | 579 | defer { dynamicOnly = saved } |
| 362 | mode = p | 580 | return try apply(parameters: items[1], body: items.dropFirst(2), args, scope: []) |
| 363 | continue | ||
| 364 | } | ||
| 365 | if mode == "&rest" { | ||
| 366 | bindings[p] = Self.list(Array(args.dropFirst(i))) | ||
| 367 | i = args.count | ||
| 368 | } else if i < args.count { | ||
| 369 | bindings[p] = args[i] | ||
| 370 | i += 1 | ||
| 371 | } else if mode == "&optional" { | ||
| 372 | bindings[p] = .nil | ||
| 373 | } else { | ||
| 374 | throw Signal(message: "Wrong number of arguments") | ||
| 375 | } | ||
| 376 | } | ||
| 377 | if i < args.count { throw Signal(message: "Wrong number of arguments") } | ||
| 378 | return try binding(bindings) { try progn(items.dropFirst(2)) } | ||
| 379 | default: | 581 | default: |
| 380 | throw Signal(message: "Invalid function: \(function.description)") | 582 | throw Signal(message: "Invalid function: \(function.description)") |
| 381 | } | 583 | } |
| 382 | } | 584 | } |
| 383 | 585 | ||
| 586 | /// Binds `parameters` to `args` and runs `body`, in `scope`'s frames instead of the | ||
| 587 | /// caller's when given. | ||
| 588 | private func apply(parameters: Sexp, body: ArraySlice<Sexp>, _ args: [Sexp], scope: [Frame]?) throws -> Sexp { | ||
| 589 | var bindings: [String: Sexp] = [:] | ||
| 590 | var mode = "required" | ||
| 591 | var i = 0 | ||
| 592 | for parameter in try Self.elements(parameters) { | ||
| 593 | guard case .symbol(let p) = parameter else { throw Signal(message: "Bad lambda list") } | ||
| 594 | if p == "&optional" || p == "&rest" { | ||
| 595 | mode = p | ||
| 596 | continue | ||
| 597 | } | ||
| 598 | if mode == "&rest" { | ||
| 599 | bindings[p] = Self.list(Array(args.dropFirst(i))) | ||
| 600 | i = args.count | ||
| 601 | } else if i < args.count { | ||
| 602 | bindings[p] = args[i] | ||
| 603 | i += 1 | ||
| 604 | } else if mode == "&optional" { | ||
| 605 | bindings[p] = .nil | ||
| 606 | } else { | ||
| 607 | throw Signal(message: "Wrong number of arguments") | ||
| 608 | } | ||
| 609 | } | ||
| 610 | if i < args.count { throw Signal(message: "Wrong number of arguments") } | ||
| 611 | guard let scope else { return try binding(bindings) { try progn(body) } } | ||
| 612 | let caller = scopes | ||
| 613 | hiddenScopes.append(caller) | ||
| 614 | scopes = [scopes[0]] + scope | ||
| 615 | defer { | ||
| 616 | scopes = caller | ||
| 617 | hiddenScopes.removeLast() | ||
| 618 | } | ||
| 619 | return try binding(bindings) { try progn(body) } | ||
| 620 | } | ||
| 621 | |||
| 384 | func callNamed(_ name: String, _ args: [Sexp]) throws -> Sexp { | 622 | func callNamed(_ name: String, _ args: [Sexp]) throws -> Sexp { |
| 385 | guard let function = functions[name] else { throw Unsupported(what: "function \(name)") } | 623 | guard let function = functions[name] else { throw Unsupported(what: "function \(name)") } |
| 624 | try refuseClosures(name, args) | ||
| 625 | inPlaceVariable = nil | ||
| 386 | return try function(self, args) | 626 | return try function(self, args) |
| 387 | } | 627 | } |
| 388 | 628 | ||
| @@ -584,7 +824,12 @@ public final class Elisp { | |||
| 584 | guard let last = args.last else { return .nil } | 824 | guard let last = args.last else { return .nil } |
| 585 | var items: [Sexp] = [] | 825 | var items: [Sexp] = [] |
| 586 | for arg in args.dropLast() { items += try sequence(arg) } | 826 | for arg in args.dropLast() { items += try sequence(arg) } |
| 587 | return items.reversed().reduce(last) { cons($1, $0) } | 827 | switch last { |
| 828 | case .list(let rest): return .list(items + rest) | ||
| 829 | case .dotted(let rest, let tail): return .dotted(items + rest, tail) | ||
| 830 | case _ where isNil(last): return list(items) | ||
| 831 | default: return items.isEmpty ? last : .dotted(items, last) | ||
| 832 | } | ||
| 588 | } | 833 | } |
| 589 | lisp.define("length") { _, args in | 834 | lisp.define("length") { _, args in |
| 590 | try arity(args, 1...1, "length") | 835 | try arity(args, 1...1, "length") |
| @@ -660,12 +905,11 @@ public final class Elisp { | |||
| 660 | try arity(args, 2...2, "delete") | 905 | try arity(args, 2...2, "delete") |
| 661 | return list(try elements(args[1]).filter { normalized($0) != normalized(args[0]) }) | 906 | return list(try elements(args[1]).filter { normalized($0) != normalized(args[0]) }) |
| 662 | } | 907 | } |
| 663 | lisp.define("error") { _, args in | 908 | for name in ["error", "user-error"] { |
| 664 | let message = args.isEmpty ? "" : try format(args) | 909 | lisp.define(name) { _, args in |
| 665 | throw Signal(message: message) | 910 | let message = args.isEmpty ? "" : try format(args) |
| 666 | } | 911 | throw Signal(message: message, symbol: name, data: [.string(message)]) |
| 667 | lisp.define("user-error") { _, args in | 912 | } |
| 668 | throw Signal(message: args.isEmpty ? "" : try format(args)) | ||
| 669 | } | 913 | } |
| 670 | 914 | ||
| 671 | // Printing. | 915 | // Printing. |
| @@ -719,13 +963,22 @@ public final class Elisp { | |||
| 719 | if case .integer(let c) = args[0] { return .integer(Int(String(try scalar(c)).lowercased().unicodeScalars.first!.value)) } | 963 | if case .integer(let c) = args[0] { return .integer(Int(String(try scalar(c)).lowercased().unicodeScalars.first!.value)) } |
| 720 | return .string(try string(args[0]).lowercased()) | 964 | return .string(try string(args[0]).lowercased()) |
| 721 | } | 965 | } |
| 722 | lisp.define("capitalize") { _, args in | 966 | // A letter is upcased after a character without word syntax, downcased after one with it. |
| 967 | lisp.define("capitalize") { lisp, args in | ||
| 723 | try arity(args, 1...1, "capitalize") | 968 | try arity(args, 1...1, "capitalize") |
| 724 | return .string(try string(args[0]).capitalized) | 969 | let s = try string(args[0]) |
| 970 | guard s.unicodeScalars.allSatisfy(\.isASCII) else { throw Unsupported(what: "capitalize past ASCII") } | ||
| 971 | var inWord = false | ||
| 972 | var out = "" | ||
| 973 | for c in s.unicodeScalars { | ||
| 974 | out += inWord ? String(c).lowercased() : String(c).uppercased() | ||
| 975 | inWord = lisp.syntax.isWord(c) | ||
| 976 | } | ||
| 977 | return .string(out) | ||
| 725 | } | 978 | } |
| 726 | lisp.define("substring") { _, args in | 979 | lisp.define("substring") { _, args in |
| 727 | try arity(args, 1...3, "substring") | 980 | try arity(args, 1...3, "substring") |
| 728 | let chars = Array(try string(args[0])) | 981 | let chars = Array(try string(args[0]).unicodeScalars) |
| 729 | func index(_ v: Sexp?, _ fallback: Int) throws -> Int { | 982 | func index(_ v: Sexp?, _ fallback: Int) throws -> Int { |
| 730 | guard let v, !isNil(v) else { return fallback } | 983 | guard let v, !isNil(v) else { return fallback } |
| 731 | let i = try int(v) | 984 | let i = try int(v) |
| @@ -734,7 +987,7 @@ public final class Elisp { | |||
| 734 | let from = try index(args.count > 1 ? args[1] : nil, 0) | 987 | let from = try index(args.count > 1 ? args[1] : nil, 0) |
| 735 | let to = try index(args.count > 2 ? args[2] : nil, chars.count) | 988 | let to = try index(args.count > 2 ? args[2] : nil, chars.count) |
| 736 | guard from >= 0, to <= chars.count, from <= to else { throw Signal(message: "Args out of range") } | 989 | guard from >= 0, to <= chars.count, from <= to else { throw Signal(message: "Args out of range") } |
| 737 | return .string(String(chars[from..<to])) | 990 | return .string(String(String.UnicodeScalarView(chars[from..<to]))) |
| 738 | } | 991 | } |
| 739 | lisp.define("string-to-number") { _, args in | 992 | lisp.define("string-to-number") { _, args in |
| 740 | try arity(args, 1...2, "string-to-number") | 993 | try arity(args, 1...2, "string-to-number") |
| @@ -762,24 +1015,6 @@ public final class Elisp { | |||
| 762 | try arity(args, 1...1, "string-trim") | 1015 | try arity(args, 1...1, "string-trim") |
| 763 | return .string(try string(args[0]).trimmingCharacters(in: .whitespacesAndNewlines)) | 1016 | return .string(try string(args[0]).trimmingCharacters(in: .whitespacesAndNewlines)) |
| 764 | } | 1017 | } |
| 765 | lisp.define("split-string") { _, args in | ||
| 766 | try arity(args, 1...2, "split-string") | ||
| 767 | let s = try string(args[0]) | ||
| 768 | if args.count == 2, !isNil(args[1]) { | ||
| 769 | let separator = try string(args[1]) | ||
| 770 | let regex = try NSRegularExpression(pattern: separator) | ||
| 771 | let ns = s as NSString | ||
| 772 | var parts: [Sexp] = [] | ||
| 773 | var start = 0 | ||
| 774 | for m in regex.matches(in: s, range: NSRange(location: 0, length: ns.length)) where m.range.length > 0 { | ||
| 775 | parts.append(.string(ns.substring(with: NSRange(location: start, length: m.range.location - start)))) | ||
| 776 | start = NSMaxRange(m.range) | ||
| 777 | } | ||
| 778 | parts.append(.string(ns.substring(from: start))) | ||
| 779 | return list(parts) | ||
| 780 | } | ||
| 781 | return list(s.split(whereSeparator: { " \t\n\r\u{0C}\u{0B}".contains($0) }).map { .string(String($0)) }) | ||
| 782 | } | ||
| 783 | } | 1018 | } |
| 784 | 1019 | ||
| 785 | static func add(_ n: Number, _ k: Int) throws -> Number { | 1020 | static func add(_ n: Number, _ k: Int) throws -> Number { |
Sources/OrgCore/Config/ElispForms.swift added +256
| @@ -0,0 +1,256 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | // `defun`, `defvar`, `defconst`, `let-alist`, `pcase`, `cl-loop`, `cl-incf`, `cl-decf` and | ||
| 4 | // `save-match-data`. | ||
| 5 | |||
| 6 | extension Elisp { | ||
| 7 | /// The special forms and macros beyond the core ones; nil when `name` isn't one. | ||
| 8 | func moreSpecial(_ name: String, _ args: [Sexp]) throws -> Sexp? { | ||
| 9 | switch name { | ||
| 10 | case "defun": return try defun(args) | ||
| 11 | case "defvar", "defconst": return try defineVariable(args, constant: name == "defconst") | ||
| 12 | case "let-alist": return try letAlist(args) | ||
| 13 | case "pcase": return try pcase(args) | ||
| 14 | case "cl-loop": return try loop(args) | ||
| 15 | case "cl-incf", "cl-decf": return try increment(args, decrement: name == "cl-decf") | ||
| 16 | case "save-match-data": | ||
| 17 | let saved = matchData | ||
| 18 | defer { matchData = saved } | ||
| 19 | return try progn(args) | ||
| 20 | default: return nil | ||
| 21 | } | ||
| 22 | } | ||
| 23 | |||
| 24 | func defun(_ args: [Sexp]) throws -> Sexp { | ||
| 25 | guard args.count >= 2, case .symbol(let name) = args[0] else { throw Signal(message: "Malformed defun") } | ||
| 26 | var body = Array(args.dropFirst(2)) | ||
| 27 | if body.count > 1, case .string = body[0] { body.removeFirst() } | ||
| 28 | while let head = body.first?.head, head == "declare" || head == "interactive" { body.removeFirst() } | ||
| 29 | let function = closure(.list([.symbol("lambda"), args[1]] + body)) | ||
| 30 | define(name) { lisp, values in try lisp.call(function, values) } | ||
| 31 | defined.insert(name) | ||
| 32 | return .symbol(name) | ||
| 33 | } | ||
| 34 | |||
| 35 | /// `defvar` sets a variable only when it has no global value; `defconst` always does. | ||
| 36 | func defineVariable(_ args: [Sexp], constant: Bool) throws -> Sexp { | ||
| 37 | guard case .symbol(let name)? = args.first, args.count <= 3 else { throw Signal(message: "Malformed \(constant ? "defconst" : "defvar")") } | ||
| 38 | if constant, args.count < 2 { throw Signal(message: "Wrong number of arguments: defconst, 1") } | ||
| 39 | specials.insert(name) | ||
| 40 | if args.count > 1, constant || scopes[0].vars[name] == nil { scopes[0].vars[name] = try eval(args[1]) } | ||
| 41 | return .symbol(name) | ||
| 42 | } | ||
| 43 | |||
| 44 | /// `let-alist`: `.key` and `.key.inner` in the body, outside inner `let-alist` bodies, bound | ||
| 45 | /// to the alist's values. | ||
| 46 | func letAlist(_ args: [Sexp]) throws -> Sexp { | ||
| 47 | guard let first = args.first else { throw Signal(message: "Wrong number of arguments: let-alist, 0") } | ||
| 48 | let alist = try eval(first) | ||
| 49 | var names: Set<String> = [] | ||
| 50 | func search(_ form: Sexp) { | ||
| 51 | switch form { | ||
| 52 | case .symbol(let s) where s.hasPrefix("."): names.insert(s) | ||
| 53 | case .list(let items) where items.first == .symbol("let-alist"): if items.count > 1 { search(items[1]) } | ||
| 54 | case .list(let items), .vector(let items): items.forEach(search) | ||
| 55 | case .dotted(let items, let last): | ||
| 56 | if items.first == .symbol("let-alist") { | ||
| 57 | if items.count > 1 { search(items[1]) } | ||
| 58 | } else { | ||
| 59 | items.forEach(search) | ||
| 60 | search(last) | ||
| 61 | } | ||
| 62 | default: break | ||
| 63 | } | ||
| 64 | } | ||
| 65 | args.dropFirst().forEach(search) | ||
| 66 | var bindings: [String: Sexp] = [:] | ||
| 67 | for name in names { | ||
| 68 | guard !name.hasPrefix("..") else { throw Unsupported(what: "let-alist \(name)") } | ||
| 69 | var value = alist | ||
| 70 | for key in name.dropFirst().split(separator: ".", omittingEmptySubsequences: false) { | ||
| 71 | var pair = Sexp.nil | ||
| 72 | for item in try Self.elements(value) { | ||
| 73 | if let car = try? Self.car(item), car == .symbol(String(key)), Self.isCons(item) { | ||
| 74 | pair = item | ||
| 75 | break | ||
| 76 | } | ||
| 77 | } | ||
| 78 | value = try Self.cdr(pair) | ||
| 79 | } | ||
| 80 | bindings[name] = value | ||
| 81 | } | ||
| 82 | return try binding(bindings) { try progn(args.dropFirst()) } | ||
| 83 | } | ||
| 84 | |||
| 85 | static func isCons(_ v: Sexp) -> Bool { | ||
| 86 | switch v { | ||
| 87 | case .list(let items): !items.isEmpty | ||
| 88 | case .dotted: true | ||
| 89 | default: false | ||
| 90 | } | ||
| 91 | } | ||
| 92 | |||
| 93 | /// `pcase` with literal, symbol, quote, backquote and `pred` patterns. | ||
| 94 | func pcase(_ args: [Sexp]) throws -> Sexp { | ||
| 95 | guard let first = args.first else { throw Signal(message: "Wrong number of arguments: pcase, 0") } | ||
| 96 | let value = try eval(first) | ||
| 97 | for clause in args.dropFirst() { | ||
| 98 | let parts = try Self.elements(clause) | ||
| 99 | guard let pattern = parts.first else { continue } | ||
| 100 | var bindings: [String: Sexp] = [:] | ||
| 101 | if try matches(pattern, value, &bindings) { return try binding(bindings) { try progn(parts.dropFirst()) } } | ||
| 102 | } | ||
| 103 | return .nil | ||
| 104 | } | ||
| 105 | |||
| 106 | func matches(_ pattern: Sexp, _ value: Sexp, _ bindings: inout [String: Sexp]) throws -> Bool { | ||
| 107 | switch pattern { | ||
| 108 | case .symbol("_"): | ||
| 109 | return true | ||
| 110 | case .symbol(let s) where s.hasPrefix(":"): | ||
| 111 | return value == pattern | ||
| 112 | case .symbol(let s) where s != "nil" && s != "t": | ||
| 113 | // A variable used twice must match the same object the second time. | ||
| 114 | if let bound = bindings[s] { return Self.eq(bound, value) } | ||
| 115 | bindings[s] = value | ||
| 116 | return true | ||
| 117 | case .integer, .character: | ||
| 118 | return Self.eq(pattern, value) | ||
| 119 | case .string: | ||
| 120 | return pattern == value | ||
| 121 | case .list(let items) where items.count == 2 && items[0] == .symbol("quote"): | ||
| 122 | return Self.normalized(items[1]) == Self.normalized(value) | ||
| 123 | case .list(let items) where items.count == 2 && items[0] == .symbol("\\`"): | ||
| 124 | return try backquoted(items[1], value, &bindings) | ||
| 125 | case .list(let items) where items.count == 2 && items[0] == .symbol("pred") && (items[1].symbol != nil || items[1].head == "lambda"): | ||
| 126 | let soFar = bindings | ||
| 127 | return !Self.isNil(try binding(soFar) { try call(closure(items[1]), [value]) }) | ||
| 128 | default: | ||
| 129 | throw Unsupported(what: "pcase pattern \(pattern.description)") | ||
| 130 | } | ||
| 131 | } | ||
| 132 | |||
| 133 | func backquoted(_ pattern: Sexp, _ value: Sexp, _ bindings: inout [String: Sexp]) throws -> Bool { | ||
| 134 | switch pattern { | ||
| 135 | case .list(let items) where items.count == 2 && items[0] == .symbol(","): | ||
| 136 | return try matches(items[1], value, &bindings) | ||
| 137 | case .list(let items) where items.first == .symbol(",@"): | ||
| 138 | throw Unsupported(what: "pcase pattern ,@") | ||
| 139 | case .list(let items) where !items.isEmpty: | ||
| 140 | guard Self.isCons(value) else { return false } | ||
| 141 | return try backquoted(items[0], Self.car(value), &bindings) && backquoted(Self.list(Array(items.dropFirst())), Self.cdr(value), &bindings) | ||
| 142 | case .dotted(let items, let last): | ||
| 143 | guard Self.isCons(value) else { return false } | ||
| 144 | let rest = items.count == 1 ? last : .dotted(Array(items.dropFirst()), last) | ||
| 145 | return try backquoted(items[0], Self.car(value), &bindings) && backquoted(rest, Self.cdr(value), &bindings) | ||
| 146 | case .vector(let patterns): | ||
| 147 | guard case .vector(let values) = value, values.count == patterns.count else { return false } | ||
| 148 | for (p, v) in zip(patterns, values) where !(try backquoted(p, v, &bindings)) { return false } | ||
| 149 | return true | ||
| 150 | default: | ||
| 151 | return Self.normalized(pattern) == Self.normalized(value) | ||
| 152 | } | ||
| 153 | } | ||
| 154 | |||
| 155 | /// `cl-loop` with `for VAR in LIST`, `for VAR from START [to END]`, `collect`, `sum` and | ||
| 156 | /// `do`. | ||
| 157 | func loop(_ args: [Sexp]) throws -> Sexp { | ||
| 158 | enum Iterator { | ||
| 159 | case list(String) | ||
| 160 | case range(String, limit: Sexp?) | ||
| 161 | } | ||
| 162 | var iterators: [Iterator] = [] | ||
| 163 | // What each `in` clause has left. | ||
| 164 | var lists: [Int: Sexp] = [:] | ||
| 165 | var actions: [(kind: String, forms: [Sexp])] = [] | ||
| 166 | scopes.append(Frame()) | ||
| 167 | defer { scopes.removeLast() } | ||
| 168 | var i = 0 | ||
| 169 | func next() throws -> Sexp { | ||
| 170 | guard i < args.count else { throw Signal(message: "Syntax error in cl-loop") } | ||
| 171 | i += 1 | ||
| 172 | return args[i - 1] | ||
| 173 | } | ||
| 174 | while i < args.count { | ||
| 175 | let word = try next() | ||
| 176 | switch word.symbol { | ||
| 177 | case "for": | ||
| 178 | guard case .symbol(let variable) = try next() else { throw Unsupported(what: "cl-loop destructuring") } | ||
| 179 | switch try next() { | ||
| 180 | case .symbol("in"): | ||
| 181 | lists[iterators.count] = try eval(try next()) | ||
| 182 | scopes[scopes.count - 1].vars[variable] = .nil | ||
| 183 | iterators.append(.list(variable)) | ||
| 184 | case .symbol("from"): | ||
| 185 | scopes[scopes.count - 1].vars[variable] = try eval(try next()) | ||
| 186 | var limit: Sexp? | ||
| 187 | if i < args.count, args[i] == .symbol("to") { | ||
| 188 | i += 1 | ||
| 189 | limit = try eval(try next()) | ||
| 190 | } | ||
| 191 | iterators.append(.range(variable, limit: limit)) | ||
| 192 | case let other: | ||
| 193 | throw Unsupported(what: "cl-loop for \(variable) \(other.description)") | ||
| 194 | } | ||
| 195 | case "collect", "sum": | ||
| 196 | actions.append((word.symbol!, [try next()])) | ||
| 197 | case "do": | ||
| 198 | var forms: [Sexp] = [] | ||
| 199 | while i < args.count, Self.isCons(args[i]) { | ||
| 200 | forms.append(args[i]) | ||
| 201 | i += 1 | ||
| 202 | } | ||
| 203 | actions.append(("do", forms)) | ||
| 204 | default: | ||
| 205 | throw Unsupported(what: "cl-loop \(word.description)") | ||
| 206 | } | ||
| 207 | } | ||
| 208 | guard !iterators.isEmpty else { throw Unsupported(what: "cl-loop without for") } | ||
| 209 | guard Set(actions.map(\.kind)).subtracting(["do"]).count <= 1 else { throw Unsupported(what: "cl-loop with collect and sum") } | ||
| 210 | var collected: [Sexp] = [] | ||
| 211 | var total = Sexp.integer(0) | ||
| 212 | var first = true | ||
| 213 | iterations: while true { | ||
| 214 | steps += 1 | ||
| 215 | if steps > Self.stepLimit { throw Signal(message: "Evaluation took too long") } | ||
| 216 | if !first { | ||
| 217 | for (n, iterator) in iterators.enumerated() { | ||
| 218 | switch iterator { | ||
| 219 | case .list: lists[n] = try Self.cdr(lists[n]!) | ||
| 220 | case .range(let variable, _): assign(variable, try callNamed("+", [try value(variable), .integer(1)])) | ||
| 221 | } | ||
| 222 | } | ||
| 223 | } | ||
| 224 | first = false | ||
| 225 | for (n, iterator) in iterators.enumerated() { | ||
| 226 | switch iterator { | ||
| 227 | case .list(let variable): | ||
| 228 | guard Self.isCons(lists[n]!) else { break iterations } | ||
| 229 | assign(variable, try Self.car(lists[n]!)) | ||
| 230 | case .range(let variable, let limit): | ||
| 231 | if let limit, Self.isNil(try callNamed("<=", [try value(variable), limit])) { break iterations } | ||
| 232 | } | ||
| 233 | } | ||
| 234 | for (kind, forms) in actions { | ||
| 235 | switch kind { | ||
| 236 | case "collect": collected.append(try eval(forms[0])) | ||
| 237 | case "sum": total = try callNamed("+", [total, try eval(forms[0])]) | ||
| 238 | default: _ = try progn(forms) | ||
| 239 | } | ||
| 240 | } | ||
| 241 | } | ||
| 242 | if actions.contains(where: { $0.kind == "collect" }) { return Self.list(collected) } | ||
| 243 | return actions.contains(where: { $0.kind == "sum" }) ? total : .nil | ||
| 244 | } | ||
| 245 | |||
| 246 | func increment(_ args: [Sexp], decrement: Bool) throws -> Sexp { | ||
| 247 | let name = decrement ? "cl-decf" : "cl-incf" | ||
| 248 | guard (1...2).contains(args.count) else { throw Signal(message: "Wrong number of arguments: \(name), \(args.count)") } | ||
| 249 | guard case .symbol(let variable) = args[0] else { throw Unsupported(what: "\(name) on a place") } | ||
| 250 | let current = try value(variable) | ||
| 251 | let delta = args.count > 1 ? try eval(args[1]) : .integer(1) | ||
| 252 | let new = try callNamed(decrement ? "-" : "+", [current, delta]) | ||
| 253 | assign(variable, new) | ||
| 254 | return new | ||
| 255 | } | ||
| 256 | } | ||
Sources/OrgCore/Config/ElispLibrary.swift added +349
| @@ -0,0 +1,349 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | // Math, string, list, seq and cl-lib functions of the evaluator. | ||
| 4 | |||
| 5 | extension Elisp { | ||
| 6 | static func library(_ lisp: Elisp) { | ||
| 7 | lisp.set("float-pi", .float(Double.pi)) | ||
| 8 | lisp.set("pi", .float(Double.pi)) | ||
| 9 | lisp.set("float-e", .float(M_E)) | ||
| 10 | mathFunctions(lisp) | ||
| 11 | stringFunctions(lisp) | ||
| 12 | sequenceFunctions(lisp) | ||
| 13 | } | ||
| 14 | |||
| 15 | static func mathFunctions(_ lisp: Elisp) { | ||
| 16 | let unary: [(String, (Double) -> Double)] = [("sqrt", { $0.squareRoot() }), ("exp", exp), ("sin", sin), ("cos", cos), ("tan", tan), ("asin", asin), ("acos", acos)] | ||
| 17 | for (name, f) in unary { | ||
| 18 | lisp.define(name) { _, args in | ||
| 19 | try arity(args, 1...1, name) | ||
| 20 | return .float(f(try number(args[0]).double)) | ||
| 21 | } | ||
| 22 | } | ||
| 23 | lisp.define("log") { _, args in | ||
| 24 | try arity(args, 1...2, "log") | ||
| 25 | let x = try number(args[0]).double | ||
| 26 | guard args.count == 2, !isNil(args[1]) else { return .float(Foundation.log(x)) } | ||
| 27 | let base = try number(args[1]).double | ||
| 28 | return .float(base == 10 ? log10(x) : base == 2 ? log2(x) : Foundation.log(x) / Foundation.log(base)) | ||
| 29 | } | ||
| 30 | lisp.define("atan") { _, args in | ||
| 31 | try arity(args, 1...2, "atan") | ||
| 32 | let y = try number(args[0]).double | ||
| 33 | return .float(args.count == 2 && !isNil(args[1]) ? atan2(y, try number(args[1]).double) : atan(y)) | ||
| 34 | } | ||
| 35 | lisp.define("expt") { _, args in | ||
| 36 | try arity(args, 2...2, "expt") | ||
| 37 | switch (try number(args[0]), try number(args[1])) { | ||
| 38 | case (.int(var base), .int(var exponent)) where exponent >= 0: | ||
| 39 | var result = 1 | ||
| 40 | while true { | ||
| 41 | if exponent & 1 == 1 { | ||
| 42 | let (product, overflow) = result.multipliedReportingOverflow(by: base) | ||
| 43 | if overflow { throw Unsupported(what: "integer size") } | ||
| 44 | result = product | ||
| 45 | } | ||
| 46 | exponent >>= 1 | ||
| 47 | if exponent == 0 { return .integer(result) } | ||
| 48 | let (square, overflow) = base.multipliedReportingOverflow(by: base) | ||
| 49 | if overflow { throw Unsupported(what: "integer size") } | ||
| 50 | base = square | ||
| 51 | } | ||
| 52 | case (let a, let b): | ||
| 53 | return .float(pow(a.double, b.double)) | ||
| 54 | } | ||
| 55 | } | ||
| 56 | lisp.define("isnan") { _, args in | ||
| 57 | try arity(args, 1...1, "isnan") | ||
| 58 | guard case .float(let d) = args[0] else { throw Signal(message: "Wrong type argument: floatp, \(args[0].description)") } | ||
| 59 | return bool(d.isNaN) | ||
| 60 | } | ||
| 61 | lisp.define("random") { _, args in | ||
| 62 | try arity(args, 0...1, "random") | ||
| 63 | switch args.first ?? .nil { | ||
| 64 | case .integer(let n): | ||
| 65 | guard n > 0 else { throw Signal(message: "Args out of range: \(n)") } | ||
| 66 | return .integer(Int.random(in: 0..<n)) | ||
| 67 | case let v where isNil(v) || v == t: | ||
| 68 | return .integer(Int.random(in: -(1 << 61)...((1 << 61) - 1))) | ||
| 69 | default: | ||
| 70 | throw Unsupported(what: "random with a seed") | ||
| 71 | } | ||
| 72 | } | ||
| 73 | for (name, identity, op) in [("logand", -1, { (a: Int, b: Int) in a & b }), ("logior", 0, { $0 | $1 }), ("logxor", 0, { $0 ^ $1 })] { | ||
| 74 | lisp.define(name) { _, args in .integer(try args.map(int).reduce(identity, op)) } | ||
| 75 | } | ||
| 76 | lisp.define("ash") { _, args in | ||
| 77 | try arity(args, 2...2, "ash") | ||
| 78 | let value = try int(args[0]) | ||
| 79 | let count = try int(args[1]) | ||
| 80 | if count < 0 { return .integer(value >> min(-count, 63)) } | ||
| 81 | guard count < 63, (value << count) >> count == value else { throw Unsupported(what: "integer size") } | ||
| 82 | return .integer(value << count) | ||
| 83 | } | ||
| 84 | } | ||
| 85 | |||
| 86 | static func stringFunctions(_ lisp: Elisp) { | ||
| 87 | lisp.define("string-join") { _, args in | ||
| 88 | try arity(args, 1...2, "string-join") | ||
| 89 | let separator = args.count > 1 && !isNil(args[1]) ? try string(args[1]) : "" | ||
| 90 | return .string(try elements(args[0]).map(printedString).joined(separator: separator)) | ||
| 91 | } | ||
| 92 | lisp.define("string-to-char") { _, args in | ||
| 93 | try arity(args, 1...1, "string-to-char") | ||
| 94 | return .integer(Int(try string(args[0]).unicodeScalars.first?.value ?? 0)) | ||
| 95 | } | ||
| 96 | lisp.define("char-to-string") { _, args in | ||
| 97 | try arity(args, 1...1, "char-to-string") | ||
| 98 | return .string(String(try scalar(try int(args[0])))) | ||
| 99 | } | ||
| 100 | lisp.define("string-pad") { _, args in | ||
| 101 | try arity(args, 2...4, "string-pad") | ||
| 102 | let s = try string(args[0]) | ||
| 103 | let length = try int(args[1]) | ||
| 104 | guard length >= 0 else { throw Signal(message: "Wrong type argument: natnump, \(length)") } | ||
| 105 | let pad = length - s.unicodeScalars.count | ||
| 106 | guard pad > 0 else { return .string(s) } | ||
| 107 | guard pad <= lengthLimit else { throw Signal(message: "Too long for string-pad") } | ||
| 108 | let padding = String(repeating: String(try scalar(args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 32)), count: pad) | ||
| 109 | return .string(args.count > 3 && !isNil(args[3]) ? padding + s : s + padding) | ||
| 110 | } | ||
| 111 | lisp.define("string-width") { _, args in | ||
| 112 | try arity(args, 1...3, "string-width") | ||
| 113 | let scalars = Array(try string(args[0]).unicodeScalars) | ||
| 114 | let from = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 0 | ||
| 115 | let to = args.count > 2 && !isNil(args[2]) ? try int(args[2]) : scalars.count | ||
| 116 | guard 0 <= from, from <= to, to <= scalars.count else { throw Signal(message: "Args out of range") } | ||
| 117 | return .integer(try scalars[from..<to].reduce(0) { width, c in | ||
| 118 | switch c.value { | ||
| 119 | case 9: return width + 8 | ||
| 120 | case 10: return width | ||
| 121 | case 0x20...0x7E, 0xC0...0x27F: return width + 1 | ||
| 122 | default: throw Unsupported(what: "string-width of \(String(c))") | ||
| 123 | } | ||
| 124 | }) | ||
| 125 | } | ||
| 126 | lisp.define("string-search") { _, args in | ||
| 127 | try arity(args, 2...3, "string-search") | ||
| 128 | let needle = Array(try string(args[0]).unicodeScalars) | ||
| 129 | let haystack = Array(try string(args[1]).unicodeScalars) | ||
| 130 | let start = args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 0 | ||
| 131 | guard (0...haystack.count).contains(start) else { throw Signal(message: "Args out of range: \(start)") } | ||
| 132 | guard needle.count <= haystack.count else { return .nil } | ||
| 133 | for i in start...(haystack.count - needle.count) where haystack[i..<(i + needle.count)].elementsEqual(needle) { return .integer(i) } | ||
| 134 | return .nil | ||
| 135 | } | ||
| 136 | lisp.define("string-replace") { _, args in | ||
| 137 | try arity(args, 3...3, "string-replace") | ||
| 138 | let from = try string(args[0]) | ||
| 139 | guard !from.isEmpty else { throw Signal(message: "Wrong length argument: 0") } | ||
| 140 | return .string(try string(args[2]).replacingOccurrences(of: from, with: try string(args[1]), options: .literal)) | ||
| 141 | } | ||
| 142 | } | ||
| 143 | |||
| 144 | /// The functions that change a list or vector in place, and what a variable holding the | ||
| 145 | /// argument holds after the call: the sorted list for an in-place `sort`, its first cell | ||
| 146 | /// for `nreverse`. | ||
| 147 | static func afterInPlace(_ name: String, _ args: [Sexp], _ result: Sexp) -> Sexp? { | ||
| 148 | switch name { | ||
| 149 | case "sort": | ||
| 150 | let inPlace = args.count == 2 || args.indices.contains { $0 % 2 == 1 && args[$0] == .symbol(":in-place") && $0 + 1 < args.count && !isNil(args[$0 + 1]) } | ||
| 151 | return inPlace ? result : nil | ||
| 152 | case "nreverse": | ||
| 153 | if case .list(let items) = args[0], let first = items.first { return .list([first]) } | ||
| 154 | return isNil(args[0]) ? nil : result | ||
| 155 | case "delete-dups": | ||
| 156 | return result | ||
| 157 | default: | ||
| 158 | return nil | ||
| 159 | } | ||
| 160 | } | ||
| 161 | |||
| 162 | /// Refuses `name` on a first argument that another value may share, when it changes it in | ||
| 163 | /// place. | ||
| 164 | static func refuseShared(_ lisp: Elisp, _ name: String, _ args: [Sexp], variable: String?) throws { | ||
| 165 | if afterInPlace(name, args, .nil) != nil { try lisp.refuseShared(args[0], variable: variable, name) } | ||
| 166 | } | ||
| 167 | |||
| 168 | /// Keyword arguments `args` after the first `count`, of which only `allowed` are known. | ||
| 169 | static func keywords(_ args: [Sexp], after count: Int, allowed: Set<String>, _ name: String) throws -> [String: Sexp] { | ||
| 170 | let rest = Array(args.dropFirst(count)) | ||
| 171 | guard rest.count % 2 == 0 else { throw Signal(message: "Odd number of keyword arguments for \(name)") } | ||
| 172 | var result: [String: Sexp] = [:] | ||
| 173 | for i in stride(from: 0, to: rest.count, by: 2) { | ||
| 174 | guard let key = rest[i].symbol, allowed.contains(key) else { throw Unsupported(what: "\(name) with \(rest[i].description)") } | ||
| 175 | if result[key] == nil { result[key] = rest[i + 1] } | ||
| 176 | } | ||
| 177 | return result | ||
| 178 | } | ||
| 179 | |||
| 180 | /// `value<` on numbers, strings and symbols. | ||
| 181 | static func valueLess(_ a: Sexp, _ b: Sexp) throws -> Bool { | ||
| 182 | if let x = try? number(a), let y = try? number(b) { | ||
| 183 | if case .int(let i) = x, case .int(let j) = y { return i < j } | ||
| 184 | return x.double < y.double | ||
| 185 | } | ||
| 186 | switch (a, b) { | ||
| 187 | case (.string(let x), .string(let y)): return x.unicodeScalars.map(\.value).lexicographicallyPrecedes(y.unicodeScalars.map(\.value)) | ||
| 188 | case (.symbol(let x), .symbol(let y)) where !isNil(a) && !isNil(b): return x.unicodeScalars.map(\.value).lexicographicallyPrecedes(y.unicodeScalars.map(\.value)) | ||
| 189 | default: throw Unsupported(what: "value< on \(a.description) and \(b.description)") | ||
| 190 | } | ||
| 191 | } | ||
| 192 | |||
| 193 | /// The first of each run of `equal` items, in order. | ||
| 194 | static func uniqueEqual(_ items: [Sexp]) -> [Sexp] { | ||
| 195 | var seen: [String: [Sexp]] = [:] | ||
| 196 | var kept: [Sexp] = [] | ||
| 197 | for item in items { | ||
| 198 | let value = normalized(item) | ||
| 199 | let key = printed(value, escape: true) | ||
| 200 | guard !(seen[key]?.contains(value) ?? false) else { continue } | ||
| 201 | seen[key, default: []].append(value) | ||
| 202 | kept.append(item) | ||
| 203 | } | ||
| 204 | return kept | ||
| 205 | } | ||
| 206 | |||
| 207 | /// A stable merge sort with a predicate that may throw. | ||
| 208 | static func stableSort(_ items: [Sexp], _ less: (Sexp, Sexp) throws -> Bool) throws -> [Sexp] { | ||
| 209 | guard items.count > 1 else { return items } | ||
| 210 | let left = try stableSort(Array(items[..<(items.count / 2)]), less) | ||
| 211 | let right = try stableSort(Array(items[(items.count / 2)...]), less) | ||
| 212 | var merged: [Sexp] = [] | ||
| 213 | merged.reserveCapacity(items.count) | ||
| 214 | var (i, j) = (0, 0) | ||
| 215 | while i < left.count, j < right.count { | ||
| 216 | if try less(right[j], left[i]) { | ||
| 217 | merged.append(right[j]) | ||
| 218 | j += 1 | ||
| 219 | } else { | ||
| 220 | merged.append(left[i]) | ||
| 221 | i += 1 | ||
| 222 | } | ||
| 223 | } | ||
| 224 | return merged + left[i...] + right[j...] | ||
| 225 | } | ||
| 226 | |||
| 227 | /// `items` as the kind of sequence `like` is. | ||
| 228 | static func sameKind(_ items: [Sexp], as like: Sexp) throws -> Sexp { | ||
| 229 | switch like { | ||
| 230 | case .vector: return .vector(items) | ||
| 231 | case .string: return .string(try printedString(.list(items))) | ||
| 232 | default: return list(items) | ||
| 233 | } | ||
| 234 | } | ||
| 235 | |||
| 236 | static func sequenceFunctions(_ lisp: Elisp) { | ||
| 237 | lisp.define("last") { _, args in | ||
| 238 | try arity(args, 1...2, "last") | ||
| 239 | let n = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 1 | ||
| 240 | switch args[0] { | ||
| 241 | case .list(let items): return list(Array(items.suffix(max(0, n)))) | ||
| 242 | case .dotted(let items, let tail): return n <= 0 ? tail : .dotted(Array(items.suffix(n)), tail) | ||
| 243 | case let v where isNil(v): return .nil | ||
| 244 | default: throw Signal(message: "Wrong type argument: listp, \(args[0].description)") | ||
| 245 | } | ||
| 246 | } | ||
| 247 | lisp.define("butlast") { _, args in | ||
| 248 | try arity(args, 1...2, "butlast") | ||
| 249 | let n = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 1 | ||
| 250 | guard n > 0 else { return args[0] } | ||
| 251 | return list(Array(try elements(args[0]).dropLast(n))) | ||
| 252 | } | ||
| 253 | lisp.define("delete-dups") { lisp, args in | ||
| 254 | let variable = lisp.takeInPlaceVariable() | ||
| 255 | try arity(args, 1...1, "delete-dups") | ||
| 256 | try refuseShared(lisp, "delete-dups", args, variable: variable) | ||
| 257 | return list(uniqueEqual(try elements(args[0]))) | ||
| 258 | } | ||
| 259 | lisp.define("nreverse") { lisp, args in | ||
| 260 | let variable = lisp.takeInPlaceVariable() | ||
| 261 | try arity(args, 1...1, "nreverse") | ||
| 262 | try refuseShared(lisp, "nreverse", args, variable: variable) | ||
| 263 | switch args[0] { | ||
| 264 | case .string(let s): return .string(String(String.UnicodeScalarView(s.unicodeScalars.reversed()))) | ||
| 265 | case .vector(let items): return .vector(items.reversed()) | ||
| 266 | default: return list(try elements(args[0]).reversed()) | ||
| 267 | } | ||
| 268 | } | ||
| 269 | lisp.define("sort") { lisp, args in | ||
| 270 | let variable = lisp.takeInPlaceVariable() | ||
| 271 | try arity(args, 1...Int.max, "sort") | ||
| 272 | var key = Sexp.nil | ||
| 273 | var lessp = Sexp.nil | ||
| 274 | var reverse = false | ||
| 275 | if args.count == 2 { | ||
| 276 | guard args[1].symbol?.hasPrefix(":") != true else { throw Signal(message: "Odd number of keyword arguments for sort") } | ||
| 277 | lessp = args[1] | ||
| 278 | } else { | ||
| 279 | let options = try keywords(args, after: 1, allowed: [":key", ":lessp", ":reverse", ":in-place"], "sort") | ||
| 280 | key = options[":key"] ?? .nil | ||
| 281 | lessp = options[":lessp"] ?? .nil | ||
| 282 | reverse = !isNil(options[":reverse"] ?? .nil) | ||
| 283 | } | ||
| 284 | let items: [Sexp] | ||
| 285 | switch args[0] { | ||
| 286 | case .vector(let v): items = v | ||
| 287 | case .string: throw Unsupported(what: "sort on a string") | ||
| 288 | default: items = try elements(args[0]) | ||
| 289 | } | ||
| 290 | try refuseShared(lisp, "sort", args, variable: variable) | ||
| 291 | let keyed = try items.map { isNil(key) ? ($0, $0) : ($0, try lisp.call(key, [$0])) } | ||
| 292 | func less(_ a: Sexp, _ b: Sexp) throws -> Bool { | ||
| 293 | isNil(lessp) ? try valueLess(a, b) : !isNil(try lisp.call(lessp, [a, b])) | ||
| 294 | } | ||
| 295 | let keys = keyed.map(\.1) | ||
| 296 | let order = try stableSort((0..<items.count).map { .integer($0) }) { a, b in | ||
| 297 | let (i, j) = (a.integer!, b.integer!) | ||
| 298 | return reverse ? try less(keys[j], keys[i]) : try less(keys[i], keys[j]) | ||
| 299 | } | ||
| 300 | let sorted = order.map { items[$0.integer!] } | ||
| 301 | if case .vector = args[0] { return .vector(sorted) } | ||
| 302 | return list(sorted) | ||
| 303 | } | ||
| 304 | lisp.define("seq-reduce") { lisp, args in | ||
| 305 | try arity(args, 3...3, "seq-reduce") | ||
| 306 | return try sequence(args[1]).reduce(args[2]) { try lisp.call(args[0], [$0, $1]) } | ||
| 307 | } | ||
| 308 | for name in ["seq-filter", "seq-remove"] { | ||
| 309 | lisp.define(name) { lisp, args in | ||
| 310 | try arity(args, 2...2, name) | ||
| 311 | return list(try sequence(args[1]).filter { isNil(try lisp.call(args[0], [$0])) == (name == "seq-remove") }) | ||
| 312 | } | ||
| 313 | } | ||
| 314 | lisp.define("seq-map") { lisp, args in | ||
| 315 | try arity(args, 2...2, "seq-map") | ||
| 316 | return list(try sequence(args[1]).map { try lisp.call(args[0], [$0]) }) | ||
| 317 | } | ||
| 318 | lisp.define("seq-uniq") { _, args in | ||
| 319 | try arity(args, 1...2, "seq-uniq") | ||
| 320 | guard args.count == 1 || isNil(args[1]) else { throw Unsupported(what: "seq-uniq with a test") } | ||
| 321 | return list(uniqueEqual(try sequence(args[0]))) | ||
| 322 | } | ||
| 323 | lisp.define("cl-reduce") { lisp, args in | ||
| 324 | try arity(args, 2...Int.max, "cl-reduce") | ||
| 325 | let options = try keywords(args, after: 2, allowed: [":initial-value"], "cl-reduce") | ||
| 326 | var items = try sequence(args[1])[...] | ||
| 327 | guard let initial = options[":initial-value"] ?? items.popFirst() else { return try lisp.call(args[0], []) } | ||
| 328 | return try items.reduce(initial) { try lisp.call(args[0], [$0, $1]) } | ||
| 329 | } | ||
| 330 | for name in ["cl-remove-if", "cl-remove-if-not"] { | ||
| 331 | lisp.define(name) { lisp, args in | ||
| 332 | try arity(args, 2...Int.max, name) | ||
| 333 | _ = try keywords(args, after: 2, allowed: [], name) | ||
| 334 | return try sameKind(try sequence(args[1]).filter { isNil(try lisp.call(args[0], [$0])) == (name == "cl-remove-if") }, as: args[1]) | ||
| 335 | } | ||
| 336 | } | ||
| 337 | for name in ["cl-find", "cl-position"] { | ||
| 338 | lisp.define(name) { lisp, args in | ||
| 339 | try arity(args, 2...Int.max, name) | ||
| 340 | let test = try keywords(args, after: 2, allowed: [":test"], name)[":test"] ?? .nil | ||
| 341 | for (i, item) in try sequence(args[1]).enumerated() { | ||
| 342 | let found = isNil(test) ? eq(args[0], item) : !isNil(try lisp.call(test, [args[0], item])) | ||
| 343 | if found { return name == "cl-find" ? item : .integer(i) } | ||
| 344 | } | ||
| 345 | return .nil | ||
| 346 | } | ||
| 347 | } | ||
| 348 | } | ||
| 349 | } | ||
Sources/OrgCore/Config/ElispRegex.swift added +535
| @@ -0,0 +1,535 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// `char-syntax` of each ASCII character in a syntax table. | ||
| 4 | struct ElispSyntax: Equatable { | ||
| 5 | let classes: [Character] | ||
| 6 | |||
| 7 | /// `org-mode-syntax-table`, where table formulas run. | ||
| 8 | static let org = ElispSyntax(classes: Array("......... . .................. .\".ww_w()__._._wwwwwwwwww..(_)..wwwwwwwwwwwwwwwwwwwwwwwwww(_)._.wwwwwwwwwwwwwwwwwwwwwwwwww(_)_.")) | ||
| 9 | /// `lisp-interaction-mode`'s table, which `emacs -Q --batch -l` evaluates Emacs Lisp | ||
| 10 | /// blocks with, in `*scratch*`. | ||
| 11 | static let emacsLisp = ElispSyntax(classes: Array("_________ >_ ___________________ _\"'___'()__'___wwwwwwwwww_<_____wwwwwwwwwwwwwwwwwwwwwwwwww(\\)__'wwwwwwwwwwwwwwwwwwwwwwwwww_____")) | ||
| 12 | |||
| 13 | func codes(_ syntaxClass: Character) -> [UInt32] { | ||
| 14 | classes.indices.filter { classes[$0] == syntaxClass }.map(UInt32.init) | ||
| 15 | } | ||
| 16 | |||
| 17 | var word: [UInt32] { codes("w") } | ||
| 18 | var symbol: [UInt32] { word + codes("_") } | ||
| 19 | |||
| 20 | func isWord(_ c: Unicode.Scalar) -> Bool { c.isASCII && classes[Int(c.value)] == "w" } | ||
| 21 | } | ||
| 22 | |||
| 23 | /// An Emacs regexp as an `NSRegularExpression`, with the syntax table of the buffer it runs | ||
| 24 | /// in. A construct it can't translate exactly throws `Elisp.Unsupported`, and so do subjects | ||
| 25 | /// where ICU's tables could differ from Emacs's: syntax classes against text past ASCII, and | ||
| 26 | /// case folding with letters past ASCII. | ||
| 27 | struct ElispRegex { | ||
| 28 | let pattern: String | ||
| 29 | let groups: Int | ||
| 30 | /// Has letters, ranges over letters or case classes: case folding changes what matches. | ||
| 31 | let foldable: Bool | ||
| 32 | /// Has classes whose members past ASCII come from Emacs's syntax or Unicode tables. | ||
| 33 | let asciiClasses: Bool | ||
| 34 | /// Has letters with case past ASCII. | ||
| 35 | let nonASCIILetters: Bool | ||
| 36 | let plain: NSRegularExpression | ||
| 37 | let folded: NSRegularExpression | ||
| 38 | |||
| 39 | static func hex(_ c: UInt32) -> String { "\\x{" + String(c, radix: 16) + "}" } | ||
| 40 | |||
| 41 | static func set(_ codes: [UInt32], negated: Bool = false) -> String { | ||
| 42 | "[" + (negated ? "^" : "") + codes.map(hex).joined() + "]" | ||
| 43 | } | ||
| 44 | |||
| 45 | /// A letter with case, which case folding changes. | ||
| 46 | static func isLetter(_ c: UInt32) -> Bool { | ||
| 47 | (65...90).contains(c) || (97...122).contains(c) || c > 127 && Unicode.Scalar(c).map { $0.properties.changesWhenCaseMapped || $0.properties.changesWhenCaseFolded } ?? false | ||
| 48 | } | ||
| 49 | |||
| 50 | init(_ pattern: String, syntax: ElispSyntax = .org) throws { | ||
| 51 | self.pattern = pattern | ||
| 52 | let p = Array(pattern.unicodeScalars) | ||
| 53 | var out = "" | ||
| 54 | var groups = 0 | ||
| 55 | var open: [Int] = [] | ||
| 56 | var closed: Set<Int> = [] | ||
| 57 | var foldable = false | ||
| 58 | var asciiClasses = false | ||
| 59 | // Where `^` is an anchor, and where `*`, `+` and `?` are ordinary characters: at the | ||
| 60 | // start, after `\(` or `\|`, and for the second also after that `^`. | ||
| 61 | var anchor = true | ||
| 62 | var ordinary = true | ||
| 63 | var quantifiable = false | ||
| 64 | // After a repetition, and whether a `?` may make it non-greedy. | ||
| 65 | var quantified = false | ||
| 66 | var lazy = false | ||
| 67 | var i = 0 | ||
| 68 | func unsupported(_ what: String) -> Elisp.Unsupported { Elisp.Unsupported(what: "regexp \(what) in \(Elisp.printed(.string(pattern), escape: true))") } | ||
| 69 | func literal(_ c: Unicode.Scalar) { | ||
| 70 | if c.isASCII, c.properties.isAlphabetic || ("0"..."9").contains(c) { out.unicodeScalars.append(c) } else { out += Self.hex(c.value) } | ||
| 71 | if Self.isLetter(c.value) { foldable = true } | ||
| 72 | (anchor, ordinary, quantifiable, quantified) = (false, false, true, false) | ||
| 73 | } | ||
| 74 | func atom(_ text: String) { | ||
| 75 | out += text | ||
| 76 | (anchor, ordinary, quantifiable, quantified) = (false, false, true, false) | ||
| 77 | } | ||
| 78 | func assertion(_ text: String) { | ||
| 79 | out += text | ||
| 80 | (anchor, ordinary, quantifiable, quantified) = (false, false, false, false) | ||
| 81 | } | ||
| 82 | while i < p.count { | ||
| 83 | let c = p[i] | ||
| 84 | i += 1 | ||
| 85 | switch c { | ||
| 86 | case "^": | ||
| 87 | if anchor { | ||
| 88 | out += "(?:(?<![\\s\\S])|(?<=\\n))" | ||
| 89 | anchor = false | ||
| 90 | } else { | ||
| 91 | literal(c) | ||
| 92 | } | ||
| 93 | case "$": | ||
| 94 | let rest = p[i...] | ||
| 95 | if rest.isEmpty || rest.starts(with: ["\\", ")"]) || rest.starts(with: ["\\", "|"]) { | ||
| 96 | assertion("(?=\\n|(?![\\s\\S]))") | ||
| 97 | } else { | ||
| 98 | literal(c) | ||
| 99 | } | ||
| 100 | case ".": | ||
| 101 | atom("[^\\n]") | ||
| 102 | case "*", "+", "?": | ||
| 103 | if quantified { | ||
| 104 | guard c == "?", lazy else { throw unsupported("\(c) after a repetition") } | ||
| 105 | out += "?" | ||
| 106 | lazy = false | ||
| 107 | } else if quantifiable { | ||
| 108 | out.unicodeScalars.append(c) | ||
| 109 | (quantifiable, quantified, lazy) = (false, true, true) | ||
| 110 | } else if ordinary { | ||
| 111 | literal(c) | ||
| 112 | } else { | ||
| 113 | throw unsupported(String(c)) | ||
| 114 | } | ||
| 115 | case "[": | ||
| 116 | var j = i | ||
| 117 | var text = "[" | ||
| 118 | if j < p.count, p[j] == "^" { | ||
| 119 | text += "^" | ||
| 120 | j += 1 | ||
| 121 | } | ||
| 122 | var first = true | ||
| 123 | while true { | ||
| 124 | guard j < p.count else { throw unsupported("[") } | ||
| 125 | let c = p[j] | ||
| 126 | if c == "]", !first { | ||
| 127 | j += 1 | ||
| 128 | break | ||
| 129 | } | ||
| 130 | first = false | ||
| 131 | if c == "[", j + 1 < p.count, p[j + 1] == ":" { | ||
| 132 | var k = j + 2 | ||
| 133 | var name = "" | ||
| 134 | while k + 1 < p.count, !(p[k] == ":" && p[k + 1] == "]") { | ||
| 135 | name.unicodeScalars.append(p[k]) | ||
| 136 | k += 1 | ||
| 137 | } | ||
| 138 | guard k + 1 < p.count else { throw unsupported("[:") } | ||
| 139 | j = k + 2 | ||
| 140 | let ascii: (String, Bool, Bool) = switch name { | ||
| 141 | case "alpha": ("A-Za-z", true, false) | ||
| 142 | case "alnum": ("0-9A-Za-z", true, false) | ||
| 143 | case "upper": ("A-Z", true, true) | ||
| 144 | case "lower": ("a-z", true, true) | ||
| 145 | case "digit": ("0-9", false, false) | ||
| 146 | case "xdigit": ("0-9A-Fa-f", false, false) | ||
| 147 | case "cntrl": ("\\x{0}-\\x{1f}", false, false) | ||
| 148 | case "ascii": ("\\x{0}-\\x{7f}", false, false) | ||
| 149 | case "nonascii": ("\\x{80}-\\x{10ffff}", false, false) | ||
| 150 | case "space": (syntax.codes(" ").map(Self.hex).joined(), true, false) | ||
| 151 | case "blank": ("\\x{9}\\x{20}", true, false) | ||
| 152 | case "punct": ((33...126).filter { !Self.isLetter($0) && !(48...57).contains($0) }.map(Self.hex).joined(), true, false) | ||
| 153 | case "graph": ("\\x{21}-\\x{7e}", true, false) | ||
| 154 | case "print": ("\\x{20}-\\x{7e}", true, false) | ||
| 155 | case "word": (syntax.word.map(Self.hex).joined(), true, false) | ||
| 156 | default: throw unsupported("[:\(name):]") | ||
| 157 | } | ||
| 158 | text += ascii.0 | ||
| 159 | if ascii.1 { asciiClasses = true } | ||
| 160 | if ascii.2 { foldable = true } | ||
| 161 | continue | ||
| 162 | } | ||
| 163 | if j + 2 < p.count, p[j + 1] == "-", p[j + 2] != "]" { | ||
| 164 | let end = p[j + 2] | ||
| 165 | guard c.value <= end.value else { throw unsupported("range") } | ||
| 166 | text += Self.hex(c.value) + "-" + Self.hex(end.value) | ||
| 167 | if end.value >= 65, c.value <= 122 || end.value > 127 { foldable = true } | ||
| 168 | j += 3 | ||
| 169 | continue | ||
| 170 | } | ||
| 171 | text += Self.hex(c.value) | ||
| 172 | if Self.isLetter(c.value) { foldable = true } | ||
| 173 | j += 1 | ||
| 174 | } | ||
| 175 | i = j | ||
| 176 | atom(text + "]") | ||
| 177 | case "\\": | ||
| 178 | guard i < p.count else { throw unsupported("\\ at the end") } | ||
| 179 | let e = p[i] | ||
| 180 | i += 1 | ||
| 181 | switch e { | ||
| 182 | case "(": | ||
| 183 | if i < p.count, p[i] == "?" { | ||
| 184 | guard i + 1 < p.count, p[i + 1] == ":" else { throw unsupported("\\(?") } | ||
| 185 | i += 2 | ||
| 186 | out += "(?:" | ||
| 187 | open.append(0) | ||
| 188 | } else { | ||
| 189 | groups += 1 | ||
| 190 | out += "(" | ||
| 191 | open.append(groups) | ||
| 192 | } | ||
| 193 | (anchor, ordinary, quantifiable, quantified) = (true, true, false, false) | ||
| 194 | case ")": | ||
| 195 | guard let n = open.popLast() else { throw unsupported("\\)") } | ||
| 196 | closed.insert(n) | ||
| 197 | atom(")") | ||
| 198 | case "|": | ||
| 199 | out += "|" | ||
| 200 | (anchor, ordinary, quantifiable, quantified) = (true, true, false, false) | ||
| 201 | case "{": | ||
| 202 | guard quantifiable else { throw unsupported("\\{") } | ||
| 203 | var low = "" | ||
| 204 | var high: String? | ||
| 205 | while i < p.count, ("0"..."9").contains(p[i]) { | ||
| 206 | low.unicodeScalars.append(p[i]) | ||
| 207 | i += 1 | ||
| 208 | } | ||
| 209 | if i < p.count, p[i] == "," { | ||
| 210 | i += 1 | ||
| 211 | var digits = "" | ||
| 212 | while i < p.count, ("0"..."9").contains(p[i]) { | ||
| 213 | digits.unicodeScalars.append(p[i]) | ||
| 214 | i += 1 | ||
| 215 | } | ||
| 216 | high = digits | ||
| 217 | } | ||
| 218 | guard i + 1 < p.count, p[i] == "\\", p[i + 1] == "}", !low.isEmpty || high != nil else { throw unsupported("\\{") } | ||
| 219 | i += 2 | ||
| 220 | out += "{" + (low.isEmpty ? "0" : low) + (high.map { "," + $0 } ?? "") + "}" | ||
| 221 | (quantifiable, quantified, lazy) = (false, true, false) | ||
| 222 | case "1"..."9": | ||
| 223 | let n = Int(e.value) - 48 | ||
| 224 | guard closed.contains(n) else { throw unsupported("\\\(n)") } | ||
| 225 | atom("(?:\\\(n))") | ||
| 226 | case "w", "W": | ||
| 227 | asciiClasses = true | ||
| 228 | atom(Self.set(syntax.word, negated: e == "W")) | ||
| 229 | case "s", "S": | ||
| 230 | guard i < p.count else { throw unsupported("\\s") } | ||
| 231 | let code: Character = switch p[i] { | ||
| 232 | case "-", " ": " " | ||
| 233 | case "w", "_", ".", "(", ")", "\"": Character(p[i]) | ||
| 234 | default: throw unsupported("\\s\(p[i])") | ||
| 235 | } | ||
| 236 | i += 1 | ||
| 237 | asciiClasses = true | ||
| 238 | let codes = syntax.codes(code) | ||
| 239 | atom(codes.isEmpty ? (e == "S" ? "[\\s\\S]" : "[^\\s\\S]") : Self.set(codes, negated: e == "S")) | ||
| 240 | case "b", "B", "<", ">": | ||
| 241 | asciiClasses = true | ||
| 242 | let w = Self.set(syntax.word) | ||
| 243 | let text = switch e { | ||
| 244 | case "b": "(?:(?<=\(w))(?!\(w))|(?<!\(w))(?=\(w)))" | ||
| 245 | case "B": "(?:(?<=\(w))(?=\(w))|(?<!\(w))(?!\(w)))" | ||
| 246 | case "<": "(?<!\(w))(?=\(w))" | ||
| 247 | default: "(?<=\(w))(?!\(w))" | ||
| 248 | } | ||
| 249 | assertion(text) | ||
| 250 | case "_": | ||
| 251 | guard i < p.count, p[i] == "<" || p[i] == ">" else { throw unsupported("\\_") } | ||
| 252 | asciiClasses = true | ||
| 253 | let s = Self.set(syntax.symbol) | ||
| 254 | assertion(p[i] == "<" ? "(?<!\(s))(?=\(s))" : "(?<=\(s))(?!\(s))") | ||
| 255 | i += 1 | ||
| 256 | case "`": | ||
| 257 | assertion("(?<![\\s\\S])") | ||
| 258 | case "'": | ||
| 259 | assertion("(?![\\s\\S])") | ||
| 260 | default: | ||
| 261 | guard !e.isASCII || !(e.properties.isAlphabetic || ("0"..."9").contains(e) || e == "}") else { throw unsupported("\\\(e)") } | ||
| 262 | literal(e) | ||
| 263 | } | ||
| 264 | default: | ||
| 265 | literal(c) | ||
| 266 | } | ||
| 267 | } | ||
| 268 | guard open.isEmpty else { throw unsupported("\\(") } | ||
| 269 | self.groups = groups | ||
| 270 | self.foldable = foldable | ||
| 271 | self.asciiClasses = asciiClasses | ||
| 272 | nonASCIILetters = p.contains { !$0.isASCII && Self.isLetter($0.value) } | ||
| 273 | do { | ||
| 274 | plain = try NSRegularExpression(pattern: out.isEmpty ? "(?:)" : out) | ||
| 275 | folded = try NSRegularExpression(pattern: out.isEmpty ? "(?:)" : out, options: .caseInsensitive) | ||
| 276 | } catch { | ||
| 277 | throw unsupported("syntax") | ||
| 278 | } | ||
| 279 | } | ||
| 280 | |||
| 281 | /// The first match at or after character `start`: each group's range in characters, nil | ||
| 282 | /// for groups that didn't match. | ||
| 283 | func firstMatch(in s: String, from start: Int, caseFold: Bool) throws -> [Range<Int>?]? { | ||
| 284 | let subjectNonASCII = s.unicodeScalars.contains { !$0.isASCII } | ||
| 285 | if asciiClasses, subjectNonASCII { throw Elisp.Unsupported(what: "regexp classes on text past ASCII") } | ||
| 286 | // Folding agrees for ASCII letters, unless the text has a character whose case maps | ||
| 287 | // to ASCII, like the Kelvin sign or ß. | ||
| 288 | if caseFold, foldable, nonASCIILetters || subjectNonASCII && s.unicodeScalars.contains(where: { c in | ||
| 289 | !c.isASCII && (String(c).lowercased() + String(c).uppercased()).unicodeScalars.contains(where: \.isASCII) | ||
| 290 | }) { | ||
| 291 | throw Elisp.Unsupported(what: "case folding past ASCII") | ||
| 292 | } | ||
| 293 | // UTF-16 offset of each character, and the end. | ||
| 294 | var offsets = [0] | ||
| 295 | if subjectNonASCII { | ||
| 296 | for scalar in s.unicodeScalars { offsets.append(offsets.last! + scalar.utf16.count) } | ||
| 297 | } | ||
| 298 | func utf16(_ i: Int) -> Int { subjectNonASCII ? offsets[i] : i } | ||
| 299 | func character(_ u: Int) -> Int { | ||
| 300 | guard subjectNonASCII else { return u } | ||
| 301 | var low = 0 | ||
| 302 | var high = offsets.count - 1 | ||
| 303 | while low < high { | ||
| 304 | let mid = (low + high) / 2 | ||
| 305 | if offsets[mid] < u { low = mid + 1 } else { high = mid } | ||
| 306 | } | ||
| 307 | return low | ||
| 308 | } | ||
| 309 | let length = (s as NSString).length | ||
| 310 | let from = utf16(start) | ||
| 311 | guard let m = (caseFold ? folded : plain).firstMatch(in: s, options: [.withTransparentBounds, .withoutAnchoringBounds], | ||
| 312 | range: NSRange(location: from, length: length - from)) else { return nil } | ||
| 313 | return (0...groups).map { g in | ||
| 314 | let r = m.range(at: g) | ||
| 315 | return r.location == NSNotFound ? nil : character(r.location)..<character(NSMaxRange(r)) | ||
| 316 | } | ||
| 317 | } | ||
| 318 | } | ||
| 319 | |||
| 320 | extension Elisp { | ||
| 321 | /// `case-fold-search`. | ||
| 322 | var caseFold: Bool { (try? value("case-fold-search")).map { !Self.isNil($0) } ?? true } | ||
| 323 | |||
| 324 | func regex(_ pattern: String) throws -> ElispRegex { | ||
| 325 | if let cached = regexes[pattern] { return cached } | ||
| 326 | let compiled = try ElispRegex(pattern, syntax: syntax) | ||
| 327 | regexes[pattern] = compiled | ||
| 328 | return compiled | ||
| 329 | } | ||
| 330 | |||
| 331 | /// `string-match`: the match data, or nil. | ||
| 332 | func stringMatch(_ pattern: String, _ s: String, start: Sexp = .nil) throws -> [Range<Int>?]? { | ||
| 333 | let count = s.unicodeScalars.count | ||
| 334 | var from = Self.isNil(start) ? 0 : try Self.int(start) | ||
| 335 | if from < 0 { from += count } | ||
| 336 | guard (0...count).contains(from) else { throw Signal(message: "Args out of range: \(Self.printed(.string(s), escape: true)), \(Self.printed(start))") } | ||
| 337 | return try regex(pattern).firstMatch(in: s, from: from, caseFold: caseFold) | ||
| 338 | } | ||
| 339 | |||
| 340 | static func substring(_ s: String, _ range: Range<Int>) throws -> String { | ||
| 341 | let scalars = Array(s.unicodeScalars) | ||
| 342 | guard range.upperBound <= scalars.count else { throw Signal(message: "Args out of range") } | ||
| 343 | return String(String.UnicodeScalarView(scalars[range])) | ||
| 344 | } | ||
| 345 | |||
| 346 | /// `replace-match` on a string, with the match data in characters of `s`. | ||
| 347 | func replaceMatch(_ newText: String, fixedCase: Bool, literal: Bool, in s: String, subexp: Int) throws -> String { | ||
| 348 | guard subexp < matchData.count, let target = matchData[subexp] else { | ||
| 349 | throw Signal(message: "replace-match subexpression does not exist") | ||
| 350 | } | ||
| 351 | var text = "" | ||
| 352 | if literal { | ||
| 353 | text = newText | ||
| 354 | } else { | ||
| 355 | var chars = newText.unicodeScalars.makeIterator() | ||
| 356 | while let c = chars.next() { | ||
| 357 | guard c == "\\" else { | ||
| 358 | text.unicodeScalars.append(c) | ||
| 359 | continue | ||
| 360 | } | ||
| 361 | switch chars.next() { | ||
| 362 | case "&": text += try Self.substring(s, matchData[0]!) | ||
| 363 | case "\\": text += "\\" | ||
| 364 | // Kept as is, for `query-replace-regexp`. | ||
| 365 | case "?": text += "\\?" | ||
| 366 | case let d? where ("1"..."9").contains(d): | ||
| 367 | let n = Int(d.value) - 48 | ||
| 368 | if n < matchData.count, let r = matchData[n] { text += try Self.substring(s, r) } | ||
| 369 | default: throw Signal(message: "Invalid use of ‘\\’ in replacement text") | ||
| 370 | } | ||
| 371 | } | ||
| 372 | } | ||
| 373 | let old = try Self.substring(s, target) | ||
| 374 | if !fixedCase, !old.unicodeScalars.allSatisfy(\.isASCII) { | ||
| 375 | // Past ASCII, only the cases that keep the replacement's case: no letter with a | ||
| 376 | // case, or a lowercase letter first. | ||
| 377 | let first = old.unicodeScalars.first.map { $0.properties.isLowercase && $0.properties.changesWhenUppercased } ?? false | ||
| 378 | guard first || !old.unicodeScalars.contains(where: \.properties.changesWhenCaseMapped) else { | ||
| 379 | throw Unsupported(what: "replace-match case past ASCII") | ||
| 380 | } | ||
| 381 | } else if !fixedCase { | ||
| 382 | // How `replace-match` decides to change the replacement's case from the replaced text. | ||
| 383 | let isWord = syntax.isWord | ||
| 384 | var (multiletter, lower, nonUpperInitial, upper) = (false, false, false, false) | ||
| 385 | var previous: Unicode.Scalar = "\n" | ||
| 386 | for c in old.unicodeScalars { | ||
| 387 | if ("a"..."z").contains(c) { | ||
| 388 | lower = true | ||
| 389 | if isWord(previous) { multiletter = true } else { nonUpperInitial = true } | ||
| 390 | } else if ("A"..."Z").contains(c) { | ||
| 391 | upper = true | ||
| 392 | if isWord(previous) { multiletter = true } | ||
| 393 | } else if !isWord(previous), isWord(c) { | ||
| 394 | nonUpperInitial = true | ||
| 395 | } | ||
| 396 | previous = c | ||
| 397 | } | ||
| 398 | let allCaps = (!lower && multiletter) || (!nonUpperInitial && !multiletter && upper) | ||
| 399 | let initials = !allCaps && !nonUpperInitial && multiletter | ||
| 400 | if allCaps || initials { | ||
| 401 | guard text.unicodeScalars.allSatisfy(\.isASCII) else { throw Unsupported(what: "replace-match case past ASCII") } | ||
| 402 | if allCaps { | ||
| 403 | text = text.uppercased() | ||
| 404 | } else { | ||
| 405 | var result = "" | ||
| 406 | var previous: Unicode.Scalar = "\n" | ||
| 407 | for c in text.unicodeScalars { | ||
| 408 | result += !isWord(previous) ? String(c).uppercased() : String(c) | ||
| 409 | previous = c | ||
| 410 | } | ||
| 411 | text = result | ||
| 412 | } | ||
| 413 | } | ||
| 414 | } | ||
| 415 | let scalars = Array(s.unicodeScalars) | ||
| 416 | return String(String.UnicodeScalarView(scalars[..<target.lowerBound])) + text + String(String.UnicodeScalarView(scalars[target.upperBound...])) | ||
| 417 | } | ||
| 418 | |||
| 419 | static func regexFunctions(_ lisp: Elisp) { | ||
| 420 | lisp.set("case-fold-search", t) | ||
| 421 | for name in ["string-match", "string-match-p"] { | ||
| 422 | lisp.define(name) { lisp, args in | ||
| 423 | try arity(args, 2...4, name) | ||
| 424 | guard let data = try lisp.stringMatch(try string(args[0]), try string(args[1]), start: args.count > 2 ? args[2] : .nil) else { return .nil } | ||
| 425 | if name == "string-match" { lisp.matchData = data } | ||
| 426 | return .integer(data[0]!.lowerBound) | ||
| 427 | } | ||
| 428 | } | ||
| 429 | for name in ["match-beginning", "match-end"] { | ||
| 430 | lisp.define(name) { lisp, args in | ||
| 431 | try arity(args, 1...1, name) | ||
| 432 | let n = try int(args[0]) | ||
| 433 | guard n >= 0 else { throw Signal(message: "Args out of range: \(n)") } | ||
| 434 | guard n < lisp.matchData.count, let r = lisp.matchData[n] else { return .nil } | ||
| 435 | return .integer(name == "match-beginning" ? r.lowerBound : r.upperBound) | ||
| 436 | } | ||
| 437 | } | ||
| 438 | for name in ["match-string", "match-string-no-properties"] { | ||
| 439 | lisp.define(name) { lisp, args in | ||
| 440 | try arity(args, 1...2, name) | ||
| 441 | guard args.count == 2, !isNil(args[1]) else { throw Unsupported(what: "\(name) in a buffer") } | ||
| 442 | let n = try int(args[0]) | ||
| 443 | guard n >= 0, n < lisp.matchData.count, let r = lisp.matchData[n] else { return .nil } | ||
| 444 | return .string(try substring(try string(args[1]), r)) | ||
| 445 | } | ||
| 446 | } | ||
| 447 | lisp.define("replace-match") { lisp, args in | ||
| 448 | try arity(args, 1...5, "replace-match") | ||
| 449 | guard args.count > 3, !isNil(args[3]) else { throw Unsupported(what: "replace-match in a buffer") } | ||
| 450 | return .string(try lisp.replaceMatch(try string(args[0]), fixedCase: args.count > 1 && !isNil(args[1]), literal: args.count > 2 && !isNil(args[2]), | ||
| 451 | in: try string(args[3]), subexp: args.count > 4 && !isNil(args[4]) ? try int(args[4]) : 0)) | ||
| 452 | } | ||
| 453 | lisp.define("replace-regexp-in-string") { lisp, args in | ||
| 454 | try arity(args, 3...7, "replace-regexp-in-string") | ||
| 455 | func optional(_ i: Int) -> Sexp { i < args.count ? args[i] : .nil } | ||
| 456 | let regexp = try string(args[0]) | ||
| 457 | let s = try string(args[2]) | ||
| 458 | let scalars = Array(s.unicodeScalars) | ||
| 459 | func piece(_ r: Range<Int>) -> String { String(String.UnicodeScalarView(scalars[r])) } | ||
| 460 | let l = scalars.count | ||
| 461 | var start = isNil(optional(6)) ? 0 : try int(optional(6)) | ||
| 462 | guard start >= 0 else { throw Unsupported(what: "replace-regexp-in-string from the end") } | ||
| 463 | var matches = "" | ||
| 464 | let saved = lisp.matchData | ||
| 465 | defer { lisp.matchData = saved } | ||
| 466 | while start < l, let data = try lisp.stringMatch(regexp, s, start: .integer(start)) { | ||
| 467 | lisp.matchData = data | ||
| 468 | let mb = data[0]!.lowerBound | ||
| 469 | var me = data[0]!.upperBound | ||
| 470 | if me == mb { me = min(l, mb + 1) } | ||
| 471 | lisp.matchData = data.map { $0.map { ($0.lowerBound - mb)..<($0.upperBound - mb) } } | ||
| 472 | let str = piece(mb..<me) | ||
| 473 | let rep: String | ||
| 474 | if case .string(let text) = args[1] { | ||
| 475 | rep = text | ||
| 476 | } else { | ||
| 477 | rep = try string(try lisp.call(args[1], [.string(try substring(str, lisp.matchData[0]!))])) | ||
| 478 | } | ||
| 479 | matches += piece(start..<mb) | ||
| 480 | matches += try lisp.replaceMatch(rep, fixedCase: !isNil(optional(3)), literal: !isNil(optional(4)), in: str, | ||
| 481 | subexp: isNil(optional(5)) ? 0 : try int(optional(5))) | ||
| 482 | start = me | ||
| 483 | } | ||
| 484 | guard start <= l else { throw Signal(message: "Args out of range") } | ||
| 485 | return .string(matches + piece(start..<l)) | ||
| 486 | } | ||
| 487 | lisp.define("regexp-quote") { _, args in | ||
| 488 | try arity(args, 1...1, "regexp-quote") | ||
| 489 | var out = "" | ||
| 490 | for c in try string(args[0]).unicodeScalars { | ||
| 491 | if "[*.\\?+^$".unicodeScalars.contains(c) { out += "\\" } | ||
| 492 | out.unicodeScalars.append(c) | ||
| 493 | } | ||
| 494 | return .string(out) | ||
| 495 | } | ||
| 496 | lisp.define("split-string") { lisp, args in | ||
| 497 | try arity(args, 1...4, "split-string") | ||
| 498 | func optional(_ i: Int) -> Sexp { i < args.count ? args[i] : .nil } | ||
| 499 | let s = try string(args[0]) | ||
| 500 | let length = s.unicodeScalars.count | ||
| 501 | let keepEmpty = !isNil(optional(1)) && isNil(optional(2)) | ||
| 502 | let separators = isNil(optional(1)) ? "[ \u{0C}\t\n\r\u{0B}]+" : try string(optional(1)) | ||
| 503 | let trim = isNil(optional(3)) ? nil : try string(optional(3)) | ||
| 504 | var list: [Sexp] = [] | ||
| 505 | // The loop of Emacs 31's `split-string`, empty separator matches included. | ||
| 506 | func push(_ item: String, last: Bool) throws { | ||
| 507 | guard let trim else { | ||
| 508 | if !last || keepEmpty || !item.isEmpty { list.append(.string(item)) } | ||
| 509 | return | ||
| 510 | } | ||
| 511 | let count = item.unicodeScalars.count | ||
| 512 | var begin = 0 | ||
| 513 | if let data = try lisp.stringMatch("\\`\\(?:" + trim + "\\)", item) { | ||
| 514 | lisp.matchData = data | ||
| 515 | begin = data[0]!.upperBound | ||
| 516 | } | ||
| 517 | let end = try lisp.stringMatch("\\(?:" + trim + "\\)\\'", item, start: .integer(begin))?[0]!.lowerBound ?? count | ||
| 518 | let trimmed = begin > 0 || end < count ? try substring(item, begin..<end) : item | ||
| 519 | if keepEmpty || (last ? !trimmed.isEmpty : begin < end) { list.append(.string(trimmed)) } | ||
| 520 | } | ||
| 521 | var next = 0 | ||
| 522 | var start = 0 | ||
| 523 | while let data = try lisp.stringMatch(separators, s, start: .integer(next)) { | ||
| 524 | lisp.matchData = data | ||
| 525 | let separator = data[0]! | ||
| 526 | if keepEmpty || start < separator.lowerBound { try push(try substring(s, start..<separator.lowerBound), last: false) } | ||
| 527 | next = max(next + 1, separator.upperBound) | ||
| 528 | start = separator.upperBound | ||
| 529 | guard start < length else { break } | ||
| 530 | } | ||
| 531 | try push(try substring(s, start..<length), last: true) | ||
| 532 | return Elisp.list(list) | ||
| 533 | } | ||
| 534 | } | ||
| 535 | } | ||
Sources/OrgCore/Config/ElispTime.swift added +251
| @@ -0,0 +1,251 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | // Lisp timestamps, `format-time-string`, the Org and `time-*` functions, and the calendar | ||
| 4 | // functions, for table formulas, Emacs Lisp blocks and capture templates. | ||
| 5 | |||
| 6 | extension Elisp { | ||
| 7 | /// A Lisp timestamp: whole seconds, picoseconds past them, and the resolution it came | ||
| 8 | /// with (1 for an integer or `(HIGH LOW)`, else a list with microseconds). | ||
| 9 | struct Time { | ||
| 10 | var seconds: Int | ||
| 11 | var picoseconds = 0 | ||
| 12 | var hz = 1 | ||
| 13 | |||
| 14 | static let pico = 1_000_000_000_000 | ||
| 15 | |||
| 16 | init(seconds: Int, picoseconds: Int = 0, hz: Int = 1) { | ||
| 17 | self.seconds = seconds | ||
| 18 | self.picoseconds = picoseconds | ||
| 19 | self.hz = hz | ||
| 20 | } | ||
| 21 | |||
| 22 | init(_ date: Date) { | ||
| 23 | let whole = date.timeIntervalSince1970.rounded(.down) | ||
| 24 | seconds = Int(whole) | ||
| 25 | picoseconds = Int((date.timeIntervalSince1970 - whole) * 1_000_000) * 1_000_000 | ||
| 26 | hz = Self.pico | ||
| 27 | } | ||
| 28 | |||
| 29 | /// `(HIGH LOW USEC PSEC)`, or an integer when the resolution is seconds. | ||
| 30 | var sexp: Sexp { | ||
| 31 | hz == 1 ? .integer(seconds) : .list([.integer(seconds >> 16), .integer(seconds & 0xFFFF), .integer(picoseconds / 1_000_000), .integer(picoseconds % 1_000_000)]) | ||
| 32 | } | ||
| 33 | |||
| 34 | /// `(HIGH LOW)`, as `encode-time` gives. | ||
| 35 | var pair: Sexp { .list([.integer(seconds >> 16), .integer(seconds & 0xFFFF)]) } | ||
| 36 | } | ||
| 37 | |||
| 38 | static func time(_ v: Sexp, now: Date) throws -> Time { | ||
| 39 | switch v { | ||
| 40 | case _ where isNil(v): return Time(now) | ||
| 41 | case .integer(let i): return Time(seconds: i) | ||
| 42 | case .float: throw Unsupported(what: "float times") | ||
| 43 | case .list(let parts) where (2...4).contains(parts.count): | ||
| 44 | let ints = try parts.map(int) | ||
| 45 | guard (-(1 << 40)...(1 << 40)).contains(ints[0]), (0..<65536).contains(ints[1]), | ||
| 46 | ints.dropFirst(2).allSatisfy({ (0..<1_000_000).contains($0) }) else { throw Unsupported(what: "time value \(v.description)") } | ||
| 47 | let micro = ints.count > 2 ? ints[2] : 0 | ||
| 48 | let pico = ints.count > 3 ? ints[3] : 0 | ||
| 49 | return Time(seconds: ints[0] << 16 + ints[1], picoseconds: micro * 1_000_000 + pico, hz: [1, 1, 1_000_000, Time.pico][ints.count - 1]) | ||
| 50 | default: throw Unsupported(what: "time value \(v.description)") | ||
| 51 | } | ||
| 52 | } | ||
| 53 | |||
| 54 | /// The seconds of a time, floats included, for the functions that read only the date. | ||
| 55 | static func wholeSeconds(_ v: Sexp, now: Date) throws -> Int { | ||
| 56 | if case .float(let d) = v { | ||
| 57 | guard d.isFinite, abs(d) < 1e15 else { throw Unsupported(what: "time value \(v.description)") } | ||
| 58 | return Int(d.rounded(.down)) | ||
| 59 | } | ||
| 60 | return try time(v, now: now).seconds | ||
| 61 | } | ||
| 62 | |||
| 63 | /// `org-ts-regexp0`. | ||
| 64 | static let orgTimeString = try! NSRegularExpression(pattern: "(([0-9]{4})-([0-9]{2})-([0-9]{2})( +[^\\]+0-9>\\r\\n \\-]+)?( +([0-9]{1,2}):([0-9]{2}))?)") | ||
| 65 | |||
| 66 | /// `org-parse-time-string`: year, month, day, hour and minute. | ||
| 67 | static func orgTime(_ s: String) throws -> [Int] { | ||
| 68 | let ns = s as NSString | ||
| 69 | guard let m = orgTimeString.firstMatch(in: s, range: NSRange(location: 0, length: ns.length)) else { | ||
| 70 | throw Signal(message: "Not an Org time string: \(s)") | ||
| 71 | } | ||
| 72 | func group(_ i: Int) -> Int { m.range(at: i).location == NSNotFound ? 0 : Int(ns.substring(with: m.range(at: i)))! } | ||
| 73 | let parts = [group(2), group(3), group(4), group(7), group(8)] | ||
| 74 | guard (1...12).contains(parts[1]), (1...31).contains(parts[2]), parts[3] < 24, parts[4] < 60 else { throw Unsupported(what: "time string \(s)") } | ||
| 75 | return parts | ||
| 76 | } | ||
| 77 | |||
| 78 | /// Days from 1 January 1970 to absolute day 1, 1 January of year 1. | ||
| 79 | static let epochDay = 719163 | ||
| 80 | |||
| 81 | /// `encode-time` of a local date and time, in the proleptic Gregorian calendar as Emacs | ||
| 82 | /// counts. Foundation's Gregorian calendar is Julian before 15 October 1582, so earlier | ||
| 83 | /// dates are counted here, where no daylight saving time applies. | ||
| 84 | static func encode(_ parts: [Int], calendar: Calendar) throws -> Time { | ||
| 85 | let second = parts.count > 5 ? parts[5] : 0 | ||
| 86 | if parts[0] >= 1583 { | ||
| 87 | guard let date = calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: parts[3], minute: parts[4], second: second)) else { | ||
| 88 | throw Unsupported(what: "date \(parts)") | ||
| 89 | } | ||
| 90 | return Time(seconds: Int(date.timeIntervalSince1970.rounded(.down))) | ||
| 91 | } | ||
| 92 | let local = (Days.absolute(year: parts[0], month: parts[1], day: parts[2]) - epochDay) * 86400 + parts[3] * 3600 + parts[4] * 60 + second | ||
| 93 | func offset(_ seconds: Int) -> Int { calendar.timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: Double(seconds))) } | ||
| 94 | return Time(seconds: local - offset(local - offset(local))) | ||
| 95 | } | ||
| 96 | |||
| 97 | /// The local date and time of `seconds` in the proleptic Gregorian calendar: the absolute | ||
| 98 | /// day, and the seconds into it. | ||
| 99 | static func civil(_ seconds: Int, calendar: Calendar) -> (day: Int, second: Int) { | ||
| 100 | let local = seconds + calendar.timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: Double(seconds))) | ||
| 101 | let day = local >= 0 ? local / 86400 : -((-local - 1) / 86400) - 1 | ||
| 102 | return (day + epochDay, local - day * 86400) | ||
| 103 | } | ||
| 104 | |||
| 105 | /// `date-to-time` for ISO 8601 dates, with or without a time. | ||
| 106 | static func dateToTime(_ s: String, calendar: Calendar) throws -> Time { | ||
| 107 | guard let m = s.wholeMatch(of: /([0-9]{4})-([0-9]{2})-([0-9]{2})(?:[ T]([0-9]{2}):([0-9]{2})(?::([0-9]{2}))?)?/) else { | ||
| 108 | throw Unsupported(what: "date-to-time of \(s)") | ||
| 109 | } | ||
| 110 | let parts = [Int(m.1)!, Int(m.2)!, Int(m.3)!, m.4.map { Int($0)! } ?? 0, m.5.map { Int($0)! } ?? 0, m.6.map { Int($0)! } ?? 0] | ||
| 111 | guard (1...12).contains(parts[1]), (1...31).contains(parts[2]), parts[3] < 24, parts[4] < 60, parts[5] < 60 else { throw Unsupported(what: "date-to-time of \(s)") } | ||
| 112 | return try encode(parts, calendar: calendar) | ||
| 113 | } | ||
| 114 | |||
| 115 | static func days(_ seconds: Int, calendar: Calendar) -> Int { | ||
| 116 | civil(seconds, calendar: calendar).day | ||
| 117 | } | ||
| 118 | |||
| 119 | /// `format-time-string` with the conversions that don't depend on the locale, without | ||
| 120 | /// flags or widths. | ||
| 121 | static func formatTime(_ format: String, _ seconds: Int, calendar: Calendar) throws -> String { | ||
| 122 | let (absolute, secondOfDay) = civil(seconds, calendar: calendar) | ||
| 123 | let (year, month, day) = Days.date(absolute) | ||
| 124 | let (hour, minute, second) = (secondOfDay / 3600, secondOfDay % 3600 / 60, secondOfDay % 60) | ||
| 125 | let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] | ||
| 126 | let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] | ||
| 127 | let weekday = Days.weekday(absolute) | ||
| 128 | // Four digits with the sign, and the last two digits of the year without it. | ||
| 129 | let yearText = year < 0 ? String(format: "-%03d", -year) : String(format: "%04d", year) | ||
| 130 | let shortYear = abs(year) % 100 | ||
| 131 | let hour12 = hour % 12 == 0 ? 12 : hour % 12 | ||
| 132 | var out = "" | ||
| 133 | var chars = format.makeIterator() | ||
| 134 | while let ch = chars.next() { | ||
| 135 | guard ch == "%" else { | ||
| 136 | out.append(ch) | ||
| 137 | continue | ||
| 138 | } | ||
| 139 | guard let f = chars.next() else { throw Unsupported(what: "format-time-string %") } | ||
| 140 | switch f { | ||
| 141 | case "Y": out += yearText | ||
| 142 | case "y": out += String(format: "%02d", shortYear) | ||
| 143 | case "m": out += String(format: "%02d", month) | ||
| 144 | case "d": out += String(format: "%02d", day) | ||
| 145 | case "e": out += String(format: "%2d", day) | ||
| 146 | case "H": out += String(format: "%02d", hour) | ||
| 147 | case "k": out += String(format: "%2d", hour) | ||
| 148 | case "I": out += String(format: "%02d", hour12) | ||
| 149 | case "l": out += String(format: "%2d", hour12) | ||
| 150 | case "M": out += String(format: "%02d", minute) | ||
| 151 | case "S": out += String(format: "%02d", second) | ||
| 152 | case "p": out += hour < 12 ? "AM" : "PM" | ||
| 153 | case "a": out += String(days[weekday].prefix(3)) | ||
| 154 | case "A": out += days[weekday] | ||
| 155 | case "b", "h": out += String(months[month - 1].prefix(3)) | ||
| 156 | case "B": out += months[month - 1] | ||
| 157 | case "u": out += String(weekday == 0 ? 7 : weekday) | ||
| 158 | case "w": out += String(weekday) | ||
| 159 | case "j": out += String(format: "%03d", Days.absolute(year: year, month: month, day: day) - Days.absolute(year: year, month: 1, day: 0)) | ||
| 160 | case "F": out += (year > 9999 ? "+" : "") + yearText + String(format: "-%02d-%02d", month, day) | ||
| 161 | case "D": out += String(format: "%02d/%02d/%02d", month, day, shortYear) | ||
| 162 | case "R": out += String(format: "%02d:%02d", hour, minute) | ||
| 163 | case "T": out += String(format: "%02d:%02d:%02d", hour, minute, second) | ||
| 164 | case "s": out += String(seconds) | ||
| 165 | case "z": | ||
| 166 | let offset = calendar.timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: Double(seconds))) / 60 | ||
| 167 | out += String(format: "%@%02d%02d", offset < 0 ? "-" : "+", abs(offset) / 60, abs(offset) % 60) | ||
| 168 | case "n": out += "\n" | ||
| 169 | case "t": out += "\t" | ||
| 170 | case "%": out += "%" | ||
| 171 | default: throw Unsupported(what: "format-time-string %\(f)") | ||
| 172 | } | ||
| 173 | } | ||
| 174 | return out | ||
| 175 | } | ||
| 176 | |||
| 177 | /// Defines the time functions and the calendar functions diary sexps use, with times in | ||
| 178 | /// `calendar`'s time zone and `now` as the clock. | ||
| 179 | public func standardTime(now: @escaping () -> Date = Date.init, calendar: Calendar = .current) { | ||
| 180 | var calendar = calendar | ||
| 181 | if calendar.identifier != .gregorian { | ||
| 182 | var gregorian = Calendar(identifier: .gregorian) | ||
| 183 | gregorian.timeZone = calendar.timeZone | ||
| 184 | calendar = gregorian | ||
| 185 | } | ||
| 186 | let local = calendar | ||
| 187 | DiarySexp.defineCalendar(self) | ||
| 188 | define("current-time") { _, args in | ||
| 189 | try Elisp.arity(args, 0...0, "current-time") | ||
| 190 | return Time(now()).sexp | ||
| 191 | } | ||
| 192 | define("format-time-string") { _, args in | ||
| 193 | try Elisp.arity(args, 1...3, "format-time-string") | ||
| 194 | var zoned = local | ||
| 195 | if args.count > 2, !Elisp.isNil(args[2]) { | ||
| 196 | guard args[2] == Elisp.t || args[2] == .string("UTC") || args[2] == .integer(0) else { throw Unsupported(what: "format-time-string zone \(args[2].description)") } | ||
| 197 | zoned.timeZone = TimeZone(identifier: "UTC")! | ||
| 198 | } | ||
| 199 | return .string(try Elisp.formatTime(try Elisp.string(args[0]), try Elisp.wholeSeconds(args.count > 1 ? args[1] : .nil, now: now()), calendar: zoned)) | ||
| 200 | } | ||
| 201 | define("org-time-string-to-time") { _, args in | ||
| 202 | try Elisp.arity(args, 1...1, "org-time-string-to-time") | ||
| 203 | return try Elisp.encode(try Elisp.orgTime(try Elisp.string(args[0])), calendar: local).pair | ||
| 204 | } | ||
| 205 | define("org-time-string-to-absolute") { _, args in | ||
| 206 | try Elisp.arity(args, 1...5, "org-time-string-to-absolute") | ||
| 207 | guard args.count == 1 else { throw Unsupported(what: "org-time-string-to-absolute with a day") } | ||
| 208 | let parts = try Elisp.orgTime(try Elisp.string(args[0])) | ||
| 209 | return .integer(Days.absolute(year: parts[0], month: parts[1], day: parts[2])) | ||
| 210 | } | ||
| 211 | for name in ["time-add", "time-subtract"] { | ||
| 212 | define(name) { _, args in | ||
| 213 | try Elisp.arity(args, 2...2, name) | ||
| 214 | let a = try Elisp.time(args[0], now: now()) | ||
| 215 | let b = try Elisp.time(args[1], now: now()) | ||
| 216 | let sign = name == "time-add" ? 1 : -1 | ||
| 217 | var picoseconds = a.picoseconds + sign * b.picoseconds | ||
| 218 | var seconds = a.seconds + sign * b.seconds | ||
| 219 | if picoseconds < 0 { | ||
| 220 | picoseconds += Time.pico | ||
| 221 | seconds -= 1 | ||
| 222 | } else if picoseconds >= Time.pico { | ||
| 223 | picoseconds -= Time.pico | ||
| 224 | seconds += 1 | ||
| 225 | } | ||
| 226 | return Time(seconds: seconds, picoseconds: picoseconds, hz: max(a.hz, b.hz)).sexp | ||
| 227 | } | ||
| 228 | } | ||
| 229 | define("float-time") { _, args in | ||
| 230 | try Elisp.arity(args, 0...1, "float-time") | ||
| 231 | if case .float(let d)? = args.first { return .float(d) } | ||
| 232 | let time = try Elisp.time(args.first ?? .nil, now: now()) | ||
| 233 | guard time.picoseconds % 1_000_000 == 0 else { throw Unsupported(what: "float-time of picoseconds") } | ||
| 234 | return .float(Double(time.seconds * 1_000_000 + time.picoseconds / 1_000_000) / 1_000_000) | ||
| 235 | } | ||
| 236 | define("date-to-time") { _, args in | ||
| 237 | try Elisp.arity(args, 1...1, "date-to-time") | ||
| 238 | return try Elisp.dateToTime(try Elisp.string(args[0]), calendar: local).pair | ||
| 239 | } | ||
| 240 | define("time-to-days") { _, args in | ||
| 241 | try Elisp.arity(args, 1...1, "time-to-days") | ||
| 242 | return .integer(Elisp.days(try Elisp.wholeSeconds(args[0], now: now()), calendar: local)) | ||
| 243 | } | ||
| 244 | define("days-between") { _, args in | ||
| 245 | try Elisp.arity(args, 2...2, "days-between") | ||
| 246 | let a = try Elisp.dateToTime(try Elisp.string(args[0]), calendar: local) | ||
| 247 | let b = try Elisp.dateToTime(try Elisp.string(args[1]), calendar: local) | ||
| 248 | return .integer(Elisp.days(a.seconds, calendar: local) - Elisp.days(b.seconds, calendar: local)) | ||
| 249 | } | ||
| 250 | } | ||
| 251 | } | ||
Sources/OrgCore/Config/Lisp.swift +6 −8
| @@ -115,6 +115,9 @@ public enum LispReader { | |||
| 115 | 115 | ||
| 116 | func error(_ message: String) -> ReadError { ReadError(line: line, message: message) } | 116 | func error(_ message: String) -> ReadError { ReadError(line: line, message: message) } |
| 117 | 117 | ||
| 118 | /// What `\a` and the other one-letter escapes in strings and characters stand for. | ||
| 119 | static let escapes: [Unicode.Scalar: Unicode.Scalar] = ["a": "\u{7}", "b": "\u{8}", "d": "\u{7F}", "e": "\u{1B}", "f": "\u{C}", "n": "\n", "r": "\r", "s": " ", "t": "\t", "v": "\u{B}"] | ||
| 120 | |||
| 118 | static let delimiters: Set<Unicode.Scalar> = ["(", ")", "[", "]", "\"", "'", "`", ",", ";"] | 121 | static let delimiters: Set<Unicode.Scalar> = ["(", ")", "[", "]", "\"", "'", "`", ",", ";"] |
| 119 | 122 | ||
| 120 | mutating func form() throws -> Sexp { | 123 | mutating func form() throws -> Sexp { |
| @@ -177,10 +180,8 @@ public enum LispReader { | |||
| 177 | case "\\": | 180 | case "\\": |
| 178 | guard let e = next() else { break } | 181 | guard let e = next() else { break } |
| 179 | switch e { | 182 | switch e { |
| 180 | case "n": out += "\n" | 183 | case "\n", " ": break |
| 181 | case "t": out += "\t" | 184 | default: out.unicodeScalars.append(Self.escapes[e] ?? e) |
| 182 | case "\n": break | ||
| 183 | default: out.unicodeScalars.append(e) | ||
| 184 | } | 185 | } |
| 185 | default: | 186 | default: |
| 186 | out.unicodeScalars.append(c) | 187 | out.unicodeScalars.append(c) |
| @@ -194,10 +195,7 @@ public enum LispReader { | |||
| 194 | guard c == "\\" else { return Int(c.value) } | 195 | guard c == "\\" else { return Int(c.value) } |
| 195 | guard let e = next() else { throw error("bad character") } | 196 | guard let e = next() else { throw error("bad character") } |
| 196 | switch e { | 197 | switch e { |
| 197 | case "n": return 10 | 198 | case _ where Self.escapes[e] != nil: return Int(Self.escapes[e]!.value) |
| 198 | case "t": return 9 | ||
| 199 | case "s": return 32 | ||
| 200 | case "e": return 27 | ||
| 201 | case "C", "M", "S", "H", "A": | 199 | case "C", "M", "S", "H", "A": |
| 202 | if peek == "-" { _ = next(); return try character() } | 200 | if peek == "-" { _ = next(); return try character() } |
| 203 | return Int(e.value) | 201 | return Int(e.value) |
Sources/OrgPrograms/Programs.swift +13 −2
| @@ -5,7 +5,12 @@ import OrgCore | |||
| 5 | 5 | ||
| 6 | /// Babel and Emacs as processes, for `DocumentSession.programs`. | 6 | /// Babel and Emacs as processes, for `DocumentSession.programs`. |
| 7 | public struct Programs: ProgramRunning { | 7 | public struct Programs: ProgramRunning { |
| 8 | public init() {} | 8 | /// Where Emacs is, or nil when it isn't installed. |
| 9 | let emacs: @Sendable () -> URL? | ||
| 10 | |||
| 11 | public init(emacs: @escaping @Sendable () -> URL? = { EmacsRunner.executable() }) { | ||
| 12 | self.emacs = emacs | ||
| 13 | } | ||
| 9 | 14 | ||
| 10 | public func runBabel(_ job: BabelJob, fileDirectory: URL) async throws -> BabelOutput { | 15 | public func runBabel(_ job: BabelJob, fileDirectory: URL) async throws -> BabelOutput { |
| 11 | // js in JavaScriptCore when node (or `:cmd`) isn't installed. A `:cmd` with arguments runs | 16 | // js in JavaScriptCore when node (or `:cmd`) isn't installed. A `:cmd` with arguments runs |
| @@ -14,7 +19,13 @@ public struct Programs: ProgramRunning { | |||
| 14 | case .process(let executable, _), .session(_, let executable, _): | 19 | case .process(let executable, _), .session(_, let executable, _): |
| 15 | if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output } | 20 | if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output } |
| 16 | case .emacs: | 21 | case .emacs: |
| 17 | break | 22 | // Emacs Lisp in `Elisp` when Emacs isn't installed. |
| 23 | if emacs() == nil { | ||
| 24 | guard let output = try Babel.evaluateNatively(job) else { | ||
| 25 | throw BabelRunner.Failure(description: "This block uses Emacs Lisp that runs only in Emacs, and Emacs isn't installed.") | ||
| 26 | } | ||
| 27 | return output | ||
| 28 | } | ||
| 18 | } | 29 | } |
| 19 | return try await BabelRunner.run(job, fileDirectory: fileDirectory) | 30 | return try await BabelRunner.run(job, fileDirectory: fileDirectory) |
| 20 | } | 31 | } |
Sources/Orgstar/ContentView.swift +3
| @@ -1053,6 +1053,9 @@ struct ContentView: View { | |||
| 1053 | commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate")) | 1053 | commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate")) |
| 1054 | #else | 1054 | #else |
| 1055 | case .emacsTable(let table, let point, let form, let reason, let lisp): | 1055 | case .emacsTable(let table, let point, let form, let reason, let lisp): |
| 1056 | guard EmacsRunner.executable() != nil else { | ||
| 1057 | return commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate")) | ||
| 1058 | } | ||
| 1056 | let run = { | 1059 | let run = { |
| 1057 | commands.show(String(localized: "Recalculating in Emacs (\(TableReason.localized(reason)))…", comment: "Table formulas sent to Emacs, and why")) | 1060 | commands.show(String(localized: "Recalculating in Emacs (\(TableReason.localized(reason)))…", comment: "Table formulas sent to Emacs, and why")) |
| 1058 | commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) } | 1061 | commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) } |
Tests/OrgAppTests/TableReasonTests.swift +18 −1
| @@ -12,7 +12,24 @@ struct TableReasonTests { | |||
| 12 | for file in files where file.hasSuffix(".swift") { | 12 | for file in files where file.hasSuffix(".swift") { |
| 13 | let text = try String(contentsOf: Self.root.appendingPathComponent("Sources/OrgCore/" + file), encoding: .utf8) | 13 | let text = try String(contentsOf: Self.root.appendingPathComponent("Sources/OrgCore/" + file), encoding: .utf8) |
| 14 | // An interpolated value stands as "x", as it would read at run time. | 14 | // An interpolated value stands as "x", as it would read at run time. |
| 15 | func sample(_ literal: Substring) -> String { String(literal).replacing(/\\\(.*\)/, with: "x") } | 15 | func sample(_ literal: Substring) -> String { |
| 16 | var out = "", depth = 0, chars = Array(literal), i = 0 | ||
| 17 | while i < chars.count { | ||
| 18 | if depth == 0, chars[i] == "\\", i + 1 < chars.count, chars[i + 1] == "(" { | ||
| 19 | out += "x" | ||
| 20 | depth = 1 | ||
| 21 | i += 2 | ||
| 22 | continue | ||
| 23 | } | ||
| 24 | if depth > 0 { | ||
| 25 | if chars[i] == "(" { depth += 1 } else if chars[i] == ")" { depth -= 1 } | ||
| 26 | } else { | ||
| 27 | out.append(chars[i]) | ||
| 28 | } | ||
| 29 | i += 1 | ||
| 30 | } | ||
| 31 | return out | ||
| 32 | } | ||
| 16 | reasons += text.matches(of: /Unsupported\("((?:[^"\\]|\\\([^)]*\)+)*)"/).map { sample($0.1) } | 33 | reasons += text.matches(of: /Unsupported\("((?:[^"\\]|\\\([^)]*\)+)*)"/).map { sample($0.1) } |
| 17 | lisp += text.matches(of: /Unsupported\(what: "((?:[^"\\]|\\\([^)]*\)+)*)"/).map { sample($0.1) } | 34 | lisp += text.matches(of: /Unsupported\(what: "((?:[^"\\]|\\\([^)]*\)+)*)"/).map { sample($0.1) } |
| 18 | } | 35 | } |
Tests/OrgCoreTests/BabelTests.swift +71
| @@ -257,6 +257,13 @@ struct BabelTests { | |||
| 257 | "#+begin_src emacs-lisp\n(car 1)\n#+end_src\n", | 257 | "#+begin_src emacs-lisp\n(car 1)\n#+end_src\n", |
| 258 | "#+begin_src emacs-lisp :results raw\n\"*bold*\"\n#+end_src\n", | 258 | "#+begin_src emacs-lisp :results raw\n\"*bold*\"\n#+end_src\n", |
| 259 | "#+begin_src emacs-lisp :wrap example\n(upcase \"wrapped\")\n#+end_src\n", | 259 | "#+begin_src emacs-lisp :wrap example\n(upcase \"wrapped\")\n#+end_src\n", |
| 260 | "#+begin_src emacs-lisp\n(defun sq (x) (* x x))\n(mapcar #'sq '(1 2 3))\n#+end_src\n", | ||
| 261 | "#+begin_src emacs-lisp\n(cl-loop for i from 1 to 3 collect (list i (* i i)))\n#+end_src\n", | ||
| 262 | "#+begin_src emacs-lisp\n(let ((s \"v2.15\")) (when (string-match \"\\\\([0-9]+\\\\)\\\\.\\\\([0-9]+\\\\)\" s) (list (match-string 1 s) (match-string 2 s))))\n#+end_src\n", | ||
| 263 | "#+begin_src emacs-lisp\n(pcase '(add 2 3) (`(add ,a ,b) (+ a b)) (_ 'unknown))\n#+end_src\n", | ||
| 264 | "#+begin_src emacs-lisp\n(replace-regexp-in-string \"o+\" \"0\" \"foo boo\")\n#+end_src\n", | ||
| 265 | "#+begin_src emacs-lisp\n(format-time-string \"%A %Y-%m-%d\" (org-time-string-to-time \"<2026-11-20>\"))\n#+end_src\n", | ||
| 266 | "#+begin_src emacs-lisp\n(let-alist '((name . \"x\") (size . 3)) (format \"%s:%d\" .name .size))\n#+end_src\n", | ||
| 260 | ] | 267 | ] |
| 261 | 268 | ||
| 262 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | 269 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) |
| @@ -285,6 +292,70 @@ struct BabelTests { | |||
| 285 | } | 292 | } |
| 286 | } | 293 | } |
| 287 | 294 | ||
| 295 | /// Blocks whose result depends on how Emacs runs them: lexical binding, and the syntax table | ||
| 296 | /// of `*scratch*`. | ||
| 297 | static let runnerCases = [ | ||
| 298 | "(list (string-match \"\\\\w\" \"'a\") (string-match \"\\\\s(\" \"<\") (string-match \"\\\\_<b\" \"a\\\\b\") (replace-regexp-in-string \"\\\\w+\" \"X\" \"it's\"))", | ||
| 299 | "(list (split-string \"a b\\nc\" \"[[:space:]]\") (string-match \"\\\\s-\" \"a\\nb\") (string-match \"\\\\s.\" \"a,b\"))", | ||
| 300 | "(progn (defun adder (n) (lambda (x) (+ x n))) (funcall (adder 3) 4))", | ||
| 301 | "(progn (defun g () y) (let ((y 5)) (g)))", | ||
| 302 | "(let ((fs nil)) (dolist (i '(1 2)) (push (lambda () i) fs)) (mapcar #'funcall fs))", | ||
| 303 | "(let ((fs nil)) (dotimes (i 2) (push (lambda () i) fs)) (mapcar #'funcall fs))", | ||
| 304 | "(mapcar #'funcall (cl-loop for i in '(1 2) collect (lambda () i)))", | ||
| 305 | "(let ((x 1)) (let ((f (lambda () x))) (let ((x 2)) (funcall f))))", | ||
| 306 | "(let* ((x 1) (f (lambda () x)) (x 2)) (funcall f))", | ||
| 307 | "(let ((n 0)) (let ((inc (lambda () (setq n (1+ n))))) (funcall inc) (funcall inc) n))", | ||
| 308 | "(progn (defvar orgstar-special 1) (defun orgstar-read () orgstar-special) (let ((orgstar-special 2)) (orgstar-read)))", | ||
| 309 | "(let ((x 5)) (defun orgstar-gx () x) (orgstar-gx))", | ||
| 310 | "(let ((x 1)) (funcall '(lambda () x)))", | ||
| 311 | "(let ((x 3)) (mapcar (lambda (y) (* x y)) '(1 2)))", | ||
| 312 | "(let ((k 1)) (pcase 2 ((pred (lambda (v) (> v k))) 'big)))", | ||
| 313 | "(list (capitalize \"it's o'neil\") (capitalize \"o'neil x_y 3d\"))", | ||
| 314 | "(progn (defun h () y) (funcall '(lambda (y) (h)) 3))", | ||
| 315 | "(progn (defun h3 () zz) (mapcar '(lambda (zz) (h3)) '(1 2)))", | ||
| 316 | "(progn (defun h2 () yy) (let ((f '(lambda (yy) (h2)))) (funcall f 8)))", | ||
| 317 | "(progn (defun h4 () w) (funcall '(lambda () (let ((w 4)) (h4)))))", | ||
| 318 | "(let ((x 2)) (funcall '(lambda (f) (funcall f)) (lambda () x)))", | ||
| 319 | "(let ((f (lambda (x) (* 2 x)))) (list (funcall f 2) (apply f '(3)) (car (list 5 f)) (length (list f f))))", | ||
| 320 | "(let ((x 1)) (condition-case err (car x) (error (funcall (lambda () (list x (car err)))))))", | ||
| 321 | ].map { "#+begin_src emacs-lisp\n\($0)\n#+end_src\n" } | ||
| 322 | |||
| 323 | /// Natively as with `emacs -Q --batch -l`, the way the app runs Emacs Lisp blocks. | ||
| 324 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | ||
| 325 | func lispRunsNativelyLikeTheEmacsRunner() throws { | ||
| 326 | let folder = FileManager.default.temporaryDirectory | ||
| 327 | for text in Self.runnerCases { | ||
| 328 | let caret = (text as NSString).range(of: "#+begin_src").location + 2 | ||
| 329 | let emacs = try TestBabelRunner.execute(text, caret: caret, directory: folder) | ||
| 330 | do { | ||
| 331 | let ours = try TestBabelRunner.execute(text, caret: caret, directory: folder, native: true) | ||
| 332 | // A Lisp error: Emacs's backtrace becomes the result here, and the run fails in the app. | ||
| 333 | if emacs.text.contains("#+begin_example\n\nError: ") { | ||
| 334 | #expect(ours.failure != nil && ours.text == text, "\(text)\nours: \(ours.text)") | ||
| 335 | continue | ||
| 336 | } | ||
| 337 | #expect(ours.text == emacs.text, "\(text)\nours (\(ours.failure ?? "")):\n\(ours.text)\nemacs (\(emacs.failure ?? "")):\n\(emacs.text)") | ||
| 338 | } catch is NativeUnsupported { | ||
| 339 | Issue.record("not run natively:\n\(text)") | ||
| 340 | } | ||
| 341 | } | ||
| 342 | } | ||
| 343 | |||
| 344 | /// Emacs's closures aren't lists: blocks that look inside one are refused. | ||
| 345 | @Test func refusesLookingInsideClosures() throws { | ||
| 346 | let folder = FileManager.default.temporaryDirectory | ||
| 347 | for form in [ | ||
| 348 | "(listp (lambda () 1))", "(let ((f (lambda () 1))) (consp f))", "(car (lambda () 1))", "(equal (lambda () 1) (lambda () 1))", | ||
| 349 | "(functionp (lambda () 1))", "(let ((f (lambda () 1))) (eq f f))", "(let ((f (lambda () 1))) (length f))", | ||
| 350 | "(let ((f (lambda () 1))) (dolist (x f) x))", "(let ((f (lambda () 1))) (push 1 f) (length f))", | ||
| 351 | "(let ((f (lambda () 1))) (format \"%S\" (list f)))", "(let ((f (lambda () 1))) (and (memq f (list f)) t))", | ||
| 352 | "(funcall '(closure 99 () 1))", | ||
| 353 | ] { | ||
| 354 | let text = "#+begin_src emacs-lisp\n\(form)\n#+end_src\n" | ||
| 355 | #expect(throws: NativeUnsupported.self, "\(form)") { try TestBabelRunner.execute(text, caret: 2, directory: folder, native: true) } | ||
| 356 | } | ||
| 357 | } | ||
| 358 | |||
| 288 | @Test func referencedQueryBlocksAskEveryTime() { | 359 | @Test func referencedQueryBlocksAskEveryTime() { |
| 289 | let text = "#+begin_src sh :var x=gen\necho $x\n#+end_src\n\n#+NAME: gen\n#+begin_src sh :eval query\necho 1\n#+end_src\n" | 360 | let text = "#+begin_src sh :var x=gen\necho $x\n#+end_src\n\n#+NAME: gen\n#+begin_src sh :eval query\necho 1\n#+end_src\n" |
| 290 | guard case .success(let job) = Babel.plan(EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])) else { | 361 | guard case .success(let job) = Babel.plan(EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])) else { |
Tests/OrgCoreTests/ElispTests.swift +213 −1
| @@ -25,6 +25,12 @@ struct ElispTests { | |||
| 25 | "(string-prefix-p \"ab\" \"abc\")", "(condition-case nil (/ 1 0) (error 'caught))", "(ignore-errors (car 1))", "(car 1)", | 25 | "(string-prefix-p \"ab\" \"abc\")", "(condition-case nil (/ 1 0) (error 'caught))", "(ignore-errors (car 1))", "(car 1)", |
| 26 | "(let ((x 0)) (while (< x 5) (setq x (1+ x))) x)", "(elt [1 2 3] 1)", "(aref \"abc\" 1)", "(length [1 2])", "(nthcdr 1 '(1 2 3))", | 26 | "(let ((x 0)) (while (< x 5) (setq x (1+ x))) x)", "(elt [1 2 3] 1)", "(aref \"abc\" 1)", "(length [1 2])", "(nthcdr 1 '(1 2 3))", |
| 27 | "(delq nil '(1 nil 2))", "(cadr '(1 2 3))", "(identity \"x\")", "(capitalize \"hello world\")", "(string-trim \" x \")", | 27 | "(delq nil '(1 nil 2))", "(cadr '(1 2 3))", "(identity \"x\")", "(capitalize \"hello world\")", "(string-trim \" x \")", |
| 28 | "(capitalize \"it's o'neil x_y 3d foo-bar\")", | ||
| 29 | #"(aref "\f" 0)"#, #"(string-match "\\s-" "\f")"#, #"(append "\a\b\d\e\f\n\r\s\t\v\ x" nil)"#, #"(list ?\a ?\b ?\d ?\e ?\f ?\r ?\s ?\v)"#, | ||
| 30 | "(condition-case err (car 1) (error (car err)))", "(condition-case err (cdr 'a) (error err))", "(condition-case err (/ 1 0) (arith-error err))", | ||
| 31 | "(condition-case err void-orgstar-variable (void-variable err))", "(condition-case nil (car 1) (wrong-type-argument 'w) (error 'e))", | ||
| 32 | "(condition-case nil (car 1) (arith-error 'a))", #"(condition-case err (error "e %d" 1) (error err))"#, | ||
| 33 | #"(condition-case err (user-error "u") (user-error err))"#, "(condition-case nil (aref [1] 5) (args-out-of-range 'r))", | ||
| 28 | ] | 34 | ] |
| 29 | 35 | ||
| 30 | static func ours(_ form: String) -> String { | 36 | static func ours(_ form: String) -> String { |
| @@ -45,6 +51,209 @@ struct ElispTests { | |||
| 45 | #expect(Self.ours(form) == expected, "\(form)") | 51 | #expect(Self.ours(form) == expected, "\(form)") |
| 46 | } | 52 | } |
| 47 | } | 53 | } |
| 54 | |||
| 55 | /// Math, strings, regexps, lists, seq and cl-lib, and the macros: each must run here. | ||
| 56 | static let library = [ | ||
| 57 | "(list float-pi pi float-e)", "(expt 2 10)", "(expt 2 -2)", "(expt 2.0 3)", "(expt 0 0)", "(expt 0 -1)", "(expt -8 0.5)", | ||
| 58 | "(sqrt 2)", "(sqrt -1)", "(exp 1)", "(log 8 2)", "(log 100 10)", "(log 9 3)", "(log 8 0)", "(log 0)", "(log 8)", "(sin 1)", | ||
| 59 | "(cos 0)", "(tan 1)", "(asin 0.5)", "(acos 2)", "(atan 1)", "(atan 1 -1)", "(isnan 1)", "(isnan (/ 0.0 0.0))", | ||
| 60 | "(logand 12 10)", "(logand)", "(logior 1 4)", "(logxor 5 1)", "(ash 1 3)", "(ash -8 -1)", "(ash 5 -10)", "(random 0)", | ||
| 61 | "(let ((r (random 10))) (and (integerp r) (<= 0 r 9)))", | ||
| 62 | #"(string-join '("a" "b") ", ")"#, #"(string-join '("a" "b"))"#, #"(string-to-char "")"#, #"(string-to-char "é")"#, | ||
| 63 | "(char-to-string 233)", #"(string-pad "ab" 5)"#, #"(string-pad "ab" 5 ?- t)"#, #"(string-pad "abcdef" 3)"#, | ||
| 64 | #"(string-width "abc\t")"#, #"(string-width "é\n")"#, #"(string-search "b" "abcb" 2)"#, #"(string-search "" "abc")"#, | ||
| 65 | #"(string-search "z" "abc")"#, #"(string-search "b" "abc" 9)"#, #"(string-replace "ab" "x" "cabab")"#, | ||
| 66 | #"(string-replace "" "x" "abc")"#, #"(substring "héllo" 1 3)"#, #"(number-to-string 1.5)"#, | ||
| 67 | #"(string-match "a" "XA")"#, #"(let ((case-fold-search nil)) (string-match "a" "XA"))"#, | ||
| 68 | #"(list (string-match "\\(b+\\)\\(x\\)?" "abbc") (match-beginning 1) (match-end 1) (match-beginning 2) (match-string 1 "abbc") (match-string 2 "abbc") (match-beginning 7))"#, | ||
| 69 | #"(string-match "^b" "a\nb")"#, #"(string-match "a$" "a\nb")"#, #"(string-match "\\`b" "a\nb")"#, #"(string-match "b\\'" "ab\n")"#, | ||
| 70 | #"(string-match "x*" "")"#, #"(string-match "\\w+" "_ab")"#, #"(string-match "\\W" "$%'_")"#, #"(string-match "\\bb" "a-b")"#, | ||
| 71 | #"(string-match "\\_<b" "a-b")"#, #"(string-match "\\_<b" "a b")"#, #"(string-match "x\\_>" "x-y x")"#, | ||
| 72 | #"(string-match "[[:space:]]" "a\tb")"#, #"(progn (string-match "\\s-+" "a \t b") (match-end 0))"#, #"(string-match "\\S-" " x")"#, | ||
| 73 | #"(string-match "\\s_" "ab=c")"#, #"(string-match "*a" "x*a")"#, #"(string-match "^*a" "*a")"#, #"(string-match "\\(*a\\)" "x*a")"#, | ||
| 74 | #"(string-match "a\\{2\\}" "caaa")"#, #"(string-match "a\\{,2\\}b" "aaab")"#, #"(progn (string-match "a\\{2,\\}" "caaaa") (match-end 0))"#, | ||
| 75 | #"(string-match "a|b" "xa|b")"#, #"(string-match "a{2}" "a{2}")"#, #"(string-match "(a)" "x(a)")"#, #"(string-match "[]a]" "x]")"#, | ||
| 76 | #"(string-match "[^]a]" "]ab")"#, #"(string-match "[\\]" "x\\")"#, #"(string-match "[a-]" "x-")"#, #"(string-match "\\(?:ab\\)+" "xabab")"#, | ||
| 77 | #"(progn (string-match "a+?" "aaa") (match-end 0))"#, #"(progn (string-match "a*?b" "aab") (match-end 0))"#, #"(string-match "\\Ba" "ba")"#, | ||
| 78 | #"(string-match "\\<b" "a b")"#, #"(string-match "a\\>" "ab a")"#, #"(string-match "\\s." "a,b")"#, #"(string-match "\\s(" "a[b")"#, | ||
| 79 | #"(string-match "[[:alpha:]]+" "12ab")"#, #"(string-match "[^[:digit:]]" "12ab")"#, #"(string-match "[[:punct:]]" "ab$")"#, | ||
| 80 | #"(string-match "[[:word:]]" ",$")"#, #"(string-match "[[:xdigit:]]+" "xyzBEEF")"#, #"(string-match "\\(a\\)\\1" "xaa")"#, | ||
| 81 | #"(string-match "[a-z]+" "ABC")"#, #"(let ((case-fold-search nil)) (string-match "[a-z]+" "ABC"))"#, #"(string-match "x\\|y" "zzy")"#, | ||
| 82 | #"(string-match "[[:upper:]]" "a")"#, #"(let ((case-fold-search nil)) (string-match "[[:upper:]]" "a"))"#, #"(string-match "a" "bab" 2)"#, | ||
| 83 | #"(string-match "a" "bab" -2)"#, #"(string-match "a" "bab" 9)"#, #"(string-match "^a" "ba" 1)"#, #"(string-match "\\." "a.b")"#, | ||
| 84 | #"(string-match "a.c" "a\nc abc")"#, #"(string-match "f." "café")"#, | ||
| 85 | #"(let ((case-fold-search nil)) (string-match "É" "café"))"#, #"(string-match-p "b" "abc")"#, | ||
| 86 | #"(progn (string-match "a" "xa") (string-match-p "b" "bbb") (match-beginning 0))"#, | ||
| 87 | #"(progn (string-match "a" "xa") (save-match-data (string-match "b" "bbb")) (match-beginning 0))"#, | ||
| 88 | #"(progn (string-match "\\(b\\)c" "abc") (list (replace-match "Z" t t "abc") (replace-match "Z" t t "abc" 1) (replace-match "[\\&]" t nil "abc")))"#, | ||
| 89 | #"(replace-regexp-in-string "b" "X" "aBc")"#, #"(replace-regexp-in-string "o" "x" "FOO BAR")"#, | ||
| 90 | #"(replace-regexp-in-string "foo" "bar" "Foo FOO foo")"#, #"(replace-regexp-in-string "foo" "bar" "Foo FOO foo" t)"#, | ||
| 91 | #"(replace-regexp-in-string "a b" "x y" "A B")"#, #"(replace-regexp-in-string "ab" "x y" "Ab")"#, #"(replace-regexp-in-string "ab" "x-y" "AB")"#, | ||
| 92 | #"(replace-regexp-in-string "" "x" "ab")"#, #"(replace-regexp-in-string "$" "x" "ab")"#, #"(replace-regexp-in-string "^" "> " "a\nb")"#, | ||
| 93 | #"(replace-regexp-in-string "\\(a\\)\\|b" "[\\1]" "ab")"#, #"(replace-regexp-in-string "a" "\\x" "a")"#, #"(replace-regexp-in-string "a" "\\1" "a")"#, | ||
| 94 | #"(replace-regexp-in-string "a" "\\\\" "a")"#, #"(replace-regexp-in-string "a\\(b\\)" "Z" "abab" nil nil 1)"#, | ||
| 95 | #"(replace-regexp-in-string "b" "Z" "abab" nil nil nil 2)"#, #"(replace-regexp-in-string "o" "0" "foo" nil t)"#, | ||
| 96 | #"(replace-regexp-in-string "\\([0-9]+\\)" "<\\1>" "a1b22")"#, #"(replace-regexp-in-string "[aeiou]" (lambda (m) (upcase m)) "hello world")"#, | ||
| 97 | #"(replace-regexp-in-string "[0-9]+" (lambda (m) (number-to-string (* 2 (string-to-number m)))) "a1b22")"#, | ||
| 98 | #"(let ((case-fold-search nil)) (replace-regexp-in-string "é" "e" "café"))"#, #"(replace-regexp-in-string "—" "-" "a—b")"#, #"(regexp-quote "a.b*[c]^$+?\\")"#, #"(string-match (regexp-quote "a.b") "axb a.b")"#, | ||
| 99 | #"(split-string "a1b22c" "[0-9]+")"#, #"(split-string " a b " " +")"#, #"(split-string "a,b,,c" "," t)"#, | ||
| 100 | #"(split-string " a , b " "," t " ")"#, #"(split-string "abc" "")"#, #"(split-string "abc" "" t)"#, #"(split-string "a-b_c" "\\W")"#, | ||
| 101 | #"(split-string "a,b" "," nil "\\s-*")"#, #"(split-string "a b" nil)"#, #"(split-string " two words " "[ ]+" t)"#, | ||
| 102 | #"(split-string "a\nb" "$")"#, #"(split-string "a\nb\nc" "^")"#, #"(split-string "foo bar" "\\>")"#, #"(split-string "foo bar" "\\<")"#, | ||
| 103 | #"(split-string "foo bar" "\\b")"#, #"(split-string "a\nb" "$" t)"#, #"(split-string " a ,, b " "," nil " +")"#, #"(split-string " a ,, b " "," t " +")"#, | ||
| 104 | #"(replace-regexp-in-string "a" "\\?" "a")"#, #"(let ((s "abc")) (string-match "b" s) (replace-match "\\?" nil nil s))"#, | ||
| 105 | #"(string-pad "ab" -1)"#, "(let* ((a (list 3 1 2)) (b (list 4 5))) (sort a #'<) (list a b))", | ||
| 106 | "(last '(1 2 3))", "(last '(1 2 3) 2)", "(last '(1 2 3) 0)", "(last '(1 2 . 3))", "(last nil)", "(butlast '(1 2 3))", | ||
| 107 | "(butlast '(1 2 3) 2)", "(butlast '(1 2 3) 0)", "(butlast nil)", "(butlast '(1 2 . 3))", #"(delete-dups (list 1 2 1 "a" "a"))"#, | ||
| 108 | "(nreverse (list 1 2 3))", "(nreverse [1 2 3])", #"(nreverse "abc")"#, "(let ((l (list 1 2 3))) (nreverse l) l)", | ||
| 109 | "(let ((l (list 1 2 3))) (setq l (nreverse l)) l)", "(sort (list 3 1 2) #'<)", "(let ((l (list 3 1 2))) (sort l #'<) l)", | ||
| 110 | "(let ((v [3 1 2])) (sort v #'<) v)", "(let ((v [3 1 2])) (sort v) v)", "(let ((l (list 3 1 2))) (sort l :in-place t) l)", | ||
| 111 | "(sort (list 3 1 2))", "(sort [3 1 2] :reverse t)", #"(sort '("b" "a" "c"))"#, "(sort (list 'b 'a))", "(sort (list 3 1 2) :key #'-)", | ||
| 112 | "(sort '(3 1 2) :lessp #'>)", "(sort '((b . 2) (a . 1) (c . 1)) :key #'cdr)", "(sort '((1 . a) (0 . b) (1 . c) (0 . d)) (lambda (x y) (< (car x) (car y))))", | ||
| 113 | "(seq-reduce #'+ '(1 2 3) 10)", "(seq-reduce #'+ [] 0)", "(seq-filter (lambda (x) (> x 2)) [1 2 3 4])", | ||
| 114 | "(seq-remove (lambda (x) (> x 2)) '(1 2 3 4))", "(seq-map #'1+ [1 2])", #"(seq-map #'1+ "ab")"#, "(seq-uniq '(1 2 2 1 3))", | ||
| 115 | #"(seq-uniq "abca")"#, "(cl-reduce #'+ '(1 2 3))", "(cl-reduce #'+ '())", "(cl-reduce #'+ '(5))", "(cl-reduce #'list '(1 2 3) :initial-value 0)", | ||
| 116 | "(cl-reduce #'+ [1 2 3] :initial-value 4)", "(cl-remove-if (lambda (x) (> x 2)) '(1 2 3 4))", "(cl-remove-if (lambda (x) (> x 2)) [1 2 3 4])", | ||
| 117 | #"(cl-remove-if (lambda (c) (= c ?a)) "banana")"#, "(cl-remove-if-not (lambda (x) (> x 2)) '(1 2 3 4))", "(cl-find 2 '(1 2 3))", | ||
| 118 | #"(cl-find "a" '("a"))"#, #"(cl-find "a" '("a") :test #'equal)"#, "(cl-find 2 '(1 2 3) :test #'=)", "(cl-position 3 '(1 2 3))", | ||
| 119 | "(cl-position 9 '(1 2 3))", #"(cl-position ?b "abc")"#, "(cl-position 2 [1 2])", | ||
| 120 | #"(progn (defun orgstar-sq (x) "Square." (* x x)) (orgstar-sq 4))"#, "(defun orgstar-f () 1)", #"(progn (defun orgstar-g () "doc") (orgstar-g))"#, | ||
| 121 | "(progn (defun orgstar-h (a) (interactive) (1+ a)) (orgstar-h 1))", "(progn (defun orgstar-fact (n) (if (< n 2) 1 (* n (orgstar-fact (1- n))))) (orgstar-fact 10))", | ||
| 122 | "(defvar orgstar-v 3)", "(progn (defvar orgstar-w 3) (defvar orgstar-w 4) orgstar-w)", "(progn (defconst orgstar-c 3) (defconst orgstar-c 4) orgstar-c)", | ||
| 123 | "(let-alist '((a . 1) (b . ((c . 2)))) (list .a .b.c .d))", "(let-alist '((a . 1)) (let-alist '((a . 2)) .a))", | ||
| 124 | "(let-alist '((a . 1) (b . 2)) (+ .a .b))", "(pcase 3 (1 'one) (3 'three))", #"(pcase "x" ("x" 'ex) (_ 'other))"#, "(pcase 'b ('a 1) ('b 2))", | ||
| 125 | "(pcase '(1 2 3) (`(,a ,b . ,c) (list a b c)))", "(pcase '(add 1 2) (`(add ,x ,y) (+ x y)) (`(sub ,x ,y) (- x y)))", | ||
| 126 | "(pcase '(sub 5 2) (`(add ,x ,y) (+ x y)) (`(sub ,x ,y) (- x y)))", "(pcase 5 ((pred stringp) 's) ((pred integerp) 'i))", | ||
| 127 | "(pcase 5 ((pred (lambda (n) (> n 3))) 'big) (_ 'small))", "(pcase 5 (x (* x 2)))", "(pcase 7 (1 'a))", "(pcase :k (:k 'kw))", | ||
| 128 | "(pcase [1 2] (`[,a ,b] (+ a b)))", "(pcase nil ('nil 'isnil))", "(pcase '(1 2) (`(1 ,x) x))", "(pcase '(1 1) (`(,x ,x) 'same) (_ 'differ))", | ||
| 129 | "(pcase '(1 2) (`(,x ,x) 'same) (_ 'differ))", "(pcase ?a (?a 'char))", "(cl-loop for x in '(1 2 3) collect (* x x))", | ||
| 130 | "(cl-loop for i from 1 to 4 sum i)", "(cl-loop for i from 1 to 3 for x in '(a b) collect (list i x))", "(cl-loop for i from 0 to 2 collect i)", | ||
| 131 | "(cl-loop for x in '(1 2.5) sum x)", "(cl-loop for i from 5 to 3 collect i)", "(cl-loop for x in nil sum x)", | ||
| 132 | "(with-output-to-string (cl-loop for x in '(1 2) do (princ x) (princ \"-\")))", "(cl-loop for i from 1 to 3 for j from i to 10 collect (+ i j))", | ||
| 133 | "(let ((n 1)) (cl-incf n) (cl-incf n 10) n)", "(let ((n 1.5)) (cl-decf n))", "(let ((n 5)) (list (cl-decf n 2) n))", | ||
| 134 | "(undefined-orgstar-function (car 1))", | ||
| 135 | ] | ||
| 136 | |||
| 137 | /// Forms that use what the evaluator lacks, refused rather than answered differently. | ||
| 138 | static let unsupported = [ | ||
| 139 | "(expt 3 40)", "(ash 1 63)", #"(random "seed")"#, #"(string-match "\\(?2:a\\)" "a")"#, #"(string-match "\\ca" "a")"#, | ||
| 140 | #"(string-match "é" "café")"#, #"(let ((case-fold-search nil)) (replace-regexp-in-string "É" "e" "cafÉ"))"#, #"(string-match "\\w" "café")"#, "(string-match \"k\" \"\u{212A}\")", #"(match-string 0)"#, | ||
| 141 | #"(string-width "中")"#, #"(sort "cba")"#, "(seq-uniq '(1 2) #'=)", "(cl-find 2 '(1 2 3) :key #'1+)", | ||
| 142 | "(pcase 1.0 (1.0 'f))", "(pcase 1 ((or 1 2) 'a))", "(pcase 1 ((pred (< 0)) 'a))", "(cl-loop for x across [1 2] collect x)", | ||
| 143 | "(cl-loop for i from 1 to 3 sum i collect i)", "(cl-loop repeat 3 collect 1)", "(let ((l (list 1 2))) (cl-incf (car l)))", | ||
| 144 | "(when-let ((x 1)) x)", "(undefined-orgstar-macro (car 1))", "(undefined-orgstar-macro void-orgstar-variable)", | ||
| 145 | // In-place changes to a list another value may share. | ||
| 146 | "(let* ((a (list 3 1 2)) (b a)) (sort a '<) b)", "(let ((x (list 1 3 2))) (sort (cdr x) '<) x)", | ||
| 147 | "(let* ((a (list 3 1 2)) (b (list a))) (sort a '<) b)", "(let* ((a (list 1 2 3)) (b a)) (nreverse a) b)", | ||
| 148 | "(let* ((a (list 1 1 2)) (b a)) (delete-dups a) b)", "(let ((a (list 3 1 2))) (list a (sort a '<)))", | ||
| 149 | "(let* ((a (list 3 1 2)) (b a)) (funcall #'sort a '<) b)", "(let ((a (list 3 1 2))) (prog1 a (sort a '<)))", | ||
| 150 | // Errors whose data, or whose symbol, isn't known here. | ||
| 151 | "(condition-case err (aref [1] 5) (error err))", "(condition-case nil (number-sequence 1 2 0) (wrong-type-argument 1))", | ||
| 152 | #"(capitalize "café")"#, | ||
| 153 | ] | ||
| 154 | |||
| 155 | static func strict(_ form: String) -> String { | ||
| 156 | guard let sexp = try? LispReader.readFirst(form).sexp else { return "read-error" } | ||
| 157 | do { | ||
| 158 | return Elisp.printed(try Elisp().eval(sexp), escape: true) | ||
| 159 | } catch is Elisp.Unsupported { | ||
| 160 | return "unsupported" | ||
| 161 | } catch { | ||
| 162 | return "error" | ||
| 163 | } | ||
| 164 | } | ||
| 165 | |||
| 166 | @Test(.enabled(if: oracle)) | ||
| 167 | func libraryMatchesEmacs() throws { | ||
| 168 | let forms = Self.library.filter { !$0.hasPrefix("(undefined-") } | ||
| 169 | let list = "(list " + forms.map { "(condition-case nil (prin1-to-string \($0)) (error \"error\"))" }.joined(separator: " ") + ")" | ||
| 170 | let emacs = try EmacsOracle.evaluate("", list, prelude: "(require 'cl-lib) (require 'seq) (require 'let-alist)") | ||
| 171 | #expect(emacs.count == forms.count) | ||
| 172 | for (form, expected) in zip(forms, emacs) { | ||
| 173 | #expect(Self.strict(form) == expected, "\(form): \(Self.strict(form)), Emacs \(expected)") | ||
| 174 | } | ||
| 175 | } | ||
| 176 | |||
| 177 | @Test func refusesWhatItLacks() { | ||
| 178 | for form in Self.unsupported { #expect(Self.strict(form) == "unsupported", "\(form)") } | ||
| 179 | // Arguments aren't evaluated for a function it doesn't have. | ||
| 180 | #expect(Self.strict("(undefined-orgstar-function (car 1))") == "unsupported") | ||
| 181 | } | ||
| 182 | |||
| 183 | /// The syntax classes follow `org-mode-syntax-table`, and for Emacs Lisp blocks, the table | ||
| 184 | /// of `*scratch*` in `emacs -Q --batch -l`. | ||
| 185 | @Test(.enabled(if: oracle)) | ||
| 186 | func syntaxTablesMatchEmacs() throws { | ||
| 187 | let classes = "(let (r) (dotimes (c 128) (push (string (char-syntax c)) r)) (apply #'concat (nreverse r)))" | ||
| 188 | let emacs = try EmacsOracle.evaluate("", "(list \(classes))") | ||
| 189 | #expect(emacs == [String(ElispSyntax.org.classes)]) | ||
| 190 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-syntax-\(UUID().uuidString)") | ||
| 191 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) | ||
| 192 | defer { try? FileManager.default.removeItem(at: folder) } | ||
| 193 | let script = folder.appendingPathComponent("syntax.el") | ||
| 194 | try ";;; -*- lexical-binding: t -*-\n(princ \(classes))\n".write(to: script, atomically: true, encoding: .utf8) | ||
| 195 | #expect(try EmacsOracle.run(["-Q", "--batch", "-l", script.path]) == String(ElispSyntax.emacsLisp.classes)) | ||
| 196 | } | ||
| 197 | |||
| 198 | static let timeForms = [ | ||
| 199 | #"(org-time-string-to-time "<2026-11-20 Fri 10:30>")"#, #"(org-time-string-to-time "2026-11-20")"#, #"(org-time-string-to-time "[2026-11-20 Fri]")"#, | ||
| 200 | #"(org-time-string-to-time "x <2026-11-20 Fri 10:30-11:00> y")"#, #"(org-time-string-to-time "2026-11-20 7:05")"#, #"(org-time-string-to-time "foo")"#, | ||
| 201 | #"(org-time-string-to-absolute "<2026-11-20 Fri>")"#, #"(org-time-string-to-absolute "<2026-11-20 Fri 23:59 +1w>")"#, | ||
| 202 | #"(time-add (org-time-string-to-time "<2026-11-20 Fri>") 3600)"#, "(time-add 1 2)", "(time-add '(1 2) '(0 5))", "(time-add '(1 2 3 4) 1)", | ||
| 203 | "(time-add '(1 2 3) 1)", "(time-add '(0 1 500000 0) '(0 1 600000 0))", "(time-subtract '(0 1 0) '(0 2 500000))", "(time-subtract 5 '(0 2))", | ||
| 204 | #"(time-subtract (org-time-string-to-time "<2026-11-21 Sat>") (org-time-string-to-time "<2026-11-20 Fri>"))"#, | ||
| 205 | "(float-time '(1 2))", "(float-time '(0 1 500000 0))", "(float-time '(0 1 1))", "(float-time 5)", "(float-time 2.5)", | ||
| 206 | #"(float-time (org-time-string-to-time "<2026-11-20 Fri 10:30>"))"#, #"(days-between "2026-11-20" "2026-01-01")"#, | ||
| 207 | #"(days-between "2026-11-20 10:00" "2026-01-01 23:00")"#, #"(date-to-time "2026-11-20")"#, #"(date-to-time "2026-11-20 10:30")"#, | ||
| 208 | #"(date-to-time "2026-11-20T10:30:05")"#, #"(time-to-days (org-time-string-to-time "<2026-11-20 Fri>"))"#, "(time-to-days 0)", | ||
| 209 | "(time-to-days 86399)", "(time-to-days 86400.5)", | ||
| 210 | #"(format-time-string "%Y-%m-%d %H:%M:%S %a %A %b %h %B %j %u %w %y %e %p %I %l %k %z %T %D %F %R %s %%" (org-time-string-to-time "<2026-11-20 Fri 15:04>"))"#, | ||
| 211 | #"(format-time-string "%Y %e|%k|%l %p" (org-time-string-to-time "<2026-01-05 Mon 00:07>"))"#, #"(format-time-string "%Y" 0)"#, | ||
| 212 | #"(format-time-string "%Y-%m-%d %H:%M" 1795170600 t)"#, #"(format-time-string "%H:%M" 1795170600.75)"#, | ||
| 213 | "(calendar-day-of-week '(11 20 2026))", "(calendar-absolute-from-gregorian '(11 20 2026))", "(calendar-gregorian-from-absolute 739940)", | ||
| 214 | "(calendar-leap-year-p 2028)", "(calendar-last-day-of-month 2 2028)", "(calendar-iso-from-absolute 739940)", | ||
| 215 | #"(let ((s (format-time-string "%Y-%m-%d"))) (string-match "\\`[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\'" s))"#, | ||
| 216 | "(let ((t0 (current-time))) (and (consp t0) (= (length t0) 4) (< (abs (- (float-time t0) (float-time))) 5)))", | ||
| 217 | "(> (time-to-days (current-time)) 739000)", | ||
| 218 | // Proleptic Gregorian dates, before 1582 and before year 1. | ||
| 219 | #"(org-time-string-to-time "<1500-01-01>")"#, #"(org-time-string-to-time "<0099-01-01>")"#, #"(date-to-time "1582-10-10")"#, | ||
| 220 | #"(format-time-string "%F %a" (date-to-time "1500-01-01"))"#, #"(format-time-string "%F" -15000000000)"#, | ||
| 221 | #"(format-time-string "%Y" -100000000000)"#, #"(format-time-string "%Y %y %D %F %j %a" -62200000000)"#, | ||
| 222 | #"(format-time-string "%Y %F" -62135596800)"#, "(time-to-days -100000000000)", #"(time-to-days (date-to-time "1500-01-01"))"#, | ||
| 223 | #"(days-between "1500-01-01" "1600-01-01")"#, #"(format-time-string "%Y %F" 300000000000 t)"#, | ||
| 224 | ] | ||
| 225 | |||
| 226 | static let unsupportedTime = [ | ||
| 227 | "(time-add 0.1 1)", "(time-add '(5 . 10) 1)", #"(format-time-string "%-d" 0)"#, #"(format-time-string "%c" 0)"#, | ||
| 228 | #"(format-time-string "%Y" 0 "EST5")"#, #"(date-to-time "Fri, 20 Nov 2026 10:30:00 +0000")"#, | ||
| 229 | #"(org-time-string-to-absolute "<2026-11-20 Fri>" 739940)"#, "(float-time '(0 1 0 1))", | ||
| 230 | ] | ||
| 231 | |||
| 232 | static func timed(_ form: String) -> String { | ||
| 233 | guard let sexp = try? LispReader.readFirst(form).sexp else { return "read-error" } | ||
| 234 | var utc = Calendar(identifier: .gregorian) | ||
| 235 | utc.timeZone = TimeZone(identifier: "UTC")! | ||
| 236 | let lisp = Elisp() | ||
| 237 | lisp.standardTime(calendar: utc) | ||
| 238 | do { | ||
| 239 | return Elisp.printed(try lisp.eval(sexp), escape: true) | ||
| 240 | } catch is Elisp.Unsupported { | ||
| 241 | return "unsupported" | ||
| 242 | } catch { | ||
| 243 | return "error" | ||
| 244 | } | ||
| 245 | } | ||
| 246 | |||
| 247 | @Test(.enabled(if: oracle)) | ||
| 248 | func timeFunctionsMatchEmacs() throws { | ||
| 249 | let list = "(list " + Self.timeForms.map { "(condition-case nil (prin1-to-string \($0)) (error \"error\"))" }.joined(separator: " ") + ")" | ||
| 250 | let emacs = try EmacsOracle.evaluate("", list, prelude: "(require 'calendar) (require 'time-date)") | ||
| 251 | #expect(emacs.count == Self.timeForms.count) | ||
| 252 | for (form, expected) in zip(Self.timeForms, emacs) { | ||
| 253 | #expect(Self.timed(form) == expected, "\(form): \(Self.timed(form)), Emacs \(expected)") | ||
| 254 | } | ||
| 255 | for form in Self.unsupportedTime { #expect(Self.timed(form) == "unsupported", "\(form)") } | ||
| 256 | } | ||
| 48 | } | 257 | } |
| 49 | 258 | ||
| 50 | /// Inputs that once crashed the evaluator, the diary functions or duration formulas. | 259 | /// Inputs that once crashed the evaluator, the diary functions or duration formulas. |
| @@ -54,11 +263,14 @@ struct HostileInputTests { | |||
| 54 | "(% -9223372036854775808 -1)", "(mod -9223372036854775808 -1)", "(/ -9223372036854775808 -1)", | 263 | "(% -9223372036854775808 -1)", "(mod -9223372036854775808 -1)", "(/ -9223372036854775808 -1)", |
| 55 | "(upcase -1)", "(downcase -1)", "(concat (list -1))", "(format \"%c\" -1)", "(format \"%c\" 99999999)", | 264 | "(upcase -1)", "(downcase -1)", "(concat (list -1))", "(format \"%c\" -1)", "(format \"%c\" 99999999)", |
| 56 | "(funcall (lambda (f) (funcall f f)) (lambda (f) (funcall f f)))", | 265 | "(funcall (lambda (f) (funcall f f)) (lambda (f) (funcall f f)))", |
| 57 | "(dotimes (i 10000000000) nil)", "(number-sequence 1 10000000000)", | 266 | "(dotimes (i 10000000000) nil)", "(number-sequence 1 10000000000)", #"(string-pad "a" 10000000000)"#, |
| 267 | "(cl-loop for i from 1 to 10000000000 sum i)", "(cl-loop for i from 1 collect i)", "(expt 7 10000000000)", | ||
| 58 | ] | 268 | ] |
| 59 | 269 | ||
| 60 | @Test func evaluatorRefusesWithoutCrashing() { | 270 | @Test func evaluatorRefusesWithoutCrashing() { |
| 61 | for form in Self.forms { #expect(ElispTests.ours(form) == "error", "\(form)") } | 271 | for form in Self.forms { #expect(ElispTests.ours(form) == "error", "\(form)") } |
| 272 | // Long lists lose duplicates without comparing every pair. | ||
| 273 | #expect(ElispTests.ours("(length (seq-uniq (append (number-sequence 1 50000) (number-sequence 1 50000))))") == "50000") | ||
| 62 | } | 274 | } |
| 63 | 275 | ||
| 64 | /// On a stack the size of a background task's, deep recursion stops with an error. | 276 | /// On a stack the size of a background task's, deep recursion stops with an error. |
Tests/OrgCoreTests/TableFormulaTests.swift +15
| @@ -102,6 +102,21 @@ struct TableFormulaTests { | |||
| 102 | try compare(Self.native, fallbacksAllowed: false) | 102 | try compare(Self.native, fallbacksAllowed: false) |
| 103 | } | 103 | } |
| 104 | 104 | ||
| 105 | /// Lisp formulas with regexps, math, sequences, loops and dates: all run natively. | ||
| 106 | static let lisp = [ | ||
| 107 | "| name | starred | words |\n|------+---------+-------|\n| apple pie | | |\n| kiwi | | |\n#+TBLFM: $2='(replace-regexp-in-string \"[aeiou]\" \"*\" $1)::$3='(length (split-string $1))\n", | ||
| 108 | "| code | number |\n|------+--------|\n| ab-12 | |\n| none | |\n#+TBLFM: $2='(if (string-match \"[0-9]+\" $1) (match-string 0 $1) \"-\")\n", | ||
| 109 | "| n | root | square | sum |\n|---+------+--------+-----|\n| 4 | | | |\n| 10 | | | |\n#+TBLFM: $2='(sqrt $1);N::$3='(expt $1 2);N::$4='(cl-loop for i from 1 to $1 sum i);N\n", | ||
| 110 | "| day | weekday | since |\n|-----+---------+-------|\n| <2026-11-20 Fri> | | |\n| [2026-03-01 Sun] | | |\n#+TBLFM: $2='(format-time-string \"%A\" (org-time-string-to-time $1))::$3='(- (org-time-string-to-absolute $1) (org-time-string-to-absolute \"<2026-01-01 Thu>\"))\n", | ||
| 111 | "| tags | sorted |\n|------+--------|\n| c,a,b | |\n#+TBLFM: $2='(string-join (sort (split-string $1 \",\") #'string<) \"+\")\n", | ||
| 112 | "| kind | label |\n|------+-------|\n| 1 | |\n| 2 | |\n| 7 | |\n#+TBLFM: $2='(pcase $1 (1 \"one\") (2 \"two\") (_ \"many\"));N\n", | ||
| 113 | ] | ||
| 114 | |||
| 115 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | ||
| 116 | func lispFormulasMatchEmacsNatively() throws { | ||
| 117 | try compare(Self.lisp, fallbacksAllowed: false) | ||
| 118 | } | ||
| 119 | |||
| 105 | func compare(_ tables: [String], fallbacksAllowed: Bool) throws { | 120 | func compare(_ tables: [String], fallbacksAllowed: Bool) throws { |
| 106 | var cases: [EmacsOracle.Case] = [] | 121 | var cases: [EmacsOracle.Case] = [] |
| 107 | var ours: [(text: String, caret: Int, failure: String?)] = [] | 122 | var ours: [(text: String, caret: Int, failure: String?)] = [] |
Tests/OrgProgramsTests/ProgramsTests.swift +20
| @@ -200,3 +200,23 @@ struct JavaScriptFallbackTests { | |||
| 200 | #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n") | 200 | #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n") |
| 201 | } | 201 | } |
| 202 | } | 202 | } |
| 203 | |||
| 204 | /// Emacs Lisp runs in `Elisp` when Emacs isn't installed. | ||
| 205 | struct EmacsLispFallbackTests { | ||
| 206 | func run(_ text: String) async throws -> BabelOutput { | ||
| 207 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2]) | ||
| 208 | guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") } | ||
| 209 | return try await Programs(emacs: { nil }).runBabel(job, fileDirectory: FileManager.default.temporaryDirectory) | ||
| 210 | } | ||
| 211 | |||
| 212 | @Test func runsWithoutEmacs() async throws { | ||
| 213 | #expect(try await run("#+begin_src emacs-lisp\n(cl-loop for i from 1 to 4 sum i)\n#+end_src\n").stdout.contains("\"s\":\"10\"")) | ||
| 214 | } | ||
| 215 | |||
| 216 | @Test func refusesWhatOnlyEmacsRuns() async throws { | ||
| 217 | let error = await #expect(throws: BabelRunner.Failure.self) { | ||
| 218 | try await run("#+begin_src emacs-lisp\n(with-temp-buffer (insert \"x\") (buffer-string))\n#+end_src\n") | ||
| 219 | } | ||
| 220 | #expect(error?.description == "This block uses Emacs Lisp that runs only in Emacs, and Emacs isn't installed.") | ||
| 221 | } | ||
| 222 | } | ||
docs/manual/guide/08-capture.org +1 −1
| @@ -215,7 +215,7 @@ From the Mac capture window, =%a= links to the heading at the cursor in the open | |||
| 215 | 215 | ||
| 216 | =%[file]= is replaced by the file's contents before anything else, as in Org, so escapes and prompts in the file work, and so does a =%[…]= in it. A relative path is relative to the configuration folder (the one with =capture.toml=), and =~= is your home folder. The file name runs to the last =]= on the line. A file that can't be read leaves =%![could not insert …]= in the text. | 216 | =%[file]= is replaced by the file's contents before anything else, as in Org, so escapes and prompts in the file work, and so does a =%[…]= in it. A relative path is relative to the configuration folder (the one with =capture.toml=), and =~= is your home folder. The file name runs to the last =]= on the line. A file that can't be read leaves =%![could not insert …]= in the text. |
| 217 | 217 | ||
| 218 | =%(sexp)= evaluates the form after the other escapes are expanded, as Org does, and inserts its value: a string as it is, nothing for =nil=; any other value is an error. Escapes inside the form, such as =%i= or =%:link= in a string, are expanded with backslashes and quotes escaped. orgstar evaluates the form with its own Lisp, not Emacs: =concat=, =format=, =upcase=, =substring=, =mapconcat=, =if=, =let= and the other basic functions, plus =format-time-string= (the codes =%<…>= takes, at the capture's time or a =current-time= value), =current-time=, =user-full-name= and =read-string=. =read-string= is asked as a question before the template's =%^= prompts. A form that calls anything else stops the capture with a message naming the function. | 218 | =%(sexp)= evaluates the form after the other escapes are expanded, as Org does, and inserts its value: a string as it is, nothing for =nil=; any other value is an error. Escapes inside the form, such as =%i= or =%:link= in a string, are expanded with backslashes and quotes escaped. orgstar evaluates the form with its own Lisp, not Emacs: =concat=, =format=, =upcase=, =substring=, =mapconcat=, =if=, =let= and the other functions listed under Lisp formulas in [[file:10-tables.org][Tables]], with =current-time= and =format-time-string= at the capture's time, plus =user-full-name= and =read-string=. =read-string= is asked as a question before the template's =%^= prompts. A form that calls anything else stops the capture with a message naming the function. |
| 219 | 219 | ||
| 220 | =%:name= inserts a property of the link being captured. From org-protocol these are =%:link=, =%:description= (the page title), =%:type= (the link's scheme, such as =https=), =%:annotation= (the same as =%a=) and =%:initial= (the same as =%i=). Without org-protocol, =%:annotation= and =%:initial= still work and other names insert nothing. | 220 | =%:name= inserts a property of the link being captured. From org-protocol these are =%:link=, =%:description= (the page title), =%:type= (the link's scheme, such as =https=), =%:annotation= (the same as =%a=) and =%:initial= (the same as =%i=). Without org-protocol, =%:annotation= and =%:initial= still work and other names insert nothing. |
| 221 | 221 | ||
docs/manual/guide/10-tables.org +47 −8
| @@ -455,25 +455,63 @@ The evaluator supports: | |||
| 455 | 455 | ||
| 456 | - special forms: =quote=, =function=, =lambda=, =progn=, =prog1=, =if=, =when=, | 456 | - special forms: =quote=, =function=, =lambda=, =progn=, =prog1=, =if=, =when=, |
| 457 | =unless=, =cond=, =and=, =or=, =let=, =let*=, =setq=, =push=, =pop=, =while=, | 457 | =unless=, =cond=, =and=, =or=, =let=, =let*=, =setq=, =push=, =pop=, =while=, |
| 458 | =dolist=, =dotimes=, =with-output-to-string=, =ignore-errors=, =condition-case=; | 458 | =dolist=, =dotimes=, =with-output-to-string=, =ignore-errors=, =condition-case=, |
| 459 | =save-match-data=, =defun=, =defvar=, =defconst=, =let-alist=, =cl-incf= and =cl-decf= | ||
| 460 | on a variable, with dynamic binding, as Org evaluates formulas; | ||
| 461 | - =pcase= with literal, symbol, quoted, backquoted and =pred= patterns, where =pred= | ||
| 462 | takes a function name or a lambda; | ||
| 463 | - =cl-loop= with =for VAR in LIST=, =for VAR from START to END=, and one kind of | ||
| 464 | =collect= or =sum=, with =do=; | ||
| 459 | - arithmetic: =+=, =-=, =*=, =/=, =%=, =mod=, =1+=, =1-=, =abs=, =max=, =min=, =float=, | 465 | - arithmetic: =+=, =-=, =*=, =/=, =%=, =mod=, =1+=, =1-=, =abs=, =max=, =min=, =float=, |
| 460 | =floor=, =ceiling=, =round=, =truncate=, ~=~, =<=, =>=, ~<=~, ~>=~, ~/=~, =zerop=; | 466 | =floor=, =ceiling=, =round=, =truncate=, ~=~, =<=, =>=, ~<=~, ~>=~, ~/=~, =zerop=, |
| 467 | =expt=, =sqrt=, =exp=, =log=, =sin=, =cos=, =tan=, =asin=, =acos=, =atan=, =isnan=, | ||
| 468 | =random=, =logand=, =logior=, =logxor=, =ash=, and the variables =float-pi=, =pi= and | ||
| 469 | =float-e=; | ||
| 461 | - predicates: =not=, =null=, =eq=, =eql=, =equal=, =numberp=, =integerp=, =floatp=, | 470 | - predicates: =not=, =null=, =eq=, =eql=, =equal=, =numberp=, =integerp=, =floatp=, |
| 462 | =stringp=, =listp=, =consp=, =symbolp=; | 471 | =stringp=, =listp=, =consp=, =symbolp=; |
| 463 | - lists: =car=, =cdr=, =cadr=, =cddr=, =cons=, =list=, =nth=, =nthcdr=, =elt=, =aref=, | 472 | - lists: =car=, =cdr=, =cadr=, =cddr=, =cons=, =list=, =nth=, =nthcdr=, =elt=, =aref=, |
| 464 | =append=, =length=, =reverse=, =number-sequence=, =memq=, =member=, =memql=, =assoc=, | 473 | =append=, =length=, =reverse=, =number-sequence=, =memq=, =member=, =memql=, =assoc=, |
| 465 | =assq=, =delq=, =delete=, =mapcar=, =mapc=, =mapconcat=, =funcall=, =apply=, | 474 | =assq=, =delq=, =delete=, =mapcar=, =mapc=, =mapconcat=, =funcall=, =apply=, |
| 466 | =identity=, =ignore=; | 475 | =identity=, =ignore=, =last=, =butlast=, =delete-dups=, =nreverse=, =sort= (both |
| 476 | calling conventions; these three need Emacs when they would change a list that | ||
| 477 | another variable, list or argument may share), =seq-reduce=, =seq-filter=, =seq-remove=, =seq-map=, =seq-uniq=, | ||
| 478 | =cl-reduce= (with =:initial-value=), =cl-remove-if=, =cl-remove-if-not=, =cl-find= and | ||
| 479 | =cl-position= (with =:test=); | ||
| 467 | - strings: =concat=, =format=, =format-message=, ~string=~, =string-equal=, =string<=, | 480 | - strings: =concat=, =format=, =format-message=, ~string=~, =string-equal=, =string<=, |
| 468 | =string-lessp=, =upcase=, =downcase=, =capitalize=, =substring=, =string-to-number=, | 481 | =string-lessp=, =upcase=, =downcase=, =capitalize=, =substring=, =string-to-number=, |
| 469 | =number-to-string=, =int-to-string=, =string-prefix-p=, =string-suffix-p=, | 482 | =number-to-string=, =int-to-string=, =string-prefix-p=, =string-suffix-p=, |
| 470 | =string-empty-p=, =string-trim=, =split-string=, =prin1-to-string=; | 483 | =string-empty-p=, =string-trim=, =split-string=, =prin1-to-string=, =string-join=, |
| 484 | =string-to-char=, =char-to-string=, =string-pad=, =string-width=, =string-search=, | ||
| 485 | =string-replace=; | ||
| 486 | - regular expressions: =string-match=, =string-match-p=, =match-beginning=, =match-end=, | ||
| 487 | =match-string=, =replace-match= and =replace-regexp-in-string= on strings, and | ||
| 488 | =regexp-quote=; | ||
| 489 | - time: =current-time=, =format-time-string=, =float-time=, =time-add=, =time-subtract=, | ||
| 490 | =time-to-days=, =date-to-time=, =days-between=, =org-time-string-to-time=, | ||
| 491 | =org-time-string-to-absolute= and the =calendar-= functions that diary sexps use, in | ||
| 492 | the local time zone and the proleptic Gregorian calendar; | ||
| 471 | - output and errors: =princ=, =prin1=, =print=, =terpri=, =message=, =error=, | 493 | - output and errors: =princ=, =prin1=, =print=, =terpri=, =message=, =error=, |
| 472 | =user-error=; | 494 | =user-error=; |
| 473 | - Org's lookup functions =org-lookup-first=, =org-lookup-last= and =org-lookup-all=. | 495 | - Org's lookup functions =org-lookup-first=, =org-lookup-last= and =org-lookup-all=. |
| 474 | 496 | ||
| 475 | Any other function needs Emacs. An error inside a Lisp formula writes =#ERROR= in the | 497 | Regular expressions use Emacs's syntax and the syntax table of an Org buffer, and |
| 476 | field, as does a Calc error. | 498 | =case-fold-search= is on unless the formula binds it to =nil=. These need Emacs: |
| 499 | numbered groups =\\(?N:=, categories =\\c=, syntax classes and character classes | ||
| 500 | such as =\\w=, =\\b= or =[[:alpha:]]= against text with characters past ASCII, | ||
| 501 | and case folding of a letter past ASCII, including =capitalize=. =condition-case= | ||
| 502 | binds its variable to the error symbol and data, such as =(wrong-type-argument listp 1)=; | ||
| 503 | reading that variable for an error whose data orgstar doesn't know, such as | ||
| 504 | =args-out-of-range=, needs Emacs, as does a handler that names a specific condition | ||
| 505 | when the error isn't one of =wrong-type-argument=, =args-out-of-range=, =arith-error=, | ||
| 506 | =void-variable=, =invalid-function=, =wrong-number-of-arguments=, =error= and | ||
| 507 | =user-error=. =format-time-string= takes =%Y=, =%y=, =%m=, | ||
| 508 | =%d=, =%e=, =%H=, =%k=, =%I=, =%l=, =%M=, =%S=, =%p=, =%a=, =%A=, =%b=, =%h=, =%B=, =%u=, | ||
| 509 | =%w=, =%j=, =%F=, =%D=, =%R=, =%T=, =%s=, =%z=, =%n=, =%t= and =%%=, without flags or | ||
| 510 | widths; other codes need Emacs, as do float times in =time-add= and =time-subtract=. =date-to-time= and =days-between= read dates as | ||
| 511 | =YYYY-MM-DD=, with an optional =HH:MM= or =HH:MM:SS=. | ||
| 512 | |||
| 513 | Any other function, or a macro not listed, needs Emacs. An error inside a Lisp formula | ||
| 514 | writes =#ERROR= in the field, as does a Calc error. | ||
| 477 | 515 | ||
| 478 | * Entering formulas | 516 | * Entering formulas |
| 479 | 517 | ||
| @@ -555,8 +593,9 @@ packages and customizations are not loaded, then replaces the table with Emacs's | |||
| 555 | result. It looks for Emacs at the path in the =ORGSTAR_EMACS= environment variable, | 593 | result. It looks for Emacs at the path in the =ORGSTAR_EMACS= environment variable, |
| 556 | then =/opt/homebrew/bin/emacs=, =/usr/local/bin/emacs=, | 594 | then =/opt/homebrew/bin/emacs=, =/usr/local/bin/emacs=, |
| 557 | =/Applications/Emacs.app/Contents/MacOS/Emacs=, =/run/current-system/sw/bin/emacs= and | 595 | =/Applications/Emacs.app/Contents/MacOS/Emacs=, =/run/current-system/sw/bin/emacs= and |
| 558 | =/usr/bin/emacs=. If none is found, the echo area says Emacs isn't installed and the | 596 | =/usr/bin/emacs=. If none is found, the echo area shows the reason, as |
| 559 | table is unchanged. Emacs gets your =PATH= with =/opt/homebrew/bin=, =/usr/local/bin=, | 597 | =This table's formulas can't be calculated here: reason.=, and the table is unchanged. |
| 598 | Emacs gets your =PATH= with =/opt/homebrew/bin=, =/usr/local/bin=, | ||
| 560 | =/Library/TeX/texbin=, =/usr/bin= and =/bin= added, as code blocks and export do, so | 599 | =/Library/TeX/texbin=, =/usr/bin= and =/bin= added, as code blocks and export do, so |
| 561 | programs a formula starts are found when orgstar was opened from the Dock. The run | 600 | programs a formula starts are found when orgstar was opened from the Dock. The run |
| 562 | stops after 60 seconds. If you edit the table while Emacs is working, its result is | 601 | stops after 60 seconds. If you edit the table while Emacs is working, its result is |
docs/manual/guide/11-code-blocks.org +3 −3
| @@ -89,7 +89,7 @@ On the Mac, orgstar starts each interpreter through =/usr/bin/env=. Because an a | |||
| 89 | | =sh=, =bash=, =zsh=, =fish=, =ksh=, =dash=, =ash=, =csh=, =mksh=, =posh= | The shell of that name | | 89 | | =sh=, =bash=, =zsh=, =fish=, =ksh=, =dash=, =ash=, =csh=, =mksh=, =posh= | The shell of that name | |
| 90 | | =shell= | The shell in =SHELL=, or =/bin/sh= | | 90 | | =shell= | The shell in =SHELL=, or =/bin/sh= | |
| 91 | | =python= | =python3=, or the program in =:python= | | 91 | | =python= | =python3=, or the program in =:python= | |
| 92 | | =emacs-lisp=, =elisp= | =emacs -Q --batch=; see Emacs Lisp blocks below | | 92 | | =emacs-lisp=, =elisp= | =emacs -Q --batch=, or the interpreter; see below | |
| 93 | | =ruby= | =ruby=, or the program in =:ruby= | | 93 | | =ruby= | =ruby=, or the program in =:ruby= | |
| 94 | | =js=, =javascript= | =node=, or JavaScriptCore without it; see below | | 94 | | =js=, =javascript= | =node=, or JavaScriptCore without it; see below | |
| 95 | | =R= | =Rscript -= | | 95 | | =R= | =Rscript -= | |
| @@ -618,9 +618,9 @@ An inline call, =call_double(n=6)=, has the same parts as a =#+CALL:= line: =cal | |||
| 618 | 618 | ||
| 619 | * Emacs Lisp blocks | 619 | * Emacs Lisp blocks |
| 620 | 620 | ||
| 621 | On the Mac, an =emacs-lisp= or =elisp= block runs in a new =emacs -Q --batch= for each run, with lexical binding on. =-Q= means your init file and packages are not loaded, and nothing carries over between runs. orgstar looks for Emacs at =ORGSTAR_EMACS=, then =/opt/homebrew/bin/emacs=, =/usr/local/bin/emacs=, =/Applications/Emacs.app/Contents/MacOS/Emacs=, =/run/current-system/sw/bin/emacs= and =/usr/bin/emacs=. Without Emacs, the block fails with "Emacs isn't installed, so Emacs Lisp blocks can't run." | 621 | On the Mac, an =emacs-lisp= or =elisp= block runs in a new =emacs -Q --batch= for each run, with lexical binding on. =-Q= means your init file and packages are not loaded, and nothing carries over between runs. orgstar looks for Emacs at =ORGSTAR_EMACS=, then =/opt/homebrew/bin/emacs=, =/usr/local/bin/emacs=, =/Applications/Emacs.app/Contents/MacOS/Emacs=, =/run/current-system/sw/bin/emacs= and =/usr/bin/emacs=. Without Emacs, the block runs in orgstar's own Emacs Lisp interpreter, and a block that uses something the interpreter does not have fails with "This block uses Emacs Lisp that runs only in Emacs, and Emacs isn't installed." |
| 622 | 622 | ||
| 623 | On iOS, Emacs Lisp blocks run in orgstar's own Emacs Lisp interpreter. It covers ordinary list, string, number and control forms, =princ= and =message=. A block that uses something the interpreter does not have fails with "This block uses Emacs Lisp that runs only in Emacs, on the Mac." A Lisp error fails the run, as it does in Emacs. | 623 | On iOS, Emacs Lisp blocks run in orgstar's own Emacs Lisp interpreter. It has the forms and functions listed under Lisp formulas in [[file:10-tables.org][Tables]]: list, string, number and control forms, regular expressions on strings, =defun=, =pcase=, =cl-loop=, the =seq-= and =cl-= sequence functions, time functions, =princ= and =message=. Like =emacs -Q --batch=, it uses lexical binding, with dynamic binding for variables declared with =defvar=, and the syntax table of Emacs Lisp mode for regular expressions and =capitalize=. A quoted lambda, ='(lambda ...)=, runs with dynamic binding, as in Emacs. A closure can be called, stored and passed to functions such as =mapcar=; a block that takes one apart as a list, compares it or prints it needs Emacs. It has no buffers. A block that uses something the interpreter does not have fails with "This block uses Emacs Lisp that runs only in Emacs, on the Mac." A Lisp error fails the run, as it does in Emacs. |
| 624 | 624 | ||
| 625 | In the [[file:../install.org][Mac App Store version]], Emacs Lisp blocks run in the same interpreter as on iOS. A block that uses something it does not have fails with "This block uses Emacs Lisp that runs only in Emacs." | 625 | In the [[file:../install.org][Mac App Store version]], Emacs Lisp blocks run in the same interpreter as on iOS. A block that uses something it does not have fails with "This block uses Emacs Lisp that runs only in Emacs." |
| 626 | 626 | ||
docs/manual/install.org +1 −1
| @@ -54,7 +54,7 @@ App Store version. | |||
| 54 | 54 | ||
| 55 | | Feature | Mac App Store version | Download version | | 55 | | Feature | Mac App Store version | Download version | |
| 56 | |----------------------------+-------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------| | 56 | |----------------------------+-------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------| |
| 57 | | Code blocks | Emacs Lisp in orgstar's own interpreter, JavaScript in JavaScriptCore | Every language installed; Emacs Lisp in Emacs; JavaScript in node, or JavaScriptCore without it | | 57 | | Code blocks | Emacs Lisp in orgstar's own interpreter, JavaScript in JavaScriptCore | Every language installed; Emacs Lisp in Emacs and JavaScript in node, or built in without them | |
| 58 | | Sessions, graphics | JavaScript sessions; no graphics | Yes | | 58 | | Sessions, graphics | JavaScript sessions; no graphics | Yes | |
| 59 | | Tangling | Yes | Yes | | 59 | | Tangling | Yes | Yes | |
| 60 | | Table formulas | Those orgstar computes itself | The rest in Emacs as well | | 60 | | Table formulas | Those orgstar computes itself | The rest in Emacs as well | |