Something went wrong. Try again.
An XML document tree and serializer for Zig 0.16, built on zxml.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The XPath data model: a document as a tree of nodes with parents, document//! order, and expanded names.//!//! zxml is a pull parser that hands out borrowed slices and never builds a//! tree, which is exactly right for reading a feed once and exactly wrong for//! XSLT. A template pattern such as `foo[@id='3']/../bar` asks for the parent//! axis; `xsl:sort` reorders a node-set and then asks for document order back;//! a key indexes every node in the document before the first template runs.//! None of that is answerable from a stream, so this module reads the stream//! once and builds the tree those questions need.//!//! The same tree is also what a transformation *produces*. An XSLT result is//! not written straight to a writer because `xsl:variable` with content builds//! a result tree fragment that `xsl:copy-of` can later copy whole, and because//! choosing how to serialize an element (an HTML `<br>` has no end tag, a//! `<script>` body is not escaped) is a decision about a tree. So `Document`//! is a builder as well as a reader, and `serialize.zig` turns the finished//! one into bytes.//!//! Nodes are referred to by `NodeId`, an index into one flat array, rather//! than by pointer. A node-set is then a sorted list of `u32`, deduplication//! is sorting, and the whole tree frees in one `deinit` because every string//! in it belongs to the document's arena.
const std = @import("std");const Allocator = std.mem.Allocator;const xml = @import("zxml");
/// The namespace the `xml` prefix is bound to without being declared.pub const xml_ns = "http://www.w3.org/XML/1998/namespace";/// The namespace `xmlns` itself is in. Never usable as a prefix.pub const xmlns_ns = "http://www.w3.org/2000/xmlns/";
/// An index into `Document.nodes`. Small enough that a node-set is a list of/// integers, which is what makes union, document order and deduplication/// cheap.pub const NodeId = u32;
pub const Kind = enum { /// The root of the tree, which XPath calls `/`. It is not the document /// element: that is its element child. document, element, attribute, text, comment, pi, /// Materialized on demand by `namespaceNodes`, because the namespace axis /// is the only thing that asks for them and most transformations never do. namespace,};
/// An expanded name: a namespace URI and a local part, plus the prefix it was/// written with.////// Two names are the same name when their URI and local part match; the prefix/// is carried only because the serializer has to write something back out, and/// because `name()` returns the qualified name as it appeared.pub const Name = struct { uri: []const u8 = "", local: []const u8 = "", prefix: []const u8 = "",
pub fn eql(a: Name, b: Name) bool { return std.mem.eql(u8, a.uri, b.uri) and std.mem.eql(u8, a.local, b.local); }
/// True when this is `{uri}local`. pub fn is(n: Name, uri: []const u8, local: []const u8) bool { return std.mem.eql(u8, n.uri, uri) and std.mem.eql(u8, n.local, local); }
/// The name as it was written: `prefix:local`, or just `local`. pub fn qualified(n: Name, gpa: Allocator) ![]u8 { if (n.prefix.len == 0) return gpa.dupe(u8, n.local); return std.fmt.allocPrint(gpa, "{s}:{s}", .{ n.prefix, n.local }); }};
/// A namespace declaration written on an element: `xmlns:prefix="uri"`. An/// empty `prefix` is the default declaration, and an empty `uri` undeclares.pub const NsDecl = struct { prefix: []const u8, uri: []const u8,};
pub const Node = struct { kind: Kind, parent: ?NodeId = null, /// Element and document children, in document order. Attributes and /// namespace nodes are deliberately not here: XPath's child axis does not /// contain them, and keeping them out means the axis is this list. children: std.ArrayList(NodeId) = .empty, /// Attribute nodes, for elements. attributes: std.ArrayList(NodeId) = .empty, /// The namespace declarations written on this element. What is *in scope* /// is this list plus those of every ancestor, which `namespaceNodes` /// walks; storing only what was written keeps a deep document from /// costing O(depth) per element. ns_decls: []const NsDecl = &.{}, name: Name = .{}, /// Attribute value, text content, comment content, PI data, or the URI a /// namespace node is bound to. value: []const u8 = "", /// Position in document order, assigned by `reindex`. Comparing these is /// how `<<` is decided and how a node-set is sorted. order: u32 = 0, /// Cached result of `namespaceNodes`, so that the namespace axis has /// stable node identity across evaluations. ns_nodes: ?[]const NodeId = null, /// Set on an attribute node whose value came from an `<!ATTLIST>` default /// rather than from the start tag. /// /// The distinction is the document type's, not the element's, and it is /// invisible once the value is in the tree -- which is exactly why it is /// worth recording: a tree that cannot tell the two apart cannot write /// back out the document it read. defaulted: bool = false, /// Set on a text node whose content the serializer writes through /// untouched, escaping nothing. /// /// It is a property of the node because the decision is made when the node /// is built and acted on much later, by which time whatever made it is /// gone. XSLT's `disable-output-escaping` is the motivating case; so is /// splicing in a fragment of markup that is already correct. verbatim: bool = false,};
/// Hands each document a serial number so that nodes in different trees have/// a stable order. XPath requires only that such an order exist and be/// consistent within an evaluation; it says nothing about what it is.var document_serial: std.atomic.Value(u32) = .init(0);
/// A reference to one node of one document.////// A node-set is not confined to a single tree: `document()` loads another,/// and a result tree fragment converted to a node-set is a third. So a node/// is identified by which document it is in as well as by its index, and/// nothing may assume two `NodeId`s belong to the same tree.pub const NodeRef = struct { doc: *Document, id: NodeId,
pub fn get(r: NodeRef) *const Node { return r.doc.node(r.id); }
pub fn kind(r: NodeRef) Kind { return r.get().kind; }
pub fn name(r: NodeRef) Name { return r.get().name; }
pub fn eql(a: NodeRef, b: NodeRef) bool { return a.doc == b.doc and a.id == b.id; }
/// A total order over every node of every document: document order within /// a tree, and the trees themselves in the order they were created. pub fn before(a: NodeRef, b: NodeRef) bool { if (a.doc != b.doc) return a.doc.serial < b.doc.serial; return a.get().order < b.get().order; }
pub fn lessThan(_: void, a: NodeRef, b: NodeRef) bool { return a.before(b); }
pub fn parent(r: NodeRef) ?NodeRef { const p = r.get().parent orelse return null; return .{ .doc = r.doc, .id = p }; }
pub fn stringValue(r: NodeRef, gpa: Allocator) ![]u8 { return r.doc.stringValue(gpa, r.id); }};
/// A parsed document, or one under construction.////// Every string reachable from a node belongs to `arena`, including the ones/// copied out of the source text, so the source may be freed as soon as/// parsing returns and the whole tree frees at once.pub const Document = struct { gpa: Allocator, arena: std.heap.ArenaAllocator, nodes: std.ArrayList(Node), /// The `/` node. Always node 0. root: NodeId, /// What `document('')` and relative URI resolution would resolve against. /// Empty when the document did not come from a file. base_uri: []const u8 = "", /// Distinguishes this tree from every other, so that a node-set spanning /// documents still has a total order. serial: u32, /// The `<!DOCTYPE>` declaration verbatim, without `<!DOCTYPE` and `>`, or /// null when the document had none or was parsed without `.dtd`. /// Copied into the arena like everything else in the tree. doctype: ?[]const u8 = null, /// What that declaration declared, when `ParseOptions.dtd` asked for it to /// be read. Its slices borrow from `doctype`, which is in the arena, so it /// stays valid for the life of the document even after the source text is /// freed. dtd: ?xml.Dtd = null,
/// A document holding nothing but its root node. /// /// Returned by pointer because an `ArenaAllocator` hands out an allocator /// that points back into it, so a `Document` must not be moved once /// anything has allocated from it. pub fn create(gpa: Allocator) !*Document { const doc = try gpa.create(Document); errdefer gpa.destroy(doc); doc.* = .{ .gpa = gpa, .arena = .init(gpa), .nodes = .empty, .root = 0, .serial = document_serial.fetchAdd(1, .monotonic), }; errdefer doc.arena.deinit(); _ = try doc.addNode(.{ .kind = .document }); return doc; }
pub fn destroy(doc: *Document) void { const gpa = doc.gpa; // The declarations index the arena but are not allocated from it. if (doc.dtd) |*d| d.deinit(); for (doc.nodes.items) |*n| { n.children.deinit(gpa); n.attributes.deinit(gpa); } doc.nodes.deinit(gpa); doc.arena.deinit(); gpa.destroy(doc); }
/// The allocator every string in the tree comes from. pub fn alloc(doc: *Document) Allocator { return doc.arena.allocator(); }
pub fn node(doc: *const Document, id: NodeId) *const Node { return &doc.nodes.items[id]; }
pub fn nodeMut(doc: *Document, id: NodeId) *Node { return &doc.nodes.items[id]; }
/// A reference to one of this document's nodes. pub fn ref(doc: *Document, id: NodeId) NodeRef { return .{ .doc = doc, .id = id }; }
fn addNode(doc: *Document, n: Node) !NodeId { const id: NodeId = @intCast(doc.nodes.items.len); try doc.nodes.append(doc.gpa, n); return id; }
// -- building ------------------------------------------------------------
/// Appends an element to `parent` and returns it. The name's strings are /// copied into the document. pub fn appendElement(doc: *Document, parent: NodeId, name: Name) !NodeId { const a = doc.alloc(); const id = try doc.addNode(.{ .kind = .element, .parent = parent, .name = .{ .uri = try a.dupe(u8, name.uri), .local = try a.dupe(u8, name.local), .prefix = try a.dupe(u8, name.prefix), }, }); try doc.nodeMut(parent).children.append(doc.gpa, id); return id; }
/// Sets an attribute on an element, replacing any attribute with the same /// expanded name. Replacement rather than duplication is what XSLT /// requires of `xsl:attribute`, and it is what makes a literal result /// element's attributes overridable by an `xsl:attribute` that follows. pub fn setAttribute(doc: *Document, elem: NodeId, name: Name, value: []const u8) !NodeId { const a = doc.alloc(); for (doc.node(elem).attributes.items) |existing| { if (doc.node(existing).name.eql(name)) { const n = doc.nodeMut(existing); n.value = try a.dupe(u8, value); n.name.prefix = try a.dupe(u8, name.prefix); return existing; } } const id = try doc.addNode(.{ .kind = .attribute, .parent = elem, .name = .{ .uri = try a.dupe(u8, name.uri), .local = try a.dupe(u8, name.local), .prefix = try a.dupe(u8, name.prefix), }, .value = try a.dupe(u8, value), }); try doc.nodeMut(elem).attributes.append(doc.gpa, id); return id; }
/// Appends character data, merging with the preceding sibling when that is /// also a text node. /// /// The merge is not an optimisation. The data model has no notion of /// adjacent text nodes, so `<a>x<!--c-->y</a>` has two text children but /// `<a>x&y</a>` has one, and a transformation that emits text in two /// instructions must produce one node or `text()[2]` would find something /// that is not there. pub fn appendText(doc: *Document, parent: NodeId, text: []const u8) !?NodeId { if (text.len == 0) return null; const a = doc.alloc(); const kids = doc.node(parent).children.items; if (kids.len > 0) { const last = kids[kids.len - 1]; if (doc.node(last).kind == .text) { const n = doc.nodeMut(last); n.value = try std.mem.concat(a, u8, &.{ n.value, text }); return last; } } const id = try doc.addNode(.{ .kind = .text, .parent = parent, .value = try a.dupe(u8, text), }); try doc.nodeMut(parent).children.append(doc.gpa, id); return id; }
/// Appends a text node the serializer writes through untouched. /// /// Deliberately never merged with a neighbour: escaped and unescaped text /// are written differently, so a run of each has to stay its own node. pub fn appendVerbatimText(doc: *Document, parent: NodeId, text: []const u8) !NodeId { const id = try doc.addNode(.{ .kind = .text, .parent = parent, .value = try doc.alloc().dupe(u8, text), .verbatim = true, }); try doc.nodeMut(parent).children.append(doc.gpa, id); return id; }
pub fn appendComment(doc: *Document, parent: NodeId, text: []const u8) !NodeId { const id = try doc.addNode(.{ .kind = .comment, .parent = parent, .value = try doc.alloc().dupe(u8, text), }); try doc.nodeMut(parent).children.append(doc.gpa, id); return id; }
pub fn appendPi(doc: *Document, parent: NodeId, target: []const u8, data: []const u8) !NodeId { const a = doc.alloc(); const id = try doc.addNode(.{ .kind = .pi, .parent = parent, .name = .{ .local = try a.dupe(u8, target) }, .value = try a.dupe(u8, data), }); try doc.nodeMut(parent).children.append(doc.gpa, id); return id; }
/// Detaches a child from its parent. Used by whitespace stripping, which /// is the one thing that takes nodes back out of a tree once it is built. /// /// The node itself stays in `nodes` -- nothing may shift, because a /// `NodeId` is an index -- so this leaks a node's worth of arena until the /// document is destroyed. Stripping runs once over a stylesheet or a /// source document, so that is a bounded and deliberate cost. pub fn removeChild(doc: *Document, parent: NodeId, child: NodeId) void { const kids = &doc.nodeMut(parent).children; const at = std.mem.findScalar(NodeId, kids.items, child) orelse return; _ = kids.orderedRemove(at); doc.nodeMut(child).parent = null; }
/// Records `xmlns` declarations on an element. Used by the parser, and by /// the transformer when a literal result element carries them. pub fn setNsDecls(doc: *Document, elem: NodeId, decls: []const NsDecl) !void { const a = doc.alloc(); const copy = try a.alloc(NsDecl, decls.len); for (decls, copy) |src, *dst| { dst.* = .{ .prefix = try a.dupe(u8, src.prefix), .uri = try a.dupe(u8, src.uri), }; } doc.nodeMut(elem).ns_decls = copy; }
/// Adds one `xmlns` declaration to an element, replacing whatever that /// prefix was declared as on this element before. /// /// `setNsDecls` replaces the whole list, which is what a parser wants and /// what a literal result element wants. Copying a *namespace node* -- /// XSLT's `xsl:copy` on one, or `xsl:copy-of` selecting the namespace axis /// -- adds a single declaration to an element that already exists, and has /// no business disturbing the rest. pub fn addNsDecl(doc: *Document, elem: NodeId, prefix: []const u8, uri: []const u8) !void { const a = doc.alloc(); const existing = doc.node(elem).ns_decls; for (existing) |d| { if (std.mem.eql(u8, d.prefix, prefix)) { // Same prefix, same URI: nothing to record. if (std.mem.eql(u8, d.uri, uri)) return; break; } }
var out = try a.alloc(NsDecl, existing.len + 1); var n: usize = 0; for (existing) |d| { if (std.mem.eql(u8, d.prefix, prefix)) continue; out[n] = d; n += 1; } out[n] = .{ .prefix = try a.dupe(u8, prefix), .uri = try a.dupe(u8, uri) }; n += 1; doc.nodeMut(elem).ns_decls = out[0..n]; }
/// Assigns `order` by a pre-order walk, which is document order: an /// element precedes its namespace nodes, which precede its attributes, /// which precede its children. /// /// Called once when parsing finishes and again whenever a result tree is /// about to be looked at as a node-set, because nodes created while /// building one are not always created in the order they end up in. pub fn reindex(doc: *Document) void { var counter: u32 = 0; doc.reindexFrom(doc.root, &counter); }
fn reindexFrom(doc: *Document, id: NodeId, counter: *u32) void { doc.nodeMut(id).order = counter.*; counter.* += 1; // A namespace node's order only matters relative to the attributes of // the same element, and only when the namespace axis has been asked // for, so they are numbered here if they exist and skipped if not. if (doc.node(id).ns_nodes) |ns| { for (ns) |n| { doc.nodeMut(n).order = counter.*; counter.* += 1; } } for (doc.node(id).attributes.items) |a| { doc.nodeMut(a).order = counter.*; counter.* += 1; } // `children` may grow while a result tree is being built, but not // during a reindex, so taking the slice once is safe. const kids = doc.node(id).children.items; for (kids) |c| doc.reindexFrom(c, counter); }
// -- reading -------------------------------------------------------------
/// The document element: the one element child of the root. pub fn documentElement(doc: *const Document) ?NodeId { for (doc.node(doc.root).children.items) |c| { if (doc.node(c).kind == .element) return c; } return null; }
/// Appends a node's string-value, as XPath defines it: for an element or /// the root, the text of every text node below it, in document order; for /// everything else, the node's own content. pub fn appendStringValue(doc: *const Document, out: *std.ArrayList(u8), gpa: Allocator, id: NodeId) !void { const n = doc.node(id); switch (n.kind) { .document, .element => try doc.appendDescendantText(out, gpa, id), .text, .attribute, .comment, .pi, .namespace => try out.appendSlice(gpa, n.value), } }
/// The text of every text node below `id`. Comments and processing /// instructions contribute nothing here even though each has a /// string-value of its own, which is the difference between the /// string-value of an element and everything written inside it. fn appendDescendantText(doc: *const Document, out: *std.ArrayList(u8), gpa: Allocator, id: NodeId) !void { for (doc.node(id).children.items) |c| { switch (doc.node(c).kind) { .text => try out.appendSlice(gpa, doc.node(c).value), .element => try doc.appendDescendantText(out, gpa, c), else => {}, } } }
/// The string-value of a node, allocated with `gpa`. pub fn stringValue(doc: *const Document, gpa: Allocator, id: NodeId) ![]u8 { const n = doc.node(id); // The common case is a node that already holds its whole string, and // for those there is nothing to concatenate. switch (n.kind) { .text, .attribute, .comment, .pi, .namespace => return gpa.dupe(u8, n.value), else => {}, } var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa); try doc.appendStringValue(&out, gpa, id); return out.toOwnedSlice(gpa); }
/// The value of the attribute with this expanded name, or null. pub fn attributeValue(doc: *const Document, elem: NodeId, uri: []const u8, local: []const u8) ?[]const u8 { for (doc.node(elem).attributes.items) |a| { if (doc.node(a).name.is(uri, local)) return doc.node(a).value; } return null; }
/// The URI a prefix resolves to at this node, following the declarations /// on it and then on each ancestor. An empty prefix asks for the default /// namespace. pub fn lookupNamespace(doc: *const Document, from: NodeId, prefix: []const u8) ?[]const u8 { if (std.mem.eql(u8, prefix, "xml")) return xml_ns; if (std.mem.eql(u8, prefix, "xmlns")) return xmlns_ns; var cur: ?NodeId = from; while (cur) |id| : (cur = doc.node(id).parent) { for (doc.node(id).ns_decls) |d| { if (std.mem.eql(u8, d.prefix, prefix)) { // `xmlns=""` undeclares rather than binding to the empty // string, so a match with no URI means "not in scope". return if (d.uri.len == 0) null else d.uri; } } } return null; }
/// A prefix that is bound to this URI at this node, preferring the one /// declared closest. Used by the serializer to write a name back out. pub fn lookupPrefix(doc: *const Document, from: NodeId, uri: []const u8) ?[]const u8 { var cur: ?NodeId = from; while (cur) |id| : (cur = doc.node(id).parent) { for (doc.node(id).ns_decls) |d| { if (std.mem.eql(u8, d.uri, uri)) { // Only if nothing nearer has shadowed that prefix. if (doc.lookupNamespace(from, d.prefix)) |bound| { if (std.mem.eql(u8, bound, uri)) return d.prefix; } } } } return null; }
/// The namespace nodes in scope on an element, materialized on first use /// and cached so that the axis has stable identity. /// /// An in-scope declaration from an ancestor is a namespace node of *this* /// element with this element as its parent, which is why they cannot /// simply be the `ns_decls` of wherever they were written. pub fn namespaceNodes(doc: *Document, elem: NodeId) ![]const NodeId { if (doc.node(elem).ns_nodes) |cached| return cached;
var ids: std.ArrayList(NodeId) = .empty; defer ids.deinit(doc.gpa); var seen: std.StringHashMapUnmanaged(void) = .empty; defer seen.deinit(doc.gpa);
// `xml` is in scope everywhere without being declared. try seen.put(doc.gpa, "xml", {}); const xml_node = try doc.addNode(.{ .kind = .namespace, .parent = elem, .name = .{ .local = "xml" }, .value = xml_ns, }); try ids.append(doc.gpa, xml_node);
var cur: ?NodeId = elem; while (cur) |id| : (cur = doc.node(id).parent) { for (doc.node(id).ns_decls) |d| { // Nearest declaration of a prefix wins, and one that has // already been seen further down has already won. if (seen.contains(d.prefix)) continue; try seen.put(doc.gpa, d.prefix, {}); // An undeclaration puts nothing in scope, but it does stop // an ancestor's declaration of the same prefix. if (d.uri.len == 0) continue; const nsid = try doc.addNode(.{ .kind = .namespace, .parent = elem, .name = .{ .local = d.prefix }, .value = d.uri, }); try ids.append(doc.gpa, nsid); } }
// XPath 1.0 5.4 leaves the order of namespace nodes among themselves // implementation-dependent, and libxml2's is this list reversed: it // gathers the same nearest-first walk and then iterates it backwards, // so an ancestor's declarations come first and each element's come out // in reverse document order. Following it costs nothing -- no // conforming document can depend on the order -- and means a // transformation that walks `namespace::*` writes what xsltproc // writes. The implicit `xml` node stays at the front, which is also // where libxml2 puts it. std.mem.reverse(NodeId, ids.items[1..]);
const owned = try doc.alloc().dupe(NodeId, ids.items); doc.nodeMut(elem).ns_nodes = owned; // These nodes did not exist when the document was numbered, so they // carry no document order at all -- which puts every one of them in // front of the document element. `reindexFrom` numbers an element's // namespace nodes when it finds them, so numbering the document again // is what gives them a place. It is a walk of the whole document per // element whose namespace axis is asked for, which is affordable // because that axis is rare and unaffordable to get wrong: XPath // compares these nodes by order, and an order of zero makes a // namespace node precede everything. doc.reindex(); return owned; }};
// -- parsing -----------------------------------------------------------------
pub const ParseError = error{ /// A prefix was used that nothing in scope declares. UnboundPrefix, /// `xmlns:foo=""` — a prefixed declaration may not be empty. EmptyPrefixedNamespace, /// The document has no element, or more than one at the top level. MalformedDocument,} || xml.Error || Allocator.Error;
/// How a parse should treat whitespace-only text nodes.pub const WhitespaceMode = enum { /// Keep every text node. What a source document gets, since /// `xsl:strip-space` is applied afterwards against the stylesheet's list. preserve, /// Drop text nodes that are entirely whitespace, unless an enclosing /// element carries `xml:space="preserve"`. What a stylesheet gets, so that /// the indentation a stylesheet is written with does not become output. strip,};
pub const ParseOptions = struct { whitespace: WhitespaceMode = .preserve, /// Read the internal subset of the document type. /// /// Off by default because it changes what the tree says: the general /// entities the subset declares resolve, and the attribute defaults it /// gives arrive as attribute nodes the start tag never wrote. With it on, /// `Document.dtd` holds the declarations and `validate` can be run against /// them. Nothing external is fetched either way. dtd: bool = false, /// What to do with an entity reference the parser does not define. The /// default matches libxslt, which treats an undefined entity as an error. entities: xml.EntityPolicy = .strict, base_uri: []const u8 = "",};
/// Builds a tree from XML text.////// The source is read once and not referenced afterwards: every string that/// ends up in the tree is copied into the document's arena, with entity/// references already resolved, so the caller may free `src` immediately.pub fn parse(gpa: Allocator, src: []const u8, options: ParseOptions) ParseError!*Document { // A document declaring ISO 8859-1 is turned into the UTF-8 that says the // same thing before anything looks at it. It is the one encoding besides // UTF-8 that can be converted with no table -- its 256 characters are the // first 256 of Unicode -- and it is common enough in older stylesheets // that reading its bytes as UTF-8 is a real failure rather than a // theoretical one: `ü` becomes an invalid sequence, and whatever is done // with it afterwards is wrong in some way. Anything else declaring an // encoding that is not UTF-8 is read as UTF-8 and will not come out right; // saying so is better than pretending otherwise. const decoded: ?[]u8 = if (isLatin1(declaredEncoding(src))) try latin1ToUtf8(gpa, src) else null; defer if (decoded) |d| gpa.free(d); const source = decoded orelse src;
const doc = try Document.create(gpa); errdefer doc.destroy(); doc.base_uri = try doc.alloc().dupe(u8, options.base_uri);
var p: Parser = .{ .doc = doc, .gpa = gpa, .options = options, .reader = if (options.dtd) .initDtd(gpa, source, .{}) else .init(source), }; defer p.deinit(); try p.run();
doc.reindex(); return doc;}
/// The `encoding` pseudo-attribute of the XML declaration, if there is one.////// This is a look at the first few bytes rather than a parse: the declaration/// has to be read before it is known what the rest of the document is encoded/// in, which is exactly why it is restricted to ASCII.fn declaredEncoding(src: []const u8) ?[]const u8 { if (!std.mem.startsWith(u8, src, "<?xml")) return null; const end = std.mem.indexOf(u8, src, "?>") orelse return null; const decl = src[0..end]; const at = std.mem.indexOf(u8, decl, "encoding") orelse return null; var rest = decl[at + "encoding".len ..]; while (rest.len != 0 and (rest[0] == ' ' or rest[0] == '\t')) rest = rest[1..]; if (rest.len == 0 or rest[0] != '=') return null; rest = rest[1..]; while (rest.len != 0 and (rest[0] == ' ' or rest[0] == '\t')) rest = rest[1..]; if (rest.len == 0) return null; const quote = rest[0]; if (quote != '"' and quote != '\'') return null; rest = rest[1..]; const close = std.mem.indexOfScalar(u8, rest, quote) orelse return null; return rest[0..close];}
fn isLatin1(encoding: ?[]const u8) bool { const name = encoding orelse return false; for ([_][]const u8{ "iso-8859-1", "iso8859-1", "iso_8859-1", "latin1", "latin-1", "l1", "cp819", "iso-ir-100", }) |n| { if (std.ascii.eqlIgnoreCase(name, n)) return true; } return false;}
fn latin1ToUtf8(gpa: Allocator, src: []const u8) Allocator.Error![]u8 { var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa); try out.ensureTotalCapacity(gpa, src.len); for (src) |c| { if (c < 0x80) { try out.append(gpa, c); } else { try out.append(gpa, 0xC0 | (c >> 6)); try out.append(gpa, 0x80 | (c & 0x3F)); } } return out.toOwnedSlice(gpa);}
const Parser = struct { doc: *Document, gpa: Allocator, options: ParseOptions, reader: xml.Reader, /// The open elements, innermost last. open: std.ArrayList(NodeId) = .empty, /// Character data seen since the last non-character event, waiting to be /// turned into one text node. pending: std.ArrayList(u8) = .empty, /// True when the pending run contains a CDATA section, which is never /// whitespace to be stripped even if it looks like it. pending_literal: bool = false,
fn deinit(p: *Parser) void { p.open.deinit(p.gpa); p.pending.deinit(p.gpa); // The reader's own copy of the declarations borrows from `src`. The // document keeps a second copy that borrows from its arena instead, // which is what lets the source be freed the moment parsing returns. p.reader.deinit(); }
fn current(p: *Parser) NodeId { if (p.open.items.len == 0) return p.doc.root; return p.open.items[p.open.items.len - 1]; }
fn run(p: *Parser) ParseError!void { while (true) { const event = try p.reader.next(); switch (event) { .eof => { try p.flushText(); break; }, .declaration => {}, .doctype => |verbatim| try p.doctype(verbatim), .text => |raw| { try p.appendRaw(raw); }, .cdata => |literal| { try p.pending.appendSlice(p.gpa, literal); p.pending_literal = true; }, .comment => |text| { try p.flushText(); _ = try p.doc.appendComment(p.current(), text); }, .pi => |pi| { try p.flushText(); _ = try p.doc.appendPi(p.current(), pi.target, pi.data); }, .start_element => |e| try p.startElement(e), .end_element => { try p.flushText(); _ = p.open.pop(); }, } } if (p.doc.documentElement() == null) return error.MalformedDocument; }
fn appendRaw(p: *Parser, raw: []const u8) ParseError!void { if (!xml.needsDecode(raw, .text)) { try p.pending.appendSlice(p.gpa, raw); return; } try xml.decodeAppend(p.gpa, &p.pending, raw, p.entities(), .text); }
/// Turns the accumulated character data into a text node, if there is any /// and if it survives whitespace stripping. fn flushText(p: *Parser) ParseError!void { defer { p.pending.clearRetainingCapacity(); p.pending_literal = false; } if (p.pending.items.len == 0) return; // Text outside the document element is not part of the tree, and // whitespace there is legal prolog padding rather than an error. if (p.open.items.len == 0) return; if (p.options.whitespace == .strip and !p.pending_literal and xml.isWhitespace(p.pending.items) and !p.preservingSpace()) { return; } _ = try p.doc.appendText(p.current(), p.pending.items); }
/// True when the innermost `xml:space` in scope says `preserve`. fn preservingSpace(p: *Parser) bool { var i = p.open.items.len; while (i > 0) { i -= 1; const elem = p.open.items[i]; if (p.doc.attributeValue(elem, xml_ns, "space")) |v| { return std.mem.eql(u8, v, "preserve"); } } return false; }
fn startElement(p: *Parser, e: xml.Element) ParseError!void { try p.flushText();
const a = p.doc.alloc();
// Namespace declarations first: an element may use a prefix it // declares on itself, so the scope has to exist before the element's // own name is resolved. var decls: std.ArrayList(NsDecl) = .empty; defer decls.deinit(p.gpa); for (e.attributes) |attr| { const decl: NsDecl = if (std.mem.eql(u8, attr.name, "xmlns")) .{ .prefix = "", .uri = try p.decodeAttr(a, attr.raw_value) } else if (attr.prefix()) |pfx| blk: { if (!std.mem.eql(u8, pfx, "xmlns")) continue; const uri = try p.decodeAttr(a, attr.raw_value); // Undeclaring a prefix is XML Namespaces 1.1; in 1.0 it is // simply not allowed, and libxslt rejects it too. if (uri.len == 0) return error.EmptyPrefixedNamespace; break :blk .{ .prefix = try a.dupe(u8, attr.localName()), .uri = uri }; } else continue; try decls.append(p.gpa, decl); }
const parent = p.current(); const id = try p.doc.addNode(.{ .kind = .element, .parent = parent, }); try p.doc.nodeMut(parent).children.append(p.gpa, id); try p.doc.setNsDecls(id, decls.items); try p.open.append(p.gpa, id);
p.doc.nodeMut(id).name = try p.resolveName(id, e.name, .element);
for (e.attributes) |attr| { if (std.mem.eql(u8, attr.name, "xmlns")) continue; if (attr.prefix()) |pfx| { if (std.mem.eql(u8, pfx, "xmlns")) continue; } const name = try p.resolveName(id, attr.name, .attribute); const value = try p.decodeAttr(a, attr.raw_value); const attr_id = try p.doc.setAttribute(id, name, value); p.doc.nodeMut(attr_id).defaulted = attr.defaulted; } }
const NameUse = enum { element, attribute };
/// Splits a qualified name and resolves its prefix. /// /// Nothing here checks the shape of the name. zxml rejects a name a /// namespace cannot read -- `<:/>`, `<a:/>`, `<a:b:c/>` -- before it ever /// reports one, so by the time a name arrives here it has a prefix and a /// local part or neither, and `localNameOf` and `prefixOf` can be trusted. fn resolveName(p: *Parser, scope: NodeId, qname: []const u8, use: NameUse) ParseError!Name { const a = p.doc.alloc(); const local = xml.localNameOf(qname); const prefix = xml.prefixOf(qname) orelse { // An unprefixed attribute is in no namespace: the default // declaration applies to element names only. const uri = switch (use) { .element => p.doc.lookupNamespace(scope, "") orelse "", .attribute => "", }; return .{ .uri = try a.dupe(u8, uri), .local = try a.dupe(u8, local), }; }; const uri = p.doc.lookupNamespace(scope, prefix) orelse return error.UnboundPrefix; return .{ .uri = try a.dupe(u8, uri), .local = try a.dupe(u8, local), .prefix = try a.dupe(u8, prefix), }; }
/// Decodes an attribute value into the document's arena. /// /// `.attribute` is the whole of it: that is the normalization XML requires /// of an attribute value, and asking for it is how this stops being the /// caller's problem. Doing it here by hand -- as this did, before zxml /// knew the difference -- meant replacing whitespace *before* decoding, so /// that a ` ` survived where a typed newline did not. fn decodeAttr(p: *Parser, a: Allocator, raw: []const u8) ParseError![]const u8 { return xml.decodeAlloc(a, raw, p.entities(), .attribute); }
/// The entity policy the options asked for, plus whatever the document /// declared for itself. fn entities(p: *const Parser) xml.EntityPolicy { return p.reader.entityPolicy(p.options.entities); }
/// Keeps the document type declaration, and reads it a second time so /// that what the document keeps borrows from the arena rather than from /// the source text. fn doctype(p: *Parser, verbatim: []const u8) ParseError!void { // Without the option nothing is kept and nothing is read, so a parse // that does not ask for the declarations behaves exactly as it did // before there were any. if (!p.options.dtd) return; // Only the first: a second document type declaration is not something // XML allows, and reading it would leak the first. if (p.doc.doctype != null) return; const kept = try p.doc.alloc().dupe(u8, verbatim); p.doc.doctype = kept; p.doc.dtd = try xml.Dtd.parse(p.gpa, kept); }};
// -- tests -------------------------------------------------------------------
const testing = std.testing;
test "a document declaring ISO 8859-1 is decoded, not read as UTF-8" { // The source is one byte per character, and `0xFC` is not a UTF-8 // sequence at all -- read as one it is either an error or a mess. Decoded, // it is `ü`, and what the tree holds is the two bytes UTF-8 spells it // with. const src = "<?xml version=\"1.0\" encoding='iso-8859-1'?><a t=\"Gr\xfc\xdf\">Fahrvergn\xfcgen</a>"; const doc = try parse(testing.allocator, src, .{}); defer doc.destroy();
const a = doc.documentElement().?; try testing.expectEqualStrings("Fahrvergn\u{00fc}gen", doc.node(doc.node(a).children.items[0]).value); try testing.expectEqualStrings("Gr\u{00fc}\u{00df}", doc.attributeValue(a, "", "t").?);}
test "a namespace node takes a place in document order" { // They are materialized on demand, long after the document was numbered, // so without renumbering they all carry order zero -- which would put a // namespace node in front of the document element. const gpa = testing.allocator; const doc = try parse(gpa, "<r xmlns:a=\"urn:a\"><c/></r>", .{}); defer doc.destroy(); const r = doc.documentElement().?; const c = doc.node(r).children.items[0];
const ns = try doc.namespaceNodes(r); try testing.expect(ns.len == 2); for (ns) |n| { try testing.expect(doc.node(n).order > doc.node(r).order); try testing.expect(doc.node(n).order < doc.node(c).order); }}
test "parses a tree with parents and document order" { const doc = try parse(testing.allocator, "<a><b>x</b><c/></a>", .{}); defer doc.destroy();
const a = doc.documentElement().?; try testing.expectEqualStrings("a", doc.node(a).name.local); try testing.expectEqual(@as(usize, 2), doc.node(a).children.items.len);
const b = doc.node(a).children.items[0]; const c = doc.node(a).children.items[1]; try testing.expectEqualStrings("b", doc.node(b).name.local); try testing.expectEqual(a, doc.node(b).parent.?); // Document order is what makes `b` precede `c`. try testing.expect(doc.node(b).order < doc.node(c).order);}
test "string-value concatenates descendant text" { const doc = try parse(testing.allocator, "<a>one<b>two</b><!--c-->three</a>", .{}); defer doc.destroy(); const s = try doc.stringValue(testing.allocator, doc.documentElement().?); defer testing.allocator.free(s); // The comment contributes nothing, which is what distinguishes a // string-value from the document's text. try testing.expectEqualStrings("onetwothree", s);}
test "adjacent character data becomes one text node" { const doc = try parse(testing.allocator, "<a>x&y<![CDATA[z]]></a>", .{}); defer doc.destroy(); const a = doc.documentElement().?; try testing.expectEqual(@as(usize, 1), doc.node(a).children.items.len); try testing.expectEqualStrings("x&yz", doc.node(doc.node(a).children.items[0]).value);}
test "a comment splits text into two nodes" { const doc = try parse(testing.allocator, "<a>x<!--c-->y</a>", .{}); defer doc.destroy(); const a = doc.documentElement().?; try testing.expectEqual(@as(usize, 3), doc.node(a).children.items.len);}
test "namespaces resolve against the nearest declaration" { const doc = try parse(testing.allocator, \\<r xmlns="urn:d" xmlns:p="urn:p"> \\ <p:x a="1" p:b="2"/> \\ <y xmlns="urn:e"/> \\</r> , .{}); defer doc.destroy();
const r = doc.documentElement().?; try testing.expectEqualStrings("urn:d", doc.node(r).name.uri);
var x: NodeId = 0; var y: NodeId = 0; for (doc.node(r).children.items) |c| { if (doc.node(c).kind != .element) continue; if (std.mem.eql(u8, doc.node(c).name.local, "x")) x = c else y = c; } try testing.expectEqualStrings("urn:p", doc.node(x).name.uri); // A redeclared default namespace applies to the element that carries it. try testing.expectEqualStrings("urn:e", doc.node(y).name.uri);
// An unprefixed attribute is in no namespace even under a default // declaration; a prefixed one is in its prefix's. try testing.expectEqualStrings("1", doc.attributeValue(x, "", "a").?); try testing.expectEqualStrings("2", doc.attributeValue(x, "urn:p", "b").?);}
test "an unbound prefix is an error" { try testing.expectError(error.UnboundPrefix, parse(testing.allocator, "<p:a/>", .{}));}
test "a name that is not a name is rejected rather than written back out" { // Each of these has a colon and no usable name on one side of it. zxml // rejects them now, so this asserts that the rejection reaches a caller of // `parse` rather than that this module does the checking -- the reason it // matters is unchanged, and it is why the check was worth pushing // upstream: a tree holding one of these would serialize to something that // no longer parses. for ([_][]const u8{ "<:/>", "<a:/>", "<:a/>", "<a:b:c/>", "<a xmlns=\"urn:x\"><:/></a>", "<a :=\"1\"/>", "<a b:=\"1\"/>", }) |src| { const result = parse(testing.allocator, src, .{}); if (result) |doc| { doc.destroy(); std.debug.print("accepted a malformed name: {s}\n", .{src}); return error.TestUnexpectedResult; } else |err| { try testing.expect(err == error.InvalidName); } }}
test "attribute values are normalized but character references are not" { // The rule lives in zxml; this pins the behaviour a tree depends on, since // an attribute value that kept its literal tabs would compare unequal to // the same value written on one line. const doc = try parse(testing.allocator, "<a b=\"one\ttwo	three\"/>", .{}); defer doc.destroy(); const a = doc.documentElement().?; try testing.expectEqualStrings("one two\tthree", doc.attributeValue(a, "", "b").?);}
test "stripping removes whitespace-only text but xml:space keeps it" { const doc = try parse(testing.allocator, \\<r> \\ <a/> \\ <b xml:space="preserve"> </b> \\</r> , .{ .whitespace = .strip }); defer doc.destroy();
const r = doc.documentElement().?; try testing.expectEqual(@as(usize, 2), doc.node(r).children.items.len);
const b = doc.node(r).children.items[1]; try testing.expectEqual(@as(usize, 1), doc.node(b).children.items.len);}
test "the namespace axis sees inherited declarations" { const doc = try parse(testing.allocator, "<r xmlns:p=\"urn:p\"><c xmlns:q=\"urn:q\"/></r>", .{}); defer doc.destroy();
const r = doc.documentElement().?; const c = doc.node(r).children.items[0]; const ns = try doc.namespaceNodes(c); // xml, q, and the inherited p. try testing.expectEqual(@as(usize, 3), ns.len);
var found_p = false; for (ns) |n| { if (std.mem.eql(u8, doc.node(n).name.local, "p")) { found_p = true; // Its parent is the element it is in scope on, not the one that // declared it. try testing.expectEqual(c, doc.node(n).parent.?); } } try testing.expect(found_p);}
test "reading the document type changes what the tree says" { const gpa = testing.allocator; const doc = try parse(gpa, \\<!DOCTYPE note [ \\<!ENTITY who "world"> \\<!ATTLIST note lang CDATA "en"> \\]> \\<note>hello &who;</note> , .{ .dtd = true }); defer doc.destroy();
const note = doc.documentElement().?; // The entity the document declared for itself resolved... const text = try doc.stringValue(gpa, note); defer gpa.free(text); try testing.expectEqualStrings("hello world", text);
// ...and the attribute it defaulted is on the element, marked as having // come from the document type rather than from the start tag. try testing.expectEqualStrings("en", doc.attributeValue(note, "", "lang").?); try testing.expect(doc.node(doc.node(note).attributes.items[0]).defaulted);
// The declaration itself is kept verbatim, and read. try testing.expect(std.mem.startsWith(u8, doc.doctype.?, "note [")); try testing.expectEqualStrings("note", doc.dtd.?.name);}
test "without the option the document type is inert, as it always was" { const gpa = testing.allocator; // `.strict` is the default entity policy, and an entity the parser does // not define is an error under it -- which is what a declared entity stops // being once the declarations are read. try testing.expectError(error.UnknownEntity, parse(gpa, \\<!DOCTYPE note [<!ENTITY who "world">]><note>hello &who;</note> , .{}));
const doc = try parse(gpa, \\<!DOCTYPE note [<!ATTLIST note lang CDATA "en">]><note/> , .{}); defer doc.destroy(); // No declarations were read, so nothing was applied and nothing is kept // to check against later. try testing.expectEqual(@as(usize, 0), doc.node(doc.documentElement().?).attributes.items.len); try testing.expect(doc.dtd == null); try testing.expect(doc.doctype == null);}
test "a document type may name a resource, and none is ever fetched" { const gpa = testing.allocator; const doc = try parse(gpa, \\<!DOCTYPE d [<!ENTITY passwd SYSTEM "file:///etc/passwd">]> \\<d>&passwd;</d> , .{ .dtd = true, .entities = .lenient }); defer doc.destroy();
// The reference survives as text: it was declared, it was not resolved, // and nothing opened the file it names. const text = try doc.stringValue(gpa, doc.documentElement().?); defer gpa.free(text); try testing.expectEqualStrings("&passwd;", text);
// Under the default policy it is refused outright rather than resolved to // nothing, which is the more useful answer for a document that meant it. try testing.expectError(error.ExternalEntityReference, parse(gpa, \\<!DOCTYPE d [<!ENTITY passwd SYSTEM "file:///etc/passwd">]><d>&passwd;</d> , .{ .dtd = true }));}