fix(schema): enforce pattern and enumeration facets on union types

A union admits any value valid for one of its member types, but pattern and
enumeration (the only constraining facets XSD 1.0 Datatypes 4.1.5 allows on a
union) were ignored, so a member-valid value outside the enumeration or failing
the pattern was accepted. validateUnion now applies both on top of membership.
Enumeration compares in the value space of the admitting member, so 01 equals
an enumerated 1 for an integer member, consistent with the atomic enumeration
path, rather than a lexical compare.

XSTS #147: invalid instances accepted 555 to 355. Baseline updated; regression
tests cover enumeration (including value-space), pattern, and the no-facet case.

Refs #147, #129.
This commit is contained in:
Mihaela Mihaljevic 2026-06-13 16:37:22 +02:00
parent 1480453125
commit 8f89acc354
4 changed files with 73 additions and 5 deletions

View File

@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Pattern and enumeration facets on a union type are now enforced (#147). A union admits a value valid for any member, but `pattern` and `enumeration` (the only constraining facets XSD allows on a union) had been ignored, so a member-valid value outside the enumeration or failing the pattern was wrongly accepted. Enumeration compares in the value space of the admitting member (so `01` equals an enumerated `1` for an integer member), matching the atomic path. XSTS #147: invalid instances accepted 555 to 355.
- Length facets on the built-in list datatypes now count list items, not characters (#146). A restriction of `NMTOKENS`, `IDREFS`, or `ENTITIES` resolved its base through neither the `BuiltinType` table (which has only the singular `NMTOKEN`) nor the user-type table, so it collapsed to an atomic string and `length`/`minLength`/`maxLength` measured characters, rejecting valid instances. The restriction base now resolves through `simpleTypeReference`, preserving the list variety. Closes the XSTS NIST `list-NMTOKENS`/`IDREFS`/`ENTITIES` facet clusters: valid instances rejected 604 to 547, invalid instances accepted 582 to 555.
- Three crash and hang classes uncovered by running the full XSTS archive to completion (#129). (1) Nested occurrence explosion: the content-model NFA capped each particle's `maxOccurs` unroll at 16384 but not the total state count, so nested high-`maxOccurs` particles multiplied (a sequence of 16384 holding a choice of 16384 is 2.7e8 states) and OOM-killed the process at 8 GB on the Microsoft Particles set; the builder now also caps total states (2^20), degrading further repetition to star. The regex `{n,m}` quantifier builder had the same unbounded unroll and the same cap is applied. (2) Quadratic content-model validation: `sequenceStructureErrors` called `follow(after: prefix)` once per child and `follow` re-walked the whole prefix from the start each time, so a content model over many children spun at 100% CPU; matching is now incremental (one active state-set advanced per child), turning O(children squared) into O(children). (3) Character-class subtraction trap: the regex pattern `[abcd-[d]]` (XSD class subtraction) was parsed as a `d` to `[` range, and since `d` (100) exceeds `[` (91) the reversed `ClosedRange` trapped (SIGBUS); `-[` now always opens a subtraction, and any reversed range (such as `[z-a]`) is a clean rejection rather than a trap.

View File

@ -141,10 +141,23 @@ public extension PureXML.Schema {
}
private func validateUnion(_ lexical: String, members: [SimpleType]) -> String? {
for member in members where member.validate(lexical) == nil {
return nil
// The value must be valid against at least one member type.
guard members.contains(where: { $0.validate(lexical) == nil }) else {
return "'\(lexical)' does not match any member type of the union"
}
return "'\(lexical)' does not match any member type of the union"
// `pattern` and `enumeration` are the only constraining facets XSD
// allows on a union (Datatypes 4.1.5); both apply on top of membership.
// Pattern matches the lexical value; enumeration compares in the
// value space of whichever member admits each value, so `01` equals an
// enumerated `1` for an integer member, matching the atomic path.
if let error = patternError(lexical) { return error }
if let enumeration = facets.enumeration {
let inEnumeration = enumeration.contains { candidate in
members.contains { $0.valueMatches(lexical, literal: candidate) }
}
if !inEnumeration { return "'\(lexical)' is not in the enumeration" }
}
return nil
}
private func validateAtomic(_ lexical: String) -> String? {

View File

@ -0,0 +1,53 @@
@testable import PureXML
import Testing
/// `pattern` and `enumeration` are the only constraining facets XSD allows on a
/// union, and both must be enforced on top of member-type membership (#147).
/// They had been ignored, so any value valid for a member slipped through.
@Suite("Union restriction facets")
struct SchemaUnionFacetTests {
private func schema(_ facets: String) throws -> PureXML.Schema.Document {
try PureXML.Schema.Document("""
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="intOrName">
<xs:union memberTypes="xs:int xs:string"/>
</xs:simpleType>
<xs:element name="v">
<xs:simpleType>
<xs:restriction base="intOrName">\(facets)</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:schema>
""")
}
@Test("Enumeration on a union restricts to the listed values")
func test_enumeration() throws {
let s = try schema(#"<xs:enumeration value="5"/><xs:enumeration value="foo"/>"#)
#expect(try s.validate("<v>5</v>").isEmpty) // listed
#expect(try s.validate("<v>foo</v>").isEmpty) // listed
#expect(try !s.validate("<v>7</v>").isEmpty) // valid int, not listed
#expect(try !s.validate("<v>bar</v>").isEmpty) // valid string, not listed
}
@Test("Union enumeration compares in value space, not lexically")
func test_enumerationValueSpace() throws {
let s = try schema(#"<xs:enumeration value="5"/>"#)
// 05 is a valid xs:int equal to the enumerated 5, so it is in the set.
#expect(try s.validate("<v>05</v>").isEmpty)
}
@Test("Pattern on a union constrains the lexical value")
func test_pattern() throws {
let s = try schema(#"<xs:pattern value="[a-z]+"/>"#)
#expect(try s.validate("<v>abc</v>").isEmpty) // valid string, matches
#expect(try !s.validate("<v>5</v>").isEmpty) // valid int, fails pattern
}
@Test("A union with no facets still admits any member value")
func test_noFacets() throws {
let s = try schema("")
#expect(try s.validate("<v>42</v>").isEmpty)
#expect(try s.validate("<v>anything</v>").isEmpty)
}
}

View File

@ -22,14 +22,15 @@ struct XSTSSuiteTests {
/// 2026-06-13, over 14383 groups). These ratchet down as conformance work
/// closes deviations (#145-#148); a count rising is a regression. The
/// instance counts reflect the #146 list-facet fix (built-in list length
/// facets now count items). The suite is opt-in, so CI and plain
/// facets now count items) and the #147 union-facet fix (pattern and
/// enumeration enforced on unions). The suite is opt-in, so CI and plain
/// `swift test` are unaffected; run it with `swift test -c release --filter
/// XSTS` (debug is far slower and the corpus is large). Per-case deviations
/// are written to /tmp/xsts-failures.txt for the burn-down.
private let knownSchemaValidRejected = 75
private let knownSchemaInvalidAccepted = 2467
private let knownInstanceValidRejected = 547
private let knownInstanceInvalidAccepted = 555
private let knownInstanceInvalidAccepted = 355
@Test("Every XSTS case behaves: compile, reject, validate, invalidate")
func test_suite() throws {