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