use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::{Arc, Mutex, PoisonError};
use einvoice_xdm::{Date, DateTime, XPathRegex};
use einvoice_xpath::{NamespaceMap, Namespaces, QName};
use crate::compile::ValueType;
use crate::error::{ErrorCode, Result, err};
use crate::eval::Argument;
use crate::item::Item;
use crate::limit::StackLimit;
use crate::tree::Node;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct VariableId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FunctionId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Cardinality {
AtMostOne,
Any,
}
#[derive(Debug, Clone)]
pub struct VariableInfo {
pub id: VariableId,
pub cardinality: Cardinality,
pub value_type: ValueType,
}
pub trait StaticContext {
fn variable(&self, name: &QName) -> Option<VariableInfo>;
fn variable_reference(&self, name: &QName, in_loop: bool) -> Option<VariableInfo> {
let _ = in_loop;
self.variable(name)
}
fn function(&self, name: &QName, arity: usize) -> Option<FunctionId>;
fn function_type(&self, id: FunctionId) -> ValueType {
let _ = id;
ValueType::unknown()
}
fn xslt_functions(&self) -> bool;
fn namespace_uri(&self, prefix: &str) -> Option<String>;
fn element_available(&self, name: &QName) -> Option<bool> {
let _ = name;
None
}
fn static_base_uri(&self) -> Option<String> {
None
}
}
#[derive(Debug, Clone, Default)]
pub struct SimpleStaticContext {
namespaces: NamespaceMap,
variables: Vec<(QName, VariableInfo)>,
functions: Vec<(QName, usize, FunctionId, ValueType)>,
xslt: bool,
}
impl SimpleStaticContext {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_namespaces(mut self, namespaces: NamespaceMap) -> Self {
self.namespaces = namespaces;
self
}
#[must_use]
pub const fn with_xslt_functions(mut self) -> Self {
self.xslt = true;
self
}
pub fn declare_variable(&mut self, name: QName, cardinality: Cardinality) -> VariableId {
self.declare_typed_variable(name, cardinality, ValueType::unknown())
}
pub fn declare_typed_variable(
&mut self,
name: QName,
cardinality: Cardinality,
value_type: ValueType,
) -> VariableId {
let id = VariableId(u32::try_from(self.variables.len()).unwrap_or(u32::MAX));
self.variables.push((
name,
VariableInfo {
id,
cardinality,
value_type,
},
));
id
}
pub fn declare_function(&mut self, name: QName, arity: usize) -> FunctionId {
self.declare_typed_function(name, arity, ValueType::unknown())
}
pub fn declare_typed_function(
&mut self,
name: QName,
arity: usize,
result: ValueType,
) -> FunctionId {
let id = FunctionId(u32::try_from(self.functions.len()).unwrap_or(u32::MAX));
self.functions.push((name, arity, id, result));
id
}
}
impl StaticContext for SimpleStaticContext {
fn variable(&self, name: &QName) -> Option<VariableInfo> {
self.variables
.iter()
.rev()
.find(|(n, _)| n.same_expanded_name(name))
.map(|(_, info)| info.clone())
}
fn function(&self, name: &QName, arity: usize) -> Option<FunctionId> {
self.functions
.iter()
.find(|(n, a, _, _)| *a == arity && n.same_expanded_name(name))
.map(|(_, _, id, _)| *id)
}
fn function_type(&self, id: FunctionId) -> ValueType {
self.functions
.iter()
.find(|(_, _, i, _)| *i == id)
.map_or_else(ValueType::unknown, |(_, _, _, result)| result.clone())
}
fn xslt_functions(&self) -> bool {
self.xslt
}
fn namespace_uri(&self, prefix: &str) -> Option<String> {
self.namespaces.namespace_uri(prefix)
}
}
pub trait Host {
fn variable(&self, id: VariableId) -> Result<Rc<[Item]>>;
fn call_function(
&self,
id: FunctionId,
args: Vec<Argument>,
dc: &DynamicContext<'_>,
) -> Result<Vec<Item>>;
fn document(&self, uri: &str, base: Option<&str>) -> Result<Node>;
fn system_property(&self, name: &QName) -> String;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoHost;
impl Host for NoHost {
fn variable(&self, id: VariableId) -> Result<Rc<[Item]>> {
err(ErrorCode::Host, format!("no variable {}", id.0))
}
fn call_function(
&self,
id: FunctionId,
_args: Vec<Argument>,
_dc: &DynamicContext<'_>,
) -> Result<Vec<Item>> {
err(ErrorCode::Host, format!("no function {}", id.0))
}
fn document(&self, uri: &str, _base: Option<&str>) -> Result<Node> {
err(ErrorCode::Host, format!("no document {uri}"))
}
fn system_property(&self, _name: &QName) -> String {
String::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Clock {
implicit_timezone: i16,
current_date_time: DateTime,
}
impl Clock {
pub fn new(implicit_timezone: i16, current_date_time: DateTime) -> Result<Self> {
check_timezone(implicit_timezone)?;
if current_date_time.timezone().is_none() {
return err(
ErrorCode::Unsupported,
"the current date and time has no timezone",
);
}
Ok(Self {
implicit_timezone,
current_date_time,
})
}
pub fn from_unix_millis(implicit_timezone: i16, millis: i64) -> Result<Self> {
check_timezone(implicit_timezone)?;
Ok(Self {
implicit_timezone,
current_date_time: date_time_from_millis(millis, implicit_timezone)?,
})
}
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
pub fn system(implicit_timezone: i16) -> Result<Self> {
use std::time::{SystemTime, UNIX_EPOCH};
let millis = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(after) => i64::try_from(after.as_millis()),
Err(before) => i64::try_from(before.duration().as_millis()).map(|m| -m),
}
.map_err(|_| crate::error::Error::new(ErrorCode::Fodt0001, "system clock out of range"))?;
Self::from_unix_millis(implicit_timezone, millis)
}
#[must_use]
pub const fn implicit_timezone(&self) -> i16 {
self.implicit_timezone
}
#[must_use]
pub const fn current_date_time(&self) -> DateTime {
self.current_date_time
}
}
fn check_timezone(minutes: i16) -> Result<()> {
if (-840..=840).contains(&minutes) {
Ok(())
} else {
err(ErrorCode::Unsupported, "timezone offset out of range")
}
}
#[derive(Debug, Default)]
pub struct RegexCache {
entries: Mutex<HashMap<(String, String), Arc<XPathRegex>>>,
}
impl RegexCache {
pub const MAX_ENTRIES: usize = 1024;
#[must_use]
pub fn new() -> Self {
Self::default()
}
fn get(&self, key: &(String, String)) -> Option<Arc<XPathRegex>> {
self.entries
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(key)
.cloned()
}
fn insert(&self, key: (String, String), regex: &Arc<XPathRegex>) {
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
if entries.len() < Self::MAX_ENTRIES {
entries.entry(key).or_insert_with(|| Arc::clone(regex));
}
}
}
pub struct DynamicContext<'h> {
pub(crate) host: &'h dyn Host,
pub(crate) implicit_timezone: i16,
pub(crate) current_date_time: DateTime,
pub(crate) regex_cache: RefCell<HashMap<(String, String), Arc<XPathRegex>>>,
pub(crate) shared_regexes: Option<&'h RegexCache>,
pub(crate) stack_limit: Option<StackLimit>,
}
impl std::fmt::Debug for DynamicContext<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DynamicContext")
.field("implicit_timezone", &self.implicit_timezone)
.field("current_date_time", &self.current_date_time)
.field("stack_limit", &self.stack_limit)
.finish_non_exhaustive()
}
}
impl<'h> DynamicContext<'h> {
#[must_use]
pub fn new(host: &'h dyn Host, clock: Clock) -> Self {
Self {
host,
implicit_timezone: clock.implicit_timezone,
current_date_time: clock.current_date_time,
regex_cache: RefCell::new(HashMap::new()),
shared_regexes: None,
stack_limit: None,
}
}
#[must_use]
pub const fn with_stack_limit(mut self, limit: StackLimit) -> Self {
self.stack_limit = Some(limit);
self
}
#[must_use]
pub const fn with_regex_cache(mut self, cache: &'h RegexCache) -> Self {
self.shared_regexes = Some(cache);
self
}
pub(crate) fn check_stack(&self) -> Result<()> {
match self.stack_limit {
Some(limit) => limit.check().map_err(crate::error::Error::limit_exceeded),
None => Ok(()),
}
}
#[must_use]
pub const fn clock(&self) -> Clock {
Clock {
implicit_timezone: self.implicit_timezone,
current_date_time: self.current_date_time,
}
}
#[must_use]
pub const fn implicit_timezone(&self) -> i16 {
self.implicit_timezone
}
#[must_use]
pub const fn current_date_time(&self) -> DateTime {
self.current_date_time
}
pub(crate) fn regex(&self, pattern: &str, flags: &str) -> Result<Arc<XPathRegex>> {
let key = (pattern.to_owned(), flags.to_owned());
if let Some(regex) = self.regex_cache.borrow().get(&key) {
return Ok(Arc::clone(regex));
}
let shared = self.shared_regexes.and_then(|cache| cache.get(&key));
let regex = if let Some(regex) = shared {
regex
} else {
let regex = Arc::new(XPathRegex::new(pattern, flags)?);
if let Some(cache) = self.shared_regexes {
cache.insert(key.clone(), ®ex);
}
regex
};
self.regex_cache
.borrow_mut()
.insert(key, Arc::clone(®ex));
Ok(regex)
}
}
fn date_time_from_millis(millis: i64, offset: i16) -> Result<DateTime> {
let local = millis
.checked_add(i64::from(offset) * 60_000)
.ok_or_else(|| crate::error::Error::new(ErrorCode::Fodt0001, "instant out of range"))?;
let days = local.div_euclid(86_400_000);
let in_day = local.rem_euclid(86_400_000);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
let narrow = |v: i64| u8::try_from(v).unwrap_or(u8::MAX);
let year = i32::try_from(year)
.map_err(|_| crate::error::Error::new(ErrorCode::Fodt0001, "year out of range"))?;
let date = Date::new(year, narrow(month), narrow(day), Some(offset))?;
let seconds = in_day / 1000;
let nanos = u32::try_from((in_day % 1000) * 1_000_000).unwrap_or(0);
Ok(DateTime::new(
date,
narrow(seconds / 3600),
narrow(seconds / 60 % 60),
narrow(seconds % 60),
nanos,
)?)
}
#[derive(Debug, Clone)]
pub struct Focus {
pub item: Item,
pub position: usize,
pub size: usize,
}
#[derive(Debug, Clone, Default)]
pub struct Context {
pub focus: Option<Focus>,
pub current: Option<Item>,
}
impl Context {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn for_item(item: Item) -> Self {
Self {
focus: Some(Focus {
item: item.clone(),
position: 1,
size: 1,
}),
current: Some(item),
}
}
#[must_use]
pub fn at(item: Item, position: usize, size: usize) -> Self {
Self {
focus: Some(Focus {
item: item.clone(),
position,
size,
}),
current: Some(item),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_regex_cache_is_shared_by_contexts() {
let cache = RegexCache::new();
let ns = einvoice_xpath::NamespaceMap::new();
let expr = einvoice_xpath::parse_expr(
"matches('abc', concat('^a', 'b')) and not(matches('x', concat('[', ']')))",
&ns,
);
let expr = crate::compile(&expr.unwrap(), &SimpleStaticContext::new()).unwrap();
for _ in 0..2 {
let dc = DynamicContext::new(&NoHost, Clock::from_unix_millis(0, 0).unwrap())
.with_regex_cache(&cache);
let error = expr
.effective_boolean_value(&dc, &Context::new())
.unwrap_err();
assert_eq!(error.code(), ErrorCode::Forx0002);
assert_eq!(dc.regex_cache.borrow().len(), 1);
assert_eq!(cache.entries.lock().unwrap().len(), 1);
}
let dc = DynamicContext::new(&NoHost, Clock::from_unix_millis(0, 0).unwrap())
.with_regex_cache(&cache);
let regex = dc.regex("^ab", "").unwrap();
assert!(Arc::ptr_eq(
®ex,
cache
.get(&("^ab".to_owned(), String::new()))
.as_ref()
.unwrap()
));
}
#[test]
fn clock_conversions() {
let dt = date_time_from_millis(0, 0).unwrap();
assert_eq!(dt.to_string(), "1970-01-01T00:00:00Z");
let dt = date_time_from_millis(1_789_000_123_456, 60).unwrap();
assert_eq!(dt.to_string(), "2026-09-10T01:28:43.456+01:00");
let dt = date_time_from_millis(-1, -300).unwrap();
assert_eq!(dt.to_string(), "1969-12-31T18:59:59.999-05:00");
for (millis, offset) in [(i64::MAX, 840), (i64::MIN, -840)] {
assert_eq!(
date_time_from_millis(millis, offset).unwrap_err().code(),
ErrorCode::Fodt0001
);
}
let dt = date_time_from_millis(i64::MAX, 0).unwrap();
assert_eq!(dt.to_string(), "292278994-08-17T07:12:55.807Z");
}
}