Sources/OrgCore/Keymap/TOML.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgCore/Keymap/TOML.swift history · blame · raw

126 lines · 5904 bytes

  1import Foundation
  2
  3/// The part of TOML keymaps use: `[table]` and `[[array-of-tables]]` headers, and
  4/// `key = value` lines with basic or literal strings, booleans and integers. Comments start
  5/// with `#` outside strings.
  6public enum TOML {
  7    public enum Value: Sendable, Equatable {
  8        case string(String)
  9        case bool(Bool)
 10        case integer(Int)
 11
 12        public var string: String? {
 13            if case .string(let value) = self { return value }
 14            return nil
 15        }
 16
 17        public var bool: Bool? {
 18            if case .bool(let value) = self { return value }
 19            return nil
 20        }
 21
 22        public var integer: Int? {
 23            if case .integer(let value) = self { return value }
 24            return nil
 25        }
 26    }
 27
 28    public struct Table: Sendable, Equatable {
 29        /// Empty for keys before the first header.
 30        public var name: String
 31        /// Declared with `[[name]]`.
 32        public var isArrayElement: Bool
 33        public var values: [String: Value]
 34        /// 1-based line of the header.
 35        public var line: Int
 36        /// The keys in the order they appear.
 37        public var keys: [String] = []
 38    }
 39
 40    public struct ParseError: Error, Equatable, CustomStringConvertible {
 41        public let line: Int
 42        public let message: String
 43        public var description: String { "line \(line): \(message)" }
 44    }
 45
 46    /// Tables in file order.
 47    public static func parse(_ text: String) throws -> [Table] {
 48        var tables = [Table(name: "", isArrayElement: false, values: [:], line: 0)]
 49        for (index, rawLine) in text.split(separator: "\n", omittingEmptySubsequences: false).enumerated() {
 50            let number = index + 1
 51            let line = rawLine.trimmingCharacters(in: [" ", "\t", "\r"])
 52            if line.isEmpty || line.hasPrefix("#") { continue }
 53            if line.hasPrefix("[") {
 54                let isArray = line.hasPrefix("[[")
 55                let close = isArray ? "]]" : "]"
 56                let body = line.dropFirst(isArray ? 2 : 1)
 57                guard let end = body.range(of: close) else { throw ParseError(line: number, message: "unclosed table header") }
 58                let rest = body[end.upperBound...].trimmingCharacters(in: [" ", "\t"])
 59                guard rest.isEmpty || rest.hasPrefix("#") else { throw ParseError(line: number, message: "text after table header") }
 60                let name = body[..<end.lowerBound].trimmingCharacters(in: [" ", "\t"])
 61                guard !name.isEmpty else { throw ParseError(line: number, message: "empty table name") }
 62                tables.append(Table(name: name, isArrayElement: isArray, values: [:], line: number))
 63                continue
 64            }
 65            guard let equals = line.firstIndex(of: "=") else { throw ParseError(line: number, message: "expected key = value") }
 66            let key = line[..<equals].trimmingCharacters(in: [" ", "\t"])
 67            guard !key.isEmpty, key.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) else {
 68                throw ParseError(line: number, message: "bad key")
 69            }
 70            var rest = Substring(line[line.index(after: equals)...]).drop { $0 == " " || $0 == "\t" }
 71            let value = try parseValue(&rest, line: number)
 72            rest = rest.drop { $0 == " " || $0 == "\t" }
 73            guard rest.isEmpty || rest.first == "#" else { throw ParseError(line: number, message: "text after value") }
 74            guard tables[tables.count - 1].values[key] == nil else { throw ParseError(line: number, message: "duplicate key \(key)") }
 75            tables[tables.count - 1].values[key] = value
 76            tables[tables.count - 1].keys.append(key)
 77        }
 78        return tables
 79    }
 80
 81    private static func parseValue(_ rest: inout Substring, line: Int) throws -> Value {
 82        switch rest.first {
 83        case "\"":
 84            rest = rest.dropFirst()
 85            var value = ""
 86            while let c = rest.first {
 87                rest = rest.dropFirst()
 88                if c == "\"" { return .string(value) }
 89                guard c == "\\" else {
 90                    value.append(c)
 91                    continue
 92                }
 93                guard let escaped = rest.first else { break }
 94                rest = rest.dropFirst()
 95                switch escaped {
 96                case "\"": value.append("\"")
 97                case "\\": value.append("\\")
 98                case "n": value.append("\n")
 99                case "t": value.append("\t")
100                case "u", "U":
101                    let digits = escaped == "u" ? 4 : 8
102                    guard let code = UInt32(rest.prefix(digits), radix: 16), let scalar = Unicode.Scalar(code), rest.count >= digits else {
103                        throw ParseError(line: line, message: "bad unicode escape")
104                    }
105                    value.unicodeScalars.append(scalar)
106                    rest = rest.dropFirst(digits)
107                default: throw ParseError(line: line, message: "bad escape \\\(escaped)")
108                }
109            }
110            throw ParseError(line: line, message: "unclosed string")
111        case "'":
112            rest = rest.dropFirst()
113            guard let end = rest.firstIndex(of: "'") else { throw ParseError(line: line, message: "unclosed string") }
114            let value = String(rest[..<end])
115            rest = rest[rest.index(after: end)...]
116            return .string(value)
117        default:
118            let word = rest.prefix { !$0.isWhitespace && $0 != "#" }
119            rest = rest.dropFirst(word.count)
120            if word == "true" { return .bool(true) }
121            if word == "false" { return .bool(false) }
122            if let number = Int(word.replacingOccurrences(of: "_", with: "")) { return .integer(number) }
123            throw ParseError(line: line, message: "unsupported value \(word)")
124        }
125    }
126}