PureYAML/Sources/Parsing/LibYAML.Scanner.Anchor.swift
Mihaela Mihaljevic 526abe9998 feat(parsing): port libyaml anchor and alias scanner to Swift
Stage 3 of the faithful libyaml scanner port, continued. Translates fetch_anchor and scan_anchor: an anchor (&name) or alias (*name) whose name is a run of IS_ALPHA characters, validated to be non-empty and followed by a blank, end of input, or a terminating indicator. The flow/quoted/anchor fetchers are consolidated into one indicator dispatch to stay within the complexity limit. Unit-tested for an anchored scalar value and a later alias. Remaining unported fetchers: tags, block scalars, directives. 311 tests, no regression.
2026-06-24 15:26:49 +02:00

38 lines
1.5 KiB
Swift

extension PureYAML.Parsing.LibYAML.Scanner {
private typealias Classify = PureYAML.Parsing.LibYAML.CharacterClass
/// Port of `yaml_parser_scan_anchor`. Scans an anchor (`&name`) or alias
/// (`*name`): the name is a run of `IS_ALPHA` characters and must be non-empty
/// and followed by a blank, the end of input, or one of the indicators that may
/// terminate it.
mutating func scanAnchor(isAnchor: Bool) throws -> PureYAML.Parsing.LibYAML.Token {
let startMark = reader.mark
reader.skip()
var name = ""
while let character = reader.peek(), Classify.isAlpha(character) {
name.unicodeScalars.append(character)
reader.skip()
}
let endMark = reader.mark
guard !name.isEmpty, Classify.isBlankZ(reader.peek()) || isAnchorTerminator(reader.peek()) else {
throw PureYAML.Parsing.LibYAML.ScannerError(
context: isAnchor ? "while scanning an anchor" : "while scanning an alias",
problem: "did not find expected alphabetic or numeric character",
mark: startMark,
)
}
return PureYAML.Parsing.LibYAML.Token(
type: isAnchor ? .anchor(name: name) : .alias(name: name),
startMark: startMark,
endMark: endMark,
)
}
private func isAnchorTerminator(_ scalar: Unicode.Scalar?) -> Bool {
switch scalar {
case "?", ":", ",", "]", "}", "%", "@", "`": true
default: false
}
}
}