From 092e9a488d4528297b578e4183850134ae637d18 Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Sat, 13 Jun 2026 19:53:27 +0200 Subject: [PATCH] feat(schema): honor instance xsi:schemaLocation for multi-document validation A strict or lax wildcard must resolve elements declared in schema documents an instance points at through xsi:schemaLocation, which the main schema need not import. validate(_:schemaLoader:) now reads the instance's xsi:schemaLocation and xsi:noNamespaceSchemaLocation hints, loads and compiles each referenced document through the loader, and merges its global declarations in (the primary schema wins on conflict). The plain validate(_:) is unchanged; the XSTS runner resolves hints relative to the instance file. XSTS: valid instances rejected 308 to 288 (the particle clusters whose wildcard-matched elements live in a separate, instance-referenced schema). Baseline updated; regression tests cover cross-document resolution, the loaded type being enforced, and strict failure without the loader. Refs #147, #129. --- CHANGELOG.md | 4 ++ Sources/Schema/SchemaDocument.swift | 99 ++++++++++++++++++++++++++++ Tests/SchemaMultiDocumentTests.swift | 54 +++++++++++++++ Tests/XSTSSuiteTests.swift | 15 +++-- 4 files changed, 168 insertions(+), 4 deletions(-) create mode 100644 Tests/SchemaMultiDocumentTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index fe41ece..e82692d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `Schema.Document.validate(_:schemaLoader:)` honors an instance's `xsi:schemaLocation` and `xsi:noNamespaceSchemaLocation` (#147). Each referenced schema document is loaded through the supplied loader, compiled, and its global declarations merged in (the primary schema's own declarations win on conflict), so a strict or lax wildcard can resolve an element declared in another document. The plain `validate(_:)` is unchanged. XSTS: valid instances rejected 308 to 288 (the particle clusters whose wildcard-matched elements live in a separate, instance-referenced schema). + ### Fixed - A `mixed="true"` complex type with no content model now permits character data (#147). Such a type (only attributes, no `sequence`/`choice`/`all`) was compiled to the empty content type, which forbids text, so a mixed element carrying only text was rejected. It is now mixed content over an empty particle: text is allowed, child elements are still not. XSTS: valid instances rejected 311 to 308. diff --git a/Sources/Schema/SchemaDocument.swift b/Sources/Schema/SchemaDocument.swift index 8e6310e..a193bb3 100644 --- a/Sources/Schema/SchemaDocument.swift +++ b/Sources/Schema/SchemaDocument.swift @@ -48,6 +48,58 @@ public extension PureXML.Schema { private let typeDerivation: [String: TypeDerivation] private let targetNamespace: String? + /// Combines already-compiled declaration tables, for merging the schemas + /// an instance references through `xsi:schemaLocation`. No consistency + /// check runs: each component schema was validated when first compiled. + private init( + elements: [String: ElementType], + types: [String: ElementType], + constraints: [String: [IdentityConstraint]], + nillableElements: Set, + elementConstraints: [String: ValueConstraint], + abstractTypes: Set, + abstractElements: Set, + typeBlock: [String: Set], + elementBlock: [String: Set], + typeDerivation: [String: TypeDerivation], + targetNamespace: String?, + ) { + self.elements = elements + self.types = types + self.constraints = constraints + self.nillableElements = nillableElements + self.elementConstraints = elementConstraints + self.abstractTypes = abstractTypes + self.abstractElements = abstractElements + self.typeBlock = typeBlock + self.elementBlock = elementBlock + self.typeDerivation = typeDerivation + self.targetNamespace = targetNamespace + } + + /// This schema with `other`'s global declarations merged in; this schema's + /// own declarations win on any key conflict. Used to fold in the schemas an + /// instance points at, so a strict/lax wildcard can resolve elements + /// declared in another document. + private func merging(_ other: Document) -> Document { + func mineFirst(_ mine: [String: V], _ theirs: [String: V]) -> [String: V] { + mine.merging(theirs) { current, _ in current } + } + return Document( + elements: mineFirst(elements, other.elements), + types: mineFirst(types, other.types), + constraints: mineFirst(constraints, other.constraints), + nillableElements: nillableElements.union(other.nillableElements), + elementConstraints: mineFirst(elementConstraints, other.elementConstraints), + abstractTypes: abstractTypes.union(other.abstractTypes), + abstractElements: abstractElements.union(other.abstractElements), + typeBlock: mineFirst(typeBlock, other.typeBlock), + elementBlock: mineFirst(elementBlock, other.elementBlock), + typeDerivation: mineFirst(typeDerivation, other.typeDerivation), + targetNamespace: targetNamespace, + ) + } + /// Compiles a schema document. `schemaLoader` resolves the /// `schemaLocation` of `xs:include`, `xs:import`, and `xs:redefine` to /// schema source; it returns nil (the default) when external schemas are @@ -86,6 +138,53 @@ public extension PureXML.Schema { try validate(PureXML.parse(xml)) } + /// Validates `xml`, additionally honoring the instance's + /// `xsi:schemaLocation` and `xsi:noNamespaceSchemaLocation` hints: each + /// referenced schema document is loaded through `schemaLoader`, compiled, + /// and its global declarations merged in (this schema's own declarations + /// win), so a strict or lax wildcard can resolve elements declared in + /// another document. With no hints this is `validate(_:)`. + public func validate(_ xml: String, schemaLoader: @escaping (String) -> String?) throws -> [PureXML.Validation.ValidationError] { + let node = try PureXML.parse(xml) + var combined = self + for location in Self.hintedSchemaLocations(in: node) { + guard let source = schemaLoader(location), + let other = try? Document(source, schemaLoader: schemaLoader) + else { continue } + combined = combined.merging(other) + } + return combined.validate(node) + } + + /// The schema-document locations an instance points at through + /// `xsi:schemaLocation` (the second token of each namespace/location pair) + /// and `xsi:noNamespaceSchemaLocation` (a single location). + private static func hintedSchemaLocations(in node: PureXML.Model.Node) -> [String] { + guard case let .document(children) = node, let root = children.compactMap(\.element).first else { + return [] + } + var locations: [String] = [] + for attribute in root.attributes { + let isInstance = attribute.name.namespaceURI == "http://www.w3.org/2001/XMLSchema-instance" + || attribute.name.prefix == "xsi" + guard isInstance else { continue } + switch attribute.name.localName { + case "schemaLocation": + let tokens = attribute.value.split(whereSeparator: \.isWhitespace).map(String.init) + var index = 1 + while index < tokens.count { + locations.append(tokens[index]) + index += 2 + } + case "noNamespaceSchemaLocation": + locations.append(attribute.value) + default: + break + } + } + return locations + } + /// Validates `xml` against the schema while it is pulled event by event (the /// libxml2 `xmlTextReader` model) rather than over a built tree. Memory is /// bounded to the open-element stack. Content models, attributes, and simple diff --git a/Tests/SchemaMultiDocumentTests.swift b/Tests/SchemaMultiDocumentTests.swift new file mode 100644 index 0000000..4392c5d --- /dev/null +++ b/Tests/SchemaMultiDocumentTests.swift @@ -0,0 +1,54 @@ +@testable import PureXML +import Testing + +/// `validate(_:schemaLoader:)` honors an instance's `xsi:schemaLocation`, +/// loading the referenced schema documents so a strict (or lax) wildcard can +/// resolve elements declared in another document (#147, XSTS particles set). +@Suite("Multi-document validation via xsi:schemaLocation") +struct SchemaMultiDocumentTests { + private let mainXSD = """ + + + + + + + + + + """ + + private let otherXSD = """ + + + + """ + + private let instance = """ + 5 + """ + + @Test("A strict wildcard resolves an element from the xsi:schemaLocation schema") + func test_resolvesAcrossDocuments() throws { + let doc = try PureXML.Schema.Document(mainXSD) + let loader: (String) -> String? = { [otherXSD] in $0 == "other.xsd" ? otherXSD : nil } + #expect(try doc.validate(instance, schemaLoader: loader).isEmpty) + } + + @Test("The loaded declaration's type is still enforced") + func test_loadedTypeEnforced() throws { + let doc = try PureXML.Schema.Document(mainXSD) + let loader: (String) -> String? = { [otherXSD] in $0 == "other.xsd" ? otherXSD : nil } + let bad = instance.replacingOccurrences(of: "5", with: "notint") + #expect(try !doc.validate(bad, schemaLoader: loader).isEmpty) + } + + @Test("Without the loader a strict wildcard cannot resolve the element") + func test_strictUnresolvedWithoutLoader() throws { + let doc = try PureXML.Schema.Document(mainXSD) + #expect(try !doc.validate(instance).isEmpty) + } +} diff --git a/Tests/XSTSSuiteTests.swift b/Tests/XSTSSuiteTests.swift index 9715550..457addc 100644 --- a/Tests/XSTSSuiteTests.swift +++ b/Tests/XSTSSuiteTests.swift @@ -30,7 +30,7 @@ struct XSTSSuiteTests { /// are written to /tmp/xsts-failures.txt for the burn-down. private let knownSchemaValidRejected = 72 private let knownSchemaInvalidAccepted = 2461 - private let knownInstanceValidRejected = 308 + private let knownInstanceValidRejected = 288 private let knownInstanceInvalidAccepted = 165 @Test("Every XSTS case behaves: compile, reject, validate, invalidate") @@ -137,10 +137,17 @@ struct XSTSSuiteTests { guard isAccepted(instanceTest) else { continue } let expected = expectedValidity(instanceTest) guard expected == "valid" || expected == "invalid", - let href = references(in: .element(instanceTest), named: "instanceDocument").first, - let xml = try? String(contentsOfFile: resolve(href, against: directory), encoding: .utf8) + let href = references(in: .element(instanceTest), named: "instanceDocument").first else { continue } - let isValid = ((try? schema.validate(xml))?.isEmpty) ?? false + let instancePath = resolve(href, against: directory) + guard let xml = try? String(contentsOfFile: instancePath, encoding: .utf8) else { continue } + // Resolve the instance's xsi:schemaLocation hints relative to the + // instance file, so a strict wildcard can find declarations in them. + let instanceDirectory = self.directory(of: instancePath) + let loader: (String) -> String? = { location in + (try? String(contentsOfFile: resolve(location, against: instanceDirectory), encoding: .utf8)) + } + let isValid = ((try? schema.validate(xml, schemaLoader: loader))?.isEmpty) ?? false if expected == "valid", !isValid { counters.instanceValidRejected += 1 counters.note("\(name)/\(attribute("name", of: instanceTest) ?? "?"): valid instance rejected")