From 6fbc92593e197796b3868c09011359d415e771bb Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Sun, 14 Jun 2026 00:32:54 +0200 Subject: [PATCH] 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. --- CHANGELOG.md | 1 + Sources/Schema/SchemaReferences.swift | 12 +++++++-- Sources/Schema/SchemaStructure.swift | 31 ++++++++++++++++++++++++ Tests/SchemaStructureTests.swift | 35 +++++++++++++++++++++++++++ Tests/XSTSSuiteTests.swift | 2 +- docs/schema-validity-burndown.md | 2 +- docs/xsts-deviations.md | 4 +-- 7 files changed, 81 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b435b2d..e96fb5b 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 +- 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. diff --git a/Sources/Schema/SchemaReferences.swift b/Sources/Schema/SchemaReferences.swift index b32dd3f..f018e21 100644 --- a/Sources/Schema/SchemaReferences.swift +++ b/Sources/Schema/SchemaReferences.swift @@ -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, diff --git a/Sources/Schema/SchemaStructure.swift b/Sources/Schema/SchemaStructure.swift index 18ad8a4..08473bb 100644 --- a/Sources/Schema/SchemaStructure.swift +++ b/Sources/Schema/SchemaStructure.swift @@ -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 = ["group", "all", "choice", "sequence"] + private static let directAttributes: Set = ["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 [] + } } diff --git a/Tests/SchemaStructureTests.swift b/Tests/SchemaStructureTests.swift index 93fe359..4b59901 100644 --- a/Tests/SchemaStructureTests.swift +++ b/Tests/SchemaStructureTests.swift @@ -115,6 +115,41 @@ struct SchemaStructureTests { try compile(#""#) } + @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(#""" + + + + + """#)) + #expect(rejects(#""" + + + + + """#)) + #expect(rejects(#""" + + + + + """#)) + } + + @Test("valid complexType content shapes compile") + func test_complexTypeContentValid() throws { + try compile(#""" + + + + """#) + try compile(#""#) + try compile(#""#) + } + @Test("an identity constraint requires a selector and field") func test_identityConstraintRequiresParts() { #expect(rejects(#""" diff --git a/Tests/XSTSSuiteTests.swift b/Tests/XSTSSuiteTests.swift index 8b36d6c..54d4a7f 100644 --- a/Tests/XSTSSuiteTests.swift +++ b/Tests/XSTSSuiteTests.swift @@ -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 diff --git a/docs/schema-validity-burndown.md b/docs/schema-validity-burndown.md index 75f1aa8..a19615e 100644 --- a/docs/schema-validity-burndown.md +++ b/docs/schema-validity-burndown.md @@ -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 | | diff --git a/docs/xsts-deviations.md b/docs/xsts-deviations.md index 2f32fc6..0ac5f1b 100644 --- a/docs/xsts-deviations.md +++ b/docs/xsts-deviations.md @@ -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)