Skip to content

Commit d845769

Browse files
committed
Restrict #[rustc_box] to Box::new calls
1 parent c4e0cd9 commit d845769

File tree

9 files changed

+115
-29
lines changed

9 files changed

+115
-29
lines changed

compiler/rustc_ast_lowering/locales/en-US.ftl

-3
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,6 @@ ast_lowering_misplaced_impl_trait =
2222
ast_lowering_misplaced_assoc_ty_binding =
2323
associated type bounds are only allowed in where clauses and function signatures, not in {$position}
2424
25-
ast_lowering_rustc_box_attribute_error =
26-
#[rustc_box] requires precisely one argument and no other attributes are allowed
27-
2825
ast_lowering_underscore_expr_lhs_assign =
2926
in expressions, `_` can only be used on the left-hand side of an assignment
3027
.label = `_` not allowed here

compiler/rustc_ast_lowering/src/errors.rs

-7
Original file line numberDiff line numberDiff line change
@@ -87,13 +87,6 @@ pub struct MisplacedAssocTyBinding<'a> {
8787
pub position: DiagnosticArgFromDisplay<'a>,
8888
}
8989

90-
#[derive(Diagnostic, Clone, Copy)]
91-
#[diag(ast_lowering_rustc_box_attribute_error)]
92-
pub struct RustcBoxAttributeError {
93-
#[primary_span]
94-
pub span: Span,
95-
}
96-
9790
#[derive(Diagnostic, Clone, Copy)]
9891
#[diag(ast_lowering_underscore_expr_lhs_assign)]
9992
pub struct UnderscoreExprLhsAssign {

compiler/rustc_ast_lowering/src/expr.rs

+2-10
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use super::errors::{
22
AsyncGeneratorsNotSupported, AsyncNonMoveClosureNotSupported, AwaitOnlyInAsyncFnAndBlocks,
33
BaseExpressionDoubleDot, ClosureCannotBeStatic, FunctionalRecordUpdateDestructuringAssignemnt,
44
GeneratorTooManyParameters, InclusiveRangeWithNoEnd, NotSupportedForLifetimeBinderAsyncClosure,
5-
RustcBoxAttributeError, UnderscoreExprLhsAssign,
5+
UnderscoreExprLhsAssign,
66
};
77
use super::ResolverAstLoweringExt;
88
use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
@@ -83,15 +83,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
8383
}
8484
ExprKind::Tup(elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
8585
ExprKind::Call(f, args) => {
86-
if e.attrs.get(0).map_or(false, |a| a.has_name(sym::rustc_box)) {
87-
if let [inner] = &args[..] && e.attrs.len() == 1 {
88-
let kind = hir::ExprKind::Box(self.lower_expr(&inner));
89-
return hir::Expr { hir_id, kind, span: self.lower_span(e.span) };
90-
} else {
91-
let guar = self.tcx.sess.emit_err(RustcBoxAttributeError { span: e.span });
92-
hir::ExprKind::Err(guar)
93-
}
94-
} else if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
86+
if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
9587
self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
9688
} else {
9789
let f = self.lower_expr(f);

compiler/rustc_mir_build/locales/en-US.ftl

+6
Original file line numberDiff line numberDiff line change
@@ -374,3 +374,9 @@ mir_build_suggest_let_else = you might want to use `let else` to handle the {$co
374374
} matched
375375
376376
mir_build_suggest_attempted_int_lit = alternatively, you could prepend the pattern with an underscore to define a new named variable; identifiers cannot begin with digits
377+
378+
379+
mir_build_rustc_box_attribute_error = `#[rustc_box]` attribute used incorrectly
380+
.attributes = no other attributes may be applied
381+
.not_box = `#[rustc_box]` may only be applied to a `Box::new()` call
382+
.missing_box = `#[rustc_box]` requires the `owned_box` lang item

compiler/rustc_mir_build/src/errors.rs

+19
Original file line numberDiff line numberDiff line change
@@ -888,3 +888,22 @@ pub enum MiscPatternSuggestion {
888888
start_span: Span,
889889
},
890890
}
891+
892+
#[derive(Diagnostic)]
893+
#[diag(mir_build_rustc_box_attribute_error)]
894+
pub struct RustcBoxAttributeError {
895+
#[primary_span]
896+
pub span: Span,
897+
#[subdiagnostic]
898+
pub reason: RustcBoxAttrReason,
899+
}
900+
901+
#[derive(Subdiagnostic)]
902+
pub enum RustcBoxAttrReason {
903+
#[note(mir_build_attributes)]
904+
Attributes,
905+
#[note(mir_build_not_box)]
906+
NotBoxNew,
907+
#[note(mir_build_missing_box)]
908+
MissingBox,
909+
}

compiler/rustc_mir_build/src/thir/cx/expr.rs

+31-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::errors;
12
use crate::thir::cx::region::Scope;
23
use crate::thir::cx::Cx;
34
use crate::thir::util::UserAnnotatedTyHelpers;
@@ -18,7 +19,7 @@ use rustc_middle::ty::subst::InternalSubsts;
1819
use rustc_middle::ty::{
1920
self, AdtKind, InlineConstSubsts, InlineConstSubstsParts, ScalarInt, Ty, UpvarSubsts, UserType,
2021
};
21-
use rustc_span::Span;
22+
use rustc_span::{sym, Span};
2223
use rustc_target::abi::VariantIdx;
2324

2425
impl<'tcx> Cx<'tcx> {
@@ -262,6 +263,7 @@ impl<'tcx> Cx<'tcx> {
262263
}
263264
}
264265

266+
#[instrument(level = "debug", skip(self), ret)]
265267
fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx> {
266268
let tcx = self.tcx;
267269
let expr_ty = self.typeck_results().expr_ty(expr);
@@ -322,6 +324,34 @@ impl<'tcx> Cx<'tcx> {
322324
fn_span: expr.span,
323325
}
324326
} else {
327+
let attrs = tcx.hir().attrs(expr.hir_id);
328+
if attrs.iter().any(|a| a.name_or_empty() == sym::rustc_box) {
329+
if attrs.len() != 1 {
330+
tcx.sess.emit_err(errors::RustcBoxAttributeError {
331+
span: attrs[0].span,
332+
reason: errors::RustcBoxAttrReason::Attributes,
333+
});
334+
} else if let Some(box_item) = tcx.lang_items().owned_box() {
335+
if let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, fn_path)) = fun.kind
336+
&& let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind
337+
&& path.res.opt_def_id().map_or(false, |did| did == box_item)
338+
&& fn_path.ident.name == sym::new
339+
&& let [value] = args
340+
{
341+
return Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind: ExprKind::Box { value: self.mirror_expr(value) } }
342+
} else {
343+
tcx.sess.emit_err(errors::RustcBoxAttributeError {
344+
span: expr.span,
345+
reason: errors::RustcBoxAttrReason::NotBoxNew
346+
});
347+
}
348+
} else {
349+
tcx.sess.emit_err(errors::RustcBoxAttributeError {
350+
span: attrs[0].span,
351+
reason: errors::RustcBoxAttrReason::MissingBox,
352+
});
353+
}
354+
}
325355
let adt_data =
326356
if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = fun.kind {
327357
// Tuple-like ADTs are represented as ExprKind::Call. We convert them here.

src/tools/clippy/clippy_utils/src/higher.rs

+5-8
Original file line numberDiff line numberDiff line change
@@ -287,15 +287,12 @@ impl<'a> VecArgs<'a> {
287287
Some(VecArgs::Repeat(&args[0], &args[1]))
288288
} else if match_def_path(cx, fun_def_id, &paths::SLICE_INTO_VEC) && args.len() == 1 {
289289
// `vec![a, b, c]` case
290-
if_chain! {
291-
if let hir::ExprKind::Box(boxed) = args[0].kind;
292-
if let hir::ExprKind::Array(args) = boxed.kind;
293-
then {
294-
return Some(VecArgs::Vec(args));
295-
}
290+
if let hir::ExprKind::Call(_, [arg]) = &args[0].kind
291+
&& let hir::ExprKind::Array(args) = arg.kind {
292+
Some(VecArgs::Vec(args))
293+
} else {
294+
None
296295
}
297-
298-
None
299296
} else if match_def_path(cx, fun_def_id, &paths::VEC_NEW) && args.is_empty() {
300297
Some(VecArgs::Vec(&[]))
301298
} else {

tests/ui/attributes/rustc-box.rs

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#![feature(rustc_attrs, stmt_expr_attributes)]
2+
3+
fn foo(_: u32, _: u32) {}
4+
fn bar(_: u32) {}
5+
6+
fn main() {
7+
#[rustc_box]
8+
Box::new(1); // OK
9+
#[rustc_box]
10+
Box::pin(1); //~ ERROR `#[rustc_box]` attribute used incorrectly
11+
#[rustc_box]
12+
foo(1, 1); //~ ERROR `#[rustc_box]` attribute used incorrectly
13+
#[rustc_box]
14+
bar(1); //~ ERROR `#[rustc_box]` attribute used incorrectly
15+
#[rustc_box] //~ ERROR `#[rustc_box]` attribute used incorrectly
16+
#[rustfmt::skip]
17+
Box::new(1);
18+
}

tests/ui/attributes/rustc-box.stderr

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
error: `#[rustc_box]` attribute used incorrectly
2+
--> $DIR/rustc-box.rs:10:5
3+
|
4+
LL | Box::pin(1);
5+
| ^^^^^^^^^^^
6+
|
7+
= note: `#[rustc_box]` may only be applied to a `Box::new()` call
8+
9+
error: `#[rustc_box]` attribute used incorrectly
10+
--> $DIR/rustc-box.rs:12:5
11+
|
12+
LL | foo(1, 1);
13+
| ^^^^^^^^^
14+
|
15+
= note: `#[rustc_box]` may only be applied to a `Box::new()` call
16+
17+
error: `#[rustc_box]` attribute used incorrectly
18+
--> $DIR/rustc-box.rs:14:5
19+
|
20+
LL | bar(1);
21+
| ^^^^^^
22+
|
23+
= note: `#[rustc_box]` may only be applied to a `Box::new()` call
24+
25+
error: `#[rustc_box]` attribute used incorrectly
26+
--> $DIR/rustc-box.rs:15:5
27+
|
28+
LL | #[rustc_box]
29+
| ^^^^^^^^^^^^
30+
|
31+
= note: no other attributes may be applied
32+
33+
error: aborting due to 4 previous errors
34+

0 commit comments

Comments
 (0)