feat(xsd): Particle Valid (Restriction)

A complex type derived by restriction is checked at schema compile to accept
a structural subset of its base, closing the declared XSD 1.0 spec gap.
ParticleRestriction covers element name matching, element-vs-wildcard
admission, wildcard narrowing, occurrence-range subsumption, and the group
recursions: sequence/all order-preserving with emptiable skips (Recurse),
choice mapping (RecurseLax), sequence-into-choice (MapAndSum, approximated by
per-particle checks, a documented simplification), sequence-into-all
(RecurseUnordered), and RecurseAsIfGroup for a lone element against a group.
An unfaithful restriction throws SchemaError.invalidRestriction(type:base:
reason:). All 834 pre-existing tests pass unchanged (no false positives on
the existing restriction-using schemas); 7 new tests cover the accept and
reject paths plus a conformance-harness pair.

Closes #117
This commit is contained in:
Mihaela Mihaljevic 2026-06-10 04:13:54 +02:00
parent 125274786e
commit f792fd6e8b
6 changed files with 329 additions and 5 deletions

View File

@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- XSD Particle Valid (Restriction) (#117): a complex type derived by restriction is now checked at schema compile to accept a structural subset of its base, covering element name matching, element-vs-wildcard admission, wildcard narrowing, occurrence-range subsumption, and the group recursions (sequence/all order-preserving with emptiable skips, choice mapping, sequence-into-choice, sequence-into-all, RecurseAsIfGroup). A structurally unfaithful restriction (widened occurrence, new element name, reordered sequence, content added to an EMPTY or required-into-empty base, an element outside a base wildcard's namespace) throws `SchemaError.invalidRestriction` with the type, base, and reason. The spec's effective-total-range arithmetic for MapAndSum is approximated by per-particle checks, a documented simplification.
- Conformance corpus harness (#105, Tier 2): the start of conformance-suite checking, expressed through the validation framework (the OpenAPIKit idiom). A `PureXML.Validation.ConformanceCase` is a `Validatable` named expectation (actual vs spec-authoritative expected output), and `Conformance.matchesExpected` is a `Validation<ConformanceCase, Void>` rule that emits one located `ValidationError` per diverging case, so a whole suite reports every failure at once with the case name as its coding path. Seeded with a Canonical XML 1.0 corpus (attribute ordering, empty-element expansion, comment removal, CDATA-to-escaped-text, processing instructions, namespace rendering) an XPath 1.0 core-function corpus, and an XSD datatype/facet corpus (length, range, pattern, enumeration, lexical space), a RELAX NG pattern corpus (text, optional, repetition, choice, ordered group, attribute, interleave, empty), an XSLT 1.0 transformation corpus (value-of, for-each, if, choose, sort, variable, format-number, apply-templates, call-template), an HTML5 tree-construction corpus (void elements, implied tag closing, case normalization, the adoption agency, entities), a Schematron corpus (assert, report, rule context), a C14N exclusive/2.0 corpus (unused-namespace dropping, render-at-use, whitespace trimming), an XPath axes/predicates corpus (descendant, ancestor, sibling axes, positional and attribute predicates, union), and a DTD content-model corpus (sequence, choice, occurrence indicators, mixed, EMPTY, ANY). The HTML corpus surfaced its first divergence (the fragment parser does not reconstruct active formatting elements like the document parser, tracked as #109). Growing the corpora against the official W3C/OASIS suites is the ongoing Tier-2 work.
- EXSLT extension functions (#105, Tier 3): the `common`, `math`, and `sets` EXSLT modules, dispatched by resolving a function's prefix to its namespace (so any prefix bound to an EXSLT namespace works). `math:min`, `math:max`, `math:highest`, `math:lowest`, `math:abs`, `math:sqrt` (with the EXSLT NaN rule for non-numeric nodes); `set:distinct`, `set:difference`, `set:intersection`, `set:has-same-node`, `set:leading`, `set:trailing` (by node identity and document order); `exsl:object-type`. `math:power` and the other transcendentals are omitted because they need a C math library, which the pure-Swift, Foundation-free target excludes; `exsl:node-set` awaits result-tree-fragment support.
- Canonical XML 1.1 (#105, Tier 3): a `Canonical.Options.canonical11` preset and a `mergeInheritedBase` option. When canonicalizing a document subset, the `xml:base` values of the apex's omitted ancestors are merged into the apex by RFC 3986 reference resolution (vs. 1.0's nearest-ancestor rule), the apex's own relative `xml:base` is resolved against that chain, and `xml:id` is no longer inherited; `xml:lang` and `xml:space` still inherit the nearest. A self-contained RFC 3986 resolver (scheme/authority/path parsing, path merging, dot-segment removal) backs the merge.

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 **834 tests in 136 suites** (`swift test`).
currently runs **841 tests in 137 suites** (`swift test`).
### Shipped (libxml2-aligned surface)

View File

@ -0,0 +1,179 @@
extension PureXML.Schema {
/// XSD 1.0 "Particle Valid (Restriction)" for the common cases: a complex
/// type derived by restriction must have a content model that accepts a
/// subset of its base's. Covers element-vs-element name matching,
/// element-vs-wildcard admission, wildcard narrowing, occurrence-range
/// subsumption, and the group recursions (sequence/all order-preserving with
/// emptiable skips, choice mapping, sequence-into-choice, sequence-into-all).
/// The spec's effective-total-range arithmetic for MapAndSum is approximated
/// by per-particle checks, a documented simplification.
enum ParticleRestriction {
/// The reason a restriction's content is not a valid subset of its
/// base's, or nil when it is.
static func violation(restricted: ContentType, base: ContentType) -> String? {
switch (restricted, base) {
case (.empty, .empty), (.simpleContent, _), (_, .simpleContent):
nil
case let (.empty, .elementOnly(baseParticle)), let (.empty, .mixed(baseParticle)):
emptiable(baseParticle) ? nil : "the base content is required, so the restriction cannot be EMPTY"
case (.mixed, .elementOnly):
"a restriction cannot add mixed content to an element-only base"
case (.elementOnly, .empty), (.mixed, .empty):
"the base content is EMPTY, so the restriction cannot add content"
case let (.elementOnly(restrictedParticle), .elementOnly(baseParticle)),
let (.elementOnly(restrictedParticle), .mixed(baseParticle)),
let (.mixed(restrictedParticle), .mixed(baseParticle)):
valid(restrictedParticle, baseParticle)
? nil
: "the restricted content model is not a subset of the base's"
}
}
/// Whether `restricted` accepts a subset of `base` (the pairwise check).
static func valid(_ restricted: Particle, _ base: Particle) -> Bool {
guard rangeSubsumed(restricted, base) else { return false }
switch (restricted.term, base.term) {
case let (.element(restrictedName, _), .element(baseName, _)):
return sameName(restrictedName, baseName)
case let (.element(name, _), .wildcard(wildcard)):
return wildcard.admits(name)
case let (.wildcard(restrictedWildcard), .wildcard(baseWildcard)):
return narrows(restrictedWildcard, baseWildcard)
case let (.element, .group(baseGroup)):
// RecurseAsIfGroup: the lone element, as a one-particle sequence,
// against the base group.
return groupValid(Group(compositor: .sequence, particles: [restricted.withUnitRange()]), baseGroup)
case let (.group(restrictedGroup), .group(baseGroup)):
return groupValid(restrictedGroup, baseGroup)
case let (.group(restrictedGroup), .wildcard(wildcard)):
// NSRecurseCheckCardinality, namespace part: every leaf element
// the group can contain must be admitted by the wildcard.
return leafNames(of: restrictedGroup).allSatisfy { wildcard.admits($0) }
default:
return false
}
}
private static func groupValid(_ restricted: Group, _ base: Group) -> Bool {
switch (restricted.compositor, base.compositor) {
case (.sequence, .sequence), (.all, .all):
recurse(restricted.particles, base.particles, skippedMustBeEmptiable: true)
case (.choice, .choice):
recurse(restricted.particles, base.particles, skippedMustBeEmptiable: false)
case (.sequence, .choice):
// MapAndSum (simplified): each restricted particle fits some branch.
restricted.particles.allSatisfy { particle in
base.particles.contains { valid(particle, $0) }
}
case (.sequence, .all):
// RecurseUnordered: map onto distinct base particles in any order.
recurseUnordered(restricted.particles, base.particles)
default:
false
}
}
/// Order-preserving mapping of the restricted particles onto the base's.
/// A skipped base particle must be emptiable for sequence/all (Recurse);
/// for choice (RecurseLax) skipping is free.
private static func recurse(_ restricted: [Particle], _ base: [Particle], skippedMustBeEmptiable: Bool) -> Bool {
var baseIndex = 0
for particle in restricted {
var matched = false
while baseIndex < base.count {
let candidate = base[baseIndex]
baseIndex += 1
if valid(particle, candidate) {
matched = true
break
}
if skippedMustBeEmptiable, !emptiable(candidate) { return false }
}
if !matched { return false }
}
if skippedMustBeEmptiable {
while baseIndex < base.count {
if !emptiable(base[baseIndex]) { return false }
baseIndex += 1
}
}
return true
}
/// Any-order mapping onto distinct base particles; unmapped base
/// particles must be emptiable.
private static func recurseUnordered(_ restricted: [Particle], _ base: [Particle]) -> Bool {
var used = [Bool](repeating: false, count: base.count)
for particle in restricted {
guard let index = base.indices.first(where: { !used[$0] && valid(particle, base[$0]) }) else {
return false
}
used[index] = true
}
return base.indices.allSatisfy { used[$0] || emptiable(base[$0]) }
}
/// Occurrence-range subsumption: the restriction may not occur less often
/// than the base requires, nor more often than the base allows.
private static func rangeSubsumed(_ restricted: Particle, _ base: Particle) -> Bool {
guard restricted.minOccurs >= base.minOccurs else { return false }
guard let baseMax = base.maxOccurs else { return true }
guard let restrictedMax = restricted.maxOccurs else { return false }
return restrictedMax <= baseMax
}
/// Whether a particle can match no children at all.
static func emptiable(_ particle: Particle) -> Bool {
if particle.minOccurs == 0 { return true }
switch particle.term {
case .element, .wildcard:
return false
case let .group(group):
switch group.compositor {
case .sequence, .all:
return group.particles.allSatisfy(emptiable)
case .choice:
return group.particles.contains(where: emptiable)
}
}
}
/// Whether the restricted wildcard admits no namespace the base refuses.
private static func narrows(_ restricted: Wildcard, _ base: Wildcard) -> Bool {
switch (restricted.namespace, base.namespace) {
case (_, .any):
true
case (.other, .other):
restricted.targetNamespace == base.targetNamespace
case let (.enumerated(narrow), .enumerated(wide)):
narrow.isSubset(of: wide)
case let (.enumerated(narrow), .other):
!narrow.contains("") && !narrow.contains(base.targetNamespace ?? "")
default:
false
}
}
private static func sameName(_ lhs: PureXML.Model.QualifiedName, _ rhs: PureXML.Model.QualifiedName) -> Bool {
lhs.localName == rhs.localName && (lhs.namespaceURI ?? "") == (rhs.namespaceURI ?? "")
}
/// Every element name a group can contain (its alphabet).
private static func leafNames(of group: Group) -> [PureXML.Model.QualifiedName] {
group.particles.flatMap { particle -> [PureXML.Model.QualifiedName] in
switch particle.term {
case let .element(name, _): [name]
case let .group(inner): leafNames(of: inner)
case .wildcard: []
}
}
}
}
}
private extension PureXML.Schema.Particle {
/// A copy occurring exactly once, for RecurseAsIfGroup's wrapping.
func withUnitRange() -> PureXML.Schema.Particle {
.init(minOccurs: minOccurs, maxOccurs: maxOccurs, term: term)
}
}

View File

@ -11,6 +11,9 @@ public extension PureXML.Schema {
/// an element with `maxOccurs` at most 1, and the group itself may occur at
/// most once.
case invalidAllGroup(reason: String)
/// A complex-type restriction's content model is not a structurally valid
/// subset of its base's ("Particle Valid (Restriction)" in XSD 1.0).
case invalidRestriction(type: String, base: String, reason: String)
public var description: String {
switch self {
@ -22,6 +25,8 @@ public extension PureXML.Schema {
"redefined type '\(type)' must derive from itself"
case let .invalidAllGroup(reason):
"invalid xs:all group: \(reason)"
case let .invalidRestriction(type, base, reason):
"type '\(type)' is not a valid restriction of '\(base)': \(reason)"
}
}
}
@ -57,6 +62,18 @@ public extension PureXML.Schema {
typeBlock = compiled.typeBlock
typeDerivation = compiled.typeDerivation
targetNamespace = compiled.targetNamespace
// Particle Valid (Restriction): a complex type derived by restriction
// must accept a subset of its base (deterministic order for stable
// error reporting).
for name in typeDerivation.keys.sorted() {
guard let derivation = typeDerivation[name], derivation.method == .restriction,
case let .complex(restrictedType)? = types[name],
case let .complex(baseType)? = types[derivation.base]
else { continue }
if let reason = ParticleRestriction.violation(restricted: restrictedType.content, base: baseType.content) {
throw SchemaError.invalidRestriction(type: name, base: derivation.base, reason: reason)
}
}
}
/// Validates an instance document against the schema, returning one located

View File

@ -9,10 +9,9 @@ extension PureXML.Schema.XSDParser {
/// substitution member's derivation against its head's `block`).
///
/// Note: this records the derivation *backbone* (base + method) and enforces
/// `block`, `final`, and abstract usage. It does NOT verify that a complex-type
/// restriction is a structurally valid subset of its base ("Particle Valid
/// (Restriction)" in XSD 1.0), which is a much larger algorithm; a structurally
/// unfaithful restriction is accepted here.
/// `block`, `final`, and abstract usage. The structural subset check for a
/// complex-type restriction ("Particle Valid (Restriction)" in XSD 1.0) runs
/// separately at schema compile, see ``ParticleRestriction``.
struct DerivationTables {
var typeDerivation: [String: PureXML.Schema.TypeDerivation] = [:]
var abstractTypes: Set<String> = []

View File

@ -0,0 +1,128 @@
@testable import PureXML
import Testing
@Suite("XSD Particle Valid (Restriction)")
struct XSDParticleRestrictionTests {
private let xsNamespace = "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\""
private func schema(base: String, restriction: String) -> String {
"""
<xs:schema \(xsNamespace)>
<xs:complexType name="B">\(base)</xs:complexType>
<xs:complexType name="R">
<xs:complexContent><xs:restriction base="B">\(restriction)</xs:restriction></xs:complexContent>
</xs:complexType>
<xs:element name="r" type="R"/>
</xs:schema>
"""
}
private func compiles(base: String, restriction: String) -> Bool {
(try? PureXML.Schema.Document(schema(base: base, restriction: restriction))) != nil
}
private func restrictionError(base: String, restriction: String) -> String? {
do {
_ = try PureXML.Schema.Document(schema(base: base, restriction: restriction))
return nil
} catch let error as PureXML.Schema.SchemaError {
return String(describing: error)
} catch {
return String(describing: error)
}
}
@Test("Valid restrictions compile: drop an optional, narrow a choice, keep order")
func test_validRestrictions() {
// Dropping an optional element.
#expect(compiles(
base: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\"/><xs:element name=\"b\" type=\"xs:string\" minOccurs=\"0\"/></xs:sequence>",
restriction: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\"/></xs:sequence>",
))
// Narrowing a choice to one branch.
#expect(compiles(
base: "<xs:choice><xs:element name=\"a\" type=\"xs:string\"/><xs:element name=\"b\" type=\"xs:string\"/></xs:choice>",
restriction: "<xs:choice><xs:element name=\"a\" type=\"xs:string\"/></xs:choice>",
))
// Narrowing an occurrence range.
#expect(compiles(
base: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\" minOccurs=\"0\" maxOccurs=\"unbounded\"/></xs:sequence>",
restriction: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\" maxOccurs=\"2\"/></xs:sequence>",
))
}
@Test("A restriction widening the occurrence range is rejected")
func test_wideningOccurrenceRejected() {
let error = restrictionError(
base: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\" maxOccurs=\"2\"/></xs:sequence>",
restriction: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\" maxOccurs=\"unbounded\"/></xs:sequence>",
)
#expect(error?.contains("not a valid restriction") == true, "\(String(describing: error))")
}
@Test("A restriction introducing a new element name is rejected")
func test_newNameRejected() {
let error = restrictionError(
base: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\"/></xs:sequence>",
restriction: "<xs:sequence><xs:element name=\"z\" type=\"xs:string\"/></xs:sequence>",
)
#expect(error?.contains("not a valid restriction") == true)
}
@Test("A restriction reordering a sequence is rejected")
func test_reorderRejected() {
let error = restrictionError(
base: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\"/><xs:element name=\"b\" type=\"xs:string\"/></xs:sequence>",
restriction: "<xs:sequence><xs:element name=\"b\" type=\"xs:string\"/><xs:element name=\"a\" type=\"xs:string\"/></xs:sequence>",
)
#expect(error?.contains("not a valid restriction") == true)
}
@Test("Restricting to empty requires an emptiable base")
func test_emptyRestriction() {
// Emptiable base: fine.
#expect(compiles(
base: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\" minOccurs=\"0\"/></xs:sequence>",
restriction: "",
))
// Required base content: rejected.
let error = restrictionError(
base: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\"/></xs:sequence>",
restriction: "",
)
#expect(error?.contains("cannot be EMPTY") == true, "\(String(describing: error))")
}
@Test("An element restricts a wildcard only when its namespace is admitted")
func test_wildcardRestriction() {
// ##any admits the unqualified element.
#expect(compiles(
base: "<xs:sequence><xs:any processContents=\"lax\"/></xs:sequence>",
restriction: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\"/></xs:sequence>",
))
// ##other refuses an unqualified element.
let error = restrictionError(
base: "<xs:sequence><xs:any namespace=\"##other\" processContents=\"lax\"/></xs:sequence>",
restriction: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\"/></xs:sequence>",
)
#expect(error?.contains("not a valid restriction") == true)
}
@Test("Conformance: the restriction corpus passes through the harness")
func test_conformanceCases() {
let valid = compiles(
base: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\" minOccurs=\"0\"/></xs:sequence>",
restriction: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\"/></xs:sequence>",
)
let invalid = compiles(
base: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\"/></xs:sequence>",
restriction: "<xs:sequence><xs:element name=\"a\" type=\"xs:string\"/><xs:element name=\"b\" type=\"xs:string\"/></xs:sequence>",
)
let cases = [
PureXML.Validation.ConformanceCase(name: "faithful-restriction-accepted", actual: valid ? "valid" : "invalid", expected: "valid"),
PureXML.Validation.ConformanceCase(name: "additive-restriction-rejected", actual: invalid ? "valid" : "invalid", expected: "invalid"),
]
let failures = PureXML.Validation.Conformance.failures(in: cases)
#expect(failures.isEmpty, "\(failures.map(\.reason))")
}
}