Sources/OrgCore/Config/Elisp.swift

1215 lines · 57014 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 unless `lexical` is set. A function or
   5/// form it doesn't have 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        /// The error symbol, by default from the message, and its data when known: what
  15        /// `condition-case` binds.
  16        public let symbol: String?
  17        public let data: [Sexp]?
  18        public var description: String { message }
  19
  20        public init(message: String, symbol: String? = nil, data: [Sexp]? = nil) {
  21            self.message = message
  22            self.symbol = symbol ?? Self.symbols.first(where: { message.hasPrefix($0.prefix) })?.symbol
  23            self.data = data ?? (message == "Arithmetic error" ? [] : nil)
  24        }
  25
  26        static let symbols: [(prefix: String, symbol: String)] = [
  27            ("Arithmetic error", "arith-error"), ("Args out of range", "args-out-of-range"), ("Invalid function", "invalid-function"),
  28            ("Symbol’s value as variable is void", "void-variable"), ("Wrong number of arguments", "wrong-number-of-arguments"),
  29            ("Wrong type argument", "wrong-type-argument"),
  30        ]
  31    }
  32
  33    /// What `condition-case` binds its variable to for an error whose data isn't known.
  34    static let unknownError = Sexp.symbol("\u{0}error")
  35
  36    public typealias Builtin = (Elisp, [Sexp]) throws -> Sexp
  37
  38    /// A set of bindings, shared by the closures created while it is in scope.
  39    final class Frame {
  40        var vars: [String: Sexp]
  41        init(_ vars: [String: Sexp] = [:]) { self.vars = vars }
  42    }
  43
  44    /// The global frame, then the visible local ones, innermost last.
  45    var scopes: [Frame] = [Frame()]
  46    /// `lexical-binding`: lambdas close over the local frames, and only special variables
  47    /// (the host's and `defvar`'s) are bound dynamically.
  48    public var lexical = false
  49    /// A variable with no value throws `Unsupported` rather than `void-variable`: Emacs may
  50    /// give it one, such as `fill-column`.
  51    public var unboundUnsupported = false
  52    /// Variables bound dynamically when `lexical` is set.
  53    var specials: Set<String> = []
  54    /// Under lexical binding, running a lambda list, which Emacs evaluates with dynamic binding:
  55    /// every variable is bound dynamically and lambdas capture nothing.
  56    private var dynamicOnly = false
  57    /// The functions `defun` defined, which may take closures.
  58    var defined: Set<String> = []
  59    /// Each closure's captured frames, by the id in its `(closure ID ARGS . BODY)` value.
  60    var closures: [[Frame]] = []
  61    /// The scopes of the callers of running closures, and the global values that dynamic
  62    /// bindings of special variables hide.
  63    private var hiddenScopes: [[Frame]] = []
  64    private var hiddenValues: [Sexp] = []
  65    /// Values held while a form evaluates: each call's evaluated arguments, innermost last.
  66    private var pending: [[Sexp]] = []
  67    /// The variable an in-place function's first argument named, for that function to read.
  68    private var inPlaceVariable: String?
  69    /// The syntax table regexps and case conversion use.
  70    var syntax = ElispSyntax.org {
  71        didSet { regexes = [:] }
  72    }
  73    private var functions: [String: Builtin] = [:]
  74    /// Forms the host defines, given their arguments unevaluated.
  75    private var forms: [String: Builtin] = [:]
  76    var steps = 0
  77    static let stepLimit = 1_000_000
  78    /// Nested evaluations, as `max-lisp-eval-depth` limits them.
  79    private var depth = 0
  80    static let depthLimit = 1600
  81    /// The most elements a list built at once may have.
  82    static let lengthLimit = 1_000_000
  83    /// What `princ` and the other printers wrote: the innermost `with-output-to-string`, or
  84    /// standard output.
  85    private var outputs: [String] = [""]
  86    /// What went to standard output.
  87    public var standardOutput: String { outputs[0] }
  88    /// What `message` wrote.
  89    public private(set) var messages = ""
  90    /// What the last `string-match` matched: each group's range in characters.
  91    var matchData: [Range<Int>?] = []
  92    var regexes: [String: ElispRegex] = [:]
  93
  94    public init() {
  95        Self.core(self)
  96        Self.library(self)
  97        Self.regexFunctions(self)
  98    }
  99
 100    /// Defines or replaces a function.
 101    public func define(_ name: String, _ function: @escaping Builtin) { functions[name] = function }
 102
 103    /// Defines a macro by its value: `form` gets the arguments unevaluated.
 104    public func defineForm(_ name: String, _ form: @escaping Builtin) { forms[name] = form }
 105
 106    /// Sets a global variable, which is special.
 107    public func set(_ name: String, _ value: Sexp) {
 108        scopes[0].vars[name] = value
 109        specials.insert(name)
 110    }
 111
 112    public func value(_ name: String) throws -> Sexp {
 113        for scope in scopes.reversed() {
 114            guard let v = scope.vars[name] else { continue }
 115            if v == Self.unknownError { throw Unsupported(what: "the data of this error") }
 116            return v
 117        }
 118        if unboundUnsupported { throw Unsupported(what: "variable \(name)") }
 119        throw Signal(message: "Symbol’s value as variable is void: \(name)", data: [.symbol(name)])
 120    }
 121
 122    /// Evaluates `body` with `bindings` added: in a new frame, or for special variables under
 123    /// lexical binding, as their global values until `body` returns.
 124    public func binding<T>(_ bindings: [String: Sexp], _ body: () throws -> T) rethrows -> T {
 125        try binding(Frame(bindings), body)
 126    }
 127
 128    func binding<T>(_ frame: Frame, _ body: () throws -> T) rethrows -> T {
 129        let dynamic = dynamicOnly ? Array(frame.vars.keys) : lexical ? frame.vars.keys.filter(specials.contains) : []
 130        var saved: [(String, Sexp?)] = []
 131        for name in dynamic {
 132            saved.append((name, scopes[0].vars[name]))
 133            if let old = scopes[0].vars[name] { hiddenValues.append(old) }
 134            scopes[0].vars[name] = frame.vars.removeValue(forKey: name)
 135        }
 136        scopes.append(frame)
 137        defer {
 138            scopes.removeLast()
 139            for (name, old) in saved.reversed() {
 140                scopes[0].vars[name] = old
 141                if old != nil { hiddenValues.removeLast() }
 142            }
 143        }
 144        return try body()
 145    }
 146
 147    func assign(_ name: String, _ v: Sexp) {
 148        for scope in scopes.reversed() where scope.vars[name] != nil {
 149            scope.vars[name] = v
 150            return
 151        }
 152        scopes[0].vars[name] = v
 153    }
 154
 155    /// The ids in `closures` of functions made under dynamic binding, which capture nothing.
 156    var dynamicClosures: Set<Int> = []
 157
 158    /// A lambda as `function` makes it: a closure over the local frames under lexical
 159    /// binding, else one that captures nothing. Emacs 31 makes both function objects, not lists.
 160    func closure(_ lambda: Sexp) -> Sexp {
 161        guard case .list(let items) = lambda, items.first == .symbol("lambda"), items.count >= 2 else { return lambda }
 162        if lexical, !dynamicOnly {
 163            closures.append(Array(scopes.dropFirst()))
 164        } else {
 165            closures.append([])
 166            dynamicClosures.insert(closures.count - 1)
 167        }
 168        return .list([.symbol("closure"), .integer(closures.count - 1)] + items.dropFirst())
 169    }
 170
 171    static func isClosure(_ v: Sexp) -> Bool {
 172        if case .list(let items) = v, items.count >= 3, items[0] == .symbol("closure"), items[1].integer != nil { return true }
 173        return false
 174    }
 175
 176    /// Builtins that may take closures as arguments, from the given position on: those that
 177    /// call them or only hold them. Emacs's closures aren't lists, as they are here.
 178    static let closureArguments: [String: Int] = [
 179        "funcall": 0, "apply": 0, "mapcar": 0, "mapc": 0, "mapconcat": 0, "seq-map": 0, "seq-filter": 0, "seq-remove": 0,
 180        "seq-reduce": 0, "cl-reduce": 0, "cl-remove-if": 0, "cl-remove-if-not": 0, "cl-find": 1, "cl-position": 1, "sort": 0,
 181        "replace-regexp-in-string": 1, "org-lookup-first": 3, "org-lookup-last": 3, "org-lookup-all": 3, "list": 0, "identity": 0, "ignore": 0, "null": 0, "not": 0,
 182    ]
 183    /// Builtins that compare or print what lists hold.
 184    static let closureInspectors: Set<String> = [
 185        "equal", "eq", "eql", "member", "memq", "memql", "assoc", "assq", "delete", "delq", "delete-dups", "seq-uniq",
 186        "format", "format-message", "message", "error", "user-error", "prin1-to-string", "princ", "prin1", "print",
 187    ]
 188
 189    /// Refuses a builtin call that would look inside a closure.
 190    func refuseClosures(_ name: String, _ args: [Sexp]) throws {
 191        guard !closures.isEmpty, !defined.contains(name) else { return }
 192        for (i, arg) in args.enumerated() {
 193            if Self.isClosure(arg) ? i < Self.closureArguments[name] ?? .max : Self.closureInspectors.contains(name) && Self.containsClosure(arg) {
 194                throw Unsupported(what: "\(name) on a closure")
 195            }
 196        }
 197    }
 198
 199    /// Whether `v` contains a closure, which Emacs prints in a form this evaluator doesn't.
 200    static func containsClosure(_ v: Sexp) -> Bool {
 201        switch v {
 202        case .list(let items): isClosure(v) || items.contains(where: containsClosure)
 203        case .dotted(let items, let last): items.contains(where: containsClosure) || containsClosure(last)
 204        case .vector(let items): items.contains(where: containsClosure)
 205        default: false
 206        }
 207    }
 208
 209    /// The variable named by the first argument of the function being called from `eval`, read
 210    /// once.
 211    func takeInPlaceVariable() -> String? {
 212        defer { inPlaceVariable = nil }
 213        return inPlaceVariable
 214    }
 215
 216    /// Refuses an in-place change to `v` when another binding, list or pending argument may
 217    /// share its cells, which Emacs would change too: any value holding a list that ends like
 218    /// `v`, or an equal vector or string. `variable`'s innermost binding is the one `eval`
 219    /// updates after the call.
 220    func refuseShared(_ v: Sexp, variable: String?, _ name: String) throws {
 221        let matches: (Sexp) -> Bool
 222        switch v {
 223        case .list(let items):
 224            guard let last = items.last.map(Self.normalized) else { return }
 225            matches = { if case .list(let xs) = $0, let l = xs.last { Self.normalized(l) == last } else { false } }
 226        case .dotted(let items, let tail):
 227            let last = Self.normalized(items.last!)
 228            matches = { if case .dotted(let xs, let t) = $0 { t == tail && Self.normalized(xs.last!) == last } else { false } }
 229        case .vector, .string:
 230            matches = { $0 == v }
 231        default:
 232            return
 233        }
 234        func contains(_ x: Sexp) -> Bool {
 235            if matches(x) { return true }
 236            switch x {
 237            case .list(let items), .vector(let items): return items.contains(where: contains)
 238            case .dotted(let items, let last): return items.contains(where: contains) || contains(last)
 239            default: return false
 240            }
 241        }
 242        let owner = variable.flatMap { name in scopes.last { $0.vars[name] != nil } }
 243        var seen: Set<ObjectIdentifier> = []
 244        for frame in (hiddenScopes + [scopes] + closures).joined() where seen.insert(ObjectIdentifier(frame)).inserted {
 245            for (key, value) in frame.vars where !(frame === owner && key == variable) && contains(value) {
 246                throw Unsupported(what: "\(name) on a list another value shares")
 247            }
 248        }
 249        if (hiddenValues + pending.dropLast().joined()).contains(where: contains) { throw Unsupported(what: "\(name) on a list another value shares") }
 250    }
 251
 252    // MARK: - Values
 253
 254    public static let t = Sexp.symbol("t")
 255
 256    public static func isNil(_ v: Sexp) -> Bool { v == .nil || v == .list([]) }
 257    public static func bool(_ b: Bool) -> Sexp { b ? t : .nil }
 258    static func list(_ items: [Sexp]) -> Sexp { items.isEmpty ? .nil : .list(items) }
 259
 260    static func cons(_ a: Sexp, _ b: Sexp) -> Sexp {
 261        switch b {
 262        case .list(let items): .list([a] + items)
 263        case .dotted(let items, let last): .dotted([a] + items, last)
 264        case _ where isNil(b): .list([a])
 265        default: .dotted([a], b)
 266        }
 267    }
 268
 269    static func car(_ v: Sexp) throws -> Sexp {
 270        if isClosure(v) { throw Unsupported(what: "car on a closure") }
 271        return switch v {
 272        case .list(let items): items.first ?? .nil
 273        case .dotted(let items, _): items[0]
 274        case _ where isNil(v): .nil
 275        default: throw Signal(message: "Wrong type argument: listp, \(v.description)", data: [.symbol("listp"), v])
 276        }
 277    }
 278
 279    static func cdr(_ v: Sexp) throws -> Sexp {
 280        if isClosure(v) { throw Unsupported(what: "cdr on a closure") }
 281        return switch v {
 282        case .list(let items): list(Array(items.dropFirst()))
 283        case .dotted(let items, let last): items.count == 1 ? last : .dotted(Array(items.dropFirst()), last)
 284        case _ where isNil(v): .nil
 285        default: throw Signal(message: "Wrong type argument: listp, \(v.description)", data: [.symbol("listp"), v])
 286        }
 287    }
 288
 289    /// A proper list's elements.
 290    static func elements(_ v: Sexp) throws -> [Sexp] {
 291        if isClosure(v) { throw Unsupported(what: "a closure as a list") }
 292        if case .list(let items) = v { return items }
 293        if isNil(v) { return [] }
 294        throw Signal(message: "Wrong type argument: listp, \(v.description)")
 295    }
 296
 297    enum Number {
 298        case int(Int), float(Double)
 299        var double: Double {
 300            switch self {
 301            case .int(let i): Double(i)
 302            case .float(let d): d
 303            }
 304        }
 305    }
 306
 307    static func number(_ v: Sexp) throws -> Number {
 308        switch v {
 309        case .integer(let i): return .int(i)
 310        case .float(let d): return .float(d)
 311        case .character(let c): return .int(c)
 312        default: throw Signal(message: "Wrong type argument: number-or-marker-p, \(v.description)")
 313        }
 314    }
 315
 316    static func int(_ v: Sexp) throws -> Int {
 317        switch v {
 318        case .integer(let i): return i
 319        case .character(let c): return c
 320        default: throw Signal(message: "Wrong type argument: integerp, \(v.description)")
 321        }
 322    }
 323
 324    static func string(_ v: Sexp) throws -> String {
 325        guard case .string(let s) = v else { throw Signal(message: "Wrong type argument: stringp, \(v.description)") }
 326        return s
 327    }
 328
 329    static func sexp(_ n: Number) -> Sexp {
 330        switch n {
 331        case .int(let i): .integer(i)
 332        case .float(let d): .float(d)
 333        }
 334    }
 335
 336    /// `prin1-to-string`, or `princ` when `escape` is false.
 337    public static func printed(_ v: Sexp, escape: Bool = false) -> String {
 338        switch v {
 339        case .string(let s): return escape ? "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" : s
 340        case .float(let d): return floatText(d)
 341        case .character(let c): return String(c)
 342        case .list(let items) where items.isEmpty: return "nil"
 343        case .list(let items): return "(" + items.map { printed($0, escape: escape) }.joined(separator: " ") + ")"
 344        case .dotted(let items, let last): return "(" + items.map { printed($0, escape: escape) }.joined(separator: " ") + " . " + printed(last, escape: escape) + ")"
 345        case .vector(let items): return "[" + items.map { printed($0, escape: escape) }.joined(separator: " ") + "]"
 346        default: return v.description
 347        }
 348    }
 349
 350    /// Emacs's float printing: the shortest text that reads back, with `.0` on whole numbers.
 351    static func floatText(_ d: Double) -> String {
 352        if d.isNaN { return d.sign == .minus ? "-0.0e+NaN" : "0.0e+NaN" }
 353        if d.isInfinite { return d < 0 ? "-1.0e+INF" : "1.0e+INF" }
 354        var text = "\(d)"
 355        if let e = text.firstIndex(of: "e") {
 356            let mantissa = text[..<e]
 357            var exponent = String(text[text.index(after: e)...])
 358            if !exponent.hasPrefix("-"), !exponent.hasPrefix("+") { exponent = "+" + exponent }
 359            text = mantissa.hasSuffix(".0") ? String(mantissa.dropLast(2)) + "e" + exponent : mantissa + "e" + exponent
 360        }
 361        return text
 362    }
 363
 364    // MARK: - Evaluation
 365
 366    /// Less than 128 KB of this thread's stack left: background threads have only 512 KB.
 367    static func stackIsLow() -> Bool {
 368        var marker = 0
 369        let here = withUnsafeMutablePointer(to: &marker) { UInt(bitPattern: $0) }
 370        let top = UInt(bitPattern: pthread_get_stackaddr_np(pthread_self()))
 371        let size = UInt(pthread_get_stacksize_np(pthread_self()))
 372        return here < top - size + 128 * 1024
 373    }
 374
 375    public func eval(_ form: Sexp) throws -> Sexp {
 376        steps += 1
 377        if steps > Self.stepLimit { throw Signal(message: "Evaluation took too long") }
 378        depth += 1
 379        defer { depth -= 1 }
 380        if depth > Self.depthLimit || Self.stackIsLow() { throw Signal(message: "Lisp nesting exceeds ‘max-lisp-eval-depth’") }
 381        switch form {
 382        case .symbol(let name):
 383            if name == "nil" || name == "t" || name.hasPrefix(":") { return form }
 384            return try value(name)
 385        case .character(let c): return .integer(c)
 386        case .list(let items):
 387            guard let head = items.first else { return .nil }
 388            guard case .symbol(let name) = head else {
 389                if case .list(let lambda) = head, lambda.first == .symbol("lambda") {
 390                    return try call(closure(head), try evaluated(items.dropFirst()))
 391                }
 392                throw Signal(message: "Invalid function: \(head.description)")
 393            }
 394            let args = Array(items.dropFirst())
 395            if let value = try special(name, args) { return value }
 396            if let form = forms[name] { return try form(self, args) }
 397            // The function first, so an unknown one, or a macro this evaluator lacks, is
 398            // unsupported rather than an error from its arguments.
 399            guard let function = functions[name] else { throw Unsupported(what: "function \(name)") }
 400            pending.append([])
 401            defer { pending.removeLast() }
 402            for arg in args { pending[pending.count - 1].append(try eval(arg)) }
 403            let values = pending[pending.count - 1]
 404            try refuseClosures(name, values)
 405            var variable: String?
 406            if case .symbol(let s)? = args.first, s != "nil", s != "t", !s.hasPrefix(":") { variable = s }
 407            inPlaceVariable = variable
 408            let result = try function(self, values)
 409            inPlaceVariable = nil
 410            if let variable, let after = Self.afterInPlace(name, values, result) { assign(variable, after) }
 411            return result
 412        case .dotted: throw Signal(message: "Invalid function")
 413        default: return form
 414        }
 415    }
 416
 417    /// `forms`' values, held as pending while the later ones evaluate.
 418    func evaluated(_ forms: some Collection<Sexp>) throws -> [Sexp] {
 419        pending.append([])
 420        defer { pending.removeLast() }
 421        for form in forms { pending[pending.count - 1].append(try eval(form)) }
 422        return pending[pending.count - 1]
 423    }
 424
 425    func progn(_ body: some Collection<Sexp>) throws -> Sexp {
 426        var result = Sexp.nil
 427        for form in body { result = try eval(form) }
 428        return result
 429    }
 430
 431    /// Special forms and macros; nil when `name` is an ordinary function.
 432    private func special(_ name: String, _ args: [Sexp]) throws -> Sexp? {
 433        switch name {
 434        case "quote":
 435            return args.first ?? .nil
 436        case "function":
 437            return closure(args.first ?? .nil)
 438        case "lambda":
 439            return closure(.list([.symbol("lambda")] + args))
 440        case "progn":
 441            return try progn(args)
 442        case "prog1":
 443            guard let first = args.first else { return .nil }
 444            pending.append([try eval(first)])
 445            defer { pending.removeLast() }
 446            _ = try progn(args.dropFirst())
 447            return pending[pending.count - 1][0]
 448        case "if":
 449            guard args.count >= 2 else { throw Signal(message: "Wrong number of arguments: if") }
 450            return Self.isNil(try eval(args[0])) ? try progn(args.dropFirst(2)) : try eval(args[1])
 451        case "when", "unless":
 452            guard let test = args.first else { return .nil }
 453            return Self.isNil(try eval(test)) == (name == "unless") ? try progn(args.dropFirst()) : .nil
 454        case "cond":
 455            for clause in args {
 456                let parts = try Self.elements(clause)
 457                guard let test = parts.first else { continue }
 458                let value = try eval(test)
 459                if !Self.isNil(value) { return parts.count == 1 ? value : try progn(parts.dropFirst()) }
 460            }
 461            return .nil
 462        case "and":
 463            var value = Self.t
 464            for form in args {
 465                value = try eval(form)
 466                if Self.isNil(value) { return .nil }
 467            }
 468            return value
 469        case "or":
 470            for form in args {
 471                let value = try eval(form)
 472                if !Self.isNil(value) { return value }
 473            }
 474            return .nil
 475        case "let", "let*":
 476            guard let first = args.first else { return .nil }
 477            var specs: [(String, Sexp?)] = []
 478            for binding in try Self.elements(first) {
 479                if case .symbol(let s) = binding {
 480                    specs.append((s, nil))
 481                } else {
 482                    let parts = try Self.elements(binding)
 483                    guard case .symbol(let s)? = parts.first else { throw Signal(message: "Bad binding") }
 484                    specs.append((s, parts.count > 1 ? parts[1] : nil))
 485                }
 486            }
 487            if name == "let" {
 488                let values = try evaluated(specs.map { $0.1 ?? .nil })
 489                var bindings: [String: Sexp] = [:]
 490                for ((variable, _), value) in zip(specs, values) { bindings[variable] = value }
 491                return try binding(bindings) { try progn(args.dropFirst()) }
 492            }
 493            // `let*` nests a binding per variable, so a closure sees the ones before it.
 494            func bind(_ rest: ArraySlice<(String, Sexp?)>) throws -> Sexp {
 495                guard let (variable, form) = rest.first else { return try progn(args.dropFirst()) }
 496                let value = try form.map(eval) ?? .nil
 497                return try binding([variable: value]) { try bind(rest.dropFirst()) }
 498            }
 499            return try bind(specs[...])
 500        case "setq":
 501            var value = Sexp.nil
 502            var i = 0
 503            while i + 1 < args.count {
 504                guard case .symbol(let variable) = args[i] else { throw Signal(message: "Bad setq") }
 505                value = try eval(args[i + 1])
 506                assign(variable, value)
 507                i += 2
 508            }
 509            return value
 510        case "push", "pop":
 511            guard case .symbol(let variable)? = (name == "push" ? args.dropFirst().first : args.first) else { throw Unsupported(what: "\(name) on a place") }
 512            let list = try value(variable)
 513            if name == "pop" {
 514                assign(variable, try Self.cdr(list))
 515                return try Self.car(list)
 516            }
 517            if Self.isClosure(list) { throw Unsupported(what: "push on a closure") }
 518            let pushed = Self.cons(try eval(args[0]), list)
 519            assign(variable, pushed)
 520            return pushed
 521        case "while":
 522            guard let test = args.first else { return .nil }
 523            while !Self.isNil(try eval(test)) { _ = try progn(args.dropFirst()) }
 524            return .nil
 525        case "dolist", "dotimes":
 526            let spec = try args.first.map(Self.elements) ?? []
 527            guard case .symbol(let variable)? = spec.first, spec.count >= 2 else { throw Signal(message: "Bad \(name)") }
 528            let source = try eval(spec[1])
 529            let items = name == "dolist" ? try Self.elements(source) : []
 530            let count = name == "dolist" ? items.count : max(0, try Self.int(source))
 531            pending.append([source])
 532            defer { pending.removeLast() }
 533            // A new binding each time round, as closures over the variable see it.
 534            for i in 0..<count {
 535                steps += 1
 536                if steps > Self.stepLimit { throw Signal(message: "Evaluation took too long") }
 537                _ = try binding([variable: name == "dolist" ? items[i] : .integer(i)]) { try progn(args.dropFirst()) }
 538            }
 539            if spec.count > 2 {
 540                return try binding([variable: name == "dotimes" ? .integer(count) : .nil]) { try eval(spec[2]) }
 541            }
 542            return .nil
 543        case "with-output-to-string":
 544            outputs.append("")
 545            do {
 546                _ = try progn(args)
 547            } catch {
 548                outputs.removeLast()
 549                throw error
 550            }
 551            return .string(outputs.removeLast())
 552        case "ignore-errors":
 553            do { return try progn(args) } catch is Signal { return .nil }
 554        case "condition-case":
 555            guard args.count >= 2 else { throw Signal(message: "Bad condition-case") }
 556            do {
 557                return try eval(args[1])
 558            } catch let signal as Signal {
 559                // Every error has the `error` condition as well as its own.
 560                let conditions = ["error", "t"] + (signal.symbol.map { [$0] } ?? [])
 561                for handler in args.dropFirst(2) {
 562                    let parts = try Self.elements(handler)
 563                    guard let condition = parts.first else { continue }
 564                    let names = ((try? Self.elements(condition)) ?? [condition]).compactMap(\.symbol)
 565                    guard names.contains(where: conditions.contains) else {
 566                        if signal.symbol == nil, !names.isEmpty { throw Unsupported(what: "condition-case on \(names.joined(separator: " "))") }
 567                        continue
 568                    }
 569                    var bindings: [String: Sexp] = [:]
 570                    if let variable = args[0].symbol, variable != "nil" {
 571                        bindings[variable] = signal.symbol.flatMap { symbol in signal.data.map { .list([.symbol(symbol)] + $0) } } ?? Self.unknownError
 572                    }
 573                    return try binding(bindings) { try progn(parts.dropFirst()) }
 574                }
 575                throw signal
 576            }
 577        default:
 578            return try moreSpecial(name, args)
 579        }
 580    }
 581
 582    /// Calls a function value: a symbol naming one, or a lambda list.
 583    public func call(_ function: Sexp, _ args: [Sexp]) throws -> Sexp {
 584        switch function {
 585        case .symbol(let name): return try callNamed(name, args)
 586        case .list(let items) where Self.isClosure(function):
 587            guard closures.indices.contains(items[1].integer!) else { throw Unsupported(what: "a closure as a list") }
 588            if dynamicClosures.contains(items[1].integer!) { return try call(.list([.symbol("lambda")] + items.dropFirst(2)), args) }
 589            let saved = dynamicOnly
 590            dynamicOnly = false
 591            defer { dynamicOnly = saved }
 592            return try apply(parameters: items[2], body: items.dropFirst(3), args, scope: closures[items[1].integer!])
 593        case .list(let items) where items.first == .symbol("lambda") && items.count >= 2:
 594            guard lexical else { return try apply(parameters: items[1], body: items.dropFirst(2), args, scope: nil) }
 595            // Under lexical binding, a lambda list runs outside the caller's local frames, with
 596            // dynamic binding.
 597            let saved = dynamicOnly
 598            dynamicOnly = true
 599            defer { dynamicOnly = saved }
 600            return try apply(parameters: items[1], body: items.dropFirst(2), args, scope: [])
 601        default:
 602            throw Signal(message: "Invalid function: \(function.description)")
 603        }
 604    }
 605
 606    /// Binds `parameters` to `args` and runs `body`, in `scope`'s frames instead of the
 607    /// caller's when given.
 608    private func apply(parameters: Sexp, body: ArraySlice<Sexp>, _ args: [Sexp], scope: [Frame]?) throws -> Sexp {
 609        var bindings: [String: Sexp] = [:]
 610        var mode = "required"
 611        var i = 0
 612        for parameter in try Self.elements(parameters) {
 613            guard case .symbol(let p) = parameter else { throw Signal(message: "Bad lambda list") }
 614            if p == "&optional" || p == "&rest" {
 615                mode = p
 616                continue
 617            }
 618            if mode == "&rest" {
 619                bindings[p] = Self.list(Array(args.dropFirst(i)))
 620                i = args.count
 621            } else if i < args.count {
 622                bindings[p] = args[i]
 623                i += 1
 624            } else if mode == "&optional" {
 625                bindings[p] = .nil
 626            } else {
 627                throw Signal(message: "Wrong number of arguments")
 628            }
 629        }
 630        if i < args.count { throw Signal(message: "Wrong number of arguments") }
 631        guard let scope else { return try binding(bindings) { try progn(body) } }
 632        let caller = scopes
 633        hiddenScopes.append(caller)
 634        scopes = [scopes[0]] + scope
 635        defer {
 636            scopes = caller
 637            hiddenScopes.removeLast()
 638        }
 639        return try binding(bindings) { try progn(body) }
 640    }
 641
 642    func callNamed(_ name: String, _ args: [Sexp]) throws -> Sexp {
 643        guard let function = functions[name] else { throw Unsupported(what: "function \(name)") }
 644        try refuseClosures(name, args)
 645        inPlaceVariable = nil
 646        return try function(self, args)
 647    }
 648
 649    static func arity(_ args: [Sexp], _ range: ClosedRange<Int>, _ name: String) throws {
 650        guard range.contains(args.count) else { throw Signal(message: "Wrong number of arguments: \(name), \(args.count)") }
 651    }
 652
 653    // MARK: - Functions
 654
 655    private static func core(_ lisp: Elisp) {
 656        func arithmetic(_ name: String, identity: Int, _ intOp: @escaping (Int, Int) -> (Int, Bool), _ floatOp: @escaping (Double, Double) -> Double) {
 657            lisp.define(name) { _, args in
 658                let numbers = try args.map(number)
 659                guard var result = numbers.first else { return .integer(identity) }
 660                if numbers.count == 1, name == "-" {
 661                    switch result {
 662                    case .int(let i):
 663                        guard i != .min else { throw Unsupported(what: "integer size") }
 664                        return .integer(-i)
 665                    case .float(let d): return .float(-d)
 666                    }
 667                }
 668                for n in numbers.dropFirst() {
 669                    switch (result, n) {
 670                    case (.int(let a), .int(let b)):
 671                        let (value, overflow) = intOp(a, b)
 672                        if overflow { throw Unsupported(what: "integer size") }
 673                        result = .int(value)
 674                    default:
 675                        result = .float(floatOp(result.double, n.double))
 676                    }
 677                }
 678                return sexp(result)
 679            }
 680        }
 681        arithmetic("+", identity: 0, { $0.addingReportingOverflow($1) }, +)
 682        arithmetic("-", identity: 0, { $0.subtractingReportingOverflow($1) }, -)
 683        arithmetic("*", identity: 1, { $0.multipliedReportingOverflow(by: $1) }, *)
 684        lisp.define("/") { _, args in
 685            try arity(args, 1...Int.max, "/")
 686            let numbers = try args.map(number)
 687            let floating = numbers.contains { if case .float = $0 { true } else { false } }
 688            if numbers.count == 1 { return try sexp(divide(.int(1), numbers[0], floating: floating)) }
 689            var result = numbers[0]
 690            for n in numbers.dropFirst() { result = try divide(result, n, floating: floating) }
 691            return sexp(result)
 692        }
 693        lisp.define("%") { _, args in
 694            try arity(args, 2...2, "%")
 695            let b = try int(args[1])
 696            guard b != 0 else { throw Signal(message: "Arithmetic error") }
 697            let (r, overflow) = try int(args[0]).remainderReportingOverflow(dividingBy: b)
 698            if overflow { throw Unsupported(what: "integer size") }
 699            return .integer(r)
 700        }
 701        lisp.define("mod") { _, args in
 702            try arity(args, 2...2, "mod")
 703            switch (try number(args[0]), try number(args[1])) {
 704            case (.int(let a), .int(let b)):
 705                guard b != 0 else { throw Signal(message: "Arithmetic error") }
 706                let (r, overflow) = a.remainderReportingOverflow(dividingBy: b)
 707                if overflow { throw Unsupported(what: "integer size") }
 708                return .integer(r != 0 && (r < 0) != (b < 0) ? r + b : r)
 709            case (let a, let b):
 710                let r = fmod(a.double, b.double)
 711                return .float(r != 0 && (r < 0) != (b.double < 0) ? r + b.double : r)
 712            }
 713        }
 714        lisp.define("1+") { _, args in try arity(args, 1...1, "1+"); return try sexp(add(number(args[0]), 1)) }
 715        lisp.define("1-") { _, args in try arity(args, 1...1, "1-"); return try sexp(add(number(args[0]), -1)) }
 716        lisp.define("abs") { _, args in
 717            try arity(args, 1...1, "abs")
 718            switch try number(args[0]) {
 719            case .int(let i):
 720                guard i != .min else { throw Unsupported(what: "integer size") }
 721                return .integer(abs(i))
 722            case .float(let d): return .float(abs(d))
 723            }
 724        }
 725        for name in ["max", "min"] {
 726            lisp.define(name) { _, args in
 727                try arity(args, 1...Int.max, name)
 728                let numbers = try args.map(number)
 729                let floating = numbers.contains { if case .float = $0 { true } else { false } }
 730                var best = numbers[0]
 731                for n in numbers.dropFirst() where name == "max" ? n.double > best.double : n.double < best.double { best = n }
 732                return floating ? .float(best.double) : sexp(best)
 733            }
 734        }
 735        for name in ["floor", "ceiling", "round", "truncate"] {
 736            lisp.define(name) { _, args in
 737                try arity(args, 1...2, name)
 738                var x = try number(args[0]).double
 739                if args.count == 2, !isNil(args[1]) {
 740                    let divisor = try number(args[1]).double
 741                    guard divisor != 0 else { throw Signal(message: "Arithmetic error") }
 742                    x /= divisor
 743                } else if case .int(let i) = try number(args[0]) {
 744                    return .integer(i)
 745                }
 746                let rule: FloatingPointRoundingRule = switch name {
 747                case "floor": .down
 748                case "ceiling": .up
 749                case "round": .toNearestOrEven
 750                default: .towardZero
 751                }
 752                guard let i = Int(exactly: x.rounded(rule)) else { throw Signal(message: "Arithmetic overflow error") }
 753                return .integer(i)
 754            }
 755        }
 756        lisp.define("float") { _, args in try arity(args, 1...1, "float"); return .float(try number(args[0]).double) }
 757        for (name, op) in [("=", { (a: Double, b: Double) in a == b }), ("<", { $0 < $1 }), (">", { $0 > $1 }), ("<=", { $0 <= $1 }), (">=", { $0 >= $1 })] {
 758            lisp.define(name) { _, args in
 759                try arity(args, 1...Int.max, name)
 760                let numbers = try args.map(number)
 761                for (a, b) in zip(numbers, numbers.dropFirst()) {
 762                    let holds: Bool = switch (a, b) {
 763                    case (.int(let x), .int(let y)): op(Double(x), Double(y)) && (name != "=" || x == y)
 764                    default: op(a.double, b.double)
 765                    }
 766                    if !holds { return .nil }
 767                }
 768                return t
 769            }
 770        }
 771        lisp.define("/=") { _, args in
 772            try arity(args, 2...2, "/=")
 773            return bool(try number(args[0]).double != (try number(args[1])).double)
 774        }
 775        lisp.define("zerop") { _, args in try arity(args, 1...1, "zerop"); return bool(try number(args[0]).double == 0) }
 776        lisp.define("not") { _, args in try arity(args, 1...1, "not"); return bool(isNil(args[0])) }
 777        lisp.define("null") { _, args in try arity(args, 1...1, "null"); return bool(isNil(args[0])) }
 778        lisp.define("eq") { _, args in try arity(args, 2...2, "eq"); return bool(eq(args[0], args[1])) }
 779        lisp.define("eql") { _, args in try arity(args, 2...2, "eql"); return bool(eq(args[0], args[1])) }
 780        lisp.define("equal") { _, args in try arity(args, 2...2, "equal"); return bool(normalized(args[0]) == normalized(args[1])) }
 781        lisp.define("numberp") { _, args in
 782            try arity(args, 1...1, "numberp")
 783            return bool((try? number(args[0])) != nil && args[0].character == nil)
 784        }
 785        lisp.define("integerp") { _, args in try arity(args, 1...1, "integerp"); return bool(args[0].integer != nil) }
 786        lisp.define("floatp") { _, args in
 787            try arity(args, 1...1, "floatp")
 788            if case .float = args[0] { return t }
 789            return .nil
 790        }
 791        lisp.define("stringp") { _, args in try arity(args, 1...1, "stringp"); return bool(args[0].string != nil) }
 792        lisp.define("listp") { _, args in
 793            try arity(args, 1...1, "listp")
 794            switch args[0] {
 795            case .list, .dotted: return t
 796            default: return bool(isNil(args[0]))
 797            }
 798        }
 799        lisp.define("consp") { _, args in
 800            try arity(args, 1...1, "consp")
 801            switch args[0] {
 802            case .list(let items): return bool(!items.isEmpty)
 803            case .dotted: return t
 804            default: return .nil
 805            }
 806        }
 807        lisp.define("symbolp") { _, args in try arity(args, 1...1, "symbolp"); return bool(args[0].symbol != nil || isNil(args[0])) }
 808
 809        // Lists.
 810        lisp.define("car") { _, args in try arity(args, 1...1, "car"); return try car(args[0]) }
 811        lisp.define("cdr") { _, args in try arity(args, 1...1, "cdr"); return try cdr(args[0]) }
 812        lisp.define("cadr") { _, args in try arity(args, 1...1, "cadr"); return try car(cdr(args[0])) }
 813        lisp.define("cddr") { _, args in try arity(args, 1...1, "cddr"); return try cdr(cdr(args[0])) }
 814        lisp.define("cons") { _, args in try arity(args, 2...2, "cons"); return cons(args[0], args[1]) }
 815        lisp.define("list") { _, args in list(args) }
 816        lisp.define("nth") { _, args in
 817            try arity(args, 2...2, "nth")
 818            var v = args[1]
 819            for _ in 0..<max(0, try int(args[0])) { v = try cdr(v) }
 820            return try car(v)
 821        }
 822        lisp.define("nthcdr") { _, args in
 823            try arity(args, 2...2, "nthcdr")
 824            var v = args[1]
 825            for _ in 0..<max(0, try int(args[0])) { v = try cdr(v) }
 826            return v
 827        }
 828        lisp.define("elt") { _, args in
 829            try arity(args, 2...2, "elt")
 830            let items = try sequence(args[0])
 831            let i = try int(args[1])
 832            if case .list = args[0], i >= items.count { return .nil }
 833            guard items.indices.contains(i) else { throw Signal(message: "Args out of range") }
 834            return items[i]
 835        }
 836        lisp.define("aref") { _, args in
 837            try arity(args, 2...2, "aref")
 838            let items = try sequence(args[0])
 839            let i = try int(args[1])
 840            guard items.indices.contains(i) else { throw Signal(message: "Args out of range") }
 841            return items[i]
 842        }
 843        lisp.define("append") { _, args in
 844            guard let last = args.last else { return .nil }
 845            var items: [Sexp] = []
 846            for arg in args.dropLast() { items += try sequence(arg) }
 847            switch last {
 848            case .list(let rest): return .list(items + rest)
 849            case .dotted(let rest, let tail): return .dotted(items + rest, tail)
 850            case _ where isNil(last): return list(items)
 851            default: return items.isEmpty ? last : .dotted(items, last)
 852            }
 853        }
 854        lisp.define("length") { _, args in
 855            try arity(args, 1...1, "length")
 856            return .integer(try sequence(args[0]).count)
 857        }
 858        lisp.define("reverse") { _, args in
 859            try arity(args, 1...1, "reverse")
 860            if case .string(let s) = args[0] { return .string(String(s.reversed())) }
 861            return list(try elements(args[0]).reversed())
 862        }
 863        lisp.define("number-sequence") { _, args in
 864            try arity(args, 1...3, "number-sequence")
 865            let from = try int(args[0])
 866            guard args.count > 1, !isNil(args[1]) else { return .list([.integer(from)]) }
 867            let to = try int(args[1])
 868            let step = args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 1
 869            guard step != 0 else { throw Signal(message: "The increment can not be zero") }
 870            let span = Double(to) - Double(from)
 871            guard span / Double(step) < Double(Self.lengthLimit) else { throw Signal(message: "Too many elements for number-sequence") }
 872            return list(Array(stride(from: from, through: to, by: step)).map { .integer($0) })
 873        }
 874        for name in ["memq", "member", "memql"] {
 875            lisp.define(name) { _, args in
 876                try arity(args, 2...2, name)
 877                var rest = args[1]
 878                while case .list(let items) = rest, let first = items.first {
 879                    if name == "member" ? normalized(first) == normalized(args[0]) : eq(first, args[0]) { return rest }
 880                    rest = list(Array(items.dropFirst()))
 881                }
 882                return .nil
 883            }
 884        }
 885        for name in ["assoc", "assq"] {
 886            lisp.define(name) { _, args in
 887                try arity(args, 2...3, name)
 888                for pair in try elements(args[1]) {
 889                    guard let key = try? car(pair) else { continue }
 890                    if name == "assoc" ? normalized(key) == normalized(args[0]) : eq(key, args[0]) { return pair }
 891                }
 892                return .nil
 893            }
 894        }
 895        lisp.define("identity") { _, args in try arity(args, 1...1, "identity"); return args[0] }
 896        lisp.define("ignore") { _, _ in .nil }
 897        lisp.define("funcall") { lisp, args in
 898            try arity(args, 1...Int.max, "funcall")
 899            return try lisp.call(args[0], Array(args.dropFirst()))
 900        }
 901        lisp.define("apply") { lisp, args in
 902            try arity(args, 1...Int.max, "apply")
 903            let spread = args.count > 1 ? Array(args[1..<(args.count - 1)]) + (try elements(args[args.count - 1])) : []
 904            return try lisp.call(args[0], spread)
 905        }
 906        lisp.define("mapcar") { lisp, args in
 907            try arity(args, 2...2, "mapcar")
 908            return list(try sequence(args[1]).map { try lisp.call(args[0], [$0]) })
 909        }
 910        lisp.define("mapc") { lisp, args in
 911            try arity(args, 2...2, "mapc")
 912            for item in try sequence(args[1]) { _ = try lisp.call(args[0], [item]) }
 913            return args[1]
 914        }
 915        lisp.define("mapconcat") { lisp, args in
 916            try arity(args, 1...3, "mapconcat")
 917            let separator = args.count > 2 ? try string(args[2]) : ""
 918            return .string(try sequence(args[1]).map { try printedString(lisp.call(args[0], [$0])) }.joined(separator: separator))
 919        }
 920        lisp.define("delq") { _, args in
 921            try arity(args, 2...2, "delq")
 922            return list(try elements(args[1]).filter { !eq($0, args[0]) })
 923        }
 924        lisp.define("delete") { _, args in
 925            try arity(args, 2...2, "delete")
 926            return list(try elements(args[1]).filter { normalized($0) != normalized(args[0]) })
 927        }
 928        for name in ["error", "user-error"] {
 929            lisp.define(name) { _, args in
 930                let message = args.isEmpty ? "" : try format(args)
 931                throw Signal(message: message, symbol: name, data: [.string(message)])
 932            }
 933        }
 934
 935        // Printing.
 936        for (name, escape) in [("princ", false), ("prin1", true), ("print", true)] {
 937            lisp.define(name) { lisp, args in
 938                try arity(args, 1...2, name)
 939                let text = printed(args[0], escape: escape)
 940                lisp.outputs[lisp.outputs.count - 1] += name == "print" ? "\n" + text + "\n" : text
 941                return args[0]
 942            }
 943        }
 944        lisp.define("terpri") { lisp, _ in
 945            lisp.outputs[lisp.outputs.count - 1] += "\n"
 946            return t
 947        }
 948        lisp.define("message") { lisp, args in
 949            guard !args.isEmpty, !isNil(args[0]) else { return .nil }
 950            let text = try format(args)
 951            lisp.messages += text + "\n"
 952            return .string(text)
 953        }
 954        lisp.define("prin1-to-string") { _, args in
 955            try arity(args, 1...2, "prin1-to-string")
 956            return .string(printed(args[0], escape: args.count < 2 || isNil(args[1])))
 957        }
 958
 959        // Strings.
 960        lisp.define("concat") { _, args in .string(try args.map(printedString).joined()) }
 961        lisp.define("format") { _, args in .string(try format(args)) }
 962        lisp.define("format-message") { _, args in .string(try format(args)) }
 963        lisp.define("string=") { _, args in
 964            try arity(args, 2...2, "string=")
 965            return bool(try stringOrSymbol(args[0]) == (try stringOrSymbol(args[1])))
 966        }
 967        lisp.define("string-equal") { _, args in
 968            try arity(args, 2...2, "string-equal")
 969            return bool(try stringOrSymbol(args[0]) == (try stringOrSymbol(args[1])))
 970        }
 971        lisp.define("string<") { _, args in
 972            try arity(args, 2...2, "string<")
 973            return bool(Array(try stringOrSymbol(args[0]).unicodeScalars.map(\.value)).lexicographicallyPrecedes(try stringOrSymbol(args[1]).unicodeScalars.map(\.value)))
 974        }
 975        lisp.define("string-lessp") { lisp, args in try lisp.callNamed("string<", args) }
 976        lisp.define("upcase") { _, args in
 977            try arity(args, 1...1, "upcase")
 978            if case .integer(let c) = args[0] { return .integer(Int(String(try scalar(c)).uppercased().unicodeScalars.first!.value)) }
 979            return .string(try string(args[0]).uppercased())
 980        }
 981        lisp.define("downcase") { _, args in
 982            try arity(args, 1...1, "downcase")
 983            if case .integer(let c) = args[0] { return .integer(Int(String(try scalar(c)).lowercased().unicodeScalars.first!.value)) }
 984            return .string(try string(args[0]).lowercased())
 985        }
 986        // A letter is upcased after a character without word syntax, downcased after one with it.
 987        lisp.define("capitalize") { lisp, args in
 988            try arity(args, 1...1, "capitalize")
 989            let s = try string(args[0])
 990            guard s.unicodeScalars.allSatisfy(\.isASCII) else { throw Unsupported(what: "capitalize past ASCII") }
 991            var inWord = false
 992            var out = ""
 993            for c in s.unicodeScalars {
 994                out += inWord ? String(c).lowercased() : String(c).uppercased()
 995                inWord = lisp.syntax.isWord(c)
 996            }
 997            return .string(out)
 998        }
 999        lisp.define("substring") { _, args in
1000            try arity(args, 1...3, "substring")
1001            let chars = Array(try string(args[0]).unicodeScalars)
1002            func index(_ v: Sexp?, _ fallback: Int) throws -> Int {
1003                guard let v, !isNil(v) else { return fallback }
1004                let i = try int(v)
1005                return i < 0 ? chars.count + i : i
1006            }
1007            let from = try index(args.count > 1 ? args[1] : nil, 0)
1008            let to = try index(args.count > 2 ? args[2] : nil, chars.count)
1009            guard from >= 0, to <= chars.count, from <= to else { throw Signal(message: "Args out of range") }
1010            return .string(String(String.UnicodeScalarView(chars[from..<to])))
1011        }
1012        lisp.define("string-to-number") { _, args in
1013            try arity(args, 1...2, "string-to-number")
1014            return stringToNumber(try string(args[0]))
1015        }
1016        for name in ["number-to-string", "int-to-string"] {
1017            lisp.define(name) { _, args in
1018                try arity(args, 1...1, name)
1019                return .string(printed(sexp(try number(args[0]))))
1020            }
1021        }
1022        lisp.define("string-prefix-p") { _, args in
1023            try arity(args, 2...3, "string-prefix-p")
1024            return bool(try string(args[1]).hasPrefix(try string(args[0])))
1025        }
1026        lisp.define("string-suffix-p") { _, args in
1027            try arity(args, 2...3, "string-suffix-p")
1028            return bool(try string(args[1]).hasSuffix(try string(args[0])))
1029        }
1030        lisp.define("string-empty-p") { _, args in
1031            try arity(args, 1...1, "string-empty-p")
1032            return bool(try stringOrSymbol(args[0]).isEmpty)
1033        }
1034        lisp.define("string-trim") { _, args in
1035            try arity(args, 1...1, "string-trim")
1036            return .string(try string(args[0]).trimmingCharacters(in: .whitespacesAndNewlines))
1037        }
1038    }
1039
1040    static func add(_ n: Number, _ k: Int) throws -> Number {
1041        switch n {
1042        case .int(let i):
1043            let (sum, overflow) = i.addingReportingOverflow(k)
1044            if overflow { throw Unsupported(what: "integer size") }
1045            return .int(sum)
1046        case .float(let d): return .float(d + Double(k))
1047        }
1048    }
1049
1050    /// A character code as a character.
1051    static func scalar(_ code: Int) throws -> Unicode.Scalar {
1052        guard code >= 0, code <= 0x10FFFF, let scalar = Unicode.Scalar(UInt32(code)) else {
1053            throw Signal(message: "Invalid character: \(code)")
1054        }
1055        return scalar
1056    }
1057
1058    static func divide(_ a: Number, _ b: Number, floating: Bool) throws -> Number {
1059        if !floating, case .int(let x) = a, case .int(let y) = b {
1060            guard y != 0 else { throw Signal(message: "Arithmetic error") }
1061            let (q, overflow) = x.dividedReportingOverflow(by: y)
1062            if overflow { throw Unsupported(what: "integer size") }
1063            return .int(q)
1064        }
1065        return .float(a.double / b.double)
1066    }
1067
1068    static func eq(_ a: Sexp, _ b: Sexp) -> Bool {
1069        switch (normalized(a), normalized(b)) {
1070        case (.symbol(let x), .symbol(let y)): x == y
1071        case (.integer(let x), .integer(let y)): x == y
1072        case (.float(let x), .float(let y)): x == y
1073        default: false
1074        }
1075    }
1076
1077    /// Characters as integers and the empty list as nil, for comparing.
1078    static func normalized(_ v: Sexp) -> Sexp {
1079        switch v {
1080        case .character(let c): .integer(c)
1081        case .list(let items): items.isEmpty ? .nil : .list(items.map(normalized))
1082        case .dotted(let items, let last): .dotted(items.map(normalized), normalized(last))
1083        case .vector(let items): .vector(items.map(normalized))
1084        default: v
1085        }
1086    }
1087
1088    static func sequence(_ v: Sexp) throws -> [Sexp] {
1089        switch v {
1090        case .string(let s): return s.unicodeScalars.map { .integer(Int($0.value)) }
1091        case .vector(let items): return items
1092        default: return try elements(v)
1093        }
1094    }
1095
1096    static func stringOrSymbol(_ v: Sexp) throws -> String {
1097        if case .symbol(let s) = v { return s }
1098        return try string(v)
1099    }
1100
1101    /// What `concat` and `mapconcat` accept: strings, and lists or vectors of characters.
1102    static func printedString(_ v: Sexp) throws -> String {
1103        switch v {
1104        case .string(let s): return s
1105        case _ where isNil(v): return ""
1106        case .list, .vector:
1107            return String(String.UnicodeScalarView(try sequence(v).map { try scalar(try int($0)) }))
1108        default: throw Signal(message: "Wrong type argument: sequencep, \(v.description)")
1109        }
1110    }
1111
1112    /// `string-to-number` in base 10.
1113    static func stringToNumber(_ s: String) -> Sexp {
1114        let trimmed = s.drop { $0 == " " || $0 == "\t" || $0 == "\n" }
1115        guard let r = trimmed.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?", options: .regularExpression) else { return .integer(0) }
1116        let text = String(trimmed[r])
1117        if text.range(of: "^[-+]?[0-9]+$", options: .regularExpression) != nil, let i = Int(text.hasPrefix("+") ? String(text.dropFirst()) : text) {
1118            return .integer(i)
1119        }
1120        if text.range(of: "^[-+]?[0-9]+\\.$", options: .regularExpression) != nil, let i = Int(text.dropLast().replacingOccurrences(of: "+", with: "")) {
1121            return .integer(i)
1122        }
1123        return .float(Double(text) ?? 0)
1124    }
1125
1126    /// `format`.
1127    static func format(_ args: [Sexp]) throws -> String {
1128        let spec = Array(try string(args[0]))
1129        var out = ""
1130        var next = 1
1131        var i = 0
1132        func argument() throws -> Sexp {
1133            guard next < args.count else { throw Signal(message: "Not enough arguments for format string") }
1134            defer { next += 1 }
1135            return args[next]
1136        }
1137        while i < spec.count {
1138            let c = spec[i]
1139            i += 1
1140            guard c == "%" else {
1141                out.append(c)
1142                continue
1143            }
1144            var flags = ""
1145            while i < spec.count, "-+ #0".contains(spec[i]) {
1146                flags.append(spec[i])
1147                i += 1
1148            }
1149            var width = ""
1150            while i < spec.count, spec[i].isNumber {
1151                width.append(spec[i])
1152                i += 1
1153            }
1154            var precision: Int?
1155            if i < spec.count, spec[i] == "." {
1156                i += 1
1157                var digits = ""
1158                while i < spec.count, spec[i].isNumber {
1159                    digits.append(spec[i])
1160                    i += 1
1161                }
1162                precision = Int(digits) ?? 0
1163            }
1164            guard i < spec.count else { throw Signal(message: "Format string ends in middle of format specifier") }
1165            let conversion = spec[i]
1166            i += 1
1167            var text: String
1168            switch conversion {
1169            case "%":
1170                out.append("%")
1171                continue
1172            case "s", "S":
1173                text = printed(try argument(), escape: conversion == "S")
1174                if let precision { text = String(text.prefix(precision)) }
1175            case "d", "o", "x", "X":
1176                let value: Int
1177                switch try number(try argument()) {
1178                case .int(let n): value = n
1179                case .float(let d):
1180                    guard let n = Int(exactly: d.rounded(.towardZero)) else { throw Signal(message: "Arithmetic overflow") }
1181                    value = n
1182                }
1183                text = String(format: "%" + flags + width + (precision.map { ".\($0)" } ?? "") + (conversion == "d" ? "ld" : "l" + String(conversion)), value)
1184                out += text
1185                continue
1186            case "c":
1187                text = String(try scalar(try int(try argument())))
1188            case "e", "f", "g":
1189                let value = try number(try argument()).double
1190                out += String(format: "%" + flags + width + (precision.map { ".\($0)" } ?? "") + String(conversion), value)
1191                continue
1192            default:
1193                throw Signal(message: "Invalid format operation %\(conversion)")
1194            }
1195            let pad = max(0, (Int(width) ?? 0) - text.count)
1196            out += flags.contains("-") ? text + String(repeating: " ", count: pad) : String(repeating: " ", count: pad) + text
1197        }
1198        return out
1199    }
1200}
1201
1202extension Sexp {
1203    var character: Int? { if case .character(let c) = self { return c } else { return nil } }
1204}
1205
1206extension LispReader {
1207    /// The first form in `text` and the number of characters it spans, as `forward-sexp`
1208    /// would read it.
1209    public static func readFirst(_ text: String) throws -> (sexp: Sexp, length: Int) {
1210        var reader = Reader(Array(text.unicodeScalars))
1211        let sexp = try reader.form()
1212        let consumed = String(String.UnicodeScalarView(reader.chars[..<reader.index]))
1213        return (sexp, consumed.count)
1214    }
1215}