// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The XPath 1.0 core function library. //! //! Two things run through the whole of it. //! //! **A string is a sequence of characters, not of bytes.** `substring`, //! `string-length` and `translate` count Unicode characters, so //! `string-length('é')` is 1 however many bytes that took. Writing them over //! bytes passes every test built from ASCII and then quietly truncates the //! first document with an accent in it. //! //! **The numeric edge cases are specified, not incidental.** `substring` is //! defined by an inequality on rounded positions precisely so that NaN and //! infinite arguments have an answer, and `round` breaks ties towards positive //! infinity, so `round(-1.5)` is -1 rather than the -2 that every language's //! built-in rounding gives. const std = @import("std"); const Allocator = std.mem.Allocator; const tree = @import("ztree"); const value = @import("value.zig"); const eval = @import("eval.zig"); const Value = value.Value; const NodeRef = tree.NodeRef; const Error = eval.CoreError; const Focus = eval.Focus; /// Calls a core function by its local name, or returns null if there is no /// such function. The caller owns the returned value. /// /// It takes an allocator rather than the evaluator because it needs nothing /// else from one: every core function is handed arguments that have already /// been evaluated, and none of them evaluates an expression of its own. That /// is what lets the core library stay outside the evaluator's type. pub fn call(gpa: Allocator, focus: Focus, name: []const u8, args: []const Value) Error!?Value { const id = names.get(name) orelse return null; switch (id) { // -- node set --------------------------------------------------------- .last => { try arity(args, 0, 0); return .{ .number = @floatFromInt(focus.size) }; }, .position => { try arity(args, 0, 0); return .{ .number = @floatFromInt(focus.position) }; }, .count => { try arity(args, 1, 1); const ns = try nodeSetArg(args[0]); return .{ .number = @floatFromInt(ns.len) }; }, .id => { try arity(args, 1, 1); return try idFunction(gpa, focus, args[0]); }, .local_name, .namespace_uri, .name => { try arity(args, 0, 1); const node = try firstNodeArg(focus, args) orelse return try Value.ownedString(gpa, ""); const n = node.name(); return switch (id) { .local_name => try Value.ownedString(gpa, n.local), .namespace_uri => try Value.ownedString(gpa, n.uri), // `name()` is the name as written, prefix and all, which is // the only place a prefix is observable from XPath. .name => .{ .string = try n.qualified(gpa) }, else => unreachable, }; }, // -- string ----------------------------------------------------------- .string => { try arity(args, 0, 1); if (args.len == 0) { return .{ .string = try focus.node.stringValue(gpa) }; } return .{ .string = try args[0].toString(gpa) }; }, .concat => { // The one core function that is variadic, and it insists on at // least two arguments. if (args.len < 2) return error.WrongArgumentCount; var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa); for (args) |a| { const s = try a.toString(gpa); defer gpa.free(s); try out.appendSlice(gpa, s); } return .{ .string = try out.toOwnedSlice(gpa) }; }, .starts_with, .contains, .substring_before, .substring_after => { try arity(args, 2, 2); const haystack = try args[0].toString(gpa); defer gpa.free(haystack); const needle = try args[1].toString(gpa); defer gpa.free(needle); return switch (id) { .starts_with => .{ .boolean = std.mem.startsWith(u8, haystack, needle) }, .contains => .{ .boolean = std.mem.indexOf(u8, haystack, needle) != null }, // A needle that does not occur yields the empty string, not // the whole haystack. .substring_before => try Value.ownedString(gpa, if (std.mem.indexOf(u8, haystack, needle)) |i| haystack[0..i] else ""), .substring_after => try Value.ownedString(gpa, if (std.mem.indexOf(u8, haystack, needle)) |i| haystack[i + needle.len ..] else ""), else => unreachable, }; }, .substring => { try arity(args, 2, 3); const s = try args[0].toString(gpa); defer gpa.free(s); const start = try args[1].toNumber(gpa); const length: ?f64 = if (args.len == 3) try args[2].toNumber(gpa) else null; return try Value.ownedString(gpa, substring(s, start, length)); }, .string_length => { try arity(args, 0, 1); const s = if (args.len == 0) try focus.node.stringValue(gpa) else try args[0].toString(gpa); defer gpa.free(s); return .{ .number = @floatFromInt(countCharacters(s)) }; }, .normalize_space => { try arity(args, 0, 1); const s = if (args.len == 0) try focus.node.stringValue(gpa) else try args[0].toString(gpa); defer gpa.free(s); return .{ .string = try normalizeSpace(gpa, s) }; }, .translate => { try arity(args, 3, 3); const s = try args[0].toString(gpa); defer gpa.free(s); const from = try args[1].toString(gpa); defer gpa.free(from); const to = try args[2].toString(gpa); defer gpa.free(to); return .{ .string = try translate(gpa, s, from, to) }; }, // -- boolean ---------------------------------------------------------- .boolean => { try arity(args, 1, 1); return .{ .boolean = args[0].toBoolean() }; }, .not => { try arity(args, 1, 1); return .{ .boolean = !args[0].toBoolean() }; }, .true_ => { try arity(args, 0, 0); return .{ .boolean = true }; }, .false_ => { try arity(args, 0, 0); return .{ .boolean = false }; }, .lang => { try arity(args, 1, 1); const wanted = try args[0].toString(gpa); defer gpa.free(wanted); return .{ .boolean = languageMatches(focus.node, wanted) }; }, // -- number ----------------------------------------------------------- .number => { try arity(args, 0, 1); if (args.len == 0) { const s = try focus.node.stringValue(gpa); defer gpa.free(s); return .{ .number = value.stringToNumber(s) }; } return .{ .number = try args[0].toNumber(gpa) }; }, .sum => { try arity(args, 1, 1); const ns = try nodeSetArg(args[0]); var total: f64 = 0; for (ns) |n| { const s = try n.stringValue(gpa); defer gpa.free(s); total += value.stringToNumber(s); } return .{ .number = total }; }, .floor, .ceiling, .round => { try arity(args, 1, 1); const n = try args[0].toNumber(gpa); return .{ .number = switch (id) { .floor => @floor(n), .ceiling => @ceil(n), .round => xpathRound(n), else => unreachable, } }; }, } } const FunctionId = enum { last, position, count, id, local_name, namespace_uri, name, string, concat, starts_with, contains, substring_before, substring_after, substring, string_length, normalize_space, translate, boolean, not, true_, false_, lang, number, sum, floor, ceiling, round, }; const names = std.StaticStringMap(FunctionId).initComptime(.{ .{ "last", .last }, .{ "position", .position }, .{ "count", .count }, .{ "id", .id }, .{ "local-name", .local_name }, .{ "namespace-uri", .namespace_uri }, .{ "name", .name }, .{ "string", .string }, .{ "concat", .concat }, .{ "starts-with", .starts_with }, .{ "contains", .contains }, .{ "substring-before", .substring_before }, .{ "substring-after", .substring_after }, .{ "substring", .substring }, .{ "string-length", .string_length }, .{ "normalize-space", .normalize_space }, .{ "translate", .translate }, .{ "boolean", .boolean }, .{ "not", .not }, .{ "true", .true_ }, .{ "false", .false_ }, .{ "lang", .lang }, .{ "number", .number }, .{ "sum", .sum }, .{ "floor", .floor }, .{ "ceiling", .ceiling }, .{ "round", .round }, }); /// True when the core library has a function of this name, which /// `function-available()` needs to answer. pub fn has(name: []const u8) bool { return names.has(name); } fn arity(args: []const Value, min: usize, max: usize) Error!void { if (args.len < min or args.len > max) return error.WrongArgumentCount; } fn nodeSetArg(v: Value) Error![]const NodeRef { return switch (v) { .node_set => |ns| ns, else => error.TypeError, }; } /// The node an optional node-set argument refers to: the first in document /// order, or the context node when the argument was omitted. fn firstNodeArg(focus: Focus, args: []const Value) Error!?NodeRef { if (args.len == 0) return focus.node; const ns = try nodeSetArg(args[0]); if (ns.len == 0) return null; return ns[0]; } // -- the awkward ones -------------------------------------------------------- /// `substring`, defined the way the specification defines it: the characters /// at positions `p` where `round(start) <= p < round(start) + round(length)`. /// /// Writing it as a clamp-and-slice gets the ordinary cases right and the /// specified ones wrong. Here the inequality is evaluated in floating point /// first, which is what makes `substring('12345', 0 div 0, 3)` empty and /// `substring('12345', -42, 1 div 0)` the whole string, both of which the /// specification calls out. fn substring(s: []const u8, start: f64, length: ?f64) []const u8 { const first = xpathRound(start); // NaN anywhere in the bounds selects nothing at all. if (std.math.isNan(first)) return ""; const last: f64 = if (length) |l| blk: { const rounded = xpathRound(l); if (std.math.isNan(rounded)) return ""; // `-Infinity + Infinity` is NaN, and the specification's own example // says that selects nothing. Without this the `@min` below would // quietly drop the NaN and return the whole string. const end = first + rounded; if (std.math.isNan(end)) return ""; break :blk end; } else std.math.inf(f64); const total = countCharacters(s); // Positions are 1-based, so character `i` (0-based) is at position i+1. const from_f = @max(first, 1); if (from_f > @as(f64, @floatFromInt(total))) return ""; const to_f = @min(last, @as(f64, @floatFromInt(total)) + 1); if (to_f <= from_f) return ""; const from: usize = @intFromFloat(from_f); const to: usize = @intFromFloat(to_f); return s[byteIndexOfCharacter(s, from - 1)..byteIndexOfCharacter(s, to - 1)]; } /// The number of Unicode characters in a UTF-8 string. /// /// Invalid bytes are counted one apiece rather than rejected: the tree only /// ever holds what the parser produced, but a stylesheet can build a string /// out of `translate` and arithmetic, and a panic here would be a crash in a /// transformation rather than a diagnosable error. pub fn countCharacters(s: []const u8) usize { var count: usize = 0; var i: usize = 0; while (i < s.len) { i = nextCharacter(s, i); count += 1; } return count; } /// The byte offset just past the character starting at `i`. /// /// Clamped to the end of the string, which is the whole point: a lead byte /// announcing a four-byte sequence in the last two bytes of a string would /// otherwise step past the end, and a caller that turns the result into a /// slice index gets an out-of-bounds panic rather than a short string. A /// stylesheet is allowed to contain a string literal that is not valid UTF-8, /// so this is reachable without anything being corrupted. fn nextCharacter(s: []const u8, i: usize) usize { const len = std.unicode.utf8ByteSequenceLength(s[i]) catch 1; return @min(i + len, s.len); } /// The byte offset of the nth character, or the end of the string. fn byteIndexOfCharacter(s: []const u8, n: usize) usize { var count: usize = 0; var i: usize = 0; while (i < s.len and count < n) { i = nextCharacter(s, i); count += 1; } return i; } /// `normalize-space`: leading and trailing whitespace removed, and every /// internal run of whitespace collapsed to one space. fn normalizeSpace(gpa: Allocator, s: []const u8) Error![]u8 { var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa); var it = std.mem.tokenizeAny(u8, s, " \t\n\r"); var first = true; while (it.next()) |word| { if (!first) try out.append(gpa, ' '); try out.appendSlice(gpa, word); first = false; } return out.toOwnedSlice(gpa); } /// `translate`: each character of `s` that occurs in `from` is replaced by the /// character at the same position in `to`, or removed if `to` is shorter. /// /// A character that occurs more than once in `from` takes its first mapping, /// which is what makes `translate(x, 'aa', 'bc')` map `a` to `b`. fn translate(gpa: Allocator, s: []const u8, from: []const u8, to: []const u8) Error![]u8 { var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa); var i: usize = 0; while (i < s.len) { const len = std.unicode.utf8ByteSequenceLength(s[i]) catch 1; const end = @min(i + len, s.len); const ch = s[i..end]; i = end; if (indexOfCharacter(from, ch)) |pos| { if (characterAt(to, pos)) |replacement| { try out.appendSlice(gpa, replacement); } // Nothing appended when `to` is too short: the character is // deleted, which is how `translate(s, ' ', '')` strips spaces. continue; } try out.appendSlice(gpa, ch); } return out.toOwnedSlice(gpa); } /// The character index of the first occurrence of `ch` in `s`, counting /// characters rather than bytes. fn indexOfCharacter(s: []const u8, ch: []const u8) ?usize { var index: usize = 0; var i: usize = 0; while (i < s.len) { const len = std.unicode.utf8ByteSequenceLength(s[i]) catch 1; const end = @min(i + len, s.len); if (std.mem.eql(u8, s[i..end], ch)) return index; i = end; index += 1; } return null; } fn characterAt(s: []const u8, n: usize) ?[]const u8 { var index: usize = 0; var i: usize = 0; while (i < s.len) { const len = std.unicode.utf8ByteSequenceLength(s[i]) catch 1; const end = @min(i + len, s.len); if (index == n) return s[i..end]; i = end; index += 1; } return null; } /// XPath's `round`, which breaks ties towards positive infinity: `round(-1.5)` /// is -1, where nearly every language's rounding gives -2. /// /// Written as a comparison against the floor rather than as `floor(x + 0.5)`, /// because adding a half can itself round: `0.49999999999999994 + 0.5` is /// exactly 1 in a double, and that form would answer 1 for a number below a /// half. pub fn xpathRound(x: f64) f64 { if (std.math.isNan(x) or std.math.isInf(x)) return x; const f = @floor(x); return if (x - f >= 0.5) f + 1 else f; } /// `lang()`: true when the nearest `xml:lang` in scope is the language asked /// for, or a sublanguage of it. Case-insensitive, and `en` matches `en-GB` /// while `en-GB` does not match `en`. fn languageMatches(node: NodeRef, wanted: []const u8) bool { var cur: ?NodeRef = node; while (cur) |n| : (cur = n.parent()) { if (n.kind() != .element) continue; const lang = n.doc.attributeValue(n.id, tree.xml_ns, "lang") orelse continue; if (!std.ascii.startsWithIgnoreCase(lang, wanted)) return false; // Either an exact match or a sublanguage, never a longer word that // merely starts the same way: `en` must not match `english`. return lang.len == wanted.len or lang[wanted.len] == '-'; } return false; } /// `id()`. /// /// Which attributes are of type ID is a question the document type answers, so /// an element counts when the internal subset declares one of its attributes /// `ID` and that attribute carries the wanted value. A document parsed without /// `ParseOptions.dtd` has no declarations to consult and no such attribute is /// found, which is what libxslt does with a document whose type it never read. /// /// `xml:id` is resolved either way: its type is fixed by its own specification /// and needs no declaration. fn idFunction(gpa: Allocator, focus: Focus, arg: Value) Error!Value { var b: value.NodeSetBuilder = .init(gpa); defer b.deinit(); // A node-set argument contributes the tokens of every node's string-value; // anything else contributes those of its string. switch (arg) { .node_set => |ns| { for (ns) |n| { const s = try n.stringValue(gpa); defer gpa.free(s); try collectById(focus.node.doc, s, &b); } }, else => { const s = try arg.toString(gpa); defer gpa.free(s); try collectById(focus.node.doc, s, &b); }, } return b.toOwnedValue(); } fn collectById(doc: *tree.Document, tokens: []const u8, b: *value.NodeSetBuilder) Error!void { var it = std.mem.tokenizeAny(u8, tokens, " \t\n\r"); while (it.next()) |token| { for (doc.nodes.items, 0..) |*n, i| { if (n.kind != .element) continue; const id: tree.NodeId = @intCast(i); if (doc.attributeValue(id, tree.xml_ns, "id")) |got| { if (std.mem.eql(u8, got, token)) { try b.add(doc.ref(id)); continue; } } if (declaredId(doc, id)) |got| { if (std.mem.eql(u8, got, token)) try b.add(doc.ref(id)); } } } } /// The value of whichever attribute of this element the document type declares /// to be of type `ID`. An element may have at most one. fn declaredId(doc: *tree.Document, elem: tree.NodeId) ?[]const u8 { const dtd = &(doc.dtd orelse return null); const defs = dtd.attributes(doc.node(elem).name.local) orelse return null; for (defs) |d| { if (d.type != .id) continue; for (doc.node(elem).attributes.items) |a| { const name = doc.node(a).name; // The declaration names the attribute as written, prefix and all, // which is the only spelling a document type knows. if (name.prefix.len == 0) { if (std.mem.eql(u8, name.local, d.name)) return doc.node(a).value; } else if (d.name.len == name.prefix.len + 1 + name.local.len and std.mem.startsWith(u8, d.name, name.prefix) and d.name[name.prefix.len] == ':' and std.mem.endsWith(u8, d.name, name.local)) { return doc.node(a).value; } } } return null; } // -- tests ------------------------------------------------------------------- const testing = std.testing; test "substring follows the specification's inequality, not a clamp" { try testing.expectEqualStrings("234", substring("12345", 1.5, 2.6)); try testing.expectEqualStrings("12", substring("12345", 0, 3)); try testing.expectEqualStrings("", substring("12345", 0, 0)); try testing.expectEqualStrings("", substring("12345", 5, -3)); try testing.expectEqualStrings("12345", substring("12345", -42, std.math.inf(f64))); try testing.expectEqualStrings("", substring("12345", -std.math.inf(f64), std.math.inf(f64))); try testing.expectEqualStrings("", substring("12345", std.math.nan(f64), 3)); try testing.expectEqualStrings("", substring("12345", 1, std.math.nan(f64))); try testing.expectEqualStrings("2345", substring("12345", 2, null)); try testing.expectEqualStrings("12345", substring("12345", 1, null)); } test "a truncated multi-byte sequence does not walk off the end" { // A string literal in an expression is whatever the document said it was, // and nothing guarantees it is valid UTF-8. A lead byte announcing more // bytes than are left used to step the cursor past the end of the string, // which `substring` then used as a slice index. const truncated = "abcd\xf0"; try testing.expectEqual(@as(usize, 5), countCharacters(truncated)); try testing.expectEqualStrings("abcd\xf0", substring(truncated, 1, 9)); try testing.expectEqualStrings("d\xf0", substring(truncated, 4, 2)); try testing.expectEqualStrings("", substring(truncated, 9, 1)); const lone = "\xf0"; try testing.expectEqual(@as(usize, 1), countCharacters(lone)); try testing.expectEqualStrings("\xf0", substring(lone, 1, 1)); } test "string functions count characters, not bytes" { // Four characters, seven bytes. const s = "aéb€"; try testing.expectEqual(@as(usize, 4), countCharacters(s)); try testing.expectEqualStrings("éb", substring(s, 2, 2)); const out = try translate(testing.allocator, "aéb", "é", "x"); defer testing.allocator.free(out); try testing.expectEqualStrings("axb", out); } test "translate deletes when the replacement runs out" { const gpa = testing.allocator; { const out = try translate(gpa, "--aaa--", "abc-", "ABC"); defer gpa.free(out); // `-` has no replacement, so it is removed. try testing.expectEqualStrings("AAA", out); } { // A repeated source character takes its first mapping. const out = try translate(gpa, "xax", "aa", "bc"); defer gpa.free(out); try testing.expectEqualStrings("xbx", out); } } test "normalize-space collapses and trims" { const gpa = testing.allocator; const out = try normalizeSpace(gpa, " one \t two\n\n three "); defer gpa.free(out); try testing.expectEqualStrings("one two three", out); const empty = try normalizeSpace(gpa, " \n "); defer gpa.free(empty); try testing.expectEqualStrings("", empty); } test "round breaks ties towards positive infinity" { try testing.expectEqual(@as(f64, 1), xpathRound(0.5)); try testing.expectEqual(@as(f64, 2), xpathRound(1.5)); // The case that separates XPath's rounding from everyone else's. try testing.expectEqual(@as(f64, -1), xpathRound(-1.5)); try testing.expectEqual(@as(f64, 0), xpathRound(-0.5)); try testing.expectEqual(@as(f64, 1), xpathRound(1.2)); // And the case that separates it from `floor(x + 0.5)`. try testing.expectEqual(@as(f64, 0), xpathRound(0.49999999999999994)); try testing.expect(std.math.isNan(xpathRound(std.math.nan(f64)))); }