diff --git a/CHANGELOG.md b/CHANGELOG.md index 1454135..b81f059 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/Sources/Schema/SchemaAttributeRestriction.swift b/Sources/Schema/SchemaAttributeRestriction.swift index 8e5fa58..a763be5 100644 --- a/Sources/Schema/SchemaAttributeRestriction.swift +++ b/Sources/Schema/SchemaAttributeRestriction.swift @@ -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" diff --git a/Sources/Schema/XSDAttributeParser.swift b/Sources/Schema/XSDAttributeParser.swift index 11602ec..7dbba1a 100644 --- a/Sources/Schema/XSDAttributeParser.swift +++ b/Sources/Schema/XSDAttributeParser.swift @@ -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 diff --git a/Sources/Schema/XSDComplexContent.swift b/Sources/Schema/XSDComplexContent.swift index 03e514e..c25a989 100644 --- a/Sources/Schema/XSDComplexContent.swift +++ b/Sources/Schema/XSDComplexContent.swift @@ -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 = []) -> 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. diff --git a/Tests/SchemaAttributeRestrictionTests.swift b/Tests/SchemaAttributeRestrictionTests.swift index 2a7f447..0c05818 100644 --- a/Tests/SchemaAttributeRestrictionTests.swift +++ b/Tests/SchemaAttributeRestrictionTests.swift @@ -108,4 +108,140 @@ struct SchemaAttributeRestrictionTests { let unionDef = "" #expect(compiles(unionDef + derive(base: base, restricted: ""))) } + + @Test("Attributes are inherited, overridden, or prohibited correctly in complexContent restriction during instance validation") + func test_attributeInheritanceAndProhibitionInInstanceValidation() throws { + let schemaSource = """ + + + + + + + + + + + + + + + + + + + + + + + + + + + + """ + + 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("").isEmpty) + // - Invalid instance: has prohibited c. + let invalidProhibit = try doc.validate("") + #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("").isEmpty) + // - Invalid instance: a is not an integer. + let invalidOverride = try doc.validate("") + #expect(!invalidOverride.isEmpty) + } + + @Test("Attributes in restriction with different namespaces are resolved correctly") + func test_multiNamespaceAttributeRestriction() throws { + let imported = """ + + + + """ + + let main = """ + + + + + + + + + + + + + + + + + + + + """ + + let loader: (String) -> String? = { $0 == "imported.xsd" ? imported : nil } + let doc = try PureXML.Schema.Document(main, schemaLoader: loader) + + let xml = """ + + """ + #expect(try doc.validate(xml).isEmpty) + } + + @Test("Prohibiting an attribute defined in an attributeGroup works correctly") + func test_attributeGroupProhibition() throws { + let main = """ + + + + + + + + + + + + + + + + + + + + + """ + + let doc = try PureXML.Schema.Document(main) + + let xml = """ + + """ + #expect(try doc.validate(xml).isEmpty) + + let invalidXML = """ + + """ + #expect(try !doc.validate(invalidXML).isEmpty) + } } diff --git a/Tests/XSTSSuiteTests.swift b/Tests/XSTSSuiteTests.swift index c08edce..c0633f4 100644 --- a/Tests/XSTSSuiteTests.swift +++ b/Tests/XSTSSuiteTests.swift @@ -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 { diff --git a/docs/schema-validity-burndown.md b/docs/schema-validity-burndown.md index c01da81..b43065b 100644 --- a/docs/schema-validity-burndown.md +++ b/docs/schema-validity-burndown.md @@ -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 `` 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 `` 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