Skip to content

Commit

Permalink
Auto merge of #97293 - est31:remove_box, r=oli-obk
Browse files Browse the repository at this point in the history
Add #[rustc_box] and use it inside alloc

This commit adds an alternative content boxing syntax, and uses it inside alloc.

```Rust
#![feature(box_syntax)]

fn foo() {
    let foo = box bar;
}
```

is equivalent to

```Rust
#![feature(rustc_attrs)]

fn foo() {
    let foo = #[rustc_box] Box::new(bar);
}
```

The usage inside the very performance relevant code in
liballoc is the only remaining relevant usage of box syntax
in the compiler (outside of tests, which are comparatively easy to port).

box syntax was originally designed to be used by all Rust
developers. This introduces a replacement syntax more tailored
to only being used inside the Rust compiler, and with it,
lays the groundwork for eventually removing box syntax.

[Earlier work](#87781 (comment)) by `@nbdd0121` to lower `Box::new` to `box` during THIR -> MIR building ran into borrow checker problems, requiring the lowering to be adjusted in a way that led to [performance regressions](#87781 (comment)). The proposed change in this PR lowers `#[rustc_box] Box::new` -> `box` in the AST -> HIR lowering step, which is way earlier in the compiler, and thus should cause less issues both performance wise as well as regarding type inference/borrow checking/etc. Hopefully, future work can move the lowering further back in the compiler, as long as there are no performance regressions.
  • Loading branch information
bors committed Jun 2, 2022
2 parents 9598b4b + 0a24b94 commit 20976ba
Show file tree
Hide file tree
Showing 8 changed files with 80 additions and 11 deletions.
17 changes: 16 additions & 1 deletion compiler/rustc_ast_lowering/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,22 @@ impl<'hir> LoweringContext<'_, 'hir> {
}
ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
ExprKind::Call(ref f, ref args) => {
if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
if e.attrs.get(0).map_or(false, |a| a.has_name(sym::rustc_box)) {
if let [inner] = &args[..] && e.attrs.len() == 1 {
let kind = hir::ExprKind::Box(self.lower_expr(&inner));
let hir_id = self.lower_node_id(e.id);
return hir::Expr { hir_id, kind, span: self.lower_span(e.span) };
} else {
self.sess
.struct_span_err(
e.span,
"#[rustc_box] requires precisely one argument \
and no other attributes are allowed",
)
.emit();
hir::ExprKind::Err
}
} else if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
} else {
let f = self.lower_expr(f);
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,12 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
"#[rustc_has_incoherent_inherent_impls] allows the addition of incoherent inherent impls for \
the given type by annotating all impl items with #[rustc_allow_incoherent_impl]."
),
rustc_attr!(
rustc_box, AttributeType::Normal, template!(Word), ErrorFollowing,
"#[rustc_box] allows creating boxes \
and it is only intended to be used in `alloc`."
),

