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

This commit is contained in:
2026-07-15 19:11:03 +08:00
parent 7220b42024
commit 09ee923903
28 changed files with 510 additions and 490 deletions
+122 -171
View File
@@ -19,33 +19,69 @@ mod private {
pub trait Cealed {}
}
/// # Safety
///
/// [`Self::TAG`] must be unique among all implementors.
unsafe trait Storable: private::Cealed {
const TAG: RawTag;
pub trait ValueVariant: private::Cealed {
#[allow(private_bounds)]
type Ty<'gc>: Storable + 'gc;
const TYPE: NixType;
}
trait Storable: private::Cealed {
fn is(raw: &RawBox) -> bool;
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, $ity:path, $iname:literal;)* }
gc { $($gtype:ty => $gtag:path, $gty:path, $gname:literal;)* }
) => {
$(
unsafe impl Storable for $itype {
const TAG: RawTag = $itag;
impl Storable for $itype {
#[inline(always)]
fn is(value: &RawBox) -> bool {
value.tag() == Some($itag)
}
#[inline(always)]
fn to_raw_box(self) -> RawBox {
RawBox::from_value(RawValue::store($itag, self))
}
#[inline(always)]
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;
const TYPE: NixType = $ity;
}
)*
$(
unsafe impl Storable for $gtype {
const TAG: RawTag = $gtag;
impl Storable for Gc<'_, $gtype> {
#[inline(always)]
fn is(value: &RawBox) -> bool {
value.tag() == Some($gtag)
}
#[inline(always)]
fn to_raw_box(self) -> RawBox {
RawBox::from_value(RawValue::store($gtag, Gc::as_ptr(self)))
}
#[inline(always)]
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)>;
const TYPE: NixType = $gty;
}
)*
const _: () = assert!(size_of::<Value<'static>>() == 8);
@@ -75,10 +111,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 +126,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"),
}
@@ -104,24 +140,46 @@ macro_rules! define_value_types {
define_value_types! {
inline {
i32 => RawTag::P1, "SmallInt";
bool => RawTag::P2, "Bool";
Null => RawTag::P3, "Null";
StringId => RawTag::P4, "SmallString";
PrimOp => RawTag::P5, "PrimOp";
Path => RawTag::P6, "Path";
i32 => RawTag::P1, NixType::Int, "SmallInt";
bool => RawTag::P2, NixType::Bool, "Bool";
Null => RawTag::P3, NixType::Null, "Null";
StringId => RawTag::P4, NixType::String, "SmallString";
PrimOp => RawTag::P5, NixType::PrimOp, "PrimOp";
Path => RawTag::P6, NixType::Path, "Path";
}
gc {
i64 => RawTag::P7, "BigInt";
NixString => RawTag::N1, "String";
AttrSet<'_> => RawTag::N2, "AttrSet";
List<'_> => RawTag::N3, "List";
Thunk<'_> => RawTag::N4, "Thunk";
Closure<'_> => RawTag::N5, "Closure";
PrimOpApp<'_> => RawTag::N6, "PrimOpApp";
i64 => RawTag::P7, NixType::Int, "BigInt";
NixString => RawTag::N1, NixType::String, "String";
AttrSet<'_> => RawTag::N2, NixType::AttrSet, "AttrSet";
List<'_> => RawTag::N3, NixType::List, "List";
Thunk<'_> => RawTag::N4, NixType::Thunk, "Thunk";
Closure<'_> => RawTag::N5, NixType::Closure, "Closure";
PrimOpApp<'_> => RawTag::N6, NixType::PrimOpApp, "PrimOpApp";
}
}
impl private::Cealed for f64 {}
impl Storable for f64 {
#[inline(always)]
fn is(value: &RawBox) -> bool {
value.is_float()
}
#[inline(always)]
fn to_raw_box(self) -> RawBox {
RawBox::from_float(self)
}
#[inline(always)]
unsafe fn from_raw_box(raw: RawBox) -> Self {
unsafe { raw.float().copied().unwrap_unchecked() }
}
}
impl ValueVariant for f64 {
type Ty<'gc> = f64;
const TYPE: NixType = NixType::Float;
}
/// # Nix runtime value representation
///
/// NaN-boxed value fitting in 8 bytes.
@@ -135,33 +193,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()
@@ -170,80 +206,31 @@ impl<'gc> Value<'gc> {
impl<'gc> Value<'gc> {
#[inline]
pub fn new_float(val: f64) -> Self {
#[allow(private_bounds)]
pub fn new<T: Storable>(val: T) -> Self {
Self {
raw: RawBox::from_float(val),
raw: val.to_raw_box(),
_marker: PhantomData,
}
}
#[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))
}
#[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))
}
}
}
impl<'gc> Value<'gc> {
#[inline]
pub fn is_float(self) -> bool {
self.raw.is_float()
}
#[inline]
#[allow(private_bounds)]
pub fn is<T: Storable>(self) -> bool {
self.tag() == Some(T::TAG)
}
}
impl<'gc> Value<'gc> {
#[inline]
pub fn as_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
Value::new(Gc::new(mc, val))
}
}
#[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 is<T: ValueVariant>(self) -> bool {
T::Ty::is(&self.raw)
}
#[inline]
pub fn downcast<T: ValueVariant>(self) -> Option<T::Ty<'gc>> {
self.is::<T>().then(|| unsafe { T::Ty::from_raw_box(self.raw) })
}
#[inline]
@@ -252,19 +239,19 @@ impl<'gc> Value<'gc> {
}
#[inline]
pub fn as_num(self) -> Option<NixNum> {
if let Some(i) = self.as_inline::<i32>() {
pub fn downcast_num(self) -> Option<NixNum> {
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::<f64>().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))
@@ -273,7 +260,7 @@ impl<'gc> Value<'gc> {
#[inline]
pub fn ty(self) -> NixType {
if self.is_float() {
if self.is::<f64>() {
NixType::Float
} else if self.is::<i32>() || self.is::<i64>() {
NixType::Int
@@ -305,30 +292,13 @@ 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]
pub fn expect_num(self) -> Result<NixNum, NixType> {
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_num().ok_or_else(|| self.ty())
}
}
@@ -345,41 +315,22 @@ impl<'gc> From<StaticValue> for Value<'gc> {
}
impl StaticValue {
#[inline]
pub fn new_float(val: f64) -> Self {
Self(Value::new_float(val))
}
#[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 {
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()
}
#[inline]
#[allow(private_bounds)]
pub fn as_inline<T: InlineStorable>(self) -> Option<T> {
self.0.as_inline::<T>()
pub fn downcast<T: ValueVariant>(self) -> Option<T::Ty<'static>> {
self.0.downcast::<T>()
}
#[inline]
pub fn to_bits(self) -> u64 {
self.0.raw.to_bits()