Commit f8dc91d0e6
Verified · cmc
Layout: unified · split
Sources/OrgCore/Agenda/DiarySexp.swift +15 −7
| @@ -125,9 +125,8 @@ public enum DiarySexp { | ||
| 125 | 125 | |
| 126 | 126 | static func optional(_ args: [Sexp], _ i: Int) -> Sexp { i < args.count ? args[i] : .nil } |
| 127 | 127 | |
| 128 | static func define(_ lisp: Elisp) { | |
| 129 | func date() throws -> Sexp { try lisp.value("date") } | |
| 130 | func entry() throws -> Sexp { try lisp.value("entry") } | |
| 128 | /// The calendar functions, which don't depend on the diary entry. | |
| 129 | static func defineCalendar(_ lisp: Elisp) { | |
| 131 | 130 | func arity(_ args: [Sexp], _ range: ClosedRange<Int>, _ name: String) throws { |
| 132 | 131 | try Elisp.arity(args, range, name) |
| 133 | 132 | } |
| @@ -180,7 +179,20 @@ public enum DiarySexp { | ||
| 180 | 179 | let thursday = day - (Days.weekday(day) + 6) % 7 + 3 |
| 181 | 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 | 196 | lisp.define("diary-ordinal-suffix") { _, args in |
| 185 | 197 | try arity(args, 1...1, "diary-ordinal-suffix") |
| 186 | 198 | return .string(try ordinalSuffix(try Elisp.int(args[0]))) |
| @@ -299,10 +311,6 @@ public enum DiarySexp { | ||
| 299 | 311 | lisp.define("org-cyclic") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-cyclic", args) } } |
| 300 | 312 | lisp.define("org-block") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-block", args) } } |
| 301 | 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 | 314 | lisp.define("org-calendar-holiday") { _, _ in |
| 307 | 315 | let names = holidays(try absolute(try date())) |
| 308 | 316 | return names.isEmpty ? .nil : .string(names.joined(separator: "; ")) |
Sources/OrgCore/Capture/CaptureLisp.swift +1 −24
| @@ -82,14 +82,7 @@ extension Capture { | ||
| 82 | 82 | self.answers = answers[...] |
| 83 | 83 | lisp.set("user-full-name", .string(context.userName)) |
| 84 | 84 | lisp.define("user-full-name") { [context] _, _ in .string(context.userName) } |
| 85 | lisp.define("current-time") { [context] _, _ in Self.time(context.now) } | |
| 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 | } | |
| 85 | lisp.standardTime(now: { [context] in context.now }, calendar: context.calendar) | |
| 93 | 86 | lisp.define("read-string") { [unowned self] _, args in |
| 94 | 87 | let prompt = args.first?.string ?? "" |
| 95 | 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 | 98 | /// The value to insert for the form `text`: a string, or "" for nil. |
| 122 | 99 | func evaluate(_ text: String) -> Result<String, Failure> { |
| 123 | 100 | let form: Sexp |
Sources/OrgCore/Compute/BabelLanguages.swift +1
| @@ -93,6 +93,7 @@ extension Babel { | ||
| 93 | 93 | public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? { |
| 94 | 94 | guard let form = job.lispForm, let sexp = try? LispReader.readFirst(form).sexp else { return nil } |
| 95 | 95 | let lisp = Elisp() |
| 96 | lisp.standardTime() | |
| 96 | 97 | let result: Sexp |
| 97 | 98 | do { |
| 98 | 99 | result = try lisp.eval(sexp) |
Sources/OrgCore/Compute/TableFormulas.swift +1
| @@ -656,6 +656,7 @@ extension EmacsBuffer { | ||
| 656 | 656 | /// `(eval (eval (read form)))` for a Lisp formula; an error is `#ERROR`. |
| 657 | 657 | func evalLisp(_ form: String, duration: DurationFormat?) throws -> String { |
| 658 | 658 | let lisp = Elisp() |
| 659 | lisp.standardTime() | |
| 659 | 660 | Self.defineLookups(lisp) |
| 660 | 661 | let value: Sexp |
| 661 | 662 | do { |
Sources/OrgCore/Config/Elisp.swift +23 −25
| @@ -16,9 +16,9 @@ public final class Elisp { | ||
| 16 | 16 | |
| 17 | 17 | public typealias Builtin = (Elisp, [Sexp]) throws -> Sexp |
| 18 | 18 | |
| 19 | private var scopes: [[String: Sexp]] = [[:]] | |
| 19 | var scopes: [[String: Sexp]] = [[:]] | |
| 20 | 20 | private var functions: [String: Builtin] = [:] |
| 21 | private var steps = 0 | |
| 21 | var steps = 0 | |
| 22 | 22 | static let stepLimit = 1_000_000 |
| 23 | 23 | /// Nested evaluations, as `max-lisp-eval-depth` limits them. |
| 24 | 24 | private var depth = 0 |
| @@ -32,9 +32,14 @@ public final class Elisp { | ||
| 32 | 32 | public var standardOutput: String { outputs[0] } |
| 33 | 33 | /// What `message` wrote. |
| 34 | 34 | public private(set) var messages = "" |
| 35 | /// What the last `string-match` matched: each group's range in characters. | |
| 36 | var matchData: [Range<Int>?] = [] | |
| 37 | var regexes: [String: ElispRegex] = [:] | |
| 35 | 38 | |
| 36 | 39 | public init() { |
| 37 | 40 | Self.core(self) |
| 41 | Self.library(self) | |
| 42 | Self.regexFunctions(self) | |
| 38 | 43 | } |
| 39 | 44 | |
| 40 | 45 | /// Defines or replaces a function. |
| @@ -55,7 +60,7 @@ public final class Elisp { | ||
| 55 | 60 | return try body() |
| 56 | 61 | } |
| 57 | 62 | |
| 58 | private func assign(_ name: String, _ v: Sexp) { | |
| 63 | func assign(_ name: String, _ v: Sexp) { | |
| 59 | 64 | for i in scopes.indices.reversed() where scopes[i][name] != nil { |
| 60 | 65 | scopes[i][name] = v |
| 61 | 66 | return |
| @@ -201,7 +206,18 @@ public final class Elisp { | ||
| 201 | 206 | } |
| 202 | 207 | throw Signal(message: "Invalid function: \(head.description)") |
| 203 | 208 | } |
| 204 | return try special(name, Array(items.dropFirst())) ?? callNamed(name, try items.dropFirst().map(eval)) | |
| 209 | let args = Array(items.dropFirst()) | |
| 210 | if let value = try special(name, args) { return value } | |
| 211 | // The function first, so an unknown one, or a macro this evaluator lacks, is | |
| 212 | // unsupported rather than an error from its arguments. | |
| 213 | guard let function = functions[name] else { throw Unsupported(what: "function \(name)") } | |
| 214 | let values = try args.map(eval) | |
| 215 | let result = try function(self, values) | |
| 216 | if case .symbol(let variable)? = args.first, variable != "nil", variable != "t", !variable.hasPrefix(":"), | |
| 217 | let after = Self.afterInPlace(name, values, result) { | |
| 218 | assign(variable, after) | |
| 219 | } | |
| 220 | return result | |
| 205 | 221 | case .dotted: throw Signal(message: "Invalid function") |
| 206 | 222 | default: return form |
| 207 | 223 | } |
| @@ -344,7 +360,7 @@ public final class Elisp { | ||
| 344 | 360 | throw signal |
| 345 | 361 | } |
| 346 | 362 | default: |
| 347 | return nil | |
| 363 | return try moreSpecial(name, args) | |
| 348 | 364 | } |
| 349 | 365 | } |
| 350 | 366 | |
| @@ -725,7 +741,7 @@ public final class Elisp { | ||
| 725 | 741 | } |
| 726 | 742 | lisp.define("substring") { _, args in |
| 727 | 743 | try arity(args, 1...3, "substring") |
| 728 | let chars = Array(try string(args[0])) | |
| 744 | let chars = Array(try string(args[0]).unicodeScalars) | |
| 729 | 745 | func index(_ v: Sexp?, _ fallback: Int) throws -> Int { |
| 730 | 746 | guard let v, !isNil(v) else { return fallback } |
| 731 | 747 | let i = try int(v) |
| @@ -734,7 +750,7 @@ public final class Elisp { | ||
| 734 | 750 | let from = try index(args.count > 1 ? args[1] : nil, 0) |
| 735 | 751 | let to = try index(args.count > 2 ? args[2] : nil, chars.count) |
| 736 | 752 | guard from >= 0, to <= chars.count, from <= to else { throw Signal(message: "Args out of range") } |
| 737 | return .string(String(chars[from..<to])) | |
| 753 | return .string(String(String.UnicodeScalarView(chars[from..<to]))) | |
| 738 | 754 | } |
| 739 | 755 | lisp.define("string-to-number") { _, args in |
| 740 | 756 | try arity(args, 1...2, "string-to-number") |
| @@ -762,24 +778,6 @@ public final class Elisp { | ||
| 762 | 778 | try arity(args, 1...1, "string-trim") |
| 763 | 779 | return .string(try string(args[0]).trimmingCharacters(in: .whitespacesAndNewlines)) |
| 764 | 780 | } |
| 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 | 781 | } |
| 784 | 782 | |
| 785 | 783 | static func add(_ n: Number, _ k: Int) throws -> Number { |
Sources/OrgCore/Config/ElispForms.swift added +255
| @@ -0,0 +1,255 @@ | ||
| 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 lambda = Sexp.list([.symbol("lambda"), args[1]] + body) | |
| 30 | define(name) { lisp, values in try lisp.call(lambda, values) } | |
| 31 | return .symbol(name) | |
| 32 | } | |
| 33 | ||
| 34 | /// `defvar` sets a variable only when it has no global value; `defconst` always does. | |
| 35 | func defineVariable(_ args: [Sexp], constant: Bool) throws -> Sexp { | |
| 36 | guard case .symbol(let name)? = args.first, args.count <= 3 else { throw Signal(message: "Malformed \(constant ? "defconst" : "defvar")") } | |
| 37 | if constant, args.count < 2 { throw Signal(message: "Wrong number of arguments: defconst, 1") } | |
| 38 | if args.count > 1, constant || scopes[0][name] == nil { scopes[0][name] = try eval(args[1]) } | |
| 39 | return .symbol(name) | |
| 40 | } | |
| 41 | ||
| 42 | /// `let-alist`: `.key` and `.key.inner` in the body, outside inner `let-alist` bodies, bound | |
| 43 | /// to the alist's values. | |
| 44 | func letAlist(_ args: [Sexp]) throws -> Sexp { | |
| 45 | guard let first = args.first else { throw Signal(message: "Wrong number of arguments: let-alist, 0") } | |
| 46 | let alist = try eval(first) | |
| 47 | var names: Set<String> = [] | |
| 48 | func search(_ form: Sexp) { | |
| 49 | switch form { | |
| 50 | case .symbol(let s) where s.hasPrefix("."): names.insert(s) | |
| 51 | case .list(let items) where items.first == .symbol("let-alist"): if items.count > 1 { search(items[1]) } | |
| 52 | case .list(let items), .vector(let items): items.forEach(search) | |
| 53 | case .dotted(let items, let last): | |
| 54 | if items.first == .symbol("let-alist") { | |
| 55 | if items.count > 1 { search(items[1]) } | |
| 56 | } else { | |
| 57 | items.forEach(search) | |
| 58 | search(last) | |
| 59 | } | |
| 60 | default: break | |
| 61 | } | |
| 62 | } | |
| 63 | args.dropFirst().forEach(search) | |
| 64 | var bindings: [String: Sexp] = [:] | |
| 65 | for name in names { | |
| 66 | guard !name.hasPrefix("..") else { throw Unsupported(what: "let-alist \(name)") } | |
| 67 | var value = alist | |
| 68 | for key in name.dropFirst().split(separator: ".", omittingEmptySubsequences: false) { | |
| 69 | var pair = Sexp.nil | |
| 70 | for item in try Self.elements(value) { | |
| 71 | if let car = try? Self.car(item), car == .symbol(String(key)), Self.isCons(item) { | |
| 72 | pair = item | |
| 73 | break | |
| 74 | } | |
| 75 | } | |
| 76 | value = try Self.cdr(pair) | |
| 77 | } | |
| 78 | bindings[name] = value | |
| 79 | } | |
| 80 | return try binding(bindings) { try progn(args.dropFirst()) } | |
| 81 | } | |
| 82 | ||
| 83 | static func isCons(_ v: Sexp) -> Bool { | |
| 84 | switch v { | |
| 85 | case .list(let items): !items.isEmpty | |
| 86 | case .dotted: true | |
| 87 | default: false | |
| 88 | } | |
| 89 | } | |
| 90 | ||
| 91 | /// `pcase` with literal, symbol, quote, backquote and `pred` patterns. | |
| 92 | func pcase(_ args: [Sexp]) throws -> Sexp { | |
| 93 | guard let first = args.first else { throw Signal(message: "Wrong number of arguments: pcase, 0") } | |
| 94 | let value = try eval(first) | |
| 95 | for clause in args.dropFirst() { | |
| 96 | let parts = try Self.elements(clause) | |
| 97 | guard let pattern = parts.first else { continue } | |
| 98 | var bindings: [String: Sexp] = [:] | |
| 99 | if try matches(pattern, value, &bindings) { return try binding(bindings) { try progn(parts.dropFirst()) } } | |
| 100 | } | |
| 101 | return .nil | |
| 102 | } | |
| 103 | ||
| 104 | func matches(_ pattern: Sexp, _ value: Sexp, _ bindings: inout [String: Sexp]) throws -> Bool { | |
| 105 | switch pattern { | |
| 106 | case .symbol("_"): | |
| 107 | return true | |
| 108 | case .symbol(let s) where s.hasPrefix(":"): | |
| 109 | return value == pattern | |
| 110 | case .symbol(let s) where s != "nil" && s != "t": | |
| 111 | // A variable used twice must match the same object the second time. | |
| 112 | if let bound = bindings[s] { return Self.eq(bound, value) } | |
| 113 | bindings[s] = value | |
| 114 | return true | |
| 115 | case .integer, .character: | |
| 116 | return Self.eq(pattern, value) | |
| 117 | case .string: | |
| 118 | return pattern == value | |
| 119 | case .list(let items) where items.count == 2 && items[0] == .symbol("quote"): | |
| 120 | return Self.normalized(items[1]) == Self.normalized(value) | |
| 121 | case .list(let items) where items.count == 2 && items[0] == .symbol("\\`"): | |
| 122 | return try backquoted(items[1], value, &bindings) | |
| 123 | case .list(let items) where items.count == 2 && items[0] == .symbol("pred") && (items[1].symbol != nil || items[1].head == "lambda"): | |
| 124 | let function = items[1] | |
| 125 | let soFar = bindings | |
| 126 | return !Self.isNil(try binding(soFar) { try call(function, [value]) }) | |
| 127 | default: | |
| 128 | throw Unsupported(what: "pcase pattern \(pattern.description)") | |
| 129 | } | |
| 130 | } | |
| 131 | ||
| 132 | func backquoted(_ pattern: Sexp, _ value: Sexp, _ bindings: inout [String: Sexp]) throws -> Bool { | |
| 133 | switch pattern { | |
| 134 | case .list(let items) where items.count == 2 && items[0] == .symbol(","): | |
| 135 | return try matches(items[1], value, &bindings) | |
| 136 | case .list(let items) where items.first == .symbol(",@"): | |
| 137 | throw Unsupported(what: "pcase pattern ,@") | |
| 138 | case .list(let items) where !items.isEmpty: | |
| 139 | guard Self.isCons(value) else { return false } | |
| 140 | return try backquoted(items[0], Self.car(value), &bindings) && backquoted(Self.list(Array(items.dropFirst())), Self.cdr(value), &bindings) | |
| 141 | case .dotted(let items, let last): | |
| 142 | guard Self.isCons(value) else { return false } | |
| 143 | let rest = items.count == 1 ? last : .dotted(Array(items.dropFirst()), last) | |
| 144 | return try backquoted(items[0], Self.car(value), &bindings) && backquoted(rest, Self.cdr(value), &bindings) | |
| 145 | case .vector(let patterns): | |
| 146 | guard case .vector(let values) = value, values.count == patterns.count else { return false } | |
| 147 | for (p, v) in zip(patterns, values) where !(try backquoted(p, v, &bindings)) { return false } | |
| 148 | return true | |
| 149 | default: | |
| 150 | return Self.normalized(pattern) == Self.normalized(value) | |
| 151 | } | |
| 152 | } | |
| 153 | ||
| 154 | /// `cl-loop` with `for VAR in LIST`, `for VAR from START [to END]`, `collect`, `sum` and | |
| 155 | /// `do`. | |
| 156 | func loop(_ args: [Sexp]) throws -> Sexp { | |
| 157 | enum Iterator { | |
| 158 | case list(String) | |
| 159 | case range(String, limit: Sexp?) | |
| 160 | } | |
| 161 | var iterators: [Iterator] = [] | |
| 162 | // What each `in` clause has left. | |
| 163 | var lists: [Int: Sexp] = [:] | |
| 164 | var actions: [(kind: String, forms: [Sexp])] = [] | |
| 165 | scopes.append([:]) | |
| 166 | defer { scopes.removeLast() } | |
| 167 | var i = 0 | |
| 168 | func next() throws -> Sexp { | |
| 169 | guard i < args.count else { throw Signal(message: "Syntax error in cl-loop") } | |
| 170 | i += 1 | |
| 171 | return args[i - 1] | |
| 172 | } | |
| 173 | while i < args.count { | |
| 174 | let word = try next() | |
| 175 | switch word.symbol { | |
| 176 | case "for": | |
| 177 | guard case .symbol(let variable) = try next() else { throw Unsupported(what: "cl-loop destructuring") } | |
| 178 | switch try next() { | |
| 179 | case .symbol("in"): | |
| 180 | lists[iterators.count] = try eval(try next()) | |
| 181 | scopes[scopes.count - 1][variable] = .nil | |
| 182 | iterators.append(.list(variable)) | |
| 183 | case .symbol("from"): | |
| 184 | scopes[scopes.count - 1][variable] = try eval(try next()) | |
| 185 | var limit: Sexp? | |
| 186 | if i < args.count, args[i] == .symbol("to") { | |
| 187 | i += 1 | |
| 188 | limit = try eval(try next()) | |
| 189 | } | |
| 190 | iterators.append(.range(variable, limit: limit)) | |
| 191 | case let other: | |
| 192 | throw Unsupported(what: "cl-loop for \(variable) \(other.description)") | |
| 193 | } | |
| 194 | case "collect", "sum": | |
| 195 | actions.append((word.symbol!, [try next()])) | |
| 196 | case "do": | |
| 197 | var forms: [Sexp] = [] | |
| 198 | while i < args.count, Self.isCons(args[i]) { | |
| 199 | forms.append(args[i]) | |
| 200 | i += 1 | |
| 201 | } | |
| 202 | actions.append(("do", forms)) | |
| 203 | default: | |
| 204 | throw Unsupported(what: "cl-loop \(word.description)") | |
| 205 | } | |
| 206 | } | |
| 207 | guard !iterators.isEmpty else { throw Unsupported(what: "cl-loop without for") } | |
| 208 | guard Set(actions.map(\.kind)).subtracting(["do"]).count <= 1 else { throw Unsupported(what: "cl-loop with collect and sum") } | |
| 209 | var collected: [Sexp] = [] | |
| 210 | var total = Sexp.integer(0) | |
| 211 | var first = true | |
| 212 | iterations: while true { | |
| 213 | steps += 1 | |
| 214 | if steps > Self.stepLimit { throw Signal(message: "Evaluation took too long") } | |
| 215 | if !first { | |
| 216 | for (n, iterator) in iterators.enumerated() { | |
| 217 | switch iterator { | |
| 218 | case .list: lists[n] = try Self.cdr(lists[n]!) | |
| 219 | case .range(let variable, _): assign(variable, try callNamed("+", [try value(variable), .integer(1)])) | |
| 220 | } | |
| 221 | } | |
| 222 | } | |
| 223 | first = false | |
| 224 | for (n, iterator) in iterators.enumerated() { | |
| 225 | switch iterator { | |
| 226 | case .list(let variable): | |
| 227 | guard Self.isCons(lists[n]!) else { break iterations } | |
| 228 | assign(variable, try Self.car(lists[n]!)) | |
| 229 | case .range(let variable, let limit): | |
| 230 | if let limit, Self.isNil(try callNamed("<=", [try value(variable), limit])) { break iterations } | |
| 231 | } | |
| 232 | } | |
| 233 | for (kind, forms) in actions { | |
| 234 | switch kind { | |
| 235 | case "collect": collected.append(try eval(forms[0])) | |
| 236 | case "sum": total = try callNamed("+", [total, try eval(forms[0])]) | |
| 237 | default: _ = try progn(forms) | |
| 238 | } | |
| 239 | } | |
| 240 | } | |
| 241 | if actions.contains(where: { $0.kind == "collect" }) { return Self.list(collected) } | |
| 242 | return actions.contains(where: { $0.kind == "sum" }) ? total : .nil | |
| 243 | } | |
| 244 | ||
| 245 | func increment(_ args: [Sexp], decrement: Bool) throws -> Sexp { | |
| 246 | let name = decrement ? "cl-decf" : "cl-incf" | |
| 247 | guard (1...2).contains(args.count) else { throw Signal(message: "Wrong number of arguments: \(name), \(args.count)") } | |
| 248 | guard case .symbol(let variable) = args[0] else { throw Unsupported(what: "\(name) on a place") } | |
| 249 | let current = try value(variable) | |
| 250 | let delta = args.count > 1 ? try eval(args[1]) : .integer(1) | |
| 251 | let new = try callNamed(decrement ? "-" : "+", [current, delta]) | |
| 252 | assign(variable, new) | |
| 253 | return new | |
| 254 | } | |
| 255 | } | |
Sources/OrgCore/Config/ElispLibrary.swift added +324
| @@ -0,0 +1,324 @@ | ||
| 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 pad = try int(args[1]) - s.unicodeScalars.count | |
| 104 | guard pad > 0 else { return .string(s) } | |
| 105 | let padding = String(repeating: String(try scalar(args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 32)), count: pad) | |
| 106 | return .string(args.count > 3 && !isNil(args[3]) ? padding + s : s + padding) | |
| 107 | } | |
| 108 | lisp.define("string-width") { _, args in | |
| 109 | try arity(args, 1...3, "string-width") | |
| 110 | let scalars = Array(try string(args[0]).unicodeScalars) | |
| 111 | let from = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 0 | |
| 112 | let to = args.count > 2 && !isNil(args[2]) ? try int(args[2]) : scalars.count | |
| 113 | guard 0 <= from, from <= to, to <= scalars.count else { throw Signal(message: "Args out of range") } | |
| 114 | return .integer(try scalars[from..<to].reduce(0) { width, c in | |
| 115 | switch c.value { | |
| 116 | case 9: return width + 8 | |
| 117 | case 10: return width | |
| 118 | case 0x20...0x7E, 0xC0...0x27F: return width + 1 | |
| 119 | default: throw Unsupported(what: "string-width of \(String(c))") | |
| 120 | } | |
| 121 | }) | |
| 122 | } | |
| 123 | lisp.define("string-search") { _, args in | |
| 124 | try arity(args, 2...3, "string-search") | |
| 125 | let needle = Array(try string(args[0]).unicodeScalars) | |
| 126 | let haystack = Array(try string(args[1]).unicodeScalars) | |
| 127 | let start = args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 0 | |
| 128 | guard (0...haystack.count).contains(start) else { throw Signal(message: "Args out of range: \(start)") } | |
| 129 | guard needle.count <= haystack.count else { return .nil } | |
| 130 | for i in start...(haystack.count - needle.count) where haystack[i..<(i + needle.count)].elementsEqual(needle) { return .integer(i) } | |
| 131 | return .nil | |
| 132 | } | |
| 133 | lisp.define("string-replace") { _, args in | |
| 134 | try arity(args, 3...3, "string-replace") | |
| 135 | let from = try string(args[0]) | |
| 136 | guard !from.isEmpty else { throw Signal(message: "Wrong length argument: 0") } | |
| 137 | return .string(try string(args[2]).replacingOccurrences(of: from, with: try string(args[1]), options: .literal)) | |
| 138 | } | |
| 139 | } | |
| 140 | ||
| 141 | /// The functions that change a list or vector in place, and what a variable holding the | |
| 142 | /// argument holds after the call: the sorted list for an in-place `sort`, its first cell | |
| 143 | /// for `nreverse`. | |
| 144 | static func afterInPlace(_ name: String, _ args: [Sexp], _ result: Sexp) -> Sexp? { | |
| 145 | switch name { | |
| 146 | case "sort": | |
| 147 | let inPlace = args.count == 2 || args.indices.contains { $0 % 2 == 1 && args[$0] == .symbol(":in-place") && $0 + 1 < args.count && !isNil(args[$0 + 1]) } | |
| 148 | return inPlace ? result : nil | |
| 149 | case "nreverse": | |
| 150 | if case .list(let items) = args[0], let first = items.first { return .list([first]) } | |
| 151 | return isNil(args[0]) ? nil : result | |
| 152 | case "delete-dups": | |
| 153 | return result | |
| 154 | default: | |
| 155 | return nil | |
| 156 | } | |
| 157 | } | |
| 158 | ||
| 159 | /// Keyword arguments `args` after the first `count`, of which only `allowed` are known. | |
| 160 | static func keywords(_ args: [Sexp], after count: Int, allowed: Set<String>, _ name: String) throws -> [String: Sexp] { | |
| 161 | let rest = Array(args.dropFirst(count)) | |
| 162 | guard rest.count % 2 == 0 else { throw Signal(message: "Odd number of keyword arguments for \(name)") } | |
| 163 | var result: [String: Sexp] = [:] | |
| 164 | for i in stride(from: 0, to: rest.count, by: 2) { | |
| 165 | guard let key = rest[i].symbol, allowed.contains(key) else { throw Unsupported(what: "\(name) with \(rest[i].description)") } | |
| 166 | if result[key] == nil { result[key] = rest[i + 1] } | |
| 167 | } | |
| 168 | return result | |
| 169 | } | |
| 170 | ||
| 171 | /// `value<` on numbers, strings and symbols. | |
| 172 | static func valueLess(_ a: Sexp, _ b: Sexp) throws -> Bool { | |
| 173 | if let x = try? number(a), let y = try? number(b) { | |
| 174 | if case .int(let i) = x, case .int(let j) = y { return i < j } | |
| 175 | return x.double < y.double | |
| 176 | } | |
| 177 | switch (a, b) { | |
| 178 | case (.string(let x), .string(let y)): return x.unicodeScalars.map(\.value).lexicographicallyPrecedes(y.unicodeScalars.map(\.value)) | |
| 179 | case (.symbol(let x), .symbol(let y)) where !isNil(a) && !isNil(b): return x.unicodeScalars.map(\.value).lexicographicallyPrecedes(y.unicodeScalars.map(\.value)) | |
| 180 | default: throw Unsupported(what: "value< on \(a.description) and \(b.description)") | |
| 181 | } | |
| 182 | } | |
| 183 | ||
| 184 | /// A stable merge sort with a predicate that may throw. | |
| 185 | static func stableSort(_ items: [Sexp], _ less: (Sexp, Sexp) throws -> Bool) throws -> [Sexp] { | |
| 186 | guard items.count > 1 else { return items } | |
| 187 | let left = try stableSort(Array(items[..<(items.count / 2)]), less) | |
| 188 | let right = try stableSort(Array(items[(items.count / 2)...]), less) | |
| 189 | var merged: [Sexp] = [] | |
| 190 | merged.reserveCapacity(items.count) | |
| 191 | var (i, j) = (0, 0) | |
| 192 | while i < left.count, j < right.count { | |
| 193 | if try less(right[j], left[i]) { | |
| 194 | merged.append(right[j]) | |
| 195 | j += 1 | |
| 196 | } else { | |
| 197 | merged.append(left[i]) | |
| 198 | i += 1 | |
| 199 | } | |
| 200 | } | |
| 201 | return merged + left[i...] + right[j...] | |
| 202 | } | |
| 203 | ||
| 204 | /// `items` as the kind of sequence `like` is. | |
| 205 | static func sameKind(_ items: [Sexp], as like: Sexp) throws -> Sexp { | |
| 206 | switch like { | |
| 207 | case .vector: return .vector(items) | |
| 208 | case .string: return .string(try printedString(.list(items))) | |
| 209 | default: return list(items) | |
| 210 | } | |
| 211 | } | |
| 212 | ||
| 213 | static func sequenceFunctions(_ lisp: Elisp) { | |
| 214 | lisp.define("last") { _, args in | |
| 215 | try arity(args, 1...2, "last") | |
| 216 | let n = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 1 | |
| 217 | switch args[0] { | |
| 218 | case .list(let items): return list(Array(items.suffix(max(0, n)))) | |
| 219 | case .dotted(let items, let tail): return n <= 0 ? tail : .dotted(Array(items.suffix(n)), tail) | |
| 220 | case let v where isNil(v): return .nil | |
| 221 | default: throw Signal(message: "Wrong type argument: listp, \(args[0].description)") | |
| 222 | } | |
| 223 | } | |
| 224 | lisp.define("butlast") { _, args in | |
| 225 | try arity(args, 1...2, "butlast") | |
| 226 | let n = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 1 | |
| 227 | guard n > 0 else { return args[0] } | |
| 228 | return list(Array(try elements(args[0]).dropLast(n))) | |
| 229 | } | |
| 230 | lisp.define("delete-dups") { _, args in | |
| 231 | try arity(args, 1...1, "delete-dups") | |
| 232 | var kept: [Sexp] = [] | |
| 233 | for item in try elements(args[0]) where !kept.contains(where: { normalized($0) == normalized(item) }) { kept.append(item) } | |
| 234 | return list(kept) | |
| 235 | } | |
| 236 | lisp.define("nreverse") { _, args in | |
| 237 | try arity(args, 1...1, "nreverse") | |
| 238 | switch args[0] { | |
| 239 | case .string(let s): return .string(String(String.UnicodeScalarView(s.unicodeScalars.reversed()))) | |
| 240 | case .vector(let items): return .vector(items.reversed()) | |
| 241 | default: return list(try elements(args[0]).reversed()) | |
| 242 | } | |
| 243 | } | |
| 244 | lisp.define("sort") { lisp, args in | |
| 245 | try arity(args, 1...Int.max, "sort") | |
| 246 | var key = Sexp.nil | |
| 247 | var lessp = Sexp.nil | |
| 248 | var reverse = false | |
| 249 | if args.count == 2 { | |
| 250 | guard args[1].symbol?.hasPrefix(":") != true else { throw Signal(message: "Odd number of keyword arguments for sort") } | |
| 251 | lessp = args[1] | |
| 252 | } else { | |
| 253 | let options = try keywords(args, after: 1, allowed: [":key", ":lessp", ":reverse", ":in-place"], "sort") | |
| 254 | key = options[":key"] ?? .nil | |
| 255 | lessp = options[":lessp"] ?? .nil | |
| 256 | reverse = !isNil(options[":reverse"] ?? .nil) | |
| 257 | } | |
| 258 | let items: [Sexp] | |
| 259 | switch args[0] { | |
| 260 | case .vector(let v): items = v | |
| 261 | case .string: throw Unsupported(what: "sort on a string") | |
| 262 | default: items = try elements(args[0]) | |
| 263 | } | |
| 264 | let keyed = try items.map { isNil(key) ? ($0, $0) : ($0, try lisp.call(key, [$0])) } | |
| 265 | func less(_ a: Sexp, _ b: Sexp) throws -> Bool { | |
| 266 | isNil(lessp) ? try valueLess(a, b) : !isNil(try lisp.call(lessp, [a, b])) | |
| 267 | } | |
| 268 | let keys = keyed.map(\.1) | |
| 269 | let order = try stableSort((0..<items.count).map { .integer($0) }) { a, b in | |
| 270 | let (i, j) = (a.integer!, b.integer!) | |
| 271 | return reverse ? try less(keys[j], keys[i]) : try less(keys[i], keys[j]) | |
| 272 | } | |
| 273 | let sorted = order.map { items[$0.integer!] } | |
| 274 | if case .vector = args[0] { return .vector(sorted) } | |
| 275 | return list(sorted) | |
| 276 | } | |
| 277 | lisp.define("seq-reduce") { lisp, args in | |
| 278 | try arity(args, 3...3, "seq-reduce") | |
| 279 | return try sequence(args[1]).reduce(args[2]) { try lisp.call(args[0], [$0, $1]) } | |
| 280 | } | |
| 281 | for name in ["seq-filter", "seq-remove"] { | |
| 282 | lisp.define(name) { lisp, args in | |
| 283 | try arity(args, 2...2, name) | |
| 284 | return list(try sequence(args[1]).filter { isNil(try lisp.call(args[0], [$0])) == (name == "seq-remove") }) | |
| 285 | } | |
| 286 | } | |
| 287 | lisp.define("seq-map") { lisp, args in | |
| 288 | try arity(args, 2...2, "seq-map") | |
| 289 | return list(try sequence(args[1]).map { try lisp.call(args[0], [$0]) }) | |
| 290 | } | |
| 291 | lisp.define("seq-uniq") { _, args in | |
| 292 | try arity(args, 1...2, "seq-uniq") | |
| 293 | guard args.count == 1 || isNil(args[1]) else { throw Unsupported(what: "seq-uniq with a test") } | |
| 294 | var kept: [Sexp] = [] | |
| 295 | for item in try sequence(args[0]) where !kept.contains(where: { normalized($0) == normalized(item) }) { kept.append(item) } | |
| 296 | return list(kept) | |
| 297 | } | |
| 298 | lisp.define("cl-reduce") { lisp, args in | |
| 299 | try arity(args, 2...Int.max, "cl-reduce") | |
| 300 | let options = try keywords(args, after: 2, allowed: [":initial-value"], "cl-reduce") | |
| 301 | var items = try sequence(args[1])[...] | |
| 302 | guard let initial = options[":initial-value"] ?? items.popFirst() else { return try lisp.call(args[0], []) } | |
| 303 | return try items.reduce(initial) { try lisp.call(args[0], [$0, $1]) } | |
| 304 | } | |
| 305 | for name in ["cl-remove-if", "cl-remove-if-not"] { | |
| 306 | lisp.define(name) { lisp, args in | |
| 307 | try arity(args, 2...Int.max, name) | |
| 308 | _ = try keywords(args, after: 2, allowed: [], name) | |
| 309 | return try sameKind(try sequence(args[1]).filter { isNil(try lisp.call(args[0], [$0])) == (name == "cl-remove-if") }, as: args[1]) | |
| 310 | } | |
| 311 | } | |
| 312 | for name in ["cl-find", "cl-position"] { | |
| 313 | lisp.define(name) { lisp, args in | |
| 314 | try arity(args, 2...Int.max, name) | |
| 315 | let test = try keywords(args, after: 2, allowed: [":test"], name)[":test"] ?? .nil | |
| 316 | for (i, item) in try sequence(args[1]).enumerated() { | |
| 317 | let found = isNil(test) ? eq(args[0], item) : !isNil(try lisp.call(test, [args[0], item])) | |
| 318 | if found { return name == "cl-find" ? item : .integer(i) } | |
| 319 | } | |
| 320 | return .nil | |
| 321 | } | |
| 322 | } | |
| 323 | } | |
| 324 | } | |
Sources/OrgCore/Config/ElispRegex.swift added +523
| @@ -0,0 +1,523 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// An Emacs regexp as an `NSRegularExpression`, with the syntax table of an Org buffer, where | |
| 4 | /// table formulas and Emacs Lisp blocks run. A construct it can't translate exactly throws | |
| 5 | /// `Elisp.Unsupported`, and so do subjects where ICU's tables could differ from Emacs's: | |
| 6 | /// syntax classes against text past ASCII, and case folding with letters past ASCII. | |
| 7 | struct ElispRegex { | |
| 8 | let pattern: String | |
| 9 | let groups: Int | |
| 10 | /// Has letters, ranges over letters or case classes: case folding changes what matches. | |
| 11 | let foldable: Bool | |
| 12 | /// Has classes whose members past ASCII come from Emacs's syntax or Unicode tables. | |
| 13 | let asciiClasses: Bool | |
| 14 | /// Has letters with case past ASCII. | |
| 15 | let nonASCIILetters: Bool | |
| 16 | let plain: NSRegularExpression | |
| 17 | let folded: NSRegularExpression | |
| 18 | ||
| 19 | /// `char-syntax` of each ASCII character in `org-mode-syntax-table`. | |
| 20 | static let syntax = Array("......... . .................. .\".ww_w()__._._wwwwwwwwww..(_)..wwwwwwwwwwwwwwwwwwwwwwwwww(_)._.wwwwwwwwwwwwwwwwwwwwwwwwww(_)_.") | |
| 21 | ||
| 22 | static func codes(_ syntaxClass: Character) -> [UInt32] { | |
| 23 | syntax.indices.filter { syntax[$0] == syntaxClass }.map(UInt32.init) | |
| 24 | } | |
| 25 | ||
| 26 | static func hex(_ c: UInt32) -> String { "\\x{" + String(c, radix: 16) + "}" } | |
| 27 | ||
| 28 | static func set(_ codes: [UInt32], negated: Bool = false) -> String { | |
| 29 | "[" + (negated ? "^" : "") + codes.map(hex).joined() + "]" | |
| 30 | } | |
| 31 | ||
| 32 | static let word = codes("w") | |
| 33 | static let symbol = word + codes("_") | |
| 34 | ||
| 35 | /// A letter with case, which case folding changes. | |
| 36 | static func isLetter(_ c: UInt32) -> Bool { | |
| 37 | (65...90).contains(c) || (97...122).contains(c) || c > 127 && Unicode.Scalar(c).map { $0.properties.changesWhenCaseMapped || $0.properties.changesWhenCaseFolded } ?? false | |
| 38 | } | |
| 39 | ||
| 40 | init(_ pattern: String) throws { | |
| 41 | self.pattern = pattern | |
| 42 | let p = Array(pattern.unicodeScalars) | |
| 43 | var out = "" | |
| 44 | var groups = 0 | |
| 45 | var open: [Int] = [] | |
| 46 | var closed: Set<Int> = [] | |
| 47 | var foldable = false | |
| 48 | var asciiClasses = false | |
| 49 | // Where `^` is an anchor, and where `*`, `+` and `?` are ordinary characters: at the | |
| 50 | // start, after `\(` or `\|`, and for the second also after that `^`. | |
| 51 | var anchor = true | |
| 52 | var ordinary = true | |
| 53 | var quantifiable = false | |
| 54 | // After a repetition, and whether a `?` may make it non-greedy. | |
| 55 | var quantified = false | |
| 56 | var lazy = false | |
| 57 | var i = 0 | |
| 58 | func unsupported(_ what: String) -> Elisp.Unsupported { Elisp.Unsupported(what: "regexp \(what) in \(Elisp.printed(.string(pattern), escape: true))") } | |
| 59 | func literal(_ c: Unicode.Scalar) { | |
| 60 | if c.isASCII, c.properties.isAlphabetic || ("0"..."9").contains(c) { out.unicodeScalars.append(c) } else { out += Self.hex(c.value) } | |
| 61 | if Self.isLetter(c.value) { foldable = true } | |
| 62 | (anchor, ordinary, quantifiable, quantified) = (false, false, true, false) | |
| 63 | } | |
| 64 | func atom(_ text: String) { | |
| 65 | out += text | |
| 66 | (anchor, ordinary, quantifiable, quantified) = (false, false, true, false) | |
| 67 | } | |
| 68 | func assertion(_ text: String) { | |
| 69 | out += text | |
| 70 | (anchor, ordinary, quantifiable, quantified) = (false, false, false, false) | |
| 71 | } | |
| 72 | while i < p.count { | |
| 73 | let c = p[i] | |
| 74 | i += 1 | |
| 75 | switch c { | |
| 76 | case "^": | |
| 77 | if anchor { | |
| 78 | out += "(?:(?<![\\s\\S])|(?<=\\n))" | |
| 79 | anchor = false | |
| 80 | } else { | |
| 81 | literal(c) | |
| 82 | } | |
| 83 | case "$": | |
| 84 | let rest = p[i...] | |
| 85 | if rest.isEmpty || rest.starts(with: ["\\", ")"]) || rest.starts(with: ["\\", "|"]) { | |
| 86 | assertion("(?=\\n|(?![\\s\\S]))") | |
| 87 | } else { | |
| 88 | literal(c) | |
| 89 | } | |
| 90 | case ".": | |
| 91 | atom("[^\\n]") | |
| 92 | case "*", "+", "?": | |
| 93 | if quantified { | |
| 94 | guard c == "?", lazy else { throw unsupported("\(c) after a repetition") } | |
| 95 | out += "?" | |
| 96 | lazy = false | |
| 97 | } else if quantifiable { | |
| 98 | out.unicodeScalars.append(c) | |
| 99 | (quantifiable, quantified, lazy) = (false, true, true) | |
| 100 | } else if ordinary { | |
| 101 | literal(c) | |
| 102 | } else { | |
| 103 | throw unsupported(String(c)) | |
| 104 | } | |
| 105 | case "[": | |
| 106 | var j = i | |
| 107 | var text = "[" | |
| 108 | if j < p.count, p[j] == "^" { | |
| 109 | text += "^" | |
| 110 | j += 1 | |
| 111 | } | |
| 112 | var first = true | |
| 113 | while true { | |
| 114 | guard j < p.count else { throw unsupported("[") } | |
| 115 | let c = p[j] | |
| 116 | if c == "]", !first { | |
| 117 | j += 1 | |
| 118 | break | |
| 119 | } | |
| 120 | first = false | |
| 121 | if c == "[", j + 1 < p.count, p[j + 1] == ":" { | |
| 122 | var k = j + 2 | |
| 123 | var name = "" | |
| 124 | while k + 1 < p.count, !(p[k] == ":" && p[k + 1] == "]") { | |
| 125 | name.unicodeScalars.append(p[k]) | |
| 126 | k += 1 | |
| 127 | } | |
| 128 | guard k + 1 < p.count else { throw unsupported("[:") } | |
| 129 | j = k + 2 | |
| 130 | let ascii: (String, Bool, Bool) = switch name { | |
| 131 | case "alpha": ("A-Za-z", true, false) | |
| 132 | case "alnum": ("0-9A-Za-z", true, false) | |
| 133 | case "upper": ("A-Z", true, true) | |
| 134 | case "lower": ("a-z", true, true) | |
| 135 | case "digit": ("0-9", false, false) | |
| 136 | case "xdigit": ("0-9A-Fa-f", false, false) | |
| 137 | case "cntrl": ("\\x{0}-\\x{1f}", false, false) | |
| 138 | case "ascii": ("\\x{0}-\\x{7f}", false, false) | |
| 139 | case "nonascii": ("\\x{80}-\\x{10ffff}", false, false) | |
| 140 | case "space": (Self.codes(" ").map(Self.hex).joined(), true, false) | |
| 141 | case "blank": ("\\x{9}\\x{20}", true, false) | |
| 142 | case "punct": ((33...126).filter { !Self.isLetter($0) && !(48...57).contains($0) }.map(Self.hex).joined(), true, false) | |
| 143 | case "graph": ("\\x{21}-\\x{7e}", true, false) | |
| 144 | case "print": ("\\x{20}-\\x{7e}", true, false) | |
| 145 | case "word": (Self.word.map(Self.hex).joined(), true, false) | |
| 146 | default: throw unsupported("[:\(name):]") | |
| 147 | } | |
| 148 | text += ascii.0 | |
| 149 | if ascii.1 { asciiClasses = true } | |
| 150 | if ascii.2 { foldable = true } | |
| 151 | continue | |
| 152 | } | |
| 153 | if j + 2 < p.count, p[j + 1] == "-", p[j + 2] != "]" { | |
| 154 | let end = p[j + 2] | |
| 155 | guard c.value <= end.value else { throw unsupported("range") } | |
| 156 | text += Self.hex(c.value) + "-" + Self.hex(end.value) | |
| 157 | if end.value >= 65, c.value <= 122 || end.value > 127 { foldable = true } | |
| 158 | j += 3 | |
| 159 | continue | |
| 160 | } | |
| 161 | text += Self.hex(c.value) | |
| 162 | if Self.isLetter(c.value) { foldable = true } | |
| 163 | j += 1 | |
| 164 | } | |
| 165 | i = j | |
| 166 | atom(text + "]") | |
| 167 | case "\\": | |
| 168 | guard i < p.count else { throw unsupported("\\ at the end") } | |
| 169 | let e = p[i] | |
| 170 | i += 1 | |
| 171 | switch e { | |
| 172 | case "(": | |
| 173 | if i < p.count, p[i] == "?" { | |
| 174 | guard i + 1 < p.count, p[i + 1] == ":" else { throw unsupported("\\(?") } | |
| 175 | i += 2 | |
| 176 | out += "(?:" | |
| 177 | open.append(0) | |
| 178 | } else { | |
| 179 | groups += 1 | |
| 180 | out += "(" | |
| 181 | open.append(groups) | |
| 182 | } | |
| 183 | (anchor, ordinary, quantifiable, quantified) = (true, true, false, false) | |
| 184 | case ")": | |
| 185 | guard let n = open.popLast() else { throw unsupported("\\)") } | |
| 186 | closed.insert(n) | |
| 187 | atom(")") | |
| 188 | case "|": | |
| 189 | out += "|" | |
| 190 | (anchor, ordinary, quantifiable, quantified) = (true, true, false, false) | |
| 191 | case "{": | |
| 192 | guard quantifiable else { throw unsupported("\\{") } | |
| 193 | var low = "" | |
| 194 | var high: String? | |
| 195 | while i < p.count, ("0"..."9").contains(p[i]) { | |
| 196 | low.unicodeScalars.append(p[i]) | |
| 197 | i += 1 | |
| 198 | } | |
| 199 | if i < p.count, p[i] == "," { | |
| 200 | i += 1 | |
| 201 | var digits = "" | |
| 202 | while i < p.count, ("0"..."9").contains(p[i]) { | |
| 203 | digits.unicodeScalars.append(p[i]) | |
| 204 | i += 1 | |
| 205 | } | |
| 206 | high = digits | |
| 207 | } | |
| 208 | guard i + 1 < p.count, p[i] == "\\", p[i + 1] == "}", !low.isEmpty || high != nil else { throw unsupported("\\{") } | |
| 209 | i += 2 | |
| 210 | out += "{" + (low.isEmpty ? "0" : low) + (high.map { "," + $0 } ?? "") + "}" | |
| 211 | (quantifiable, quantified, lazy) = (false, true, false) | |
| 212 | case "1"..."9": | |
| 213 | let n = Int(e.value) - 48 | |
| 214 | guard closed.contains(n) else { throw unsupported("\\\(n)") } | |
| 215 | atom("(?:\\\(n))") | |
| 216 | case "w", "W": | |
| 217 | asciiClasses = true | |
| 218 | atom(Self.set(Self.word, negated: e == "W")) | |
| 219 | case "s", "S": | |
| 220 | guard i < p.count else { throw unsupported("\\s") } | |
| 221 | let code: Character = switch p[i] { | |
| 222 | case "-", " ": " " | |
| 223 | case "w", "_", ".", "(", ")", "\"": Character(p[i]) | |
| 224 | default: throw unsupported("\\s\(p[i])") | |
| 225 | } | |
| 226 | i += 1 | |
| 227 | asciiClasses = true | |
| 228 | atom(Self.set(Self.codes(code), negated: e == "S")) | |
| 229 | case "b", "B", "<", ">": | |
| 230 | asciiClasses = true | |
| 231 | let w = Self.set(Self.word) | |
| 232 | let text = switch e { | |
| 233 | case "b": "(?:(?<=\(w))(?!\(w))|(?<!\(w))(?=\(w)))" | |
| 234 | case "B": "(?:(?<=\(w))(?=\(w))|(?<!\(w))(?!\(w)))" | |
| 235 | case "<": "(?<!\(w))(?=\(w))" | |
| 236 | default: "(?<=\(w))(?!\(w))" | |
| 237 | } | |
| 238 | assertion(text) | |
| 239 | case "_": | |
| 240 | guard i < p.count, p[i] == "<" || p[i] == ">" else { throw unsupported("\\_") } | |
| 241 | asciiClasses = true | |
| 242 | let s = Self.set(Self.symbol) | |
| 243 | assertion(p[i] == "<" ? "(?<!\(s))(?=\(s))" : "(?<=\(s))(?!\(s))") | |
| 244 | i += 1 | |
| 245 | case "`": | |
| 246 | assertion("(?<![\\s\\S])") | |
| 247 | case "'": | |
| 248 | assertion("(?![\\s\\S])") | |
| 249 | default: | |
| 250 | guard !e.isASCII || !(e.properties.isAlphabetic || ("0"..."9").contains(e) || e == "}") else { throw unsupported("\\\(e)") } | |
| 251 | literal(e) | |
| 252 | } | |
| 253 | default: | |
| 254 | literal(c) | |
| 255 | } | |
| 256 | } | |
| 257 | guard open.isEmpty else { throw unsupported("\\(") } | |
| 258 | self.groups = groups | |
| 259 | self.foldable = foldable | |
| 260 | self.asciiClasses = asciiClasses | |
| 261 | nonASCIILetters = p.contains { !$0.isASCII && Self.isLetter($0.value) } | |
| 262 | do { | |
| 263 | plain = try NSRegularExpression(pattern: out.isEmpty ? "(?:)" : out) | |
| 264 | folded = try NSRegularExpression(pattern: out.isEmpty ? "(?:)" : out, options: .caseInsensitive) | |
| 265 | } catch { | |
| 266 | throw unsupported("syntax") | |
| 267 | } | |
| 268 | } | |
| 269 | ||
| 270 | /// The first match at or after character `start`: each group's range in characters, nil | |
| 271 | /// for groups that didn't match. | |
| 272 | func firstMatch(in s: String, from start: Int, caseFold: Bool) throws -> [Range<Int>?]? { | |
| 273 | let subjectNonASCII = s.unicodeScalars.contains { !$0.isASCII } | |
| 274 | if asciiClasses, subjectNonASCII { throw Elisp.Unsupported(what: "regexp classes on text past ASCII") } | |
| 275 | // Folding agrees for ASCII letters, unless the text has a character whose case maps | |
| 276 | // to ASCII, like the Kelvin sign or ß. | |
| 277 | if caseFold, foldable, nonASCIILetters || subjectNonASCII && s.unicodeScalars.contains(where: { c in | |
| 278 | !c.isASCII && (String(c).lowercased() + String(c).uppercased()).unicodeScalars.contains(where: \.isASCII) | |
| 279 | }) { | |
| 280 | throw Elisp.Unsupported(what: "case folding past ASCII") | |
| 281 | } | |
| 282 | // UTF-16 offset of each character, and the end. | |
| 283 | var offsets = [0] | |
| 284 | if subjectNonASCII { | |
| 285 | for scalar in s.unicodeScalars { offsets.append(offsets.last! + scalar.utf16.count) } | |
| 286 | } | |
| 287 | func utf16(_ i: Int) -> Int { subjectNonASCII ? offsets[i] : i } | |
| 288 | func character(_ u: Int) -> Int { | |
| 289 | guard subjectNonASCII else { return u } | |
| 290 | var low = 0 | |
| 291 | var high = offsets.count - 1 | |
| 292 | while low < high { | |
| 293 | let mid = (low + high) / 2 | |
| 294 | if offsets[mid] < u { low = mid + 1 } else { high = mid } | |
| 295 | } | |
| 296 | return low | |
| 297 | } | |
| 298 | let length = (s as NSString).length | |
| 299 | let from = utf16(start) | |
| 300 | guard let m = (caseFold ? folded : plain).firstMatch(in: s, options: [.withTransparentBounds, .withoutAnchoringBounds], | |
| 301 | range: NSRange(location: from, length: length - from)) else { return nil } | |
| 302 | return (0...groups).map { g in | |
| 303 | let r = m.range(at: g) | |
| 304 | return r.location == NSNotFound ? nil : character(r.location)..<character(NSMaxRange(r)) | |
| 305 | } | |
| 306 | } | |
| 307 | } | |
| 308 | ||
| 309 | extension Elisp { | |
| 310 | /// `case-fold-search`. | |
| 311 | var caseFold: Bool { (try? value("case-fold-search")).map { !Self.isNil($0) } ?? true } | |
| 312 | ||
| 313 | func regex(_ pattern: String) throws -> ElispRegex { | |
| 314 | if let cached = regexes[pattern] { return cached } | |
| 315 | let compiled = try ElispRegex(pattern) | |
| 316 | regexes[pattern] = compiled | |
| 317 | return compiled | |
| 318 | } | |
| 319 | ||
| 320 | /// `string-match`: the match data, or nil. | |
| 321 | func stringMatch(_ pattern: String, _ s: String, start: Sexp = .nil) throws -> [Range<Int>?]? { | |
| 322 | let count = s.unicodeScalars.count | |
| 323 | var from = Self.isNil(start) ? 0 : try Self.int(start) | |
| 324 | if from < 0 { from += count } | |
| 325 | guard (0...count).contains(from) else { throw Signal(message: "Args out of range: \(Self.printed(.string(s), escape: true)), \(Self.printed(start))") } | |
| 326 | return try regex(pattern).firstMatch(in: s, from: from, caseFold: caseFold) | |
| 327 | } | |
| 328 | ||
| 329 | static func substring(_ s: String, _ range: Range<Int>) throws -> String { | |
| 330 | let scalars = Array(s.unicodeScalars) | |
| 331 | guard range.upperBound <= scalars.count else { throw Signal(message: "Args out of range") } | |
| 332 | return String(String.UnicodeScalarView(scalars[range])) | |
| 333 | } | |
| 334 | ||
| 335 | /// `replace-match` on a string, with the match data in characters of `s`. | |
| 336 | func replaceMatch(_ newText: String, fixedCase: Bool, literal: Bool, in s: String, subexp: Int) throws -> String { | |
| 337 | guard subexp < matchData.count, let target = matchData[subexp] else { | |
| 338 | throw Signal(message: "replace-match subexpression does not exist") | |
| 339 | } | |
| 340 | var text = "" | |
| 341 | if literal { | |
| 342 | text = newText | |
| 343 | } else { | |
| 344 | var chars = newText.unicodeScalars.makeIterator() | |
| 345 | while let c = chars.next() { | |
| 346 | guard c == "\\" else { | |
| 347 | text.unicodeScalars.append(c) | |
| 348 | continue | |
| 349 | } | |
| 350 | switch chars.next() { | |
| 351 | case "&": text += try Self.substring(s, matchData[0]!) | |
| 352 | case "\\": text += "\\" | |
| 353 | case let d? where ("1"..."9").contains(d): | |
| 354 | let n = Int(d.value) - 48 | |
| 355 | if n < matchData.count, let r = matchData[n] { text += try Self.substring(s, r) } | |
| 356 | default: throw Signal(message: "Invalid use of ‘\\’ in replacement text") | |
| 357 | } | |
| 358 | } | |
| 359 | } | |
| 360 | let old = try Self.substring(s, target) | |
| 361 | if !fixedCase, !old.unicodeScalars.allSatisfy(\.isASCII) { | |
| 362 | // Past ASCII, only the cases that keep the replacement's case: no letter with a | |
| 363 | // case, or a lowercase letter first. | |
| 364 | let first = old.unicodeScalars.first.map { $0.properties.isLowercase && $0.properties.changesWhenUppercased } ?? false | |
| 365 | guard first || !old.unicodeScalars.contains(where: \.properties.changesWhenCaseMapped) else { | |
| 366 | throw Unsupported(what: "replace-match case past ASCII") | |
| 367 | } | |
| 368 | } else if !fixedCase { | |
| 369 | // How `replace-match` decides to change the replacement's case from the replaced text. | |
| 370 | func isWord(_ c: Unicode.Scalar) -> Bool { c.isASCII && ElispRegex.syntax[Int(c.value)] == "w" } | |
| 371 | var (multiletter, lower, nonUpperInitial, upper) = (false, false, false, false) | |
| 372 | var previous: Unicode.Scalar = "\n" | |
| 373 | for c in old.unicodeScalars { | |
| 374 | if ("a"..."z").contains(c) { | |
| 375 | lower = true | |
| 376 | if isWord(previous) { multiletter = true } else { nonUpperInitial = true } | |
| 377 | } else if ("A"..."Z").contains(c) { | |
| 378 | upper = true | |
| 379 | if isWord(previous) { multiletter = true } | |
| 380 | } else if !isWord(previous), isWord(c) { | |
| 381 | nonUpperInitial = true | |
| 382 | } | |
| 383 | previous = c | |
| 384 | } | |
| 385 | let allCaps = (!lower && multiletter) || (!nonUpperInitial && !multiletter && upper) | |
| 386 | let initials = !allCaps && !nonUpperInitial && multiletter | |
| 387 | if allCaps || initials { | |
| 388 | guard text.unicodeScalars.allSatisfy(\.isASCII) else { throw Unsupported(what: "replace-match case past ASCII") } | |
| 389 | if allCaps { | |
| 390 | text = text.uppercased() | |
| 391 | } else { | |
| 392 | var result = "" | |
| 393 | var previous: Unicode.Scalar = "\n" | |
| 394 | for c in text.unicodeScalars { | |
| 395 | result += !isWord(previous) ? String(c).uppercased() : String(c) | |
| 396 | previous = c | |
| 397 | } | |
| 398 | text = result | |
| 399 | } | |
| 400 | } | |
| 401 | } | |
| 402 | let scalars = Array(s.unicodeScalars) | |
| 403 | return String(String.UnicodeScalarView(scalars[..<target.lowerBound])) + text + String(String.UnicodeScalarView(scalars[target.upperBound...])) | |
| 404 | } | |
| 405 | ||
| 406 | static func regexFunctions(_ lisp: Elisp) { | |
| 407 | lisp.set("case-fold-search", t) | |
| 408 | for name in ["string-match", "string-match-p"] { | |
| 409 | lisp.define(name) { lisp, args in | |
| 410 | try arity(args, 2...4, name) | |
| 411 | guard let data = try lisp.stringMatch(try string(args[0]), try string(args[1]), start: args.count > 2 ? args[2] : .nil) else { return .nil } | |
| 412 | if name == "string-match" { lisp.matchData = data } | |
| 413 | return .integer(data[0]!.lowerBound) | |
| 414 | } | |
| 415 | } | |
| 416 | for name in ["match-beginning", "match-end"] { | |
| 417 | lisp.define(name) { lisp, args in | |
| 418 | try arity(args, 1...1, name) | |
| 419 | let n = try int(args[0]) | |
| 420 | guard n >= 0 else { throw Signal(message: "Args out of range: \(n)") } | |
| 421 | guard n < lisp.matchData.count, let r = lisp.matchData[n] else { return .nil } | |
| 422 | return .integer(name == "match-beginning" ? r.lowerBound : r.upperBound) | |
| 423 | } | |
| 424 | } | |
| 425 | for name in ["match-string", "match-string-no-properties"] { | |
| 426 | lisp.define(name) { lisp, args in | |
| 427 | try arity(args, 1...2, name) | |
| 428 | guard args.count == 2, !isNil(args[1]) else { throw Unsupported(what: "\(name) in a buffer") } | |
| 429 | let n = try int(args[0]) | |
| 430 | guard n >= 0, n < lisp.matchData.count, let r = lisp.matchData[n] else { return .nil } | |
| 431 | return .string(try substring(try string(args[1]), r)) | |
| 432 | } | |
| 433 | } | |
| 434 | lisp.define("replace-match") { lisp, args in | |
| 435 | try arity(args, 1...5, "replace-match") | |
| 436 | guard args.count > 3, !isNil(args[3]) else { throw Unsupported(what: "replace-match in a buffer") } | |
| 437 | return .string(try lisp.replaceMatch(try string(args[0]), fixedCase: args.count > 1 && !isNil(args[1]), literal: args.count > 2 && !isNil(args[2]), | |
| 438 | in: try string(args[3]), subexp: args.count > 4 && !isNil(args[4]) ? try int(args[4]) : 0)) | |
| 439 | } | |
| 440 | lisp.define("replace-regexp-in-string") { lisp, args in | |
| 441 | try arity(args, 3...7, "replace-regexp-in-string") | |
| 442 | func optional(_ i: Int) -> Sexp { i < args.count ? args[i] : .nil } | |
| 443 | let regexp = try string(args[0]) | |
| 444 | let s = try string(args[2]) | |
| 445 | let scalars = Array(s.unicodeScalars) | |
| 446 | func piece(_ r: Range<Int>) -> String { String(String.UnicodeScalarView(scalars[r])) } | |
| 447 | let l = scalars.count | |
| 448 | var start = isNil(optional(6)) ? 0 : try int(optional(6)) | |
| 449 | guard start >= 0 else { throw Unsupported(what: "replace-regexp-in-string from the end") } | |
| 450 | var matches = "" | |
| 451 | let saved = lisp.matchData | |
| 452 | defer { lisp.matchData = saved } | |
| 453 | while start < l, let data = try lisp.stringMatch(regexp, s, start: .integer(start)) { | |
| 454 | lisp.matchData = data | |
| 455 | let mb = data[0]!.lowerBound | |
| 456 | var me = data[0]!.upperBound | |
| 457 | if me == mb { me = min(l, mb + 1) } | |
| 458 | lisp.matchData = data.map { $0.map { ($0.lowerBound - mb)..<($0.upperBound - mb) } } | |
| 459 | let str = piece(mb..<me) | |
| 460 | let rep: String | |
| 461 | if case .string(let text) = args[1] { | |
| 462 | rep = text | |
| 463 | } else { | |
| 464 | rep = try string(try lisp.call(args[1], [.string(try substring(str, lisp.matchData[0]!))])) | |
| 465 | } | |
| 466 | matches += piece(start..<mb) | |
| 467 | matches += try lisp.replaceMatch(rep, fixedCase: !isNil(optional(3)), literal: !isNil(optional(4)), in: str, | |
| 468 | subexp: isNil(optional(5)) ? 0 : try int(optional(5))) | |
| 469 | start = me | |
| 470 | } | |
| 471 | guard start <= l else { throw Signal(message: "Args out of range") } | |
| 472 | return .string(matches + piece(start..<l)) | |
| 473 | } | |
| 474 | lisp.define("regexp-quote") { _, args in | |
| 475 | try arity(args, 1...1, "regexp-quote") | |
| 476 | var out = "" | |
| 477 | for c in try string(args[0]).unicodeScalars { | |
| 478 | if "[*.\\?+^$".unicodeScalars.contains(c) { out += "\\" } | |
| 479 | out.unicodeScalars.append(c) | |
| 480 | } | |
| 481 | return .string(out) | |
| 482 | } | |
| 483 | lisp.define("split-string") { lisp, args in | |
| 484 | try arity(args, 1...4, "split-string") | |
| 485 | func optional(_ i: Int) -> Sexp { i < args.count ? args[i] : .nil } | |
| 486 | let s = try string(args[0]) | |
| 487 | let length = s.unicodeScalars.count | |
| 488 | let keepNulls = isNil(optional(1)) ? false : isNil(optional(2)) | |
| 489 | let separators = isNil(optional(1)) ? "[ \u{0C}\t\n\r\u{0B}]+" : try string(optional(1)) | |
| 490 | let trim = isNil(optional(3)) ? nil : try string(optional(3)) | |
| 491 | var list: [Sexp] = [] | |
| 492 | func push(_ from: Int, _ to: Int) throws { | |
| 493 | var from = from | |
| 494 | if let trim, let data = try lisp.stringMatch(trim, s, start: .integer(from)) { | |
| 495 | lisp.matchData = data | |
| 496 | if data[0]!.lowerBound == from { from = data[0]!.upperBound } | |
| 497 | } | |
| 498 | guard keepNulls || from < to else { return } | |
| 499 | guard from <= to else { throw Signal(message: "Args out of range") } | |
| 500 | var this = try substring(s, from..<to) | |
| 501 | if let trim, let data = try lisp.stringMatch(trim + "\\'", this) { | |
| 502 | lisp.matchData = data | |
| 503 | if data[0]!.lowerBound < this.unicodeScalars.count { this = try substring(this, 0..<data[0]!.lowerBound) } | |
| 504 | } | |
| 505 | if keepNulls || !this.isEmpty { list.append(.string(this)) } | |
| 506 | } | |
| 507 | var start = 0 | |
| 508 | var notFirst = false | |
| 509 | while true { | |
| 510 | let from = notFirst && start == lisp.matchData.first??.lowerBound && start < length ? start + 1 : start | |
| 511 | guard let data = try lisp.stringMatch(separators, s, start: .integer(from)) else { break } | |
| 512 | lisp.matchData = data | |
| 513 | guard start < length else { break } | |
| 514 | notFirst = true | |
| 515 | let thisStart = start | |
| 516 | start = data[0]!.upperBound | |
| 517 | try push(thisStart, data[0]!.lowerBound) | |
| 518 | } | |
| 519 | try push(start, length) | |
| 520 | return Elisp.list(list) | |
| 521 | } | |
| 522 | } | |
| 523 | } | |
Sources/OrgCore/Config/ElispTime.swift added +228
| @@ -0,0 +1,228 @@ | ||
| 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 | /// `encode-time` of a local date and time. | |
| 79 | static func encode(_ parts: [Int], calendar: Calendar) throws -> Time { | |
| 80 | guard let date = calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: parts[3], minute: parts[4], second: parts.count > 5 ? parts[5] : 0)) else { | |
| 81 | throw Unsupported(what: "date \(parts)") | |
| 82 | } | |
| 83 | return Time(seconds: Int(date.timeIntervalSince1970.rounded(.down))) | |
| 84 | } | |
| 85 | ||
| 86 | /// `date-to-time` for ISO 8601 dates, with or without a time. | |
| 87 | static func dateToTime(_ s: String, calendar: Calendar) throws -> Time { | |
| 88 | 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 { | |
| 89 | throw Unsupported(what: "date-to-time of \(s)") | |
| 90 | } | |
| 91 | 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] | |
| 92 | 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)") } | |
| 93 | return try encode(parts, calendar: calendar) | |
| 94 | } | |
| 95 | ||
| 96 | static func days(_ seconds: Int, calendar: Calendar) -> Int { | |
| 97 | Days.absolute(Date(timeIntervalSince1970: Double(seconds)), calendar: calendar) | |
| 98 | } | |
| 99 | ||
| 100 | /// `format-time-string` with the conversions that don't depend on the locale, without | |
| 101 | /// flags or widths. | |
| 102 | static func formatTime(_ format: String, _ seconds: Int, calendar: Calendar) throws -> String { | |
| 103 | let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second], from: Date(timeIntervalSince1970: Double(seconds))) | |
| 104 | let (year, month, day, hour, minute, second) = (c.year!, c.month!, c.day!, c.hour!, c.minute!, c.second!) | |
| 105 | let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] | |
| 106 | let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] | |
| 107 | let weekday = c.weekday! - 1 | |
| 108 | let hour12 = hour % 12 == 0 ? 12 : hour % 12 | |
| 109 | var out = "" | |
| 110 | var chars = format.makeIterator() | |
| 111 | while let ch = chars.next() { | |
| 112 | guard ch == "%" else { | |
| 113 | out.append(ch) | |
| 114 | continue | |
| 115 | } | |
| 116 | guard let f = chars.next() else { throw Unsupported(what: "format-time-string %") } | |
| 117 | switch f { | |
| 118 | case "Y": out += String(year) | |
| 119 | case "y": out += String(format: "%02d", year % 100) | |
| 120 | case "m": out += String(format: "%02d", month) | |
| 121 | case "d": out += String(format: "%02d", day) | |
| 122 | case "e": out += String(format: "%2d", day) | |
| 123 | case "H": out += String(format: "%02d", hour) | |
| 124 | case "k": out += String(format: "%2d", hour) | |
| 125 | case "I": out += String(format: "%02d", hour12) | |
| 126 | case "l": out += String(format: "%2d", hour12) | |
| 127 | case "M": out += String(format: "%02d", minute) | |
| 128 | case "S": out += String(format: "%02d", second) | |
| 129 | case "p": out += hour < 12 ? "AM" : "PM" | |
| 130 | case "a": out += String(days[weekday].prefix(3)) | |
| 131 | case "A": out += days[weekday] | |
| 132 | case "b", "h": out += String(months[month - 1].prefix(3)) | |
| 133 | case "B": out += months[month - 1] | |
| 134 | case "u": out += String(weekday == 0 ? 7 : weekday) | |
| 135 | case "w": out += String(weekday) | |
| 136 | case "j": out += String(format: "%03d", Days.absolute(year: year, month: month, day: day) - Days.absolute(year: year, month: 1, day: 0)) | |
| 137 | case "F": out += String(format: "%d-%02d-%02d", year, month, day) | |
| 138 | case "D": out += String(format: "%02d/%02d/%02d", month, day, year % 100) | |
| 139 | case "R": out += String(format: "%02d:%02d", hour, minute) | |
| 140 | case "T": out += String(format: "%02d:%02d:%02d", hour, minute, second) | |
| 141 | case "s": out += String(seconds) | |
| 142 | case "z": | |
| 143 | let offset = calendar.timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: Double(seconds))) / 60 | |
| 144 | out += String(format: "%@%02d%02d", offset < 0 ? "-" : "+", abs(offset) / 60, abs(offset) % 60) | |
| 145 | case "n": out += "\n" | |
| 146 | case "t": out += "\t" | |
| 147 | case "%": out += "%" | |
| 148 | default: throw Unsupported(what: "format-time-string %\(f)") | |
| 149 | } | |
| 150 | } | |
| 151 | return out | |
| 152 | } | |
| 153 | ||
| 154 | /// Defines the time functions and the calendar functions diary sexps use, with times in | |
| 155 | /// `calendar`'s time zone and `now` as the clock. | |
| 156 | public func standardTime(now: @escaping () -> Date = Date.init, calendar: Calendar = .current) { | |
| 157 | var calendar = calendar | |
| 158 | if calendar.identifier != .gregorian { | |
| 159 | var gregorian = Calendar(identifier: .gregorian) | |
| 160 | gregorian.timeZone = calendar.timeZone | |
| 161 | calendar = gregorian | |
| 162 | } | |
| 163 | let local = calendar | |
| 164 | DiarySexp.defineCalendar(self) | |
| 165 | define("current-time") { _, args in | |
| 166 | try Elisp.arity(args, 0...0, "current-time") | |
| 167 | return Time(now()).sexp | |
| 168 | } | |
| 169 | define("format-time-string") { _, args in | |
| 170 | try Elisp.arity(args, 1...3, "format-time-string") | |
| 171 | var zoned = local | |
| 172 | if args.count > 2, !Elisp.isNil(args[2]) { | |
| 173 | guard args[2] == Elisp.t || args[2] == .string("UTC") || args[2] == .integer(0) else { throw Unsupported(what: "format-time-string zone \(args[2].description)") } | |
| 174 | zoned.timeZone = TimeZone(identifier: "UTC")! | |
| 175 | } | |
| 176 | return .string(try Elisp.formatTime(try Elisp.string(args[0]), try Elisp.wholeSeconds(args.count > 1 ? args[1] : .nil, now: now()), calendar: zoned)) | |
| 177 | } | |
| 178 | define("org-time-string-to-time") { _, args in | |
| 179 | try Elisp.arity(args, 1...1, "org-time-string-to-time") | |
| 180 | return try Elisp.encode(try Elisp.orgTime(try Elisp.string(args[0])), calendar: local).pair | |
| 181 | } | |
| 182 | define("org-time-string-to-absolute") { _, args in | |
| 183 | try Elisp.arity(args, 1...5, "org-time-string-to-absolute") | |
| 184 | guard args.count == 1 else { throw Unsupported(what: "org-time-string-to-absolute with a day") } | |
| 185 | let parts = try Elisp.orgTime(try Elisp.string(args[0])) | |
| 186 | return .integer(Days.absolute(year: parts[0], month: parts[1], day: parts[2])) | |
| 187 | } | |
| 188 | for name in ["time-add", "time-subtract"] { | |
| 189 | define(name) { _, args in | |
| 190 | try Elisp.arity(args, 2...2, name) | |
| 191 | let a = try Elisp.time(args[0], now: now()) | |
| 192 | let b = try Elisp.time(args[1], now: now()) | |
| 193 | let sign = name == "time-add" ? 1 : -1 | |
| 194 | var picoseconds = a.picoseconds + sign * b.picoseconds | |
| 195 | var seconds = a.seconds + sign * b.seconds | |
| 196 | if picoseconds < 0 { | |
| 197 | picoseconds += Time.pico | |
| 198 | seconds -= 1 | |
| 199 | } else if picoseconds >= Time.pico { | |
| 200 | picoseconds -= Time.pico | |
| 201 | seconds += 1 | |
| 202 | } | |
| 203 | return Time(seconds: seconds, picoseconds: picoseconds, hz: max(a.hz, b.hz)).sexp | |
| 204 | } | |
| 205 | } | |
| 206 | define("float-time") { _, args in | |
| 207 | try Elisp.arity(args, 0...1, "float-time") | |
| 208 | if case .float(let d)? = args.first { return .float(d) } | |
| 209 | let time = try Elisp.time(args.first ?? .nil, now: now()) | |
| 210 | guard time.picoseconds % 1_000_000 == 0 else { throw Unsupported(what: "float-time of picoseconds") } | |
| 211 | return .float(Double(time.seconds * 1_000_000 + time.picoseconds / 1_000_000) / 1_000_000) | |
| 212 | } | |
| 213 | define("date-to-time") { _, args in | |
| 214 | try Elisp.arity(args, 1...1, "date-to-time") | |
| 215 | return try Elisp.dateToTime(try Elisp.string(args[0]), calendar: local).pair | |
| 216 | } | |
| 217 | define("time-to-days") { _, args in | |
| 218 | try Elisp.arity(args, 1...1, "time-to-days") | |
| 219 | return .integer(Elisp.days(try Elisp.wholeSeconds(args[0], now: now()), calendar: local)) | |
| 220 | } | |
| 221 | define("days-between") { _, args in | |
| 222 | try Elisp.arity(args, 2...2, "days-between") | |
| 223 | let a = try Elisp.dateToTime(try Elisp.string(args[0]), calendar: local) | |
| 224 | let b = try Elisp.dateToTime(try Elisp.string(args[1]), calendar: local) | |
| 225 | return .integer(Elisp.days(a.seconds, calendar: local) - Elisp.days(b.seconds, calendar: local)) | |
| 226 | } | |
| 227 | } | |
| 228 | } | |
Tests/OrgCoreTests/BabelTests.swift +7
| @@ -257,6 +257,13 @@ struct BabelTests { | ||
| 257 | 257 | "#+begin_src emacs-lisp\n(car 1)\n#+end_src\n", |
| 258 | 258 | "#+begin_src emacs-lisp :results raw\n\"*bold*\"\n#+end_src\n", |
| 259 | 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 | 269 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) |
Tests/OrgCoreTests/ElispTests.swift +177
| @@ -45,6 +45,183 @@ struct ElispTests { | ||
| 45 | 45 | #expect(Self.ours(form) == expected, "\(form)") |
| 46 | 46 | } |
| 47 | 47 | } |
| 48 | ||
| 49 | /// Math, strings, regexps, lists, seq and cl-lib, and the macros: each must run here. | |
| 50 | static let library = [ | |
| 51 | "(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)", | |
| 52 | "(sqrt 2)", "(sqrt -1)", "(exp 1)", "(log 8 2)", "(log 100 10)", "(log 9 3)", "(log 8 0)", "(log 0)", "(log 8)", "(sin 1)", | |
| 53 | "(cos 0)", "(tan 1)", "(asin 0.5)", "(acos 2)", "(atan 1)", "(atan 1 -1)", "(isnan 1)", "(isnan (/ 0.0 0.0))", | |
| 54 | "(logand 12 10)", "(logand)", "(logior 1 4)", "(logxor 5 1)", "(ash 1 3)", "(ash -8 -1)", "(ash 5 -10)", "(random 0)", | |
| 55 | "(let ((r (random 10))) (and (integerp r) (<= 0 r 9)))", | |
| 56 | #"(string-join '("a" "b") ", ")"#, #"(string-join '("a" "b"))"#, #"(string-to-char "")"#, #"(string-to-char "é")"#, | |
| 57 | "(char-to-string 233)", #"(string-pad "ab" 5)"#, #"(string-pad "ab" 5 ?- t)"#, #"(string-pad "abcdef" 3)"#, | |
| 58 | #"(string-width "abc\t")"#, #"(string-width "é\n")"#, #"(string-search "b" "abcb" 2)"#, #"(string-search "" "abc")"#, | |
| 59 | #"(string-search "z" "abc")"#, #"(string-search "b" "abc" 9)"#, #"(string-replace "ab" "x" "cabab")"#, | |
| 60 | #"(string-replace "" "x" "abc")"#, #"(substring "héllo" 1 3)"#, #"(number-to-string 1.5)"#, | |
| 61 | #"(string-match "a" "XA")"#, #"(let ((case-fold-search nil)) (string-match "a" "XA"))"#, | |
| 62 | #"(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))"#, | |
| 63 | #"(string-match "^b" "a\nb")"#, #"(string-match "a$" "a\nb")"#, #"(string-match "\\`b" "a\nb")"#, #"(string-match "b\\'" "ab\n")"#, | |
| 64 | #"(string-match "x*" "")"#, #"(string-match "\\w+" "_ab")"#, #"(string-match "\\W" "$%'_")"#, #"(string-match "\\bb" "a-b")"#, | |
| 65 | #"(string-match "\\_<b" "a-b")"#, #"(string-match "\\_<b" "a b")"#, #"(string-match "x\\_>" "x-y x")"#, | |
| 66 | #"(string-match "[[:space:]]" "a\tb")"#, #"(progn (string-match "\\s-+" "a \t b") (match-end 0))"#, #"(string-match "\\S-" " x")"#, | |
| 67 | #"(string-match "\\s_" "ab=c")"#, #"(string-match "*a" "x*a")"#, #"(string-match "^*a" "*a")"#, #"(string-match "\\(*a\\)" "x*a")"#, | |
| 68 | #"(string-match "a\\{2\\}" "caaa")"#, #"(string-match "a\\{,2\\}b" "aaab")"#, #"(progn (string-match "a\\{2,\\}" "caaaa") (match-end 0))"#, | |
| 69 | #"(string-match "a|b" "xa|b")"#, #"(string-match "a{2}" "a{2}")"#, #"(string-match "(a)" "x(a)")"#, #"(string-match "[]a]" "x]")"#, | |
| 70 | #"(string-match "[^]a]" "]ab")"#, #"(string-match "[\\]" "x\\")"#, #"(string-match "[a-]" "x-")"#, #"(string-match "\\(?:ab\\)+" "xabab")"#, | |
| 71 | #"(progn (string-match "a+?" "aaa") (match-end 0))"#, #"(progn (string-match "a*?b" "aab") (match-end 0))"#, #"(string-match "\\Ba" "ba")"#, | |
| 72 | #"(string-match "\\<b" "a b")"#, #"(string-match "a\\>" "ab a")"#, #"(string-match "\\s." "a,b")"#, #"(string-match "\\s(" "a[b")"#, | |
| 73 | #"(string-match "[[:alpha:]]+" "12ab")"#, #"(string-match "[^[:digit:]]" "12ab")"#, #"(string-match "[[:punct:]]" "ab$")"#, | |
| 74 | #"(string-match "[[:word:]]" ",$")"#, #"(string-match "[[:xdigit:]]+" "xyzBEEF")"#, #"(string-match "\\(a\\)\\1" "xaa")"#, | |
| 75 | #"(string-match "[a-z]+" "ABC")"#, #"(let ((case-fold-search nil)) (string-match "[a-z]+" "ABC"))"#, #"(string-match "x\\|y" "zzy")"#, | |
| 76 | #"(string-match "[[:upper:]]" "a")"#, #"(let ((case-fold-search nil)) (string-match "[[:upper:]]" "a"))"#, #"(string-match "a" "bab" 2)"#, | |
| 77 | #"(string-match "a" "bab" -2)"#, #"(string-match "a" "bab" 9)"#, #"(string-match "^a" "ba" 1)"#, #"(string-match "\\." "a.b")"#, | |
| 78 | #"(string-match "a.c" "a\nc abc")"#, #"(string-match "f." "café")"#, | |
| 79 | #"(let ((case-fold-search nil)) (string-match "É" "café"))"#, #"(string-match-p "b" "abc")"#, | |
| 80 | #"(progn (string-match "a" "xa") (string-match-p "b" "bbb") (match-beginning 0))"#, | |
| 81 | #"(progn (string-match "a" "xa") (save-match-data (string-match "b" "bbb")) (match-beginning 0))"#, | |
| 82 | #"(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")))"#, | |
| 83 | #"(replace-regexp-in-string "b" "X" "aBc")"#, #"(replace-regexp-in-string "o" "x" "FOO BAR")"#, | |
| 84 | #"(replace-regexp-in-string "foo" "bar" "Foo FOO foo")"#, #"(replace-regexp-in-string "foo" "bar" "Foo FOO foo" t)"#, | |
| 85 | #"(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")"#, | |
| 86 | #"(replace-regexp-in-string "" "x" "ab")"#, #"(replace-regexp-in-string "$" "x" "ab")"#, #"(replace-regexp-in-string "^" "> " "a\nb")"#, | |
| 87 | #"(replace-regexp-in-string "\\(a\\)\\|b" "[\\1]" "ab")"#, #"(replace-regexp-in-string "a" "\\x" "a")"#, #"(replace-regexp-in-string "a" "\\1" "a")"#, | |
| 88 | #"(replace-regexp-in-string "a" "\\\\" "a")"#, #"(replace-regexp-in-string "a\\(b\\)" "Z" "abab" nil nil 1)"#, | |
| 89 | #"(replace-regexp-in-string "b" "Z" "abab" nil nil nil 2)"#, #"(replace-regexp-in-string "o" "0" "foo" nil t)"#, | |
| 90 | #"(replace-regexp-in-string "\\([0-9]+\\)" "<\\1>" "a1b22")"#, #"(replace-regexp-in-string "[aeiou]" (lambda (m) (upcase m)) "hello world")"#, | |
| 91 | #"(replace-regexp-in-string "[0-9]+" (lambda (m) (number-to-string (* 2 (string-to-number m)))) "a1b22")"#, | |
| 92 | #"(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")"#, | |
| 93 | #"(split-string "a1b22c" "[0-9]+")"#, #"(split-string " a b " " +")"#, #"(split-string "a,b,,c" "," t)"#, | |
| 94 | #"(split-string " a , b " "," t " ")"#, #"(split-string "abc" "")"#, #"(split-string "abc" "" t)"#, #"(split-string "a-b_c" "\\W")"#, | |
| 95 | #"(split-string "a,b" "," nil "\\s-*")"#, #"(split-string "a b" nil)"#, #"(split-string " two words " "[ ]+" t)"#, | |
| 96 | "(last '(1 2 3))", "(last '(1 2 3) 2)", "(last '(1 2 3) 0)", "(last '(1 2 . 3))", "(last nil)", "(butlast '(1 2 3))", | |
| 97 | "(butlast '(1 2 3) 2)", "(butlast '(1 2 3) 0)", "(butlast nil)", "(butlast '(1 2 . 3))", #"(delete-dups (list 1 2 1 "a" "a"))"#, | |
| 98 | "(nreverse (list 1 2 3))", "(nreverse [1 2 3])", #"(nreverse "abc")"#, "(let ((l (list 1 2 3))) (nreverse l) l)", | |
| 99 | "(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)", | |
| 100 | "(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)", | |
| 101 | "(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 #'-)", | |
| 102 | "(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))))", | |
| 103 | "(seq-reduce #'+ '(1 2 3) 10)", "(seq-reduce #'+ [] 0)", "(seq-filter (lambda (x) (> x 2)) [1 2 3 4])", | |
| 104 | "(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))", | |
| 105 | #"(seq-uniq "abca")"#, "(cl-reduce #'+ '(1 2 3))", "(cl-reduce #'+ '())", "(cl-reduce #'+ '(5))", "(cl-reduce #'list '(1 2 3) :initial-value 0)", | |
| 106 | "(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])", | |
| 107 | #"(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))", | |
| 108 | #"(cl-find "a" '("a"))"#, #"(cl-find "a" '("a") :test #'equal)"#, "(cl-find 2 '(1 2 3) :test #'=)", "(cl-position 3 '(1 2 3))", | |
| 109 | "(cl-position 9 '(1 2 3))", #"(cl-position ?b "abc")"#, "(cl-position 2 [1 2])", | |
| 110 | #"(progn (defun orgstar-sq (x) "Square." (* x x)) (orgstar-sq 4))"#, "(defun orgstar-f () 1)", #"(progn (defun orgstar-g () "doc") (orgstar-g))"#, | |
| 111 | "(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))", | |
| 112 | "(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)", | |
| 113 | "(let-alist '((a . 1) (b . ((c . 2)))) (list .a .b.c .d))", "(let-alist '((a . 1)) (let-alist '((a . 2)) .a))", | |
| 114 | "(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))", | |
| 115 | "(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)))", | |
| 116 | "(pcase '(sub 5 2) (`(add ,x ,y) (+ x y)) (`(sub ,x ,y) (- x y)))", "(pcase 5 ((pred stringp) 's) ((pred integerp) 'i))", | |
| 117 | "(pcase 5 ((pred (lambda (n) (> n 3))) 'big) (_ 'small))", "(pcase 5 (x (* x 2)))", "(pcase 7 (1 'a))", "(pcase :k (:k 'kw))", | |
| 118 | "(pcase [1 2] (`[,a ,b] (+ a b)))", "(pcase nil ('nil 'isnil))", "(pcase '(1 2) (`(1 ,x) x))", "(pcase '(1 1) (`(,x ,x) 'same) (_ 'differ))", | |
| 119 | "(pcase '(1 2) (`(,x ,x) 'same) (_ 'differ))", "(pcase ?a (?a 'char))", "(cl-loop for x in '(1 2 3) collect (* x x))", | |
| 120 | "(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)", | |
| 121 | "(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)", | |
| 122 | "(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))", | |
| 123 | "(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))", | |
| 124 | "(undefined-orgstar-function (car 1))", | |
| 125 | ] | |
| 126 | ||
| 127 | /// Forms that use what the evaluator lacks, refused rather than answered differently. | |
| 128 | static let unsupported = [ | |
| 129 | "(expt 3 40)", "(ash 1 63)", #"(random "seed")"#, #"(string-match "\\(?2:a\\)" "a")"#, #"(string-match "\\ca" "a")"#, | |
| 130 | #"(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)"#, | |
| 131 | #"(string-width "中")"#, #"(sort "cba")"#, "(seq-uniq '(1 2) #'=)", "(cl-find 2 '(1 2 3) :key #'1+)", | |
| 132 | "(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)", | |
| 133 | "(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)))", | |
| 134 | "(when-let ((x 1)) x)", "(undefined-orgstar-macro (car 1))", "(undefined-orgstar-macro void-orgstar-variable)", | |
| 135 | ] | |
| 136 | ||
| 137 | static func strict(_ form: String) -> String { | |
| 138 | guard let sexp = try? LispReader.readFirst(form).sexp else { return "read-error" } | |
| 139 | do { | |
| 140 | return Elisp.printed(try Elisp().eval(sexp), escape: true) | |
| 141 | } catch is Elisp.Unsupported { | |
| 142 | return "unsupported" | |
| 143 | } catch { | |
| 144 | return "error" | |
| 145 | } | |
| 146 | } | |
| 147 | ||
| 148 | @Test(.enabled(if: oracle)) | |
| 149 | func libraryMatchesEmacs() throws { | |
| 150 | let forms = Self.library.filter { !$0.hasPrefix("(undefined-") } | |
| 151 | let list = "(list " + forms.map { "(condition-case nil (prin1-to-string \($0)) (error \"error\"))" }.joined(separator: " ") + ")" | |
| 152 | let emacs = try EmacsOracle.evaluate("", list, prelude: "(require 'cl-lib) (require 'seq) (require 'let-alist)") | |
| 153 | #expect(emacs.count == forms.count) | |
| 154 | for (form, expected) in zip(forms, emacs) { | |
| 155 | #expect(Self.strict(form) == expected, "\(form): \(Self.strict(form)), Emacs \(expected)") | |
| 156 | } | |
| 157 | } | |
| 158 | ||
| 159 | @Test func refusesWhatItLacks() { | |
| 160 | for form in Self.unsupported { #expect(Self.strict(form) == "unsupported", "\(form)") } | |
| 161 | // Arguments aren't evaluated for a function it doesn't have. | |
| 162 | #expect(Self.strict("(undefined-orgstar-function (car 1))") == "unsupported") | |
| 163 | } | |
| 164 | ||
| 165 | /// The syntax classes follow `org-mode-syntax-table`. | |
| 166 | @Test(.enabled(if: oracle)) | |
| 167 | func syntaxTableMatchesOrgMode() throws { | |
| 168 | let emacs = try EmacsOracle.evaluate("", "(list (let (r) (dotimes (c 128) (push (string (char-syntax c)) r)) (apply #'concat (nreverse r))))") | |
| 169 | #expect(emacs == [String(ElispRegex.syntax)]) | |
| 170 | } | |
| 171 | ||
| 172 | static let timeForms = [ | |
| 173 | #"(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]")"#, | |
| 174 | #"(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")"#, | |
| 175 | #"(org-time-string-to-absolute "<2026-11-20 Fri>")"#, #"(org-time-string-to-absolute "<2026-11-20 Fri 23:59 +1w>")"#, | |
| 176 | #"(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)", | |
| 177 | "(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))", | |
| 178 | #"(time-subtract (org-time-string-to-time "<2026-11-21 Sat>") (org-time-string-to-time "<2026-11-20 Fri>"))"#, | |
| 179 | "(float-time '(1 2))", "(float-time '(0 1 500000 0))", "(float-time '(0 1 1))", "(float-time 5)", "(float-time 2.5)", | |
| 180 | #"(float-time (org-time-string-to-time "<2026-11-20 Fri 10:30>"))"#, #"(days-between "2026-11-20" "2026-01-01")"#, | |
| 181 | #"(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")"#, | |
| 182 | #"(date-to-time "2026-11-20T10:30:05")"#, #"(time-to-days (org-time-string-to-time "<2026-11-20 Fri>"))"#, "(time-to-days 0)", | |
| 183 | "(time-to-days 86399)", "(time-to-days 86400.5)", | |
| 184 | #"(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>"))"#, | |
| 185 | #"(format-time-string "%Y %e|%k|%l %p" (org-time-string-to-time "<2026-01-05 Mon 00:07>"))"#, #"(format-time-string "%Y" 0)"#, | |
| 186 | #"(format-time-string "%Y-%m-%d %H:%M" 1795170600 t)"#, #"(format-time-string "%H:%M" 1795170600.75)"#, | |
| 187 | "(calendar-day-of-week '(11 20 2026))", "(calendar-absolute-from-gregorian '(11 20 2026))", "(calendar-gregorian-from-absolute 739940)", | |
| 188 | "(calendar-leap-year-p 2028)", "(calendar-last-day-of-month 2 2028)", "(calendar-iso-from-absolute 739940)", | |
| 189 | #"(let ((s (format-time-string "%Y-%m-%d"))) (string-match "\\`[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\'" s))"#, | |
| 190 | "(let ((t0 (current-time))) (and (consp t0) (= (length t0) 4) (< (abs (- (float-time t0) (float-time))) 5)))", | |
| 191 | "(> (time-to-days (current-time)) 739000)", | |
| 192 | ] | |
| 193 | ||
| 194 | static let unsupportedTime = [ | |
| 195 | "(time-add 0.1 1)", "(time-add '(5 . 10) 1)", #"(format-time-string "%-d" 0)"#, #"(format-time-string "%c" 0)"#, | |
| 196 | #"(format-time-string "%Y" 0 "EST5")"#, #"(date-to-time "Fri, 20 Nov 2026 10:30:00 +0000")"#, | |
| 197 | #"(org-time-string-to-absolute "<2026-11-20 Fri>" 739940)"#, "(float-time '(0 1 0 1))", | |
| 198 | ] | |
| 199 | ||
| 200 | static func timed(_ form: String) -> String { | |
| 201 | guard let sexp = try? LispReader.readFirst(form).sexp else { return "read-error" } | |
| 202 | var utc = Calendar(identifier: .gregorian) | |
| 203 | utc.timeZone = TimeZone(identifier: "UTC")! | |
| 204 | let lisp = Elisp() | |
| 205 | lisp.standardTime(calendar: utc) | |
| 206 | do { | |
| 207 | return Elisp.printed(try lisp.eval(sexp), escape: true) | |
| 208 | } catch is Elisp.Unsupported { | |
| 209 | return "unsupported" | |
| 210 | } catch { | |
| 211 | return "error" | |
| 212 | } | |
| 213 | } | |
| 214 | ||
| 215 | @Test(.enabled(if: oracle)) | |
| 216 | func timeFunctionsMatchEmacs() throws { | |
| 217 | let list = "(list " + Self.timeForms.map { "(condition-case nil (prin1-to-string \($0)) (error \"error\"))" }.joined(separator: " ") + ")" | |
| 218 | let emacs = try EmacsOracle.evaluate("", list, prelude: "(require 'calendar) (require 'time-date)") | |
| 219 | #expect(emacs.count == Self.timeForms.count) | |
| 220 | for (form, expected) in zip(Self.timeForms, emacs) { | |
| 221 | #expect(Self.timed(form) == expected, "\(form): \(Self.timed(form)), Emacs \(expected)") | |
| 222 | } | |
| 223 | for form in Self.unsupportedTime { #expect(Self.timed(form) == "unsupported", "\(form)") } | |
| 224 | } | |
| 48 | 225 | } |
| 49 | 226 | |
| 50 | 227 | /// Inputs that once crashed the evaluator, the diary functions or duration formulas. |
Tests/OrgCoreTests/TableFormulaTests.swift +15
| @@ -102,6 +102,21 @@ struct TableFormulaTests { | ||
| 102 | 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 | 120 | func compare(_ tables: [String], fallbacksAllowed: Bool) throws { |
| 106 | 121 | var cases: [EmacsOracle.Case] = [] |
| 107 | 122 | var ours: [(text: String, caret: Int, failure: String?)] = [] |