// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The engine: running a stylesheet against a source document to build a //! result tree. //! //! XSLT's control flow is not the loop it looks like. `xsl:apply-templates` //! does not say what to do with the nodes it selects; it asks which template //! rule each node matches, and the answer depends on every rule in the //! stylesheet at once. So the centre of this file is `findRule`, which resolves //! that question in the order the specification lays down -- import precedence //! first, then priority, then whichever rule was written last -- and //! `builtInRule`, which is what happens when nothing matches and is the reason //! a stylesheet with one template still produces all the text in the document. //! //! Two kinds of "current" are deliberately kept apart. The *context node* is //! what `.` means and changes inside every predicate; the *current node* is //! what `current()` means and changes only when `xsl:for-each` or //! `xsl:apply-templates` moves it. In `item[@id = current()/@id]` the two are //! different nodes, which is the whole reason the function exists. //! //! Variables are a stack with a floor. A template body may see variables //! declared by its own preceding siblings and by its enclosing elements, but //! never those of whatever called it, so instantiating a template raises the //! floor and restores it afterwards. Without the floor a recursive template //! would see its own caller's bindings, which is the kind of bug that only //! shows up on the second level of recursion. const std = @import("std"); const Allocator = std.mem.Allocator; const tree = @import("ztree"); const xpath = @import("zxpath"); const value = @import("zxpath").value; const runtime = @import("runtime.zig"); const pattern = @import("pattern.zig"); const sheet_mod = @import("stylesheet.zig"); const exslt = @import("exslt.zig"); const regexp = @import("regexp.zig"); const date_mod = @import("date.zig"); const datetime = @import("datetime"); const collate = @import("collate"); const serialize = @import("ztree").serialize; const number = @import("number.zig"); const functions = @import("zxpath").functions; const Document = tree.Document; const NodeId = tree.NodeId; const NodeRef = tree.NodeRef; const Name = tree.Name; const Value = value.Value; const Evaluator = runtime.Evaluator; const Focus = xpath.Focus; const Error = runtime.Error; const Stylesheet = sheet_mod.Stylesheet; const xslt_ns = sheet_mod.xslt_ns; /// The namespace EXSLT's `node-set` lives in. Supported because a stylesheet /// that needs to look inside a result tree fragment has no other way to say /// so in XSLT 1.0, and because for this implementation it costs nothing: a /// fragment is already a tree. pub const exsl_ns = "http://exslt.org/common"; /// EXSLT's `functions` module. pub const func_ns = sheet_mod.func_ns; /// EXSLT's `dynamic` module, whose functions take an XPath expression as a /// string and evaluate it. pub const dyn_ns = "http://exslt.org/dynamic"; /// How deep `use-attribute-sets` may chain before it is called a circle. const max_attribute_set_depth = 64; /// Where a secondary result document goes. /// /// `exsl:document` is the one thing in a stylesheet that *writes*, and this /// library opens nothing: a `Loader` supplies what a transformation reads and /// a `Sink` takes what it produces, so what a stylesheet may touch stays the /// caller's decision at both ends. `Sink.none` refuses everything and is the /// default, which is what keeps an untrusted stylesheet off the filesystem -- /// it has nothing to reach it with. /// /// The document arrives serialized, because the output attributes on /// `exsl:document` are the stylesheet's business rather than the caller's: /// `method`, `indent`, `encoding` and the rest have been applied already, the /// same way `transformToString` applies `xsl:output` to the main result. /// /// `href` is the attribute as the stylesheet wrote it, resolved against /// nothing. A sink writing into a directory has to decide for itself what a /// relative reference means there and refuse what climbs out of it -- which /// it is in a position to do and this is not, since this knows of no /// directory to be relative to. pub const Sink = struct { ctx: ?*anyopaque = null, writeFn: *const fn (ctx: ?*anyopaque, href: []const u8, bytes: []const u8) Error!void, fn refuseWrite(_: ?*anyopaque, _: []const u8, _: []const u8) Error!void { return error.DocumentNotWritten; } /// A sink that refuses everything, which is the default. pub const none: Sink = .{ .writeFn = refuseWrite }; pub fn write(s: Sink, href: []const u8, bytes: []const u8) Error!void { return s.writeFn(s.ctx, href, bytes); } }; pub const Options = struct { loader: sheet_mod.Loader = .none, /// Where `exsl:document` writes. Refuses everything by default. sink: Sink = .none, /// How many instructions a transformation may instantiate before it is /// abandoned with `error.StepLimitExceeded`, or null for no limit. /// /// The recursion guard bounds *nesting* -- a template that calls itself /// is stopped at 128 frames. This bounds *work*, which is a different /// quantity: a stylesheet can loop sideways for as long as it likes /// without ever nesting deeply. /// /// Null by default, because a transformation a caller wrote itself should /// be allowed to take as long as it takes. What wants a limit is a /// harness running thousands of stylesheets nobody has read, where one /// that does not terminate takes every result after it with it. step_limit: ?u64 = null, /// Enter by calling this named template rather than by applying templates /// to the source root. /// /// XSLT 1.0 has only the one way in, so this is 2.0's -- and it is the /// way a large part of the W3C test suite is written, where a case has a /// stylesheet and an entry point rather than a document to match against. /// The template is called with no parameters. /// /// The context item is a separate question from this one, and 2.0 keeps /// them separate: entering at a named template does not by itself say /// what `.` is, and what decides is whether a source document was /// supplied at all. Saxon with `-it` and no source raises XPDY0002 for /// `count(//n)`; Saxon with `-it` and a source answers it. This function /// always has a source, so the source root is the current node -- which /// is the answer for the case it can express, and the reason it cannot /// yet express the other one is that `Focus.node` is not optional. That /// is XPath 2.0's change to make, not this one's. initial_template: ?Name = null, /// Apply templates to the source root in this mode rather than in the /// unnamed one. Ignored when `initial_template` is set, since a named /// template is not reached through a mode. initial_mode: ?Name = null, /// Values for the stylesheet's top-level `xsl:param`s. parameters: []const Parameter = &.{}, /// Where `xsl:message` goes. Messages are discarded when this is null. messages: ?*std.Io.Writer = null, /// Where EXSLT's `date:date-time()`, and the no-argument forms of the /// other date accessors, read the clock. /// /// Null means the transformation has no clock, and those functions then /// answer as they do for a date they cannot read: the empty string, or /// NaN. A transformation is otherwise a pure function of its inputs, and /// a caller that wants to keep it that way simply does not pass one. io: ?std.Io = null, /// How `xsl:sort` compares text. /// /// XSLT 1.0 section 10 leaves text ordering implementation-defined, so /// this is a choice rather than a requirement, and the default is /// `root_table`, the Unicode Collation Algorithm's root collation. That /// is a better default than code point order for every stylesheet /// whether or not it says which language its data is in: `Märtens` sorts /// before `Mueller` because the root collation gives ä the same primary /// weight as a, not because anybody asked for German. /// /// `non_ignorable` rather than the UCA's own `shifted` default, because /// `shifted` moves what it takes from punctuation to a fourth level that /// tertiary strength never reads -- so at the UCA's defaults `"a-b"` and /// `"ab"` compare equal, and two sort keys that differ only in /// punctuation would tie and fall back to document order. LDML defaults /// to `non_ignorable` for the same reason. A caller who wants punctuation /// ignored, or a different strength, passes one. collation: collate.Collator = .{ .table = root_table, .options = .{ .alternate = .non_ignorable } }, }; /// The root collation everything starts from: CLDR's when this build asked /// zig-collate for any tailorings, and DUCET's when it did not. /// /// The two are not interchangeable under a tailoring. CLDR writes its /// per-locale rules against its own root -- scripts regrouped, the variable /// band narrowed -- so a delta computed against that root and then laid over /// DUCET is being applied to a table it was not written for. `-Dlocales` /// therefore turns zig-collate's `-Dembed-cldr` on with it, and this is the /// other half of that: use the root the tailorings were resolved against. /// /// An unembedded `cldr_root` is the empty table rather than an error, which /// is what makes this a comptime test of the build rather than an option /// somebody has to pass twice. const root_table = if (collate.cldr_root.stage1.len != 0) collate.cldr_root else collate.ducet; pub const Parameter = struct { name: Name, /// Passed as a string, which is what a command line can supply. A /// stylesheet that wants a number will convert it, exactly as it would /// convert an attribute. value: []const u8, }; /// Runs a stylesheet and returns the result tree, which the caller owns. pub fn transform( gpa: Allocator, sheet: *Stylesheet, source: *Document, options: Options, ) Error!*Document { const result = try Document.create(gpa); errdefer result.destroy(); var t: Transformer = .{ .gpa = gpa, .sheet = sheet, .result = result, .options = options, .current = source.ref(source.root), .ev = .init(gpa), }; defer t.deinit(); t.ev.variables = .{ .ctx = &t, .lookupFn = Transformer.lookupVariable }; t.ev.extensions = .{ .ctx = &t, .callFn = Transformer.callFunction }; try t.stripSourceSpace(source); try t.prepareGlobals(source); const root = source.ref(source.root); if (options.initial_template) |name| { const template = t.findNamedTemplate(name) orelse { sheet.setDiagnostic("no template named {s}", .{name.local}); return error.InvalidStylesheet; }; t.current = root; try t.runNamedTemplate(template, &.{}, .{ .node = root }); } else { try t.applyToNode(root, options.initial_mode, 1, 1, std.math.maxInt(i32)); } result.reindex(); return result; } /// Runs a stylesheet and serializes the result with the `xsl:output` settings /// the stylesheet asked for. pub fn transformToString( gpa: Allocator, sheet: *Stylesheet, source: *Document, options: Options, ) Error![]u8 { const result = try transform(gpa, sheet, source, options); defer result.destroy(); return serialize.toOwnedSlice(gpa, result, sheet.output) catch |err| switch (err) { error.OutOfMemory => error.OutOfMemory, // An `Allocating` writer only fails by running out of memory. else => error.OutOfMemory, }; } const Binding = struct { name: Name, value: Value, /// True for a parameter handed over by `xsl:with-param` that the template /// being entered has not yet claimed with an `xsl:param`. /// /// XSLT 11.6 says passing a parameter to a template that declares no /// `xsl:param` for it is not an error -- the parameter is ignored. Ignored /// has to mean invisible: a binding left in place would shadow a global /// variable of the same name for the whole template. So the binding is /// made, skipped by every lookup, and turned into a real one by the /// `xsl:param` that claims it. pending: bool = false, }; /// A global variable and its value, which is computed the first time anything /// asks for it. const GlobalSlot = struct { decl: sheet_mod.GlobalVariable, value: ?Value = null, /// True while this variable's own expression is being evaluated, so that a /// variable defined in terms of itself is a message rather than a stack /// overflow. evaluating: bool = false, }; const LoadedDocument = struct { uri: []const u8, doc: *Document, }; /// A key's index over one document, built the first time that key is asked /// about and kept for the rest of the transformation. const KeyIndex = struct { name: Name, serial: u32, entries: std.StringHashMapUnmanaged(std.ArrayList(NodeRef)), }; const Transformer = struct { gpa: Allocator, sheet: *Stylesheet, result: *Document, options: Options, ev: Evaluator, /// Local variables, innermost last. `frame_base` is the floor a lookup /// stops at, which is what stops a template seeing its caller's. bindings: std.ArrayList(Binding) = .empty, frame_base: usize = 0, globals: std.ArrayList(GlobalSlot) = .empty, /// The focus a global variable's own expression is evaluated with: the /// root of the source document, which is what XSLT 11.4 says it is. global_focus: Focus = undefined, /// True while a result tree fragment is being built rather than the /// result tree itself, which is what stops a literal result element in one /// from dragging the stylesheet's namespace declarations in with it. building_fragment: bool = false, /// The value a `func:result` has set, while a `func:function` body is /// unwinding. /// /// EXSLT's `func:result` ends the function it is in, and there is no way /// to say that in Zig's control flow from the middle of a template body, /// so it is said with a flag: every loop over a template body stops when /// this is set, and the call that entered the function takes the value. func_result: ?Value = null, /// The stylesheet element whose expression is being evaluated, which is /// the namespace context a QName written *inside* one resolves against. /// /// `system-property('xsl:version')` passes its QName as a string, so the /// compiler never sees the prefix and cannot resolve it. The instruction /// that owns the expression is the only thing that knows what `xsl:` is /// bound to there. scope: ?struct { doc: *Document, node: NodeId } = null, /// Result tree fragments, and documents `document()` loaded. Both are /// owned for the life of the transformation because a variable may hold a /// node in either. fragments: std.ArrayList(*Document) = .empty, loaded: std.ArrayList(LoadedDocument) = .empty, keys: std.ArrayList(KeyIndex) = .empty, /// Scratch for building `xsl:sort` keys, kept across nodes so that /// sorting a node-set allocates the working buffers once rather than /// once per node. collator: collate.Builder = .empty, /// What `current()` returns: the node the innermost `xsl:for-each` or /// `xsl:apply-templates` selected, which is not what `.` means inside a /// predicate. current: NodeRef, /// Where instructions append. Moves as literal result elements are opened. output: NodeId = 0, /// The import precedence of the rule being instantiated, which is what /// `xsl:apply-imports` needs in order to look below it. precedence: i32 = std.math.maxInt(i32), /// Guards a template that instantiates itself without a base case. depth: u32 = 0, /// Instructions instantiated so far, counted only when `Options.step_limit` /// asks for it. steps: u64 = 0, /// Guards `xsl:attribute-set` definitions that use each other in a circle, /// which the specification forbids and a stylesheet can still contain. attribute_set_depth: u32 = 0, /// How many of the output element's attributes were already there when /// the current attribute set began, and are therefore stronger than /// anything it can contribute. Null outside an attribute set, where an /// `xsl:attribute` simply replaces. /// /// A count works because `setAttribute` replaces in place: an attribute /// written before the guard keeps its index, so index-below-guard is /// exactly "written by something stronger". attribute_guard: ?usize = null, /// A compiled `.`, kept for `xsl:sort` with no `select`. self_expr: ?*const xpath.Expr = null, /// The clock reading EXSLT's date functions use, taken the first time one /// of them asks for it. clock_reading: ?datetime.DateTime = null, fn deinit(t: *Transformer) void { const gpa = t.gpa; for (t.bindings.items) |b| b.value.deinit(gpa); t.bindings.deinit(gpa); for (t.globals.items) |slot| { if (slot.value) |v| v.deinit(gpa); } t.globals.deinit(gpa); for (t.fragments.items) |d| d.destroy(); t.fragments.deinit(gpa); for (t.loaded.items) |l| { gpa.free(l.uri); l.doc.destroy(); } t.loaded.deinit(gpa); for (t.keys.items) |*k| { var it = k.entries.iterator(); while (it.next()) |entry| { gpa.free(entry.key_ptr.*); entry.value_ptr.deinit(gpa); } k.entries.deinit(gpa); } t.keys.deinit(gpa); t.collator.deinit(gpa); } // -- whitespace ---------------------------------------------------------- /// Applies `xsl:strip-space` to the source document. /// /// Only whitespace-only text nodes are candidates, and `xml:space` on an /// ancestor overrides the stylesheet, which is why this cannot be folded /// into the parser: the rules come from a stylesheet the parser has never /// seen. fn stripSourceSpace(t: *Transformer, doc: *Document) Error!void { if (t.sheet.space_rules.items.len == 0) return; try t.stripUnder(doc, doc.root, false); } /// Strips the whitespace-only text children of one element, and recurses. /// /// The default is to **preserve**. `xsl:strip-space` names the elements /// whose whitespace is thrown away and everything else keeps it, which is /// the opposite of what a stylesheet's own whitespace gets. Having it the /// wrong way round means a stylesheet with a single narrow `strip-space` /// silently loses the spacing of the whole document. /// /// Whether a text node is stripped depends on its **parent's** name, not /// on anything inherited: only `xml:space` is inherited, and it wins. fn stripUnder(t: *Transformer, doc: *Document, elem: NodeId, preserving: bool) Error!void { var preserve = preserving; if (doc.node(elem).kind == .element) { if (doc.attributeValue(elem, tree.xml_ns, "space")) |v| { preserve = std.mem.eql(u8, v, "preserve"); } } const strip_here = !preserve and doc.node(elem).kind == .element and (t.spaceRuleFor(doc.node(elem).name) orelse false); var i = doc.node(elem).children.items.len; while (i > 0) { i -= 1; const child = doc.node(elem).children.items[i]; switch (doc.node(child).kind) { .text => if (strip_here and isAllWhitespace(doc.node(child).value)) { doc.removeChild(elem, child); }, .element => try t.stripUnder(doc, child, preserve), else => {}, } } } /// Whether an element's children are stripped, by the most specific rule /// that names it. Null when no rule does, in which case the enclosing /// setting stands. fn spaceRuleFor(t: *Transformer, name: Name) ?bool { var best: ?sheet_mod.SpaceRule = null; for (t.sheet.space_rules.items) |rule| { if (rule.local) |local| { if (!std.mem.eql(u8, local, name.local)) continue; } if (rule.uri) |uri| { if (!std.mem.eql(u8, uri, name.uri)) continue; } // A rule with no URI and no local part is a bare `*`, which // matches an element in any namespace, so there is nothing left // to check. if (best == null or rule.priority >= best.?.priority) best = rule; } return if (best) |b| b.strip else null; } // -- variables ----------------------------------------------------------- /// Makes a slot for each global variable, without evaluating any of them. /// /// XSLT 11.4 says the order in which global variables are declared does /// not matter, so one may be defined in terms of another declared after /// it. Evaluating them in declaration order cannot do that: a forward /// reference finds nothing and comes back as `UnknownVariable`. So none is /// evaluated until something asks for it, which is also why a global /// nothing refers to is never evaluated at all. fn prepareGlobals(t: *Transformer, source: *Document) Error!void { t.global_focus = .{ .node = source.ref(source.root) }; for (t.sheet.globals.items, 0..) |g, i| { // Of two declarations of the same name, the one of higher import // precedence wins, and at equal precedence the one written last. // Imports are read before the stylesheet that imports them, so // taking the first declaration of a name would make an imported // variable override the importing stylesheet's own. if (outrankedGlobal(t.sheet.globals.items, i)) continue; try t.globals.append(t.gpa, .{ .decl = g }); } } /// True when another declaration of the same name beats this one. fn outrankedGlobal(globals: []const sheet_mod.GlobalVariable, index: usize) bool { const g = globals[index]; for (globals, 0..) |other, i| { if (i == index) continue; if (!other.name.eql(g.name)) continue; if (other.precedence > g.precedence) return true; if (other.precedence == g.precedence and i > index) return true; } return false; } fn suppliedParameter(t: *Transformer, name: Name) ?[]const u8 { for (t.options.parameters) |p| { if (p.name.eql(name)) return p.value; } return null; } /// The value of a global variable, evaluating it if this is the first time /// anybody asked. /// /// The returned value belongs to the slot and is borrowed, so a caller /// that keeps it clones it. /// /// A variable already being evaluated is one defined in terms of itself, /// which XSLT 11.4 makes an error. Saying so is better than the /// alternative, which is a stack overflow. fn findGlobal(t: *Transformer, name: Name) Error!?Value { const index = blk: { for (t.globals.items, 0..) |slot, i| { if (slot.decl.name.eql(name)) break :blk i; } return null; }; if (t.globals.items[index].value) |v| return v; if (t.globals.items[index].evaluating) { return t.fail("global variable {s} is defined in terms of itself", .{name.local}); } // The slots are all made before any is evaluated, so this index stays // valid across the evaluation however deeply it recurses. t.globals.items[index].evaluating = true; errdefer t.globals.items[index].evaluating = false; const decl = t.globals.items[index].decl; const computed = blk: { // A caller's parameter overrides the stylesheet's default. if (decl.is_param) { if (t.suppliedParameter(decl.name)) |text| { break :blk try Value.ownedString(t.gpa, text); } } const saved_scope = t.scope; t.scope = .{ .doc = decl.doc, .node = decl.element }; defer t.scope = saved_scope; break :blk try t.variableValue(decl.doc, decl.element, t.global_focus); }; t.globals.items[index].evaluating = false; t.globals.items[index].value = computed; return computed; } /// The value of an `xsl:variable` or `xsl:param`: its `select`, or its /// content as a result tree fragment, or the empty string. fn variableValue(t: *Transformer, doc: *Document, elem: NodeId, focus: Focus) Error!Value { if (sheet_mod.findAttribute(doc, elem, "", "select")) |attr| { const expr = try t.sheet.expression(doc, attr); return t.ev.eval(expr, focus); } if (doc.node(elem).children.items.len == 0) { return Value.ownedString(t.gpa, ""); } const fragment = try t.buildFragment(doc, elem, focus); // A fragment is handed out as the node-set holding its root. XSLT 1.0 // says a fragment may only be turned into a string, but representing // it as a tree is what makes `xsl:copy-of` of one work at all -- and // it means `exsl:node-set` has nothing left to do. const ns = try t.gpa.alloc(NodeRef, 1); ns[0] = fragment.ref(fragment.root); return .{ .node_set = ns }; } /// EXSLT `exsl:document`: a secondary result document. /// /// The content is a template like any other, instantiated into a document /// of its own, serialized by this element's own output attributes and /// handed to the caller's `Sink`. It is a *result tree* and not a result /// tree fragment, so a literal result element in it carries the /// stylesheet's in-scope namespace declarations exactly as one in the /// main result does. /// /// The output attributes start from the defaults rather than from /// `xsl:output`, which the module is explicit about: "the attributes on /// `xsl:output` elements affect only the main result document". They are /// attribute value templates, unlike `xsl:output`'s, so they are read /// here rather than when the stylesheet was. fn exsltDocument(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { var arena: std.heap.ArenaAllocator = .init(t.gpa); defer arena.deinit(); const a = arena.allocator(); const href = try t.avtInto(a, doc, node, "href", focus) orelse return t.fail("exsl:document has no href", .{}); var output: serialize.Output = .{}; if (try t.avtInto(a, doc, node, "method", focus)) |m| { // An unrecognised method is the XML one rather than an error, // which is how `xsl:output` reads the same attribute. output.method = if (std.mem.eql(u8, m, "xml")) .xml else if (std.mem.eql(u8, m, "html")) .html else if (std.mem.eql(u8, m, "text")) .text else output.method; } if (try t.avtInto(a, doc, node, "version", focus)) |v| output.version = v; if (try t.avtInto(a, doc, node, "encoding", focus)) |v| output.encoding = v; if (try t.avtInto(a, doc, node, "omit-xml-declaration", focus)) |v| { output.omit_xml_declaration = std.mem.eql(u8, v, "yes"); } if (try t.avtInto(a, doc, node, "standalone", focus)) |v| { output.standalone = std.mem.eql(u8, v, "yes"); } if (try t.avtInto(a, doc, node, "doctype-public", focus)) |v| output.doctype_public = v; if (try t.avtInto(a, doc, node, "doctype-system", focus)) |v| output.doctype_system = v; if (try t.avtInto(a, doc, node, "indent", focus)) |v| { output.indent = std.mem.eql(u8, v, "yes"); } if (try t.avtInto(a, doc, node, "cdata-section-elements", focus)) |v| { var names: std.ArrayList(Name) = .empty; var it = std.mem.tokenizeAny(u8, v, " \t\n\r"); while (it.next()) |token| { // A QName in this list resolves against the declarations in // scope on this element, and an unprefixed one takes the // default namespace -- the same reading `xsl:output` gets, // and for the same reason: a list of QNames is not a list of // XPath name tests. const uri = if (prefixOf(token)) |prefix| doc.lookupNamespace(node, prefix) orelse continue else doc.lookupNamespace(node, "") orelse ""; try names.append(a, .{ .uri = uri, .local = localOf(token) }); } output.cdata_section_elements = names.items; } // `media-type` is accepted and ignored, as it is on `xsl:output`: it // names a MIME type and changes no bytes. const secondary = try Document.create(t.gpa); defer secondary.destroy(); { const saved_result = t.result; const saved_output = t.output; const saved_fragment = t.building_fragment; t.result = secondary; t.output = secondary.root; t.building_fragment = false; defer { t.result = saved_result; t.output = saved_output; t.building_fragment = saved_fragment; } try t.instantiateChildren(doc, node, focus); secondary.reindex(); } const bytes = serialize.toOwnedSlice(t.gpa, secondary, output) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // An `Allocating` writer only fails by running out of memory. else => return error.OutOfMemory, }; defer t.gpa.free(bytes); try t.options.sink.write(href, bytes); } /// An attribute value template read into `a` rather than into `gpa`, so /// that a run of them is one `deinit` instead of a `defer free` apiece. fn avtInto( t: *Transformer, a: Allocator, doc: *Document, node: NodeId, attr: []const u8, focus: Focus, ) Error!?[]const u8 { const v = try t.optionalAvt(doc, node, attr, focus) orelse return null; defer t.gpa.free(v); return try a.dupe(u8, v); } /// Instantiates a sequence constructor into a document of its own. /// Builds a result tree fragment: the value of an `xsl:variable` with /// content, and of everything defined in terms of one. fn buildFragment(t: *Transformer, doc: *Document, elem: NodeId, focus: Focus) Error!*Document { const fragment = try Document.create(t.gpa); { errdefer fragment.destroy(); try t.fragments.append(t.gpa, fragment); } const saved_result = t.result; const saved_output = t.output; const saved_fragment = t.building_fragment; t.result = fragment; t.output = fragment.root; t.building_fragment = true; defer { t.result = saved_result; t.output = saved_output; t.building_fragment = saved_fragment; } try t.instantiateChildren(doc, elem, focus); fragment.reindex(); return fragment; } /// The string a sequence constructor produces, which is what /// `xsl:attribute`, `xsl:comment` and `xsl:processing-instruction` are /// defined in terms of. fn instantiateToString(t: *Transformer, doc: *Document, elem: NodeId, focus: Focus) Error![]u8 { const fragment = try t.buildFragment(doc, elem, focus); return fragment.stringValue(t.gpa, fragment.root); } fn lookupVariable(ctx: ?*anyopaque, ev: *Evaluator, name: Name) Error!?Value { const t: *Transformer = @ptrCast(@alignCast(ctx.?)); var i = t.bindings.items.len; while (i > t.frame_base) { i -= 1; if (t.bindings.items[i].pending) continue; if (t.bindings.items[i].name.eql(name)) { return try t.bindings.items[i].value.clone(ev.gpa); } } if (try t.findGlobal(name)) |v| return try v.clone(ev.gpa); return null; } // -- template dispatch --------------------------------------------------- /// Finds the rule that should handle a node, or null if none does. /// /// The order is the specification's: the highest import precedence wins /// outright, then the highest priority, then -- for rules still tied -- /// the one written last. The last of those is a recoverable error the /// specification permits a processor to report; libxslt takes the last /// rule silently, and so does this. /// /// Only the rules that could possibly match are considered. A node is /// looked up in at most four of the index's buckets -- the one for its /// name, the one for its kind's wildcard, `node()`, and the handful of /// patterns that cannot be classified -- and since each bucket is sorted /// best-first, walking them in merged order means the first rule that /// actually matches is the answer. Testing every rule against every node /// instead is what made `bug-166` take minutes. fn findRule( t: *Transformer, node: NodeRef, mode: ?Name, max_precedence: i32, ) Error!?*const sheet_mod.Rule { const index = &t.sheet.rule_index; const rules = t.sheet.rules.items; var buckets: [4][]const u32 = undefined; var count: usize = 0; switch (node.kind()) { .element => { buckets[count] = index.forElement(node.name().local); count += 1; buckets[count] = index.element_any.items; count += 1; buckets[count] = index.any_child.items; count += 1; }, .attribute => { buckets[count] = index.forAttribute(node.name().local); count += 1; buckets[count] = index.attribute_any.items; count += 1; }, // `node()` reaches these; a name test never does. .text => { buckets[count] = index.text.items; count += 1; buckets[count] = index.any_child.items; count += 1; }, .comment => { buckets[count] = index.comment.items; count += 1; buckets[count] = index.any_child.items; count += 1; }, .pi => { buckets[count] = index.pi.items; count += 1; buckets[count] = index.any_child.items; count += 1; }, // The root is not a child of anything, so only `/` reaches it. .document => { buckets[count] = index.root.items; count += 1; }, // Nothing matches a namespace node but an unclassifiable pattern. .namespace => {}, } buckets[count] = index.unclassified.items; count += 1; var cursor: [4]usize = @splat(0); while (true) { // The best-ranked head across the buckets still in play. var pick: ?usize = null; for (buckets[0..count], 0..) |bucket, i| { if (cursor[i] >= bucket.len) continue; if (pick) |best| { const challenger = rules[bucket[cursor[i]]]; const holder = rules[buckets[best][cursor[best]]]; if (!sheet_mod.outranks(challenger, holder)) continue; } pick = i; } const at = pick orelse return null; const rule = &rules[buckets[at][cursor[at]]]; cursor[at] += 1; if (rule.precedence > max_precedence) continue; if (!modesMatch(rule.mode, mode)) continue; var p: pattern.Pattern = .{ .alternatives = (&rule.alternative)[0..1] }; if (!try p.matches(&t.ev, node)) continue; // Buckets are sorted best-first and walked in merged order, so // nothing still unexamined can outrank this. return rule; } } fn modesMatch(a: ?Name, b: ?Name) bool { if (a == null and b == null) return true; if (a == null or b == null) return false; return a.?.eql(b.?); } /// Applies templates to one node, falling back to the built-in rule. fn applyToNode( t: *Transformer, node: NodeRef, mode: ?Name, position: usize, size: usize, max_precedence: i32, ) Error!void { t.depth += 1; defer t.depth -= 1; if (t.depth > xpath.max_depth) return error.RecursionLimit; const focus: Focus = .{ .node = node, .position = position, .size = size }; const saved_current = t.current; t.current = node; defer t.current = saved_current; if (try t.findRule(node, mode, max_precedence)) |rule| { const saved_precedence = t.precedence; t.precedence = rule.precedence; defer t.precedence = saved_precedence; const doc = rule.doc; const saved_base = t.frame_base; t.frame_base = t.bindings.items.len; defer { for (t.bindings.items[t.frame_base..]) |b| b.value.deinit(t.gpa); t.bindings.shrinkRetainingCapacity(t.frame_base); t.frame_base = saved_base; } // The simplified syntax makes the document element itself the // body rather than its children. if (isSimplifiedBody(doc, rule.element)) { try t.instantiate(doc, rule.element, focus); } else { try t.instantiateChildren(doc, rule.element, focus); } return; } try t.builtInRule(node, mode, focus); } fn isSimplifiedBody(doc: *Document, elem: NodeId) bool { return !std.mem.eql(u8, doc.node(elem).name.uri, xslt_ns); } /// What happens to a node no template matches. /// /// These rules are why a stylesheet with a single template still emits the /// document's text: an element with no rule keeps looking down, and a text /// node with no rule copies itself. fn builtInRule(t: *Transformer, node: NodeRef, mode: ?Name, focus: Focus) Error!void { switch (node.kind()) { .document, .element => { const kids = node.get().children.items; for (kids, 0..) |child, i| { try t.applyToNode( node.doc.ref(child), mode, i + 1, kids.len, std.math.maxInt(i32), ); } }, .text, .attribute => { const s = try node.stringValue(t.gpa); defer t.gpa.free(s); _ = try t.result.appendText(t.output, s); }, // A comment, a processing instruction, or a namespace node // produces nothing at all. .comment, .pi, .namespace => {}, } _ = focus; } // -- instantiation ------------------------------------------------------- fn instantiateChildren(t: *Transformer, doc: *Document, elem: NodeId, focus: Focus) Error!void { // Variables declared among these children are visible to the ones // after them and go out of scope here. const mark = t.bindings.items.len; defer { for (t.bindings.items[mark..]) |b| b.value.deinit(t.gpa); t.bindings.shrinkRetainingCapacity(mark); } // By index: instantiating a child cannot change this list, but taking // the slice once and holding it across calls that may grow other // documents' node arrays is a habit worth not having. var i: usize = 0; while (i < doc.node(elem).children.items.len) : (i += 1) { const child = doc.node(elem).children.items[i]; try t.instantiate(doc, child, focus); // A `func:result` somewhere below has ended the function this // body belongs to; nothing after it runs. if (t.func_result != null) return; } } fn instantiate(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { // Counted here because this is the one funnel every instruction, every // literal result element and every text node passes through, so "one // step" means one thing rather than whatever each call site decided. if (t.options.step_limit) |limit| { t.steps += 1; if (t.steps > limit) return error.StepLimitExceeded; } const saved_scope = t.scope; t.scope = .{ .doc = doc, .node = node }; defer t.scope = saved_scope; switch (doc.node(node).kind) { .text => { _ = try t.result.appendText(t.output, doc.node(node).value); }, .element => { const name = doc.node(node).name; if (std.mem.eql(u8, name.uri, xslt_ns)) { return t.instruction(doc, node, name.local, focus); } if (std.mem.eql(u8, name.uri, func_ns)) { // `func:result` is the only one of EXSLT's function // elements that appears in a body. `func:script` names // code in another language and is not implemented, and // anything else in that namespace is not an instruction at // all, so both take the extension-element path below. if (std.mem.eql(u8, name.local, "result")) { return t.funcResult(doc, node, focus); } } // An element in a namespace the stylesheet declared as an // extension namespace is an instruction, not content; one in // a namespace it did not is a literal result element. So the // designation is what decides here, and `exsl:document` is // checked inside that test rather than beside `func:result` // above: an `` in a template body that never // declared the prefix as an extension is an element the // stylesheet means to copy out, and XSLT 1.0 15 says so. if (t.isExtensionNamespace(doc, node, name.uri)) { if (std.mem.eql(u8, name.uri, exsl_ns) and std.mem.eql(u8, name.local, "document")) { return t.exsltDocument(doc, node, focus); } // Nothing else is implemented, so it falls back -- which // is the case `xsl:fallback` exists for. return t.runFallback(doc, node, focus); } return t.literalResultElement(doc, node, focus); }, // A comment or processing instruction in a template body belongs // to the stylesheet, not to the result. else => {}, } } fn instruction( t: *Transformer, doc: *Document, node: NodeId, local: []const u8, focus: Focus, ) Error!void { const Instruction = enum { @"apply-templates", @"apply-imports", attribute, @"call-template", choose, comment, copy, @"copy-of", element, fallback, @"for-each", @"if", message, number, param, @"processing-instruction", text, @"value-of", variable, /// Read by the instruction that encloses them, and skipped when /// instantiation walks past them. consumed_by_parent, }; const table = std.StaticStringMap(Instruction).initComptime(.{ .{ "apply-templates", .@"apply-templates" }, .{ "apply-imports", .@"apply-imports" }, .{ "attribute", .attribute }, .{ "call-template", .@"call-template" }, .{ "choose", .choose }, .{ "comment", .comment }, .{ "copy", .copy }, .{ "copy-of", .@"copy-of" }, .{ "element", .element }, .{ "fallback", .fallback }, .{ "for-each", .@"for-each" }, .{ "if", .@"if" }, .{ "message", .message }, .{ "number", .number }, .{ "param", .param }, .{ "processing-instruction", .@"processing-instruction" }, .{ "text", .text }, .{ "value-of", .@"value-of" }, .{ "variable", .variable }, .{ "sort", .consumed_by_parent }, .{ "with-param", .consumed_by_parent }, .{ "when", .consumed_by_parent }, .{ "otherwise", .consumed_by_parent }, }); const which = table.get(local) orelse { // An unknown instruction runs its `xsl:fallback` child if it has // one, which is how a stylesheet written for a later version // degrades rather than failing. return t.runFallback(doc, node, focus); }; switch (which) { .@"value-of" => try t.valueOf(doc, node, focus), .text => try t.textInstruction(doc, node), .@"if" => { const attr = sheet_mod.findAttribute(doc, node, "", "test") orelse return t.fail("xsl:if needs a test attribute", .{}); const expr = try t.sheet.expression(doc, attr); if (try t.ev.evalBoolean(expr, focus)) { try t.instantiateChildren(doc, node, focus); } }, .choose => try t.choose(doc, node, focus), .@"for-each" => try t.forEach(doc, node, focus), .@"apply-templates" => try t.applyTemplates(doc, node, focus), .@"apply-imports" => { // Only rules below the current one's precedence are eligible. try t.applyToNode(t.current, null, focus.position, focus.size, t.precedence - 1); }, .@"call-template" => try t.callTemplate(doc, node, focus), .variable, .param => try t.declareVariable(doc, node, focus), .element => try t.elementInstruction(doc, node, focus), .attribute => try t.attributeInstruction(doc, node, focus), .comment => { const text = try t.instantiateToString(doc, node, focus); defer t.gpa.free(text); _ = try t.result.appendComment(t.output, text); }, .@"processing-instruction" => { const name = try t.optionalAvt(doc, node, "name", focus) orelse return t.fail("xsl:processing-instruction needs a name attribute", .{}); defer t.gpa.free(name); const text = try t.instantiateToString(doc, node, focus); defer t.gpa.free(text); _ = try t.result.appendPi(t.output, name, text); }, .copy => try t.copy(doc, node, focus), .@"copy-of" => try t.copyOf(doc, node, focus), .number => try t.numberInstruction(doc, node, focus), .message => try t.message(doc, node, focus), // `xsl:fallback` runs only when its parent was not understood, so // reaching one here means the parent *was*, and it does nothing. .fallback, .consumed_by_parent => {}, } } fn runFallback(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { var found = false; for (doc.node(node).children.items) |child| { const n = doc.node(child); if (n.kind != .element) continue; if (!std.mem.eql(u8, n.name.uri, xslt_ns)) continue; if (!std.mem.eql(u8, n.name.local, "fallback")) continue; found = true; try t.instantiateChildren(doc, child, focus); } if (!found) { const name = doc.node(node).name; if (std.mem.eql(u8, name.uri, xslt_ns)) { return t.fail("no template for xsl:{s}", .{name.local}); } return t.fail("no implementation of extension element {{{s}}}{s}, and no xsl:fallback", .{ name.uri, name.local }); } } /// `func:result`, which ends the `func:function` it appears in. /// /// The value comes from `select` if there is one and from the element's /// content as a result tree fragment otherwise, which is `xsl:variable`'s /// rule and is what `variableValue` already implements. fn funcResult(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { // A second `func:result` in the same function cannot be reached, since // the first stops the body -- but one could be reached by a template // called from a function, and the *first* value is the one that wins. if (t.func_result != null) return; t.func_result = try t.variableValue(doc, node, focus); } /// `xsl:value-of`, in both of the readings XSLT has given it. /// /// XSLT 1.0 writes the string-value of the *first* node the expression /// selects and drops the rest, which is the rule `Value.toString` carries. /// XSLT 2.0 writes every item, separated by `separator` -- which defaults /// to a single space when `select` is present and to nothing when the /// value came from a sequence constructor. /// /// The 2.0 behaviour needs no sequences to implement, which is why it is /// here and not four stages away: in the 1.0 data model the only value /// that can hold more than one thing *is* a node-set, so "every item" /// and "every node" are the same list. /// /// Which of the two applies is decided by the version the *stylesheet* /// asked for, not by whether backwards-compatible mode is on. Those are /// different questions: the mode is relative to what this processor /// implements and moves when that does, while `version="1.0"` means 1.0 /// whoever is reading it. Keying this on the mode made every 1.0 /// stylesheet take the 2.0 path the moment it was written, because at a /// 1.0 processor `version="1.0"` is `.current` and not `.backwards` -- /// which `tests/cases/predicates` caught within the minute. fn valueOf(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const version = try t.sheet.effectiveVersion(doc, node); const has_content = doc.node(node).children.items.len != 0; const attr = sheet_mod.findAttribute(doc, node, "", "select") orelse { // 2.0 lets the content be a sequence constructor instead. In 1.0 // the attribute is required, and saying so is more useful than // silently writing nothing. if (!version.atLeast(2.0)) { return t.fail("xsl:value-of needs a select attribute", .{}); } // XTSE0870, the half nobody expects: neither a `select` nor any // content is an error rather than the empty string. An // `` that writes nothing is always a mistake, and // writing nothing is exactly how it would go unnoticed. if (!has_content) { return t.failCode( "XTSE0870", "xsl:value-of has neither a select attribute nor content", .{}, ); } const text = try t.instantiateToString(doc, node, focus); defer t.gpa.free(text); return t.appendTextMaybeRaw(doc, node, text); }; // The other half of XTSE0870. XSLT 1.0 said nothing about content on // an `xsl:value-of` that has a `select`, so this is checked only from // 2.0 up -- a 1.0 stylesheet that carries both keeps whatever it did. if (version.atLeast(2.0) and has_content) { return t.failCode( "XTSE0870", "xsl:value-of has both a select attribute and content", .{}, ); } const expr = try t.sheet.expression(doc, attr); if (!version.atLeast(2.0)) { const text = try t.ev.evalString(expr, focus); defer t.gpa.free(text); return t.appendTextMaybeRaw(doc, node, text); } const separator = try t.avtOr(doc, node, "separator", " ", focus); defer t.gpa.free(separator); var v = try t.ev.eval(expr, focus); defer v.deinit(t.gpa); var buf: std.ArrayList(u8) = .empty; defer buf.deinit(t.gpa); switch (v) { .node_set => |ns| for (ns, 0..) |ref, i| { if (i != 0) try buf.appendSlice(t.gpa, separator); const piece = try ref.stringValue(t.gpa); defer t.gpa.free(piece); try buf.appendSlice(t.gpa, piece); }, else => { const piece = try v.toString(t.gpa); defer t.gpa.free(piece); try buf.appendSlice(t.gpa, piece); }, } try t.appendTextMaybeRaw(doc, node, buf.items); } /// An attribute value template with a default, read into `gpa`. fn avtOr( t: *Transformer, doc: *Document, node: NodeId, name: []const u8, default: []const u8, focus: Focus, ) Error![]u8 { return (try t.optionalAvt(doc, node, name, focus)) orelse try t.gpa.dupe(u8, default); } fn textInstruction(t: *Transformer, doc: *Document, node: NodeId) Error!void { var buf: std.ArrayList(u8) = .empty; defer buf.deinit(t.gpa); for (doc.node(node).children.items) |child| { if (doc.node(child).kind == .text) { try buf.appendSlice(t.gpa, doc.node(child).value); } } try t.appendTextMaybeRaw(doc, node, buf.items); } /// Appends text, honouring `disable-output-escaping`. fn appendTextMaybeRaw(t: *Transformer, doc: *Document, node: NodeId, text: []const u8) Error!void { const raw = if (doc.attributeValue(node, "", "disable-output-escaping")) |v| std.mem.eql(u8, v, "yes") else false; if (!raw) { _ = try t.result.appendText(t.output, text); return; } _ = try t.result.appendVerbatimText(t.output, text); } fn choose(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { for (doc.node(node).children.items) |child| { const n = doc.node(child); if (n.kind != .element or !std.mem.eql(u8, n.name.uri, xslt_ns)) continue; if (std.mem.eql(u8, n.name.local, "when")) { const attr = sheet_mod.findAttribute(doc, child, "", "test") orelse return t.fail("xsl:when needs a test attribute", .{}); const expr = try t.sheet.expression(doc, attr); if (try t.ev.evalBoolean(expr, focus)) { return t.instantiateChildren(doc, child, focus); } continue; } if (std.mem.eql(u8, n.name.local, "otherwise")) { return t.instantiateChildren(doc, child, focus); } } } fn forEach(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const attr = sheet_mod.findAttribute(doc, node, "", "select") orelse return t.fail("xsl:for-each needs a select attribute", .{}); const expr = try t.sheet.expression(doc, attr); const nodes = try t.ev.evalNodeSet(expr, focus); defer t.gpa.free(nodes); try t.sortNodes(doc, node, nodes); const saved_current = t.current; defer t.current = saved_current; for (nodes, 0..) |n, i| { t.current = n; try t.instantiateChildren(doc, node, .{ .node = n, .position = i + 1, .size = nodes.len, }); if (t.func_result != null) return; } } fn applyTemplates(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const mode: ?Name = if (doc.attributeValue(node, "", "mode")) |text| try t.resolveQName(doc, node, text) else null; var nodes: []NodeRef = undefined; if (sheet_mod.findAttribute(doc, node, "", "select")) |attr| { const expr = try t.sheet.expression(doc, attr); nodes = try t.ev.evalNodeSet(expr, focus); } else { // The default is the children of the current node. const kids = focus.node.get().children.items; nodes = try t.gpa.alloc(NodeRef, kids.len); for (kids, nodes) |id, *slot| slot.* = focus.node.doc.ref(id); } defer t.gpa.free(nodes); try t.sortNodes(doc, node, nodes); // Parameters are evaluated in the caller's context, once, before any // template runs. var params: std.ArrayList(Binding) = .empty; defer { for (params.items) |p| p.value.deinit(t.gpa); params.deinit(t.gpa); } try t.collectWithParams(doc, node, focus, ¶ms); for (nodes, 0..) |n, i| { const mark = t.bindings.items.len; for (params.items) |p| { try t.bindings.append(t.gpa, .{ .name = p.name, .value = try p.value.clone(t.gpa), .pending = true, }); } // The parameters sit below the callee's floor so that // `applyToNode` can raise it past them and still find them -- // which is what makes a passed parameter visible and a caller's // own variables not. try t.applyToNodeWithParams(n, mode, i + 1, nodes.len, mark); } } /// Like `applyToNode`, but the bindings from `mark` onwards are parameters /// meant for the template being entered. fn applyToNodeWithParams( t: *Transformer, node: NodeRef, mode: ?Name, position: usize, size: usize, mark: usize, ) Error!void { const saved_base = t.frame_base; t.frame_base = mark; defer { for (t.bindings.items[mark..]) |b| b.value.deinit(t.gpa); t.bindings.shrinkRetainingCapacity(mark); t.frame_base = saved_base; } try t.applyToNodeInFrame(node, mode, position, size, std.math.maxInt(i32)); } /// The body of `applyToNode` without the frame handling, so that a caller /// which has already placed parameters in the frame does not have them /// hidden by a second floor. fn applyToNodeInFrame( t: *Transformer, node: NodeRef, mode: ?Name, position: usize, size: usize, max_precedence: i32, ) Error!void { t.depth += 1; defer t.depth -= 1; if (t.depth > xpath.max_depth) return error.RecursionLimit; const focus: Focus = .{ .node = node, .position = position, .size = size }; const saved_current = t.current; t.current = node; defer t.current = saved_current; if (try t.findRule(node, mode, max_precedence)) |rule| { const saved_precedence = t.precedence; t.precedence = rule.precedence; defer t.precedence = saved_precedence; const doc = rule.doc; if (isSimplifiedBody(doc, rule.element)) { try t.instantiate(doc, rule.element, focus); } else { try t.instantiateChildren(doc, rule.element, focus); } return; } try t.builtInRule(node, mode, focus); } fn collectWithParams( t: *Transformer, doc: *Document, node: NodeId, focus: Focus, out: *std.ArrayList(Binding), ) Error!void { for (doc.node(node).children.items) |child| { const n = doc.node(child); if (n.kind != .element) continue; if (!std.mem.eql(u8, n.name.uri, xslt_ns)) continue; if (!std.mem.eql(u8, n.name.local, "with-param")) continue; const name_text = doc.attributeValue(child, "", "name") orelse return t.fail("xsl:with-param needs a name attribute", .{}); const name = try t.resolveQName(doc, child, name_text); const v = try t.variableValue(doc, child, focus); try out.append(t.gpa, .{ .name = name, .value = v }); } } fn callTemplate(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const name_text = doc.attributeValue(node, "", "name") orelse return t.fail("xsl:call-template needs a name attribute", .{}); const name = try t.resolveQName(doc, node, name_text); const template = t.findNamedTemplate(name) orelse return t.fail("no template named {s}", .{name_text}); var params: std.ArrayList(Binding) = .empty; defer { for (params.items) |p| p.value.deinit(t.gpa); params.deinit(t.gpa); } try t.collectWithParams(doc, node, focus, ¶ms); try t.runNamedTemplate(template, params.items, focus); } /// The `xsl:template name=` of this name with the highest import /// precedence, or null. fn findNamedTemplate(t: *Transformer, name: Name) ?*const sheet_mod.NamedTemplate { var target: ?*const sheet_mod.NamedTemplate = null; for (t.sheet.named.items) |*nt| { if (!nt.name.eql(name)) continue; if (target == null or nt.precedence >= target.?.precedence) target = nt; } return target; } /// Instantiates a named template's body in a frame of its own. /// /// Shared by `xsl:call-template` and by entering the transformation at a /// named template, which differ only in where the parameters came from -- /// `xsl:with-param` children in the one case and nothing at all in the /// other. fn runNamedTemplate( t: *Transformer, template: *const sheet_mod.NamedTemplate, params: []const Binding, focus: Focus, ) Error!void { t.depth += 1; defer t.depth -= 1; if (t.depth > xpath.max_depth) return error.RecursionLimit; const mark = t.bindings.items.len; for (params) |p| { try t.bindings.append(t.gpa, .{ .name = p.name, .value = try p.value.clone(t.gpa), .pending = true, }); } const saved_base = t.frame_base; t.frame_base = mark; const saved_precedence = t.precedence; t.precedence = template.precedence; defer { for (t.bindings.items[mark..]) |b| b.value.deinit(t.gpa); t.bindings.shrinkRetainingCapacity(mark); t.frame_base = saved_base; t.precedence = saved_precedence; } // A called template keeps the caller's current node: `xsl:call-template` // moves control without moving the focus. try t.instantiateChildren(template.doc, template.element, focus); } /// `xsl:variable` or `xsl:param` inside a template body. fn declareVariable(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const name_text = doc.attributeValue(node, "", "name") orelse return t.fail("xsl:variable needs a name attribute", .{}); const name = try t.resolveQName(doc, node, name_text); // A parameter that the caller supplied is already bound; the // declaration only provides a default. const is_param = std.mem.eql(u8, doc.node(node).name.local, "param"); if (is_param) { var i = t.bindings.items.len; while (i > t.frame_base) { i -= 1; if (!t.bindings.items[i].name.eql(name)) continue; // Claiming it is what makes it visible: until an `xsl:param` // declares the name, a parameter the caller passed is ignored // rather than allowed to shadow a global. t.bindings.items[i].pending = false; return; } } const v = try t.variableValue(doc, node, focus); errdefer v.deinit(t.gpa); try t.bindings.append(t.gpa, .{ .name = name, .value = v }); } // -- result construction ------------------------------------------------- fn literalResultElement(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const source_name = doc.node(node).name; const name = t.aliasedName(source_name); const elem = try t.result.appendElement(t.output, name); // The namespace declarations in scope on the stylesheet element come // along only into the result tree. A result tree fragment gets none of // them: its elements are copied out later, and `deepCopy` declares // whatever their names then need. Carrying the whole scope through a // variable would put a declaration nothing uses on every element that // passed through one, which is what libxslt avoids by the same means. if (!t.building_fragment) try t.copyInScopeNamespaces(doc, node, elem); const saved_output = t.output; t.output = elem; defer t.output = saved_output; // The sets go on first and the element's own attributes after, which // is what the specification's own example in section 7.1.4 shows: // `` // comes out with the set's attributes first and `quadding` last. // Because `setAttribute` replaces in place, an attribute the element // and a set both name keeps the set's position and takes the element's // value -- position from the first write, value from the last. if (doc.attributeValue(node, xslt_ns, "use-attribute-sets")) |sets| { try t.applyAttributeSets(sets, doc, node, focus); } for (doc.node(node).attributes.items) |attr| { const an = doc.node(attr); // Attributes in the XSLT namespace control the element rather // than appearing on it. if (std.mem.eql(u8, an.name.uri, xslt_ns)) continue; const avt = try t.sheet.attributeValueTemplate(doc, attr); const text = try t.expandAvt(avt, focus); defer t.gpa.free(text); _ = try t.result.setAttribute(elem, t.aliasedName(an.name), text); } try t.instantiateChildren(doc, node, focus); } /// Applies `xsl:namespace-alias` to a name written in the stylesheet. fn aliasedName(t: *Transformer, name: Name) Name { var best: ?sheet_mod.NamespaceAlias = null; for (t.sheet.aliases.items) |alias| { if (!std.mem.eql(u8, alias.stylesheet_uri, name.uri)) continue; if (best == null or alias.precedence >= best.?.precedence) best = alias; } const alias = best orelse return name; // The namespace URI is replaced and the prefix is not. That is what // the specification actually says -- only the URI of the expanded name // changes -- and it is what libxslt does, so a stylesheet that // generates a stylesheet comes out with its own prefix bound to the // XSLT namespace rather than with `xsl:`. // // Aliasing to *no* namespace is the exception, and it is the case // `result-prefix="#default"` produces when the stylesheet declares no // default namespace: an element in no namespace has no prefix to // carry, and keeping one would ask the writer for an `xmlns:p=""` // that XML has no way to spell. if (alias.result_uri.len == 0) { return .{ .uri = "", .local = name.local }; } return .{ .uri = alias.result_uri, .local = name.local, .prefix = name.prefix }; } /// Copies the namespace declarations in scope on a literal result element /// to the element it produces. /// /// The XSLT namespace never goes, nor does anything the stylesheet /// excluded, nor anything the result tree already has in scope -- the last /// of which is what keeps a declaration from being repeated on every /// element of a deep result. fn copyInScopeNamespaces( t: *Transformer, doc: *Document, source: NodeId, target: NodeId, ) Error!void { var decls: std.ArrayList(tree.NsDecl) = .empty; defer decls.deinit(t.gpa); var seen: std.StringHashMapUnmanaged(void) = .empty; defer seen.deinit(t.gpa); var cur: ?NodeId = source; while (cur) |id| : (cur = doc.node(id).parent) { for (doc.node(id).ns_decls) |d| { if (seen.contains(d.prefix)) continue; try seen.put(t.gpa, d.prefix, {}); if (d.uri.len == 0) continue; if (std.mem.eql(u8, d.uri, xslt_ns)) continue; if (t.isExcludedPrefix(doc, source, d.prefix)) continue; // XSLT 1.0 7.1.1: an extension namespace is excluded from the // result tree without having to be named twice. if (t.isExtensionNamespace(doc, source, d.uri)) continue; // A namespace alias replaces the declaration rather than // adding to it. if (t.aliasTargetFor(d.uri)) |aliased| { // A namespace aliased to nothing is not declared at all: // the elements that used it are in no namespace now, and // there is nothing left for a declaration to say. if (aliased.result_uri.len == 0) continue; // Otherwise the declaration keeps its prefix and changes // its URI, to match what `aliasedName` did to the element // name. const parent_id = t.result.node(target).parent orelse t.result.root; if (t.result.lookupNamespace(parent_id, d.prefix)) |have| { if (std.mem.eql(u8, have, aliased.result_uri)) continue; } try decls.append(t.gpa, .{ .prefix = d.prefix, .uri = aliased.result_uri, }); continue; } const parent = t.result.node(target).parent orelse t.result.root; if (t.result.lookupNamespace(parent, d.prefix)) |have| { if (std.mem.eql(u8, have, d.uri)) continue; } try decls.append(t.gpa, d); } } // The element's own namespace is declared first, ahead of whatever // else it inherited. Nothing requires an order -- namespace // declarations are attributes, and attributes are a set -- but libxslt // has one, because it creates the element with its namespace and // copies the rest afterwards, and a serializer that agrees with the // oracle on the order is a serializer whose output can be compared // byte for byte. const own = t.result.node(target).name.prefix; if (own.len != 0) { for (decls.items, 0..) |d, i| { if (!std.mem.eql(u8, d.prefix, own)) continue; std.mem.rotate(tree.NsDecl, decls.items[0 .. i + 1], i); break; } } if (decls.items.len != 0) try t.result.setNsDecls(target, decls.items); } fn aliasTargetFor(t: *Transformer, uri: []const u8) ?sheet_mod.NamespaceAlias { var best: ?sheet_mod.NamespaceAlias = null; for (t.sheet.aliases.items) |alias| { if (!std.mem.eql(u8, alias.stylesheet_uri, uri)) continue; if (best == null or alias.precedence >= best.?.precedence) best = alias; } return best; } fn isExcludedPrefix(t: *Transformer, doc: *Document, elem: NodeId, prefix: []const u8) bool { _ = t; var cur: ?NodeId = elem; while (cur) |id| : (cur = doc.node(id).parent) { // Written unprefixed on a literal result element and prefixed on // `xsl:stylesheet`, so both spellings are checked. const text = doc.attributeValue(id, xslt_ns, "exclude-result-prefixes") orelse doc.attributeValue(id, "", "exclude-result-prefixes") orelse continue; var it = std.mem.tokenizeAny(u8, text, " \t\n\r"); while (it.next()) |token| { const want = if (std.mem.eql(u8, token, "#default")) "" else token; if (std.mem.eql(u8, want, prefix)) return true; } } return false; } /// True when a namespace was declared an extension namespace by this /// element or an ancestor. /// /// The comparison is by URI rather than by prefix: `extension-element- /// prefixes` names prefixes, but what it designates is the namespaces they /// are bound to, and an element may reach the same namespace through a /// different prefix. fn isExtensionNamespace(t: *Transformer, doc: *Document, elem: NodeId, uri: []const u8) bool { _ = t; if (uri.len == 0) return false; var cur: ?NodeId = elem; while (cur) |id| : (cur = doc.node(id).parent) { // Written unprefixed on `xsl:stylesheet` and prefixed on a literal // result element, so both spellings are checked. const text = doc.attributeValue(id, xslt_ns, "extension-element-prefixes") orelse doc.attributeValue(id, "", "extension-element-prefixes") orelse continue; var it = std.mem.tokenizeAny(u8, text, " \t\n\r"); while (it.next()) |token| { const prefix = if (std.mem.eql(u8, token, "#default")) "" else token; const declared = doc.lookupNamespace(id, prefix) orelse continue; if (std.mem.eql(u8, declared, uri)) return true; } } return false; } fn elementInstruction(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const qname = try t.optionalAvt(doc, node, "name", focus) orelse return t.fail("xsl:element needs a name attribute", .{}); defer t.gpa.free(qname); const local = localOf(qname); const prefix = prefixOf(qname) orelse ""; const uri: []const u8 = if (try t.optionalAvt(doc, node, "namespace", focus)) |ns| blk: { defer t.gpa.free(ns); break :blk try t.result.alloc().dupe(u8, ns); } else // No `namespace` attribute: the prefix means whatever it means on // the `xsl:element` element itself. doc.lookupNamespace(node, prefix) orelse ""; const elem = try t.result.appendElement(t.output, .{ .uri = uri, .local = local, .prefix = usablePrefix(prefix, uri), }); const saved_output = t.output; t.output = elem; defer t.output = saved_output; if (doc.attributeValue(node, "", "use-attribute-sets")) |sets| { try t.applyAttributeSets(sets, doc, node, focus); } try t.instantiateChildren(doc, node, focus); } /// The prefix to ask the serializer for, which is not always the one that /// was written. /// /// `xsl:element` and `xsl:attribute` take a QName the stylesheet computed, /// and nothing stops that QName carrying a prefix XML Namespaces reserves. /// `` is the case in /// the Recommendation's own test 7.1.3, and honouring its prefix produces /// `xmlns:xmlns="whatever"` -- a namespace declaration for the one prefix /// that may never be declared, next to an attribute called `xmlns:xsl` /// that reads as a second one. The output is not well-formed, and nothing /// downstream can recover the attribute that was meant. /// /// Returning the empty prefix asks the serializer to invent one instead, /// which keeps the name -- the namespace and the local part, which are /// what the attribute *is* -- and gives up only the spelling of a prefix /// that was never usable. fn usablePrefix(prefix: []const u8, uri: []const u8) []const u8 { if (uri.len == 0) return ""; if (std.mem.eql(u8, prefix, "xmlns")) return ""; // `xml` is bound to one namespace and may not be bound to another. if (std.mem.eql(u8, prefix, "xml") and !std.mem.eql(u8, uri, tree.xml_ns)) return ""; return prefix; } fn attributeInstruction(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const qname = try t.optionalAvt(doc, node, "name", focus) orelse return t.fail("xsl:attribute needs a name attribute", .{}); defer t.gpa.free(qname); // An attribute added when there is no element to add it to is // discarded rather than being an error, which is what libxslt does. if (t.result.node(t.output).kind != .element) return; const local = localOf(qname); const prefix = prefixOf(qname) orelse ""; const uri: []const u8 = if (try t.optionalAvt(doc, node, "namespace", focus)) |ns| blk: { defer t.gpa.free(ns); break :blk try t.result.alloc().dupe(u8, ns); } else if (prefix.len == 0) // An unprefixed attribute is in no namespace, default declaration // or not. "" else doc.lookupNamespace(node, prefix) orelse ""; const name: Name = .{ .uri = uri, .local = local, .prefix = usablePrefix(prefix, uri), }; // An attribute that something stronger has already written is not // produced at all -- not even evaluated, since its content cannot // affect the result. if (t.attributeIsProtected(name)) return; const text = try t.instantiateToString(doc, node, focus); defer t.gpa.free(text); _ = try t.result.setAttribute(t.output, name, text); } /// Applies the named attribute sets to whatever element is being built. /// /// Precedence and order run in opposite directions here, which is the /// whole subtlety. /// /// A set's own attributes take precedence over those of the sets it uses, /// and an element's own take precedence over both. But they are *written* /// the other way round: the element's own first, then its sets', then /// theirs. Applying the inherited ones first and letting them be /// overwritten gets the precedence right and the order backwards. /// /// So it is done in writing order, with `attribute_fill_only` making the /// later, weaker attributes fill gaps rather than replace. Same precedence, /// and the output matches what every other processor emits. /// /// Several `xsl:attribute-set` elements may also share a name, in which /// case they merge. That falls out of applying every match in the order /// they were read: imports are read before the stylesheet importing them, /// so the importing definition is the one that lands last -- and under /// fill-only the *first* write wins, so they are applied in reverse. fn applyAttributeSets( t: *Transformer, names: []const u8, doc: *Document, scope: NodeId, focus: Focus, ) Error!void { t.attribute_set_depth += 1; defer t.attribute_set_depth -= 1; if (t.attribute_set_depth > max_attribute_set_depth) { return t.fail("xsl:attribute-set definitions use each other in a circle", .{}); } const saved_guard = t.attribute_guard; defer t.attribute_guard = saved_guard; // Everything already on the element outranks this whole list. const base = t.outputAttributeCount(); var it = std.mem.tokenizeAny(u8, names, " \t\n\r"); while (it.next()) |token| { const name = try t.resolveQName(doc, scope, token); // The definitions of this name, strongest first. Several // `xsl:attribute-set` elements may share a name, in which case // they merge, and an attribute from a definition with higher // import precedence wins. var definitions: std.ArrayList(u32) = .empty; defer definitions.deinit(t.gpa); for (t.sheet.attribute_sets.items, 0..) |set, i| { if (set.name.eql(name)) try definitions.append(t.gpa, @intCast(i)); } const Order = struct { sets: []const sheet_mod.AttributeSet, fn strongerFirst(ctx: @This(), a: u32, b: u32) bool { return ctx.sets[a].precedence > ctx.sets[b].precedence; } }; // Stable, so that definitions of equal precedence keep the order // they were written in. std.sort.insertion(u32, definitions.items, Order{ .sets = t.sheet.attribute_sets.items, }, Order.strongerFirst); // Walked as groups of equal import precedence, strongest group // first. Within a group the definitions run in declaration order // and may replace each other -- two `xsl:attribute-set` elements // of the same name in one stylesheet merge, and the later one // wins. Between groups the guard rises, so a weaker group can only // fill what is still missing. var i: usize = 0; while (i < definitions.items.len) { const group_precedence = t.sheet.attribute_sets.items[definitions.items[i]].precedence; // Fixed for the whole group: the first group is guarded only // against what preceded this list, so a set named later in the // list overrides one named earlier. const guard = if (i == 0) base else t.outputAttributeCount(); while (i < definitions.items.len) : (i += 1) { const set = t.sheet.attribute_sets.items[definitions.items[i]]; if (set.precedence != group_precedence) break; t.attribute_guard = guard; try t.instantiateChildren(set.doc, set.element, focus); if (set.doc.attributeValue(set.element, "", "use-attribute-sets")) |used| { // Weaker than everything written so far, which the // recursion's own base takes care of. try t.applyAttributeSets(used, set.doc, set.element, focus); } } } } } fn outputAttributeCount(t: *Transformer) usize { const n = t.result.node(t.output); if (n.kind != .element) return 0; return n.attributes.items.len; } /// True when an attribute of this name was written by something stronger /// than the attribute set currently being applied. fn attributeIsProtected(t: *Transformer, name: Name) bool { const guard = t.attribute_guard orelse return false; if (t.result.node(t.output).kind != .element) return false; const attributes = t.result.node(t.output).attributes.items; for (attributes[0..@min(guard, attributes.len)]) |a| { if (t.result.node(a).name.is(name.uri, name.local)) return true; } return false; } fn copy(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const src = focus.node; switch (src.kind()) { .document => try t.instantiateChildren(doc, node, focus), .element => { const elem = try t.result.appendElement(t.output, src.name()); // The namespace nodes of the source element come with it, but // its attributes and children do not: `xsl:copy` is shallow, // which is the whole difference from `xsl:copy-of`. try t.copyNamespaceDeclarations(src, elem); const saved_output = t.output; t.output = elem; defer t.output = saved_output; if (doc.attributeValue(node, "", "use-attribute-sets")) |sets| { try t.applyAttributeSets(sets, doc, node, focus); } try t.instantiateChildren(doc, node, focus); }, .attribute => { if (t.result.node(t.output).kind != .element) return; _ = try t.result.setAttribute(t.output, src.name(), src.get().value); }, .text => _ = try t.result.appendText(t.output, src.get().value), .comment => _ = try t.result.appendComment(t.output, src.get().value), .pi => _ = try t.result.appendPi(t.output, src.name().local, src.get().value), .namespace => try t.copyNamespaceNode(src), } } /// Copies a namespace node onto whatever element is being built. /// /// A namespace node is a prefix and the URI it is bound to, and copying /// one means declaring that binding on the element the copy lands in. It /// is refused where it would change the meaning of a name already written: /// XSLT 1.0 7.5 makes it an error to add a declaration to an element whose /// own name, or one of whose attributes' names, uses that prefix for a /// different namespace. Nothing to add is not an error, so that is a quiet /// return rather than a message. fn copyNamespaceNode(t: *Transformer, src: NodeRef) Error!void { if (t.result.node(t.output).kind != .element) return; const prefix = src.name().local; const uri = src.get().value; // The XML namespace is in scope everywhere without being declared, so // copying its node writes nothing. if (std.mem.eql(u8, prefix, "xml")) return; if (t.result.lookupNamespace(t.output, prefix)) |have| { if (std.mem.eql(u8, have, uri)) return; } if (usesPrefixOtherwise(t.result, t.output, prefix, uri)) return; try t.result.addNsDecl(t.output, prefix, uri); } /// True when the element or one of its attributes is written with this /// prefix but a different namespace, so that declaring it here would /// rename them. fn usesPrefixOtherwise( result: *Document, elem: NodeId, prefix: []const u8, uri: []const u8, ) bool { const own = result.node(elem).name; if (std.mem.eql(u8, own.prefix, prefix) and !std.mem.eql(u8, own.uri, uri)) return true; for (result.node(elem).attributes.items) |a| { const name = result.node(a).name; if (std.mem.eql(u8, name.prefix, prefix) and !std.mem.eql(u8, name.uri, uri)) return true; } return false; } fn copyOf(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const attr = sheet_mod.findAttribute(doc, node, "", "select") orelse return t.fail("xsl:copy-of needs a select attribute", .{}); const expr = try t.sheet.expression(doc, attr); const v = try t.ev.eval(expr, focus); defer v.deinit(t.gpa); switch (v) { .node_set => |ns| for (ns) |n| try t.deepCopy(n), else => { const s = try v.toString(t.gpa); defer t.gpa.free(s); _ = try t.result.appendText(t.output, s); }, } } fn deepCopy(t: *Transformer, src: NodeRef) Error!void { switch (src.kind()) { // The root of a result tree fragment contributes its children, not // itself: a document node cannot be nested inside an element. .document => { for (src.get().children.items) |c| try t.deepCopy(src.doc.ref(c)); }, .element => { const elem = try t.result.appendElement(t.output, src.name()); try t.copyNamespaceDeclarations(src, elem); for (src.get().attributes.items) |a| { const an = src.doc.node(a); _ = try t.result.setAttribute(elem, an.name, an.value); } const saved_output = t.output; t.output = elem; defer t.output = saved_output; for (src.get().children.items) |c| try t.deepCopy(src.doc.ref(c)); }, .attribute => { if (t.result.node(t.output).kind != .element) return; _ = try t.result.setAttribute(t.output, src.name(), src.get().value); }, .text => _ = try t.result.appendText(t.output, src.get().value), .comment => _ = try t.result.appendComment(t.output, src.get().value), .pi => _ = try t.result.appendPi(t.output, src.name().local, src.get().value), .namespace => try t.copyNamespaceNode(src), } } /// Carries the namespace declarations a source element needs into the /// result, skipping those the result already has in scope. fn copyNamespaceDeclarations(t: *Transformer, src: NodeRef, target: NodeId) Error!void { var decls: std.ArrayList(tree.NsDecl) = .empty; defer decls.deinit(t.gpa); var seen: std.StringHashMapUnmanaged(void) = .empty; defer seen.deinit(t.gpa); const parent = t.result.node(target).parent orelse t.result.root; var cur: ?NodeId = src.id; while (cur) |id| : (cur = src.doc.node(id).parent) { for (src.doc.node(id).ns_decls) |d| { if (seen.contains(d.prefix)) continue; try seen.put(t.gpa, d.prefix, {}); if (d.uri.len == 0) continue; if (t.result.lookupNamespace(parent, d.prefix)) |have| { if (std.mem.eql(u8, have, d.uri)) continue; } try decls.append(t.gpa, d); } } if (decls.items.len != 0) try t.result.setNsDecls(target, decls.items); } // -- sorting ------------------------------------------------------------- const SortSpec = struct { expr: *const xpath.Expr, numeric: bool, descending: bool, /// The collation this level compares with: the transformation's, /// with `lang` and `case-order` applied. Per level, because /// `xsl:sort` carries both attributes per level. collation: collate.Collator, }; /// Reorders a node-set by the `xsl:sort` children of an instruction. /// /// Sort keys are computed against the *unsorted* list, because /// `position()` inside a sort key means the node's place before sorting -- /// and computing them up front rather than inside the comparison is also /// what keeps the sort from being quadratic in expression evaluations. fn sortNodes(t: *Transformer, doc: *Document, node: NodeId, nodes: []NodeRef) Error!void { var specs: std.ArrayList(SortSpec) = .empty; defer specs.deinit(t.gpa); for (doc.node(node).children.items) |child| { const n = doc.node(child); if (n.kind != .element) continue; if (!std.mem.eql(u8, n.name.uri, xslt_ns)) continue; if (!std.mem.eql(u8, n.name.local, "sort")) continue; const expr = if (sheet_mod.findAttribute(doc, child, "", "select")) |a| try t.sheet.expression(doc, a) else // The default key is the node's own string-value. try t.selfExpression(); const data_type = try t.optionalAvt(doc, child, "data-type", .{ .node = t.current }); defer if (data_type) |d| t.gpa.free(d); const order = try t.optionalAvt(doc, child, "order", .{ .node = t.current }); defer if (order) |o| t.gpa.free(o); // XSLT 10 puts `lang` and `case-order` on each `xsl:sort`, so // both are per level rather than per transformation. const lang = try t.optionalAvt(doc, child, "lang", .{ .node = t.current }); defer if (lang) |l| t.gpa.free(l); const case_order = try t.optionalAvt(doc, child, "case-order", .{ .node = t.current }); defer if (case_order) |c| t.gpa.free(c); const numeric = data_type != null and std.mem.eql(u8, data_type.?, "number"); var collation = t.options.collation; // `lang` selects a CLDR tailoring on top of the root collation. // A language with no tailoring compiled in -- or none in CLDR at // all, which is true of German and French, because the root // collation is already their answer -- leaves the root in place. // That is what XSLT 10 permits: the attribute says what language // the keys are in, and the ordering it produces is // implementation-defined. if (lang) |tag| { if (collate.locales.match(tag)) |tailoring| { collation.table = collation.table.tailored(tailoring); // A locale's rules can ask for the parametric settings // themselves -- Danish opens with `[caseFirst upper]`, // which is what puts `AA` before `aa` -- and those are // recorded on the tailoring rather than baked into a // weight, because they change how a sort key is built. // Taken up here and not later, so that `case-order` // below overrides the locale rather than the other way // round: the attribute is what the stylesheet asked for. collation.options = collation.options.applying(tailoring.settings); } } // `case-order` is `upper-first` or `lower-first`, and XSLT 10 // scopes it: it "applies when data-type="text"", so a numeric // sort ignores it. A value that is neither is ignored rather // than refused, which is the latitude the specification takes // for the attribute's own default -- "the default value is // language dependent". if (!numeric) { if (case_order) |requested| { if (std.mem.eql(u8, requested, "upper-first")) { collation.options.case_first = .upper_first; } else if (std.mem.eql(u8, requested, "lower-first")) { collation.options.case_first = .lower_first; } } } try specs.append(t.gpa, .{ .expr = expr, .numeric = numeric, .descending = order != null and std.mem.eql(u8, order.?, "descending"), .collation = collation, }); } if (specs.items.len == 0) return; // One key per node per sort level, computed once. // // `text` is a collation sort key rather than the string itself: the // whole point of building one is that the comparison then costs a // `memcmp`, so ordering n nodes is n key constructions and n log n // byte comparisons instead of n log n collations. const Key = struct { text: []u8, num: f64 }; const keys = try t.gpa.alloc(Key, nodes.len * specs.items.len); defer { for (keys) |k| t.gpa.free(k.text); t.gpa.free(keys); } for (keys) |*k| k.* = .{ .text = &.{}, .num = 0 }; // XSLT 10: a sort key is computed with the node being sorted as the // current node and the whole list being sorted as the current node // list. `current()` in a key is therefore the node whose key it is, // and not whatever the enclosing template was processing -- which is // the difference between a two-level sort and a one-level one, since a // key that cannot see its own node returns the same answer for every // node and leaves them where they were. const saved_current = t.current; defer t.current = saved_current; for (nodes, 0..) |n, i| { t.current = n; for (specs.items, 0..) |spec, level| { const focus: Focus = .{ .node = n, .position = i + 1, .size = nodes.len }; const text = try t.ev.evalString(spec.expr, focus); defer t.gpa.free(text); keys[i * specs.items.len + level] = .{ // A numeric sort compares the number and never looks at // the text, so there is no reason to collate it. .text = if (spec.numeric) &.{} else t.collator.sortKeyAlloc(t.gpa, spec.collation, text) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // A node's string-value is built from the source // document, which was parsed as UTF-8, so this // cannot arise from a well-formed input. Ordering // by the bytes is the least surprising thing to // do if it ever does. error.InvalidUtf8 => try t.gpa.dupe(u8, text), }, .num = if (spec.numeric) value.stringToNumber(text) else 0, }; } } // Sorting indices rather than nodes keeps each node with its keys. const order_index = try t.gpa.alloc(usize, nodes.len); defer t.gpa.free(order_index); for (order_index, 0..) |*slot, i| slot.* = i; const Context = struct { keys: []const Key, specs: []const SortSpec, fn lessThan(ctx: @This(), a: usize, b: usize) bool { const levels = ctx.specs.len; for (ctx.specs, 0..) |spec, level| { const ka = ctx.keys[a * levels + level]; const kb = ctx.keys[b * levels + level]; var cmp: i8 = 0; if (spec.numeric) { // NaN sorts before every number, which is where a // non-numeric value in a numeric sort ends up. const na = ka.num; const nb = kb.num; const a_nan = std.math.isNan(na); const b_nan = std.math.isNan(nb); if (a_nan and b_nan) { cmp = 0; } else if (a_nan) { cmp = -1; } else if (b_nan) { cmp = 1; } else { cmp = if (na < nb) -1 else if (na > nb) @as(i8, 1) else 0; } } else { cmp = switch (std.mem.order(u8, ka.text, kb.text)) { .lt => -1, .eq => 0, .gt => 1, }; } if (cmp == 0) continue; return if (spec.descending) cmp > 0 else cmp < 0; } // Equal on every key: keep the original order, which is what // makes the sort stable. return a < b; } }; std.mem.sort(usize, order_index, Context{ .keys = keys, .specs = specs.items }, Context.lessThan); const reordered = try t.gpa.alloc(NodeRef, nodes.len); defer t.gpa.free(reordered); for (order_index, 0..) |from, to| reordered[to] = nodes[from]; @memcpy(nodes, reordered); } /// A compiled `.`, kept for `xsl:sort` with no `select`. fn selfExpression(t: *Transformer) Error!*const xpath.Expr { if (t.self_expr) |e| return e; const e = xpath.compile(t.sheet.arena.allocator(), ".", .none) catch return error.OutOfMemory; t.self_expr = e; return e; } // -- xsl:number ---------------------------------------------------------- fn numberInstruction(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const format_text = try t.optionalAvt(doc, node, "format", focus) orelse try t.gpa.dupe(u8, "1"); defer t.gpa.free(format_text); const parsed = try number.parseFormat(t.gpa, format_text); defer t.gpa.free(parsed.tokens); // Grouping applies to the decimal numerals only, and only when both // halves of it are usable: a size that is zero, negative or not a // number at all means no grouping, and so does an empty separator. const group_separator = try t.optionalAvt(doc, node, "grouping-separator", focus); defer if (group_separator) |g| t.gpa.free(g); const group_size_text = try t.optionalAvt(doc, node, "grouping-size", focus); defer if (group_size_text) |g| t.gpa.free(g); const group_size: usize = if (group_size_text) |text| std.fmt.parseInt(usize, std.mem.trim(u8, text, " \t\n\r"), 10) catch 0 else 0; const grouping: ?number.Grouping = if (group_size != 0) if (group_separator) |sep| if (sep.len != 0) .{ .separator = sep, .size = group_size } else null else null else null; var values: std.ArrayList(i64) = .empty; defer values.deinit(t.gpa); if (sheet_mod.findAttribute(doc, node, "", "value")) |attr| { const expr = try t.sheet.expression(doc, attr); const n = try t.ev.evalNumber(expr, focus); const rounded = functions.xpathRound(n); // A `value` that is not a positive number is numbered as zero. // XSLT 7.7 says only what a positive integer means, and every // format then writes the zero its own way -- `format="001"` gives // `000` and `format="i"` gives `0`, which is what libxslt does // after complaining about the value. try values.append(t.gpa, if (std.math.isNan(rounded) or std.math.isInf(rounded) or rounded < 0) 0 else @intFromFloat(rounded)); } else { try t.countNode(doc, node, focus, &values); } var out: std.ArrayList(u8) = .empty; defer out.deinit(t.gpa); for (values.items, 0..) |v, i| { // A sequence longer than the format has tokens repeats the last // one, which is what makes `format="1."` number every level. const token = parsed.tokens[@min(i, parsed.tokens.len - 1)]; // The separator before a repeated token is the one that precedes // it in the format -- but the separator before the *only* token is // a prefix, not a separator, and XSLT 7.7.1 uses `.` in its place. // `format="1"` on three levels is `1.1.1`, and `format="(1)"` is // `(1.1.1)` rather than `(1(1(1)`. const separator = if (i < parsed.tokens.len or parsed.tokens.len > 1) token.separator else "."; try out.appendSlice(t.gpa, separator); try number.appendNumeral(t.gpa, &out, v, token, grouping); } try out.appendSlice(t.gpa, parsed.trailer); _ = try t.result.appendText(t.output, out.items); } /// Counts the current node's place, by one of the three levels. fn countNode( t: *Transformer, doc: *Document, node: NodeId, focus: Focus, out: *std.ArrayList(i64), ) Error!void { const level_text = doc.attributeValue(node, "", "level") orelse "single"; const count_pattern: ?pattern.Pattern = if (sheet_mod.findAttribute(doc, node, "", "count")) |a| try t.sheet.matchPattern(doc, a) else null; const from_pattern: ?pattern.Pattern = if (sheet_mod.findAttribute(doc, node, "", "from")) |a| try t.sheet.matchPattern(doc, a) else null; const target = focus.node; if (std.mem.eql(u8, level_text, "any")) { // XSLT 7.7: the set counted is "the current node and all nodes at // any level of the document that are before the current node in // document order, excluding any namespace and attribute nodes" -- // the union of the `preceding` and `ancestor-or-self` axes. The // exclusion is the part that is easy to miss and is what // `` turns on: an attribute of // an earlier element is not on either axis, so an attribute is // always the first of its kind. var total: i64 = 0; var started = from_pattern == null; const doc_ref = target.doc; for (0..doc_ref.nodes.items.len) |i| { const ref = doc_ref.ref(@intCast(i)); if (ref.id != target.id) { if (ref.get().order >= target.get().order) continue; if (ref.kind() == .attribute or ref.kind() == .namespace) continue; } if (from_pattern) |fp| { if (try fp.matches(&t.ev, ref)) { started = true; total = 0; continue; } } if (!started) continue; if (!try t.countMatches(count_pattern, ref, target)) continue; total += 1; } try out.append(t.gpa, total); return; } const multiple = std.mem.eql(u8, level_text, "multiple"); // Walk up from the node, counting preceding siblings that match at // each level. For `single` only the nearest matching ancestor-or-self // is counted; for `multiple` every one up to `from`. var chain: std.ArrayList(i64) = .empty; defer chain.deinit(t.gpa); var cur: ?NodeRef = target; while (cur) |n| : (cur = n.parent()) { if (from_pattern) |fp| { if (try fp.matches(&t.ev, n)) break; } if (!try t.countMatches(count_pattern, n, target)) continue; var position: i64 = 1; if (n.parent()) |p| { for (p.get().children.items) |sibling| { const ref = n.doc.ref(sibling); if (ref.get().order >= n.get().order) break; if (try t.countMatches(count_pattern, ref, target)) position += 1; } } try chain.append(t.gpa, position); if (!multiple) break; } // Collected innermost first; the output runs outermost first. var i = chain.items.len; while (i > 0) { i -= 1; try out.append(t.gpa, chain.items[i]); } if (out.items.len == 0) try out.append(t.gpa, 0); } /// Whether a node counts: against the `count` pattern if there is one, and /// otherwise against anything with the same name and kind as the node /// being numbered. fn countMatches( t: *Transformer, count_pattern: ?pattern.Pattern, candidate: NodeRef, target: NodeRef, ) Error!bool { if (count_pattern) |p| return p.matches(&t.ev, candidate); if (candidate.kind() != target.kind()) return false; return switch (candidate.kind()) { .element, .attribute, .pi => candidate.name().eql(target.name()), else => true, }; } // -- messages and diagnostics -------------------------------------------- fn message(t: *Transformer, doc: *Document, node: NodeId, focus: Focus) Error!void { const text = try t.instantiateToString(doc, node, focus); defer t.gpa.free(text); if (t.options.messages) |w| { w.writeAll(text) catch {}; w.writeAll("\n") catch {}; } if (doc.attributeValue(node, "", "terminate")) |v| { if (std.mem.eql(u8, v, "yes")) return error.Terminated; } } fn fail(t: *Transformer, comptime fmt: []const u8, args: anytype) Error { t.sheet.setDiagnostic(fmt, args); return error.InvalidStylesheet; } /// The same, carrying the XSLT error code the specification names. /// /// Worth the second function rather than a nullable parameter on the /// first: there are dozens of `fail` sites and only a handful have a code /// anyone is sure of, and a wrong code is worse than none -- it turns a /// case that was honestly unjudged into one that is confidently wrong. fn failCode( t: *Transformer, code: []const u8, comptime fmt: []const u8, args: anytype, ) Error { t.sheet.setDiagnosticCode(code, fmt, args); return error.InvalidStylesheet; } // -- helpers ------------------------------------------------------------- /// Expands a QName written on a stylesheet element. /// /// Nothing is copied: the local part and prefix are slices of the /// attribute value and the URI is a slice of a namespace declaration, all /// of which live in the stylesheet document's arena and so outlive the /// transformation. Duplicating them into the stylesheet's own arena, which /// is what this used to do, made every instantiation of an `xsl:variable` /// grow that arena by the length of its name -- a slow leak that a long /// transformation pays for in earnest. fn resolveQName(t: *Transformer, doc: *Document, scope: NodeId, text: []const u8) Error!Name { const trimmed = std.mem.trim(u8, text, " \t\n\r"); const local = localOf(trimmed); const prefix = prefixOf(trimmed) orelse return .{ .uri = "", .local = local }; const uri = doc.lookupNamespace(scope, prefix) orelse return t.fail("prefix {s}: is not declared here", .{prefix}); return .{ .uri = uri, .local = local, .prefix = prefix }; } fn expandAvt(t: *Transformer, avt: sheet_mod.Avt, focus: Focus) Error![]u8 { if (avt.constant()) |text| return t.gpa.dupe(u8, text); var out: std.ArrayList(u8) = .empty; errdefer out.deinit(t.gpa); for (avt.parts) |part| { switch (part) { .literal => |s| try out.appendSlice(t.gpa, s), .expr => |e| { const s = try t.ev.evalString(e, focus); defer t.gpa.free(s); try out.appendSlice(t.gpa, s); }, } } return out.toOwnedSlice(t.gpa); } fn optionalAvt( t: *Transformer, doc: *Document, node: NodeId, attr: []const u8, focus: Focus, ) Error!?[]u8 { const id = sheet_mod.findAttribute(doc, node, "", attr) orelse return null; const avt = try t.sheet.attributeValueTemplate(doc, id); return try t.expandAvt(avt, focus); } // -- XSLT's own functions ------------------------------------------------- fn callFunction( ctx: ?*anyopaque, ev: *Evaluator, focus: Focus, name: Name, args: []const Value, ) Error!?Value { const t: *Transformer = @ptrCast(@alignCast(ctx.?)); if (std.mem.eql(u8, name.uri, exsl_ns)) { if (std.mem.eql(u8, name.local, "node-set")) { if (args.len != 1) return error.WrongArgumentCount; // A result tree fragment is already a tree here, so a // node-set argument is handed straight back. Anything else is // converted to a string and wrapped in a fragment holding one // text node, which is what the module asks for and what makes // `exsl:node-set('a')/text()` mean something. if (args[0] == .node_set) return try args[0].clone(t.gpa); return try t.textFragment(args[0]); } if (std.mem.eql(u8, name.local, "object-type")) { if (args.len != 1) return error.WrongArgumentCount; return try Value.ownedString(t.gpa, t.objectType(args[0])); } return null; } if (name.uri.len != 0) { if (t.findExsltFunction(name)) |decl| { return try t.callExsltFunction(decl, args, focus); } // These three build node-sets, and a node-set has to hold nodes of // some document, so they are the engine's business rather than the // module's. if (std.mem.eql(u8, name.uri, regexp.ns)) { return t.regexpFunction(name.local, args) catch |err| switch (err) { error.BadPattern => t.fail( "{s}() was given a regular expression it cannot compile", .{name.local}, ), error.PatternTooCostly => t.fail( "{s}() ran out of steps on this pattern and subject", .{name.local}, ), else => |e| e, }; } if (std.mem.eql(u8, name.uri, exslt.strings_ns)) { if (std.mem.eql(u8, name.local, "tokenize")) { return try t.tokenize(args, .whitespace_or_set); } if (std.mem.eql(u8, name.local, "split")) { return try t.tokenize(args, .whole_separator); } if (std.mem.eql(u8, name.local, "replace")) { // EXSLT has `str:replace` return a *node set*, so that a // replacement may itself be nodes. What comes back here is // a node-set holding the text node, not the fragment that // owns it, which is what makes `$result/self::text()` the // string and `count($result)` one. const text = try exslt.replace(t.gpa, args); defer t.gpa.free(text); return try t.textNodeSet(text); } } if (std.mem.eql(u8, name.uri, date_mod.ns)) { return try date_mod.call(t.gpa, name.local, args, t.now()); } if (std.mem.eql(u8, name.uri, dyn_ns)) { if (std.mem.eql(u8, name.local, "evaluate")) { return try t.dynEvaluate(args, focus); } if (std.mem.eql(u8, name.local, "map")) { return try t.dynMap(args); } } return try exslt.call(ev.gpa, name, args); } const which = std.StaticStringMap(enum { current, document, key, @"format-number", @"generate-id", @"system-property", @"element-available", @"function-available", @"unparsed-entity-uri", }).initComptime(.{ .{ "current", .current }, .{ "document", .document }, .{ "key", .key }, .{ "format-number", .@"format-number" }, .{ "generate-id", .@"generate-id" }, .{ "system-property", .@"system-property" }, .{ "element-available", .@"element-available" }, .{ "function-available", .@"function-available" }, .{ "unparsed-entity-uri", .@"unparsed-entity-uri" }, }).get(name.local) orelse return null; const gpa = ev.gpa; switch (which) { .current => { if (args.len != 0) return error.WrongArgumentCount; const ns = try gpa.alloc(NodeRef, 1); ns[0] = t.current; return .{ .node_set = ns }; }, .key => { if (args.len != 2) return error.WrongArgumentCount; return try t.keyFunction(args[0], args[1], focus); }, .document => { if (args.len < 1 or args.len > 2) return error.WrongArgumentCount; return try t.documentFunction(args[0], focus); }, .@"format-number" => { if (args.len < 2 or args.len > 3) return error.WrongArgumentCount; const n = try args[0].toNumber(gpa); const picture = try args[1].toString(gpa); defer gpa.free(picture); var format: sheet_mod.DecimalFormat = .{}; if (args.len == 3) { const wanted = try args[2].toString(gpa); defer gpa.free(wanted); // The format is named by a QName, and two stylesheets may // declare `testns:format` against different namespaces. // Matching on the local part alone picks whichever was // read last. if (t.expandedName(wanted)) |named| { for (t.sheet.decimal_formats.items) |f| { if (f.name) |fname| { if (fname.eql(named)) format = f; } } } } else { for (t.sheet.decimal_formats.items) |f| { if (f.name == null) format = f; } } const text = number.formatNumber(gpa, n, picture, format) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // An unusable picture yields the plain number rather than // stopping the transformation, which is what libxslt does. error.InvalidPicture => return .{ .string = try value.numberToString(gpa, n) }, }; return .{ .string = text }; }, .@"generate-id" => { if (args.len > 1) return error.WrongArgumentCount; const node = if (args.len == 0) focus.node else blk: { if (args[0] != .node_set) return error.TypeError; if (args[0].node_set.len == 0) return try Value.ownedString(gpa, ""); break :blk args[0].node_set[0]; }; // Stable for the life of the transformation and distinct for // distinct nodes, which is all the specification asks. return .{ .string = try std.fmt.allocPrint( gpa, "d{d}n{d}", .{ node.doc.serial, node.id }, ) }; }, .@"system-property" => { if (args.len != 1) return error.WrongArgumentCount; const wanted = try args[0].toString(gpa); defer gpa.free(wanted); // Every property the specification defines is in the XSLT // namespace. `msxsl:version` names another processor's, which // this does not have, and the empty string says so. if (!t.isXsltQName(wanted)) return try Value.ownedString(gpa, ""); const local = localOf(wanted); // The same constant the version dispatch compares against, // so that what this answers and what makes a stylesheet // forwards-compatible can never drift apart. if (std.mem.eql(u8, local, "version")) { return .{ .number = sheet_mod.Stylesheet.implemented_version }; } if (std.mem.eql(u8, local, "vendor")) return try Value.ownedString(gpa, "zxsl"); if (std.mem.eql(u8, local, "vendor-url")) { return try Value.ownedString(gpa, "https://git.jcollie.dev/jeff/zxsl"); } return try Value.ownedString(gpa, ""); }, .@"element-available" => { if (args.len != 1) return error.WrongArgumentCount; const wanted = try args[0].toString(gpa); defer gpa.free(wanted); // `exsl:document` and `func:result` are the extension // elements implemented. `func:function` is deliberately not // available: it is a declaration rather than an instruction, // so an `element-available` asking whether it can be *run* is // answered no. Neither answer depends on whether the // stylesheet designated the namespace as an extension one -- // the question is what this processor can instantiate. if (t.expandedName(wanted)) |named| { if (std.mem.eql(u8, named.uri, func_ns)) { return .{ .boolean = std.mem.eql(u8, named.local, "result") }; } if (std.mem.eql(u8, named.uri, exsl_ns)) { return .{ .boolean = std.mem.eql(u8, named.local, "document") }; } } // Otherwise only XSLT's own instructions are available: no // other extension element is implemented. if (!t.isXsltQName(wanted)) return .{ .boolean = false }; return .{ .boolean = isKnownInstruction(localOf(wanted)) }; }, .@"function-available" => { if (args.len != 1) return error.WrongArgumentCount; const wanted = try args[0].toString(gpa); defer gpa.free(wanted); // An unprefixed name is the core library plus XSLT's additions; // a prefixed one is available only if it is `exsl:node-set`. if (prefixOf(wanted)) |_| { const named = t.expandedName(wanted) orelse return .{ .boolean = false }; if (std.mem.eql(u8, named.uri, exsl_ns)) { return .{ .boolean = std.mem.eql(u8, named.local, "node-set") }; } // A function the stylesheet declared with `func:function` // is as available as one built in. if (t.findExsltFunction(named) != null) return .{ .boolean = true }; if (std.mem.eql(u8, named.uri, exslt.strings_ns)) { if (std.mem.eql(u8, named.local, "tokenize") or std.mem.eql(u8, named.local, "split")) { return .{ .boolean = true }; } } if (std.mem.eql(u8, named.uri, date_mod.ns)) { return .{ .boolean = date_mod.has(named.local) }; } if (std.mem.eql(u8, named.uri, regexp.ns)) { return .{ .boolean = regexp.has(named.local) }; } if (std.mem.eql(u8, named.uri, dyn_ns)) { return .{ .boolean = std.mem.eql(u8, named.local, "evaluate") or std.mem.eql(u8, named.local, "map") }; } return .{ .boolean = exslt.has(named) }; } const local = localOf(wanted); return .{ .boolean = functions.has(local) or isXsltFunction(local) }; }, .@"unparsed-entity-uri" => { if (args.len != 1) return error.WrongArgumentCount; const wanted = try args[0].toString(gpa); defer gpa.free(wanted); // The entity is looked for in the document the context node // came from, which is the document the reference would have // had to appear in. An entity that is not declared, or is // declared without `NDATA`, is not an unparsed entity, and the // empty string is the answer for both. const dtd = &(focus.node.doc.dtd orelse return try Value.ownedString(gpa, "")); const entity = dtd.general.get(wanted) orelse return try Value.ownedString(gpa, ""); switch (entity.value) { .internal => return try Value.ownedString(gpa, ""), .external => |x| { if (x.notation == null) return try Value.ownedString(gpa, ""); return try Value.ownedString(gpa, x.id.system orelse ""); }, } }, } } /// The namespace a QName written inside an expression resolves to, or null /// when its prefix is not declared where that expression was written. /// /// An unprefixed name is in no namespace, which is what `.{}` says: the /// three functions that take a QName all treat "no namespace" as their own /// unprefixed case. fn qnameUri(t: *Transformer, text: []const u8) ?[]const u8 { const prefix = prefixOf(text) orelse return ""; const scope = t.scope orelse return null; return scope.doc.lookupNamespace(scope.node, prefix); } /// A QName written inside an expression, expanded against the namespaces /// in scope where that expression was written. /// /// The `local` and `uri` borrow from `text` and from the stylesheet, so /// the answer lives exactly as long as the string it was read from. fn expandedName(t: *Transformer, text: []const u8) ?Name { const trimmed = std.mem.trim(u8, text, " \t\n\r"); return .{ .uri = t.qnameUri(trimmed) orelse return null, .local = localOf(trimmed) }; } /// True when a QName names something in the XSLT namespace, which includes /// an unprefixed name: `system-property('version')` and /// `system-property('xsl:version')` mean the same property. fn isXsltQName(t: *Transformer, text: []const u8) bool { const uri = t.qnameUri(text) orelse return false; return uri.len == 0 or std.mem.eql(u8, uri, xslt_ns); } /// The current date and time in UTC, or null when the caller gave this /// transformation no clock. /// /// Read once and kept, because `date:date-time()` called twice in one /// transformation must not be able to disagree: a stylesheet stamping a /// document with the time is stamping it with *a* time, not with however /// long the transformation took. fn now(t: *Transformer) ?datetime.DateTime { if (t.clock_reading) |dt| return dt; const io = t.options.io orelse return null; var reading = datetime.DateTime.utc(io); // Truncated to the second, which is the precision EXSLT's examples // are written to and all libxslt reports. A stylesheet stamping a // document with the time wants a time, not a measurement. reading.nanosecond = 0; t.clock_reading = reading; return t.clock_reading; } /// A fragment holding one text node, which is what `exsl:node-set` makes /// of an argument that is not already a node-set. /// /// The node-set holds the fragment's *root*, because that is what a result /// tree fragment is here and what `exsl:node-set('x')/text()` then has a /// text node to select. fn textFragment(t: *Transformer, v: Value) Error!Value { const text = try v.toString(t.gpa); defer t.gpa.free(text); return t.textValue(text, .root); } /// The same text, but as a node-set holding the text node itself rather /// than the fragment root. `str:replace` answers this way, which is what /// makes `count($result)` one and `$result/self::text()` the string. fn textNodeSet(t: *Transformer, text: []const u8) Error!Value { return t.textValue(text, .text); } fn textValue(t: *Transformer, text: []const u8, which: enum { root, text }) Error!Value { const holder = try Document.create(t.gpa); { errdefer holder.destroy(); try t.fragments.append(t.gpa, holder); } const node = try holder.appendText(holder.root, text); holder.reindex(); const ns = try t.gpa.alloc(NodeRef, 1); // Empty text appends nothing, so there is no text node to point at and // the root is the only answer there is. ns[0] = holder.ref(if (which == .root) holder.root else node orelse holder.root); return .{ .node_set = ns }; } /// `exsl:object-type`, which names the four XPath types plus the two /// things XSLT adds to them. /// /// Telling a result tree fragment from an ordinary node-set is the whole /// difficulty, because a fragment *is* a node-set here -- so the question /// becomes whether the node-set is exactly the root of a document this /// transformation built, which is what `fragments` records. fn objectType(t: *Transformer, v: Value) []const u8 { return switch (v) { .string => "string", .number => "number", .boolean => "boolean", .node_set => |ns| blk: { if (ns.len != 1 or ns[0].kind() != .document) break :blk "node-set"; for (t.fragments.items) |f| { if (f == ns[0].doc) break :blk "RTF"; } break :blk "node-set"; }, }; } /// The declaration of an EXSLT function, taking the one of highest import /// precedence and, among equals, the one declared last. fn findExsltFunction(t: *Transformer, name: Name) ?sheet_mod.ExsltFunction { var best: ?sheet_mod.ExsltFunction = null; for (t.sheet.functions.items) |f| { if (!f.name.eql(name)) continue; if (best) |b| { if (f.precedence < b.precedence) continue; } best = f; } return best; } /// Calls a `func:function`. /// /// The arguments bind to the declared `xsl:param` children in order, and a /// parameter with no argument takes its own default -- which is why they /// are bound as ordinary parameters and the body is then instantiated: /// `declareVariable` already knows that an `xsl:param` whose name is /// already bound is a default nobody needs. /// /// The focus does not change. A function is called from an expression, and /// the expression's context node, position and size are the function /// body's too. fn callExsltFunction( t: *Transformer, decl: sheet_mod.ExsltFunction, args: []const Value, focus: Focus, ) Error!Value { t.depth += 1; defer t.depth -= 1; if (t.depth > xpath.max_depth) return error.RecursionLimit; const doc = decl.doc; const mark = t.bindings.items.len; var next: usize = 0; for (doc.node(decl.element).children.items) |child| { const n = doc.node(child); if (n.kind != .element) continue; if (!std.mem.eql(u8, n.name.uri, xslt_ns)) break; if (!std.mem.eql(u8, n.name.local, "param")) break; if (next >= args.len) break; const param_name = try t.resolveQName(doc, child, doc.attributeValue(child, "", "name") orelse return t.fail("xsl:param needs a name attribute", .{})); try t.bindings.append(t.gpa, .{ .name = param_name, .value = try args[next].clone(t.gpa), }); next += 1; } if (next < args.len) return error.WrongArgumentCount; const saved_base = t.frame_base; t.frame_base = mark; const saved_precedence = t.precedence; t.precedence = decl.precedence; const saved_result = t.func_result; t.func_result = null; defer { for (t.bindings.items[mark..]) |b| b.value.deinit(t.gpa); t.bindings.shrinkRetainingCapacity(mark); t.frame_base = saved_base; t.precedence = saved_precedence; // A body that set a result and then failed still owns it. if (t.func_result) |v| v.deinit(t.gpa); t.func_result = saved_result; } try t.instantiateChildren(doc, decl.element, focus); // A function body that reaches no `func:result` returns the empty // string, which is EXSLT's rule and not an error. const result = t.func_result orelse return Value.ownedString(t.gpa, ""); t.func_result = null; return result; } /// `str:tokenize` and `str:split`, which differ only in how the separator /// argument is read. /// /// `tokenize(string, delimiters)` treats the second argument as a *set* of /// single-character delimiters, and whitespace when it is omitted. /// `split(string, separator)` treats it as one whole separator, and a /// single space when it is omitted. An empty separator splits into /// characters, which is `split`'s documented special case. /// /// The tokens become text nodes of a document this transformation owns, /// because a node-set holds nodes and there is nowhere else to put them. fn tokenize( t: *Transformer, args: []const Value, mode: enum { whitespace_or_set, whole_separator }, ) Error!Value { if (args.len < 1 or args.len > 2) return error.WrongArgumentCount; const subject = try args[0].toString(t.gpa); defer t.gpa.free(subject); const default: []const u8 = if (mode == .whole_separator) " " else " \t\n\r"; const separator = if (args.len == 2) try args[1].toString(t.gpa) else try t.gpa.dupe(u8, default); defer t.gpa.free(separator); const holder = try Document.create(t.gpa); { errdefer holder.destroy(); try t.fragments.append(t.gpa, holder); } var b: value.NodeSetBuilder = .init(t.gpa); defer b.deinit(); if (mode == .whole_separator and separator.len == 0) { var it: usize = 0; while (it < subject.len) { const len = std.unicode.utf8ByteSequenceLength(subject[it]) catch 1; const end = @min(it + len, subject.len); try b.add(holder.ref(try appendToken(holder, subject[it..end]))); it = end; } } else if (mode == .whole_separator) { // An empty stretch between two separators is not a token, which // is what libxslt does and is the only reading that makes // `str:split` of a list with a stray extra comma in it behave. var rest = subject; while (std.mem.indexOf(u8, rest, separator)) |i| { if (i != 0) try b.add(holder.ref(try appendToken(holder, rest[0..i]))); rest = rest[i + separator.len ..]; } if (rest.len != 0) try b.add(holder.ref(try appendToken(holder, rest))); } else { // A run of delimiters yields no empty tokens, which is what makes // `str:tokenize($s)` on an indented string give the words. var it = std.mem.tokenizeAny(u8, subject, separator); while (it.next()) |token| { try b.add(holder.ref(try appendToken(holder, token))); } } holder.reindex(); return try b.toOwnedValue(); } /// EXSLT's `regexp` module. `regexp:match` is the only one of the three /// that needs anything from the transformation -- a document to hold the /// nodes it returns, which lives as long as the transformation does /// because a node-set it produced may outlive the expression. fn regexpFunction(t: *Transformer, local: []const u8, args: []const Value) regexp.Error!Value { if (std.mem.eql(u8, local, "test")) return regexp.matches(t.gpa, args); if (std.mem.eql(u8, local, "replace")) return regexp.replace(t.gpa, args); if (std.mem.eql(u8, local, "match")) { const holder = try Document.create(t.gpa); { errdefer holder.destroy(); try t.fragments.append(t.gpa, holder); } return regexp.match(t.gpa, holder, args); } // Not one of the three, so it is an unknown function like any other. return error.TypeError; } fn keyFunction(t: *Transformer, name_value: Value, want: Value, focus: Focus) Error!Value { const gpa = t.gpa; const key_name_text = try name_value.toString(gpa); defer gpa.free(key_name_text); // A key is named by a QName too, so the namespace its prefix resolves // to is part of which key is meant. const wanted = t.expandedName(key_name_text) orelse return error.UnknownKey; // The declaration's own copy of the name is what the index is keyed // by: it lives in the stylesheet's arena, where `key_name_text` is // freed the moment this call returns. var declared: ?Name = null; for (t.sheet.keys.items) |k| { if (k.name.eql(wanted)) declared = k.name; } const key_name = declared orelse return error.UnknownKey; const doc = focus.node.doc; const slot = try t.keyIndex(key_name, doc); const entries = &t.keys.items[slot].entries; var b: value.NodeSetBuilder = .init(gpa); defer b.deinit(); // A node-set argument looks up every one of its nodes' string-values, // which is what makes `key('k', @refs)` work for a list of references. switch (want) { .node_set => |ns| for (ns) |n| { const s = try n.stringValue(gpa); defer gpa.free(s); if (entries.get(s)) |list| try b.addSlice(list.items); }, else => { const s = try want.toString(gpa); defer gpa.free(s); if (entries.get(s)) |list| try b.addSlice(list.items); }, } return b.toOwnedValue(); } /// The index for one key over one document, built on first use. /// The index for one key over one document, built on first use. /// /// Returns a *position* rather than a pointer, and never holds one across /// the build. A key's own `match` pattern or `use` expression may call /// `key()` for a different key -- which is exactly what Muenchian grouping /// does, and what `bug-166` in libxslt's corpus does six ways -- and that /// nested build appends to this very list. A pointer taken before the loop /// dangles the moment the list grows, and writing entries through it /// corrupts the heap rather than failing. fn keyIndex(t: *Transformer, key_name: Name, doc: *Document) Error!usize { for (t.keys.items, 0..) |*k, i| { if (k.serial == doc.serial and k.name.eql(key_name)) return i; } // The slot is reserved *before* the build, so that a key whose own // pattern asks for this same key finds an empty index and stops rather // than recursing without end. try t.keys.append(t.gpa, .{ .name = key_name, .serial = doc.serial, .entries = .empty, }); const slot = t.keys.items.len - 1; // Built into a local map and installed at the end, for the same // reason: `t.keys` may be reallocated underneath this loop. var entries: std.StringHashMapUnmanaged(std.ArrayList(NodeRef)) = .empty; errdefer { var it = entries.iterator(); while (it.next()) |entry| { t.gpa.free(entry.key_ptr.*); entry.value_ptr.deinit(t.gpa); } entries.deinit(t.gpa); } for (t.sheet.keys.items) |decl| { if (!decl.name.eql(key_name)) continue; const decl_doc = decl.doc; const match_attr = sheet_mod.findAttribute(decl_doc, decl.element, "", "match").?; const use_attr = sheet_mod.findAttribute(decl_doc, decl.element, "", "use").?; const p = try t.sheet.matchPattern(decl_doc, match_attr); const use = try t.sheet.expression(decl_doc, use_attr); // Every node in the document, because a key indexes the document // and not a subtree. const count = doc.nodes.items.len; for (0..count) |i| { const ref = doc.ref(@intCast(i)); // A node detached by whitespace stripping is still in the // array but no longer in the tree. if (ref.kind() != .document and ref.get().parent == null) continue; if (!try p.matches(&t.ev, ref)) continue; // XSLT 12.2 evaluates `use` with the node being indexed as // both the context node and the current node, so a `use` of // `current()/@k` indexes on that node's own attribute rather // than on whatever was current when `key()` was called. const saved_current = t.current; t.current = ref; defer t.current = saved_current; const v = try t.ev.eval(use, .{ .node = ref }); defer v.deinit(t.gpa); switch (v) { // A `use` that yields a node-set indexes the node once per // node in it, which is how one element gets several keys. .node_set => |ns| for (ns) |n| { const key = try n.stringValue(t.gpa); defer t.gpa.free(key); try addKeyEntry(t.gpa, &entries, key, ref); }, else => { const key = try v.toString(t.gpa); defer t.gpa.free(key); try addKeyEntry(t.gpa, &entries, key, ref); }, } } } t.keys.items[slot].entries = entries; return slot; } fn addKeyEntry( gpa: Allocator, entries: *std.StringHashMapUnmanaged(std.ArrayList(NodeRef)), key: []const u8, node: NodeRef, ) Error!void { const found = try entries.getOrPut(gpa, key); if (!found.found_existing) { found.key_ptr.* = try gpa.dupe(u8, key); found.value_ptr.* = .empty; } try found.value_ptr.append(gpa, node); } fn documentFunction(t: *Transformer, arg: Value, focus: Focus) Error!Value { const gpa = t.gpa; var b: value.NodeSetBuilder = .init(gpa); defer b.deinit(); switch (arg) { .node_set => |ns| for (ns) |n| { const uri = try n.stringValue(gpa); defer gpa.free(uri); try t.addDocument(uri, focus, &b); }, else => { const uri = try arg.toString(gpa); defer gpa.free(uri); try t.addDocument(uri, focus, &b); }, } return b.toOwnedValue(); } /// `dyn:evaluate`, which compiles its argument as an XPath expression and /// evaluates it where the call stands. /// /// An empty string is an empty node-set rather than an error, and so is /// anything that will not compile or will not evaluate -- which is /// libxslt's behaviour and the only sane one: the expression came from the /// *document*, so a stylesheet cannot be held responsible for it and a /// transformation should not die of it. `OutOfMemory` still propagates, /// being about this process rather than about the expression. fn dynEvaluate(t: *Transformer, args: []const Value, focus: Focus) Error!Value { if (args.len != 1) return error.WrongArgumentCount; const source = try args[0].toString(t.gpa); defer t.gpa.free(source); return t.evaluateDynamic(source, focus) catch |err| switch (err) { error.OutOfMemory => error.OutOfMemory, else => .{ .node_set = &.{} }, }; } fn evaluateDynamic(t: *Transformer, source: []const u8, focus: Focus) Error!Value { if (source.len == 0) return .{ .node_set = &.{} }; const scope = t.scope orelse return .{ .node_set = &.{} }; // Prefixes resolve where the *call* was written, not where the string // came from: the document being transformed has no say in what `dyn:` // means. var resolver: sheet_mod.DynamicResolver = .{ .doc = scope.doc, .node = scope.node }; // A compile failure is not this transformation's fault -- the text // came from the document -- so it is the same empty answer as an // expression that will not evaluate. var compiled = xpath.Compiled.init(t.gpa, source, .{ .ctx = &resolver, .lookupFn = sheet_mod.DynamicResolver.lookup, }) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return .{ .node_set = &.{} }, }; defer compiled.deinit(); // An expression that evaluates itself is the reason this counts at // all. Five at a time, as libxslt does, so that a chain of them runs // out of budget long before the machine runs out of stack. t.depth += 5; defer t.depth -= 5; if (t.depth > xpath.max_depth) return error.RecursionLimit; return t.ev.eval(compiled.expr, focus); } /// `dyn:map`, which evaluates one expression once per node. /// /// The answer is a node-set, so a result that is not one has to become a /// node: a boolean, number or string is wrapped in an `exsl:boolean`, /// `exsl:number` or `exsl:string` element of a document this /// transformation owns. A false boolean wraps the *empty* string rather /// than `false`, which is libxslt's choice and is why the module is /// usable for filtering at all. fn dynMap(t: *Transformer, args: []const Value) Error!Value { if (args.len != 2) return error.WrongArgumentCount; if (args[0] != .node_set) return error.TypeError; const source = try args[1].toString(t.gpa); defer t.gpa.free(source); const nodes = args[0].node_set; var b: value.NodeSetBuilder = .init(t.gpa); defer b.deinit(); if (nodes.len == 0 or source.len == 0) return b.toOwnedValue(); const holder = try Document.create(t.gpa); { errdefer holder.destroy(); try t.fragments.append(t.gpa, holder); } for (nodes, 0..) |node, i| { const each: Focus = .{ .node = node, .position = i + 1, .size = nodes.len }; const result = t.evaluateDynamic(source, each) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => continue, }; defer result.deinit(t.gpa); switch (result) { .node_set => |ns| try b.addSlice(ns), .boolean => |v| try b.add(holder.ref( try appendWrapped(holder, "boolean", if (v) "true" else ""), )), .number => |v| { const text = try value.numberToString(t.gpa, v); defer t.gpa.free(text); try b.add(holder.ref(try appendWrapped(holder, "number", text))); }, .string => |v| try b.add(holder.ref(try appendWrapped(holder, "string", v))), } } holder.reindex(); return b.toOwnedValue(); } /// Loads one URI and adds what it names to a node-set. /// /// A URI reference is not a file name, and two things follow. Its /// percent-escapes have to come off before anything can look it up -- /// `document('doc%5Ffile.xml')` names `doc_file.xml` -- and a fragment /// identifier after a `#` selects part of the document rather than the /// whole of it. /// /// XSLT 1.0 12.1 leaves what a fragment means to the media type, and says /// the behaviour is undefined for XML. libxslt reads XPointer there, and /// the two forms it is asked for in practice are the whole of what is /// supported: `#xpointer(expression)` evaluates the expression against the /// loaded document, and a bare `#name` is `id(name)`. fn addDocument( t: *Transformer, reference: []const u8, focus: Focus, b: *value.NodeSetBuilder, ) Error!void { const hash = std.mem.findScalar(u8, reference, '#'); const uri = try unescapeUri(t.gpa, reference[0 .. hash orelse reference.len]); defer t.gpa.free(uri); const doc = try t.loadDocument(uri, focus) orelse return; const fragment = if (hash) |i| reference[i + 1 ..] else return b.add(doc.ref(doc.root)); const root: Focus = .{ .node = doc.ref(doc.root) }; const expression = if (std.mem.startsWith(u8, fragment, "xpointer(") and std.mem.endsWith(u8, fragment, ")")) fragment["xpointer(".len .. fragment.len - 1] else null; if (expression) |src| { var compiled = xpath.Compiled.init(t.gpa, src, .none) catch return; defer compiled.deinit(); const v = try t.ev.eval(compiled.expr, root); defer v.deinit(t.gpa); if (v == .node_set) try b.addSlice(v.node_set); return; } // A bare name is an id, which `id()` already knows how to find. const wanted = try Value.ownedString(t.gpa, fragment); defer wanted.deinit(t.gpa); const v = try functions.call(t.gpa, root, "id", &.{wanted}) orelse return; defer v.deinit(t.gpa); if (v == .node_set) try b.addSlice(v.node_set); } /// Turns the percent-escapes of a URI reference back into the bytes they /// stand for. A `%` that is not followed by two hexadecimal digits is /// itself, which is what a name that was never escaped looks like. fn unescapeUri(gpa: Allocator, reference: []const u8) Error![]u8 { if (std.mem.findScalar(u8, reference, '%') == null) return gpa.dupe(u8, reference); var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa); var i: usize = 0; while (i < reference.len) { if (reference[i] == '%' and i + 2 < reference.len) { if (std.fmt.parseInt(u8, reference[i + 1 ..][0..2], 16)) |byte| { try out.append(gpa, byte); i += 3; continue; } else |_| {} } try out.append(gpa, reference[i]); i += 1; } return out.toOwnedSlice(gpa); } fn loadDocument(t: *Transformer, uri: []const u8, focus: Focus) Error!?*Document { _ = focus; for (t.loaded.items) |l| { if (std.mem.eql(u8, l.uri, uri)) return l.doc; } const base = t.sheet.documents.items[0].base_uri; // `document('')` is the stylesheet itself, which is how a stylesheet // reads its own top-level data elements. It is read again rather than // handed over: the tree the engine runs from has had its // whitespace-only text nodes removed, because that is what happens to // a stylesheet, and the document a stylesheet reads with // `document('')` is not a stylesheet. const own = uri.len == 0; const text = if (own) try t.gpa.dupe(u8, t.sheet.sources.items[0]) else t.options.loader.load(t.gpa, base, uri) catch return null; defer t.gpa.free(text); const resolved = if (own) try t.gpa.dupe(u8, base) else try t.options.loader.resolve(t.gpa, base, uri); defer t.gpa.free(resolved); const doc = runtime.parse(t.gpa, text, resolved) catch return null; { errdefer doc.destroy(); const owned_uri = try t.gpa.dupe(u8, uri); errdefer t.gpa.free(owned_uri); try t.loaded.append(t.gpa, .{ .uri = owned_uri, .doc = doc }); } try t.stripSourceSpace(doc); return doc; } }; /// One of `dyn:map`'s wrappers for a result that is not a node-set: an /// element named in the EXSLT common namespace with the value as its text. fn appendWrapped(holder: *Document, local: []const u8, text: []const u8) Error!NodeId { const elem = try holder.appendElement(holder.root, .{ .uri = exsl_ns, .local = local, .prefix = "exsl", }); _ = try holder.appendText(elem, text); return elem; } /// One token of `str:tokenize` or `str:split`, which the module defines as a /// `token` element rather than as a bare text node -- and which has to be an /// element anyway, since two text nodes appended to the same parent merge into /// one and two adjacent tokens would stop being two. fn appendToken(holder: *Document, text: []const u8) Error!NodeId { const elem = try holder.appendElement(holder.root, .{ .local = "token" }); _ = try holder.appendText(elem, text); return elem; } fn isKnownInstruction(local: []const u8) bool { const table = [_][]const u8{ "apply-imports", "apply-templates", "attribute", "call-template", "choose", "comment", "copy", "copy-of", "element", "fallback", "for-each", "if", "message", "number", "param", "processing-instruction", "text", "value-of", "variable", "when", "otherwise", "sort", "with-param", }; for (table) |t| { if (std.mem.eql(u8, t, local)) return true; } return false; } fn isXsltFunction(local: []const u8) bool { const table = [_][]const u8{ "current", "document", "key", "format-number", "generate-id", "system-property", "element-available", "function-available", "unparsed-entity-uri", }; for (table) |t| { if (std.mem.eql(u8, t, local)) return true; } return false; } fn localOf(qname: []const u8) []const u8 { if (std.mem.findScalar(u8, qname, ':')) |i| return qname[i + 1 ..]; return qname; } fn prefixOf(qname: []const u8) ?[]const u8 { const i = std.mem.findScalar(u8, qname, ':') orelse return null; return qname[0..i]; } fn isAllWhitespace(s: []const u8) bool { for (s) |c| { if (c != ' ' and c != '\t' and c != '\n' and c != '\r') return false; } return true; } // -- tests ------------------------------------------------------------------- const testing = std.testing; fn run(gpa: Allocator, stylesheet_src: []const u8, source_src: []const u8) ![]u8 { const sheet = try sheet_mod.parse(gpa, stylesheet_src, .{}); defer sheet.destroy(); const source = try runtime.parse(gpa, source_src, ""); defer source.destroy(); return transformToString(gpa, sheet, source, .{}); } fn expectTransform(expected: []const u8, stylesheet_src: []const u8, source_src: []const u8) !void { const got = try run(testing.allocator, stylesheet_src, source_src); defer testing.allocator.free(got); try testing.expectEqualStrings(expected, got); } const wrap_text = \\ \\ ; const wrap_xml = \\ \\ ; /// A `Sink` that keeps every secondary document in memory, which is what a /// test wants and is also the smallest example of one. const CollectingSink = struct { gpa: Allocator, written: std.ArrayList(struct { href: []u8, bytes: []u8 }) = .empty, fn deinit(c: *CollectingSink) void { for (c.written.items) |w| { c.gpa.free(w.href); c.gpa.free(w.bytes); } c.written.deinit(c.gpa); } fn writeFn(ctx: ?*anyopaque, href: []const u8, bytes: []const u8) Error!void { const c: *CollectingSink = @ptrCast(@alignCast(ctx.?)); const h = try c.gpa.dupe(u8, href); errdefer c.gpa.free(h); const b = try c.gpa.dupe(u8, bytes); errdefer c.gpa.free(b); try c.written.append(c.gpa, .{ .href = h, .bytes = b }); } fn sink(c: *CollectingSink) Sink { return .{ .ctx = c, .writeFn = writeFn }; } }; /// Runs a stylesheet and returns the main result and every secondary /// document, the latter as `href\n` joined by a rule, so that one /// string comparison covers the lot. fn runWithSink(gpa: Allocator, stylesheet_src: []const u8, source_src: []const u8) ![]u8 { const sheet = try sheet_mod.parse(gpa, stylesheet_src, .{}); defer sheet.destroy(); const source = try runtime.parse(gpa, source_src, ""); defer source.destroy(); var collector: CollectingSink = .{ .gpa = gpa }; defer collector.deinit(); const main = try transformToString(gpa, sheet, source, .{ .sink = collector.sink() }); defer gpa.free(main); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); out.writer.writeAll(main) catch return error.OutOfMemory; for (collector.written.items) |w| { out.writer.print("--- {s}\n{s}", .{ w.href, w.bytes }) catch return error.OutOfMemory; } return out.toOwnedSlice() catch error.OutOfMemory; } test "exsl:document writes a secondary result document" { // The module's own framing example: a main document that refers to two // subsidiary ones, and the subsidiary ones built beside it. Each is a // result tree in its own right, serialized by its own attributes -- so // `method="text"` on one of them writes text while the main result is // XML. const got = try runWithSink( testing.allocator, \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ , "

