// MARK: - Scalar styles extension PureYAML.Tagged.Dumper { /// Renders a scalar honoring its per-node style where the value can /// legally take it, falling back to double quoting otherwise. Values /// with a plain source style re-emit their source spelling when that /// spelling is syntactically safe. func renderScalarValue( _ scalar: PureYAML.Tagged.Scalar, flow: Bool, renderer: PureYAML.Emitting.Dumper, ) -> String { if scalar.value == .null, scalar.style == .plain, isPlainNullForm(scalar.rawValue) { // A plain null re-emits its source spelling: `key:` with an empty // value, `~`, and the null word forms all reparse to null, so the // source form is preserved instead of normalizing to "null". return scalar.rawValue } guard case let .string(string) = scalar.value else { return renderNonString(scalar, flow: flow, renderer: renderer) } switch scalar.style { case .plain: return renderPlainString(string, tag: scalar.tag, flow: flow, renderer: renderer) case .singleQuoted: return renderSingleQuoted(string, renderer: renderer) case .doubleQuoted: return renderer.quote(string) case .literal, .folded: // Multi-line handling happens in renderLiteralBlock; reaching // here means the value cannot take a block form (single line, or // flow context, or block-unsafe content), so quote it. return renderer.quote(string) case nil: return flow ? renderer.renderFlowScalar(scalar.value) : renderer.renderScalar(scalar.value) } } /// A plain non-string re-emits its source spelling when that spelling /// is syntactically safe: `NO` resolved to a bool and `1_000` to an int /// on parse, so the same resolver maps the same text back to the same /// value, and normalizing the spelling (`NO` to `false`) would lose the /// source form for nothing. func renderNonString( _ scalar: PureYAML.Tagged.Scalar, flow: Bool, renderer: PureYAML.Emitting.Dumper, ) -> String { if scalar.style == .plain, isSyntacticallyPlainSafe(scalar.rawValue, flow: flow, renderer: renderer) { return scalar.rawValue } return renderer.renderScalar(scalar.value) } /// A plain string must stay a string on reparse: without an explicit /// tag, content that resolves as a number, bool, or null must be /// quoted; with one, the tag governs resolution (`!!str 42` reparses as /// the string "42") and only syntax matters. func renderPlainString( _ string: String, tag: PureYAML.Tagged.Tag?, flow: Bool, renderer: PureYAML.Emitting.Dumper, ) -> String { let stringSafe = tag != nil || (!renderer.isReservedPlainScalar(string) && !renderer.isNumberLikePlainScalar(string)) return stringSafe && isSyntacticallyPlainSafe(string, flow: flow, renderer: renderer) ? string : renderer.quote(string) } /// Single quoting escapes only the quote itself (by doubling); content /// with line breaks has no exact single-quoted form (quoted folding /// would rewrite the breaks), so it degrades to double quoting. func renderSingleQuoted( _ string: String, renderer: PureYAML.Emitting.Dumper, ) -> String { guard !string.contains("\n"), !string.contains("\r") else { return renderer.quote(string) } var escaped = "" for character in string { escaped.append(character) if character == "'" { escaped.append("'") } } return "'" + escaped + "'" } /// The plain source spellings that reparse to null: an empty value, `~`, /// and the three null word forms. func isPlainNullForm(_ rawValue: String) -> Bool { switch rawValue { case "", "~", "null", "Null", "NULL": true default: false } } /// Syntactic plain safety, following the spec's actual rules rather than /// the emitter policy path's coarser ones: a leading `-`, `?`, or `:` is /// safe unless followed by a space (or alone), and `#` only opens a /// comment after whitespace, so a URL fragment stays plain. Resolution /// safety (a string that would re-resolve as a number or bool) is the /// caller's concern: it applies to untagged strings but is exactly wrong /// for non-strings re-emitting their source spelling. func isSyntacticallyPlainSafe( _ string: String, flow: Bool, renderer: PureYAML.Emitting.Dumper, ) -> Bool { guard !string.isEmpty, string.first?.isWhitespace == false, string.last?.isWhitespace == false, !string.contains("\n"), !string.contains("\r"), !string.contains("\t") else { return false } // A trailing `:` reparses as a mapping key with an empty value, so a // scalar that ends in one is not plain-safe even when no interior `:` // is followed by a space. guard string.last != ":", let first = string.first else { return false } let second = string.dropFirst().first switch first { case "-", "?", ":": if second == nil || second == " " { return false } case ",", "[", "]", "{", "}", "#", "&", "*", "!", "|", ">", "'", "\"", "%", "@", "`": return false default: break } guard !renderer.containsColonSpace(string), !containsCommentAfterSpace(string) else { return false } return !flow || !renderer.containsFlowDelimiter(string) } /// `#` starts a comment only when preceded by whitespace; a `#` embedded /// in a word (a URL fragment, an IP:port#tag form) is plain content. func containsCommentAfterSpace(_ string: String) -> Bool { var previousWasWhitespace = false for character in string { if character == "#", previousWasWhitespace { return true } previousWasWhitespace = character.isWhitespace } return false } } // MARK: - Block scalars extension PureYAML.Tagged.Dumper { /// Block-scalar rendering for `literal` and `folded` styles. A folded /// scalar re-emits as `>` when the value's shape allows an exact /// inversion of the folding rules, otherwise it degrades to a literal /// block (`|`), which still reproduces the value exactly; only the fold /// marks differ. Returns `nil` when the value cannot take any block /// form, in which case the scalar falls back to double quoting. func renderLiteralBlock( _ scalar: PureYAML.Tagged.Scalar, props: String, contentIndent: Int, ) -> (header: String, content: [String])? { guard case let .string(string) = scalar.value, scalar.style == .literal || scalar.style == .folded else { return nil } if scalar.style == .folded, let folded = renderFoldedBlock(string, props: props, contentIndent: contentIndent) { return folded } guard canRenderLiteralBlockContent(string) else { return nil } let trailingNewlines = countTrailingNewlines(string) let chomping: String let contentSource: String switch trailingNewlines { case 0: chomping = "-" contentSource = string case 1: chomping = "" contentSource = String(string.dropLast()) default: // Two or more trailing newlines need keep chomping: clip (`|`) // would collapse them to one. chomping = "+" contentSource = String(string.dropLast()) } // A whitespace-led first content line defeats indentation // auto-detection, so the header carries an explicit indentation // indicator and the leading whitespace becomes content. let needsIndicator = firstContentLine(of: contentSource)?.first?.isWhitespace == true if needsIndicator, !(1 ... 9).contains(options.indentWidth) { return nil } let indicator = "|" + (needsIndicator ? String(options.indentWidth) : "") + chomping let header = props.isEmpty ? indicator : props + " " + indicator let prefix = String(repeating: " ", count: contentIndent) let content = contentSource .split(separator: "\n", omittingEmptySubsequences: false) .map { $0.isEmpty ? "" : prefix + String($0) } return (header, content) } /// Exact inversion of folding for the shapes that allow one: every /// logical line separated by single newlines, no empty logical lines, no /// leading or trailing whitespace per line. Emitting each logical line /// as its own paragraph (blank line between) folds back to exactly one /// newline per boundary. func renderFoldedBlock( _ string: String, props: String, contentIndent: Int, ) -> (header: String, content: [String])? { let trailingNewlines = countTrailingNewlines(string) guard trailingNewlines <= 1 else { return nil } let contentSource = trailingNewlines == 1 ? String(string.dropLast()) : string guard !contentSource.isEmpty, !contentSource.contains("\r"), !contentSource.contains("\t") else { return nil } let lines = contentSource.split(separator: "\n", omittingEmptySubsequences: false) let safe = lines.allSatisfy { line in !line.isEmpty && line.first?.isWhitespace == false && line.last?.isWhitespace == false } guard safe else { return nil } let indicator = trailingNewlines == 1 ? ">" : ">-" let header = props.isEmpty ? indicator : props + " " + indicator let prefix = String(repeating: " ", count: contentIndent) var content: [String] = [] for (index, line) in lines.enumerated() { if index > 0 { content.append("") } content.append(prefix + String(line)) } return (header, content) } func countTrailingNewlines(_ string: String) -> Int { var count = 0 for character in string.reversed() { guard character == "\n" else { break } count += 1 } return count } /// A literal block can hold any string with at least one non-empty line /// and no carriage returns (single-line content emits as `|-`, a /// whitespace-led first line gets an explicit indentation indicator). /// Trailing spaces, tab-led or whitespace-only interior lines, leading /// blank lines, and more deeply indented interior lines are all /// preserved content: the block's own indent is stripped and the rest /// survives verbatim. func canRenderLiteralBlockContent(_ value: String) -> Bool { guard !value.contains("\r") else { return false } let contentSource = value.hasSuffix("\n") ? String(value.dropLast()) : value guard !contentSource.isEmpty else { return false } return firstContentLine(of: contentSource) != nil } func firstContentLine(of contentSource: String) -> Substring? { contentSource .split(separator: "\n", omittingEmptySubsequences: false) .first { !$0.isEmpty } } }