Sources/OrgCore/Config/ElispLibrary.swift
cmc Run Emacs Lisp natively when Emacs is missing; translate the new Lisp reasons
db6552840c 6 days ago335 lines · 16482 bytes
1import Foundation
2
3// Math, string, list, seq and cl-lib functions of the evaluator.
4
5extension Elisp {
6 static func library(_ lisp: Elisp) {
7 lisp.set("float-pi", .float(Double.pi))
8 lisp.set("pi", .float(Double.pi))
9 lisp.set("float-e", .float(M_E))
10 mathFunctions(lisp)
11 stringFunctions(lisp)
12 sequenceFunctions(lisp)
13 }
14
15 static func mathFunctions(_ lisp: Elisp) {
16 let unary: [(String, (Double) -> Double)] = [("sqrt", { $0.squareRoot() }), ("exp", exp), ("sin", sin), ("cos", cos), ("tan", tan), ("asin", asin), ("acos", acos)]
17 for (name, f) in unary {
18 lisp.define(name) { _, args in
19 try arity(args, 1...1, name)
20 return .float(f(try number(args[0]).double))
21 }
22 }
23 lisp.define("log") { _, args in
24 try arity(args, 1...2, "log")
25 let x = try number(args[0]).double
26 guard args.count == 2, !isNil(args[1]) else { return .float(Foundation.log(x)) }
27 let base = try number(args[1]).double
28 return .float(base == 10 ? log10(x) : base == 2 ? log2(x) : Foundation.log(x) / Foundation.log(base))
29 }
30 lisp.define("atan") { _, args in
31 try arity(args, 1...2, "atan")
32 let y = try number(args[0]).double
33 return .float(args.count == 2 && !isNil(args[1]) ? atan2(y, try number(args[1]).double) : atan(y))
34 }
35 lisp.define("expt") { _, args in
36 try arity(args, 2...2, "expt")
37 switch (try number(args[0]), try number(args[1])) {
38 case (.int(var base), .int(var exponent)) where exponent >= 0:
39 var result = 1
40 while true {
41 if exponent & 1 == 1 {
42 let (product, overflow) = result.multipliedReportingOverflow(by: base)
43 if overflow { throw Unsupported(what: "integer size") }
44 result = product
45 }
46 exponent >>= 1
47 if exponent == 0 { return .integer(result) }
48 let (square, overflow) = base.multipliedReportingOverflow(by: base)
49 if overflow { throw Unsupported(what: "integer size") }
50 base = square
51 }
52 case (let a, let b):
53 return .float(pow(a.double, b.double))
54 }
55 }
56 lisp.define("isnan") { _, args in
57 try arity(args, 1...1, "isnan")
58 guard case .float(let d) = args[0] else { throw Signal(message: "Wrong type argument: floatp, \(args[0].description)") }
59 return bool(d.isNaN)
60 }
61 lisp.define("random") { _, args in
62 try arity(args, 0...1, "random")
63 switch args.first ?? .nil {
64 case .integer(let n):
65 guard n > 0 else { throw Signal(message: "Args out of range: \(n)") }
66 return .integer(Int.random(in: 0..<n))
67 case let v where isNil(v) || v == t:
68 return .integer(Int.random(in: -(1 << 61)...((1 << 61) - 1)))
69 default:
70 throw Unsupported(what: "random with a seed")
71 }
72 }
73 for (name, identity, op) in [("logand", -1, { (a: Int, b: Int) in a & b }), ("logior", 0, { $0 | $1 }), ("logxor", 0, { $0 ^ $1 })] {
74 lisp.define(name) { _, args in .integer(try args.map(int).reduce(identity, op)) }
75 }
76 lisp.define("ash") { _, args in
77 try arity(args, 2...2, "ash")
78 let value = try int(args[0])
79 let count = try int(args[1])
80 if count < 0 { return .integer(value >> min(-count, 63)) }
81 guard count < 63, (value << count) >> count == value else { throw Unsupported(what: "integer size") }
82 return .integer(value << count)
83 }
84 }
85
86 static func stringFunctions(_ lisp: Elisp) {
87 lisp.define("string-join") { _, args in
88 try arity(args, 1...2, "string-join")
89 let separator = args.count > 1 && !isNil(args[1]) ? try string(args[1]) : ""
90 return .string(try elements(args[0]).map(printedString).joined(separator: separator))
91 }
92 lisp.define("string-to-char") { _, args in
93 try arity(args, 1...1, "string-to-char")
94 return .integer(Int(try string(args[0]).unicodeScalars.first?.value ?? 0))
95 }
96 lisp.define("char-to-string") { _, args in
97 try arity(args, 1...1, "char-to-string")
98 return .string(String(try scalar(try int(args[0]))))
99 }
100 lisp.define("string-pad") { _, args in
101 try arity(args, 2...4, "string-pad")
102 let s = try string(args[0])
103 let pad = try int(args[1]) - s.unicodeScalars.count
104 guard pad > 0 else { return .string(s) }
105 guard pad <= lengthLimit else { throw Signal(message: "Too long for string-pad") }
106 let padding = String(repeating: String(try scalar(args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 32)), count: pad)
107 return .string(args.count > 3 && !isNil(args[3]) ? padding + s : s + padding)
108 }
109 lisp.define("string-width") { _, args in
110 try arity(args, 1...3, "string-width")
111 let scalars = Array(try string(args[0]).unicodeScalars)
112 let from = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 0
113 let to = args.count > 2 && !isNil(args[2]) ? try int(args[2]) : scalars.count
114 guard 0 <= from, from <= to, to <= scalars.count else { throw Signal(message: "Args out of range") }
115 return .integer(try scalars[from..<to].reduce(0) { width, c in
116 switch c.value {
117 case 9: return width + 8
118 case 10: return width
119 case 0x20...0x7E, 0xC0...0x27F: return width + 1
120 default: throw Unsupported(what: "string-width of \(String(c))")
121 }
122 })
123 }
124 lisp.define("string-search") { _, args in
125 try arity(args, 2...3, "string-search")
126 let needle = Array(try string(args[0]).unicodeScalars)
127 let haystack = Array(try string(args[1]).unicodeScalars)
128 let start = args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 0
129 guard (0...haystack.count).contains(start) else { throw Signal(message: "Args out of range: \(start)") }
130 guard needle.count <= haystack.count else { return .nil }
131 for i in start...(haystack.count - needle.count) where haystack[i..<(i + needle.count)].elementsEqual(needle) { return .integer(i) }
132 return .nil
133 }
134 lisp.define("string-replace") { _, args in
135 try arity(args, 3...3, "string-replace")
136 let from = try string(args[0])
137 guard !from.isEmpty else { throw Signal(message: "Wrong length argument: 0") }
138 return .string(try string(args[2]).replacingOccurrences(of: from, with: try string(args[1]), options: .literal))
139 }
140 }
141
142 /// The functions that change a list or vector in place, and what a variable holding the
143 /// argument holds after the call: the sorted list for an in-place `sort`, its first cell
144 /// for `nreverse`.
145 static func afterInPlace(_ name: String, _ args: [Sexp], _ result: Sexp) -> Sexp? {
146 switch name {
147 case "sort":
148 let inPlace = args.count == 2 || args.indices.contains { $0 % 2 == 1 && args[$0] == .symbol(":in-place") && $0 + 1 < args.count && !isNil(args[$0 + 1]) }
149 return inPlace ? result : nil
150 case "nreverse":
151 if case .list(let items) = args[0], let first = items.first { return .list([first]) }
152 return isNil(args[0]) ? nil : result
153 case "delete-dups":
154 return result
155 default:
156 return nil
157 }
158 }
159
160 /// Keyword arguments `args` after the first `count`, of which only `allowed` are known.
161 static func keywords(_ args: [Sexp], after count: Int, allowed: Set<String>, _ name: String) throws -> [String: Sexp] {
162 let rest = Array(args.dropFirst(count))
163 guard rest.count % 2 == 0 else { throw Signal(message: "Odd number of keyword arguments for \(name)") }
164 var result: [String: Sexp] = [:]
165 for i in stride(from: 0, to: rest.count, by: 2) {
166 guard let key = rest[i].symbol, allowed.contains(key) else { throw Unsupported(what: "\(name) with \(rest[i].description)") }
167 if result[key] == nil { result[key] = rest[i + 1] }
168 }
169 return result
170 }
171
172 /// `value<` on numbers, strings and symbols.
173 static func valueLess(_ a: Sexp, _ b: Sexp) throws -> Bool {
174 if let x = try? number(a), let y = try? number(b) {
175 if case .int(let i) = x, case .int(let j) = y { return i < j }
176 return x.double < y.double
177 }
178 switch (a, b) {
179 case (.string(let x), .string(let y)): return x.unicodeScalars.map(\.value).lexicographicallyPrecedes(y.unicodeScalars.map(\.value))
180 case (.symbol(let x), .symbol(let y)) where !isNil(a) && !isNil(b): return x.unicodeScalars.map(\.value).lexicographicallyPrecedes(y.unicodeScalars.map(\.value))
181 default: throw Unsupported(what: "value< on \(a.description) and \(b.description)")
182 }
183 }
184
185 /// The first of each run of `equal` items, in order.
186 static func uniqueEqual(_ items: [Sexp]) -> [Sexp] {
187 var seen: [String: [Sexp]] = [:]
188 var kept: [Sexp] = []
189 for item in items {
190 let value = normalized(item)
191 let key = printed(value, escape: true)
192 guard !(seen[key]?.contains(value) ?? false) else { continue }
193 seen[key, default: []].append(value)
194 kept.append(item)
195 }
196 return kept
197 }
198
199 /// A stable merge sort with a predicate that may throw.
200 static func stableSort(_ items: [Sexp], _ less: (Sexp, Sexp) throws -> Bool) throws -> [Sexp] {
201 guard items.count > 1 else { return items }
202 let left = try stableSort(Array(items[..<(items.count / 2)]), less)
203 let right = try stableSort(Array(items[(items.count / 2)...]), less)
204 var merged: [Sexp] = []
205 merged.reserveCapacity(items.count)
206 var (i, j) = (0, 0)
207 while i < left.count, j < right.count {
208 if try less(right[j], left[i]) {
209 merged.append(right[j])
210 j += 1
211 } else {
212 merged.append(left[i])
213 i += 1
214 }
215 }
216 return merged + left[i...] + right[j...]
217 }
218
219 /// `items` as the kind of sequence `like` is.
220 static func sameKind(_ items: [Sexp], as like: Sexp) throws -> Sexp {
221 switch like {
222 case .vector: return .vector(items)
223 case .string: return .string(try printedString(.list(items)))
224 default: return list(items)
225 }
226 }
227
228 static func sequenceFunctions(_ lisp: Elisp) {
229 lisp.define("last") { _, args in
230 try arity(args, 1...2, "last")
231 let n = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 1
232 switch args[0] {
233 case .list(let items): return list(Array(items.suffix(max(0, n))))
234 case .dotted(let items, let tail): return n <= 0 ? tail : .dotted(Array(items.suffix(n)), tail)
235 case let v where isNil(v): return .nil
236 default: throw Signal(message: "Wrong type argument: listp, \(args[0].description)")
237 }
238 }
239 lisp.define("butlast") { _, args in
240 try arity(args, 1...2, "butlast")
241 let n = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 1
242 guard n > 0 else { return args[0] }
243 return list(Array(try elements(args[0]).dropLast(n)))
244 }
245 lisp.define("delete-dups") { _, args in
246 try arity(args, 1...1, "delete-dups")
247 return list(uniqueEqual(try elements(args[0])))
248 }
249 lisp.define("nreverse") { _, args in
250 try arity(args, 1...1, "nreverse")
251 switch args[0] {
252 case .string(let s): return .string(String(String.UnicodeScalarView(s.unicodeScalars.reversed())))
253 case .vector(let items): return .vector(items.reversed())
254 default: return list(try elements(args[0]).reversed())
255 }
256 }
257 lisp.define("sort") { lisp, args in
258 try arity(args, 1...Int.max, "sort")
259 var key = Sexp.nil
260 var lessp = Sexp.nil
261 var reverse = false
262 if args.count == 2 {
263 guard args[1].symbol?.hasPrefix(":") != true else { throw Signal(message: "Odd number of keyword arguments for sort") }
264 lessp = args[1]
265 } else {
266 let options = try keywords(args, after: 1, allowed: [":key", ":lessp", ":reverse", ":in-place"], "sort")
267 key = options[":key"] ?? .nil
268 lessp = options[":lessp"] ?? .nil
269 reverse = !isNil(options[":reverse"] ?? .nil)
270 }
271 let items: [Sexp]
272 switch args[0] {
273 case .vector(let v): items = v
274 case .string: throw Unsupported(what: "sort on a string")
275 default: items = try elements(args[0])
276 }
277 let keyed = try items.map { isNil(key) ? ($0, $0) : ($0, try lisp.call(key, [$0])) }
278 func less(_ a: Sexp, _ b: Sexp) throws -> Bool {
279 isNil(lessp) ? try valueLess(a, b) : !isNil(try lisp.call(lessp, [a, b]))
280 }
281 let keys = keyed.map(\.1)
282 let order = try stableSort((0..<items.count).map { .integer($0) }) { a, b in
283 let (i, j) = (a.integer!, b.integer!)
284 return reverse ? try less(keys[j], keys[i]) : try less(keys[i], keys[j])
285 }
286 let sorted = order.map { items[$0.integer!] }
287 if case .vector = args[0] { return .vector(sorted) }
288 return list(sorted)
289 }
290 lisp.define("seq-reduce") { lisp, args in
291 try arity(args, 3...3, "seq-reduce")
292 return try sequence(args[1]).reduce(args[2]) { try lisp.call(args[0], [$0, $1]) }
293 }
294 for name in ["seq-filter", "seq-remove"] {
295 lisp.define(name) { lisp, args in
296 try arity(args, 2...2, name)
297 return list(try sequence(args[1]).filter { isNil(try lisp.call(args[0], [$0])) == (name == "seq-remove") })
298 }
299 }
300 lisp.define("seq-map") { lisp, args in
301 try arity(args, 2...2, "seq-map")
302 return list(try sequence(args[1]).map { try lisp.call(args[0], [$0]) })
303 }
304 lisp.define("seq-uniq") { _, args in
305 try arity(args, 1...2, "seq-uniq")
306 guard args.count == 1 || isNil(args[1]) else { throw Unsupported(what: "seq-uniq with a test") }
307 return list(uniqueEqual(try sequence(args[0])))
308 }
309 lisp.define("cl-reduce") { lisp, args in
310 try arity(args, 2...Int.max, "cl-reduce")
311 let options = try keywords(args, after: 2, allowed: [":initial-value"], "cl-reduce")
312 var items = try sequence(args[1])[...]
313 guard let initial = options[":initial-value"] ?? items.popFirst() else { return try lisp.call(args[0], []) }
314 return try items.reduce(initial) { try lisp.call(args[0], [$0, $1]) }
315 }
316 for name in ["cl-remove-if", "cl-remove-if-not"] {
317 lisp.define(name) { lisp, args in
318 try arity(args, 2...Int.max, name)
319 _ = try keywords(args, after: 2, allowed: [], name)
320 return try sameKind(try sequence(args[1]).filter { isNil(try lisp.call(args[0], [$0])) == (name == "cl-remove-if") }, as: args[1])
321 }
322 }
323 for name in ["cl-find", "cl-position"] {
324 lisp.define(name) { lisp, args in
325 try arity(args, 2...Int.max, name)
326 let test = try keywords(args, after: 2, allowed: [":test"], name)[":test"] ?? .nil
327 for (i, item) in try sequence(args[1]).enumerated() {
328 let found = isNil(test) ? eq(args[0], item) : !isNil(try lisp.call(test, [args[0], item]))
329 if found { return name == "cl-find" ? item : .integer(i) }
330 }
331 return .nil
332 }
333 }
334 }
335}