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::{CtorKind, 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().parent_id(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 let name = self.tcx.item_name(def_id);
424 let kind = self.tcx.def_kind(def_id);
425 if let DefKind::Ctor(of, CtorKind::Fn) = kind {
426 err.span_label(sp, format!("`{name}` defines {} constructor here, which should be called", match of {
427 CtorOf::Struct => "a struct",
428 CtorOf::Variant => "an enum variant",
431 let descr = kind.descr(def_id);
432 err.span_label(sp, format!("{descr} `{name}` defined here"));
435 } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
438 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
439 if !methods.is_empty() {
440 let mut suggestions = methods.iter()
441 .filter_map(|conversion_method| {
442 let receiver_method_ident = expr.method_ident();
443 if let Some(method_ident) = receiver_method_ident
444 && method_ident.name == conversion_method.name
446 return None // do not suggest code that is already there (#53348)
449 let method_call_list = [sym::to_vec, sym::to_string];
450 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
451 && receiver_method.ident.name == sym::clone
452 && method_call_list.contains(&conversion_method.name)
453 // If receiver is `.clone()` and found type has one of those methods,
454 // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
455 // to an owned type (`Vec` or `String`). These conversions clone internally,
456 // so we remove the user's `clone` call.
459 receiver_method.ident.span,
460 conversion_method.name.to_string()
462 } else if expr.precedence().order()
463 < ExprPrecedence::MethodCall.order()
466 (expr.span.shrink_to_lo(), "(".to_string()),
467 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
470 vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
472 let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
473 if let Some(name) = struct_pat_shorthand_field {
476 (expr.span.shrink_to_lo(), format!("{}: ", name)),
482 if suggestions.peek().is_some() {
483 err.multipart_suggestions(
484 "try using a conversion method",
486 Applicability::MaybeIncorrect,
490 } else if let ty::Adt(found_adt, found_substs) = found.kind()
491 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
492 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
493 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
494 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
497 let ty = found_substs.type_at(0);
500 while let ty::Ref(_, inner, _) = peeled.kind() {
504 if let ty::Adt(adt, _) = peeled.kind()
505 && Some(adt.did()) == self.tcx.lang_items().string()
507 err.span_suggestion_verbose(
508 expr.span.shrink_to_hi(),
509 "try converting the passed type into a `&str`",
510 format!(".map(|x| &*{}x)", "*".repeat(ref_cnt)),
511 Applicability::MaybeIncorrect,
521 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
522 /// in the heap by calling `Box::new()`.
523 pub(in super::super) fn suggest_boxing_when_appropriate(
525 err: &mut Diagnostic,
526 expr: &hir::Expr<'_>,
530 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
531 // Do not suggest `Box::new` in const context.
534 if !expected.is_box() || found.is_box() {
537 let boxed_found = self.tcx.mk_box(found);
538 if self.can_coerce(boxed_found, expected) {
539 err.multipart_suggestion(
540 "store this in the heap by calling `Box::new`",
542 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
543 (expr.span.shrink_to_hi(), ")".to_string()),
545 Applicability::MachineApplicable,
548 "for more on the distinction between the stack and the heap, read \
549 https://doc.rust-lang.org/book/ch15-01-box.html, \
550 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
551 https://doc.rust-lang.org/std/boxed/index.html",
559 /// When encountering a closure that captures variables, where a FnPtr is expected,
560 /// suggest a non-capturing closure
561 pub(in super::super) fn suggest_no_capture_closure(
563 err: &mut Diagnostic,
567 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
568 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
569 // Report upto four upvars being captured to reduce the amount error messages
570 // reported back to the user.
571 let spans_and_labels = upvars
574 .map(|(var_hir_id, upvar)| {
575 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
576 let msg = format!("`{}` captured here", var_name);
579 .collect::<Vec<_>>();
581 let mut multi_span: MultiSpan =
582 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
583 for (sp, label) in spans_and_labels {
584 multi_span.push_span_label(sp, label);
588 "closures can only be coerced to `fn` types if they do not capture any variables"
596 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
597 #[instrument(skip(self, err))]
598 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
600 err: &mut Diagnostic,
601 expr: &hir::Expr<'_>,
607 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
608 // Do not suggest `Box::new` in const context.
611 let pin_did = self.tcx.lang_items().pin_type();
612 // This guards the `unwrap` and `mk_box` below.
613 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
616 let box_found = self.tcx.mk_box(found);
617 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
618 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
619 match expected.kind() {
620 ty::Adt(def, _) if Some(def.did()) == pin_did => {
621 if self.can_coerce(pin_box_found, expected) {
622 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
624 ty::Adt(def, _) if def.is_box() => {
625 err.help("use `Box::pin`");
628 err.multipart_suggestion(
629 "you need to pin and box this expression",
631 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
632 (expr.span.shrink_to_hi(), ")".to_string()),
634 Applicability::MaybeIncorrect,
639 } else if self.can_coerce(pin_found, expected) {
641 ty::Adt(def, _) if def.is_box() => {
642 err.help("use `Box::pin`");
651 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
652 // Check if the parent expression is a call to Pin::new. If it
653 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
654 // can suggest Box::pin.
655 let parent = self.tcx.hir().parent_id(expr.hir_id);
656 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
660 ExprKind::Path(QPath::TypeRelative(
662 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
666 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
669 "use `Box::pin` to pin and box this expression",
671 Applicability::MachineApplicable,
682 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
684 /// ```compile_fail,E0308
685 /// # fn bar_that_returns_u32() -> u32 { 4 }
687 /// bar_that_returns_u32()
691 /// This routine checks if the return expression in a block would make sense on its own as a
692 /// statement and the return type has been left as default or has been specified as `()`. If so,
693 /// it suggests adding a semicolon.
695 /// If the expression is the expression of a closure without block (`|| expr`), a
696 /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
697 pub fn suggest_missing_semicolon(
699 err: &mut Diagnostic,
700 expression: &'tcx hir::Expr<'tcx>,
704 if expected.is_unit() {
705 // `BlockTailExpression` only relevant if the tail expr would be
706 // useful on its own.
707 match expression.kind {
709 | ExprKind::MethodCall(..)
712 | ExprKind::Match(..)
713 | ExprKind::Block(..)
714 if expression.can_have_side_effects()
715 // If the expression is from an external macro, then do not suggest
716 // adding a semicolon, because there's nowhere to put it.
718 && !in_external_macro(self.tcx.sess, expression.span) =>
721 err.multipart_suggestion(
722 "consider using a semicolon here",
724 (expression.span.shrink_to_lo(), "{ ".to_owned()),
725 (expression.span.shrink_to_hi(), "; }".to_owned()),
727 Applicability::MachineApplicable,
731 expression.span.shrink_to_hi(),
732 "consider using a semicolon here",
734 Applicability::MachineApplicable,
743 /// A possible error is to forget to add a return type that is needed:
745 /// ```compile_fail,E0308
746 /// # fn bar_that_returns_u32() -> u32 { 4 }
748 /// bar_that_returns_u32()
752 /// This routine checks if the return type is left as default, the method is not part of an
753 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
755 pub(in super::super) fn suggest_missing_return_type(
757 err: &mut Diagnostic,
758 fn_decl: &hir::FnDecl<'_>,
765 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
766 // Only suggest changing the return type for methods that
767 // haven't set a return type at all (and aren't `fn main()` or an impl).
768 match &fn_decl.output {
769 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
770 // `fn main()` must return `()`, do not suggest changing return type
771 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
774 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
775 if found.is_suggestable(self.tcx, false) {
776 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
778 } else if let ty::Closure(_, substs) = found.kind()
779 // FIXME(compiler-errors): Get better at printing binders...
780 && let closure = substs.as_closure()
781 && closure.sig().is_suggestable(self.tcx, false)
783 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
786 // FIXME: if `found` could be `impl Iterator` we should suggest that.
787 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
791 hir::FnRetTy::Return(ty) => {
792 // Only point to return type if the expected type is the return type, as if they
793 // are not, the expectation must have been caused by something else.
794 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
796 let ty = self.astconv().ast_ty_to_ty(ty);
797 debug!("suggest_missing_return_type: return type {:?}", ty);
798 debug!("suggest_missing_return_type: expected type {:?}", ty);
799 let bound_vars = self.tcx.late_bound_vars(fn_id);
800 let ty = Binder::bind_with_vars(ty, bound_vars);
801 let ty = self.normalize(span, ty);
802 let ty = self.tcx.erase_late_bound_regions(ty);
803 if self.can_coerce(expected, ty) {
804 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
805 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
814 /// check whether the return type is a generic type with a trait bound
815 /// only suggest this if the generic param is not present in the arguments
816 /// if this is true, hint them towards changing the return type to `impl Trait`
817 /// ```compile_fail,E0308
818 /// fn cant_name_it<T: Fn() -> u32>() -> T {
822 fn try_suggest_return_impl_trait(
824 err: &mut Diagnostic,
829 // Only apply the suggestion if:
830 // - the return type is a generic parameter
831 // - the generic param is not used as a fn param
832 // - the generic param has at least one bound
833 // - the generic param doesn't appear in any other bounds where it's not the Self type
835 // - Changing the return type to be `impl <all bounds>`
837 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
839 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
841 let fn_node = self.tcx.hir().find(fn_id);
843 let Some(hir::Node::Item(hir::Item {
846 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
847 hir::Generics { params, predicates, .. },
851 })) = fn_node else { return };
853 if params.get(expected_ty_as_param.index as usize).is_none() {
857 // get all where BoundPredicates here, because they are used in to cases below
858 let where_predicates = predicates
860 .filter_map(|p| match p {
861 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
866 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
867 let ty = self.astconv().ast_ty_to_ty(bounded_ty);
872 .map(|(ty, bounds)| match ty.kind() {
873 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
874 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
875 _ => match ty.contains(expected) {
880 .collect::<Result<Vec<_>, _>>();
882 let Ok(where_predicates) = where_predicates else { return };
884 // now get all predicates in the same types as the where bounds, so we can chain them
885 let predicates_from_where =
886 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
888 // extract all bounds from the source code using their spans
889 let all_matching_bounds_strs = predicates_from_where
890 .filter_map(|bound| match bound {
891 GenericBound::Trait(_, _) => {
892 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
896 .collect::<Vec<String>>();
898 if all_matching_bounds_strs.len() == 0 {
902 let all_bounds_str = all_matching_bounds_strs.join(" + ");
904 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
905 let ty = self.astconv().ast_ty_to_ty( param);
906 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
909 if ty_param_used_in_fn_params {
915 "consider using an impl return type",
916 format!("impl {}", all_bounds_str),
917 Applicability::MaybeIncorrect,
921 pub(in super::super) fn suggest_missing_break_or_return_expr(
923 err: &mut Diagnostic,
924 expr: &'tcx hir::Expr<'tcx>,
925 fn_decl: &hir::FnDecl<'_>,
931 if !expected.is_unit() {
934 let found = self.resolve_vars_with_obligations(found);
936 let in_loop = self.is_loop(id)
937 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
939 let in_local_statement = self.is_local_statement(id)
944 .any(|(parent_id, _)| self.is_local_statement(parent_id));
946 if in_loop && in_local_statement {
947 err.multipart_suggestion(
948 "you might have meant to break the loop with this value",
950 (expr.span.shrink_to_lo(), "break ".to_string()),
951 (expr.span.shrink_to_hi(), ";".to_string()),
953 Applicability::MaybeIncorrect,
958 if let hir::FnRetTy::Return(ty) = fn_decl.output {
959 let ty = self.astconv().ast_ty_to_ty(ty);
960 let bound_vars = self.tcx.late_bound_vars(fn_id);
961 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
962 let ty = match self.tcx.asyncness(fn_id.owner) {
963 hir::IsAsync::Async => self.get_impl_future_output_ty(ty).unwrap_or_else(|| {
964 span_bug!(fn_decl.output.span(), "failed to get output type of async function")
966 hir::IsAsync::NotAsync => ty,
968 let ty = self.normalize(expr.span, ty);
969 if self.can_coerce(found, ty) {
970 err.multipart_suggestion(
971 "you might have meant to return this value",
973 (expr.span.shrink_to_lo(), "return ".to_string()),
974 (expr.span.shrink_to_hi(), ";".to_string()),
976 Applicability::MaybeIncorrect,
982 pub(in super::super) fn suggest_missing_parentheses(
984 err: &mut Diagnostic,
985 expr: &hir::Expr<'_>,
987 let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
988 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
989 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
990 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
997 /// Given an expression type mismatch, peel any `&` expressions until we get to
998 /// a block expression, and then suggest replacing the braces with square braces
999 /// if it was possibly mistaken array syntax.
1000 pub(crate) fn suggest_block_to_brackets_peeling_refs(
1002 diag: &mut Diagnostic,
1003 mut expr: &hir::Expr<'_>,
1004 mut expr_ty: Ty<'tcx>,
1005 mut expected_ty: Ty<'tcx>,
1008 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
1010 hir::ExprKind::AddrOf(_, _, inner_expr),
1011 ty::Ref(_, inner_expr_ty, _),
1012 ty::Ref(_, inner_expected_ty, _),
1015 expr_ty = *inner_expr_ty;
1016 expected_ty = *inner_expected_ty;
1018 (hir::ExprKind::Block(blk, _), _, _) => {
1019 self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
1027 pub(crate) fn suggest_clone_for_ref(
1029 diag: &mut Diagnostic,
1030 expr: &hir::Expr<'_>,
1032 expected_ty: Ty<'tcx>,
1034 if let ty::Ref(_, inner_ty, hir::Mutability::Not) = expr_ty.kind()
1035 && let Some(clone_trait_def) = self.tcx.lang_items().clone_trait()
1036 && expected_ty == *inner_ty
1039 .type_implements_trait(
1041 [self.tcx.erase_regions(expected_ty)],
1044 .must_apply_modulo_regions()
1046 diag.span_suggestion_verbose(
1047 expr.span.shrink_to_hi(),
1048 "consider using clone here",
1050 Applicability::MachineApplicable,
1057 pub(crate) fn suggest_copied_or_cloned(
1059 diag: &mut Diagnostic,
1060 expr: &hir::Expr<'_>,
1062 expected_ty: Ty<'tcx>,
1064 let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
1065 let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
1066 if adt_def != expected_adt_def {
1070 let mut suggest_copied_or_cloned = || {
1071 let expr_inner_ty = substs.type_at(0);
1072 let expected_inner_ty = expected_substs.type_at(0);
1073 if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
1074 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
1076 let def_path = self.tcx.def_path_str(adt_def.did());
1077 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
1078 diag.span_suggestion_verbose(
1079 expr.span.shrink_to_hi(),
1081 "use `{def_path}::copied` to copy the value inside the `{def_path}`"
1084 Applicability::MachineApplicable,
1087 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
1088 && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1096 diag.span_suggestion_verbose(
1097 expr.span.shrink_to_hi(),
1099 "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
1102 Applicability::MachineApplicable,
1110 if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1111 && adt_def.did() == result_did
1112 // Check that the error types are equal
1113 && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1115 return suggest_copied_or_cloned();
1116 } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1117 && adt_def.did() == option_did
1119 return suggest_copied_or_cloned();
1125 pub(crate) fn suggest_into(
1127 diag: &mut Diagnostic,
1128 expr: &hir::Expr<'_>,
1130 expected_ty: Ty<'tcx>,
1132 let expr = expr.peel_blocks();
1134 // We have better suggestions for scalar interconversions...
1135 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1139 // Don't suggest turning a block into another type (e.g. `{}.into()`)
1140 if matches!(expr.kind, hir::ExprKind::Block(..)) {
1144 // We'll later suggest `.as_ref` when noting the type error,
1145 // so skip if we will suggest that instead.
1146 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1150 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1151 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1153 self.misc(expr.span),
1155 ty::Binder::dummy(self.tcx.mk_trait_ref(
1157 [expr_ty, expected_ty]
1161 let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1162 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1164 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1166 diag.multipart_suggestion(
1167 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1169 Applicability::MaybeIncorrect
1177 /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1178 pub(crate) fn suggest_option_to_bool(
1180 diag: &mut Diagnostic,
1181 expr: &hir::Expr<'_>,
1183 expected_ty: Ty<'tcx>,
1185 if !expected_ty.is_bool() {
1189 let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; };
1190 if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1194 let hir = self.tcx.hir();
1195 let cond_parent = hir.parent_iter(expr.hir_id).find(|(_, node)| {
1196 !matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1199 // `let Some(_) = a.is_some() && b`
1201 // since the user probably just misunderstood how `let else`
1202 // and `&&` work together.
1203 if let Some((_, hir::Node::Local(local))) = cond_parent
1204 && let hir::PatKind::Path(qpath) | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1205 && let hir::QPath::Resolved(None, path) = qpath
1206 && let Some(did) = path.res.opt_def_id()
1207 .and_then(|did| self.tcx.opt_parent(did))
1208 .and_then(|did| self.tcx.opt_parent(did))
1209 && self.tcx.is_diagnostic_item(sym::Option, did)
1214 diag.span_suggestion(
1215 expr.span.shrink_to_hi(),
1216 "use `Option::is_some` to test if the `Option` has a value",
1218 Applicability::MachineApplicable,
1224 /// Suggest wrapping the block in square brackets instead of curly braces
1225 /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1226 pub(crate) fn suggest_block_to_brackets(
1228 diag: &mut Diagnostic,
1229 blk: &hir::Block<'_>,
1231 expected_ty: Ty<'tcx>,
1233 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1234 if self.can_coerce(blk_ty, *elem_ty)
1235 && blk.stmts.is_empty()
1236 && blk.rules == hir::BlockCheckMode::DefaultBlock
1238 let source_map = self.tcx.sess.source_map();
1239 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1240 if snippet.starts_with('{') && snippet.ends_with('}') {
1241 diag.multipart_suggestion_verbose(
1242 "to create an array, use square brackets instead of curly braces",
1247 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1253 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1257 Applicability::MachineApplicable,
1265 #[instrument(skip(self, err))]
1266 pub(crate) fn suggest_floating_point_literal(
1268 err: &mut Diagnostic,
1269 expr: &hir::Expr<'_>,
1270 expected_ty: Ty<'tcx>,
1272 if !expected_ty.is_floating_point() {
1276 ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [start, end], _) => {
1277 err.span_suggestion_verbose(
1278 start.span.shrink_to_hi().with_hi(end.span.lo()),
1279 "remove the unnecessary `.` operator for a floating point literal",
1281 Applicability::MaybeIncorrect,
1285 ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, ..), [start], _) => {
1286 err.span_suggestion_verbose(
1287 expr.span.with_lo(start.span.hi()),
1288 "remove the unnecessary `.` operator for a floating point literal",
1290 Applicability::MaybeIncorrect,
1294 ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, ..), [end], _) => {
1295 err.span_suggestion_verbose(
1296 expr.span.until(end.span),
1297 "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1299 Applicability::MaybeIncorrect,
1303 ExprKind::Lit(Spanned {
1304 node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed),
1307 let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) else { return false; };
1308 if !(snippet.starts_with("0x") || snippet.starts_with("0X")) {
1311 if snippet.len() <= 5 || !snippet.is_char_boundary(snippet.len() - 3) {
1314 let (_, suffix) = snippet.split_at(snippet.len() - 3);
1315 let value = match suffix {
1316 "f32" => (lit - 0xf32) / (16 * 16 * 16),
1317 "f64" => (lit - 0xf64) / (16 * 16 * 16),
1320 err.span_suggestions(
1322 "rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
1323 [format!("0x{value:X} as {suffix}"), format!("{value}_{suffix}")],
1324 Applicability::MaybeIncorrect,
1332 pub(crate) fn suggest_associated_const(
1334 err: &mut Diagnostic,
1335 expr: &hir::Expr<'_>,
1336 expected_ty: Ty<'tcx>,
1338 let Some((DefKind::AssocFn, old_def_id)) = self.typeck_results.borrow().type_dependent_def(expr.hir_id) else {
1341 let old_item_name = self.tcx.item_name(old_def_id);
1342 let capitalized_name = Symbol::intern(&old_item_name.as_str().to_uppercase());
1343 if old_item_name == capitalized_name {
1346 let (item, segment) = match expr.kind {
1347 hir::ExprKind::Path(QPath::Resolved(
1349 hir::Path { segments: [segment], .. },
1351 | hir::ExprKind::Path(QPath::TypeRelative(ty, segment)) => {
1352 let self_ty = self.astconv().ast_ty_to_ty(ty);
1353 if let Ok(pick) = self.probe_for_name(
1355 Ident::new(capitalized_name, segment.ident.span),
1360 ProbeScope::TraitsInScope,
1362 (pick.item, segment)
1367 hir::ExprKind::Path(QPath::Resolved(
1369 hir::Path { segments: [.., segment], .. },
1371 // we resolved through some path that doesn't end in the item name,
1372 // better not do a bad suggestion by accident.
1373 if old_item_name != segment.ident.name {
1376 if let Some(item) = self
1378 .associated_items(self.tcx.parent(old_def_id))
1379 .filter_by_name_unhygienic(capitalized_name)
1389 if item.def_id == old_def_id || self.tcx.def_kind(item.def_id) != DefKind::AssocConst {
1393 let item_ty = self.tcx.type_of(item.def_id);
1394 // FIXME(compiler-errors): This check is *so* rudimentary
1395 if item_ty.needs_subst() {
1398 if self.can_coerce(item_ty, expected_ty) {
1399 err.span_suggestion_verbose(
1401 format!("try referring to the associated const `{capitalized_name}` instead",),
1403 Applicability::MachineApplicable,
1411 fn is_loop(&self, id: hir::HirId) -> bool {
1412 let node = self.tcx.hir().get(id);
1413 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1416 fn is_local_statement(&self, id: hir::HirId) -> bool {
1417 let node = self.tcx.hir().get(id);
1418 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1421 /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1422 /// which is a side-effect of autoref.
1423 pub(crate) fn note_type_is_not_clone(
1425 diag: &mut Diagnostic,
1426 expected_ty: Ty<'tcx>,
1428 expr: &hir::Expr<'_>,
1430 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1431 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1432 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1433 let results = self.typeck_results.borrow();
1434 // First, look for a `Clone::clone` call
1435 if segment.ident.name == sym::clone
1436 && results.type_dependent_def_id(expr.hir_id).map_or(
1439 let assoc_item = self.tcx.associated_item(did);
1440 assoc_item.container == ty::AssocItemContainer::TraitContainer
1441 && assoc_item.container_id(self.tcx) == clone_trait_did
1444 // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1445 // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1446 && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1447 // Check that we're in fact trying to clone into the expected type
1448 && self.can_coerce(*pointee_ty, expected_ty)
1449 && let trait_ref = ty::Binder::dummy(self.tcx.mk_trait_ref(clone_trait_did, [expected_ty]))
1450 // And the expected type doesn't implement `Clone`
1451 && !self.predicate_must_hold_considering_regions(&traits::Obligation::new(
1453 traits::ObligationCause::dummy(),
1461 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1464 let owner = self.tcx.hir().enclosing_body_owner(expr.hir_id);
1465 if let ty::Param(param) = expected_ty.kind()
1466 && let Some(generics) = self.tcx.hir().get_generics(owner)
1468 suggest_constraining_type_params(
1472 vec![(param.name.as_str(), "Clone", Some(clone_trait_did))].into_iter(),
1475 self.suggest_derive(diag, &[(trait_ref.to_predicate(self.tcx), None, None)]);
1480 /// A common error is to add an extra semicolon:
1482 /// ```compile_fail,E0308
1483 /// fn foo() -> usize {
1488 /// This routine checks if the final statement in a block is an
1489 /// expression with an explicit semicolon whose type is compatible
1490 /// with `expected_ty`. If so, it suggests removing the semicolon.
1491 pub(crate) fn consider_removing_semicolon(
1493 blk: &'tcx hir::Block<'tcx>,
1494 expected_ty: Ty<'tcx>,
1495 err: &mut Diagnostic,
1497 if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1498 if let StatementAsExpression::NeedsBoxing = boxed {
1499 err.span_suggestion_verbose(
1501 "consider removing this semicolon and boxing the expression",
1503 Applicability::HasPlaceholders,
1506 err.span_suggestion_short(
1508 "remove this semicolon to return this value",
1510 Applicability::MachineApplicable,