feat(parser): add a streaming, iterative XML parser
Replace the notImplemented stub with a real parser built on a pull-based, streaming event core that never requires the whole document in memory. - Parsing.EventReader: pulls characters through a source closure with a bounded lookahead buffer and emits one Parsing.Event at a time, holding only an open-element stack. Drives chunked/streamed input. - Parsing.Parser: builds a Model.Node tree iteratively over the event core (explicit stack, no recursion). - Reader: streaming character cursor (closure-backed, bounded buffer) replacing the previous whole-string Array. - EntityDecoder: the five predefined entities and decimal/hex char references. - Handles elements, attributes, text, comments, CDATA, processing instructions, and an XML declaration in the prolog. Rejects <!DOCTYPE> by default (no DTD/XXE/entity-expansion exposure). - Top-level API: parse(_:), parse(pulling:), events(_:), events(pulling:). - 21 tests including event-stream and chunked-source coverage.
This commit is contained in:
parent
7683c67449
commit
5c306482e5
13
CHANGELOG.md
13
CHANGELOG.md
@ -17,6 +17,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
output and correct text and attribute escaping.
|
||||
- Structural validation (`PureXML.Validation.Validator`) for duplicate attribute
|
||||
names.
|
||||
- Stable parser surface (`PureXML.Parsing.Parser`, `ParseError`, `Mark`).
|
||||
`PureXML.parse(_:)` raises `ParseError.notImplemented` until the scanner lands;
|
||||
the gap is pinned by a test.
|
||||
- Streaming, iterative XML parser. `PureXML.Parsing.EventReader` is a pull-based
|
||||
event core that consumes input through a character-source closure and emits one
|
||||
`Event` at a time, holding only bounded state (an open-element stack and a small
|
||||
lookahead buffer). It never requires the whole document in memory and can drive
|
||||
chunked input. `PureXML.Parsing.Parser` builds a `Model.Node` tree iteratively
|
||||
over the event core (no recursion). Handles elements, attributes, text, the five
|
||||
predefined entities and numeric character references, comments, CDATA, and
|
||||
processing instructions. Safe by default: `<!DOCTYPE>` is rejected (no DTD/XXE).
|
||||
- Top-level API: `PureXML.parse(_:)`, `PureXML.parse(pulling:)`, and
|
||||
`PureXML.events(_:)` / `PureXML.events(pulling:)` for streaming.
|
||||
|
||||
27
README.md
27
README.md
@ -21,8 +21,8 @@ follows the same structure, rules, and verification gates.
|
||||
|
||||
## Status
|
||||
|
||||
This is an early scaffold. The node model and the emitter are implemented and
|
||||
usable today; the tokenizing parser is still being built.
|
||||
The node model, the emitter, and a streaming parser are implemented and usable
|
||||
today.
|
||||
|
||||
- **Model** (`PureXML.Model`): `Node`, `Element`, `Attribute`, `QualifiedName`.
|
||||
Preserves document order and the distinction between text, CDATA, comments,
|
||||
@ -33,10 +33,15 @@ usable today; the tokenizing parser is still being built.
|
||||
- **Validation** (`PureXML.Validation`): structural checks such as duplicate
|
||||
attribute names. Schema validation (DTD/XSD/RELAX NG) is out of scope for the
|
||||
library target.
|
||||
- **Parsing** (`PureXML.Parsing`): the public surface (`Parser`, `ParseError`,
|
||||
`Mark`) is stable. `PureXML.parse(_:)` currently raises
|
||||
`ParseError.notImplemented` so callers can wire against the final API before
|
||||
the scanner lands. The gap is pinned by a test rather than left silent.
|
||||
- **Parsing** (`PureXML.Parsing`): a streaming, iterative parser. `EventReader`
|
||||
is a pull-based event core that consumes input through a character-source
|
||||
closure and emits one `Event` at a time, never holding the whole document in
|
||||
memory (it drives chunked input). `Parser` builds a `Model.Node` tree
|
||||
iteratively over the event core. Handles elements, attributes, text, the five
|
||||
predefined entities and numeric character references, comments, CDATA, and
|
||||
processing instructions. Safe by default: `<!DOCTYPE>` is rejected, which
|
||||
removes the DTD-based threat classes (XXE, entity-expansion DoS). DTD support,
|
||||
namespaces-as-resolved-URIs, and validation are deliberate future layers.
|
||||
|
||||
## Usage
|
||||
|
||||
@ -53,8 +58,14 @@ let element = PureXML.Model.Element(
|
||||
let xml = PureXML.serialize(.element(element))
|
||||
try PureXML.validate(.element(element))
|
||||
|
||||
// Parsing is not implemented yet:
|
||||
// let node = try PureXML.parse(xml)
|
||||
// Parse it back into a tree.
|
||||
let node = try PureXML.parse(xml)
|
||||
|
||||
// Or stream events without building a tree (drives chunked input too).
|
||||
var reader = PureXML.events(xml)
|
||||
while let event = try reader.next() {
|
||||
// handle .startElement / .characters / .endElement / ...
|
||||
}
|
||||
```
|
||||
|
||||
## Attribution
|
||||
|
||||
@ -8,6 +8,25 @@ public extension PureXML {
|
||||
try Parsing.Parser().parse(xml)
|
||||
}
|
||||
|
||||
/// Parses an XML document from an incremental character source into a
|
||||
/// ``Model/Node`` tree. The closure returns the next character or nil at end
|
||||
/// of input, so the document can arrive in chunks and is never held whole.
|
||||
static func parse(pulling pull: @escaping () -> Character?) throws -> Model.Node {
|
||||
try Parsing.Parser().parse(pulling: pull)
|
||||
}
|
||||
|
||||
/// Returns a streaming ``Parsing/EventReader`` over an XML string. Pull events
|
||||
/// one at a time with `next()` to process documents without building a tree.
|
||||
static func events(_ xml: String) -> Parsing.EventReader {
|
||||
Parsing.EventReader(xml)
|
||||
}
|
||||
|
||||
/// Returns a streaming ``Parsing/EventReader`` over an incremental character
|
||||
/// source, for processing arbitrarily large or chunked input.
|
||||
static func events(pulling pull: @escaping () -> Character?) -> Parsing.EventReader {
|
||||
Parsing.EventReader(pulling: pull)
|
||||
}
|
||||
|
||||
/// Serializes a ``Model/Node`` tree into XML with the selected options.
|
||||
static func serialize(
|
||||
_ node: Model.Node,
|
||||
|
||||
54
Sources/Parsing/EntityDecoder.swift
Normal file
54
Sources/Parsing/EntityDecoder.swift
Normal file
@ -0,0 +1,54 @@
|
||||
extension PureXML.Parsing {
|
||||
/// Decodes XML references inside text and attribute values: the five
|
||||
/// predefined entities and decimal/hex character references. General entity
|
||||
/// declarations from a DTD are deliberately not supported (DTD processing is
|
||||
/// off by default), so any other `&name;` is rejected rather than expanded.
|
||||
enum EntityDecoder {
|
||||
static func decode(_ raw: String, at mark: Mark) throws -> String {
|
||||
guard raw.contains("&") else { return raw }
|
||||
var result = ""
|
||||
var iterator = raw.startIndex
|
||||
while iterator < raw.endIndex {
|
||||
let character = raw[iterator]
|
||||
guard character == "&" else {
|
||||
result.append(character)
|
||||
iterator = raw.index(after: iterator)
|
||||
continue
|
||||
}
|
||||
guard let semicolon = raw[iterator...].firstIndex(of: ";") else {
|
||||
throw PureXML.Parsing.ParseError.invalidReference(String(raw[iterator...]), mark)
|
||||
}
|
||||
let body = String(raw[raw.index(after: iterator) ..< semicolon])
|
||||
try result.append(resolve(body, at: mark))
|
||||
iterator = raw.index(after: semicolon)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private static func resolve(_ body: String, at mark: Mark) throws -> Character {
|
||||
switch body {
|
||||
case "amp": return "&"
|
||||
case "lt": return "<"
|
||||
case "gt": return ">"
|
||||
case "quot": return "\""
|
||||
case "apos": return "'"
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
guard body.hasPrefix("#") else {
|
||||
throw PureXML.Parsing.ParseError.invalidReference("&\(body);", mark)
|
||||
}
|
||||
let digits = String(body.dropFirst())
|
||||
let scalarValue: UInt32? = if digits.hasPrefix("x") || digits.hasPrefix("X") {
|
||||
UInt32(digits.dropFirst(), radix: 16)
|
||||
} else {
|
||||
UInt32(digits, radix: 10)
|
||||
}
|
||||
guard let value = scalarValue, let scalar = Unicode.Scalar(value) else {
|
||||
throw PureXML.Parsing.ParseError.invalidReference("&\(body);", mark)
|
||||
}
|
||||
return Character(scalar)
|
||||
}
|
||||
}
|
||||
}
|
||||
15
Sources/Parsing/Event.swift
Normal file
15
Sources/Parsing/Event.swift
Normal file
@ -0,0 +1,15 @@
|
||||
public extension PureXML.Parsing {
|
||||
/// A single XML parse event emitted by the streaming ``EventReader``.
|
||||
///
|
||||
/// An empty element `<br/>` emits ``startElement(name:attributes:)`` followed
|
||||
/// immediately by ``endElement(name:)``, so consumers see a consistent
|
||||
/// open/close pair regardless of the source syntax.
|
||||
enum Event: Equatable, Sendable {
|
||||
case startElement(name: PureXML.Model.QualifiedName, attributes: [PureXML.Model.Attribute])
|
||||
case endElement(name: PureXML.Model.QualifiedName)
|
||||
case characters(String)
|
||||
case cdata(String)
|
||||
case comment(String)
|
||||
case processingInstruction(target: String, data: String)
|
||||
}
|
||||
}
|
||||
248
Sources/Parsing/EventReader.swift
Normal file
248
Sources/Parsing/EventReader.swift
Normal file
@ -0,0 +1,248 @@
|
||||
public extension PureXML.Parsing {
|
||||
/// A pull-based, streaming XML event reader.
|
||||
///
|
||||
/// It consumes its input incrementally through a character-source closure and
|
||||
/// emits one ``Event`` at a time from ``next()``, holding only bounded state:
|
||||
/// a stack of open element names and a small lookahead buffer. It never
|
||||
/// requires the whole document in memory, so it can drive arbitrarily large
|
||||
/// or chunked input (a file, a socket, a generator). The tree-building
|
||||
/// ``Parser`` is a thin adapter over this core.
|
||||
///
|
||||
/// Safe by default: a `<!DOCTYPE ...>` declaration is rejected rather than
|
||||
/// processed, removing the DTD-based threat classes (XXE, entity-expansion
|
||||
/// DoS) at the door.
|
||||
struct EventReader {
|
||||
private var reader: Reader
|
||||
private var open: [PureXML.Model.QualifiedName] = []
|
||||
private var pending: [Event] = []
|
||||
private var sawRoot = false
|
||||
private var primed = false
|
||||
|
||||
/// Creates a reader over a character-pulling source. The closure returns
|
||||
/// the next character or nil at end of input.
|
||||
init(pulling pull: @escaping () -> Character?) {
|
||||
reader = Reader(pulling: pull)
|
||||
}
|
||||
|
||||
/// Creates a reader over a string (a convenience over the streaming init).
|
||||
init(_ string: String) {
|
||||
reader = Reader(string)
|
||||
}
|
||||
|
||||
/// Returns the next event, or nil at the end of the document.
|
||||
mutating func next() throws -> Event? {
|
||||
if !primed {
|
||||
primed = true
|
||||
if reader.peek() == "\u{FEFF}" {
|
||||
reader.advance()
|
||||
}
|
||||
}
|
||||
if !pending.isEmpty {
|
||||
return pending.removeFirst()
|
||||
}
|
||||
return open.isEmpty ? try nextAtTopLevel() : try nextInContent()
|
||||
}
|
||||
|
||||
private mutating func nextAtTopLevel() throws -> Event? {
|
||||
while true {
|
||||
reader.skipSpace()
|
||||
guard let lead = reader.peek() else {
|
||||
return nil
|
||||
}
|
||||
if reader.matches("<!--") {
|
||||
return try scanComment()
|
||||
}
|
||||
if reader.matches("<![CDATA[") {
|
||||
throw ParseError.unexpectedCharacter("[", reader.mark)
|
||||
}
|
||||
if reader.matches("<?") {
|
||||
let instruction = try scanProcessingInstruction()
|
||||
if instruction.target.lowercased() == "xml" {
|
||||
continue
|
||||
}
|
||||
return .processingInstruction(target: instruction.target, data: instruction.data)
|
||||
}
|
||||
if reader.matches("<!DOCTYPE") {
|
||||
throw ParseError.unsupportedDoctype(reader.mark)
|
||||
}
|
||||
if reader.matches("</") {
|
||||
throw ParseError.unexpectedEndTag(name: "", reader.mark)
|
||||
}
|
||||
if lead == "<" {
|
||||
if sawRoot {
|
||||
throw ParseError.junkAfterDocumentElement(reader.mark)
|
||||
}
|
||||
return try scanStartTag()
|
||||
}
|
||||
throw ParseError.junkAfterDocumentElement(reader.mark)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func nextInContent() throws -> Event? {
|
||||
guard let lead = reader.peek() else {
|
||||
throw ParseError.unexpectedEndOfInput(reader.mark)
|
||||
}
|
||||
if reader.matches("</") {
|
||||
return try scanEndTag()
|
||||
}
|
||||
if reader.matches("<!--") {
|
||||
return try scanComment()
|
||||
}
|
||||
if reader.matches("<![CDATA[") {
|
||||
return try scanCDATA()
|
||||
}
|
||||
if reader.matches("<?") {
|
||||
let instruction = try scanProcessingInstruction()
|
||||
return .processingInstruction(target: instruction.target, data: instruction.data)
|
||||
}
|
||||
if reader.matches("<!DOCTYPE") {
|
||||
throw ParseError.unsupportedDoctype(reader.mark)
|
||||
}
|
||||
if lead == "<" {
|
||||
return try scanStartTag()
|
||||
}
|
||||
return try scanText()
|
||||
}
|
||||
|
||||
private mutating func scanStartTag() throws -> Event {
|
||||
reader.consume("<")
|
||||
let name = try scanName()
|
||||
let attributes = try scanAttributes()
|
||||
if reader.consume("/>") {
|
||||
pending.append(.endElement(name: name))
|
||||
sawRoot = true
|
||||
return .startElement(name: name, attributes: attributes)
|
||||
}
|
||||
guard reader.consume(">") else {
|
||||
throw ParseError.unterminatedTag(reader.mark)
|
||||
}
|
||||
open.append(name)
|
||||
sawRoot = true
|
||||
return .startElement(name: name, attributes: attributes)
|
||||
}
|
||||
|
||||
private mutating func scanEndTag() throws -> Event {
|
||||
let mark = reader.mark
|
||||
reader.consume("</")
|
||||
let name = try scanName()
|
||||
reader.skipSpace()
|
||||
guard reader.consume(">") else {
|
||||
throw ParseError.unterminatedTag(reader.mark)
|
||||
}
|
||||
guard let top = open.last else {
|
||||
throw ParseError.unexpectedEndTag(name: name.description, mark)
|
||||
}
|
||||
guard top == name else {
|
||||
throw ParseError.mismatchedEndTag(expected: top.description, found: name.description, mark)
|
||||
}
|
||||
open.removeLast()
|
||||
return .endElement(name: name)
|
||||
}
|
||||
|
||||
private mutating func scanText() throws -> Event {
|
||||
let mark = reader.mark
|
||||
var raw = ""
|
||||
while let character = reader.peek(), character != "<" {
|
||||
raw.append(character)
|
||||
reader.advance()
|
||||
}
|
||||
return try .characters(EntityDecoder.decode(raw, at: mark))
|
||||
}
|
||||
|
||||
private mutating func scanComment() throws -> Event {
|
||||
let mark = reader.mark
|
||||
reader.consume("<!--")
|
||||
var content = ""
|
||||
while !reader.matches("-->") {
|
||||
guard let character = reader.advance() else {
|
||||
throw ParseError.unterminatedComment(mark)
|
||||
}
|
||||
content.append(character)
|
||||
}
|
||||
reader.consume("-->")
|
||||
return .comment(content)
|
||||
}
|
||||
|
||||
private mutating func scanCDATA() throws -> Event {
|
||||
let mark = reader.mark
|
||||
reader.consume("<![CDATA[")
|
||||
var content = ""
|
||||
while !reader.matches("]]>") {
|
||||
guard let character = reader.advance() else {
|
||||
throw ParseError.unterminatedCDATA(mark)
|
||||
}
|
||||
content.append(character)
|
||||
}
|
||||
reader.consume("]]>")
|
||||
return .cdata(content)
|
||||
}
|
||||
|
||||
private mutating func scanProcessingInstruction() throws -> (target: String, data: String) {
|
||||
let mark = reader.mark
|
||||
reader.consume("<?")
|
||||
let target = try scanName()
|
||||
reader.skipSpace()
|
||||
var data = ""
|
||||
while !reader.matches("?>") {
|
||||
guard let character = reader.advance() else {
|
||||
throw ParseError.unterminatedTag(mark)
|
||||
}
|
||||
data.append(character)
|
||||
}
|
||||
reader.consume("?>")
|
||||
return (target.description, data)
|
||||
}
|
||||
|
||||
private mutating func scanAttributes() throws -> [PureXML.Model.Attribute] {
|
||||
var attributes: [PureXML.Model.Attribute] = []
|
||||
var seen: Set<String> = []
|
||||
while true {
|
||||
reader.skipSpace()
|
||||
guard let next = reader.peek(), next != ">", next != "/" else {
|
||||
return attributes
|
||||
}
|
||||
let mark = reader.mark
|
||||
let name = try scanName()
|
||||
reader.skipSpace()
|
||||
guard reader.consume("=") else {
|
||||
throw ParseError.expectedEquals(reader.mark)
|
||||
}
|
||||
reader.skipSpace()
|
||||
let value = try scanAttributeValue()
|
||||
guard seen.insert(name.description).inserted else {
|
||||
throw ParseError.duplicateAttribute(name: name.description, mark)
|
||||
}
|
||||
attributes.append(PureXML.Model.Attribute(name: name, value: value))
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func scanAttributeValue() throws -> String {
|
||||
let mark = reader.mark
|
||||
guard let quote = reader.peek(), quote == "\"" || quote == "'" else {
|
||||
throw ParseError.unquotedAttributeValue(reader.mark)
|
||||
}
|
||||
reader.advance()
|
||||
var raw = ""
|
||||
while let character = reader.peek(), character != quote {
|
||||
raw.append(character)
|
||||
reader.advance()
|
||||
}
|
||||
guard reader.consume(String(quote)) else {
|
||||
throw ParseError.unexpectedEndOfInput(reader.mark)
|
||||
}
|
||||
return try EntityDecoder.decode(raw, at: mark)
|
||||
}
|
||||
|
||||
private mutating func scanName() throws -> PureXML.Model.QualifiedName {
|
||||
guard let first = reader.peek(), first.isXMLNameStart else {
|
||||
throw ParseError.expectedName(reader.mark)
|
||||
}
|
||||
var raw = ""
|
||||
while let character = reader.peek(), character.isXMLNameContinuation {
|
||||
raw.append(character)
|
||||
reader.advance()
|
||||
}
|
||||
return PureXML.Model.QualifiedName(raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -9,6 +9,16 @@ public extension PureXML.Parsing {
|
||||
case unterminatedCDATA(Mark)
|
||||
case mismatchedEndTag(expected: String, found: String, Mark)
|
||||
case duplicateAttribute(name: String, Mark)
|
||||
case expectedName(Mark)
|
||||
case expectedEquals(Mark)
|
||||
case unquotedAttributeValue(Mark)
|
||||
case invalidReference(String, Mark)
|
||||
case unexpectedEndTag(name: String, Mark)
|
||||
case junkAfterDocumentElement(Mark)
|
||||
/// A `<!DOCTYPE ...>` declaration was found. DTD processing is disabled by
|
||||
/// default as a security posture (XXE, entity-expansion DoS); enabling it
|
||||
/// is a deliberate future opt-in, not silent behavior.
|
||||
case unsupportedDoctype(Mark)
|
||||
/// Raised by entry points whose parsing path is not implemented yet.
|
||||
case notImplemented(String)
|
||||
|
||||
@ -30,6 +40,20 @@ public extension PureXML.Parsing {
|
||||
"expected </\(expected)> but found </\(found)> at \(mark)"
|
||||
case let .duplicateAttribute(name, mark):
|
||||
"duplicate attribute '\(name)' at \(mark)"
|
||||
case let .expectedName(mark):
|
||||
"expected a name at \(mark)"
|
||||
case let .expectedEquals(mark):
|
||||
"expected '=' after attribute name at \(mark)"
|
||||
case let .unquotedAttributeValue(mark):
|
||||
"attribute value must be quoted at \(mark)"
|
||||
case let .invalidReference(reference, mark):
|
||||
"invalid reference '\(reference)' at \(mark)"
|
||||
case let .unexpectedEndTag(name, mark):
|
||||
"unexpected end tag </\(name)> at \(mark)"
|
||||
case let .junkAfterDocumentElement(mark):
|
||||
"content after the root element at \(mark)"
|
||||
case let .unsupportedDoctype(mark):
|
||||
"DTD processing is disabled (DOCTYPE at \(mark))"
|
||||
case let .notImplemented(detail):
|
||||
"not implemented: \(detail)"
|
||||
}
|
||||
|
||||
@ -1,17 +1,80 @@
|
||||
/// A partially-built element while its children stream in. File-scope and
|
||||
/// private: an internal detail of the tree builder, not part of the namespace.
|
||||
private struct ElementFrame {
|
||||
let name: PureXML.Model.QualifiedName
|
||||
let attributes: [PureXML.Model.Attribute]
|
||||
var children: [PureXML.Model.Node] = []
|
||||
}
|
||||
|
||||
public extension PureXML.Parsing {
|
||||
/// The pure-Swift XML parser.
|
||||
///
|
||||
/// The tokenizing scanner and the well-formedness rules are still being
|
||||
/// built out. The public entry points exist and are stable; calling them
|
||||
/// today raises ``ParseError/notImplemented(_:)`` so that downstream code
|
||||
/// can wire against the final surface before the parser lands.
|
||||
/// Builds a ``PureXML/Model/Node`` tree by draining the streaming
|
||||
/// ``EventReader`` with an explicit element stack. It is iterative, not
|
||||
/// recursive, and the streaming core means it never requires the whole input
|
||||
/// in memory at once: characters are pulled on demand. Callers that do not
|
||||
/// need a full tree should consume ``EventReader`` directly.
|
||||
struct Parser: Sendable {
|
||||
public init() {}
|
||||
|
||||
/// Parses a single XML document into a ``PureXML/Model/Node/document(_:)`` tree.
|
||||
/// Parses a single XML document from a string into a document node.
|
||||
public func parse(_ xml: String) throws -> PureXML.Model.Node {
|
||||
guard !xml.isEmpty else { throw ParseError.emptyDocument }
|
||||
throw ParseError.notImplemented("document parsing")
|
||||
try build(EventReader(xml))
|
||||
}
|
||||
|
||||
/// Parses a single XML document from an incremental character source. The
|
||||
/// closure returns the next character or nil at end of input, so the
|
||||
/// document can arrive in chunks and is never held whole.
|
||||
public func parse(pulling pull: @escaping () -> Character?) throws -> PureXML.Model.Node {
|
||||
try build(EventReader(pulling: pull))
|
||||
}
|
||||
|
||||
private func build(_ source: EventReader) throws -> PureXML.Model.Node {
|
||||
var reader = source
|
||||
var roots: [PureXML.Model.Node] = []
|
||||
var stack: [ElementFrame] = []
|
||||
var produced = false
|
||||
|
||||
while let event = try reader.next() {
|
||||
produced = true
|
||||
switch event {
|
||||
case let .startElement(name, attributes):
|
||||
stack.append(ElementFrame(name: name, attributes: attributes))
|
||||
case .endElement:
|
||||
guard let frame = stack.popLast() else {
|
||||
throw ParseError.unexpectedEndOfInput(.start)
|
||||
}
|
||||
let element = PureXML.Model.Element(
|
||||
name: frame.name,
|
||||
attributes: frame.attributes,
|
||||
children: frame.children,
|
||||
)
|
||||
attach(.element(element), to: &stack, roots: &roots)
|
||||
case let .characters(text):
|
||||
attach(.text(text), to: &stack, roots: &roots)
|
||||
case let .cdata(text):
|
||||
attach(.cdata(text), to: &stack, roots: &roots)
|
||||
case let .comment(text):
|
||||
attach(.comment(text), to: &stack, roots: &roots)
|
||||
case let .processingInstruction(target, data):
|
||||
attach(.processingInstruction(target: target, data: data), to: &stack, roots: &roots)
|
||||
}
|
||||
}
|
||||
|
||||
guard produced else {
|
||||
throw ParseError.emptyDocument
|
||||
}
|
||||
return .document(roots)
|
||||
}
|
||||
|
||||
private func attach(
|
||||
_ node: PureXML.Model.Node,
|
||||
to stack: inout [ElementFrame],
|
||||
roots: inout [PureXML.Model.Node],
|
||||
) {
|
||||
if stack.isEmpty {
|
||||
roots.append(node)
|
||||
} else {
|
||||
stack[stack.count - 1].children.append(node)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
105
Sources/Parsing/Reader.swift
Normal file
105
Sources/Parsing/Reader.swift
Normal file
@ -0,0 +1,105 @@
|
||||
extension PureXML.Parsing {
|
||||
/// A streaming character cursor. It pulls characters from a source closure
|
||||
/// one at a time, keeping only a small lookahead buffer, so it never holds
|
||||
/// the whole input in memory. Tracks line, column, and offset for
|
||||
/// diagnostics. Internal to the parser; not part of the API.
|
||||
struct Reader {
|
||||
private let pull: () -> Character?
|
||||
private var buffer: [Character] = []
|
||||
private var exhausted = false
|
||||
private(set) var offset = 0
|
||||
private(set) var line = 1
|
||||
private(set) var column = 1
|
||||
|
||||
init(pulling pull: @escaping () -> Character?) {
|
||||
self.pull = pull
|
||||
}
|
||||
|
||||
init(_ string: String) {
|
||||
var iterator = string.makeIterator()
|
||||
self.init(pulling: { iterator.next() })
|
||||
}
|
||||
|
||||
/// Ensures the lookahead buffer holds at least `count` characters (or the
|
||||
/// source is exhausted). The buffer stays bounded by the largest lookahead
|
||||
/// any single scan needs, never by the document size.
|
||||
private mutating func ensure(_ count: Int) {
|
||||
while buffer.count < count, !exhausted {
|
||||
if let character = pull() {
|
||||
buffer.append(character)
|
||||
} else {
|
||||
exhausted = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mutating func peek(_ ahead: Int = 0) -> Character? {
|
||||
ensure(ahead + 1)
|
||||
return ahead < buffer.count ? buffer[ahead] : nil
|
||||
}
|
||||
|
||||
var mark: Mark {
|
||||
Mark(line: line, column: column, offset: offset)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
mutating func advance() -> Character? {
|
||||
ensure(1)
|
||||
guard !buffer.isEmpty else { return nil }
|
||||
let character = buffer.removeFirst()
|
||||
offset += 1
|
||||
if character == "\n" {
|
||||
line += 1
|
||||
column = 1
|
||||
} else {
|
||||
column += 1
|
||||
}
|
||||
return character
|
||||
}
|
||||
|
||||
/// True if the upcoming characters equal `literal`, without consuming.
|
||||
mutating func matches(_ literal: String) -> Bool {
|
||||
let target = Array(literal)
|
||||
ensure(target.count)
|
||||
guard buffer.count >= target.count else { return false }
|
||||
for index in target.indices where buffer[index] != target[index] {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// If the upcoming characters equal `literal`, consume them and return true.
|
||||
@discardableResult
|
||||
mutating func consume(_ literal: String) -> Bool {
|
||||
guard matches(literal) else { return false }
|
||||
for _ in literal {
|
||||
advance()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
mutating func skipSpace() {
|
||||
while let character = peek(), character.isXMLWhitespace {
|
||||
advance()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Character {
|
||||
/// XML S production: space, tab, carriage return, line feed.
|
||||
var isXMLWhitespace: Bool {
|
||||
self == " " || self == "\t" || self == "\r" || self == "\n"
|
||||
}
|
||||
|
||||
/// A character allowed to start an XML name (a practical subset of the spec
|
||||
/// NameStartChar production: letters, underscore, and colon).
|
||||
var isXMLNameStart: Bool {
|
||||
isLetter || self == "_" || self == ":"
|
||||
}
|
||||
|
||||
/// A character allowed within an XML name after the first.
|
||||
var isXMLNameContinuation: Bool {
|
||||
isXMLNameStart || isNumber || self == "-" || self == "."
|
||||
}
|
||||
}
|
||||
@ -10,20 +10,131 @@ struct ParsingTests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tokenizing parser is not implemented yet. This test pins the current
|
||||
/// contract so the gap is explicit rather than a silent partial parse.
|
||||
@Test("Non-empty input reports the parser is not implemented yet")
|
||||
func test_nonEmptyInputNotImplemented() {
|
||||
do {
|
||||
_ = try PureXML.parse("<root/>")
|
||||
Issue.record("expected parse to throw notImplemented")
|
||||
} catch let error as PureXML.Parsing.ParseError {
|
||||
guard case .notImplemented = error else {
|
||||
Issue.record("expected notImplemented, got \(error)")
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
Issue.record("unexpected error: \(error)")
|
||||
@Test("Parses an empty element")
|
||||
func test_parsesEmptyElement() throws {
|
||||
let node = try PureXML.parse("<root/>")
|
||||
guard case let .document(children) = node else {
|
||||
Issue.record("expected a document node")
|
||||
return
|
||||
}
|
||||
#expect(children == [.element(.init("root"))])
|
||||
}
|
||||
|
||||
@Test("Parses attributes, decoding entities")
|
||||
func test_parsesAttributes() throws {
|
||||
let node = try PureXML.parse("<a href=\"x?b=1&c=2\" id='bk1'/>")
|
||||
let element = node.firstElement
|
||||
#expect(element?.attributes == [.init("href", "x?b=1&c=2"), .init("id", "bk1")])
|
||||
}
|
||||
|
||||
@Test("Parses nested elements and text with entities")
|
||||
func test_parsesNestedAndText() throws {
|
||||
let node = try PureXML.parse("<p>1 < 2 & ok<b>x</b></p>")
|
||||
let paragraph = node.firstElement
|
||||
#expect(paragraph?.name.localName == "p")
|
||||
#expect(paragraph?.children.first == .text("1 < 2 & ok"))
|
||||
#expect(paragraph?.children.last == .element(.init("b", children: [.text("x")])))
|
||||
}
|
||||
|
||||
@Test("Parses comments, CDATA, and processing instructions")
|
||||
func test_parsesMiscNodes() throws {
|
||||
let node = try PureXML.parse("<r><!--c--><![CDATA[a<b]]><?pi go?></r>")
|
||||
let root = node.firstElement
|
||||
#expect(root?.children == [
|
||||
.comment("c"),
|
||||
.cdata("a<b"),
|
||||
.processingInstruction(target: "pi", data: "go"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("Skips an XML declaration in the prolog")
|
||||
func test_skipsXMLDeclaration() throws {
|
||||
let node = try PureXML.parse("<?xml version=\"1.0\"?>\n<root>hi</root>")
|
||||
#expect(node.firstElement?.text == "hi")
|
||||
}
|
||||
|
||||
@Test("Round-trips through the serializer")
|
||||
func test_roundTripsSerializerOutput() throws {
|
||||
let original = PureXML.Model.Element(
|
||||
"catalog",
|
||||
children: [.element(.init("book", attributes: [.init("id", "bk101")], children: [.text("A & B")]))],
|
||||
)
|
||||
let xml = PureXML.serialize(.element(original), options: .compact)
|
||||
let reparsed = try PureXML.parse(xml)
|
||||
#expect(reparsed.firstElement == original)
|
||||
}
|
||||
|
||||
@Test("Mismatched end tag is an error")
|
||||
func test_mismatchedEndTagThrows() {
|
||||
#expect(throws: PureXML.Parsing.ParseError.self) {
|
||||
try PureXML.parse("<a></b>")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("DOCTYPE is rejected by default (security posture)")
|
||||
func test_doctypeRejected() {
|
||||
#expect(throws: PureXML.Parsing.ParseError.self) {
|
||||
try PureXML.parse("<!DOCTYPE a><a/>")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Unterminated tag is an error")
|
||||
func test_unterminatedTagThrows() {
|
||||
#expect(throws: PureXML.Parsing.ParseError.self) {
|
||||
try PureXML.parse("<a><b></a>")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Streams events one at a time without building a tree")
|
||||
func test_streamsEvents() throws {
|
||||
var reader = PureXML.events("<r a=\"1\">hi<b/></r>")
|
||||
var events: [PureXML.Parsing.Event] = []
|
||||
while let event = try reader.next() {
|
||||
events.append(event)
|
||||
}
|
||||
#expect(events == [
|
||||
.startElement(name: .init("r"), attributes: [.init("a", "1")]),
|
||||
.characters("hi"),
|
||||
.startElement(name: .init("b"), attributes: []),
|
||||
.endElement(name: .init("b")),
|
||||
.endElement(name: .init("r")),
|
||||
])
|
||||
}
|
||||
|
||||
/// Proves the parser does not require the whole string at once: the source is
|
||||
/// a closure pulling characters across separate chunks, never joined.
|
||||
@Test("Parses from an incremental, chunked character source")
|
||||
func test_parsesFromChunkedSource() throws {
|
||||
let chunks = ["<ro", "ot a", "=", "'1'>", "te", "xt<c/>", "</roo", "t>"]
|
||||
var chunkIterator = chunks.makeIterator()
|
||||
var charIterator = (chunkIterator.next() ?? "").makeIterator()
|
||||
let pull: () -> Character? = {
|
||||
while true {
|
||||
if let character = charIterator.next() {
|
||||
return character
|
||||
}
|
||||
guard let nextChunk = chunkIterator.next() else {
|
||||
return nil
|
||||
}
|
||||
charIterator = nextChunk.makeIterator()
|
||||
}
|
||||
}
|
||||
|
||||
let node = try PureXML.parse(pulling: pull)
|
||||
let root = node.firstElement
|
||||
#expect(root?.name.localName == "root")
|
||||
#expect(root?.attributes == [.init("a", "1")])
|
||||
#expect(root?.children.first == .text("text"))
|
||||
#expect(root?.children.last == .element(.init("c")))
|
||||
}
|
||||
}
|
||||
|
||||
private extension PureXML.Model.Node {
|
||||
var firstElement: PureXML.Model.Element? {
|
||||
guard case let .document(children) = self else { return element }
|
||||
for child in children {
|
||||
if case let .element(element) = child { return element }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user