From a938f0972ff7da264977efd0cfaa12784deac078 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Wed, 31 Jul 2024 22:39:40 +0000 Subject: [PATCH] Detect `*` operator on `!Sized` expression ``` error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/unsized-str-in-return-expr-arg-and-local.rs:15:9 | LL | let x = *""; | ^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `str` = note: all local variables must have a statically known size = help: unsized locals are gated as an unstable feature help: references to `!Sized` types like `&str` are `Sized`; consider not dereferencing the expression | LL - let x = *""; LL + let x = ""; | ``` --- compiler/rustc_hir_typeck/src/expr.rs | 6 +- compiler/rustc_middle/src/traits/mod.rs | 2 +- .../src/error_reporting/traits/suggestions.rs | 60 +++++++++++++-- tests/ui/dst/dst-rvalue.stderr | 10 +++ tests/ui/issues/issue-17651.stderr | 5 ++ tests/ui/sized/unsized-binding.stderr | 5 ++ ...nsized-str-in-return-expr-arg-and-local.rs | 30 ++++++++ ...ed-str-in-return-expr-arg-and-local.stderr | 74 +++++++++++++++++++ .../suggestions/issue-84973-blacklist.stderr | 5 ++ tests/ui/unsized/unsized6.stderr | 10 +++ 10 files changed, 198 insertions(+), 9 deletions(-) create mode 100644 tests/ui/sized/unsized-str-in-return-expr-arg-and-local.rs create mode 100644 tests/ui/sized/unsized-str-in-return-expr-arg-and-local.stderr diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index f3266e04f8194..6cdda75f19d3a 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -841,6 +841,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ret_ty = ret_coercion.borrow().expected_ty(); let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty); let mut span = return_expr.span; + let mut hir_id = return_expr.hir_id; // Use the span of the trailing expression for our cause, // not the span of the entire function if !explicit_return @@ -848,6 +849,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let Some(last_expr) = body.expr { span = last_expr.span; + hir_id = last_expr.hir_id; } ret_coercion.borrow_mut().coerce( self, @@ -864,6 +866,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.select_obligations_where_possible(|errors| { self.point_at_return_for_opaque_ty_error( errors, + hir_id, span, return_expr_ty, return_expr.span, @@ -921,6 +924,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn point_at_return_for_opaque_ty_error( &self, errors: &mut Vec>, + hir_id: HirId, span: Span, return_expr_ty: Ty<'tcx>, return_span: Span, @@ -935,7 +939,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let new_cause = ObligationCause::new( cause.span, cause.body_id, - ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, span))), + ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, hir_id))), ); *cause = new_cause; } diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index d54e2ca0a74f7..a3277fb96d229 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -353,7 +353,7 @@ pub enum ObligationCauseCode<'tcx> { ReturnValue(HirId), /// Opaque return type of this function - OpaqueReturnType(Option<(Ty<'tcx>, Span)>), + OpaqueReturnType(Option<(Ty<'tcx>, HirId)>), /// Block implicit return BlockTailExpression(HirId, hir::MatchSource), diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 0d15ef55e24e7..5f730ae447f3c 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -2725,6 +2725,31 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let tcx = self.tcx; let predicate = predicate.upcast(tcx); + info!(?predicate, ?cause_code); + let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| { + if let Some(pred) = predicate.as_trait_clause() + && tcx.is_lang_item(pred.def_id(), LangItem::Sized) + && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind + { + let like_ty = match self + .typeck_results + .as_ref() + .and_then(|t| t.expr_ty_adjusted_opt(inner)) + { + Some(ty) => format!(" like `{}`", self.tcx.erase_regions(ty)), + None => String::new(), + }; + err.span_suggestion_verbose( + expr.span.until(inner.span), + format!( + "references to `!Sized` types{like_ty} are `Sized`; consider not \ + dereferencing the expression", + ), + String::new(), + Applicability::MaybeIncorrect, + ); + } + }; match *cause_code { ObligationCauseCode::ExprAssignable | ObligationCauseCode::MatchExpressionArm { .. } @@ -2771,6 +2796,19 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..) if !span.is_dummy() => { + if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code { + if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id) + && let hir::ExprKind::Call(_, args) = expr.kind + && let Some(expr) = args.get(*pos) + { + suggest_remove_deref(err, &expr); + } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id) + && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind + && let Some(expr) = args.get(*pos) + { + suggest_remove_deref(err, &expr); + } + } let item_name = tcx.def_path_str(item_def_id); let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id)); let mut multispan = MultiSpan::from(span); @@ -2968,6 +3006,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { )); err.downgrade_to_delayed_bug(); } + let mut local = true; match tcx.parent_hir_node(hir_id) { Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => { err.span_suggestion_verbose( @@ -2976,7 +3015,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { "&", Applicability::MachineApplicable, ); - err.note("all local variables must have a statically known size"); } Node::LetStmt(hir::LetStmt { init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }), @@ -2991,7 +3029,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { "&", Applicability::MachineApplicable, ); - err.note("all local variables must have a statically known size"); + } + Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => { + // When encountering an assignment of an unsized trait, like `let x = *"";`, + // we check if the RHS is a deref operation, to suggest removing it. + suggest_remove_deref(err, &expr); } Node::Param(param) => { err.span_suggestion_verbose( @@ -3001,10 +3043,12 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { "&", Applicability::MachineApplicable, ); + local = false; } - _ => { - err.note("all local variables must have a statically known size"); - } + _ => {} + } + if local { + err.note("all local variables must have a statically known size"); } if !tcx.features().unsized_locals { err.help("unsized locals are gated as an unstable feature"); @@ -3527,14 +3571,16 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ); } ObligationCauseCode::OpaqueReturnType(expr_info) => { - if let Some((expr_ty, expr_span)) = expr_info { + if let Some((expr_ty, hir_id)) = expr_info { let expr_ty = self.tcx.short_ty_string(expr_ty, &mut long_ty_file); + let expr = self.infcx.tcx.hir().expect_expr(hir_id); err.span_label( - expr_span, + expr.span, with_forced_trimmed_paths!(format!( "return type was inferred to be `{expr_ty}` here", )), ); + suggest_remove_deref(err, &expr); } } } diff --git a/tests/ui/dst/dst-rvalue.stderr b/tests/ui/dst/dst-rvalue.stderr index 8d0a82b707dda..8ee60a8149174 100644 --- a/tests/ui/dst/dst-rvalue.stderr +++ b/tests/ui/dst/dst-rvalue.stderr @@ -9,6 +9,11 @@ LL | let _x: Box = Box::new(*"hello world"); = help: the trait `Sized` is not implemented for `str` note: required by a bound in `Box::::new` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL +help: references to `!Sized` types like `&str` are `Sized`; consider not dereferencing the expression + | +LL - let _x: Box = Box::new(*"hello world"); +LL + let _x: Box = Box::new("hello world"); + | error[E0277]: the size for values of type `[isize]` cannot be known at compilation time --> $DIR/dst-rvalue.rs:8:37 @@ -21,6 +26,11 @@ LL | let _x: Box<[isize]> = Box::new(*array); = help: the trait `Sized` is not implemented for `[isize]` note: required by a bound in `Box::::new` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL +help: references to `!Sized` types like `&[isize]` are `Sized`; consider not dereferencing the expression + | +LL - let _x: Box<[isize]> = Box::new(*array); +LL + let _x: Box<[isize]> = Box::new(array); + | error: aborting due to 2 previous errors diff --git a/tests/ui/issues/issue-17651.stderr b/tests/ui/issues/issue-17651.stderr index 0c95a3c0c40d8..6927ea1520e8d 100644 --- a/tests/ui/issues/issue-17651.stderr +++ b/tests/ui/issues/issue-17651.stderr @@ -9,6 +9,11 @@ LL | (|| Box::new(*(&[0][..])))(); = help: the trait `Sized` is not implemented for `[{integer}]` note: required by a bound in `Box::::new` --> $SRC_DIR/alloc/src/boxed.rs:LL:COL +help: references to `!Sized` types like `&[{integer}]` are `Sized`; consider not dereferencing the expression + | +LL - (|| Box::new(*(&[0][..])))(); +LL + (|| Box::new((&[0][..])))(); + | error: aborting due to 1 previous error diff --git a/tests/ui/sized/unsized-binding.stderr b/tests/ui/sized/unsized-binding.stderr index 7c3276032c2b4..2dc711257be8b 100644 --- a/tests/ui/sized/unsized-binding.stderr +++ b/tests/ui/sized/unsized-binding.stderr @@ -7,6 +7,11 @@ LL | let x = *""; = help: the trait `Sized` is not implemented for `str` = note: all local variables must have a statically known size = help: unsized locals are gated as an unstable feature +help: references to `!Sized` types like `&str` are `Sized`; consider not dereferencing the expression + | +LL - let x = *""; +LL + let x = ""; + | error: aborting due to 1 previous error diff --git a/tests/ui/sized/unsized-str-in-return-expr-arg-and-local.rs b/tests/ui/sized/unsized-str-in-return-expr-arg-and-local.rs new file mode 100644 index 0000000000000..35abbb80d99e5 --- /dev/null +++ b/tests/ui/sized/unsized-str-in-return-expr-arg-and-local.rs @@ -0,0 +1,30 @@ +fn foo() -> impl Sized { +//~^ ERROR the size for values of type `str` cannot be known at compilation time +//~| HELP the trait `Sized` is not implemented for `str` + *"" //~ HELP consider not dereferencing the expression +} +fn bar(_: impl Sized) {} +struct S; + +impl S { + fn baz(&self, _: impl Sized) {} +} + +fn main() { + let _ = foo(); + let x = *""; + //~^ ERROR the size for values of type `str` cannot be known at compilation time + //~| HELP consider not dereferencing the expression + //~| HELP the trait `Sized` is not implemented for `str` + //~| HELP unsized locals are gated as an unstable feature + bar(x); + S.baz(x); + bar(*""); + //~^ ERROR the size for values of type `str` cannot be known at compilation time + //~| HELP consider not dereferencing the expression + //~| HELP the trait `Sized` is not implemented for `str` + S.baz(*""); + //~^ ERROR the size for values of type `str` cannot be known at compilation time + //~| HELP consider not dereferencing the expression + //~| HELP the trait `Sized` is not implemented for `str` +} diff --git a/tests/ui/sized/unsized-str-in-return-expr-arg-and-local.stderr b/tests/ui/sized/unsized-str-in-return-expr-arg-and-local.stderr new file mode 100644 index 0000000000000..2cd858a47be99 --- /dev/null +++ b/tests/ui/sized/unsized-str-in-return-expr-arg-and-local.stderr @@ -0,0 +1,74 @@ +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/unsized-str-in-return-expr-arg-and-local.rs:1:13 + | +LL | fn foo() -> impl Sized { + | ^^^^^^^^^^ doesn't have a size known at compile-time +... +LL | *"" + | --- return type was inferred to be `str` here + | + = help: the trait `Sized` is not implemented for `str` +help: references to `!Sized` types like `&str` are `Sized`; consider not dereferencing the expression + | +LL - *"" +LL + "" + | + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/unsized-str-in-return-expr-arg-and-local.rs:15:9 + | +LL | let x = *""; + | ^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` + = note: all local variables must have a statically known size + = help: unsized locals are gated as an unstable feature +help: references to `!Sized` types like `&str` are `Sized`; consider not dereferencing the expression + | +LL - let x = *""; +LL + let x = ""; + | + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/unsized-str-in-return-expr-arg-and-local.rs:22:9 + | +LL | bar(*""); + | --- ^^^ doesn't have a size known at compile-time + | | + | required by a bound introduced by this call + | + = help: the trait `Sized` is not implemented for `str` +note: required by a bound in `bar` + --> $DIR/unsized-str-in-return-expr-arg-and-local.rs:6:16 + | +LL | fn bar(_: impl Sized) {} + | ^^^^^ required by this bound in `bar` +help: references to `!Sized` types like `&str` are `Sized`; consider not dereferencing the expression + | +LL - bar(*""); +LL + bar(""); + | + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/unsized-str-in-return-expr-arg-and-local.rs:26:11 + | +LL | S.baz(*""); + | --- ^^^ doesn't have a size known at compile-time + | | + | required by a bound introduced by this call + | + = help: the trait `Sized` is not implemented for `str` +note: required by a bound in `S::baz` + --> $DIR/unsized-str-in-return-expr-arg-and-local.rs:10:27 + | +LL | fn baz(&self, _: impl Sized) {} + | ^^^^^ required by this bound in `S::baz` +help: references to `!Sized` types like `&str` are `Sized`; consider not dereferencing the expression + | +LL - S.baz(*""); +LL + S.baz(""); + | + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/suggestions/issue-84973-blacklist.stderr b/tests/ui/suggestions/issue-84973-blacklist.stderr index 4fd063e46926a..0db534f5326e3 100644 --- a/tests/ui/suggestions/issue-84973-blacklist.stderr +++ b/tests/ui/suggestions/issue-84973-blacklist.stderr @@ -66,6 +66,11 @@ note: required by a bound in `f_sized` | LL | fn f_sized(t: T) {} | ^^^^^ required by this bound in `f_sized` +help: references to `!Sized` types like `&dyn Fn()` are `Sized`; consider not dereferencing the expression + | +LL - f_sized(*ref_cl); +LL + f_sized(ref_cl); + | error[E0277]: `Rc<{integer}>` cannot be sent between threads safely --> $DIR/issue-84973-blacklist.rs:27:12 diff --git a/tests/ui/unsized/unsized6.stderr b/tests/ui/unsized/unsized6.stderr index 56e7f60f9ff08..e75299eea79bf 100644 --- a/tests/ui/unsized/unsized6.stderr +++ b/tests/ui/unsized/unsized6.stderr @@ -123,6 +123,11 @@ help: consider removing the `?Sized` bound to make the type parameter `Sized` LL - fn f3(x1: Box, x2: Box, x3: Box) { LL + fn f3(x1: Box, x2: Box, x3: Box) { | +help: references to `!Sized` types like `Box` are `Sized`; consider not dereferencing the expression + | +LL - let y = *x2; +LL + let y = x2; + | error[E0277]: the size for values of type `X` cannot be known at compilation time --> $DIR/unsized6.rs:26:10 @@ -177,6 +182,11 @@ help: consider removing the `?Sized` bound to make the type parameter `Sized` LL - fn f4(x1: Box, x2: Box, x3: Box) { LL + fn f4(x1: Box, x2: Box, x3: Box) { | +help: references to `!Sized` types like `Box` are `Sized`; consider not dereferencing the expression + | +LL - let y = *x2; +LL + let y = x2; + | error[E0277]: the size for values of type `X` cannot be known at compilation time --> $DIR/unsized6.rs:34:10