diff --git a/book/src/sandboxing.md b/book/src/sandboxing.md index e4bda7747..2cb7ca8ba 100644 --- a/book/src/sandboxing.md +++ b/book/src/sandboxing.md @@ -29,8 +29,8 @@ Memory limiting is performed using the [`with` function] in the `rune::alloc::limit` module. ```rust +use rune::alloc::prelude::*; use rune::alloc::limit; -use rune::alloc::Vec; let f = limit::with(1024, || { let mut vec = Vec::::try_with_capacity(256)?; diff --git a/crates/rune-alloc/src/hashbrown/map.rs b/crates/rune-alloc/src/hashbrown/map.rs index 6b2c5a851..39d18f909 100644 --- a/crates/rune-alloc/src/hashbrown/map.rs +++ b/crates/rune-alloc/src/hashbrown/map.rs @@ -2907,20 +2907,24 @@ impl ExtractIfInner<'_, K, V, A> { /// # Examples /// /// ``` +/// use rune::alloc::prelude::*; /// use rune::alloc::HashMap; /// -/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].try_into()?; +/// let mut map: HashMap<_, _> = [ +/// (1, "One".try_to_owned()?), +/// (2, "Two".try_to_owned()?) +/// ].try_into()?; /// /// let mut values = map.values_mut(); -/// values.next().map(|v| v.push_str(" Mississippi")); -/// values.next().map(|v| v.push_str(" Mississippi")); +/// values.next().unwrap().try_push_str(" Mississippi")?; +/// values.next().unwrap().try_push_str(" Mississippi")?; /// /// // It is fused iterator /// assert_eq!(values.next(), None); /// assert_eq!(values.next(), None); /// -/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned()); -/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned()); +/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".try_to_owned()?); +/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".try_to_owned()?); /// # Ok::<_, rune::alloc::Error>(()) /// ``` pub struct ValuesMut<'a, K, V> { @@ -3004,8 +3008,9 @@ pub struct RawEntryBuilderMut<'a, K, V, S, A: Allocator = Global> { /// /// ``` /// use core::hash::{BuildHasher, Hash}; -/// use rune::alloc::hash_map::{HashMap, RawEntryMut, RawOccupiedEntryMut}; +/// /// use rune::alloc::prelude::*; +/// use rune::alloc::hash_map::{HashMap, RawEntryMut, RawOccupiedEntryMut}; /// /// let mut map = HashMap::new(); /// map.try_extend([('a', 1), ('b', 2), ('c', 3)])?; @@ -3067,7 +3072,7 @@ pub struct RawEntryBuilderMut<'a, K, V, S, A: Allocator = Global> { /// /// println!("Our HashMap: {:?}", map); /// -/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect(); +/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).try_collect()?; /// // The `Iter` iterator produces items in arbitrary order, so the /// // items must be sorted to test them against a sorted array. /// vec.sort_unstable(); @@ -4379,8 +4384,8 @@ impl Debug for RawEntryBuilder<'_, K, V, S, A> { /// # Examples /// /// ``` -/// use rune::alloc::hash_map::{Entry, HashMap, OccupiedEntry}; /// use rune::alloc::prelude::*; +/// use rune::alloc::hash_map::{Entry, HashMap, OccupiedEntry}; /// /// let mut map = HashMap::new(); /// map.try_extend([("a", 10), ("b", 20), ("c", 30)])?; @@ -4407,7 +4412,7 @@ impl Debug for RawEntryBuilder<'_, K, V, S, A> { /// /// println!("Our HashMap: {:?}", map); /// -/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect(); +/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).try_collect()?; /// // The `Iter` iterator produces items in arbitrary order, so the /// // items must be sorted to test them against a sorted array. /// vec.sort_unstable(); @@ -4596,15 +4601,20 @@ impl Debug for VacantEntry<'_, K, V, S, A> { /// # Examples /// /// ``` -/// use rune::alloc::hash_map::{EntryRef, HashMap, OccupiedEntryRef}; /// use rune::alloc::prelude::*; +/// use rune::alloc::hash_map::{EntryRef, HashMap, OccupiedEntryRef}; /// /// let mut map = HashMap::new(); -/// map.try_extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)])?; +/// map.try_extend([ +/// ("a".try_to_owned()?, 10), +/// ("b".try_to_owned()?, 20), +/// ("c".try_to_owned()?, 30) +/// ])?; +/// /// assert_eq!(map.len(), 3); /// /// // Existing key (try_insert) -/// let key = String::from("a"); +/// let key = String::try_from("a")?; /// let entry: EntryRef<_, _, _, _> = map.entry_ref(&key); /// let _raw_o: OccupiedEntryRef<_, _, _, _> = entry.try_insert(1)?; /// assert_eq!(map.len(), 3); @@ -4685,14 +4695,14 @@ enum KeyOrRef<'a, K, Q: ?Sized> { } impl<'a, K, Q: ?Sized> KeyOrRef<'a, K, Q> { - fn into_owned(self) -> K + fn try_into_owned(self) -> Result where - K: From<&'a Q>, + K: TryFrom<&'a Q>, { - match self { - Self::Borrowed(borrowed) => borrowed.into(), + Ok(match self { + Self::Borrowed(borrowed) => borrowed.try_into()?, Self::Owned(owned) => owned, - } + }) } } @@ -4717,9 +4727,14 @@ impl<'a, K: Borrow, Q: ?Sized> AsRef for KeyOrRef<'a, K, Q> { /// use rune::alloc::prelude::*; /// /// let mut map = HashMap::new(); -/// map.try_extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)])?; /// -/// let key = String::from("a"); +/// map.try_extend([ +/// ("a".try_to_owned()?, 10), +/// ("b".try_to_owned()?, 20), +/// ("c".try_to_owned()?, 30) +/// ])?; +/// +/// let key = String::try_from("a")?; /// let _entry_o: OccupiedEntryRef<_, _, _, _> = map.entry_ref(&key).try_insert(100)?; /// assert_eq!(map.len(), 3); /// @@ -4741,7 +4756,7 @@ impl<'a, K: Borrow, Q: ?Sized> AsRef for KeyOrRef<'a, K, Q> { /// match map.entry_ref("c") { /// EntryRef::Vacant(_) => unreachable!(), /// EntryRef::Occupied(view) => { -/// assert_eq!(view.remove_entry(), ("c".to_owned(), 30)); +/// assert_eq!(view.remove_entry(), ("c".try_to_owned()?, 30)); /// } /// } /// assert_eq!(map.get("c"), None); @@ -5987,7 +6002,8 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> { #[cfg_attr(feature = "inline-more", inline)] pub fn try_insert(self, value: V) -> Result, Error> where - K: Hash + From<&'b Q>, + K: Hash + TryFrom<&'b Q>, + Error: From, S: BuildHasher, { match self { @@ -6002,7 +6018,8 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> { #[cfg(test)] pub(crate) fn insert(self, value: V) -> OccupiedEntryRef<'a, 'b, K, Q, V, S, A> where - K: Hash + From<&'b Q>, + K: Hash + TryFrom<&'b Q>, + Error: From, S: BuildHasher, { self.try_insert(value).abort() @@ -6030,7 +6047,8 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> { #[cfg_attr(feature = "inline-more", inline)] pub fn or_try_insert(self, default: V) -> Result<&'a mut V, Error> where - K: Hash + From<&'b Q>, + K: Hash + TryFrom<&'b Q>, + Error: From, S: BuildHasher, { match self { @@ -6042,7 +6060,8 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> { #[cfg(test)] pub(crate) fn or_insert(self, default: V) -> &'a mut V where - K: Hash + From<&'b Q>, + K: Hash + TryFrom<&'b Q>, + Error: From, S: BuildHasher, { self.or_try_insert(default).abort() @@ -6070,7 +6089,8 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> { #[cfg_attr(feature = "inline-more", inline)] pub fn or_try_insert_with V>(self, default: F) -> Result<&'a mut V, Error> where - K: Hash + From<&'b Q>, + K: Hash + TryFrom<&'b Q>, + Error: From, S: BuildHasher, { match self { @@ -6102,7 +6122,8 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> { #[cfg_attr(feature = "inline-more", inline)] pub fn or_try_insert_with_key V>(self, default: F) -> Result<&'a mut V, Error> where - K: Hash + Borrow + From<&'b Q>, + K: Hash + Borrow + TryFrom<&'b Q>, + Error: From, S: BuildHasher, { match self { @@ -6266,7 +6287,8 @@ impl<'a, 'b, K, Q: ?Sized, V: Default, S, A: Allocator> EntryRef<'a, 'b, K, Q, V #[cfg_attr(feature = "inline-more", inline)] pub fn or_try_default(self) -> Result<&'a mut V, Error> where - K: Hash + From<&'b Q>, + K: Hash + TryFrom<&'b Q>, + Error: From, S: BuildHasher, { match self { @@ -6486,7 +6508,7 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> OccupiedEntryRef<'a, 'b, K, Q, V, /// /// match map.entry_ref("Stringthing") { /// EntryRef::Occupied(entry) => { - /// let (old_key, old_value): (Rc, u32) = entry.replace_entry(16); + /// let (old_key, old_value): (Rc, u32) = entry.try_replace_entry(16)?; /// assert!(Rc::ptr_eq(&key, &old_key) && old_value == 15); /// } /// EntryRef::Vacant(_) => panic!(), @@ -6497,16 +6519,17 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> OccupiedEntryRef<'a, 'b, K, Q, V, /// # Ok::<_, rune::alloc::Error>(()) /// ``` #[cfg_attr(feature = "inline-more", inline)] - pub fn replace_entry(self, value: V) -> (K, V) + pub fn try_replace_entry(self, value: V) -> Result<(K, V), Error> where - K: From<&'b Q>, + K: TryFrom<&'b Q>, + Error: From, { let entry = unsafe { self.elem.as_mut() }; - let old_key = mem::replace(&mut entry.0, self.key.unwrap().into_owned()); + let old_key = mem::replace(&mut entry.0, self.key.unwrap().try_into_owned()?); let old_value = mem::replace(&mut entry.1, value); - (old_key, old_value) + Ok((old_key, old_value)) } /// Replaces the key in the hash map with the key used to create this entry. @@ -6519,9 +6542,11 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> OccupiedEntryRef<'a, 'b, K, Q, V, /// # Examples /// /// ``` - /// use rune::alloc::hash_map::{EntryRef, HashMap}; /// use std::rc::Rc; /// + /// use rune::alloc::hash_map::{EntryRef, HashMap}; + /// use rune::alloc::Error; + /// /// let mut map: HashMap, usize> = HashMap::try_with_capacity(6)?; /// let mut keys: Vec> = Vec::with_capacity(6); /// @@ -6539,23 +6564,28 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> OccupiedEntryRef<'a, 'b, K, Q, V, /// /// assert!(keys.iter().all(|key| Rc::strong_count(key) == 1)); /// - /// fn reclaim_memory(map: &mut HashMap, usize>, keys: &[Rc]) { + /// fn reclaim_memory(map: &mut HashMap, usize>, keys: &[Rc]) -> Result<(), Error> { /// for key in keys { /// if let EntryRef::Occupied(entry) = map.entry_ref(key.as_ref()) { /// // Replaces the entry's key with our version of it in `keys`. - /// entry.replace_key(); + /// entry.try_replace_key()?; /// } /// } + /// + /// Ok(()) /// } /// # Ok::<_, rune::alloc::Error>(()) /// ``` #[cfg_attr(feature = "inline-more", inline)] - pub fn replace_key(self) -> K + pub fn try_replace_key(self) -> Result where - K: From<&'b Q>, + K: TryFrom<&'b Q>, { let entry = unsafe { self.elem.as_mut() }; - mem::replace(&mut entry.0, self.key.unwrap().into_owned()) + Ok(mem::replace( + &mut entry.0, + self.key.unwrap().try_into_owned()?, + )) } /// Provides shared access to the key and owned access to the value of @@ -6671,15 +6701,17 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'a, 'b, K, Q, V, S /// let key: &str = "poneyland"; /// /// if let EntryRef::Vacant(v) = map.entry_ref(key) { - /// assert_eq!(v.into_key(), "poneyland"); + /// assert_eq!(v.try_into_key()?, "poneyland"); /// } + /// # Ok::<_, rune::alloc::Error>(()) /// ``` #[cfg_attr(feature = "inline-more", inline)] - pub fn into_key(self) -> K + pub fn try_into_key(self) -> Result where - K: From<&'b Q>, + K: TryFrom<&'b Q>, + Error: From, { - self.key.into_owned() + Ok(self.key.try_into_owned()?) } /// Sets the value of the entry with the VacantEntryRef's key, and returns a @@ -6704,7 +6736,8 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'a, 'b, K, Q, V, S #[cfg_attr(feature = "inline-more", inline)] pub fn try_insert(self, value: V) -> Result<&'a mut V, Error> where - K: Hash + From<&'b Q>, + K: Hash + TryFrom<&'b Q>, + Error: From, S: BuildHasher, { let table = &mut self.table.table; @@ -6713,7 +6746,7 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'a, 'b, K, Q, V, S let entry = into_ok_try(table.insert_entry( &mut (), self.hash, - (self.key.into_owned(), value), + (self.key.try_into_owned()?, value), hasher.into_tuple(), ))?; @@ -6723,7 +6756,8 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'a, 'b, K, Q, V, S #[cfg(test)] pub(crate) fn insert(self, value: V) -> &'a mut V where - K: Hash + From<&'b Q>, + K: Hash + TryFrom<&'b Q>, + Error: From, S: BuildHasher, { self.try_insert(value).abort() @@ -6732,15 +6766,16 @@ impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'a, 'b, K, Q, V, S #[cfg_attr(feature = "inline-more", inline)] fn try_insert_entry(self, value: V) -> Result, Error> where + K: Hash + TryFrom<&'b Q>, + Error: From, S: BuildHasher, - K: Hash + From<&'b Q>, { let hasher = make_hasher::(&self.table.hash_builder); let elem = into_ok_try(self.table.table.insert( &mut (), self.hash, - (self.key.into_owned(), value), + (self.key.try_into_owned()?, value), hasher.into_tuple(), ))?; @@ -6884,8 +6919,8 @@ where /// # Examples /// /// ``` - /// use rune::alloc::hash_map::HashMap; /// use rune::alloc::prelude::*; + /// use rune::alloc::HashMap; /// /// let mut map = HashMap::new(); /// map.try_insert(1, 100)?; @@ -6897,7 +6932,7 @@ where /// // So that the map.get(&1) doesn't return Some(&100). /// assert_eq!(map.get(&1), Some(&1)); /// - /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)]; + /// let some_vec: Vec<_> = try_vec![(3, 3), (4, 4)]; /// map.try_extend(some_vec.iter().map(|(k, v)| (k, v)))?; /// /// let some_arr = [(5, 5), (6, 6)]; @@ -6908,7 +6943,7 @@ where /// new_map.try_extend(&map)?; /// assert_eq!(new_map, map); /// - /// let mut vec: Vec<_> = new_map.into_iter().collect(); + /// let mut vec: Vec<_> = new_map.into_iter().try_collect()?; /// // The `IntoIter` iterator produces items in arbitrary order, so the /// // items must be sorted to test them against a sorted array. /// vec.sort_unstable(); @@ -6952,8 +6987,8 @@ where /// # Examples /// /// ``` - /// use rune::alloc::hash_map::HashMap; /// use rune::alloc::prelude::*; + /// use rune::alloc::HashMap; /// /// let mut map = HashMap::new(); /// map.try_insert(1, 100)?; @@ -6965,13 +7000,13 @@ where /// // So that the map.get(&1) doesn't return Some(&100). /// assert_eq!(map.get(&1), Some(&1)); /// - /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)]; + /// let some_vec: Vec<_> = try_vec![(3, 3), (4, 4)]; /// map.try_extend(&some_vec)?; /// /// let some_arr = [(5, 5), (6, 6)]; /// map.try_extend(&some_arr)?; /// - /// let mut vec: Vec<_> = map.into_iter().collect(); + /// let mut vec: Vec<_> = map.into_iter().try_collect()?; /// // The `IntoIter` iterator produces items in arbitrary order, so the /// // items must be sorted to test them against a sorted array. /// vec.sort_unstable(); diff --git a/crates/rune-alloc/src/hashbrown/mod.rs b/crates/rune-alloc/src/hashbrown/mod.rs index 805a671a6..ee542ad17 100644 --- a/crates/rune-alloc/src/hashbrown/mod.rs +++ b/crates/rune-alloc/src/hashbrown/mod.rs @@ -161,11 +161,12 @@ pub trait Equivalent { fn equivalent(&self, key: &K) -> bool; } -impl Equivalent for Q +impl Equivalent for Q where - Q: Eq, - K: core::borrow::Borrow, + Q: ?Sized + Eq, + K: ?Sized + core::borrow::Borrow, { + #[inline] fn equivalent(&self, key: &K) -> bool { self == key.borrow() } diff --git a/crates/rune-alloc/src/hashbrown/set.rs b/crates/rune-alloc/src/hashbrown/set.rs index ec3395672..22446fcae 100644 --- a/crates/rune-alloc/src/hashbrown/set.rs +++ b/crates/rune-alloc/src/hashbrown/set.rs @@ -1632,12 +1632,12 @@ impl IntoIterator for HashSet { /// # Examples /// /// ``` - /// use rune::alloc::{HashSet, Vec}; /// use rune::alloc::prelude::*; + /// use rune::alloc::HashSet; /// /// let mut set = HashSet::new(); - /// set.try_insert("a".to_string())?; - /// set.try_insert("b".to_string())?; + /// set.try_insert("a".try_to_string()?)?; + /// set.try_insert("b".try_to_string()?)?; /// /// // Not possible to collect to a Vec with a regular `.iter()`. /// let v: Vec = set.into_iter().try_collect()?; diff --git a/crates/rune-alloc/src/lib.rs b/crates/rune-alloc/src/lib.rs index 3084c75f3..dea2742fa 100644 --- a/crates/rune-alloc/src/lib.rs +++ b/crates/rune-alloc/src/lib.rs @@ -138,11 +138,15 @@ pub mod callable; pub mod prelude { //! Prelude for common traits used in combination with this crate which //! matches the behavior of the std prelude. + pub use crate::borrow::TryToOwned; + pub use crate::boxed::Box; pub use crate::clone::{TryClone, TryCopy}; pub use crate::iter::{IteratorExt, TryExtend, TryFromIterator, TryFromIteratorIn}; pub use crate::option::OptionExt; - pub use crate::string::TryToString; + pub use crate::string::{String, TryToString}; + pub use crate::vec::Vec; + pub use crate::{try_format, try_vec}; } pub mod limit; diff --git a/crates/rune-alloc/src/string/mod.rs b/crates/rune-alloc/src/string/mod.rs index f11447c94..0ac87e3c8 100644 --- a/crates/rune-alloc/src/string/mod.rs +++ b/crates/rune-alloc/src/string/mod.rs @@ -9,7 +9,6 @@ //! There are multiple ways to create a new [`String`] from a string literal: //! //! ``` -//! use rune::alloc::String; //! use rune::alloc::prelude::*; //! //! let s = "Hello".try_to_string()?; @@ -23,7 +22,6 @@ //! it. You can do the reverse too. //! //! ``` -//! use rune::alloc::{try_vec, String}; //! use rune::alloc::prelude::*; //! //! let sparkle_heart = try_vec![240, 159, 146, 150]; @@ -34,7 +32,7 @@ //! let bytes = sparkle_heart.into_bytes(); //! //! assert_eq!(bytes, [240, 159, 146, 150]); -//! # Ok::<_, Box>(()) +//! # Ok::<_, std::boxed::Box>(()) //! ``` #[cfg(feature = "serde")] @@ -2092,6 +2090,16 @@ impl From> for ::rust_alloc::string::String { } } +#[cfg(feature = "alloc")] +impl From<&String> for ::rust_alloc::string::String { + /// Try to convert a [`String`] reference into a std `String`. + /// + /// The result is allocated on the heap. + fn from(s: &String) -> Self { + Self::from(s.as_str()) + } +} + impl TryFrom<&str> for String { type Error = Error; @@ -2142,6 +2150,30 @@ impl TryFrom> for String { } } +impl TryFrom<&String> for String { + type Error = Error; + + /// Converts the given [`String`] to a boxed `str` slice that is owned. + /// + /// # Examples + /// + /// ``` + /// use rune::alloc::{String, Box}; + /// + /// let s1: String = String::try_from("Hello World")?; + /// let s2: String = String::try_from(&s1)?; + /// + /// assert_eq!(s2, "Hello World"); + /// # Ok::<_, rune::alloc::Error>(()) + /// ``` + #[inline] + fn try_from(s: &String) -> Result { + let mut this = String::new_in(s.allocator().clone()); + this.try_push_str(s.as_str())?; + Ok(this) + } +} + impl TryFrom> for Box { type Error = Error; @@ -2158,7 +2190,8 @@ impl TryFrom> for Box { /// assert_eq!("Hello World", s2.as_ref()); /// # Ok::<_, rune::alloc::Error>(()) /// ``` - fn try_from(s: String) -> Result, Error> { + #[inline] + fn try_from(s: String) -> Result { s.try_into_boxed_str() } } @@ -2179,6 +2212,7 @@ impl TryFrom> for Box { /// assert_eq!("Hello World", s2.as_ref()); /// # Ok::<_, rune::alloc::Error>(()) /// ``` + #[inline] fn try_from(s: Cow<'_, str>) -> Result { Self::try_from(s.as_ref()) } @@ -2200,6 +2234,7 @@ impl From> for Vec { /// } /// # Ok::<_, rune::alloc::Error>(()) /// ``` + #[inline] fn from(string: String) -> Vec { string.into_bytes() } diff --git a/crates/rune-core/src/item/component.rs b/crates/rune-core/src/item/component.rs index 09abf4a4c..25ac4a1e4 100644 --- a/crates/rune-core/src/item/component.rs +++ b/crates/rune-core/src/item/component.rs @@ -1,11 +1,9 @@ use core::fmt; -use crate::alloc::Box; - use serde::{Deserialize, Serialize}; use crate::alloc; -use crate::alloc::clone::TryClone; +use crate::alloc::prelude::*; use crate::item::ComponentRef; /// The component of an item. diff --git a/crates/rune-macros/tests/derive.rs b/crates/rune-macros/tests/derive.rs index 489fc8436..5efb3e584 100644 --- a/crates/rune-macros/tests/derive.rs +++ b/crates/rune-macros/tests/derive.rs @@ -1,19 +1,15 @@ +#![allow(unused)] + use rune::T; use rune_macros::*; -#[test] -fn derive_outside_rune() { - #[derive(Debug, Clone, PartialEq, Eq, ToTokens, Parse, Spanned)] - struct SomeThing { - eq: T![=], - } +#[derive(Debug, Clone, PartialEq, Eq, ToTokens, Parse, Spanned)] +struct SomeThing { + eq: T![=], } -#[test] -fn generic_derive() { - #[derive(Debug, Clone, PartialEq, Eq, ToTokens, Parse, Spanned)] - struct EqValue { - eq: rune::ast::Eq, - value: T, - } +#[derive(Debug, Clone, PartialEq, Eq, ToTokens, Parse, Spanned)] +struct EqValue { + eq: rune::ast::Eq, + value: T, } diff --git a/crates/rune/src/ast/attribute.rs b/crates/rune/src/ast/attribute.rs index f392910d0..e650e07b7 100644 --- a/crates/rune/src/ast/attribute.rs +++ b/crates/rune/src/ast/attribute.rs @@ -153,7 +153,8 @@ impl Parse for AttrStyle { } /// Helper struct to only parse inner attributes. -pub(crate) struct InnerAttribute(#[allow(unused)] pub(crate) Attribute); +#[allow(unused)] +pub(crate) struct InnerAttribute(pub(crate) Attribute); impl Parse for InnerAttribute { fn parse(p: &mut Parser) -> Result { diff --git a/crates/rune/src/ast/prelude.rs b/crates/rune/src/ast/prelude.rs index 52e661e47..23370ab40 100644 --- a/crates/rune/src/ast/prelude.rs +++ b/crates/rune/src/ast/prelude.rs @@ -1,8 +1,8 @@ //! Prelude for ast elements. pub(crate) use crate as rune; +pub(crate) use crate::alloc; pub(crate) use crate::alloc::prelude::*; -pub(crate) use crate::alloc::{self, try_vec, Box, String, Vec}; pub(crate) use crate::ast; pub(crate) use crate::ast::{OptionSpanned, Span, Spanned}; pub(crate) use crate::compile::{self, ErrorKind}; diff --git a/crates/rune/src/cli/doc.rs b/crates/rune/src/cli/doc.rs index 0e400a70d..a7b0bcaa2 100644 --- a/crates/rune/src/cli/doc.rs +++ b/crates/rune/src/cli/doc.rs @@ -7,7 +7,6 @@ use anyhow::{Context, Result}; use clap::Parser; use crate::alloc::prelude::*; -use crate::alloc::Vec; use crate::cli::naming::Naming; use crate::cli::{AssetKind, CommandBase, Config, Entry, EntryPoint, ExitCode, Io, SharedFlags}; use crate::compile::{FileSourceLoader, ItemBuf}; diff --git a/crates/rune/src/cli/tests.rs b/crates/rune/src/cli/tests.rs index efde525ef..a0a0ac502 100644 --- a/crates/rune/src/cli/tests.rs +++ b/crates/rune/src/cli/tests.rs @@ -5,7 +5,6 @@ use std::time::Instant; use anyhow::{bail, Context, Result}; use crate::alloc::prelude::*; -use crate::alloc::Vec; use crate::cli::naming::Naming; use crate::cli::visitor; use crate::cli::{ diff --git a/crates/rune/src/cli/visitor.rs b/crates/rune/src/cli/visitor.rs index 238ea15ec..16543c6c0 100644 --- a/crates/rune/src/cli/visitor.rs +++ b/crates/rune/src/cli/visitor.rs @@ -1,5 +1,4 @@ use crate::alloc::prelude::*; -use crate::alloc::Vec; use crate::compile::meta; use crate::compile::{CompileVisitor, ItemBuf, MetaError, MetaRef}; use crate::Hash; diff --git a/crates/rune/src/compile/assembly.rs b/crates/rune/src/compile/assembly.rs index d6151d3c1..62d3075c0 100644 --- a/crates/rune/src/compile/assembly.rs +++ b/crates/rune/src/compile/assembly.rs @@ -6,7 +6,6 @@ use crate as rune; use crate::alloc::fmt::TryWrite; use crate::alloc::prelude::*; use crate::alloc::{hash_map, HashMap}; -use crate::alloc::{try_vec, String, Vec}; use crate::ast::{Span, Spanned}; use crate::compile::{self, Location}; use crate::runtime::{Inst, Label}; diff --git a/crates/rune/src/compile/compile.rs b/crates/rune/src/compile/compile.rs index 8db8b54f5..0aadcff0a 100644 --- a/crates/rune/src/compile/compile.rs +++ b/crates/rune/src/compile/compile.rs @@ -1,5 +1,5 @@ +use crate::alloc; use crate::alloc::prelude::*; -use crate::alloc::{self, try_vec, Box, Vec}; use crate::ast; use crate::ast::{Span, Spanned}; use crate::compile::v1; diff --git a/crates/rune/src/compile/error.rs b/crates/rune/src/compile/error.rs index 1a1a7d8ba..cb393ae0f 100644 --- a/crates/rune/src/compile/error.rs +++ b/crates/rune/src/compile/error.rs @@ -794,14 +794,14 @@ impl fmt::Display for ErrorKind { current, existing, } => { - write!(f,"Conflicting static string for hash `{hash}`\n between `{existing:?}` and `{current:?}`")?; + write!(f,"Conflicting static string for hash `{hash}` between `{existing:?}` and `{current:?}`")?; } ErrorKind::StaticBytesHashConflict { hash, current, existing, } => { - write!(f,"Conflicting static string for hash `{hash}`\n between `{existing:?}` and `{current:?}`")?; + write!(f,"Conflicting static string for hash `{hash}` between `{existing:?}` and `{current:?}`")?; } ErrorKind::StaticObjectKeysMissing { hash, slot } => { write!( @@ -816,10 +816,10 @@ impl fmt::Display for ErrorKind { current, existing, } => { - write!(f,"Conflicting static object keys for hash `{hash}`\n between `{existing:?}` and `{current:?}`")?; + write!(f,"Conflicting static object keys for hash `{hash}` between `{existing:?}` and `{current:?}`")?; } ErrorKind::MissingLoopLabel { label } => { - write!(f, "Missing loop label `{label}`", label = label)?; + write!(f, "Missing loop label `{label}`")?; } ErrorKind::ExpectedLeadingPathSegment => { write!(f, "Segment is only supported in the first position")?; @@ -846,14 +846,10 @@ impl fmt::Display for ErrorKind { write!(f, "Attribute `#[bench]` is not supported on nested items")?; } ErrorKind::MissingFunctionHash { hash } => { - write!(f, "Missing function with hash `{hash}`", hash = hash)?; + write!(f, "Missing function with hash `{hash}`")?; } ErrorKind::FunctionConflictHash { hash } => { - write!( - f, - "Conflicting function already exists `{hash}`", - hash = hash - )?; + write!(f, "Conflicting function already exists `{hash}`")?; } ErrorKind::PatternMissingFields { item, .. } => { write!(f, "Non-exhaustive pattern for `{item}`")?; diff --git a/crates/rune/src/compile/ir/compiler.rs b/crates/rune/src/compile/ir/compiler.rs index bb6e82e0d..518234ee4 100644 --- a/crates/rune/src/compile/ir/compiler.rs +++ b/crates/rune/src/compile/ir/compiler.rs @@ -1,4 +1,4 @@ -use core::mem::{replace, take}; +use core::mem::take; use crate::alloc::prelude::*; use crate::alloc::{try_format, Box, Vec}; @@ -304,32 +304,22 @@ pub(crate) fn block(hir: &hir::Block<'_>, c: &mut Ctxt<'_, '_>) -> compile::Resu let mut instructions = Vec::new(); for stmt in hir.statements { - let (e, term) = match stmt { + match stmt { hir::Stmt::Local(l) => { if let Some((e, _)) = take(&mut last) { instructions.try_push(expr(e, c)?)?; } instructions.try_push(local(l, c)?)?; - continue; } - hir::Stmt::Expr(e) => (e, false), - hir::Stmt::Semi(e) => (e, true), - hir::Stmt::Item(..) => continue, + hir::Stmt::Expr(e) => { + instructions.try_push(expr(e, c)?)?; + } }; - - if let Some((e, _)) = replace(&mut last, Some((e, term))) { - instructions.try_push(expr(e, c)?)?; - } } - let last = if let Some((e, term)) = last { - if term { - instructions.try_push(expr(e, c)?)?; - None - } else { - Some(Box::try_new(expr(e, c)?)?) - } + let last = if let Some(e) = hir.value { + Some(Box::try_new(expr(e, c)?)?) } else { None }; diff --git a/crates/rune/src/compile/ir/scopes.rs b/crates/rune/src/compile/ir/scopes.rs index ce8ce5de3..9da2e8a01 100644 --- a/crates/rune/src/compile/ir/scopes.rs +++ b/crates/rune/src/compile/ir/scopes.rs @@ -1,5 +1,5 @@ use crate::alloc::prelude::*; -use crate::alloc::{self, try_vec, Box, HashMap, Vec}; +use crate::alloc::{self, HashMap}; use crate::ast::Spanned; use crate::compile::{self, ErrorKind}; use crate::hir; diff --git a/crates/rune/src/compile/v1/assemble.rs b/crates/rune/src/compile/v1/assemble.rs index 34288e430..6c5675a85 100644 --- a/crates/rune/src/compile/v1/assemble.rs +++ b/crates/rune/src/compile/v1/assemble.rs @@ -1,5 +1,3 @@ -use core::mem::{replace, take}; - use crate as rune; use crate::alloc::prelude::*; use crate::alloc::{try_format, Vec}; @@ -201,7 +199,7 @@ impl<'hir> Asm<'hir> { /// Assemble into an instruction. fn apply(self, cx: &mut Ctxt) -> compile::Result<()> { if let AsmKind::Var(var) = self.kind { - var.copy(cx, &self.span, &format_args!("var `{}`", var))?; + var.copy(cx, &self.span, None)?; } Ok(()) @@ -253,14 +251,14 @@ pub(crate) fn fn_from_item_fn<'hir>( pat_with_offset(cx, pat, offset)?; } - if hir.body.statements.is_empty() { + if hir.body.statements.is_empty() && hir.body.value.is_none() { let total_var_count = cx.scopes.total(hir)?; cx.locals_pop(total_var_count, hir)?; cx.asm.push(Inst::ReturnUnit, hir)?; return Ok(()); } - if !hir.body.produces_nothing() { + if hir.body.value.is_some() { return_(cx, hir, &hir.body, block)?; } else { block(cx, &hir.body, Needs::None)?.apply(cx)?; @@ -681,38 +679,20 @@ fn block<'hir>( cx.contexts.try_push(hir.span())?; let scopes_count = cx.scopes.child(hir)?; - let mut last = None::<(&hir::Expr<'_>, bool)>; - for stmt in hir.statements { - let (e, semi) = match stmt { - hir::Stmt::Local(l) => { - if let Some((e, _)) = take(&mut last) { - // NB: terminated expressions do not need to produce a value. - expr(cx, e, Needs::None)?.apply(cx)?; - } - - local(cx, l, Needs::None)?.apply(cx)?; - continue; + match stmt { + hir::Stmt::Local(hir) => { + local(cx, hir, Needs::None)?.apply(cx)?; + } + hir::Stmt::Expr(hir) => { + expr(cx, hir, Needs::None)?.apply(cx)?; } - hir::Stmt::Expr(expr) => (expr, false), - hir::Stmt::Semi(expr) => (expr, true), - hir::Stmt::Item(..) => continue, - }; - - if let Some((e, _)) = replace(&mut last, Some((e, semi))) { - // NB: terminated expressions do not need to produce a value. - expr(cx, e, Needs::None)?.apply(cx)?; } } - let produced = if let Some((e, semi)) = last { - if semi { - expr(cx, e, Needs::None)?.apply(cx)?; - false - } else { - expr(cx, e, needs)?.apply(cx)?; - true - } + let produced = if let Some(e) = hir.value { + expr(cx, e, needs)?.apply(cx)?; + true } else { false }; @@ -1255,10 +1235,10 @@ fn expr_async_block<'hir>( for capture in hir.captures.iter().copied() { if hir.do_move { let var = cx.scopes.take(&mut cx.q, capture, span)?; - var.do_move(cx.asm, span, &"capture")?; + var.do_move(cx.asm, span, Some(&"capture"))?; } else { let var = cx.scopes.get(&mut cx.q, capture, span)?; - var.copy(cx, span, &"capture")?; + var.copy(cx, span, Some(&"capture"))?; } } @@ -1380,7 +1360,7 @@ fn expr_call<'hir>( cx.scopes.alloc(span)?; } - var.copy(cx, span, &"call")?; + var.copy(cx, span, Some(&"call"))?; cx.scopes.alloc(span)?; cx.asm.push(Inst::CallFn { args }, span)?; @@ -1459,10 +1439,10 @@ fn expr_call_closure<'hir>( for capture in hir.captures.iter().copied() { if hir.do_move { let var = cx.scopes.take(&mut cx.q, capture, span)?; - var.do_move(cx.asm, span, &"capture")?; + var.do_move(cx.asm, span, Some(&"capture"))?; } else { let var = cx.scopes.get(&mut cx.q, capture, span)?; - var.copy(cx, span, &"capture")?; + var.copy(cx, span, Some(&"capture"))?; } } diff --git a/crates/rune/src/compile/v1/scopes.rs b/crates/rune/src/compile/v1/scopes.rs index 017f7bdf5..965f5e18a 100644 --- a/crates/rune/src/compile/v1/scopes.rs +++ b/crates/rune/src/compile/v1/scopes.rs @@ -2,7 +2,7 @@ use core::fmt; use crate as rune; use crate::alloc::prelude::*; -use crate::alloc::{self, try_format, try_vec, HashMap, Vec}; +use crate::alloc::{self, HashMap}; use crate::ast::Spanned; use crate::compile::v1::Ctxt; use crate::compile::{self, Assembly, ErrorKind, WithSpan}; @@ -50,14 +50,14 @@ impl<'hir> Var<'hir> { &self, cx: &mut Ctxt<'_, '_, '_>, span: &dyn Spanned, - comment: &dyn fmt::Display, + comment: Option<&dyn fmt::Display>, ) -> compile::Result<()> { cx.asm.push_with_comment( Inst::Copy { offset: self.offset, }, span, - &format_args!("var `{}`; {comment}", self.name), + &format_args!("var `{}`{}", self.name, Append("; ", comment)), ) } @@ -66,18 +66,36 @@ impl<'hir> Var<'hir> { &self, asm: &mut Assembly, span: &dyn Spanned, - comment: &dyn fmt::Display, + comment: Option<&dyn fmt::Display>, ) -> compile::Result<()> { asm.push_with_comment( Inst::Move { offset: self.offset, }, span, - &format_args!("var `{}`; {comment}", self.name), + &format_args!("var `{}`{}", self.name, Append("; ", comment)), ) } } +struct Append(P, T); + +impl fmt::Display for Append +where + P: fmt::Display, + T: Copy + IntoIterator, + T::Item: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for item in self.1 { + self.0.fmt(f)?; + item.fmt(f)?; + } + + Ok(()) + } +} + #[derive(Debug, TryClone)] pub(crate) struct Layer<'hir> { /// Named variables. diff --git a/crates/rune/src/fmt.rs b/crates/rune/src/fmt.rs index 2da05acdd..87352a613 100644 --- a/crates/rune/src/fmt.rs +++ b/crates/rune/src/fmt.rs @@ -9,8 +9,7 @@ mod indent_writer; mod printer; mod whitespace; -use crate::alloc::String; -use crate::alloc::Vec; +use crate::alloc::prelude::*; use crate::ast; use crate::parse::{Parse, Parser}; use crate::SourceId; diff --git a/crates/rune/src/fmt/comments.rs b/crates/rune/src/fmt/comments.rs index d60f5b9ae..058dda7c5 100644 --- a/crates/rune/src/fmt/comments.rs +++ b/crates/rune/src/fmt/comments.rs @@ -5,7 +5,7 @@ mod tests; use core::str::CharIndices; -use crate::alloc::Vec; +use crate::alloc::prelude::*; use crate::ast::Span; use crate::fmt::FormattingError; diff --git a/crates/rune/src/fmt/indent_writer.rs b/crates/rune/src/fmt/indent_writer.rs index 61e1a5092..ec676f7f3 100644 --- a/crates/rune/src/fmt/indent_writer.rs +++ b/crates/rune/src/fmt/indent_writer.rs @@ -6,9 +6,9 @@ mod tests; use core::ops::{Deref, DerefMut}; use core::str; +use crate::alloc; use crate::alloc::fmt::TryWrite; use crate::alloc::prelude::*; -use crate::alloc::{self, try_vec, Vec}; use crate::ast::{ByteIndex, Span}; use super::comments::Comment; diff --git a/crates/rune/src/fmt/printer.rs b/crates/rune/src/fmt/printer.rs index fae59dae9..ebbd3f073 100644 --- a/crates/rune/src/fmt/printer.rs +++ b/crates/rune/src/fmt/printer.rs @@ -4,7 +4,6 @@ use core::mem::take; use crate::alloc::fmt::TryWrite; use crate::alloc::prelude::*; -use crate::alloc::Vec; use crate::ast::{self, Span, Spanned}; use super::error::FormattingError; diff --git a/crates/rune/src/hir/arena.rs b/crates/rune/src/hir/arena.rs index a28b12a90..aff8844c7 100644 --- a/crates/rune/src/hir/arena.rs +++ b/crates/rune/src/hir/arena.rs @@ -9,7 +9,8 @@ use core::ptr; use core::slice; use core::str; -use crate::alloc::{self, try_vec, Box, HashMap, Vec}; +use crate::alloc::prelude::*; +use crate::alloc::{self, HashMap}; #[non_exhaustive] pub struct ArenaWriteSliceOutOfBounds { diff --git a/crates/rune/src/hir/hir.rs b/crates/rune/src/hir/hir.rs index 3e3320444..37696cf5e 100644 --- a/crates/rune/src/hir/hir.rs +++ b/crates/rune/src/hir/hir.rs @@ -718,20 +718,13 @@ pub(crate) struct Block<'hir> { pub(crate) span: Span, /// Statements in the block. pub(crate) statements: &'hir [Stmt<'hir>], + /// Default value produced by the block. + pub(crate) value: Option<&'hir Expr<'hir>>, /// Variables that need to be dropped by the end of this block. #[allow(unused)] pub(crate) drop: &'hir [Name<'hir>], } -impl Block<'_> { - /// Test if the block doesn't produce anything. Which is when the last - /// element is either a non-expression or is an expression terminated by a - /// semi. - pub(crate) fn produces_nothing(&self) -> bool { - matches!(self.statements.last(), Some(Stmt::Semi(..)) | None) - } -} - #[derive(Debug, TryClone, Clone, Copy)] #[try_clone(copy)] pub(crate) struct AsyncBlock<'hir> { @@ -748,10 +741,6 @@ pub(crate) enum Stmt<'hir> { Local(&'hir Local<'hir>), /// An expression. Expr(&'hir Expr<'hir>), - /// An expression with a trailing semi-colon. - Semi(&'hir Expr<'hir>), - /// An ignored item. - Item(Span), } /// A local variable declaration `let = ;` diff --git a/crates/rune/src/hir/lowering.rs b/crates/rune/src/hir/lowering.rs index 68187953e..fc8060997 100644 --- a/crates/rune/src/hir/lowering.rs +++ b/crates/rune/src/hir/lowering.rs @@ -37,6 +37,7 @@ pub(crate) struct Ctxt<'hir, 'a, 'arena> { needs: Cell, scopes: hir::Scopes<'hir>, const_eval: bool, + statements: Vec>, } impl<'hir, 'a, 'arena> Ctxt<'hir, 'a, 'arena> { @@ -86,6 +87,7 @@ impl<'hir, 'a, 'arena> Ctxt<'hir, 'a, 'arena> { needs: Cell::new(Needs::default()), scopes: hir::Scopes::new()?, const_eval, + statements: Vec::new(), }) } @@ -120,24 +122,10 @@ pub(crate) fn empty_fn<'hir>( ast: &ast::EmptyBlock, span: &dyn Spanned, ) -> compile::Result> { - alloc_with!(cx, span); - - cx.scopes.push()?; - - let statements = iter!(&ast.statements, |ast| stmt(cx, ast)?); - - let layer = cx.scopes.pop().with_span(span)?; - - let body = hir::Block { - span: span.span(), - statements, - drop: iter!(layer.into_drop_order()), - }; - Ok(hir::ItemFn { span: span.span(), args: &[], - body, + body: statements(cx, &ast.statements, span)?, }) } /// Lower a function item. @@ -303,26 +291,66 @@ fn expr_call_closure<'hir>( }))) } -#[instrument(span = ast)] +#[inline] pub(crate) fn block<'hir>( cx: &mut Ctxt<'hir, '_, '_>, ast: &ast::Block, ) -> compile::Result> { - alloc_with!(cx, ast); + statements(cx, &ast.statements, ast) +} + +#[instrument(span = span)] +pub(crate) fn statements<'hir>( + cx: &mut Ctxt<'hir, '_, '_>, + statements: &[ast::Stmt], + span: &dyn Spanned, +) -> compile::Result> { + alloc_with!(cx, span); cx.scopes.push()?; - let statements = iter!(&ast.statements, |ast| stmt(cx, ast)?); + let at = cx.statements.len(); + + let mut value = None; + + for ast in statements { + let (last, stmt) = match ast { + ast::Stmt::Local(ast) => ( + value.take(), + Some(hir::Stmt::Local(alloc!(local(cx, ast)?))), + ), + ast::Stmt::Expr(ast) => ( + None, + value.replace(&*alloc!(expr(cx, ast)?)).map(hir::Stmt::Expr), + ), + ast::Stmt::Semi(ast) => ( + value.take(), + Some(hir::Stmt::Expr(alloc!(expr(cx, &ast.expr)?))), + ), + ast::Stmt::Item(..) => continue, + }; - let layer = cx.scopes.pop().with_span(ast)?; + if let Some(last) = last { + cx.statements + .try_push(hir::Stmt::Expr(last)) + .with_span(span)?; + } - let block = hir::Block { - span: ast.span(), + if let Some(stmt) = stmt { + cx.statements.try_push(stmt).with_span(span)?; + } + } + + let statements = iter!(cx.statements.drain(at..)); + + let layer = cx.scopes.pop().with_span(span)?; + + Ok(hir::Block { + span: span.span(), statements, + value, drop: iter!(layer.into_drop_order()), - }; - - Ok(block) + }) } #[instrument(span = ast)] @@ -1155,18 +1183,6 @@ fn local<'hir>(cx: &mut Ctxt<'hir, '_, '_>, ast: &ast::Local) -> compile::Result }) } -/// Lower a statement -fn stmt<'hir>(cx: &mut Ctxt<'hir, '_, '_>, ast: &ast::Stmt) -> compile::Result> { - alloc_with!(cx, ast); - - Ok(match ast { - ast::Stmt::Local(ast) => hir::Stmt::Local(alloc!(local(cx, ast)?)), - ast::Stmt::Expr(ast) => hir::Stmt::Expr(alloc!(expr(cx, ast)?)), - ast::Stmt::Semi(ast) => hir::Stmt::Semi(alloc!(expr(cx, &ast.expr)?)), - ast::Stmt::Item(..) => hir::Stmt::Item(ast.span()), - }) -} - fn pat<'hir>(cx: &mut Ctxt<'hir, '_, '_>, ast: &ast::Pat) -> compile::Result> { fn filter((ast, _): &(ast::Pat, Option)) -> Option<&ast::Pat> { if matches!(ast, ast::Pat::Binding(..) | ast::Pat::Rest(..)) { diff --git a/crates/rune/src/indexing.rs b/crates/rune/src/indexing.rs index 7088845e6..020b38156 100644 --- a/crates/rune/src/indexing.rs +++ b/crates/rune/src/indexing.rs @@ -4,7 +4,6 @@ mod scopes; use crate as rune; use crate::alloc::prelude::*; -use crate::alloc::Box; use crate::ast::{self, Span, Spanned}; use crate::compile::meta; use crate::compile::{ItemId, ItemMeta}; diff --git a/crates/rune/src/macros/token_stream.rs b/crates/rune/src/macros/token_stream.rs index 436fd8caf..bbc414e0e 100644 --- a/crates/rune/src/macros/token_stream.rs +++ b/crates/rune/src/macros/token_stream.rs @@ -4,9 +4,9 @@ use core::slice; use crate::compile; use crate as rune; +use crate::alloc; use crate::alloc::prelude::*; -use crate::alloc::vec::{self, Vec}; -use crate::alloc::{self, Box}; +use crate::alloc::vec; use crate::ast; use crate::ast::{OptionSpanned, Span}; use crate::macros::MacroContext; diff --git a/crates/rune/src/module/function_meta.rs b/crates/rune/src/module/function_meta.rs index 88bdc2977..c19739a15 100644 --- a/crates/rune/src/module/function_meta.rs +++ b/crates/rune/src/module/function_meta.rs @@ -3,11 +3,9 @@ use core::marker::PhantomData; use ::rust_alloc::sync::Arc; use crate as rune; +use crate::alloc; use crate::alloc::borrow::Cow; use crate::alloc::prelude::*; -#[cfg(feature = "doc")] -use crate::alloc::Vec; -use crate::alloc::{self, try_vec, Box}; use crate::compile::{self, meta, IntoComponent, ItemBuf}; use crate::hash::Hash; use crate::macros::{MacroContext, TokenStream}; diff --git a/crates/rune/src/modules/object.rs b/crates/rune/src/modules/object.rs index f71289f3b..82d4d9c7b 100644 --- a/crates/rune/src/modules/object.rs +++ b/crates/rune/src/modules/object.rs @@ -4,7 +4,6 @@ use core::cmp::Ordering; use crate as rune; use crate::alloc::prelude::*; -use crate::alloc::Vec; use crate::runtime::{EnvProtocolCaller, Iterator, Object, Protocol, Value, VmResult}; use crate::{ContextError, Module}; diff --git a/crates/rune/src/query/query.rs b/crates/rune/src/query/query.rs index 452ef8bb9..4377c17ff 100644 --- a/crates/rune/src/query/query.rs +++ b/crates/rune/src/query/query.rs @@ -7,7 +7,7 @@ use ::rust_alloc::sync::Arc; use crate::alloc::borrow::Cow; use crate::alloc::prelude::*; -use crate::alloc::{self, try_format, try_vec, BTreeMap, Box, HashSet, Vec, VecDeque}; +use crate::alloc::{self, BTreeMap, HashSet, VecDeque}; use crate::alloc::{hash_map, HashMap}; use crate::ast::{Span, Spanned}; use crate::compile::context::ContextMeta; diff --git a/crates/rune/src/runtime/vm_execution.rs b/crates/rune/src/runtime/vm_execution.rs index 1c0e83c45..8d67bd908 100644 --- a/crates/rune/src/runtime/vm_execution.rs +++ b/crates/rune/src/runtime/vm_execution.rs @@ -4,8 +4,7 @@ use core::mem::{replace, take}; use ::rust_alloc::sync::Arc; -use crate::alloc::clone::TryClone; -use crate::alloc::Vec; +use crate::alloc::prelude::*; use crate::runtime::budget; use crate::runtime::{ Generator, GeneratorState, RuntimeContext, Stream, Unit, Value, Vm, VmErrorKind, VmHalt, diff --git a/crates/rune/src/sources.rs b/crates/rune/src/sources.rs index feaaa1353..7d30a810c 100644 --- a/crates/rune/src/sources.rs +++ b/crates/rune/src/sources.rs @@ -2,9 +2,9 @@ use core::fmt; use core::num; use crate as rune; +use crate::alloc; use crate::alloc::path::Path; use crate::alloc::prelude::*; -use crate::alloc::{self, Vec}; use crate::ast::Span; use crate::source::Source; #[cfg(feature = "codespan-reporting")] diff --git a/crates/rune/src/worker/wildcard_import.rs b/crates/rune/src/worker/wildcard_import.rs index f6eca5573..057d853ec 100644 --- a/crates/rune/src/worker/wildcard_import.rs +++ b/crates/rune/src/worker/wildcard_import.rs @@ -1,5 +1,4 @@ use crate::alloc::prelude::*; -use crate::alloc::Vec; use crate::compile::{self, ErrorKind, IntoComponent, ItemBuf, Location, ModId, Visibility}; use crate::query::Query;