Skip to main content

libxml_rs/exslt/
mod.rs

1//! EXSLT implementation — native Rust (§35).
2//!
3//! EXSLT is a community-driven set of extensions to XSLT 1.0. libxslt ships
4//! implementations of the following modules:
5//!
6//! - `exsl:` — Common (exsl:node-set, exsl:object-type, exsl:document)
7//! - `math:` — Math (math:max, math:min, math:sin, math:cos, ...)
8//! - `set:` — Sets (set:difference, set:distinct, set:intersection, ...)
9//! - `str:` — Strings (str:concat, str:padding, str:split, ...)
10//! - `dyn:` — Dynamic (dyn:element, dyn:attribute, dyn:evaluate, ...)
11//! - `func:` — Functions (func:function, func:result, func:script)
12//! - `date:` — Dates and Times (date:date, date:format-date, ...)
13//!
14//! # Registration model
15//!
16//! Upstream libxslt requires an explicit `exsltRegisterAll()` call (usually
17//! from the host application; `xsltproc` calls it at startup) before EXSLT
18//! functions are available. This module mirrors that model: a process-wide
19//! registry of EXSLT functions keyed by their full QName (e.g. `"math:max"`).
20//! `exsltRegisterAll()` populates the registry; each new transform context
21//! copies the registered functions into its XPath context (§31 integration).
22//!
23//! # EXSLT namespaces
24//!
25//! | Prefix | URI |
26//! |--------|-----|
27//! | exsl | `http://exslt.org/common` |
28//! | math | `http://exslt.org/math` |
29//! | set | `http://exslt.org/sets` |
30//! | str | `http://exslt.org/strings` |
31//! | dyn | `http://exslt.org/dynamic` |
32//! | func | `http://exslt.org/functions` |
33//! | date | `http://exslt.org/dates-and-times` |
34//!
35//! # Phase 9 status
36//!
37//! Complete: all seven modules implemented and registered.
38
39use once_cell::sync::Lazy;
40use parking_lot::Mutex;
41use std::collections::HashMap;
42use std::ffi::c_void;
43use std::os::raw::c_int;
44
45use crate::abi::types::xmlChar;
46use crate::xml::xpath::context::XPathContext;
47use crate::xml::xpath::types::XPathValue;
48
49pub mod common;
50pub mod dates;
51pub mod dynamic;
52pub mod functions;
53pub mod math;
54pub mod saxon;
55pub mod sets;
56pub mod strings;
57
58/// EXSLT namespace URIs.
59pub const EXSLT_NS_COMMON: &str = "http://exslt.org/common";
60pub const EXSLT_NS_MATH: &str = "http://exslt.org/math";
61pub const EXSLT_NS_SETS: &str = "http://exslt.org/sets";
62pub const EXSLT_NS_STRINGS: &str = "http://exslt.org/strings";
63pub const EXSLT_NS_DYNAMIC: &str = "http://exslt.org/dynamic";
64pub const EXSLT_NS_FUNCTIONS: &str = "http://exslt.org/functions";
65pub const EXSLT_NS_DATES: &str = "http://exslt.org/dates-and-times";
66
67/// The XPath function signature used throughout the EXSLT modules.
68pub type ExsltFunction = fn(&mut XPathContext, &[XPathValue]) -> Result<XPathValue, String>;
69
70/// A capture-capable EXSLT function (used by `func:function` bodies).
71///
72/// Stored as a leaked `&'static` reference so entries are `Copy` and the
73/// registry can hand out clones. The process-wide registry lives for the
74/// lifetime of the program, so leaking is intentional and bounded.
75pub type ExsltClosure =
76    &'static (dyn Fn(&mut XPathContext, &[XPathValue]) -> Result<XPathValue, String> + Send + Sync);
77
78/// Process-wide EXSLT function registry, keyed by full QName
79/// (e.g. `"math:max"`). Populated by `exsltRegisterAll()`.
80static REGISTRY: Lazy<Mutex<HashMap<String, ExsltClosure>>> =
81    Lazy::new(|| Mutex::new(HashMap::new()));
82
83/// Register a single EXSLT function under its full QName.
84pub fn register<F>(name: &str, f: F)
85where
86    F: Fn(&mut XPathContext, &[XPathValue]) -> Result<XPathValue, String> + Send + Sync + 'static,
87{
88    // SAFETY: the boxed closure is leaked; it lives for the process lifetime
89    // (the registry is never cleared) so the resulting 'static reference is
90    // sound.
91    let leaked: &'static (dyn Fn(&mut XPathContext, &[XPathValue]) -> Result<XPathValue, String>
92                  + Send
93                  + Sync) = Box::leak(Box::new(f));
94    REGISTRY.lock().insert(name.to_string(), leaked);
95}
96
97/// Look up a registered EXSLT function by full QName.
98pub fn lookup(name: &str) -> Option<ExsltClosure> {
99    REGISTRY.lock().get(name).copied()
100}
101
102/// Iterate over all registered EXSLT functions.
103pub fn iter_functions() -> Vec<(String, ExsltClosure)> {
104    REGISTRY
105        .lock()
106        .iter()
107        .map(|(k, v)| (k.clone(), *v))
108        .collect()
109}
110
111/// Whether any EXSLT functions have been registered.
112pub fn is_registered() -> bool {
113    !REGISTRY.lock().is_empty()
114}
115
116/// Register every EXSLT module (mirrors upstream `exsltRegisterAll`).
117pub fn register_all() {
118    common::register_all();
119    math::register_all();
120    sets::register_all();
121    strings::register_all();
122    dynamic::register_all();
123    dates::register_all();
124    functions::register_all();
125    saxon::register_all();
126}
127
128/// The C ABI entry point: register all EXSLT modules.
129///
130/// # UPSTREAM-PARITY
131///
132/// ```c
133/// void exsltRegisterAll(void);
134/// ```
135///
136/// Oracle behavior: registers every EXSLT function so it becomes available
137/// to subsequently created transform contexts. Calling it twice is a no-op
138/// (re-registration overwrites identical entries).
139#[no_mangle]
140pub extern "C" fn exsltRegisterAll() {
141    register_all();
142}
143
144// ═══════════════════════════════════════════════════════════════════════════════
145// Per-module registration entry points (11.1-X R-000165 closure)
146// ═══════════════════════════════════════════════════════════════════════════════
147//
148// Upstream libexslt exposes one register function per module (exslt.c). The
149// candidate's registry is keyed by "prefix:name"; each module's register_all
150// populates it. saxon/crypto have no candidate module — their register
151// functions are exported no-ops (upstream contracts: void / int 0).
152
153/// `exsltCommonRegister` — register the EXSLT common module.
154#[no_mangle]
155pub extern "C" fn exsltCommonRegister() {
156    common::register_all();
157}
158
159/// `exsltMathRegister` — register the EXSLT math module.
160#[no_mangle]
161pub extern "C" fn exsltMathRegister() {
162    math::register_all();
163}
164
165/// `exsltSetsRegister` — register the EXSLT sets module.
166#[no_mangle]
167pub extern "C" fn exsltSetsRegister() {
168    sets::register_all();
169}
170
171/// `exsltFuncRegister` — register the EXSLT functions module.
172#[no_mangle]
173pub extern "C" fn exsltFuncRegister() {
174    functions::register_all();
175}
176
177/// `exsltStrRegister` — register the EXSLT strings module.
178#[no_mangle]
179pub extern "C" fn exsltStrRegister() {
180    strings::register_all();
181}
182
183/// `exsltDateRegister` — register the EXSLT dates module.
184#[no_mangle]
185pub extern "C" fn exsltDateRegister() {
186    dates::register_all();
187}
188
189/// `exsltSaxonRegister` — register the EXSLT Saxon extensions
190/// (upstream exslt.c calls this from `exsltRegisterAll`).
191#[no_mangle]
192pub extern "C" fn exsltSaxonRegister() {
193    saxon::register_all();
194}
195
196/// `exsltDynRegister` — register the EXSLT dynamic module.
197#[no_mangle]
198pub extern "C" fn exsltDynRegister() {
199    dynamic::register_all();
200}
201
202/// `exsltCryptoRegister` — register the EXSLT crypto module. The candidate
203/// has no crypto module; upstream returns void, so this is a no-op.
204#[no_mangle]
205pub extern "C" fn exsltCryptoRegister() {}
206
207/// `exsltDateXpathCtxtRegister(ctxt, prefix)` — register the dates module
208/// on a specific XPath context (upstream date.c). The candidate's registry
209/// is global; registration is performed for all contexts.
210#[no_mangle]
211pub extern "C" fn exsltDateXpathCtxtRegister(_ctxt: *mut c_void, _prefix: *const xmlChar) -> c_int {
212    dates::register_all();
213    0
214}
215
216/// `exsltMathXpathCtxtRegister(ctxt, prefix)` — math module (see above).
217#[no_mangle]
218pub extern "C" fn exsltMathXpathCtxtRegister(_ctxt: *mut c_void, _prefix: *const xmlChar) -> c_int {
219    math::register_all();
220    0
221}
222
223/// `exsltSetsXpathCtxtRegister(ctxt, prefix)` — sets module (see above).
224#[no_mangle]
225pub extern "C" fn exsltSetsXpathCtxtRegister(_ctxt: *mut c_void, _prefix: *const xmlChar) -> c_int {
226    sets::register_all();
227    0
228}
229
230/// `exsltStrXpathCtxtRegister(ctxt, prefix)` — strings module (see above).
231#[no_mangle]
232pub extern "C" fn exsltStrXpathCtxtRegister(_ctxt: *mut c_void, _prefix: *const xmlChar) -> c_int {
233    strings::register_all();
234    0
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn test_register_and_lookup() {
243        fn my_func(_ctx: &mut XPathContext, _args: &[XPathValue]) -> Result<XPathValue, String> {
244            Ok(XPathValue::String("hello".to_string()))
245        }
246        register("test:myfunc", my_func);
247        let f = lookup("test:myfunc");
248        assert!(f.is_some());
249        let (names, _) = iter_functions()
250            .into_iter()
251            .find(|(n, _)| n == "test:myfunc")
252            .unwrap();
253        assert_eq!(names, "test:myfunc");
254    }
255
256    #[test]
257    fn test_lookup_missing() {
258        assert!(lookup("nonexistent:fn").is_none());
259    }
260
261    #[test]
262    fn test_register_all_populates() {
263        // Register everything; all module functions must be present.
264        register_all();
265        for name in [
266            "exsl:node-set",
267            "exsl:object-type",
268            "math:max",
269            "math:sin",
270            "math:constant",
271            "set:difference",
272            "set:distinct",
273            "str:tokenize",
274            "str:padding",
275            "dyn:evaluate",
276            "date:date",
277            "date:date-time",
278        ] {
279            assert!(lookup(name).is_some(), "missing EXSLT function {}", name);
280        }
281    }
282}