Sources/OrgCore/Config/ElispLibrary.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Config/ElispLibrary.swift history · blame · raw

349 lines · 17335 bytes

12 symbols in this file
  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 length = try int(args[1])
104            guard length >= 0 else { throw Signal(message: "Wrong type argument: natnump, \(length)") }
105            let pad = length - s.unicodeScalars.count
106            guard pad > 0 else { return .string(s) }
107            guard pad <= lengthLimit else { throw Signal(message: "Too long for string-pad") }
108            let padding = String(repeating: String(try scalar(args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 32)), count: pad)
109            return .string(args.count > 3 && !isNil(args[3]) ? padding + s : s + padding)
110        }
111        lisp.define("string-width") { _, args in
112            try arity(args, 1...3, "string-width")
113            let scalars = Array(try string(args[0]).unicodeScalars)
114            let from = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 0
115            let to = args.count > 2 && !isNil(args[2]) ? try int(args[2]) : scalars.count
116            guard 0 <= from, from <= to, to <= scalars.count else { throw Signal(message: "Args out of range") }
117            return .integer(try scalars[from..<to].reduce(0) { width, c in
118                switch c.value {
119                case 9: return width + 8
120                case 10: return width
121                case 0x20...0x7E, 0xC0...0x27F: return width + 1
122                default: throw Unsupported(what: "string-width of \(String(c))")
123                }
124            })
125        }
126        lisp.define("string-search") { _, args in
127            try arity(args, 2...3, "string-search")
128            let needle = Array(try string(args[0]).unicodeScalars)
129            let haystack = Array(try string(args[1]).unicodeScalars)
130            let start = args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 0
131            guard (0...haystack.count).contains(start) else { throw Signal(message: "Args out of range: \(start)") }
132            guard needle.count <= haystack.count else { return .nil }
133            for i in start...(haystack.count - needle.count) where haystack[i..<(i + needle.count)].elementsEqual(needle) { return .integer(i) }
134            return .nil
135        }
136        lisp.define("string-replace") { _, args in
137            try arity(args, 3...3, "string-replace")
138            let from = try string(args[0])
139            guard !from.isEmpty else { throw Signal(message: "Wrong length argument: 0") }
140            return .string(try string(args[2]).replacingOccurrences(of: from, with: try string(args[1]), options: .literal))
141        }
142    }
143
144    /// The functions that change a list or vector in place, and what a variable holding the
145    /// argument holds after the call: the sorted list for an in-place `sort`, its first cell
146    /// for `nreverse`.
147    static func afterInPlace(_ name: String, _ args: [Sexp], _ result: Sexp) -> Sexp? {
148        switch name {
149        case "sort":
150            let inPlace = args.count == 2 || args.indices.contains { $0 % 2 == 1 && args[$0] == .symbol(":in-place") && $0 + 1 < args.count && !isNil(args[$0 + 1]) }
151            return inPlace ? result : nil
152        case "nreverse":
153            if case .list(let items) = args[0], let first = items.first { return .list([first]) }
154            return isNil(args[0]) ? nil : result
155        case "delete-dups":
156            return result
157        default:
158            return nil
159        }
160    }
161
162    /// Refuses `name` on a first argument that another value may share, when it changes it in
163    /// place.
164    static func refuseShared(_ lisp: Elisp, _ name: String, _ args: [Sexp], variable: String?) throws {
165        if afterInPlace(name, args, .nil) != nil { try lisp.refuseShared(args[0], variable: variable, name) }
166    }
167
168    /// Keyword arguments `args` after the first `count`, of which only `allowed` are known.
169    static func keywords(_ args: [Sexp], after count: Int, allowed: Set<String>, _ name: String) throws -> [String: Sexp] {
170        let rest = Array(args.dropFirst(count))
171        guard rest.count % 2 == 0 else { throw Signal(message: "Odd number of keyword arguments for \(name)") }
172        var result: [String: Sexp] = [:]
173        for i in stride(from: 0, to: rest.count, by: 2) {
174            guard let key = rest[i].symbol, allowed.contains(key) else { throw Unsupported(what: "\(name) with \(rest[i].description)") }
175            if result[key] == nil { result[key] = rest[i + 1] }
176        }
177        return result
178    }
179
180    /// `value<` on numbers, strings and symbols.
181    static func valueLess(_ a: Sexp, _ b: Sexp) throws -> Bool {
182        if let x = try? number(a), let y = try? number(b) {
183            if case .int(let i) = x, case .int(let j) = y { return i < j }
184            return x.double < y.double
185        }
186        switch (a, b) {
187        case (.string(let x), .string(let y)): return x.unicodeScalars.map(\.value).lexicographicallyPrecedes(y.unicodeScalars.map(\.value))
188        case (.symbol(let x), .symbol(let y)) where !isNil(a) && !isNil(b): return x.unicodeScalars.map(\.value).lexicographicallyPrecedes(y.unicodeScalars.map(\.value))
189        default: throw Unsupported(what: "value< on \(a.description) and \(b.description)")
190        }
191    }
192
193    /// The first of each run of `equal` items, in order.
194    static func uniqueEqual(_ items: [Sexp]) -> [Sexp] {
195        var seen: [String: [Sexp]] = [:]
196        var kept: [Sexp] = []
197        for item in items {
198            let value = normalized(item)
199            let key = printed(value, escape: true)
200            guard !(seen[key]?.contains(value) ?? false) else { continue }
201            seen[key, default: []].append(value)
202            kept.append(item)
203        }
204        return kept
205    }
206
207    /// A stable merge sort with a predicate that may throw.
208    static func stableSort(_ items: [Sexp], _ less: (Sexp, Sexp) throws -> Bool) throws -> [Sexp] {
209        guard items.count > 1 else { return items }
210        let left = try stableSort(Array(items[..<(items.count / 2)]), less)
211        let right = try stableSort(Array(items[(items.count / 2)...]), less)
212        var merged: [Sexp] = []
213        merged.reserveCapacity(items.count)
214        var (i, j) = (0, 0)
215        while i < left.count, j < right.count {
216            if try less(right[j], left[i]) {
217                merged.append(right[j])
218                j += 1
219            } else {
220                merged.append(left[i])
221                i += 1
222            }
223        }
224        return merged + left[i...] + right[j...]
225    }
226
227    /// `items` as the kind of sequence `like` is.
228    static func sameKind(_ items: [Sexp], as like: Sexp) throws -> Sexp {
229        switch like {
230        case .vector: return .vector(items)
231        case .string: return .string(try printedString(.list(items)))
232        default: return list(items)
233        }
234    }
235
236    static func sequenceFunctions(_ lisp: Elisp) {
237        lisp.define("last") { _, args in
238            try arity(args, 1...2, "last")
239            let n = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 1
240            switch args[0] {
241            case .list(let items): return list(Array(items.suffix(max(0, n))))
242            case .dotted(let items, let tail): return n <= 0 ? tail : .dotted(Array(items.suffix(n)), tail)
243            case let v where isNil(v): return .nil
244            default: throw Signal(message: "Wrong type argument: listp, \(args[0].description)")
245            }
246        }
247        lisp.define("butlast") { _, args in
248            try arity(args, 1...2, "butlast")
249            let n = args.count > 1 && !isNil(args[1]) ? try int(args[1]) : 1
250            guard n > 0 else { return args[0] }
251            return list(Array(try elements(args[0]).dropLast(n)))
252        }
253        lisp.define("delete-dups") { lisp, args in
254            let variable = lisp.takeInPlaceVariable()
255            try arity(args, 1...1, "delete-dups")
256            try refuseShared(lisp, "delete-dups", args, variable: variable)
257            return list(uniqueEqual(try elements(args[0])))
258        }
259        lisp.define("nreverse") { lisp, args in
260            let variable = lisp.takeInPlaceVariable()
261            try arity(args, 1...1, "nreverse")
262            try refuseShared(lisp, "nreverse", args, variable: variable)
263            switch args[0] {
264            case .string(let s): return .string(String(String.UnicodeScalarView(s.unicodeScalars.reversed())))
265            case .vector(let items): return .vector(items.reversed())
266            default: return list(try elements(args[0]).reversed())
267            }
268        }
269        lisp.define("sort") { lisp, args in
270            let variable = lisp.takeInPlaceVariable()
271            try arity(args, 1...Int.max, "sort")
272            var key = Sexp.nil
273            var lessp = Sexp.nil
274            var reverse = false
275            if args.count == 2 {
276                guard args[1].symbol?.hasPrefix(":") != true else { throw Signal(message: "Odd number of keyword arguments for sort") }
277                lessp = args[1]
278            } else {
279                let options = try keywords(args, after: 1, allowed: [":key", ":lessp", ":reverse", ":in-place"], "sort")
280                key = options[":key"] ?? .nil
281                lessp = options[":lessp"] ?? .nil
282                reverse = !isNil(options[":reverse"] ?? .nil)
283            }
284            let items: [Sexp]
285            switch args[0] {
286            case .vector(let v): items = v
287            case .string: throw Unsupported(what: "sort on a string")
288            default: items = try elements(args[0])
289            }
290            try refuseShared(lisp, "sort", args, variable: variable)
291            let keyed = try items.map { isNil(key) ? ($0, $0) : ($0, try lisp.call(key, [$0])) }
292            func less(_ a: Sexp, _ b: Sexp) throws -> Bool {
293                isNil(lessp) ? try valueLess(a, b) : !isNil(try lisp.call(lessp, [a, b]))
294            }
295            let keys = keyed.map(\.1)
296            let order = try stableSort((0..<items.count).map { .integer($0) }) { a, b in
297                let (i, j) = (a.integer!, b.integer!)
298                return reverse ? try less(keys[j], keys[i]) : try less(keys[i], keys[j])
299            }
300            let sorted = order.map { items[$0.integer!] }
301            if case .vector = args[0] { return .vector(sorted) }
302            return list(sorted)
303        }
304        lisp.define("seq-reduce") { lisp, args in
305            try arity(args, 3...3, "seq-reduce")
306            return try sequence(args[1]).reduce(args[2]) { try lisp.call(args[0], [$0, $1]) }
307        }
308        for name in ["seq-filter", "seq-remove"] {
309            lisp.define(name) { lisp, args in
310                try arity(args, 2...2, name)
311                return list(try sequence(args[1]).filter { isNil(try lisp.call(args[0], [$0])) == (name == "seq-remove") })
312            }
313        }
314        lisp.define("seq-map") { lisp, args in
315            try arity(args, 2...2, "seq-map")
316            return list(try sequence(args[1]).map { try lisp.call(args[0], [$0]) })
317        }
318        lisp.define("seq-uniq") { _, args in
319            try arity(args, 1...2, "seq-uniq")
320            guard args.count == 1 || isNil(args[1]) else { throw Unsupported(what: "seq-uniq with a test") }
321            return list(uniqueEqual(try sequence(args[0])))
322        }
323        lisp.define("cl-reduce") { lisp, args in
324            try arity(args, 2...Int.max, "cl-reduce")
325            let options = try keywords(args, after: 2, allowed: [":initial-value"], "cl-reduce")
326            var items = try sequence(args[1])[...]
327            guard let initial = options[":initial-value"] ?? items.popFirst() else { return try lisp.call(args[0], []) }
328            return try items.reduce(initial) { try lisp.call(args[0], [$0, $1]) }
329        }
330        for name in ["cl-remove-if", "cl-remove-if-not"] {
331            lisp.define(name) { lisp, args in
332                try arity(args, 2...Int.max, name)
333                _ = try keywords(args, after: 2, allowed: [], name)
334                return try sameKind(try sequence(args[1]).filter { isNil(try lisp.call(args[0], [$0])) == (name == "cl-remove-if") }, as: args[1])
335            }
336        }
337        for name in ["cl-find", "cl-position"] {
338            lisp.define(name) { lisp, args in
339                try arity(args, 2...Int.max, name)
340                let test = try keywords(args, after: 2, allowed: [":test"], name)[":test"] ?? .nil
341                for (i, item) in try sequence(args[1]).enumerated() {
342                    let found = isNil(test) ? eq(args[0], item) : !isNil(try lisp.call(test, [args[0], item]))
343                    if found { return name == "cl-find" ? item : .integer(i) }
344                }
345                return .nil
346            }
347        }
348    }
349}