Something went wrong. Try again.
An XSLT 1.0 processor for Zig 0.16, built on zxml.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! XSLT match patterns: what `xsl:template match="..."` compares a node//! against, and how two templates that both match are told apart.//!//! A pattern is written like a location path but it does not mean one. `title`//! as an expression selects the title children of the context node; as a//! pattern it asks whether *this* node is a title child of something. The//! specification defines it that way round -- a node matches when it is in the//! node-set some ancestor would select -- and the consequence is that a//! pattern is matched from its **last** step backwards. `chapter/title`//! against a node is "is this a title, and is its parent a chapter", which//! answers in two steps instead of walking the document.//!//! Because a pattern is syntactically a location path, it is compiled by the//! XPath parser rather than by a second one. That also means `//` has already//! become a `descendant-or-self::node()` step by the time it arrives here, and//! such a step read backwards is exactly "any ancestor" -- which is what the//! abbreviation means in a pattern too.//!//! The one shape this cannot answer backwards is a pattern rooted at `id()` or//! `key()`, since neither can be checked without evaluating it. Those fall//! back to evaluating the pattern and testing for membership, which is correct//! and slow, and which is why it is not how the others work.
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 NodeRef = tree.NodeRef;const Evaluator = runtime.Evaluator;const Error = runtime.Error;const Focus = xpath.Focus;
/// One alternative of a pattern. `a|b` is two of these, because the/// specification gives each alternative its own default priority and treats/// them as separate template rules.pub const Alternative = struct { steps: []const xpath.Step, absolute: bool, /// For a pattern rooted at `id()` or `key()`, the whole expression, to be /// evaluated and searched rather than matched backwards. membership: ?*const xpath.Expr = null, /// The default priority the specification assigns this shape, used unless /// the template says otherwise. priority: f64,};
pub const Pattern = struct { alternatives: []const Alternative,
/// True when `node` matches any alternative. pub fn matches(p: Pattern, ev: *Evaluator, node: NodeRef) Error!bool { for (p.alternatives) |alt| { if (try matchAlternative(ev, alt, node)) return true; } return false; }};
/// Compiles a pattern, allocating from `arena`.////// The alternatives come back separately so that the caller can install each/// as its own template rule, which is what the specification says happens to/// `match="a|b"`.pub fn compile( arena: Allocator, src: []const u8, ns: xpath.NsResolver,) (xpath.CompileError || error{InvalidPattern})!Pattern { const expr = try xpath.compile(arena, src, ns);
var alts: std.ArrayList(Alternative) = .empty; defer alts.deinit(arena); try flatten(arena, expr, &alts); return .{ .alternatives = try arena.dupe(Alternative, alts.items) };}
/// Splits a `|` tree into its alternatives, refusing anything that is a valid/// expression but not a valid pattern.fn flatten( arena: Allocator, expr: *const xpath.Expr, out: *std.ArrayList(Alternative),) (xpath.CompileError || error{InvalidPattern})!void { switch (expr.*) { .binary => |b| { if (b.op != .union_) return error.InvalidPattern; try flatten(arena, b.lhs, out); try flatten(arena, b.rhs, out); }, .path => |p| { if (p.start) |start| { // Only `id()` and `key()` may root a pattern. Anything else -- // `$x/foo`, `(a|b)/c` -- is an expression, not a pattern. if (start.* != .call) return error.InvalidPattern; const local = start.call.name.local; if (start.call.name.uri.len != 0) return error.InvalidPattern; if (!std.mem.eql(u8, local, "id") and !std.mem.eql(u8, local, "key")) { return error.InvalidPattern; } try out.append(arena, .{ .steps = p.steps, .absolute = false, .membership = expr, .priority = 0.5, }); return; } for (p.steps) |s| { if (!axisAllowed(s.axis)) return error.InvalidPattern; } try out.append(arena, .{ .steps = p.steps, .absolute = p.absolute, .priority = defaultPriority(p.absolute, p.steps), }); }, // A bare `id('x')` with no following steps is a pattern too. .call => |c| { if (c.name.uri.len != 0) return error.InvalidPattern; if (!std.mem.eql(u8, c.name.local, "id") and !std.mem.eql(u8, c.name.local, "key")) { return error.InvalidPattern; } try out.append(arena, .{ .steps = &.{}, .absolute = false, .membership = expr, .priority = 0.5, }); }, else => return error.InvalidPattern, }}
/// A pattern may only step down: `child::`, `attribute::`, and the/// `descendant-or-self::node()` that `//` abbreviates.fn axisAllowed(axis: xpath.Axis) bool { return switch (axis) { .child, .attribute, .descendant_or_self => true, else => false, };}
/// True for the step `//` expands to, which read backwards means "any/// ancestor" rather than a step of its own.fn isConnector(step: xpath.Step) bool { return step.axis == .descendant_or_self and step.node_test == .any and step.predicates.len == 0;}
/// The priority the specification gives a pattern that does not state one.////// The scale only has four values, and they exist so that a more specific/// rule wins without anybody having to say so: a name beats `prefix:*`, which/// beats a bare `*`, and anything with a path or a predicate in it beats all/// three.pub fn defaultPriority(absolute: bool, steps: []const xpath.Step) f64 { // `/` on its own. if (steps.len == 0) return 0.5; // Anything with more than one step, or rooted, or filtered, is specific // enough to outrank every bare node test. if (steps.len != 1 or absolute or steps[0].predicates.len != 0) return 0.5;
const step = steps[0]; return switch (step.node_test) { .name => |nt| if (nt.local != null) // A QName. 0 else if (nt.uri != null) // `prefix:*` -0.25 else // `*` -0.5, // `processing-instruction('target')` names one thing, so it ranks // with a QName; the unqualified form is just a node test. .pi => |target| if (target != null) 0 else -0.5, .any, .text, .comment => -0.5, };}
// -- matching ----------------------------------------------------------------
fn matchAlternative(ev: *Evaluator, alt: Alternative, node: NodeRef) Error!bool { if (alt.membership) |expr| return matchByMembership(ev, expr, node); return matchFrom(ev, node, alt.steps, @as(isize, @intCast(alt.steps.len)) - 1, alt.absolute);}
/// Walks the steps backwards, `node` being what the step at `idx` must match.fn matchFrom( ev: *Evaluator, node: ?NodeRef, steps: []const xpath.Step, idx: isize, absolute: bool,) Error!bool { if (idx < 0) { // Every step is accounted for. A rooted pattern additionally requires // that we arrived at the root rather than somewhere in the middle. if (!absolute) return true; const n = node orelse return false; return n.kind() == .document; }
const n = node orelse return false; const step = steps[@intCast(idx)];
if (isConnector(step)) { // `//` read backwards: the steps to its left may match this node or // any of its ancestors. var cur: ?NodeRef = n; while (cur) |c| : (cur = c.parent()) { if (try matchFrom(ev, c, steps, idx - 1, absolute)) return true; } return false; }
if (!try stepMatches(ev, step, n)) return false; return matchFrom(ev, n.parent(), steps, idx - 1, absolute);}
/// One step of a pattern against one node: the axis places it, the node test/// names it, and the predicates are evaluated with the node numbered among its/// siblings.fn stepMatches(ev: *Evaluator, step: xpath.Step, node: NodeRef) Error!bool { // The axis says where the node must sit relative to its parent. An // attribute step matches only attributes and a child step only what is in // the child list, which is what keeps `@id` from matching an element // called `id`. switch (step.axis) { .attribute => if (node.kind() != .attribute) return false, .child => { if (node.kind() == .attribute or node.kind() == .namespace) return false; // And it must actually *be* a child. The root is not one, so // `node()` -- which is `child::node()` -- does not match it, and // the root is left to `/` and to the built-in rule. Without this // a stylesheet whose only template is `match="node()"` matches the // root, stops there, and produces nothing. if (node.get().parent == null) return false; }, else => return false, }
if (!xpath.matchesTest(step.node_test, step.axis, node)) return false; if (step.predicates.len == 0) return true;
// `para[1]` means "the first para child of its parent", so the position a // predicate sees is the node's place among the siblings this same step // would have selected -- not its place in the document. var siblings: std.ArrayList(NodeRef) = .empty; defer siblings.deinit(ev.gpa); try collectMatchingSiblings(ev, step, node, &siblings);
const position = indexOfRef(siblings.items, node) orelse return false;
const focus: Focus = .{ .node = node, .position = position + 1, .size = siblings.items.len, };
for (step.predicates) |pred| { const v = try ev.eval(pred, focus); defer v.deinit(ev.gpa); const holds = if (v == .number) v.number == @as(f64, @floatFromInt(focus.position)) else v.toBoolean(); if (!holds) return false; } return true;}
fn collectMatchingSiblings( ev: *Evaluator, step: xpath.Step, node: NodeRef, out: *std.ArrayList(NodeRef),) Error!void { const parent = node.parent() orelse { // A node with no parent is the only member of its own sibling set. try out.append(ev.gpa, node); return; }; const doc = node.doc; const ids = switch (step.axis) { .attribute => parent.get().attributes.items, else => parent.get().children.items, }; for (ids) |id| { const ref = doc.ref(id); if (xpath.matchesTest(step.node_test, step.axis, ref)) try out.append(ev.gpa, ref); }}
fn indexOfRef(haystack: []const NodeRef, needle: NodeRef) ?usize { for (haystack, 0..) |n, i| { if (n.eql(needle)) return i; } return null;}
/// The fallback for `id()` and `key()` patterns: evaluate the pattern from the/// root of the node's tree and look for the node in the result.fn matchByMembership(ev: *Evaluator, expr: *const xpath.Expr, node: NodeRef) Error!bool { const doc = node.doc; const v = try ev.eval(expr, .{ .node = doc.ref(doc.root) }); defer v.deinit(ev.gpa); if (v != .node_set) return error.TypeError; return indexOfRef(v.node_set, node) != null;}
// -- tests -------------------------------------------------------------------
const testing = std.testing;
const sample = \\<doc> \\ <chapter n="1"> \\ <title>First</title> \\ <para>a</para> \\ <para>b</para> \\ </chapter> \\ <appendix> \\ <title>Last</title> \\ </appendix> \\</doc>;
/// Compiles a pattern and reports which nodes of the sample it matches, by/// their string value.fn matchingNodes(gpa: Allocator, doc: *tree.Document, src: []const u8) ![]u8 { var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const p = try compile(arena.allocator(), src, .none);
var ev: Evaluator = .init(gpa); var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa);
// By index rather than over the slice: matching can materialize namespace // nodes, which appends to the very list being walked. const count = doc.nodes.items.len; for (0..count) |i| { const ref = doc.ref(@intCast(i)); if (!try p.matches(&ev, ref)) continue; if (out.items.len != 0) try out.append(gpa, ' '); switch (ref.kind()) { .document => try out.appendSlice(gpa, "/"), .attribute => { try out.append(gpa, '@'); try out.appendSlice(gpa, ref.name().local); }, .element => { try out.appendSlice(gpa, ref.name().local); const sv = try ref.stringValue(gpa); defer gpa.free(sv); if (sv.len <= 8) { try out.append(gpa, ':'); try out.appendSlice(gpa, sv); } }, else => try out.appendSlice(gpa, "?"), } } return out.toOwnedSlice(gpa);}
fn expectMatches(expected: []const u8, doc: *tree.Document, src: []const u8) !void { const got = try matchingNodes(testing.allocator, doc, src); defer testing.allocator.free(got); testing.expectEqualStrings(expected, got) catch |err| { std.debug.print("pattern: {s}\n", .{src}); return err; };}
test "patterns match from the last step backwards" { const doc = try tree.parse(testing.allocator, sample, .{ .whitespace = .strip }); defer doc.destroy();
try expectMatches("title:First title:Last", doc, "title"); // Only the title whose parent is a chapter. try expectMatches("title:First", doc, "chapter/title"); try expectMatches("title:Last", doc, "appendix/title"); try expectMatches("/", doc, "/"); try expectMatches("doc", doc, "/doc"); try expectMatches("title:First title:Last", doc, "//title"); try expectMatches("title:First", doc, "chapter//title"); try expectMatches("@n", doc, "@n"); try expectMatches("para:a para:b", doc, "para");}
test "a predicate in a pattern numbers the node among its siblings" { const doc = try tree.parse(testing.allocator, sample, .{ .whitespace = .strip }); defer doc.destroy();
// `para[1]` is the first para child of its own parent, not the first in // the document -- and `para[2]` proves the numbering is over paras rather // than over all children, since the second child of chapter is a para but // the first para is the second child. try expectMatches("para:a", doc, "para[1]"); try expectMatches("para:b", doc, "para[2]"); try expectMatches("title:First", doc, "chapter[@n='1']/title"); try expectMatches("", doc, "chapter[@n='2']/title");}
test "alternatives are separate rules" { const doc = try tree.parse(testing.allocator, sample, .{ .whitespace = .strip }); defer doc.destroy(); try expectMatches("title:First para:a para:b title:Last", doc, "title|para");}
test "default priorities follow the specification's four values" { const gpa = testing.allocator; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const map: xpath.MapResolver = .{ .entries = &.{.{ "p", "urn:p" }} };
const cases = [_]struct { []const u8, f64 }{ .{ "para", 0 }, .{ "@id", 0 }, .{ "processing-instruction('x')", 0 }, .{ "p:*", -0.25 }, .{ "*", -0.5 }, .{ "@*", -0.5 }, .{ "node()", -0.5 }, .{ "text()", -0.5 }, .{ "comment()", -0.5 }, .{ "processing-instruction()", -0.5 }, .{ "chapter/para", 0.5 }, .{ "para[1]", 0.5 }, .{ "/", 0.5 }, .{ "//para", 0.5 }, }; for (cases) |c| { const p = try compile(arena.allocator(), c[0], map.resolver()); testing.expectEqual(c[1], p.alternatives[0].priority) catch |err| { std.debug.print("pattern: {s}\n", .{c[0]}); return err; }; }}
test "an expression that is not a pattern is refused" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); for ([_][]const u8{ "ancestor::a", "following-sibling::a", "$x/a", "1 + 2", "'literal'", "count(a)", }) |src| { try testing.expectError( error.InvalidPattern, compile(arena.allocator(), src, .none), ); }}