first

second

", ); defer testing.allocator.free(got); try testing.expectEqualStrings( \\ \\--- a.xml \\first \\--- a.txt \\first--- b.xml \\second \\--- b.txt \\second , got); } test "exsl:document with no sink is an error rather than a silent discard" { // `Sink.none` is the default, and it refuses: a stylesheet that writes // where the caller gave it nowhere to write has not done what it said it // did, and saying so is the only honest answer. const sheet = try sheet_mod.parse(testing.allocator, \\ \\ \\ , .{}); defer sheet.destroy(); const source = try runtime.parse(testing.allocator, "", ""); defer source.destroy(); try testing.expectError( error.DocumentNotWritten, transformToString(testing.allocator, sheet, source, .{}), ); } test "an exsl:document in a namespace that was not designated is a literal result element" { // XSLT 1.0 15: an element is an extension element only if its namespace // was designated as an extension namespace. Without that designation this // is an element the stylesheet means to copy out, and copying it out is // what a processor that had never heard of EXSLT would do. try expectTransform( "
\n", \\ \\ \\ \\ , "", ); } test "element-available knows exsl:document" { // The prefix has to be declared for the argument to expand into a name at // all -- an unresolvable prefix is not available by definition -- but it // does not have to be designated an extension prefix: the question is // what this processor can instantiate, not what this stylesheet asked to // be allowed to. try expectTransform( "yes|no|", \\ \\ \\ \\yes| \\no| \\ \\ , "", ); } test "copying a namespace node declares it on the element being built" { // A namespace node is a prefix and the URI it is bound to, so copying one // is how a stylesheet puts a declaration on a result element that uses // none of it -- which is the only way to say `xmlns:a` on an element whose // own name and attributes are in no namespace at all. try expectTransform( "\n", wrap_xml ++ \\ \\ \\ \\ , "", ); } test "a copied namespace node never renames what is already written" { // XSLT 1.0 7.5: adding a declaration to an element whose own name, or one // of whose attributes' names, uses that prefix for a different namespace // would change what those names mean. The declaration is refused rather // than allowed to rewrite them. try expectTransform( "\n", \\ \\ \\ \\ \\ \\ , "", ); } test "the namespace axis comes out in libxml2's order" { // Implementation-dependent by XPath 1.0 5.4, and this is the order the // oracle uses: `xml` first, then an ancestor's declarations before the // element's own, each element's in reverse document order. try expectTransform( "[xml][b][a][f][c]", wrap_text ++ \\ \\[] \\ \\ , "", ); } test "xsl:value-of writes one node in 1.0 and every node in 2.0" { // The same stylesheet body, read twice. XSLT 1.0 takes the string-value // of the first node the expression selects and silently drops the rest; // 2.0 writes every one of them, separated. const body = \\ \\ \\ ; const source = "abc"; try expectTransform("a", wrap_text ++ \\ \\ , source); try expectTransform("a b c", \\ ++ "\n" ++ body, source); } test "xsl:value-of separator is an attribute value template" { // The default is one space with `select` and nothing without it, which is // the module's own rule and the reason the two forms are not written the // same way. const source = "ab"; try expectTransform("a-b|ab|a b", \\ \\ \\ \\ \\| \\ \\| \\ \\ \\ , source); } test "xsl:value-of without select is a sequence constructor above 1.0" { // 2.0 lets the content stand in for the attribute. Below that version the // attribute is required, and saying so beats writing nothing. // The content, not a nested `select`, so that what is being shown is the // sequence constructor and not the separator rule twice over. try expectTransform("[a-b]", \\ \\ \\[a-b] \\ , ""); const sheet = try sheet_mod.parse(testing.allocator, wrap_text ++ \\ \\ , .{}); defer sheet.destroy(); const source = try runtime.parse(testing.allocator, "", ""); defer source.destroy(); try testing.expectError( error.InvalidStylesheet, transformToString(testing.allocator, sheet, source, .{}), ); } test "a transformation can be entered at a named template" { // XSLT 2.0's other way in, and the way a large part of the W3C test suite // is written. The named template is called with no parameters and with // the source root as the current node, so a stylesheet that also reads // its input still can. const src = \\ \\ \\via-match \\via-name: \\ ; const sheet = try sheet_mod.parse(testing.allocator, src, .{}); defer sheet.destroy(); const source = try runtime.parse(testing.allocator, "", ""); defer source.destroy(); { const got = try transformToString(testing.allocator, sheet, source, .{}); defer testing.allocator.free(got); try testing.expectEqualStrings("via-match", got); } { const got = try transformToString(testing.allocator, sheet, source, .{ .initial_template = .{ .local = "start" }, }); defer testing.allocator.free(got); try testing.expectEqualStrings("via-name:2", got); } // A name no template carries is a stylesheet error with a diagnostic, not // an empty result. try testing.expectError(error.InvalidStylesheet, transformToString( testing.allocator, sheet, source, .{ .initial_template = .{ .local = "nonesuch" } }, )); } test "a transformation can be entered in a named mode" { const src = \\ \\ \\unnamed \\in-toc \\ ; const sheet = try sheet_mod.parse(testing.allocator, src, .{}); defer sheet.destroy(); const source = try runtime.parse(testing.allocator, "", ""); defer source.destroy(); { const got = try transformToString(testing.allocator, sheet, source, .{}); defer testing.allocator.free(got); try testing.expectEqualStrings("unnamed", got); } { const got = try transformToString(testing.allocator, sheet, source, .{ .initial_mode = .{ .local = "toc" }, }); defer testing.allocator.free(got); try testing.expectEqualStrings("in-toc", got); } } test "a step limit stops work that nesting does not bound" { // The recursion guard counts frames, so it catches a template that calls // itself. It does not catch a stylesheet that loops sideways -- this one // nests two deep and instantiates without end, which is the shape a // harness running stylesheets nobody has read will meet. const src = \\ \\ \\ \\ \\ \\ . \\ \\ \\ ; const sheet = try sheet_mod.parse(testing.allocator, src, .{}); defer sheet.destroy(); const source = try runtime.parse(testing.allocator, "", ""); defer source.destroy(); try testing.expectError( error.StepLimitExceeded, transformToString(testing.allocator, sheet, source, .{ .step_limit = 50 }), ); // And with no limit it is the recursion guard that stops it, which is the // behaviour every caller had before this option existed. try testing.expectError( error.RecursionLimit, transformToString(testing.allocator, sheet, source, .{}), ); } test "a step limit large enough to finish changes nothing" { // The counter must not be able to fail a transformation that would // otherwise have succeeded, which is the only way this option could do // harm. try expectTransform( "abc", wrap_text ++ \\ \\ , "abc", ); const sheet = try sheet_mod.parse(testing.allocator, wrap_text ++ \\ \\ , .{}); defer sheet.destroy(); const source = try runtime.parse(testing.allocator, "abc", ""); defer source.destroy(); const got = try transformToString(testing.allocator, sheet, source, .{ .step_limit = 1_000 }); defer testing.allocator.free(got); try testing.expectEqualStrings("abc", got); } test "an extension element runs its fallback" { // XSLT 1.0 15: an element in an extension namespace is an instruction, and // a processor that does not implement it runs the `xsl:fallback` children // instead -- all of them, and nothing else the element contains. The // extension namespace itself never reaches the result. try expectTransform( "\n", \\ \\ \\ \\ , "", ); } test "an extension element with no fallback is an error" { const err = run( testing.allocator, \\ \\ \\ , "", ); try testing.expectError(error.InvalidStylesheet, err); } test "unparsed-entity-uri answers only for an NDATA entity" { try expectTransform( "[graphic.gif][][]", wrap_text ++ \\[][][] \\ , \\ \\ \\ \\]> \\ , ); } test "document('') reads the stylesheet with its whitespace intact" { // The tree the engine runs from has had its whitespace-only text nodes // removed, because that is what XSLT 3.4 does to a stylesheet. What // `document('')` hands back is not a stylesheet, and its indentation is // still there. try expectTransform( "[\n][\n]", wrap_text ++ \\ \\[] \\ \\ , "", ); } test "a multi-level xsl:number separates its levels" { const sheet = wrap_text ++ \\ \\[][][][] \\ ; try expectTransform("[1.1.1][(1.1.1)][1.1.1][A-1-1]", sheet, ""); } test "a parameter no xsl:param claims is ignored, not shadowing" { // XSLT 11.6: passing a parameter to a template that declares none of that // name is not an error, and the parameter is ignored. Ignored has to mean // invisible -- a binding left in place would hide the global for the whole // template. const sheet = wrap_text ++ \\ \\[] \\[] \\ \\ \\ \\ \\ ; try expectTransform("[passed][global]", sheet, ""); } test "a global variable of higher import precedence wins" { // The importing stylesheet outranks what it imports, and its declarations // are read last -- so taking the first declaration of a name, which is // what skipping an already-bound one amounts to, had it exactly backwards. const gpa = testing.allocator; const imported = \\ \\imported \\ ; const Imported = struct { var text: []const u8 = ""; fn loadFn(_: ?*anyopaque, a: Allocator, _: []const u8, _: []const u8) Error![]u8 { return a.dupe(u8, text); } fn resolveFn(_: ?*anyopaque, a: Allocator, _: []const u8, href: []const u8) Error![]u8 { return a.dupe(u8, href); } }; Imported.text = imported; const sheet = try sheet_mod.parse(gpa, \\ \\ \\ \\importing \\ \\ , .{ .loader = .{ .loadFn = Imported.loadFn, .resolveFn = Imported.resolveFn } }); defer sheet.destroy(); const source = try runtime.parse(gpa, "", ""); defer source.destroy(); const got = try transformToString(gpa, sheet, source, .{}); defer gpa.free(got); try testing.expectEqualStrings("importing", got); } test "a QName argument is read in the namespace it was written in" { try expectTransform( "[1][][true][false][true][false]", \\ \\ \\[][][][][][] \\ , "", ); } test "a key's use expression is evaluated with the indexed node as current" { try expectTransform( "hello", wrap_text ++ \\ \\ \\ , "hello2", ); } test "level=any counts neither attributes nor namespace nodes" { // XSLT 7.7 counts "the current node and all nodes at any level of the // document that are before the current node in document order, excluding // any namespace and attribute nodes" -- the union of the `preceding` and // `ancestor-or-self` axes. An attribute of an earlier element is on // neither, so every attribute is the first of its kind; the ancestors of a // namespace node are on one of them, so its element's depth is what it // counts. try expectTransform( "[1][1][1]", wrap_text ++ \\ \\[] \\ , "", ); try expectTransform( "[1][2][3]", wrap_text ++ \\ \\[] \\ , "", ); } test "xsl:number writes a value below one as zero" { // XSLT 7.7 says what a positive integer means and nothing else, and each // format writes the zero its own way: the width a padded token asks for is // still honoured, and a system with no zero falls back to a plain digit. try expectTransform( "[000][000][007][0][0][0]", wrap_text ++ \\[][][][][][] \\ , "", ); } test "a decimal format and a key are named by expanded QNames" { // Two declarations may share a local part and differ in namespace, and // matching on the local part alone picks whichever was read last. try expectTransform( "[123,00][hit]", \\ \\ \\ \\ \\ \\ \\[][] \\ , "hit", ); } test "cdata-section-elements takes the default namespace, strip-space does not" { // The first is a list of QNames and the second a list of NameTests, and // XPath never applies a default namespace to an unprefixed name test. try expectTransform( "\n", \\ \\ \\a \\ , "", ); try expectTransform( "[ ]", \\ \\ \\ \\ \\[] \\ , " ", ); } test "a sort key sees the node it is the key of" { // XSLT 10 computes a key with the node being sorted as the current node. // Without that, `current()` in a key is whatever the enclosing template // was processing, the key is the same for every node, and a sort level // does nothing at all -- which is how a two-level sort silently becomes a // one-level one. try expectTransform( "[a3][b1][a2][c2]", wrap_text ++ \\ \\ \\ \\ \\ \\[] \\ , "

