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::{self, Binder, DefIdTree, IsSuggestable, ToPredicate, Ty};
17 use rustc_session::errors::ExprParenthesesNeeded;
18 use rustc_span::symbol::sym;
20 use rustc_trait_selection::infer::InferCtxtExt;
21 use rustc_trait_selection::traits::error_reporting::DefIdOrName;
22 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
23 use rustc_trait_selection::traits::NormalizeExt;
25 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
26 pub(crate) fn body_fn_sig(&self) -> Option<ty::FnSig<'tcx>> {
30 .get(self.tcx.hir().get_parent_node(self.body_id))
34 pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
35 // This suggestion is incorrect for
36 // fn foo() -> bool { match () { () => true } || match () { () => true } }
37 err.span_suggestion_short(
39 "consider using a semicolon here",
41 Applicability::MaybeIncorrect,
45 /// On implicit return expressions with mismatched types, provides the following suggestions:
47 /// - Points out the method's return type as the reason for the expected type.
48 /// - Possible missing semicolon.
49 /// - Possible missing return type if the return type is the default, and not `fn main()`.
50 pub fn suggest_mismatched_types_on_tail(
53 expr: &'tcx hir::Expr<'tcx>,
58 let expr = expr.peel_drop_temps();
59 self.suggest_missing_semicolon(err, expr, expected, false);
60 let mut pointing_at_return_type = false;
61 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
62 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
63 pointing_at_return_type = self.suggest_missing_return_type(
71 self.suggest_missing_break_or_return_expr(
72 err, expr, &fn_decl, expected, found, blk_id, fn_id,
75 pointing_at_return_type
78 /// When encountering an fn-like type, try accessing the output of the type
79 /// and suggesting calling it if it satisfies a predicate (i.e. if the
80 /// output has a method or a field):
81 /// ```compile_fail,E0308
82 /// fn foo(x: usize) -> usize { x }
83 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
85 pub(crate) fn suggest_fn_call(
90 can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
92 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(expr, found)
93 else { return false; };
94 if can_satisfy(output) {
95 let (sugg_call, mut applicability) = match inputs.len() {
96 0 => ("".to_string(), Applicability::MachineApplicable),
101 if ty.is_suggestable(self.tcx, false) {
102 format!("/* {ty} */")
104 "/* value */".to_string()
109 Applicability::HasPlaceholders,
111 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
114 let msg = match def_id_or_name {
115 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
116 DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
117 DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
118 kind => format!("call this {}", kind.descr(def_id)),
120 DefIdOrName::Name(name) => format!("call this {name}"),
123 let sugg = match expr.kind {
124 hir::ExprKind::Call(..)
125 | hir::ExprKind::Path(..)
126 | hir::ExprKind::Index(..)
127 | hir::ExprKind::Lit(..) => {
128 vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
130 hir::ExprKind::Closure { .. } => {
131 // Might be `{ expr } || { bool }`
132 applicability = Applicability::MaybeIncorrect;
134 (expr.span.shrink_to_lo(), "(".to_string()),
135 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
140 (expr.span.shrink_to_lo(), "(".to_string()),
141 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
146 err.multipart_suggestion_verbose(
147 format!("use parentheses to {msg}"),
156 /// Extracts information about a callable type for diagnostics. This is a
157 /// heuristic -- it doesn't necessarily mean that a type is always callable,
158 /// because the callable type must also be well-formed to be called.
159 pub(in super::super) fn extract_callable_info(
163 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
164 // Autoderef is useful here because sometimes we box callables, etc.
165 let Some((def_id_or_name, output, inputs)) = self.autoderef(expr.span, found).silence_errors().find_map(|(found, _)| {
166 match *found.kind() {
168 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
169 ty::FnDef(def_id, _) => {
170 let fn_sig = found.fn_sig(self.tcx);
171 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
173 ty::Closure(def_id, substs) => {
174 let fn_sig = substs.as_closure().sig();
175 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
177 ty::Opaque(def_id, substs) => {
178 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
179 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
180 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
181 // args tuple will always be substs[1]
182 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
185 DefIdOrName::DefId(def_id),
186 pred.kind().rebind(proj.term.ty().unwrap()),
187 pred.kind().rebind(args.as_slice()),
194 ty::Dynamic(data, _, ty::Dyn) => {
195 data.iter().find_map(|pred| {
196 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
197 && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
198 // for existential projection, substs are shifted over by 1
199 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
202 DefIdOrName::Name("trait object"),
203 pred.rebind(proj.term.ty().unwrap()),
204 pred.rebind(args.as_slice()),
211 ty::Param(param) => {
212 let def_id = self.tcx.generics_of(self.body_id.owner).type_param(¶m, self.tcx).def_id;
213 self.tcx.predicates_of(self.body_id.owner).predicates.iter().find_map(|(pred, _)| {
214 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
215 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
216 && proj.projection_ty.self_ty() == found
217 // args tuple will always be substs[1]
218 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
221 DefIdOrName::DefId(def_id),
222 pred.kind().rebind(proj.term.ty().unwrap()),
223 pred.kind().rebind(args.as_slice()),
232 }) else { return None; };
234 let output = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, output);
239 self.replace_bound_vars_with_fresh_vars(
247 // We don't want to register any extra obligations, which should be
248 // implied by wf, but also because that would possibly result in
249 // erroneous errors later on.
250 let infer::InferOk { value: output, obligations: _ } =
251 self.at(&self.misc(expr.span), self.param_env).normalize(output);
253 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
256 pub fn suggest_two_fn_call(
258 err: &mut Diagnostic,
259 lhs_expr: &'tcx hir::Expr<'tcx>,
261 rhs_expr: &'tcx hir::Expr<'tcx>,
263 can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
265 let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_expr, lhs_ty)
266 else { return false; };
267 let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_expr, rhs_ty)
268 else { return false; };
270 if can_satisfy(lhs_output_ty, rhs_output_ty) {
271 let mut sugg = vec![];
272 let mut applicability = Applicability::MachineApplicable;
274 for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
275 let (sugg_call, this_applicability) = match inputs.len() {
276 0 => ("".to_string(), Applicability::MachineApplicable),
281 if ty.is_suggestable(self.tcx, false) {
282 format!("/* {ty} */")
284 "/* value */".to_string()
289 Applicability::HasPlaceholders,
291 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
294 applicability = applicability.max(this_applicability);
297 hir::ExprKind::Call(..)
298 | hir::ExprKind::Path(..)
299 | hir::ExprKind::Index(..)
300 | hir::ExprKind::Lit(..) => {
301 sugg.extend([(expr.span.shrink_to_hi(), format!("({sugg_call})"))]);
303 hir::ExprKind::Closure { .. } => {
304 // Might be `{ expr } || { bool }`
305 applicability = Applicability::MaybeIncorrect;
307 (expr.span.shrink_to_lo(), "(".to_string()),
308 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
313 (expr.span.shrink_to_lo(), "(".to_string()),
314 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
320 err.multipart_suggestion_verbose(
321 format!("use parentheses to call these"),
332 pub fn suggest_deref_ref_or_into(
334 err: &mut Diagnostic,
335 expr: &hir::Expr<'tcx>,
338 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
340 let expr = expr.peel_blocks();
341 if let Some((sp, msg, suggestion, applicability, verbose, annotation)) =
342 self.check_ref(expr, found, expected)
345 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
347 err.span_suggestion(sp, &msg, suggestion, applicability);
350 let suggest_annotation = match expr.peel_drop_temps().kind {
351 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, _) => mutbl.ref_prefix_str(),
354 let mut tuple_indexes = Vec::new();
355 let mut expr_id = expr.hir_id;
356 for (parent_id, node) in self.tcx.hir().parent_iter(expr.hir_id) {
358 Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
362 .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
368 Node::Local(local) => {
369 if let Some(mut ty) = local.ty {
370 while let Some(index) = tuple_indexes.pop() {
372 TyKind::Tup(tys) => ty = &tys[index],
376 let annotation_span = ty.span;
378 annotation_span.with_hi(annotation_span.lo()),
379 "alternatively, consider changing the type annotation",
381 Applicability::MaybeIncorrect,
391 } else if self.suggest_else_fn_with_closure(err, expr, found, expected) {
393 } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected))
394 && let ty::FnDef(def_id, ..) = &found.kind()
395 && let Some(sp) = self.tcx.hir().span_if_local(*def_id)
397 err.span_label(sp, format!("{found} defined here"));
399 } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
402 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
403 if !methods.is_empty() {
404 let mut suggestions = methods.iter()
405 .filter_map(|conversion_method| {
406 let receiver_method_ident = expr.method_ident();
407 if let Some(method_ident) = receiver_method_ident
408 && method_ident.name == conversion_method.name
410 return None // do not suggest code that is already there (#53348)
413 let method_call_list = [sym::to_vec, sym::to_string];
414 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
415 && receiver_method.ident.name == sym::clone
416 && method_call_list.contains(&conversion_method.name)
417 // If receiver is `.clone()` and found type has one of those methods,
418 // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
419 // to an owned type (`Vec` or `String`). These conversions clone internally,
420 // so we remove the user's `clone` call.
423 receiver_method.ident.span,
424 conversion_method.name.to_string()
426 } else if expr.precedence().order()
427 < ExprPrecedence::MethodCall.order()
430 (expr.span.shrink_to_lo(), "(".to_string()),
431 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
434 vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
436 let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
437 if let Some(name) = struct_pat_shorthand_field {
440 (expr.span.shrink_to_lo(), format!("{}: ", name)),
446 if suggestions.peek().is_some() {
447 err.multipart_suggestions(
448 "try using a conversion method",
450 Applicability::MaybeIncorrect,
454 } else if let ty::Adt(found_adt, found_substs) = found.kind()
455 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
456 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
457 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
458 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
461 let ty = found_substs.type_at(0);
464 while let ty::Ref(_, inner, _) = peeled.kind() {
468 if let ty::Adt(adt, _) = peeled.kind()
469 && Some(adt.did()) == self.tcx.lang_items().string()
471 err.span_suggestion_verbose(
472 expr.span.shrink_to_hi(),
473 "try converting the passed type into a `&str`",
474 format!(".map(|x| &*{}x)", "*".repeat(ref_cnt)),
475 Applicability::MaybeIncorrect,
485 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
486 /// in the heap by calling `Box::new()`.
487 pub(in super::super) fn suggest_boxing_when_appropriate(
489 err: &mut Diagnostic,
490 expr: &hir::Expr<'_>,
494 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
495 // Do not suggest `Box::new` in const context.
498 if !expected.is_box() || found.is_box() {
501 let boxed_found = self.tcx.mk_box(found);
502 if self.can_coerce(boxed_found, expected) {
503 err.multipart_suggestion(
504 "store this in the heap by calling `Box::new`",
506 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
507 (expr.span.shrink_to_hi(), ")".to_string()),
509 Applicability::MachineApplicable,
512 "for more on the distinction between the stack and the heap, read \
513 https://doc.rust-lang.org/book/ch15-01-box.html, \
514 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
515 https://doc.rust-lang.org/std/boxed/index.html",
523 /// When encountering a closure that captures variables, where a FnPtr is expected,
524 /// suggest a non-capturing closure
525 pub(in super::super) fn suggest_no_capture_closure(
527 err: &mut Diagnostic,
531 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
532 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
533 // Report upto four upvars being captured to reduce the amount error messages
534 // reported back to the user.
535 let spans_and_labels = upvars
538 .map(|(var_hir_id, upvar)| {
539 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
540 let msg = format!("`{}` captured here", var_name);
543 .collect::<Vec<_>>();
545 let mut multi_span: MultiSpan =
546 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
547 for (sp, label) in spans_and_labels {
548 multi_span.push_span_label(sp, label);
552 "closures can only be coerced to `fn` types if they do not capture any variables"
560 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
561 #[instrument(skip(self, err))]
562 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
564 err: &mut Diagnostic,
565 expr: &hir::Expr<'_>,
571 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
572 // Do not suggest `Box::new` in const context.
575 let pin_did = self.tcx.lang_items().pin_type();
576 // This guards the `unwrap` and `mk_box` below.
577 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
580 let box_found = self.tcx.mk_box(found);
581 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
582 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
583 match expected.kind() {
584 ty::Adt(def, _) if Some(def.did()) == pin_did => {
585 if self.can_coerce(pin_box_found, expected) {
586 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
588 ty::Adt(def, _) if def.is_box() => {
589 err.help("use `Box::pin`");
592 err.multipart_suggestion(
593 "you need to pin and box this expression",
595 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
596 (expr.span.shrink_to_hi(), ")".to_string()),
598 Applicability::MaybeIncorrect,
603 } else if self.can_coerce(pin_found, expected) {
605 ty::Adt(def, _) if def.is_box() => {
606 err.help("use `Box::pin`");
615 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
616 // Check if the parent expression is a call to Pin::new. If it
617 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
618 // can suggest Box::pin.
619 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
620 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
624 ExprKind::Path(QPath::TypeRelative(
626 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
630 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
633 "use `Box::pin` to pin and box this expression",
635 Applicability::MachineApplicable,
646 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
648 /// ```compile_fail,E0308
649 /// # fn bar_that_returns_u32() -> u32 { 4 }
651 /// bar_that_returns_u32()
655 /// This routine checks if the return expression in a block would make sense on its own as a
656 /// statement and the return type has been left as default or has been specified as `()`. If so,
657 /// it suggests adding a semicolon.
659 /// If the expression is the expression of a closure without block (`|| expr`), a
660 /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
661 pub fn suggest_missing_semicolon(
663 err: &mut Diagnostic,
664 expression: &'tcx hir::Expr<'tcx>,
668 if expected.is_unit() {
669 // `BlockTailExpression` only relevant if the tail expr would be
670 // useful on its own.
671 match expression.kind {
673 | ExprKind::MethodCall(..)
676 | ExprKind::Match(..)
677 | ExprKind::Block(..)
678 if expression.can_have_side_effects()
679 // If the expression is from an external macro, then do not suggest
680 // adding a semicolon, because there's nowhere to put it.
682 && !in_external_macro(self.tcx.sess, expression.span) =>
685 err.multipart_suggestion(
686 "consider using a semicolon here",
688 (expression.span.shrink_to_lo(), "{ ".to_owned()),
689 (expression.span.shrink_to_hi(), "; }".to_owned()),
691 Applicability::MachineApplicable,
695 expression.span.shrink_to_hi(),
696 "consider using a semicolon here",
698 Applicability::MachineApplicable,
707 /// A possible error is to forget to add a return type that is needed:
709 /// ```compile_fail,E0308
710 /// # fn bar_that_returns_u32() -> u32 { 4 }
712 /// bar_that_returns_u32()
716 /// This routine checks if the return type is left as default, the method is not part of an
717 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
719 pub(in super::super) fn suggest_missing_return_type(
721 err: &mut Diagnostic,
722 fn_decl: &hir::FnDecl<'_>,
729 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
730 // Only suggest changing the return type for methods that
731 // haven't set a return type at all (and aren't `fn main()` or an impl).
732 match &fn_decl.output {
733 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
734 // `fn main()` must return `()`, do not suggest changing return type
735 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
738 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
739 if found.is_suggestable(self.tcx, false) {
740 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
742 } else if let ty::Closure(_, substs) = found.kind()
743 // FIXME(compiler-errors): Get better at printing binders...
744 && let closure = substs.as_closure()
745 && closure.sig().is_suggestable(self.tcx, false)
747 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
750 // FIXME: if `found` could be `impl Iterator` we should suggest that.
751 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
755 &hir::FnRetTy::Return(ref ty) => {
756 // Only point to return type if the expected type is the return type, as if they
757 // are not, the expectation must have been caused by something else.
758 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
760 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
761 debug!("suggest_missing_return_type: return type {:?}", ty);
762 debug!("suggest_missing_return_type: expected type {:?}", ty);
763 let bound_vars = self.tcx.late_bound_vars(fn_id);
764 let ty = Binder::bind_with_vars(ty, bound_vars);
765 let ty = self.normalize(span, ty);
766 let ty = self.tcx.erase_late_bound_regions(ty);
767 if self.can_coerce(expected, ty) {
768 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
769 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
778 /// check whether the return type is a generic type with a trait bound
779 /// only suggest this if the generic param is not present in the arguments
780 /// if this is true, hint them towards changing the return type to `impl Trait`
781 /// ```compile_fail,E0308
782 /// fn cant_name_it<T: Fn() -> u32>() -> T {
786 fn try_suggest_return_impl_trait(
788 err: &mut Diagnostic,
793 // Only apply the suggestion if:
794 // - the return type is a generic parameter
795 // - the generic param is not used as a fn param
796 // - the generic param has at least one bound
797 // - the generic param doesn't appear in any other bounds where it's not the Self type
799 // - Changing the return type to be `impl <all bounds>`
801 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
803 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
805 let fn_node = self.tcx.hir().find(fn_id);
807 let Some(hir::Node::Item(hir::Item {
810 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
811 hir::Generics { params, predicates, .. },
815 })) = fn_node else { return };
817 if params.get(expected_ty_as_param.index as usize).is_none() {
821 // get all where BoundPredicates here, because they are used in to cases below
822 let where_predicates = predicates
824 .filter_map(|p| match p {
825 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
830 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
831 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
836 .map(|(ty, bounds)| match ty.kind() {
837 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
838 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
839 _ => match ty.contains(expected) {
844 .collect::<Result<Vec<_>, _>>();
846 let Ok(where_predicates) = where_predicates else { return };
848 // now get all predicates in the same types as the where bounds, so we can chain them
849 let predicates_from_where =
850 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
852 // extract all bounds from the source code using their spans
853 let all_matching_bounds_strs = predicates_from_where
854 .filter_map(|bound| match bound {
855 GenericBound::Trait(_, _) => {
856 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
860 .collect::<Vec<String>>();
862 if all_matching_bounds_strs.len() == 0 {
866 let all_bounds_str = all_matching_bounds_strs.join(" + ");
868 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
869 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
870 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
873 if ty_param_used_in_fn_params {
879 "consider using an impl return type",
880 format!("impl {}", all_bounds_str),
881 Applicability::MaybeIncorrect,
885 pub(in super::super) fn suggest_missing_break_or_return_expr(
887 err: &mut Diagnostic,
888 expr: &'tcx hir::Expr<'tcx>,
889 fn_decl: &hir::FnDecl<'_>,
895 if !expected.is_unit() {
898 let found = self.resolve_vars_with_obligations(found);
900 let in_loop = self.is_loop(id)
901 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
903 let in_local_statement = self.is_local_statement(id)
908 .any(|(parent_id, _)| self.is_local_statement(parent_id));
910 if in_loop && in_local_statement {
911 err.multipart_suggestion(
912 "you might have meant to break the loop with this value",
914 (expr.span.shrink_to_lo(), "break ".to_string()),
915 (expr.span.shrink_to_hi(), ";".to_string()),
917 Applicability::MaybeIncorrect,
922 if let hir::FnRetTy::Return(ty) = fn_decl.output {
923 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
924 let bound_vars = self.tcx.late_bound_vars(fn_id);
925 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
926 let ty = match self.tcx.asyncness(fn_id.owner) {
927 hir::IsAsync::Async => self.get_impl_future_output_ty(ty).unwrap_or_else(|| {
928 span_bug!(fn_decl.output.span(), "failed to get output type of async function")
930 hir::IsAsync::NotAsync => ty,
932 let ty = self.normalize(expr.span, ty);
933 if self.can_coerce(found, ty) {
934 err.multipart_suggestion(
935 "you might have meant to return this value",
937 (expr.span.shrink_to_lo(), "return ".to_string()),
938 (expr.span.shrink_to_hi(), ";".to_string()),
940 Applicability::MaybeIncorrect,
946 pub(in super::super) fn suggest_missing_parentheses(
948 err: &mut Diagnostic,
949 expr: &hir::Expr<'_>,
951 let sp = self.tcx.sess.source_map().start_point(expr.span);
952 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
953 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
954 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
961 /// Given an expression type mismatch, peel any `&` expressions until we get to
962 /// a block expression, and then suggest replacing the braces with square braces
963 /// if it was possibly mistaken array syntax.
964 pub(crate) fn suggest_block_to_brackets_peeling_refs(
966 diag: &mut Diagnostic,
967 mut expr: &hir::Expr<'_>,
968 mut expr_ty: Ty<'tcx>,
969 mut expected_ty: Ty<'tcx>,
972 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
974 hir::ExprKind::AddrOf(_, _, inner_expr),
975 ty::Ref(_, inner_expr_ty, _),
976 ty::Ref(_, inner_expected_ty, _),
979 expr_ty = *inner_expr_ty;
980 expected_ty = *inner_expected_ty;
982 (hir::ExprKind::Block(blk, _), _, _) => {
983 self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
991 pub(crate) fn suggest_copied_or_cloned(
993 diag: &mut Diagnostic,
994 expr: &hir::Expr<'_>,
996 expected_ty: Ty<'tcx>,
998 let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
999 let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
1000 if adt_def != expected_adt_def {
1004 let mut suggest_copied_or_cloned = || {
1005 let expr_inner_ty = substs.type_at(0);
1006 let expected_inner_ty = expected_substs.type_at(0);
1007 if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
1008 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
1010 let def_path = self.tcx.def_path_str(adt_def.did());
1011 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
1012 diag.span_suggestion_verbose(
1013 expr.span.shrink_to_hi(),
1015 "use `{def_path}::copied` to copy the value inside the `{def_path}`"
1018 Applicability::MachineApplicable,
1021 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
1022 && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1030 diag.span_suggestion_verbose(
1031 expr.span.shrink_to_hi(),
1033 "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
1036 Applicability::MachineApplicable,
1044 if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1045 && adt_def.did() == result_did
1046 // Check that the error types are equal
1047 && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1049 return suggest_copied_or_cloned();
1050 } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1051 && adt_def.did() == option_did
1053 return suggest_copied_or_cloned();
1059 pub(crate) fn suggest_into(
1061 diag: &mut Diagnostic,
1062 expr: &hir::Expr<'_>,
1064 expected_ty: Ty<'tcx>,
1066 let expr = expr.peel_blocks();
1068 // We have better suggestions for scalar interconversions...
1069 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1073 // Don't suggest turning a block into another type (e.g. `{}.into()`)
1074 if matches!(expr.kind, hir::ExprKind::Block(..)) {
1078 // We'll later suggest `.as_ref` when noting the type error,
1079 // so skip if we will suggest that instead.
1080 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1084 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1085 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1087 self.misc(expr.span),
1089 ty::Binder::dummy(self.tcx.mk_trait_ref(
1091 [expr_ty, expected_ty]
1095 let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1096 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1098 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1100 diag.multipart_suggestion(
1101 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1103 Applicability::MaybeIncorrect
1111 /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1112 pub(crate) fn suggest_option_to_bool(
1114 diag: &mut Diagnostic,
1115 expr: &hir::Expr<'_>,
1117 expected_ty: Ty<'tcx>,
1119 if !expected_ty.is_bool() {
1123 let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; };
1124 if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1128 let hir = self.tcx.hir();
1129 let cond_parent = hir.parent_iter(expr.hir_id).skip_while(|(_, node)| {
1130 matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1133 // `let Some(_) = a.is_some() && b`
1135 // since the user probably just misunderstood how `let else`
1136 // and `&&` work together.
1137 if let Some((_, hir::Node::Local(local))) = cond_parent
1138 && let hir::PatKind::Path(qpath) | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1139 && let hir::QPath::Resolved(None, path) = qpath
1140 && let Some(did) = path.res.opt_def_id()
1141 .and_then(|did| self.tcx.opt_parent(did))
1142 .and_then(|did| self.tcx.opt_parent(did))
1143 && self.tcx.is_diagnostic_item(sym::Option, did)
1148 diag.span_suggestion(
1149 expr.span.shrink_to_hi(),
1150 "use `Option::is_some` to test if the `Option` has a value",
1152 Applicability::MachineApplicable,
1158 /// Suggest wrapping the block in square brackets instead of curly braces
1159 /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1160 pub(crate) fn suggest_block_to_brackets(
1162 diag: &mut Diagnostic,
1163 blk: &hir::Block<'_>,
1165 expected_ty: Ty<'tcx>,
1167 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1168 if self.can_coerce(blk_ty, *elem_ty)
1169 && blk.stmts.is_empty()
1170 && blk.rules == hir::BlockCheckMode::DefaultBlock
1172 let source_map = self.tcx.sess.source_map();
1173 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1174 if snippet.starts_with('{') && snippet.ends_with('}') {
1175 diag.multipart_suggestion_verbose(
1176 "to create an array, use square brackets instead of curly braces",
1181 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1187 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1191 Applicability::MachineApplicable,
1199 #[instrument(skip(self, err))]
1200 pub(crate) fn suggest_floating_point_literal(
1202 err: &mut Diagnostic,
1203 expr: &hir::Expr<'_>,
1204 expected_ty: Ty<'tcx>,
1206 if !expected_ty.is_floating_point() {
1210 ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [start, end], _) => {
1211 err.span_suggestion_verbose(
1212 start.span.shrink_to_hi().with_hi(end.span.lo()),
1213 "remove the unnecessary `.` operator for a floating point literal",
1215 Applicability::MaybeIncorrect,
1219 ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, ..), [start], _) => {
1220 err.span_suggestion_verbose(
1221 expr.span.with_lo(start.span.hi()),
1222 "remove the unnecessary `.` operator for a floating point literal",
1224 Applicability::MaybeIncorrect,
1228 ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, ..), [end], _) => {
1229 err.span_suggestion_verbose(
1230 expr.span.until(end.span),
1231 "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1233 Applicability::MaybeIncorrect,
1241 fn is_loop(&self, id: hir::HirId) -> bool {
1242 let node = self.tcx.hir().get(id);
1243 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1246 fn is_local_statement(&self, id: hir::HirId) -> bool {
1247 let node = self.tcx.hir().get(id);
1248 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1251 /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1252 /// which is a side-effect of autoref.
1253 pub(crate) fn note_type_is_not_clone(
1255 diag: &mut Diagnostic,
1256 expected_ty: Ty<'tcx>,
1258 expr: &hir::Expr<'_>,
1260 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1261 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1262 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1263 let results = self.typeck_results.borrow();
1264 // First, look for a `Clone::clone` call
1265 if segment.ident.name == sym::clone
1266 && results.type_dependent_def_id(expr.hir_id).map_or(
1269 let assoc_item = self.tcx.associated_item(did);
1270 assoc_item.container == ty::AssocItemContainer::TraitContainer
1271 && assoc_item.container_id(self.tcx) == clone_trait_did
1274 // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1275 // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1276 && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1277 // Check that we're in fact trying to clone into the expected type
1278 && self.can_coerce(*pointee_ty, expected_ty)
1279 // And the expected type doesn't implement `Clone`
1280 && !self.predicate_must_hold_considering_regions(&traits::Obligation {
1281 cause: traits::ObligationCause::dummy(),
1282 param_env: self.param_env,
1284 predicate: ty::Binder::dummy(ty::TraitRef {
1285 def_id: clone_trait_did,
1286 substs: self.tcx.mk_substs([expected_ty.into()].iter()),
1289 .to_predicate(self.tcx),
1295 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1301 /// A common error is to add an extra semicolon:
1303 /// ```compile_fail,E0308
1304 /// fn foo() -> usize {
1309 /// This routine checks if the final statement in a block is an
1310 /// expression with an explicit semicolon whose type is compatible
1311 /// with `expected_ty`. If so, it suggests removing the semicolon.
1312 pub(crate) fn consider_removing_semicolon(
1314 blk: &'tcx hir::Block<'tcx>,
1315 expected_ty: Ty<'tcx>,
1316 err: &mut Diagnostic,
1318 if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1319 if let StatementAsExpression::NeedsBoxing = boxed {
1320 err.span_suggestion_verbose(
1322 "consider removing this semicolon and boxing the expression",
1324 Applicability::HasPlaceholders,
1327 err.span_suggestion_short(
1329 "remove this semicolon to return this value",
1331 Applicability::MachineApplicable,