// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! EXSLT's [`regexp`][module] module: `regexp:match`, `regexp:replace` and //! `regexp:test`. //! //! [module]: https://exslt.github.io/regexp/index.html //! //! The engine is [zregex][], because a regular expression engine is the kind //! of thing that is wrong in the same way in every project that writes its //! own -- the same reason the calendar is zig-datetime's and the collation is //! zig-collate's. Zig's standard library ships none. //! //! [zregex]: https://git.jcollie.dev/jeff/zregex //! //! **There is no oracle for this module.** libxslt implements no `regexp`, so //! nothing in the corpus exercises these and nothing can be compared against //! it. What the behaviour is checked against is the module's own text and its //! worked examples, and where those are silent this says what it decided and //! why. //! //! The module says the pattern "follows the Javascript regular expression //! syntax" and nothing more, so what is actually being promised is //! JavaScript's `RegExp`. zregex is PCRE-shaped rather than //! ECMAScript-shaped, and the two agree on everything these functions are //! used for -- classes, quantifiers, alternation, groups, anchors -- while //! zregex also accepts patterns JavaScript would refuse. Accepting more is //! the safe direction: a pattern written for JavaScript works. const std = @import("std"); const Allocator = std.mem.Allocator; const tree = @import("ztree"); const zxpath = @import("zxpath"); const zregex = @import("zregex"); const Document = tree.Document; const NodeId = tree.NodeId; const Value = zxpath.value.Value; const value = zxpath.value; pub const ns = "http://exslt.org/regexp"; pub const Error = error{ TypeError, WrongArgumentCount, /// The second argument is not a regular expression this engine can /// compile. The caller turns this into a diagnostic naming it, because a /// pattern is nearly always written in the stylesheet and a stylesheet /// that cannot say what it meant is worth failing over rather than /// quietly answering "no match" for the rest of the run. BadPattern, /// The search ran past zregex's step budget. A pattern and a subject that /// together cost more than that is not a match and not a non-match; it is /// a question nobody should be asking, and saying so beats returning /// "false" for what was never decided. PatternTooCostly, } || Allocator.Error; /// True when this module implements a function of this name, which is what /// `function-available()` answers with. pub fn has(local: []const u8) bool { return std.mem.eql(u8, local, "match") or std.mem.eql(u8, local, "replace") or std.mem.eql(u8, local, "test"); } /// The flags argument: `g` for global and `i` for case-insensitive. /// /// Every other character is ignored rather than refused, which is what the /// module's own wording asks for -- "a string consisting of character flags /// to be used by the match; if a character is present then that flag is /// true". A character that names no flag makes no flag true. const Flags = struct { global: bool = false, case_insensitive: bool = false, fn parse(text: []const u8) Flags { var f: Flags = .{}; for (text) |c| switch (c) { 'g' => f.global = true, 'i' => f.case_insensitive = true, else => {}, }; return f; } }; fn compile(gpa: Allocator, pattern: []const u8, flags: Flags) Error!zregex.Regex { return zregex.Regex.compileWithFlags(gpa, pattern, .{ .case_insensitive = flags.case_insensitive, }) catch |err| switch (err) { error.OutOfMemory => error.OutOfMemory, else => error.BadPattern, }; } fn run(err: zregex.RunError) Error { return switch (err) { error.OutOfMemory => error.OutOfMemory, error.StepLimitExceeded => error.PatternTooCostly, }; } /// The subject, pattern and flags every one of these three starts with. const Arguments = struct { subject: []u8, pattern: []u8, flags: Flags, fn read(gpa: Allocator, args: []const Value, flags_index: usize) Error!Arguments { const subject = try args[0].toString(gpa); errdefer gpa.free(subject); const pattern = try args[1].toString(gpa); errdefer gpa.free(pattern); var flags: Flags = .{}; if (args.len > flags_index) { const text = try args[flags_index].toString(gpa); defer gpa.free(text); flags = .parse(text); } return .{ .subject = subject, .pattern = pattern, .flags = flags }; } fn deinit(a: Arguments, gpa: Allocator) void { gpa.free(a.subject); gpa.free(a.pattern); } }; /// `regexp:test(string, pattern, flags?)`. /// /// `g` is accepted and does nothing, which the module says in so many words: /// it is "retained for consistency with `regexp:match` and /// `regexp:replace`". pub fn matches(gpa: Allocator, args: []const Value) Error!Value { if (args.len < 2 or args.len > 3) return error.WrongArgumentCount; const a = try Arguments.read(gpa, args, 2); defer a.deinit(gpa); var re = try compile(gpa, a.pattern, a.flags); defer re.deinit(); return .{ .boolean = re.isMatch(gpa, a.subject) catch |err| return run(err) }; } /// `regexp:replace(string, pattern, flags, replacement)`. /// /// The replacement is literal: `$1` in it is a dollar sign and a one, not the /// first capture. The module describes the fourth argument as "the string to /// replace the matched parts of the string" and scopes its mention of /// JavaScript to the *pattern*, so expanding `$1` here would be inventing a /// feature rather than implementing one -- and a stylesheet that wants a /// capture back can take it from `regexp:match`. pub fn replace(gpa: Allocator, args: []const Value) Error!Value { if (args.len != 4) return error.WrongArgumentCount; const a = try Arguments.read(gpa, args, 2); defer a.deinit(gpa); const replacement = try args[3].toString(gpa); defer gpa.free(replacement); var re = try compile(gpa, a.pattern, a.flags); defer re.deinit(); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var it = re.iterator(gpa, a.subject); defer it.deinit(); var written: usize = 0; while (it.next() catch |err| return run(err)) |found| { var m = found; defer m.deinit(gpa); const span = m.span(); try out.appendSlice(gpa, a.subject[written..span.start]); try out.appendSlice(gpa, replacement); written = span.end; if (!a.flags.global) break; } try out.appendSlice(gpa, a.subject[written..]); return .{ .string = try out.toOwnedSlice(gpa) }; } /// `regexp:match(string, pattern, flags?)`, a node-set of `match` elements. /// /// What is in them is the one place the module's prose and its examples have /// to be read together, and it comes out as JavaScript's `String.match`, /// which is what "follows the Javascript regular expression syntax" points /// at: /// /// - Without `g`, the first match: one element for the whole match, then one /// per capture group in order. A group that did not participate is an empty /// element, which is what the module's own URI example shows for the /// optional `(:\d*)?` port. /// - With `g`, one element per match, each holding the whole of that match. /// The module says "the submatches from all the matches", and its examples /// settle what that means: `([a-z])+ ` over `This is a test string` gives /// four elements, which is one per match and not one per capture. /// /// The elements become children of a document this transformation owns, /// because a node-set holds nodes and there is nowhere else to put them. pub fn match(gpa: Allocator, holder: *Document, args: []const Value) Error!Value { if (args.len < 2 or args.len > 3) return error.WrongArgumentCount; const a = try Arguments.read(gpa, args, 2); defer a.deinit(gpa); var re = try compile(gpa, a.pattern, a.flags); defer re.deinit(); var b: value.NodeSetBuilder = .init(gpa); defer b.deinit(); if (a.flags.global) { var it = re.iterator(gpa, a.subject); defer it.deinit(); while (it.next() catch |err| return run(err)) |found| { var m = found; defer m.deinit(gpa); try b.add(holder.ref(try appendMatch(holder, m.span().slice(a.subject)))); } } else if (re.find(gpa, a.subject) catch |err| return run(err)) |found| { var m = found; defer m.deinit(gpa); for (m.groups) |group| { const text = if (group) |span| span.slice(a.subject) else ""; try b.add(holder.ref(try appendMatch(holder, text))); } } holder.reindex(); return try b.toOwnedValue(); } fn appendMatch(holder: *Document, text: []const u8) Allocator.Error!NodeId { const elem = try holder.appendElement(holder.root, .{ .local = "match" }); // An empty group gets an element with no text node at all rather than one // holding the empty string: the two have the same string-value, and the // first is what a serializer writes as ``. if (text.len != 0) _ = try holder.appendText(elem, text); return elem; }