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