// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie
// SPDX-License-Identifier: MIT
//! Reading a stylesheet: its top-level declarations, and the machinery for
//! compiling the expressions written inside it.
//!
//! A stylesheet is an XML document, so it is parsed by the same parser as
//! everything else and then *interpreted from its tree* rather than compiled
//! into an instruction set of its own. What gets compiled is only what has to
//! be: the XPath in `select`, `test` and `match` attributes, and the attribute
//! value templates in literal result elements. Everything else -- which
//! instruction an element is, what its children are -- is read off the tree as
//! the transformation runs.
//!
//! That is a deliberate trade. An instruction set would run faster and would
//! be several hundred lines of translation whose only job is to restate a tree
//! that is already in memory. Since every expression is compiled once and
//! cached by the identity of the attribute node it came from, the work that
//! actually repeats is not repeated.
//!
//! Prefixes are the reason compilation needs a *place* and not just a string.
//! `select="x:a"` means whatever `x` was bound to on the element the attribute
//! sits on, so an expression is compiled against the stylesheet element it was
//! written on and the cache is keyed by that attribute node.
const std = @import("std");
const Allocator = std.mem.Allocator;
const tree = @import("ztree");
const xpath = @import("zxpath");
const pattern = @import("pattern.zig");
const runtime = @import("runtime.zig");
const serialize = @import("ztree").serialize;
const Document = tree.Document;
const NodeId = tree.NodeId;
const Name = tree.Name;
const Error = runtime.Error;
/// The XSLT namespace. An element is an instruction because it is in this
/// namespace, not because of how it is spelled, so a stylesheet may bind the
/// prefix to anything it likes.
pub const xslt_ns = "http://www.w3.org/1999/XSL/Transform";
/// EXSLT's `functions` module, whose `func:function` declares a function a
/// stylesheet may then call from any expression.
pub const func_ns = "http://exslt.org/functions";
/// Reads a stylesheet's included and imported documents.
///
/// An interface rather than a path, because a library that reaches for the
/// filesystem on its own cannot be used by anything that does not want it to
/// -- and because `document()` and `xsl:include` should be answerable from a
/// bundle, a cache, or nothing at all.
pub const Loader = struct {
ctx: ?*anyopaque = null,
/// Returns the text of `href` resolved against `base`. The caller frees it.
loadFn: *const fn (ctx: ?*anyopaque, gpa: Allocator, base: []const u8, href: []const u8) Error![]u8,
/// Resolves `href` against `base` into the URI the result should carry, so
/// that a document included from a subdirectory resolves its own relative
/// references correctly. The caller frees it.
resolveFn: *const fn (ctx: ?*anyopaque, gpa: Allocator, base: []const u8, href: []const u8) Error![]u8,
fn refuseLoad(_: ?*anyopaque, _: Allocator, _: []const u8, _: []const u8) Error![]u8 {
return error.DocumentNotFound;
}
fn passThroughResolve(_: ?*anyopaque, gpa: Allocator, _: []const u8, href: []const u8) Error![]u8 {
return gpa.dupe(u8, href);
}
/// A loader that refuses everything, which is what a stylesheet with no
/// includes needs and what keeps an untrusted one off the filesystem.
pub const none: Loader = .{ .loadFn = refuseLoad, .resolveFn = passThroughResolve };
pub fn load(l: Loader, gpa: Allocator, base: []const u8, href: []const u8) Error![]u8 {
return l.loadFn(l.ctx, gpa, base, href);
}
pub fn resolve(l: Loader, gpa: Allocator, base: []const u8, href: []const u8) Error![]u8 {
return l.resolveFn(l.ctx, gpa, base, href);
}
};
/// One template rule. A `match="a|b"` becomes two of these, because the
/// specification gives each alternative its own default priority and resolves
/// conflicts between them independently.
pub const Rule = struct {
/// The stylesheet document the template is in. Stored rather than looked
/// up: with `xsl:include` a stylesheet is several documents, and a
/// `NodeId` means nothing without knowing which.
doc: *Document,
alternative: pattern.Alternative,
mode: ?Name,
priority: f64,
/// The `xsl:template` element whose children are the body.
element: NodeId,
/// Lower is less important. An imported stylesheet's rules lose to the
/// importing one's however high their priority.
precedence: i32,
/// Position among all rules, which breaks a tie that precedence and
/// priority both leave open.
order: u32,
};
/// What a pattern's last step can possibly match, which is how a rule is
/// filed in `RuleIndex`.
///
/// It is deliberately about the *last* step only. A pattern is matched from
/// its last step backwards, so that step alone decides whether a rule could
/// apply to a given node at all -- everything to its left is about ancestors
/// and cannot be checked without walking them.
pub const Selector = union(enum) {
/// A name test on the child axis: matches elements with this local name.
element_named: []const u8,
/// `*` or `prefix:*` on the child axis.
element_any,
attribute_named: []const u8,
attribute_any,
text,
comment,
pi,
/// `/`, which matches nothing but the root.
root,
/// `node()` on the child axis: any kind of child.
any_child,
/// A pattern rooted at `id()` or `key()`, which cannot be classified
/// without evaluating it, so it is a candidate for everything.
unclassified,
};
/// Template rules grouped by what they could possibly match.
///
/// Dispatch asks "which rule handles this node" once per node, and answering
/// it by testing every rule in the stylesheet is quadratic in the obvious way:
/// libxslt's own `bug-166` -- fifteen thousand elements against a few dozen
/// rules -- took minutes that way and takes well under a second now.
///
/// Each bucket is sorted best-first, by the same order dispatch resolves
/// conflicts in, so a lookup is a merge across at most four of them that stops
/// at the first rule which actually matches.
pub const RuleIndex = struct {
/// Indices into `Stylesheet.rules`, keyed by local name. The namespace is
/// left to the pattern match: sharing a local name across namespaces is
/// rare enough that filing by it is already almost all of the win.
by_element: std.StringHashMapUnmanaged(std.ArrayList(u32)) = .empty,
by_attribute: std.StringHashMapUnmanaged(std.ArrayList(u32)) = .empty,
element_any: std.ArrayList(u32) = .empty,
attribute_any: std.ArrayList(u32) = .empty,
text: std.ArrayList(u32) = .empty,
comment: std.ArrayList(u32) = .empty,
pi: std.ArrayList(u32) = .empty,
root: std.ArrayList(u32) = .empty,
any_child: std.ArrayList(u32) = .empty,
unclassified: std.ArrayList(u32) = .empty,
pub fn deinit(index: *RuleIndex, gpa: Allocator) void {
var elements = index.by_element.valueIterator();
while (elements.next()) |list| list.deinit(gpa);
index.by_element.deinit(gpa);
var attributes = index.by_attribute.valueIterator();
while (attributes.next()) |list| list.deinit(gpa);
index.by_attribute.deinit(gpa);
index.element_any.deinit(gpa);
index.attribute_any.deinit(gpa);
index.text.deinit(gpa);
index.comment.deinit(gpa);
index.pi.deinit(gpa);
index.root.deinit(gpa);
index.any_child.deinit(gpa);
index.unclassified.deinit(gpa);
}
/// The rules filed under an element's local name, or nothing.
pub fn forElement(index: *const RuleIndex, local: []const u8) []const u32 {
const list = index.by_element.getPtr(local) orelse return &.{};
return list.items;
}
pub fn forAttribute(index: *const RuleIndex, local: []const u8) []const u32 {
const list = index.by_attribute.getPtr(local) orelse return &.{};
return list.items;
}
};
/// Where a rule belongs in the index.
pub fn selectorOf(alt: pattern.Alternative) Selector {
// An `id()` or `key()` pattern is a candidate for anything.
if (alt.membership != null) return .unclassified;
// `/` and nothing else.
if (alt.steps.len == 0) return .root;
const last = alt.steps[alt.steps.len - 1];
return switch (last.axis) {
.attribute => switch (last.node_test) {
.name => |nt| if (nt.local) |local|
.{ .attribute_named = local }
else
.attribute_any,
else => .attribute_any,
},
.child => switch (last.node_test) {
// A name test matches only the principal node type, which on the
// child axis is an element.
.name => |nt| if (nt.local) |local|
.{ .element_named = local }
else
.element_any,
.any => .any_child,
.text => .text,
.comment => .comment,
.pi => .pi,
},
// A pattern ends in a real step; a trailing `//` connector would be
// a syntax error, so this is unreachable in practice and harmless if
// it ever is not.
else => .unclassified,
};
}
/// True when `a` beats `b`: higher import precedence first, then higher
/// priority, then whichever was written last.
pub fn outranks(a: Rule, b: Rule) bool {
if (a.precedence != b.precedence) return a.precedence > b.precedence;
if (a.priority != b.priority) return a.priority > b.priority;
return a.order > b.order;
}
pub const NamedTemplate = struct {
doc: *Document,
name: Name,
element: NodeId,
precedence: i32,
};
pub const GlobalVariable = struct {
doc: *Document,
name: Name,
element: NodeId,
/// True for `xsl:param`, which a caller may override.
is_param: bool,
precedence: i32,
};
pub const Key = struct {
doc: *Document,
name: Name,
match_src: []const u8,
use_src: []const u8,
/// The `xsl:key` element, which is the scope the two expressions were
/// written in and so what their prefixes resolve against.
element: NodeId,
};
pub const AttributeSet = struct {
doc: *Document,
name: Name,
element: NodeId,
precedence: i32,
};
/// Resolves a namespace prefix against the declarations in scope on one
/// stylesheet element, which is what a prefix inside an expression means.
///
/// It is public because `dyn:evaluate` needs the same answer for an
/// expression that arrived as a string: the prefixes in it mean whatever they
/// mean where the *call* was written, not where the string came from.
pub const DynamicResolver = struct {
doc: *const Document,
node: NodeId,
pub fn lookup(ctx: ?*const anyopaque, prefix: []const u8) ?[]const u8 {
const self: *const DynamicResolver = @ptrCast(@alignCast(ctx.?));
return self.doc.lookupNamespace(self.node, prefix);
}
};
/// A function declared with EXSLT's `func:function`.
///
/// The shape is an `xsl:template`'s: `xsl:param` children first, then a
/// template body, which a `func:result` ends. What makes it a function rather
/// than a template is that the name must be in a namespace -- a function in no
/// namespace would collide with the core library -- and that it is reached by
/// being called from an expression rather than by matching or by name.
pub const ExsltFunction = struct {
doc: *Document,
name: Name,
element: NodeId,
precedence: i32,
};
/// A whitespace-stripping rule from `xsl:strip-space` or `xsl:preserve-space`.
pub const SpaceRule = struct {
/// The name test, as a `NameTest` rather than a pattern: these elements
/// take `*`, `prefix:*` and QNames and nothing else.
uri: ?[]const u8,
local: ?[]const u8,
strip: bool,
/// Same scale as a pattern's default priority, so that `*` loses to a
/// QName the same way a template rule would.
priority: f64,
};
/// A `xsl:decimal-format`, which `format-number` reads.
pub const DecimalFormat = struct {
name: ?Name = null,
decimal_separator: u21 = '.',
grouping_separator: u21 = ',',
infinity: []const u8 = "Infinity",
minus_sign: u21 = '-',
nan: []const u8 = "NaN",
percent: u21 = '%',
per_mille: u21 = '\u{2030}',
zero_digit: u21 = '0',
digit: u21 = '#',
pattern_separator: u21 = ';',
};
/// A `xsl:namespace-alias`: a namespace used in the stylesheet that stands for
/// a different one in the result. It exists so that a stylesheet can generate
/// another stylesheet without its own processor claiming the instructions.
pub const NamespaceAlias = struct {
stylesheet_uri: []const u8,
result_uri: []const u8,
result_prefix: []const u8,
precedence: i32,
};
/// An attribute value template: the `{...}` substitution that literal result
/// element attributes, and a handful of instruction attributes, use.
pub const Avt = struct {
parts: []const Part,
pub const Part = union(enum) {
literal: []const u8,
expr: *const xpath.Expr,
};
/// True when the template is a single literal, which is the common case
/// and lets the caller skip evaluation entirely.
pub fn constant(a: Avt) ?[]const u8 {
if (a.parts.len == 0) return "";
if (a.parts.len == 1 and a.parts[0] == .literal) return a.parts[0].literal;
return null;
}
};
pub const Stylesheet = struct {
gpa: Allocator,
/// Holds every compiled expression, every pattern, and the strings this
/// structure points at. The stylesheet documents themselves are separate,
/// because a `Document` owns an arena of its own.
arena: std.heap.ArenaAllocator,
/// The principal stylesheet document and everything it included or
/// imported, in the order they were read. All are owned.
documents: std.ArrayList(*Document) = .empty,
/// The text each of those documents was parsed from, in the same order,
/// held in the arena.
///
/// It is kept for `document('')`, which hands the stylesheet back to
/// itself as an ordinary XML document. The tree in `documents` has had its
/// whitespace-only text nodes removed, because that is what XSLT 3.4 says
/// happens to a *stylesheet*; the document a stylesheet reads with
/// `document('')` is not a stylesheet, and libxslt hands over one with its
/// indentation intact. Re-reading the source is the only way to have both.
sources: std.ArrayList([]const u8) = .empty,
rules: std.ArrayList(Rule) = .empty,
named: std.ArrayList(NamedTemplate) = .empty,
globals: std.ArrayList(GlobalVariable) = .empty,
keys: std.ArrayList(Key) = .empty,
attribute_sets: std.ArrayList(AttributeSet) = .empty,
functions: std.ArrayList(ExsltFunction) = .empty,
space_rules: std.ArrayList(SpaceRule) = .empty,
decimal_formats: std.ArrayList(DecimalFormat) = .empty,
aliases: std.ArrayList(NamespaceAlias) = .empty,
output: serialize.Output = .{},
/// Compiled expressions, keyed by the attribute node they were written on,
/// which is also what determines the prefixes they resolve against.
expr_cache: std.AutoHashMapUnmanaged(CacheKey, *const xpath.Expr) = .empty,
avt_cache: std.AutoHashMapUnmanaged(CacheKey, Avt) = .empty,
pattern_cache: std.AutoHashMapUnmanaged(CacheKey, pattern.Pattern) = .empty,
/// The effective version of each element that has been asked about,
/// keyed the same way the compiled artefacts are.
///
/// Computed from the tree rather than stored on the declarations, because
/// `xsl:version` can appear on a literal result element in the *middle*
/// of a template body -- so an effective version is a property of an
/// element, not of a declaration.
version_cache: std.AutoHashMapUnmanaged(CacheKey, Version) = .empty,
/// Rules grouped by what they can match, so that dispatch does not have
/// to test every rule against every node.
rule_index: RuleIndex = .{},
/// Where a diagnostic goes when parsing fails. Points into the arena.
diagnostic: ?[]const u8 = null,
/// The XSLT error code for whatever `diagnostic` describes, when there is
/// one this processor is confident about.
///
/// XSLT names its errors -- `XTSE0870`, `XTDE0160`, `XPST0003` -- and the
/// W3C suite asserts those names: 1,079 of the cases in scope here expect
/// a specific one. Without a code every "this should raise" case passes
/// on the strength of *any* error, which is how four `use-when` cases came
/// to pass by raising a complaint about `xsl:value-of` instead of the
/// XTSE0090 they were testing for.
///
/// Null where no code has been assigned yet, which is most places. A
/// wrong code is worse than none -- it turns a case that was honestly
/// unjudged into one that is confidently wrong -- so a site gets one only
/// when the specification plainly names it.
code: ?[]const u8 = null,
/// An expression is identified by the document it is in and the node it is
/// on, since a stylesheet may be several documents.
pub const CacheKey = struct {
serial: u32,
node: NodeId,
};
/// The version of XSLT this processor implements.
///
/// One constant, because two things depend on it and they must never
/// disagree: it is what `system-property('xsl:version')` answers, and it is
/// what a stylesheet's own version is compared against to decide whether
/// backwards- or forwards-compatible behaviour is in force.
///
/// It stays at 1.0 until the XSLT 2.0 instruction set is complete. Raising it
/// early would be worse than claiming less than is offered: a stylesheet that
/// asks `system-property('xsl:version')` takes the 2.0 branch, and a
/// stylesheet declaring `version="2.0"` stops being in forwards-compatible
/// mode and so stops degrading gracefully around the parts that are missing.
/// `element-available()` is the honest per-feature answer in the meantime,
/// and that is what it is for.
pub const implemented_version: f64 = 1.0;
/// The effective version of a stylesheet element, and what it turns on.
///
/// XSLT 2.0 section 3.5 gives every element in a stylesheet an effective
/// version, taken from the nearest ancestor-or-self carrying a version
/// attribute. Three modes come out of comparing it with
/// `implemented_version`, and they are not two.
///
/// The comparison is against what *this* processor implements rather than
/// against a fixed 2.0, which is the whole of what forwards compatibility
/// means: a stylesheet is forwards-compatible when it was written for a
/// later version than the one reading it. libxslt's `general/bug-175` is the
/// case that makes this concrete -- it declares `version="2.0"` and an
/// `xsl:function`, and expects a processor that lacks `xsl:function` to
/// ignore the declaration and take the `xsl:otherwise` branch. Comparing
/// against a fixed 2.0 would put it in `.current` mode and reject a
/// stylesheet whose whole point is degrading gracefully.
pub const Version = struct {
value: f64,
mode: Mode,
pub const Mode = enum { backwards, current, forwards };
/// What a stated version number means to this processor.
pub fn of(value: f64) Version {
return .{
.value = value,
.mode = if (value < implemented_version)
.backwards
else if (value > implemented_version)
.forwards
else
.current,
};
}
/// Whether the stylesheet asked for at least this version of XSLT.
///
/// This is the question a *feature* asks, and it is not the question
/// `mode` answers. `mode` is about expression semantics -- whether XPath
/// 1.0 compatibility is in force -- and is relative to what this
/// processor implements, so it moves when that constant moves. Whether
/// `xsl:value-of` writes one node or all of them is instead a property of
/// the version the stylesheet was written for, and `version="1.0"` means
/// 1.0 whichever processor is reading it.
pub fn atLeast(v: Version, want: f64) bool {
return v.value >= want;
}
/// What an element with no version anywhere above it gets.
///
/// Only reachable for an element outside a stylesheet, since
/// `xsl:stylesheet` is required to carry one and a literal result element
/// used as a stylesheet is required to carry `xsl:version`.
pub const unknown: Version = .of(implemented_version);
};
/// The version attribute stated on this element, if it states one.
///
/// The spelling depends on where it is: unprefixed `version` on an
/// element in the XSLT namespace, `xsl:version` on anything else. And
/// there are two XSLT elements where an unprefixed `version` is **not**
/// this attribute at all -- on `xsl:output` and `xsl:result-document` it
/// is a serialization parameter naming the XML declaration's version, so
/// reading it here would have `` silently put
/// a 2.0 stylesheet into backwards-compatible mode from that element
/// down.
fn statedVersion(doc: *Document, elem: NodeId) ?[]const u8 {
const name = doc.node(elem).name;
if (std.mem.eql(u8, name.uri, xslt_ns)) {
if (std.mem.eql(u8, name.local, "output")) return null;
if (std.mem.eql(u8, name.local, "result-document")) return null;
return doc.attributeValue(elem, "", "version");
}
return doc.attributeValue(elem, xslt_ns, "version");
}
/// The effective version in force at an element, memoized.
pub fn effectiveVersion(s: *Stylesheet, doc: *Document, elem: NodeId) Error!Version {
const key: CacheKey = .{ .serial = doc.serial, .node = elem };
if (s.version_cache.get(key)) |v| return v;
var version: Version = .unknown;
var at: ?NodeId = elem;
while (at) |id| : (at = doc.node(id).parent) {
if (doc.node(id).kind != .element) continue;
const text = statedVersion(doc, id) orelse continue;
// A version that is not a number is not a version. XSLT makes
// this a static error; taking it as 1.0 would be a guess, and a
// guess here changes the meaning of every expression below it.
const value = std.fmt.parseFloat(f64, std.mem.trim(u8, text, " \t\n\r")) catch {
s.setDiagnostic("version=\"{s}\" is not a number", .{text});
return error.InvalidStylesheet;
};
version = .of(value);
break;
}
try s.version_cache.put(s.gpa, key, version);
return version;
}
pub fn destroy(s: *Stylesheet) void {
const gpa = s.gpa;
for (s.documents.items) |d| d.destroy();
s.documents.deinit(gpa);
s.sources.deinit(gpa);
s.rules.deinit(gpa);
s.named.deinit(gpa);
s.globals.deinit(gpa);
s.keys.deinit(gpa);
s.attribute_sets.deinit(gpa);
s.functions.deinit(gpa);
s.space_rules.deinit(gpa);
s.decimal_formats.deinit(gpa);
s.aliases.deinit(gpa);
s.rule_index.deinit(gpa);
s.expr_cache.deinit(gpa);
s.avt_cache.deinit(gpa);
s.pattern_cache.deinit(gpa);
s.version_cache.deinit(gpa);
s.arena.deinit();
gpa.destroy(s);
}
// -- compiling expressions ------------------------------------------------
/// Resolves prefixes the way the element an expression was written on
/// does.
const ScopeResolver = DynamicResolver;
/// Compiles the expression in an attribute, or returns the one already
/// compiled for it.
///
/// `scope` is the element the attribute is on: prefixes resolve there, and
/// the compiled form is cached against the attribute node so that a
/// template body inside a loop compiles its expressions once.
pub fn expression(s: *Stylesheet, doc: *Document, attr: NodeId) Error!*const xpath.Expr {
const key: CacheKey = .{ .serial = doc.serial, .node = attr };
if (s.expr_cache.get(key)) |e| return e;
const scope = doc.node(attr).parent orelse return error.InvalidStylesheet;
var resolver: ScopeResolver = .{ .doc = doc, .node = scope };
const compiled = xpath.compile(
s.arena.allocator(),
doc.node(attr).value,
.{ .ctx = &resolver, .lookupFn = ScopeResolver.lookup },
) catch |err| return s.fail(doc, attr, "expression", err, codeFor(err));
try s.expr_cache.put(s.gpa, key, compiled);
return compiled;
}
/// The same for a match pattern.
pub fn matchPattern(s: *Stylesheet, doc: *Document, attr: NodeId) Error!pattern.Pattern {
const key: CacheKey = .{ .serial = doc.serial, .node = attr };
if (s.pattern_cache.get(key)) |p| return p;
const scope = doc.node(attr).parent orelse return error.InvalidStylesheet;
var resolver: ScopeResolver = .{ .doc = doc, .node = scope };
const compiled = pattern.compile(
s.arena.allocator(),
doc.node(attr).value,
.{ .ctx = &resolver, .lookupFn = ScopeResolver.lookup },
// XTSE0340: the `match` attribute holds something that is not a
// pattern. Distinct from XPST0003 because a pattern is a
// *restriction* of an expression -- `$x/foo` parses perfectly and
// is still not one -- but a prefix that resolves to nothing is
// still the prefix's error rather than the pattern's.
) catch |err| return s.fail(doc, attr, "pattern", err, switch (err) {
error.UnboundPrefix => "XPST0081",
else => "XTSE0340",
});
try s.pattern_cache.put(s.gpa, key, compiled);
return compiled;
}
/// Compiles an attribute value template.
pub fn attributeValueTemplate(s: *Stylesheet, doc: *Document, attr: NodeId) Error!Avt {
const key: CacheKey = .{ .serial = doc.serial, .node = attr };
if (s.avt_cache.get(key)) |a| return a;
const scope = doc.node(attr).parent orelse return error.InvalidStylesheet;
var resolver: ScopeResolver = .{ .doc = doc, .node = scope };
const compiled = parseAvt(
s.arena.allocator(),
doc.node(attr).value,
.{ .ctx = &resolver, .lookupFn = ScopeResolver.lookup },
// An attribute value template is a run of XPath expressions, so
// a failure in one is XPath's.
) catch |err| return s.fail(doc, attr, "attribute value template", err, codeFor(err));
try s.avt_cache.put(s.gpa, key, compiled);
return compiled;
}
fn fail(
s: *Stylesheet,
doc: *Document,
attr: NodeId,
what: []const u8,
err: anyerror,
code: ?[]const u8,
) Error {
// A diagnostic is worth more than the error name on its own: an
// unbound prefix and a stray bracket are both `InvalidStylesheet` to
// the caller, and neither is findable without the text that caused it.
s.diagnostic = std.fmt.allocPrint(
s.arena.allocator(),
"{s} in {s}=\"{s}\": {s}",
.{ what, doc.node(attr).name.local, doc.node(attr).value, @errorName(err) },
) catch null;
s.code = code;
return error.InvalidStylesheet;
}
pub fn setDiagnostic(s: *Stylesheet, comptime fmt: []const u8, args: anytype) void {
s.diagnostic = std.fmt.allocPrint(s.arena.allocator(), fmt, args) catch null;
s.code = null;
}
/// The same, with the XSLT error code the specification names for it.
pub fn setDiagnosticCode(
s: *Stylesheet,
code: []const u8,
comptime fmt: []const u8,
args: anytype,
) void {
s.diagnostic = std.fmt.allocPrint(s.arena.allocator(), fmt, args) catch null;
s.code = code;
}
};
/// The XSLT error code for a failure out of `xpath.compile`.
///
/// The parser refuses for three reasons and two of them are the same error to
/// the specification: a stray bracket and an expression nested past the depth
/// limit are both XPST0003, "this is not an expression". A prefix that is not
/// declared is its own error, XPST0081, and is worth telling apart -- it is
/// the one a stylesheet author can fix by adding an `xmlns:`.
fn codeFor(err: anyerror) []const u8 {
return switch (err) {
error.UnboundPrefix => "XPST0081",
else => "XPST0003",
};
}
/// Splits an attribute value template into its literal and expression parts.
///
/// `{` and `}` are doubled to escape them, which is why this is a scanner
/// rather than a search: `{{` is a literal brace and not the start of
/// anything, and a `}` outside an expression is only legal doubled.
fn parseAvt(arena: Allocator, src: []const u8, ns: xpath.NsResolver) !Avt {
var parts: std.ArrayList(Avt.Part) = .empty;
defer parts.deinit(arena);
var literal: std.ArrayList(u8) = .empty;
defer literal.deinit(arena);
var i: usize = 0;
while (i < src.len) {
const c = src[i];
if (c == '{') {
if (i + 1 < src.len and src[i + 1] == '{') {
try literal.append(arena, '{');
i += 2;
continue;
}
if (literal.items.len != 0) {
try parts.append(arena, .{ .literal = try arena.dupe(u8, literal.items) });
literal.clearRetainingCapacity();
}
const end = try findExpressionEnd(src, i + 1);
const expr = try xpath.compile(arena, src[i + 1 .. end], ns);
try parts.append(arena, .{ .expr = expr });
i = end + 1;
continue;
}
if (c == '}') {
// Only the doubled form is legal here; a lone `}` would have been
// consumed as the end of an expression.
if (i + 1 < src.len and src[i + 1] == '}') {
try literal.append(arena, '}');
i += 2;
continue;
}
return error.UnexpectedCharacter;
}
try literal.append(arena, c);
i += 1;
}
if (literal.items.len != 0) {
try parts.append(arena, .{ .literal = try arena.dupe(u8, literal.items) });
}
return .{ .parts = try arena.dupe(Avt.Part, parts.items) };
}
/// The index of the `}` that closes an expression starting at `from`.
///
/// It cannot be the first `}`: the expression may contain a string literal,
/// and `{substring-before(., '}')}` is a perfectly ordinary thing to write.
fn findExpressionEnd(src: []const u8, from: usize) !usize {
var i = from;
var quote: ?u8 = null;
while (i < src.len) : (i += 1) {
const c = src[i];
if (quote) |q| {
if (c == q) quote = null;
continue;
}
switch (c) {
'\'', '"' => quote = c,
'}' => return i,
else => {},
}
}
return error.UnterminatedLiteral;
}
// -- reading a stylesheet ----------------------------------------------------
/// Somewhere for a failed parse to leave what went wrong.
///
/// A `Stylesheet` carries its own `diagnostic` and `code`, which is enough
/// for every failure *after* it was built. A failure during the parse is the
/// awkward one: the half-built stylesheet is destroyed on the way out and its
/// arena with it, so what it had to say goes too -- and static errors, the
/// XTSE family, are precisely the ones that happen then. A caller that wants
/// them hands over one of these.
pub const Diagnostic = struct {
/// Allocated with the allocator passed to `parse`; the caller frees it.
message: ?[]u8 = null,
/// The XSLT error code. Not owned: every code this library sets is a
/// string literal, because they are names out of the specification rather
/// than text anybody composes.
code: ?[]const u8 = null,
pub fn deinit(d: *Diagnostic, gpa: Allocator) void {
if (d.message) |m| gpa.free(m);
d.* = .{};
}
};
pub const ParseOptions = struct {
loader: Loader = .none,
base_uri: []const u8 = "",
/// Filled in if the parse fails. Null discards what went wrong, which is
/// what every caller that only wants the error wants.
diagnostic: ?*Diagnostic = null,
};
/// Parses a stylesheet from its text.
pub fn parse(gpa: Allocator, src: []const u8, options: ParseOptions) Error!*Stylesheet {
const s = try gpa.create(Stylesheet);
s.* = .{ .gpa = gpa, .arena = .init(gpa) };
// One cleanup path rather than two: `destroy` already frees every list and
// every document, so an error anywhere below unwinds through exactly the
// same code a successful caller eventually runs. What has to happen first
// is copying the diagnostic out, since it lives in the arena `destroy`
// is about to drop.
errdefer {
if (options.diagnostic) |d| {
d.* = .{
.message = if (s.diagnostic) |m| gpa.dupe(u8, m) catch null else null,
.code = s.code,
};
}
s.destroy();
}
var reader: Reader = .{ .s = s, .loader = options.loader };
try reader.readDocument(src, options.base_uri, 0);
// A rule declared later wins a tie, so they are numbered in the order they
// were read and compared by that number at the end.
for (s.rules.items, 0..) |*r, i| r.order = @intCast(i);
try buildRuleIndex(s);
return s;
}
const max_include_depth = 32;
/// Passed to `readDocument` to say "this is an `xsl:include`, share the
/// includer's precedence rather than taking a number".
const included_precedence: i32 = std.math.minInt(i32);
const Reader = struct {
s: *Stylesheet,
loader: Loader,
depth: u32 = 0,
/// The precedence an `xsl:include` should read its contents at.
included: i32 = 0,
/// Handed out in post-order, so that a number is only ever assigned once
/// everything the stylesheet imports already has one.
next_precedence: i32 = 0,
/// Reads a stylesheet and everything it imports.
///
/// Import precedence is a post-order numbering of the import tree, which
/// is what the specification's two rules amount to: a stylesheet outranks
/// everything it imports, and among the stylesheets one document imports,
/// a later one outranks an earlier one. Numbering the imports first and
/// the importer afterwards gives exactly that, with no arithmetic to get
/// backwards -- which the previous scheme, subtracting the import's
/// position from the importer's number, did: it made the *first* import
/// the strongest.
fn readDocument(r: *Reader, src: []const u8, base_uri: []const u8, precedence: i32) Error!void {
r.depth += 1;
defer r.depth -= 1;
if (r.depth > max_include_depth) {
r.s.setDiagnostic("stylesheet includes nested more than {d} deep", .{max_include_depth});
return error.InvalidStylesheet;
}
const kept = try r.s.arena.allocator().dupe(u8, src);
const doc = try runtime.parse(r.s.gpa, src, base_uri);
{
// Scoped so that it covers only the append. Once the document is
// in the list the stylesheet owns it, and letting this errdefer
// stay live would free it a second time on the way out.
errdefer doc.destroy();
try r.s.documents.append(r.s.gpa, doc);
}
try r.s.sources.append(r.s.gpa, kept);
stripStylesheetSpace(doc);
const root = doc.documentElement() orelse {
r.s.setDiagnostic("stylesheet has no document element", .{});
return error.InvalidStylesheet;
};
const root_name = doc.node(root).name;
// A literal result element as the document element is the simplified
// syntax: the whole document is the body of one template matching `/`.
if (!std.mem.eql(u8, root_name.uri, xslt_ns)) {
if (Stylesheet.statedVersion(doc, root) == null) {
r.s.setDiagnostic(
"document element <{s}> is neither xsl:stylesheet nor a literal result element with xsl:version",
.{root_name.local},
);
return error.InvalidStylesheet;
}
try r.addSimplifiedTemplate(doc, root, precedence);
return;
}
if (!std.mem.eql(u8, root_name.local, "stylesheet") and
!std.mem.eql(u8, root_name.local, "transform"))
{
r.s.setDiagnostic("document element is xsl:{s}, not xsl:stylesheet", .{root_name.local});
return error.InvalidStylesheet;
}
try r.readTopLevel(doc, root, precedence, base_uri);
}
/// The simplified syntax, where the stylesheet *is* the result: the
/// document element is a literal result element carrying `xsl:version`,
/// and it stands for a single template matching the root.
fn addSimplifiedTemplate(r: *Reader, doc: *Document, root: NodeId, precedence: i32) Error!void {
// `/` is a constant, so the only way this fails is running out of
// memory; the catch is here because the compiler's error set is wider
// than what a fixed pattern can actually raise.
const p = pattern.compile(r.s.arena.allocator(), "/", .none) catch return error.OutOfMemory;
try r.s.rules.append(r.s.gpa, .{
.doc = doc,
.alternative = p.alternatives[0],
.mode = null,
.priority = p.alternatives[0].priority,
// The body is the element itself rather than its children, since
// the element is part of the result.
.element = root,
.precedence = precedence,
.order = 0,
});
}
fn readTopLevel(
r: *Reader,
doc: *Document,
root: NodeId,
precedence: i32,
base_uri: []const u8,
) Error!void {
// Imports first, each numbered as it finishes, so that by the time
// this stylesheet takes its own number every one of them is below it
// and they are ordered among themselves as written.
for (doc.node(root).children.items) |child| {
const n = doc.node(child);
if (n.kind != .element) continue;
if (!std.mem.eql(u8, n.name.uri, xslt_ns)) continue;
if (!std.mem.eql(u8, n.name.local, "import")) continue;
try r.include(doc, child, base_uri, 0);
}
// An included stylesheet shares the includer's precedence, so it is
// read below with `own` rather than taking a number of its own.
const own = if (precedence == included_precedence) r.included else blk: {
const p = r.next_precedence;
r.next_precedence += 1;
break :blk p;
};
const saved_included = r.included;
r.included = own;
defer r.included = saved_included;
for (doc.node(root).children.items) |child| {
const n = doc.node(child);
if (n.kind != .element) continue;
if (!std.mem.eql(u8, n.name.uri, xslt_ns)) {
// EXSLT's functions module puts its declaration at the top
// level in its own namespace, so it is read here rather than
// through `readDeclaration`.
if (std.mem.eql(u8, n.name.uri, func_ns) and
std.mem.eql(u8, n.name.local, "function"))
{
try r.readFunction(doc, child, own);
continue;
}
// Any other top-level element in another namespace is data the
// stylesheet may read with `document('')`, and is ignored here
// rather than being an error.
continue;
}
try r.readDeclaration(doc, child, n.name.local, own, base_uri);
}
}
fn readDeclaration(
r: *Reader,
doc: *Document,
elem: NodeId,
local: []const u8,
precedence: i32,
base_uri: []const u8,
) Error!void {
const s = r.s;
const gpa = s.gpa;
// A table rather than a chain of comparisons, which is the shape the
// transformer's `instruction` already uses for the same job. Two
// reasons beyond neatness: the set of top-level declarations is about
// to grow by several, and an unrecognised name has to be
// distinguishable from a recognised one that did nothing -- which an
// if-chain falling off its end cannot do.
const Declaration = enum {
import,
include,
template,
variable,
param,
key,
@"attribute-set",
@"strip-space",
@"preserve-space",
output,
@"decimal-format",
@"namespace-alias",
/// Read where it is found rather than here: `xsl:fallback` is an
/// instruction and is only meaningful inside a template body, and
/// meeting one at the top level is not an error.
fallback,
};
const table = std.StaticStringMap(Declaration).initComptime(.{
.{ "import", .import },
.{ "include", .include },
.{ "template", .template },
.{ "variable", .variable },
.{ "param", .param },
.{ "key", .key },
.{ "attribute-set", .@"attribute-set" },
.{ "strip-space", .@"strip-space" },
.{ "preserve-space", .@"preserve-space" },
.{ "output", .output },
.{ "decimal-format", .@"decimal-format" },
.{ "namespace-alias", .@"namespace-alias" },
.{ "fallback", .fallback },
});
const which = table.get(local) orelse {
// XSLT 1.0 section 2.5 and 2.0 section 3.7: a top-level element in
// the XSLT namespace that the processor does not recognise is an
// error *unless* forwards-compatible behaviour is in force. The
// lenience here used to be unconditional, which made every
// misspelled declaration a silent no-op at `version="1.0"` -- so
// `` read as a stylesheet with no such
// variable rather than as a stylesheet with a typo.
const version = try s.effectiveVersion(doc, elem);
if (version.mode != .forwards) {
// XTSE0010 is the specification's catch-all for a stylesheet
// that is not one: an element where none is allowed.
s.setDiagnosticCode(
"XTSE0010",
"xsl:{s} is not a top-level declaration this processor knows," ++
" and version=\"{d}\" does not allow forwards-compatible behaviour",
.{ local, version.value },
);
return error.InvalidStylesheet;
}
return;
};
switch (which) {
// Already handled, and handled first.
.import => return,
.include => {
// Textual inclusion: the included stylesheet's declarations sit
// at the includer's precedence rather than below it.
r.included = precedence;
return r.include(doc, elem, base_uri, included_precedence);
},
.template => return r.readTemplate(doc, elem, precedence),
.variable, .param => {
const name = try r.requiredName(doc, elem, "name");
try s.globals.append(gpa, .{
.doc = doc,
.name = name,
.element = elem,
.is_param = which == .param,
.precedence = precedence,
});
},
.key => {
const name = try r.requiredName(doc, elem, "name");
const match_src = doc.attributeValue(elem, "", "match") orelse
return r.missing(doc, elem, "match");
const use_src = doc.attributeValue(elem, "", "use") orelse
return r.missing(doc, elem, "use");
try s.keys.append(gpa, .{
.doc = doc,
.name = name,
.match_src = match_src,
.use_src = use_src,
.element = elem,
});
},
.@"attribute-set" => {
const name = try r.requiredName(doc, elem, "name");
try s.attribute_sets.append(gpa, .{
.doc = doc,
.name = name,
.element = elem,
.precedence = precedence,
});
},
.@"strip-space", .@"preserve-space" => {
return r.readSpaceRules(doc, elem, which == .@"strip-space");
},
.output => return r.readOutput(doc, elem),
.@"decimal-format" => return r.readDecimalFormat(doc, elem),
.@"namespace-alias" => return r.readNamespaceAlias(doc, elem, precedence),
.fallback => return,
}
}
fn include(r: *Reader, doc: *Document, elem: NodeId, base_uri: []const u8, precedence: i32) Error!void {
const href = doc.attributeValue(elem, "", "href") orelse
return r.missing(doc, elem, "href");
const text = r.loader.load(r.s.gpa, base_uri, href) catch |err| {
r.s.setDiagnostic("cannot read {s}: {s}", .{ href, @errorName(err) });
return error.InvalidStylesheet;
};
defer r.s.gpa.free(text);
const resolved = try r.loader.resolve(r.s.gpa, base_uri, href);
defer r.s.gpa.free(resolved);
try r.readDocument(text, resolved, precedence);
}
fn readTemplate(r: *Reader, doc: *Document, elem: NodeId, precedence: i32) Error!void {
const s = r.s;
const gpa = s.gpa;
if (doc.attributeValue(elem, "", "name")) |_| {
const name = try r.requiredName(doc, elem, "name");
try s.named.append(gpa, .{
.doc = doc,
.name = name,
.element = elem,
.precedence = precedence,
});
}
const match_attr = findAttribute(doc, elem, "", "match") orelse return;
const p = try s.matchPattern(doc, match_attr);
const stated: ?f64 = if (doc.attributeValue(elem, "", "priority")) |text| blk: {
const parsed = std.fmt.parseFloat(f64, std.mem.trim(u8, text, " \t\n\r")) catch {
s.setDiagnostic("priority=\"{s}\" is not a number", .{text});
return error.InvalidStylesheet;
};
break :blk parsed;
} else null;
const mode: ?Name = if (doc.attributeValue(elem, "", "mode")) |_|
try r.requiredName(doc, elem, "mode")
else
null;
for (p.alternatives) |alt| {
try s.rules.append(gpa, .{
.doc = doc,
.alternative = alt,
.mode = mode,
// A stated priority applies to every alternative; only the
// default is per-alternative.
.priority = stated orelse alt.priority,
.element = elem,
.precedence = precedence,
.order = 0,
});
}
}
fn readSpaceRules(r: *Reader, doc: *Document, elem: NodeId, strip: bool) Error!void {
const text = doc.attributeValue(elem, "", "elements") orelse
return r.missing(doc, elem, "elements");
var it = std.mem.tokenizeAny(u8, text, " \t\n\r");
while (it.next()) |token| {
const local = xmlLocalName(token);
const prefix = xmlPrefix(token);
const is_wildcard = std.mem.eql(u8, local, "*");
// A null URI means "any namespace", and only `*` gets one. An
// unprefixed name means the *no-namespace* one, exactly as a name
// test in a pattern does -- the default declaration does not reach
// either. Treating it as "any namespace" makes
// `strip-space elements="child"` strip a `child` from every
// vocabulary in the document.
var uri: ?[]const u8 = if (is_wildcard) null else "";
if (prefix) |p| {
uri = doc.lookupNamespace(elem, p) orelse {
r.s.setDiagnostic("prefix {s}: is not declared on xsl:strip-space", .{p});
return error.InvalidStylesheet;
};
}
try r.s.space_rules.append(r.s.gpa, .{
.uri = uri,
.local = if (is_wildcard) null else local,
.strip = strip,
.priority = if (!is_wildcard) 0 else if (prefix != null) @as(f64, -0.25) else -0.5,
});
}
}
fn readOutput(r: *Reader, doc: *Document, elem: NodeId) Error!void {
const s = r.s;
const a = s.arena.allocator();
if (doc.attributeValue(elem, "", "method")) |m| {
s.output.method = if (std.mem.eql(u8, m, "xml"))
.xml
else if (std.mem.eql(u8, m, "html"))
.html
else if (std.mem.eql(u8, m, "text"))
.text
else
// A method with a prefix is an extension; anything else
// unrecognised falls back to XML rather than failing.
s.output.method;
}
if (doc.attributeValue(elem, "", "version")) |v| s.output.version = try a.dupe(u8, v);
if (doc.attributeValue(elem, "", "encoding")) |v| s.output.encoding = try a.dupe(u8, v);
if (doc.attributeValue(elem, "", "omit-xml-declaration")) |v| {
s.output.omit_xml_declaration = std.mem.eql(u8, v, "yes");
}
if (doc.attributeValue(elem, "", "standalone")) |v| {
s.output.standalone = std.mem.eql(u8, v, "yes");
}
if (doc.attributeValue(elem, "", "doctype-public")) |v| {
s.output.doctype_public = try a.dupe(u8, v);
}
if (doc.attributeValue(elem, "", "doctype-system")) |v| {
s.output.doctype_system = try a.dupe(u8, v);
}
if (doc.attributeValue(elem, "", "indent")) |v| {
s.output.indent = std.mem.eql(u8, v, "yes");
}
if (doc.attributeValue(elem, "", "cdata-section-elements")) |v| {
var names: std.ArrayList(Name) = .empty;
defer names.deinit(s.gpa);
try names.appendSlice(s.gpa, s.output.cdata_section_elements);
var it = std.mem.tokenizeAny(u8, v, " \t\n\r");
while (it.next()) |token| {
try names.append(s.gpa, try r.resolveQNameWithDefault(doc, elem, token));
}
s.output.cdata_section_elements = try a.dupe(Name, names.items);
}
}
/// `func:function`, EXSLT's function declaration.
///
/// The name is required to be in a namespace, which is the module's own
/// rule and a load-bearing one: a function in no namespace could shadow
/// something in the core library, and an expression could no longer be
/// read without knowing which stylesheet compiled it.
fn readFunction(r: *Reader, doc: *Document, elem: NodeId, precedence: i32) Error!void {
const name = try r.requiredName(doc, elem, "name");
if (name.uri.len == 0) {
r.s.setDiagnostic("func:function name {s} is in no namespace", .{name.local});
return error.InvalidStylesheet;
}
try r.s.functions.append(r.s.gpa, .{
.doc = doc,
.name = name,
.element = elem,
.precedence = precedence,
});
}
fn readDecimalFormat(r: *Reader, doc: *Document, elem: NodeId) Error!void {
var f: DecimalFormat = .{};
if (doc.attributeValue(elem, "", "name")) |_| {
f.name = try r.requiredName(doc, elem, "name");
}
const a = r.s.arena.allocator();
if (doc.attributeValue(elem, "", "decimal-separator")) |v| f.decimal_separator = firstCodepoint(v);
if (doc.attributeValue(elem, "", "grouping-separator")) |v| f.grouping_separator = firstCodepoint(v);
if (doc.attributeValue(elem, "", "infinity")) |v| f.infinity = try a.dupe(u8, v);
if (doc.attributeValue(elem, "", "minus-sign")) |v| f.minus_sign = firstCodepoint(v);
if (doc.attributeValue(elem, "", "NaN")) |v| f.nan = try a.dupe(u8, v);
if (doc.attributeValue(elem, "", "percent")) |v| f.percent = firstCodepoint(v);
if (doc.attributeValue(elem, "", "per-mille")) |v| f.per_mille = firstCodepoint(v);
if (doc.attributeValue(elem, "", "zero-digit")) |v| f.zero_digit = firstCodepoint(v);
if (doc.attributeValue(elem, "", "digit")) |v| f.digit = firstCodepoint(v);
if (doc.attributeValue(elem, "", "pattern-separator")) |v| f.pattern_separator = firstCodepoint(v);
try r.s.decimal_formats.append(r.s.gpa, f);
}
fn readNamespaceAlias(r: *Reader, doc: *Document, elem: NodeId, precedence: i32) Error!void {
const from = doc.attributeValue(elem, "", "stylesheet-prefix") orelse
return r.missing(doc, elem, "stylesheet-prefix");
const to = doc.attributeValue(elem, "", "result-prefix") orelse
return r.missing(doc, elem, "result-prefix");
// `#default` names the default declaration rather than a prefix.
const from_uri = if (std.mem.eql(u8, from, "#default"))
doc.lookupNamespace(elem, "") orelse ""
else
doc.lookupNamespace(elem, from) orelse {
r.s.setDiagnostic("stylesheet-prefix {s} is not declared", .{from});
return error.InvalidStylesheet;
};
const to_prefix = if (std.mem.eql(u8, to, "#default")) "" else to;
const to_uri = doc.lookupNamespace(elem, to_prefix) orelse "";
const a = r.s.arena.allocator();
try r.s.aliases.append(r.s.gpa, .{
.stylesheet_uri = try a.dupe(u8, from_uri),
.result_uri = try a.dupe(u8, to_uri),
.result_prefix = try a.dupe(u8, to_prefix),
.precedence = precedence,
});
}
// -- small helpers -------------------------------------------------------
fn requiredName(r: *Reader, doc: *Document, elem: NodeId, attr: []const u8) Error!Name {
const text = doc.attributeValue(elem, "", attr) orelse return r.missing(doc, elem, attr);
return r.resolveQName(doc, elem, std.mem.trim(u8, text, " \t\n\r"));
}
/// The same, except that an unprefixed name takes the default namespace
/// rather than no namespace.
///
/// This is what `cdata-section-elements` wants, and it is not what
/// `xsl:strip-space` wants: that attribute holds *NameTests*, which are
/// XPath's, and XPath never applies a default namespace to an unprefixed
/// name test. A list of QNames is a different thing, and libxslt resolves
/// one against every declaration in scope -- so a stylesheet whose result
/// elements are all in a default namespace can name them here without
/// inventing a prefix for the purpose.
fn resolveQNameWithDefault(r: *Reader, doc: *Document, elem: NodeId, text: []const u8) Error!Name {
if (xmlPrefix(text) == null) {
if (doc.lookupNamespace(elem, "")) |uri| {
const a = r.s.arena.allocator();
return .{
.uri = try a.dupe(u8, uri),
.local = try a.dupe(u8, xmlLocalName(text)),
};
}
}
return r.resolveQName(doc, elem, text);
}
/// Expands a QName written in an attribute *value*, whose prefix resolves
/// against the element it is written on just as one in an expression does.
fn resolveQName(r: *Reader, doc: *Document, elem: NodeId, text: []const u8) Error!Name {
const a = r.s.arena.allocator();
const local = xmlLocalName(text);
const prefix = xmlPrefix(text) orelse return .{
.uri = "",
.local = try a.dupe(u8, local),
};
const uri = doc.lookupNamespace(elem, prefix) orelse {
r.s.setDiagnostic("prefix {s}: is not declared here", .{prefix});
return error.InvalidStylesheet;
};
return .{
.uri = try a.dupe(u8, uri),
.local = try a.dupe(u8, local),
.prefix = try a.dupe(u8, prefix),
};
}
fn missing(r: *Reader, doc: *Document, elem: NodeId, attr: []const u8) Error {
// XTSE0010 names exactly this: "a required attribute is omitted" is
// one of the three things it covers, alongside an element used where
// it is not permitted and content that is not allowed.
r.s.setDiagnosticCode(
"XTSE0010",
"xsl:{s} needs a {s} attribute",
.{ doc.node(elem).name.local, attr },
);
return error.InvalidStylesheet;
}
};
pub fn findAttribute(doc: *const Document, elem: NodeId, uri: []const u8, local: []const u8) ?NodeId {
for (doc.node(elem).attributes.items) |a| {
if (doc.node(a).name.is(uri, local)) return a;
}
return null;
}
fn xmlLocalName(qname: []const u8) []const u8 {
if (std.mem.findScalar(u8, qname, ':')) |i| return qname[i + 1 ..];
return qname;
}
fn xmlPrefix(qname: []const u8) ?[]const u8 {
const i = std.mem.findScalar(u8, qname, ':') orelse return null;
return qname[0..i];
}
fn firstCodepoint(s: []const u8) u21 {
if (s.len == 0) return 0;
const len = std.unicode.utf8ByteSequenceLength(s[0]) catch return s[0];
if (len > s.len) return s[0];
return std.unicode.utf8Decode(s[0..len]) catch s[0];
}
/// Removes whitespace-only text nodes from a stylesheet.
///
/// Everywhere except inside `xsl:text`, whose whole purpose is to hold
/// whitespace that would otherwise be stripped, and inside anything carrying
/// `xml:space="preserve"`.
fn stripStylesheetSpace(doc: *Document) void {
stripUnder(doc, doc.root, false);
}
fn stripUnder(doc: *Document, elem: NodeId, preserving: bool) void {
var preserve = preserving;
if (doc.node(elem).kind == .element) {
const name = doc.node(elem).name;
if (std.mem.eql(u8, name.uri, xslt_ns) and std.mem.eql(u8, name.local, "text")) {
// `xsl:text` is literal all the way down, and has only text in it.
return;
}
if (doc.attributeValue(elem, tree.xml_ns, "space")) |v| {
preserve = std.mem.eql(u8, v, "preserve");
}
}
// Backwards, so that removing one child does not renumber the ones still
// to be looked at.
var i = doc.node(elem).children.items.len;
while (i > 0) {
i -= 1;
const child = doc.node(elem).children.items[i];
switch (doc.node(child).kind) {
.text => {
if (!preserve and isAllWhitespace(doc.node(child).value)) {
doc.removeChild(elem, child);
}
},
.element => stripUnder(doc, child, preserve),
else => {},
}
}
}
fn isAllWhitespace(s: []const u8) bool {
for (s) |c| {
if (c != ' ' and c != '\t' and c != '\n' and c != '\r') return false;
}
return true;
}
// -- tests -------------------------------------------------------------------
const testing = std.testing;
fn parseSource(src: []const u8) Error!*Stylesheet {
return parse(testing.allocator, src, .{});
}
test "reads templates and gives each alternative its own rule" {
const s = try parseSource(
\\
\\
\\
\\
\\
);
defer s.destroy();
try testing.expectEqual(@as(usize, 3), s.rules.items.len);
try testing.expectEqual(@as(f64, 0), s.rules.items[0].priority);
try testing.expectEqual(@as(f64, 3), s.rules.items[2].priority);
try testing.expectEqual(@as(usize, 1), s.named.items.len);
try testing.expectEqualStrings("named", s.named.items[0].name.local);
}
test "reads output settings" {
const s = try parseSource(
\\
\\
\\
);
defer s.destroy();
try testing.expectEqual(serialize.Method.html, s.output.method.?);
try testing.expect(s.output.indent.?);
try testing.expectEqualStrings("iso-8859-1", s.output.encoding.?);
try testing.expectEqualStrings("about:legacy-compat", s.output.doctype_system.?);
}
test "whitespace is stripped from the stylesheet but not from xsl:text" {
const s = try parseSource(
\\
\\
\\
\\
\\
\\
\\
);
defer s.destroy();
const doc = s.documents.items[0];
const template = s.rules.items[0].element;
// The indentation between the tags is gone, so the template has exactly
// one child.
try testing.expectEqual(@as(usize, 1), doc.node(template).children.items.len);
const out = doc.node(template).children.items[0];
const text_instruction = doc.node(out).children.items[0];
const kept = doc.node(text_instruction).children.items[0];
try testing.expectEqualStrings(" ", doc.node(kept).value);
}
test "attribute value templates split on braces" {
const gpa = testing.allocator;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
const a = arena.allocator();
{
const avt = try parseAvt(a, "plain", .none);
try testing.expectEqualStrings("plain", avt.constant().?);
}
{
const avt = try parseAvt(a, "a{1}b", .none);
try testing.expectEqual(@as(usize, 3), avt.parts.len);
try testing.expectEqualStrings("a", avt.parts[0].literal);
try testing.expect(avt.parts[1] == .expr);
try testing.expectEqualStrings("b", avt.parts[2].literal);
}
{
// Doubled braces are literal.
const avt = try parseAvt(a, "{{not an expression}}", .none);
try testing.expectEqualStrings("{not an expression}", avt.constant().?);
}
{
// A `}` inside a string literal does not end the expression.
const avt = try parseAvt(a, "{substring-before(., '}')}", .none);
try testing.expectEqual(@as(usize, 1), avt.parts.len);
try testing.expect(avt.parts[0] == .expr);
}
}
test "a stylesheet that is not one is refused with a diagnostic" {
const gpa = testing.allocator;
try testing.expectError(error.InvalidStylesheet, parse(gpa, "", .{}));
try testing.expectError(
error.InvalidStylesheet,
parse(gpa,
\\
\\
\\
, .{}),
);
}
test "a later import outranks an earlier one" {
// The specification's rule, and the one easiest to implement backwards: of
// the stylesheets a document imports, the last one written wins. The
// importer outranks all of them.
const gpa = testing.allocator;
const Modules = struct {
fn loadFn(_: ?*anyopaque, a: Allocator, _: []const u8, href: []const u8) Error![]u8 {
const body =
\\
\\
\\
;
_ = href;
return a.dupe(u8, body);
}
fn resolveFn(_: ?*anyopaque, a: Allocator, _: []const u8, href: []const u8) Error![]u8 {
return a.dupe(u8, href);
}
};
const sheet = try parse(gpa,
\\
\\
\\
\\
\\
, .{ .loader = .{ .loadFn = Modules.loadFn, .resolveFn = Modules.resolveFn } });
defer sheet.destroy();
// Three rules for `a`: one per import and the importing stylesheet's.
try testing.expectEqual(@as(usize, 3), sheet.rules.items.len);
// They were read first, second, importer -- so their precedences must
// increase in that order.
const first = sheet.rules.items[0].precedence;
const second = sheet.rules.items[1].precedence;
const importer = sheet.rules.items[2].precedence;
try testing.expect(first < second);
try testing.expect(second < importer);
}
test "the simplified syntax is one template matching the root" {
const s = try parseSource(
\\
\\
\\
);
defer s.destroy();
try testing.expectEqual(@as(usize, 1), s.rules.items.len);
try testing.expect(s.rules.items[0].alternative.absolute);
}
/// Files every rule under what its pattern could match, and sorts each bucket
/// best-first so that a lookup can stop at its first match.
fn buildRuleIndex(s: *Stylesheet) Error!void {
const gpa = s.gpa;
for (s.rules.items, 0..) |rule, i| {
const at: u32 = @intCast(i);
const list = switch (selectorOf(rule.alternative)) {
.element_named => |local| blk: {
const found = try s.rule_index.by_element.getOrPut(gpa, local);
if (!found.found_existing) found.value_ptr.* = .empty;
break :blk found.value_ptr;
},
.attribute_named => |local| blk: {
const found = try s.rule_index.by_attribute.getOrPut(gpa, local);
if (!found.found_existing) found.value_ptr.* = .empty;
break :blk found.value_ptr;
},
.element_any => &s.rule_index.element_any,
.attribute_any => &s.rule_index.attribute_any,
.text => &s.rule_index.text,
.comment => &s.rule_index.comment,
.pi => &s.rule_index.pi,
.root => &s.rule_index.root,
.any_child => &s.rule_index.any_child,
.unclassified => &s.rule_index.unclassified,
};
try list.append(gpa, at);
}
const Sorter = struct {
rules: []const Rule,
fn lessThan(ctx: @This(), a: u32, b: u32) bool {
return outranks(ctx.rules[a], ctx.rules[b]);
}
};
const sorter: Sorter = .{ .rules = s.rules.items };
var elements = s.rule_index.by_element.valueIterator();
while (elements.next()) |list| std.mem.sort(u32, list.items, sorter, Sorter.lessThan);
var attributes = s.rule_index.by_attribute.valueIterator();
while (attributes.next()) |list| std.mem.sort(u32, list.items, sorter, Sorter.lessThan);
for ([_]*std.ArrayList(u32){
&s.rule_index.element_any,
&s.rule_index.attribute_any,
&s.rule_index.text,
&s.rule_index.comment,
&s.rule_index.pi,
&s.rule_index.root,
&s.rule_index.any_child,
&s.rule_index.unclassified,
}) |list| std.mem.sort(u32, list.items, sorter, Sorter.lessThan);
}
test "the effective version comes from the nearest element that states one" {
const gpa = testing.allocator;
// Every placement that matters, in one stylesheet: the root, a literal
// result element in the middle of a body overriding it, and an
// `xsl:output` whose `version` is a serialization parameter and must not
// count at all.
const sheet = try parse(gpa,
\\
\\
\\
\\
\\
\\
\\
, .{});
defer sheet.destroy();
const doc = sheet.documents.items[0];
const root = doc.documentElement().?;
// The root itself.
try testing.expectEqual(@as(f64, 1.0), (try sheet.effectiveVersion(doc, root)).value);
try testing.expectEqual(Stylesheet.Version.Mode.current, (try sheet.effectiveVersion(doc, root)).mode);
// Walk to the elements that matter rather than guessing node ids.
var output: ?NodeId = null;
var template: ?NodeId = null;
for (doc.node(root).children.items) |id| {
if (doc.node(id).kind != .element) continue;
if (std.mem.eql(u8, doc.node(id).name.local, "output")) output = id;
if (std.mem.eql(u8, doc.node(id).name.local, "template")) template = id;
}
// `xsl:output version="4.0"` is the XML declaration's version. Reading it
// as the stylesheet's would put everything below it into
// forwards-compatible mode, silently.
try testing.expectEqual(@as(f64, 1.0), (try sheet.effectiveVersion(doc, output.?)).value);
var plain: ?NodeId = null;
var newer: ?NodeId = null;
for (doc.node(template.?).children.items) |id| {
if (doc.node(id).kind != .element) continue;
if (std.mem.eql(u8, doc.node(id).name.local, "plain")) plain = id;
if (std.mem.eql(u8, doc.node(id).name.local, "newer")) newer = id;
}
try testing.expectEqual(@as(f64, 1.0), (try sheet.effectiveVersion(doc, plain.?)).value);
// `xsl:version` on a literal result element, and inherited by its child.
try testing.expectEqual(@as(f64, 9.0), (try sheet.effectiveVersion(doc, newer.?)).value);
try testing.expectEqual(Stylesheet.Version.Mode.forwards, (try sheet.effectiveVersion(doc, newer.?)).mode);
const inner = for (doc.node(newer.?).children.items) |id| {
if (doc.node(id).kind == .element) break id;
} else unreachable;
try testing.expectEqual(@as(f64, 9.0), (try sheet.effectiveVersion(doc, inner)).value);
}
test "a version that is not a number is refused rather than guessed at" {
const gpa = testing.allocator;
try testing.expectError(error.InvalidStylesheet, parse(gpa,
\\
\\
\\
, .{}));
}
test "an unknown top-level declaration is an error unless the stylesheet is newer" {
const gpa = testing.allocator;
// At the version this processor implements, an `xsl:` element it does not
// know is a mistake -- most often a typo -- and XSLT 1.0 section 2.5 says
// so. This used to pass silently, which made `` a
// stylesheet with no such variable rather than a stylesheet with a typo.
{
const sheet = parse(gpa,
\\
\\
\\
\\
, .{});
try testing.expectError(error.InvalidStylesheet, sheet);
}
// A stylesheet written for a later version than this one is in
// forwards-compatible mode, and there the same element is ignored -- which
// is how `xsl:function` in a `version="2.0"` stylesheet degrades to its
// `xsl:otherwise` branch on a 1.0 processor.
{
const sheet = try parse(gpa,
\\
\\
\\
\\
, .{});
defer sheet.destroy();
try testing.expectEqual(@as(usize, 1), sheet.rules.items.len);
}
}