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::{self, TyCtxtInferExt};
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 _;
24 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25 pub(crate) fn body_fn_sig(&self) -> Option<ty::FnSig<'tcx>> {
29 .get(self.tcx.hir().get_parent_node(self.body_id))
33 pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
34 err.span_suggestion_short(
36 "consider using a semicolon here",
38 Applicability::MachineApplicable,
42 /// On implicit return expressions with mismatched types, provides the following suggestions:
44 /// - Points out the method's return type as the reason for the expected type.
45 /// - Possible missing semicolon.
46 /// - Possible missing return type if the return type is the default, and not `fn main()`.
47 pub fn suggest_mismatched_types_on_tail(
50 expr: &'tcx hir::Expr<'tcx>,
55 let expr = expr.peel_drop_temps();
56 self.suggest_missing_semicolon(err, expr, expected, false);
57 let mut pointing_at_return_type = false;
58 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
59 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
60 pointing_at_return_type = self.suggest_missing_return_type(
68 self.suggest_missing_break_or_return_expr(
69 err, expr, &fn_decl, expected, found, blk_id, fn_id,
72 pointing_at_return_type
75 /// When encountering an fn-like type, try accessing the output of the type
76 /// and suggesting calling it if it satisfies a predicate (i.e. if the
77 /// output has a method or a field):
78 /// ```compile_fail,E0308
79 /// fn foo(x: usize) -> usize { x }
80 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
82 pub(crate) fn suggest_fn_call(
87 can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
89 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(expr, found)
90 else { return false; };
91 if can_satisfy(output) {
92 let (sugg_call, mut applicability) = match inputs.len() {
93 0 => ("".to_string(), Applicability::MachineApplicable),
98 if ty.is_suggestable(self.tcx, false) {
101 "/* value */".to_string()
106 Applicability::HasPlaceholders,
108 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
111 let msg = match def_id_or_name {
112 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
113 DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
114 DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
115 kind => format!("call this {}", kind.descr(def_id)),
117 DefIdOrName::Name(name) => format!("call this {name}"),
120 let sugg = match expr.kind {
121 hir::ExprKind::Call(..)
122 | hir::ExprKind::Path(..)
123 | hir::ExprKind::Index(..)
124 | hir::ExprKind::Lit(..) => {
125 vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
127 hir::ExprKind::Closure { .. } => {
128 // Might be `{ expr } || { bool }`
129 applicability = Applicability::MaybeIncorrect;
131 (expr.span.shrink_to_lo(), "(".to_string()),
132 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
137 (expr.span.shrink_to_lo(), "(".to_string()),
138 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
143 err.multipart_suggestion_verbose(
144 format!("use parentheses to {msg}"),
153 /// Extracts information about a callable type for diagnostics. This is a
154 /// heuristic -- it doesn't necessarily mean that a type is always callable,
155 /// because the callable type must also be well-formed to be called.
156 pub(in super::super) fn extract_callable_info(
160 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
161 // Autoderef is useful here because sometimes we box callables, etc.
162 let Some((def_id_or_name, output, inputs)) = self.autoderef(expr.span, found).silence_errors().find_map(|(found, _)| {
163 match *found.kind() {
165 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
166 ty::FnDef(def_id, _) => {
167 let fn_sig = found.fn_sig(self.tcx);
168 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
170 ty::Closure(def_id, substs) => {
171 let fn_sig = substs.as_closure().sig();
172 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
174 ty::Opaque(def_id, substs) => {
175 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
176 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
177 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
178 // args tuple will always be substs[1]
179 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
182 DefIdOrName::DefId(def_id),
183 pred.kind().rebind(proj.term.ty().unwrap()),
184 pred.kind().rebind(args.as_slice()),
191 ty::Dynamic(data, _, ty::Dyn) => {
192 data.iter().find_map(|pred| {
193 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
194 && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
195 // for existential projection, substs are shifted over by 1
196 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
199 DefIdOrName::Name("trait object"),
200 pred.rebind(proj.term.ty().unwrap()),
201 pred.rebind(args.as_slice()),
208 ty::Param(param) => {
209 let def_id = self.tcx.generics_of(self.body_id.owner).type_param(¶m, self.tcx).def_id;
210 self.tcx.predicates_of(self.body_id.owner).predicates.iter().find_map(|(pred, _)| {
211 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
212 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
213 && proj.projection_ty.self_ty() == found
214 // args tuple will always be substs[1]
215 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
218 DefIdOrName::DefId(def_id),
219 pred.kind().rebind(proj.term.ty().unwrap()),
220 pred.kind().rebind(args.as_slice()),
229 }) else { return None; };
231 let output = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, output);
236 self.replace_bound_vars_with_fresh_vars(
244 // We don't want to register any extra obligations, which should be
245 // implied by wf, but also because that would possibly result in
246 // erroneous errors later on.
247 let infer::InferOk { value: output, obligations: _ } =
248 self.normalize_associated_types_in_as_infer_ok(expr.span, output);
250 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
253 pub fn suggest_two_fn_call(
255 err: &mut Diagnostic,
256 lhs_expr: &'tcx hir::Expr<'tcx>,
258 rhs_expr: &'tcx hir::Expr<'tcx>,
260 can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
262 let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_expr, lhs_ty)
263 else { return false; };
264 let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_expr, rhs_ty)
265 else { return false; };
267 if can_satisfy(lhs_output_ty, rhs_output_ty) {
268 let mut sugg = vec![];
269 let mut applicability = Applicability::MachineApplicable;
271 for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
272 let (sugg_call, this_applicability) = match inputs.len() {
273 0 => ("".to_string(), Applicability::MachineApplicable),
278 if ty.is_suggestable(self.tcx, false) {
279 format!("/* {ty} */")
281 "/* value */".to_string()
286 Applicability::HasPlaceholders,
288 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
291 applicability = applicability.max(this_applicability);
294 hir::ExprKind::Call(..)
295 | hir::ExprKind::Path(..)
296 | hir::ExprKind::Index(..)
297 | hir::ExprKind::Lit(..) => {
298 sugg.extend([(expr.span.shrink_to_hi(), format!("({sugg_call})"))]);
300 hir::ExprKind::Closure { .. } => {
301 // Might be `{ expr } || { bool }`
302 applicability = Applicability::MaybeIncorrect;
304 (expr.span.shrink_to_lo(), "(".to_string()),
305 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
310 (expr.span.shrink_to_lo(), "(".to_string()),
311 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
317 err.multipart_suggestion_verbose(
318 format!("use parentheses to call these"),
329 pub fn suggest_deref_ref_or_into(
331 err: &mut Diagnostic,
332 expr: &hir::Expr<'tcx>,
335 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
337 let expr = expr.peel_blocks();
338 if let Some((sp, msg, suggestion, applicability, verbose, annotation)) =
339 self.check_ref(expr, found, expected)
342 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
344 err.span_suggestion(sp, &msg, suggestion, applicability);
347 let suggest_annotation = match expr.peel_drop_temps().kind {
348 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, _) => "&",
349 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, _) => "&mut ",
352 let mut tuple_indexes = Vec::new();
353 let mut expr_id = expr.hir_id;
354 for (parent_id, node) in self.tcx.hir().parent_iter(expr.hir_id) {
356 Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
360 .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
366 Node::Local(local) => {
367 if let Some(mut ty) = local.ty {
368 while let Some(index) = tuple_indexes.pop() {
370 TyKind::Tup(tys) => ty = &tys[index],
374 let annotation_span = ty.span;
376 annotation_span.with_hi(annotation_span.lo()),
377 "alternatively, consider changing the type annotation",
379 Applicability::MaybeIncorrect,
389 } else if self.suggest_else_fn_with_closure(err, expr, found, expected) {
391 } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected))
392 && let ty::FnDef(def_id, ..) = &found.kind()
393 && let Some(sp) = self.tcx.hir().span_if_local(*def_id)
395 err.span_label(sp, format!("{found} defined here"));
397 } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
400 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
401 if !methods.is_empty() {
402 let mut suggestions = methods.iter()
403 .filter_map(|conversion_method| {
404 let receiver_method_ident = expr.method_ident();
405 if let Some(method_ident) = receiver_method_ident
406 && method_ident.name == conversion_method.name
408 return None // do not suggest code that is already there (#53348)
411 let method_call_list = [sym::to_vec, sym::to_string];
412 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
413 && receiver_method.ident.name == sym::clone
414 && method_call_list.contains(&conversion_method.name)
415 // If receiver is `.clone()` and found type has one of those methods,
416 // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
417 // to an owned type (`Vec` or `String`). These conversions clone internally,
418 // so we remove the user's `clone` call.
421 receiver_method.ident.span,
422 conversion_method.name.to_string()
424 } else if expr.precedence().order()
425 < ExprPrecedence::MethodCall.order()
428 (expr.span.shrink_to_lo(), "(".to_string()),
429 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
432 vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
434 let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
435 if let Some(name) = struct_pat_shorthand_field {
438 (expr.span.shrink_to_lo(), format!("{}: ", name)),
444 if suggestions.peek().is_some() {
445 err.multipart_suggestions(
446 "try using a conversion method",
448 Applicability::MaybeIncorrect,
452 } else if let ty::Adt(found_adt, found_substs) = found.kind()
453 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
454 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
455 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
456 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
459 let ty = found_substs.type_at(0);
462 while let ty::Ref(_, inner, _) = peeled.kind() {
466 if let ty::Adt(adt, _) = peeled.kind()
467 && Some(adt.did()) == self.tcx.lang_items().string()
469 err.span_suggestion_verbose(
470 expr.span.shrink_to_hi(),
471 "try converting the passed type into a `&str`",
472 format!(".map(|x| &*{}x)", "*".repeat(ref_cnt)),
473 Applicability::MaybeIncorrect,
483 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
484 /// in the heap by calling `Box::new()`.
485 pub(in super::super) fn suggest_boxing_when_appropriate(
487 err: &mut Diagnostic,
488 expr: &hir::Expr<'_>,
492 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
493 // Do not suggest `Box::new` in const context.
496 if !expected.is_box() || found.is_box() {
499 let boxed_found = self.tcx.mk_box(found);
500 if self.can_coerce(boxed_found, expected) {
501 err.multipart_suggestion(
502 "store this in the heap by calling `Box::new`",
504 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
505 (expr.span.shrink_to_hi(), ")".to_string()),
507 Applicability::MachineApplicable,
510 "for more on the distinction between the stack and the heap, read \
511 https://doc.rust-lang.org/book/ch15-01-box.html, \
512 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
513 https://doc.rust-lang.org/std/boxed/index.html",
521 /// When encountering a closure that captures variables, where a FnPtr is expected,
522 /// suggest a non-capturing closure
523 pub(in super::super) fn suggest_no_capture_closure(
525 err: &mut Diagnostic,
529 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
530 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
531 // Report upto four upvars being captured to reduce the amount error messages
532 // reported back to the user.
533 let spans_and_labels = upvars
536 .map(|(var_hir_id, upvar)| {
537 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
538 let msg = format!("`{}` captured here", var_name);
541 .collect::<Vec<_>>();
543 let mut multi_span: MultiSpan =
544 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
545 for (sp, label) in spans_and_labels {
546 multi_span.push_span_label(sp, label);
550 "closures can only be coerced to `fn` types if they do not capture any variables"
558 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
559 #[instrument(skip(self, err))]
560 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
562 err: &mut Diagnostic,
563 expr: &hir::Expr<'_>,
569 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
570 // Do not suggest `Box::new` in const context.
573 let pin_did = self.tcx.lang_items().pin_type();
574 // This guards the `unwrap` and `mk_box` below.
575 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
578 let box_found = self.tcx.mk_box(found);
579 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
580 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
581 match expected.kind() {
582 ty::Adt(def, _) if Some(def.did()) == pin_did => {
583 if self.can_coerce(pin_box_found, expected) {
584 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
586 ty::Adt(def, _) if def.is_box() => {
587 err.help("use `Box::pin`");
590 err.multipart_suggestion(
591 "you need to pin and box this expression",
593 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
594 (expr.span.shrink_to_hi(), ")".to_string()),
596 Applicability::MaybeIncorrect,
601 } else if self.can_coerce(pin_found, expected) {
603 ty::Adt(def, _) if def.is_box() => {
604 err.help("use `Box::pin`");
613 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
614 // Check if the parent expression is a call to Pin::new. If it
615 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
616 // can suggest Box::pin.
617 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
618 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
622 ExprKind::Path(QPath::TypeRelative(
624 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
628 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
631 "use `Box::pin` to pin and box this expression",
633 Applicability::MachineApplicable,
644 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
646 /// ```compile_fail,E0308
647 /// # fn bar_that_returns_u32() -> u32 { 4 }
649 /// bar_that_returns_u32()
653 /// This routine checks if the return expression in a block would make sense on its own as a
654 /// statement and the return type has been left as default or has been specified as `()`. If so,
655 /// it suggests adding a semicolon.
657 /// If the expression is the expression of a closure without block (`|| expr`), a
658 /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
659 pub fn suggest_missing_semicolon(
661 err: &mut Diagnostic,
662 expression: &'tcx hir::Expr<'tcx>,
666 if expected.is_unit() {
667 // `BlockTailExpression` only relevant if the tail expr would be
668 // useful on its own.
669 match expression.kind {
671 | ExprKind::MethodCall(..)
674 | ExprKind::Match(..)
675 | ExprKind::Block(..)
676 if expression.can_have_side_effects()
677 // If the expression is from an external macro, then do not suggest
678 // adding a semicolon, because there's nowhere to put it.
680 && !in_external_macro(self.tcx.sess, expression.span) =>
683 err.multipart_suggestion(
684 "consider using a semicolon here",
686 (expression.span.shrink_to_lo(), "{ ".to_owned()),
687 (expression.span.shrink_to_hi(), "; }".to_owned()),
689 Applicability::MachineApplicable,
693 expression.span.shrink_to_hi(),
694 "consider using a semicolon here",
696 Applicability::MachineApplicable,
705 /// A possible error is to forget to add a return type that is needed:
707 /// ```compile_fail,E0308
708 /// # fn bar_that_returns_u32() -> u32 { 4 }
710 /// bar_that_returns_u32()
714 /// This routine checks if the return type is left as default, the method is not part of an
715 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
717 pub(in super::super) fn suggest_missing_return_type(
719 err: &mut Diagnostic,
720 fn_decl: &hir::FnDecl<'_>,
727 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
728 // Only suggest changing the return type for methods that
729 // haven't set a return type at all (and aren't `fn main()` or an impl).
730 match &fn_decl.output {
731 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
732 // `fn main()` must return `()`, do not suggest changing return type
733 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
736 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
737 if found.is_suggestable(self.tcx, false) {
738 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
740 } else if let ty::Closure(_, substs) = found.kind()
741 // FIXME(compiler-errors): Get better at printing binders...
742 && let closure = substs.as_closure()
743 && closure.sig().is_suggestable(self.tcx, false)
745 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
748 // FIXME: if `found` could be `impl Iterator` we should suggest that.
749 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
753 &hir::FnRetTy::Return(ref ty) => {
754 // Only point to return type if the expected type is the return type, as if they
755 // are not, the expectation must have been caused by something else.
756 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
758 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
759 debug!("suggest_missing_return_type: return type {:?}", ty);
760 debug!("suggest_missing_return_type: expected type {:?}", ty);
761 let bound_vars = self.tcx.late_bound_vars(fn_id);
762 let ty = Binder::bind_with_vars(ty, bound_vars);
763 let ty = self.normalize_associated_types_in(span, ty);
764 let ty = self.tcx.erase_late_bound_regions(ty);
765 if self.can_coerce(expected, ty) {
766 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
767 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
776 /// check whether the return type is a generic type with a trait bound
777 /// only suggest this if the generic param is not present in the arguments
778 /// if this is true, hint them towards changing the return type to `impl Trait`
779 /// ```compile_fail,E0308
780 /// fn cant_name_it<T: Fn() -> u32>() -> T {
784 fn try_suggest_return_impl_trait(
786 err: &mut Diagnostic,
791 // Only apply the suggestion if:
792 // - the return type is a generic parameter
793 // - the generic param is not used as a fn param
794 // - the generic param has at least one bound
795 // - the generic param doesn't appear in any other bounds where it's not the Self type
797 // - Changing the return type to be `impl <all bounds>`
799 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
801 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
803 let fn_node = self.tcx.hir().find(fn_id);
805 let Some(hir::Node::Item(hir::Item {
808 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
809 hir::Generics { params, predicates, .. },
813 })) = fn_node else { return };
815 if params.get(expected_ty_as_param.index as usize).is_none() {
819 // get all where BoundPredicates here, because they are used in to cases below
820 let where_predicates = predicates
822 .filter_map(|p| match p {
823 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
828 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
829 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
834 .map(|(ty, bounds)| match ty.kind() {
835 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
836 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
837 _ => match ty.contains(expected) {
842 .collect::<Result<Vec<_>, _>>();
844 let Ok(where_predicates) = where_predicates else { return };
846 // now get all predicates in the same types as the where bounds, so we can chain them
847 let predicates_from_where =
848 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
850 // extract all bounds from the source code using their spans
851 let all_matching_bounds_strs = predicates_from_where
852 .filter_map(|bound| match bound {
853 GenericBound::Trait(_, _) => {
854 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
858 .collect::<Vec<String>>();
860 if all_matching_bounds_strs.len() == 0 {
864 let all_bounds_str = all_matching_bounds_strs.join(" + ");
866 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
867 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
868 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
871 if ty_param_used_in_fn_params {
877 "consider using an impl return type",
878 format!("impl {}", all_bounds_str),
879 Applicability::MaybeIncorrect,
883 pub(in super::super) fn suggest_missing_break_or_return_expr(
885 err: &mut Diagnostic,
886 expr: &'tcx hir::Expr<'tcx>,
887 fn_decl: &hir::FnDecl<'_>,
893 if !expected.is_unit() {
896 let found = self.resolve_vars_with_obligations(found);
898 let in_loop = self.is_loop(id)
899 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
901 let in_local_statement = self.is_local_statement(id)
906 .any(|(parent_id, _)| self.is_local_statement(parent_id));
908 if in_loop && in_local_statement {
909 err.multipart_suggestion(
910 "you might have meant to break the loop with this value",
912 (expr.span.shrink_to_lo(), "break ".to_string()),
913 (expr.span.shrink_to_hi(), ";".to_string()),
915 Applicability::MaybeIncorrect,
920 if let hir::FnRetTy::Return(ty) = fn_decl.output {
921 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
922 let bound_vars = self.tcx.late_bound_vars(fn_id);
923 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
924 let ty = self.normalize_associated_types_in(expr.span, ty);
925 let ty = match self.tcx.asyncness(fn_id.owner) {
926 hir::IsAsync::Async => {
927 let infcx = self.tcx.infer_ctxt().build();
929 .get_impl_future_output_ty(ty)
932 fn_decl.output.span(),
933 "failed to get output type of async function"
938 hir::IsAsync::NotAsync => ty,
940 if self.can_coerce(found, ty) {
941 err.multipart_suggestion(
942 "you might have meant to return this value",
944 (expr.span.shrink_to_lo(), "return ".to_string()),
945 (expr.span.shrink_to_hi(), ";".to_string()),
947 Applicability::MaybeIncorrect,
953 pub(in super::super) fn suggest_missing_parentheses(
955 err: &mut Diagnostic,
956 expr: &hir::Expr<'_>,
958 let sp = self.tcx.sess.source_map().start_point(expr.span);
959 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
960 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
961 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
968 /// Given an expression type mismatch, peel any `&` expressions until we get to
969 /// a block expression, and then suggest replacing the braces with square braces
970 /// if it was possibly mistaken array syntax.
971 pub(crate) fn suggest_block_to_brackets_peeling_refs(
973 diag: &mut Diagnostic,
974 mut expr: &hir::Expr<'_>,
975 mut expr_ty: Ty<'tcx>,
976 mut expected_ty: Ty<'tcx>,
979 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
981 hir::ExprKind::AddrOf(_, _, inner_expr),
982 ty::Ref(_, inner_expr_ty, _),
983 ty::Ref(_, inner_expected_ty, _),
986 expr_ty = *inner_expr_ty;
987 expected_ty = *inner_expected_ty;
989 (hir::ExprKind::Block(blk, _), _, _) => {
990 self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
998 pub(crate) fn suggest_copied_or_cloned(
1000 diag: &mut Diagnostic,
1001 expr: &hir::Expr<'_>,
1003 expected_ty: Ty<'tcx>,
1005 let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
1006 let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
1007 if adt_def != expected_adt_def {
1011 let mut suggest_copied_or_cloned = || {
1012 let expr_inner_ty = substs.type_at(0);
1013 let expected_inner_ty = expected_substs.type_at(0);
1014 if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
1015 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
1017 let def_path = self.tcx.def_path_str(adt_def.did());
1018 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
1019 diag.span_suggestion_verbose(
1020 expr.span.shrink_to_hi(),
1022 "use `{def_path}::copied` to copy the value inside the `{def_path}`"
1025 Applicability::MachineApplicable,
1028 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
1029 && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1037 diag.span_suggestion_verbose(
1038 expr.span.shrink_to_hi(),
1040 "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
1043 Applicability::MachineApplicable,
1051 if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1052 && adt_def.did() == result_did
1053 // Check that the error types are equal
1054 && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1056 return suggest_copied_or_cloned();
1057 } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1058 && adt_def.did() == option_did
1060 return suggest_copied_or_cloned();
1066 pub(crate) fn suggest_into(
1068 diag: &mut Diagnostic,
1069 expr: &hir::Expr<'_>,
1071 expected_ty: Ty<'tcx>,
1073 let expr = expr.peel_blocks();
1075 // We have better suggestions for scalar interconversions...
1076 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1080 // Don't suggest turning a block into another type (e.g. `{}.into()`)
1081 if matches!(expr.kind, hir::ExprKind::Block(..)) {
1085 // We'll later suggest `.as_ref` when noting the type error,
1086 // so skip if we will suggest that instead.
1087 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1091 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1092 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1094 self.misc(expr.span),
1096 ty::Binder::dummy(self.tcx.mk_trait_ref(
1098 [expr_ty, expected_ty]
1100 .to_poly_trait_predicate(),
1103 let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1104 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1106 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1108 diag.multipart_suggestion(
1109 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1111 Applicability::MaybeIncorrect
1119 /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1120 pub(crate) fn suggest_option_to_bool(
1122 diag: &mut Diagnostic,
1123 expr: &hir::Expr<'_>,
1125 expected_ty: Ty<'tcx>,
1127 if !expected_ty.is_bool() {
1131 let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; };
1132 if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1136 let hir = self.tcx.hir();
1137 let cond_parent = hir.parent_iter(expr.hir_id).skip_while(|(_, node)| {
1138 matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1141 // `let Some(_) = a.is_some() && b`
1143 // since the user probably just misunderstood how `let else`
1144 // and `&&` work together.
1145 if let Some((_, hir::Node::Local(local))) = cond_parent
1146 && let hir::PatKind::Path(qpath) | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1147 && let hir::QPath::Resolved(None, path) = qpath
1148 && let Some(did) = path.res.opt_def_id()
1149 .and_then(|did| self.tcx.opt_parent(did))
1150 .and_then(|did| self.tcx.opt_parent(did))
1151 && self.tcx.is_diagnostic_item(sym::Option, did)
1156 diag.span_suggestion(
1157 expr.span.shrink_to_hi(),
1158 "use `Option::is_some` to test if the `Option` has a value",
1160 Applicability::MachineApplicable,
1166 /// Suggest wrapping the block in square brackets instead of curly braces
1167 /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1168 pub(crate) fn suggest_block_to_brackets(
1170 diag: &mut Diagnostic,
1171 blk: &hir::Block<'_>,
1173 expected_ty: Ty<'tcx>,
1175 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1176 if self.can_coerce(blk_ty, *elem_ty)
1177 && blk.stmts.is_empty()
1178 && blk.rules == hir::BlockCheckMode::DefaultBlock
1180 let source_map = self.tcx.sess.source_map();
1181 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1182 if snippet.starts_with('{') && snippet.ends_with('}') {
1183 diag.multipart_suggestion_verbose(
1184 "to create an array, use square brackets instead of curly braces",
1189 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1195 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1199 Applicability::MachineApplicable,
1207 #[instrument(skip(self, err))]
1208 pub(crate) fn suggest_floating_point_literal(
1210 err: &mut Diagnostic,
1211 expr: &hir::Expr<'_>,
1212 expected_ty: Ty<'tcx>,
1214 if !expected_ty.is_floating_point() {
1218 ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [start, end], _) => {
1219 err.span_suggestion_verbose(
1220 start.span.shrink_to_hi().with_hi(end.span.lo()),
1221 "remove the unnecessary `.` operator for a floating point literal",
1223 Applicability::MaybeIncorrect,
1227 ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, ..), [start], _) => {
1228 err.span_suggestion_verbose(
1229 expr.span.with_lo(start.span.hi()),
1230 "remove the unnecessary `.` operator for a floating point literal",
1232 Applicability::MaybeIncorrect,
1236 ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, ..), [end], _) => {
1237 err.span_suggestion_verbose(
1238 expr.span.until(end.span),
1239 "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1241 Applicability::MaybeIncorrect,
1249 fn is_loop(&self, id: hir::HirId) -> bool {
1250 let node = self.tcx.hir().get(id);
1251 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1254 fn is_local_statement(&self, id: hir::HirId) -> bool {
1255 let node = self.tcx.hir().get(id);
1256 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1259 /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1260 /// which is a side-effect of autoref.
1261 pub(crate) fn note_type_is_not_clone(
1263 diag: &mut Diagnostic,
1264 expected_ty: Ty<'tcx>,
1266 expr: &hir::Expr<'_>,
1268 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1269 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1270 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1271 let results = self.typeck_results.borrow();
1272 // First, look for a `Clone::clone` call
1273 if segment.ident.name == sym::clone
1274 && results.type_dependent_def_id(expr.hir_id).map_or(
1277 let assoc_item = self.tcx.associated_item(did);
1278 assoc_item.container == ty::AssocItemContainer::TraitContainer
1279 && assoc_item.container_id(self.tcx) == clone_trait_did
1282 // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1283 // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1284 && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1285 // Check that we're in fact trying to clone into the expected type
1286 && self.can_coerce(*pointee_ty, expected_ty)
1287 // And the expected type doesn't implement `Clone`
1288 && !self.predicate_must_hold_considering_regions(&traits::Obligation {
1289 cause: traits::ObligationCause::dummy(),
1290 param_env: self.param_env,
1292 predicate: ty::Binder::dummy(ty::TraitRef {
1293 def_id: clone_trait_did,
1294 substs: self.tcx.mk_substs([expected_ty.into()].iter()),
1297 .to_predicate(self.tcx),
1303 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1309 /// A common error is to add an extra semicolon:
1311 /// ```compile_fail,E0308
1312 /// fn foo() -> usize {
1317 /// This routine checks if the final statement in a block is an
1318 /// expression with an explicit semicolon whose type is compatible
1319 /// with `expected_ty`. If so, it suggests removing the semicolon.
1320 pub(crate) fn consider_removing_semicolon(
1322 blk: &'tcx hir::Block<'tcx>,
1323 expected_ty: Ty<'tcx>,
1324 err: &mut Diagnostic,
1326 if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1327 if let StatementAsExpression::NeedsBoxing = boxed {
1328 err.span_suggestion_verbose(
1330 "consider removing this semicolon and boxing the expression",
1332 Applicability::HasPlaceholders,
1335 err.span_suggestion_short(
1337 "remove this semicolon to return this value",
1339 Applicability::MachineApplicable,