Skip to content

Commit

Permalink
rune: Remove distinction in dynamic variants
Browse files Browse the repository at this point in the history
  • Loading branch information
udoprog committed Nov 3, 2024
1 parent e884877 commit 84acd09
Show file tree
Hide file tree
Showing 24 changed files with 211 additions and 681 deletions.
4 changes: 1 addition & 3 deletions crates/rune-core/src/item/component_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ pub enum ComponentRef<'a> {
}

impl<'a> ComponentRef<'a> {
/// Get the component as a string.
#[cfg(feature = "doc")]
#[doc(hidden)]
/// Get the component as a `&str` reference.
pub fn as_str(&self) -> Option<&'a str> {
match self {
ComponentRef::Str(string) => Some(string),
Expand Down
8 changes: 8 additions & 0 deletions crates/rune-core/src/item/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,14 @@ impl Item {
self.iter().next_back()
}

/// Access the base name of the item if available.
///
/// The base name is the last string component of the item.
#[inline]
pub fn base_name(&self) -> Option<&str> {
self.iter().next_back()?.as_str()
}

/// An iterator over the [Component]s that constitute this item.
///
/// # Examples
Expand Down
2 changes: 0 additions & 2 deletions crates/rune-macros/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -775,7 +775,6 @@ impl Context {
value_mut_guard: path(m, ["runtime", "ValueMutGuard"]),
value_ref_guard: path(m, ["runtime", "ValueRefGuard"]),
value: path(m, ["runtime", "Value"]),
variant_data: path(m, ["runtime", "VariantData"]),
vec: path(m, ["alloc", "Vec"]),
vm_result: path(m, ["runtime", "VmResult"]),
vm_try: path(m, ["vm_try"]),
Expand Down Expand Up @@ -870,7 +869,6 @@ pub(crate) struct Tokens {
pub(crate) value_mut_guard: syn::Path,
pub(crate) value_ref_guard: syn::Path,
pub(crate) value: syn::Path,
pub(crate) variant_data: syn::Path,
pub(crate) vec: syn::Path,
pub(crate) vm_result: syn::Path,
pub(crate) vm_try: syn::Path,
Expand Down
39 changes: 21 additions & 18 deletions crates/rune-macros/src/from_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ impl Expander<'_> {
let Tokens {
type_value,
from_value,
variant_data,
value,
result,
runtime_error,
Expand Down Expand Up @@ -145,27 +144,31 @@ impl Expander<'_> {
};

let variant = quote! {
#type_value::Variant(variant) => {
let mut it = variant.rtti().item.iter();
#type_value::EmptyStruct(data) => {
let Some(name) = data.rtti().item().base_name() else {
return #result::Err(#runtime_error::__rune_macros__missing_variant_name());
};

let Some(name) = it.next_back_str() else {
match name {
#(#unit_matches,)* #missing,
}
}
#type_value::TupleStruct(tuple) => {
let Some(name) = tuple.rtti().item().base_name() else {
return #result::Err(#runtime_error::__rune_macros__missing_variant_name());
};

match variant.data() {
#variant_data::Empty => match name {
#(#unit_matches,)* #missing,
},
#variant_data::Tuple(tuple) => match name {
#(#unnamed_matches,)* #missing,
},
#variant_data::Struct(data) => {
let object = variant.accessor(data);

match name {
#(#named_matches,)* #missing,
}
}
match name {
#(#unnamed_matches,)* #missing,
}
}
#type_value::Struct(object) => {
let Some(name) = object.rtti().item().base_name() else {
return #result::Err(#runtime_error::__rune_macros__missing_variant_name());
};

match name {
#(#named_matches,)* #missing,
}
}
};
Expand Down
2 changes: 1 addition & 1 deletion crates/rune/src/compile/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,7 @@ impl Context {
item: item.try_clone()?,
hash,
type_check: None,
type_info: TypeInfo::typed(Arc::new(Rtti {
type_info: TypeInfo::rtti(Arc::new(Rtti {
hash: ty.hash,
variant_hash: hash,
item: item.try_clone()?,
Expand Down
4 changes: 2 additions & 2 deletions crates/rune/src/compile/unit_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ impl UnitBuilder {
));
}

let info = UnitFn::UnitVariant { hash: meta.hash };
let info = UnitFn::EmptyStruct { hash: meta.hash };

let signature = DebugSignature::new(
pool.item(meta.item_meta.item).try_to_owned()?,
Expand Down Expand Up @@ -545,7 +545,7 @@ impl UnitBuilder {
));
}

let info = UnitFn::TupleVariant {
let info = UnitFn::TupleStruct {
hash: meta.hash,
args,
};
Expand Down
12 changes: 1 addition & 11 deletions crates/rune/src/compile/v1/assemble.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2527,7 +2527,7 @@ fn expr_object<'a, 'hir>(
span,
)?;
}
hir::ExprObjectKind::Struct { hash } => {
hir::ExprObjectKind::Struct { hash } | hir::ExprObjectKind::StructVariant { hash } => {
cx.asm.push(
Inst::Struct {
addr: linear.addr(),
Expand All @@ -2537,16 +2537,6 @@ fn expr_object<'a, 'hir>(
span,
)?;
}
hir::ExprObjectKind::StructVariant { hash } => {
cx.asm.push(
Inst::StructVariant {
addr: linear.addr(),
hash,
out: needs.alloc_output()?,
},
span,
)?;
}
hir::ExprObjectKind::ExternalType { hash, args } => {
reorder_field_assignments(cx, hir, linear.addr(), span)?;

Expand Down
97 changes: 8 additions & 89 deletions crates/rune/src/runtime/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ use crate::Hash;

use super::{
Args, Call, ConstValue, Formatter, FromValue, FunctionHandler, GuardedArgs, InstAddress,
Output, OwnedTuple, Rtti, RuntimeContext, RuntimeError, Stack, Unit, Value, Vm, VmCall,
VmErrorKind, VmHalt, VmResult,
Output, OwnedTuple, Rtti, RuntimeContext, RuntimeError, Stack, TupleStruct, Unit, Value, Vm,
VmCall, VmErrorKind, VmHalt, VmResult,
};

/// The type of a function in Rune.
Expand Down Expand Up @@ -255,16 +255,6 @@ impl Function {
Self(FunctionImpl::from_tuple_struct(rtti, args))
}

/// Create a function pointer that constructs a empty variant.
pub(crate) fn from_unit_variant(rtti: Arc<Rtti>) -> Self {
Self(FunctionImpl::from_unit_variant(rtti))
}

/// Create a function pointer that constructs a tuple variant.
pub(crate) fn from_tuple_variant(rtti: Arc<Rtti>, args: usize) -> Self {
Self(FunctionImpl::from_tuple_variant(rtti, args))
}

/// Type [Hash][struct@Hash] of the underlying function.
///
/// # Examples
Expand Down Expand Up @@ -581,16 +571,6 @@ where
let (args, _guard) = vm_try!(unsafe { args.guarded_into_vec() });
vm_try!(Value::tuple_struct(tuple.rtti.clone(), args))
}
Inner::FnUnitVariant(unit) => {
vm_try!(check_args(args.count(), 0));
vm_try!(Value::unit_variant(unit.rtti.clone()))
}
Inner::FnTupleVariant(tuple) => {
vm_try!(check_args(args.count(), tuple.args));
// SAFETY: We don't let the guard outlive the value.
let (args, _guard) = vm_try!(unsafe { args.guarded_into_vec() });
vm_try!(Value::tuple_variant(tuple.rtti.clone(), args))
}
};

VmResult::Ok(vm_try!(T::from_value(value)))
Expand Down Expand Up @@ -667,30 +647,13 @@ where
vm_try!(check_args(args, tuple.args));

let seq = vm_try!(vm.stack().slice_at(addr, args));
let seq = vm_try!(seq.iter().cloned().try_collect());
let data = vm_try!(seq.iter().cloned().try_collect());

vm_try!(out.store(vm.stack_mut(), || {
Value::tuple_struct(tuple.rtti.clone(), seq)
vm_try!(out.store(vm.stack_mut(), || TupleStruct {
rtti: tuple.rtti.clone(),
data
}));

None
}
Inner::FnUnitVariant(tuple) => {
vm_try!(check_args(args, 0));
vm_try!(out.store(vm.stack_mut(), || Value::unit_variant(tuple.rtti.clone())));
None
}
Inner::FnTupleVariant(tuple) => {
vm_try!(check_args(args, tuple.args));

let seq = vm_try!(vm.stack().slice_at(addr, args));
let seq = vm_try!(seq.iter().cloned().try_collect());

vm_try!(out.store(vm.stack_mut(), || Value::tuple_variant(
tuple.rtti.clone(),
seq
)));

None
}
};
Expand Down Expand Up @@ -765,31 +728,15 @@ where
}
}

/// Create a function pointer that constructs a empty variant.
pub(crate) fn from_unit_variant(rtti: Arc<Rtti>) -> Self {
Self {
inner: Inner::FnUnitVariant(FnUnitVariant { rtti }),
}
}

/// Create a function pointer that constructs a tuple variant.
pub(crate) fn from_tuple_variant(rtti: Arc<Rtti>, args: usize) -> Self {
Self {
inner: Inner::FnTupleVariant(FnTupleVariant { rtti, args }),
}
}

#[inline]
fn type_hash(&self) -> Hash {
match &self.inner {
Inner::FnHandler(FnHandler { hash, .. }) | Inner::FnOffset(FnOffset { hash, .. }) => {
*hash
}
Inner::FnClosureOffset(fco) => fco.fn_offset.hash,
Inner::FnUnitStruct(func) => func.rtti.hash,
Inner::FnTupleStruct(func) => func.rtti.hash,
Inner::FnUnitVariant(func) => func.rtti.hash,
Inner::FnTupleVariant(func) => func.rtti.hash,
Inner::FnUnitStruct(func) => func.rtti.type_hash(),
Inner::FnTupleStruct(func) => func.rtti.type_hash(),
}
}
}
Expand All @@ -814,8 +761,6 @@ impl FunctionImpl<Value> {
Inner::FnOffset(inner) => Inner::FnOffset(inner),
Inner::FnUnitStruct(inner) => Inner::FnUnitStruct(inner),
Inner::FnTupleStruct(inner) => Inner::FnTupleStruct(inner),
Inner::FnUnitVariant(inner) => Inner::FnUnitVariant(inner),
Inner::FnTupleVariant(inner) => Inner::FnTupleVariant(inner),
};

Ok(FunctionImpl { inner })
Expand Down Expand Up @@ -844,12 +789,6 @@ impl fmt::Debug for Function {
Inner::FnTupleStruct(tuple) => {
write!(f, "tuple {}", tuple.rtti.item)?;
}
Inner::FnUnitVariant(empty) => {
write!(f, "variant empty {}", empty.rtti.item)?;
}
Inner::FnTupleVariant(tuple) => {
write!(f, "variant tuple {}", tuple.rtti.item)?;
}
}

Ok(())
Expand All @@ -875,10 +814,6 @@ enum Inner<V> {
FnUnitStruct(FnUnitStruct),
/// Constructor for a tuple.
FnTupleStruct(FnTupleStruct),
/// Constructor for an empty variant.
FnUnitVariant(FnUnitVariant),
/// Constructor for a tuple variant.
FnTupleVariant(FnTupleVariant),
}

impl<V> TryClone for Inner<V>
Expand All @@ -892,8 +827,6 @@ where
Inner::FnClosureOffset(inner) => Inner::FnClosureOffset(inner.try_clone()?),
Inner::FnUnitStruct(inner) => Inner::FnUnitStruct(inner.clone()),
Inner::FnTupleStruct(inner) => Inner::FnTupleStruct(inner.clone()),
Inner::FnUnitVariant(inner) => Inner::FnUnitVariant(inner.clone()),
Inner::FnTupleVariant(inner) => Inner::FnTupleVariant(inner.clone()),
})
}
}
Expand Down Expand Up @@ -1029,20 +962,6 @@ struct FnTupleStruct {
args: usize,
}

