1use std::cell::RefCell;
6use std::collections::HashMap;
7use std::rc::Rc;
8use std::sync::{Arc, Mutex, PoisonError};
9
10use einvoice_xdm::{Date, DateTime, XPathRegex};
11use einvoice_xpath::{NamespaceMap, Namespaces, QName};
12
13use crate::compile::ValueType;
14use crate::error::{ErrorCode, Result, err};
15use crate::eval::Argument;
16use crate::item::Item;
17use crate::limit::StackLimit;
18use crate::tree::Node;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub struct VariableId(pub u32);
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
26pub struct FunctionId(pub u32);
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum Cardinality {
31 AtMostOne,
33 Any,
35}
36
37#[derive(Debug, Clone)]
39pub struct VariableInfo {
40 pub id: VariableId,
42 pub cardinality: Cardinality,
45 pub value_type: ValueType,
48}
49
50pub trait StaticContext {
53 fn variable(&self, name: &QName) -> Option<VariableInfo>;
55
56 fn variable_reference(&self, name: &QName, in_loop: bool) -> Option<VariableInfo> {
62 let _ = in_loop;
63 self.variable(name)
64 }
65
66 fn function(&self, name: &QName, arity: usize) -> Option<FunctionId>;
68
69 fn function_type(&self, id: FunctionId) -> ValueType {
73 let _ = id;
74 ValueType::unknown()
75 }
76
77 fn xslt_functions(&self) -> bool;
80
81 fn namespace_uri(&self, prefix: &str) -> Option<String>;
83
84 fn element_available(&self, name: &QName) -> Option<bool> {
87 let _ = name;
88 None
89 }
90
91 fn static_base_uri(&self) -> Option<String> {
94 None
95 }
96}
97
98#[derive(Debug, Clone, Default)]
101pub struct SimpleStaticContext {
102 namespaces: NamespaceMap,
103 variables: Vec<(QName, VariableInfo)>,
104 functions: Vec<(QName, usize, FunctionId, ValueType)>,
105 xslt: bool,
106}
107
108impl SimpleStaticContext {
109 #[must_use]
111 pub fn new() -> Self {
112 Self::default()
113 }
114
115 #[must_use]
117 pub fn with_namespaces(mut self, namespaces: NamespaceMap) -> Self {
118 self.namespaces = namespaces;
119 self
120 }
121
122 #[must_use]
124 pub const fn with_xslt_functions(mut self) -> Self {
125 self.xslt = true;
126 self
127 }
128
129 pub fn declare_variable(&mut self, name: QName, cardinality: Cardinality) -> VariableId {
132 self.declare_typed_variable(name, cardinality, ValueType::unknown())
133 }
134
135 pub fn declare_typed_variable(
137 &mut self,
138 name: QName,
139 cardinality: Cardinality,
140 value_type: ValueType,
141 ) -> VariableId {
142 let id = VariableId(u32::try_from(self.variables.len()).unwrap_or(u32::MAX));
143 self.variables.push((
144 name,
145 VariableInfo {
146 id,
147 cardinality,
148 value_type,
149 },
150 ));
151 id
152 }
153
154 pub fn declare_function(&mut self, name: QName, arity: usize) -> FunctionId {
157 self.declare_typed_function(name, arity, ValueType::unknown())
158 }
159
160 pub fn declare_typed_function(
163 &mut self,
164 name: QName,
165 arity: usize,
166 result: ValueType,
167 ) -> FunctionId {
168 let id = FunctionId(u32::try_from(self.functions.len()).unwrap_or(u32::MAX));
169 self.functions.push((name, arity, id, result));
170 id
171 }
172}
173
174impl StaticContext for SimpleStaticContext {
175 fn variable(&self, name: &QName) -> Option<VariableInfo> {
176 self.variables
177 .iter()
178 .rev()
179 .find(|(n, _)| n.same_expanded_name(name))
180 .map(|(_, info)| info.clone())
181 }
182
183 fn function(&self, name: &QName, arity: usize) -> Option<FunctionId> {
184 self.functions
185 .iter()
186 .find(|(n, a, _, _)| *a == arity && n.same_expanded_name(name))
187 .map(|(_, _, id, _)| *id)
188 }
189
190 fn function_type(&self, id: FunctionId) -> ValueType {
191 self.functions
192 .iter()
193 .find(|(_, _, i, _)| *i == id)
194 .map_or_else(ValueType::unknown, |(_, _, _, result)| result.clone())
195 }
196
197 fn xslt_functions(&self) -> bool {
198 self.xslt
199 }
200
201 fn namespace_uri(&self, prefix: &str) -> Option<String> {
202 self.namespaces.namespace_uri(prefix)
203 }
204}
205
206pub trait Host {
210 fn variable(&self, id: VariableId) -> Result<Rc<[Item]>>;
216
217 fn call_function(
226 &self,
227 id: FunctionId,
228 args: Vec<Argument>,
229 dc: &DynamicContext<'_>,
230 ) -> Result<Vec<Item>>;
231
232 fn document(&self, uri: &str, base: Option<&str>) -> Result<Node>;
242
243 fn system_property(&self, name: &QName) -> String;
246}
247
248#[derive(Debug, Clone, Copy, Default)]
250pub struct NoHost;
251
252impl Host for NoHost {
253 fn variable(&self, id: VariableId) -> Result<Rc<[Item]>> {
254 err(ErrorCode::Host, format!("no variable {}", id.0))
255 }
256
257 fn call_function(
258 &self,
259 id: FunctionId,
260 _args: Vec<Argument>,
261 _dc: &DynamicContext<'_>,
262 ) -> Result<Vec<Item>> {
263 err(ErrorCode::Host, format!("no function {}", id.0))
264 }
265
266 fn document(&self, uri: &str, _base: Option<&str>) -> Result<Node> {
267 err(ErrorCode::Host, format!("no document {uri}"))
268 }
269
270 fn system_property(&self, _name: &QName) -> String {
271 String::new()
272 }
273}
274
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub struct Clock {
285 implicit_timezone: i16,
286 current_date_time: DateTime,
287}
288
289impl Clock {
290 pub fn new(implicit_timezone: i16, current_date_time: DateTime) -> Result<Self> {
298 check_timezone(implicit_timezone)?;
299 if current_date_time.timezone().is_none() {
300 return err(
301 ErrorCode::Unsupported,
302 "the current date and time has no timezone",
303 );
304 }
305 Ok(Self {
306 implicit_timezone,
307 current_date_time,
308 })
309 }
310
311 pub fn from_unix_millis(implicit_timezone: i16, millis: i64) -> Result<Self> {
319 check_timezone(implicit_timezone)?;
320 Ok(Self {
321 implicit_timezone,
322 current_date_time: date_time_from_millis(millis, implicit_timezone)?,
323 })
324 }
325
326 #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
334 pub fn system(implicit_timezone: i16) -> Result<Self> {
335 use std::time::{SystemTime, UNIX_EPOCH};
336 let millis = match SystemTime::now().duration_since(UNIX_EPOCH) {
337 Ok(after) => i64::try_from(after.as_millis()),
338 Err(before) => i64::try_from(before.duration().as_millis()).map(|m| -m),
339 }
340 .map_err(|_| crate::error::Error::new(ErrorCode::Fodt0001, "system clock out of range"))?;
341 Self::from_unix_millis(implicit_timezone, millis)
342 }
343
344 #[must_use]
346 pub const fn implicit_timezone(&self) -> i16 {
347 self.implicit_timezone
348 }
349
350 #[must_use]
352 pub const fn current_date_time(&self) -> DateTime {
353 self.current_date_time
354 }
355}
356
357fn check_timezone(minutes: i16) -> Result<()> {
358 if (-840..=840).contains(&minutes) {
359 Ok(())
360 } else {
361 err(ErrorCode::Unsupported, "timezone offset out of range")
362 }
363}
364
365#[derive(Debug, Default)]
371pub struct RegexCache {
372 entries: Mutex<HashMap<(String, String), Arc<XPathRegex>>>,
373}
374
375impl RegexCache {
376 pub const MAX_ENTRIES: usize = 1024;
378
379 #[must_use]
381 pub fn new() -> Self {
382 Self::default()
383 }
384
385 fn get(&self, key: &(String, String)) -> Option<Arc<XPathRegex>> {
386 self.entries
387 .lock()
388 .unwrap_or_else(PoisonError::into_inner)
389 .get(key)
390 .cloned()
391 }
392
393 fn insert(&self, key: (String, String), regex: &Arc<XPathRegex>) {
394 let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
395 if entries.len() < Self::MAX_ENTRIES {
396 entries.entry(key).or_insert_with(|| Arc::clone(regex));
397 }
398 }
399}
400
401pub struct DynamicContext<'h> {
406 pub(crate) host: &'h dyn Host,
407 pub(crate) implicit_timezone: i16,
408 pub(crate) current_date_time: DateTime,
409 pub(crate) regex_cache: RefCell<HashMap<(String, String), Arc<XPathRegex>>>,
410 pub(crate) shared_regexes: Option<&'h RegexCache>,
411 pub(crate) stack_limit: Option<StackLimit>,
412}
413
414impl std::fmt::Debug for DynamicContext<'_> {
415 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
416 f.debug_struct("DynamicContext")
417 .field("implicit_timezone", &self.implicit_timezone)
418 .field("current_date_time", &self.current_date_time)
419 .field("stack_limit", &self.stack_limit)
420 .finish_non_exhaustive()
421 }
422}
423
424impl<'h> DynamicContext<'h> {
425 #[must_use]
427 pub fn new(host: &'h dyn Host, clock: Clock) -> Self {
428 Self {
429 host,
430 implicit_timezone: clock.implicit_timezone,
431 current_date_time: clock.current_date_time,
432 regex_cache: RefCell::new(HashMap::new()),
433 shared_regexes: None,
434 stack_limit: None,
435 }
436 }
437
438 #[must_use]
446 pub const fn with_stack_limit(mut self, limit: StackLimit) -> Self {
447 self.stack_limit = Some(limit);
448 self
449 }
450
451 #[must_use]
454 pub const fn with_regex_cache(mut self, cache: &'h RegexCache) -> Self {
455 self.shared_regexes = Some(cache);
456 self
457 }
458
459 pub(crate) fn check_stack(&self) -> Result<()> {
462 match self.stack_limit {
463 Some(limit) => limit.check().map_err(crate::error::Error::limit_exceeded),
464 None => Ok(()),
465 }
466 }
467
468 #[must_use]
470 pub const fn clock(&self) -> Clock {
471 Clock {
472 implicit_timezone: self.implicit_timezone,
473 current_date_time: self.current_date_time,
474 }
475 }
476
477 #[must_use]
479 pub const fn implicit_timezone(&self) -> i16 {
480 self.implicit_timezone
481 }
482
483 #[must_use]
485 pub const fn current_date_time(&self) -> DateTime {
486 self.current_date_time
487 }
488
489 pub(crate) fn regex(&self, pattern: &str, flags: &str) -> Result<Arc<XPathRegex>> {
490 let key = (pattern.to_owned(), flags.to_owned());
491 if let Some(regex) = self.regex_cache.borrow().get(&key) {
492 return Ok(Arc::clone(regex));
493 }
494 let shared = self.shared_regexes.and_then(|cache| cache.get(&key));
495 let regex = if let Some(regex) = shared {
496 regex
497 } else {
498 let regex = Arc::new(XPathRegex::new(pattern, flags)?);
499 if let Some(cache) = self.shared_regexes {
500 cache.insert(key.clone(), ®ex);
501 }
502 regex
503 };
504 self.regex_cache
505 .borrow_mut()
506 .insert(key, Arc::clone(®ex));
507 Ok(regex)
508 }
509}
510
511fn date_time_from_millis(millis: i64, offset: i16) -> Result<DateTime> {
513 let local = millis
514 .checked_add(i64::from(offset) * 60_000)
515 .ok_or_else(|| crate::error::Error::new(ErrorCode::Fodt0001, "instant out of range"))?;
516 let days = local.div_euclid(86_400_000);
517 let in_day = local.rem_euclid(86_400_000);
518 let z = days + 719_468;
520 let era = z.div_euclid(146_097);
521 let doe = z - era * 146_097;
522 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
523 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
524 let mp = (5 * doy + 2) / 153;
525 let day = doy - (153 * mp + 2) / 5 + 1;
526 let month = if mp < 10 { mp + 3 } else { mp - 9 };
527 let year = yoe + era * 400 + i64::from(month <= 2);
528 let narrow = |v: i64| u8::try_from(v).unwrap_or(u8::MAX);
529 let year = i32::try_from(year)
530 .map_err(|_| crate::error::Error::new(ErrorCode::Fodt0001, "year out of range"))?;
531 let date = Date::new(year, narrow(month), narrow(day), Some(offset))?;
532 let seconds = in_day / 1000;
533 let nanos = u32::try_from((in_day % 1000) * 1_000_000).unwrap_or(0);
534 Ok(DateTime::new(
535 date,
536 narrow(seconds / 3600),
537 narrow(seconds / 60 % 60),
538 narrow(seconds % 60),
539 nanos,
540 )?)
541}
542
543#[derive(Debug, Clone)]
545pub struct Focus {
546 pub item: Item,
548 pub position: usize,
550 pub size: usize,
552}
553
554#[derive(Debug, Clone, Default)]
556pub struct Context {
557 pub focus: Option<Focus>,
559 pub current: Option<Item>,
561}
562
563impl Context {
564 #[must_use]
566 pub fn new() -> Self {
567 Self::default()
568 }
569
570 #[must_use]
573 pub fn for_item(item: Item) -> Self {
574 Self {
575 focus: Some(Focus {
576 item: item.clone(),
577 position: 1,
578 size: 1,
579 }),
580 current: Some(item),
581 }
582 }
583
584 #[must_use]
587 pub fn at(item: Item, position: usize, size: usize) -> Self {
588 Self {
589 focus: Some(Focus {
590 item: item.clone(),
591 position,
592 size,
593 }),
594 current: Some(item),
595 }
596 }
597}
598
599#[cfg(test)]
600mod tests {
601 use super::*;
602
603 #[test]
604 fn a_regex_cache_is_shared_by_contexts() {
605 let cache = RegexCache::new();
606 let ns = einvoice_xpath::NamespaceMap::new();
607 let expr = einvoice_xpath::parse_expr(
608 "matches('abc', concat('^a', 'b')) and not(matches('x', concat('[', ']')))",
609 &ns,
610 );
611 let expr = crate::compile(&expr.unwrap(), &SimpleStaticContext::new()).unwrap();
613 for _ in 0..2 {
614 let dc = DynamicContext::new(&NoHost, Clock::from_unix_millis(0, 0).unwrap())
615 .with_regex_cache(&cache);
616 let error = expr
617 .effective_boolean_value(&dc, &Context::new())
618 .unwrap_err();
619 assert_eq!(error.code(), ErrorCode::Forx0002);
620 assert_eq!(dc.regex_cache.borrow().len(), 1);
621 assert_eq!(cache.entries.lock().unwrap().len(), 1);
622 }
623 let dc = DynamicContext::new(&NoHost, Clock::from_unix_millis(0, 0).unwrap())
624 .with_regex_cache(&cache);
625 let regex = dc.regex("^ab", "").unwrap();
626 assert!(Arc::ptr_eq(
627 ®ex,
628 cache
629 .get(&("^ab".to_owned(), String::new()))
630 .as_ref()
631 .unwrap()
632 ));
633 }
634
635 #[test]
636 fn clock_conversions() {
637 let dt = date_time_from_millis(0, 0).unwrap();
638 assert_eq!(dt.to_string(), "1970-01-01T00:00:00Z");
639 let dt = date_time_from_millis(1_789_000_123_456, 60).unwrap();
640 assert_eq!(dt.to_string(), "2026-09-10T01:28:43.456+01:00");
641 let dt = date_time_from_millis(-1, -300).unwrap();
642 assert_eq!(dt.to_string(), "1969-12-31T18:59:59.999-05:00");
643 for (millis, offset) in [(i64::MAX, 840), (i64::MIN, -840)] {
645 assert_eq!(
646 date_time_from_millis(millis, offset).unwrap_err().code(),
647 ErrorCode::Fodt0001
648 );
649 }
650 let dt = date_time_from_millis(i64::MAX, 0).unwrap();
651 assert_eq!(dt.to_string(), "292278994-08-17T07:12:55.807Z");
652 }
653}