a2

b1

a3

c2

", ); } const wrap_func = \\ \\ ; test "a func:function is callable from any expression" { try expectTransform( "[16][default][]", wrap_func ++ \\ \\ \\ \\[][][] \\ , "", ); } test "func:result ends the function it is in" { // Everything after it in the body is skipped, at whatever depth -- which // is the whole of its control flow, and the only thing that makes a // function with an `xsl:choose` in it work. try expectTransform( "[first][6]", wrap_func ++ \\ \\ \\ \\ \\ \\[][] \\ , "", ); } test "a func:result may build a tree, and function-available sees the function" { try expectTransform( "12\n", \\ \\ \\ \\ \\ , "12", ); } test "a fragment does not carry the stylesheet's namespace declarations" { // A literal result element written straight into the result tree takes // the declarations in scope on it; one built inside a result tree fragment // does not, because its elements are copied out later and the copy // declares whatever their names then need. Carrying the whole scope // through a variable would put a declaration nothing uses on every element // that passed through one. try expectTransform( "\n", \\ \\ \\
\\ , "", ); } test "a global variable may refer to one declared after it" { // XSLT 11.4: the order in which global variables are declared does not // matter. Evaluating them in declaration order cannot honour that, so // none is evaluated until something asks for it. try expectTransform( "[late-then-early]", wrap_text ++ \\ \\ \\[] \\ , "", ); } test "a global variable defined in terms of itself is reported" { const err = run( testing.allocator, wrap_text ++ \\ \\ \\ , "", ); try testing.expectError(error.InvalidStylesheet, err); } test "the EXSLT modules answer from an expression" { // `set:difference` and `set:intersection` compare nodes, not their // string-values, so two disjoint sets intersect in nothing however much // their text agrees -- while `set:distinct` is about string-values and // drops the second `2`. try expectTransform( "[1,2,2,][][1,2,][3][7][a|b|c|][a|b|c|]", \\ \\ \\[,][,][,][][][|][|] \\ , "12229537", ); } const wrap_regexp = \\ \\ ; test "regexp:match returns the module's own examples" { // Every line here is an example out of the module's own page, which is // the only reference there is: libxslt implements no `regexp`, so nothing // in the corpus covers these and there is nothing to compare against. // // The trailing spaces in the last two are the point of them. The page // renders `his`, `is`, `a`, `test` for a pattern ending in a space, which // reads like the captures until the whitespace at the end of each line is // taken seriously -- the elements hold whole matches, and a whole match // of `([a-z])+ ` ends with the space it asked for. try expectTransform( "uri:[http://www.bayes.co.uk/xml/index.xml?/xml/utils/rechecker.xml][http][www.bayes.co.uk][][/xml/index.xml?/xml/utils/rechecker.xml]|" ++ "g1:[This][is][a][test][string]|" ++ "g2:[his ][is ][a ][test ]|" ++ "gi:[This ][is ][a ][test ]|", wrap_regexp ++ \\ \\uri: \\[] \\|g1: \\[] \\|g2: \\[] \\|gi: \\[] \\| \\ \\ , "", ); } test "regexp:replace and regexp:test" { // The module's `replace` example, and the two things its text settles: // without `g` only the first occurrence goes, and `g` on `test` is // accepted and does nothing because it is "retained for consistency". // // The last one is this implementation's own reading rather than the // module's: the replacement is literal, so `$1` is a dollar sign and a // one. The module calls the fourth argument "the string to replace the // matched parts" and mentions JavaScript only for the pattern. try expectTransform( "g:Is this EXSLT? No. yes!!!|" ++ "gi:Is this EXSLT? yes!!!. yes!!!|" ++ "i:Is this EXSLT? yes!!!. no|" ++ "test:true false true|" ++ "literal:[$1]|", wrap_regexp ++ \\ \\g: \\|gi: \\|i: \\|test: \\ \\ \\ \\|literal:[]| \\ \\ , "", ); } test "a regexp:match element holds no text node when its group did not participate" { // The URI example's `(:\d*)?` matches nothing, and what comes out is // `` rather than ``: the two have the same // string-value, and an element with no child is what an absent group // actually is. try expectTransform( "aba\n", \\ \\ \\ \\ , "", ); } test "a pattern that will not compile fails the transformation and says so" { // Not an empty node-set: a pattern is nearly always written in the // stylesheet, so one the engine cannot compile is a mistake worth // stopping for rather than a silent "no match" for the rest of the run. const sheet = try sheet_mod.parse(testing.allocator, wrap_regexp ++ \\ \\ , .{}); defer sheet.destroy(); const source = try runtime.parse(testing.allocator, "", ""); defer source.destroy(); try testing.expectError( error.InvalidStylesheet, transformToString(testing.allocator, sheet, source, .{}), ); try testing.expect(sheet.diagnostic != null); try testing.expect(std.mem.indexOf(u8, sheet.diagnostic.?, "test()") != null); } test "function-available knows the regexp module" { try expectTransform( "true true true false", wrap_regexp ++ \\ \\ \\ \\ \\ \\ \\ , "", ); } test "a token of str:tokenize is a node in document order" { // The tokens are `token` elements of a document the transformation owns, // which is what lets a node-set hold them at all -- and they come out in // the order they were cut, because a node-set is sorted by document order // and they were appended in that order. try expectTransform( "ab\n", \\ \\ \\ \\ , "", ); } test "an extension namespace is excluded only when it is designated" { // EXSLT's namespaces are not special to the result tree: `exsl` and `func` // reach it like any other declaration unless the stylesheet says // otherwise, and `extension-element-prefixes` is one of the two ways of // saying so. const sheet = \\ \\ \\ \\ ; try expectTransform( "\n", sheet, "", ); try expectTransform( "\n", \\ \\ \\ \\ , "", ); } test "a parameter does not survive a built-in rule" { // XSLT 1.0 5.8 defines the built-in rules as literal templates, and they // have no `xsl:param` -- so 11.6 ignores a parameter passed to one, and // the rule's own `xsl:apply-templates` passes nothing on. libxslt threads // the parameters through instead, which is worth knowing when porting a // stylesheet: one relying on it needs an explicit rule for the elements // in between, which it needs anyway to run on anything else. const sheet = wrap_text ++ \\ \\[] \\ ; try expectTransform("[default]", sheet, ""); // With a rule for the element in between, and that rule passing the // parameter on, it arrives. try expectTransform( "[passed]", wrap_text ++ \\ \\ \\[] \\ , "", ); } const wrap_dyn = \\ \\ ; test "dyn:evaluate compiles an expression the document supplied" { // The prefixes in it mean whatever they mean where the *call* was // written: the document being transformed has no say in what `dyn:` is. try expectTransform( "[2][b][]", wrap_dyn ++ \\[][][] \\ , "ab", ); } test "dyn:evaluate answers an expression it cannot run with nothing" { // The expression came from the document, so a stylesheet cannot be held // responsible for it and a transformation should not die of it -- not // even when it evaluates itself, which is what the second of these does. try expectTransform( "[][]", wrap_dyn ++ \\[][] \\ , "dyn:evaluate(.)", ); } test "dyn:map wraps a result that is not a node-set" { // The answer has to be a node-set, so a boolean, number or string becomes // an element in the EXSLT common namespace. A false boolean wraps the // empty string rather than `false`, which is what makes the module usable // for filtering. try expectTransform( "" ++ "1" ++ "2" ++ "true" ++ "" ++ "ab\n", \\ \\ \\ \\ , "ab", ); } test "generate-id names every kind of node, distinctly and in ASCII" { // XSLT 12.4 asks for four things and says nothing else: the id is ASCII // alphanumeric, it begins with a letter, the same node gets the same one // twice, and different nodes get different ones. libxslt's corpus tests // this by comparing the ids *literally*, which is a test of libxslt's // numbering rather than of the function -- so the properties the // specification actually states are pinned here instead. const gpa = testing.allocator; const got = try run( gpa, wrap_text ++ \\ \\ , "text", ); defer gpa.free(got); var seen: std.ArrayList([]const u8) = .empty; defer seen.deinit(gpa); var it = std.mem.tokenizeScalar(u8, got, ' '); while (it.next()) |id| { try testing.expect(id.len != 0); try testing.expect(std.ascii.isAlphabetic(id[0])); for (id) |c| try testing.expect(std.ascii.isAlphanumeric(c)); for (seen.items) |other| { if (std.mem.eql(u8, id, other)) { std.debug.print("two nodes share the id {s}\n{s}\n", .{ id, got }); return error.TestUnexpectedResult; } } try seen.append(gpa, id); } // The document, four elements-and-text, an attribute, a comment, a // processing instruction and the namespace nodes: enough that every kind // is in there and none of them collided. try testing.expect(seen.items.len >= 9); } test "an id is stable for a node and never shared between two" { try expectTransform( "[true][true][][false]", \\[][][][] , "", ); } test "the built-in rules copy text when nothing matches" { try expectTransform( "onetwo", wrap_text ++ \\ , "onetwo", ); } test "value-of, for-each and if" { try expectTransform("[one][three]", wrap_text ++ \\ \\ \\ [] \\ \\ \\ , \\onetwothree ); } test "position and last are the loop's, not the document's" { try expectTransform( "1/3 2/3 3/3 ", wrap_text ++ \\ \\ \\ / \\ \\ \\ \\ , "", ); } test "template priority picks the more specific rule" { try expectTransform( "specific", wrap_text ++ \\ \\generic \\specific \\ , "", ); } test "source whitespace is preserved unless strip-space names the element" { // The default is the opposite of the stylesheet's own: `xsl:strip-space` // names what to throw away, and everything else keeps its spacing. A // narrow rule must not quietly strip the whole document. try expectTransform( "[ [a] ][[b]]", wrap_text ++ \\ \\ \\[] \\ , " a b ", ); } test "an unprefixed name in strip-space means no namespace, not any" { // Only `*` matches every namespace. `elements="c"` is the `c` in no // namespace, exactly as a name test in a pattern is -- the default // declaration reaches neither. try expectTransform( "[[b]][ [a] ]", wrap_text ++ \\ \\ \\[] \\ , " b a ", ); } test "preserve-space outranks a wildcard strip-space" { try expectTransform( "[ [a] ][[b]]", wrap_text ++ \\ \\ \\ \\[] \\ , " a b ", ); } test "attribute sets chain, merge, and lose to what is stronger" { // `outer` uses `inner`, and the element has an attribute of its own. All // three set `a`, and the element must win -- but the sets are written // first, so `a` keeps the position the set gave it and takes the element's // value. Position from the first write, value from the last. try expectTransform( "\n", \\ \\ \\ \\ inner \\ inner \\ \\ \\ outer \\ outer \\ \\ \\ , "", ); // Two definitions of one name are merged, and `xsl:element` gets the same // treatment as a literal result element. try expectTransform( "\n", \\ \\ \\one \\two \\ \\ , "", ); } test "an imported attribute set loses to the importing one, including its used sets" { // The subtle half: the importing definition's *used* set outranks the // imported definition's *own* attribute. Applying all the definitions' // own attributes first and their used sets afterwards gets this wrong. const gpa = testing.allocator; const Imported = struct { fn loadFn(_: ?*anyopaque, a: Allocator, _: []const u8, _: []const u8) Error![]u8 { return a.dupe(u8, \\ \\ \\ BAD \\ BAD \\ \\ ); } fn resolveFn(_: ?*anyopaque, a: Allocator, _: []const u8, href: []const u8) Error![]u8 { return a.dupe(u8, href); } }; const sheet = try sheet_mod.parse(gpa, \\ \\ \\ \\ \\ GOOD \\ \\ \\ GOOD \\ \\ \\ , .{ .loader = .{ .loadFn = Imported.loadFn, .resolveFn = Imported.resolveFn } }); defer sheet.destroy(); const source = try tree.parse(gpa, "", .{}); defer source.destroy(); const out = try transformToString(gpa, sheet, source, .{}); defer gpa.free(out); try testing.expectEqualStrings("\n", out); } test "a set named later in the list beats one named earlier" { // And an attribute only the element carries is appended after the sets', // which is what the specification's own example in section 7.1.4 shows. try expectTransform( "\n", \\ \\ \\ \\ first \\ first \\ \\second \\ \\ , "", ); // Two definitions of one name at the same precedence merge, and the later // one wins -- while the attribute keeps the position of its first write. try expectTransform( "\n", \\ \\ \\ \\ 1 \\ 2 \\ 1 \\ \\2 \\ \\ , "", ); } test "attribute sets that use each other in a circle are an error" { const result = run(testing.allocator, \\ \\ \\ \\ \\ , ""); try testing.expectError(error.InvalidStylesheet, result); } test "the rule index resolves conflicts the way the scan did" { // Every rule below could match the node; only the order matters. The // index files them in different buckets -- by name, the element wildcard, // `node()` -- so this is the check that a merge across buckets still // picks what a scan over all of them would. try expectTransform( "name", wrap_text ++ \\ \\node \\star \\name \\ , "", ); // A stated priority beats the default that would otherwise win. try expectTransform( "star", wrap_text ++ \\ \\star \\name \\ , "", ); // Equal priority: the one written last wins. try expectTransform( "second", wrap_text ++ \\ \\first \\second \\ , "", ); // A predicate that fails hands the node to the next-best rule rather than // to nothing -- which is what makes the merge have to keep walking. try expectTransform( "star", wrap_text ++ \\ \\star \\name \\ , "", ); } test "node() does not match the root" { // `node()` is `child::node()`, and the root is not a child of anything, so // it is left to `/` and to the built-in rule. Matching it there stops the // traversal at the root and produces nothing. try expectTransform( "[r][a]", wrap_text ++ \\[] \\ , "", ); } test "modes keep two traversals apart" { try expectTransform( "TOC:x BODY:x ", wrap_text ++ \\ \\ \\ \\ \\TOC: \\BODY: \\ , "x", ); } test "variables and parameters" { try expectTransform( "global local 42", wrap_text ++ \\global \\ \\ local \\ \\ \\ \\ \\ \\ 0 \\ \\ \\ , "", ); } test "a called template does not see its caller's variables" { // `$hidden` is in scope where the call is written but not inside the // template, which is what the frame floor is for. const gpa = testing.allocator; const result = run(gpa, wrap_text ++ \\ \\ x \\ \\ \\ \\ , ""); try testing.expectError(error.UnknownVariable, result); } test "sorting, by text and by number" { try expectTransform( "10 2 9 |2 9 10 |10 9 2 |", wrap_text ++ \\ \\ \\ | \\ \\ | \\ \\ | \\ \\ , "9102", ); } test "case-order chooses which case sorts first" { // XSLT 10's `case-order`, which is the collation's `caseFirst`. Default // is the table's own order, which for the root collation is lowercase // first; `upper-first` inverts it. Case is a tertiary difference either // way, so it only decides between keys that are otherwise equal. try expectTransform( "a A b B |A a B b |a A b B |", wrap_text ++ \\ \\ \\ | \\ \\ | \\ \\ | \\ \\ , "BaAb", ); } test "case-order applies to text sorts only" { // XSLT 10 scopes it: it "applies when data-type='text'". A numeric sort // compares numbers and has no case to order, so the attribute is // ignored rather than refused. try expectTransform( "2 10 |2 10 |", wrap_text ++ \\ \\ \\ | \\ \\ | \\ \\ , "102", ); } test "lang selects a collation and an unknown one falls back to the root" { // Every one of these is the root collation, whatever `-Dlocales` this // build was given, and the point of the test is that naming a language // is never an error and never changes the answer into nonsense. // // German is root-ordered because CLDR has no `standard` tailoring for // it -- the root collation is already its answer -- which is what makes // `REC/test-10-3` pass, since that case sorts with `lang="de"`. Quebec // French has one, but it only asks for `[backwards 2]`, and these three // names differ at the primary level where that never looks. const expected = "Märtens Möller Mueller |Märtens Möller Mueller |" ++ "Märtens Möller Mueller |Märtens Möller Mueller |"; try expectTransform( expected, wrap_text ++ \\ \\ \\ | \\ \\ | \\ \\ | \\ \\ | \\ \\ , "MuellerMärtensMöller", ); } test "a tailoring puts letters where the root collation does not" { // The whole point of `lang`. Swedish's å, ä and ö are letters after z // rather than variants of a and o; Czech sorts `ch` as a letter between // h and i; Turkish's dotless ı is a letter of its own, before i rather // than beside it. None of the three is reachable from the root // collation, and all three are what a reader of that language expects. if (collate.locales.match("sv") == null) return error.SkipZigTest; try expectTransform( "sv: Ahlgren Zetterlund Ängström Östberg |root: Ahlgren Ängström Östberg Zetterlund |", wrap_text ++ \\ \\ sv: \\ \\ |root: \\ \\ | \\ \\ , "ÖstbergZetterlundAhlgrenÄngström", ); try expectTransform( "cs: cukr hora chata irena |root: chata cukr hora irena |", wrap_text ++ \\ \\ cs: \\ \\ |root: \\ \\ | \\ \\ , "chatahorairenacukr", ); try expectTransform( "tr: halk ılık iyi zil |root: halk iyi ılık zil |", wrap_text ++ \\ \\ tr: \\ \\ |root: \\ \\ | \\ \\ , "zilılıkiyihalk", ); } test "a language tag falls back to the most specific tailoring there is" { // `lang` carries a language tag, and a tag is matched by dropping its // last subtag until something is found: Finland Swedish is Swedish, and // a tag nobody has a tailoring for is the root collation rather than an // error. That is zig-collate's `locales.match`, and what this checks is // that `xsl:sort` hands it the attribute rather than looking for an // exact file name. if (collate.locales.match("sv") == null) return error.SkipZigTest; try expectTransform( "Ahlgren Zetterlund Ängström Östberg |Ahlgren Ängström Östberg Zetterlund |", wrap_text ++ \\ \\ \\ | \\ \\ | \\ \\ , "ÖstbergZetterlundAhlgrenÄngström", ); } test "a locale's own settings apply, and case-order overrides them" { // Danish's rules open with `[caseFirst upper]`, which is a parametric // setting rather than a weight: it is recorded on the tailoring and // changes how a sort key is built. Taking it up is what puts `AA` before // `aa`, and CLDR relies on all three cases of `aa` being distinguishable // -- Danish sorts `aa` with å, after z, and orders the three spellings // among themselves by case. // // `case-order` then has to be able to win, because it is what the // stylesheet asked for and the locale's opinion is only a default. if (collate.locales.match("da") == null) return error.SkipZigTest; try expectTransform( "da: ab zz AA Aa aa |lower-first: ab zz aa Aa AA |", wrap_text ++ \\ \\ da: \\ \\ |lower-first: \\ \\ | \\ \\ , "aaAaAAabzz", ); } test "lang and case-order are attribute value templates" { // XSLT 10 lists both as attribute value templates, so a stylesheet can // compute them. Nothing else about them is special. try expectTransform( "A a |", wrap_text ++ \\ \\ \\ \\ \\ \\ | \\ \\ , "aA", ); } test "literal result elements and attribute value templates" { try expectTransform( "\n", \\ \\ \\ \\ \\ \\ , "", ); } test "copy is shallow and copy-of is deep" { try expectTransform( "\n", \\ \\ \\ \\ , "", ); } test "keys index the document" { try expectTransform("Beta", wrap_text ++ \\ \\ \\ , \\AlphaBeta ); } test "xsl:number counts a node's place" { try expectTransform( "1.2.", wrap_text ++ \\ \\ \\ , "", ); } test "current() is not the context node" { try expectTransform("match", wrap_text ++ \\ \\ \\ match \\ \\ \\ , \\ ); } test "a result tree fragment can be looked inside" { // XSLT 1.0 says a fragment may only become a string, and libxslt raises // `Invalid type` for both of these. Here a fragment is a real tree, so // both work and `exsl:node-set` has nothing left to convert. It is the one // place this library is deliberately more permissive than the // specification, because the strict behaviour breaks stylesheets that // every other processor runs. try expectTransform( "2 2 two", \\ \\ \\ \\ onetwo \\ \\ \\ \\ \\ , "", ); } test "apply-templates recurses through the built-in rule" { try expectTransform( "
  • one
  • two
\n", \\ \\ \\
\\
  • \\
    , "onetwo", ); }