Something went wrong. Try again.
XPath 1.0 for Zig 0.16, over a ztree document.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Evaluating a compiled XPath expression against a document.//!//! Three things here are easy to get wrong and are the reason most of this//! file is not just a tree walk.//!//! **Predicates are positional, and position depends on the axis.** In//! `preceding-sibling::a[1]` the `[1]` means the *nearest* preceding sibling,//! not the first one in the document, because a reverse axis is numbered from//! the context node outwards. So a step collects its nodes in axis order,//! filters them in axis order, and only then lets them be merged into the//! document-ordered set that a node-set has to be.//!//! **Comparison against a node-set is existential.** `@x = 1` is true when//! *some* node in the set is 1, which means `@x != 1` is not the negation of//! `@x = 1` -- both are true for a set holding 1 and 2, and both are false for//! the empty set. Writing this as a conversion followed by a comparison gives//! the wrong answer in exactly the cases people write tests for.//!//! **A step is evaluated once per context node and the results are merged.**//! `a/b` is not "the b children of the first a"; it is the union over every//! `a`. The union is what removes duplicates, which is why `../a/../a` does//! not report the same element twice.
const std = @import("std");const Allocator = std.mem.Allocator;const tree = @import("ztree");const xpath = @import("xpath.zig");const value = @import("value.zig");const functions = @import("functions.zig");
const NodeRef = tree.NodeRef;const Value = value.Value;const Expr = xpath.Expr;const Axis = xpath.Axis;
/// Everything that can go wrong while running a transformation.////// One error set rather than one per module: the evaluator calls functions the/// XSLT engine supplies, and those call back into the evaluator, so the sets/// would be mutually recursive if they were separate./// What evaluating an XPath expression can go wrong with.////// Deliberately short, and deliberately does not include anything a *host*/// might fail at. A caller that supplies variables or extension functions/// brings its own error set to `Evaluator`, so that "the key does not exist"/// or "the stylesheet is invalid" stays the property of whatever has keys and/// stylesheets rather than becoming part of XPath's vocabulary.pub const CoreError = error{ /// An operand had a type the operator cannot use, such as `|` applied to /// something that is not a node-set. TypeError, UnknownFunction, UnknownVariable, WrongArgumentCount, InvalidArgument, /// Evaluation nested deeper than `max_depth`. A crash here would be a /// stack overflow, which is not something a library may do to its caller. RecursionLimit,} || Allocator.Error;
/// How deep evaluation may nest. Reached only by a recursive template or a/// pathological expression; a crash here would be a stack overflow, which is/// not something a library may do to its caller.pub const max_depth = 400;
/// What `.`, `position()` and `last()` mean right now.pub const Focus = struct { node: NodeRef, /// 1-based, as XPath counts. position: usize = 1, size: usize = 1,};
/// Supplies the value of `$name`. The XSLT engine puts its variable scopes/// behind this; a standalone caller can put a fixed table behind it./// An evaluator, over whatever error set the caller's own variables and/// functions can fail with.////// The parameter exists so that XPath does not have to know what a host can go/// wrong at. An XSLT engine's `key()` can fail with `UnknownKey` and its/// `xsl:message` with `Terminated`; neither is an XPath error, and neither/// should appear in the error set of a library that has no keys and no/// messages. `Evaluator(error{})` is the evaluator for a caller with no/// extensions of its own.pub fn Evaluator(comptime HostError: type) type { return struct { const Self = @This();
/// Everything a call on this evaluator can fail with: XPath's own /// errors, and the host's. pub const Error = CoreError || HostError;
pub const VariableResolver = struct { ctx: ?*anyopaque = null, lookupFn: *const fn (ctx: ?*anyopaque, ev: *Self, name: tree.Name) Error!?Value,
fn noneLookup(_: ?*anyopaque, _: *Self, _: tree.Name) Error!?Value { return null; }
pub const none: VariableResolver = .{ .lookupFn = noneLookup }; };
/// Supplies the functions the core library does not have: XSLT's `key`, /// `document`, `current`, `format-number` and the rest, and whatever /// extensions a caller adds. /// /// Returning null rather than an error means "not mine", so that the core /// library is consulted first and an unknown name is still an error. pub const FunctionResolver = struct { ctx: ?*anyopaque = null, callFn: *const fn ( ctx: ?*anyopaque, ev: *Self, focus: Focus, name: tree.Name, args: []const Value, ) Error!?Value,
fn noneCall(_: ?*anyopaque, _: *Self, _: Focus, _: tree.Name, _: []const Value) Error!?Value { return null; }
pub const none: FunctionResolver = .{ .callFn = noneCall }; };
gpa: Allocator, variables: VariableResolver = .none, extensions: FunctionResolver = .none, depth: u32 = 0,
pub fn init(gpa: Allocator) Self { return .{ .gpa = gpa }; }
/// Evaluates an expression and returns a value the caller owns. pub fn eval(ev: *Self, e: *const Expr, focus: Focus) Error!Value { ev.depth += 1; defer ev.depth -= 1; if (ev.depth > max_depth) return error.RecursionLimit;
return switch (e.*) { .number => |n| .{ .number = n }, .literal => |s| Value.ownedString(ev.gpa, s), .variable => |name| ev.evalVariable(name), .negate => |inner| { const v = try ev.eval(inner, focus); defer v.deinit(ev.gpa); return .{ .number = -(try v.toNumber(ev.gpa)) }; }, .binary => |b| evalBinary(ev, b.op, b.lhs, b.rhs, focus), .call => |c| ev.evalCall(c.name, c.args, focus), .filter => |f| { const base = try ev.eval(f.base, focus); if (base != .node_set) { // No `errdefer` here, deliberately. Freeing on the error // path *and* returning the error would run both, and // `'x'[1]` -- a filter over something that is not a // node-set -- would free the string twice. base.deinit(ev.gpa); return error.TypeError; } // `applyPredicates` takes the slice, and frees it itself if a // predicate fails partway through. return ev.applyPredicates(base.node_set, f.predicates, true); }, .path => |p| ev.evalPath(p.absolute, p.start, p.steps, focus), }; }
/// Evaluates and converts in one step, which is what most callers want and /// what keeps the `defer` out of every call site. pub fn evalBoolean(ev: *Self, e: *const Expr, focus: Focus) Error!bool { const v = try ev.eval(e, focus); defer v.deinit(ev.gpa); return v.toBoolean(); }
pub fn evalString(ev: *Self, e: *const Expr, focus: Focus) Error![]u8 { const v = try ev.eval(e, focus); defer v.deinit(ev.gpa); return v.toString(ev.gpa); }
pub fn evalNumber(ev: *Self, e: *const Expr, focus: Focus) Error!f64 { const v = try ev.eval(e, focus); defer v.deinit(ev.gpa); return v.toNumber(ev.gpa); }
/// Evaluates an expression that must be a node-set. The caller owns the /// slice. pub fn evalNodeSet(ev: *Self, e: *const Expr, focus: Focus) Error![]NodeRef { const v = try ev.eval(e, focus); if (v != .node_set) { v.deinit(ev.gpa); return error.TypeError; } return v.node_set; }
fn evalVariable(ev: *Self, name: tree.Name) Error!Value { const found = try ev.variables.lookupFn(ev.variables.ctx, ev, name); return found orelse error.UnknownVariable; }
fn evalCall(ev: *Self, name: tree.Name, arg_exprs: []const *const Expr, focus: Focus) Error!Value { var args: std.ArrayList(Value) = .empty; defer { for (args.items) |a| a.deinit(ev.gpa); args.deinit(ev.gpa); } try args.ensureTotalCapacity(ev.gpa, arg_exprs.len); for (arg_exprs) |ae| args.appendAssumeCapacity(try ev.eval(ae, focus));
// The caller's functions are asked first, so that a host may shadow a // core function; unprefixed names it does not claim fall through to // the core library. if (try ev.extensions.callFn(ev.extensions.ctx, ev, focus, name, args.items)) |v| return v; if (name.uri.len == 0) { if (try functions.call(ev.gpa, focus, name.local, args.items)) |v| return v; } return error.UnknownFunction; }
// -- paths ---------------------------------------------------------------
fn evalPath( ev: *Self, absolute: bool, start: ?*const Expr, steps: []const xpath.Step, focus: Focus, ) Error!Value { // The set the first step is evaluated from. var current: []NodeRef = undefined; var owned = true; if (start) |s| { current = try ev.evalNodeSet(s, focus); } else if (absolute) { const doc = focus.node.doc; current = try ev.gpa.alloc(NodeRef, 1); current[0] = doc.ref(doc.root); } else { current = try ev.gpa.alloc(NodeRef, 1); current[0] = focus.node; } defer if (owned) ev.gpa.free(current);
for (steps) |step| { const next = try ev.evalStep(step, current); ev.gpa.free(current); current = next; }
owned = false; return .{ .node_set = current }; }
/// One step, evaluated from every node of `from` and merged. fn evalStep(ev: *Self, step: xpath.Step, from: []const NodeRef) Error![]NodeRef { var merged: value.NodeSetBuilder = .init(ev.gpa); defer merged.deinit();
// Reused across context nodes so that a step over a large node-set // does not allocate once per node. var axis_nodes: std.ArrayList(NodeRef) = .empty; defer axis_nodes.deinit(ev.gpa);
for (from) |node| { axis_nodes.clearRetainingCapacity(); try ev.collectAxis(step.axis, node, &axis_nodes);
// The node test first, in axis order, because the predicates that // follow number what survives it. var kept: usize = 0; for (axis_nodes.items) |n| { if (!matchesTest(step.node_test, step.axis, n)) continue; axis_nodes.items[kept] = n; kept += 1; } axis_nodes.shrinkRetainingCapacity(kept);
for (step.predicates) |pred| { try ev.filterInPlace(&axis_nodes, pred); }
try merged.addSlice(axis_nodes.items); }
const v = try merged.toOwnedValue(); return v.node_set; }
/// Keeps the nodes a predicate is true for, numbering them in the order /// they arrive -- which is axis order, so a reverse axis counts from the /// context node. fn filterInPlace(ev: *Self, nodes: *std.ArrayList(NodeRef), pred: *const Expr) Error!void { const size = nodes.items.len; var kept: usize = 0; for (nodes.items, 0..) |n, i| { const focus: Focus = .{ .node = n, .position = i + 1, .size = size }; if (!try ev.predicateHolds(pred, focus)) continue; nodes.items[kept] = n; kept += 1; } nodes.shrinkRetainingCapacity(kept); }
/// A predicate that evaluates to a number selects the node at that /// position; anything else is taken as a boolean. `[1]` and `[position() /// = 1]` are the same thing, and `[0]` selects nothing. fn predicateHolds(ev: *Self, pred: *const Expr, focus: Focus) Error!bool { const v = try ev.eval(pred, focus); defer v.deinit(ev.gpa); if (v == .number) { return v.number == @as(f64, @floatFromInt(focus.position)); } return v.toBoolean(); }
/// Applies the predicates of a filter expression, where position is /// document order because a filter has no axis of its own. fn applyPredicates( ev: *Self, nodes_in: []NodeRef, predicates: []const *const Expr, take_ownership: bool, ) Error!Value { var nodes: std.ArrayList(NodeRef) = .empty; errdefer nodes.deinit(ev.gpa); if (take_ownership) { nodes = .fromOwnedSlice(nodes_in); } else { try nodes.appendSlice(ev.gpa, nodes_in); } for (predicates) |pred| try ev.filterInPlace(&nodes, pred); return .{ .node_set = try nodes.toOwnedSlice(ev.gpa) }; }
// -- axes ----------------------------------------------------------------
/// Appends the nodes of an axis in *axis order*: document order for a /// forward axis, and away from the context node for a reverse one. fn collectAxis(ev: *Self, axis: Axis, node: NodeRef, out: *std.ArrayList(NodeRef)) Error!void { const gpa = ev.gpa; const doc = node.doc; switch (axis) { .self => try out.append(gpa, node), .parent => if (node.parent()) |p| try out.append(gpa, p), .child => { for (node.get().children.items) |c| try out.append(gpa, doc.ref(c)); }, .attribute => { for (node.get().attributes.items) |a| try out.append(gpa, doc.ref(a)); }, .namespace => { if (node.kind() != .element) return; for (try doc.namespaceNodes(node.id)) |n| try out.append(gpa, doc.ref(n)); }, .descendant => try appendDescendants(gpa, node, out), .descendant_or_self => { try out.append(gpa, node); try appendDescendants(gpa, node, out); }, .ancestor => { var cur = node.parent(); while (cur) |c| : (cur = c.parent()) try out.append(gpa, c); }, .ancestor_or_self => { var cur: ?NodeRef = node; while (cur) |c| : (cur = c.parent()) try out.append(gpa, c); }, .following_sibling => { // An attribute or namespace node has no siblings at all: it is // not among its parent's children, so there is nothing after // it on this axis. if (node.kind() == .attribute or node.kind() == .namespace) return; const siblings = try siblingsOf(node) orelse return; const idx = indexOfChild(siblings, node.id) orelse return; for (siblings[idx + 1 ..]) |c| try out.append(gpa, doc.ref(c)); }, .preceding_sibling => { if (node.kind() == .attribute or node.kind() == .namespace) return; const siblings = try siblingsOf(node) orelse return; const idx = indexOfChild(siblings, node.id) orelse return; // Reverse order: the nearest preceding sibling is `[1]`. var i = idx; while (i > 0) { i -= 1; try out.append(gpa, doc.ref(siblings[i])); } }, .following => try ev.collectFollowing(node, out), .preceding => try ev.collectPreceding(node, out), } }
/// Everything after the context node in document order, minus its own /// descendants, and never an attribute or namespace node. fn collectFollowing(ev: *Self, node: NodeRef, out: *std.ArrayList(NodeRef)) Error!void { const gpa = ev.gpa; const doc = node.doc; var cur = node; // An attribute precedes everything inside its element, so the // element's children are all on its following axis even though they // are not its siblings. if (node.kind() == .attribute or node.kind() == .namespace) { const owner = node.parent() orelse return; try appendDescendants(gpa, owner, out); cur = owner; } while (true) { const parent = cur.parent() orelse return; const siblings = parent.get().children.items; const idx = indexOfChild(siblings, cur.id) orelse return; for (siblings[idx + 1 ..]) |c| { const ref = doc.ref(c); try out.append(gpa, ref); try appendDescendants(gpa, ref, out); } cur = parent; } }
/// Everything before the context node in document order, minus its /// ancestors, in reverse document order so that `[1]` is the nearest. fn collectPreceding(ev: *Self, node: NodeRef, out: *std.ArrayList(NodeRef)) Error!void { const gpa = ev.gpa; const doc = node.doc; var cur = node; if (node.kind() == .attribute or node.kind() == .namespace) { cur = node.parent() orelse return; } while (true) { const parent = cur.parent() orelse return; const siblings = parent.get().children.items; const idx = indexOfChild(siblings, cur.id) orelse return; var i = idx; while (i > 0) { i -= 1; try appendReverseSubtree(gpa, doc.ref(siblings[i]), out); } cur = parent; } }
fn evalBinary( ev: *Self, op: xpath.BinOp, lhs_expr: *const Expr, rhs_expr: *const Expr, focus: Focus, ) Error!Value { // `and` and `or` short-circuit, which is not an optimisation: `$x and // $x/y` is written precisely so that the right side is not evaluated when // the left is false. switch (op) { .and_ => { if (!try ev.evalBoolean(lhs_expr, focus)) return .{ .boolean = false }; return .{ .boolean = try ev.evalBoolean(rhs_expr, focus) }; }, .or_ => { if (try ev.evalBoolean(lhs_expr, focus)) return .{ .boolean = true }; return .{ .boolean = try ev.evalBoolean(rhs_expr, focus) }; }, else => {}, }
const lhs = try ev.eval(lhs_expr, focus); defer lhs.deinit(ev.gpa); const rhs = try ev.eval(rhs_expr, focus); defer rhs.deinit(ev.gpa);
switch (op) { .and_, .or_ => unreachable, .union_ => { if (lhs != .node_set or rhs != .node_set) return error.TypeError; var b: value.NodeSetBuilder = .init(ev.gpa); defer b.deinit(); try b.addSlice(lhs.node_set); try b.addSlice(rhs.node_set); return b.toOwnedValue(); }, .eq, .ne => return .{ .boolean = try equalityHolds(ev, op == .eq, lhs, rhs) }, .lt, .le, .gt, .ge => return .{ .boolean = try relationHolds(ev, op, lhs, rhs) }, .add, .sub, .mul, .div, .mod => { const a = try lhs.toNumber(ev.gpa); const b = try rhs.toNumber(ev.gpa); return .{ .number = switch (op) { .add => a + b, .sub => a - b, .mul => a * b, .div => a / b, // XPath's `mod` is the remainder of a *truncating* division, // so it takes the sign of the dividend: `-5 mod 2` is -1. .mod => @rem(a, b), else => unreachable, }, }; }, } }
/// `=` and `!=`, which are existential whenever a node-set is involved. /// /// `x != y` is not `not(x = y)`. For a set holding both 1 and 2, `. = 1` and /// `. != 1` are both true, because each asks whether *some* node satisfies it. fn equalityHolds(ev: *Self, want_equal: bool, lhs: Value, rhs: Value) Error!bool { const gpa = ev.gpa;
if (lhs == .node_set and rhs == .node_set) { // Quadratic in principle. In practice one side is almost always a // single node, and comparing string-values pairwise is what the // specification says to do. for (lhs.node_set) |a| { const as = try a.stringValue(gpa); defer gpa.free(as); for (rhs.node_set) |b| { const bs = try b.stringValue(gpa); defer gpa.free(bs); if (std.mem.eql(u8, as, bs) == want_equal) return true; } } return false; }
if (lhs == .node_set or rhs == .node_set) { const set = if (lhs == .node_set) lhs.node_set else rhs.node_set; const other = if (lhs == .node_set) rhs else lhs;
// Against a boolean the set is converted as a whole rather than node // by node, which is the one case that is not existential. if (other == .boolean) { const set_as_bool = set.len != 0; return (set_as_bool == other.boolean) == want_equal; }
for (set) |n| { const s = try n.stringValue(gpa); defer gpa.free(s); const holds = switch (other) { .number => |num| blk: { const parsed = value.stringToNumber(s); break :blk parsed == num; }, .string => |str| std.mem.eql(u8, s, str), else => unreachable, }; if (holds == want_equal) return true; } return false; }
// No node-sets: a boolean comparison wins over a numeric one, which wins // over a string one. if (lhs == .boolean or rhs == .boolean) { return (lhs.toBoolean() == rhs.toBoolean()) == want_equal; } if (lhs == .number or rhs == .number) { const a = try lhs.toNumber(gpa); const b = try rhs.toNumber(gpa); return (a == b) == want_equal; } const a = try lhs.toString(gpa); defer gpa.free(a); const b = try rhs.toString(gpa); defer gpa.free(b); return std.mem.eql(u8, a, b) == want_equal; }
/// `<`, `<=`, `>`, `>=`, which always compare numbers -- and existentially /// when a node-set is involved. fn relationHolds(ev: *Self, op: xpath.BinOp, lhs: Value, rhs: Value) Error!bool { const gpa = ev.gpa;
if (lhs == .node_set or rhs == .node_set) { // Collect each side's candidate numbers, then look for one pair that // satisfies the relation. A non-node-set side contributes one number. var lhs_buf: [1]f64 = undefined; var rhs_buf: [1]f64 = undefined; const lhs_numbers = try numbersOf(ev, lhs, &lhs_buf); defer if (lhs == .node_set) gpa.free(lhs_numbers); const rhs_numbers = try numbersOf(ev, rhs, &rhs_buf); defer if (rhs == .node_set) gpa.free(rhs_numbers);
for (lhs_numbers) |a| { for (rhs_numbers) |b| { if (compare(op, a, b)) return true; } } return false; }
return compare(op, try lhs.toNumber(gpa), try rhs.toNumber(gpa)); }
/// The numbers a side of a relational comparison contributes: one for a /// non-node-set, and one per node otherwise. fn numbersOf(ev: *Self, v: Value, scratch: *[1]f64) Error![]f64 { switch (v) { .node_set => |ns| { const out = try ev.gpa.alloc(f64, ns.len); errdefer ev.gpa.free(out); for (ns, out) |n, *slot| { const s = try n.stringValue(ev.gpa); defer ev.gpa.free(s); slot.* = value.stringToNumber(s); } return out; }, else => { scratch[0] = try v.toNumber(ev.gpa); return scratch[0..1]; }, } } };}
fn siblingsOf(node: NodeRef) CoreError!?[]const tree.NodeId { const parent = node.parent() orelse return null; return parent.get().children.items;}
fn indexOfChild(children: []const tree.NodeId, id: tree.NodeId) ?usize { return std.mem.findScalar(tree.NodeId, children, id);}
fn appendDescendants(gpa: Allocator, node: NodeRef, out: *std.ArrayList(NodeRef)) CoreError!void { for (node.get().children.items) |c| { const ref = node.doc.ref(c); try out.append(gpa, ref); try appendDescendants(gpa, ref, out); }}
/// A subtree in reverse document order: the last descendant first, the node/// itself last.fn appendReverseSubtree(gpa: Allocator, node: NodeRef, out: *std.ArrayList(NodeRef)) CoreError!void { const kids = node.get().children.items; var i = kids.len; while (i > 0) { i -= 1; try appendReverseSubtree(gpa, node.doc.ref(kids[i]), out); } try out.append(gpa, node);}
/// True when a node satisfies a step's node test on a given axis.pub fn matchesTest(node_test: xpath.NodeTest, axis: Axis, node: NodeRef) bool { return switch (node_test) { .any => true, .text => node.kind() == .text, .comment => node.kind() == .comment, .pi => |target| node.kind() == .pi and (target == null or std.mem.eql(u8, node.name().local, target.?)), .name => |nt| blk: { // A name test matches only the axis's principal node type, which // is the entire difference between `*` and `@*`. if (node.kind() != axis.principalKind()) break :blk false; if (nt.local) |l| { if (!std.mem.eql(u8, node.name().local, l)) break :blk false; } if (nt.uri) |u| { if (!std.mem.eql(u8, node.name().uri, u)) break :blk false; } break :blk true; }, };}
// -- operators ---------------------------------------------------------------
fn compare(op: xpath.BinOp, a: f64, b: f64) bool { // Every comparison against NaN is false, which Zig's operators already do. return switch (op) { .lt => a < b, .le => a <= b, .gt => a > b, .ge => a >= b, else => unreachable, };}
// -- tests -------------------------------------------------------------------
const testing = std.testing;
/// Compiles and evaluates against a document, returning the value as a string.fn evalToString(gpa: Allocator, doc: *tree.Document, expr_src: []const u8) ![]u8 { var compiled = try xpath.Compiled.init(gpa, expr_src, .none); defer compiled.deinit(); var ev: Evaluator(error{}) = .init(gpa); const v = try ev.eval(compiled.expr, .{ .node = doc.ref(doc.root) }); defer v.deinit(gpa); return v.toString(gpa);}
fn expectEval(expected: []const u8, doc: *tree.Document, expr_src: []const u8) !void { const got = try evalToString(testing.allocator, doc, expr_src); defer testing.allocator.free(got); testing.expectEqualStrings(expected, got) catch |err| { std.debug.print("expression: {s}\n", .{expr_src}); return err; };}
fn expectCount(expected: usize, doc: *tree.Document, expr_src: []const u8) !void { const gpa = testing.allocator; var compiled = try xpath.Compiled.init(gpa, expr_src, .none); defer compiled.deinit(); var ev: Evaluator(error{}) = .init(gpa); const v = try ev.eval(compiled.expr, .{ .node = doc.ref(doc.root) }); defer v.deinit(gpa); try testing.expect(v == .node_set); testing.expectEqual(expected, v.node_set.len) catch |err| { std.debug.print("expression: {s}\n", .{expr_src}); return err; };}
const sample = \\<catalog> \\ <book id="b1" lang="en"><title>Alpha</title><price>10</price></book> \\ <book id="b2" lang="fr"><title>Beta</title><price>25</price></book> \\ <book id="b3" lang="en"><title>Gamma</title><price>5</price></book> \\</catalog>;
test "id() finds an attribute the document type declares to be an ID" { const gpa = testing.allocator; const src = \\<!DOCTYPE catalog [ \\<!ATTLIST book code ID #IMPLIED> \\]> \\<catalog><book code="b1">Alpha</book><book code="b2">Beta</book> \\<note xml:id="n1">Note</note></catalog> ; const doc = try tree.parse(gpa, src, .{ .dtd = true }); defer doc.destroy(); try expectEval("Beta", doc, "id('b2')"); try expectEval("Note", doc, "id('n1')"); try expectCount(2, doc, "id('b1 n1')"); // An attribute the document type says nothing about is not an id, however // much it looks like one. try expectCount(0, doc, "id('Alpha')");
// Without the declarations, only `xml:id` answers -- which is what a // document parsed with the document type left unread gets. const plain = try tree.parse(gpa, src, .{}); defer plain.destroy(); try expectCount(0, plain, "id('b2')"); try expectEval("Note", plain, "id('n1')");}
test "location paths select what they say" { const doc = try tree.parse(testing.allocator, sample, .{ .whitespace = .strip }); defer doc.destroy();
try expectCount(3, doc, "/catalog/book"); try expectCount(3, doc, "//book"); try expectCount(3, doc, "//title"); try expectCount(1, doc, "/catalog"); try expectCount(1, doc, "/"); try expectCount(2, doc, "//book[@lang='en']"); try expectCount(1, doc, "//book[@id='b2']"); try expectCount(1, doc, "//book[price > 20]"); try expectCount(2, doc, "//book[price < 20]"); try expectEval("Alpha", doc, "//title"); try expectEval("Beta", doc, "//book[2]/title"); try expectEval("3", doc, "count(//book)");}
test "predicates on a reverse axis count from the context node" { const doc = try tree.parse(testing.allocator, sample, .{ .whitespace = .strip }); defer doc.destroy();
// The nearest preceding sibling of the last book is the second one, not // the first. Getting this wrong is the classic reverse-axis bug. try expectEval("Beta", doc, "//book[3]/preceding-sibling::book[1]/title"); try expectEval("Alpha", doc, "//book[3]/preceding-sibling::book[2]/title"); try expectEval("Beta", doc, "//book[1]/following-sibling::book[1]/title"); try expectEval("Alpha", doc, "//book[2]/preceding-sibling::book[1]/title");}
test "comparison against a node-set is existential" { const doc = try tree.parse(testing.allocator, sample, .{ .whitespace = .strip }); defer doc.destroy();
// Some price is 10 and some price is not 10, so both are true. This is // the pair that proves `!=` is not `not(=)`. try expectEval("true", doc, "//price = 10"); try expectEval("true", doc, "//price != 10"); try expectEval("false", doc, "//price = 99"); try expectEval("false", doc, "//price != 99 = false()");
// Against an empty node-set both are false. try expectEval("false", doc, "//nothing = 1"); try expectEval("false", doc, "//nothing != 1");
// But against a boolean the set converts as a whole. try expectEval("true", doc, "//price = true()"); try expectEval("false", doc, "//nothing = true()");}
test "arithmetic and its conversions" { const doc = try tree.parse(testing.allocator, sample, .{ .whitespace = .strip }); defer doc.destroy();
try expectEval("40", doc, "sum(//price)"); try expectEval("3", doc, "1 + 2"); try expectEval("-1", doc, "1 - 2"); try expectEval("2.5", doc, "5 div 2"); try expectEval("1", doc, "5 mod 2"); // `mod` takes the sign of the dividend. try expectEval("-1", doc, "-5 mod 2"); try expectEval("4", doc, "'3' + 1"); try expectEval("NaN", doc, "'x' + 1");}
test "axes reach the right nodes" { const doc = try tree.parse(testing.allocator, sample, .{ .whitespace = .strip }); defer doc.destroy();
try expectCount(2, doc, "//book[@id='b2']/ancestor::node()"); try expectCount(1, doc, "//book[@id='b2']/parent::catalog"); try expectCount(2, doc, "//book[@id='b2']/@*"); try expectCount(3, doc, "//book[@id='b2']/ancestor-or-self::*/..|//book[@id='b2']/ancestor-or-self::*"); // `following` excludes the context node's own descendants, so the two // elements inside this book are not on it: what remains is the third book // and the two elements inside it. try expectCount(3, doc, "//book[@id='b2']/following::*"); try expectCount(3, doc, "//book[@id='b2']/preceding::*"); try expectEval("Gamma", doc, "//book[@id='b2']/following::title"); try expectEval("Alpha", doc, "//book[@id='b2']/preceding::title");}
test "a union is sorted and deduplicated" { const doc = try tree.parse(testing.allocator, sample, .{ .whitespace = .strip }); defer doc.destroy();
try expectCount(3, doc, "//book | //book"); try expectCount(6, doc, "//book | //title"); // The first node of the union in document order, not of the left operand. try expectEval("Alpha", doc, "//title[3] | //title[1]");}
test "the root is reachable from anywhere and a path is merged, not chained" { const doc = try tree.parse(testing.allocator, sample, .{ .whitespace = .strip }); defer doc.destroy();
// `book/../book` would report each book three times without the union's // deduplication. try expectCount(3, doc, "//book/../book"); try expectCount(3, doc, "//title/ancestor::book");}