Sources/OrgCore/Config/Elisp.swift

46d6a046f519e5ab5a9338ff643341bd53e7788f
orgstar/Sources/OrgCore/Config/Elisp.swift history · blame · raw

918 lines · 41139 bytes

  1import Foundation
  2
  3/// A small Emacs Lisp evaluator over `Sexp` values: the special forms and functions diary
  4/// sexps and table formulas use, with dynamic binding. A function or form it doesn't have
  5/// throws `Unsupported`; errors Emacs would signal throw `Signal`.
  6public final class Elisp {
  7    public struct Unsupported: Error, Equatable, CustomStringConvertible {
  8        public let what: String
  9        public var description: String { what }
 10    }
 11
 12    public struct Signal: Error, Equatable, CustomStringConvertible {
 13        public let message: String
 14        public var description: String { message }
 15    }
 16
 17    public typealias Builtin = (Elisp, [Sexp]) throws -> Sexp
 18
 19    private var scopes: [[String: Sexp]] = [[:]]
 20    private var functions: [String: Builtin] = [:]
 21    private var steps = 0
 22    static let stepLimit = 1_000_000
 23    /// What `princ` and the other printers wrote: the innermost `with-output-to-string`, or
 24    /// standard output.
 25    private var outputs: [String] = [""]
 26    /// What went to standard output.
 27    public var standardOutput: String { outputs[0] }
 28    /// What `message` wrote.
 29    public private(set) var messages = ""
 30
 31    public init() {
 32        Self.core(self)
 33    }
 34
 35    /// Defines or replaces a function.
 36    public func define(_ name: String, _ function: @escaping Builtin) { functions[name] = function }
 37
 38    /// Sets a global variable.
 39    public func set(_ name: String, _ value: Sexp) { scopes[0][name] = value }
 40
 41    public func value(_ name: String) throws -> Sexp {
 42        for scope in scopes.reversed() { if let v = scope[name] { return v } }
 43        throw Signal(message: "Symbol’s value as variable is void: \(name)")
 44    }
 45
 46    /// Evaluates `body` with `bindings` added.
 47    public func binding<T>(_ bindings: [String: Sexp], _ body: () throws -> T) rethrows -> T {
 48        scopes.append(bindings)
 49        defer { scopes.removeLast() }
 50        return try body()
 51    }
 52
 53    private func assign(_ name: String, _ v: Sexp) {
 54        for i in scopes.indices.reversed() where scopes[i][name] != nil {
 55            scopes[i][name] = v
 56            return
 57        }
 58        scopes[0][name] = v
 59    }
 60
 61    // MARK: - Values
 62
 63    public static let t = Sexp.symbol("t")
 64
 65    public static func isNil(_ v: Sexp) -> Bool { v == .nil || v == .list([]) }
 66    public static func bool(_ b: Bool) -> Sexp { b ? t : .nil }
 67    static func list(_ items: [Sexp]) -> Sexp { items.isEmpty ? .nil : .list(items) }
 68
 69    static func cons(_ a: Sexp, _ b: Sexp) -> Sexp {
 70        switch b {
 71        case .list(let items): .list([a] + items)
 72        case .dotted(let items, let last): .dotted([a] + items, last)
 73        case _ where isNil(b): .list([a])
 74        default: .dotted([a], b)
 75        }
 76    }
 77
 78    static func car(_ v: Sexp) throws -> Sexp {
 79        switch v {
 80        case .list(let items): items.first ?? .nil
 81        case .dotted(let items, _): items[0]
 82        case _ where isNil(v): .nil
 83        default: throw Signal(message: "Wrong type argument: listp, \(v.description)")
 84        }
 85    }
 86
 87    static func cdr(_ v: Sexp) throws -> Sexp {
 88        switch v {
 89        case .list(let items): list(Array(items.dropFirst()))
 90        case .dotted(let items, let last): items.count == 1 ? last : .dotted(Array(items.dropFirst()), last)
 91        case _ where isNil(v): .nil
 92        default: throw Signal(message: "Wrong type argument: listp, \(v.description)")
 93        }
 94    }
 95
 96    /// A proper list's elements.
 97    static func elements(_ v: Sexp) throws -> [Sexp] {
 98        if case .list(let items) = v { return items }
 99        if isNil(v) { return [] }
100        throw Signal(message: "Wrong type argument: listp, \(v.description)")
101    }
102
103    enum Number {
104        case int(Int), float(Double)
105        var double: Double {
106            switch self {
107            case .int(let i): Double(i)
108            case .float(let d): d
109            }
110        }
111    }
112
113    static func number(_ v: Sexp) throws -> Number {
114        switch v {
115        case .integer(let i): return .int(i)
116        case .float(let d): return .float(d)
117        case .character(let c): return .int(c)
118        default: throw Signal(message: "Wrong type argument: number-or-marker-p, \(v.description)")
119        }
120    }
121
122    static func int(_ v: Sexp) throws -> Int {
123        switch v {
124        case .integer(let i): return i
125        case .character(let c): return c
126        default: throw Signal(message: "Wrong type argument: integerp, \(v.description)")
127        }
128    }
129
130    static func string(_ v: Sexp) throws -> String {
131        guard case .string(let s) = v else { throw Signal(message: "Wrong type argument: stringp, \(v.description)") }
132        return s
133    }
134
135    static func sexp(_ n: Number) -> Sexp {
136        switch n {
137        case .int(let i): .integer(i)
138        case .float(let d): .float(d)
139        }
140    }
141
142    /// `prin1-to-string` with `princ` for strings when `escape` is false.
143    public static func printed(_ v: Sexp, escape: Bool = false) -> String {
144        switch v {
145        case .string(let s): return escape ? "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" : s
146        case .float(let d): return floatText(d)
147        case .character(let c): return String(c)
148        case .list(let items): return "(" + items.map { printed($0, escape: true) }.joined(separator: " ") + ")"
149        case .dotted(let items, let last): return "(" + items.map { printed($0, escape: true) }.joined(separator: " ") + " . " + printed(last, escape: true) + ")"
150        case .vector(let items): return "[" + items.map { printed($0, escape: true) }.joined(separator: " ") + "]"
151        default: return v.description
152        }
153    }
154
155    /// Emacs's float printing: the shortest text that reads back, with `.0` on whole numbers.
156    static func floatText(_ d: Double) -> String {
157        if d.isNaN { return d.sign == .minus ? "-0.0e+NaN" : "0.0e+NaN" }
158        if d.isInfinite { return d < 0 ? "-1.0e+INF" : "1.0e+INF" }
159        var text = "\(d)"
160        if let e = text.firstIndex(of: "e") {
161            let mantissa = text[..<e]
162            var exponent = String(text[text.index(after: e)...])
163            if !exponent.hasPrefix("-"), !exponent.hasPrefix("+") { exponent = "+" + exponent }
164            text = mantissa.hasSuffix(".0") ? String(mantissa.dropLast(2)) + "e" + exponent : mantissa + "e" + exponent
165        }
166        return text
167    }
168
169    // MARK: - Evaluation
170
171    public func eval(_ form: Sexp) throws -> Sexp {
172        steps += 1
173        if steps > Self.stepLimit { throw Signal(message: "Evaluation took too long") }
174        switch form {
175        case .symbol(let name):
176            if name == "nil" || name == "t" || name.hasPrefix(":") { return form }
177            return try value(name)
178        case .character(let c): return .integer(c)
179        case .list(let items):
180            guard let head = items.first else { return .nil }
181            guard case .symbol(let name) = head else {
182                if case .list(let lambda) = head, lambda.first == .symbol("lambda") {
183                    return try call(head, try items.dropFirst().map(eval))
184                }
185                throw Signal(message: "Invalid function: \(head.description)")
186            }
187            return try special(name, Array(items.dropFirst())) ?? callNamed(name, try items.dropFirst().map(eval))
188        case .dotted: throw Signal(message: "Invalid function")
189        default: return form
190        }
191    }
192
193    func progn(_ body: some Collection<Sexp>) throws -> Sexp {
194        var result = Sexp.nil
195        for form in body { result = try eval(form) }
196        return result
197    }
198
199    /// Special forms and macros; nil when `name` is an ordinary function.
200    private func special(_ name: String, _ args: [Sexp]) throws -> Sexp? {
201        switch name {
202        case "quote":
203            return args.first ?? .nil
204        case "function":
205            return args.first ?? .nil
206        case "lambda":
207            return .list([.symbol("lambda")] + args)
208        case "progn":
209            return try progn(args)
210        case "prog1":
211            guard let first = args.first else { return .nil }
212            let value = try eval(first)
213            _ = try progn(args.dropFirst())
214            return value
215        case "if":
216            guard args.count >= 2 else { throw Signal(message: "Wrong number of arguments: if") }
217            return Self.isNil(try eval(args[0])) ? try progn(args.dropFirst(2)) : try eval(args[1])
218        case "when", "unless":
219            guard let test = args.first else { return .nil }
220            return Self.isNil(try eval(test)) == (name == "unless") ? try progn(args.dropFirst()) : .nil
221        case "cond":
222            for clause in args {
223                let parts = try Self.elements(clause)
224                guard let test = parts.first else { continue }
225                let value = try eval(test)
226                if !Self.isNil(value) { return parts.count == 1 ? value : try progn(parts.dropFirst()) }
227            }
228            return .nil
229        case "and":
230            var value = Self.t
231            for form in args {
232                value = try eval(form)
233                if Self.isNil(value) { return .nil }
234            }
235            return value
236        case "or":
237            for form in args {
238                let value = try eval(form)
239                if !Self.isNil(value) { return value }
240            }
241            return .nil
242        case "let", "let*":
243            guard let first = args.first else { return .nil }
244            var bindings: [String: Sexp] = [:]
245            scopes.append([:])
246            defer { scopes.removeLast() }
247            for binding in try Self.elements(first) {
248                let (variable, value): (String, Sexp)
249                if case .symbol(let s) = binding {
250                    (variable, value) = (s, .nil)
251                } else {
252                    let parts = try Self.elements(binding)
253                    guard case .symbol(let s)? = parts.first else { throw Signal(message: "Bad binding") }
254                    (variable, value) = (s, parts.count > 1 ? try eval(parts[1]) : .nil)
255                }
256                if name == "let*" { scopes[scopes.count - 1][variable] = value } else { bindings[variable] = value }
257            }
258            if name == "let" { scopes[scopes.count - 1] = bindings }
259            return try progn(args.dropFirst())
260        case "setq":
261            var value = Sexp.nil
262            var i = 0
263            while i + 1 < args.count {
264                guard case .symbol(let variable) = args[i] else { throw Signal(message: "Bad setq") }
265                value = try eval(args[i + 1])
266                assign(variable, value)
267                i += 2
268            }
269            return value
270        case "push", "pop":
271            guard case .symbol(let variable)? = (name == "push" ? args.dropFirst().first : args.first) else { throw Unsupported(what: "\(name) on a place") }
272            let list = try value(variable)
273            if name == "pop" {
274                assign(variable, try Self.cdr(list))
275                return try Self.car(list)
276            }
277            let pushed = Self.cons(try eval(args[0]), list)
278            assign(variable, pushed)
279            return pushed
280        case "while":
281            guard let test = args.first else { return .nil }
282            while !Self.isNil(try eval(test)) { _ = try progn(args.dropFirst()) }
283            return .nil
284        case "dolist", "dotimes":
285            let spec = try args.first.map(Self.elements) ?? []
286            guard case .symbol(let variable)? = spec.first, spec.count >= 2 else { throw Signal(message: "Bad \(name)") }
287            let source = try eval(spec[1])
288            let items = name == "dolist" ? try Self.elements(source) : (0..<max(0, try Self.int(source))).map { Sexp.integer($0) }
289            scopes.append([:])
290            defer { scopes.removeLast() }
291            for item in items {
292                scopes[scopes.count - 1][variable] = item
293                _ = try progn(args.dropFirst())
294            }
295            if spec.count > 2 {
296                scopes[scopes.count - 1][variable] = name == "dotimes" ? .integer(items.count) : .nil
297                return try eval(spec[2])
298            }
299            return .nil
300        case "with-output-to-string":
301            outputs.append("")
302            do {
303                _ = try progn(args)
304            } catch {
305                outputs.removeLast()
306                throw error
307            }
308            return .string(outputs.removeLast())
309        case "ignore-errors":
310            do { return try progn(args) } catch is Signal { return .nil }
311        case "condition-case":
312            guard args.count >= 2 else { throw Signal(message: "Bad condition-case") }
313            do {
314                return try eval(args[1])
315            } catch let signal as Signal {
316                for handler in args.dropFirst(2) {
317                    let parts = try Self.elements(handler)
318                    guard let condition = parts.first else { continue }
319                    let names = (try? Self.elements(condition)) ?? [condition]
320                    guard names.contains(.symbol("error")) || names.contains(.symbol("t")) else { continue }
321                    let bindings: [String: Sexp] = args[0].symbol.map { $0 == "nil" ? [:] : [$0: .list([.symbol("error"), .string(signal.message)])] } ?? [:]
322                    return try binding(bindings) { try progn(parts.dropFirst()) }
323                }
324                throw signal
325            }
326        default:
327            return nil
328        }
329    }
330
331    /// Calls a function value: a symbol naming one, or a lambda list.
332    public func call(_ function: Sexp, _ args: [Sexp]) throws -> Sexp {
333        switch function {
334        case .symbol(let name): return try callNamed(name, args)
335        case .list(let items) where items.first == .symbol("lambda") && items.count >= 2:
336            var bindings: [String: Sexp] = [:]
337            var mode = "required"
338            var i = 0
339            for parameter in try Self.elements(items[1]) {
340                guard case .symbol(let p) = parameter else { throw Signal(message: "Bad lambda list") }
341                if p == "&optional" || p == "&rest" {
342                    mode = p
343                    continue
344                }
345                if mode == "&rest" {
346                    bindings[p] = Self.list(Array(args.dropFirst(i)))
347                    i = args.count
348                } else if i < args.count {
349                    bindings[p] = args[i]
350                    i += 1
351                } else if mode == "&optional" {
352                    bindings[p] = .nil
353                } else {
354                    throw Signal(message: "Wrong number of arguments")
355                }
356            }
357            if i < args.count { throw Signal(message: "Wrong number of arguments") }
358            return try binding(bindings) { try progn(items.dropFirst(2)) }
359        default:
360            throw Signal(message: "Invalid function: \(function.description)")
361        }
362    }
363
364    func callNamed(_ name: String, _ args: [Sexp]) throws -> Sexp {
365        guard let function = functions[name] else { throw Unsupported(what: "function \(name)") }
366        return try function(self, args)
367    }
368
369    static func arity(_ args: [Sexp], _ range: ClosedRange<Int>, _ name: String) throws {
370        guard range.contains(args.count) else { throw Signal(message: "Wrong number of arguments: \(name), \(args.count)") }
371    }
372
373    // MARK: - Functions
374
375    private static func core(_ lisp: Elisp) {
376        func arithmetic(_ name: String, identity: Int, _ intOp: @escaping (Int, Int) -> (Int, Bool), _ floatOp: @escaping (Double, Double) -> Double) {
377            lisp.define(name) { _, args in
378                let numbers = try args.map(number)
379                guard var result = numbers.first else { return .integer(identity) }
380                if numbers.count == 1, name == "-" {
381                    switch result {
382                    case .int(let i): return .integer(-i)
383                    case .float(let d): return .float(-d)
384                    }
385                }
386                for n in numbers.dropFirst() {
387                    switch (result, n) {
388                    case (.int(let a), .int(let b)):
389                        let (value, overflow) = intOp(a, b)
390                        if overflow { throw Unsupported(what: "integer size") }
391                        result = .int(value)
392                    default:
393                        result = .float(floatOp(result.double, n.double))
394                    }
395                }
396                return sexp(result)
397            }
398        }
399        arithmetic("+", identity: 0, { $0.addingReportingOverflow($1) }, +)
400        arithmetic("-", identity: 0, { $0.subtractingReportingOverflow($1) }, -)
401        arithmetic("*", identity: 1, { $0.multipliedReportingOverflow(by: $1) }, *)
402        lisp.define("/") { _, args in
403            try arity(args, 1...Int.max, "/")
404            let numbers = try args.map(number)
405            let floating = numbers.contains { if case .float = $0 { true } else { false } }
406            if numbers.count == 1 { return try sexp(divide(.int(1), numbers[0], floating: floating)) }
407            var result = numbers[0]
408            for n in numbers.dropFirst() { result = try divide(result, n, floating: floating) }
409            return sexp(result)
410        }
411        lisp.define("%") { _, args in
412            try arity(args, 2...2, "%")
413            let b = try int(args[1])
414            guard b != 0 else { throw Signal(message: "Arithmetic error") }
415            return .integer(try int(args[0]) % b)
416        }
417        lisp.define("mod") { _, args in
418            try arity(args, 2...2, "mod")
419            switch (try number(args[0]), try number(args[1])) {
420            case (.int(let a), .int(let b)):
421                guard b != 0 else { throw Signal(message: "Arithmetic error") }
422                let r = a % b
423                return .integer(r != 0 && (r < 0) != (b < 0) ? r + b : r)
424            case (let a, let b):
425                let r = fmod(a.double, b.double)
426                return .float(r != 0 && (r < 0) != (b.double < 0) ? r + b.double : r)
427            }
428        }
429        lisp.define("1+") { _, args in try arity(args, 1...1, "1+"); return try sexp(add(number(args[0]), 1)) }
430        lisp.define("1-") { _, args in try arity(args, 1...1, "1-"); return try sexp(add(number(args[0]), -1)) }
431        lisp.define("abs") { _, args in
432            try arity(args, 1...1, "abs")
433            switch try number(args[0]) {
434            case .int(let i): return .integer(abs(i))
435            case .float(let d): return .float(abs(d))
436            }
437        }
438        for name in ["max", "min"] {
439            lisp.define(name) { _, args in
440                try arity(args, 1...Int.max, name)
441                let numbers = try args.map(number)
442                let floating = numbers.contains { if case .float = $0 { true } else { false } }
443                var best = numbers[0]
444                for n in numbers.dropFirst() where name == "max" ? n.double > best.double : n.double < best.double { best = n }
445                return floating ? .float(best.double) : sexp(best)
446            }
447        }
448        for name in ["floor", "ceiling", "round", "truncate"] {
449            lisp.define(name) { _, args in
450                try arity(args, 1...2, name)
451                var x = try number(args[0]).double
452                if args.count == 2, !isNil(args[1]) {
453                    let divisor = try number(args[1]).double
454                    guard divisor != 0 else { throw Signal(message: "Arithmetic error") }
455                    x /= divisor
456                } else if case .int(let i) = try number(args[0]) {
457                    return .integer(i)
458                }
459                let rule: FloatingPointRoundingRule = switch name {
460                case "floor": .down
461                case "ceiling": .up
462                case "round": .toNearestOrEven
463                default: .towardZero
464                }
465                guard let i = Int(exactly: x.rounded(rule)) else { throw Signal(message: "Arithmetic overflow error") }
466                return .integer(i)
467            }
468        }
469        lisp.define("float") { _, args in try arity(args, 1...1, "float"); return .float(try number(args[0]).double) }
470        for (name, op) in [("=", { (a: Double, b: Double) in a == b }), ("<", { $0 < $1 }), (">", { $0 > $1 }), ("<=", { $0 <= $1 }), (">=", { $0 >= $1 })] {
471            lisp.define(name) { _, args in
472                try arity(args, 1...Int.max, name)
473                let numbers = try args.map(number)
474                for (a, b) in zip(numbers, numbers.dropFirst()) {
475                    let holds: Bool = switch (a, b) {
476                    case (.int(let x), .int(let y)): op(Double(x), Double(y)) && (name != "=" || x == y)
477                    default: op(a.double, b.double)
478                    }
479                    if !holds { return .nil }
480                }
481                return t
482            }
483        }
484        lisp.define("/=") { _, args in
485            try arity(args, 2...2, "/=")
486            return bool(try number(args[0]).double != (try number(args[1])).double)
487        }
488        lisp.define("zerop") { _, args in try arity(args, 1...1, "zerop"); return bool(try number(args[0]).double == 0) }
489        lisp.define("not") { _, args in try arity(args, 1...1, "not"); return bool(isNil(args[0])) }
490        lisp.define("null") { _, args in try arity(args, 1...1, "null"); return bool(isNil(args[0])) }
491        lisp.define("eq") { _, args in try arity(args, 2...2, "eq"); return bool(eq(args[0], args[1])) }
492        lisp.define("eql") { _, args in try arity(args, 2...2, "eql"); return bool(eq(args[0], args[1])) }
493        lisp.define("equal") { _, args in try arity(args, 2...2, "equal"); return bool(normalized(args[0]) == normalized(args[1])) }
494        lisp.define("numberp") { _, args in
495            try arity(args, 1...1, "numberp")
496            return bool((try? number(args[0])) != nil && args[0].character == nil)
497        }
498        lisp.define("integerp") { _, args in try arity(args, 1...1, "integerp"); return bool(args[0].integer != nil) }
499        lisp.define("floatp") { _, args in
500            try arity(args, 1...1, "floatp")
501            if case .float = args[0] { return t }
502            return .nil
503        }
504        lisp.define("stringp") { _, args in try arity(args, 1...1, "stringp"); return bool(args[0].string != nil) }
505        lisp.define("listp") { _, args in
506            try arity(args, 1...1, "listp")
507            switch args[0] {
508            case .list, .dotted: return t
509            default: return bool(isNil(args[0]))
510            }
511        }
512        lisp.define("consp") { _, args in
513            try arity(args, 1...1, "consp")
514            switch args[0] {
515            case .list(let items): return bool(!items.isEmpty)
516            case .dotted: return t
517            default: return .nil
518            }
519        }
520        lisp.define("symbolp") { _, args in try arity(args, 1...1, "symbolp"); return bool(args[0].symbol != nil || isNil(args[0])) }
521
522        // Lists.
523        lisp.define("car") { _, args in try arity(args, 1...1, "car"); return try car(args[0]) }
524        lisp.define("cdr") { _, args in try arity(args, 1...1, "cdr"); return try cdr(args[0]) }
525        lisp.define("cadr") { _, args in try arity(args, 1...1, "cadr"); return try car(cdr(args[0])) }
526        lisp.define("cddr") { _, args in try arity(args, 1...1, "cddr"); return try cdr(cdr(args[0])) }
527        lisp.define("cons") { _, args in try arity(args, 2...2, "cons"); return cons(args[0], args[1]) }
528        lisp.define("list") { _, args in list(args) }
529        lisp.define("nth") { _, args in
530            try arity(args, 2...2, "nth")
531            var v = args[1]
532            for _ in 0..<max(0, try int(args[0])) { v = try cdr(v) }
533            return try car(v)
534        }
535        lisp.define("nthcdr") { _, args in
536            try arity(args, 2...2, "nthcdr")
537            var v = args[1]
538            for _ in 0..<max(0, try int(args[0])) { v = try cdr(v) }
539            return v
540        }
541        lisp.define("elt") { _, args in
542            try arity(args, 2...2, "elt")
543            let items = try sequence(args[0])
544            let i = try int(args[1])
545            if case .list = args[0], i >= items.count { return .nil }
546            guard items.indices.contains(i) else { throw Signal(message: "Args out of range") }
547            return items[i]
548        }
549        lisp.define("aref") { _, args in
550            try arity(args, 2...2, "aref")
551            let items = try sequence(args[0])
552            let i = try int(args[1])
553            guard items.indices.contains(i) else { throw Signal(message: "Args out of range") }
554            return items[i]
555        }
556        lisp.define("append") { _, args in
557            guard let last = args.last else { return .nil }
558            var items: [Sexp] = []
559            for arg in args.dropLast() { items += try sequence(arg) }
560            return try items.reversed().reduce(last) { cons($1, $0) }
561        }
562        lisp.define("length") { _, args in
563            try arity(args, 1...1, "length")
564            return .integer(try sequence(args[0]).count)
565        }
566        lisp.define("reverse") { _, args in
567            try arity(args, 1...1, "reverse")
568            if case .string(let s) = args[0] { return .string(String(s.reversed())) }
569            return list(try elements(args[0]).reversed())
570        }
571        lisp.define("number-sequence") { _, args in
572            try arity(args, 1...3, "number-sequence")
573            let from = try int(args[0])
574            guard args.count > 1, !isNil(args[1]) else { return .list([.integer(from)]) }
575            let to = try int(args[1])
576            let step = args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 1
577            guard step != 0 else { throw Signal(message: "The increment can not be zero") }
578            return list(Array(stride(from: from, through: to, by: step)).map { .integer($0) })
579        }
580        for name in ["memq", "member", "memql"] {
581            lisp.define(name) { _, args in
582                try arity(args, 2...2, name)
583                var rest = args[1]
584                while case .list(let items) = rest, let first = items.first {
585                    if name == "member" ? normalized(first) == normalized(args[0]) : eq(first, args[0]) { return rest }
586                    rest = list(Array(items.dropFirst()))
587                }
588                return .nil
589            }
590        }
591        for name in ["assoc", "assq"] {
592            lisp.define(name) { _, args in
593                try arity(args, 2...3, name)
594                for pair in try elements(args[1]) {
595                    guard let key = try? car(pair) else { continue }
596                    if name == "assoc" ? normalized(key) == normalized(args[0]) : eq(key, args[0]) { return pair }
597                }
598                return .nil
599            }
600        }
601        lisp.define("identity") { _, args in try arity(args, 1...1, "identity"); return args[0] }
602        lisp.define("ignore") { _, _ in .nil }
603        lisp.define("funcall") { lisp, args in
604            try arity(args, 1...Int.max, "funcall")
605            return try lisp.call(args[0], Array(args.dropFirst()))
606        }
607        lisp.define("apply") { lisp, args in
608            try arity(args, 1...Int.max, "apply")
609            let spread = args.count > 1 ? Array(args[1..<(args.count - 1)]) + (try elements(args[args.count - 1])) : []
610            return try lisp.call(args[0], spread)
611        }
612        lisp.define("mapcar") { lisp, args in
613            try arity(args, 2...2, "mapcar")
614            return list(try sequence(args[1]).map { try lisp.call(args[0], [$0]) })
615        }
616        lisp.define("mapc") { lisp, args in
617            try arity(args, 2...2, "mapc")
618            for item in try sequence(args[1]) { _ = try lisp.call(args[0], [item]) }
619            return args[1]
620        }
621        lisp.define("mapconcat") { lisp, args in
622            try arity(args, 1...3, "mapconcat")
623            let separator = args.count > 2 ? try string(args[2]) : ""
624            return .string(try sequence(args[1]).map { try printedString(lisp.call(args[0], [$0])) }.joined(separator: separator))
625        }
626        lisp.define("delq") { _, args in
627            try arity(args, 2...2, "delq")
628            return list(try elements(args[1]).filter { !eq($0, args[0]) })
629        }
630        lisp.define("delete") { _, args in
631            try arity(args, 2...2, "delete")
632            return list(try elements(args[1]).filter { normalized($0) != normalized(args[0]) })
633        }
634        lisp.define("error") { _, args in
635            let message = args.isEmpty ? "" : try format(args)
636            throw Signal(message: message)
637        }
638        lisp.define("user-error") { _, args in
639            throw Signal(message: args.isEmpty ? "" : try format(args))
640        }
641
642        // Printing.
643        for (name, escape) in [("princ", false), ("prin1", true), ("print", true)] {
644            lisp.define(name) { lisp, args in
645                try arity(args, 1...2, name)
646                let text = printed(args[0], escape: escape)
647                lisp.outputs[lisp.outputs.count - 1] += name == "print" ? "\n" + text + "\n" : text
648                return args[0]
649            }
650        }
651        lisp.define("terpri") { lisp, _ in
652            lisp.outputs[lisp.outputs.count - 1] += "\n"
653            return t
654        }
655        lisp.define("message") { lisp, args in
656            guard !args.isEmpty, !isNil(args[0]) else { return .nil }
657            let text = try format(args)
658            lisp.messages += text + "\n"
659            return .string(text)
660        }
661        lisp.define("prin1-to-string") { _, args in
662            try arity(args, 1...2, "prin1-to-string")
663            return .string(printed(args[0], escape: args.count < 2 || isNil(args[1])))
664        }
665
666        // Strings.
667        lisp.define("concat") { _, args in .string(try args.map(printedString).joined()) }
668        lisp.define("format") { _, args in .string(try format(args)) }
669        lisp.define("format-message") { _, args in .string(try format(args)) }
670        lisp.define("string=") { _, args in
671            try arity(args, 2...2, "string=")
672            return bool(try stringOrSymbol(args[0]) == (try stringOrSymbol(args[1])))
673        }
674        lisp.define("string-equal") { _, args in
675            try arity(args, 2...2, "string-equal")
676            return bool(try stringOrSymbol(args[0]) == (try stringOrSymbol(args[1])))
677        }
678        lisp.define("string<") { _, args in
679            try arity(args, 2...2, "string<")
680            return bool(Array(try stringOrSymbol(args[0]).unicodeScalars.map(\.value)).lexicographicallyPrecedes(try stringOrSymbol(args[1]).unicodeScalars.map(\.value)))
681        }
682        lisp.define("string-lessp") { lisp, args in try lisp.callNamed("string<", args) }
683        lisp.define("upcase") { _, args in
684            try arity(args, 1...1, "upcase")
685            if case .integer(let c) = args[0] { return .integer(Int(Unicode.Scalar(c).map { String($0).uppercased().unicodeScalars.first!.value } ?? UInt32(c))) }
686            return .string(try string(args[0]).uppercased())
687        }
688        lisp.define("downcase") { _, args in
689            try arity(args, 1...1, "downcase")
690            if case .integer(let c) = args[0] { return .integer(Int(Unicode.Scalar(c).map { String($0).lowercased().unicodeScalars.first!.value } ?? UInt32(c))) }
691            return .string(try string(args[0]).lowercased())
692        }
693        lisp.define("capitalize") { _, args in
694            try arity(args, 1...1, "capitalize")
695            return .string(try string(args[0]).capitalized)
696        }
697        lisp.define("substring") { _, args in
698            try arity(args, 1...3, "substring")
699            let chars = Array(try string(args[0]))
700            func index(_ v: Sexp?, _ fallback: Int) throws -> Int {
701                guard let v, !isNil(v) else { return fallback }
702                let i = try int(v)
703                return i < 0 ? chars.count + i : i
704            }
705            let from = try index(args.count > 1 ? args[1] : nil, 0)
706            let to = try index(args.count > 2 ? args[2] : nil, chars.count)
707            guard from >= 0, to <= chars.count, from <= to else { throw Signal(message: "Args out of range") }
708            return .string(String(chars[from..<to]))
709        }
710        lisp.define("string-to-number") { _, args in
711            try arity(args, 1...2, "string-to-number")
712            return stringToNumber(try string(args[0]))
713        }
714        for name in ["number-to-string", "int-to-string"] {
715            lisp.define(name) { _, args in
716                try arity(args, 1...1, name)
717                return .string(printed(sexp(try number(args[0]))))
718            }
719        }
720        lisp.define("string-prefix-p") { _, args in
721            try arity(args, 2...3, "string-prefix-p")
722            return bool(try string(args[1]).hasPrefix(try string(args[0])))
723        }
724        lisp.define("string-suffix-p") { _, args in
725            try arity(args, 2...3, "string-suffix-p")
726            return bool(try string(args[1]).hasSuffix(try string(args[0])))
727        }
728        lisp.define("string-empty-p") { _, args in
729            try arity(args, 1...1, "string-empty-p")
730            return bool(try stringOrSymbol(args[0]).isEmpty)
731        }
732        lisp.define("string-trim") { _, args in
733            try arity(args, 1...1, "string-trim")
734            return .string(try string(args[0]).trimmingCharacters(in: .whitespacesAndNewlines))
735        }
736        lisp.define("split-string") { _, args in
737            try arity(args, 1...2, "split-string")
738            let s = try string(args[0])
739            if args.count == 2, !isNil(args[1]) {
740                let separator = try string(args[1])
741                let regex = try NSRegularExpression(pattern: separator)
742                let ns = s as NSString
743                var parts: [Sexp] = []
744                var start = 0
745                for m in regex.matches(in: s, range: NSRange(location: 0, length: ns.length)) where m.range.length > 0 {
746                    parts.append(.string(ns.substring(with: NSRange(location: start, length: m.range.location - start))))
747                    start = NSMaxRange(m.range)
748                }
749                parts.append(.string(ns.substring(from: start)))
750                return list(parts)
751            }
752            return list(s.split(whereSeparator: { " \t\n\r\u{0C}\u{0B}".contains($0) }).map { .string(String($0)) })
753        }
754    }
755
756    static func add(_ n: Number, _ k: Int) -> Number {
757        switch n {
758        case .int(let i): .int(i + k)
759        case .float(let d): .float(d + Double(k))
760        }
761    }
762
763    static func divide(_ a: Number, _ b: Number, floating: Bool) throws -> Number {
764        if !floating, case .int(let x) = a, case .int(let y) = b {
765            guard y != 0 else { throw Signal(message: "Arithmetic error") }
766            return .int(x / y)
767        }
768        return .float(a.double / b.double)
769    }
770
771    static func eq(_ a: Sexp, _ b: Sexp) -> Bool {
772        switch (normalized(a), normalized(b)) {
773        case (.symbol(let x), .symbol(let y)): x == y
774        case (.integer(let x), .integer(let y)): x == y
775        case (.float(let x), .float(let y)): x == y
776        default: false
777        }
778    }
779
780    /// Characters as integers and the empty list as nil, for comparing.
781    static func normalized(_ v: Sexp) -> Sexp {
782        switch v {
783        case .character(let c): .integer(c)
784        case .list(let items): items.isEmpty ? .nil : .list(items.map(normalized))
785        case .dotted(let items, let last): .dotted(items.map(normalized), normalized(last))
786        case .vector(let items): .vector(items.map(normalized))
787        default: v
788        }
789    }
790
791    static func sequence(_ v: Sexp) throws -> [Sexp] {
792        switch v {
793        case .string(let s): return s.unicodeScalars.map { .integer(Int($0.value)) }
794        case .vector(let items): return items
795        default: return try elements(v)
796        }
797    }
798
799    static func stringOrSymbol(_ v: Sexp) throws -> String {
800        if case .symbol(let s) = v { return s }
801        return try string(v)
802    }
803
804    /// What `concat` and `mapconcat` accept: strings, and lists or vectors of characters.
805    static func printedString(_ v: Sexp) throws -> String {
806        switch v {
807        case .string(let s): return s
808        case _ where isNil(v): return ""
809        case .list, .vector:
810            return String(String.UnicodeScalarView(try sequence(v).map { Unicode.Scalar(UInt32(try int($0))) ?? " " }))
811        default: throw Signal(message: "Wrong type argument: sequencep, \(v.description)")
812        }
813    }
814
815    /// `string-to-number` in base 10.
816    static func stringToNumber(_ s: String) -> Sexp {
817        let trimmed = s.drop { $0 == " " || $0 == "\t" || $0 == "\n" }
818        guard let r = trimmed.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?", options: .regularExpression) else { return .integer(0) }
819        let text = String(trimmed[r])
820        if text.range(of: "^[-+]?[0-9]+$", options: .regularExpression) != nil, let i = Int(text.hasPrefix("+") ? String(text.dropFirst()) : text) {
821            return .integer(i)
822        }
823        if text.range(of: "^[-+]?[0-9]+\\.$", options: .regularExpression) != nil, let i = Int(text.dropLast().replacingOccurrences(of: "+", with: "")) {
824            return .integer(i)
825        }
826        return .float(Double(text) ?? 0)
827    }
828
829    /// `format`.
830    static func format(_ args: [Sexp]) throws -> String {
831        let spec = Array(try string(args[0]))
832        var out = ""
833        var next = 1
834        var i = 0
835        func argument() throws -> Sexp {
836            guard next < args.count else { throw Signal(message: "Not enough arguments for format string") }
837            defer { next += 1 }
838            return args[next]
839        }
840        while i < spec.count {
841            let c = spec[i]
842            i += 1
843            guard c == "%" else {
844                out.append(c)
845                continue
846            }
847            var flags = ""
848            while i < spec.count, "-+ #0".contains(spec[i]) {
849                flags.append(spec[i])
850                i += 1
851            }
852            var width = ""
853            while i < spec.count, spec[i].isNumber {
854                width.append(spec[i])
855                i += 1
856            }
857            var precision: Int?
858            if i < spec.count, spec[i] == "." {
859                i += 1
860                var digits = ""
861                while i < spec.count, spec[i].isNumber {
862                    digits.append(spec[i])
863                    i += 1
864                }
865                precision = Int(digits) ?? 0
866            }
867            guard i < spec.count else { throw Signal(message: "Format string ends in middle of format specifier") }
868            let conversion = spec[i]
869            i += 1
870            var text: String
871            switch conversion {
872            case "%":
873                out.append("%")
874                continue
875            case "s", "S":
876                text = printed(try argument(), escape: conversion == "S")
877                if let precision { text = String(text.prefix(precision)) }
878            case "d", "o", "x", "X":
879                let value: Int
880                switch try number(try argument()) {
881                case .int(let n): value = n
882                case .float(let d):
883                    guard let n = Int(exactly: d.rounded(.towardZero)) else { throw Signal(message: "Arithmetic overflow") }
884                    value = n
885                }
886                text = String(format: "%" + flags + width + (precision.map { ".\($0)" } ?? "") + (conversion == "d" ? "ld" : "l" + String(conversion)), value)
887                out += text
888                continue
889            case "c":
890                text = Unicode.Scalar(UInt32(try int(try argument()))).map { String($0) } ?? ""
891            case "e", "f", "g":
892                let value = try number(try argument()).double
893                out += String(format: "%" + flags + width + (precision.map { ".\($0)" } ?? "") + String(conversion), value)
894                continue
895            default:
896                throw Signal(message: "Invalid format operation %\(conversion)")
897            }
898            let pad = max(0, (Int(width) ?? 0) - text.count)
899            out += flags.contains("-") ? text + String(repeating: " ", count: pad) : String(repeating: " ", count: pad) + text
900        }
901        return out
902    }
903}
904
905extension Sexp {
906    var character: Int? { if case .character(let c) = self { return c } else { return nil } }
907}
908
909extension LispReader {
910    /// The first form in `text` and the number of characters it spans, as `forward-sexp`
911    /// would read it.
912    public static func readFirst(_ text: String) throws -> (sexp: Sexp, length: Int) {
913        var reader = Reader(Array(text.unicodeScalars))
914        let sexp = try reader.form()
915        let consumed = String(String.UnicodeScalarView(reader.chars[..<reader.index]))
916        return (sexp, consumed.count)
917    }
918}