Skip to main content

einvoice_xpath_eval/
context.rs

1//! The static context an expression is compiled in and the dynamic context it is
2//! evaluated in, with the hooks the XSLT layer provides: variables, user functions,
3//! `current()`, `document()` and `system-property()`.
4
5use std::cell::RefCell;
6use std::collections::HashMap;
7use std::rc::Rc;
8
9use einvoice_xdm::{Date, DateTime, XPathRegex};
10use einvoice_xpath::{NamespaceMap, Namespaces, QName};
11
12use crate::error::{ErrorCode, Result, err};
13use crate::item::Item;
14use crate::tree::Node;
15
16/// The identity of a variable declared by the host, given back to it at evaluation.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct VariableId(pub u32);
19
20/// The identity of a function declared by the host (an `xsl:function`).
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub struct FunctionId(pub u32);
23
24/// What is statically known of the number of items of a value.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum Cardinality {
27    /// At most one item.
28    AtMostOne,
29    /// Any number of items.
30    Any,
31}
32
33/// A variable in scope.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct VariableInfo {
36    /// Its identity at evaluation.
37    pub id: VariableId,
38    /// What is known of its value. It only affects the evaluation strategy (which side
39    /// of a general comparison is read first), never the result.
40    pub cardinality: Cardinality,
41}
42
43/// The static context of an expression (XPath 2.0 section 2.1.1), as far as the compiler
44/// needs it: names are already resolved by the parser.
45pub trait StaticContext {
46    /// The variable of that expanded name in scope, if any.
47    fn variable(&self, name: &QName) -> Option<VariableInfo>;
48
49    /// The host function of that expanded name and arity, if any.
50    fn function(&self, name: &QName, arity: usize) -> Option<FunctionId>;
51
52    /// Whether the XSLT functions `current()`, `document()` and `system-property()` are
53    /// available.
54    fn xslt_functions(&self) -> bool;
55
56    /// The namespace bound to a prefix, for the `QName` argument of `system-property()`.
57    fn namespace_uri(&self, prefix: &str) -> Option<String>;
58}
59
60/// A static context built by hand: namespaces, variables and functions declared one by
61/// one.
62#[derive(Debug, Clone, Default)]
63pub struct SimpleStaticContext {
64    namespaces: NamespaceMap,
65    variables: Vec<(QName, VariableInfo)>,
66    functions: Vec<(QName, usize, FunctionId)>,
67    xslt: bool,
68}
69
70impl SimpleStaticContext {
71    /// An empty context: no namespaces, variables or functions, no XSLT functions.
72    #[must_use]
73    pub fn new() -> Self {
74        Self::default()
75    }
76
77    /// Uses these prefix bindings for `system-property()`.
78    #[must_use]
79    pub fn with_namespaces(mut self, namespaces: NamespaceMap) -> Self {
80        self.namespaces = namespaces;
81        self
82    }
83
84    /// Makes the XSLT functions available.
85    #[must_use]
86    pub const fn with_xslt_functions(mut self) -> Self {
87        self.xslt = true;
88        self
89    }
90
91    /// Declares a variable (a later declaration of the same name hides the earlier one)
92    /// and returns its identity: the declaration order, from 0.
93    pub fn declare_variable(&mut self, name: QName, cardinality: Cardinality) -> VariableId {
94        let id = VariableId(u32::try_from(self.variables.len()).unwrap_or(u32::MAX));
95        self.variables
96            .push((name, VariableInfo { id, cardinality }));
97        id
98    }
99
100    /// Declares a host function and returns its identity: the declaration order, from 0.
101    pub fn declare_function(&mut self, name: QName, arity: usize) -> FunctionId {
102        let id = FunctionId(u32::try_from(self.functions.len()).unwrap_or(u32::MAX));
103        self.functions.push((name, arity, id));
104        id
105    }
106}
107
108impl StaticContext for SimpleStaticContext {
109    fn variable(&self, name: &QName) -> Option<VariableInfo> {
110        self.variables
111            .iter()
112            .rev()
113            .find(|(n, _)| n.same_expanded_name(name))
114            .map(|(_, info)| *info)
115    }
116
117    fn function(&self, name: &QName, arity: usize) -> Option<FunctionId> {
118        self.functions
119            .iter()
120            .find(|(n, a, _)| *a == arity && n.same_expanded_name(name))
121            .map(|(_, _, id)| *id)
122    }
123
124    fn xslt_functions(&self) -> bool {
125        self.xslt
126    }
127
128    fn namespace_uri(&self, prefix: &str) -> Option<String> {
129        self.namespaces.namespace_uri(prefix)
130    }
131}
132
133/// What the host (the XSLT layer) provides at evaluation. The compiler only lets
134/// through references to variables and functions the static context declared, so a
135/// host is only asked for those.
136pub trait Host {
137    /// The value of a variable.
138    ///
139    /// # Errors
140    ///
141    /// Whatever evaluating the variable raises.
142    fn variable(&self, id: VariableId) -> Result<Rc<[Item]>>;
143
144    /// Calls a host function.
145    ///
146    /// # Errors
147    ///
148    /// Whatever the function raises.
149    fn call_function(&self, id: FunctionId, args: Vec<Vec<Item>>) -> Result<Vec<Item>>;
150
151    /// `document()`: the document node of the resource at `uri`, resolved against `base`
152    /// (the base URI of the node the URI came from, `None` for the static base URI). The
153    /// same URI must give the same document node, parsed with
154    /// [`Document::parse_loaded`](crate::Document::parse_loaded)
155    /// so that `fn:document-uri` gives its absolute URI, as in Saxon.
156    ///
157    /// # Errors
158    ///
159    /// The resource cannot be retrieved or parsed.
160    fn document(&self, uri: &str, base: Option<&str>) -> Result<Node>;
161
162    /// `system-property()`: the value of the property (the empty string for an unknown
163    /// one).
164    fn system_property(&self, name: &QName) -> String;
165}
166
167/// A host for plain XPath: no variables, functions or documents.
168#[derive(Debug, Clone, Copy, Default)]
169pub struct NoHost;
170
171impl Host for NoHost {
172    fn variable(&self, id: VariableId) -> Result<Rc<[Item]>> {
173        err(ErrorCode::Host, format!("no variable {}", id.0))
174    }
175
176    fn call_function(&self, id: FunctionId, _args: Vec<Vec<Item>>) -> Result<Vec<Item>> {
177        err(ErrorCode::Host, format!("no function {}", id.0))
178    }
179
180    fn document(&self, uri: &str, _base: Option<&str>) -> Result<Node> {
181        err(ErrorCode::Host, format!("no document {uri}"))
182    }
183
184    fn system_property(&self, _name: &QName) -> String {
185        String::new()
186    }
187}
188
189/// The clock of an evaluation: the implicit timezone and the value of
190/// `fn:current-dateTime()`. Both are inputs: the evaluator never reads a clock itself, and
191/// the current date and time stays the same for every evaluation made with the clock, as
192/// Saxon reads its clock once per transformation.
193///
194/// [`Clock::system`] reads the system clock on the targets that have one; elsewhere, such
195/// as `wasm32-unknown-unknown`, the host gives the time it reads, for instance with
196/// [`Clock::from_unix_millis`] and JavaScript's `Date.now()`.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub struct Clock {
199    implicit_timezone: i16,
200    current_date_time: DateTime,
201}
202
203impl Clock {
204    /// The implicit timezone, in minutes east of UTC (Saxon takes the JVM's), and the value
205    /// of `fn:current-dateTime()`, returned as given.
206    ///
207    /// # Errors
208    ///
209    /// An offset beyond ±14:00, or a date and time without a timezone (the current date
210    /// and time always has one).
211    pub fn new(implicit_timezone: i16, current_date_time: DateTime) -> Result<Self> {
212        check_timezone(implicit_timezone)?;
213        if current_date_time.timezone().is_none() {
214            return err(
215                ErrorCode::Unsupported,
216                "the current date and time has no timezone",
217            );
218        }
219        Ok(Self {
220            implicit_timezone,
221            current_date_time,
222        })
223    }
224
225    /// The implicit timezone, in minutes east of UTC, and the instant `millis`
226    /// milliseconds after the Unix epoch (1970-01-01T00:00:00Z) as the current date and
227    /// time, expressed in that timezone.
228    ///
229    /// # Errors
230    ///
231    /// An offset beyond ±14:00, or an instant beyond the supported dates.
232    pub fn from_unix_millis(implicit_timezone: i16, millis: i64) -> Result<Self> {
233        check_timezone(implicit_timezone)?;
234        Ok(Self {
235            implicit_timezone,
236            current_date_time: date_time_from_millis(millis, implicit_timezone)?,
237        })
238    }
239
240    /// The implicit timezone, in minutes east of UTC, and the current reading of the
241    /// system clock, expressed in that timezone. Not available on
242    /// `wasm32-unknown-unknown`, which has no clock.
243    ///
244    /// # Errors
245    ///
246    /// An offset beyond ±14:00, or a system clock beyond the supported dates.
247    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
248    pub fn system(implicit_timezone: i16) -> Result<Self> {
249        use std::time::{SystemTime, UNIX_EPOCH};
250        let millis = match SystemTime::now().duration_since(UNIX_EPOCH) {
251            Ok(after) => i64::try_from(after.as_millis()),
252            Err(before) => i64::try_from(before.duration().as_millis()).map(|m| -m),
253        }
254        .map_err(|_| crate::error::Error::new(ErrorCode::Fodt0001, "system clock out of range"))?;
255        Self::from_unix_millis(implicit_timezone, millis)
256    }
257
258    /// The implicit timezone in minutes.
259    #[must_use]
260    pub const fn implicit_timezone(&self) -> i16 {
261        self.implicit_timezone
262    }
263
264    /// The value of `fn:current-dateTime()`.
265    #[must_use]
266    pub const fn current_date_time(&self) -> DateTime {
267        self.current_date_time
268    }
269}
270
271fn check_timezone(minutes: i16) -> Result<()> {
272    if (-840..=840).contains(&minutes) {
273        Ok(())
274    } else {
275        err(ErrorCode::Unsupported, "timezone offset out of range")
276    }
277}
278
279/// The dynamic context shared by evaluations: the host, the [`Clock`] (implicit timezone
280/// and current date and time) and a cache of compiled regular expressions.
281pub struct DynamicContext<'h> {
282    pub(crate) host: &'h dyn Host,
283    pub(crate) implicit_timezone: i16,
284    pub(crate) current_date_time: DateTime,
285    pub(crate) regex_cache: RefCell<HashMap<(String, String), Rc<XPathRegex>>>,
286}
287
288impl std::fmt::Debug for DynamicContext<'_> {
289    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
290        f.debug_struct("DynamicContext")
291            .field("implicit_timezone", &self.implicit_timezone)
292            .field("current_date_time", &self.current_date_time)
293            .finish_non_exhaustive()
294    }
295}
296
297impl<'h> DynamicContext<'h> {
298    /// A context with this host and clock.
299    #[must_use]
300    pub fn new(host: &'h dyn Host, clock: Clock) -> Self {
301        Self {
302            host,
303            implicit_timezone: clock.implicit_timezone,
304            current_date_time: clock.current_date_time,
305            regex_cache: RefCell::new(HashMap::new()),
306        }
307    }
308
309    /// The clock: implicit timezone and current date and time.
310    #[must_use]
311    pub const fn clock(&self) -> Clock {
312        Clock {
313            implicit_timezone: self.implicit_timezone,
314            current_date_time: self.current_date_time,
315        }
316    }
317
318    /// The implicit timezone in minutes.
319    #[must_use]
320    pub const fn implicit_timezone(&self) -> i16 {
321        self.implicit_timezone
322    }
323
324    /// The value of `fn:current-dateTime()`.
325    #[must_use]
326    pub const fn current_date_time(&self) -> DateTime {
327        self.current_date_time
328    }
329
330    pub(crate) fn regex(&self, pattern: &str, flags: &str) -> Result<Rc<XPathRegex>> {
331        let key = (pattern.to_owned(), flags.to_owned());
332        if let Some(regex) = self.regex_cache.borrow().get(&key) {
333            return Ok(Rc::clone(regex));
334        }
335        let regex = Rc::new(XPathRegex::new(pattern, flags)?);
336        self.regex_cache.borrow_mut().insert(key, Rc::clone(&regex));
337        Ok(regex)
338    }
339}
340
341/// The date-time `millis` after the epoch, in the timezone `offset` (minutes).
342fn date_time_from_millis(millis: i64, offset: i16) -> Result<DateTime> {
343    let local = millis
344        .checked_add(i64::from(offset) * 60_000)
345        .ok_or_else(|| crate::error::Error::new(ErrorCode::Fodt0001, "instant out of range"))?;
346    let days = local.div_euclid(86_400_000);
347    let in_day = local.rem_euclid(86_400_000);
348    // Civil date from days since 1970-01-01 (proleptic Gregorian).
349    let z = days + 719_468;
350    let era = z.div_euclid(146_097);
351    let doe = z - era * 146_097;
352    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
353    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
354    let mp = (5 * doy + 2) / 153;
355    let day = doy - (153 * mp + 2) / 5 + 1;
356    let month = if mp < 10 { mp + 3 } else { mp - 9 };
357    let year = yoe + era * 400 + i64::from(month <= 2);
358    let narrow = |v: i64| u8::try_from(v).unwrap_or(u8::MAX);
359    let year = i32::try_from(year)
360        .map_err(|_| crate::error::Error::new(ErrorCode::Fodt0001, "year out of range"))?;
361    let date = Date::new(year, narrow(month), narrow(day), Some(offset))?;
362    let seconds = in_day / 1000;
363    let nanos = u32::try_from((in_day % 1000) * 1_000_000).unwrap_or(0);
364    Ok(DateTime::new(
365        date,
366        narrow(seconds / 3600),
367        narrow(seconds / 60 % 60),
368        narrow(seconds % 60),
369        nanos,
370    )?)
371}
372
373/// The focus of an evaluation: the context item, position and size.
374#[derive(Debug, Clone)]
375pub struct Focus {
376    /// The context item.
377    pub item: Item,
378    /// The context position, from 1.
379    pub position: usize,
380    /// The context size.
381    pub size: usize,
382}
383
384/// Where an expression is evaluated: its focus, and the item `current()` returns.
385#[derive(Debug, Clone, Default)]
386pub struct Context {
387    /// The focus; `None` when the context item is absent.
388    pub focus: Option<Focus>,
389    /// The current item of XSLT (`current()`); `None` where it is absent.
390    pub current: Option<Item>,
391}
392
393impl Context {
394    /// No focus and no current item.
395    #[must_use]
396    pub fn new() -> Self {
397        Self::default()
398    }
399
400    /// The item as context item (position and size 1) and as current item, as for an
401    /// expression of an XSLT instruction evaluated with that item as context.
402    #[must_use]
403    pub fn for_item(item: Item) -> Self {
404        Self {
405            focus: Some(Focus {
406                item: item.clone(),
407                position: 1,
408                size: 1,
409            }),
410            current: Some(item),
411        }
412    }
413
414    /// The item as context and current item, at a given position in a sequence of `size`
415    /// items.
416    #[must_use]
417    pub fn at(item: Item, position: usize, size: usize) -> Self {
418        Self {
419            focus: Some(Focus {
420                item: item.clone(),
421                position,
422                size,
423            }),
424            current: Some(item),
425        }
426    }
427}
428
429#[cfg(test)]
430mod tests {
431    use super::*;
432
433    #[test]
434    fn clock_conversions() {
435        let dt = date_time_from_millis(0, 0).unwrap();
436        assert_eq!(dt.to_string(), "1970-01-01T00:00:00Z");
437        let dt = date_time_from_millis(1_789_000_123_456, 60).unwrap();
438        assert_eq!(dt.to_string(), "2026-09-10T01:28:43.456+01:00");
439        let dt = date_time_from_millis(-1, -300).unwrap();
440        assert_eq!(dt.to_string(), "1969-12-31T18:59:59.999-05:00");
441        // An offset that takes the instant beyond i64: an error, never an overflow.
442        for (millis, offset) in [(i64::MAX, 840), (i64::MIN, -840)] {
443            assert_eq!(
444                date_time_from_millis(millis, offset).unwrap_err().code(),
445                ErrorCode::Fodt0001
446            );
447        }
448        let dt = date_time_from_millis(i64::MAX, 0).unwrap();
449        assert_eq!(dt.to_string(), "292278994-08-17T07:12:55.807Z");
450    }
451}