BuiltinAttribute {
name: sym::rustc_diagnostic_item,
// FIXME: This can be `true` once we always use `tcx.is_diagnostic_item`.
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1173,6 +1173,7 @@ symbols! {
rustc_allow_const_fn_unstable,
rustc_allow_incoherent_impl,
rustc_attrs,
rustc_box,
rustc_builtin_macro,
rustc_capture_analysis,
rustc_clean,
Expand Down
30 changes: 26 additions & 4 deletions library/alloc/src/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,25 @@ impl<T> Box<T> {
/// ```
/// let five = Box::new(5);
/// ```
#[cfg(not(no_global_oom_handling))]
#[cfg(all(not(no_global_oom_handling), not(bootstrap)))]
#[inline(always)]
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn new(x: T) -> Self {
#[rustc_box]
Box::new(x)
}

/// Allocates memory on the heap and then places `x` into it.
///
/// This doesn't actually allocate if `T` is zero-sized.
///
/// # Examples
///
/// ```
/// let five = Box::new(5);
/// ```
#[cfg(all(not(no_global_oom_handling), bootstrap))]
#[inline(always)]
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
Expand Down Expand Up @@ -273,7 +291,9 @@ impl<T> Box<T> {
#[must_use]
#[inline(always)]
pub fn pin(x: T) -> Pin<Box<T>> {
(box x).into()
(#[cfg_attr(not(bootstrap), rustc_box)]
Box::new(x))
.into()
}

/// Allocates memory on the heap then places `x` into it,
Expand Down Expand Up @@ -1219,7 +1239,8 @@ unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
impl<T: Default> Default for Box<T> {
/// Creates a `Box<T>`, with the `Default` value for T.
fn default() -> Self {
box T::default()
#[cfg_attr(not(bootstrap), rustc_box)]
Box::new(T::default())
}
}

Expand Down Expand Up @@ -1583,7 +1604,8 @@ impl<T, const N: usize> From<[T; N]> for Box<[T]> {
/// println!("{boxed:?}");
/// ```
fn from(array: [T; N]) -> Box<[T]> {
box array
#[cfg_attr(not(bootstrap), rustc_box)]
Box::new(array)
}
}

Expand Down
3 changes: 2 additions & 1 deletion library/alloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@
#![feature(allocator_internals)]
#![feature(allow_internal_unstable)]
#![feature(associated_type_bounds)]
#![feature(box_syntax)]
#![cfg_attr(bootstrap, feature(box_syntax))]
#![feature(cfg_sanitize)]
#![feature(const_deref)]
#![feature(const_mut_refs)]
Expand All @@ -171,6 +171,7 @@
#![feature(rustc_attrs)]
#![feature(slice_internals)]
#![feature(staged_api)]
#![feature(stmt_expr_attributes)]
#![cfg_attr(test, feature(test))]
#![feature(unboxed_closures)]
#![feature(unsized_fn_params)]
Expand Down
25 changes: 23 additions & 2 deletions library/alloc/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,28 @@
/// be mindful of side effects.
///
/// [`Vec`]: crate::vec::Vec
#[cfg(all(not(no_global_oom_handling), not(test)))]
#[cfg(all(not(no_global_oom_handling), not(test), not(bootstrap)))]
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_diagnostic_item = "vec_macro"]
#[allow_internal_unstable(rustc_attrs, liballoc_internals)]
macro_rules! vec {
() => (
$crate::__rust_force_expr!($crate::vec::Vec::new())
);
($elem:expr; $n:expr) => (
$crate::__rust_force_expr!($crate::vec::from_elem($elem, $n))
);
($($x:expr),+ $(,)?) => (
$crate::__rust_force_expr!(<[_]>::into_vec(
#[rustc_box]
$crate::boxed::Box::new([$($x),+])
))
);
}

/// Creates a `Vec` containing the arguments (bootstrap version).
#[cfg(all(not(no_global_oom_handling), not(test), bootstrap))]
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_diagnostic_item = "vec_macro"]
Expand Down Expand Up @@ -65,7 +86,7 @@ macro_rules! vec {
$crate::vec::from_elem($elem, $n)
);
($($x:expr),*) => (
$crate::slice::into_vec(box [$($x),*])
$crate::slice::into_vec($crate::boxed::Box::new([$($x),*]))
);
($($x:expr,)*) => (vec![$($x),*])
}
Expand Down
7 changes: 5 additions & 2 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2987,12 +2987,15 @@ impl<T, const N: usize> From<[T; N]> for Vec<T> {
/// ```
#[cfg(not(test))]
fn from(s: [T; N]) -> Vec<T> {
<[T]>::into_vec(box s)
<[T]>::into_vec(
#[cfg_attr(not(bootstrap), rustc_box)]
Box::new(s),
)
}

#[cfg(test)]
fn from(s: [T; N]) -> Vec<T> {
crate::slice::into_vec(box s)
crate::slice::into_vec(Box::new(s))
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/type/ascription/issue-47666.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error: expected type, found `<[_]>::into_vec(box [0, 1])`
error: expected type, found `<[_]>::into_vec(#[rustc_box] ::alloc::boxed::Box::new([0, 1]))`
--> $DIR/issue-47666.rs:3:25
|
LL | let _ = Option:Some(vec![0, 1]);
Expand Down

0 comments on commit 20976ba

Please sign in to comment.