feat(schema): XSD complex types and particles

Add ComplexValidator validating an element against a ComplexType: attribute
uses (required, typed, unknown-attribute rejection) and the content model
(empty, simpleContent, elementOnly, mixed). Particles compile to a Thompson
NFA over element names honoring minOccurs/maxOccurs with sequence and choice
compositors; all groups are validated order-independently by counting. Child
elements are validated recursively against their declared types.

Closes #9
This commit is contained in:
Mihaela Mihaljevic 2026-06-08 06:33:51 +02:00
parent 56e3315d6e
commit 135f9c5cb8
5 changed files with 566 additions and 0 deletions

View File

@ -9,6 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- XSD complex types and particles (toward #2 schema validation).
`PureXML.Schema.ComplexValidator` validates an element against a
`ComplexType`: its attribute uses (required and typed, with unknown-attribute
rejection), and its content model. Content is `empty`, `simpleContent` (text
validated against a simple type), `elementOnly`, or `mixed`. Particles compile
to a Thompson NFA over element names honoring `minOccurs`/`maxOccurs`, with
`sequence`/`choice` compositors; `all` groups are validated order-independently
by counting. Child elements are validated recursively against their declared
types (the XSD Element-Declarations-Consistent rule makes the name-to-type map
well defined).
- XSD simple-type datatype library (toward #2 schema validation). The new
`PureXML.Schema` namespace validates a lexical value against the XSD Part 2
built-in datatypes (`string`, `boolean`, `decimal`, the bounded integer family,

View File

@ -0,0 +1,99 @@
public extension PureXML.Schema {
/// A model-group compositor.
enum Compositor: Sendable {
/// An ordered list (`xs:sequence`).
case sequence
/// One of the alternatives (`xs:choice`).
case choice
/// Each member once, in any order (`xs:all`).
case all
}
/// An element wildcard (`xs:any`). The minimal namespace constraint: any
/// element matches.
struct Wildcard: Sendable {
public init() {}
}
/// The term of a particle: an element declaration, a nested model group, or a
/// wildcard.
indirect enum Term: Sendable {
case element(name: PureXML.Model.QualifiedName, type: ElementType?)
case group(Group)
case wildcard(Wildcard)
}
/// A particle: a term with an occurrence range. `maxOccurs` nil means
/// unbounded.
struct Particle: Sendable {
public var minOccurs: Int
public var maxOccurs: Int?
public var term: Term
public init(minOccurs: Int = 1, maxOccurs: Int? = 1, term: Term) {
self.minOccurs = minOccurs
self.maxOccurs = maxOccurs
self.term = term
}
}
/// A model group: a compositor over particles.
struct Group: Sendable {
public var compositor: Compositor
public var particles: [Particle]
public init(compositor: Compositor, particles: [Particle]) {
self.compositor = compositor
self.particles = particles
}
}
/// The declared type of an element: a simple type (text only) or a complex one.
indirect enum ElementType: Sendable {
case simple(SimpleType)
case complex(ComplexType)
}
/// An attribute use on a complex type.
struct AttributeUse: Sendable {
public var name: PureXML.Model.QualifiedName
public var type: SimpleType
public var required: Bool
public init(name: PureXML.Model.QualifiedName, type: SimpleType, required: Bool = false) {
self.name = name
self.type = type
self.required = required
}
}
/// The content of a complex type.
indirect enum ContentType: Sendable {
/// No child elements or non-whitespace text.
case empty
/// Character data validated against a simple type, no child elements.
case simpleContent(SimpleType)
/// Child elements matching the particle; no non-whitespace text.
case elementOnly(Particle)
/// Child elements matching the particle, with text allowed between them.
case mixed(Particle)
}
/// A complex type: its attribute uses, whether unknown attributes are allowed,
/// and its content model.
struct ComplexType: Sendable {
public var attributes: [AttributeUse]
public var allowsOtherAttributes: Bool
public var content: ContentType
public init(
attributes: [AttributeUse] = [],
allowsOtherAttributes: Bool = false,
content: ContentType = .empty,
) {
self.attributes = attributes
self.allowsOtherAttributes = allowsOtherAttributes
self.content = content
}
}
}

View File

@ -0,0 +1,180 @@
public extension PureXML.Schema {
/// Validates an element against a ``ComplexType``: its attribute uses, its
/// content model, and, recursively, each child element against the type
/// declared for its name.
struct ComplexValidator {
public init() {}
/// Validates `element` against `type`, returning one issue per violation.
public func validate(
_ element: PureXML.Model.Element,
against type: ComplexType,
) -> [PureXML.Validation.Issue] {
var issues: [PureXML.Validation.Issue] = []
validateAttributes(element, type, into: &issues)
validateContent(element, type.content, into: &issues)
return issues
}
// MARK: Attributes
private func validateAttributes(
_ element: PureXML.Model.Element,
_ type: ComplexType,
into issues: inout [PureXML.Validation.Issue],
) {
let present = element.attributes.filter { !Self.isNamespaceDeclaration($0) }
for use in type.attributes {
let match = present.first { $0.name.localName == use.name.localName }
if let match {
if let error = use.type.validate(match.value) {
issues.append(.init(severity: .error, message: "attribute '\(use.name.localName)': \(error)"))
}
} else if use.required {
issues.append(.init(severity: .error, message: "missing required attribute '\(use.name.localName)'"))
}
}
guard !type.allowsOtherAttributes else { return }
for attribute in present where !type.attributes.contains(where: { $0.name.localName == attribute.name.localName }) {
issues.append(.init(severity: .error, message: "undeclared attribute '\(attribute.name.localName)'"))
}
}
// MARK: Content
private func validateContent(
_ element: PureXML.Model.Element,
_ content: ContentType,
into issues: inout [PureXML.Validation.Issue],
) {
let children = element.children.compactMap(\.element)
switch content {
case .empty:
if !children.isEmpty { issues.append(.init(severity: .error, message: "element must be empty")) }
rejectText(element, allowed: false, into: &issues)
case let .simpleContent(type):
if !children.isEmpty { issues.append(.init(severity: .error, message: "element must not have children")) }
if let error = type.validate(Self.textContent(element)) {
issues.append(.init(severity: .error, message: "content: \(error)"))
}
case let .elementOnly(particle):
rejectText(element, allowed: false, into: &issues)
validateParticle(particle, children: children, into: &issues)
case let .mixed(particle):
validateParticle(particle, children: children, into: &issues)
}
}
private func rejectText(
_ element: PureXML.Model.Element,
allowed: Bool,
into issues: inout [PureXML.Validation.Issue],
) {
guard !allowed, !Self.textContent(element).isEmpty else { return }
issues.append(.init(severity: .error, message: "element must not contain text"))
}
// MARK: Particles
private func validateParticle(
_ particle: Particle,
children: [PureXML.Model.Element],
into issues: inout [PureXML.Validation.Issue],
) {
let names = children.map(\.name)
let structureValid: Bool = if case let .group(group) = particle.term, group.compositor == .all {
Self.matchesAll(group, names: names)
} else {
ContentNFABuilder.build(particle).matchesWhole(names)
}
if !structureValid {
issues.append(.init(severity: .error, message: "content does not match the content model"))
return
}
validateChildren(children, types: Self.elementTypes(in: particle.term), into: &issues)
}
private func validateChildren(
_ children: [PureXML.Model.Element],
types: [String: ElementType],
into issues: inout [PureXML.Validation.Issue],
) {
for child in children {
guard let type = types[Self.key(child.name)] else { continue }
switch type {
case let .simple(simple):
if !child.children.compactMap(\.element).isEmpty {
issues.append(.init(severity: .error, message: "'\(child.name.localName)' must not have children"))
}
if let error = simple.validate(Self.textContent(child)) {
issues.append(.init(severity: .error, message: "'\(child.name.localName)': \(error)"))
}
case let .complex(complex):
issues.append(contentsOf: validate(child, against: complex))
}
}
}
// MARK: Helpers
/// Validates an `all` group order-independently: every child matches a
/// member within its occurrence bounds, and each member meets its minimum.
private static func matchesAll(_ group: Group, names: [PureXML.Model.QualifiedName]) -> Bool {
var counts = [Int](repeating: 0, count: group.particles.count)
for name in names {
guard let index = group.particles.indices.first(where: { position in
let member = group.particles[position]
let room = member.maxOccurs.map { counts[position] < $0 } ?? true
return room && label(of: member.term).matches(name)
}) else { return false }
counts[index] += 1
}
for (index, member) in group.particles.enumerated() where counts[index] < member.minOccurs {
return false
}
return true
}
private static func label(of term: Term) -> TermLabel {
if case let .element(name, _) = term { return .name(name) }
return .any
}
private static func elementTypes(in term: Term) -> [String: ElementType] {
var result: [String: ElementType] = [:]
collectTypes(term, into: &result)
return result
}
private static func collectTypes(_ term: Term, into result: inout [String: ElementType]) {
switch term {
case let .element(name, type):
if let type { result[key(name)] = type }
case let .group(group):
for member in group.particles {
collectTypes(member.term, into: &result)
}
case .wildcard:
break
}
}
private static func key(_ name: PureXML.Model.QualifiedName) -> String {
"{\(name.namespaceURI ?? "")}\(name.localName)"
}
private static func textContent(_ element: PureXML.Model.Element) -> String {
let text = element.children.reduce(into: "") { result, child in
switch child {
case let .text(value), let .cdata(value): result += value
default: break
}
}
return text.trimmingXMLWhitespace()
}
private static func isNamespaceDeclaration(_ attribute: PureXML.Model.Attribute) -> Bool {
attribute.name.prefix == "xmlns" || (attribute.name.prefix == nil && attribute.name.localName == "xmlns")
}
}
}

View File

@ -0,0 +1,164 @@
extension PureXML.Schema {
/// A transition label in the content-model automaton: a specific expanded
/// element name, or a wildcard.
enum TermLabel: Sendable {
case name(PureXML.Model.QualifiedName)
case any
func matches(_ actual: PureXML.Model.QualifiedName) -> Bool {
switch self {
case .any: true
case let .name(declared): declared.localName == actual.localName
&& declared.namespaceURI == actual.namespaceURI
}
}
}
/// One state of the content-model automaton.
struct ContentState: Sendable {
var epsilon: [Int] = []
var label: TermLabel?
var target: Int?
}
/// A Thompson NFA over element names compiled from a ``Particle``. `all` groups
/// are validated separately by ``ContentMatcher`` and are not represented here.
struct ContentNFA: Sendable {
var states: [ContentState]
var start: Int
var accept: Int
func matchesWhole(_ names: [PureXML.Model.QualifiedName]) -> Bool {
var current = closure([start])
for name in names {
var next: Set<Int> = []
for state in current {
if let label = states[state].label, let target = states[state].target, label.matches(name) {
next.insert(target)
}
}
if next.isEmpty { return false }
current = closure(next)
}
return current.contains(accept)
}
private func closure(_ seed: Set<Int>) -> Set<Int> {
var seen = seed
var stack = Array(seed)
while let state = stack.popLast() {
for next in states[state].epsilon where seen.insert(next).inserted {
stack.append(next)
}
}
return seen
}
}
/// Builds a ``ContentNFA`` from a particle by Thompson construction.
struct ContentNFABuilder {
private var states: [ContentState] = []
static func build(_ particle: PureXML.Schema.Particle) -> ContentNFA {
var builder = ContentNFABuilder()
let fragment = builder.particle(particle)
return ContentNFA(states: builder.states, start: fragment.start, accept: fragment.accept)
}
private mutating func addState() -> Int {
states.append(ContentState())
return states.count - 1
}
private mutating func particle(_ particle: PureXML.Schema.Particle) -> (start: Int, accept: Int) {
let start = addState()
var current = start
for _ in 0 ..< particle.minOccurs {
let part = term(particle.term)
states[current].epsilon.append(part.start)
current = part.accept
}
let accept = addState()
if let maximum = particle.maxOccurs {
appendOptional(particle.term, count: maximum - particle.minOccurs, from: current, to: accept)
} else {
appendStar(particle.term, from: current, to: accept)
}
return (start, accept)
}
private mutating func appendOptional(_ term: PureXML.Schema.Term, count: Int, from: Int, to accept: Int) {
var current = from
for _ in 0 ..< Swift.max(0, count) {
let part = self.term(term)
states[current].epsilon.append(part.start)
states[current].epsilon.append(accept)
current = part.accept
}
states[current].epsilon.append(accept)
}
private mutating func appendStar(_ term: PureXML.Schema.Term, from current: Int, to accept: Int) {
let part = self.term(term)
states[current].epsilon.append(part.start)
states[current].epsilon.append(accept)
states[part.accept].epsilon.append(part.start)
states[part.accept].epsilon.append(accept)
}
private mutating func term(_ term: PureXML.Schema.Term) -> (start: Int, accept: Int) {
switch term {
case let .element(name, _):
labeled(.name(name))
case .wildcard:
labeled(.any)
case let .group(group):
self.group(group)
}
}
private mutating func labeled(_ label: TermLabel) -> (start: Int, accept: Int) {
let start = addState()
let accept = addState()
states[start].label = label
states[start].target = accept
return (start, accept)
}
private mutating func group(_ group: PureXML.Schema.Group) -> (start: Int, accept: Int) {
// `all` is validated by counting, not in the NFA; treat it as a
// sequence here so a nested occurrence still parses.
group.compositor == .choice ? choice(group.particles) : sequence(group.particles)
}
private mutating func sequence(_ particles: [PureXML.Schema.Particle]) -> (start: Int, accept: Int) {
guard !particles.isEmpty else { return labeledEmpty() }
var first: Int?
var last: Int?
for member in particles {
let part = particle(member)
if let previous = last { states[previous].epsilon.append(part.start) } else { first = part.start }
last = part.accept
}
return (first ?? addState(), last ?? addState())
}
private mutating func choice(_ particles: [PureXML.Schema.Particle]) -> (start: Int, accept: Int) {
let start = addState()
let accept = addState()
for member in particles {
let part = particle(member)
states[start].epsilon.append(part.start)
states[part.accept].epsilon.append(accept)
}
return (start, accept)
}
private mutating func labeledEmpty() -> (start: Int, accept: Int) {
let start = addState()
let accept = addState()
states[start].epsilon.append(accept)
return (start, accept)
}
}
}

View File

@ -0,0 +1,113 @@
@testable import PureXML
import Testing
@Suite("XSD complex types")
struct XSDComplexTypeTests {
private typealias Schema = PureXML.Schema
private func element(_ name: String, type: Schema.ElementType? = nil, min: Int = 1, max: Int? = 1) -> Schema.Particle {
Schema.Particle(minOccurs: min, maxOccurs: max, term: .element(name: .init(name), type: type))
}
private func parse(_ xml: String) throws -> PureXML.Model.Element {
guard case let .document(children) = try PureXML.parse(xml), let root = children.compactMap(\.element).first else {
throw TestFailure.noRoot
}
return root
}
private enum TestFailure: Error { case noRoot }
private func validate(_ xml: String, _ type: Schema.ComplexType) throws -> [PureXML.Validation.Issue] {
try Schema.ComplexValidator().validate(parse(xml), against: type)
}
// MARK: Sequence and occurrence
@Test("A sequence accepts the declared order and occurrence")
func test_sequence() throws {
let type = Schema.ComplexType(content: .elementOnly(
Schema.Particle(term: .group(.init(compositor: .sequence, particles: [
element("title"),
element("author", min: 1, max: nil),
]))),
))
#expect(try validate("<book><title>T</title><author>A</author><author>B</author></book>", type).isEmpty)
#expect(try !validate("<book><author>A</author><title>T</title></book>", type).isEmpty)
#expect(try !validate("<book><title>T</title></book>", type).isEmpty)
}
@Test("A choice accepts exactly one alternative")
func test_choice() throws {
let type = Schema.ComplexType(content: .elementOnly(
Schema.Particle(term: .group(.init(compositor: .choice, particles: [element("a"), element("b")]))),
))
#expect(try validate("<r><a/></r>", type).isEmpty)
#expect(try validate("<r><b/></r>", type).isEmpty)
#expect(try !validate("<r><a/><b/></r>", type).isEmpty)
}
@Test("An all group accepts any order, each member once")
func test_all() throws {
let type = Schema.ComplexType(content: .elementOnly(
Schema.Particle(term: .group(.init(compositor: .all, particles: [
element("x"),
element("y", min: 0, max: 1),
]))),
))
#expect(try validate("<r><y/><x/></r>", type).isEmpty)
#expect(try validate("<r><x/></r>", type).isEmpty)
#expect(try !validate("<r><x/><x/></r>", type).isEmpty)
#expect(try !validate("<r><y/></r>", type).isEmpty)
}
// MARK: Attributes
@Test("Required and typed attributes are enforced")
func test_attributes() throws {
let type = Schema.ComplexType(
attributes: [
.init(name: .init("id"), type: .init(base: .int), required: true),
.init(name: .init("lang"), type: .init(base: .language)),
],
content: .empty,
)
#expect(try validate("<e id=\"1\" lang=\"en\"/>", type).isEmpty)
#expect(try !validate("<e/>", type).isEmpty) // missing required id
#expect(try !validate("<e id=\"x\"/>", type).isEmpty) // id not an int
#expect(try !validate("<e id=\"1\" extra=\"y\"/>", type).isEmpty) // undeclared attribute
}
// MARK: Simple and mixed content
@Test("Simple content validates the text against a simple type")
func test_simpleContent() throws {
let type = Schema.ComplexType(content: .simpleContent(.init(base: .int)))
#expect(try validate("<n>42</n>", type).isEmpty)
#expect(try !validate("<n>x</n>", type).isEmpty)
#expect(try !validate("<n><child/></n>", type).isEmpty)
}
@Test("Element-only content rejects stray text; mixed allows it")
func test_elementOnlyVsMixed() throws {
let particle = Schema.Particle(term: .group(.init(compositor: .sequence, particles: [element("a")])))
let elementOnly = Schema.ComplexType(content: .elementOnly(particle))
let mixed = Schema.ComplexType(content: .mixed(particle))
#expect(try !validate("<r>text<a/></r>", elementOnly).isEmpty)
#expect(try validate("<r>text<a/></r>", mixed).isEmpty)
}
// MARK: Recursion
@Test("Child elements are validated against their declared types")
func test_recursiveTypes() throws {
let count = Schema.ElementType.simple(.init(base: .nonNegativeInteger))
let type = Schema.ComplexType(content: .elementOnly(
Schema.Particle(term: .group(.init(compositor: .sequence, particles: [
element("count", type: count),
]))),
))
#expect(try validate("<r><count>3</count></r>", type).isEmpty)
#expect(try !validate("<r><count>-1</count></r>", type).isEmpty)
}
}