#[derive(Debug, Clone, TryClone)]
struct FnUnitVariant {
/// Runtime information fo variant.
rtti: Arc<Rtti>,
}

#[derive(Debug, Clone, TryClone)]
struct FnTupleVariant {
/// Runtime information fo variant.
rtti: Arc<Rtti>,
/// The number of arguments the tuple takes.
args: usize,
}

impl FromValue for SyncFunction {
#[inline]
fn from_value(value: Value) -> Result<Self, RuntimeError> {
Expand Down
21 changes: 0 additions & 21 deletions crates/rune/src/runtime/inst.rs
Original file line number Diff line number Diff line change
Expand Up @@ -664,27 +664,6 @@ pub enum Inst {
/// Where to write the constructed struct.
out: Output,
},
/// Construct a push an object variant of the given type onto the stack. The
/// number of elements in the object are determined the slot of the object
/// keys `slot` and are popped from the stack.
///
/// For each element, a value is popped corresponding to the object key.
///
/// # Operation
///
/// ```text
/// <value..>
/// => <object>
/// ```
#[musli(packed)]
StructVariant {
/// The address to load fields from.
addr: InstAddress,
/// The type hash of the object variant to construct.
hash: Hash,
/// Where to write the constructed variant.
out: Output,
},
/// Load a literal string from a static string slot.
///
/// # Operation
Expand Down
5 changes: 1 addition & 4 deletions crates/rune/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,7 @@ pub use self::value::{
Accessor, EmptyStruct, Inline, RawValueGuard, Rtti, Struct, TupleStruct, TypeValue, Value,
ValueMutGuard, ValueRefGuard,
};
pub(crate) use self::value::{Mutable, ReprMut, ReprOwned, ReprRef};

mod variant;
pub use self::variant::{Variant, VariantData};
pub(crate) use self::value::{Mutable, ReprMut, ReprRef};

pub mod slice;

Expand Down
1 change: 1 addition & 0 deletions crates/rune/src/runtime/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,7 @@ impl TryClone for Stack {
}

impl TryFromIteratorIn<Value, Global> for Stack {
#[inline]
fn try_from_iter_in<T: IntoIterator<Item = Value>>(
iter: T,
alloc: Global,
Expand Down
Loading

0 comments on commit 84acd09

Please sign in to comment.