Sources/OrgCore/Config/Lisp.swift

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

222 lines · 8665 bytes

15 symbols in this file
  1import Foundation
  2
  3/// Emacs Lisp read without evaluating: for importing settings from an Emacs configuration.
  4public indirect enum Sexp: Equatable, Sendable {
  5    case symbol(String)
  6    case string(String)
  7    case integer(Int)
  8    case float(Double)
  9    /// `?a`, as its code point.
 10    case character(Int)
 11    case list([Sexp])
 12    /// `(a b . c)`: the elements, then the final cdr.
 13    case dotted([Sexp], Sexp)
 14    case vector([Sexp])
 15
 16    public static let `nil` = Sexp.symbol("nil")
 17
 18    public var symbol: String? { if case .symbol(let s) = self { return s } else { return nil } }
 19    public var string: String? { if case .string(let s) = self { return s } else { return nil } }
 20    public var integer: Int? { if case .integer(let i) = self { return i } else { return nil } }
 21
 22    /// A list's elements; `nil` is the empty list.
 23    public var elements: [Sexp]? {
 24        switch self {
 25        case .list(let items): items
 26        case .symbol("nil"): []
 27        default: nil
 28        }
 29    }
 30
 31    /// The symbol a list starts with: `setq` for `(setq ...)`.
 32    public var head: String? { elements?.first?.symbol }
 33
 34    /// Written back as Lisp, for reports.
 35    public var description: String {
 36        switch self {
 37        case .symbol(let s): return s
 38        case .string(let s): return "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\n", with: "\\n") + "\""
 39        case .integer(let i): return String(i)
 40        case .float(let d): return String(d)
 41        case .character(let c): return "?" + (Unicode.Scalar(c).map { String(Character($0)) } ?? "")
 42        case .list(let items):
 43            if items.count == 2, let head = items[0].symbol {
 44                switch head {
 45                case "quote": return "'" + items[1].description
 46                case "function": return "#'" + items[1].description
 47                case "\\`": return "`" + items[1].description
 48                case ",": return "," + items[1].description
 49                case ",@": return ",@" + items[1].description
 50                default: break
 51                }
 52            }
 53            return "(" + items.map(\.description).joined(separator: " ") + ")"
 54        case .dotted(let items, let last): return "(" + items.map(\.description).joined(separator: " ") + " . " + last.description + ")"
 55        case .vector(let items): return "[" + items.map(\.description).joined(separator: " ") + "]"
 56        }
 57    }
 58}
 59
 60public enum LispReader {
 61    public struct Form: Sendable {
 62        public let sexp: Sexp
 63        /// 1-based line where the form starts.
 64        public let line: Int
 65    }
 66
 67    public struct ReadError: Error, Equatable, CustomStringConvertible {
 68        public let line: Int
 69        public let message: String
 70        public var description: String { "line \(line): \(message)" }
 71    }
 72
 73    /// The top-level forms of `text`.
 74    public static func read(_ text: String) throws -> [Form] {
 75        var reader = Reader(Array(text.unicodeScalars))
 76        var forms: [Form] = []
 77        while true {
 78            reader.skipSpace()
 79            guard !reader.atEnd else { break }
 80            let line = reader.line
 81            forms.append(Form(sexp: try reader.form(), line: line))
 82        }
 83        return forms
 84    }
 85
 86    struct Reader {
 87        let chars: [Unicode.Scalar]
 88        var index = 0
 89        var line = 1
 90
 91        init(_ chars: [Unicode.Scalar]) { self.chars = chars }
 92
 93        var atEnd: Bool { index >= chars.count }
 94        var peek: Unicode.Scalar? { index < chars.count ? chars[index] : nil }
 95
 96        mutating func next() -> Unicode.Scalar? {
 97            guard index < chars.count else { return nil }
 98            let c = chars[index]
 99            index += 1
100            if c == "\n" { line += 1 }
101            return c
102        }
103
104        mutating func skipSpace() {
105            while let c = peek {
106                if c == ";" {
107                    while let d = peek, d != "\n" { _ = next() }
108                } else if c.properties.isWhitespace {
109                    _ = next()
110                } else {
111                    return
112                }
113            }
114        }
115
116        func error(_ message: String) -> ReadError { ReadError(line: line, message: message) }
117
118        /// What `\a` and the other one-letter escapes in strings and characters stand for.
119        static let escapes: [Unicode.Scalar: Unicode.Scalar] = ["a": "\u{7}", "b": "\u{8}", "d": "\u{7F}", "e": "\u{1B}", "f": "\u{C}", "n": "\n", "r": "\r", "s": " ", "t": "\t", "v": "\u{B}"]
120
121        static let delimiters: Set<Unicode.Scalar> = ["(", ")", "[", "]", "\"", "'", "`", ",", ";"]
122
123        mutating func form() throws -> Sexp {
124            skipSpace()
125            guard let c = next() else { throw error("unexpected end of file") }
126            switch c {
127            case "(": return try list(close: ")")
128            case "[":
129                guard case .list(let items) = try list(close: "]") else { throw error("bad vector") }
130                return .vector(items)
131            case ")", "]": throw error("unexpected \(c)")
132            case "\"": return .string(try string())
133            case "'": return .list([.symbol("quote"), try form()])
134            case "`": return .list([.symbol("\\`"), try form()])
135            case ",":
136                if peek == "@" {
137                    _ = next()
138                    return .list([.symbol(",@"), try form()])
139                }
140                return .list([.symbol(","), try form()])
141            case "?": return .character(try character())
142            case "#":
143                if peek == "'" {
144                    _ = next()
145                    return .list([.symbol("function"), try form()])
146                }
147                return .symbol("#" + atom())
148            default:
149                index -= 1
150                if c == "\n" { line -= 1 }
151                return number(atom())
152            }
153        }
154
155        mutating func list(close: Unicode.Scalar) throws -> Sexp {
156            var items: [Sexp] = []
157            while true {
158                skipSpace()
159                guard let c = peek else { throw error("unclosed list") }
160                if c == close {
161                    _ = next()
162                    return .list(items)
163                }
164                if c == ".", index + 1 < chars.count, chars[index + 1].properties.isWhitespace || Self.delimiters.contains(chars[index + 1]) {
165                    _ = next()
166                    let last = try form()
167                    skipSpace()
168                    guard next() == close else { throw error("bad dotted list") }
169                    return .dotted(items, last)
170                }
171                items.append(try form())
172            }
173        }
174
175        mutating func string() throws -> String {
176            var out = ""
177            while let c = next() {
178                switch c {
179                case "\"": return out
180                case "\\":
181                    guard let e = next() else { break }
182                    switch e {
183                    case "\n", " ": break
184                    default: out.unicodeScalars.append(Self.escapes[e] ?? e)
185                    }
186                default:
187                    out.unicodeScalars.append(c)
188                }
189            }
190            throw error("unclosed string")
191        }
192
193        mutating func character() throws -> Int {
194            guard let c = next() else { throw error("bad character") }
195            guard c == "\\" else { return Int(c.value) }
196            guard let e = next() else { throw error("bad character") }
197            switch e {
198            case _ where Self.escapes[e] != nil: return Int(Self.escapes[e]!.value)
199            case "C", "M", "S", "H", "A":
200                if peek == "-" { _ = next(); return try character() }
201                return Int(e.value)
202            default: return Int(e.value)
203            }
204        }
205
206        mutating func atom() -> String {
207            var out = ""
208            while let c = peek, !c.properties.isWhitespace, !Self.delimiters.contains(c) {
209                _ = next()
210                if c == "\\", let escaped = next() { out.unicodeScalars.append(escaped) } else { out.unicodeScalars.append(c) }
211            }
212            return out
213        }
214
215        func number(_ text: String) -> Sexp {
216            if let i = Int(text.hasPrefix("+") ? String(text.dropFirst()) : text) { return .integer(i) }
217            if text.contains(where: { $0 == "." || $0 == "e" }), text.first.map({ $0.isNumber || $0 == "-" || $0 == "+" || $0 == "." }) == true,
218               let d = Double(text) { return .float(d) }
219            return .symbol(text)
220        }
221    }
222}