// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Checking a document against the declarations of its own document type. //! //! XML 1.0 (fifth edition), section 3 and the validity constraints throughout: //! https://www.w3.org/TR/2008/REC-xml-20081126/#sec-logical-struct //! //! [zxml][] reads a `` into declarations and stops there, on purpose: //! supplying attribute defaults and resolving declared entities is what XML //! asks of a processor that does *not* validate, and reaching a verdict is a //! separate job with a different shape. It needs the whole document at once — //! an `IDREF` may point at an element that has not been parsed yet, and no //! amount of care makes a stream able to answer that — which is the same //! reason this library exists at all. //! //! [zxml]: https://git.jcollie.dev/jeff/zxml //! //! So the split is: zxml parses the DTD, ztree checks against it. //! //! ```zig //! const doc = try ztree.parse(gpa, source, .{ .dtd = true }); //! defer doc.destroy(); //! //! const report = try ztree.validate.run(gpa, doc); //! defer report.deinit(gpa); //! //! for (report.problems) |problem| std.debug.print("{s}\n", .{problem.detail}); //! ``` //! //! Every problem is reported rather than the first one thrown, because a //! document that fails validation usually fails it in several places and //! fixing them one run at a time is miserable. const std = @import("std"); const Allocator = std.mem.Allocator; const xml = @import("zxml"); const tree = @import("tree.zig"); const Document = tree.Document; const NodeId = tree.NodeId; const Name = tree.Name; pub const Error = error{ /// The document has no document type, or was parsed without /// `ParseOptions.dtd` so its declarations were never read. NoDoctype, /// The document type names an external subset, which nothing here will /// fetch. The declarations are therefore incomplete, and a verdict /// reached against them would be mostly false reports of things the /// unread half declares. ExternalSubsetNotRead, // Plus what zxml can report while a `#FIXED` value is decoded for // comparison: a declaration whose replacement text is recursive or // ruinous is the document type's problem rather than the document's, and // is thrown rather than filed against a node. } || xml.Error || Allocator.Error; /// What went wrong, in a form something other than a person can branch on. pub const Code = enum { /// The document element is not the one the document type names. root_element_mismatch, /// An element with no `` declaration. undeclared_element, /// A child element the parent's content model does not allow here. element_not_allowed, /// An end tag reached with the content model unsatisfied. incomplete_content, /// Character data where the content model allows only elements. text_not_allowed, /// An attribute with no `` declaration for that element. undeclared_attribute, /// A `#REQUIRED` attribute the start tag does not carry. missing_required_attribute, /// A `#FIXED` attribute given some other value. fixed_attribute_mismatch, /// A value outside its enumeration, or malformed for its declared type. invalid_attribute_value, /// Two elements carrying the same `ID`. duplicate_id, /// An `IDREF` naming an `ID` that no element in the document carries. unresolved_idref, /// A notation named by an `` and never declared. undeclared_notation, /// An `ENTITY` attribute naming something that is not a declared unparsed /// entity. undeclared_entity, }; pub const Problem = struct { /// The element or attribute node the complaint is about. node: NodeId, code: Code, /// A sentence saying what is wrong, allocated by `run`. detail: []const u8, }; pub const Report = struct { /// In document order, and empty when the document is valid. problems: []const Problem, pub fn valid(r: Report) bool { return r.problems.len == 0; } pub fn deinit(r: Report, gpa: Allocator) void { for (r.problems) |problem| gpa.free(problem.detail); gpa.free(r.problems); } }; /// Checks `doc` against the declarations it was parsed with. /// /// The document must have been parsed with `.{ .dtd = true }`, which is what /// puts the declarations on it; without them there is nothing to check against /// and that is `error.NoDoctype` rather than a clean bill of health. pub fn run(gpa: Allocator, doc: *const Document) Error!Report { const dtd = if (doc.dtd) |*d| d else return error.NoDoctype; if (dtd.incomplete) return error.ExternalSubsetNotRead; var v: Validator = .{ .gpa = gpa, .doc = doc, .dtd = dtd }; defer v.deinit(); // The widest content model decides how much working set a cursor needs, // and one buffer is reused for all of them: a model is finished with // before its children are descended into. v.cursor_buf = try gpa.alloc(u64, 2 * dtd.max_words); try v.document(); // The problems found while walking are already in document order; the // unresolved references are found afterwards and are not, so the whole // list is put back in order before it is handed over. const problems = try v.problems.toOwnedSlice(gpa); std.mem.sort(Problem, problems, doc, lessThan); return .{ .problems = problems }; } fn lessThan(doc: *const Document, a: Problem, b: Problem) bool { return doc.node(a.node).order < doc.node(b.node).order; } const Reference = struct { /// The attribute node carrying it. node: NodeId, /// Owned, because the name buffers are reused for the next element and /// this is not looked at until the whole document has been walked. The /// value beside it needs no copy: it belongs to the document's arena. attribute: []const u8, value: []const u8, }; const Validator = struct { gpa: Allocator, doc: *const Document, dtd: *const xml.Dtd, problems: std.ArrayList(Problem) = .empty, /// The qualified name of the element being checked, and a second buffer /// for the names needed only in passing beside it -- a child's, an /// attribute's. Two, because one element's name stays live across the /// whole of its check and every message about a child mentions both. subject_buf: std.ArrayList(u8) = .empty, other_buf: std.ArrayList(u8) = .empty, cursor_buf: []u64 = &.{}, /// Every `ID` value seen, against the element carrying it. ids: std.StringHashMapUnmanaged(NodeId) = .empty, /// Every `IDREF`, held until the whole document has been seen, because one /// may point forward. idrefs: std.ArrayList(Reference) = .empty, /// The elements still to visit, deepest last. pending: std.ArrayList(NodeId) = .empty, fn deinit(v: *Validator) void { v.problems.deinit(v.gpa); v.subject_buf.deinit(v.gpa); v.other_buf.deinit(v.gpa); v.gpa.free(v.cursor_buf); v.ids.deinit(v.gpa); for (v.idrefs.items) |ref| v.gpa.free(ref.attribute); v.idrefs.deinit(v.gpa); v.pending.deinit(v.gpa); } fn report(v: *Validator, node: NodeId, code: Code, comptime fmt: []const u8, args: anytype) !void { const detail = try std.fmt.allocPrint(v.gpa, fmt, args); errdefer v.gpa.free(detail); try v.problems.append(v.gpa, .{ .node = node, .code = code, .detail = detail }); } /// A name as the document type spells it: qualified, prefix and all. /// /// A DTD predates namespaces and knows nothing about them, so `` is /// declared as `x:a` and an element bound to the same namespace through a /// different prefix is, to the DTD, a different element. That is XML's /// answer rather than this library's, and pretending otherwise would /// accept documents no other validator does. fn written(v: *Validator, buf: *std.ArrayList(u8), name: Name) ![]const u8 { buf.clearRetainingCapacity(); if (name.prefix.len != 0) { try buf.appendSlice(v.gpa, name.prefix); try buf.append(v.gpa, ':'); } try buf.appendSlice(v.gpa, name.local); return buf.items; } /// The name of the element being checked. Stays valid until the next /// element is reached. fn subject(v: *Validator, name: Name) ![]const u8 { return v.written(&v.subject_buf, name); } /// A name wanted only for the next comparison or message, which is every /// name that is not the subject's. fn other(v: *Validator, name: Name) ![]const u8 { return v.written(&v.other_buf, name); } fn document(v: *Validator) !void { const root = v.doc.documentElement() orelse return; const name = try v.subject(v.doc.node(root).name); if (!std.mem.eql(u8, name, v.dtd.name)) { try v.report(root, .root_element_mismatch, "the document element is <{s}>, and the document type declares <{s}>", .{ name, v.dtd.name }); } try v.pending.append(v.gpa, root); while (v.pending.pop()) |id| try v.element(id); try v.references(); } fn element(v: *Validator, id: NodeId) !void { const node = v.doc.node(id); const name = try v.subject(node.name); const decl = v.dtd.element(name); if (decl == null) { try v.report(id, .undeclared_element, "no declaration for <{s}>", .{name}); } try v.attributes(id, name); if (decl) |d| try v.content(id, name, d); // Children are pushed in reverse so that popping them walks the // document forwards, and pushed only after this element's own content // model has been decided, so that one cursor buffer serves them all. var i = node.children.items.len; while (i > 0) { i -= 1; const child = node.children.items[i]; if (v.doc.node(child).kind == .element) try v.pending.append(v.gpa, child); } } // -- content ------------------------------------------------------------ fn content(v: *Validator, id: NodeId, name: []const u8, decl: xml.ElementDecl) !void { switch (decl.content) { .empty => try v.emptyContent(id, name), // ANY allows any declared element and any character data, so the // only thing to check is that the children are declared, which // happens when each of them is visited. .any => {}, .mixed => |allowed| try v.mixedContent(id, name, allowed, decl.source), .children => |*model| try v.elementContent(id, name, model, decl.source), } } fn emptyContent(v: *Validator, id: NodeId, name: []const u8) !void { for (v.doc.node(id).children.items) |child| { switch (v.doc.node(child).kind) { .element => try v.report(child, .element_not_allowed, "<{s}> is declared EMPTY and may not contain <{s}>", .{ name, try v.other(v.doc.node(child).name) }), // Not even whitespace: EMPTY means the tags touch, and a // document that indents between them is invalid however // harmless it looks. .text => try v.report(child, .text_not_allowed, "<{s}> is declared EMPTY and may not contain character data", .{name}), else => {}, } } } fn mixedContent(v: *Validator, id: NodeId, name: []const u8, allowed: []const []const u8, source: []const u8) !void { for (v.doc.node(id).children.items) |child| { if (v.doc.node(child).kind != .element) continue; const child_name = try v.other(v.doc.node(child).name); for (allowed) |candidate| { if (std.mem.eql(u8, candidate, child_name)) break; } else { try v.report(child, .element_not_allowed, "<{s}> is not one of the elements <{s}> allows beside its text, {s}", .{ child_name, name, source }); } } } fn elementContent(v: *Validator, id: NodeId, name: []const u8, model: *const xml.Model, source: []const u8) !void { var cursor = model.cursor(v.cursor_buf[0..model.scratchWords()]); for (v.doc.node(id).children.items) |child| { const child_node = v.doc.node(child); switch (child_node.kind) { .element => { const child_name = try v.other(child_node.name); if (!cursor.accept(child_name)) { try v.report(child, .element_not_allowed, "<{s}> does not allow <{s}> at this point in {s}", .{ name, child_name, source }); } }, .text => { // Whitespace between the children of an element-content // element is what a pretty-printed document is mostly made // of, and XML allows it; anything else is content the // model has no room for. if (xml.isWhitespace(child_node.value)) continue; try v.report(child, .text_not_allowed, "<{s}> has element content, {s}, so it may not contain character data", .{ name, source }); }, else => {}, } } if (!cursor.complete()) { try v.report(id, .incomplete_content, "<{s}> ends with its content model, {s}, unsatisfied", .{ name, source }); } } // -- attributes --------------------------------------------------------- fn attributes(v: *Validator, id: NodeId, name: []const u8) !void { const node = v.doc.node(id); const defs = v.dtd.attributes(name); for (node.attributes.items) |attr| { const attr_node = v.doc.node(attr); const attr_name = try v.other(attr_node.name); const def = v.dtd.attribute(name, attr_name) orelse { // A namespace declaration is an attribute to a DTD, but ztree // has already taken it out of the attribute list, so one is // never seen here and never complained about. try v.report(attr, .undeclared_attribute, "no declaration for `{s}` on <{s}>", .{ attr_name, name }); continue; }; try v.attributeValue(attr, attr_name, attr_node.value, def); } const required: []const xml.AttDef = defs orelse &.{}; for (required) |def| { if (def.default != .required) continue; for (node.attributes.items) |attr| { if (std.mem.eql(u8, try v.other(v.doc.node(attr).name), def.name)) break; } else { try v.report(id, .missing_required_attribute, "<{s}> is missing `{s}`, which is #REQUIRED", .{ name, def.name }); } } } fn attributeValue(v: *Validator, id: NodeId, name: []const u8, value: []const u8, def: xml.AttDef) !void { if (def.default == .fixed) { // The value in the tree is decoded and normalized; the declaration // holds the literal as written, so it has to make the same trip // before the two can be compared. const fixed = try xml.decodeAlloc(v.gpa, def.default.fixed, .{ .declared = .{ .dtd = v.dtd } }, .attribute); defer v.gpa.free(fixed); if (!std.mem.eql(u8, fixed, value)) { try v.report(id, .fixed_attribute_mismatch, "`{s}` is #FIXED \"{s}\", and this one says \"{s}\"", .{ name, fixed, value }); } } switch (def.type) { .cdata => {}, .id => { if (!isName(value)) { return v.report(id, .invalid_attribute_value, "`{s}` is an ID and \"{s}\" is not a name", .{ name, value }); } const slot = try v.ids.getOrPut(v.gpa, value); if (slot.found_existing) { try v.report(id, .duplicate_id, "`{s}` is \"{s}\", which another element already carries", .{ name, value }); } else slot.value_ptr.* = id; }, .idref => try v.reference(id, name, value), .idrefs => try v.eachToken(id, name, value, reference), .entity => try v.unparsedEntity(id, name, value), .entities => try v.eachToken(id, name, value, unparsedEntity), .nmtoken => if (!isNmtoken(value)) { try v.report(id, .invalid_attribute_value, "`{s}` is an NMTOKEN and \"{s}\" is not one", .{ name, value }); }, .nmtokens => try v.eachToken(id, name, value, nameToken), .notation => |allowed| { for (allowed) |candidate| { if (std.mem.eql(u8, candidate, value)) break; } else return v.report(id, .invalid_attribute_value, "`{s}` is \"{s}\", which is not one of its notations", .{ name, value }); if (v.dtd.notations.get(value) == null) { try v.report(id, .undeclared_notation, "`{s}` names the notation `{s}`, which is not declared", .{ name, value }); } }, .enumeration => |allowed| { for (allowed) |candidate| { if (std.mem.eql(u8, candidate, value)) break; } else try v.report(id, .invalid_attribute_value, "`{s}` is \"{s}\", which is not one of its allowed values", .{ name, value }); }, } } /// Applies a per-token check to a whitespace-separated list value. fn eachToken( v: *Validator, id: NodeId, name: []const u8, value: []const u8, each: fn (*Validator, NodeId, []const u8, []const u8) Allocator.Error!void, ) !void { var it = std.mem.tokenizeAny(u8, value, xml.whitespace); var any = false; while (it.next()) |token| { any = true; try each(v, id, name, token); } if (!any) { try v.report(id, .invalid_attribute_value, "`{s}` is a list and is empty", .{name}); } } fn nameToken(v: *Validator, id: NodeId, name: []const u8, token: []const u8) Allocator.Error!void { if (!isNmtoken(token)) { try v.report(id, .invalid_attribute_value, "`{s}` is NMTOKENS and \"{s}\" is not a name token", .{ name, token }); } } fn reference(v: *Validator, id: NodeId, name: []const u8, token: []const u8) Allocator.Error!void { if (!isName(token)) { return v.report(id, .invalid_attribute_value, "`{s}` refers to \"{s}\", which is not a name", .{ name, token }); } const kept = try v.gpa.dupe(u8, name); errdefer v.gpa.free(kept); try v.idrefs.append(v.gpa, .{ .node = id, .attribute = kept, .value = token }); } fn unparsedEntity(v: *Validator, id: NodeId, name: []const u8, token: []const u8) Allocator.Error!void { if (v.dtd.resolve(token) != .unparsed) { try v.report(id, .undeclared_entity, "`{s}` names `{s}`, which is not a declared unparsed entity", .{ name, token }); } } /// The half of the job a stream cannot do: every `IDREF` gathered above, /// now that every `ID` in the document has been seen. fn references(v: *Validator) !void { for (v.idrefs.items) |ref| { if (v.ids.contains(ref.value)) continue; try v.report(ref.node, .unresolved_idref, "`{s}` refers to \"{s}\", and no element carries that ID", .{ ref.attribute, ref.value }); } } }; // -- XML names --------------------------------------------------------------- /// XML 1.0 (fifth edition) `NameStartChar`. /// /// The ranges are Unicode's, not ASCII's, which is the whole reason this is /// written out rather than deferred to `std.ascii`: an `ID` of `café` is a /// perfectly good name and rejecting it would be wrong. fn isNameStartChar(cp: u21) bool { return switch (cp) { ':', '_', 'A'...'Z', 'a'...'z' => true, 0xC0...0xD6, 0xD8...0xF6, 0xF8...0x2FF => true, 0x370...0x37D, 0x37F...0x1FFF => true, 0x200C...0x200D, 0x2070...0x218F => true, 0x2C00...0x2FEF, 0x3001...0xD7FF => true, 0xF900...0xFDCF, 0xFDF0...0xFFFD => true, 0x10000...0xEFFFF => true, else => false, }; } /// `NameChar`: a `NameStartChar`, or one of the characters that may not begin /// a name but may continue one. fn isNameChar(cp: u21) bool { if (isNameStartChar(cp)) return true; return switch (cp) { '-', '.', '0'...'9', 0xB7 => true, 0x300...0x36F, 0x203F...0x2040 => true, else => false, }; } /// True when `s` is an XML `Name`. pub fn isName(s: []const u8) bool { var it = (std.unicode.Utf8View.init(s) catch return false).iterator(); if (!isNameStartChar(it.nextCodepoint() orelse return false)) return false; while (it.nextCodepoint()) |cp| { if (!isNameChar(cp)) return false; } return true; } /// True when `s` is an XML `Nmtoken`, which is a name that need not start /// like one: `1999` is a name token and not a name. pub fn isNmtoken(s: []const u8) bool { var it = (std.unicode.Utf8View.init(s) catch return false).iterator(); var any = false; while (it.nextCodepoint()) |cp| { if (!isNameChar(cp)) return false; any = true; } return any; } // -- tests ------------------------------------------------------------------- const testing = std.testing; const catalog_dtd = \\ \\ \\ \\ \\ \\ \\]> ; const Checked = struct { doc: *Document, report: Report, fn deinit(c: Checked) void { c.report.deinit(testing.allocator); c.doc.destroy(); } /// Asserts the exact problems reported, in order, and prints what came /// back instead when they disagree -- which is most of the value of /// collecting problems rather than throwing the first. fn expect(c: Checked, expected: []const Code) !void { var wrong = c.report.problems.len != expected.len; if (!wrong) { for (c.report.problems, expected) |problem, want| { if (problem.code != want) wrong = true; } } if (wrong) { std.debug.print("reported {d} problem(s):\n", .{c.report.problems.len}); for (c.report.problems) |problem| { std.debug.print(" {t}: {s}\n", .{ problem.code, problem.detail }); } return error.TestUnexpectedResult; } } }; fn check(src: []const u8) !Checked { const doc = try tree.parse(testing.allocator, src, .{ .dtd = true }); errdefer doc.destroy(); return .{ .doc = doc, .report = try run(testing.allocator, doc) }; } test "a document that satisfies its declarations is valid" { const c = try check(catalog_dtd ++ \\ \\ Widget \\ GadgetA fine one. \\ ); defer c.deinit(); try c.expect(&.{}); try testing.expect(c.report.valid()); } test "the whitespace a document is indented with is not content" { // `(product+)` is element content, and a pretty-printed document is mostly // the whitespace between its tags. XML allows it there; anything else is // character data the model has no room for. const c = try check(catalog_dtd ++ "\n W\n"); defer c.deinit(); try c.expect(&.{}); const bad = try check(catalog_dtd ++ "oopsW"); defer bad.deinit(); try bad.expect(&.{.text_not_allowed}); } test "the document element must be the one the document type names" { const c = try check("]>"); defer c.deinit(); try c.expect(&.{.root_element_mismatch}); try testing.expectEqualStrings( "the document element is , and the document type declares ", c.report.problems[0].detail, ); } test "an element with no declaration is reported once, and its children still checked" { const c = try check(catalog_dtd ++ \\W ); defer c.deinit(); // Two complaints about the same element: the model does not allow it // here, and nothing declares it anywhere. try c.expect(&.{ .element_not_allowed, .undeclared_element }); } test "a content model refuses a child in the wrong place and notices one missing" { // `(name, note?)`: the note may be left out, but not put first, and the // name may not be left out at all. const out_of_order = try check(catalog_dtd ++ \\nW ); defer out_of_order.deinit(); try out_of_order.expect(&.{.element_not_allowed}); const missing = try check(catalog_dtd ++ ""); defer missing.deinit(); try missing.expect(&.{.incomplete_content}); try testing.expectEqualStrings( " ends with its content model, (name, note?), unsatisfied", missing.report.problems[0].detail, ); // `(product+)` wants at least one. const none = try check(catalog_dtd ++ ""); defer none.deinit(); try none.expect(&.{.incomplete_content}); } test "EMPTY means empty, indentation included" { const src = "]>"; const ok = try check(src ++ ""); defer ok.deinit(); try ok.expect(&.{}); // A space between the tags is character data, and EMPTY allows none. const spaced = try check(src ++ " "); defer spaced.deinit(); try spaced.expect(&.{.text_not_allowed}); const nested = try check(src ++ ""); defer nested.deinit(); try nested.expect(&.{.element_not_allowed}); } test "mixed content allows its text and only the elements it lists" { const c = try check(catalog_dtd ++ \\WA fine one. ); defer c.deinit(); try c.expect(&.{}); const wrong = try check(catalog_dtd ++ \\WA x one. ); defer wrong.deinit(); try wrong.expect(&.{.element_not_allowed}); } test "attributes must be declared, required ones present, fixed ones fixed" { const undeclared = try check(catalog_dtd ++ \\W ); defer undeclared.deinit(); try undeclared.expect(&.{.undeclared_attribute}); const missing = try check(catalog_dtd ++ \\W ); defer missing.deinit(); try missing.expect(&.{.missing_required_attribute}); const fixed = try check( \\]> \\ ); defer fixed.deinit(); try fixed.expect(&.{.fixed_attribute_mismatch}); try testing.expectEqualStrings( "`version` is #FIXED \"1.0\", and this one says \"2.0\"", fixed.report.problems[0].detail, ); } test "an enumerated attribute takes one of its values" { const c = try check(catalog_dtd ++ \\W ); defer c.deinit(); try c.expect(&.{.invalid_attribute_value}); } test "a value the document type supplies satisfies the declaration it came from" { // `status` and `currency` are defaulted, so they are on the element // without the start tag writing them, and validate against their own // declarations like anything else. const c = try check(catalog_dtd ++ \\W ); defer c.deinit(); try c.expect(&.{}); const product = c.doc.node(c.doc.documentElement().?).children.items[0]; try testing.expectEqualStrings("USD", c.doc.attributeValue(product, "", "currency").?); for (c.doc.node(product).attributes.items) |a| { const n = c.doc.node(a); // The document type supplied two of the three and the start tag wrote // the other, and the tree can still say which is which. const from_dtd = !std.mem.eql(u8, n.name.local, "id"); try testing.expectEqual(from_dtd, n.defaulted); } } test "an ID is unique, and an IDREF resolves even when it points forward" { const forward = try check(catalog_dtd ++ \\W \\G ); defer forward.deinit(); // The whole reason this lives here and not in the parser: at the moment // `ref="p2"` is read, no such element has been seen. try forward.expect(&.{}); const dangling = try check(catalog_dtd ++ \\W ); defer dangling.deinit(); try dangling.expect(&.{.unresolved_idref}); const duplicate = try check(catalog_dtd ++ \\W \\G ); defer duplicate.deinit(); try duplicate.expect(&.{.duplicate_id}); } test "an ID must be a name, and a name is not an ASCII question" { const numeric = try check(catalog_dtd ++ \\W ); defer numeric.deinit(); try numeric.expect(&.{.invalid_attribute_value}); // `café` is a perfectly good XML name, and a validator that only knew // ASCII would reject it. const accented = try check(catalog_dtd ++ \\W ); defer accented.deinit(); try accented.expect(&.{}); } test "list-valued attributes are checked one token at a time" { const src = \\ \\ \\ \\]> ; const ok = try check(src ++ \\ ); defer ok.deinit(); try ok.expect(&.{}); const bad = try check(src ++ \\ ); defer bad.deinit(); try bad.expect(&.{.unresolved_idref}); } test "ENTITY and NOTATION attributes name things that must be declared" { const src = \\ \\ \\ \\ \\]> ; const ok = try check(src ++ ""); defer ok.deinit(); try ok.expect(&.{}); // `gif` is in the attribute's list and was never declared as a notation, // and `nope` is not an unparsed entity at all. const bad = try check(src ++ ""); defer bad.deinit(); try bad.expect(&.{ .undeclared_entity, .undeclared_notation }); } test "a DTD validates the names as written, prefixes and all" { // A DTD predates namespaces: `x:a` is declared as `x:a`, and the same // element bound to the same namespace through another prefix is, to the // document type, something else entirely. A namespace declaration is an // attribute to a DTD too, which is why one is declared here -- though // ztree has already turned it into a namespace node by the time this // runs, so it is never checked. const c = try check( \\ \\ \\ \\]> \\ ); defer c.deinit(); try c.expect(&.{}); const renamed = try check( \\ \\ \\ \\]> \\ ); defer renamed.deinit(); // `y:item` is the same expanded name as `x:item` and the document type // cannot tell: it sees a name it never declared, and a model left wanting. try renamed.expect(&.{ .incomplete_content, .element_not_allowed, .undeclared_element }); } test "problems come back in document order" { const c = try check(catalog_dtd ++ \\ \\ W \\ G \\ ); defer c.deinit(); // The dangling reference is found only at the end, and still sorts back // to where the attribute carrying it sits. try c.expect(&.{ .unresolved_idref, .duplicate_id, .undeclared_attribute }); var previous: u32 = 0; for (c.report.problems) |problem| { const order = c.doc.node(problem.node).order; try testing.expect(order >= previous); previous = order; } } test "there has to be something to validate against" { // Parsed without `.dtd`, the declarations were never read, and saying so // is the answer rather than a clean bill of health. const doc = try tree.parse(testing.allocator, catalog_dtd ++ "W", .{}); defer doc.destroy(); try testing.expectError(error.NoDoctype, run(testing.allocator, doc)); const none = try tree.parse(testing.allocator, "", .{ .dtd = true }); defer none.destroy(); try testing.expectError(error.NoDoctype, run(testing.allocator, none)); } test "an external subset is refused rather than guessed at" { // Nothing here fetches it, so most of the declarations are missing, and a // verdict reached against what is left would be mostly false alarms. const doc = try tree.parse(testing.allocator, "", .{ .dtd = true }); defer doc.destroy(); try testing.expectError(error.ExternalSubsetNotRead, run(testing.allocator, doc)); } test "the source may be freed before the document is validated" { // ztree's whole contract is that the tree owns its strings. The // declarations have to be copied in the same way, or validating a // document whose source has gone reads freed memory. const gpa = testing.allocator; const source = try gpa.dupe(u8, catalog_dtd ++ \\W ); const doc = try tree.parse(gpa, source, .{ .dtd = true }); defer doc.destroy(); gpa.free(source); const report = try run(gpa, doc); defer report.deinit(gpa); try testing.expectEqual(@as(usize, 1), report.problems.len); try testing.expectEqual(Code.unresolved_idref, report.problems[0].code); // The message quotes the declarations, which is the part that would be // reading freed memory if they had not been copied. try testing.expectEqualStrings( "`ref` refers to \"p9\", and no element carries that ID", report.problems[0].detail, ); } test "names and name tokens" { try testing.expect(isName("a")); try testing.expect(isName("_x-1.2")); try testing.expect(isName("x:y")); try testing.expect(isName("café")); try testing.expect(!isName("")); try testing.expect(!isName("1999")); try testing.expect(!isName("-a")); try testing.expect(!isName("a b")); try testing.expect(!isName("a\xFF")); // A name token may begin with anything a name may continue with. try testing.expect(isNmtoken("1999")); try testing.expect(isNmtoken("-a")); try testing.expect(!isNmtoken("")); try testing.expect(!isNmtoken("a b")); }