extension PureYAML.Emitting.Dumper { /// The YAML-specification canonical form, matching libyaml's canonical /// emitter layout: an explicit `---` document start, an explicit tag on /// every node, double-quoted scalars, and flow collections with one /// entry per line, mapping entries in the explicit `? key : value,` /// form. Tags derive from each value's case, the same resolution the /// parser applies in reverse. func canonicalDocument(_ value: PureYAML.Model.Value) -> String { "---\n" + canonicalBody(value) } /// The canonical body without the leading `---` marker, so the marker is /// owned by the single-document and stream paths, not baked into the body. func canonicalBody(_ value: PureYAML.Model.Value) -> String { canonicalLines(value, indent: 0).joined(separator: "\n") + "\n" } func canonicalLines( _ value: PureYAML.Model.Value, indent: Int, ) -> [String] { let prefix = String(repeating: " ", count: indent) switch value { case let .sequence(values): return canonicalSequenceLines(values, indent: indent) case let .mapping(mapping): return canonicalMappingLines(mapping, indent: indent) default: return [prefix + canonicalScalar(value)] } } func canonicalSequenceLines( _ values: [PureYAML.Model.Value], indent: Int, ) -> [String] { let prefix = String(repeating: " ", count: indent) guard !values.isEmpty else { return [prefix + "!!seq []"] } var lines = [prefix + "!!seq ["] for value in values { var entry = canonicalLines(value, indent: indent + options.indentWidth) entry[entry.count - 1] += "," lines.append(contentsOf: entry) } lines.append(prefix + "]") return lines } func canonicalMappingLines( _ mapping: PureYAML.Model.Mapping, indent: Int, ) -> [String] { let prefix = String(repeating: " ", count: indent) guard !mapping.pairs.isEmpty else { return [prefix + "!!map {}"] } let inner = indent + options.indentWidth let innerPrefix = String(repeating: " ", count: inner) var lines = [prefix + "!!map {"] for pair in orderedPairs(mapping) { var keyLines = canonicalLines(pair.keyNode.value, indent: inner) keyLines[0] = innerPrefix + "? " + String(keyLines[0].dropFirst(innerPrefix.count)) lines.append(contentsOf: keyLines) var valueLines = canonicalLines(pair.value, indent: inner) valueLines[0] = innerPrefix + ": " + String(valueLines[0].dropFirst(innerPrefix.count)) valueLines[valueLines.count - 1] += "," lines.append(contentsOf: valueLines) } lines.append(prefix + "}") return lines } /// A canonical scalar: the value's implicit tag made explicit, content /// double-quoted so no resolution ambiguity survives. func canonicalScalar(_ value: PureYAML.Model.Value) -> String { switch value { case .null: "!!null \"null\"" case let .bool(flag): "!!bool \"\(flag ? "true" : "false")\"" case let .int(number): "!!int \"\(number)\"" case let .double(number): "!!float \"\(number)\"" case let .string(string): "!!str " + quote(string) case .sequence, .mapping: "" } } }