diff --git a/CHANGELOG.md b/CHANGELOG.md
index aa7d2aa..c58f542 100644
--- a/CHANGELOG.md
+++ b/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: `` is rejected (no DTD/XXE).
+- Top-level API: `PureXML.parse(_:)`, `PureXML.parse(pulling:)`, and
+ `PureXML.events(_:)` / `PureXML.events(pulling:)` for streaming.
diff --git a/README.md b/README.md
index b3ec44e..5c73ffa 100644
--- a/README.md
+++ b/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: `` 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
diff --git a/Sources/API.swift b/Sources/API.swift
index 8ce0307..8ad087b 100644
--- a/Sources/API.swift
+++ b/Sources/API.swift
@@ -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,
diff --git a/Sources/Parsing/EntityDecoder.swift b/Sources/Parsing/EntityDecoder.swift
new file mode 100644
index 0000000..948a014
--- /dev/null
+++ b/Sources/Parsing/EntityDecoder.swift
@@ -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)
+ }
+ }
+}
diff --git a/Sources/Parsing/Event.swift b/Sources/Parsing/Event.swift
new file mode 100644
index 0000000..da411c2
--- /dev/null
+++ b/Sources/Parsing/Event.swift
@@ -0,0 +1,15 @@
+public extension PureXML.Parsing {
+ /// A single XML parse event emitted by the streaming ``EventReader``.
+ ///
+ /// An empty element `
` 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)
+ }
+}
diff --git a/Sources/Parsing/EventReader.swift b/Sources/Parsing/EventReader.swift
new file mode 100644
index 0000000..21219c1
--- /dev/null
+++ b/Sources/Parsing/EventReader.swift
@@ -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 `` 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("") {
+ 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("") {
+ 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 = []
+ 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)
+ }
+ }
+}
diff --git a/Sources/Parsing/ParseError.swift b/Sources/Parsing/ParseError.swift
index 5e48a08..70944e9 100644
--- a/Sources/Parsing/ParseError.swift
+++ b/Sources/Parsing/ParseError.swift
@@ -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 `` 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)"
}
diff --git a/Sources/Parsing/Parser.swift b/Sources/Parsing/Parser.swift
index 90b62e2..055288a 100644
--- a/Sources/Parsing/Parser.swift
+++ b/Sources/Parsing/Parser.swift
@@ -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)
+ }
}
}
}
diff --git a/Sources/Parsing/Reader.swift b/Sources/Parsing/Reader.swift
new file mode 100644
index 0000000..1f5e357
--- /dev/null
+++ b/Sources/Parsing/Reader.swift
@@ -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 == "."
+ }
+}
diff --git a/Tests/ParsingTests.swift b/Tests/ParsingTests.swift
index 9783793..294a854 100644
--- a/Tests/ParsingTests.swift
+++ b/Tests/ParsingTests.swift
@@ -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("")
- 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("")
+ 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("")
+ 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("1 < 2 & okx
")
+ 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("")
+ let root = node.firstElement
+ #expect(root?.children == [
+ .comment("c"),
+ .cdata("a\nhi")
+ #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("")
}
}
+
+ @Test("DOCTYPE is rejected by default (security posture)")
+ func test_doctypeRejected() {
+ #expect(throws: PureXML.Parsing.ParseError.self) {
+ try PureXML.parse("")
+ }
+ }
+
+ @Test("Unterminated tag is an error")
+ func test_unterminatedTagThrows() {
+ #expect(throws: PureXML.Parsing.ParseError.self) {
+ try PureXML.parse("")
+ }
+ }
+
+ @Test("Streams events one at a time without building a tree")
+ func test_streamsEvents() throws {
+ var reader = PureXML.events("hi")
+ 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 = ["", "te", "xt", ""]
+ 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
+ }
}