fix(schema): inherit and prohibit attributes under complexContent restriction

This commit is contained in:
Mihaela Mihaljevic 2026-06-15 18:52:23 +02:00
parent 80064be6b8
commit 9004efe400
7 changed files with 220 additions and 11 deletions

View File

@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Support attribute inheritance and prohibition in complexContent restriction derivations (XSD 1.0 Structures §3.4.6 / Schema Component Constraint: Derivation Valid (Restriction, Complex)). When a complexType restricts a base type, the restricted type inherits all base attributes that are not explicitly overridden or prohibited by the restriction. A prohibited attribute is excluded from the final type's attributes, preventing its use in instance validation. Resolves referenced attributes namespace-aware using prefix bindings. XSTS: valid instances rejected 180 to 171, invalid instances accepted 158 to 155, no other bucket raised.
- A complexContent restriction must keep a base attribute's required use and its fixed value constraint (XSD 1.0 `cos-ct-derived-ok` / `derivation-ok-restriction.2` / `derivation-ok-restriction.4`). A restriction redeclaring a base `required` attribute may not make it optional or prohibited, and if a base attribute use has a `fixed` value constraint, the restriction must also make it `fixed` with the same value. The fixed values are compared in the attribute type's value space (supporting lists and unions) to avoid over-rejecting valid schemas. A prohibited attribute is removed, so the fixed clause does not apply to it. XSTS: invalid schemas accepted 390 to 387, no other bucket raised.
- Enforce top-level declaration naming, block xs:anySimpleType derivation, and restrict simpleType facets. Top-level definitions must specify a `name` attribute. Derivation by restriction or extension of `xs:anySimpleType` is disallowed. Restriction facets (`length`, `minLength`, `maxLength`, `totalDigits`, `fractionDigits`) must be tighter than or equal to the base type's facets. XSTS: invalid schemas accepted 387 to 383, no other bucket raised.
- Enforce simpleType derivation constraints on restricted complexType attributes (XSD 1.0 `cos-ct-derived-ok` / `derivation-ok-restriction.1`). The type of a restricted attribute must be validly derived by restriction from its base counterpart, checking atomic built-in derivation, list item type restriction, and union membership or member-to-member restriction recursively. XSTS: invalid schemas accepted 367 to 365, no other bucket raised.

View File

