From 589c13896f4b2d6bc3f0f996bb1d1b689e6e5cfa Mon Sep 17 00:00:00 2001 From: Michael Schimmel Date: Sun, 22 Feb 2026 08:44:49 +0100 Subject: [PATCH] Add `now()` built-in function This commit introduces the `now()` built-in function, which returns the current timestamp in milliseconds. It also includes an integration test to ensure that `now()` is not constant-folded during AST dumping, verifying its non-deterministic nature. --- src/ast/rtl/datetime.rs | 10 ++++++++++ src/integration_test.rs | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/ast/rtl/datetime.rs b/src/ast/rtl/datetime.rs index 94eb6b7..28ae86d 100644 --- a/src/ast/rtl/datetime.rs +++ b/src/ast/rtl/datetime.rs @@ -27,4 +27,14 @@ pub fn register(env: &Environment) { } Value::Void }); + + let now_ty = StaticType::Function(Box::new(Signature { + params: StaticType::Tuple(vec![]), + ret: StaticType::DateTime, + })); + + env.register_native("now", now_ty, Purity::SideEffectFree, |_| { + let ts = chrono::Utc::now().timestamp_millis(); + Value::DateTime(ts) + }); } diff --git a/src/integration_test.rs b/src/integration_test.rs index f7902b5..190e5ad 100644 --- a/src/integration_test.rs +++ b/src/integration_test.rs @@ -169,6 +169,27 @@ mod tests { assert_eq!(format!("{}", env.run_script("NaN").unwrap()), "NaN"); } + #[test] + fn test_now_function_not_folded() { + let env = Environment::new(); + let source = "(now)"; + + // 1. Check result type and value plausibility + let result = env.run_script(source).expect("Failed to run script"); + if let Value::DateTime(ts) = result { + let current = chrono::Utc::now().timestamp_millis(); + assert!(ts > 0); + assert!(ts <= current); + } else { + panic!("Expected DateTime, got {:?}", result); + } + + // 2. Verify it's NOT constant folded in the AST dump + let dump = env.dump_ast(source).expect("Failed to dump AST"); + assert!(dump.contains("Call"), "now() should remain a Call, not a Constant. Dump: \n{}", dump); + assert!(!dump.contains("Constant: #"), "now() should NOT be folded into a specific timestamp constant. Dump: \n{}", dump); + } + #[test] fn test_date_parsing() { let env = Environment::new();