feat(schema): top-level attribute may not have use/form/ref (topLevelAttribute)

A top-level xs:attribute declaration (a direct child of schema, or of redefine)
was accepted with use, form, or ref. Those belong to a local attribute use, not
a global declaration: the schema-for-schemas topLevelAttribute marks ref, form,
and use as prohibited, allowing only default, fixed, id, name, type and an inline
simpleType. The per-component applicability table is the permissive global/local
union, so it could not draw the distinction; a focused scan of the direct
attribute children of schema and redefine supplies the global-only constraint. A
local attribute use inside a complex type or attribute group is unaffected.

The existing test_validAttributeValues asserted a top-level attribute with use
compiles, which is itself invalid; corrected to a local attribute use.

XSTS: invalid schemas accepted 454 to 439, no other bucket raised.
This commit is contained in:
Mihaela Mihaljevic 2026-06-15 14:18:25 +02:00
parent aa6e76da88
commit be5d260b52
7 changed files with 82 additions and 3 deletions

View File

@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- A top-level `xs:attribute` declaration may no longer carry `use`, `form`, or `ref` (XSD 1.0 schema-for-schemas `topLevelAttribute`, #170). Those belong to a local attribute use, not a global declaration; the per-component applicability table is the permissive global/local union and so could not draw the distinction, leaving such schemas accepted. A focused scan of the direct `attribute` children of `schema` (and of `redefine`) supplies the global-only constraint; a local attribute use inside a complex type or attribute group is unaffected. XSTS: invalid schemas accepted 454 to 439, no other bucket raised.
- A `default`/`fixed` value on an element or attribute whose `type` names a user-declared type must now be a valid value of that type (XSD 1.0 `e-props-correct.2` / `a-props-correct.2`, #170). This runs after the named types are compiled, complementing the existing built-in-only check: a `default` failing the type's `pattern`, a malformed value for a type restricting a built-in, or a value invalid against a complex type's simple content is now rejected. The type name is resolved namespace-aware; only a type in the schema's own target namespace is checked (built-ins are handled at structure time; imported, foreign, or inline anonymous types are left alone), and the compiled `SimpleType` validator (the one instance validation uses) performs the check, so whitespace and facet handling match. XSTS: invalid schemas accepted 462 to 454, no other bucket raised.
- A simple-type `restriction` whose base is an inline anonymous `<simpleType>` (no `base` attribute) now resolves that inline child as its base, preserving its list or union variety. The base was read only from the `base` attribute, so an inline list/union base was dropped and the type collapsed to an atomic string: a `length` facet then counted characters instead of list items, and a list-valued `default` of the correct length was wrongly rejected once value constraints are checked. Resolving the inline base fixes both schema-time value checking and instance validation. XSTS: invalid instances accepted 160 to 158, no other bucket raised.
- An `xs:attribute` declaration carrying a `default` value constraint must now have `use="optional"` (XSD 1.0 `src-attribute.2`, #170). A default makes the attribute optional, so `use="required"` or `use="prohibited"` alongside it is contradictory; such schemas were accepted. The check rides the existing value-constraint walk, gated to XSD-namespace `attribute` declarations reading the unprefixed `default`/`use`, and is per declaration. Only `fixed` (not `default`) may pair with `use="required"`. XSTS: invalid schemas accepted 469 to 462, no other bucket raised. Disclosed under-rejection: a whitespace-padded `use=" required "` (whose NMTOKEN actual value is `required`) is not flagged.

View File

@ -78,6 +78,35 @@ extension PureXML.Schema.XSDParser {
return errors
}
/// A top-level `attribute` declaration (a direct child of `schema`, or of a
/// `redefine`) admits only `default`/`fixed`/`id`/`name`/`type` (the
/// schema-for-schemas `topLevelAttribute`): `use`, `form`, and `ref` belong to a
/// local attribute use, not a global declaration, so they are rejected here. The
/// per-component applicability table is the permissive global/local union and so
/// cannot make this distinction; this scan supplies the global-only constraint.
static func topLevelAttributeErrors(_ schema: XSDTree) -> [String] {
var errors: [String] = []
collectTopLevelAttributeErrors(in: schema, into: &errors)
for redefine in PureXML.Schema.XSDNode.elementChildren(schema) {
guard PureXML.Schema.XSDNode.localName(redefine) == "redefine" else { continue }
collectTopLevelAttributeErrors(in: redefine, into: &errors)
}
return errors
}
private static func collectTopLevelAttributeErrors(in container: XSDTree, into errors: inout [String]) {
for attribute in PureXML.Schema.XSDNode.elementChildren(container) {
guard PureXML.Schema.XSDNode.localName(attribute) == "attribute", attribute.name?.namespaceURI == xsdNamespace else { continue }
for forbidden in ["use", "form", "ref"] where hasUnprefixed(attribute, forbidden) {
errors.append("a top-level 'attribute' declaration may not specify '\(forbidden)'")
}
}
}
private static func hasUnprefixed(_ node: XSDTree, _ local: String) -> Bool {
node.attributes.contains { $0.name.prefix == nil && $0.name.localName == local }
}
private static func hasInlineType(_ node: XSDTree, _ local: String) -> Bool {
PureXML.Schema.XSDNode.elementChildren(node).contains { child in
// Only an inline type in the XSD namespace counts; a foreign-namespace

View File

@ -58,6 +58,7 @@ extension PureXML.Schema.XSDParser {
collectStructure(schema, into: &errors)
errors += simpleTypeVarietyFacetErrors(schema)
errors += valueConstraintErrors(schema)
errors += topLevelAttributeErrors(schema)
return errors
}

View File

@ -106,7 +106,8 @@ struct SchemaStructureTests {
@Test("valid enumerated and occurrence attribute values compile")
func test_validAttributeValues() throws {
try compile(#"<xs:attribute name="a" type="xs:string" use="required"/>"#)
// `use` is valid on a local attribute use, not on a top-level declaration.
try compile(#"<xs:complexType name="t"><xs:attribute name="a" type="xs:string" use="required"/></xs:complexType>"#)
try compile(#"<xs:complexType name="t" mixed="true"><xs:sequence/></xs:complexType>"#)
try compile(#"<xs:complexType name="t" abstract="false"><xs:sequence/></xs:complexType>"#)
}

View File

@ -0,0 +1,47 @@
@testable import PureXML
import Testing
@Suite("XSD top-level attribute applicability (topLevelAttribute)")
struct SchemaTopLevelAttributeTests {
private let xsd = "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\""
private func compiles(_ body: String) -> Bool {
(try? PureXML.Schema.Document("<xs:schema \(xsd)>\(body)</xs:schema>")) != nil
}
@Test("A top-level attribute with use is rejected")
func test_topLevelUseRejected() {
#expect(!compiles("<xs:attribute name=\"a\" type=\"xs:string\" use=\"required\"/>"))
#expect(!compiles("<xs:attribute name=\"a\" type=\"xs:string\" use=\"optional\"/>"))
#expect(!compiles("<xs:attribute name=\"a\" type=\"xs:string\" use=\"prohibited\"/>"))
}
@Test("A top-level attribute with form is rejected")
func test_topLevelFormRejected() {
#expect(!compiles("<xs:attribute name=\"a\" type=\"xs:string\" form=\"qualified\"/>"))
}
@Test("A plain top-level attribute declaration compiles")
func test_plainTopLevelAccepted() {
#expect(compiles("<xs:attribute name=\"a\" type=\"xs:string\"/>"))
#expect(compiles("<xs:attribute name=\"a\" type=\"xs:string\" default=\"x\"/>"))
}
/// `use`, `form`, and a `ref` are legitimate on a LOCAL attribute use inside a
/// complex type; the rule applies only to top-level declarations.
@Test("A local attribute use with use/form compiles")
func test_localUseAccepted() {
#expect(compiles(
"<xs:element name=\"e\"><xs:complexType>"
+ "<xs:attribute name=\"a\" type=\"xs:string\" use=\"required\" form=\"qualified\"/>"
+ "</xs:complexType></xs:element>",
))
// A local ref with use is fine.
#expect(compiles(
"<xs:attribute name=\"g\" type=\"xs:string\"/>"
+ "<xs:element name=\"e\"><xs:complexType>"
+ "<xs:attribute ref=\"g\" use=\"required\"/>"
+ "</xs:complexType></xs:element>",
))
}
}

View File

@ -29,7 +29,7 @@ struct XSTSSuiteTests {
/// 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 = 1
private let knownSchemaInvalidAccepted = 454
private let knownSchemaInvalidAccepted = 439
private let knownInstanceValidRejected = 180
private let knownInstanceInvalidAccepted = 158

View File

@ -10,7 +10,7 @@ irreducible tail. Do not deviate to new features while this is open.
| Bucket | Count | Reading |
|---|---|---|
| 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 -> 454** | 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 landed). |
| **invalid-schemas-accepted** | **2461 -> 439** | 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 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) |