// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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 = \\ \\ Alpha10 \\ Beta25 \\ Gamma5 \\ ; test "id() finds an attribute the document type declares to be an ID" { const gpa = testing.allocator; const src = \\ \\]> \\AlphaBeta \\Note ; 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"); }