logicaffeine_compile/semantics/
temporal.rs1use std::cell::Cell;
4
5use crate::interpreter::RuntimeValue;
6
7thread_local! {
8 static FIXED_CLOCK: Cell<Option<(i32, i64)>> = const { Cell::new(None) };
12}
13
14pub fn set_fixed_clock(days_since_epoch: i32, nanos_since_epoch: i64) {
16 FIXED_CLOCK.with(|c| c.set(Some((days_since_epoch, nanos_since_epoch))));
17}
18
19pub fn clear_fixed_clock() {
21 FIXED_CLOCK.with(|c| c.set(None));
22}
23
24pub fn fixed_clock() -> Option<(i32, i64)> {
28 FIXED_CLOCK.with(|c| c.get())
29}
30
31pub fn today() -> RuntimeValue {
33 if let Some((days, _)) = FIXED_CLOCK.with(|c| c.get()) {
34 return RuntimeValue::Date(days);
35 }
36 #[cfg(not(target_arch = "wasm32"))]
37 {
38 use std::time::{SystemTime, UNIX_EPOCH};
39 let duration = SystemTime::now()
40 .duration_since(UNIX_EPOCH)
41 .unwrap_or_default();
42 RuntimeValue::Date((duration.as_secs() / 86400) as i32)
43 }
44 #[cfg(target_arch = "wasm32")]
45 {
46 RuntimeValue::Date(0) }
48}
49
50pub fn now() -> RuntimeValue {
52 if let Some((_, nanos)) = FIXED_CLOCK.with(|c| c.get()) {
53 return RuntimeValue::Moment(nanos);
54 }
55 #[cfg(not(target_arch = "wasm32"))]
56 {
57 use std::time::{SystemTime, UNIX_EPOCH};
58 let duration = SystemTime::now()
59 .duration_since(UNIX_EPOCH)
60 .unwrap_or_default();
61 RuntimeValue::Moment(duration.as_nanos() as i64)
62 }
63 #[cfg(target_arch = "wasm32")]
64 {
65 RuntimeValue::Moment(0) }
67}
68
69pub use logicaffeine_base::temporal::date_add_span;
70
71pub fn moment_add_span(nanos_since_epoch: i64, months: i32, days: i32) -> i64 {
76 let dt = logicaffeine_base::temporal::civil_from_unix_nanos(nanos_since_epoch);
77 let shifted = logicaffeine_base::temporal::add_span(dt, months as i64, days as i64);
78 logicaffeine_base::temporal::unix_nanos_from_civil(shifted)
79}
80
81pub fn days_in_month(year: i32, month: i32) -> i32 {
83 match month {
84 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
85 4 | 6 | 9 | 11 => 30,
86 2 => {
87 let is_leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
88 if is_leap {
89 29
90 } else {
91 28
92 }
93 }
94 _ => 30, }
96}
97
98#[cfg(test)]
99#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/temporal/tests.rs"]
100mod tests;