feat(schema): enforce the complexType content-model shape

XSD 1.0 allows a complexType's content to be simpleContent, or complexContent,
or a model group followed by attributes, never a mix. The allowedChildren
set-membership check permitted illegal combinations, so a complexType with two
simpleContent, simpleContent beside a sequence, or two model groups was accepted.

complexTypeContentErrors now enforces, over the complexType's direct children:
at most one of simpleContent/complexContent; when one is present, no direct model
group and no direct attribute (those belong inside the extension/restriction);
and at most one model group. Only direct children are examined, so attributes
nested inside a derivation are not flagged.

XSTS: invalid schemas accepted 1051 to 997 (-54); valid schemas rejected held at
72; instance buckets unchanged. Also folds in a behavior-identical lint cleanup
of the reference-walk external-definition check.
This commit is contained in:
Mihaela Mihaljevic 2026-06-14 00:32:54 +02:00
parent cbeea0e3c2
commit 6fbc92593e
7 changed files with 81 additions and 6 deletions

View File

@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- A complexType's content-model shape is now enforced at compile time (#147). XSD 1.0 allows a complexType's content to be `simpleContent`, or `complexContent`, or a model group followed by attributes, but never a mix: so at most one of `simpleContent`/`complexContent`, neither beside a model group or a direct attribute (those belong inside the derivation), and at most one model group. The `allowedChildren` set-membership check did not catch these combinations, so a malformed complexType (two `simpleContent`, `simpleContent` plus a `sequence`, two model groups) was accepted. Only the complexType's direct children are examined, so attributes legitimately nested inside an extension/restriction are not flagged. XSTS: invalid schemas accepted 1051 to 997, no other bucket raised.
- Unresolvable references are now rejected at compile time (#147). Every QName a schema names (a `type`/`base`/`itemType`/`memberTypes` type, an `element`/`attribute`/`group`/`attributeGroup` `ref`, an element `substitutionGroup`) must resolve to a declared component or a built-in; an undeclared reference was previously accepted and only surfaced (if at all) lazily during instance validation. The reference is matched by local name with whitespace trimmed, as the rest of the compiler resolves it. The check is skipped when the document pulls in external definitions through `import`/`include`/`redefine`, which the default compile does not load, so a reference into them is never flagged. XSTS: invalid schemas accepted 1092 to 1051, no other bucket raised.
- `pattern` facet regular expressions are now validated at compile time (#147). Each `pattern` value is compiled when the schema is; a structurally malformed one (unbalanced parentheses `((a)`, a quantifier with nothing to repeat `?a`) is rejected, where before it was only compiled lazily at instance time (`try?`) and so silently ignored. The check is conservative: a construct the engine merely does not support on an otherwise-valid pattern (the empty pattern, an untabulated `\p{Is...}` block such as a surrogate or historic block, the lenient `{,m}` quantifier) is tolerated, so no valid schema is rejected. XSTS: invalid schemas accepted 1129 to 1092, no other bucket raised.
- Schema-vocabulary name and reference attribute values are now checked for lexical validity at compile time (#147). A component's `name` must be a valid NCName (`name=""`, `name="123"`, `name="a:b"` are rejected), and the reference attributes `type`/`base`/`ref`/`itemType`/`refer`/`substitutionGroup` must be lexical QNames (`type=":_"`, `type="a:b:c"` rejected), with `memberTypes` a list of QNames; these were unchecked and the schema accepted. Only the lexical form is checked (a QName's prefix is resolved elsewhere), so no valid schema is rejected. XSTS: invalid schemas accepted 1190 to 1129, no other bucket raised.

View File

@ -36,8 +36,7 @@ extension PureXML.Schema.XSDParser {
private static func hasExternalReference(_ schema: XSDTree) -> Bool {
var found = false
func walk(_ node: XSDTree) {
if node.name?.namespaceURI == xsdNamespace, let local = PureXML.Schema.XSDNode.localName(node),
["import", "include", "redefine"].contains(local) {
if isExternalDefinition(node) {
found = true
return
}
@ -49,6 +48,15 @@ extension PureXML.Schema.XSDParser {
return found
}
/// Whether `node` is an `xs:import`/`xs:include`/`xs:redefine` (an XSD-namespace
/// element bringing in external definitions).
private static func isExternalDefinition(_ node: XSDTree) -> Bool {
guard node.name?.namespaceURI == xsdNamespace, let local = PureXML.Schema.XSDNode.localName(node) else {
return false
}
return local == "import" || local == "include" || local == "redefine"
}
private static func collectReferenceErrors(
_ node: XSDTree,
types: Set<String>,

View File

@ -154,6 +154,37 @@ extension PureXML.Schema.XSDParser {
if ["unique", "key", "keyref"].contains(local), !(children.contains("selector") && children.contains("field")) {
errors.append("identity constraint '\(local)' requires a selector and at least one field")
}
if local == "complexType" {
errors += complexTypeContentErrors(children)
}
return errors
}
/// The model groups and the attribute declarations a `complexType` may carry
/// directly, used to enforce its content-model shape.
private static let modelGroups: Set<String> = ["group", "all", "choice", "sequence"]
private static let directAttributes: Set<String> = ["attribute", "attributeGroup", "anyAttribute"]
/// Findings for a `complexType`'s direct content shape (XSD 1.0 Structures):
/// its content is `simpleContent`, `complexContent`, or a model group followed
/// by attributes, never a mix. So at most one of `simpleContent`/
/// `complexContent`; when one is present, no model group and no direct
/// attribute may sit beside it (they belong inside the derivation); and at most
/// one model group. Children inside `simpleContent`/`complexContent` are not
/// examined here, only the complexType's own children.
private static func complexTypeContentErrors(_ children: [String]) -> [String] {
let contentSpecs = children.count { $0 == "simpleContent" || $0 == "complexContent" }
let groups = children.count { modelGroups.contains($0) }
let attributes = children.count { directAttributes.contains($0) }
if contentSpecs > 1 {
return ["'complexType' may have only one of simpleContent or complexContent"]
}
if contentSpecs == 1, groups > 0 || attributes > 0 {
return ["'complexType' with simpleContent or complexContent may not also have a model group or attribute"]
}
if groups > 1 {
return ["'complexType' may have at most one model group"]
}
return []
}
}

View File

@ -115,6 +115,41 @@ struct SchemaStructureTests {
try compile(#"<xs:complexType name="t"><xs:sequence><xs:element ref="g"/></xs:sequence></xs:complexType><xs:element name="g" type="xs:string"/>"#)
}
@Test("a complexType's content shape is exclusive")
func test_complexTypeContentExclusivity() {
// simpleContent/complexContent are mutually exclusive and exclude a model
// group or a direct attribute; only one model group is allowed.
#expect(rejects(#"""
<xs:complexType name="t">
<xs:simpleContent><xs:extension base="xs:string"/></xs:simpleContent>
<xs:simpleContent><xs:extension base="xs:string"/></xs:simpleContent>
</xs:complexType>
"""#))
#expect(rejects(#"""
<xs:complexType name="t">
<xs:simpleContent><xs:extension base="xs:string"/></xs:simpleContent>
<xs:sequence><xs:element name="a" type="xs:string"/></xs:sequence>
</xs:complexType>
"""#))
#expect(rejects(#"""
<xs:complexType name="t">
<xs:sequence><xs:element name="a" type="xs:string"/></xs:sequence>
<xs:choice><xs:element name="b" type="xs:string"/></xs:choice>
</xs:complexType>
"""#))
}
@Test("valid complexType content shapes compile")
func test_complexTypeContentValid() throws {
try compile(#"""
<xs:complexType name="t">
<xs:simpleContent><xs:extension base="xs:string"><xs:attribute name="a" type="xs:string"/></xs:extension></xs:simpleContent>
</xs:complexType>
"""#)
try compile(#"<xs:complexType name="t"><xs:sequence><xs:element name="a" type="xs:string"/></xs:sequence><xs:attribute name="x" type="xs:string"/></xs:complexType>"#)
try compile(#"<xs:complexType name="t"><xs:attribute name="x" type="xs:string"/></xs:complexType>"#)
}
@Test("an identity constraint requires a selector and field")
func test_identityConstraintRequiresParts() {
#expect(rejects(#"""

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 = 72
private let knownSchemaInvalidAccepted = 1051
private let knownSchemaInvalidAccepted = 997
private let knownInstanceValidRejected = 214
private let knownInstanceInvalidAccepted = 165

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 | we rarely reject a good schema |
| **invalid-schemas-accepted** | **2461 -> 1051** | we rarely catch a bad one (facet, id, and structural content-model validity landed) |
| **invalid-schemas-accepted** | **2461 -> 997** | we rarely catch a bad one (facet, id, and structural content-model validity landed) |
| valid-instances-rejected | 233 | (instance side, separately tracked) |
| invalid-instances-accepted | 165 | |

View File

@ -47,7 +47,7 @@ and to document the remainder as spec-justified, deliberate exclusions.
## Category A: genuine correctness bugs
### Fixed (twenty-two root causes, ~2084 deviations cleared)
### Fixed (twenty-three root causes, ~2138 deviations cleared)
list-datatype length facets (#146) · union pattern/enumeration facets · duration
partial-order facets · QName length non-constraining · the full XSD `\p{Is...}`
@ -65,7 +65,7 @@ validity (`min`/`maxInclusive`, `min`/`maxExclusive`, `enumeration` values valid
in the base space; inclusive/exclusive exclusions; bound ordering) · `gMonth`
`--MM--` lexical form · schema `id` attribute validity (`xs:ID`: NCName and
unique within the document). The schema-validity work brought invalid schemas
accepted 2461 to 1051 (schema-document structural validity: content model, attribute values, name/reference + pattern-regex lexical validity, and reference resolution, against the schema-for-schemas); see `schema-validity-burndown.md`.
accepted 2461 to 997 (schema-document structural validity: content model + complexType content shape, attribute values, name/reference + pattern-regex lexical validity, and reference resolution, against the schema-for-schemas); see `schema-validity-burndown.md`.
Plus the measurement fix (exclude W3C-disputed `status="queried"` entries).
### Remaining, root-caused (the hard tail)