Something went wrong. Try again.
An XML document tree and serializer for Zig 0.16, built on zxml.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Turning a result tree into bytes, by one of the three output methods XSLT//! defines.//!//! The result of a transformation is a tree, not a string, and a good deal of//! what "the output" looks like is decided here rather than by the stylesheet://! whether an empty element is `<br>` or `<br/>`, whether the text inside//! `<script>` is escaped, whether there is an XML declaration at all. Those are//! what `xsl:output` selects between.//!//! Namespaces are fixed up while writing rather than while building. A result//! element knows the namespace URI of its name, but a *prefix* is only//! meaningful against the declarations in scope at the point it is written --//! and the transformer may have copied an element out of a source document//! whose declarations are nowhere near. So the writer keeps its own scope//! stack and emits whatever declarations are missing, which is the only point//! at which the question has a definite answer.
const std = @import("std");const Allocator = std.mem.Allocator;const tree = @import("tree.zig");const Document = tree.Document;const NodeId = tree.NodeId;const Writer = std.Io.Writer;
pub const Method = enum { xml, html, text };
/// The namespace an XHTML document's elements are in.const xhtml_ns = "http://www.w3.org/1999/xhtml";
/// The `xsl:output` settings that affect serialization.pub const Output = struct { method: ?Method = null, version: []const u8 = "1.0", /// Written into the declaration only when the stylesheet asked for one. /// Leaving it out means UTF-8, which is what the output is, and is what /// libxslt does -- so a stylesheet that says nothing about encoding gets /// the same first line from both. encoding: ?[]const u8 = null, omit_xml_declaration: bool = false, standalone: ?bool = null, doctype_public: ?[]const u8 = null, doctype_system: ?[]const u8 = null, /// Null means the method's own default, which is not the same for both: /// XSLT asks for no indenting from the XML method and for indenting from /// the HTML one. indent: ?bool = null, /// Elements whose text children are written as CDATA sections. cdata_section_elements: []const tree.Name = &.{},
/// The method actually used, applying the rule that a result whose /// document element is `html` in no namespace defaults to the HTML method /// rather than the XML one. /// Whether to indent *elements*, applying the per-method default. pub fn effectiveIndent(o: Output, method: Method) bool { return o.indent orelse (method == .html); }
/// Whether a newline follows a comment, and the last child, at the /// document level. /// /// For the XML method `indent` has three states and they are not two. /// Leaving it unspecified gives these newlines without indenting any /// element; asking for `indent="no"` suppresses them as well, so that the /// output is one line with nothing after it; `indent="yes"` gives both. /// /// The HTML method does not play along: it terminates its document with a /// newline whatever `indent` says. pub fn documentNewlines(o: Output, method: Method) bool { return switch (method) { .html => true, .text => false, .xml => o.indent orelse true, }; }
pub fn effectiveMethod(o: Output, doc: *const Document) Method { if (o.method) |m| return m; const root_elem = doc.documentElement() orelse return .xml; const name = doc.node(root_elem).name; if (name.uri.len == 0 and std.ascii.eqlIgnoreCase(name.local, "html")) return .html; return .xml; }};
pub const Error = Writer.Error || Allocator.Error;
/// Writes a whole document.pub fn write(gpa: Allocator, w: *Writer, doc: *const Document, output: Output) Error!void { const method = output.effectiveMethod(doc); var s: Serializer = .{ .gpa = gpa, .w = w, .doc = doc, .output = output, .method = method, .indenting = output.effectiveIndent(method), .document_newlines = output.documentNewlines(method), // The `text` method has no syntax for a character reference, so it is // left as UTF-8 whatever was declared and the encoding is the caller's // problem. .charset = if (method == .text) .utf8 else Charset.of(output.encoding), .xhtml = method == .xml and isXhtml(output.doctype_public, output.doctype_system), }; // The `xml` prefix is bound everywhere without being declared, so it is // seeded into the scope rather than left to be discovered. Without this a // name in that namespace finds nothing in scope and the writer invents // `xmlns:xml="http://www.w3.org/XML/1998/namespace"`, which is legal and // which nothing else emits -- an `xml:lang` attribute would drag the // declaration along behind it. try s.scope.append(gpa, .{ .prefix = "xml", .uri = tree.xml_ns }); defer s.deinit(); try s.writeDocument();}
/// The same, into a caller-owned buffer.pub fn toOwnedSlice(gpa: Allocator, doc: *const Document, output: Output) Error![]u8 { var aw: Writer.Allocating = .init(gpa); defer aw.deinit(); try write(gpa, &aw.writer, doc, output); return aw.toOwnedSlice();}
/// The document type declarations of XHTML 1.0, by which libxslt recognizes/// that an XML document is meant to be read as HTML as well -- and gives it the/// character encoding declaration an HTML reader looks for. The set is/// libxslt's: the strict, transitional and frameset flavours and nothing else.fn isXhtml(public: ?[]const u8, system: ?[]const u8) bool { if (public) |id| { for ([_][]const u8{ "-//W3C//DTD XHTML 1.0 Strict//EN", "-//W3C//DTD XHTML 1.0 Transitional//EN", "-//W3C//DTD XHTML 1.0 Frameset//EN", }) |known| { if (std.mem.eql(u8, id, known)) return true; } return false; } const id = system orelse return false; for ([_][]const u8{ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd", }) |known| { if (std.mem.eql(u8, id, known)) return true; } return false;}
/// How much of Unicode the declared encoding can carry.////// Nothing here is a transcoder. Two cases can be served without being one:/// UTF-8, which is what the bytes already are, and ISO 8859-1, whose 256 code/// points are the first 256 of Unicode and so are one `@intCast` away. Every/// other encoding is treated as ASCII, and anything above it is written as a/// numeric character reference -- which is representable in all of them, and/// is a truthful document rather than bytes no reader of that declaration/// could interpret./// What the two escapers need to know: which method's rules apply, and what/// the declared encoding can carry.pub const Escaping = struct { method: Method, charset: Charset,};
pub const Charset = enum { utf8, latin1, ascii,
fn of(encoding: ?[]const u8) Charset { const name = encoding orelse return .utf8; for ([_][]const u8{ "utf-8", "utf8" }) |n| { if (std.ascii.eqlIgnoreCase(name, n)) return .utf8; } 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 .latin1; } return .ascii; }};
const Binding = struct { prefix: []const u8, uri: []const u8,};
const Serializer = struct { gpa: Allocator, w: *Writer, doc: *const Document, output: Output, method: Method, /// Namespace declarations currently in scope, innermost last. scope: std.ArrayList(Binding) = .empty, depth: usize = 0, /// Counter for invented prefixes, so that two different namespaces needing /// one do not both get `ns_1`. generated: usize = 0, /// The invented names, which the scope stack points at until the document /// is written and which are freed with the serializer. generated_prefixes: std.ArrayList([]u8) = .empty, /// What the declared encoding can carry, which decides whether a /// character outside ASCII is written as bytes or as a reference. charset: Charset = .utf8, /// Resolved once rather than per element. indenting: bool = false, /// True inside an element that is not indentable, which suppresses /// indenting for everything below it as well as around its own children. indent_suppressed: bool = false, /// True for the XML method writing a document whose type declaration is /// one of XHTML 1.0's, which libxslt serializes with some of the HTML /// method's habits. xhtml: bool = false, /// Whether the document level gets newlines at all. document_newlines: bool = false, /// The `<head>` a character encoding declaration was inserted into, which /// changes how that element's end tag is laid out. meta_head: ?NodeId = null,
fn deinit(s: *Serializer) void { for (s.generated_prefixes.items) |name| s.gpa.free(name); s.generated_prefixes.deinit(s.gpa); s.scope.deinit(s.gpa); }
fn writeDocument(s: *Serializer) Error!void { if (s.method == .text) { // The text method writes the text nodes and nothing else -- no // markup, no escaping, not even for the characters that would need // it in XML. try s.writeTextDescendants(s.doc.root); return; }
if (s.method == .xml and !s.output.omit_xml_declaration) { try s.w.print("<?xml version=\"{s}\"", .{s.output.version}); if (s.output.encoding) |enc| try s.w.print(" encoding=\"{s}\"", .{enc}); if (s.output.standalone) |sa| { try s.w.print(" standalone=\"{s}\"", .{if (sa) "yes" else "no"}); } try s.w.writeAll("?>\n"); }
try s.writeDoctype();
// A newline follows a child of the document when that child is a // comment, or when it is the last one. Nothing else gets one. // // The asymmetry is libxml2's and is worth stating because it is not // guessable: `<!--c--><root/>` comes out with a newline between them // and `<?pi?><root/>` does not, while `<root/><!--c-->` has none after // the element. Writing one after *every* child -- which this did, // briefly, to fix a missing trailing newline -- is right for the // common shapes and wrong for a prolog. const children = s.doc.node(s.doc.root).children.items; for (children, 0..) |c, i| { try s.writeNode(c); if (!s.document_newlines) continue; const last = i + 1 == children.len; if (last or s.doc.node(c).kind == .comment) try s.w.writeAll("\n"); } }
fn writeDoctype(s: *Serializer) Error!void { const public = s.output.doctype_public; const system = s.output.doctype_system; // HTML 5's document type declaration names no identifier at all, so // `version="5"` is the only thing that asks for it -- and asking for // it with a public or system identifier as well means something else // was wanted. const html5 = s.method == .html and std.mem.eql(u8, s.output.version, "5") and public == null and system == null; if (public == null and system == null and !html5) return; const root_elem = s.doc.documentElement() orelse return; const name = s.doc.node(root_elem).name;
try s.w.writeAll("<!DOCTYPE "); try s.writeQualifiedName(name, false); if (public) |p| { try s.w.print(" PUBLIC \"{s}\"", .{p}); if (system) |sys| try s.w.print(" \"{s}\"", .{sys}); } else if (system) |sys| { try s.w.print(" SYSTEM \"{s}\"", .{sys}); } try s.w.writeAll(">\n"); }
fn writeTextDescendants(s: *Serializer, id: NodeId) Error!void { const n = s.doc.node(id); switch (n.kind) { .text => try s.w.writeAll(n.value), .document, .element => { for (n.children.items) |c| try s.writeTextDescendants(c); }, else => {}, } }
fn writeNode(s: *Serializer, id: NodeId) Error!void { const n = s.doc.node(id); switch (n.kind) { .element => try s.writeElement(id), .text => try s.writeTextNode(id), .comment => { try s.w.writeAll("<!--"); try s.w.writeAll(n.value); try s.w.writeAll("-->"); }, .pi => { try s.w.print("<?{s}", .{n.name.local}); if (n.value.len != 0) try s.w.print(" {s}", .{n.value}); // HTML has no `?>`: a processing instruction ends at `>`. try s.w.writeAll(if (s.method == .html) ">" else "?>"); }, // Attributes and namespace nodes are written by their element, and // the root has already been handled. .document, .attribute, .namespace => {}, } }
fn writeTextNode(s: *Serializer, id: NodeId) Error!void { const n = s.doc.node(id); if (n.verbatim) { try s.w.writeAll(n.value); return; } const parent = n.parent orelse { try escapeText(s.w, n.value, s.escaping()); return; }; if (s.method == .html) { if (htmlInfo(s.doc.node(parent).name, false)) |info| { if (info.raw_text) { // `<script>` and `<style>` hold character data that HTML // does not escape; escaping the `&&` in a script would // change what it means. try s.w.writeAll(n.value); return; } } } if (s.inCdataElement(parent)) { try writeCdata(s.w, n.value); return; } try escapeText(s.w, n.value, s.escaping()); }
fn inCdataElement(s: *Serializer, elem: NodeId) bool { const name = s.doc.node(elem).name; if (s.doc.node(elem).kind != .element) return false; for (s.output.cdata_section_elements) |want| { if (want.eql(name)) return true; } return false; }
fn writeElement(s: *Serializer, id: NodeId) Error!void { const n = s.doc.node(id); const scope_mark = s.scope.items.len; s.depth += 1; defer { s.depth -= 1; s.scope.shrinkRetainingCapacity(scope_mark); }
// The declarations the element itself carries go into scope first, so // that a prefix the source document used is reused rather than // reinvented. for (n.ns_decls) |d| { if (d.uri.len == 0) continue; try s.scope.append(s.gpa, .{ .prefix = d.prefix, .uri = d.uri }); }
// Then whatever the names in play still need. var pending: std.ArrayList(Binding) = .empty; defer pending.deinit(s.gpa); try s.ensureBinding(n.name, false, &pending); for (n.attributes.items) |a| { try s.ensureBinding(s.doc.node(a).name, true, &pending); }
// The XHTML method needs the table too, to know which empty elements // are written `<br />` and which `<p></p>`. const info: ?ElementInfo = if (s.method == .html) htmlInfo(n.name, false) else if (s.xhtml) htmlInfo(n.name, true) else null;
// Whether this is the `<head>` that gets a character encoding // declaration inserted into it. const add_meta = (s.method == .html or s.xhtml) and s.needsMetaCharset(id); if (add_meta) s.meta_head = id;
try s.w.writeAll("<"); try s.writeQualifiedName(n.name, false);
// XHTML asks for one declaration nobody wrote: libxml2 gives an // `html` document element in no namespace the XHTML namespace, on the // grounds that a document with an XHTML document type declaration and // an `html` root is XHTML whatever its author forgot to say. An // `html` already in a namespace keeps it, and a root by any other name // gets nothing. if (s.xhtml and s.doc.documentElement() == id and n.name.uri.len == 0 and std.ascii.eqlIgnoreCase(n.name.local, "html")) { // Written but deliberately *not* put in scope. Putting it there // would make every child in no namespace need an `xmlns=""` of // its own to say so, and libxslt writes none: the declaration is // a fix-up for a document that should have been XHTML all along, // not a claim about the tree it came from. try s.w.print(" xmlns=\"{s}\"", .{xhtml_ns}); }
// Declarations written on the element, then the ones just invented. for (n.ns_decls) |d| { if (d.prefix.len == 0) { try s.w.writeAll(" xmlns=\""); } else { // `xmlns:p=""` is not something XML 1.0 allows: a prefix // cannot be undeclared, only rebound. A declaration like that // reaches here from a namespace alias whose target is no // namespace, and writing it would make the output unreadable. if (d.uri.len == 0) continue; try s.w.print(" xmlns:{s}=\"", .{d.prefix}); } try escapeAttribute(s.w, d.uri, s.escaping()); try s.w.writeAll("\""); } for (pending.items) |b| { if (b.prefix.len == 0) { try s.w.writeAll(" xmlns=\""); } else { try s.w.print(" xmlns:{s}=\"", .{b.prefix}); } try escapeAttribute(s.w, b.uri, s.escaping()); try s.w.writeAll("\""); }
for (n.attributes.items) |a| try s.writeAttribute(a);
if (s.method == .html and info != null and info.?.empty) { // `<br/>` is not HTML: a void element has no end tag and no // slash, and anything inside it is dropped. try s.w.writeAll(">"); try s.writeSeparatorAfter(id, info); return; }
// XHTML splits the difference between the two methods, because its // output has to be read by an HTML parser as well as an XML one: a // void element is `<br />`, with the space an HTML parser needs in // front of a slash it does not understand, and everything else gets // both tags, because an HTML parser would not treat `<p/>` as empty. if (s.xhtml and n.children.items.len == 0 and !add_meta) { if (info != null and info.?.empty) { try s.w.writeAll(" />"); } else { try s.w.writeAll("></"); try s.writeQualifiedName(n.name, false); try s.w.writeAll(">"); } return; }
// An empty `<head>` still needs its encoding declaration. The HTML // method writes one in the branch below; the XHTML one is written // among the children, so that element takes the ordinary path. if (n.children.items.len == 0 and !(add_meta and s.xhtml)) { if (s.method == .html) { // HTML has no empty-element syntax at all, so even an element // with no content gets both tags. try s.w.writeAll(">"); if (add_meta) try s.writeMetaCharset(); try s.w.writeAll("</"); try s.writeQualifiedName(n.name, false); try s.w.writeAll(">"); try s.writeSeparatorAfter(id, info); } else { try s.w.writeAll("/>"); } return; }
try s.w.writeAll(">");
if (s.method == .html) { try s.writeHtmlChildren(id, info, add_meta); } else { try s.writeXmlChildren(id, add_meta); }
try s.w.writeAll("</"); try s.writeQualifiedName(n.name, false); try s.w.writeAll(">"); if (s.method == .html) try s.writeSeparatorAfter(id, info); }
fn writeXmlChildren(s: *Serializer, id: NodeId, add_meta: bool) Error!void { const n = s.doc.node(id); const suppressed = s.indent_suppressed or !s.indentable(id); const indenting = s.indenting and !suppressed; const saved = s.indent_suppressed; s.indent_suppressed = suppressed; defer s.indent_suppressed = saved;
if (add_meta) { if (indenting) { try s.w.writeAll("\n"); try s.writeIndent(s.depth); } try s.writeMetaContentType(); } for (n.children.items) |c| { if (indenting) { try s.w.writeAll("\n"); try s.writeIndent(s.depth); } try s.writeNode(c); } if (indenting) { try s.w.writeAll("\n"); try s.writeIndent(s.depth - 1); } }
/// HTML's idea of indenting, which is not the XML method's. /// /// There are no indentation spaces at all: the only thing inserted is a /// newline, and only in three places. An element gets one after its start /// tag and one before its end tag when it is a known block element with /// more than one child, none of them text; and one after itself when it /// has a following sibling that is not text. All three are skipped inside /// an element whose name begins with `p`. /// /// That last condition is libxml2's, and it is a coarse stand-in for "p, /// pre and param" that also catches `picture`. It is reproduced exactly /// rather than corrected, because the point of matching the reference /// implementation's whitespace is to match it. fn writeHtmlChildren(s: *Serializer, id: NodeId, info: ?ElementInfo, add_meta: bool) Error!void { const n = s.doc.node(id); const first_is_text = s.doc.node(n.children.items[0]).kind == .text; const last_is_text = s.doc.node(n.children.items[n.children.items.len - 1]).kind == .text; const several = n.children.items.len > 1;
if (s.indenting and (add_meta or (htmlBlock(info) and !first_is_text and several and !pInitial(n.name)))) { try s.w.writeAll("\n"); } if (add_meta) { try s.writeMetaCharset(); if (s.indenting and !first_is_text) try s.w.writeAll("\n"); }
for (n.children.items) |c| try s.writeNode(c);
// An inserted meta makes a one-child head into a two-child one, which // is why it counts here as well. if (s.indenting and htmlBlock(info) and !last_is_text and (several or id == s.meta_head) and !pInitial(n.name)) { try s.w.writeAll("\n"); } }
/// The newline that follows a block element when something that is not /// text comes after it. fn writeSeparatorAfter(s: *Serializer, id: NodeId, info: ?ElementInfo) Error!void { if (!s.indenting or !htmlBlock(info)) return; const next = s.nextSibling(id) orelse return; if (s.doc.node(next).kind == .text) return; const parent = s.doc.node(id).parent orelse return; if (s.doc.node(parent).kind != .element) return; if (pInitial(s.doc.node(parent).name)) return; try s.w.writeAll("\n"); }
/// A known HTML element that is not an inline one. An element HTML does /// not define is neither, and is never formatted. fn nextSibling(s: *Serializer, id: NodeId) ?NodeId { const parent = s.doc.node(id).parent orelse return null; const siblings = s.doc.node(parent).children.items; const at = std.mem.findScalar(NodeId, siblings, id) orelse return null; if (at + 1 >= siblings.len) return null; return siblings[at + 1]; }
/// Whether a `<head>` should have a character encoding declaration put /// into it: it must be the head of the document element, and must not /// already carry one. fn needsMetaCharset(s: *Serializer, id: NodeId) bool { if (s.meta_head != null) return false; const n = s.doc.node(id); // By local name, ignoring the namespace. libxml2 looks up its element // table only for a name in no namespace -- which is why `htmlInfo` // keeps that guard -- but compares the name directly here, so a // `<head>` in the REC-html40 namespace still gets the declaration. if (!std.ascii.eqlIgnoreCase(n.name.local, "head")) return false; const parent = n.parent orelse return false; const pn = s.doc.node(parent); if (pn.kind != .element or !std.ascii.eqlIgnoreCase(pn.name.local, "html")) return false; // The `<html>` must itself be the document element. const grandparent = pn.parent orelse return false; if (s.doc.node(grandparent).kind != .document) return false;
for (n.children.items) |c| { if (metaEncodingAttribute(s.doc, c) != null) return false; } return true; }
/// XHTML's character encoding declaration, which is HTML 4's rather than /// HTML 5's -- an XHTML document is meant to be readable by an HTML 4 /// parser, and `<meta charset>` is not. fn writeMetaContentType(s: *Serializer) Error!void { try s.w.writeAll("<meta http-equiv=\"Content-Type\" content=\"text/html; charset="); try escapeAttribute(s.w, s.output.encoding orelse "UTF-8", s.escaping()); try s.w.writeAll("\" />"); }
fn writeMetaCharset(s: *Serializer) Error!void { try s.w.writeAll("<meta charset=\""); try escapeAttribute(s.w, s.output.encoding orelse "UTF-8", s.escaping()); try s.w.writeAll("\">"); }
/// An element is indented only if it has no text children. Indenting /// mixed content would change it: the whitespace added between `<b>bold</b>` /// and the words around it is text that was not there before. /// Whether an element's children may be laid out on lines of their own. /// /// Not if any of them is text: the whitespace an indent inserts would be /// part of the content. That answer carries down the whole subtree rather /// than being asked again at each element, which is what libxml2 does -- /// once an element is found to hold text, nothing inside it is reformatted /// either, so a result whose root has whitespace copied in from its source /// comes out exactly as it was built. fn indentable(s: *Serializer, id: NodeId) bool { for (s.doc.node(id).children.items) |c| { if (s.doc.node(c).kind == .text) return false; } return true; }
fn writeIndent(s: *Serializer, levels: usize) Error!void { try s.w.splatBytesAll(" ", levels); }
fn writeAttribute(s: *Serializer, id: NodeId) Error!void { const n = s.doc.node(id); try s.w.writeAll(" "); try s.writeQualifiedName(n.name, true); // An HTML boolean attribute is written as a bare name. XSLT asks for // this explicitly, and a `checked="checked"` that survived would be // legal but is not what the method is for. if (s.method == .html and isBooleanAttribute(n.name) and (n.value.len == 0 or std.ascii.eqlIgnoreCase(n.value, n.name.local))) { return; } try s.w.writeAll("=\""); if (s.method == .html and s.isUriAttribute(id)) { try writeEscapedUri(s.w, n.value); } else { try escapeAttribute(s.w, n.value, s.escaping()); } try s.w.writeAll("\""); }
fn escaping(s: *const Serializer) Escaping { return .{ .method = s.method, .charset = s.charset }; }
/// Whether the HTML output method percent-escapes this attribute's value. /// /// The set is libxml2's, and it is short: `href`, `action`, `src`, and /// `name` when it is on an `a` element -- which is the anchor a fragment /// identifier points at, and so is a URI in everything but position. /// An attribute in a namespace is never one of them. fn isUriAttribute(s: *Serializer, id: NodeId) bool { const name = s.doc.node(id).name; if (name.uri.len != 0) return false; if (std.ascii.eqlIgnoreCase(name.local, "href")) return true; if (std.ascii.eqlIgnoreCase(name.local, "action")) return true; if (std.ascii.eqlIgnoreCase(name.local, "src")) return true; if (!std.ascii.eqlIgnoreCase(name.local, "name")) return false; const owner = s.doc.node(id).parent orelse return false; return std.ascii.eqlIgnoreCase(s.doc.node(owner).name.local, "a"); }
/// Writes a name with whatever prefix is bound to its namespace here. fn writeQualifiedName(s: *Serializer, name: tree.Name, is_attribute: bool) Error!void { if (name.uri.len == 0) { try s.w.writeAll(name.local); return; } if (s.prefixFor(name.uri, name.prefix, is_attribute)) |prefix| { if (prefix.len != 0) { try s.w.print("{s}:", .{prefix}); } } try s.w.writeAll(name.local); }
/// A prefix bound to `uri` in the current scope, preferring `preferred`. /// /// The default declaration is not an answer for an attribute. An /// unprefixed attribute is in no namespace however `xmlns` is bound -- so /// an attribute whose namespace happens to be the default one still has to /// be written with a prefix, and offering it the empty one here writes a /// name that reads back as something else. `ensureBinding` invents the /// prefix such an attribute needs; this is the half that then uses it. fn prefixFor( s: *Serializer, uri: []const u8, preferred: []const u8, is_attribute: bool, ) ?[]const u8 { // The preferred prefix wins if it is bound to the right URI. var i = s.scope.items.len; while (i > 0) { i -= 1; const b = s.scope.items[i]; if (is_attribute and b.prefix.len == 0) continue; if (std.mem.eql(u8, b.prefix, preferred) and std.mem.eql(u8, b.uri, uri)) { return b.prefix; } } i = s.scope.items.len; while (i > 0) { i -= 1; const b = s.scope.items[i]; if (is_attribute and b.prefix.len == 0) continue; if (!std.mem.eql(u8, b.uri, uri)) continue; // Only if nothing nearer has rebound that prefix to something else. if (s.boundTo(b.prefix)) |bound| { if (std.mem.eql(u8, bound, uri)) return b.prefix; } } return null; }
fn boundTo(s: *Serializer, prefix: []const u8) ?[]const u8 { var i = s.scope.items.len; while (i > 0) { i -= 1; if (std.mem.eql(u8, s.scope.items[i].prefix, prefix)) return s.scope.items[i].uri; } return null; }
/// Makes sure a name's namespace has a prefix here, inventing a /// declaration if it does not. fn ensureBinding( s: *Serializer, name: tree.Name, is_attribute: bool, pending: *std.ArrayList(Binding), ) Error!void { if (name.uri.len == 0) { // An unprefixed attribute is in no namespace whatever the default // declaration says, so only an element name can be shadowed by one. if (is_attribute) return; if (s.boundTo("")) |bound| { if (bound.len != 0) { const b: Binding = .{ .prefix = "", .uri = "" }; try s.scope.append(s.gpa, b); try pending.append(s.gpa, b); } } return; } if (s.prefixFor(name.uri, name.prefix, is_attribute)) |_| return;
// Reuse the name's own prefix when it is free, so that output keeps // looking like its input. var prefix = name.prefix; if (prefix.len == 0 and is_attribute) prefix = ""; if (prefix.len == 0 or s.boundTo(prefix) != null) { if (!(prefix.len == 0 and !is_attribute and s.boundTo("") == null)) { prefix = try s.generatePrefix(); } }
const b: Binding = .{ .prefix = prefix, .uri = name.uri }; try s.scope.append(s.gpa, b); try pending.append(s.gpa, b); }
/// Invents a prefix nothing in scope is using. /// /// The name has to outlive this call -- the scope stack holds it until the /// document is written -- so it is kept in `generated_prefixes` and freed /// with the serializer. It was simply leaked before, on the grounds that /// there are only ever a handful; a handful per document is still a leak, /// and a library has no business deciding its caller can afford one. fn generatePrefix(s: *Serializer) Error![]const u8 { while (true) { s.generated += 1; // `ns_1`, `ns_2`, ... is libxml2's spelling, and following it means // a document written here and the same document written by anything // built on libxml2 differ in nothing at all rather than in the // arbitrary part of a name. const candidate = try std.fmt.allocPrint(s.gpa, "ns_{d}", .{s.generated}); if (s.boundTo(candidate) == null) { errdefer s.gpa.free(candidate); try s.generated_prefixes.append(s.gpa, candidate); return candidate; } s.gpa.free(candidate); } }};
/// A known HTML element that is not an inline one. An element HTML does not/// define is neither, and is never formatted.fn htmlBlock(info: ?ElementInfo) bool { const i = info orelse return false; return !i.inline_;}
/// True when a name begins with `p`.////// libxml2 uses this as its test for "p, pre or param", the elements whose/// content must not have whitespace inserted into it. It also catches/// `picture` and anything else beginning with the letter, and that is/// reproduced here deliberately: the output is being matched, not the/// intention behind it.fn pInitial(name: tree.Name) bool { return name.local.len != 0 and (name.local[0] == 'p' or name.local[0] == 'P');}
/// The attribute of a `<meta>` element that carries a character encoding: a/// `charset`, or the `content` of a `<meta http-equiv="Content-Type">`.fn metaEncodingAttribute(doc: *const Document, elem: NodeId) ?NodeId { const n = doc.node(elem); if (n.kind != .element) return null; if (n.name.uri.len != 0 or !std.ascii.eqlIgnoreCase(n.name.local, "meta")) return null;
var content: ?NodeId = null; var is_content_type = false; for (n.attributes.items) |a| { const an = doc.node(a); if (an.name.uri.len != 0) continue; if (std.ascii.eqlIgnoreCase(an.name.local, "charset")) return a; if (std.ascii.eqlIgnoreCase(an.name.local, "content")) content = a; if (std.ascii.eqlIgnoreCase(an.name.local, "http-equiv") and std.ascii.eqlIgnoreCase(an.value, "Content-Type")) { is_content_type = true; } } return if (is_content_type) content else null;}
/// Escapes the characters that would otherwise be markup.////// `>` is escaped as well as `<` and `&`, which is not strictly required --/// a lone `>` is legal character data -- but is what every serializer does,/// because the one place it *is* required, `]]>`, is easy to miss.////// Nothing above ASCII is touched. There used to be a rule here turning a/// non-breaking space into ` ` for the HTML method, and it was wrong/// twice over: libxslt passes the character straight through, and the check/// compared a single byte against 0xA0 -- which in UTF-8 is never a character/// but a *continuation* byte, so `U+00A0` came out as an orphaned 0xC2/// followed by ` `. Output that is not valid UTF-8 is a worse failure/// than output that is merely unusual.pub fn escapeText(w: *Writer, text: []const u8, e: Escaping) Error!void { var i: usize = 0; while (i < text.len) { const c = text[i]; if (c >= 0x80 and e.charset != .utf8) { i += try writeNonAscii(w, text[i..], e.charset); continue; } i += 1; switch (c) { '<' => try w.writeAll("<"), '>' => try w.writeAll(">"), '&' => try w.writeAll("&"), // A carriage return has to be written as a reference or it does // not survive: a parser reading this back normalizes a literal CR // to a line feed, so writing one raw silently changes the // document. The only way a CR reaches here is a `
` that was // deliberately preserved, which makes losing it worse. '\r' => if (e.method == .xml) try w.writeAll(" ") else try w.writeByte(c), else => try w.writeByte(c), } }}
pub fn escapeAttribute(w: *Writer, text: []const u8, e: Escaping) Error!void { var i: usize = 0; while (i < text.len) { const c = text[i]; if (c >= 0x80 and e.charset != .utf8) { i += try writeNonAscii(w, text[i..], e.charset); continue; } i += 1; switch (c) { '<' => try w.writeAll("<"), '>' => try w.writeAll(">"), '&' => try w.writeAll("&"), '"' => try w.writeAll("""), // A literal newline or tab in an attribute value would be turned // into a space by any XML parser reading it back, so it has to be // written as a character reference to survive the round trip. HTML // does not normalize attribute values, so there is nothing to // survive and libxslt writes the character itself. '\n', '\r', '\t' => if (e.method == .xml) { try w.print("&#{d};", .{c}); } else { try w.writeByte(c); }, else => try w.writeByte(c), } }}
/// Writes the character at the front of `rest` in a charset that is not/// UTF-8, and answers how many bytes of it were consumed.////// A byte that is not the start of a well-formed sequence is written as a/// reference to itself and consumed on its own, which keeps a malformed input/// from either stalling the loop or swallowing what follows it.fn writeNonAscii(w: *Writer, rest: []const u8, charset: Charset) Error!usize { const cp = decodeOne(rest) orelse { try w.print("&#{d};", .{rest[0]}); return 1; }; if (charset == .latin1 and cp.value <= 0xFF) { try w.writeByte(@intCast(cp.value)); } else { try w.print("&#{d};", .{cp.value}); } return cp.len;}
fn decodeOne(rest: []const u8) ?struct { value: u21, len: usize } { const len = std.unicode.utf8ByteSequenceLength(rest[0]) catch return null; if (len > rest.len) return null; const value = std.unicode.utf8Decode(rest[0..len]) catch return null; return .{ .value = value, .len = len };}
/// Percent-escapes a URI-valued attribute for the HTML output method.////// XSLT 1.0 16.2 asks the HTML method to escape non-ASCII characters in URI/// attribute values the way HTML 4.0 B.2.1 recommends. libxml2 escapes rather/// more than that -- everything outside the unreserved set and a short list of/// URI punctuation -- so a space becomes `%20` as well. What it leaves alone/// includes `%` itself, so a value that was already escaped is not escaped/// twice, and `&`, which HTML allows unescaped in an attribute value.fn writeEscapedUri(w: *Writer, value: []const u8) Error!void { for (value) |c| { if (uriSafe(c)) { try w.writeByte(c); } else { try w.print("%{X:0>2}", .{c}); } }}
fn uriSafe(c: u8) bool { if (std.ascii.isAlphanumeric(c)) return true; return switch (c) { // The unreserved marks of RFC 2396. '-', '_', '.', '!', '~', '*', '\'', '(', ')' => true, // Punctuation a URI is made of, which escaping would destroy. '@', '/', ':', '=', '?', ';', '#', '%', '&', ',', '+' => true, else => false, };}
/// Writes text as one or more CDATA sections, splitting around any `]]>` the/// text contains -- which cannot appear inside one.fn writeCdata(w: *Writer, text: []const u8) Error!void { var rest = text; try w.writeAll("<![CDATA["); while (std.mem.indexOf(u8, rest, "]]>")) |i| { try w.writeAll(rest[0 .. i + 2]); try w.writeAll("]]><![CDATA["); rest = rest[i + 2 ..]; } try w.writeAll(rest); try w.writeAll("]]>");}
/// What the HTML output method needs to know about an element.////// The three flags and their values come from libxml2's `html40ElementTable`,/// read out of the source rather than recalled, because the whole of HTML/// serialization turns on them: `empty` decides whether there is an end tag,/// `inline_` decides where a newline may be inserted, and `raw_text` decides/// whether the content is escaped. An element that is not in this table gets/// none of the three, which is why an invented element is never formatted.pub const ElementInfo = struct { empty: bool, /// Named with a trailing underscore because `inline` is a keyword. inline_: bool, raw_text: bool,};
const html_elements = std.StaticStringMap(ElementInfo).initComptime(.{ .{ "a", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "abbr", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "acronym", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "address", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "applet", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "area", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "b", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "base", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "basefont", ElementInfo{ .empty = true, .inline_ = true, .raw_text = false } }, .{ "bdo", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "bgsound", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "big", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "blockquote", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "body", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "br", ElementInfo{ .empty = true, .inline_ = true, .raw_text = false } }, .{ "button", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "caption", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "center", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "cite", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "code", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "col", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "colgroup", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "dd", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "del", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "dfn", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "dir", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "div", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "dl", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "dt", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "em", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "embed", ElementInfo{ .empty = true, .inline_ = true, .raw_text = false } }, .{ "fieldset", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "font", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "form", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "frame", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "frameset", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "h1", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "h2", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "h3", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "h4", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "h5", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "h6", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "head", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "hr", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "html", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "i", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "iframe", ElementInfo{ .empty = false, .inline_ = true, .raw_text = true } }, .{ "img", ElementInfo{ .empty = true, .inline_ = true, .raw_text = false } }, .{ "input", ElementInfo{ .empty = true, .inline_ = true, .raw_text = false } }, .{ "ins", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "isindex", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "kbd", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "keygen", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "label", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "legend", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "li", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "link", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "map", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "menu", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "meta", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "noembed", ElementInfo{ .empty = false, .inline_ = false, .raw_text = true } }, .{ "noframes", ElementInfo{ .empty = false, .inline_ = false, .raw_text = true } }, .{ "noscript", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "object", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "ol", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "optgroup", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "option", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "p", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "param", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "plaintext", ElementInfo{ .empty = false, .inline_ = false, .raw_text = true } }, .{ "pre", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "q", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "s", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "samp", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "script", ElementInfo{ .empty = false, .inline_ = true, .raw_text = true } }, .{ "select", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "small", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "source", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "span", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "strike", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "strong", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "style", ElementInfo{ .empty = false, .inline_ = false, .raw_text = true } }, .{ "sub", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "sup", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "table", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "tbody", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "td", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "textarea", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "tfoot", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "th", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "thead", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "title", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "tr", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "track", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "tt", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "u", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "ul", ElementInfo{ .empty = false, .inline_ = false, .raw_text = false } }, .{ "var", ElementInfo{ .empty = false, .inline_ = true, .raw_text = false } }, .{ "wbr", ElementInfo{ .empty = true, .inline_ = false, .raw_text = false } }, .{ "xmp", ElementInfo{ .empty = false, .inline_ = true, .raw_text = true } },});
/// The HTML table entry for a name, or null when the element is not one HTML/// defines. Element names in HTML are case-insensitive, and a name in a/// namespace is not an HTML element at all./// What HTML says about an element of this name, or null when HTML says/// nothing.////// `namespaced` is for the XHTML output method, whose elements are in the/// XHTML namespace and are still `br` and `img`: libxml2 matches them by/// local name there, where for the HTML method it consults its table only for/// a name in no namespace.fn htmlInfo(name: tree.Name, namespaced: bool) ?ElementInfo { if (name.uri.len != 0 and !namespaced) return null; if (name.local.len > 32) return null; var lowered: [32]u8 = undefined; for (name.local, 0..) |c, i| lowered[i] = std.ascii.toLower(c); return html_elements.get(lowered[0..name.local.len]);}
fn isBooleanAttribute(name: tree.Name) bool { if (name.uri.len != 0) return false; const table = [_][]const u8{ "checked", "compact", "declare", "defer", "disabled", "ismap", "multiple", "nohref", "noresize", "noshade", "nowrap", "readonly", "selected", }; for (table) |t| { if (std.ascii.eqlIgnoreCase(name.local, t)) return true; } return false;}
// -- tests -------------------------------------------------------------------
const testing = std.testing;
fn roundTrip(gpa: Allocator, src: []const u8, output: Output) ![]u8 { const doc = try tree.parse(gpa, src, .{}); defer doc.destroy(); return toOwnedSlice(gpa, doc, output);}
fn expectOutput(expected: []const u8, src: []const u8, output: Output) !void { const got = try roundTrip(testing.allocator, src, output); defer testing.allocator.free(got); try testing.expectEqualStrings(expected, got);}
test "the xml method writes a declaration and empty-element tags" { try expectOutput( "<?xml version=\"1.0\"?>\n<a><b/></a>\n", "<a><b/></a>", .{ .method = .xml }, ); try expectOutput( "<a><b/></a>\n", "<a><b/></a>", .{ .method = .xml, .omit_xml_declaration = true }, );}
test "text is escaped and attributes more so" { try expectOutput( "<a t=\"<&" \"><&></a>\n", "<a t=\"<&" \"><&></a>", .{ .method = .xml, .omit_xml_declaration = true }, );}
test "the text method writes only text" { try expectOutput( "onetwo", "<a>one<b>two</b><!--c--></a>", .{ .method = .text }, );}
test "the html method knows which elements have no end tag" { // The newlines are the HTML method's indenting, which is on by default // and puts one after a block element's start tag and after each non-inline // child. `br` and `img` are inline, so nothing separates them from what // follows. try expectOutput( "<html><body>\n<br><p>hi</p>\n<img src=\"x\">\n</body></html>\n", "<html><body><br/><p>hi</p><img src=\"x\"/></body></html>", .{ .method = .html }, );}
test "html is the default method when the document element is html" { try expectOutput( "<html><br></html>\n", "<html><br/></html>", .{}, ); // And not otherwise. try expectOutput( "<?xml version=\"1.0\"?>\n<htmlish><br/></htmlish>\n", "<htmlish><br/></htmlish>", .{}, );}
test "html does not escape script content and minimizes boolean attributes" { try expectOutput( "<html>\n<script>if (a && b) x();</script><input checked>\n</html>\n", "<html><script>if (a && b) x();</script><input checked=\"checked\"/></html>", .{ .method = .html }, );}
test "indenting leaves mixed content alone" { try expectOutput( "<a>\n <b>\n <c/>\n </b>\n</a>\n", "<a><b><c/></b></a>", .{ .method = .xml, .omit_xml_declaration = true, .indent = true }, ); // `<a>` has a text child, so its children are written where they are. try expectOutput( "<a>one<b/></a>\n", "<a>one<b/></a>", .{ .method = .xml, .omit_xml_declaration = true, .indent = true }, );}
test "a doctype is written when asked for" { try expectOutput( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html><br></html>\n", "<html><br/></html>", .{ .method = .html, .doctype_public = "-//W3C//DTD HTML 4.01//EN", .doctype_system = "http://www.w3.org/TR/html4/strict.dtd", }, );}
test "a character above ASCII passes through whole" { // The bug this pins: `U+00A0` is 0xC2 0xA0 in UTF-8, and a serializer that // compares single bytes against 0xA0 splits it -- emitting the lead byte // and then an entity, which is not valid UTF-8 at all. try expectOutput( "<html><body>a\u{00A0}b \u{2014} \u{0451}</body></html>\n", "<html><body>a b — ё</body></html>", .{ .method = .html }, ); try expectOutput( "<a t=\"\u{00A0}\">\u{00A0}</a>\n", "<a t=\" \"> </a>", .{ .method = .xml, .omit_xml_declaration = true }, );}
test "an attribute never borrows the default declaration" { // `xmlns="urn:a"` puts elements in `urn:a` and attributes nowhere: an // unprefixed attribute name is in no namespace however the default is // bound. So an attribute that really is in `urn:a` cannot be written as // `attr=` -- it needs a prefix of its own, even though the element beside // it needs none. const gpa = testing.allocator; const doc = try tree.parse(gpa, "<r xmlns=\"urn:a\"/>", .{}); defer doc.destroy(); const r = doc.documentElement().?; _ = try doc.setAttribute(r, .{ .uri = "urn:a", .local = "attr" }, "1");
const out = try toOwnedSlice(gpa, doc, .{ .method = .xml, .omit_xml_declaration = true }); defer gpa.free(out); try testing.expectEqualStrings("<r xmlns=\"urn:a\" xmlns:ns_1=\"urn:a\" ns_1:attr=\"1\"/>\n", out);}
test "one namespace declaration can be added without disturbing the rest" { const gpa = testing.allocator; const doc = try tree.parse(gpa, "<r xmlns:a=\"urn:a\"/>", .{}); defer doc.destroy(); const r = doc.documentElement().?; try doc.addNsDecl(r, "b", "urn:b"); // A prefix already declared here is replaced rather than repeated. try doc.addNsDecl(r, "a", "urn:a2"); try doc.addNsDecl(r, "b", "urn:b");
const out = try toOwnedSlice(gpa, doc, .{ .method = .xml, .omit_xml_declaration = true }); defer gpa.free(out); try testing.expectEqualStrings("<r xmlns:b=\"urn:b\" xmlns:a=\"urn:a2\"/>\n", out);}
test "the HTML method escapes a URI attribute" { try expectOutput( "<a href=\"a%20b%20c\" title=\"a b c\">x</a>\n", "<a href='a b c' title='a b c'>x</a>", .{ .method = .html }, ); // `name` is a URI only on an anchor, and `%` is left alone so that a value // which was already escaped is not escaped twice. try expectOutput( "<a name=\"%D1%91\"></a>\n", "<a name='\u{0451}'/>", .{ .method = .html }, ); try expectOutput( "<meta name=\"a b\">\n", "<meta name='a b'/>", .{ .method = .html }, ); try expectOutput( "<a href=\"%20already%20%20escaped\">x</a>\n", "<a href=' already %20escaped'>x</a>", .{ .method = .html }, );}
test "an encoding that is not UTF-8 gets character references" { // Nothing here transcodes: the bytes written are always UTF-8. An encoding // that cannot carry a character is honoured by not writing one, since a // numeric reference says the same thing in every encoding a document is // likely to declare. try expectOutput( "<a t=\"ё\">ё—</a>", "<a t=\"\u{0451}\">\u{0451}\u{2014}</a>", .{ .method = .xml, .encoding = "ascii", .omit_xml_declaration = true, .indent = false }, ); // Spelled either way, UTF-8 passes through whole. try expectOutput( "<a>\u{0451}</a>", "<a>\u{0451}</a>", .{ .method = .xml, .encoding = "UTF8", .omit_xml_declaration = true, .indent = false }, ); // ISO 8859-1 is the one encoding that can be served without transcoding: // its 256 characters are the first 256 of Unicode, so `ü` is one byte. // Anything above that still needs a reference. try expectOutput( "<a>\xfcё</a>", "<a>\u{00fc}\u{0451}</a>", .{ .method = .xml, .encoding = "iso-8859-1", .omit_xml_declaration = true, .indent = false }, );}
test "the HTML method with version 5 writes the HTML 5 document type" { try expectOutput( "<!DOCTYPE html>\n<html></html>\n", "<html/>", .{ .method = .html, .version = "5" }, ); // Any other version, or a declaration that names an identifier, is left // to say what it says. try expectOutput("<html></html>\n", "<html/>", .{ .method = .html }); try expectOutput( "<!DOCTYPE html SYSTEM \"about:legacy-compat\">\n<html></html>\n", "<html/>", .{ .method = .html, .version = "5", .doctype_system = "about:legacy-compat" }, );}
test "the HTML method leaves a newline in an attribute alone" { // XML normalizes an attribute value, so a literal newline there has to be // written as a reference to survive a round trip. HTML normalizes nothing, // so there is nothing to survive. try expectOutput( "<a href=\"x\" title=\"a\nb\tc\">y</a>\n", "<a href='x' title='a b	c'>y</a>", .{ .method = .html }, ); try expectOutput( "<a title=\"a b	c\"/>", "<a title='a b	c'/>", .{ .method = .xml, .omit_xml_declaration = true, .indent = false }, );}
test "indenting stops for a whole subtree, not just one element" { // `r` holds text, so its children are written where they stand -- and so // are `a`'s, even though `a` holds nothing but elements. libxml2 turns // formatting off for the subtree of the element that holds the text, which // is what makes a result carrying whitespace copied from its source come // out as it was built. try expectOutput( "<r>x<a><b/><c/></a></r>\n", "<r>x<a><b/><c/></a></r>", .{ .method = .xml, .omit_xml_declaration = true, .indent = true }, ); try expectOutput( "<r>\n <a>\n <b/>\n </a>\n</r>\n", "<r><a><b/></a></r>", .{ .method = .xml, .omit_xml_declaration = true, .indent = true }, );}
test "an XHTML document gets the encoding declaration HTML 4 looks for" { const xhtml = "http://www.w3.org/1999/xhtml"; try expectOutput( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"x.dtd\">\n" ++ "<html xmlns=\"" ++ xhtml ++ "\">\n" ++ " <head>\n" ++ " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=US-ASCII\" />\n" ++ " <title>t</title>\n" ++ " </head>\n" ++ "</html>\n", "<html xmlns=\"" ++ xhtml ++ "\"><head><title>t</title></head></html>", .{ .method = .xml, .omit_xml_declaration = true, .indent = true, .encoding = "US-ASCII", .doctype_public = "-//W3C//DTD XHTML 1.0 Strict//EN", .doctype_system = "x.dtd", }, ); // XHTML writes a void element as `<br />` -- with the space an HTML // parser needs in front of a slash it does not understand -- and // everything else with both tags, because an HTML parser would not treat // `<p/>` as empty. The elements are in the XHTML namespace and are still // `br` and `img`, so the table is consulted by local name here. try expectOutput( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"x.dtd\">\n" ++ "<html xmlns=\"" ++ xhtml ++ "\"><body><br /><img src=\"x\" /><p></p><custom></custom></body></html>", "<html xmlns=\"" ++ xhtml ++ "\"><body><br/><img src=\"x\"/><p/><custom/></body></html>", .{ .method = .xml, .omit_xml_declaration = true, .indent = false, .doctype_public = "-//W3C//DTD XHTML 1.0 Strict//EN", .doctype_system = "x.dtd", }, );
// An `html` document element in no namespace is given the XHTML // namespace: a document with an XHTML document type declaration and an // `html` root is XHTML whatever its author forgot to say. A root by any // other name gets nothing, and one already in a namespace keeps it. try expectOutput( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"x.dtd\">\n" ++ "<html xmlns=\"" ++ xhtml ++ "\"><p></p></html>", "<html><p/></html>", .{ .method = .xml, .omit_xml_declaration = true, .indent = false, .doctype_public = "-//W3C//DTD XHTML 1.0 Strict//EN", .doctype_system = "x.dtd", }, ); try expectOutput( "<!DOCTYPE other PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"x.dtd\">\n" ++ "<other><inner></inner></other>", "<other><inner/></other>", .{ .method = .xml, .omit_xml_declaration = true, .indent = false, .doctype_public = "-//W3C//DTD XHTML 1.0 Strict//EN", .doctype_system = "x.dtd", }, );
// An empty `<head>` still gets one, by either method. try expectOutput( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"x.dtd\">\n" ++ "<html xmlns=\"" ++ xhtml ++ "\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head></html>", "<html xmlns=\"" ++ xhtml ++ "\"><head/></html>", .{ .method = .xml, .omit_xml_declaration = true, .indent = false, .doctype_public = "-//W3C//DTD XHTML 1.0 Strict//EN", .doctype_system = "x.dtd", }, ); try expectOutput( "<html><head><meta charset=\"UTF-8\"></head></html>\n", "<html><head/></html>", .{ .method = .html }, );
// A document type that is not XHTML's gets nothing inserted. try expectOutput( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"x.dtd\">\n" ++ "<html><head><title>t</title></head></html>", "<html><head><title>t</title></head></html>", .{ .method = .xml, .omit_xml_declaration = true, .indent = false, .doctype_public = "-//W3C//DTD HTML 4.01//EN", .doctype_system = "x.dtd", }, );}
test "a prefix is never undeclared" { // XML 1.0 has no way to undeclare a prefix -- only to rebind one -- so // `xmlns:p=""` is not something a reader can be given. A declaration like // that reaches the writer from a namespace alias whose target is no // namespace at all, and dropping it is the only answer that leaves the // output readable. The *default* namespace is the exception: `xmlns=""` // is legal and says the element is in no namespace. const gpa = testing.allocator; const doc = try tree.parse(gpa, "<r/>", .{}); defer doc.destroy(); const r = doc.documentElement().?; try doc.setNsDecls(r, &.{ .{ .prefix = "p", .uri = "" }, .{ .prefix = "q", .uri = "urn:q" }, });
const out = try toOwnedSlice(gpa, doc, .{ .method = .xml, .omit_xml_declaration = true }); defer gpa.free(out); try testing.expectEqualStrings("<r xmlns:q=\"urn:q\"/>\n", out);}
test "an invented namespace prefix is not leaked" { // The testing allocator fails this test on a leak, which is the whole // check: an attribute in a namespace nothing declares makes the writer // invent a prefix, and that name has to outlive the call that made it. const gpa = testing.allocator; const doc = try tree.parse(gpa, "<r/>", .{}); defer doc.destroy(); const r = doc.documentElement().?; _ = try doc.setAttribute(r, .{ .uri = "urn:a", .local = "x" }, "1"); _ = try doc.setAttribute(r, .{ .uri = "urn:b", .local = "y" }, "2");
const out = try toOwnedSlice(gpa, doc, .{ .method = .xml, .omit_xml_declaration = true }); defer gpa.free(out); try testing.expect(std.mem.indexOf(u8, out, "xmlns:ns_1=\"urn:a\"") != null); try testing.expect(std.mem.indexOf(u8, out, "xmlns:ns_2=\"urn:b\"") != null);}
test "a carriage return in text is written as a reference" { // It arrived as `
` and has to leave as one: a raw CR is normalized // back to a line feed by whatever reads the output. try expectOutput( "<doc> </doc>\n", "<doc>
</doc>", .{ .method = .xml, .omit_xml_declaration = true }, ); // A line feed is ordinary text and stays as it is. try expectOutput( "<doc>\n</doc>\n", "<doc>
</doc>", .{ .method = .xml, .omit_xml_declaration = true }, );}
test "the implicit xml prefix is never declared" { // `xml` is bound everywhere by the Namespaces specification, so an // `xml:lang` must not drag a declaration along behind it. Inventing one is // legal and nothing else does it. try expectOutput( "<a xml:lang=\"fr\"><b xml:space=\"preserve\">x</b></a>\n", "<a xml:lang=\"fr\"><b xml:space=\"preserve\">x</b></a>", .{ .method = .xml, .omit_xml_declaration = true }, );}
test "a newline follows a comment, and the last child, and nothing else" { const gpa = testing.allocator; const options: Output = .{ .method = .xml, .omit_xml_declaration = true };
// A result that is nothing but text still ends with a newline, which is // the case that matters most: it is every text-producing stylesheet. { const doc = try Document.create(gpa); defer doc.destroy(); _ = try doc.appendText(doc.root, "bare text"); const out = try toOwnedSlice(gpa, doc, options); defer gpa.free(out); try testing.expectEqualStrings("bare text\n", out); } // A comment in the prolog is followed by one; a processing instruction is // not, and neither is an element that is not last. try expectOutput("<!--c-->\n<a/>\n", "<!--c--><a/>", options); try expectOutput("<?pi d?><a/>\n", "<?pi d?><a/>", options); try expectOutput("<a/><!--c-->\n", "<a/><!--c-->", options); try expectOutput("<!--c-->\n<!--d-->\n<a/>\n", "<!--c--><!--d--><a/>", options);
// Asking for no indenting suppresses these too, which is a third state // and not the same as leaving it unspecified. const flat: Output = .{ .method = .xml, .omit_xml_declaration = true, .indent = false }; try expectOutput("<!--c--><a><b/></a>", "<!--c--><a><b/></a>", flat); try expectOutput("<a/>", "<a/>", flat);
// The HTML method ends its document with a newline whatever `indent` // says, which is the one place the three states collapse back to two. try expectOutput("<html><br></html>\n", "<html><br/></html>", .{ .method = .html, .indent = false });}
test "namespace declarations survive a round trip" { try expectOutput( "<r xmlns=\"urn:d\" xmlns:p=\"urn:p\"><p:x p:a=\"1\"/></r>\n", "<r xmlns=\"urn:d\" xmlns:p=\"urn:p\"><p:x p:a=\"1\"/></r>", .{ .method = .xml, .omit_xml_declaration = true }, );}
test "cdata-section-elements wrap text and split around a terminator" { const doc = try tree.parse(testing.allocator, "<a><raw>x]]>y</raw></a>", .{}); defer doc.destroy(); const out = try toOwnedSlice(testing.allocator, doc, .{ .method = .xml, .omit_xml_declaration = true, .cdata_section_elements = &.{.{ .local = "raw" }}, }); defer testing.allocator.free(out); try testing.expectEqualStrings("<a><raw><![CDATA[x]]]]><![CDATA[>y]]></raw></a>\n", out);}