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::compile::ValueType;
13use crate::error::{ErrorCode, Result, err};
14use crate::item::Item;
15use crate::tree::Node;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
19pub struct VariableId(pub u32);
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
23pub struct FunctionId(pub u32);
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub enum Cardinality {
28 AtMostOne,
30 Any,
32}
33
34#[derive(Debug, Clone)]
36pub struct VariableInfo {
37 pub id: VariableId,
39 pub cardinality: Cardinality,
42 pub value_type: ValueType,
45}
46
47pub trait StaticContext {
50 fn variable(&self, name: &QName) -> Option<VariableInfo>;
52
53 fn function(&self, name: &QName, arity: usize) -> Option<FunctionId>;
55
56 fn function_type(&self, id: FunctionId) -> ValueType {
60 let _ = id;
61 ValueType::unknown()
62 }
63
64 fn xslt_functions(&self) -> bool;
67
68 fn namespace_uri(&self, prefix: &str) -> Option<String>;
70}
71
72#[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 #[must_use]
85 pub fn new() -> Self {
86 Self::default()
87 }
88
89 #[must_use]
91 pub fn with_namespaces(mut self, namespaces: NamespaceMap) -> Self {
92 self.namespaces = namespaces;
93 self
94 }
95
96 #[must_use]
98 pub const fn with_xslt_functions(mut self) -> Self {
99 self.xslt = true;
100 self
101 }
102
103 pub fn declare_variable(&mut self, name: QName, cardinality: Cardinality) -> VariableId {
106 self.declare_typed_variable(name, cardinality, ValueType::unknown())
107 }
108
109 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 pub fn declare_function(&mut self, name: QName, arity: usize) -> FunctionId {
131 self.declare_typed_function(name, arity, ValueType::unknown())
132 }
133
134 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
180pub trait Host {
184 fn variable(&self, id: VariableId) -> Result<Rc<[Item]>>;
190
191 fn call_function(&self, id: FunctionId, args: Vec<Vec<Item>>) -> Result<Vec<Item>>;
197
198 fn document(&self, uri: &str, base: Option<&str>) -> Result<Node>;
208
209 fn system_property(&self, name: &QName) -> String;
212}
213
214#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub struct Clock {
246 implicit_timezone: i16,
247 current_date_time: DateTime,
248}
249
250impl Clock {
251 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 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 #[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 #[must_use]
307 pub const fn implicit_timezone(&self) -> i16 {
308 self.implicit_timezone
309 }
310
311 #[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
326pub 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 #[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 #[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 #[must_use]
367 pub const fn implicit_timezone(&self) -> i16 {
368 self.implicit_timezone
369 }
370
371 #[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(®ex));
384 Ok(regex)
385 }
386}
387
388fn 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 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#[derive(Debug, Clone)]
422pub struct Focus {
423 pub item: Item,
425 pub position: usize,
427 pub size: usize,
429}
430
431#[derive(Debug, Clone, Default)]
433pub struct Context {
434 pub focus: Option<Focus>,
436 pub current: Option<Item>,
438}
439
440impl Context {
441 #[must_use]
443 pub fn new() -> Self {
444 Self::default()
445 }
446
447 #[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 #[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 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}