mirror of
https://github.com/pjh456/OxideJS.git
synced 2026-10-23 18:21:13 +08:00
feat: Temporal 最小子集(Temporal.Now/Instant/PlainDate/PlainTime)
This commit is contained in:
@@ -49,5 +49,7 @@ pub mod string;
|
||||
pub mod stubs;
|
||||
/// Symbol 内置对象实现(constructor/for/keyFor/toString)。
|
||||
pub mod symbol;
|
||||
/// Temporal 内置对象实现(Now/Instant/PlainDate/PlainTime 最小子集)。
|
||||
pub mod temporal;
|
||||
/// TypedArray 内置对象实现(元素访问、fill/slice/subarray/set 等)。
|
||||
pub mod typed_array;
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
use chrono::{DateTime, Datelike, NaiveDate, SecondsFormat, Utc};
|
||||
|
||||
use oxide_kernel::shape_forge::EMPTY_SHAPE_ID;
|
||||
use oxide_runtime_api::{to_number, to_string, NativeResult, VmHost};
|
||||
use oxide_types::object::JsObject;
|
||||
use oxide_types::value::JsValue;
|
||||
|
||||
// Temporal 命名空间的最小实现子集:Temporal.Now / Temporal.Instant /
|
||||
// Temporal.PlainDate / Temporal.PlainTime。内部数据按对象类型存入 prop 槽:
|
||||
// Instant 存纪元纳秒(f64,prop 0)、PlainDate 存年/月/日(prop 0-2)、
|
||||
// PlainTime 存午夜后纳秒(f64,prop 0)。
|
||||
|
||||
macro_rules! native_try {
|
||||
($expr:expr) => {
|
||||
match $expr {
|
||||
Ok(value) => value,
|
||||
Err(err) => return NativeResult::Err(err),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn get_double_prop(obj: &JsObject, pos: usize) -> f64 {
|
||||
let v = obj.get_prop_at(pos);
|
||||
if v.is_double() {
|
||||
v.as_double()
|
||||
} else {
|
||||
f64::NAN
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_instant<H: VmHost>(vm: &mut H, obj: &JsObject) -> Result<(), JsValue> {
|
||||
if !obj.is_instant_obj() {
|
||||
return Err(crate::error::create_type_error(vm, "called on incompatible receiver"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_plain_date<H: VmHost>(vm: &mut H, obj: &JsObject) -> Result<(), JsValue> {
|
||||
if !obj.is_plain_date_obj() {
|
||||
return Err(crate::error::create_type_error(vm, "called on incompatible receiver"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_plain_time<H: VmHost>(vm: &mut H, obj: &JsObject) -> Result<(), JsValue> {
|
||||
if !obj.is_plain_time_obj() {
|
||||
return Err(crate::error::create_type_error(vm, "called on incompatible receiver"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn receiver_obj<H: VmHost>(vm: &mut H, args: &[u8]) -> Result<*mut JsObject, JsValue> {
|
||||
let raw = vm.reg(if args.is_empty() { 0 } else { args[0] });
|
||||
if !raw.is_object() {
|
||||
return Err(crate::error::create_type_error(vm, "called on incompatible receiver"));
|
||||
}
|
||||
let ptr = raw.as_js_object_ptr();
|
||||
if ptr.is_null() {
|
||||
return Err(crate::error::create_type_error(vm, "called on incompatible receiver"));
|
||||
}
|
||||
Ok(ptr)
|
||||
}
|
||||
|
||||
/// 读 receiver 是否为构造调用:`new` 时 this 的原型是相应构造器的 prototype。
|
||||
fn is_ctor_call<H: VmHost>(vm: &mut H, args: &[u8], proto_ptr: *const JsObject) -> bool {
|
||||
let this_val = vm.reg(if args.is_empty() { 0 } else { args[0] });
|
||||
if !this_val.is_object() {
|
||||
return false;
|
||||
}
|
||||
let ptr = this_val.as_js_object_ptr();
|
||||
if ptr.is_null() {
|
||||
return false;
|
||||
}
|
||||
let obj = unsafe { &*ptr };
|
||||
let this_proto = obj.proto().as_js_object_ptr();
|
||||
!this_proto.is_null() && std::ptr::eq(this_proto, proto_ptr)
|
||||
}
|
||||
|
||||
fn make_instant<H: VmHost>(vm: &mut H, epoch_ns: i128) -> NativeResult {
|
||||
let proto = JsValue::from_js_object(vm.session().builtin_world().instant_proto.as_ptr() as *mut JsObject);
|
||||
let mut obj = JsObject::new_empty(EMPTY_SHAPE_ID, proto);
|
||||
obj.type_tag = JsObject::OBJ_TYPE_INSTANT;
|
||||
obj.set_prop_at(0, JsValue::float(epoch_ns as f64));
|
||||
NativeResult::Ok(JsValue::from_js_object(vm.alloc_object(obj)))
|
||||
}
|
||||
|
||||
/// 把 epoch 纳秒拆成秒 + 亚秒纳秒(供 chrono 时间转换)。
|
||||
fn ns_to_datetime(epoch_ns: f64) -> Option<DateTime<Utc>> {
|
||||
if !epoch_ns.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let secs = (epoch_ns / 1e9).trunc() as i64;
|
||||
let sub_ns = (epoch_ns - (epoch_ns / 1e9).trunc() * 1e9).round() as u32;
|
||||
DateTime::from_timestamp(secs, sub_ns)
|
||||
}
|
||||
|
||||
/// 解析 `YYYY-MM-DDTHH:MM:SS[.fff](Z|±HH:MM)` 形式的 ISO 字符串到纪元纳秒。
|
||||
fn parse_instant_string(s: &str) -> Option<i128> {
|
||||
let t = s.trim();
|
||||
let dt = DateTime::parse_from_rfc3339(t).ok()?;
|
||||
let utc = dt.with_timezone(&Utc);
|
||||
Some(utc.timestamp() as i128 * 1_000_000_000 + utc.timestamp_subsec_nanos() as i128)
|
||||
}
|
||||
|
||||
/// `Temporal.Now.instant()`:返回当前时刻的 Temporal.Instant。
|
||||
pub fn now_instant<H: VmHost>(vm: &mut H, _args: &[u8]) -> NativeResult {
|
||||
let now = Utc::now();
|
||||
let epoch_ns = now.timestamp() as i128 * 1_000_000_000 + now.timestamp_subsec_nanos() as i128;
|
||||
make_instant(vm, epoch_ns)
|
||||
}
|
||||
|
||||
/// `Temporal.Now.timeZoneId()`:引擎固定使用 UTC。
|
||||
pub fn now_time_zone_id<H: VmHost>(vm: &mut H, _args: &[u8]) -> NativeResult {
|
||||
NativeResult::Ok(vm.new_string("UTC"))
|
||||
}
|
||||
|
||||
/// `Temporal.Instant` 构造器:接受一个数值(纪元纳秒,BigInt 未实现故按 number 处理)。
|
||||
pub fn instant_constructor<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let ctor_proto = vm.session().builtin_world().instant_proto.as_ptr();
|
||||
if !is_ctor_call(vm, args, ctor_proto) {
|
||||
return NativeResult::Err(crate::error::create_type_error(
|
||||
vm,
|
||||
"Class constructor Temporal.Instant cannot be invoked without 'new'",
|
||||
));
|
||||
}
|
||||
let epoch_ns = if args.len() < 2 {
|
||||
0.0
|
||||
} else {
|
||||
to_number(vm.reg(args[1]))
|
||||
};
|
||||
make_instant(vm, epoch_ns as i128)
|
||||
}
|
||||
|
||||
/// `Temporal.Instant.from(value)`:接受 ISO 字符串、数值(纪元纳秒)或
|
||||
/// 带 `epochMilliseconds`/`epochNanoseconds` 数值字段的对象。
|
||||
pub fn instant_from<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let val = if args.len() < 2 { JsValue::undefined() } else { vm.reg(args[1]) };
|
||||
let epoch_ns = if val.is_string() {
|
||||
let s = to_string(val);
|
||||
match parse_instant_string(&s) {
|
||||
Some(ns) => ns,
|
||||
None => {
|
||||
return NativeResult::Err(crate::error::create_range_error(vm, "invalid ISO 8601 string"));
|
||||
}
|
||||
}
|
||||
} else if val.is_int() || val.is_double() {
|
||||
to_number(val) as i128
|
||||
} else if val.is_object() && {
|
||||
let ptr = val.as_js_object_ptr();
|
||||
!ptr.is_null() && unsafe { &*ptr }.is_instant_obj()
|
||||
} {
|
||||
let obj = unsafe { &*val.as_js_object_ptr() };
|
||||
get_double_prop(obj, 0) as i128
|
||||
} else if val.is_object() {
|
||||
let obj = unsafe { &*val.as_js_object_ptr() };
|
||||
let obj_val = val;
|
||||
let ms = read_prop_number(vm, obj, obj_val, "epochMilliseconds");
|
||||
let ns = read_prop_number(vm, obj, obj_val, "epochNanoseconds");
|
||||
if !ns.is_nan() {
|
||||
ns as i128
|
||||
} else if !ms.is_nan() {
|
||||
(ms * 1e6) as i128
|
||||
} else {
|
||||
return NativeResult::Err(crate::error::create_type_error(vm, "cannot convert object to Instant"));
|
||||
}
|
||||
} else {
|
||||
return NativeResult::Err(crate::error::create_type_error(vm, "cannot convert value to Instant"));
|
||||
};
|
||||
make_instant(vm, epoch_ns)
|
||||
}
|
||||
|
||||
/// 读对象的数值字段(普通对象访问器 getter 路径)。
|
||||
fn read_prop_number<H: VmHost>(vm: &mut H, obj: &JsObject, receiver: JsValue, name: &str) -> f64 {
|
||||
let key_val = vm.new_string(name);
|
||||
let si = vm.property_key_si(key_val);
|
||||
vm.ordinary_get(obj, si, receiver).map(to_number).unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
/// `Temporal.Instant.prototype.epochSeconds` getter。
|
||||
pub fn instant_epoch_seconds<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let ptr = native_try!(receiver_obj(vm, args));
|
||||
let obj = unsafe { &*ptr };
|
||||
native_try!(ensure_instant(vm, obj));
|
||||
NativeResult::Ok(JsValue::float((get_double_prop(obj, 0) / 1e9).trunc()))
|
||||
}
|
||||
|
||||
/// `Temporal.Instant.prototype.epochMilliseconds` getter。
|
||||
pub fn instant_epoch_milliseconds<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let ptr = native_try!(receiver_obj(vm, args));
|
||||
let obj = unsafe { &*ptr };
|
||||
native_try!(ensure_instant(vm, obj));
|
||||
NativeResult::Ok(JsValue::float((get_double_prop(obj, 0) / 1e6).trunc()))
|
||||
}
|
||||
|
||||
/// `Temporal.Instant.prototype.epochMicroseconds` getter。
|
||||
pub fn instant_epoch_microseconds<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let ptr = native_try!(receiver_obj(vm, args));
|
||||
let obj = unsafe { &*ptr };
|
||||
native_try!(ensure_instant(vm, obj));
|
||||
NativeResult::Ok(JsValue::float((get_double_prop(obj, 0) / 1e3).trunc()))
|
||||
}
|
||||
|
||||
/// `Temporal.Instant.prototype.epochNanoseconds` getter:BigInt 未实现,返回 number 近似。
|
||||
pub fn instant_epoch_nanoseconds<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let ptr = native_try!(receiver_obj(vm, args));
|
||||
let obj = unsafe { &*ptr };
|
||||
native_try!(ensure_instant(vm, obj));
|
||||
NativeResult::Ok(JsValue::float(get_double_prop(obj, 0)))
|
||||
}
|
||||
|
||||
/// `Temporal.Instant.prototype.toString()`:输出 ISO 8601 UTC(如 `2024-01-01T00:00:00Z`)。
|
||||
pub fn instant_to_string<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let ptr = native_try!(receiver_obj(vm, args));
|
||||
let obj = unsafe { &*ptr };
|
||||
native_try!(ensure_instant(vm, obj));
|
||||
match ns_to_datetime(get_double_prop(obj, 0)) {
|
||||
Some(dt) => {
|
||||
let s = dt.to_rfc3339_opts(SecondsFormat::AutoSi, true);
|
||||
NativeResult::Ok(vm.new_string(&s))
|
||||
}
|
||||
None => NativeResult::Err(crate::error::create_range_error(vm, "invalid Instant")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `Temporal.Instant.prototype.valueOf()`:Temporal 对象禁止转原始值。
|
||||
pub fn instant_value_of<H: VmHost>(vm: &mut H, _args: &[u8]) -> NativeResult {
|
||||
NativeResult::Err(crate::error::create_type_error(vm, "Temporal.Instant has no valueOf"))
|
||||
}
|
||||
|
||||
fn make_plain_date<H: VmHost>(vm: &mut H, year: i32, month: u32, day: u32) -> NativeResult {
|
||||
let proto =
|
||||
JsValue::from_js_object(vm.session().builtin_world().plain_date_proto.as_ptr() as *mut JsObject);
|
||||
let mut obj = JsObject::new_empty(EMPTY_SHAPE_ID, proto);
|
||||
obj.type_tag = JsObject::OBJ_TYPE_PLAIN_DATE;
|
||||
obj.set_prop_at(0, JsValue::float(year as f64));
|
||||
obj.set_prop_at(1, JsValue::float(month as f64));
|
||||
obj.set_prop_at(2, JsValue::float(day as f64));
|
||||
NativeResult::Ok(JsValue::from_js_object(vm.alloc_object(obj)))
|
||||
}
|
||||
|
||||
/// 校验 ISO 日期分量(month 1-12、day 按月份与闰年)。
|
||||
fn valid_iso_date(year: i32, month: u32, day: u32) -> bool {
|
||||
NaiveDate::from_ymd_opt(year, month, day).is_some()
|
||||
}
|
||||
|
||||
fn parse_plain_date_string(s: &str) -> Option<(i32, u32, u32)> {
|
||||
let t = s.trim();
|
||||
NaiveDate::parse_from_str(t, "%Y-%m-%d").ok().map(|d| {
|
||||
let (y, m, day) = (d.year(), d.month(), d.day());
|
||||
(y, m, day)
|
||||
})
|
||||
}
|
||||
|
||||
/// `Temporal.PlainDate` 构造器:`new PlainDate(year, month, day)`。
|
||||
pub fn plain_date_constructor<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let ctor_proto = vm.session().builtin_world().plain_date_proto.as_ptr();
|
||||
if !is_ctor_call(vm, args, ctor_proto) {
|
||||
return NativeResult::Err(crate::error::create_type_error(
|
||||
vm,
|
||||
"Class constructor Temporal.PlainDate cannot be invoked without 'new'",
|
||||
));
|
||||
}
|
||||
let year = if args.len() > 1 { to_number(vm.reg(args[1])).trunc() as i32 } else { 0 };
|
||||
let month = if args.len() > 2 { to_number(vm.reg(args[2])).trunc() as u32 } else { 1 };
|
||||
let day = if args.len() > 3 { to_number(vm.reg(args[3])).trunc() as u32 } else { 1 };
|
||||
if !valid_iso_date(year, month, day) {
|
||||
return NativeResult::Err(crate::error::create_range_error(vm, "invalid ISO date"));
|
||||
}
|
||||
make_plain_date(vm, year, month, day)
|
||||
}
|
||||
|
||||
/// `Temporal.PlainDate.from(value)`:接受 `YYYY-MM-DD` 字符串或 `{year, month, day}` 对象。
|
||||
pub fn plain_date_from<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let val = if args.len() < 2 { JsValue::undefined() } else { vm.reg(args[1]) };
|
||||
let (year, month, day) = if val.is_string() {
|
||||
let s = to_string(val);
|
||||
match parse_plain_date_string(&s) {
|
||||
Some(ymd) => ymd,
|
||||
None => {
|
||||
return NativeResult::Err(crate::error::create_range_error(vm, "invalid ISO 8601 date"));
|
||||
}
|
||||
}
|
||||
} else if val.is_object() && {
|
||||
let ptr = val.as_js_object_ptr();
|
||||
!ptr.is_null() && unsafe { &*ptr }.is_plain_date_obj()
|
||||
} {
|
||||
let obj = unsafe { &*val.as_js_object_ptr() };
|
||||
(
|
||||
get_double_prop(obj, 0) as i32,
|
||||
get_double_prop(obj, 1) as u32,
|
||||
get_double_prop(obj, 2) as u32,
|
||||
)
|
||||
} else if val.is_object() {
|
||||
let obj = unsafe { &*val.as_js_object_ptr() };
|
||||
let y = read_prop_number(vm, obj, val, "year");
|
||||
let m = read_prop_number(vm, obj, val, "month");
|
||||
let d = read_prop_number(vm, obj, val, "day");
|
||||
if y.is_nan() || m.is_nan() || d.is_nan() {
|
||||
return NativeResult::Err(crate::error::create_type_error(vm, "cannot convert object to PlainDate"));
|
||||
}
|
||||
(y.trunc() as i32, m.trunc() as u32, d.trunc() as u32)
|
||||
} else {
|
||||
return NativeResult::Err(crate::error::create_type_error(vm, "cannot convert value to PlainDate"));
|
||||
};
|
||||
if !valid_iso_date(year, month, day) {
|
||||
return NativeResult::Err(crate::error::create_range_error(vm, "invalid ISO date"));
|
||||
}
|
||||
make_plain_date(vm, year, month, day)
|
||||
}
|
||||
|
||||
fn plain_date_ymd<H: VmHost>(vm: &mut H, args: &[u8]) -> Result<(f64, f64, f64), JsValue> {
|
||||
let ptr = receiver_obj(vm, args)?;
|
||||
let obj = unsafe { &*ptr };
|
||||
ensure_plain_date(vm, obj)?;
|
||||
Ok((
|
||||
get_double_prop(obj, 0),
|
||||
get_double_prop(obj, 1),
|
||||
get_double_prop(obj, 2),
|
||||
))
|
||||
}
|
||||
|
||||
/// `Temporal.PlainDate.prototype.year` getter。
|
||||
pub fn plain_date_year<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let (y, _, _) = native_try!(plain_date_ymd(vm, args));
|
||||
NativeResult::Ok(JsValue::float(y))
|
||||
}
|
||||
|
||||
/// `Temporal.PlainDate.prototype.month` getter。
|
||||
pub fn plain_date_month<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let (_, m, _) = native_try!(plain_date_ymd(vm, args));
|
||||
NativeResult::Ok(JsValue::float(m))
|
||||
}
|
||||
|
||||
/// `Temporal.PlainDate.prototype.day` getter。
|
||||
pub fn plain_date_day<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let (_, _, d) = native_try!(plain_date_ymd(vm, args));
|
||||
NativeResult::Ok(JsValue::float(d))
|
||||
}
|
||||
|
||||
/// `Temporal.PlainDate.prototype.toString()`:输出 `YYYY-MM-DD`。
|
||||
pub fn plain_date_to_string<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let ptr = native_try!(receiver_obj(vm, args));
|
||||
let obj = unsafe { &*ptr };
|
||||
native_try!(ensure_plain_date(vm, obj));
|
||||
let year = get_double_prop(obj, 0) as i32;
|
||||
let month = get_double_prop(obj, 1) as u32;
|
||||
let day = get_double_prop(obj, 2) as u32;
|
||||
NativeResult::Ok(vm.new_string(&format!("{year:04}-{month:02}-{day:02}")))
|
||||
}
|
||||
|
||||
fn make_plain_time<H: VmHost>(vm: &mut H, hour: u32, minute: u32, second: u32, ms: u32, us: u32, ns: u32) -> NativeResult {
|
||||
let total_ns = hour as f64 * 3.6e12 + minute as f64 * 6e10 + second as f64 * 1e9 + ms as f64 * 1e6 + us as f64 * 1e3 + ns as f64;
|
||||
let proto =
|
||||
JsValue::from_js_object(vm.session().builtin_world().plain_time_proto.as_ptr() as *mut JsObject);
|
||||
let mut obj = JsObject::new_empty(EMPTY_SHAPE_ID, proto);
|
||||
obj.type_tag = JsObject::OBJ_TYPE_PLAIN_TIME;
|
||||
obj.set_prop_at(0, JsValue::float(total_ns));
|
||||
NativeResult::Ok(JsValue::from_js_object(vm.alloc_object(obj)))
|
||||
}
|
||||
|
||||
fn valid_plain_time(hour: u32, minute: u32, second: u32, ms: u32, us: u32, ns: u32) -> bool {
|
||||
hour <= 23 && minute <= 59 && second <= 59 && ms <= 999 && us <= 999 && ns <= 999
|
||||
}
|
||||
|
||||
/// `Temporal.PlainTime` 构造器:`new PlainTime(h, m, s, ms, us, ns)`,缺省为 0。
|
||||
pub fn plain_time_constructor<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let ctor_proto = vm.session().builtin_world().plain_time_proto.as_ptr();
|
||||
if !is_ctor_call(vm, args, ctor_proto) {
|
||||
return NativeResult::Err(crate::error::create_type_error(
|
||||
vm,
|
||||
"Class constructor Temporal.PlainTime cannot be invoked without 'new'",
|
||||
));
|
||||
}
|
||||
let get = |i: usize, default: f64| -> f64 {
|
||||
if args.len() > i {
|
||||
to_number(vm.reg(args[i])).trunc()
|
||||
} else {
|
||||
default
|
||||
}
|
||||
};
|
||||
let hour = get(1, 0.0) as u32;
|
||||
let minute = get(2, 0.0) as u32;
|
||||
let second = get(3, 0.0) as u32;
|
||||
let ms = get(4, 0.0) as u32;
|
||||
let us = get(5, 0.0) as u32;
|
||||
let ns = get(6, 0.0) as u32;
|
||||
if !valid_plain_time(hour, minute, second, ms, us, ns) {
|
||||
return NativeResult::Err(crate::error::create_range_error(vm, "invalid time component"));
|
||||
}
|
||||
make_plain_time(vm, hour, minute, second, ms, us, ns)
|
||||
}
|
||||
|
||||
/// 拆解午夜后纳秒为各分量。
|
||||
fn plain_time_components(total_ns: f64) -> (u32, u32, u32, u32, u32, u32) {
|
||||
let total = total_ns as u64;
|
||||
let ns = total % 1_000;
|
||||
let us = total / 1_000 % 1_000;
|
||||
let ms = total / 1_000_000 % 1_000;
|
||||
let second = total / 1_000_000_000 % 60;
|
||||
let minute = total / 60_000_000_000 % 60;
|
||||
let hour = total / 3_600_000_000_000 % 24;
|
||||
(hour as u32, minute as u32, second as u32, ms as u32, us as u32, ns as u32)
|
||||
}
|
||||
|
||||
fn plain_time_get<H: VmHost>(vm: &mut H, args: &[u8], select: fn(u32, u32, u32, u32, u32, u32) -> u32) -> NativeResult {
|
||||
let ptr = match receiver_obj(vm, args) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return NativeResult::Err(e),
|
||||
};
|
||||
let obj = unsafe { &*ptr };
|
||||
if let Err(e) = ensure_plain_time(vm, obj) {
|
||||
return NativeResult::Err(e);
|
||||
}
|
||||
let (h, m, s, ms, us, ns) = plain_time_components(get_double_prop(obj, 0));
|
||||
NativeResult::Ok(JsValue::float(select(h, m, s, ms, us, ns) as f64))
|
||||
}
|
||||
|
||||
/// `Temporal.PlainTime.prototype.hour` getter。
|
||||
pub fn plain_time_hour<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
plain_time_get(vm, args, |h, _, _, _, _, _| h)
|
||||
}
|
||||
|
||||
/// `Temporal.PlainTime.prototype.minute` getter。
|
||||
pub fn plain_time_minute<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
plain_time_get(vm, args, |_, m, _, _, _, _| m)
|
||||
}
|
||||
|
||||
/// `Temporal.PlainTime.prototype.second` getter。
|
||||
pub fn plain_time_second<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
plain_time_get(vm, args, |_, _, s, _, _, _| s)
|
||||
}
|
||||
|
||||
/// `Temporal.PlainTime.prototype.millisecond` getter。
|
||||
pub fn plain_time_millisecond<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
plain_time_get(vm, args, |_, _, _, ms, _, _| ms)
|
||||
}
|
||||
|
||||
/// `Temporal.PlainTime.prototype.microsecond` getter。
|
||||
pub fn plain_time_microsecond<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
plain_time_get(vm, args, |_, _, _, _, us, _| us)
|
||||
}
|
||||
|
||||
/// `Temporal.PlainTime.prototype.nanosecond` getter。
|
||||
pub fn plain_time_nanosecond<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
plain_time_get(vm, args, |_, _, _, _, _, ns| ns)
|
||||
}
|
||||
|
||||
/// `Temporal.PlainTime.prototype.toString()`:`HH:MM:SS`,亚秒部分按需输出。
|
||||
pub fn plain_time_to_string<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let ptr = native_try!(receiver_obj(vm, args));
|
||||
let obj = unsafe { &*ptr };
|
||||
native_try!(ensure_plain_time(vm, obj));
|
||||
let (h, m, s, ms, us, ns) = plain_time_components(get_double_prop(obj, 0));
|
||||
let frac = ms as u64 * 1_000_000 + us as u64 * 1_000 + ns as u64;
|
||||
if frac == 0 {
|
||||
NativeResult::Ok(vm.new_string(&format!("{h:02}:{m:02}:{s:02}")))
|
||||
} else {
|
||||
let mut digits = format!("{frac:09}");
|
||||
while digits.ends_with('0') {
|
||||
digits.pop();
|
||||
}
|
||||
NativeResult::Ok(vm.new_string(&format!("{h:02}:{m:02}:{s:02}.{digits}")))
|
||||
}
|
||||
}
|
||||
@@ -243,6 +243,14 @@ pub struct BuiltinWorld {
|
||||
pub sym_has_instance: P<JsObject>,
|
||||
pub sym_match_all: P<JsObject>,
|
||||
pub sym_async_iterator: P<JsObject>,
|
||||
pub temporal_object: P<JsObject>,
|
||||
pub temporal_now_object: P<JsObject>,
|
||||
pub instant_constructor: P<JsObject>,
|
||||
pub instant_proto: P<JsObject>,
|
||||
pub plain_date_constructor: P<JsObject>,
|
||||
pub plain_date_proto: P<JsObject>,
|
||||
pub plain_time_constructor: P<JsObject>,
|
||||
pub plain_time_proto: P<JsObject>,
|
||||
pub stub_objects: Vec<P<JsObject>>,
|
||||
}
|
||||
|
||||
@@ -491,9 +499,12 @@ fn wire_builtin_world_links(world: &BuiltinWorld) {
|
||||
wire_ctor_proto(&world.float64array_constructor, &world.float64array_proto);
|
||||
wire_ctor_proto(&world.bigint64array_constructor, &world.bigint64array_proto);
|
||||
wire_ctor_proto(&world.biguint64array_constructor, &world.biguint64array_proto);
|
||||
wire_ctor_proto(&world.instant_constructor, &world.instant_proto);
|
||||
wire_ctor_proto(&world.plain_date_constructor, &world.plain_date_proto);
|
||||
wire_ctor_proto(&world.plain_time_constructor, &world.plain_time_proto);
|
||||
|
||||
let obj_proto_val = JsValue::from_js_object(world.object_proto.as_ptr() as *mut JsObject);
|
||||
let non_object_protos: [&P<JsObject>; 14] = [
|
||||
let non_object_protos: [&P<JsObject>; 17] = [
|
||||
&world.array_proto,
|
||||
&world.function_proto,
|
||||
&world.string_proto,
|
||||
@@ -508,11 +519,18 @@ fn wire_builtin_world_links(world: &BuiltinWorld) {
|
||||
&world.array_buffer_proto,
|
||||
&world.data_view_proto,
|
||||
&world.typed_array_proto,
|
||||
&world.instant_proto,
|
||||
&world.plain_date_proto,
|
||||
&world.plain_time_proto,
|
||||
];
|
||||
for proto in &non_object_protos {
|
||||
set_proto_if_changed(proto, obj_proto_val);
|
||||
}
|
||||
|
||||
// Temporal 命名空间对象(非构造器)继承 Object.prototype。
|
||||
set_proto_if_changed(&world.temporal_object, obj_proto_val);
|
||||
set_proto_if_changed(&world.temporal_now_object, obj_proto_val);
|
||||
|
||||
let typed_array_proto_val = JsValue::from_js_object(world.typed_array_proto.as_ptr() as *mut JsObject);
|
||||
let typed_array_protos: [&P<JsObject>; 11] = [
|
||||
&world.int8array_proto,
|
||||
@@ -630,6 +648,14 @@ impl BuiltinWorld {
|
||||
BuiltinId::SymHasInstance => &self.sym_has_instance,
|
||||
BuiltinId::SymMatchAll => &self.sym_match_all,
|
||||
BuiltinId::SymAsyncIterator => &self.sym_async_iterator,
|
||||
BuiltinId::TemporalObject => &self.temporal_object,
|
||||
BuiltinId::TemporalNowObject => &self.temporal_now_object,
|
||||
BuiltinId::InstantConstructor => &self.instant_constructor,
|
||||
BuiltinId::InstantProto => &self.instant_proto,
|
||||
BuiltinId::PlainDateConstructor => &self.plain_date_constructor,
|
||||
BuiltinId::PlainDateProto => &self.plain_date_proto,
|
||||
BuiltinId::PlainTimeConstructor => &self.plain_time_constructor,
|
||||
BuiltinId::PlainTimeProto => &self.plain_time_proto,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -671,6 +697,13 @@ impl BuiltinWorld {
|
||||
let sym_has_instance = P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null()));
|
||||
let sym_match_all = P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null()));
|
||||
let sym_async_iterator = P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null()));
|
||||
let temporal_object = P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null()));
|
||||
let temporal_now_object = P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null()));
|
||||
let (instant_proto, instant_constructor) = make_named_pair(string_forge, shape_forge, labels, "Instant");
|
||||
let (plain_date_proto, plain_date_constructor) =
|
||||
make_named_pair(string_forge, shape_forge, labels, "PlainDate");
|
||||
let (plain_time_proto, plain_time_constructor) =
|
||||
make_named_pair(string_forge, shape_forge, labels, "PlainTime");
|
||||
let stub_objects = Vec::new();
|
||||
|
||||
let world = Self {
|
||||
@@ -743,6 +776,14 @@ impl BuiltinWorld {
|
||||
sym_has_instance,
|
||||
sym_match_all,
|
||||
sym_async_iterator,
|
||||
temporal_object,
|
||||
temporal_now_object,
|
||||
instant_constructor,
|
||||
instant_proto,
|
||||
plain_date_constructor,
|
||||
plain_date_proto,
|
||||
plain_time_constructor,
|
||||
plain_time_proto,
|
||||
stub_objects,
|
||||
};
|
||||
wire_builtin_world_links(&world);
|
||||
@@ -917,6 +958,35 @@ impl BuiltinWorld {
|
||||
biguint64array_proto: current.biguint64array_proto.clone(),
|
||||
}
|
||||
};
|
||||
let (temporal_object, temporal_now_object, instant_proto, instant_constructor, plain_date_proto, plain_date_constructor, plain_time_proto, plain_time_constructor) = if dirty.temporal {
|
||||
let (instant_proto, instant_constructor) =
|
||||
make_named_pair(string_forge, shape_forge, labels, "Instant");
|
||||
let (plain_date_proto, plain_date_constructor) =
|
||||
make_named_pair(string_forge, shape_forge, labels, "PlainDate");
|
||||
let (plain_time_proto, plain_time_constructor) =
|
||||
make_named_pair(string_forge, shape_forge, labels, "PlainTime");
|
||||
(
|
||||
P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null())),
|
||||
P::new(JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::null())),
|
||||
instant_proto,
|
||||
instant_constructor,
|
||||
plain_date_proto,
|
||||
plain_date_constructor,
|
||||
plain_time_proto,
|
||||
plain_time_constructor,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
current.temporal_object.clone(),
|
||||
current.temporal_now_object.clone(),
|
||||
current.instant_proto.clone(),
|
||||
current.instant_constructor.clone(),
|
||||
current.plain_date_proto.clone(),
|
||||
current.plain_date_constructor.clone(),
|
||||
current.plain_time_proto.clone(),
|
||||
current.plain_time_constructor.clone(),
|
||||
)
|
||||
};
|
||||
let stub_objects = if dirty.stubs { Vec::new() } else { current.stub_objects.clone() };
|
||||
|
||||
let world = BuiltinWorld {
|
||||
@@ -989,6 +1059,14 @@ impl BuiltinWorld {
|
||||
sym_has_instance,
|
||||
sym_match_all,
|
||||
sym_async_iterator,
|
||||
temporal_object,
|
||||
temporal_now_object,
|
||||
instant_constructor,
|
||||
instant_proto,
|
||||
plain_date_constructor,
|
||||
plain_date_proto,
|
||||
plain_time_constructor,
|
||||
plain_time_proto,
|
||||
stub_objects,
|
||||
};
|
||||
wire_builtin_world_links(&world);
|
||||
|
||||
@@ -225,7 +225,7 @@ pub struct KernelSession {
|
||||
/// 维护注意:每个新增的 `BuiltinWorld` 对象字段都必须加到这里以及
|
||||
/// `KernelSession::dirty_since_snapshot()`,以便选择性重置重建正确的
|
||||
/// builtin 家族。
|
||||
pub const NUM_BUILTINS: usize = 68;
|
||||
pub const NUM_BUILTINS: usize = 76;
|
||||
|
||||
/// 内置对象枚举 id,与 `BuiltinWorld` 中的存储槽一一对应。
|
||||
///
|
||||
@@ -302,6 +302,14 @@ pub enum BuiltinId {
|
||||
SymHasInstance = 65,
|
||||
SymMatchAll = 66,
|
||||
SymAsyncIterator = 67,
|
||||
TemporalObject = 68,
|
||||
TemporalNowObject = 69,
|
||||
InstantConstructor = 70,
|
||||
InstantProto = 71,
|
||||
PlainDateConstructor = 72,
|
||||
PlainDateProto = 73,
|
||||
PlainTimeConstructor = 74,
|
||||
PlainTimeProto = 75,
|
||||
}
|
||||
|
||||
impl BuiltinId {
|
||||
@@ -375,6 +383,14 @@ impl BuiltinId {
|
||||
BuiltinId::SymHasInstance,
|
||||
BuiltinId::SymMatchAll,
|
||||
BuiltinId::SymAsyncIterator,
|
||||
BuiltinId::TemporalObject,
|
||||
BuiltinId::TemporalNowObject,
|
||||
BuiltinId::InstantConstructor,
|
||||
BuiltinId::InstantProto,
|
||||
BuiltinId::PlainDateConstructor,
|
||||
BuiltinId::PlainDateProto,
|
||||
BuiltinId::PlainTimeConstructor,
|
||||
BuiltinId::PlainTimeProto,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -432,6 +448,7 @@ pub struct BuiltinDirtySet {
|
||||
pub array_buffer: bool,
|
||||
pub data_view: bool,
|
||||
pub typed_array_family: bool,
|
||||
pub temporal: bool,
|
||||
pub stubs: bool,
|
||||
pub global: bool,
|
||||
}
|
||||
@@ -456,6 +473,7 @@ impl BuiltinDirtySet {
|
||||
|| self.array_buffer
|
||||
|| self.data_view
|
||||
|| self.typed_array_family
|
||||
|| self.temporal
|
||||
|| self.stubs
|
||||
}
|
||||
|
||||
@@ -598,6 +616,14 @@ impl KernelSession {
|
||||
|| gen(BuiltinId::BigInt64ArrayProto) != snap(BuiltinId::BigInt64ArrayProto)
|
||||
|| gen(BuiltinId::BigUint64ArrayConstructor) != snap(BuiltinId::BigUint64ArrayConstructor)
|
||||
|| gen(BuiltinId::BigUint64ArrayProto) != snap(BuiltinId::BigUint64ArrayProto),
|
||||
temporal: gen(BuiltinId::TemporalObject) != snap(BuiltinId::TemporalObject)
|
||||
|| gen(BuiltinId::TemporalNowObject) != snap(BuiltinId::TemporalNowObject)
|
||||
|| gen(BuiltinId::InstantConstructor) != snap(BuiltinId::InstantConstructor)
|
||||
|| gen(BuiltinId::InstantProto) != snap(BuiltinId::InstantProto)
|
||||
|| gen(BuiltinId::PlainDateConstructor) != snap(BuiltinId::PlainDateConstructor)
|
||||
|| gen(BuiltinId::PlainDateProto) != snap(BuiltinId::PlainDateProto)
|
||||
|| gen(BuiltinId::PlainTimeConstructor) != snap(BuiltinId::PlainTimeConstructor)
|
||||
|| gen(BuiltinId::PlainTimeProto) != snap(BuiltinId::PlainTimeProto),
|
||||
stubs: world.stub_objects.len() != snapshot.stub_objects_len || stub_generations_dirty,
|
||||
global: BuiltinSnapshot::gen(&self.global_object) != snapshot.global_object_generation,
|
||||
}
|
||||
|
||||
@@ -437,6 +437,12 @@ impl JsObject {
|
||||
/// 异步生成器迭代器对象(`async function*` 调用返回):`AsyncGeneratorState`
|
||||
/// 快照存于 `native_data`。
|
||||
pub const OBJ_TYPE_ASYNC_GENERATOR: u8 = 13;
|
||||
/// Temporal.Instant 对象:纪元纳秒存于 prop 0。
|
||||
pub const OBJ_TYPE_INSTANT: u8 = 14;
|
||||
/// Temporal.PlainDate 对象:ISO 年/月/日存于 prop 0-2。
|
||||
pub const OBJ_TYPE_PLAIN_DATE: u8 = 15;
|
||||
/// Temporal.PlainTime 对象:午夜后纳秒存于 prop 0。
|
||||
pub const OBJ_TYPE_PLAIN_TIME: u8 = 16;
|
||||
/// `is_session_epoch` 字段中的 session 标记位。
|
||||
pub const SESSION_EPOCH_BIT: u8 = 0x01;
|
||||
/// `is_session_epoch` 字段中的 GC 标记位。
|
||||
@@ -502,6 +508,21 @@ impl JsObject {
|
||||
pub fn is_async_generator_obj(&self) -> bool {
|
||||
self.type_tag == Self::OBJ_TYPE_ASYNC_GENERATOR
|
||||
}
|
||||
/// 是否 Temporal.Instant 对象。
|
||||
#[inline]
|
||||
pub fn is_instant_obj(&self) -> bool {
|
||||
self.type_tag == Self::OBJ_TYPE_INSTANT
|
||||
}
|
||||
/// 是否 Temporal.PlainDate 对象。
|
||||
#[inline]
|
||||
pub fn is_plain_date_obj(&self) -> bool {
|
||||
self.type_tag == Self::OBJ_TYPE_PLAIN_DATE
|
||||
}
|
||||
/// 是否 Temporal.PlainTime 对象。
|
||||
#[inline]
|
||||
pub fn is_plain_time_obj(&self) -> bool {
|
||||
self.type_tag == Self::OBJ_TYPE_PLAIN_TIME
|
||||
}
|
||||
|
||||
/// 构造无属性、可扩展的空对象(`new Object()` 的基础对象)。
|
||||
pub fn new_empty(shape_id: ShapeId, proto: JsValue) -> Self {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::bindings::{apply_binding_table, bind_accessor_getter, bind_global_value, configure_native_constructor};
|
||||
use oxide_kernel::kernel::{KernelCore, KernelSession};
|
||||
use oxide_types::object::JsObject;
|
||||
use oxide_types::value::JsValue;
|
||||
|
||||
/// 把 Temporal 命名空间及其 Now/Instant/PlainDate/PlainTime 子对象绑定到 global。
|
||||
pub fn bind_temporal(core: &Arc<KernelCore>, session: &KernelSession, global: &mut JsObject) {
|
||||
let world = session.builtin_world();
|
||||
let temporal_ptr = world.temporal_object.as_ptr() as *mut JsObject;
|
||||
let temporal = unsafe { &mut *temporal_ptr };
|
||||
|
||||
// Temporal.Now:非构造器命名空间,方法直接绑定。
|
||||
let now_ptr = world.temporal_now_object.as_ptr() as *mut JsObject;
|
||||
let now = unsafe { &mut *now_ptr };
|
||||
apply_binding_table(
|
||||
world,
|
||||
now,
|
||||
core,
|
||||
&[
|
||||
("instant", oxide_builtins::temporal::now_instant::<crate::vm::Vm> as *const (), 0),
|
||||
(
|
||||
"timeZoneId",
|
||||
oxide_builtins::temporal::now_time_zone_id::<crate::vm::Vm> as *const (),
|
||||
0,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
// Temporal.Instant:构造器 + from 静态方法 + 原型 getter 与 toString/valueOf。
|
||||
let instant_ctor_ptr = world.instant_constructor.as_ptr() as *mut JsObject;
|
||||
let instant_ctor = unsafe { &mut *instant_ctor_ptr };
|
||||
configure_native_constructor(
|
||||
instant_ctor,
|
||||
oxide_builtins::temporal::instant_constructor::<crate::vm::Vm> as *const (),
|
||||
1,
|
||||
);
|
||||
apply_binding_table(
|
||||
world,
|
||||
instant_ctor,
|
||||
core,
|
||||
&[("from", oxide_builtins::temporal::instant_from::<crate::vm::Vm> as *const (), 1)],
|
||||
);
|
||||
let instant_proto_ptr = world.instant_proto.as_ptr() as *mut JsObject;
|
||||
let instant_proto = unsafe { &mut *instant_proto_ptr };
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
instant_proto,
|
||||
"epochSeconds",
|
||||
oxide_builtins::temporal::instant_epoch_seconds::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
instant_proto,
|
||||
"epochMilliseconds",
|
||||
oxide_builtins::temporal::instant_epoch_milliseconds::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
instant_proto,
|
||||
"epochMicroseconds",
|
||||
oxide_builtins::temporal::instant_epoch_microseconds::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
instant_proto,
|
||||
"epochNanoseconds",
|
||||
oxide_builtins::temporal::instant_epoch_nanoseconds::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
apply_binding_table(
|
||||
world,
|
||||
instant_proto,
|
||||
core,
|
||||
&[
|
||||
("toString", oxide_builtins::temporal::instant_to_string::<crate::vm::Vm> as *const (), 0),
|
||||
("valueOf", oxide_builtins::temporal::instant_value_of::<crate::vm::Vm> as *const (), 0),
|
||||
],
|
||||
);
|
||||
|
||||
// Temporal.PlainDate:构造器 + from 静态方法 + year/month/day getter 与 toString。
|
||||
let plain_date_ctor_ptr = world.plain_date_constructor.as_ptr() as *mut JsObject;
|
||||
let plain_date_ctor = unsafe { &mut *plain_date_ctor_ptr };
|
||||
configure_native_constructor(
|
||||
plain_date_ctor,
|
||||
oxide_builtins::temporal::plain_date_constructor::<crate::vm::Vm> as *const (),
|
||||
3,
|
||||
);
|
||||
apply_binding_table(
|
||||
world,
|
||||
plain_date_ctor,
|
||||
core,
|
||||
&[("from", oxide_builtins::temporal::plain_date_from::<crate::vm::Vm> as *const (), 1)],
|
||||
);
|
||||
let plain_date_proto_ptr = world.plain_date_proto.as_ptr() as *mut JsObject;
|
||||
let plain_date_proto = unsafe { &mut *plain_date_proto_ptr };
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
plain_date_proto,
|
||||
"year",
|
||||
oxide_builtins::temporal::plain_date_year::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
plain_date_proto,
|
||||
"month",
|
||||
oxide_builtins::temporal::plain_date_month::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
plain_date_proto,
|
||||
"day",
|
||||
oxide_builtins::temporal::plain_date_day::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
apply_binding_table(
|
||||
world,
|
||||
plain_date_proto,
|
||||
core,
|
||||
&[("toString", oxide_builtins::temporal::plain_date_to_string::<crate::vm::Vm> as *const (), 0)],
|
||||
);
|
||||
|
||||
// Temporal.PlainTime:构造器 + 6 个分量 getter 与 toString。
|
||||
let plain_time_ctor_ptr = world.plain_time_constructor.as_ptr() as *mut JsObject;
|
||||
let plain_time_ctor = unsafe { &mut *plain_time_ctor_ptr };
|
||||
configure_native_constructor(
|
||||
plain_time_ctor,
|
||||
oxide_builtins::temporal::plain_time_constructor::<crate::vm::Vm> as *const (),
|
||||
6,
|
||||
);
|
||||
let plain_time_proto_ptr = world.plain_time_proto.as_ptr() as *mut JsObject;
|
||||
let plain_time_proto = unsafe { &mut *plain_time_proto_ptr };
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
plain_time_proto,
|
||||
"hour",
|
||||
oxide_builtins::temporal::plain_time_hour::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
plain_time_proto,
|
||||
"minute",
|
||||
oxide_builtins::temporal::plain_time_minute::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
plain_time_proto,
|
||||
"second",
|
||||
oxide_builtins::temporal::plain_time_second::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
plain_time_proto,
|
||||
"millisecond",
|
||||
oxide_builtins::temporal::plain_time_millisecond::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
plain_time_proto,
|
||||
"microsecond",
|
||||
oxide_builtins::temporal::plain_time_microsecond::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
bind_accessor_getter(
|
||||
core,
|
||||
session,
|
||||
plain_time_proto,
|
||||
"nanosecond",
|
||||
oxide_builtins::temporal::plain_time_nanosecond::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
apply_binding_table(
|
||||
world,
|
||||
plain_time_proto,
|
||||
core,
|
||||
&[("toString", oxide_builtins::temporal::plain_time_to_string::<crate::vm::Vm> as *const (), 0)],
|
||||
);
|
||||
|
||||
// 把子对象挂到 Temporal 命名空间对象上,再把 Temporal 挂到 global。
|
||||
bind_global_value(core, temporal, "Now", JsValue::from_js_object(now_ptr));
|
||||
bind_global_value(core, temporal, "Instant", JsValue::from_js_object(instant_ctor_ptr));
|
||||
bind_global_value(core, temporal, "PlainDate", JsValue::from_js_object(plain_date_ctor_ptr));
|
||||
bind_global_value(core, temporal, "PlainTime", JsValue::from_js_object(plain_time_ctor_ptr));
|
||||
bind_global_value(core, global, "Temporal", JsValue::from_js_object(temporal_ptr));
|
||||
}
|
||||
@@ -42,6 +42,8 @@ pub mod bind_string;
|
||||
pub mod bind_stubs;
|
||||
/// Symbol 构造器与原型的 native 方法绑定。
|
||||
pub mod bind_symbol;
|
||||
/// Temporal 命名空间对象(Now/Instant/PlainDate/PlainTime)绑定。
|
||||
pub mod bind_temporal;
|
||||
/// 各 TypedArray 构造器与共享原型的 native 方法绑定。
|
||||
pub mod bind_typed_array;
|
||||
|
||||
@@ -483,6 +485,7 @@ pub fn bind_global_builtin_slots(core: &Arc<KernelCore>, session: &KernelSession
|
||||
("Symbol", JsValue::from_js_object(world.symbol_constructor.as_ptr() as *mut JsObject)),
|
||||
("Math", JsValue::from_js_object(world.math_object.as_ptr() as *mut JsObject)),
|
||||
("JSON", JsValue::from_js_object(world.json_object.as_ptr() as *mut JsObject)),
|
||||
("Temporal", JsValue::from_js_object(world.temporal_object.as_ptr() as *mut JsObject)),
|
||||
] {
|
||||
bind_existing_global(core, global, name, value);
|
||||
}
|
||||
@@ -665,6 +668,9 @@ pub fn rebind_dirty_builtins(core: &Arc<KernelCore>, session: &mut KernelSession
|
||||
if dirty.map_or(true, |d| d.symbol_family) {
|
||||
bind_symbol::bind_symbol(core, session, global);
|
||||
}
|
||||
if dirty.map_or(true, |d| d.temporal) {
|
||||
bind_temporal::bind_temporal(core, session, global);
|
||||
}
|
||||
if dirty.map_or(true, |d| d.stubs) {
|
||||
bind_stubs::bind_stubs(core, session, global);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
use oxide_compiler::compiler::Compiler;
|
||||
use oxide_vm::vm::Vm;
|
||||
|
||||
fn eval(vm: &mut Vm, source: &str) -> Result<oxide_types::value::JsValue, String> {
|
||||
let allocator = oxide_parser::Allocator::default();
|
||||
let program = oxide_parser::parse(&allocator, source).map_err(|e| format!("Parse error: {:?}", e))?;
|
||||
let module = Compiler::new().compile(&program).map_err(|e| format!("Compile error: {}", e))?;
|
||||
vm.run(&module)
|
||||
}
|
||||
|
||||
fn str_val(vm: &Vm, val: oxide_types::value::JsValue) -> String {
|
||||
vm.lookup_str(val).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn num(vm: &mut Vm, source: &str) -> f64 {
|
||||
let r = eval(vm, source).unwrap();
|
||||
if r.is_double() {
|
||||
r.as_double()
|
||||
} else {
|
||||
r.as_int() as f64
|
||||
}
|
||||
}
|
||||
|
||||
// -- Temporal 命名空间 --
|
||||
|
||||
#[test]
|
||||
fn temporal_is_object() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "typeof Temporal").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporal_now_time_zone_id_is_utc() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "Temporal.Now.timeZoneId()").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "UTC");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporal_now_instant_returns_instant() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "Temporal.Now.instant() instanceof Temporal.Instant").unwrap();
|
||||
assert!(r.as_bool());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporal_now_instant_epoch_is_positive() {
|
||||
let mut vm = Vm::new();
|
||||
let r = num(&mut vm, "Temporal.Now.instant().epochMilliseconds");
|
||||
assert!(r > 1_500_000_000_000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporal_now_is_namespace_not_constructor() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "typeof Temporal.Now").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "object");
|
||||
}
|
||||
|
||||
// -- Temporal.Instant --
|
||||
|
||||
#[test]
|
||||
fn instant_from_iso_string() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "Temporal.Instant.from('2024-01-01T00:00:00Z').toString()").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "2024-01-01T00:00:00Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instant_epoch_seconds() {
|
||||
let mut vm = Vm::new();
|
||||
assert_eq!(num(&mut vm, "Temporal.Instant.from('2024-01-01T00:00:00Z').epochSeconds"), 1704067200.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instant_epoch_milliseconds() {
|
||||
let mut vm = Vm::new();
|
||||
assert_eq!(
|
||||
num(&mut vm, "Temporal.Instant.from('2024-01-01T00:00:00Z').epochMilliseconds"),
|
||||
1704067200000.0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instant_epoch_nanoseconds() {
|
||||
let mut vm = Vm::new();
|
||||
assert_eq!(
|
||||
num(&mut vm, "Temporal.Instant.from('2024-01-01T00:00:00Z').epochNanoseconds"),
|
||||
1704067200000000000.0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instant_constructor_requires_new() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "try { Temporal.Instant(0); 'no' } catch (e) { e.constructor.name }").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instant_value_of_throws() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(
|
||||
&mut vm,
|
||||
"try { Temporal.Instant.prototype.valueOf.call(Temporal.Now.instant()) } catch (e) { e.constructor.name }",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(str_val(&vm, r), "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instant_method_on_non_instant_throws() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "try { Temporal.Instant.prototype.toString.call({}) } catch (e) { e.constructor.name }")
|
||||
.unwrap();
|
||||
assert_eq!(str_val(&vm, r), "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instant_from_invalid_throws_range_error() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "try { Temporal.Instant.from('nope') } catch (e) { e.constructor.name }").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "RangeError");
|
||||
}
|
||||
|
||||
// -- Temporal.PlainDate --
|
||||
|
||||
#[test]
|
||||
fn plain_date_from_string() {
|
||||
let mut vm = Vm::new();
|
||||
assert_eq!(num(&mut vm, "Temporal.PlainDate.from('2024-01-15').year"), 2024.0);
|
||||
assert_eq!(num(&mut vm, "Temporal.PlainDate.from('2024-01-15').month"), 1.0);
|
||||
assert_eq!(num(&mut vm, "Temporal.PlainDate.from('2024-01-15').day"), 15.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_date_from_object() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "Temporal.PlainDate.from({year:2023, month:3, day:5}).toString()").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "2023-03-05");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_date_constructor_month_day() {
|
||||
let mut vm = Vm::new();
|
||||
assert_eq!(num(&mut vm, "new Temporal.PlainDate(2024, 2, 29).month"), 2.0);
|
||||
assert_eq!(num(&mut vm, "new Temporal.PlainDate(2024, 2, 29).day"), 29.0);
|
||||
assert_eq!(num(&mut vm, "new Temporal.PlainDate(2024, 2, 29).year"), 2024.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_date_leap_year_validation() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "try { new Temporal.PlainDate(2024, 2, 30) } catch (e) { e.constructor.name }").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "RangeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_date_invalid_month() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "try { new Temporal.PlainDate(2024, 13, 1) } catch (e) { e.constructor.name }").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "RangeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_date_to_string() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "new Temporal.PlainDate(2024, 1, 5).toString()").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "2024-01-05");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_date_requires_new() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "try { Temporal.PlainDate(2024, 1, 1); 'no' } catch (e) { e.constructor.name }").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_date_method_on_non_date_throws() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(
|
||||
&mut vm,
|
||||
"try { Temporal.PlainDate.prototype.year.get.call({}) } catch (e) { e.constructor.name }",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(str_val(&vm, r), "TypeError");
|
||||
}
|
||||
|
||||
// -- Temporal.PlainTime --
|
||||
|
||||
#[test]
|
||||
fn plain_time_constructor_components() {
|
||||
let mut vm = Vm::new();
|
||||
assert_eq!(num(&mut vm, "new Temporal.PlainTime(12, 30, 5).hour"), 12.0);
|
||||
assert_eq!(num(&mut vm, "new Temporal.PlainTime(12, 30, 5).minute"), 30.0);
|
||||
assert_eq!(num(&mut vm, "new Temporal.PlainTime(12, 30, 5).second"), 5.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_time_full_precision_components() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(
|
||||
&mut vm,
|
||||
"let t = new Temporal.PlainTime(23, 59, 59, 999, 999, 999); t.hour + ',' + t.minute + ',' + t.second + ',' + t.millisecond + ',' + t.microsecond + ',' + t.nanosecond",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(str_val(&vm, r), "23,59,59,999,999,999");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_time_to_string() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "new Temporal.PlainTime(12, 30, 5).toString()").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "12:30:05");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_time_to_string_with_subseconds() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "new Temporal.PlainTime(12, 30, 5, 500, 250, 1).toString()").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "12:30:05.500250001");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_time_missing_components_default_zero() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "new Temporal.PlainTime().toString()").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "00:00:00");
|
||||
let r = eval(&mut vm, "new Temporal.PlainTime(12).toString()").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "12:00:00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_time_range_validation() {
|
||||
let mut vm = Vm::new();
|
||||
let r = eval(&mut vm, "try { new Temporal.PlainTime(24, 0, 0) } catch (e) { e.constructor.name }").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "RangeError");
|
||||
let r = eval(&mut vm, "try { new Temporal.PlainTime(0, 60, 0) } catch (e) { e.constructor.name }").unwrap();
|
||||
assert_eq!(str_val(&vm, r), "RangeError");
|
||||
}
|
||||
Reference in New Issue
Block a user