@ -129,7 +129,8 @@ extension PureXML.Schema.XSDParser {
private static func attributeName(_ node: XSDTree, _ context: PureXML.Schema.XSDContext) -> PureXML.Model.QualifiedName? {
if let ref = AttrRestrictNode.attribute(node, "ref") {
let refName = AttrRestrictNode.stripPrefix(ref)
return PureXML.Model.QualifiedName(localName: refName, namespaceURI: context.targetNamespace)
let namespace = AttrRestrictNode.referenceNamespace(ref, context.namespaceBindings)
return PureXML.Model.QualifiedName(localName: refName, namespaceURI: namespace)
}
guard let name = AttrRestrictNode.attribute(node, "name") else { return nil }
let qualified = AttrRestrictNode.attribute(node, "form") == "qualified"

View File

@ -28,7 +28,8 @@ extension PureXML.Schema.XSDParser {
let refName = PureXML.Schema.XSDNode.stripPrefix(ref)
guard let declaration = context.globalAttributes[refName],
var use = attributeUse(declaration, context) else { return nil }
use.name = PureXML.Model.QualifiedName(localName: refName, namespaceURI: context.targetNamespace)
let namespace = PureXML.Schema.XSDNode.referenceNamespace(ref, context.namespaceBindings)
use.name = PureXML.Model.QualifiedName(localName: refName, namespaceURI: namespace)
if PureXML.Schema.XSDNode.attribute(node, "use") == "required" { use.required = true }
if let constraint = valueConstraint(of: node) { use.valueConstraint = constraint }
return use

View File

@ -18,16 +18,86 @@ extension PureXML.Schema.XSDParser {
let ownAttributes = attributeUses(under: derivationNode, context)
let ownWildcard = attributeWildcard(under: derivationNode, context)
let ownParticle = modelGroup(in: derivationNode, context)
guard XSDContentNode.localName(derivationNode) == "extension", let base = resolvedBase(derivationNode, context) else {
return XSDComplexType(attributes: ownAttributes, attributeWildcard: ownWildcard, content: content(ownParticle, mixed: mixed))
let derivationType = XSDContentNode.localName(derivationNode)
if derivationType == "extension", let base = resolvedBase(derivationNode, context) {
return XSDComplexType(
attributes: base.attributes + ownAttributes,
attributeWildcard: ownWildcard ?? base.attributeWildcard,
content: extendedContent(base: base.content, own: ownParticle, mixed: mixed),
)
} else if derivationType == "restriction" {
let allowedOwnAttributes = ownAttributes.filter { !isProhibited($0.name, under: derivationNode, context) }
let finalAttributes: [PureXML.Schema.AttributeUse]
if let base = resolvedBase(derivationNode, context) {
var attributes: [PureXML.Schema.AttributeUse] = []
for baseAttr in base.attributes {
if isProhibited(baseAttr.name, under: derivationNode, context) {
continue
}
if let derived = allowedOwnAttributes.first(where: { $0.name == baseAttr.name }) {
attributes.append(derived)
} else {
attributes.append(baseAttr)
}
}
for ownAttr in allowedOwnAttributes {
guard !base.attributes.contains(where: { $0.name == ownAttr.name }) else { continue }
attributes.append(ownAttr)
}
finalAttributes = attributes
} else {
finalAttributes = allowedOwnAttributes
}
return XSDComplexType(
attributes: finalAttributes,
attributeWildcard: ownWildcard,
content: content(ownParticle, mixed: mixed),
)
}
return XSDComplexType(
attributes: base.attributes + ownAttributes,
attributeWildcard: ownWildcard ?? base.attributeWildcard,
content: extendedContent(base: base.content, own: ownParticle, mixed: mixed),
attributes: ownAttributes,
attributeWildcard: ownWildcard,
content: content(ownParticle, mixed: mixed),
)
}
private static func isProhibited(_ name: PureXML.Model.QualifiedName, under node: XSDTree, _ context: PureXML.Schema.XSDContext, visited: Set<String> = []) -> Bool {
for child in XSDContentNode.elementChildren(node) {
switch XSDContentNode.localName(child) {
case "attribute":
if let attrName = attributeName(child, context), attrName == name {
if XSDContentNode.attribute(child, "use") == "prohibited" {
return true
}
}
case "attributeGroup":
guard let ref = XSDContentNode.attribute(child, "ref") else { break }
let refName = XSDContentNode.stripPrefix(ref)
guard !visited.contains(refName), let group = context.attributeGroups[refName] else { break }
if isProhibited(name, under: group, context, visited: visited.union([refName])) {
return true
}
default:
break
}
}
return false
}
private static func attributeName(_ node: XSDTree, _ context: PureXML.Schema.XSDContext) -> PureXML.Model.QualifiedName? {
if let ref = XSDContentNode.attribute(node, "ref") {
let refName = XSDContentNode.stripPrefix(ref)
let namespace = XSDContentNode.referenceNamespace(ref, context.namespaceBindings)
return PureXML.Model.QualifiedName(localName: refName, namespaceURI: namespace)
}
guard let name = XSDContentNode.attribute(node, "name") else { return nil }
let qualified = XSDContentNode.attribute(node, "form") == "qualified"
|| (XSDContentNode.attribute(node, "form") == nil && context.attributeFormQualified)
return PureXML.Model.QualifiedName(localName: name, namespaceURI: qualified ? context.targetNamespace : nil)
}
/// The base complex type a derivation extends, parsed from its definition
/// node, or nil when the base is unknown (a built-in or undeclared type) or
/// would form a derivation cycle.

View File

@ -108,4 +108,140 @@ struct SchemaAttributeRestrictionTests {
let unionDef = "<xs:simpleType name=\"U\"><xs:union memberTypes=\"xs:integer xs:string\"/></xs:simpleType>"
#expect(compiles(unionDef + derive(base: base, restricted: "<xs:attribute name=\"a\" type=\"U\"/>")))
}
@Test("Attributes are inherited, overridden, or prohibited correctly in complexContent restriction during instance validation")
func test_attributeInheritanceAndProhibitionInInstanceValidation() throws {
let schemaSource = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:foo" xmlns="urn:foo" elementFormDefault="qualified">
<xs:complexType name="Base">
<xs:attribute name="a" type="xs:integer"/>
<xs:attribute name="b" type="xs:string"/>
<xs:attribute name="c" type="xs:string"/>
</xs:complexType>
<xs:element name="prohibit">
<xs:complexType>
<xs:complexContent>
<xs:restriction base="Base">
<xs:attribute name="c" use="prohibited"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:element>
<xs:element name="override">
<xs:complexType>
<xs:complexContent>
<xs:restriction base="Base">
<xs:attribute name="a" type="xs:int"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:element>
</xs:schema>
"""
let doc = try PureXML.Schema.Document(schemaSource)
// 1. Prohibit element: a and b are inherited, c is prohibited.
// - Valid instance: only has a and b.
#expect(try doc.validate("<prohibit xmlns=\"urn:foo\" a=\"123\" b=\"y\"/>").isEmpty)
// - Invalid instance: has prohibited c.
let invalidProhibit = try doc.validate("<prohibit xmlns=\"urn:foo\" a=\"123\" c=\"z\"/>")
#expect(!invalidProhibit.isEmpty)
// 2. Override element: a is overridden to xs:int, b and c are inherited.
// - Valid instance: a is an integer, b and c are strings.
#expect(try doc.validate("<override xmlns=\"urn:foo\" a=\"123\" b=\"y\" c=\"z\"/>").isEmpty)
// - Invalid instance: a is not an integer.
let invalidOverride = try doc.validate("<override xmlns=\"urn:foo\" a=\"abc\"/>")
#expect(!invalidOverride.isEmpty)
}
@Test("Attributes in restriction with different namespaces are resolved correctly")
func test_multiNamespaceAttributeRestriction() throws {
let imported = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:imported"
elementFormDefault="qualified">
<xs:attribute name="attr" type="xs:string"/>
</xs:schema>
"""
let main = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:main"
xmlns:imp="urn:imported"
xmlns:tns="urn:main"
elementFormDefault="qualified">
<xs:import namespace="urn:imported" schemaLocation="imported.xsd"/>
<xs:complexType name="Base">
<xs:attribute ref="imp:attr" use="required"/>
<xs:attribute name="attr" type="xs:int" use="optional"/>
</xs:complexType>
<xs:element name="doc">
<xs:complexType>
<xs:complexContent>
<xs:restriction base="tns:Base">
<xs:attribute ref="imp:attr" use="required"/>
<xs:attribute name="attr" type="xs:int" use="prohibited"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:element>
</xs:schema>
"""
let loader: (String) -> String? = { $0 == "imported.xsd" ? imported : nil }
let doc = try PureXML.Schema.Document(main, schemaLoader: loader)
let xml = """
<tns:doc xmlns:tns="urn:main" xmlns:imp="urn:imported" imp:attr="hello"/>
"""
#expect(try doc.validate(xml).isEmpty)
}
@Test("Prohibiting an attribute defined in an attributeGroup works correctly")
func test_attributeGroupProhibition() throws {
let main = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:main"
xmlns:tns="urn:main"
elementFormDefault="qualified">
<xs:attributeGroup name="Group">
<xs:attribute name="attr" type="xs:string" use="optional"/>
</xs:attributeGroup>
<xs:complexType name="Base">
<xs:attributeGroup ref="tns:Group"/>
</xs:complexType>
<xs:element name="doc">
<xs:complexType>
<xs:complexContent>
<xs:restriction base="tns:Base">
<xs:attribute name="attr" use="prohibited"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:element>
</xs:schema>
"""
let doc = try PureXML.Schema.Document(main)
let xml = """
<doc xmlns="urn:main"/>
"""
#expect(try doc.validate(xml).isEmpty)
let invalidXML = """
<doc xmlns="urn:main" attr="hello"/>
"""
#expect(try !doc.validate(invalidXML).isEmpty)
}
}

View File

@ -30,8 +30,8 @@ struct XSTSSuiteTests {
/// are written to /tmp/xsts-failures.txt for the burn-down.
private let knownSchemaValidRejected = 1
private let knownSchemaInvalidAccepted = 354
private let knownInstanceValidRejected = 180
private let knownInstanceInvalidAccepted = 158
private let knownInstanceValidRejected = 171
private let knownInstanceInvalidAccepted = 155
@Test("Every XSTS case behaves: compile, reject, validate, invalidate")
func test_suite() throws {

View File

@ -11,8 +11,8 @@ irreducible tail. Do not deviate to new features while this is open.
|---|---|---|
| valid-schemas-rejected | **72 -> 4** | production target is 0: rejecting a correct schema is the most user-hostile defect (#148). Particle-restriction over-rejection fixed: pointless `maxOccurs=0` particles removed, content-free restriction of an EMPTY base, empty-derived emptiable-base, and (#163) the pairwise check over the normalized content model with occurrence subsumption applied only to same-kind pairings (cross-kind element/group, group/element, group/wildcard match occurrence inside, by effective total range / member). #164 resolved element-ref namespaces by prefix binding (the `particlesJj/Jk/Jm/Jn/Js`, `particlesQ/R` cluster, -28). Content-free (`maxOccurs=0`) derived groups and substitution-group declaration order closed `particlesW006`/`elemZ027_a`; the W3C MapAndSum rule (Sequence:Choice, #165) closed `particlesV003`. Remaining 1 (`particlesZ001`): a documented spec ambiguity (RecurseAsIfGroup; the reference rejects it), not a defect. |
| **invalid-schemas-accepted** | **2461 -> 354** | we rarely catch a bad one (facet, default/fixed value, particle-restriction name+type, id, structural content-model, UPA determinism, content order, identity-constraint XPath-subset, wildcard-namespace, final/block, simpleType content, group/wildcard and group/element cardinality, element-ref namespace, sequence/choice MapAndSum, circular type derivation, circular group/attributeGroup/substitution references, attribute-use uniqueness and single-ID, type-excludes-inline-type, ID-typed value-constraint exclusion, all-group reference placement, substitution-member type derivation, default/fixed mutual exclusion, elementTypeRestrictionOK NameAndTypeOK union checks, prohibited attribute type-check bypass, keyref arity verification landed). |
| valid-instances-rejected | **233 -> 180** | (instance side; #164's element-ref namespace fix is shared with instance validation, -34) |
| invalid-instances-accepted | **160 -> 158** | (instance side; resolving an inline `<simpleType>` restriction base preserves list/union variety, so a `length` facet counts items and two more invalid instances are caught) |
| valid-instances-rejected | **233 -> 171** | (instance side; #164's element-ref namespace fix is shared with instance validation, complexContent restriction attributes inheritance and namespace fixes) |
| invalid-instances-accepted | **160 -> 155** | (instance side; resolving inline `<simpleType>` restriction base, complexContent restriction attributes prohibition) |
One-sentence diagnosis: *the validator runs its instance-validity rules but not
its schema-validity rules.* It compiles what it understands and ignores the