Something went wrong. Try again.
XPath 1.0 for Zig 0.16, over a ztree document.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! XPath 1.0: the lexer, the abstract syntax tree, and the parser that turns//! one into the other. Evaluating the result is `eval.zig`.//!//! Two things about XPath make it more awkward to parse than its size//! suggests.//!//! The first is that its lexer cannot be written without knowing what came//! before. `*` is a multiplication operator in `3 * 4` and a name test in//! `a/*`; `div` is an operator in `6 div 2` and an element name in//! `child::div`. The specification resolves this with a rule about the//! preceding token rather than with a grammar, so `Lexer` carries exactly that//! one bit of state -- whether an operator may appear next -- and that is what//! `operator_may_follow` is.//!//! The second is that prefixes in an expression mean whatever the *stylesheet*//! said they meant at the place the expression was written, not whatever the//! source document says. `//x:a` in a stylesheet that binds `x` to one URI is//! a different expression from the same text in a stylesheet that binds it to//! another, and neither has anything to do with the prefixes in the document//! being transformed. So prefixes are resolved here, while compiling, against//! a resolver the caller supplies, and the tree that comes out holds expanded//! names that need no further context.
const std = @import("std");const Allocator = std.mem.Allocator;const tree = @import("ztree");const Name = tree.Name;
pub const CompileError = error{ UnexpectedCharacter, UnexpectedToken, UnterminatedLiteral, InvalidNumber, UnknownAxis, /// A prefix in the expression is not declared where the expression was /// written. XSLT makes this a static error, not an empty node-set. UnboundPrefix, InvalidNodeTest, TrailingInput, /// Nesting deep enough to be an attack rather than an expression. ExpressionTooDeep,} || Allocator.Error;
/// How deep a parse may nest before it is refused. A hand-written expression/// does not come close; a generated or hostile one would otherwise recurse/// until the stack ran out, which is a crash rather than an error.pub const max_depth = 128;
/// Resolves a namespace prefix to a URI in the static context the expression/// was written in.////// An interface rather than a map because the two callers want different/// things behind it: the XSLT engine resolves against the stylesheet element/// the expression came from, walking its ancestors, while a standalone call/// wants a literal table.pub const NsResolver = struct { ctx: ?*const anyopaque = null, lookupFn: *const fn (ctx: ?*const anyopaque, prefix: []const u8) ?[]const u8,
pub fn lookup(r: NsResolver, prefix: []const u8) ?[]const u8 { return r.lookupFn(r.ctx, prefix); }
fn noneLookup(_: ?*const anyopaque, _: []const u8) ?[]const u8 { return null; }
/// A resolver that binds nothing, so any prefix is an error. pub const none: NsResolver = .{ .lookupFn = noneLookup };};
// -- syntax tree -------------------------------------------------------------
pub const Axis = enum { ancestor, ancestor_or_self, attribute, child, descendant, descendant_or_self, following, following_sibling, namespace, parent, preceding, preceding_sibling, self,
/// The node kind an unqualified name test on this axis matches. It is the /// reason `@*` finds attributes while `*` finds elements, with no /// difference in the node test itself. pub fn principalKind(a: Axis) tree.Kind { return switch (a) { .attribute => .attribute, .namespace => .namespace, else => .element, }; }
/// True for the axes that run backwards through the document, whose /// proximity positions are counted from the context node rather than /// towards the end of the document. pub fn isReverse(a: Axis) bool { return switch (a) { .ancestor, .ancestor_or_self, .preceding, .preceding_sibling => true, else => false, }; }
pub fn fromName(s: []const u8) ?Axis { const table = std.StaticStringMap(Axis).initComptime(.{ .{ "ancestor", .ancestor }, .{ "ancestor-or-self", .ancestor_or_self }, .{ "attribute", .attribute }, .{ "child", .child }, .{ "descendant", .descendant }, .{ "descendant-or-self", .descendant_or_self }, .{ "following", .following }, .{ "following-sibling", .following_sibling }, .{ "namespace", .namespace }, .{ "parent", .parent }, .{ "preceding", .preceding }, .{ "preceding-sibling", .preceding_sibling }, .{ "self", .self }, }); return table.get(s); }};
pub const NodeTest = union(enum) { /// A name test. A null `local` is `*`; a null `uri` on a `*` test means /// no namespace was named, so it matches any. name: struct { uri: ?[]const u8, local: ?[]const u8, }, /// `node()` -- every kind. any, text, comment, /// `processing-instruction()`, or with a literal, only that target. pi: ?[]const u8,};
pub const Step = struct { axis: Axis, node_test: NodeTest, predicates: []const *const Expr = &.{},};
pub const BinOp = enum { or_, and_, eq, ne, lt, le, gt, ge, add, sub, mul, div, mod, /// `|`. Not really arithmetic, but it binds like an operator and both /// sides must be node-sets. union_,};
pub const Expr = union(enum) { number: f64, literal: []const u8, /// `$name`, with its prefix already resolved. variable: Name, binary: struct { op: BinOp, lhs: *const Expr, rhs: *const Expr }, negate: *const Expr, /// A function call, with the name expanded. An unprefixed name is in no /// namespace and refers to the core library. call: struct { name: Name, args: []const *const Expr }, /// A location path, optionally rooted at `/` or at another expression -- /// `key('k', 'v')/foo` and `(a|b)[1]` both arrive here. path: struct { /// True for a path starting at the root of the context node's tree. absolute: bool, /// The expression the path starts from, for the `FilterExpr '/' ...` /// form. Mutually exclusive with `absolute`. start: ?*const Expr = null, steps: []const Step, }, /// A primary expression with predicates: `$x[1]`, `foo()[@a]`. filter: struct { base: *const Expr, predicates: []const *const Expr },};
// -- lexer -------------------------------------------------------------------
const Token = union(enum) { lparen, rparen, lbracket, rbracket, at, comma, colon_colon, dot, dot_dot, slash, slash_slash, pipe, plus, minus, eq, ne, lt, le, gt, ge, star, dollar, /// An operator keyword, recognised as one only where an operator may /// appear. op_and, op_or, op_div, op_mod, /// A name, possibly prefixed. `local` is null for `prefix:*`. name: struct { prefix: ?[]const u8, local: ?[]const u8 }, literal: []const u8, number: f64, eof,
/// Whether an operator may follow this token, which is the whole of /// XPath's lexical disambiguation. After a name, a number, a literal, `)`, /// `]`, `*` or `.`/`..` the expression so far is complete, so what comes /// next is an operator; everywhere else a `*` is a name test and `div` is /// a name. fn allowsOperatorAfter(t: Token) bool { return switch (t) { .name, .literal, .number, .rparen, .rbracket, .star, .dot, .dot_dot => true, else => false, }; }};
const Lexer = struct { src: []const u8, pos: usize = 0, /// Set from the previous token. When false, `*` is a name test and `div`, /// `mod`, `and` and `or` are names rather than operators. operator_may_follow: bool = false,
fn isNameStart(c: u8) bool { return std.ascii.isAlphabetic(c) or c == '_' or c >= 0x80; }
fn isNameChar(c: u8) bool { return std.ascii.isAlphanumeric(c) or c == '_' or c == '-' or c == '.' or c >= 0x80; }
fn skipSpace(l: *Lexer) void { while (l.pos < l.src.len and std.ascii.isWhitespace(l.src[l.pos])) l.pos += 1; }
fn peekByte(l: *Lexer, ahead: usize) ?u8 { const i = l.pos + ahead; return if (i < l.src.len) l.src[i] else null; }
/// The next character that is not whitespace, without consuming anything. /// Needed because whether an NCName is a function name or an axis depends /// on what follows it, and XPath permits whitespace in between. fn peekNonSpace(l: *Lexer, from: usize) ?u8 { var i = from; while (i < l.src.len and std.ascii.isWhitespace(l.src[i])) i += 1; return if (i < l.src.len) l.src[i] else null; }
fn nonSpaceIndex(l: *Lexer, from: usize) usize { var i = from; while (i < l.src.len and std.ascii.isWhitespace(l.src[i])) i += 1; return i; }
fn next(l: *Lexer) CompileError!Token { const t = try l.scan(); l.operator_may_follow = t.allowsOperatorAfter(); return t; }
fn scan(l: *Lexer) CompileError!Token { l.skipSpace(); if (l.pos >= l.src.len) return .eof; const c = l.src[l.pos]; switch (c) { '(' => { l.pos += 1; return .lparen; }, ')' => { l.pos += 1; return .rparen; }, '[' => { l.pos += 1; return .lbracket; }, ']' => { l.pos += 1; return .rbracket; }, '@' => { l.pos += 1; return .at; }, ',' => { l.pos += 1; return .comma; }, '|' => { l.pos += 1; return .pipe; }, '+' => { l.pos += 1; return .plus; }, '-' => { l.pos += 1; return .minus; }, '=' => { l.pos += 1; return .eq; }, '$' => { l.pos += 1; return .dollar; }, '*' => { l.pos += 1; return .star; }, '!' => { if (l.peekByte(1) != '=') return error.UnexpectedCharacter; l.pos += 2; return .ne; }, '<' => { if (l.peekByte(1) == '=') { l.pos += 2; return .le; } l.pos += 1; return .lt; }, '>' => { if (l.peekByte(1) == '=') { l.pos += 2; return .ge; } l.pos += 1; return .gt; }, '/' => { if (l.peekByte(1) == '/') { l.pos += 2; return .slash_slash; } l.pos += 1; return .slash; }, ':' => { if (l.peekByte(1) != ':') return error.UnexpectedCharacter; l.pos += 2; return .colon_colon; }, '.' => { if (l.peekByte(1)) |n| { if (std.ascii.isDigit(n)) return l.scanNumber(); if (n == '.') { l.pos += 2; return .dot_dot; } } l.pos += 1; return .dot; }, '\'', '"' => return l.scanLiteral(c), else => { if (std.ascii.isDigit(c)) return l.scanNumber(); if (isNameStart(c)) return l.scanName(); return error.UnexpectedCharacter; }, } }
fn scanLiteral(l: *Lexer, quote: u8) CompileError!Token { l.pos += 1; const start = l.pos; // XPath string literals have no escapes at all: the other quote // character is how you write a quote. while (l.pos < l.src.len and l.src[l.pos] != quote) l.pos += 1; if (l.pos >= l.src.len) return error.UnterminatedLiteral; const text = l.src[start..l.pos]; l.pos += 1; return .{ .literal = text }; }
fn scanNumber(l: *Lexer) CompileError!Token { const start = l.pos; while (l.pos < l.src.len and std.ascii.isDigit(l.src[l.pos])) l.pos += 1; if (l.pos < l.src.len and l.src[l.pos] == '.') { l.pos += 1; while (l.pos < l.src.len and std.ascii.isDigit(l.src[l.pos])) l.pos += 1; } const text = l.src[start..l.pos]; // XPath 1.0 numbers have no exponent and no sign, so anything Zig // would accept beyond that cannot appear in `text`. const value = std.fmt.parseFloat(f64, text) catch return error.InvalidNumber; return .{ .number = value }; }
fn scanNcName(l: *Lexer) []const u8 { const start = l.pos; while (l.pos < l.src.len and isNameChar(l.src[l.pos])) l.pos += 1; return l.src[start..l.pos]; }
fn scanName(l: *Lexer) CompileError!Token { const first = l.scanNcName();
// An operator keyword is only an operator where one may appear. In // `child::div` and `a[mod]` these are element names. if (l.operator_may_follow) { if (std.mem.eql(u8, first, "and")) return .op_and; if (std.mem.eql(u8, first, "or")) return .op_or; if (std.mem.eql(u8, first, "div")) return .op_div; if (std.mem.eql(u8, first, "mod")) return .op_mod; }
// A `:` that is not `::` makes this a QName. `p:*` is the wildcard // form, which only a name test may use. if (l.pos < l.src.len and l.src[l.pos] == ':' and l.peekByte(1) != ':') { l.pos += 1; if (l.pos < l.src.len and l.src[l.pos] == '*') { l.pos += 1; return .{ .name = .{ .prefix = first, .local = null } }; } if (l.pos >= l.src.len or !isNameStart(l.src[l.pos])) return error.UnexpectedCharacter; const local = l.scanNcName(); return .{ .name = .{ .prefix = first, .local = local } }; }
return .{ .name = .{ .prefix = null, .local = first } }; }
/// True when the next thing after the current position is `(`, which is /// what distinguishes a function call or node type from a name test. fn followedByLparen(l: *Lexer) bool { return l.peekNonSpace(l.pos) == '('; }
/// True when the next thing after the current position is `::`. fn followedByAxis(l: *Lexer) bool { const i = l.nonSpaceIndex(l.pos); return i + 1 < l.src.len and l.src[i] == ':' and l.src[i + 1] == ':'; }};
// -- parser ------------------------------------------------------------------
/// Compiles an expression, allocating the tree from `arena`.////// Everything the returned tree points at -- names, string literals, argument/// lists -- is allocated from `arena`, so `src` may be freed once this/// returns and the whole tree is discarded by resetting the arena. There is/// nothing to free individually and no destructor to call.pub fn compile(arena: Allocator, src: []const u8, ns: NsResolver) CompileError!*const Expr { var p: Parser = .{ .arena = arena, .lexer = .{ .src = src }, .ns = ns }; try p.advance(); const e = try p.parseExpr(); if (p.token != .eof) return error.TrailingInput; return e;}
/// A compiled expression that owns its own storage, for a caller that has no/// arena of its own to lend. The XSLT engine does not use this: a stylesheet/// compiles hundreds of expressions into one arena.pub const Compiled = struct { arena: std.heap.ArenaAllocator, expr: *const Expr,
pub fn init(gpa: Allocator, src: []const u8, ns: NsResolver) CompileError!Compiled { var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const expr = try compile(arena.allocator(), src, ns); return .{ .arena = arena, .expr = expr }; }
pub fn deinit(c: *Compiled) void { c.arena.deinit(); }};
const Parser = struct { arena: Allocator, lexer: Lexer, ns: NsResolver, token: Token = .eof, depth: u32 = 0,
fn advance(p: *Parser) CompileError!void { p.token = try p.lexer.next(); }
fn eat(p: *Parser, comptime tag: std.meta.Tag(Token)) CompileError!bool { if (p.token != tag) return false; try p.advance(); return true; }
fn expect(p: *Parser, comptime tag: std.meta.Tag(Token)) CompileError!void { if (p.token != tag) return error.UnexpectedToken; try p.advance(); }
fn create(p: *Parser, e: Expr) CompileError!*const Expr { const out = try p.arena.create(Expr); out.* = e; return out; }
fn binary(p: *Parser, op: BinOp, lhs: *const Expr, rhs: *const Expr) CompileError!*const Expr { return p.create(.{ .binary = .{ .op = op, .lhs = lhs, .rhs = rhs } }); }
fn enter(p: *Parser) CompileError!void { p.depth += 1; if (p.depth > max_depth) return error.ExpressionTooDeep; }
fn leave(p: *Parser) void { p.depth -= 1; }
// Each level of the precedence ladder is its own function, in the order // the grammar gives them: or, and, equality, relational, additive, // multiplicative, unary, union, path.
fn parseExpr(p: *Parser) CompileError!*const Expr { try p.enter(); defer p.leave(); var lhs = try p.parseAnd(); while (p.token == .op_or) { try p.advance(); lhs = try p.binary(.or_, lhs, try p.parseAnd()); } return lhs; }
fn parseAnd(p: *Parser) CompileError!*const Expr { var lhs = try p.parseEquality(); while (p.token == .op_and) { try p.advance(); lhs = try p.binary(.and_, lhs, try p.parseEquality()); } return lhs; }
fn parseEquality(p: *Parser) CompileError!*const Expr { var lhs = try p.parseRelational(); while (true) { const op: BinOp = switch (p.token) { .eq => .eq, .ne => .ne, else => return lhs, }; try p.advance(); lhs = try p.binary(op, lhs, try p.parseRelational()); } }
fn parseRelational(p: *Parser) CompileError!*const Expr { var lhs = try p.parseAdditive(); while (true) { const op: BinOp = switch (p.token) { .lt => .lt, .le => .le, .gt => .gt, .ge => .ge, else => return lhs, }; try p.advance(); lhs = try p.binary(op, lhs, try p.parseAdditive()); } }
fn parseAdditive(p: *Parser) CompileError!*const Expr { var lhs = try p.parseMultiplicative(); while (true) { const op: BinOp = switch (p.token) { .plus => .add, .minus => .sub, else => return lhs, }; try p.advance(); lhs = try p.binary(op, lhs, try p.parseMultiplicative()); } }
fn parseMultiplicative(p: *Parser) CompileError!*const Expr { var lhs = try p.parseUnary(); while (true) { const op: BinOp = switch (p.token) { .star => .mul, .op_div => .div, .op_mod => .mod, else => return lhs, }; try p.advance(); lhs = try p.binary(op, lhs, try p.parseUnary()); } }
fn parseUnary(p: *Parser) CompileError!*const Expr { try p.enter(); defer p.leave(); if (try p.eat(.minus)) { return p.create(.{ .negate = try p.parseUnary() }); } return p.parseUnion(); }
fn parseUnion(p: *Parser) CompileError!*const Expr { var lhs = try p.parsePath(); while (try p.eat(.pipe)) { lhs = try p.binary(.union_, lhs, try p.parsePath()); } return lhs; }
/// A path, which is either a location path or a primary expression that /// may be followed by one. fn parsePath(p: *Parser) CompileError!*const Expr { try p.enter(); defer p.leave();
switch (p.token) { .slash, .slash_slash => return p.parseAbsolutePath(), // A token that can only begin a step starts a relative location // path; anything else is a primary expression. .at, .dot, .dot_dot, .star => return p.parseRelativePath(null, false, false), .name => |n| { // `foo(` is a call unless `foo` is a node type, and `foo::` is // an axis. Everything else beginning with a name is a step. // // A *prefixed* name followed by `(` is always a call: node // types have no prefix, so `exsl:node-set(...)` cannot be // anything else. Missing that is what makes every extension // function look like a syntax error. if (n.local != null and p.lexer.followedByLparen() and (n.prefix != null or nodeTypeOf(n.local.?) == null)) { // A function call, which may itself be the start of a path. return p.parseFilterThenPath(); } return p.parseRelativePath(null, false, false); }, .dollar, .lparen, .literal, .number => return p.parseFilterThenPath(), else => return error.UnexpectedToken, } }
/// A primary expression with its predicates, then optionally `/steps`. fn parseFilterThenPath(p: *Parser) CompileError!*const Expr { const base = try p.parseFilter(); switch (p.token) { .slash, .slash_slash => return p.parseRelativePath(base, false, false), else => return base, } }
fn parseFilter(p: *Parser) CompileError!*const Expr { const primary = try p.parsePrimary(); if (p.token != .lbracket) return primary; const predicates = try p.parsePredicates(); return p.create(.{ .filter = .{ .base = primary, .predicates = predicates } }); }
fn parsePrimary(p: *Parser) CompileError!*const Expr { try p.enter(); defer p.leave(); switch (p.token) { .number => |v| { try p.advance(); return p.create(.{ .number = v }); }, .literal => |s| { try p.advance(); return p.create(.{ .literal = try p.arena.dupe(u8, s) }); }, .dollar => { try p.advance(); const n = switch (p.token) { .name => |n| n, else => return error.UnexpectedToken, }; const local = n.local orelse return error.UnexpectedToken; const name = try p.expandName(n.prefix, local); try p.advance(); return p.create(.{ .variable = name }); }, .lparen => { try p.advance(); const inner = try p.parseExpr(); try p.expect(.rparen); return inner; }, .name => |n| { const local = n.local orelse return error.UnexpectedToken; // An unprefixed function name is in no namespace, which is // what the core library lives in. const name = if (n.prefix) |pfx| try p.expandName(pfx, local) else Name{ .uri = "", .local = try p.arena.dupe(u8, local) }; try p.advance(); try p.expect(.lparen); var args: std.ArrayList(*const Expr) = .empty; defer args.deinit(p.arena); if (p.token != .rparen) { while (true) { try args.append(p.arena, try p.parseExpr()); if (!try p.eat(.comma)) break; } } try p.expect(.rparen); return p.create(.{ .call = .{ .name = name, .args = try p.arena.dupe(*const Expr, args.items), } }); }, else => return error.UnexpectedToken, } }
fn parseAbsolutePath(p: *Parser) CompileError!*const Expr { if (try p.eat(.slash_slash)) { // `//x` abbreviates `/descendant-or-self::node()/x`. return p.parseRelativePath(null, true, true); } try p.expect(.slash); // A lone `/` is the root itself. It is the one case where a path has // no steps at all, and it is why `absolute` is a flag rather than an // implied first step. if (!p.startsStep()) { return p.create(.{ .path = .{ .absolute = true, .steps = &.{} } }); } return p.parseRelativePath(null, false, true); }
/// True when the current token could begin a step, which is how `/` alone /// and `/foo` are told apart -- and how `(a|b)` is not mistaken for the /// start of one. fn startsStep(p: *Parser) bool { return switch (p.token) { .at, .dot, .dot_dot, .star, .name => true, else => false, }; }
/// The steps of a location path. `start` is the expression the path hangs /// off for the `FilterExpr '/' ...` form, and `absolute` marks a path /// rooted at `/`. /// /// `leading_descendant` inserts the `descendant-or-self::node()` step that /// `//` abbreviates. Expanding the abbreviation here rather than /// representing it means the evaluator never has to know about it, and /// that `//a[1]` predicates the right step -- which is the whole reason /// `//a[1]` and `/descendant::a[1]` differ. fn parseRelativePath( p: *Parser, start: ?*const Expr, leading_descendant: bool, absolute: bool, ) CompileError!*const Expr { var steps: std.ArrayList(Step) = .empty; defer steps.deinit(p.arena);
if (leading_descendant) try steps.append(p.arena, descendantOrSelfStep);
// When a path hangs off a filter expression the `/` has not been // consumed yet. if (start != null) { if (try p.eat(.slash_slash)) { try steps.append(p.arena, descendantOrSelfStep); } else { try p.expect(.slash); } }
while (true) { try steps.append(p.arena, try p.parseStep()); if (try p.eat(.slash_slash)) { try steps.append(p.arena, descendantOrSelfStep); continue; } if (try p.eat(.slash)) continue; break; }
return p.create(.{ .path = .{ .absolute = absolute, .start = start, .steps = try p.arena.dupe(Step, steps.items), } }); }
const descendantOrSelfStep: Step = .{ .axis = .descendant_or_self, .node_test = .any };
fn parseStep(p: *Parser) CompileError!Step { switch (p.token) { .dot => { try p.advance(); return .{ .axis = .self, .node_test = .any }; }, .dot_dot => { try p.advance(); return .{ .axis = .parent, .node_test = .any }; }, else => {}, }
var axis: Axis = .child; if (try p.eat(.at)) { axis = .attribute; } else if (p.token == .name) { const n = p.token.name; if (n.prefix == null and p.lexer.followedByAxis()) { axis = Axis.fromName(n.local.?) orelse return error.UnknownAxis; try p.advance(); try p.expect(.colon_colon); } }
const node_test = try p.parseNodeTest(axis); const predicates = try p.parsePredicates(); return .{ .axis = axis, .node_test = node_test, .predicates = predicates }; }
fn parseNodeTest(p: *Parser, axis: Axis) CompileError!NodeTest { switch (p.token) { .star => { try p.advance(); return .{ .name = .{ .uri = null, .local = null } }; }, .name => |n| { if (n.local) |local| { if (n.prefix == null and p.lexer.followedByLparen()) { if (nodeTypeOf(local)) |kind| { try p.advance(); return p.parseNodeType(kind); } } try p.advance(); // On the attribute axis an unprefixed name is in no // namespace; on the child axis it is too, because XPath // 1.0 has no default namespace for names in expressions. // A stylesheet that wants a namespaced element must use a // prefix, which is a frequent surprise and is nonetheless // what the specification says. const uri: []const u8 = if (n.prefix) |pfx| p.ns.lookup(pfx) orelse return error.UnboundPrefix else ""; return .{ .name = .{ .uri = try p.arena.dupe(u8, uri), .local = try p.arena.dupe(u8, local), } }; } // `prefix:*` const pfx = n.prefix.?; const uri = p.ns.lookup(pfx) orelse return error.UnboundPrefix; try p.advance(); return .{ .name = .{ .uri = try p.arena.dupe(u8, uri), .local = null } }; }, else => { _ = axis; return error.InvalidNodeTest; }, } }
const NodeTypeKind = enum { node, text, comment, pi };
fn nodeTypeOf(s: []const u8) ?NodeTypeKind { const table = std.StaticStringMap(NodeTypeKind).initComptime(.{ .{ "node", .node }, .{ "text", .text }, .{ "comment", .comment }, .{ "processing-instruction", .pi }, }); return table.get(s); }
fn parseNodeType(p: *Parser, kind: NodeTypeKind) CompileError!NodeTest { try p.expect(.lparen); switch (kind) { .pi => { var target: ?[]const u8 = null; if (p.token == .literal) { target = try p.arena.dupe(u8, p.token.literal); try p.advance(); } try p.expect(.rparen); return .{ .pi = target }; }, else => { try p.expect(.rparen); return switch (kind) { .node => .any, .text => .text, .comment => .comment, .pi => unreachable, }; }, } }
fn parsePredicates(p: *Parser) CompileError![]const *const Expr { if (p.token != .lbracket) return &.{}; var list: std.ArrayList(*const Expr) = .empty; defer list.deinit(p.arena); while (try p.eat(.lbracket)) { try list.append(p.arena, try p.parseExpr()); try p.expect(.rbracket); } return p.arena.dupe(*const Expr, list.items); }
fn expandName(p: *Parser, prefix: ?[]const u8, local: []const u8) CompileError!Name { const uri: []const u8 = if (prefix) |pfx| p.ns.lookup(pfx) orelse return error.UnboundPrefix else ""; return .{ .uri = try p.arena.dupe(u8, uri), .local = try p.arena.dupe(u8, local), .prefix = if (prefix) |pfx| try p.arena.dupe(u8, pfx) else "", }; }};
// -- tests -------------------------------------------------------------------
const testing = std.testing;
/// A resolver over a literal table, for tests and for a caller with a fixed/// set of prefixes.pub const MapResolver = struct { entries: []const struct { []const u8, []const u8 },
fn lookupFn(ctx: ?*const anyopaque, prefix: []const u8) ?[]const u8 { const self: *const MapResolver = @ptrCast(@alignCast(ctx.?)); for (self.entries) |e| { if (std.mem.eql(u8, e[0], prefix)) return e[1]; } return null; }
pub fn resolver(m: *const MapResolver) NsResolver { return .{ .ctx = m, .lookupFn = lookupFn }; }};
fn expectParses(src: []const u8) !void { var c = try Compiled.init(testing.allocator, src, .none); defer c.deinit();}
test "parses the shapes a stylesheet actually uses" { for ([_][]const u8{ "/", ".", "..", "@id", "@*", "*", "node()", "text()", "comment()", "processing-instruction()", "processing-instruction('xml-stylesheet')", "foo/bar", "//foo", "foo//bar", "/foo/bar[@id='3']", "child::foo", "ancestor-or-self::node()", "following-sibling::*[1]", "a[1][@b]", "$var", "$var[2]", "concat('a', 'b', 'c')", "count(//item)", "normalize-space(.)", "(a | b)/c", "1 + 2 * 3 - 4 div 5 mod 6", "a = 1 and b != 2 or c < 3", "-1", "- -1", "not(@x)", "a/b/../c", "key('k', @ref)/title", "substring('12345', 2, 3)", }) |src| { expectParses(src) catch |err| { std.debug.print("failed to parse: {s}\n", .{src}); return err; }; }}
test "operator keywords are names where an operator cannot appear" { // The whole point of the lexer's one bit of state: in `div` the name is a // name, in `4 div 2` it is an operator, and in `div div div` it is both. var c = try Compiled.init(testing.allocator, "div div div", .none); defer c.deinit(); try testing.expect(c.expr.* == .binary); try testing.expectEqual(BinOp.div, c.expr.binary.op); try testing.expect(c.expr.binary.lhs.* == .path); try testing.expectEqualStrings("div", c.expr.binary.lhs.path.steps[0].node_test.name.local.?);}
test "a star is a name test or a multiplication depending on what precedes it" { { var c = try Compiled.init(testing.allocator, "*", .none); defer c.deinit(); try testing.expect(c.expr.* == .path); try testing.expect(c.expr.path.steps[0].node_test.name.local == null); } { var c = try Compiled.init(testing.allocator, "2 * 3", .none); defer c.deinit(); try testing.expectEqual(BinOp.mul, c.expr.binary.op); } { // After `]` an operator may follow, so this multiplies. var c = try Compiled.init(testing.allocator, "a[1] * 2", .none); defer c.deinit(); try testing.expectEqual(BinOp.mul, c.expr.binary.op); }}
test "// expands to a descendant-or-self step" { var c = try Compiled.init(testing.allocator, "//a", .none); defer c.deinit(); const path = c.expr.path; try testing.expect(path.absolute); try testing.expectEqual(@as(usize, 2), path.steps.len); try testing.expectEqual(Axis.descendant_or_self, path.steps[0].axis); try testing.expectEqual(Axis.child, path.steps[1].axis);}
test "an absolute path is marked absolute however it is written" { for ([_][]const u8{ "/", "/a", "/a/b", "//a" }) |src| { var c = try Compiled.init(testing.allocator, src, .none); defer c.deinit(); try testing.expect(c.expr.path.absolute); } for ([_][]const u8{ "a", "a/b", "./a", "../a" }) |src| { var c = try Compiled.init(testing.allocator, src, .none); defer c.deinit(); try testing.expect(!c.expr.path.absolute); }}
test "a prefixed name followed by a parenthesis is an extension function" { const map: MapResolver = .{ .entries = &.{.{ "e", "urn:e" }} }; { var c = try Compiled.init(testing.allocator, "e:f($x)", map.resolver()); defer c.deinit(); try testing.expect(c.expr.* == .call); try testing.expectEqualStrings("urn:e", c.expr.call.name.uri); try testing.expectEqualStrings("f", c.expr.call.name.local); } { // And it may begin a path, the same way an unprefixed one may. var c = try Compiled.init(testing.allocator, "e:f($x)/a", map.resolver()); defer c.deinit(); try testing.expect(c.expr.* == .path); try testing.expect(c.expr.path.start.?.* == .call); } { // Without the parenthesis it is still a name test. var c = try Compiled.init(testing.allocator, "e:f", map.resolver()); defer c.deinit(); try testing.expect(c.expr.* == .path); }}
test "prefixes resolve against the static context" { const map: MapResolver = .{ .entries = &.{.{ "p", "urn:p" }} }; var c = try Compiled.init(testing.allocator, "p:a/@p:b", map.resolver()); defer c.deinit(); try testing.expectEqualStrings("urn:p", c.expr.path.steps[0].node_test.name.uri.?); try testing.expectEqualStrings("urn:p", c.expr.path.steps[1].node_test.name.uri.?);
try testing.expectError( error.UnboundPrefix, Compiled.init(testing.allocator, "q:a", map.resolver()), );}
test "malformed expressions are errors rather than crashes" { for ([_][]const u8{ "", "a/", "a[", "'unterminated", "1 +", "foo(", "(a", "a ** b", "@", "$", "bogus-axis::a", }) |src| { try testing.expect(std.meta.isError(Compiled.init(testing.allocator, src, .none))); }}
test "deep nesting is refused rather than overflowing the stack" { const gpa = testing.allocator; const depth = max_depth + 50; var src: std.ArrayList(u8) = .empty; defer src.deinit(gpa); try src.appendNTimes(gpa, '(', depth); try src.append(gpa, '1'); try src.appendNTimes(gpa, ')', depth); try testing.expectError(error.ExpressionTooDeep, Compiled.init(gpa, src.items, .none));}