Something went wrong. Try again.
An XSLT 1.0 processor for Zig 0.16, built on zxml.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! `zxsl`, the command line transformer.//!//! Deliberately shaped like `xsltproc`, because that is the program every//! example on the web is written for and because the test suite compares the//! two: a case that has to be invoked differently is a case that is not really//! being compared.//!//! The filesystem only becomes reachable here. The library takes a `Loader`//! and has none of its own, so `xsl:include` and `document()` read a file when//! this program is driving and read nothing at all when something else is --//! which is also how the `Io` gets in, since the library never names one.
const std = @import("std");const Io = std.Io;const zxsl = @import("zxsl");
const usage = \\usage: zxsl [options] <stylesheet> <document> \\ \\Transforms an XML document with an XSLT 1.0 stylesheet. A document of `-` \\is read from standard input. \\ \\options: \\ -o, --output FILE write to FILE instead of standard output \\ --stringparam N V bind the top-level parameter N to the string V \\ --param N V bind N to the result of the XPath expression V \\ --initial-template N enter by calling the named template N \\ --initial-mode N apply templates to the source root in mode N \\ --novalid, --nonet accepted and ignored; no DTD or network is read \\ -q, --quiet suppress xsl:message output \\ -h, --help show this message \\ -V, --version show the version \\;
const max_file_bytes: usize = 256 * 1024 * 1024;
pub fn main(init: std.process.Init) !void { var stdout_buffer: [64 * 1024]u8 = undefined; var stdout: Io.File.Writer = .init(.stdout(), init.io, &stdout_buffer); // `zxsl s.xsl big.xml | head` closes the pipe under us. That is how the // tool is meant to be used rather than a failure, so it must not surface // as an error and a stack trace. run(init, &stdout) catch |err| { if (err == error.WriteFailed) exitOnBrokenPipe(&stdout); return err; };}
fn run(init: std.process.Init, stdout: *Io.File.Writer) !void { const gpa = init.gpa; const io = init.io; const arena = init.arena.allocator();
const out = &stdout.interface;
const args = try init.minimal.args.toSlice(arena);
var output_path: ?[]const u8 = null; // XSLT 2.0's two other ways in. `xsltproc` has neither, because XSLT 1.0 // has only the one -- apply templates to the source root in the unnamed // mode -- so these are the first options here that are not its. var initial_template: ?[]const u8 = null; var initial_mode: ?[]const u8 = null; var quiet = false; var params: std.ArrayList(zxsl.transform.Parameter) = .empty; var positional: std.ArrayList([]const u8) = .empty;
var i: usize = @min(1, args.len); while (i < args.len) : (i += 1) { const arg = args[i]; if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { try out.writeAll(usage); try out.flush(); return; } else if (std.mem.eql(u8, arg, "-V") or std.mem.eql(u8, arg, "--version")) { try out.writeAll("zxsl 0.2.0-dev (XSLT 1.0)\n"); try out.flush(); return; } else if (std.mem.eql(u8, arg, "-q") or std.mem.eql(u8, arg, "--quiet")) { quiet = true; } else if (std.mem.eql(u8, arg, "--novalid") or std.mem.eql(u8, arg, "--nonet")) { // `xsltproc` takes these. Nothing here reads a DTD or the network, // so they are already true. } else if (std.mem.eql(u8, arg, "--initial-template")) { i += 1; if (i >= args.len) fatal(io, "--initial-template needs a template name", .{}); initial_template = args[i]; } else if (std.mem.eql(u8, arg, "--initial-mode")) { i += 1; if (i >= args.len) fatal(io, "--initial-mode needs a mode name", .{}); initial_mode = args[i]; } else if (std.mem.eql(u8, arg, "-o") or std.mem.eql(u8, arg, "--output")) { i += 1; if (i >= args.len) fatal(io, "{s} needs a file name", .{arg}); output_path = args[i]; } else if (std.mem.eql(u8, arg, "--stringparam") or std.mem.eql(u8, arg, "--param")) { if (i + 2 >= args.len) fatal(io, "{s} needs a name and a value", .{arg}); const name = args[i + 1]; const raw = args[i + 2]; i += 2; // `--param` takes an XPath expression, and the overwhelmingly // common use is a quoted string literal. Unwrapping that is enough // to make the two spellings interchangeable for what anyone // actually writes on a command line. const text = if (std.mem.eql(u8, arg, "--param")) unquote(raw) else raw; try params.append(arena, .{ .name = .{ .local = name }, .value = text }); } else if (arg.len > 1 and arg[0] == '-' and !std.mem.eql(u8, arg, "-")) { fatal(io, "unknown option {s}", .{arg}); } else { try positional.append(arena, arg); } }
if (positional.items.len != 2) { var stderr_buffer: [4096]u8 = undefined; var stderr: Io.File.Writer = .init(.stderr(), io, &stderr_buffer); stderr.interface.writeAll(usage) catch {}; stderr.interface.flush() catch {}; std.process.exit(2); }
const stylesheet_path = positional.items[0]; const document_path = positional.items[1];
const stylesheet_src = readFile(gpa, io, stylesheet_path) catch |err| { fatal(io, "cannot read {s}: {t}", .{ stylesheet_path, err }); }; defer gpa.free(stylesheet_src);
var file_loader: FileLoader = .{ .io = io }; const loader = file_loader.loader();
// Secondary documents are resolved against the directory the main result // goes to, which is XSLT 2.0's rule for `xsl:result-document` and the // only reading of "relative URI" that makes `-o out/index.html` put // `ch01.html` beside it. Standard output has no directory, so the working // directory stands in. var document_sink: DocumentSink = .{ .gpa = gpa, .io = io, .base = if (output_path) |path| std.fs.path.dirname(path) orelse "." else ".", };
const sheet = zxsl.stylesheet.parse(gpa, stylesheet_src, .{ .loader = loader, .base_uri = stylesheet_path, }) catch |err| { fatal(io, "{s}: {t}", .{ stylesheet_path, err }); }; defer sheet.destroy(); // A parse can succeed with a diagnostic only when it failed, so this is // reached only on the way out. errdefer if (sheet.diagnostic) |d| reportDiagnostic(io, stylesheet_path, d);
const document_src = readFile(gpa, io, document_path) catch |err| { fatal(io, "cannot read {s}: {t}", .{ document_path, err }); }; defer gpa.free(document_src);
const source = zxsl.parse(gpa, document_src, document_path) catch |err| { fatal(io, "{s}: {t}", .{ document_path, err }); }; defer source.destroy();
var message_buffer: [4096]u8 = undefined; var messages: Io.File.Writer = .init(.stderr(), io, &message_buffer);
const result = zxsl.transform.transformToString(gpa, sheet, source, .{ .loader = loader, .parameters = params.items, .messages = if (quiet) null else &messages.interface, .sink = document_sink.sink(), .initial_template = if (initial_template) |n| .{ .local = n } else null, .initial_mode = if (initial_mode) |n| .{ .local = n } else null, // The tool has a clock, so `date:date-time()` works. A library // caller that wants a transformation to be a pure function of its // inputs simply does not pass one. .io = io, }) catch |err| { messages.interface.flush() catch {}; if (sheet.diagnostic) |d| fatal(io, "{s}: {s}", .{ stylesheet_path, d }); fatal(io, "{s}: {t}", .{ stylesheet_path, err }); }; defer gpa.free(result); messages.interface.flush() catch {};
if (output_path) |path| { const file = Io.Dir.cwd().createFile(io, path, .{}) catch |err| { fatal(io, "cannot write {s}: {t}", .{ path, err }); }; defer file.close(io); var buffer: [64 * 1024]u8 = undefined; var w = file.writer(io, &buffer); try w.interface.writeAll(result); try w.interface.flush(); return; }
try out.writeAll(result); try out.flush();}
/// Where `exsl:document` writes, and the only files this program creates that/// it was not named on the command line.////// It is confined to `base`. A stylesheet naming an absolute path, a URI with/// a scheme of its own, or a relative one that climbs out with `..` is/// refused rather than obeyed -- a stylesheet is input, and this is the one/// thing this program does at input's request that leaves a mark. Directories/// along the way are created, because a chunking stylesheet writes/// `ch01/s02.html` and expects `ch01` to appear.const DocumentSink = struct { gpa: std.mem.Allocator, io: Io, base: []const u8,
fn sink(d: *DocumentSink) zxsl.transform.Sink { return .{ .ctx = d, .writeFn = writeFn }; }
fn writeFn(ctx: ?*anyopaque, href: []const u8, bytes: []const u8) zxsl.Error!void { const d: *DocumentSink = @ptrCast(@alignCast(ctx.?)); const path = try d.confine(href) orelse return error.DocumentNotWritten; defer d.gpa.free(path);
if (std.fs.path.dirname(path)) |dir| { Io.Dir.cwd().createDirPath(d.io, dir) catch return error.DocumentNotWritten; } const file = Io.Dir.cwd().createFile(d.io, path, .{}) catch return error.DocumentNotWritten; defer file.close(d.io); var buffer: [64 * 1024]u8 = undefined; var w = file.writer(d.io, &buffer); w.interface.writeAll(bytes) catch return error.DocumentNotWritten; w.interface.flush() catch return error.DocumentNotWritten; }
/// `href` as a path under `base`, or null if it does not stay there. /// /// `resolve` is what does the work: it folds `.` and `..` away, so the /// answer is a real path and a prefix test on it means what it looks like /// it means. Testing the unfolded string instead would accept /// `sub/../../etc/passwd`, which starts with the base and is not under /// it. fn confine(d: *DocumentSink, href: []const u8) std.mem.Allocator.Error!?[]u8 { if (href.len == 0) return null; // A URI with a scheme names something this program cannot write, and // a fragment is forbidden on this attribute by the module itself. if (std.mem.indexOf(u8, href, "://") != null) return null; if (std.mem.findScalar(u8, href, '#') != null) return null; if (std.fs.path.isAbsolute(href)) return null;
const base = try std.fs.path.resolve(d.gpa, &.{d.base}); defer d.gpa.free(base); const full = try std.fs.path.resolve(d.gpa, &.{ d.base, href }); errdefer d.gpa.free(full);
// The base itself is not a file to write, and a sibling whose name // merely starts with the base's -- `out-of-band` against `out` -- is // not under it either, which is what the separator check is for. if (full.len <= base.len or !std.mem.startsWith(u8, full, base) or full[base.len] != std.fs.path.sep) { d.gpa.free(full); return null; } return full; }};
/// Reads `xsl:include`, `xsl:import` and `document()` from the filesystem,/// resolving each against the file that named it.////// This is where the `Io` lives: the library's `Loader` has no room for one/// because the library has no opinion about where a document comes from.const FileLoader = struct { io: Io,
fn loader(f: *FileLoader) zxsl.stylesheet.Loader { return .{ .ctx = f, .loadFn = loadFn, .resolveFn = resolveFn }; }
fn loadFn( ctx: ?*anyopaque, gpa: std.mem.Allocator, base: []const u8, href: []const u8, ) zxsl.Error![]u8 { const f: *FileLoader = @ptrCast(@alignCast(ctx.?)); const path = try resolvePath(gpa, base, href); defer gpa.free(path); return readFile(gpa, f.io, path) catch error.DocumentNotFound; }
fn resolveFn( _: ?*anyopaque, gpa: std.mem.Allocator, base: []const u8, href: []const u8, ) zxsl.Error![]u8 { return resolvePath(gpa, base, href); }
/// Resolves `href` against the *directory* of `base`, which is what makes /// a stylesheet that includes `common.xsl` find the one beside it rather /// than one in the working directory. fn resolvePath( gpa: std.mem.Allocator, base: []const u8, href: []const u8, ) std.mem.Allocator.Error![]u8 { if (href.len != 0 and href[0] == '/') return gpa.dupe(u8, href); const dir = std.fs.path.dirname(base) orelse return gpa.dupe(u8, href); return std.fs.path.join(gpa, &.{ dir, href }); }};
fn readFile(gpa: std.mem.Allocator, io: Io, path: []const u8) ![]u8 { var buffer: [64 * 1024]u8 = undefined; if (std.mem.eql(u8, path, "-")) { var reader = Io.File.stdin().readerStreaming(io, &buffer); return reader.interface.allocRemaining(gpa, .limited(max_file_bytes)); } const file = try Io.Dir.cwd().openFile(io, path, .{}); defer file.close(io); var reader = file.reader(io, &buffer); return reader.interface.allocRemaining(gpa, .limited(max_file_bytes));}
fn reportDiagnostic(io: Io, path: []const u8, diagnostic: []const u8) void { var buffer: [4096]u8 = undefined; var w: Io.File.Writer = .init(.stderr(), io, &buffer); w.interface.print("zxsl: {s}: {s}\n", .{ path, diagnostic }) catch {}; w.interface.flush() catch {};}
/// Takes its `Io` rather than reaching for one, which is the same rule the/// library follows: there is exactly one implementation in this program and it/// still arrives as a parameter.fn fatal(io: Io, comptime fmt: []const u8, args: anytype) noreturn { var buffer: [4096]u8 = undefined; var w: Io.File.Writer = .init(.stderr(), io, &buffer); w.interface.print("zxsl: " ++ fmt ++ "\n", args) catch {}; w.interface.flush() catch {}; std.process.exit(1);}
fn exitOnBrokenPipe(w: *Io.File.Writer) noreturn { w.interface.flush() catch |err| { if (err == error.BrokenPipe) std.process.exit(0); }; std.process.exit(1);}
/// Strips the quotes from an XPath string literal, leaving anything else/// alone.fn unquote(text: []const u8) []const u8 { if (text.len >= 2 and (text[0] == '\'' or text[0] == '"') and text[text.len - 1] == text[0]) { return text[1 .. text.len - 1]; } return text;}
const testing = std.testing;
test "an XPath string literal passed on the command line loses its quotes" { try testing.expectEqualStrings("value", unquote("'value'")); try testing.expectEqualStrings("value", unquote("\"value\"")); // Anything that is not a quoted literal is left as written. try testing.expectEqualStrings("1 + 2", unquote("1 + 2")); try testing.expectEqualStrings("'", unquote("'"));}
test "a relative href resolves against the directory of the file that named it" { const gpa = testing.allocator; { const path = try FileLoader.resolvePath(gpa, "a/b/style.xsl", "common.xsl"); defer gpa.free(path); try testing.expectEqualStrings("a/b/common.xsl", path); } { const path = try FileLoader.resolvePath(gpa, "style.xsl", "sub/common.xsl"); defer gpa.free(path); try testing.expectEqualStrings("sub/common.xsl", path); }}
test "a secondary document is confined to the directory the main result goes to" { const gpa = testing.allocator; var sink: DocumentSink = .{ .gpa = gpa, .io = undefined, .base = "out" };
const expected_dir = try std.fs.path.resolve(gpa, &.{"out"}); defer gpa.free(expected_dir);
// A plain name, and a name in a subdirectory that does not exist yet, // both land under the base. for ([_][]const u8{ "ch01.html", "ch01/s02.html", "./ch01.html" }) |href| { const path = (try sink.confine(href)).?; defer gpa.free(path); try testing.expect(std.mem.startsWith(u8, path, expected_dir)); try testing.expectEqual(std.fs.path.sep, path[expected_dir.len]); }
// `..` that stays inside is fine; `..` that leaves is not, and neither is // an absolute path, a URI with a scheme, a fragment, the empty string, or // a sibling directory whose name merely starts with the base's. { const path = (try sink.confine("ch01/../ch02.html")).?; defer gpa.free(path); try testing.expect(std.mem.endsWith(u8, path, "ch02.html")); } for ([_][]const u8{ "../escape.html", "ch01/../../escape.html", "/etc/passwd", "https://example.org/x.html", "file:///etc/passwd", "ch01.html#frag", // The case the separator check is for: this resolves to a path that // starts with the base's and is not under it. "../out-of-band/x.html", "", ".", "..", }) |href| { try testing.expectEqual(@as(?[]u8, null), try sink.confine(href)); }}