Sources/OrgCore/Keymap/TOML.swift
256 lines · 11360 bytes
9 symbols in this file
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,
5/// integers and arrays of these, which may run over several lines. Comments start with `#`
6/// outside strings.
7public enum TOML {
8 public enum Value: Sendable, Equatable {
9 case string(String)
10 case bool(Bool)
11 case integer(Int)
12 case array([Value])
13
14 public var string: String? {
15 if case .string(let value) = self { return value }
16 return nil
17 }
18
19 public var bool: Bool? {
20 if case .bool(let value) = self { return value }
21 return nil
22 }
23
24 public var integer: Int? {
25 if case .integer(let value) = self { return value }
26 return nil
27 }
28
29 public var array: [Value]? {
30 if case .array(let value) = self { return value }
31 return nil
32 }
33 }
34
35 public struct Table: Sendable, Equatable {
36 /// Empty for keys before the first header.
37 public var name: String
38 /// Declared with `[[name]]`.
39 public var isArrayElement: Bool
40 public var values: [String: Value]
41 /// 1-based line of the header.
42 public var line: Int
43 /// The keys in the order they appear.
44 public var keys: [String] = []
45 }
46
47 public struct ParseError: Error, Equatable, CustomStringConvertible {
48 public let line: Int
49 public let message: String
50 public var description: String { "line \(line): \(message)" }
51 }
52
53 /// Tables in file order.
54 public static func parse(_ text: String) throws -> [Table] {
55 var tables = [Table(name: "", isArrayElement: false, values: [:], line: 0)]
56 let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
57 var index = 0
58 while index < lines.count {
59 let number = index + 1
60 let line = lines[index].trimmingCharacters(in: [" ", "\t", "\r"])
61 index += 1
62 if line.isEmpty || line.hasPrefix("#") { continue }
63 if line.hasPrefix("[") {
64 let isArray = line.hasPrefix("[[")
65 let close = isArray ? "]]" : "]"
66 let body = line.dropFirst(isArray ? 2 : 1)
67 guard let end = body.range(of: close) else { throw ParseError(line: number, message: "unclosed table header") }
68 let rest = body[end.upperBound...].trimmingCharacters(in: [" ", "\t"])
69 guard rest.isEmpty || rest.hasPrefix("#") else { throw ParseError(line: number, message: "text after table header") }
70 let name = body[..<end.lowerBound].trimmingCharacters(in: [" ", "\t"])
71 guard !name.isEmpty else { throw ParseError(line: number, message: "empty table name") }
72 tables.append(Table(name: name, isArrayElement: isArray, values: [:], line: number))
73 continue
74 }
75 guard let equals = line.firstIndex(of: "=") else { throw ParseError(line: number, message: "expected key = value") }
76 let key = line[..<equals].trimmingCharacters(in: [" ", "\t"])
77 guard !key.isEmpty, key.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) else {
78 throw ParseError(line: number, message: "bad key")
79 }
80 var rest = Substring(line[line.index(after: equals)...]).drop { $0 == " " || $0 == "\t" }
81 let value: Value
82 if let delimiter = ["\"\"\"", "\'\'\'"].first(where: { rest.hasPrefix($0) }) {
83 // A multi-line string runs to the next delimiter, on this line or a later one.
84 var body = String(rest.dropFirst(3))
85 while body.range(of: delimiter) == nil {
86 guard index < lines.count else { throw ParseError(line: number, message: "unclosed string") }
87 body += "\n" + lines[index].replacingOccurrences(of: "\r", with: "")
88 index += 1
89 }
90 let end = body.range(of: delimiter)!
91 value = .string(try multiline(String(body[..<end.lowerBound]), literal: delimiter == "\'\'\'", line: number))
92 rest = body[end.upperBound...]
93 } else if rest.first == "[" {
94 // An array runs to its closing bracket, on this line or a later one.
95 var body = String(rest)
96 while !closesArray(body) {
97 guard index < lines.count else { throw ParseError(line: number, message: "unclosed array") }
98 body += "\n" + lines[index].replacingOccurrences(of: "\r", with: "")
99 index += 1
100 }
101 var array = Substring(body)
102 value = try parseValue(&array, line: number)
103 rest = array
104 } else {
105 value = try parseValue(&rest, line: number)
106 }
107 rest = rest.drop { $0 == " " || $0 == "\t" }
108 guard rest.isEmpty || rest.first == "#" else { throw ParseError(line: number, message: "text after value") }
109 guard tables[tables.count - 1].values[key] == nil else { throw ParseError(line: number, message: "duplicate key \(key)") }
110 tables[tables.count - 1].values[key] = value
111 tables[tables.count - 1].keys.append(key)
112 }
113 return tables
114 }
115
116 /// The body of a multi-line string: a newline right after the opening delimiter is
117 /// dropped; in a basic one escapes apply, and a backslash at the end of a line joins it to
118 /// the next non-blank text.
119 private static func multiline(_ raw: String, literal: Bool, line: Int) throws -> String {
120 let body = raw.hasPrefix("\n") ? String(raw.dropFirst()) : raw
121 if literal { return body }
122 var out = ""
123 var rest = Substring(body)
124 while let c = rest.first {
125 rest = rest.dropFirst()
126 guard c == "\\" else {
127 out.append(c)
128 continue
129 }
130 let blanks = rest.prefix { $0 == " " || $0 == "\t" }
131 if rest.dropFirst(blanks.count).first == "\n" {
132 rest = rest.drop { $0.isWhitespace }
133 continue
134 }
135 guard let escaped = rest.first else { throw ParseError(line: line, message: "bad escape") }
136 rest = rest.dropFirst()
137 switch escaped {
138 case "\"": out.append("\"")
139 case "\\": out.append("\\")
140 case "n": out.append("\n")
141 case "t": out.append("\t")
142 case "u", "U":
143 let digits = escaped == "u" ? 4 : 8
144 guard rest.count >= digits, let code = UInt32(rest.prefix(digits), radix: 16), let scalar = Unicode.Scalar(code) else {
145 throw ParseError(line: line, message: "bad unicode escape")
146 }
147 out.unicodeScalars.append(scalar)
148 rest = rest.dropFirst(digits)
149 default: throw ParseError(line: line, message: "bad escape \\\(escaped)")
150 }
151 }
152 return out
153 }
154
155 /// Whether `text`, starting with `[`, has the bracket that closes it, outside strings and
156 /// comments.
157 private static func closesArray(_ text: String) -> Bool {
158 var depth = 0
159 var quote: Character?
160 var comment = false
161 var escaped = false
162 for c in text {
163 if comment {
164 if c == "\n" { comment = false }
165 } else if let q = quote {
166 if escaped { escaped = false } else if c == "\\" && q == "\"" { escaped = true } else if c == q { quote = nil }
167 } else {
168 switch c {
169 case "\"", "'": quote = c
170 case "#": comment = true
171 case "[": depth += 1
172 case "]":
173 depth -= 1
174 if depth == 0 { return true }
175 default: break
176 }
177 }
178 }
179 return false
180 }
181
182 /// Spaces, line ends and comments between an array's values.
183 private static func skipBlanks(_ rest: inout Substring) {
184 while let c = rest.first {
185 if c.isWhitespace {
186 rest = rest.dropFirst()
187 } else if c == "#" {
188 rest = rest.drop { $0 != "\n" }
189 } else {
190 return
191 }
192 }
193 }
194
195 private static func parseValue(_ rest: inout Substring, line: Int) throws -> Value {
196 switch rest.first {
197 case "[":
198 rest = rest.dropFirst()
199 var values: [Value] = []
200 while true {
201 skipBlanks(&rest)
202 if rest.first == "]" { break }
203 values.append(try parseValue(&rest, line: line))
204 skipBlanks(&rest)
205 if rest.first == "," {
206 rest = rest.dropFirst()
207 } else if rest.first != "]" {
208 throw ParseError(line: line, message: rest.isEmpty ? "unclosed array" : "expected , or ] in array")
209 }
210 }
211 rest = rest.dropFirst()
212 return .array(values)
213 case "\"":
214 rest = rest.dropFirst()
215 var value = ""
216 while let c = rest.first {
217 rest = rest.dropFirst()
218 if c == "\"" { return .string(value) }
219 guard c == "\\" else {
220 value.append(c)
221 continue
222 }
223 guard let escaped = rest.first else { break }
224 rest = rest.dropFirst()
225 switch escaped {
226 case "\"": value.append("\"")
227 case "\\": value.append("\\")
228 case "n": value.append("\n")
229 case "t": value.append("\t")
230 case "u", "U":
231 let digits = escaped == "u" ? 4 : 8
232 guard let code = UInt32(rest.prefix(digits), radix: 16), let scalar = Unicode.Scalar(code), rest.count >= digits else {
233 throw ParseError(line: line, message: "bad unicode escape")
234 }
235 value.unicodeScalars.append(scalar)
236 rest = rest.dropFirst(digits)
237 default: throw ParseError(line: line, message: "bad escape \\\(escaped)")
238 }
239 }
240 throw ParseError(line: line, message: "unclosed string")
241 case "'":
242 rest = rest.dropFirst()
243 guard let end = rest.firstIndex(of: "'") else { throw ParseError(line: line, message: "unclosed string") }
244 let value = String(rest[..<end])
245 rest = rest[rest.index(after: end)...]
246 return .string(value)
247 default:
248 let word = rest.prefix { !$0.isWhitespace && $0 != "#" && $0 != "," && $0 != "]" }
249 rest = rest.dropFirst(word.count)
250 if word == "true" { return .bool(true) }
251 if word == "false" { return .bool(false) }
252 if let number = Int(word.replacingOccurrences(of: "_", with: "")) { return .integer(number) }
253 throw ParseError(line: line, message: "unsupported value \(word)")
254 }
255 }
256}