diff --git a/Sources/API.swift b/Sources/API.swift index a1b3364..b12adb7 100644 --- a/Sources/API.swift +++ b/Sources/API.swift @@ -89,6 +89,20 @@ public extension PureXML { return Validation.DTD.validator(strict: strict).errors(for: parsed.node, in: schema) } + /// Parses an XML document and returns its tree with the DTD attribute defaults + /// from the internal subset applied: every element gains any attribute its + /// `` declares with a default or `#FIXED` value and that the element + /// omits, so an editor sees the same effective attributes a validating + /// processor would. DTD processing must be enabled. + static func parseApplyingInternalDTDDefaults( + _ xml: String, + limits: Parsing.Limits = .init(allowDoctype: true), + resolver: Parsing.EntityResolver = .refusing, + ) throws -> Model.Node { + let parsed = try Parsing.Parser().parseWithDocumentType(xml, limits: limits, resolver: resolver) + return Validation.DTDSchema(parsed.documentType).applyingDefaults(to: parsed.node) + } + /// Compiles and evaluates an XPath query over a node, returning the selected /// node-set. Compile once with ``XPath/Query`` to reuse a query. static func xpath(_ path: String, over node: Model.Node) throws -> [XPath.Selection] { diff --git a/Sources/Parsing/XMLCharacter.swift b/Sources/Parsing/XMLCharacter.swift index da30e30..ed69b0d 100644 --- a/Sources/Parsing/XMLCharacter.swift +++ b/Sources/Parsing/XMLCharacter.swift @@ -75,5 +75,12 @@ public extension PureXML.Parsing { } return true } + + /// `Nmtoken`: one or more NameChar (no name-start requirement). + public static func isNmtoken(_ token: String) -> Bool { + let scalars = token.unicodeScalars + guard !scalars.isEmpty else { return false } + return scalars.allSatisfy(isNameChar) + } } } diff --git a/Sources/Validation/AttributeListParser.swift b/Sources/Validation/AttributeListParser.swift index ba40ae8..45d0e24 100644 --- a/Sources/Validation/AttributeListParser.swift +++ b/Sources/Validation/AttributeListParser.swift @@ -25,7 +25,7 @@ extension PureXML.Validation { skipSpace() let type = parseType() skipSpace() - let defaultDecl = parseDefault() + let defaultDecl = parseDefault(type: type) declarations.append(AttributeDeclaration(name: name, type: type, defaultDecl: defaultDecl)) } return declarations @@ -40,6 +40,10 @@ extension PureXML.Validation { case "ID": return .id case "IDREF": return .idReference case "IDREFS": return .idReferences + case "NMTOKEN": return .nmToken + case "NMTOKENS": return .nmTokens + case "ENTITY": return .entity + case "ENTITIES": return .entities case "NOTATION": skipSpace() return peek() == "(" ? .enumeration(parseEnumeration()) : .cdata @@ -64,23 +68,74 @@ extension PureXML.Validation { return names } - private mutating func parseDefault() -> AttributeDefault { + private mutating func parseDefault(type: AttributeType) -> AttributeDefault { if peek() == "#" { let token = parseHashToken() switch token { case "#REQUIRED": return .required case "#FIXED": skipSpace() - return .fixed(parseLiteral()) + return .fixed(Self.normalize(parseLiteral(), type: type)) default: return .implied } } if let quote = peek(), quote == "\"" || quote == "'" { - return .value(parseLiteral()) + return .value(Self.normalize(parseLiteral(), type: type)) } return .implied } + /// Normalizes a DTD default attribute value per XML 1.0 attribute-value + /// normalization: character and predefined-entity references are expanded, + /// each literal whitespace character becomes a space, and for every type + /// other than CDATA leading and trailing spaces are stripped and internal + /// runs collapsed. General (non-predefined) entity references are left as + /// written, since the referenced entities are not resolved here. + static func normalize(_ raw: String, type: AttributeType) -> String { + let expanded = expandReferences(raw) + let spaced = String(expanded.map { ($0 == "\t" || $0 == "\n" || $0 == "\r") ? " " : $0 }) + guard type != .cdata else { return spaced } + return spaced.split(separator: " ", omittingEmptySubsequences: true).joined(separator: " ") + } + + private static func expandReferences(_ raw: String) -> String { + var result = "" + let chars = Array(raw) + var index = 0 + while index < chars.count { + guard chars[index] == "&", let semicolon = chars[(index + 1)...].firstIndex(of: ";") else { + result.append(chars[index]) + index += 1 + continue + } + let reference = String(chars[(index + 1) ..< semicolon]) + if let resolved = resolveReference(reference) { + result.append(resolved) + } else { + result += "&\(reference);" + } + index = semicolon + 1 + } + return result + } + + private static func resolveReference(_ reference: String) -> Character? { + switch reference { + case "lt": return "<" + case "gt": return ">" + case "amp": return "&" + case "apos": return "'" + case "quot": return "\"" + default: break + } + guard reference.hasPrefix("#") else { return nil } + let digits = reference.dropFirst() + let isHex = digits.hasPrefix("x") || digits.hasPrefix("X") + let value = isHex ? UInt32(digits.dropFirst(), radix: 16) : UInt32(digits, radix: 10) + guard let value, let scalar = Unicode.Scalar(value) else { return nil } + return Character(scalar) + } + private mutating func parseHashToken() -> String { var token = "#" advance() diff --git a/Sources/Validation/AttributeType.swift b/Sources/Validation/AttributeType.swift index ef557c0..182c7b5 100644 --- a/Sources/Validation/AttributeType.swift +++ b/Sources/Validation/AttributeType.swift @@ -1,8 +1,8 @@ extension PureXML.Validation { - /// 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. + /// The declared type of a DTD attribute. An enumeration constrains the value to + /// a fixed set; the tokenized types constrain its lexical form (a name token, a + /// name); and the ID family drives cross-document uniqueness and reference + /// checks. enum AttributeType: Equatable { case cdata case enumeration([String]) @@ -12,5 +12,13 @@ extension PureXML.Validation { case idReference /// `IDREFS`: each whitespace-separated value must match some declared `ID`. case idReferences + /// `NMTOKEN`: the value must be a single XML name token. + case nmToken + /// `NMTOKENS`: each whitespace-separated value must be a name token. + case nmTokens + /// `ENTITY`: the value must be an XML name (naming an unparsed entity). + case entity + /// `ENTITIES`: each whitespace-separated value must be a name. + case entities } } diff --git a/Sources/Validation/DTDDefaults.swift b/Sources/Validation/DTDDefaults.swift new file mode 100644 index 0000000..6de2ed2 --- /dev/null +++ b/Sources/Validation/DTDDefaults.swift @@ -0,0 +1,38 @@ +public extension PureXML.Validation.DTDSchema { + /// Returns `node` with DTD attribute defaults applied: every element gains any + /// attribute its `` declares with a default or `#FIXED` value and + /// that the element omits. `#REQUIRED` and `#IMPLIED` add nothing. The injected + /// values are the normalized defaults from the declaration, so an editor reads + /// the same effective attributes a validating processor would see. + func applyingDefaults(to node: PureXML.Model.Node) -> PureXML.Model.Node { + switch node { + case let .document(children): + .document(children.map(applyingDefaults(to:))) + case let .element(element): + .element(applyingDefaults(to: element)) + case .text, .cdata, .comment, .processingInstruction: + node + } + } + + private func applyingDefaults(to element: PureXML.Model.Element) -> PureXML.Model.Element { + var result = element + result.children = element.children.map { applyingDefaults(to: $0) } + guard let declarations = attributes[element.name.description] else { return result } + for declaration in declarations { + guard let value = Self.defaultValue(declaration) else { continue } + let present = result.attributes.contains { + $0.name.description == declaration.name || $0.name.localName == declaration.name + } + if !present { result.attributes.append(PureXML.Model.Attribute(declaration.name, value)) } + } + return result + } + + private static func defaultValue(_ declaration: PureXML.Validation.AttributeDeclaration) -> String? { + switch declaration.defaultDecl { + case let .value(value), let .fixed(value): value + case .required, .implied: nil + } + } +} diff --git a/Sources/Validation/DTDValidationHelpers.swift b/Sources/Validation/DTDValidationHelpers.swift index 99a288e..cbb08fa 100644 --- a/Sources/Validation/DTDValidationHelpers.swift +++ b/Sources/Validation/DTDValidationHelpers.swift @@ -79,9 +79,51 @@ extension PureXML.Validation.DTD { if case let .enumeration(allowed) = declaration.type, !allowed.contains(value) { result.append(DTDFailure(reason: "attribute '\(declaration.name)' on <\(name)> has a value outside its enumeration", at: path)) } + if let tokenError = tokenizedTypeError(declaration, value: value, on: name, at: path) { + result.append(tokenError) + } return result } + /// The error when a tokenized attribute value does not match its declared + /// lexical form: `NMTOKEN(S)` must be name token(s), `ENTITY`/`ENTITIES` must be + /// XML name(s). The ID family is checked separately for cross-reference + /// integrity. + /// + /// Note: `ENTITY`/`ENTITIES` are checked only for name syntax. That the named + /// entity is a declared *unparsed* entity is not verified, since NDATA entity + /// declarations are not yet tracked. + static func tokenizedTypeError( + _ declaration: PureXML.Validation.AttributeDeclaration, + value: String, + on element: String, + at path: DTDPath, + ) -> DTDFailure? { + let isName = PureXML.Parsing.XMLCharacter.isValidName + let isNmtoken = PureXML.Parsing.XMLCharacter.isNmtoken + let tokens = value.split(whereSeparator: \.isWhitespace).map(String.init) + let valid: Bool + switch declaration.type { + case .nmToken: valid = isNmtoken(value) + case .nmTokens: valid = !tokens.isEmpty && tokens.allSatisfy(isNmtoken) + case .entity: valid = isName(value) + case .entities: valid = !tokens.isEmpty && tokens.allSatisfy(isName) + case .cdata, .enumeration, .id, .idReference, .idReferences: return nil + } + guard !valid else { return nil } + return DTDFailure(reason: "attribute '\(declaration.name)' on <\(element)> is not a valid \(typeName(declaration.type))", at: path) + } + + private static func typeName(_ type: PureXML.Validation.AttributeType) -> String { + switch type { + case .nmToken: "NMTOKEN" + case .nmTokens: "NMTOKENS" + case .entity: "ENTITY" + case .entities: "ENTITIES" + default: "value" + } + } + // MARK: ID / IDREF integrity static func identifierErrors(_ node: PureXML.Model.Node, schema: PureXML.Validation.DTDSchema, at path: DTDPath) -> [DTDFailure] { @@ -141,7 +183,7 @@ extension PureXML.Validation.DTD { for token in value.split(whereSeparator: { $0.isWhitespace }) { references.append((String(token), name)) } - case .cdata, .enumeration: + case .cdata, .enumeration, .nmToken, .nmTokens, .entity, .entities: break } } diff --git a/Tests/DTDDefaultingTests.swift b/Tests/DTDDefaultingTests.swift new file mode 100644 index 0000000..cfeb08a --- /dev/null +++ b/Tests/DTDDefaultingTests.swift @@ -0,0 +1,104 @@ +@testable import PureXML +import Testing + +@Suite("DTD attribute defaulting and tokenized types") +struct DTDDefaultingTests { + private func validate(_ xml: String) throws -> [PureXML.Validation.ValidationError] { + try PureXML.validateAgainstInternalDTD(xml) + } + + private func attribute(_ element: PureXML.Model.Element?, _ name: String) -> String? { + element?.attributes.first { $0.name.description == name }?.value + } + + private func root(_ node: PureXML.Model.Node) -> PureXML.Model.Element? { + guard case let .document(children) = node else { return nil } + return children.compactMap(\.element).first + } + + // MARK: Defaulting + + @Test("A default attribute value is injected into an element that omits it") + func test_defaultInjected() throws { + let xml = "]>" + let node = try PureXML.parseApplyingInternalDTDDefaults(xml) + #expect(attribute(root(node), "kind") == "box") + } + + @Test("A present attribute is not overwritten by its default") + func test_presentNotOverwritten() throws { + let xml = "]>" + let node = try PureXML.parseApplyingInternalDTDDefaults(xml) + #expect(attribute(root(node), "kind") == "crate") + } + + @Test("A #FIXED value is injected when absent") + func test_fixedInjected() throws { + let xml = "]>" + let node = try PureXML.parseApplyingInternalDTDDefaults(xml) + #expect(attribute(root(node), "v") == "1") + } + + @Test("#REQUIRED and #IMPLIED inject nothing") + func test_requiredImpliedInjectNothing() throws { + let xml = "]>" + let node = try PureXML.parseApplyingInternalDTDDefaults(xml) + #expect(attribute(root(node), "b") == nil) + } + + @Test("A non-CDATA default value is whitespace-normalized") + func test_defaultNormalized() throws { + let xml = "]>" + let node = try PureXML.parseApplyingInternalDTDDefaults(xml) + // Tabs become spaces and the value is collapsed and trimmed. + #expect(attribute(root(node), "t") == "a b") + } + + @Test("A CDATA default keeps internal content but replaces tabs with spaces") + func test_cdataDefaultReplaceOnly() throws { + let xml = "]>" + let node = try PureXML.parseApplyingInternalDTDDefaults(xml) + #expect(attribute(root(node), "t") == "a b") + } + + @Test("A character reference in a default is expanded") + func test_defaultCharacterReference() throws { + let xml = "]>" + let node = try PureXML.parseApplyingInternalDTDDefaults(xml) + #expect(attribute(root(node), "t") == "AB") + } + + // MARK: Tokenized type validation + + @Test("A valid NMTOKEN passes and an invalid one fails") + func test_nmtoken() throws { + let valid = "]>" + #expect(try validate(valid).isEmpty) + let bad = "]>" + #expect(try !validate(bad).isEmpty) + } + + @Test("NMTOKENS requires every whitespace-separated token to be a name token") + func test_nmtokens() throws { + let valid = "]>" + #expect(try validate(valid).isEmpty) + let bad = "]>" + #expect(try !validate(bad).isEmpty) + } + + @Test("ENTITY requires an XML name") + func test_entity() throws { + let valid = "]>" + #expect(try validate(valid).isEmpty) + let bad = "]>" + #expect(try !validate(bad).isEmpty) + } + + @Test("ENTITIES requires every token to be a name") + func test_entities() throws { + let valid = "]>" + #expect(try validate(valid).isEmpty) + let bad = "]>" + #expect(try !validate(bad).isEmpty) + } +}