import Foundation /// The part of TOML keymaps use: `[table]` and `[[array-of-tables]]` headers, and /// `key = value` lines with basic or literal strings (multi-line ones too), booleans, /// integers and arrays of these, which may run over several lines. Comments start with `#` /// outside strings. public enum TOML { public enum Value: Sendable, Equatable { case string(String) case bool(Bool) case integer(Int) case array([Value]) public var string: String? { if case .string(let value) = self { return value } return nil } public var bool: Bool? { if case .bool(let value) = self { return value } return nil } public var integer: Int? { if case .integer(let value) = self { return value } return nil } public var array: [Value]? { if case .array(let value) = self { return value } return nil } } public struct Table: Sendable, Equatable { /// Empty for keys before the first header. public var name: String /// Declared with `[[name]]`. public var isArrayElement: Bool public var values: [String: Value] /// 1-based line of the header. public var line: Int /// The keys in the order they appear. public var keys: [String] = [] } public struct ParseError: Error, Equatable, CustomStringConvertible { public let line: Int public let message: String public var description: String { "line \(line): \(message)" } } /// Tables in file order. public static func parse(_ text: String) throws -> [Table] { var tables = [Table(name: "", isArrayElement: false, values: [:], line: 0)] let lines = text.split(separator: "\n", omittingEmptySubsequences: false) var index = 0 while index < lines.count { let number = index + 1 let line = lines[index].trimmingCharacters(in: [" ", "\t", "\r"]) index += 1 if line.isEmpty || line.hasPrefix("#") { continue } if line.hasPrefix("[") { let isArray = line.hasPrefix("[[") let close = isArray ? "]]" : "]" let body = line.dropFirst(isArray ? 2 : 1) guard let end = body.range(of: close) else { throw ParseError(line: number, message: "unclosed table header") } let rest = body[end.upperBound...].trimmingCharacters(in: [" ", "\t"]) guard rest.isEmpty || rest.hasPrefix("#") else { throw ParseError(line: number, message: "text after table header") } let name = body[.. String { let body = raw.hasPrefix("\n") ? String(raw.dropFirst()) : raw if literal { return body } var out = "" var rest = Substring(body) while let c = rest.first { rest = rest.dropFirst() guard c == "\\" else { out.append(c) continue } let blanks = rest.prefix { $0 == " " || $0 == "\t" } if rest.dropFirst(blanks.count).first == "\n" { rest = rest.drop { $0.isWhitespace } continue } guard let escaped = rest.first else { throw ParseError(line: line, message: "bad escape") } rest = rest.dropFirst() switch escaped { case "\"": out.append("\"") case "\\": out.append("\\") case "n": out.append("\n") case "t": out.append("\t") case "u", "U": let digits = escaped == "u" ? 4 : 8 guard rest.count >= digits, let code = UInt32(rest.prefix(digits), radix: 16), let scalar = Unicode.Scalar(code) else { throw ParseError(line: line, message: "bad unicode escape") } out.unicodeScalars.append(scalar) rest = rest.dropFirst(digits) default: throw ParseError(line: line, message: "bad escape \\\(escaped)") } } return out } /// Whether `text`, starting with `[`, has the bracket that closes it, outside strings and /// comments. private static func closesArray(_ text: String) -> Bool { var depth = 0 var quote: Character? var comment = false var escaped = false for c in text { if comment { if c == "\n" { comment = false } } else if let q = quote { if escaped { escaped = false } else if c == "\\" && q == "\"" { escaped = true } else if c == q { quote = nil } } else { switch c { case "\"", "'": quote = c case "#": comment = true case "[": depth += 1 case "]": depth -= 1 if depth == 0 { return true } default: break } } } return false } /// Spaces, line ends and comments between an array's values. private static func skipBlanks(_ rest: inout Substring) { while let c = rest.first { if c.isWhitespace { rest = rest.dropFirst() } else if c == "#" { rest = rest.drop { $0 != "\n" } } else { return } } } private static func parseValue(_ rest: inout Substring, line: Int) throws -> Value { switch rest.first { case "[": rest = rest.dropFirst() var values: [Value] = [] while true { skipBlanks(&rest) if rest.first == "]" { break } values.append(try parseValue(&rest, line: line)) skipBlanks(&rest) if rest.first == "," { rest = rest.dropFirst() } else if rest.first != "]" { throw ParseError(line: line, message: rest.isEmpty ? "unclosed array" : "expected , or ] in array") } } rest = rest.dropFirst() return .array(values) case "\"": rest = rest.dropFirst() var value = "" while let c = rest.first { rest = rest.dropFirst() if c == "\"" { return .string(value) } guard c == "\\" else { value.append(c) continue } guard let escaped = rest.first else { break } rest = rest.dropFirst() switch escaped { case "\"": value.append("\"") case "\\": value.append("\\") case "n": value.append("\n") case "t": value.append("\t") case "u", "U": let digits = escaped == "u" ? 4 : 8 guard let code = UInt32(rest.prefix(digits), radix: 16), let scalar = Unicode.Scalar(code), rest.count >= digits else { throw ParseError(line: line, message: "bad unicode escape") } value.unicodeScalars.append(scalar) rest = rest.dropFirst(digits) default: throw ParseError(line: line, message: "bad escape \\\(escaped)") } } throw ParseError(line: line, message: "unclosed string") case "'": rest = rest.dropFirst() guard let end = rest.firstIndex(of: "'") else { throw ParseError(line: line, message: "unclosed string") } let value = String(rest[..