3 use crate::errors::{AddReturnTypeSuggestion, ExpectedReturnTypeLabel};
4 use crate::method::probe::{IsSuggestion, Mode, ProbeScope};
5 use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX};
6 use rustc_errors::{Applicability, Diagnostic, MultiSpan};
8 use rustc_hir::def::{CtorOf, DefKind};
9 use rustc_hir::lang_items::LangItem;
11 Expr, ExprKind, GenericBound, Node, Path, QPath, Stmt, StmtKind, TyKind, WherePredicate,
13 use rustc_hir_analysis::astconv::AstConv;
14 use rustc_infer::infer;
15 use rustc_infer::traits::{self, StatementAsExpression};
16 use rustc_middle::lint::in_external_macro;
17 use rustc_middle::ty::{
18 self, suggest_constraining_type_params, Binder, DefIdTree, IsSuggestable, ToPredicate, Ty,
21 use rustc_session::errors::ExprParenthesesNeeded;
22 use rustc_span::source_map::Spanned;
23 use rustc_span::symbol::{sym, Ident};
24 use rustc_span::{Span, Symbol};
25 use rustc_trait_selection::infer::InferCtxtExt;
26 use rustc_trait_selection::traits::error_reporting::DefIdOrName;
27 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
28 use rustc_trait_selection::traits::NormalizeExt;
30 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
31 pub(crate) fn body_fn_sig(&self) -> Option<ty::FnSig<'tcx>> {
35 .get(self.tcx.hir().get_parent_node(self.body_id))
39 pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
40 // This suggestion is incorrect for
41 // fn foo() -> bool { match () { () => true } || match () { () => true } }
42 err.span_suggestion_short(
44 "consider using a semicolon here",
46 Applicability::MaybeIncorrect,
50 /// On implicit return expressions with mismatched types, provides the following suggestions:
52 /// - Points out the method's return type as the reason for the expected type.
53 /// - Possible missing semicolon.
54 /// - Possible missing return type if the return type is the default, and not `fn main()`.
55 pub fn suggest_mismatched_types_on_tail(
58 expr: &'tcx hir::Expr<'tcx>,
63 let expr = expr.peel_drop_temps();
64 self.suggest_missing_semicolon(err, expr, expected, false);
65 let mut pointing_at_return_type = false;
66 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
67 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
68 pointing_at_return_type = self.suggest_missing_return_type(
76 self.suggest_missing_break_or_return_expr(
77 err, expr, &fn_decl, expected, found, blk_id, fn_id,
80 pointing_at_return_type
83 /// When encountering an fn-like type, try accessing the output of the type
84 /// and suggesting calling it if it satisfies a predicate (i.e. if the
85 /// output has a method or a field):
86 /// ```compile_fail,E0308
87 /// fn foo(x: usize) -> usize { x }
88 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
90 pub(crate) fn suggest_fn_call(
95 can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
97 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(expr, found)
98 else { return false; };
99 if can_satisfy(output) {
100 let (sugg_call, mut applicability) = match inputs.len() {
101 0 => ("".to_string(), Applicability::MachineApplicable),
106 if ty.is_suggestable(self.tcx, false) {
107 format!("/* {ty} */")
109 "/* value */".to_string()
114 Applicability::HasPlaceholders,
116 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
119 let msg = match def_id_or_name {
120 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
121 DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
122 DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
123 kind => format!("call this {}", kind.descr(def_id)),
125 DefIdOrName::Name(name) => format!("call this {name}"),
128 let sugg = match expr.kind {
129 hir::ExprKind::Call(..)
130 | hir::ExprKind::Path(..)
131 | hir::ExprKind::Index(..)
132 | hir::ExprKind::Lit(..) => {
133 vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
135 hir::ExprKind::Closure { .. } => {
136 // Might be `{ expr } || { bool }`
137 applicability = Applicability::MaybeIncorrect;
139 (expr.span.shrink_to_lo(), "(".to_string()),
140 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
145 (expr.span.shrink_to_lo(), "(".to_string()),
146 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
151 err.multipart_suggestion_verbose(
152 format!("use parentheses to {msg}"),
161 /// Extracts information about a callable type for diagnostics. This is a
162 /// heuristic -- it doesn't necessarily mean that a type is always callable,
163 /// because the callable type must also be well-formed to be called.
164 pub(in super::super) fn extract_callable_info(
168 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
169 // Autoderef is useful here because sometimes we box callables, etc.
170 let Some((def_id_or_name, output, inputs)) = self.autoderef(expr.span, found).silence_errors().find_map(|(found, _)| {
171 match *found.kind() {
173 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
174 ty::FnDef(def_id, _) => {
175 let fn_sig = found.fn_sig(self.tcx);
176 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
178 ty::Closure(def_id, substs) => {
179 let fn_sig = substs.as_closure().sig();
180 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
182 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
183 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
184 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
185 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
186 // args tuple will always be substs[1]
187 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
190 DefIdOrName::DefId(def_id),
191 pred.kind().rebind(proj.term.ty().unwrap()),
192 pred.kind().rebind(args.as_slice()),
199 ty::Dynamic(data, _, ty::Dyn) => {
200 data.iter().find_map(|pred| {
201 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
202 && Some(proj.def_id) == self.tcx.lang_items().fn_once_output()
203 // for existential projection, substs are shifted over by 1
204 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
207 DefIdOrName::Name("trait object"),
208 pred.rebind(proj.term.ty().unwrap()),
209 pred.rebind(args.as_slice()),
216 ty::Param(param) => {
217 let def_id = self.tcx.generics_of(self.body_id.owner).type_param(¶m, self.tcx).def_id;
218 self.tcx.predicates_of(self.body_id.owner).predicates.iter().find_map(|(pred, _)| {
219 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
220 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
221 && proj.projection_ty.self_ty() == found
222 // args tuple will always be substs[1]
223 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
226 DefIdOrName::DefId(def_id),
227 pred.kind().rebind(proj.term.ty().unwrap()),
228 pred.kind().rebind(args.as_slice()),
237 }) else { return None; };
239 let output = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, output);
244 self.replace_bound_vars_with_fresh_vars(
252 // We don't want to register any extra obligations, which should be
253 // implied by wf, but also because that would possibly result in
254 // erroneous errors later on.
255 let infer::InferOk { value: output, obligations: _ } =
256 self.at(&self.misc(expr.span), self.param_env).normalize(output);
258 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
261 pub fn suggest_two_fn_call(
263 err: &mut Diagnostic,
264 lhs_expr: &'tcx hir::Expr<'tcx>,
266 rhs_expr: &'tcx hir::Expr<'tcx>,
268 can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
270 let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_expr, lhs_ty)
271 else { return false; };
272 let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_expr, rhs_ty)
273 else { return false; };
275 if can_satisfy(lhs_output_ty, rhs_output_ty) {
276 let mut sugg = vec![];
277 let mut applicability = Applicability::MachineApplicable;
279 for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
280 let (sugg_call, this_applicability) = match inputs.len() {
281 0 => ("".to_string(), Applicability::MachineApplicable),
286 if ty.is_suggestable(self.tcx, false) {
287 format!("/* {ty} */")
289 "/* value */".to_string()
294 Applicability::HasPlaceholders,
296 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
299 applicability = applicability.max(this_applicability);
302 hir::ExprKind::Call(..)
303 | hir::ExprKind::Path(..)
304 | hir::ExprKind::Index(..)
305 | hir::ExprKind::Lit(..) => {
306 sugg.extend([(expr.span.shrink_to_hi(), format!("({sugg_call})"))]);
308 hir::ExprKind::Closure { .. } => {
309 // Might be `{ expr } || { bool }`
310 applicability = Applicability::MaybeIncorrect;
312 (expr.span.shrink_to_lo(), "(".to_string()),
313 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
318 (expr.span.shrink_to_lo(), "(".to_string()),
319 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
325 err.multipart_suggestion_verbose("use parentheses to call these", sugg, applicability);
333 pub fn suggest_remove_last_method_call(
335 err: &mut Diagnostic,
336 expr: &hir::Expr<'tcx>,
339 if let hir::ExprKind::MethodCall(hir::PathSegment { ident: method, .. }, recv_expr, &[], _) = expr.kind &&
340 let Some(recv_ty) = self.typeck_results.borrow().expr_ty_opt(recv_expr) &&
341 self.can_coerce(recv_ty, expected) {
342 let span = if let Some(recv_span) = recv_expr.span.find_ancestor_inside(expr.span) {
343 expr.span.with_lo(recv_span.hi())
345 expr.span.with_lo(method.span.lo() - rustc_span::BytePos(1))
347 err.span_suggestion_verbose(
349 "try removing the method call",
351 Applicability::MachineApplicable,
358 pub fn suggest_deref_ref_or_into(
360 err: &mut Diagnostic,
361 expr: &hir::Expr<'tcx>,
364 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
366 let expr = expr.peel_blocks();
367 if let Some((sp, msg, suggestion, applicability, verbose, annotation)) =
368 self.check_ref(expr, found, expected)
371 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
373 err.span_suggestion(sp, &msg, suggestion, applicability);
376 let suggest_annotation = match expr.peel_drop_temps().kind {
377 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, _) => mutbl.ref_prefix_str(),
380 let mut tuple_indexes = Vec::new();
381 let mut expr_id = expr.hir_id;
382 for (parent_id, node) in self.tcx.hir().parent_iter(expr.hir_id) {
384 Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
388 .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
394 Node::Local(local) => {
395 if let Some(mut ty) = local.ty {
396 while let Some(index) = tuple_indexes.pop() {
398 TyKind::Tup(tys) => ty = &tys[index],
402 let annotation_span = ty.span;
404 annotation_span.with_hi(annotation_span.lo()),
405 "alternatively, consider changing the type annotation",
407 Applicability::MaybeIncorrect,
417 } else if self.suggest_else_fn_with_closure(err, expr, found, expected) {
419 } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected))
420 && let ty::FnDef(def_id, ..) = &found.kind()
421 && let Some(sp) = self.tcx.hir().span_if_local(*def_id)
423 err.span_label(sp, format!("{found} defined here"));
425 } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
428 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
429 if !methods.is_empty() {
430 let mut suggestions = methods.iter()
431 .filter_map(|conversion_method| {
432 let receiver_method_ident = expr.method_ident();
433 if let Some(method_ident) = receiver_method_ident
434 && method_ident.name == conversion_method.name
436 return None // do not suggest code that is already there (#53348)
439 let method_call_list = [sym::to_vec, sym::to_string];
440 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
441 && receiver_method.ident.name == sym::clone
442 && method_call_list.contains(&conversion_method.name)
443 // If receiver is `.clone()` and found type has one of those methods,
444 // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
445 // to an owned type (`Vec` or `String`). These conversions clone internally,
446 // so we remove the user's `clone` call.
449 receiver_method.ident.span,
450 conversion_method.name.to_string()
452 } else if expr.precedence().order()
453 < ExprPrecedence::MethodCall.order()
456 (expr.span.shrink_to_lo(), "(".to_string()),
457 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
460 vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
462 let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
463 if let Some(name) = struct_pat_shorthand_field {
466 (expr.span.shrink_to_lo(), format!("{}: ", name)),
472 if suggestions.peek().is_some() {
473 err.multipart_suggestions(
474 "try using a conversion method",
476 Applicability::MaybeIncorrect,
480 } else if let ty::Adt(found_adt, found_substs) = found.kind()
481 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
482 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
483 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
484 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
487 let ty = found_substs.type_at(0);
490 while let ty::Ref(_, inner, _) = peeled.kind() {
494 if let ty::Adt(adt, _) = peeled.kind()
495 && Some(adt.did()) == self.tcx.lang_items().string()
497 err.span_suggestion_verbose(
498 expr.span.shrink_to_hi(),
499 "try converting the passed type into a `&str`",
500 format!(".map(|x| &*{}x)", "*".repeat(ref_cnt)),
501 Applicability::MaybeIncorrect,
511 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
512 /// in the heap by calling `Box::new()`.
513 pub(in super::super) fn suggest_boxing_when_appropriate(
515 err: &mut Diagnostic,
516 expr: &hir::Expr<'_>,
520 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
521 // Do not suggest `Box::new` in const context.
524 if !expected.is_box() || found.is_box() {
527 let boxed_found = self.tcx.mk_box(found);
528 if self.can_coerce(boxed_found, expected) {
529 err.multipart_suggestion(
530 "store this in the heap by calling `Box::new`",
532 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
533 (expr.span.shrink_to_hi(), ")".to_string()),
535 Applicability::MachineApplicable,
538 "for more on the distinction between the stack and the heap, read \
539 https://doc.rust-lang.org/book/ch15-01-box.html, \
540 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
541 https://doc.rust-lang.org/std/boxed/index.html",
549 /// When encountering a closure that captures variables, where a FnPtr is expected,
550 /// suggest a non-capturing closure
551 pub(in super::super) fn suggest_no_capture_closure(
553 err: &mut Diagnostic,
557 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
558 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
559 // Report upto four upvars being captured to reduce the amount error messages
560 // reported back to the user.
561 let spans_and_labels = upvars
564 .map(|(var_hir_id, upvar)| {
565 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
566 let msg = format!("`{}` captured here", var_name);
569 .collect::<Vec<_>>();
571 let mut multi_span: MultiSpan =
572 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
573 for (sp, label) in spans_and_labels {
574 multi_span.push_span_label(sp, label);
578 "closures can only be coerced to `fn` types if they do not capture any variables"
586 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
587 #[instrument(skip(self, err))]
588 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
590 err: &mut Diagnostic,
591 expr: &hir::Expr<'_>,
597 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
598 // Do not suggest `Box::new` in const context.
601 let pin_did = self.tcx.lang_items().pin_type();
602 // This guards the `unwrap` and `mk_box` below.
603 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
606 let box_found = self.tcx.mk_box(found);
607 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
608 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
609 match expected.kind() {
610 ty::Adt(def, _) if Some(def.did()) == pin_did => {
611 if self.can_coerce(pin_box_found, expected) {
612 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
614 ty::Adt(def, _) if def.is_box() => {
615 err.help("use `Box::pin`");
618 err.multipart_suggestion(
619 "you need to pin and box this expression",
621 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
622 (expr.span.shrink_to_hi(), ")".to_string()),
624 Applicability::MaybeIncorrect,
629 } else if self.can_coerce(pin_found, expected) {
631 ty::Adt(def, _) if def.is_box() => {
632 err.help("use `Box::pin`");
641 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
642 // Check if the parent expression is a call to Pin::new. If it
643 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
644 // can suggest Box::pin.
645 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
646 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
650 ExprKind::Path(QPath::TypeRelative(
652 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
656 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
659 "use `Box::pin` to pin and box this expression",
661 Applicability::MachineApplicable,
672 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
674 /// ```compile_fail,E0308
675 /// # fn bar_that_returns_u32() -> u32 { 4 }
677 /// bar_that_returns_u32()
681 /// This routine checks if the return expression in a block would make sense on its own as a
682 /// statement and the return type has been left as default or has been specified as `()`. If so,
683 /// it suggests adding a semicolon.
685 /// If the expression is the expression of a closure without block (`|| expr`), a
686 /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
687 pub fn suggest_missing_semicolon(
689 err: &mut Diagnostic,
690 expression: &'tcx hir::Expr<'tcx>,
694 if expected.is_unit() {
695 // `BlockTailExpression` only relevant if the tail expr would be
696 // useful on its own.
697 match expression.kind {
699 | ExprKind::MethodCall(..)
702 | ExprKind::Match(..)
703 | ExprKind::Block(..)
704 if expression.can_have_side_effects()
705 // If the expression is from an external macro, then do not suggest
706 // adding a semicolon, because there's nowhere to put it.
708 && !in_external_macro(self.tcx.sess, expression.span) =>
711 err.multipart_suggestion(
712 "consider using a semicolon here",
714 (expression.span.shrink_to_lo(), "{ ".to_owned()),
715 (expression.span.shrink_to_hi(), "; }".to_owned()),
717 Applicability::MachineApplicable,
721 expression.span.shrink_to_hi(),
722 "consider using a semicolon here",
724 Applicability::MachineApplicable,
733 /// A possible error is to forget to add a return type that is needed:
735 /// ```compile_fail,E0308
736 /// # fn bar_that_returns_u32() -> u32 { 4 }
738 /// bar_that_returns_u32()
742 /// This routine checks if the return type is left as default, the method is not part of an
743 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
745 pub(in super::super) fn suggest_missing_return_type(
747 err: &mut Diagnostic,
748 fn_decl: &hir::FnDecl<'_>,
755 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
756 // Only suggest changing the return type for methods that
757 // haven't set a return type at all (and aren't `fn main()` or an impl).
758 match &fn_decl.output {
759 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
760 // `fn main()` must return `()`, do not suggest changing return type
761 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
764 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
765 if found.is_suggestable(self.tcx, false) {
766 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
768 } else if let ty::Closure(_, substs) = found.kind()
769 // FIXME(compiler-errors): Get better at printing binders...
770 && let closure = substs.as_closure()
771 && closure.sig().is_suggestable(self.tcx, false)
773 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
776 // FIXME: if `found` could be `impl Iterator` we should suggest that.
777 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
781 hir::FnRetTy::Return(ty) => {
782 // Only point to return type if the expected type is the return type, as if they
783 // are not, the expectation must have been caused by something else.
784 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
786 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
787 debug!("suggest_missing_return_type: return type {:?}", ty);
788 debug!("suggest_missing_return_type: expected type {:?}", ty);
789 let bound_vars = self.tcx.late_bound_vars(fn_id);
790 let ty = Binder::bind_with_vars(ty, bound_vars);
791 let ty = self.normalize(span, ty);
792 let ty = self.tcx.erase_late_bound_regions(ty);
793 if self.can_coerce(expected, ty) {
794 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
795 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
804 /// check whether the return type is a generic type with a trait bound
805 /// only suggest this if the generic param is not present in the arguments
806 /// if this is true, hint them towards changing the return type to `impl Trait`
807 /// ```compile_fail,E0308
808 /// fn cant_name_it<T: Fn() -> u32>() -> T {
812 fn try_suggest_return_impl_trait(
814 err: &mut Diagnostic,
819 // Only apply the suggestion if:
820 // - the return type is a generic parameter
821 // - the generic param is not used as a fn param
822 // - the generic param has at least one bound
823 // - the generic param doesn't appear in any other bounds where it's not the Self type
825 // - Changing the return type to be `impl <all bounds>`
827 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
829 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
831 let fn_node = self.tcx.hir().find(fn_id);
833 let Some(hir::Node::Item(hir::Item {
836 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
837 hir::Generics { params, predicates, .. },
841 })) = fn_node else { return };
843 if params.get(expected_ty_as_param.index as usize).is_none() {
847 // get all where BoundPredicates here, because they are used in to cases below
848 let where_predicates = predicates
850 .filter_map(|p| match p {
851 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
856 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
857 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
862 .map(|(ty, bounds)| match ty.kind() {
863 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
864 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
865 _ => match ty.contains(expected) {
870 .collect::<Result<Vec<_>, _>>();
872 let Ok(where_predicates) = where_predicates else { return };
874 // now get all predicates in the same types as the where bounds, so we can chain them
875 let predicates_from_where =
876 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
878 // extract all bounds from the source code using their spans
879 let all_matching_bounds_strs = predicates_from_where
880 .filter_map(|bound| match bound {
881 GenericBound::Trait(_, _) => {
882 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
886 .collect::<Vec<String>>();
888 if all_matching_bounds_strs.len() == 0 {
892 let all_bounds_str = all_matching_bounds_strs.join(" + ");
894 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
895 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
896 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
899 if ty_param_used_in_fn_params {
905 "consider using an impl return type",
906 format!("impl {}", all_bounds_str),
907 Applicability::MaybeIncorrect,
911 pub(in super::super) fn suggest_missing_break_or_return_expr(
913 err: &mut Diagnostic,
914 expr: &'tcx hir::Expr<'tcx>,
915 fn_decl: &hir::FnDecl<'_>,
921 if !expected.is_unit() {
924 let found = self.resolve_vars_with_obligations(found);
926 let in_loop = self.is_loop(id)
927 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
929 let in_local_statement = self.is_local_statement(id)
934 .any(|(parent_id, _)| self.is_local_statement(parent_id));
936 if in_loop && in_local_statement {
937 err.multipart_suggestion(
938 "you might have meant to break the loop with this value",
940 (expr.span.shrink_to_lo(), "break ".to_string()),
941 (expr.span.shrink_to_hi(), ";".to_string()),
943 Applicability::MaybeIncorrect,
948 if let hir::FnRetTy::Return(ty) = fn_decl.output {
949 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
950 let bound_vars = self.tcx.late_bound_vars(fn_id);
951 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
952 let ty = match self.tcx.asyncness(fn_id.owner) {
953 hir::IsAsync::Async => self.get_impl_future_output_ty(ty).unwrap_or_else(|| {
954 span_bug!(fn_decl.output.span(), "failed to get output type of async function")
956 hir::IsAsync::NotAsync => ty,
958 let ty = self.normalize(expr.span, ty);
959 if self.can_coerce(found, ty) {
960 err.multipart_suggestion(
961 "you might have meant to return this value",
963 (expr.span.shrink_to_lo(), "return ".to_string()),
964 (expr.span.shrink_to_hi(), ";".to_string()),
966 Applicability::MaybeIncorrect,
972 pub(in super::super) fn suggest_missing_parentheses(
974 err: &mut Diagnostic,
975 expr: &hir::Expr<'_>,
977 let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
978 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
979 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
980 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
987 /// Given an expression type mismatch, peel any `&` expressions until we get to
988 /// a block expression, and then suggest replacing the braces with square braces
989 /// if it was possibly mistaken array syntax.
990 pub(crate) fn suggest_block_to_brackets_peeling_refs(
992 diag: &mut Diagnostic,
993 mut expr: &hir::Expr<'_>,
994 mut expr_ty: Ty<'tcx>,
995 mut expected_ty: Ty<'tcx>,
998 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
1000 hir::ExprKind::AddrOf(_, _, inner_expr),
1001 ty::Ref(_, inner_expr_ty, _),
1002 ty::Ref(_, inner_expected_ty, _),
1005 expr_ty = *inner_expr_ty;
1006 expected_ty = *inner_expected_ty;
1008 (hir::ExprKind::Block(blk, _), _, _) => {
1009 self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
1017 pub(crate) fn suggest_copied_or_cloned(
1019 diag: &mut Diagnostic,
1020 expr: &hir::Expr<'_>,
1022 expected_ty: Ty<'tcx>,
1024 let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
1025 let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
1026 if adt_def != expected_adt_def {
1030 let mut suggest_copied_or_cloned = || {
1031 let expr_inner_ty = substs.type_at(0);
1032 let expected_inner_ty = expected_substs.type_at(0);
1033 if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
1034 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
1036 let def_path = self.tcx.def_path_str(adt_def.did());
1037 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
1038 diag.span_suggestion_verbose(
1039 expr.span.shrink_to_hi(),
1041 "use `{def_path}::copied` to copy the value inside the `{def_path}`"
1044 Applicability::MachineApplicable,
1047 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
1048 && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1056 diag.span_suggestion_verbose(
1057 expr.span.shrink_to_hi(),
1059 "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
1062 Applicability::MachineApplicable,
1070 if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1071 && adt_def.did() == result_did
1072 // Check that the error types are equal
1073 && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1075 return suggest_copied_or_cloned();
1076 } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1077 && adt_def.did() == option_did
1079 return suggest_copied_or_cloned();
1085 pub(crate) fn suggest_into(
1087 diag: &mut Diagnostic,
1088 expr: &hir::Expr<'_>,
1090 expected_ty: Ty<'tcx>,
1092 let expr = expr.peel_blocks();
1094 // We have better suggestions for scalar interconversions...
1095 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1099 // Don't suggest turning a block into another type (e.g. `{}.into()`)
1100 if matches!(expr.kind, hir::ExprKind::Block(..)) {
1104 // We'll later suggest `.as_ref` when noting the type error,
1105 // so skip if we will suggest that instead.
1106 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1110 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1111 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1113 self.misc(expr.span),
1115 ty::Binder::dummy(self.tcx.mk_trait_ref(
1117 [expr_ty, expected_ty]
1121 let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1122 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1124 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1126 diag.multipart_suggestion(
1127 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1129 Applicability::MaybeIncorrect
1137 /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1138 pub(crate) fn suggest_option_to_bool(
1140 diag: &mut Diagnostic,
1141 expr: &hir::Expr<'_>,
1143 expected_ty: Ty<'tcx>,
1145 if !expected_ty.is_bool() {
1149 let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; };
1150 if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1154 let hir = self.tcx.hir();
1155 let cond_parent = hir.parent_iter(expr.hir_id).find(|(_, node)| {
1156 !matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1159 // `let Some(_) = a.is_some() && b`
1161 // since the user probably just misunderstood how `let else`
1162 // and `&&` work together.
1163 if let Some((_, hir::Node::Local(local))) = cond_parent
1164 && let hir::PatKind::Path(qpath) | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1165 && let hir::QPath::Resolved(None, path) = qpath
1166 && let Some(did) = path.res.opt_def_id()
1167 .and_then(|did| self.tcx.opt_parent(did))
1168 .and_then(|did| self.tcx.opt_parent(did))
1169 && self.tcx.is_diagnostic_item(sym::Option, did)
1174 diag.span_suggestion(
1175 expr.span.shrink_to_hi(),
1176 "use `Option::is_some` to test if the `Option` has a value",
1178 Applicability::MachineApplicable,
1184 /// Suggest wrapping the block in square brackets instead of curly braces
1185 /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1186 pub(crate) fn suggest_block_to_brackets(
1188 diag: &mut Diagnostic,
1189 blk: &hir::Block<'_>,
1191 expected_ty: Ty<'tcx>,
1193 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1194 if self.can_coerce(blk_ty, *elem_ty)
1195 && blk.stmts.is_empty()
1196 && blk.rules == hir::BlockCheckMode::DefaultBlock
1198 let source_map = self.tcx.sess.source_map();
1199 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1200 if snippet.starts_with('{') && snippet.ends_with('}') {
1201 diag.multipart_suggestion_verbose(
1202 "to create an array, use square brackets instead of curly braces",
1207 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1213 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1217 Applicability::MachineApplicable,
1225 #[instrument(skip(self, err))]
1226 pub(crate) fn suggest_floating_point_literal(
1228 err: &mut Diagnostic,
1229 expr: &hir::Expr<'_>,
1230 expected_ty: Ty<'tcx>,
1232 if !expected_ty.is_floating_point() {
1236 ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [start, end], _) => {
1237 err.span_suggestion_verbose(
1238 start.span.shrink_to_hi().with_hi(end.span.lo()),
1239 "remove the unnecessary `.` operator for a floating point literal",
1241 Applicability::MaybeIncorrect,
1245 ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, ..), [start], _) => {
1246 err.span_suggestion_verbose(
1247 expr.span.with_lo(start.span.hi()),
1248 "remove the unnecessary `.` operator for a floating point literal",
1250 Applicability::MaybeIncorrect,
1254 ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, ..), [end], _) => {
1255 err.span_suggestion_verbose(
1256 expr.span.until(end.span),
1257 "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1259 Applicability::MaybeIncorrect,
1263 ExprKind::Lit(Spanned {
1264 node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed),
1267 let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) else { return false; };
1268 if !(snippet.starts_with("0x") || snippet.starts_with("0X")) {
1271 if snippet.len() <= 5 || !snippet.is_char_boundary(snippet.len() - 3) {
1274 let (_, suffix) = snippet.split_at(snippet.len() - 3);
1275 let value = match suffix {
1276 "f32" => (lit - 0xf32) / (16 * 16 * 16),
1277 "f64" => (lit - 0xf64) / (16 * 16 * 16),
1280 err.span_suggestions(
1282 "rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
1283 [format!("0x{value:X} as {suffix}"), format!("{value}_{suffix}")],
1284 Applicability::MaybeIncorrect,
1292 pub(crate) fn suggest_associated_const(
1294 err: &mut Diagnostic,
1295 expr: &hir::Expr<'_>,
1296 expected_ty: Ty<'tcx>,
1298 let Some((DefKind::AssocFn, old_def_id)) = self.typeck_results.borrow().type_dependent_def(expr.hir_id) else {
1301 let old_item_name = self.tcx.item_name(old_def_id);
1302 let capitalized_name = Symbol::intern(&old_item_name.as_str().to_uppercase());
1303 if old_item_name == capitalized_name {
1306 let (item, segment) = match expr.kind {
1307 hir::ExprKind::Path(QPath::Resolved(
1309 hir::Path { segments: [segment], .. },
1311 | hir::ExprKind::Path(QPath::TypeRelative(ty, segment)) => {
1312 let self_ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
1313 if let Ok(pick) = self.probe_for_name(
1315 Ident::new(capitalized_name, segment.ident.span),
1319 ProbeScope::TraitsInScope,
1321 (pick.item, segment)
1326 hir::ExprKind::Path(QPath::Resolved(
1328 hir::Path { segments: [.., segment], .. },
1330 // we resolved through some path that doesn't end in the item name,
1331 // better not do a bad suggestion by accident.
1332 if old_item_name != segment.ident.name {
1335 if let Some(item) = self
1337 .associated_items(self.tcx.parent(old_def_id))
1338 .filter_by_name_unhygienic(capitalized_name)
1348 if item.def_id == old_def_id || self.tcx.def_kind(item.def_id) != DefKind::AssocConst {
1352 let item_ty = self.tcx.type_of(item.def_id);
1353 // FIXME(compiler-errors): This check is *so* rudimentary
1354 if item_ty.needs_subst() {
1357 if self.can_coerce(item_ty, expected_ty) {
1358 err.span_suggestion_verbose(
1360 format!("try referring to the associated const `{capitalized_name}` instead",),
1362 Applicability::MachineApplicable,
1370 fn is_loop(&self, id: hir::HirId) -> bool {
1371 let node = self.tcx.hir().get(id);
1372 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1375 fn is_local_statement(&self, id: hir::HirId) -> bool {
1376 let node = self.tcx.hir().get(id);
1377 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1380 /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1381 /// which is a side-effect of autoref.
1382 pub(crate) fn note_type_is_not_clone(
1384 diag: &mut Diagnostic,
1385 expected_ty: Ty<'tcx>,
1387 expr: &hir::Expr<'_>,
1389 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1390 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1391 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1392 let results = self.typeck_results.borrow();
1393 // First, look for a `Clone::clone` call
1394 if segment.ident.name == sym::clone
1395 && results.type_dependent_def_id(expr.hir_id).map_or(
1398 let assoc_item = self.tcx.associated_item(did);
1399 assoc_item.container == ty::AssocItemContainer::TraitContainer
1400 && assoc_item.container_id(self.tcx) == clone_trait_did
1403 // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1404 // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1405 && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1406 // Check that we're in fact trying to clone into the expected type
1407 && self.can_coerce(*pointee_ty, expected_ty)
1408 && let trait_ref = ty::Binder::dummy(self.tcx.mk_trait_ref(clone_trait_did, [expected_ty]))
1409 // And the expected type doesn't implement `Clone`
1410 && !self.predicate_must_hold_considering_regions(&traits::Obligation::new(
1412 traits::ObligationCause::dummy(),
1420 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1423 let owner = self.tcx.hir().enclosing_body_owner(expr.hir_id);
1424 if let ty::Param(param) = expected_ty.kind()
1425 && let Some(generics) = self.tcx.hir().get_generics(owner)
1427 suggest_constraining_type_params(
1431 vec![(param.name.as_str(), "Clone", Some(clone_trait_did))].into_iter(),
1434 self.suggest_derive(diag, &[(trait_ref.to_predicate(self.tcx), None, None)]);
1439 /// A common error is to add an extra semicolon:
1441 /// ```compile_fail,E0308
1442 /// fn foo() -> usize {
1447 /// This routine checks if the final statement in a block is an
1448 /// expression with an explicit semicolon whose type is compatible
1449 /// with `expected_ty`. If so, it suggests removing the semicolon.
1450 pub(crate) fn consider_removing_semicolon(
1452 blk: &'tcx hir::Block<'tcx>,
1453 expected_ty: Ty<'tcx>,
1454 err: &mut Diagnostic,
1456 if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1457 if let StatementAsExpression::NeedsBoxing = boxed {
1458 err.span_suggestion_verbose(
1460 "consider removing this semicolon and boxing the expression",
1462 Applicability::HasPlaceholders,
1465 err.span_suggestion_short(
1467 "remove this semicolon to return this value",
1469 Applicability::MachineApplicable,