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