From 55daca46bedc0253aca3186f1f212573784b49d1 Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Tue, 16 Jun 2026 00:02:04 +0200 Subject: [PATCH] fix(schema): implement facet applicability and validation constraints --- CHANGELOG.md | 2 + Sources/Schema/SchemaNotationValidity.swift | 2 +- Sources/Schema/SimpleType.swift | 19 ++- Sources/Schema/XSDParser.swift | 72 +++----- Sources/Schema/XSDParserHelpers.swift | 32 ++++ Sources/Schema/XSDSimpleParser+Facets.swift | 113 +++++++++++++ Sources/Schema/XSDSimpleParser.swift | 176 ++++++++------------ Tests/SchemaFacetDefinitionTests.swift | 80 +++++++++ Tests/XSTSSuiteTests.swift | 2 +- docs/schema-validity-burndown.md | 2 +- 10 files changed, 336 insertions(+), 164 deletions(-) create mode 100644 Sources/Schema/XSDSimpleParser+Facets.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 10f30d8..19826b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Enforce facet applicability per base type, fractionDigits constraints on integer types, ordered duration range bounds, and built-in list non-emptiness constraints (XSD 1.0 Datatypes §4.3). Ensure that built-in list types (xs:IDREFS, xs:ENTITIES, xs:NMTOKENS) are validated as non-empty unless restricted with an explicit minLength. Resolve type references namespace-aware to avoid prefix conflation with user types of the same name. Ignore foreign elements matching facet names inside xs:restriction. XSTS: invalid schemas accepted 296 to 266, no other bucket raised. + - Enforce schema element order (imports, includes, and redefines must precede other global declarations) and validate import constraints (namespace attribute must not match the schema's targetNamespace, and if missing, the schema must have a targetNamespace) (XSD 1.0 Structures §3.10.6, §3.15.2). XSTS: invalid schemas accepted 302 to 296, no other bucket raised. - Validate duplicate schema container names across separate files with identical content (XSD 1.0 Structures §3.14). Deduplicate schema include/import containers during compilation using both targetNamespace/structural equality and their relative schemaLocation paths to prevent false deduplication of separate documents. Keep circular self-imports/includes of the root schema valid. XSTS: invalid schemas accepted 304 to 302, no other bucket raised. - Validate standard `xml:lang` and `xml:space` attributes on XSD schema elements (like `` and ``). Traversal is adjusted to process attributes on these documentation-related elements before skipping their foreign children, and validation checks the lexical pattern of `xml:lang` (using BCP 47) and restricts `xml:space` to 'default' or 'preserve'. XSTS: invalid schemas accepted 306 to 304, no other bucket raised. diff --git a/Sources/Schema/SchemaNotationValidity.swift b/Sources/Schema/SchemaNotationValidity.swift index f151ff9..5032165 100644 --- a/Sources/Schema/SchemaNotationValidity.swift +++ b/Sources/Schema/SchemaNotationValidity.swift @@ -67,7 +67,7 @@ extension PureXML.Schema.XSDParser { return } let baseType = PureXML.Schema.XSDSimpleParser.simpleTypeReference(baseAttr, context) - guard baseType.base == .notation else { return } + guard baseType.base == PureXML.Schema.BuiltinType.notation else { return } let bindings = collectBindings(from: node) for child in PureXML.Schema.XSDNode.elementChildren(node) where child.name?.namespaceURI == xsdNamespace && PureXML.Schema.XSDNode.localName(child) == "enumeration" { diff --git a/Sources/Schema/SimpleType.swift b/Sources/Schema/SimpleType.swift index 011bed2..9b95d1d 100644 --- a/Sources/Schema/SimpleType.swift +++ b/Sources/Schema/SimpleType.swift @@ -74,17 +74,25 @@ public extension PureXML.Schema { public var facets: Facets public var variety: Variety public var isAnySimpleType: Bool + public var isBuiltinList: Bool - public init(base: BuiltinType, facets: Facets = Facets(), variety: Variety = .atomic, isAnySimpleType: Bool = false) { + public init( + base: BuiltinType, + facets: Facets = Facets(), + variety: Variety = .atomic, + isAnySimpleType: Bool = false, + isBuiltinList: Bool = false, + ) { self.base = base self.facets = facets self.variety = variety self.isAnySimpleType = isAnySimpleType + self.isBuiltinList = isBuiltinList } /// A list type whose items are `item`, carrying its own (list) facets. - public static func list(item: SimpleType, facets: Facets = Facets()) -> SimpleType { - SimpleType(base: .string, facets: facets, variety: .list(item)) + public static func list(item: SimpleType, facets: Facets = Facets(), isBuiltinList: Bool = false) -> SimpleType { + SimpleType(base: .string, facets: facets, variety: .list(item), isBuiltinList: isBuiltinList) } /// A union of `members`: a value is valid if any member admits it. @@ -116,6 +124,11 @@ public extension PureXML.Schema { if let exact = facets.length, tokens.count != exact { return "list length \(tokens.count) is not \(exact)" } if let minimum = facets.minLength, tokens.count < minimum { return "list length \(tokens.count) is below \(minimum)" } if let maximum = facets.maxLength, tokens.count > maximum { return "list length \(tokens.count) is above \(maximum)" } + if facets.minLength == nil, facets.length == nil { + if isBuiltinList, tokens.isEmpty { + return "list must not be empty" + } + } if let error = patternError(normalized) { return error } if let enumeration = facets.enumeration, !enumeration.contains(normalized) { return "'\(normalized)' is not in the enumeration" diff --git a/Sources/Schema/XSDParser.swift b/Sources/Schema/XSDParser.swift index b236284..3f6dcda 100644 --- a/Sources/Schema/XSDParser.swift +++ b/Sources/Schema/XSDParser.swift @@ -171,37 +171,11 @@ extension PureXML.Schema.XSDParser { } } - static func elementKey(_ name: String) -> String { - "element:\(name)" - } - - private static func indexByName(_ nodes: [XSDTree]) -> [String: XSDTree] { - var index: [String: XSDTree] = [:] - for node in nodes { - if let name = XSDNode.attribute(node, "name") { index[name] = node } - } - return index - } - // MARK: Element and type references - /// The derivation identity of an element's type: the resolved local name of - /// its `type` reference, `anyType` when the type is absent (the implied type), - /// or nil when the type is an inline anonymous definition (no name to derive - /// against). - static func elementTypeName(_ node: XSDTree) -> String? { - if let typeName = XSDNode.attribute(node, "type") { - return XSDNode.stripPrefix(typeName) - } - if XSDNode.firstChild(node, named: "simpleType") != nil || XSDNode.firstChild(node, named: "complexType") != nil { - return nil - } - return "anyType" - } - private static func elementType(_ node: XSDTree, _ context: XSDContext) -> ElementType { if let typeName = XSDNode.attribute(node, "type") { - return typeReference(typeName) + return typeReference(typeName, context) } if let inline = XSDNode.firstChild(node, named: "simpleType") { return .simple(XSDSimpleParser.simpleType(inline, context)) @@ -212,13 +186,16 @@ extension PureXML.Schema.XSDParser { return .complex(anyType) } - private static func typeReference(_ typeName: String) -> ElementType { + private static func typeReference(_ typeName: String, _ context: XSDContext) -> ElementType { let local = XSDNode.stripPrefix(typeName) - if let builtin = BuiltinType(rawValue: local) { - return .simple(SimpleType(base: builtin)) - } - if let item = XSDSimpleParser.listBuiltinItem(local) { - return .simple(.list(item: SimpleType(base: item))) + let uri = XSDNode.referenceNamespace(typeName, context.namespaceBindings) + if uri == PureXML.Schema.XSDParser.xsdNamespace { + if let builtin = BuiltinType(rawValue: local) { + return .simple(SimpleType(base: builtin)) + } + if let item = XSDSimpleParser.listBuiltinItem(local) { + return .simple(.list(item: SimpleType(base: item), isBuiltinList: true)) + } } return .typeReference(local) } @@ -258,29 +235,28 @@ extension PureXML.Schema.XSDParser { return ComplexType(attributes: attributes, attributeWildcard: wildcard, content: mixed ? .mixed(particle) : .elementOnly(particle)) } - private static func derivation(_ node: XSDTree) -> XSDTree? { - XSDNode.firstChild(node, named: "restriction") ?? XSDNode.firstChild(node, named: "extension") - } - private static func simpleContentType(_ node: XSDTree, _ context: XSDContext) -> SimpleType { guard let inner = derivation(node) else { return SimpleType(base: .string) } - let baseName = XSDNode.stripPrefix(XSDNode.attribute(inner, "base") ?? "string") - let base = BuiltinType(rawValue: baseName) ?? context.simpleTypes[baseName]?.base ?? .string - var facets = context.simpleTypes[baseName]?.facets ?? Facets() + let rawBase = XSDNode.attribute(inner, "base") ?? "string" + let baseName = XSDNode.stripPrefix(rawBase) + let uri = XSDNode.referenceNamespace(rawBase, context.namespaceBindings) + + let base: BuiltinType + let inheritedFacets: Facets + if uri == PureXML.Schema.XSDParser.xsdNamespace { + base = BuiltinType(rawValue: baseName) ?? .string + inheritedFacets = Facets() + } else { + base = context.simpleTypes[baseName]?.base ?? .string + inheritedFacets = context.simpleTypes[baseName]?.facets ?? Facets() + } + var facets = inheritedFacets XSDSimpleParser.applyFacets(inner, into: &facets) return SimpleType(base: base, facets: facets) } // MARK: Attribute uses and groups - /// The `default` or `fixed` value constraint declared on an attribute or - /// element node, if any (`fixed` takes precedence). - static func valueConstraint(of node: XSDTree) -> PureXML.Schema.ValueConstraint? { - if let fixed = XSDNode.attribute(node, "fixed") { return .fixed(fixed) } - if let value = XSDNode.attribute(node, "default") { return .default(value) } - return nil - } - // MARK: Model groups static func modelGroup(in node: XSDTree, _ context: PureXML.Schema.XSDContext) -> PureXML.Schema.Particle? { diff --git a/Sources/Schema/XSDParserHelpers.swift b/Sources/Schema/XSDParserHelpers.swift index d779c9d..497c1b9 100644 --- a/Sources/Schema/XSDParserHelpers.swift +++ b/Sources/Schema/XSDParserHelpers.swift @@ -57,4 +57,36 @@ extension PureXML.Schema.XSDParser { let qualified = form == "qualified" || (form == nil && context.elementFormQualified) return PureXML.Model.QualifiedName(localName: name, namespaceURI: qualified ? context.targetNamespace : nil) } + + static func elementKey(_ name: String) -> String { + "element:\(name)" + } + + static func indexByName(_ nodes: [XSDTree]) -> [String: XSDTree] { + var index: [String: XSDTree] = [:] + for node in nodes { + if let name = PureXML.Schema.XSDNode.attribute(node, "name") { index[name] = node } + } + return index + } + + static func elementTypeName(_ node: XSDTree) -> String? { + if let typeName = PureXML.Schema.XSDNode.attribute(node, "type") { + return PureXML.Schema.XSDNode.stripPrefix(typeName) + } + if PureXML.Schema.XSDNode.firstChild(node, named: "simpleType") != nil || PureXML.Schema.XSDNode.firstChild(node, named: "complexType") != nil { + return nil + } + return "anyType" + } + + static func derivation(_ node: XSDTree) -> XSDTree? { + PureXML.Schema.XSDNode.firstChild(node, named: "restriction") ?? PureXML.Schema.XSDNode.firstChild(node, named: "extension") + } + + static func valueConstraint(of node: XSDTree) -> PureXML.Schema.ValueConstraint? { + if let fixed = PureXML.Schema.XSDNode.attribute(node, "fixed") { return .fixed(fixed) } + if let value = PureXML.Schema.XSDNode.attribute(node, "default") { return .default(value) } + return nil + } } diff --git a/Sources/Schema/XSDSimpleParser+Facets.swift b/Sources/Schema/XSDSimpleParser+Facets.swift new file mode 100644 index 0000000..70bf35b --- /dev/null +++ b/Sources/Schema/XSDSimpleParser+Facets.swift @@ -0,0 +1,113 @@ +private typealias XSDNode = PureXML.Schema.XSDNode +private typealias SimpleType = PureXML.Schema.SimpleType +private typealias XSDContext = PureXML.Schema.XSDContext +private typealias BuiltinType = PureXML.Schema.BuiltinType +private typealias Facets = PureXML.Schema.Facets + +extension PureXML.Schema.XSDSimpleParser { + /// The canonical digit string of a lexical `nonNegativeInteger` (optional + /// leading `+`, ASCII digits, surrounding whitespace tolerated), with the + /// sign and leading zeros stripped (`"0"` for zero), or nil when the lexical + /// is not one (`-1`, ``, `a`, `1e2`). Independent of machine-integer range, + /// so a huge but well-formed value is canonicalized, not misreported as + /// malformed; the canonical form orders two values by length then lexically. + static func canonicalNonNegativeInteger(_ lexical: String) -> String? { + var digits = Substring(lexical.trimmingXMLWhitespace()) + if digits.first == "+" { digits = digits.dropFirst() } + guard !digits.isEmpty, digits.allSatisfy({ $0.isASCII && $0.isNumber }) else { return nil } + let trimmed = digits.drop { $0 == "0" } + return trimmed.isEmpty ? "0" : String(trimmed) + } + + /// Whether canonical nonNegativeInteger `lhs` is greater than `rhs`: a longer + /// digit string is larger, and same-length strings compare lexicographically. + static func greater(_ lhs: String, than rhs: String) -> Bool { + lhs.count != rhs.count ? lhs.count > rhs.count : lhs > rhs + } + + static func simpleTypeReference(_ typeName: String, _ context: PureXML.Schema.XSDContext) -> PureXML.Schema.SimpleType { + let local = XSDNode.stripPrefix(typeName) + let uri = XSDNode.referenceNamespace(typeName, context.namespaceBindings) + + if uri == PureXML.Schema.XSDParser.xsdNamespace { + if local == "anySimpleType" { return PureXML.Schema.SimpleType(base: .string, isAnySimpleType: true) } + if let builtin = PureXML.Schema.BuiltinType(rawValue: local) { return PureXML.Schema.SimpleType(base: builtin) } + if let item = listBuiltinItem(local) { return .list(item: PureXML.Schema.SimpleType(base: item), isBuiltinList: true) } + } + return context.simpleTypes[local] ?? PureXML.Schema.SimpleType(base: .string) + } + + /// The item type of a built-in list datatype (`IDREFS`, `ENTITIES`, + /// `NMTOKENS`), each a whitespace-separated list of its singular form. + static func listBuiltinItem(_ name: String) -> PureXML.Schema.BuiltinType? { + switch name { + case "IDREFS": .idref + case "ENTITIES": .entity + case "NMTOKENS": .nmtoken + default: nil + } + } + + static func applyFacets(_ restriction: XSDTree, into facets: inout PureXML.Schema.Facets) { + for facet in XSDNode.elementChildren(restriction) { + guard facet.name?.namespaceURI == PureXML.Schema.XSDParser.xsdNamespace else { continue } + let value = XSDNode.attribute(facet, "value") + applyStringFacet(XSDNode.localName(facet), value, into: &facets) + applyNumericFacet(XSDNode.localName(facet), value, into: &facets) + } + } + + static func listType(_ node: XSDTree, _ context: PureXML.Schema.XSDContext) -> PureXML.Schema.SimpleType { + let item: PureXML.Schema.SimpleType = if let itemType = XSDNode.attribute(node, "itemType") { + simpleTypeReference(itemType, context) + } else if let inline = XSDNode.firstChild(node, named: "simpleType") { + simpleType(inline, context) + } else { + PureXML.Schema.SimpleType(base: .string) + } + return .list(item: item) + } + + static func unionType(_ node: XSDTree, _ context: PureXML.Schema.XSDContext) -> PureXML.Schema.SimpleType { + var members: [PureXML.Schema.SimpleType] = [] + if let names = XSDNode.attribute(node, "memberTypes") { + members += names.split(whereSeparator: { $0.isWhitespace }).map { simpleTypeReference(String($0), context) } + } + members += XSDNode.children(node, named: "simpleType").map { simpleType($0, context) } + return .union(members) + } + + private static func applyStringFacet(_ name: String?, _ value: String?, into facets: inout PureXML.Schema.Facets) { + switch name { + case "pattern": if let value { facets.patterns.append(value) } + case "enumeration": if let value { facets.enumeration = (facets.enumeration ?? []) + [value] } + case "minInclusive": facets.minInclusive = value + case "maxInclusive": facets.maxInclusive = value + case "minExclusive": facets.minExclusive = value + case "maxExclusive": facets.maxExclusive = value + case "whiteSpace": facets.whiteSpace = whiteSpace(value) + default: break + } + } + + private static func applyNumericFacet(_ name: String?, _ value: String?, into facets: inout PureXML.Schema.Facets) { + let number = value.flatMap(Int.init) + switch name { + case "length": facets.length = number + case "minLength": facets.minLength = number + case "maxLength": facets.maxLength = number + case "totalDigits": facets.totalDigits = number + case "fractionDigits": facets.fractionDigits = number + default: break + } + } + + static func whiteSpace(_ value: String?) -> PureXML.Schema.WhiteSpace? { + switch value { + case "preserve": .preserve + case "replace": .replace + case "collapse": .collapse + default: nil + } + } +} diff --git a/Sources/Schema/XSDSimpleParser.swift b/Sources/Schema/XSDSimpleParser.swift index 93ca02f..ded4ba6 100644 --- a/Sources/Schema/XSDSimpleParser.swift +++ b/Sources/Schema/XSDSimpleParser.swift @@ -1,3 +1,9 @@ +private typealias XSDNode = PureXML.Schema.XSDNode +private typealias SimpleType = PureXML.Schema.SimpleType +private typealias XSDContext = PureXML.Schema.XSDContext +private typealias BuiltinType = PureXML.Schema.BuiltinType +private typealias Facets = PureXML.Schema.Facets + extension PureXML.Schema { /// Parses XSD simple types: atomic restrictions with the full facet set, and /// the `list` and `union` varieties. Kept beside ``XSDParser``, sharing its @@ -39,7 +45,7 @@ extension PureXML.Schema { for error in facetDefinitionErrors(restriction, base: baseType) + patternErrors(restriction) { context.diagnostics.report(error) } - return SimpleType(base: baseType.base, facets: facets, variety: baseType.variety) + return SimpleType(base: baseType.base, facets: facets, variety: baseType.variety, isBuiltinList: baseType.isBuiltinList) } /// Schema-validity findings for the `pattern` facets declared on one @@ -52,6 +58,7 @@ extension PureXML.Schema { static func patternErrors(_ restriction: XSDTree) -> [String] { var errors: [String] = [] for facet in XSDNode.elementChildren(restriction) where XSDNode.localName(facet) == "pattern" { + guard facet.name?.namespaceURI == PureXML.Schema.XSDParser.xsdNamespace else { continue } let value = XSDNode.attribute(facet, "value") ?? "" do { _ = try PureXML.Regex.Pattern(value) @@ -83,9 +90,11 @@ extension PureXML.Schema { /// the value-bound rules, both limited to the facets declared on this step /// so an inherited facet is never flagged here. static func facetDefinitionErrors(_ restriction: XSDTree, base: SimpleType) -> [String] { - countFacetErrors(restriction) + boundFacetErrors(restriction, base: base) - + whiteSpaceRestrictionErrors(restriction, base: base) - + facetRestrictionErrors(restriction, base: base) + var errors = countFacetErrors(restriction) + boundFacetErrors(restriction, base: base) + errors += whiteSpaceRestrictionErrors(restriction, base: base) + errors += facetRestrictionErrors(restriction, base: base) + errors += facetApplicabilityErrors(restriction, base: base) + return errors } /// The `length`, `minLength`, `maxLength`, `totalDigits`, and `fractionDigits` @@ -106,12 +115,44 @@ extension PureXML.Schema { if let baseTotalDigits = base.facets.totalDigits, let localTotalDigits = localFacets.totalDigits, localTotalDigits > baseTotalDigits { errors.append("facet 'totalDigits' (\(localTotalDigits)) cannot be greater than base 'totalDigits' (\(baseTotalDigits))") } - if let baseFractionDigits = base.facets.fractionDigits, let localFractionDigits = localFacets.fractionDigits, localFractionDigits > baseFractionDigits { + let baseFractionDigits = base.facets.fractionDigits ?? (base.base.derives(from: .integer) ? 0 : nil) + if let baseFractionDigits, let localFractionDigits = localFacets.fractionDigits, localFractionDigits > baseFractionDigits { errors.append("facet 'fractionDigits' (\(localFractionDigits)) cannot be greater than base 'fractionDigits' (\(baseFractionDigits))") } return errors } + private static func facetApplicabilityErrors(_ restriction: XSDTree, base: SimpleType) -> [String] { + guard case .atomic = base.variety else { return [] } + var errors: [String] = [] + let allowed = allowedFacets(for: base.base.primitive) + let facetNames: Set = [ + "length", "minLength", "maxLength", "pattern", "enumeration", "whiteSpace", + "maxInclusive", "maxExclusive", "minInclusive", "minExclusive", "totalDigits", "fractionDigits", + ] + for child in XSDNode.elementChildren(restriction) { + guard child.name?.namespaceURI == PureXML.Schema.XSDParser.xsdNamespace else { continue } + guard let name = XSDNode.localName(child), facetNames.contains(name) else { continue } + if !allowed.contains(name) { + errors.append("facet '\(name)' does not apply to base type '\(base.base.rawValue)'") + } + } + return errors + } + + private static func allowedFacets(for primitive: Primitive) -> Set { + switch primitive { + case .string, .anyURI, .hexBinary, .base64Binary, .name, .ncName, .nmtoken, .language, .qName, .notation: + ["length", "minLength", "maxLength", "pattern", "enumeration", "whiteSpace"] + case .boolean: + ["pattern", "whiteSpace"] + case .decimal, .integer: + ["totalDigits", "fractionDigits", "pattern", "whiteSpace", "enumeration", "maxInclusive", "maxExclusive", "minInclusive", "minExclusive"] + case .double, .float, .duration, .dateKind: + ["pattern", "whiteSpace", "enumeration", "maxInclusive", "maxExclusive", "minInclusive", "minExclusive"] + } + } + /// The `whiteSpace` facet may only strengthen, never relax, the base type's /// effective whiteSpace (XSD Part 2 §4.3.6, the facet's valid-restriction /// rule): the order is `preserve` < `replace` < `collapse`, so a base fixed @@ -129,6 +170,7 @@ extension PureXML.Schema { private static func declaredWhiteSpace(_ restriction: XSDTree) -> WhiteSpace? { for facet in XSDNode.elementChildren(restriction) where XSDNode.localName(facet) == "whiteSpace" { + guard facet.name?.namespaceURI == PureXML.Schema.XSDParser.xsdNamespace else { continue } return whiteSpace(XSDNode.attribute(facet, "value")) } return nil @@ -161,6 +203,7 @@ extension PureXML.Schema { var values: [String: String] = [:] // facet name -> canonical digit string let countFacets: Set = ["length", "minLength", "maxLength", "totalDigits", "fractionDigits"] for facet in XSDNode.elementChildren(restriction) { + guard facet.name?.namespaceURI == PureXML.Schema.XSDParser.xsdNamespace else { continue } guard let name = XSDNode.localName(facet), countFacets.contains(name) else { continue } let raw = XSDNode.attribute(facet, "value") guard let canonical = raw.flatMap(canonicalNonNegativeInteger) else { @@ -197,6 +240,7 @@ extension PureXML.Schema { var errors: [String] = [] var bounds: [String: String] = [:] for facet in XSDNode.elementChildren(restriction) { + guard facet.name?.namespaceURI == PureXML.Schema.XSDParser.xsdNamespace else { continue } guard let name = XSDNode.localName(facet) else { continue } let raw = XSDNode.attribute(facet, "value") ?? "" switch name { @@ -229,8 +273,23 @@ extension PureXML.Schema { /// `ordered` lookup returns nil), so only a defined order is checked. private static func boundOrderErrors(_ bounds: [String: String], base: SimpleType) -> [String] { guard let low = bounds["minInclusive"] ?? bounds["minExclusive"], - let high = bounds["maxInclusive"] ?? bounds["maxExclusive"], - let lowValue = base.base.primitive.ordered(low), + let high = bounds["maxInclusive"] ?? bounds["maxExclusive"] + else { return [] } + if case .duration = base.base.primitive { + guard let lowDuration = DurationValue(low), let highDuration = DurationValue(high) else { return [] } + let order = lowDuration.compare(to: highDuration) + if order == .greaterThan { + return ["lower bound '\(low)' exceeds upper bound '\(high)'"] + } + let exclusive = bounds["minExclusive"] != nil || bounds["maxExclusive"] != nil + if exclusive { + if order == .equal { + return ["bounds '\(low)' and '\(high)' describe an empty value space"] + } + } + return [] + } + guard let lowValue = base.base.primitive.ordered(low), let highValue = base.base.primitive.ordered(high) else { return [] } if lowValue > highValue { @@ -242,108 +301,5 @@ extension PureXML.Schema { } return [] } - - /// The canonical digit string of a lexical `nonNegativeInteger` (optional - /// leading `+`, ASCII digits, surrounding whitespace tolerated), with the - /// sign and leading zeros stripped (`"0"` for zero), or nil when the lexical - /// is not one (`-1`, ``, `a`, `1e2`). Independent of machine-integer range, - /// so a huge but well-formed value is canonicalized, not misreported as - /// malformed; the canonical form orders two values by length then lexically. - private static func canonicalNonNegativeInteger(_ lexical: String) -> String? { - var digits = Substring(lexical.trimmingXMLWhitespace()) - if digits.first == "+" { digits = digits.dropFirst() } - guard !digits.isEmpty, digits.allSatisfy({ $0.isASCII && $0.isNumber }) else { return nil } - let trimmed = digits.drop { $0 == "0" } - return trimmed.isEmpty ? "0" : String(trimmed) - } - - /// Whether canonical nonNegativeInteger `lhs` is greater than `rhs`: a longer - /// digit string is larger, and same-length strings compare lexicographically. - private static func greater(_ lhs: String, than rhs: String) -> Bool { - lhs.count != rhs.count ? lhs.count > rhs.count : lhs > rhs - } - - static func simpleTypeReference(_ typeName: String, _ context: XSDContext) -> SimpleType { - let local = XSDNode.stripPrefix(typeName) - if local == "anySimpleType" { return SimpleType(base: .string, isAnySimpleType: true) } - if let builtin = BuiltinType(rawValue: local) { return SimpleType(base: builtin) } - if let item = listBuiltinItem(local) { return .list(item: SimpleType(base: item)) } - return context.simpleTypes[local] ?? SimpleType(base: .string) - } - - /// The item type of a built-in list datatype (`IDREFS`, `ENTITIES`, - /// `NMTOKENS`), each a whitespace-separated list of its singular form. - static func listBuiltinItem(_ name: String) -> BuiltinType? { - switch name { - case "IDREFS": .idref - case "ENTITIES": .entity - case "NMTOKENS": .nmtoken - default: nil - } - } - - static func applyFacets(_ restriction: XSDTree, into facets: inout Facets) { - for facet in XSDNode.elementChildren(restriction) { - let value = XSDNode.attribute(facet, "value") - applyStringFacet(XSDNode.localName(facet), value, into: &facets) - applyNumericFacet(XSDNode.localName(facet), value, into: &facets) - } - } - - private static func listType(_ node: XSDTree, _ context: XSDContext) -> SimpleType { - let item: SimpleType = if let itemType = XSDNode.attribute(node, "itemType") { - simpleTypeReference(itemType, context) - } else if let inline = XSDNode.firstChild(node, named: "simpleType") { - simpleType(inline, context) - } else { - SimpleType(base: .string) - } - return .list(item: item) - } - - private static func unionType(_ node: XSDTree, _ context: XSDContext) -> SimpleType { - var members: [SimpleType] = [] - if let names = XSDNode.attribute(node, "memberTypes") { - members += names.split(whereSeparator: \.isWhitespace).map { simpleTypeReference(String($0), context) } - } - members += XSDNode.children(node, named: "simpleType").map { simpleType($0, context) } - return .union(members) - } - } -} - -extension PureXML.Schema.XSDSimpleParser { - private static func applyStringFacet(_ name: String?, _ value: String?, into facets: inout PureXML.Schema.Facets) { - switch name { - case "pattern": if let value { facets.patterns.append(value) } - case "enumeration": if let value { facets.enumeration = (facets.enumeration ?? []) + [value] } - case "minInclusive": facets.minInclusive = value - case "maxInclusive": facets.maxInclusive = value - case "minExclusive": facets.minExclusive = value - case "maxExclusive": facets.maxExclusive = value - case "whiteSpace": facets.whiteSpace = whiteSpace(value) - default: break - } - } - - private static func applyNumericFacet(_ name: String?, _ value: String?, into facets: inout PureXML.Schema.Facets) { - let number = value.flatMap(Int.init) - switch name { - case "length": facets.length = number - case "minLength": facets.minLength = number - case "maxLength": facets.maxLength = number - case "totalDigits": facets.totalDigits = number - case "fractionDigits": facets.fractionDigits = number - default: break - } - } - - private static func whiteSpace(_ value: String?) -> PureXML.Schema.WhiteSpace? { - switch value { - case "preserve": .preserve - case "replace": .replace - case "collapse": .collapse - default: nil - } } } diff --git a/Tests/SchemaFacetDefinitionTests.swift b/Tests/SchemaFacetDefinitionTests.swift index 9fbecaa..8c873ca 100644 --- a/Tests/SchemaFacetDefinitionTests.swift +++ b/Tests/SchemaFacetDefinitionTests.swift @@ -112,4 +112,84 @@ struct SchemaFacetDefinitionTests { #expect(String(describing: error).contains("length")) } } + + @Test("fractionDigits on integer types must be zero") + func test_fractionDigitsOnInteger() throws { + try compile(#""#, base: "xs:integer") + #expect(rejects(#""#, base: "xs:integer")) + #expect(rejects(#""#, base: "xs:int")) + } + + @Test("duration range bounds must be ordered") + func test_durationBoundOrdering() throws { + // minInclusive <= maxInclusive is valid + try compile(#""#, base: "xs:duration") + // minInclusive > maxInclusive is invalid + #expect(rejects(#""#, base: "xs:duration")) + #expect(rejects(#""#, base: "xs:duration")) + #expect(rejects(#""#, base: "xs:duration")) + } + + @Test("built-in list types require minLength of 1") + func test_listBuiltinMinLength() { + #expect(rejects(#""#, base: "xs:IDREFS")) + #expect(rejects(#""#, base: "xs:NMTOKENS")) + } + + @Test("facet applicability per base type") + func test_facetApplicabilityPerBase() { + #expect(rejects(#""#, base: "xs:string")) + #expect(rejects(#""#, base: "xs:boolean")) + #expect(rejects(#""#, base: "xs:decimal")) + } + + @Test("foreign elements inside restriction matching facet names are ignored") + func test_foreignElementsInRestriction() throws { + let xml = """ + + + + + + + + + + """ + _ = try PureXML.Schema.Document(xml) + } + + @Test("namespace prefix conflation: user-defined type named decimal is not conflated with built-in decimal") + func test_userTypeNamedDecimal() throws { + let xml = """ + + + + + + + + + + + """ + _ = try PureXML.Schema.Document(xml) + } + + @Test("incomparable duration bounds are valid") + func test_incomparableDurationBounds() throws { + let xml = """ + + + + + + + + + """ + _ = try PureXML.Schema.Document(xml) + } } diff --git a/Tests/XSTSSuiteTests.swift b/Tests/XSTSSuiteTests.swift index f7c5f42..175d426 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 = 1 - private let knownSchemaInvalidAccepted = 296 + private let knownSchemaInvalidAccepted = 266 private let knownInstanceValidRejected = 171 private let knownInstanceInvalidAccepted = 155 diff --git a/docs/schema-validity-burndown.md b/docs/schema-validity-burndown.md index e8c2e1e..1e7d7ec 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 -> 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 -> 296** | 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, top-level group/attributeGroup local-attribute checks, simpleType restriction structure and prefix binding checks, namespace-aware reference resolution checks, simpleType variety constraints on list itemType and union memberTypes, targetNamespace scope matching on local schema references, substitution group exclusions based on element final and schema finalDefault attributes, cross-container component-name and identity-constraint uniqueness checks, notation declarations and notation enumeration restrictions, xml:lang and xml:space on documentation/appinfo elements, duplicate schema container validation across separate files with identical content, schema element order, and import constraints validation landed). | +| **invalid-schemas-accepted** | **2461 -> 266** | 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, top-level group/attributeGroup local-attribute checks, simpleType restriction structure and prefix binding checks, namespace-aware reference resolution checks, simpleType variety constraints on list itemType and union memberTypes, targetNamespace scope matching on local schema references, substitution group exclusions based on element final and schema finalDefault attributes, cross-container component-name and identity-constraint uniqueness checks, notation declarations and notation enumeration restrictions, xml:lang and xml:space on documentation/appinfo elements, duplicate schema container validation across separate files with identical content, schema element order, import constraints validation, facet applicability per base type, fractionDigits constraints on integer types, ordered duration range bounds, and built-in list non-emptiness constraints landed). | | 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) |