Something went wrong. Try again.
An XSLT 1.0 processor for Zig 0.16, built on zxml.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The [EXSLT][] modules this library implements as functions: `sets`, `math`//! and `strings`.//!//! [EXSLT]: http://exslt.org///!//! EXSLT is not one specification but a collection of small ones, each in its//! own namespace, and a stylesheet reaches for whichever it needs. These three//! are the ones that are pure functions over values the engine already has --//! node-sets, numbers and strings -- so each is a few lines and none of them//! needs anything from the transformation but its arguments.//!//! The two modules that are *not* here are the two that need more than that.//! `common` lives in the engine, because `exsl:node-set` is about what a//! result tree fragment is; `functions` lives there too, because//! `func:function` is a declaration the stylesheet reader has to see.//! `dates-and-times` is absent because it is a calendar library rather than a//! function or two, and a wrong one is worse than none.//!//! A name this does not know returns null rather than an error, so that the//! engine can go on to try whatever else might answer -- and so that an//! unimplemented EXSLT function reaches `xsl:fallback` or a diagnostic naming//! it, rather than being quietly confused with one that is implemented.
const std = @import("std");const Allocator = std.mem.Allocator;const tree = @import("ztree");const zxpath = @import("zxpath");
const Name = tree.Name;const NodeRef = tree.NodeRef;const Value = zxpath.value.Value;const value = zxpath.value;
pub const sets_ns = "http://exslt.org/sets";pub const math_ns = "http://exslt.org/math";pub const strings_ns = "http://exslt.org/strings";pub const crypto_ns = "http://exslt.org/crypto";
pub const Error = error{ TypeError, WrongArgumentCount } || Allocator.Error;
/// Calls an EXSLT function, or answers null when this is not one of them.pub fn call(gpa: Allocator, name: Name, args: []const Value) Error!?Value { if (std.mem.eql(u8, name.uri, sets_ns)) return sets(gpa, name.local, args); if (std.mem.eql(u8, name.uri, math_ns)) return math(gpa, name.local, args); if (std.mem.eql(u8, name.uri, strings_ns)) return strings(gpa, name.local, args); if (std.mem.eql(u8, name.uri, crypto_ns)) return crypto(gpa, name.local, args); return null;}
/// True when a function of this name is implemented, which is what/// `function-available()` needs to answer.pub fn has(name: Name) bool { if (std.mem.eql(u8, name.uri, sets_ns)) return set_names.has(name.local); if (std.mem.eql(u8, name.uri, math_ns)) return math_names.has(name.local); if (std.mem.eql(u8, name.uri, strings_ns)) return string_names.has(name.local); if (std.mem.eql(u8, name.uri, crypto_ns)) return crypto_names.has(name.local); return false;}
// -- sets --------------------------------------------------------------------
const SetFunction = enum { difference, intersection, distinct, @"has-same-node", leading, trailing,};
const set_names = std.StaticStringMap(SetFunction).initComptime(.{ .{ "difference", .difference }, .{ "intersection", .intersection }, .{ "distinct", .distinct }, .{ "has-same-node", .@"has-same-node" }, .{ "leading", .leading }, .{ "trailing", .trailing },});
/// `http://exslt.org/sets`, every one of which is an operation on node-sets.////// `leading` and `trailing` are the two that are not symmetric: they cut the/// first node-set at the *first* node of the second in document order, which/// is why they take a position rather than a membership test.fn sets(gpa: Allocator, local: []const u8, args: []const Value) Error!?Value { const which = set_names.get(local) orelse return null;
if (which == .distinct) { if (args.len != 1) return error.WrongArgumentCount; const ns = try nodeSet(args[0]); var b: value.NodeSetBuilder = .init(gpa); defer b.deinit(); // The first node of each distinct string-value, in document order -- // and the nodes arrive in document order, so the first one seen wins. var seen: std.StringHashMapUnmanaged(void) = .empty; defer { var it = seen.keyIterator(); while (it.next()) |k| gpa.free(k.*); seen.deinit(gpa); } for (ns) |n| { const s = try n.stringValue(gpa); const slot = try seen.getOrPut(gpa, s); if (slot.found_existing) { gpa.free(s); continue; } try b.add(n); } return try b.toOwnedValue(); }
if (args.len != 2) return error.WrongArgumentCount; const first = try nodeSet(args[0]); const second = try nodeSet(args[1]);
switch (which) { .distinct => unreachable, .@"has-same-node" => { for (first) |a| { for (second) |b| { if (a.eql(b)) return .{ .boolean = true }; } } return .{ .boolean = false }; }, .difference, .intersection => { var b: value.NodeSetBuilder = .init(gpa); defer b.deinit(); for (first) |a| { const present = contains(second, a); if (present == (which == .intersection)) try b.add(a); } return try b.toOwnedValue(); }, .leading, .trailing => { // An empty second argument has no node to cut at, and the module // says the first node set comes back whole -- for both of these, // which is not what falling through a "nothing matched" would // give. if (second.len == 0) return try args[0].clone(gpa);
// The cut is made at the *first* node of the second set in // document order, and the module is emphatic about the case that // is easy to miss: if that node is not itself in the first set, // the answer is empty. `set:leading(a|b|c, h)` is nothing at all // rather than all three, even though all three precede `h`. var cut = second[0]; for (second[1..]) |n| { if (n.before(cut)) cut = n; } if (!contains(first, cut)) return .{ .node_set = &.{} };
var b: value.NodeSetBuilder = .init(gpa); defer b.deinit(); for (first) |a| { const keep = if (which == .leading) a.before(cut) else cut.before(a); if (keep) try b.add(a); } return try b.toOwnedValue(); }, }}
fn nodeSet(v: Value) Error![]const NodeRef { if (v != .node_set) return error.TypeError; return v.node_set;}
fn contains(ns: []const NodeRef, want: NodeRef) bool { for (ns) |n| { if (n.eql(want)) return true; } return false;}
// -- math --------------------------------------------------------------------
const MathFunction = enum { min, max, highest, lowest, abs, sqrt, power, log, exp, constant,};
const math_names = std.StaticStringMap(MathFunction).initComptime(.{ .{ "min", .min }, .{ "max", .max }, .{ "highest", .highest }, .{ "lowest", .lowest }, .{ "abs", .abs }, .{ "sqrt", .sqrt }, .{ "power", .power }, .{ "log", .log }, .{ "exp", .exp }, .{ "constant", .constant },});
/// `http://exslt.org/math`.////// `min` and `max` return a *number* and `lowest` and `highest` return the/// nodes that carry it -- all of them, since several nodes may share the/// extreme value. A node whose string-value is not a number makes the whole/// answer NaN, which is what taking the minimum of a set containing NaN means.fn math(gpa: Allocator, local: []const u8, args: []const Value) Error!?Value { const which = math_names.get(local) orelse return null;
switch (which) { .min, .max, .highest, .lowest => { if (args.len != 1) return error.WrongArgumentCount; const ns = try nodeSet(args[0]); if (ns.len == 0) { if (which == .min or which == .max) return .{ .number = std.math.nan(f64) }; return .{ .node_set = &.{} }; } var best: f64 = std.math.nan(f64); for (ns, 0..) |n, i| { const x = try nodeNumber(gpa, n); if (std.math.isNan(x)) { best = x; break; } const wider = if (which == .min or which == .lowest) x < best else x > best; if (i == 0 or wider) best = x; } if (which == .min or which == .max) return .{ .number = best }; var b: value.NodeSetBuilder = .init(gpa); defer b.deinit(); if (std.math.isNan(best)) return try b.toOwnedValue(); for (ns) |n| { if (try nodeNumber(gpa, n) == best) try b.add(n); } return try b.toOwnedValue(); }, .constant => { // `math:constant('PI', 5)`. The second argument is a precision, // and the module defines it as a number of digits of the // constant's decimal expansion -- so the expansions are kept as // text and cut, which is both what libxslt does and the only way // to answer for a precision a double cannot hold. if (args.len != 2) return error.WrongArgumentCount; const wanted = try args[0].toString(gpa); defer gpa.free(wanted); const precision = try args[1].toNumber(gpa); if (std.math.isNan(precision) or precision < 1) return .{ .number = std.math.nan(f64) }; const table = [_]struct { []const u8, []const u8 }{ .{ "E", "2.71828182845904523536028747135266249775724709369995" }, .{ "LN2", "0.69314718055994530941723212145817656807550013436025" }, .{ "LN10", "2.30258509299404568401799145468436420760110148862877" }, .{ "LOG2E", "1.44269504088896340735992468100189213742664595415298" }, .{ "SQRT2", "1.41421356237309504880168872420969807856967187537694" }, .{ "PI", "3.14159265358979323846264338327950288419716939937510" }, }; for (table) |pair| { if (!std.mem.eql(u8, wanted, pair[0])) continue; const digits = @min(@as(usize, @intFromFloat(precision)), pair[1].len); return .{ .number = value.stringToNumber(pair[1][0..digits]) }; } return .{ .number = std.math.nan(f64) }; }, .power => { if (args.len != 2) return error.WrongArgumentCount; const base = try args[0].toNumber(gpa); const exponent = try args[1].toNumber(gpa); return .{ .number = std.math.pow(f64, base, exponent) }; }, .abs, .sqrt, .log, .exp => { if (args.len != 1) return error.WrongArgumentCount; const x = try args[0].toNumber(gpa); return .{ .number = switch (which) { .abs => @abs(x), .sqrt => @sqrt(x), .log => @log(x), .exp => @exp(x), else => unreachable, } }; }, }}
fn nodeNumber(gpa: Allocator, n: NodeRef) Allocator.Error!f64 { const s = try n.stringValue(gpa); defer gpa.free(s); return value.stringToNumber(s);}
// -- crypto ------------------------------------------------------------------
const CryptoFunction = enum { md5, sha1 };
const crypto_names = std.StaticStringMap(CryptoFunction).initComptime(.{ .{ "md5", .md5 }, .{ "sha1", .sha1 },});
/// `http://exslt.org/crypto`, of which the two message digests are here and/// the ciphers are not.////// `crypto:md5` and `crypto:sha1` are useful for the things a stylesheet/// actually wants a digest for -- naming a fragment, keying a cache, telling/// two documents apart -- and neither is a secret-keeping claim. The module's/// `crypto:rc4-encrypt` and `crypto:rc4-decrypt` are deliberately absent: RC4/// is broken, and a function named "encrypt" is an invitation to rely on it./// libxslt provides them for the stylesheets that already call them; a new/// implementation has no such debt.////// Both digests are over the UTF-8 bytes of the string and come back as lower/// case hexadecimal, which is what libxslt writes.fn crypto(gpa: Allocator, local: []const u8, args: []const Value) Error!?Value { const which = crypto_names.get(local) orelse return null; if (args.len != 1) return error.WrongArgumentCount; const text = try args[0].toString(gpa); defer gpa.free(text);
// The empty string gets no digest. `d41d8cd9...` is a perfectly good // answer and libxslt declines to give it -- its wrapper returns before // pushing anything when the input has no length -- so a stylesheet that // hashes a missing value sees nothing rather than the one digest every // missing value shares. if (text.len == 0) return try Value.ownedString(gpa, "");
return switch (which) { .md5 => try hex(gpa, std.crypto.hash.Md5, text), .sha1 => try hex(gpa, std.crypto.hash.Sha1, text), };}
fn hex(gpa: Allocator, comptime Hash: type, text: []const u8) Error!Value { var digest: [Hash.digest_length]u8 = undefined; Hash.hash(text, &digest, .{}); const out = try gpa.alloc(u8, digest.len * 2); _ = std.fmt.bufPrint(out, "{x}", .{&digest}) catch unreachable; return .{ .string = out };}
// -- strings -----------------------------------------------------------------
const StringFunction = enum { replace, padding, concat, tokenize, split, @"align", @"encode-uri", @"decode-uri",};
const string_names = std.StaticStringMap(StringFunction).initComptime(.{ .{ "replace", .replace }, .{ "padding", .padding }, .{ "concat", .concat }, .{ "tokenize", .tokenize }, .{ "split", .split }, .{ "align", .@"align" }, .{ "encode-uri", .@"encode-uri" }, .{ "decode-uri", .@"decode-uri" },});
/// `http://exslt.org/strings`.////// `tokenize` and `split` return node-sets, and a node-set has to hold nodes/// of some document -- so those two are the engine's business rather than this/// module's and are not answered here. The rest are string functions.fn strings(gpa: Allocator, local: []const u8, args: []const Value) Error!?Value { const which = string_names.get(local) orelse return null;
switch (which) { // These three build node-sets, and a node-set holds nodes of some // document -- so they are the engine's business rather than this // module's. `replace` is among them because EXSLT has it return a node // set: its replacements may themselves be nodes. .tokenize, .split, .replace => return null, .@"encode-uri" => { // `str:encode-uri(string, escape-reserved)`. An encoding argument // is accepted only if it says UTF-8, which is the only one there // is here; anything else yields the empty string rather than a // wrong answer. if (args.len < 2 or args.len > 3) return error.WrongArgumentCount; if (args.len == 3) { const encoding = try args[2].toString(gpa); defer gpa.free(encoding); if (!std.ascii.eqlIgnoreCase(encoding, "UTF-8")) { return try Value.ownedString(gpa, ""); } } const subject = try args[0].toString(gpa); defer gpa.free(subject); const escape_reserved = args[1].toBoolean();
var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); for (subject) |c| { if (uriUnreserved(c) or (!escape_reserved and uriReserved(c))) { try out.append(gpa, c); } else { try out.print(gpa, "%{X:0>2}", .{c}); } } return .{ .string = try out.toOwnedSlice(gpa) }; }, .@"decode-uri" => { if (args.len < 1 or args.len > 2) return error.WrongArgumentCount; if (args.len == 2) { const encoding = try args[1].toString(gpa); defer gpa.free(encoding); if (!std.ascii.eqlIgnoreCase(encoding, "UTF-8")) { return try Value.ownedString(gpa, ""); } } const subject = try args[0].toString(gpa); defer gpa.free(subject);
var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var i: usize = 0; while (i < subject.len) { if (subject[i] == '%' and i + 2 < subject.len) { if (std.fmt.parseInt(u8, subject[i + 1 ..][0..2], 16)) |byte| { try out.append(gpa, byte); i += 3; continue; } else |_| {} } try out.append(gpa, subject[i]); i += 1; } // Decoding can produce bytes that are not a character in any // encoding, and a string that is not UTF-8 has no business // reaching the rest of the engine. libxslt throws the whole // answer away rather than part of it, and so does this. if (!std.unicode.utf8ValidateSlice(out.items)) { return try Value.ownedString(gpa, ""); } return .{ .string = try out.toOwnedSlice(gpa) }; }, .padding => { // `str:padding(length, padding)`: the padding string repeated and // cut to that many characters, which is how a caller builds an // indent without a recursive template. if (args.len < 1 or args.len > 2) return error.WrongArgumentCount; const wanted = try args[0].toNumber(gpa); const count: usize = if (std.math.isNan(wanted) or wanted < 1) 0 else if (wanted > 1 << 20) 1 << 20 else @intFromFloat(wanted); const pad = if (args.len == 2) try args[1].toString(gpa) else try gpa.dupe(u8, " "); defer gpa.free(pad); const unit = if (pad.len == 0) " " else pad;
var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var written: usize = 0; while (written < count) { var it = CharacterIterator{ .src = unit }; while (it.next()) |c| { if (written == count) break; try out.appendSlice(gpa, c); written += 1; } } return .{ .string = try out.toOwnedSlice(gpa) }; }, .concat => { // `str:concat(node-set)`: every node's string-value, run together. if (args.len != 1) return error.WrongArgumentCount; const ns = try nodeSet(args[0]); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); for (ns) |n| { const s = try n.stringValue(gpa); defer gpa.free(s); try out.appendSlice(gpa, s); } return .{ .string = try out.toOwnedSlice(gpa) }; }, .@"align" => { // `str:align(string, width, mode)`: cut to the width if it is // longer, padded to it if shorter. if (args.len < 2 or args.len > 3) return error.WrongArgumentCount; const subject = try args[0].toString(gpa); defer gpa.free(subject); const target = try args[1].toString(gpa); defer gpa.free(target); const mode = if (args.len == 3) try args[2].toString(gpa) else try gpa.dupe(u8, "left"); defer gpa.free(mode);
const width = countCharacters(target); const have = countCharacters(subject); // A string at least as long as the padding is cut to its first // `width` characters whatever the mode says. The mode decides // where the *padding* goes, and there is none to place here. if (have >= width) { return .{ .string = try gpa.dupe(u8, sliceCharacters(subject, 0, width)) }; } const missing = width - have; const before: usize = if (std.mem.eql(u8, mode, "right")) missing else if (std.mem.eql(u8, mode, "center")) missing / 2 else 0;
var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); try out.appendSlice(gpa, sliceCharacters(target, 0, before)); try out.appendSlice(gpa, subject); try out.appendSlice(gpa, sliceCharacters(target, before + have, missing - before)); return .{ .string = try out.toOwnedSlice(gpa) }; }, }}
/// Whether a character is never escaped by `str:encode-uri`: the alphanumerics/// and RFC 2396's unreserved marks, plus `@`, which libxml2's escaper leaves/// alone whatever list it is given.fn uriUnreserved(c: u8) bool { if (std.ascii.isAlphanumeric(c)) return true; return switch (c) { '-', '_', '.', '!', '~', '*', '\'', '(', ')', '@' => true, else => false, };}
/// The characters `str:encode-uri` leaves alone when it is told not to escape/// the reserved set. `%` is not among them, so an already-escaped string is/// escaped again -- which is right here, because these two are a pair and/// `decode-uri` has to be able to undo exactly what `encode-uri` did.fn uriReserved(c: u8) bool { return switch (c) { ';', '/', '?', ':', '&', '=', '+', '$', ',', '[', ']' => true, else => false, };}
/// The string `str:replace` produces, which the engine wraps in a node-set.////// `search` and `replace` may each be one string or a node-set of them: the/// n-th thing searched for is replaced by the n-th replacement, and one with/// no replacement is deleted. The longest match at a position wins, so that a/// pair of searches where one is a prefix of the other does the expected/// thing.pub fn replace(gpa: Allocator, args: []const Value) Error![]u8 { if (args.len != 3) return error.WrongArgumentCount; const subject = try args[0].toString(gpa); defer gpa.free(subject);
var search: Strings = try .init(gpa, args[1]); defer search.deinit(gpa); var replacement: Strings = try .init(gpa, args[2]); defer replacement.deinit(gpa);
// An *empty* search string cannot match at a position, so it is handled // apart: its replacement is inserted between characters, before each one // that something else did not already consume. Only the first empty search // counts, and only if it has a replacement to insert. var empty: ?usize = null; for (search.items, 0..) |needle, k| { if (needle.len == 0) { empty = k; break; } } if (empty) |k| { if (k >= replacement.items.len or replacement.items[k].len == 0) empty = null; }
var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa);
// `start` trails `src` over the run of characters that nothing matched, // so an unmatched stretch is copied in one go rather than a byte at a // time. var src: usize = 0; var start: usize = 0; while (src < subject.len) { var best: usize = 0; var best_len: usize = 0; for (search.items, 0..) |needle, k| { if (needle.len <= best_len) continue; if (!std.mem.startsWith(u8, subject[src..], needle)) continue; best = k; best_len = needle.len; }
if (best_len == 0) { if (empty) |k| { if (start < src) { try out.appendSlice(gpa, subject[start..src]); try out.appendSlice(gpa, replacement.items[k]); start = src; } } src += nextCharacter(subject, src); continue; }
if (start < src) try out.appendSlice(gpa, subject[start..src]); if (best < replacement.items.len) try out.appendSlice(gpa, replacement.items[best]); src += best_len; start = src; } if (start < src) try out.appendSlice(gpa, subject[start..src]);
return out.toOwnedSlice(gpa);}
fn nextCharacter(s: []const u8, i: usize) usize { const len = std.unicode.utf8ByteSequenceLength(s[i]) catch 1; return @min(len, s.len - i);}
/// An argument that may be one string or a node-set of them.////// `str:replace` takes its searches and replacements either way, which is the/// only reason this exists: the two shapes have to be read as one list, and a/// node-set's string-values have to be owned by somebody.const Strings = struct { items: [][]const u8, owned: bool,
fn init(gpa: Allocator, v: Value) Allocator.Error!Strings { switch (v) { .node_set => |ns| { const items = try gpa.alloc([]const u8, ns.len); var filled: usize = 0; errdefer { for (items[0..filled]) |s| gpa.free(s); gpa.free(items); } for (ns, items) |n, *slot| { slot.* = try n.stringValue(gpa); filled += 1; } return .{ .items = items, .owned = true }; }, else => { const items = try gpa.alloc([]const u8, 1); errdefer gpa.free(items); items[0] = try v.toString(gpa); return .{ .items = items, .owned = true }; }, } }
fn deinit(s: *Strings, gpa: Allocator) void { if (s.owned) { for (s.items) |item| gpa.free(item); } gpa.free(s.items); }};
/// Walks a string one character at a time, so that a width is counted in/// characters rather than in bytes.const CharacterIterator = struct { src: []const u8, pos: usize = 0,
fn next(it: *CharacterIterator) ?[]const u8 { if (it.pos >= it.src.len) return null; const len = std.unicode.utf8ByteSequenceLength(it.src[it.pos]) catch 1; const end = @min(it.pos + len, it.src.len); const out = it.src[it.pos..end]; it.pos = end; return out; }};
fn countCharacters(s: []const u8) usize { var it = CharacterIterator{ .src = s }; var n: usize = 0; while (it.next() != null) n += 1; return n;}
/// `count` characters of `s` starting at character `from`, clamped to what is/// there rather than refusing.fn sliceCharacters(s: []const u8, from: usize, count: usize) []const u8 { var it = CharacterIterator{ .src = s }; var i: usize = 0; var start = s.len; var end = s.len; while (it.next() != null) : (i += 1) { if (i == from) start = it.pos - lastLength(s, it.pos); if (i == from + count) { end = it.pos - lastLength(s, it.pos); break; } } if (start > end) return s[s.len..]; return s[start..end];}
fn lastLength(s: []const u8, pos: usize) usize { var back: usize = 1; while (back < pos and back < 4 and (s[pos - back] & 0xC0) == 0x80) back += 1; return back;}
// -- tests -------------------------------------------------------------------
const testing = std.testing;
fn expectString(expected: []const u8, name: Name, args: []const Value) !void { const gpa = testing.allocator; const got = (try call(gpa, name, args)).?; defer got.deinit(gpa); const text = try got.toString(gpa); defer gpa.free(text); try testing.expectEqualStrings(expected, text);}
fn str(s: []const u8) Value { return .{ .string = @constCast(s) };}
test "str:replace takes the longest match" { const gpa = testing.allocator; { const got = try replace(gpa, &.{ str("xabcy"), str("abc"), str("1") }); defer gpa.free(got); try testing.expectEqualStrings("x1y", got); } { // With nothing to search for, the subject comes back unchanged. const got = try replace(gpa, &.{ str("xabcy"), .{ .node_set = &.{} }, .{ .node_set = &.{} } }); defer gpa.free(got); try testing.expectEqualStrings("xabcy", got); } { // An empty search string matches nowhere, so its replacement lands // between the characters nothing else consumed -- and not before the // first or after the last, since neither has an unmatched run in // front of it. const got = try replace(gpa, &.{ str("foo"), str(""), str("baz") }); defer gpa.free(got); try testing.expectEqualStrings("fbazobazo", got); } { // An empty replacement for the empty search turns the whole thing off // rather than inserting nothing many times. const got = try replace(gpa, &.{ str("foo"), str(""), str("") }); defer gpa.free(got); try testing.expectEqualStrings("foo", got); }}
test "str:encode-uri and str:decode-uri are a pair" { const encode: Name = .{ .uri = strings_ns, .local = "encode-uri" }; const decode: Name = .{ .uri = strings_ns, .local = "decode-uri" }; // The reserved characters go when asked for and stay when not; `%` goes // either way, so that decoding can undo exactly what encoding did. try expectString("%3B%2F%3F%3A%26%3D%5B%5D%2B%24%2C", encode, &.{ str(";/?:&=[]+$,"), .{ .boolean = true } }); try expectString(";/?:&=[]+$,", encode, &.{ str(";/?:&=[]+$,"), .{ .boolean = false } }); try expectString("-_.!~*'()@", encode, &.{ str("-_.!~*'()@"), .{ .boolean = true } }); try expectString("%25", encode, &.{ str("%"), .{ .boolean = true } }); try expectString("%F0%9F%91%8C", encode, &.{ str("\u{1F44C}"), .{ .boolean = true } }); try expectString("\u{1F44C}", decode, &.{str("%F0%9F%91%8C")}); // Bytes that are not UTF-8 are no answer at all. try expectString("", decode, &.{str("%FF")}); // An encoding other than UTF-8 is not one this can produce. try expectString("", encode, &.{ str("x"), .{ .boolean = true }, str("ISO-8859-1") });}
test "str:padding repeats its unit and cuts it to the width" { try expectString("-*-*-", .{ .uri = strings_ns, .local = "padding" }, &.{ .{ .number = 5 }, str("-*"), }); // A width below one is no padding, and an empty unit falls back to a // space rather than looping forever. try expectString("", .{ .uri = strings_ns, .local = "padding" }, &.{ .{ .number = 0 }, str("-") }); try expectString(" ", .{ .uri = strings_ns, .local = "padding" }, &.{ .{ .number = 3 }, str("") });}
test "str:align pads or cuts to the width of its second argument" { const name: Name = .{ .uri = strings_ns, .local = "align" }; try expectString("ab...", name, &.{ str("ab"), str("....."), str("left") }); try expectString("...ab", name, &.{ str("ab"), str("....."), str("right") }); try expectString(".ab..", name, &.{ str("ab"), str("....."), str("center") }); // Longer than the width is cut from the left whatever the mode says: // the mode places the padding, and there is none to place. try expectString("abc", name, &.{ str("abcdef"), str("..."), str("left") }); try expectString("abc", name, &.{ str("abcdef"), str("..."), str("right") });}
test "math:constant reads as many digits as were asked for" { try expectString("3.141", .{ .uri = math_ns, .local = "constant" }, &.{ str("PI"), .{ .number = 5 }, }); try expectString("NaN", .{ .uri = math_ns, .local = "constant" }, &.{ str("nothing"), .{ .number = 5 }, });}
test "a name from no module this implements is not answered" { const gpa = testing.allocator; try testing.expect(try call(gpa, .{ .uri = "http://exslt.org/dates-and-times", .local = "add" }, &.{}) == null); try testing.expect(try call(gpa, .{ .uri = math_ns, .local = "atan2" }, &.{}) == null); try testing.expect(!has(.{ .uri = math_ns, .local = "atan2" })); try testing.expect(has(.{ .uri = math_ns, .local = "power" })); try testing.expect(has(.{ .uri = sets_ns, .local = "distinct" }));}
test "crypto:md5 and crypto:sha1 are hexadecimal digests of the UTF-8 bytes" { try expectString( "5d41402abc4b2a76b9719d911017c592", .{ .uri = crypto_ns, .local = "md5" }, &.{str("hello")}, ); try expectString( "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", .{ .uri = crypto_ns, .local = "sha1" }, &.{str("hello")}, ); // The empty string gets no digest, which is libxslt's choice rather than // an absence of one to give. try expectString("", .{ .uri = crypto_ns, .local = "md5" }, &.{str("")}); // The ciphers are not implemented, so their names are not answered at // all -- which is what lets an `xsl:fallback` run or a diagnostic name // them, rather than a stylesheet believing RC4 protected something. const gpa = testing.allocator; try testing.expect(try call(gpa, .{ .uri = crypto_ns, .local = "rc4-encrypt" }, &.{}) == null); try testing.expect(!has(.{ .uri = crypto_ns, .local = "rc4-encrypt" })); try testing.expect(has(.{ .uri = crypto_ns, .local = "sha1" }));}