Files
RustAst/src/ast/rtl/datetime.rs
T
Michael Schimmel cb94f20c0b Refactor native function registration and instantiation
Introduces `register_native` for direct registration of `NativeFunction`
and `register_native_fn` for convenience from closures. The
`Environment::run`
method is removed, and its functionality is now handled by
`Environment::instantiate`,
which packages the linked AST into an invokable `NativeFunction`. This
streamlines
the execution path and better separates compilation/linking from runtime
execution.
2026-02-22 11:56:46 +01:00

40 lines
1.3 KiB
Rust

use crate::ast::environment::Environment;
use crate::ast::types::{Purity, Signature, StaticType, Value};
use chrono::{NaiveDate, NaiveDateTime};
pub fn register(env: &Environment) {
let date_ty = StaticType::Function(Box::new(Signature {
params: StaticType::Tuple(vec![StaticType::Text]),
ret: StaticType::DateTime,
}));
env.register_native_fn("date", date_ty, Purity::Pure, |args| {
if let Value::Text(s) = &args[0] {
// Try parse YYYY-MM-DD
if let Ok(dt) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
let ts = dt
.and_hms_opt(0, 0, 0)
.unwrap()
.and_utc()
.timestamp_millis();
return Value::DateTime(ts);
}
// Try parse YYYY-MM-DD HH:MM:SS
if let Ok(dt) = NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
return Value::DateTime(dt.and_utc().timestamp_millis());
}
}
Value::Void
});
let now_ty = StaticType::Function(Box::new(Signature {
params: StaticType::Tuple(vec![]),
ret: StaticType::DateTime,
}));
env.register_native_fn("now", now_ty, Purity::SideEffectFree, |_| {
let ts = chrono::Utc::now().timestamp_millis();
Value::DateTime(ts)
});
}