import Foundation public struct TOMLDocument: Sendable { public private(set) var source: String public private(set) var root: TOMLNode private var sections: [TOMLSection] private var editableRanges: [[TOMLPathComponent]: SourceRange] public init(parsing source: String) throws { var reader = TOMLReader(source) self.root = try reader.parse() self.source = source self.sections = reader.sections self.editableRanges = reader.editableRanges } public func render() -> String { source } public func node(at path: [TOMLPathComponent]) -> TOMLNode? { var node = root for component in path { switch (component, node.value) { case (.key(let key), .table(let entries)): guard let child = entries[key] else { return nil } node = child case (.index(let index), .array(let entries)): guard entries.indices.contains(index) else { return nil } node = entries[index] default: return nil } } return node } public func node(forKey path: [String]) -> TOMLNode? { node(at: path.map { .key($0) }) } public mutating func setValue(_ value: TOMLValue, forKey path: [String]) throws { try setValue(value, at: path.map { .key($0) }) } /// Reparse before committing an edit so a failed change never damages the document. public mutating func setValue(_ value: TOMLValue, at path: [TOMLPathComponent]) throws { let replacement = try TOMLWriter.encode(value) if let range = editableRanges[path] { try replace(range.start.offset.. String? in guard case .key(let key) = component else { return nil } return TOMLWriter.quote(key) } guard keys.count == suffix.count else { break } let insertion = parentRange.end.offset - 1 let separator = entries.isEmpty ? "" : ", " try replace(insertion.. String? in guard case .key(let key) = component else { return nil } return TOMLWriter.quote(key) } let newline = source.contains("\r\n") ? "\r\n" : "\n" let offset = section.insertionOffset let needsNewline = offset > 0 && Array(source.unicodeScalars)[offset - 1] != "\n" let assignment = (needsNewline ? newline : "") + keys.joined(separator: ".") + " = " + replacement + newline try replace(offset.., with replacement: String) throws { var scalars = Array(source.unicodeScalars) scalars.replaceSubrange(offsets, with: replacement.unicodeScalars) self = try TOMLDocument(parsing: String(String.UnicodeScalarView(scalars))) } private func editingError(_ message: String.LocalizationValue) -> ConfigDiagnostic { ConfigDiagnostic(message: String(localized: message, table: "Parser", bundle: .module)) } } public enum TOMLWriter { public static func write(_ document: TOMLDocument) -> String { document.source } public static func encode(_ value: TOMLValue) throws -> String { try encode(value, depth: 0) } private static func encode(_ value: TOMLValue, depth: Int) throws -> String { guard depth < 128 else { throw ConfigDiagnostic( message: String( localized: "This value is nested too deeply; use fewer than 128 levels.", table: "Parser", bundle: .module) ) } switch value { case .string(let string): return quote(string) case .integer(let integer): return String(integer) case .float(let number): if number.isNaN { return "nan" } if number == .infinity { return "inf" } if number == -.infinity { return "-inf" } return String(number) case .bool(let bool): return bool ? "true" : "false" case .array(let values): return "[" + (try values.map { try encode($0.value, depth: depth + 1) }).joined(separator: ", ") + "]" case .table(let values): let pairs = try values.sorted { $0.key < $1.key }.map { key, node in quote(key) + " = " + (try encode(node.value, depth: depth + 1)) } return "{" + pairs.joined(separator: ", ") + "}" } } static func quote(_ string: String) -> String { var result = "\"" for scalar in string.unicodeScalars { switch scalar { case "\"": result += "\\\"" case "\\": result += "\\\\" case "\n": result += "\\n" case "\r": result += "\\r" case "\t": result += "\\t" case "\u{08}": result += "\\b" case "\u{0C}": result += "\\f" default: if scalar.value < 0x20 || scalar.value == 0x7F { let hex = String(scalar.value, radix: 16, uppercase: true) result += "\\u" + String(repeating: "0", count: 4 - hex.count) + hex } else { result.unicodeScalars.append(scalar) } } } return result + "\"" } }