runtime, macros: unify NaN-boxed value API under ValueVariant trait

This commit is contained in:
2026-07-14 23:14:18 +08:00
parent 7220b42024
commit abf7dc0855
28 changed files with 475 additions and 362 deletions
+1
View File
@@ -13,3 +13,4 @@ string-interner = { workspace = true }
fix-bytecode = { path = "../fix-bytecode" }
fix-error = { path = "../fix-error" }
fix-lang = { path = "../fix-lang" }
fix-macros = { path = "../fix-macros" }
+6 -6
View File
@@ -63,7 +63,7 @@ macro_rules! impl_forced_inline {
) -> Step {
m.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
let v = m.peek_forced(base_depth);
if v.as_inline::<$ty>().is_none() {
if v.downcast::<$ty>().is_none() {
let _: Step = m.finish_type_err($nix_ty, v.ty());
return Step::Break(Break::Done);
}
@@ -73,7 +73,7 @@ macro_rules! impl_forced_inline {
#[inline(always)]
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
m.pop_forced()
.as_inline::<$ty>()
.downcast::<$ty>()
.expect("type checked in force_and_check")
}
}
@@ -97,7 +97,7 @@ macro_rules! impl_forced_gc {
) -> Step {
m.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
let v = m.peek_forced(base_depth);
if v.as_gc::<$ty>().is_none() {
if v.downcast::<$ty>().is_none() {
let _: Step = m.finish_type_err($nix_ty, v.ty());
return Step::Break(Break::Done);
}
@@ -107,7 +107,7 @@ macro_rules! impl_forced_gc {
#[inline(always)]
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
m.pop_forced()
.as_gc::<$ty>()
.downcast::<$ty>()
.expect("type checked in force_and_check")
}
}
@@ -173,7 +173,7 @@ impl<'gc> Forced<'gc> for f64 {
) -> Step {
m.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
let v = m.peek_forced(base_depth);
if v.as_float().is_none() {
if v.downcast_float().is_none() {
let _: Step = m.finish_type_err(NixType::Float, v.ty());
return Step::Break(Break::Done);
}
@@ -183,7 +183,7 @@ impl<'gc> Forced<'gc> for f64 {
#[inline(always)]
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
m.pop_forced()
.as_float()
.downcast_float()
.expect("type checked in force_and_check")
}
}
+18 -18
View File
@@ -44,10 +44,10 @@ pub trait VmRuntimeCtxExt: VmRuntimeCtx {
impl<T: VmRuntimeCtx> VmRuntimeCtxExt for T {
fn get_string<'a, 'gc: 'a>(&'a self, val: StrictValue<'gc>) -> Option<&'a str> {
if let Some(sid) = val.as_inline::<StringId>() {
if let Some(sid) = val.downcast::<StringId>() {
Some(self.resolve_string(sid))
} else {
val.as_gc::<NixString>().map(|ns| ns.as_ref().as_str())
val.downcast::<NixString>().map(|ns| ns.as_ref().as_str())
}
}
@@ -56,7 +56,7 @@ impl<T: VmRuntimeCtx> VmRuntimeCtxExt for T {
/// would coerce a path to a string (string interpolation, file IO
/// builtins, etc.).
fn get_string_or_path<'a, 'gc: 'a>(&'a self, val: StrictValue<'gc>) -> Option<&'a str> {
if let Some(p) = val.as_inline::<Path>() {
if let Some(p) = val.downcast::<Path>() {
Some(self.resolve_string(p.0))
} else {
self.get_string(val)
@@ -67,9 +67,9 @@ impl<T: VmRuntimeCtx> VmRuntimeCtxExt for T {
&'a mut self,
val: StrictValue<'gc>,
) -> std::result::Result<StringId, NixType> {
if let Some(sid) = val.as_inline::<StringId>() {
if let Some(sid) = val.downcast::<StringId>() {
Ok(sid)
} else if let Some(s) = val.as_gc::<NixString>().map(|ns| ns.as_ref().as_str()) {
} else if let Some(s) = val.downcast::<NixString>().map(|ns| ns.as_ref().as_str()) {
Ok(self.intern_string(s))
} else {
Err(val.ty())
@@ -77,7 +77,7 @@ impl<T: VmRuntimeCtx> VmRuntimeCtxExt for T {
}
fn get_string_context<'gc>(&self, val: StrictValue<'gc>) -> &'gc StringContext {
if let Some(ns) = val.as_gc::<NixString>() {
if let Some(ns) = val.downcast::<NixString>() {
ns.as_ref().context()
} else {
StringContext::empty()
@@ -96,24 +96,24 @@ pub(crate) trait ConvertValueWithSeen: VmRuntimeCtx {
impl<T: VmRuntimeCtx> ConvertValueWithSeen for T {
fn convert_value_with_seen(&self, val: Value, seen: &mut HashSet<u64>) -> fix_lang::Value {
use fix_lang::Value;
if let Some(i) = val.as_inline::<i32>() {
if let Some(i) = val.downcast::<i32>() {
Value::Int(i as i64)
} else if let Some(gc_i) = val.as_gc::<i64>() {
} else if let Some(gc_i) = val.downcast::<i64>() {
Value::Int(*gc_i)
} else if let Some(f) = val.as_float() {
} else if let Some(f) = val.downcast_float() {
Value::Float(f)
} else if let Some(b) = val.as_inline::<bool>() {
} else if let Some(b) = val.downcast::<bool>() {
Value::Bool(b)
} else if val.is::<Null>() {
Value::Null
} else if let Some(sid) = val.as_inline::<StringId>() {
} else if let Some(sid) = val.downcast::<StringId>() {
let s = self.resolve_string(sid).to_owned();
Value::String(s)
} else if let Some(ns) = val.as_gc::<NixString>() {
} else if let Some(ns) = val.downcast::<NixString>() {
Value::String(ns.as_str().to_owned())
} else if let Some(p) = val.as_inline::<Path>() {
} else if let Some(p) = val.downcast::<Path>() {
Value::Path(self.resolve_string(p.0).to_owned())
} else if let Some(attrs) = val.as_gc::<AttrSet>() {
} else if let Some(attrs) = val.downcast::<AttrSet>() {
let bits = val.to_bits();
if attrs.entries.is_empty() {
return Value::AttrSet(Default::default());
@@ -128,7 +128,7 @@ impl<T: VmRuntimeCtx> ConvertValueWithSeen for T {
map.insert(fix_lang::Symbol::from(key), converted);
}
Value::AttrSet(fix_lang::AttrSet::new(map))
} else if let Some(list) = val.as_gc::<List>() {
} else if let Some(list) = val.downcast::<List>() {
let bits = val.to_bits();
if list.inner.borrow().is_empty() {
return Value::List(Default::default());
@@ -146,16 +146,16 @@ impl<T: VmRuntimeCtx> ConvertValueWithSeen for T {
Value::List(fix_lang::List::new(items))
} else if val.is::<Closure>() {
Value::Func
} else if let Some(thunk) = val.as_gc::<Thunk>() {
} else if let Some(thunk) = val.downcast::<Thunk>() {
if let ThunkState::Evaluated(v) = *thunk.borrow() {
self.convert_value_with_seen(v.relax(), seen)
} else {
Value::Thunk
}
} else if let Some(primop) = val.as_inline::<PrimOp>() {
} else if let Some(primop) = val.downcast::<PrimOp>() {
let name = BUILTINS[primop.id as usize].0;
Value::PrimOp(name.strip_prefix("__").unwrap_or(name))
} else if let Some(app) = val.as_gc::<PrimOpApp>() {
} else if let Some(app) = val.downcast::<PrimOpApp>() {
let name = BUILTINS[app.primop.id as usize].0;
Value::PrimOpApp(name.strip_prefix("__").unwrap_or(name))
} else {
+8 -3
View File
@@ -18,16 +18,21 @@ pub fn resolve_operand<'gc, M: Machine<'gc>>(
use OperandData::*;
match *op {
Const(id) => ctx.get_const(id).into(),
BigInt(val) => Value::new_gc(Gc::new(mc, val)),
BigInt(val) => Value::new(Gc::new(mc, val)),
Local { layer, idx } => m.local(layer, idx),
#[allow(clippy::unwrap_used)]
BuiltinConst(id) => m.builtins().as_gc::<AttrSet>().unwrap().lookup(id).unwrap(),
BuiltinConst(id) => m
.builtins()
.downcast::<AttrSet>()
.unwrap()
.lookup(id)
.unwrap(),
Builtins => m.builtins(),
ReplBinding(_id) => todo!(),
ScopedImportBinding { slot_id, name } => {
let scope = m.scope_slot(slot_id);
#[allow(clippy::unwrap_used)]
let attrs = scope.as_gc::<AttrSet>().expect("scope must be attrset");
let attrs = scope.downcast::<AttrSet>().expect("scope must be attrset");
#[allow(clippy::unwrap_used)]
attrs.lookup(name).expect("scoped binding not found")
}
+120 -110
View File
@@ -19,33 +19,81 @@ mod private {
pub trait Cealed {}
}
pub trait ValueVariant: private::Cealed {
type Ty<'gc>: 'gc;
fn is_value(value: &Value<'_>) -> bool;
/// # Safety
///
/// [`Self::is_value`] must hold for `value`.
unsafe fn from_raw<'gc>(value: &Value<'gc>) -> Self::Ty<'gc>;
}
/// # Safety
///
/// [`Self::TAG`] must be unique among all implementors.
unsafe trait Storable: private::Cealed {
const TAG: RawTag;
/// Each implementor must round-trip through [`Self::to_raw_box`] /
/// [`Self::from_raw_box`] and must be the sole owner of its NaN-boxed
/// representation (tagged payload or float).
pub(crate) unsafe trait Storable: private::Cealed {
fn to_raw_box(self) -> RawBox;
/// # Safety
///
/// `raw` must represent a valid `Self`.
unsafe fn from_raw_box(raw: &RawBox) -> Self;
}
trait InlineStorable: Storable + RawStore {}
trait GcStorable: Storable {}
macro_rules! define_value_types {
(
inline { $($itype:ty => $itag:expr, $iname:literal;)* }
gc { $($gtype:ty => $gtag:expr, $gname:literal;)* }
inline { $($itype:ty => $itag:path, $iname:literal;)* }
gc { $($gtype:ty => $gtag:path, $gname:literal;)* }
) => {
$(
unsafe impl Storable for $itype {
const TAG: RawTag = $itag;
fn to_raw_box(self) -> RawBox {
RawBox::from_value(RawValue::store($itag, self))
}
unsafe fn from_raw_box(raw: &RawBox) -> Self {
unsafe { <Self as RawStore>::from_val(raw.value().unwrap_unchecked()) }
}
}
impl InlineStorable for $itype {}
impl private::Cealed for $itype {}
impl ValueVariant for $itype {
type Ty<'gc> = $itype;
#[inline(always)]
fn is_value(value: &Value<'_>) -> bool {
value.raw.tag() == Some($itag)
}
#[inline(always)]
unsafe fn from_raw<'gc>(value: &Value<'gc>) -> Self::Ty<'gc> {
unsafe { <$itype as Storable>::from_raw_box(&value.raw) }
}
}
)*
$(
unsafe impl Storable for $gtype {
const TAG: RawTag = $gtag;
unsafe impl Storable for Gc<'_, $gtype> {
fn to_raw_box(self) -> RawBox {
RawBox::from_value(RawValue::store($gtag, Gc::as_ptr(self)))
}
unsafe fn from_raw_box(raw: &RawBox) -> Self {
unsafe { Gc::from_ptr(<*mut $gtype as RawStore>::from_val(raw.value().unwrap_unchecked())) }
}
}
impl GcStorable for $gtype {}
impl private::Cealed for Gc<'_, $gtype> {}
impl private::Cealed for $gtype {}
impl ValueVariant for $gtype {
type Ty<'gc> = Gc<'gc, fix_macros::unelide_lifetimes!('gc; $gtype)>;
#[inline(always)]
fn is_value(value: &Value<'_>) -> bool {
value.raw.tag() == Some($gtag)
}
#[inline(always)]
unsafe fn from_raw<'gc>(value: &Value<'gc>) -> Self::Ty<'gc> {
unsafe {
<Gc<'gc, fix_macros::unelide_lifetimes!('gc; $gtype)> as Storable>::from_raw_box(
&value.raw,
)
}
}
}
)*
const _: () = assert!(size_of::<Value<'static>>() == 8);
@@ -75,10 +123,10 @@ macro_rules! define_value_types {
fn trace<T: Trace<'gc>>(&self, cc: &mut T) {
let Some(tag) = self.raw.tag() else { return };
match tag {
$(<$gtype as Storable>::TAG => unsafe {
self.load_gc::<$gtype>().trace(cc)
$($gtag => unsafe {
self.downcast::<$gtype>().unwrap_unchecked().trace(cc)
},)*
$(<$itype as Storable>::TAG => (),)*
$($itag => (),)*
_ => unreachable!("invalid value tag"),
}
}
@@ -90,10 +138,10 @@ macro_rules! define_value_types {
None => write!(f, "Float({:?})", unsafe {
self.raw.float().unwrap_unchecked()
}),
$(Some(<$itype as Storable>::TAG) => write!(f, "{}({:?})", $iname, unsafe {
self.as_inline::<$itype>().unwrap_unchecked()
$(Some($itag) => write!(f, "{}({:?})", $iname, unsafe {
self.downcast::<$itype>().unwrap_unchecked()
}),)*
$(Some(<$gtype as Storable>::TAG) =>
$(Some($gtag) =>
write!(f, "{}(..)", $gname),)*
_ => unreachable!("invalid value tag"),
}
@@ -122,6 +170,29 @@ define_value_types! {
}
}
impl private::Cealed for f64 {}
unsafe impl Storable for f64 {
fn to_raw_box(self) -> RawBox {
RawBox::from_float(self)
}
unsafe fn from_raw_box(raw: &RawBox) -> Self {
unsafe { raw.float().copied().unwrap_unchecked() }
}
}
impl ValueVariant for f64 {
type Ty<'gc> = f64;
#[inline(always)]
fn is_value(value: &Value<'_>) -> bool {
value.raw.is_float()
}
#[inline(always)]
unsafe fn from_raw<'gc>(value: &Value<'gc>) -> Self::Ty<'gc> {
unsafe { <f64 as Storable>::from_raw_box(&value.raw) }
}
}
/// # Nix runtime value representation
///
/// NaN-boxed value fitting in 8 bytes.
@@ -135,33 +206,11 @@ pub struct Value<'gc> {
impl Default for Value<'_> {
#[inline(always)]
fn default() -> Self {
Self::new_inline(Null)
Self::new(Null)
}
}
impl<'gc> Value<'gc> {
#[inline(always)]
fn from_raw_value(rv: RawValue) -> Self {
Self {
raw: RawBox::from_value(rv),
_marker: PhantomData,
}
}
/// Load a GC pointer from a value with a negative tag.
///
/// # Safety
///
/// The value must actually store a `Gc<'gc, T>` with the matching type.
#[inline(always)]
unsafe fn load_gc<T: GcStorable>(self) -> Gc<'gc, T> {
unsafe {
let rv = self.raw.value().unwrap_unchecked();
let ptr: *const T = <*const T as RawStore>::from_val(rv);
Gc::from_ptr(ptr)
}
}
#[inline(always)]
const fn tag(self) -> Option<RawTag> {
self.raw.tag()
@@ -179,23 +228,19 @@ impl<'gc> Value<'gc> {
#[inline]
#[allow(private_bounds)]
pub fn new_inline<T: InlineStorable>(val: T) -> Self {
Self::from_raw_value(RawValue::store(T::TAG, val))
}
#[inline]
#[allow(private_bounds)]
pub fn new_gc<T: GcStorable>(gc: Gc<'gc, T>) -> Self {
let ptr = Gc::as_ptr(gc);
Self::from_raw_value(RawValue::store(T::TAG, ptr))
pub fn new<T: Storable>(val: T) -> Self {
Self {
raw: val.to_raw_box(),
_marker: PhantomData,
}
}
#[inline]
pub fn make_int(val: i64, mc: &Mutation<'gc>) -> Self {
if val >= i32::MIN as i64 && val <= i32::MAX as i64 {
Value::new_inline(val as i32)
Value::new(val as i32)
} else {
Value::new_gc(Gc::new(mc, val))
Value::new(Gc::new(mc, val))
}
}
}
@@ -207,43 +252,20 @@ impl<'gc> Value<'gc> {
}
#[inline]
#[allow(private_bounds)]
pub fn is<T: Storable>(self) -> bool {
self.tag() == Some(T::TAG)
pub fn is<T: ValueVariant>(self) -> bool {
T::is_value(&self)
}
}
impl<'gc> Value<'gc> {
#[inline]
pub fn as_float(self) -> Option<f64> {
pub fn downcast_float(self) -> Option<f64> {
self.raw.float().copied()
}
#[inline]
#[allow(private_bounds)]
pub fn as_inline<T: InlineStorable>(self) -> Option<T> {
if self.is::<T>() {
Some(unsafe {
let rv = self.raw.value().unwrap_unchecked();
T::from_val(rv)
})
} else {
None
}
}
#[inline]
#[allow(private_bounds)]
pub fn as_gc<T: GcStorable>(self) -> Option<Gc<'gc, T>> {
if self.is::<T>() {
Some(unsafe {
let rv = self.raw.value().unwrap_unchecked();
let ptr: *const T = <*const T as RawStore>::from_val(rv);
Gc::from_ptr(ptr)
})
} else {
None
}
pub fn downcast<T: ValueVariant>(self) -> Option<T::Ty<'gc>> {
self.is::<T>().then(|| unsafe { T::from_raw(&self) })
}
#[inline]
@@ -253,18 +275,18 @@ impl<'gc> Value<'gc> {
#[inline]
pub fn as_num(self) -> Option<NixNum> {
if let Some(i) = self.as_inline::<i32>() {
if let Some(i) = self.downcast::<i32>() {
Some(NixNum::Int(i as i64))
} else if let Some(gc_i) = self.as_gc::<i64>() {
} else if let Some(gc_i) = self.downcast::<i64>() {
Some(NixNum::Int(*gc_i))
} else {
self.as_float().map(NixNum::Float)
self.downcast_float().map(NixNum::Float)
}
}
#[inline]
pub fn restrict(self) -> Result<StrictValue<'gc>, Gc<'gc, Thunk<'gc>>> {
if let Some(thunk) = self.as_gc::<Thunk<'gc>>() {
if let Some(thunk) = self.downcast::<Thunk>() {
Err(thunk)
} else {
Ok(StrictValue(self))
@@ -305,15 +327,8 @@ impl<'gc> Value<'gc> {
}
#[inline]
#[allow(private_bounds)]
pub fn expect_inline<T: InlineStorable>(self) -> Result<T, NixType> {
self.as_inline::<T>().ok_or_else(|| self.ty())
}
#[inline]
#[allow(private_bounds)]
pub fn expect_gc<T: GcStorable>(self) -> Result<Gc<'gc, T>, NixType> {
self.as_gc::<T>().ok_or_else(|| self.ty())
pub fn expect<T: ValueVariant>(self) -> Result<T::Ty<'gc>, NixType> {
self.downcast::<T>().ok_or_else(|| self.ty())
}
#[inline]
@@ -321,14 +336,9 @@ impl<'gc> Value<'gc> {
self.as_num().ok_or_else(|| self.ty())
}
#[inline]
pub fn expect_bool(self) -> Result<bool, NixType> {
self.as_inline::<bool>().ok_or_else(|| self.ty())
}
#[inline]
pub fn expect_float(self) -> Result<f64, NixType> {
self.as_float().ok_or_else(|| self.ty())
self.downcast_float().ok_or_else(|| self.ty())
}
}
@@ -351,35 +361,35 @@ impl StaticValue {
}
#[inline]
#[allow(private_bounds)]
pub fn new_inline<T: InlineStorable>(val: T) -> Self {
Self(Value::new_inline(val))
pub fn new<T: Storable + 'static>(val: T) -> Self {
Self(Value::new(val))
}
#[inline]
pub fn new_primop(id: BuiltinId, arity: u8, dispatch_ip: u32) -> Self {
Self(Value::new_inline(PrimOp {
Self::new(PrimOp {
id,
arity,
dispatch_ip,
}))
})
}
#[inline]
pub fn is_float(self) -> bool {
self.0.is_float()
}
#[inline]
#[allow(private_bounds)]
pub fn is<T: InlineStorable>(self) -> bool {
pub fn is<T: ValueVariant>(self) -> bool {
self.0.is::<T>()
}
#[inline]
pub fn as_float(self) -> Option<f64> {
self.0.as_float()
pub fn downcast<T: ValueVariant>(self) -> Option<T::Ty<'static>> {
self.0.downcast::<T>()
}
#[inline]
#[allow(private_bounds)]
pub fn as_inline<T: InlineStorable>(self) -> Option<T> {
self.0.as_inline::<T>()
pub fn downcast_float(self) -> Option<f64> {
self.0.downcast_float()
}
#[inline]
pub fn to_bits(self) -> u64 {
self.0.raw.to_bits()