1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct VariableId(pub u32);
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub struct FunctionId(pub u32);
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum Cardinality {
27 AtMostOne,
29 Any,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct VariableInfo {
36 pub id: VariableId,
38 pub cardinality: Cardinality,
41}
42
43pub trait StaticContext {
46 fn variable(&self, name: &QName) -> Option<VariableInfo>;
48
49 fn function(&self, name: &QName, arity: usize) -> Option<FunctionId>;
51
52 fn xslt_functions(&self) -> bool;
55
56 fn namespace_uri(&self, prefix: &str) -> Option<String>;
58}
59
60#[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 #[must_use]
73 pub fn new() -> Self {
74 Self::default()
75 }
76
77 #[must_use]
79 pub fn with_namespaces(mut self, namespaces: NamespaceMap) -> Self {
80 self.namespaces = namespaces;
81 self
82 }
83
84 #[must_use]
86 pub const fn with_xslt_functions(mut self) -> Self {
87 self.xslt = true;
88 self
89 }
90
91 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 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
133pub trait Host {
137 fn variable(&self, id: VariableId) -> Result<Rc<[Item]>>;
143
144 fn call_function(&self, id: FunctionId, args: Vec<Vec<Item>>) -> Result<Vec<Item>>;
150
151 fn document(&self, uri: &str, base: Option<&str>) -> Result<Node>;
161
162 fn system_property(&self, name: &QName) -> String;
165}
166
167#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub struct Clock {
199 implicit_timezone: i16,
200 current_date_time: DateTime,
201}
202
203impl Clock {
204 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 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 #[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 #[must_use]
260 pub const fn implicit_timezone(&self) -> i16 {
261 self.implicit_timezone
262 }
263
264 #[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
279pub 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 #[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 #[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 #[must_use]
320 pub const fn implicit_timezone(&self) -> i16 {
321 self.implicit_timezone
322 }
323
324 #[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(®ex));
337 Ok(regex)
338 }
339}
340
341fn 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 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#[derive(Debug, Clone)]
375pub struct Focus {
376 pub item: Item,
378 pub position: usize,
380 pub size: usize,
382}
383
384#[derive(Debug, Clone, Default)]
386pub struct Context {
387 pub focus: Option<Focus>,
389 pub current: Option<Item>,
391}
392
393impl Context {
394 #[must_use]
396 pub fn new() -> Self {
397 Self::default()
398 }
399
400 #[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 #[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 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}