From 5ebf3b861c7bd5218959f10324dea2a360b7c9b1 Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Sun, 14 Jun 2026 02:28:29 +0200 Subject: [PATCH] feat(schema): enforce component-name uniqueness Within a schema, global type names (simpleType and complexType share one symbol space), global element names, global attribute names, named model-group names, and named attribute-group names must each be unique, and identity-constraint names must be unique across the document. A duplicate was accepted, with the later definition silently overwriting the earlier one. Only the document's own globals are examined (xs:redefine children and unloaded included documents are not direct globals), so a redefinition is not mistaken for a clash; the symbol spaces are kept separate, so a type and an element may share a name. XSTS: invalid schemas accepted 909 to 891 (-18); valid schemas rejected held at 72; instance buckets unchanged. --- CHANGELOG.md | 1 + Sources/Schema/SchemaNameUniqueness.swift | 65 +++++++++++++++++++++++ Sources/Schema/XSDParser.swift | 2 +- Tests/SchemaNameUniquenessTests.swift | 65 +++++++++++++++++++++++ Tests/XSTSSuiteTests.swift | 2 +- docs/schema-validity-burndown.md | 9 ++-- docs/xsts-deviations.md | 4 +- 7 files changed, 139 insertions(+), 9 deletions(-) create mode 100644 Sources/Schema/SchemaNameUniqueness.swift create mode 100644 Tests/SchemaNameUniquenessTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 0339b98..543c72c 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 +- Component-name uniqueness is now enforced (#147). Within a schema, global type names (`simpleType` and `complexType` share one symbol space), global element names, global attribute names, named model-group names, and named attribute-group names must each be unique, and identity-constraint names must be unique across the document; a duplicate was accepted, with the later definition silently overwriting the earlier. Only the document's own globals are examined (an `xs:redefine`'s same-named type is not a clash), and the symbol spaces are kept separate (a type and an element may share a name). XSTS: invalid schemas accepted 909 to 891, no other bucket raised. - Element Declarations Consistent (`cos-element-consistent`) is now enforced (#147). Within one complex type's content model, two element declarations with the same name must have the same type; two same-name elements with different types (e.g. `a` as `xs:string` and as `xs:integer`) were accepted. The check walks the content model (through model groups and content-derivation wrappers) but not into an element's own nested type, so a reused name in a nested anonymous type, a separate content model, is not flagged. Modeled on Xerces (libxml2 only partially enforces this); substitution-group expansion is not folded in (an accepted under-rejection). XSTS: invalid schemas accepted 925 to 909, no other bucket raised. - Schema-vocabulary attribute applicability is now enforced at compile time (#147), the attribute sibling of the content-model table. Each XSD component admits a fixed set of attributes (the schema for schemas); an unprefixed attribute outside that set (a typo like `nullable`, a stray `foo`, `name` on a `sequence`) is now rejected, and `ref` may not co-occur with `name` or `type`. Foreign (prefixed) attributes and namespace declarations are not the component's own and are not checked, and the element/attribute sets are the permissive union of global and local use, so no valid schema is rejected. XSTS: invalid schemas accepted 956 to 925, no other bucket raised. - A named model-group definition (`xs:group name="..."`) must contain exactly one of `all`/`choice`/`sequence` (#147). XSD 1.0 gives a group's content as `(annotation?, (all | choice | sequence))`, but the `allowedChildren` set-membership check did not enforce the cardinality, so a group with two compositors or with none was accepted. A `group` reference (no `name`) is excluded. XSTS: invalid schemas accepted 977 to 956, no other bucket raised. diff --git a/Sources/Schema/SchemaNameUniqueness.swift b/Sources/Schema/SchemaNameUniqueness.swift new file mode 100644 index 0000000..de27529 --- /dev/null +++ b/Sources/Schema/SchemaNameUniqueness.swift @@ -0,0 +1,65 @@ +extension PureXML.Schema.XSDParser { + /// Schema-validity findings for component-name uniqueness. Within a schema, + /// global type names (simpleType and complexType share one symbol space), + /// global element names, global attribute names, named model-group names, and + /// named attribute-group names must each be unique; identity-constraint names + /// (unique/key/keyref) must be unique across the whole schema. A duplicate was + /// accepted, with a later definition silently overwriting the earlier one. + /// + /// Only the document's own globals are examined (`xs:redefine` children and + /// included documents are not direct globals here), so a redefinition is not + /// mistaken for a clash. + static func componentNameErrors(_ schema: XSDTree) -> [String] { + let globals = PureXML.Schema.XSDNode.elementChildren(schema) + .filter { $0.name?.namespaceURI == xsdNamespace } + var errors: [String] = [] + errors += duplicateNames(of: ["simpleType", "complexType"], in: globals, label: "type") + errors += duplicateNames(of: ["element"], in: globals, label: "element") + errors += duplicateNames(of: ["attribute"], in: globals, label: "attribute") + errors += duplicateNames(of: ["group"], in: globals, label: "model group") + errors += duplicateNames(of: ["attributeGroup"], in: globals, label: "attribute group") + errors += identityConstraintNameErrors(schema) + return errors + } + + /// Duplicate `name` values among the `kinds` components in `nodes`. + private static func duplicateNames(of kinds: Set, in nodes: [XSDTree], label: String) -> [String] { + var seen: Set = [] + var errors: [String] = [] + for node in nodes where kinds.contains(PureXML.Schema.XSDNode.localName(node) ?? "") { + guard let name = PureXML.Schema.XSDNode.attribute(node, "name")?.trimmingXMLWhitespace() else { continue } + if !seen.insert(name).inserted { + errors.append("duplicate \(label) name '\(name)'") + } + } + return errors + } + + /// Duplicate identity-constraint names anywhere in the schema document. + private static func identityConstraintNameErrors(_ schema: XSDTree) -> [String] { + var seen: Set = [] + var errors: [String] = [] + func walk(_ node: XSDTree) { + let local = PureXML.Schema.XSDNode.localName(node) + if local == "appinfo" || local == "documentation" { return } + if let name = identityConstraintName(node), !seen.insert(name).inserted { + errors.append("duplicate identity constraint name '\(name)'") + } + for child in PureXML.Schema.XSDNode.elementChildren(node) { + walk(child) + } + } + walk(schema) + return errors + } + + /// The `name` of `node` when it is an identity constraint (`unique`/`key`/ + /// `keyref`) in the XSD namespace, or nil. + private static func identityConstraintName(_ node: XSDTree) -> String? { + guard node.name?.namespaceURI == xsdNamespace, + let local = PureXML.Schema.XSDNode.localName(node), + ["unique", "key", "keyref"].contains(local) + else { return nil } + return PureXML.Schema.XSDNode.attribute(node, "name")?.trimmingXMLWhitespace() + } +} diff --git a/Sources/Schema/XSDParser.swift b/Sources/Schema/XSDParser.swift index 64853bd..faa2a30 100644 --- a/Sources/Schema/XSDParser.swift +++ b/Sources/Schema/XSDParser.swift @@ -33,7 +33,7 @@ extension PureXML.Schema { context.attributeFormQualified = XSDNode.attribute(schema, "attributeFormDefault") == "qualified" context.complexTypeNodes = indexByName(allChildren(containers, named: "complexType")) context.globalAttributes = indexByName(allChildren(containers, named: "attribute")) - for error in idAttributeErrors(schema) + structureErrors(schema) { + for error in idAttributeErrors(schema) + structureErrors(schema) + componentNameErrors(schema) { context.diagnostics.report(error) } var types = namedTypes(containers, into: &context) diff --git a/Tests/SchemaNameUniquenessTests.swift b/Tests/SchemaNameUniquenessTests.swift new file mode 100644 index 0000000..78a0ebc --- /dev/null +++ b/Tests/SchemaNameUniquenessTests.swift @@ -0,0 +1,65 @@ +@testable import PureXML +import Testing + +/// Component-name uniqueness (XSD 1.0 symbol-space constraints): within a schema, +/// global type names (simpleType and complexType share one space), global element +/// names, global attribute names, named model-group names, and named +/// attribute-group names must each be unique, and identity-constraint names must +/// be unique across the document. A duplicate was previously accepted, with the +/// later definition silently overwriting the earlier one. +@Suite("Schema component-name uniqueness") +struct SchemaNameUniquenessTests { + private func compile(_ body: String) throws { + _ = try PureXML.Schema.Document(""" + + \(body) + + """) + } + + private func rejects(_ body: String) -> Bool { + do { try compile(body) + return false + } catch { return true } + } + + @Test("distinct global names compile") + func test_valid() throws { + try compile(#""" + + + + """#) + // A name shared across different symbol spaces (a type and an element) is + // allowed. + try compile(#""" + + + """#) + } + + @Test("a duplicate global type name is rejected (one symbol space)") + func test_duplicateType() { + #expect(rejects(#""#)) + // simpleType and complexType share the type symbol space. + #expect(rejects(#""#)) + } + + @Test("a duplicate global element or attribute name is rejected") + func test_duplicateElementAttribute() { + #expect(rejects(#""#)) + #expect(rejects(#""#)) + } + + @Test("a duplicate identity-constraint name is rejected") + func test_duplicateIdentityConstraint() { + #expect(rejects(#""" + + + + + + + """#)) + } +} diff --git a/Tests/XSTSSuiteTests.swift b/Tests/XSTSSuiteTests.swift index fad7de9..6520c2e 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 = 909 + private let knownSchemaInvalidAccepted = 891 private let knownInstanceValidRejected = 214 private let knownInstanceInvalidAccepted = 165 diff --git a/docs/schema-validity-burndown.md b/docs/schema-validity-burndown.md index dcac00e..c23188f 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 -> 909** | we rarely catch a bad one (facet, id, and structural content-model validity landed) | +| **invalid-schemas-accepted** | **2461 -> 891** | 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 | | @@ -57,10 +57,9 @@ Each iteration targets one self-contained rule family with a clean root cause. unique within the schema document. Walks the schema-document tree, skipping `appinfo`/`documentation` foreign content and treating only the unprefixed `id` as the component identifier. Broad reach (idA-idK, attgA, attB, ctA). -3. **Component-name uniqueness.** Identity-constraint names unique per schema; - type / element / attribute names unique per namespace; no duplicate attribute - uses on a type. Cheap graph checks (~12 identity-constraint-name cases, plus - type/element/attribute name collisions). +3. **Component-name uniqueness.** _Done (909 -> 891)._ Global type (one space for + simpleType+complexType), element, attribute, model-group, attribute-group names + unique; identity-constraint names unique per document (`SchemaNameUniqueness.swift`). 4. **Resolvable references.** _Done (1092 -> 1051)._ `type`/`base`/`itemType`/ `memberTypes` types, `element`/`attribute`/`group`/`attributeGroup` `ref`, and element `substitutionGroup` must resolve to a declared component or a built-in diff --git a/docs/xsts-deviations.md b/docs/xsts-deviations.md index 358fcfb..90dfeed 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-seven root causes, ~2226 deviations cleared) +### Fixed (twenty-eight root causes, ~2244 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 909 (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`. +accepted 2461 to 891 (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)