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