Sources/OrgCore/Keymap/TOML.swift

c4d5cb219ab6fe95c4d840f835a207f3da933181
orgstar/Sources/OrgCore/Keymap/TOML.swift

182 lines · 8561 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 (multi-line ones too), booleans and
  5/// integers. Comments start 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        let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
 50        var index = 0
 51        while index < lines.count {
 52            let number = index + 1
 53            let line = lines[index].trimmingCharacters(in: [" ", "\t", "\r"])
 54            index += 1
 55            if line.isEmpty || line.hasPrefix("#") { continue }
 56            if line.hasPrefix("[") {
 57                let isArray = line.hasPrefix("[[")
 58                let close = isArray ? "]]" : "]"
 59                let body = line.dropFirst(isArray ? 2 : 1)
 60                guard let end = body.range(of: close) else { throw ParseError(line: number, message: "unclosed table header") }
 61                let rest = body[end.upperBound...].trimmingCharacters(in: [" ", "\t"])
 62                guard rest.isEmpty || rest.hasPrefix("#") else { throw ParseError(line: number, message: "text after table header") }
 63                let name = body[..<end.lowerBound].trimmingCharacters(in: [" ", "\t"])
 64                guard !name.isEmpty else { throw ParseError(line: number, message: "empty table name") }
 65                tables.append(Table(name: name, isArrayElement: isArray, values: [:], line: number))
 66                continue
 67            }
 68            guard let equals = line.firstIndex(of: "=") else { throw ParseError(line: number, message: "expected key = value") }
 69            let key = line[..<equals].trimmingCharacters(in: [" ", "\t"])
 70            guard !key.isEmpty, key.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) else {
 71                throw ParseError(line: number, message: "bad key")
 72            }
 73            var rest = Substring(line[line.index(after: equals)...]).drop { $0 == " " || $0 == "\t" }
 74            let value: Value
 75            if let delimiter = ["\"\"\"", "\'\'\'"].first(where: { rest.hasPrefix($0) }) {
 76                // A multi-line string runs to the next delimiter, on this line or a later one.
 77                var body = String(rest.dropFirst(3))
 78                while body.range(of: delimiter) == nil {
 79                    guard index < lines.count else { throw ParseError(line: number, message: "unclosed string") }
 80                    body += "\n" + lines[index].replacingOccurrences(of: "\r", with: "")
 81                    index += 1
 82                }
 83                let end = body.range(of: delimiter)!
 84                value = .string(try multiline(String(body[..<end.lowerBound]), literal: delimiter == "\'\'\'", line: number))
 85                rest = body[end.upperBound...]
 86            } else {
 87                value = try parseValue(&rest, line: number)
 88            }
 89            rest = rest.drop { $0 == " " || $0 == "\t" }
 90            guard rest.isEmpty || rest.first == "#" else { throw ParseError(line: number, message: "text after value") }
 91            guard tables[tables.count - 1].values[key] == nil else { throw ParseError(line: number, message: "duplicate key \(key)") }
 92            tables[tables.count - 1].values[key] = value
 93            tables[tables.count - 1].keys.append(key)
 94        }
 95        return tables
 96    }
 97
 98    /// The body of a multi-line string: a newline right after the opening delimiter is
 99    /// dropped; in a basic one escapes apply, and a backslash at the end of a line joins it to
100    /// the next non-blank text.
101    private static func multiline(_ raw: String, literal: Bool, line: Int) throws -> String {
102        let body = raw.hasPrefix("\n") ? String(raw.dropFirst()) : raw
103        if literal { return body }
104        var out = ""
105        var rest = Substring(body)
106        while let c = rest.first {
107            rest = rest.dropFirst()
108            guard c == "\\" else {
109                out.append(c)
110                continue
111            }
112            let blanks = rest.prefix { $0 == " " || $0 == "\t" }
113            if rest.dropFirst(blanks.count).first == "\n" {
114                rest = rest.drop { $0.isWhitespace }
115                continue
116            }
117            guard let escaped = rest.first else { throw ParseError(line: line, message: "bad escape") }
118            rest = rest.dropFirst()
119            switch escaped {
120            case "\"": out.append("\"")
121            case "\\": out.append("\\")
122            case "n": out.append("\n")
123            case "t": out.append("\t")
124            case "u", "U":
125                let digits = escaped == "u" ? 4 : 8
126                guard rest.count >= digits, let code = UInt32(rest.prefix(digits), radix: 16), let scalar = Unicode.Scalar(code) else {
127                    throw ParseError(line: line, message: "bad unicode escape")
128                }
129                out.unicodeScalars.append(scalar)
130                rest = rest.dropFirst(digits)
131            default: throw ParseError(line: line, message: "bad escape \\\(escaped)")
132            }
133        }
134        return out
135    }
136
137    private static func parseValue(_ rest: inout Substring, line: Int) throws -> Value {
138        switch rest.first {
139        case "\"":
140            rest = rest.dropFirst()
141            var value = ""
142            while let c = rest.first {
143                rest = rest.dropFirst()
144                if c == "\"" { return .string(value) }
145                guard c == "\\" else {
146                    value.append(c)
147                    continue
148                }
149                guard let escaped = rest.first else { break }
150                rest = rest.dropFirst()
151                switch escaped {
152                case "\"": value.append("\"")
153                case "\\": value.append("\\")
154                case "n": value.append("\n")
155                case "t": value.append("\t")
156                case "u", "U":
157                    let digits = escaped == "u" ? 4 : 8
158                    guard let code = UInt32(rest.prefix(digits), radix: 16), let scalar = Unicode.Scalar(code), rest.count >= digits else {
159                        throw ParseError(line: line, message: "bad unicode escape")
160                    }
161                    value.unicodeScalars.append(scalar)
162                    rest = rest.dropFirst(digits)
163                default: throw ParseError(line: line, message: "bad escape \\\(escaped)")
164                }
165            }
166            throw ParseError(line: line, message: "unclosed string")
167        case "'":
168            rest = rest.dropFirst()
169            guard let end = rest.firstIndex(of: "'") else { throw ParseError(line: line, message: "unclosed string") }
170            let value = String(rest[..<end])
171            rest = rest[rest.index(after: end)...]
172            return .string(value)
173        default:
174            let word = rest.prefix { !$0.isWhitespace && $0 != "#" }
175            rest = rest.dropFirst(word.count)
176            if word == "true" { return .bool(true) }
177            if word == "false" { return .bool(false) }
178            if let number = Int(word.replacingOccurrences(of: "_", with: "")) { return .integer(number) }
179            throw ParseError(line: line, message: "unsupported value \(word)")
180        }
181    }
182}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form