// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The four types an XPath expression can evaluate to, and the conversions //! between them. //! //! XPath is dynamically typed in an unusually aggressive way: almost every //! operator converts its operands rather than rejecting them, so `'3' + 1` is //! 4 and `boolean(0)` is false. The conversions are therefore not a detail at //! the edges but most of what the language does, and getting one of them //! subtly wrong shows up as a transformation that is quietly the wrong shape //! rather than as an error. //! //! Values own their storage and are freed with `deinit`. An arena would be //! easier to write and would mean the peak memory of a transformation was //! whatever the worst template happened to allocate; since a node-set can hold //! every node in a large document and a string can hold its entire text, //! that is a difference worth the `defer`s. const std = @import("std"); const Allocator = std.mem.Allocator; const tree = @import("ztree"); const NodeRef = tree.NodeRef; pub const Value = union(enum) { /// Sorted in document order and free of duplicates, which is the /// invariant everything else relies on: `string()` takes the first node, /// predicates count positions, and a union is a merge. node_set: []NodeRef, boolean: bool, number: f64, string: []u8, pub fn deinit(v: Value, gpa: Allocator) void { switch (v) { .node_set => |ns| gpa.free(ns), .string => |s| gpa.free(s), .boolean, .number => {}, } } /// A `.string` value owning a copy of `s`. pub fn ownedString(gpa: Allocator, s: []const u8) !Value { return .{ .string = try gpa.dupe(u8, s) }; } /// The empty node-set, which allocates nothing. pub const empty_node_set: Value = .{ .node_set = &.{} }; pub fn typeName(v: Value) []const u8 { return switch (v) { .node_set => "node-set", .boolean => "boolean", .number => "number", .string => "string", }; } // -- conversions --------------------------------------------------------- /// `boolean()`: a number is true unless it is zero or NaN, a string unless /// it is empty, a node-set unless it has no nodes. pub fn toBoolean(v: Value) bool { return switch (v) { .boolean => |b| b, .number => |n| n != 0 and !std.math.isNan(n), .string => |s| s.len != 0, .node_set => |ns| ns.len != 0, }; } /// `string()`. The caller owns the result. pub fn toString(v: Value, gpa: Allocator) ![]u8 { return switch (v) { .string => |s| gpa.dupe(u8, s), .boolean => |b| gpa.dupe(u8, if (b) "true" else "false"), .number => |n| numberToString(gpa, n), // The string-value of a node-set is that of its *first* node in // document order, and of the empty set is the empty string. Not a // concatenation, which is the mistake that makes `value-of` on a // multi-node set look right in the easy cases. .node_set => |ns| if (ns.len == 0) gpa.dupe(u8, "") else ns[0].stringValue(gpa), }; } /// `number()`. Anything that is not a number is converted through its /// string, which is why `number(@x)` on a node whose text has a stray /// space still works and on one with a trailing letter is NaN. pub fn toNumber(v: Value, gpa: Allocator) !f64 { switch (v) { .number => |n| return n, .boolean => |b| return if (b) 1 else 0, .string => |s| return stringToNumber(s), .node_set => { const s = try v.toString(gpa); defer gpa.free(s); return stringToNumber(s); }, } } /// A deep copy, so that a value may outlive the arena or the list it came /// from. pub fn clone(v: Value, gpa: Allocator) !Value { return switch (v) { .node_set => |ns| .{ .node_set = try gpa.dupe(NodeRef, ns) }, .string => |s| .{ .string = try gpa.dupe(u8, s) }, .boolean, .number => v, }; } }; /// XPath's string form of a number, which is not C's and not Zig's. /// /// The rules are: NaN is `NaN`, the infinities are `Infinity` and /// `-Infinity`, both zeroes are `0`, an integer has no decimal point, and /// anything else is written in plain decimal with as many digits as it takes /// to tell it from every other double -- and, crucially, **never** in /// exponent notation. `1000000 * 1000000` is `1000000000000`. /// /// libxslt does not do this. It hands the number to C's `%g` once the /// magnitude passes `INT_MAX`, so the same expression there is `1e+12`, and /// it rounds to fifteen significant digits, so `1 div 3` is /// `0.333333333333333` where the specification asks for /// `0.3333333333333333`. Those are the two places this library deliberately /// disagrees with its own oracle, and `tests/cases` records the disagreement /// rather than hiding it. pub fn numberToString(gpa: Allocator, n: f64) ![]u8 { if (std.math.isNan(n)) return gpa.dupe(u8, "NaN"); if (std.math.isPositiveInf(n)) return gpa.dupe(u8, "Infinity"); if (std.math.isNegativeInf(n)) return gpa.dupe(u8, "-Infinity"); // Negative zero is `0`, not `-0`. if (n == 0) return gpa.dupe(u8, "0"); // An integer is written without a decimal point. The bound is where // doubles stop being able to represent consecutive integers; above it the // value is still integral and still printed in full by the decimal // renderer below. if (@trunc(n) == n and @abs(n) < 1e21) { return std.fmt.allocPrint(gpa, "{d}", .{@as(i128, @intFromFloat(n))}); } // Full-precision decimal, which is shortest-round-trip without an // exponent. The buffer is sized for the widest a subnormal double can be. var buf: [std.fmt.float.bufferSize(.decimal, f64)]u8 = undefined; // `bufferSize` is the width of the widest `f64` there is, so the only // error this can return cannot happen. const rendered = std.fmt.float.render(&buf, n, .{ .mode = .decimal }) catch unreachable; return gpa.dupe(u8, rendered); } /// XPath's number form of a string: optional whitespace, an optional sign, and /// a decimal number, with nothing else allowed. Anything else is NaN -- /// including the empty string, and including anything with an exponent, since /// XPath 1.0 has no exponent notation. pub fn stringToNumber(s: []const u8) f64 { const trimmed = std.mem.trim(u8, s, " \t\n\r"); if (trimmed.len == 0) return std.math.nan(f64); var i: usize = 0; if (trimmed[0] == '-' or trimmed[0] == '+') { // A leading `+` is not part of the grammar, so it is not a number. if (trimmed[0] == '+') return std.math.nan(f64); i = 1; } var digits: usize = 0; while (i < trimmed.len and std.ascii.isDigit(trimmed[i])) : (i += 1) digits += 1; if (i < trimmed.len and trimmed[i] == '.') { i += 1; while (i < trimmed.len and std.ascii.isDigit(trimmed[i])) : (i += 1) digits += 1; } // Trailing anything -- a letter, an exponent, a second sign -- is not a // number, and neither is a lone sign or a lone dot. if (i != trimmed.len or digits == 0) return std.math.nan(f64); return std.fmt.parseFloat(f64, trimmed) catch std.math.nan(f64); } // -- node-set helpers -------------------------------------------------------- /// Sorts a node-set into document order and removes duplicates in place, /// returning the shortened length. /// /// Every node-set in circulation is kept in this form. It is what makes union /// cheap, what makes `[1]` mean the first in document order, and what stops a /// path such as `a/../a` from reporting the same element twice. pub fn sortUnique(nodes: []NodeRef) usize { if (nodes.len <= 1) return nodes.len; std.mem.sort(NodeRef, nodes, {}, NodeRef.lessThan); var out: usize = 1; for (nodes[1..]) |n| { if (n.eql(nodes[out - 1])) continue; nodes[out] = n; out += 1; } return out; } /// Builds node-sets while keeping the sorted-and-unique invariant, which it /// restores once at the end rather than on every insertion. pub const NodeSetBuilder = struct { gpa: Allocator, items: std.ArrayList(NodeRef) = .empty, pub fn init(gpa: Allocator) NodeSetBuilder { return .{ .gpa = gpa }; } pub fn deinit(b: *NodeSetBuilder) void { b.items.deinit(b.gpa); } pub fn add(b: *NodeSetBuilder, n: NodeRef) !void { try b.items.append(b.gpa, n); } pub fn addSlice(b: *NodeSetBuilder, ns: []const NodeRef) !void { try b.items.appendSlice(b.gpa, ns); } /// The finished node-set, sorted and deduplicated. The builder is left /// empty and the caller owns the slice. pub fn toOwnedValue(b: *NodeSetBuilder) !Value { const owned = try b.items.toOwnedSlice(b.gpa); errdefer b.gpa.free(owned); const len = sortUnique(owned); // `toOwnedSlice` has already shrunk the allocation to fit, so the // resize below is the only thing that can give the tail back. if (len != owned.len) { if (b.gpa.resize(owned, len)) return .{ .node_set = owned[0..len] }; const exact = try b.gpa.dupe(NodeRef, owned[0..len]); b.gpa.free(owned); return .{ .node_set = exact }; } return .{ .node_set = owned }; } }; // -- tests ------------------------------------------------------------------- const testing = std.testing; fn expectNumberString(expected: []const u8, n: f64) !void { const s = try numberToString(testing.allocator, n); defer testing.allocator.free(s); try testing.expectEqualStrings(expected, s); } test "numbers become strings the way XPath says, not the way C does" { try expectNumberString("NaN", std.math.nan(f64)); try expectNumberString("Infinity", std.math.inf(f64)); try expectNumberString("-Infinity", -std.math.inf(f64)); try expectNumberString("0", 0); try expectNumberString("0", -0.0); try expectNumberString("1", 1); try expectNumberString("-1", -1); try expectNumberString("2.5", 2.5); try expectNumberString("-0.5", -0.5); // The two places libxslt reaches for an exponent and the specification // does not. try expectNumberString("1000000000000", 1e12); try expectNumberString("0.00001", 1e-5); try expectNumberString("0.000001", 1e-6); try expectNumberString("100000000000000000000", 1e20); // Full precision rather than fifteen significant digits. The operands go // through runtime `f64`s deliberately: Zig would otherwise do the // arithmetic at comptime in `f128`, and `0.1 + 0.2` rounded from that is // the double nearest 0.3 rather than the one XPath would compute. var third: f64 = 1; third /= 3; try expectNumberString("0.3333333333333333", third); var sum: f64 = 0.1; sum += 0.2; try expectNumberString("0.30000000000000004", sum); } test "strings become numbers, and non-numbers become NaN" { try testing.expectEqual(@as(f64, 42), stringToNumber("42")); try testing.expectEqual(@as(f64, 42), stringToNumber(" 42\n")); try testing.expectEqual(@as(f64, -1.5), stringToNumber("-1.5")); try testing.expectEqual(@as(f64, 0.5), stringToNumber(".5")); try testing.expectEqual(@as(f64, 5), stringToNumber("5.")); for ([_][]const u8{ "", " ", "abc", "1abc", "+1", "1e5", "--1", ".", "-", "1.2.3" }) |s| { try testing.expect(std.math.isNan(stringToNumber(s))); } } test "boolean conversion follows the value, not the type" { try testing.expect(!(Value{ .number = 0 }).toBoolean()); try testing.expect(!(Value{ .number = std.math.nan(f64) }).toBoolean()); try testing.expect((Value{ .number = -1 }).toBoolean()); try testing.expect(!(Value{ .string = @constCast("") }).toBoolean()); // A string is true because it is non-empty, so "false" is true. try testing.expect((Value{ .string = @constCast("false") }).toBoolean()); try testing.expect(!Value.empty_node_set.toBoolean()); } test "a node-set's string value is its first node in document order" { const doc = try tree.parse(testing.allocator, "onetwo", .{}); defer doc.destroy(); const r = doc.documentElement().?; const kids = doc.node(r).children.items; // Deliberately out of order going in: the builder must sort them. var b: NodeSetBuilder = .init(testing.allocator); defer b.deinit(); try b.add(doc.ref(kids[1])); try b.add(doc.ref(kids[0])); try b.add(doc.ref(kids[1])); const v = try b.toOwnedValue(); defer v.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), v.node_set.len); const s = try v.toString(testing.allocator); defer testing.allocator.free(s); try testing.expectEqualStrings("one", s); }