fix(xsd): error on unknown xsi:type; cycle-detect type references

An xsi:type naming an undeclared type is now a located error in both the
tree validator (validateChild) and the streaming driver, instead of a silent
fallback to the declared type. typeReference chains resolve through one
shared resolver (resolveReference, with a visited set), replacing the inline
recursion, the 64-hop cap, and the completions guard: a circular chain now
reports 'circular type reference' instead of silently truncating, and the
streaming shallow check no longer recurses without bound on a cyclic table
(a latent crash). Tests cover unknown xsi:type (tree + streaming agree),
the circular chain (tree + shallow), the resolver's three outcomes, and a
conformance-harness case pair.

Closes #110
This commit is contained in:
Mihaela Mihaljevic 2026-06-10 03:10:00 +02:00
parent 1aea327709
commit 38b3f75243
8 changed files with 186 additions and 22 deletions

View File

@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- XSD type resolution no longer accepts invalid input silently (#110): an `xsi:type` naming an undeclared type is now a located error ("unknown xsi:type '...'") instead of a silent fallback to the declared type, in both the tree and streaming validators; and `typeReference` chains are resolved through one shared cycle-detecting resolver, so a circular chain reports "circular type reference '...'" instead of silently truncating after 64 hops (and no longer recurses without bound in the streaming shallow check, a latent crash). Completions use the same resolver, best-effort.
- The HTML fragment parser (`HTML.parse`) now reconstructs active formatting elements, matching the document parser and the HTML5 algorithm (#109, surfaced by the Tier-2 conformance corpus). When a formatting element is closed out of order it is re-opened for the following content, so `<b><i></b>X</i>` yields `<b><i></i></b><i>X</i>` (not `<b><i></i></b>X`), in both the fragment and document paths.
- XSD identity-constraint errors now locate the offending field, not just the element (#104): a single-field `key`/`keyref`/`unique` error extends the coding path with the field itself, an attribute (`... at path: list/item[2]/@id`) or a child element (`.../code`), resolved from the constraint's field XPath. keyref scope resolution is confirmed to resolve a key declared on an ancestor element (cross-scope), with a test. Full XSD qualified-node-set conformance for pathological multi-level same-name nesting remains part of the conformance-corpus work.
- XSD identity-constraint errors (`key`, `keyref`, `unique`) now carry a coding path locating the actual offending element, instead of always rendering "at root of document". The `IdentityValidator` walk threads a `[PathKey]` the same way the content-model validator does, and each error is located at the selected target node, so a duplicate-key failure reports "... at path: list/item[2]" and a dangling keyref "... at path: orders/line" rather than an empty path. This brings the identity-constraint rule into line with the validation framework's path-carrying contract, which every other rule already honored. The "no element declaration for the root" XSD error is likewise located at the root element, matching the namespace check beside it.

View File

@ -99,7 +99,7 @@ flowchart TB
PureXML is a working, dependency-free XML library today: parse, emit, validate,
query, and stream documents on macOS, Linux, Windows, and WASM. The test suite
currently runs **820 tests in 129 suites** (`swift test`).
currently runs **824 tests in 130 suites** (`swift test`).
### Shipped (libxml2-aligned surface)

View File

@ -246,10 +246,7 @@ public extension PureXML.Schema {
errors.append(missing)
return
}
var declared = declared
if let overriding = Self.xsiTypeName(child), let resolved = types[overriding] {
declared = resolved
}
guard let declared = overriddenType(declared, for: child, at: path, into: &errors) else { return }
switch declared {
case let .simple(simple):
if let nilErrors = nilErrors(child, at: path) {
@ -265,11 +262,42 @@ public extension PureXML.Schema {
errors += elementFixedErrors(child, at: path)
case let .complex(complex):
errors.append(contentsOf: validate(child, against: complex, at: path))
case let .typeReference(name):
guard let resolved = types[name] else {
errors.append(XSDFailure(reason: "unknown type '\(name)'", at: path))
return
}
case .typeReference:
validateResolvedReference(declared, child, at: path, into: &errors)
}
}
/// The declared type after an `xsi:type` override. An override naming an
/// undeclared type appends an error and returns nil, not a silent fallback
/// to the declared type.
private func overriddenType(
_ declared: ElementType,
for child: PureXML.Model.Element,
at path: XSDPath,
into errors: inout [XSDFailure],
) -> ElementType? {
guard let overriding = Self.xsiTypeName(child) else { return declared }
guard let resolved = types[overriding] else {
errors.append(XSDFailure(reason: "unknown xsi:type '\(overriding)' on '\(child.name.localName)'", at: path))
return nil
}
return resolved
}
/// Validates a child against a `typeReference` through the shared resolver,
/// reporting an unknown name or a circular chain as a located error.
private func validateResolvedReference(
_ declared: ElementType,
_ child: PureXML.Model.Element,
at path: XSDPath,
into errors: inout [XSDFailure],
) {
switch resolveReference(declared) {
case let .unknown(name):
errors.append(XSDFailure(reason: "unknown type '\(name)'", at: path))
case let .circular(name):
errors.append(XSDFailure(reason: "circular type reference '\(name)'", at: path))
case let .resolved(resolved):
validateChild(child, against: resolved, at: path, into: &errors)
}
}

View File

@ -145,3 +145,39 @@ extension PureXML.Schema.ComplexValidator {
!textContent(element).isEmpty || element.children.contains { if case .element = $0 { true } else { false } }
}
}
public extension PureXML.Schema {
/// The outcome of following a `typeReference` chain: the underlying simple or
/// complex type, or the failure to report (an unknown name, or a circular
/// chain that can never resolve).
enum TypeResolution {
case resolved(ElementType)
case unknown(String)
case circular(String)
}
}
extension PureXML.Schema.ComplexValidator {
/// Follows a `typeReference` chain through `types` with cycle detection, the
/// one shared resolver behind the tree validator, the streaming validator, and
/// completions, so unknown names and circular chains are reported identically
/// everywhere instead of being silently truncated.
static func resolveReference(
_ type: PureXML.Schema.ElementType,
in types: [String: PureXML.Schema.ElementType],
) -> PureXML.Schema.TypeResolution {
var current = type
var visited: Set<String> = []
while case let .typeReference(name) = current {
guard visited.insert(name).inserted else { return .circular(name) }
guard let next = types[name] else { return .unknown(name) }
current = next
}
return .resolved(current)
}
/// The instance resolver over this validator's type table.
func resolveReference(_ type: PureXML.Schema.ElementType) -> PureXML.Schema.TypeResolution {
Self.resolveReference(type, in: types)
}
}

View File

@ -35,10 +35,10 @@ public extension PureXML.Schema.ComplexValidator {
if let overriding = Self.xsiTypeName(element), let resolved = types[overriding] {
type = resolved
}
var followed = 0
while case let .typeReference(name) = type, let resolved = types[name], followed < 64 {
// An unknown or circular chain stays a typeReference, which
// validateShallow reports as a located error.
if case let .resolved(resolved) = resolveReference(type) {
type = resolved
followed += 1
}
return type
}
@ -74,11 +74,17 @@ public extension PureXML.Schema.ComplexValidator {
if let nilErrors = nilErrors(element, at: path) { return errors + nilErrors }
shallowContent(element, complex.content, at: path, into: &errors)
errors += elementFixedErrors(element, at: path)
case let .typeReference(name):
guard let resolved = types[name] else {
case .typeReference:
// The shared resolver also guards a circular chain, which would
// otherwise recurse here without terminating.
switch resolveReference(type) {
case let .unknown(name):
return [XSDFailure(reason: "unknown type '\(name)'", at: path)]
case let .circular(name):
return [XSDFailure(reason: "circular type reference '\(name)'", at: path)]
case let .resolved(resolved):
return validateShallow(element, as: resolved, at: path)
}
return validateShallow(element, as: resolved, at: path)
}
return errors
}

View File

@ -62,6 +62,14 @@ public extension PureXML.Validation {
stack[stack.count - 1].childElements.append(PureXML.Model.Element(name: name))
}
let probe = PureXML.Model.Element(name: name, attributes: attributes)
// An xsi:type naming an undeclared type is an error here too, so the
// streaming and tree validators report the same problem.
let overriding = PureXML.Schema.ComplexValidator.xsiTypeName(probe)
if declared != nil, let overriding, validator.types[overriding] == nil {
collected.append(ValidationError(reason: "unknown xsi:type '\(overriding)' on '\(name.localName)'", at: path))
stack.append(XSDStreamFrame(name: name, attributes: attributes, effective: nil, path: path))
return
}
let effective = declared.map { validator.effectiveType($0, of: probe) }
stack.append(XSDStreamFrame(name: name, attributes: attributes, effective: effective, path: path))
}

View File

@ -88,13 +88,12 @@ public extension PureXML.Schema {
/// Resolves an `ElementType` to its underlying simple or complex type,
/// following named references.
static func resolve(_ type: ElementType, types: [String: ElementType]) -> ElementType {
var current = type
var guardCount = 0
while case let .typeReference(name) = current, let next = types[name], guardCount < types.count + 1 {
current = next
guardCount += 1
// Completions are best-effort: an unknown or circular chain keeps the
// unresolved reference, which simply offers no completions.
if case let .resolved(resolved) = PureXML.Schema.ComplexValidator.resolveReference(type, in: types) {
return resolved
}
return current
return type
}
/// The child element declarations of a complex type's content model, keyed

View File

@ -0,0 +1,86 @@
@testable import PureXML
import Testing
@Suite("XSD type resolution: unknown xsi:type and circular references")
struct XSDTypeResolutionTests {
private let schema = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="r">
<xs:complexType>
<xs:sequence><xs:element name="v" type="xs:string"/></xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
"""
@Test("An xsi:type naming an undeclared type is a located error, not a silent fallback")
func test_unknownXsiType() throws {
let xml = "<r xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><v xsi:type=\"Nope\">x</v></r>"
let document = try PureXML.Schema.Document(schema)
let tree = try document.validate(xml)
#expect(tree.contains { $0.reason.contains("unknown xsi:type 'Nope'") }, "\(tree.map(\.reason))")
// Streaming reports the same problem.
let streamed = try document.validate(streaming: xml)
#expect(streamed.contains { $0.reason.contains("unknown xsi:type 'Nope'") }, "\(streamed.map(\.reason))")
// A known xsi:type still validates cleanly.
let known = "<r xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><v>x</v></r>"
try #expect(document.validate(known).isEmpty)
}
@Test("A circular typeReference chain is a located error, not silent truncation")
func test_circularReference() {
let validator = PureXML.Schema.ComplexValidator(
types: ["A": .typeReference("B"), "B": .typeReference("A")],
)
let element = PureXML.Model.Element("e")
let errors = validator.validate(element, as: .typeReference("A"), at: [.element("e")])
#expect(errors.contains { $0.reason.contains("circular type reference") }, "\(errors.map(\.reason))")
// The shallow (streaming) check reports it too, and terminates (this
// previously recursed without bound on a cyclic table).
let shallow = validator.validateShallow(element, as: .typeReference("A"), at: [.element("e")])
#expect(shallow.contains { $0.reason.contains("circular type reference") }, "\(shallow.map(\.reason))")
}
@Test("The shared resolver distinguishes resolved, unknown, and circular")
func test_resolver() {
let types: [String: PureXML.Schema.ElementType] = [
"Alias": .typeReference("Real"),
"Real": .complex(PureXML.Schema.ComplexType(content: .empty)),
"Loop": .typeReference("Loop"),
]
if case .resolved = PureXML.Schema.ComplexValidator.resolveReference(.typeReference("Alias"), in: types) {} else {
Issue.record("alias chain should resolve")
}
if case let .unknown(name) = PureXML.Schema.ComplexValidator.resolveReference(.typeReference("Missing"), in: types) {
#expect(name == "Missing")
} else {
Issue.record("missing name should be unknown")
}
if case let .circular(name) = PureXML.Schema.ComplexValidator.resolveReference(.typeReference("Loop"), in: types) {
#expect(name == "Loop")
} else {
Issue.record("self-reference should be circular")
}
}
@Test("Conformance: the instance-override corpus passes through the harness")
func test_conformanceCases() throws {
let document = try PureXML.Schema.Document(schema)
let bad = "<r xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><v xsi:type=\"Nope\">x</v></r>"
let good = "<r><v>x</v></r>"
let cases = try [
PureXML.Validation.ConformanceCase(
name: "unknown-xsi-type-rejected",
actual: document.validate(bad).isEmpty ? "valid" : "invalid",
expected: "invalid",
),
PureXML.Validation.ConformanceCase(
name: "plain-instance-accepted",
actual: document.validate(good).isEmpty ? "valid" : "invalid",
expected: "valid",
),
]
let failures = PureXML.Validation.Conformance.failures(in: cases)
#expect(failures.isEmpty, "\(failures.map(\.reason))")
}
}