From 4a966260f3b9042e494d3f868c1a3dc6e2a08659 Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Mon, 8 Jun 2026 08:46:24 +0200 Subject: [PATCH] feat(xsd): add include/import/redefine, substitution groups, and xsi:type Compose schemas across documents and resolve types at the instance: - xs:include, xs:import, and xs:redefine pull a transitive closure of schema documents through an injected loader (resolved by schemaLocation), base schemas first so the including schema wins; a redefine's nested definitions override the schema it includes. - substitution groups: an xs:element ref to a head also admits every element that substitutes for it, expanded at parse time into a choice over the head and its transitive members. - xsi:type overrides an element's declared type with the named type at the instance; XML Schema instance attributes are exempt from attribute checks. The schema parser splits across XSDContext (shared tree helpers, document collection, parsing context), XSDSimpleParser (simple types and facets), and XSDParser (elements, complex types, model groups) to keep each within bounds. Closes #66 --- Sources/Schema/ComplexValidator.swift | 29 +++- Sources/Schema/SchemaDocument.swift | 10 +- Sources/Schema/XSDContext.swift | 115 ++++++++++++++ Sources/Schema/XSDParser.swift | 217 +++++--------------------- Sources/Schema/XSDSimpleParser.swift | 99 ++++++++++++ Tests/XSDImportTests.swift | 93 +++++++++++ 6 files changed, 383 insertions(+), 180 deletions(-) create mode 100644 Sources/Schema/XSDContext.swift create mode 100644 Sources/Schema/XSDSimpleParser.swift create mode 100644 Tests/XSDImportTests.swift diff --git a/Sources/Schema/ComplexValidator.swift b/Sources/Schema/ComplexValidator.swift index 5abc914..3cc6fa1 100644 --- a/Sources/Schema/ComplexValidator.swift +++ b/Sources/Schema/ComplexValidator.swift @@ -39,7 +39,7 @@ public extension PureXML.Schema { _ type: ComplexType, into issues: inout [PureXML.Validation.Issue], ) { - let present = element.attributes.filter { !Self.isNamespaceDeclaration($0) } + let present = element.attributes.filter { !Self.isNamespaceDeclaration($0) && !Self.isSchemaInstanceAttribute($0) } for use in type.attributes { let match = present.first { $0.name.localName == use.name.localName } if let match { @@ -126,6 +126,13 @@ public extension PureXML.Schema { against declared: ElementType, into issues: inout [PureXML.Validation.Issue], ) { + // An instance `xsi:type` overrides the declared type, provided the + // named type exists in the schema. Resolve to the type itself rather + // than a reference so re-entry does not re-read the same xsi:type. + var declared = declared + if let overriding = Self.xsiTypeName(child), let resolved = types[overriding] { + declared = resolved + } switch declared { case let .simple(simple): if !child.children.compactMap(\.element).isEmpty { @@ -206,5 +213,25 @@ public extension PureXML.Schema { private static func isNamespaceDeclaration(_ attribute: PureXML.Model.Attribute) -> Bool { attribute.name.prefix == "xmlns" || (attribute.name.prefix == nil && attribute.name.localName == "xmlns") } + + /// Whether an attribute belongs to the XML Schema instance namespace + /// (`xsi:type`, `xsi:nil`, and the schema-location hints), which are + /// processing directives rather than declared attributes. + private static func isSchemaInstanceAttribute(_ attribute: PureXML.Model.Attribute) -> Bool { + attribute.name.namespaceURI == "http://www.w3.org/2001/XMLSchema-instance" || attribute.name.prefix == "xsi" + } + + /// The local name of an element's `xsi:type` attribute value, or nil when + /// it carries none. Recognizes the attribute by the XML Schema instance + /// namespace or, failing namespace resolution, the conventional `xsi` + /// prefix. + private static func xsiTypeName(_ element: PureXML.Model.Element) -> String? { + let schemaInstance = "http://www.w3.org/2001/XMLSchema-instance" + let match = element.attributes.first { attribute in + attribute.name.localName == "type" + && (attribute.name.namespaceURI == schemaInstance || attribute.name.prefix == "xsi") + } + return match.map { $0.value.split(separator: ":").last.map(String.init) ?? $0.value } + } } } diff --git a/Sources/Schema/SchemaDocument.swift b/Sources/Schema/SchemaDocument.swift index dd3274e..64763b2 100644 --- a/Sources/Schema/SchemaDocument.swift +++ b/Sources/Schema/SchemaDocument.swift @@ -16,9 +16,13 @@ public extension PureXML.Schema { private let elements: [String: ElementType] private let types: [String: ElementType] - /// Compiles a schema document. - public init(_ xsd: String) throws { - (elements, types) = try XSDParser.parse(xsd) + /// Compiles a schema document. `schemaLoader` resolves the + /// `schemaLocation` of `xs:include`, `xs:import`, and `xs:redefine` to + /// schema source; it returns nil (the default) when external schemas are + /// not available, which keeps compilation from reaching the filesystem or + /// network by default. + public init(_ xsd: String, schemaLoader: @escaping (String) -> String? = { _ in nil }) throws { + (elements, types) = try XSDParser.parse(xsd, loader: schemaLoader) } /// Validates an instance document against the schema, returning one issue diff --git a/Sources/Schema/XSDContext.swift b/Sources/Schema/XSDContext.swift new file mode 100644 index 0000000..6160f95 --- /dev/null +++ b/Sources/Schema/XSDContext.swift @@ -0,0 +1,115 @@ +/// A schema-document tree node. +typealias XSDTree = PureXML.Model.TreeNode + +extension PureXML.Schema { + /// Tree-access helpers and document collection shared by the schema parser + /// across its files. + enum XSDNode { + static func localName(_ node: XSDTree) -> String? { + node.name?.localName + } + + static func attribute(_ node: XSDTree, _ name: String) -> String? { + node.attributes.first { $0.name.localName == name }?.value + } + + static func elementChildren(_ node: XSDTree) -> [XSDTree] { + node.children.filter { $0.kind == .element } + } + + static func children(_ node: XSDTree, named name: String) -> [XSDTree] { + elementChildren(node).filter { localName($0) == name } + } + + static func firstChild(_ node: XSDTree, named name: String) -> XSDTree? { + children(node, named: name).first + } + + static func stripPrefix(_ qualified: String) -> String { + qualified.split(separator: ":").last.map(String.init) ?? qualified + } + + static func occurrence(_ node: XSDTree) -> (min: Int, max: Int?) { + let minimum = attribute(node, "minOccurs").flatMap(Int.init) ?? 1 + let maximumText = attribute(node, "maxOccurs") + let maximum: Int? = maximumText == "unbounded" ? nil : (maximumText.flatMap(Int.init) ?? 1) + return (minimum, maximum) + } + + /// Collects the schema's own element and a transitive closure of the + /// schemas it pulls in through `include`, `import`, and `redefine` + /// (resolved through `loader` by `schemaLocation`), base schemas first so + /// the including schema's definitions take precedence. A `redefine` + /// element is itself returned as a container so its nested redefinitions + /// override the schema it includes. + static func collectContainers( + _ schema: XSDTree, + _ loader: (String) -> String?, + _ visited: inout Set, + ) -> [XSDTree] { + var containers: [XSDTree] = [] + for child in elementChildren(schema) { + let kind = localName(child) + guard kind == "include" || kind == "import" || kind == "redefine", + let location = attribute(child, "schemaLocation"), !visited.contains(location) + else { + continue + } + visited.insert(location) + let sub = loader(location).flatMap { try? PureXML.parseTree($0) } + .flatMap { root in elementChildren(root).first { localName($0) == "schema" } } + if let sub { containers += collectContainers(sub, loader, &visited) } + if kind == "redefine" { containers.append(child) } + } + containers.append(schema) + return containers + } + + /// The transitive substitution-group membership across all definition + /// containers: each head element maps to every element that may substitute + /// for it, directly or through a chain of heads. + static func substitutionMembers(_ containers: [XSDTree]) -> [String: [String]] { + var direct: [String: [String]] = [:] + for container in containers { + for element in children(container, named: "element") { + guard let name = attribute(element, "name"), let head = attribute(element, "substitutionGroup") else { + continue + } + direct[stripPrefix(head), default: []].append(name) + } + } + var closure: [String: [String]] = [:] + for head in direct.keys { + var members: [String] = [] + var stack = direct[head] ?? [] + var seen: Set = [] + while let member = stack.popLast() { + guard seen.insert(member).inserted else { continue } + members.append(member) + stack += direct[member] ?? [] + } + closure[head] = members + } + return closure + } + } + + /// The parsing context: the named simple types resolved so far, plus the + /// definition nodes for named attribute groups and model groups (so their + /// refs can be expanded), and a guard against cyclic group references. + struct XSDContext { + var simpleTypes: [String: SimpleType] + var attributeGroups: [String: XSDTree] + var groups: [String: XSDTree] + /// Each substitution-group head maps to its transitive member element + /// names, so an `xs:element ref` to a head also admits its members. + var substitutions: [String: [String]] = [:] + var visitingGroups: Set = [] + + func visiting(_ group: String) -> XSDContext { + var copy = self + copy.visitingGroups.insert(group) + return copy + } + } +} diff --git a/Sources/Schema/XSDParser.swift b/Sources/Schema/XSDParser.swift index b6cc5e5..f603b25 100644 --- a/Sources/Schema/XSDParser.swift +++ b/Sources/Schema/XSDParser.swift @@ -1,56 +1,3 @@ -private typealias Tree = PureXML.Model.TreeNode - -/// Tree-access helpers shared by the schema parser. File-scope and private. -private enum XSDNode { - static func localName(_ node: Tree) -> String? { - node.name?.localName - } - - static func attribute(_ node: Tree, _ name: String) -> String? { - node.attributes.first { $0.name.localName == name }?.value - } - - static func elementChildren(_ node: Tree) -> [Tree] { - node.children.filter { $0.kind == .element } - } - - static func children(_ node: Tree, named name: String) -> [Tree] { - elementChildren(node).filter { localName($0) == name } - } - - static func firstChild(_ node: Tree, named name: String) -> Tree? { - children(node, named: name).first - } - - static func stripPrefix(_ qualified: String) -> String { - qualified.split(separator: ":").last.map(String.init) ?? qualified - } - - static func occurrence(_ node: Tree) -> (min: Int, max: Int?) { - let minimum = attribute(node, "minOccurs").flatMap(Int.init) ?? 1 - let maximumText = attribute(node, "maxOccurs") - let maximum: Int? = maximumText == "unbounded" ? nil : (maximumText.flatMap(Int.init) ?? 1) - return (minimum, maximum) - } -} - -/// The parsing context: the named simple types resolved so far, plus the -/// definition nodes for named attribute groups and model groups (so their refs -/// can be expanded), and a guard against cyclic group references. File-scope and -/// private. -private struct Context { - var simpleTypes: [String: PureXML.Schema.SimpleType] - var attributeGroups: [String: Tree] - var groups: [String: Tree] - var visitingGroups: Set = [] - - func visiting(_ group: String) -> Context { - var copy = self - copy.visitingGroups.insert(group) - return copy - } -} - extension PureXML.Schema { /// Parses an XSD schema document into its global element declarations and its /// named-type table. Matches the schema vocabulary by local name, so the XML @@ -62,21 +9,25 @@ extension PureXML.Schema { enum XSDParser { static func parse( _ xsd: String, + loader: (String) -> String? = { _ in nil }, ) throws -> (elements: [String: ElementType], types: [String: ElementType]) { let root = try PureXML.parseTree(xsd) guard let schema = XSDNode.elementChildren(root).first(where: { XSDNode.localName($0) == "schema" }) else { throw PureXML.Schema.SchemaError.notASchema } - var context = Context( + var visited: Set = [] + let containers = XSDNode.collectContainers(schema, loader, &visited) + var context = XSDContext( simpleTypes: [:], - attributeGroups: indexByName(XSDNode.children(schema, named: "attributeGroup")), - groups: indexByName(XSDNode.children(schema, named: "group")), + attributeGroups: indexByName(allChildren(containers, named: "attributeGroup")), + groups: indexByName(allChildren(containers, named: "group")), + substitutions: XSDNode.substitutionMembers(containers), ) // Named simple types may restrict or list one another regardless of // document order, so resolve them over repeated passes: each pass sees // the types resolved by the previous one. A chain of length n settles // in at most n passes. - let simpleNodes = XSDNode.children(schema, named: "simpleType").filter { XSDNode.attribute($0, "name") != nil } + let simpleNodes = allChildren(containers, named: "simpleType").filter { XSDNode.attribute($0, "name") != nil } for _ in simpleNodes.indices { for node in simpleNodes { if let name = XSDNode.attribute(node, "name") { @@ -85,13 +36,13 @@ extension PureXML.Schema { } } var types: [String: ElementType] = context.simpleTypes.mapValues(ElementType.simple) - for node in XSDNode.children(schema, named: "complexType") { + for node in allChildren(containers, named: "complexType") { if let name = XSDNode.attribute(node, "name") { types[name] = .complex(complexType(node, context)) } } var elements: [String: ElementType] = [:] - for node in XSDNode.children(schema, named: "element") { + for node in allChildren(containers, named: "element") { if let name = XSDNode.attribute(node, "name") { let type = elementType(node, context) elements[name] = type @@ -105,12 +56,16 @@ extension PureXML.Schema { return (elements, types) } + private static func allChildren(_ containers: [XSDTree], named name: String) -> [XSDTree] { + containers.flatMap { XSDNode.children($0, named: name) } + } + static func elementKey(_ name: String) -> String { "element:\(name)" } - private static func indexByName(_ nodes: [Tree]) -> [String: Tree] { - var index: [String: Tree] = [:] + 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 } } @@ -119,7 +74,7 @@ extension PureXML.Schema { // MARK: Element and type references - private static func elementType(_ node: Tree, _ context: Context) -> ElementType { + private static func elementType(_ node: XSDTree, _ context: XSDContext) -> ElementType { if let typeName = XSDNode.attribute(node, "type") { return typeReference(typeName) } @@ -149,7 +104,7 @@ extension PureXML.Schema { // MARK: Complex types - private static func complexType(_ node: Tree, _ context: Context) -> ComplexType { + private static func complexType(_ node: XSDTree, _ context: XSDContext) -> ComplexType { let mixed = XSDNode.attribute(node, "mixed") == "true" var attributes = attributeUses(under: node, context) if let simpleContent = XSDNode.firstChild(node, named: "simpleContent") { @@ -165,11 +120,11 @@ extension PureXML.Schema { return ComplexType(attributes: attributes, content: mixed ? .mixed(particle) : .elementOnly(particle)) } - private static func derivation(_ node: Tree) -> Tree? { + private static func derivation(_ node: XSDTree) -> XSDTree? { XSDNode.firstChild(node, named: "restriction") ?? XSDNode.firstChild(node, named: "extension") } - private static func simpleContentType(_ node: Tree, _ context: Context) -> SimpleType { + 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 @@ -180,7 +135,7 @@ extension PureXML.Schema { // MARK: Attribute uses and groups - private static func attributeUses(under node: Tree, _ context: Context, visited: Set = []) -> [AttributeUse] { + private static func attributeUses(under node: XSDTree, _ context: XSDContext, visited: Set = []) -> [AttributeUse] { var uses: [AttributeUse] = [] for child in XSDNode.elementChildren(node) { switch XSDNode.localName(child) { @@ -198,7 +153,7 @@ extension PureXML.Schema { return uses } - private static func attributeUse(_ node: Tree, _ context: Context) -> AttributeUse? { + private static func attributeUse(_ node: XSDTree, _ context: XSDContext) -> AttributeUse? { guard let name = XSDNode.attribute(node, "name") else { return nil } let required = XSDNode.attribute(node, "use") == "required" let type: SimpleType = if let typeName = XSDNode.attribute(node, "type") { @@ -213,7 +168,7 @@ extension PureXML.Schema { // MARK: Model groups - private static func modelGroup(in node: Tree, _ context: Context) -> Particle? { + private static func modelGroup(in node: XSDTree, _ context: XSDContext) -> Particle? { for (name, compositor) in [("sequence", Compositor.sequence), ("choice", .choice), ("all", .all)] { if let group = XSDNode.firstChild(node, named: name) { return groupParticle(group, compositor, context) @@ -226,9 +181,9 @@ extension PureXML.Schema { } private static func groupParticle( - _ node: Tree, + _ node: XSDTree, _ compositor: Compositor, - _ context: Context, + _ context: XSDContext, ) -> Particle { var particles: [Particle] = [] for child in XSDNode.elementChildren(node) { @@ -242,7 +197,7 @@ extension PureXML.Schema { ) } - private static func particle(_ node: Tree, _ context: Context) -> Particle? { + private static func particle(_ node: XSDTree, _ context: XSDContext) -> Particle? { let (minimum, maximum) = XSDNode.occurrence(node) switch XSDNode.localName(node) { case "element": @@ -262,14 +217,18 @@ extension PureXML.Schema { } } - private static func elementParticle(_ node: Tree, _ minimum: Int, _ maximum: Int?, _ context: Context) -> Particle { + private static func elementParticle(_ node: XSDTree, _ minimum: Int, _ maximum: Int?, _ context: XSDContext) -> Particle { if let ref = XSDNode.attribute(node, "ref") { let name = XSDNode.stripPrefix(ref) - return Particle( - minOccurs: minimum, - maxOccurs: maximum, - term: .element(name: PureXML.Model.QualifiedName(name), type: .typeReference(elementKey(name))), - ) + let alternatives = [name] + (context.substitutions[name] ?? []) + if alternatives.count == 1 { + return Particle(minOccurs: minimum, maxOccurs: maximum, term: elementReferenceTerm(name)) + } + // The reference admits its substitution-group members, so expand it + // to a choice over the head and every member, each carrying its own + // declared type. + let members = alternatives.map { Particle(term: elementReferenceTerm($0)) } + return Particle(minOccurs: minimum, maxOccurs: maximum, term: .group(Group(compositor: .choice, particles: members))) } let name = XSDNode.attribute(node, "name") ?? "" return Particle( @@ -279,7 +238,11 @@ extension PureXML.Schema { ) } - private static func groupReferenceParticle(_ node: Tree, _ minimum: Int, _ maximum: Int?, _ context: Context) -> Particle? { + private static func elementReferenceTerm(_ name: String) -> Term { + .element(name: PureXML.Model.QualifiedName(name), type: .typeReference(elementKey(name))) + } + + private static func groupReferenceParticle(_ node: XSDTree, _ minimum: Int, _ maximum: Int?, _ context: XSDContext) -> Particle? { guard let ref = XSDNode.attribute(node, "ref") else { return nil } let name = XSDNode.stripPrefix(ref) guard !context.visitingGroups.contains(name), let definition = context.groups[name], @@ -290,102 +253,4 @@ extension PureXML.Schema { return Particle(minOccurs: minimum, maxOccurs: maximum, term: inner.term) } } - - /// Parses XSD simple types: atomic restrictions with the full facet set, and - /// the `list` and `union` varieties. Kept beside ``XSDParser`` so the two - /// share the file-scope tree helpers and parsing context. - enum XSDSimpleParser { - fileprivate static func simpleType(_ node: Tree, _ context: Context) -> SimpleType { - if let list = XSDNode.firstChild(node, named: "list") { - return listType(list, context) - } - if let union = XSDNode.firstChild(node, named: "union") { - return unionType(union, context) - } - guard let restriction = XSDNode.firstChild(node, named: "restriction") else { - return SimpleType(base: .string) - } - let baseName = XSDNode.stripPrefix(XSDNode.attribute(restriction, "base") ?? "string") - var base = BuiltinType.string - var facets = Facets() - var variety = Variety.atomic - if let builtin = BuiltinType(rawValue: baseName) { - base = builtin - } else if let parent = context.simpleTypes[baseName] { - base = parent.base - facets = parent.facets - variety = parent.variety - } - applyFacets(restriction, into: &facets) - return SimpleType(base: base, facets: facets, variety: variety) - } - - fileprivate static func simpleTypeReference(_ typeName: String, _ context: Context) -> SimpleType { - let local = XSDNode.stripPrefix(typeName) - if let builtin = BuiltinType(rawValue: local) { return SimpleType(base: builtin) } - return context.simpleTypes[local] ?? SimpleType(base: .string) - } - - fileprivate static func applyFacets(_ restriction: Tree, 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: Tree, _ context: Context) -> 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: Tree, _ context: Context) -> 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) - } - - private static func applyStringFacet(_ name: String?, _ value: String?, into facets: inout 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 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?) -> 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 new file mode 100644 index 0000000..c2997a0 --- /dev/null +++ b/Sources/Schema/XSDSimpleParser.swift @@ -0,0 +1,99 @@ +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 + /// module-scope tree helpers and parsing context. + enum XSDSimpleParser { + static func simpleType(_ node: XSDTree, _ context: XSDContext) -> SimpleType { + if let list = XSDNode.firstChild(node, named: "list") { + return listType(list, context) + } + if let union = XSDNode.firstChild(node, named: "union") { + return unionType(union, context) + } + guard let restriction = XSDNode.firstChild(node, named: "restriction") else { + return SimpleType(base: .string) + } + let baseName = XSDNode.stripPrefix(XSDNode.attribute(restriction, "base") ?? "string") + var base = BuiltinType.string + var facets = Facets() + var variety = Variety.atomic + if let builtin = BuiltinType(rawValue: baseName) { + base = builtin + } else if let parent = context.simpleTypes[baseName] { + base = parent.base + facets = parent.facets + variety = parent.variety + } + applyFacets(restriction, into: &facets) + return SimpleType(base: base, facets: facets, variety: variety) + } + + static func simpleTypeReference(_ typeName: String, _ context: XSDContext) -> SimpleType { + let local = XSDNode.stripPrefix(typeName) + if let builtin = BuiltinType(rawValue: local) { return SimpleType(base: builtin) } + return context.simpleTypes[local] ?? SimpleType(base: .string) + } + + 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) + } + + private static func applyStringFacet(_ name: String?, _ value: String?, into facets: inout 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 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?) -> WhiteSpace? { + switch value { + case "preserve": .preserve + case "replace": .replace + case "collapse": .collapse + default: nil + } + } + } +} diff --git a/Tests/XSDImportTests.swift b/Tests/XSDImportTests.swift new file mode 100644 index 0000000..855151a --- /dev/null +++ b/Tests/XSDImportTests.swift @@ -0,0 +1,93 @@ +@testable import PureXML +import Testing + +@Suite("XSD includes, substitution groups, xsi:type") +struct XSDImportTests { + private func validate( + _ xsd: String, + _ xml: String, + loader: @escaping (String) -> String? = { _ in nil }, + ) throws -> [PureXML.Validation.Issue] { + try PureXML.Schema.Document(xsd, schemaLoader: loader).validate(xml) + } + + @Test("xs:include pulls in another schema's named type") + func test_include() throws { + let library = """ + + + + + + """ + let main = """ + + + + + """ + let loader: (String) -> String? = { $0 == "lib.xsd" ? library : nil } + #expect(try validate(main, "ABC", loader: loader).isEmpty) + #expect(try !validate(main, "abc", loader: loader).isEmpty) + } + + @Test("xs:redefine overrides an included type") + func test_redefine() throws { + let base = """ + + + + + + """ + let main = """ + + + + + + + + + """ + let loader: (String) -> String? = { $0 == "base.xsd" ? base : nil } + #expect(try validate(main, "5", loader: loader).isEmpty) + #expect(try !validate(main, "50", loader: loader).isEmpty) + } + + @Test("A substitution-group member is accepted where the head is referenced") + func test_substitutionGroup() throws { + let xsd = """ + + + + + + + + + + + + """ + #expect(try validate(xsd, "ab").isEmpty) + #expect(try !validate(xsd, "b").isEmpty) + } + + @Test("xsi:type overrides the declared type at the instance") + func test_xsiType() throws { + let xsd = """ + + + + + + + + """ + let valid = "3" + let invalid = "x" + #expect(try validate(xsd, valid).isEmpty) + #expect(try !validate(xsd, invalid).isEmpty) + } +}