3 use crate::errors::{AddReturnTypeSuggestion, ExpectedReturnTypeLabel};
4 use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX};
5 use rustc_errors::{Applicability, Diagnostic, MultiSpan};
7 use rustc_hir::def::{CtorOf, DefKind};
8 use rustc_hir::lang_items::LangItem;
10 Expr, ExprKind, GenericBound, Node, Path, QPath, Stmt, StmtKind, TyKind, WherePredicate,
12 use rustc_hir_analysis::astconv::AstConv;
13 use rustc_infer::infer;
14 use rustc_infer::traits::{self, StatementAsExpression};
15 use rustc_middle::lint::in_external_macro;
16 use rustc_middle::ty::{
17 self, suggest_constraining_type_params, Binder, DefIdTree, IsSuggestable, ToPredicate, Ty,
19 use rustc_session::errors::ExprParenthesesNeeded;
20 use rustc_span::symbol::sym;
22 use rustc_trait_selection::infer::InferCtxtExt;
23 use rustc_trait_selection::traits::error_reporting::DefIdOrName;
24 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
25 use rustc_trait_selection::traits::NormalizeExt;
27 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
28 pub(crate) fn body_fn_sig(&self) -> Option<ty::FnSig<'tcx>> {
32 .get(self.tcx.hir().get_parent_node(self.body_id))
36 pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
37 // This suggestion is incorrect for
38 // fn foo() -> bool { match () { () => true } || match () { () => true } }
39 err.span_suggestion_short(
41 "consider using a semicolon here",
43 Applicability::MaybeIncorrect,
47 /// On implicit return expressions with mismatched types, provides the following suggestions:
49 /// - Points out the method's return type as the reason for the expected type.
50 /// - Possible missing semicolon.
51 /// - Possible missing return type if the return type is the default, and not `fn main()`.
52 pub fn suggest_mismatched_types_on_tail(
55 expr: &'tcx hir::Expr<'tcx>,
60 let expr = expr.peel_drop_temps();
61 self.suggest_missing_semicolon(err, expr, expected, false);
62 let mut pointing_at_return_type = false;
63 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
64 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
65 pointing_at_return_type = self.suggest_missing_return_type(
73 self.suggest_missing_break_or_return_expr(
74 err, expr, &fn_decl, expected, found, blk_id, fn_id,
77 pointing_at_return_type
80 /// When encountering an fn-like type, try accessing the output of the type
81 /// and suggesting calling it if it satisfies a predicate (i.e. if the
82 /// output has a method or a field):
83 /// ```compile_fail,E0308
84 /// fn foo(x: usize) -> usize { x }
85 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
87 pub(crate) fn suggest_fn_call(
92 can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
94 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(expr, found)
95 else { return false; };
96 if can_satisfy(output) {
97 let (sugg_call, mut applicability) = match inputs.len() {
98 0 => ("".to_string(), Applicability::MachineApplicable),
103 if ty.is_suggestable(self.tcx, false) {
104 format!("/* {ty} */")
106 "/* value */".to_string()
111 Applicability::HasPlaceholders,
113 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
116 let msg = match def_id_or_name {
117 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
118 DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
119 DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
120 kind => format!("call this {}", kind.descr(def_id)),
122 DefIdOrName::Name(name) => format!("call this {name}"),
125 let sugg = match expr.kind {
126 hir::ExprKind::Call(..)
127 | hir::ExprKind::Path(..)
128 | hir::ExprKind::Index(..)
129 | hir::ExprKind::Lit(..) => {
130 vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
132 hir::ExprKind::Closure { .. } => {
133 // Might be `{ expr } || { bool }`
134 applicability = Applicability::MaybeIncorrect;
136 (expr.span.shrink_to_lo(), "(".to_string()),
137 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
142 (expr.span.shrink_to_lo(), "(".to_string()),
143 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
148 err.multipart_suggestion_verbose(
149 format!("use parentheses to {msg}"),
158 /// Extracts information about a callable type for diagnostics. This is a
159 /// heuristic -- it doesn't necessarily mean that a type is always callable,
160 /// because the callable type must also be well-formed to be called.
161 pub(in super::super) fn extract_callable_info(
165 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
166 // Autoderef is useful here because sometimes we box callables, etc.
167 let Some((def_id_or_name, output, inputs)) = self.autoderef(expr.span, found).silence_errors().find_map(|(found, _)| {
168 match *found.kind() {
170 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
171 ty::FnDef(def_id, _) => {
172 let fn_sig = found.fn_sig(self.tcx);
173 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
175 ty::Closure(def_id, substs) => {
176 let fn_sig = substs.as_closure().sig();
177 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
179 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
180 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
181 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
182 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
183 // args tuple will always be substs[1]
184 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
187 DefIdOrName::DefId(def_id),
188 pred.kind().rebind(proj.term.ty().unwrap()),
189 pred.kind().rebind(args.as_slice()),
196 ty::Dynamic(data, _, ty::Dyn) => {
197 data.iter().find_map(|pred| {
198 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
199 && Some(proj.def_id) == self.tcx.lang_items().fn_once_output()
200 // for existential projection, substs are shifted over by 1
201 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
204 DefIdOrName::Name("trait object"),
205 pred.rebind(proj.term.ty().unwrap()),
206 pred.rebind(args.as_slice()),
213 ty::Param(param) => {
214 let def_id = self.tcx.generics_of(self.body_id.owner).type_param(¶m, self.tcx).def_id;
215 self.tcx.predicates_of(self.body_id.owner).predicates.iter().find_map(|(pred, _)| {
216 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
217 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
218 && proj.projection_ty.self_ty() == found
219 // args tuple will always be substs[1]
220 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
223 DefIdOrName::DefId(def_id),
224 pred.kind().rebind(proj.term.ty().unwrap()),
225 pred.kind().rebind(args.as_slice()),
234 }) else { return None; };
236 let output = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, output);
241 self.replace_bound_vars_with_fresh_vars(
249 // We don't want to register any extra obligations, which should be
250 // implied by wf, but also because that would possibly result in
251 // erroneous errors later on.
252 let infer::InferOk { value: output, obligations: _ } =
253 self.at(&self.misc(expr.span), self.param_env).normalize(output);
255 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
258 pub fn suggest_two_fn_call(
260 err: &mut Diagnostic,
261 lhs_expr: &'tcx hir::Expr<'tcx>,
263 rhs_expr: &'tcx hir::Expr<'tcx>,
265 can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
267 let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_expr, lhs_ty)
268 else { return false; };
269 let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_expr, rhs_ty)
270 else { return false; };
272 if can_satisfy(lhs_output_ty, rhs_output_ty) {
273 let mut sugg = vec![];
274 let mut applicability = Applicability::MachineApplicable;
276 for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
277 let (sugg_call, this_applicability) = match inputs.len() {
278 0 => ("".to_string(), Applicability::MachineApplicable),
283 if ty.is_suggestable(self.tcx, false) {
284 format!("/* {ty} */")
286 "/* value */".to_string()
291 Applicability::HasPlaceholders,
293 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
296 applicability = applicability.max(this_applicability);
299 hir::ExprKind::Call(..)
300 | hir::ExprKind::Path(..)
301 | hir::ExprKind::Index(..)
302 | hir::ExprKind::Lit(..) => {
303 sugg.extend([(expr.span.shrink_to_hi(), format!("({sugg_call})"))]);
305 hir::ExprKind::Closure { .. } => {
306 // Might be `{ expr } || { bool }`
307 applicability = Applicability::MaybeIncorrect;
309 (expr.span.shrink_to_lo(), "(".to_string()),
310 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
315 (expr.span.shrink_to_lo(), "(".to_string()),
316 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
322 err.multipart_suggestion_verbose(
323 format!("use parentheses to call these"),
334 pub fn suggest_deref_ref_or_into(
336 err: &mut Diagnostic,
337 expr: &hir::Expr<'tcx>,
340 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
342 let expr = expr.peel_blocks();
343 if let Some((sp, msg, suggestion, applicability, verbose, annotation)) =
344 self.check_ref(expr, found, expected)
347 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
349 err.span_suggestion(sp, &msg, suggestion, applicability);
352 let suggest_annotation = match expr.peel_drop_temps().kind {
353 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, _) => mutbl.ref_prefix_str(),
356 let mut tuple_indexes = Vec::new();
357 let mut expr_id = expr.hir_id;
358 for (parent_id, node) in self.tcx.hir().parent_iter(expr.hir_id) {
360 Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
364 .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
370 Node::Local(local) => {
371 if let Some(mut ty) = local.ty {
372 while let Some(index) = tuple_indexes.pop() {
374 TyKind::Tup(tys) => ty = &tys[index],
378 let annotation_span = ty.span;
380 annotation_span.with_hi(annotation_span.lo()),
381 "alternatively, consider changing the type annotation",
383 Applicability::MaybeIncorrect,
393 } else if self.suggest_else_fn_with_closure(err, expr, found, expected) {
395 } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected))
396 && let ty::FnDef(def_id, ..) = &found.kind()
397 && let Some(sp) = self.tcx.hir().span_if_local(*def_id)
399 err.span_label(sp, format!("{found} defined here"));
401 } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
404 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
405 if !methods.is_empty() {
406 let mut suggestions = methods.iter()
407 .filter_map(|conversion_method| {
408 let receiver_method_ident = expr.method_ident();
409 if let Some(method_ident) = receiver_method_ident
410 && method_ident.name == conversion_method.name
412 return None // do not suggest code that is already there (#53348)
415 let method_call_list = [sym::to_vec, sym::to_string];
416 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
417 && receiver_method.ident.name == sym::clone
418 && method_call_list.contains(&conversion_method.name)
419 // If receiver is `.clone()` and found type has one of those methods,
420 // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
421 // to an owned type (`Vec` or `String`). These conversions clone internally,
422 // so we remove the user's `clone` call.
425 receiver_method.ident.span,
426 conversion_method.name.to_string()
428 } else if expr.precedence().order()
429 < ExprPrecedence::MethodCall.order()
432 (expr.span.shrink_to_lo(), "(".to_string()),
433 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
436 vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
438 let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
439 if let Some(name) = struct_pat_shorthand_field {
442 (expr.span.shrink_to_lo(), format!("{}: ", name)),
448 if suggestions.peek().is_some() {
449 err.multipart_suggestions(
450 "try using a conversion method",
452 Applicability::MaybeIncorrect,
456 } else if let ty::Adt(found_adt, found_substs) = found.kind()
457 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
458 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
459 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
460 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
463 let ty = found_substs.type_at(0);
466 while let ty::Ref(_, inner, _) = peeled.kind() {
470 if let ty::Adt(adt, _) = peeled.kind()
471 && Some(adt.did()) == self.tcx.lang_items().string()
473 err.span_suggestion_verbose(
474 expr.span.shrink_to_hi(),
475 "try converting the passed type into a `&str`",
476 format!(".map(|x| &*{}x)", "*".repeat(ref_cnt)),
477 Applicability::MaybeIncorrect,
487 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
488 /// in the heap by calling `Box::new()`.
489 pub(in super::super) fn suggest_boxing_when_appropriate(
491 err: &mut Diagnostic,
492 expr: &hir::Expr<'_>,
496 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
497 // Do not suggest `Box::new` in const context.
500 if !expected.is_box() || found.is_box() {
503 let boxed_found = self.tcx.mk_box(found);
504 if self.can_coerce(boxed_found, expected) {
505 err.multipart_suggestion(
506 "store this in the heap by calling `Box::new`",
508 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
509 (expr.span.shrink_to_hi(), ")".to_string()),
511 Applicability::MachineApplicable,
514 "for more on the distinction between the stack and the heap, read \
515 https://doc.rust-lang.org/book/ch15-01-box.html, \
516 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
517 https://doc.rust-lang.org/std/boxed/index.html",
525 /// When encountering a closure that captures variables, where a FnPtr is expected,
526 /// suggest a non-capturing closure
527 pub(in super::super) fn suggest_no_capture_closure(
529 err: &mut Diagnostic,
533 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
534 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
535 // Report upto four upvars being captured to reduce the amount error messages
536 // reported back to the user.
537 let spans_and_labels = upvars
540 .map(|(var_hir_id, upvar)| {
541 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
542 let msg = format!("`{}` captured here", var_name);
545 .collect::<Vec<_>>();
547 let mut multi_span: MultiSpan =
548 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
549 for (sp, label) in spans_and_labels {
550 multi_span.push_span_label(sp, label);
554 "closures can only be coerced to `fn` types if they do not capture any variables"
562 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
563 #[instrument(skip(self, err))]
564 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
566 err: &mut Diagnostic,
567 expr: &hir::Expr<'_>,
573 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
574 // Do not suggest `Box::new` in const context.
577 let pin_did = self.tcx.lang_items().pin_type();
578 // This guards the `unwrap` and `mk_box` below.
579 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
582 let box_found = self.tcx.mk_box(found);
583 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
584 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
585 match expected.kind() {
586 ty::Adt(def, _) if Some(def.did()) == pin_did => {
587 if self.can_coerce(pin_box_found, expected) {
588 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
590 ty::Adt(def, _) if def.is_box() => {
591 err.help("use `Box::pin`");
594 err.multipart_suggestion(
595 "you need to pin and box this expression",
597 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
598 (expr.span.shrink_to_hi(), ")".to_string()),
600 Applicability::MaybeIncorrect,
605 } else if self.can_coerce(pin_found, expected) {
607 ty::Adt(def, _) if def.is_box() => {
608 err.help("use `Box::pin`");
617 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
618 // Check if the parent expression is a call to Pin::new. If it
619 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
620 // can suggest Box::pin.
621 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
622 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
626 ExprKind::Path(QPath::TypeRelative(
628 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
632 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
635 "use `Box::pin` to pin and box this expression",
637 Applicability::MachineApplicable,
648 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
650 /// ```compile_fail,E0308
651 /// # fn bar_that_returns_u32() -> u32 { 4 }
653 /// bar_that_returns_u32()
657 /// This routine checks if the return expression in a block would make sense on its own as a
658 /// statement and the return type has been left as default or has been specified as `()`. If so,
659 /// it suggests adding a semicolon.
661 /// If the expression is the expression of a closure without block (`|| expr`), a
662 /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
663 pub fn suggest_missing_semicolon(
665 err: &mut Diagnostic,
666 expression: &'tcx hir::Expr<'tcx>,
670 if expected.is_unit() {
671 // `BlockTailExpression` only relevant if the tail expr would be
672 // useful on its own.
673 match expression.kind {
675 | ExprKind::MethodCall(..)
678 | ExprKind::Match(..)
679 | ExprKind::Block(..)
680 if expression.can_have_side_effects()
681 // If the expression is from an external macro, then do not suggest
682 // adding a semicolon, because there's nowhere to put it.
684 && !in_external_macro(self.tcx.sess, expression.span) =>
687 err.multipart_suggestion(
688 "consider using a semicolon here",
690 (expression.span.shrink_to_lo(), "{ ".to_owned()),
691 (expression.span.shrink_to_hi(), "; }".to_owned()),
693 Applicability::MachineApplicable,
697 expression.span.shrink_to_hi(),
698 "consider using a semicolon here",
700 Applicability::MachineApplicable,
709 /// A possible error is to forget to add a return type that is needed:
711 /// ```compile_fail,E0308
712 /// # fn bar_that_returns_u32() -> u32 { 4 }
714 /// bar_that_returns_u32()
718 /// This routine checks if the return type is left as default, the method is not part of an
719 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
721 pub(in super::super) fn suggest_missing_return_type(
723 err: &mut Diagnostic,
724 fn_decl: &hir::FnDecl<'_>,
731 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
732 // Only suggest changing the return type for methods that
733 // haven't set a return type at all (and aren't `fn main()` or an impl).
734 match &fn_decl.output {
735 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
736 // `fn main()` must return `()`, do not suggest changing return type
737 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
740 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
741 if found.is_suggestable(self.tcx, false) {
742 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
744 } else if let ty::Closure(_, substs) = found.kind()
745 // FIXME(compiler-errors): Get better at printing binders...
746 && let closure = substs.as_closure()
747 && closure.sig().is_suggestable(self.tcx, false)
749 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
752 // FIXME: if `found` could be `impl Iterator` we should suggest that.
753 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
757 &hir::FnRetTy::Return(ref ty) => {
758 // Only point to return type if the expected type is the return type, as if they
759 // are not, the expectation must have been caused by something else.
760 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
762 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
763 debug!("suggest_missing_return_type: return type {:?}", ty);
764 debug!("suggest_missing_return_type: expected type {:?}", ty);
765 let bound_vars = self.tcx.late_bound_vars(fn_id);
766 let ty = Binder::bind_with_vars(ty, bound_vars);
767 let ty = self.normalize(span, ty);
768 let ty = self.tcx.erase_late_bound_regions(ty);
769 if self.can_coerce(expected, ty) {
770 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
771 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
780 /// check whether the return type is a generic type with a trait bound
781 /// only suggest this if the generic param is not present in the arguments
782 /// if this is true, hint them towards changing the return type to `impl Trait`
783 /// ```compile_fail,E0308
784 /// fn cant_name_it<T: Fn() -> u32>() -> T {
788 fn try_suggest_return_impl_trait(
790 err: &mut Diagnostic,
795 // Only apply the suggestion if:
796 // - the return type is a generic parameter
797 // - the generic param is not used as a fn param
798 // - the generic param has at least one bound
799 // - the generic param doesn't appear in any other bounds where it's not the Self type
801 // - Changing the return type to be `impl <all bounds>`
803 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
805 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
807 let fn_node = self.tcx.hir().find(fn_id);
809 let Some(hir::Node::Item(hir::Item {
812 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
813 hir::Generics { params, predicates, .. },
817 })) = fn_node else { return };
819 if params.get(expected_ty_as_param.index as usize).is_none() {
823 // get all where BoundPredicates here, because they are used in to cases below
824 let where_predicates = predicates
826 .filter_map(|p| match p {
827 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
832 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
833 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
838 .map(|(ty, bounds)| match ty.kind() {
839 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
840 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
841 _ => match ty.contains(expected) {
846 .collect::<Result<Vec<_>, _>>();
848 let Ok(where_predicates) = where_predicates else { return };
850 // now get all predicates in the same types as the where bounds, so we can chain them
851 let predicates_from_where =
852 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
854 // extract all bounds from the source code using their spans
855 let all_matching_bounds_strs = predicates_from_where
856 .filter_map(|bound| match bound {
857 GenericBound::Trait(_, _) => {
858 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
862 .collect::<Vec<String>>();
864 if all_matching_bounds_strs.len() == 0 {
868 let all_bounds_str = all_matching_bounds_strs.join(" + ");
870 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
871 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
872 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
875 if ty_param_used_in_fn_params {
881 "consider using an impl return type",
882 format!("impl {}", all_bounds_str),
883 Applicability::MaybeIncorrect,
887 pub(in super::super) fn suggest_missing_break_or_return_expr(
889 err: &mut Diagnostic,
890 expr: &'tcx hir::Expr<'tcx>,
891 fn_decl: &hir::FnDecl<'_>,
897 if !expected.is_unit() {
900 let found = self.resolve_vars_with_obligations(found);
902 let in_loop = self.is_loop(id)
903 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
905 let in_local_statement = self.is_local_statement(id)
910 .any(|(parent_id, _)| self.is_local_statement(parent_id));
912 if in_loop && in_local_statement {
913 err.multipart_suggestion(
914 "you might have meant to break the loop with this value",
916 (expr.span.shrink_to_lo(), "break ".to_string()),
917 (expr.span.shrink_to_hi(), ";".to_string()),
919 Applicability::MaybeIncorrect,
924 if let hir::FnRetTy::Return(ty) = fn_decl.output {
925 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
926 let bound_vars = self.tcx.late_bound_vars(fn_id);
927 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
928 let ty = match self.tcx.asyncness(fn_id.owner) {
929 hir::IsAsync::Async => self.get_impl_future_output_ty(ty).unwrap_or_else(|| {
930 span_bug!(fn_decl.output.span(), "failed to get output type of async function")
932 hir::IsAsync::NotAsync => ty,
934 let ty = self.normalize(expr.span, ty);
935 if self.can_coerce(found, ty) {
936 err.multipart_suggestion(
937 "you might have meant to return this value",
939 (expr.span.shrink_to_lo(), "return ".to_string()),
940 (expr.span.shrink_to_hi(), ";".to_string()),
942 Applicability::MaybeIncorrect,
948 pub(in super::super) fn suggest_missing_parentheses(
950 err: &mut Diagnostic,
951 expr: &hir::Expr<'_>,
953 let sp = self.tcx.sess.source_map().start_point(expr.span);
954 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
955 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
956 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
963 /// Given an expression type mismatch, peel any `&` expressions until we get to
964 /// a block expression, and then suggest replacing the braces with square braces
965 /// if it was possibly mistaken array syntax.
966 pub(crate) fn suggest_block_to_brackets_peeling_refs(
968 diag: &mut Diagnostic,
969 mut expr: &hir::Expr<'_>,
970 mut expr_ty: Ty<'tcx>,
971 mut expected_ty: Ty<'tcx>,
974 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
976 hir::ExprKind::AddrOf(_, _, inner_expr),
977 ty::Ref(_, inner_expr_ty, _),
978 ty::Ref(_, inner_expected_ty, _),
981 expr_ty = *inner_expr_ty;
982 expected_ty = *inner_expected_ty;
984 (hir::ExprKind::Block(blk, _), _, _) => {
985 self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
993 pub(crate) fn suggest_copied_or_cloned(
995 diag: &mut Diagnostic,
996 expr: &hir::Expr<'_>,
998 expected_ty: Ty<'tcx>,
1000 let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
1001 let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
1002 if adt_def != expected_adt_def {
1006 let mut suggest_copied_or_cloned = || {
1007 let expr_inner_ty = substs.type_at(0);
1008 let expected_inner_ty = expected_substs.type_at(0);
1009 if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
1010 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
1012 let def_path = self.tcx.def_path_str(adt_def.did());
1013 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
1014 diag.span_suggestion_verbose(
1015 expr.span.shrink_to_hi(),
1017 "use `{def_path}::copied` to copy the value inside the `{def_path}`"
1020 Applicability::MachineApplicable,
1023 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
1024 && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1032 diag.span_suggestion_verbose(
1033 expr.span.shrink_to_hi(),
1035 "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
1038 Applicability::MachineApplicable,
1046 if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1047 && adt_def.did() == result_did
1048 // Check that the error types are equal
1049 && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1051 return suggest_copied_or_cloned();
1052 } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1053 && adt_def.did() == option_did
1055 return suggest_copied_or_cloned();
1061 pub(crate) fn suggest_into(
1063 diag: &mut Diagnostic,
1064 expr: &hir::Expr<'_>,
1066 expected_ty: Ty<'tcx>,
1068 let expr = expr.peel_blocks();
1070 // We have better suggestions for scalar interconversions...
1071 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1075 // Don't suggest turning a block into another type (e.g. `{}.into()`)
1076 if matches!(expr.kind, hir::ExprKind::Block(..)) {
1080 // We'll later suggest `.as_ref` when noting the type error,
1081 // so skip if we will suggest that instead.
1082 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1086 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1087 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1089 self.misc(expr.span),
1091 ty::Binder::dummy(self.tcx.mk_trait_ref(
1093 [expr_ty, expected_ty]
1097 let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1098 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1100 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1102 diag.multipart_suggestion(
1103 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1105 Applicability::MaybeIncorrect
1113 /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1114 pub(crate) fn suggest_option_to_bool(
1116 diag: &mut Diagnostic,
1117 expr: &hir::Expr<'_>,
1119 expected_ty: Ty<'tcx>,
1121 if !expected_ty.is_bool() {
1125 let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; };
1126 if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1130 let hir = self.tcx.hir();
1131 let cond_parent = hir.parent_iter(expr.hir_id).skip_while(|(_, node)| {
1132 matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1135 // `let Some(_) = a.is_some() && b`
1137 // since the user probably just misunderstood how `let else`
1138 // and `&&` work together.
1139 if let Some((_, hir::Node::Local(local))) = cond_parent
1140 && let hir::PatKind::Path(qpath) | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1141 && let hir::QPath::Resolved(None, path) = qpath
1142 && let Some(did) = path.res.opt_def_id()
1143 .and_then(|did| self.tcx.opt_parent(did))
1144 .and_then(|did| self.tcx.opt_parent(did))
1145 && self.tcx.is_diagnostic_item(sym::Option, did)
1150 diag.span_suggestion(
1151 expr.span.shrink_to_hi(),
1152 "use `Option::is_some` to test if the `Option` has a value",
1154 Applicability::MachineApplicable,
1160 /// Suggest wrapping the block in square brackets instead of curly braces
1161 /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1162 pub(crate) fn suggest_block_to_brackets(
1164 diag: &mut Diagnostic,
1165 blk: &hir::Block<'_>,
1167 expected_ty: Ty<'tcx>,
1169 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1170 if self.can_coerce(blk_ty, *elem_ty)
1171 && blk.stmts.is_empty()
1172 && blk.rules == hir::BlockCheckMode::DefaultBlock
1174 let source_map = self.tcx.sess.source_map();
1175 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1176 if snippet.starts_with('{') && snippet.ends_with('}') {
1177 diag.multipart_suggestion_verbose(
1178 "to create an array, use square brackets instead of curly braces",
1183 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1189 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1193 Applicability::MachineApplicable,
1201 #[instrument(skip(self, err))]
1202 pub(crate) fn suggest_floating_point_literal(
1204 err: &mut Diagnostic,
1205 expr: &hir::Expr<'_>,
1206 expected_ty: Ty<'tcx>,
1208 if !expected_ty.is_floating_point() {
1212 ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [start, end], _) => {
1213 err.span_suggestion_verbose(
1214 start.span.shrink_to_hi().with_hi(end.span.lo()),
1215 "remove the unnecessary `.` operator for a floating point literal",
1217 Applicability::MaybeIncorrect,
1221 ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, ..), [start], _) => {
1222 err.span_suggestion_verbose(
1223 expr.span.with_lo(start.span.hi()),
1224 "remove the unnecessary `.` operator for a floating point literal",
1226 Applicability::MaybeIncorrect,
1230 ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, ..), [end], _) => {
1231 err.span_suggestion_verbose(
1232 expr.span.until(end.span),
1233 "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1235 Applicability::MaybeIncorrect,
1243 fn is_loop(&self, id: hir::HirId) -> bool {
1244 let node = self.tcx.hir().get(id);
1245 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1248 fn is_local_statement(&self, id: hir::HirId) -> bool {
1249 let node = self.tcx.hir().get(id);
1250 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1253 /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1254 /// which is a side-effect of autoref.
1255 pub(crate) fn note_type_is_not_clone(
1257 diag: &mut Diagnostic,
1258 expected_ty: Ty<'tcx>,
1260 expr: &hir::Expr<'_>,
1262 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1263 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1264 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1265 let results = self.typeck_results.borrow();
1266 // First, look for a `Clone::clone` call
1267 if segment.ident.name == sym::clone
1268 && results.type_dependent_def_id(expr.hir_id).map_or(
1271 let assoc_item = self.tcx.associated_item(did);
1272 assoc_item.container == ty::AssocItemContainer::TraitContainer
1273 && assoc_item.container_id(self.tcx) == clone_trait_did
1276 // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1277 // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1278 && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1279 // Check that we're in fact trying to clone into the expected type
1280 && self.can_coerce(*pointee_ty, expected_ty)
1281 && let trait_ref = ty::Binder::dummy(self.tcx.mk_trait_ref(clone_trait_did, [expected_ty]))
1282 // And the expected type doesn't implement `Clone`
1283 && !self.predicate_must_hold_considering_regions(&traits::Obligation::new(
1285 traits::ObligationCause::dummy(),
1293 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1296 let owner = self.tcx.hir().enclosing_body_owner(expr.hir_id);
1297 if let ty::Param(param) = expected_ty.kind()
1298 && let Some(generics) = self.tcx.hir().get_generics(owner)
1300 suggest_constraining_type_params(
1304 vec![(param.name.as_str(), "Clone", Some(clone_trait_did))].into_iter(),
1307 self.suggest_derive(diag, &[(trait_ref.to_predicate(self.tcx), None, None)]);
1312 /// A common error is to add an extra semicolon:
1314 /// ```compile_fail,E0308
1315 /// fn foo() -> usize {
1320 /// This routine checks if the final statement in a block is an
1321 /// expression with an explicit semicolon whose type is compatible
1322 /// with `expected_ty`. If so, it suggests removing the semicolon.
1323 pub(crate) fn consider_removing_semicolon(
1325 blk: &'tcx hir::Block<'tcx>,
1326 expected_ty: Ty<'tcx>,
1327 err: &mut Diagnostic,
1329 if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1330 if let StatementAsExpression::NeedsBoxing = boxed {
1331 err.span_suggestion_verbose(
1333 "consider removing this semicolon and boxing the expression",
1335 Applicability::HasPlaceholders,
1338 err.span_suggestion_short(
1340 "remove this semicolon to return this value",
1342 Applicability::MachineApplicable,