diff --git a/CHANGELOG.md b/CHANGELOG.md
index d6d0bcc..a1465e9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- DTD ID/IDREF validation. Attributes typed `ID` must be unique across the
+ document; `IDREF` and `IDREFS` values must each resolve to a declared `ID`
+ (forward references included, via a second pass). Completes the structural DTD
+ validation layer alongside content models and attribute rules.
- DTD attribute validation (``). The parser surfaces attribute
declarations alongside element models, and `DTDSchema` now checks `#REQUIRED`
attributes are present, `#FIXED` attributes match when present, and enumerated
diff --git a/Sources/Validation/AttributeListParser.swift b/Sources/Validation/AttributeListParser.swift
index b146c9e..ba40ae8 100644
--- a/Sources/Validation/AttributeListParser.swift
+++ b/Sources/Validation/AttributeListParser.swift
@@ -36,13 +36,16 @@ extension PureXML.Validation {
return .enumeration(parseEnumeration())
}
let token = parseName()
- if token == "NOTATION" {
+ switch token {
+ case "ID": return .id
+ case "IDREF": return .idReference
+ case "IDREFS": return .idReferences
+ case "NOTATION":
skipSpace()
- if peek() == "(" {
- return .enumeration(parseEnumeration())
- }
+ return peek() == "(" ? .enumeration(parseEnumeration()) : .cdata
+ default:
+ return .cdata
}
- return .cdata
}
private mutating func parseEnumeration() -> [String] {
diff --git a/Sources/Validation/AttributeType.swift b/Sources/Validation/AttributeType.swift
index 8702eb4..ef557c0 100644
--- a/Sources/Validation/AttributeType.swift
+++ b/Sources/Validation/AttributeType.swift
@@ -1,9 +1,16 @@
extension PureXML.Validation {
- /// The declared type of a DTD attribute. Tokenized types (ID, IDREF, NMTOKEN,
- /// and so on) are treated as unconstrained character data here, since their
- /// value rules are not yet enforced; only an enumeration constrains the value.
+ /// The declared type of a DTD attribute. Remaining tokenized types (NMTOKEN,
+ /// ENTITY, and so on) are treated as unconstrained character data; only an
+ /// enumeration constrains the value, and the ID family drives cross-document
+ /// uniqueness and reference checks.
enum AttributeType: Equatable {
case cdata
case enumeration([String])
+ /// `ID`: the value must be unique across the document.
+ case id
+ /// `IDREF`: the value must match some declared `ID`.
+ case idReference
+ /// `IDREFS`: each whitespace-separated value must match some declared `ID`.
+ case idReferences
}
}
diff --git a/Sources/Validation/DTDSchema.swift b/Sources/Validation/DTDSchema.swift
index 37abd9a..8f37f3c 100644
--- a/Sources/Validation/DTDSchema.swift
+++ b/Sources/Validation/DTDSchema.swift
@@ -25,52 +25,77 @@ public extension PureXML.Validation {
models.isEmpty && attributes.isEmpty
}
- /// Validates a node tree against the declared content models. In strict
- /// mode an element with no declaration is itself an error; otherwise
- /// undeclared elements are skipped.
+ /// Validates a node tree against the declared content models and attribute
+ /// rules. Element structure and attribute presence/value are checked in one
+ /// walk; ID uniqueness and IDREF resolution are checked afterward, since a
+ /// reference may point forward to an ID later in the document. In strict
+ /// mode an element with no declaration is itself an error.
public func validate(_ node: PureXML.Model.Node, strict: Bool = false) -> [Issue] {
- var issues: [Issue] = []
- walk(node, strict: strict, into: &issues)
- return issues
+ var state = DTDState()
+ walk(node, strict: strict, into: &state)
+ for (value, count) in state.idCounts where count > 1 {
+ state.issues.append(error("duplicate ID '\(value)' (declared \(count) times)"))
+ }
+ for reference in state.references where state.idCounts[reference.value] == nil {
+ state.issues.append(error("IDREF '\(reference.value)' on <\(reference.element)> matches no ID"))
+ }
+ return state.issues
}
- private func walk(_ node: PureXML.Model.Node, strict: Bool, into issues: inout [Issue]) {
+ private func walk(_ node: PureXML.Model.Node, strict: Bool, into state: inout DTDState) {
switch node {
case let .document(children):
for child in children {
- walk(child, strict: strict, into: &issues)
+ walk(child, strict: strict, into: &state)
}
case let .element(element):
- validateElement(element, strict: strict, into: &issues)
+ validateElement(element, strict: strict, into: &state)
for child in element.children {
- walk(child, strict: strict, into: &issues)
+ walk(child, strict: strict, into: &state)
}
case .text, .cdata, .comment, .processingInstruction:
break
}
}
- private func validateElement(_ element: PureXML.Model.Element, strict: Bool, into issues: inout [Issue]) {
+ private func validateElement(_ element: PureXML.Model.Element, strict: Bool, into state: inout DTDState) {
let name = element.name.description
if let model = models[name] {
let content = childContent(of: element)
- issues.append(contentsOf: violations(name: name, model: model, content: content))
+ state.issues.append(contentsOf: violations(name: name, model: model, content: content))
} else if strict {
- issues.append(error("element <\(name)> is not declared in the DTD"))
+ state.issues.append(error("element <\(name)> is not declared in the DTD"))
}
- issues.append(contentsOf: attributeViolations(name: name, element: element))
- }
-
- private func attributeViolations(name: String, element: PureXML.Model.Element) -> [Issue] {
- guard let declarations = attributes[name] else { return [] }
- var result: [Issue] = []
+ guard let declarations = attributes[name] else { return }
for declaration in declarations {
let value = element.attributes.first {
$0.name.description == declaration.name || $0.name.localName == declaration.name
}?.value
- result.append(contentsOf: checkAttribute(declaration, value: value, on: name))
+ state.issues.append(contentsOf: checkAttribute(declaration, value: value, on: name))
+ if let value {
+ collectIdentifiers(declaration, value: value, element: name, into: &state)
+ }
+ }
+ }
+
+ private func collectIdentifiers(
+ _ declaration: AttributeDeclaration,
+ value: String,
+ element: String,
+ into state: inout DTDState,
+ ) {
+ switch declaration.type {
+ case .id:
+ state.idCounts[value, default: 0] += 1
+ case .idReference:
+ state.references.append((value, element))
+ case .idReferences:
+ for token in value.split(whereSeparator: { $0.isWhitespace }) {
+ state.references.append((String(token), element))
+ }
+ case .cdata, .enumeration:
+ break
}
- return result
}
private func checkAttribute(_ declaration: AttributeDeclaration, value: String?, on element: String) -> [Issue] {
@@ -146,3 +171,11 @@ public extension PureXML.Validation {
}
}
}
+
+/// Mutable state carried through one DTD validation walk: the issues found, the
+/// count of each declared ID, and the IDREF references to resolve afterward.
+private struct DTDState {
+ var issues: [PureXML.Validation.Issue] = []
+ var idCounts: [String: Int] = [:]
+ var references: [(value: String, element: String)] = []
+}
diff --git a/Tests/DTDIdentifierTests.swift b/Tests/DTDIdentifierTests.swift
new file mode 100644
index 0000000..227189b
--- /dev/null
+++ b/Tests/DTDIdentifierTests.swift
@@ -0,0 +1,36 @@
+@testable import PureXML
+import Testing
+
+@Suite("DTD ID and IDREF validation")
+struct DTDIdentifierTests {
+ private func issues(_ xml: String) throws -> [PureXML.Validation.Issue] {
+ try PureXML.validateAgainstInternalDTD(xml)
+ }
+
+ private let idDTD = ""
+ + "]>"
+
+ @Test("Unique IDs validate; duplicate IDs are rejected")
+ func test_idUniqueness() throws {
+ try #expect(issues("\(idDTD) ").isEmpty)
+ try #expect(!issues("\(idDTD) ").isEmpty)
+ }
+
+ @Test("IDREF resolves to an ID anywhere in the document, including forward")
+ func test_idrefForwardReference() throws {
+ try #expect(issues("\(idDTD) ").isEmpty)
+ }
+
+ @Test("A dangling IDREF is rejected")
+ func test_danglingIdref() throws {
+ try #expect(!issues("\(idDTD) ").isEmpty)
+ }
+
+ @Test("IDREFS resolves each token; a dangling token is rejected")
+ func test_idrefs() throws {
+ let valid = "\(idDTD) "
+ try #expect(issues(valid).isEmpty)
+ let dangling = "\(idDTD) "
+ try #expect(!issues(dangling).isEmpty)
+ }
+}