feat(validation): add DTD ID/IDREF/IDREFS validation

Complete the structural DTD validation layer. AttributeType now distinguishes
the ID family; the validator does a second pass after the structural walk
(since an IDREF may point forward to an ID later in the document):

- ID-typed attribute values must be unique across the document.
- IDREF values must each resolve to a declared ID.
- IDREFS values are split on whitespace and each token must resolve.

Reimplemented from the DTD ID/IDREF spec; no upstream code copied. 4 tests; 79
total.
This commit is contained in:
Mihaela Mihaljevic 2026-06-08 02:13:11 +02:00
parent 5cbe938826
commit 537b455ce8
5 changed files with 112 additions and 29 deletions

View File

@ -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 (`<!ATTLIST>`). The parser surfaces attribute
declarations alongside element models, and `DTDSchema` now checks `#REQUIRED`
attributes are present, `#FIXED` attributes match when present, and enumerated

View File

@ -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] {

View File

@ -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
}
}

View File

@ -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)] = []
}

View File

@ -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 = "<!DOCTYPE root [<!ELEMENT root (item)*><!ELEMENT item EMPTY>"
+ "<!ATTLIST item id ID #IMPLIED ref IDREF #IMPLIED refs IDREFS #IMPLIED>]>"
@Test("Unique IDs validate; duplicate IDs are rejected")
func test_idUniqueness() throws {
try #expect(issues("\(idDTD)<root><item id=\"a\"/><item id=\"b\"/></root>").isEmpty)
try #expect(!issues("\(idDTD)<root><item id=\"a\"/><item id=\"a\"/></root>").isEmpty)
}
@Test("IDREF resolves to an ID anywhere in the document, including forward")
func test_idrefForwardReference() throws {
try #expect(issues("\(idDTD)<root><item ref=\"b\"/><item id=\"b\"/></root>").isEmpty)
}
@Test("A dangling IDREF is rejected")
func test_danglingIdref() throws {
try #expect(!issues("\(idDTD)<root><item ref=\"x\"/><item id=\"b\"/></root>").isEmpty)
}
@Test("IDREFS resolves each token; a dangling token is rejected")
func test_idrefs() throws {
let valid = "\(idDTD)<root><item id=\"a\"/><item id=\"b\"/><item refs=\"a b\"/></root>"
try #expect(issues(valid).isEmpty)
let dangling = "\(idDTD)<root><item id=\"a\"/><item refs=\"a z\"/></root>"
try #expect(!issues(dangling).isEmpty)
}
}