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::traits::{self, StatementAsExpression};
15 use rustc_middle::lint::in_external_macro;
16 use rustc_middle::ty::{
17 self, suggest_constraining_type_params, Binder, DefIdTree, IsSuggestable, ToPredicate, Ty,
20 use rustc_session::errors::ExprParenthesesNeeded;
21 use rustc_span::source_map::Spanned;
22 use rustc_span::symbol::{sym, Ident};
23 use rustc_span::{Span, Symbol};
24 use rustc_trait_selection::infer::InferCtxtExt;
25 use rustc_trait_selection::traits::error_reporting::suggestions::TypeErrCtxtExt;
26 use rustc_trait_selection::traits::error_reporting::DefIdOrName;
27 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
29 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30 pub(crate) fn body_fn_sig(&self) -> Option<ty::FnSig<'tcx>> {
34 .get(self.tcx.hir().local_def_id_to_hir_id(self.body_id))
38 pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
39 // This suggestion is incorrect for
40 // fn foo() -> bool { match () { () => true } || match () { () => true } }
41 err.span_suggestion_short(
43 "consider using a semicolon here",
45 Applicability::MaybeIncorrect,
49 /// On implicit return expressions with mismatched types, provides the following suggestions:
51 /// - Points out the method's return type as the reason for the expected type.
52 /// - Possible missing semicolon.
53 /// - Possible missing return type if the return type is the default, and not `fn main()`.
54 pub fn suggest_mismatched_types_on_tail(
57 expr: &'tcx hir::Expr<'tcx>,
62 let expr = expr.peel_drop_temps();
63 self.suggest_missing_semicolon(err, expr, expected, false);
64 let mut pointing_at_return_type = false;
65 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
66 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
67 pointing_at_return_type = self.suggest_missing_return_type(
75 self.suggest_missing_break_or_return_expr(
76 err, expr, &fn_decl, expected, found, blk_id, fn_id,
79 pointing_at_return_type
82 /// When encountering an fn-like type, try accessing the output of the type
83 /// and suggesting calling it if it satisfies a predicate (i.e. if the
84 /// output has a method or a field):
85 /// ```compile_fail,E0308
86 /// fn foo(x: usize) -> usize { x }
87 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
89 pub(crate) fn suggest_fn_call(
94 can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
96 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(found)
97 else { return false; };
98 if can_satisfy(output) {
99 let (sugg_call, mut applicability) = match inputs.len() {
100 0 => ("".to_string(), Applicability::MachineApplicable),
105 if ty.is_suggestable(self.tcx, false) {
106 format!("/* {ty} */")
108 "/* value */".to_string()
113 Applicability::HasPlaceholders,
115 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
118 let msg = match def_id_or_name {
119 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
120 DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
121 DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
122 kind => format!("call this {}", kind.descr(def_id)),
124 DefIdOrName::Name(name) => format!("call this {name}"),
127 let sugg = match expr.kind {
128 hir::ExprKind::Call(..)
129 | hir::ExprKind::Path(..)
130 | hir::ExprKind::Index(..)
131 | hir::ExprKind::Lit(..) => {
132 vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
134 hir::ExprKind::Closure { .. } => {
135 // Might be `{ expr } || { bool }`
136 applicability = Applicability::MaybeIncorrect;
138 (expr.span.shrink_to_lo(), "(".to_string()),
139 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
144 (expr.span.shrink_to_lo(), "(".to_string()),
145 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
150 err.multipart_suggestion_verbose(
151 format!("use parentheses to {msg}"),
160 /// Extracts information about a callable type for diagnostics. This is a
161 /// heuristic -- it doesn't necessarily mean that a type is always callable,
162 /// because the callable type must also be well-formed to be called.
163 pub(in super::super) fn extract_callable_info(
166 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
167 let body_hir_id = self.tcx.hir().local_def_id_to_hir_id(self.body_id);
168 self.err_ctxt().extract_callable_info(body_hir_id, self.param_env, ty)
171 pub fn suggest_two_fn_call(
173 err: &mut Diagnostic,
174 lhs_expr: &'tcx hir::Expr<'tcx>,
176 rhs_expr: &'tcx hir::Expr<'tcx>,
178 can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
180 let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_ty)
181 else { return false; };
182 let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_ty)
183 else { return false; };
185 if can_satisfy(lhs_output_ty, rhs_output_ty) {
186 let mut sugg = vec![];
187 let mut applicability = Applicability::MachineApplicable;
189 for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
190 let (sugg_call, this_applicability) = match inputs.len() {
191 0 => ("".to_string(), Applicability::MachineApplicable),
196 if ty.is_suggestable(self.tcx, false) {
197 format!("/* {ty} */")
199 "/* value */".to_string()
204 Applicability::HasPlaceholders,
206 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
209 applicability = applicability.max(this_applicability);
212 hir::ExprKind::Call(..)
213 | hir::ExprKind::Path(..)
214 | hir::ExprKind::Index(..)
215 | hir::ExprKind::Lit(..) => {
216 sugg.extend([(expr.span.shrink_to_hi(), format!("({sugg_call})"))]);
218 hir::ExprKind::Closure { .. } => {
219 // Might be `{ expr } || { bool }`
220 applicability = Applicability::MaybeIncorrect;
222 (expr.span.shrink_to_lo(), "(".to_string()),
223 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
228 (expr.span.shrink_to_lo(), "(".to_string()),
229 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
235 err.multipart_suggestion_verbose("use parentheses to call these", sugg, applicability);
243 pub fn suggest_remove_last_method_call(
245 err: &mut Diagnostic,
246 expr: &hir::Expr<'tcx>,
249 if let hir::ExprKind::MethodCall(hir::PathSegment { ident: method, .. }, recv_expr, &[], _) = expr.kind &&
250 let Some(recv_ty) = self.typeck_results.borrow().expr_ty_opt(recv_expr) &&
251 self.can_coerce(recv_ty, expected) {
252 let span = if let Some(recv_span) = recv_expr.span.find_ancestor_inside(expr.span) {
253 expr.span.with_lo(recv_span.hi())
255 expr.span.with_lo(method.span.lo() - rustc_span::BytePos(1))
257 err.span_suggestion_verbose(
259 "try removing the method call",
261 Applicability::MachineApplicable,
268 pub fn suggest_deref_ref_or_into(
270 err: &mut Diagnostic,
271 expr: &hir::Expr<'tcx>,
274 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
276 let expr = expr.peel_blocks();
277 if let Some((sp, msg, suggestion, applicability, verbose, annotation)) =
278 self.check_ref(expr, found, expected)
281 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
283 err.span_suggestion(sp, &msg, suggestion, applicability);
286 let suggest_annotation = match expr.peel_drop_temps().kind {
287 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, _) => mutbl.ref_prefix_str(),
290 let mut tuple_indexes = Vec::new();
291 let mut expr_id = expr.hir_id;
292 for (parent_id, node) in self.tcx.hir().parent_iter(expr.hir_id) {
294 Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
298 .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
304 Node::Local(local) => {
305 if let Some(mut ty) = local.ty {
306 while let Some(index) = tuple_indexes.pop() {
308 TyKind::Tup(tys) => ty = &tys[index],
312 let annotation_span = ty.span;
314 annotation_span.with_hi(annotation_span.lo()),
315 "alternatively, consider changing the type annotation",
317 Applicability::MaybeIncorrect,
327 } else if self.suggest_else_fn_with_closure(err, expr, found, expected) {
329 } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected))
330 && let ty::FnDef(def_id, ..) = *found.kind()
331 && let Some(sp) = self.tcx.hir().span_if_local(def_id)
333 let name = self.tcx.item_name(def_id);
334 let kind = self.tcx.def_kind(def_id);
335 if let DefKind::Ctor(of, CtorKind::Fn) = kind {
336 err.span_label(sp, format!("`{name}` defines {} constructor here, which should be called", match of {
337 CtorOf::Struct => "a struct",
338 CtorOf::Variant => "an enum variant",
341 let descr = kind.descr(def_id);
342 err.span_label(sp, format!("{descr} `{name}` defined here"));
345 } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
348 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
349 if !methods.is_empty() {
350 let mut suggestions = methods.iter()
351 .filter_map(|conversion_method| {
352 let receiver_method_ident = expr.method_ident();
353 if let Some(method_ident) = receiver_method_ident
354 && method_ident.name == conversion_method.name
356 return None // do not suggest code that is already there (#53348)
359 let method_call_list = [sym::to_vec, sym::to_string];
360 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
361 && receiver_method.ident.name == sym::clone
362 && method_call_list.contains(&conversion_method.name)
363 // If receiver is `.clone()` and found type has one of those methods,
364 // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
365 // to an owned type (`Vec` or `String`). These conversions clone internally,
366 // so we remove the user's `clone` call.
369 receiver_method.ident.span,
370 conversion_method.name.to_string()
372 } else if expr.precedence().order()
373 < ExprPrecedence::MethodCall.order()
376 (expr.span.shrink_to_lo(), "(".to_string()),
377 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
380 vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
382 let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
383 if let Some(name) = struct_pat_shorthand_field {
386 (expr.span.shrink_to_lo(), format!("{}: ", name)),
392 if suggestions.peek().is_some() {
393 err.multipart_suggestions(
394 "try using a conversion method",
396 Applicability::MaybeIncorrect,
400 } else if let ty::Adt(found_adt, found_substs) = found.kind()
401 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
402 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
403 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
404 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
407 let ty = found_substs.type_at(0);
410 while let ty::Ref(_, inner, _) = peeled.kind() {
414 if let ty::Adt(adt, _) = peeled.kind()
415 && Some(adt.did()) == self.tcx.lang_items().string()
417 err.span_suggestion_verbose(
418 expr.span.shrink_to_hi(),
419 "try converting the passed type into a `&str`",
420 format!(".map(|x| &*{}x)", "*".repeat(ref_cnt)),
421 Applicability::MaybeIncorrect,
431 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
432 /// in the heap by calling `Box::new()`.
433 pub(in super::super) fn suggest_boxing_when_appropriate(
435 err: &mut Diagnostic,
436 expr: &hir::Expr<'_>,
440 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
441 // Do not suggest `Box::new` in const context.
444 if !expected.is_box() || found.is_box() {
447 let boxed_found = self.tcx.mk_box(found);
448 if self.can_coerce(boxed_found, expected) {
449 err.multipart_suggestion(
450 "store this in the heap by calling `Box::new`",
452 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
453 (expr.span.shrink_to_hi(), ")".to_string()),
455 Applicability::MachineApplicable,
458 "for more on the distinction between the stack and the heap, read \
459 https://doc.rust-lang.org/book/ch15-01-box.html, \
460 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
461 https://doc.rust-lang.org/std/boxed/index.html",
469 /// When encountering a closure that captures variables, where a FnPtr is expected,
470 /// suggest a non-capturing closure
471 pub(in super::super) fn suggest_no_capture_closure(
473 err: &mut Diagnostic,
477 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
478 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
479 // Report upto four upvars being captured to reduce the amount error messages
480 // reported back to the user.
481 let spans_and_labels = upvars
484 .map(|(var_hir_id, upvar)| {
485 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
486 let msg = format!("`{}` captured here", var_name);
489 .collect::<Vec<_>>();
491 let mut multi_span: MultiSpan =
492 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
493 for (sp, label) in spans_and_labels {
494 multi_span.push_span_label(sp, label);
498 "closures can only be coerced to `fn` types if they do not capture any variables"
506 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
507 #[instrument(skip(self, err))]
508 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
510 err: &mut Diagnostic,
511 expr: &hir::Expr<'_>,
517 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
518 // Do not suggest `Box::new` in const context.
521 let pin_did = self.tcx.lang_items().pin_type();
522 // This guards the `unwrap` and `mk_box` below.
523 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
526 let box_found = self.tcx.mk_box(found);
527 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
528 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
529 match expected.kind() {
530 ty::Adt(def, _) if Some(def.did()) == pin_did => {
531 if self.can_coerce(pin_box_found, expected) {
532 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
534 ty::Adt(def, _) if def.is_box() => {
535 err.help("use `Box::pin`");
538 err.multipart_suggestion(
539 "you need to pin and box this expression",
541 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
542 (expr.span.shrink_to_hi(), ")".to_string()),
544 Applicability::MaybeIncorrect,
549 } else if self.can_coerce(pin_found, expected) {
551 ty::Adt(def, _) if def.is_box() => {
552 err.help("use `Box::pin`");
561 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
562 // Check if the parent expression is a call to Pin::new. If it
563 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
564 // can suggest Box::pin.
565 let parent = self.tcx.hir().parent_id(expr.hir_id);
566 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
570 ExprKind::Path(QPath::TypeRelative(
572 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
576 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
579 "use `Box::pin` to pin and box this expression",
581 Applicability::MachineApplicable,
592 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
594 /// ```compile_fail,E0308
595 /// # fn bar_that_returns_u32() -> u32 { 4 }
597 /// bar_that_returns_u32()
601 /// This routine checks if the return expression in a block would make sense on its own as a
602 /// statement and the return type has been left as default or has been specified as `()`. If so,
603 /// it suggests adding a semicolon.
605 /// If the expression is the expression of a closure without block (`|| expr`), a
606 /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
607 pub fn suggest_missing_semicolon(
609 err: &mut Diagnostic,
610 expression: &'tcx hir::Expr<'tcx>,
614 if expected.is_unit() {
615 // `BlockTailExpression` only relevant if the tail expr would be
616 // useful on its own.
617 match expression.kind {
619 | ExprKind::MethodCall(..)
622 | ExprKind::Match(..)
623 | ExprKind::Block(..)
624 if expression.can_have_side_effects()
625 // If the expression is from an external macro, then do not suggest
626 // adding a semicolon, because there's nowhere to put it.
628 && !in_external_macro(self.tcx.sess, expression.span) =>
631 err.multipart_suggestion(
632 "consider using a semicolon here",
634 (expression.span.shrink_to_lo(), "{ ".to_owned()),
635 (expression.span.shrink_to_hi(), "; }".to_owned()),
637 Applicability::MachineApplicable,
641 expression.span.shrink_to_hi(),
642 "consider using a semicolon here",
644 Applicability::MachineApplicable,
653 /// A possible error is to forget to add a return type that is needed:
655 /// ```compile_fail,E0308
656 /// # fn bar_that_returns_u32() -> u32 { 4 }
658 /// bar_that_returns_u32()
662 /// This routine checks if the return type is left as default, the method is not part of an
663 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
665 pub(in super::super) fn suggest_missing_return_type(
667 err: &mut Diagnostic,
668 fn_decl: &hir::FnDecl<'_>,
675 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
676 // Only suggest changing the return type for methods that
677 // haven't set a return type at all (and aren't `fn main()` or an impl).
678 match &fn_decl.output {
679 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
680 // `fn main()` must return `()`, do not suggest changing return type
681 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
684 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
685 if found.is_suggestable(self.tcx, false) {
686 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
688 } else if let ty::Closure(_, substs) = found.kind()
689 // FIXME(compiler-errors): Get better at printing binders...
690 && let closure = substs.as_closure()
691 && closure.sig().is_suggestable(self.tcx, false)
693 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
696 // FIXME: if `found` could be `impl Iterator` we should suggest that.
697 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
701 hir::FnRetTy::Return(ty) => {
702 // Only point to return type if the expected type is the return type, as if they
703 // are not, the expectation must have been caused by something else.
704 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
706 let ty = self.astconv().ast_ty_to_ty(ty);
707 debug!("suggest_missing_return_type: return type {:?}", ty);
708 debug!("suggest_missing_return_type: expected type {:?}", ty);
709 let bound_vars = self.tcx.late_bound_vars(fn_id);
710 let ty = Binder::bind_with_vars(ty, bound_vars);
711 let ty = self.normalize(span, ty);
712 let ty = self.tcx.erase_late_bound_regions(ty);
713 if self.can_coerce(expected, ty) {
714 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
715 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
724 /// check whether the return type is a generic type with a trait bound
725 /// only suggest this if the generic param is not present in the arguments
726 /// if this is true, hint them towards changing the return type to `impl Trait`
727 /// ```compile_fail,E0308
728 /// fn cant_name_it<T: Fn() -> u32>() -> T {
732 fn try_suggest_return_impl_trait(
734 err: &mut Diagnostic,
739 // Only apply the suggestion if:
740 // - the return type is a generic parameter
741 // - the generic param is not used as a fn param
742 // - the generic param has at least one bound
743 // - the generic param doesn't appear in any other bounds where it's not the Self type
745 // - Changing the return type to be `impl <all bounds>`
747 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
749 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
751 let fn_node = self.tcx.hir().find(fn_id);
753 let Some(hir::Node::Item(hir::Item {
756 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
757 hir::Generics { params, predicates, .. },
761 })) = fn_node else { return };
763 if params.get(expected_ty_as_param.index as usize).is_none() {
767 // get all where BoundPredicates here, because they are used in to cases below
768 let where_predicates = predicates
770 .filter_map(|p| match p {
771 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
776 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
777 let ty = self.astconv().ast_ty_to_ty(bounded_ty);
782 .map(|(ty, bounds)| match ty.kind() {
783 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
784 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
785 _ => match ty.contains(expected) {
790 .collect::<Result<Vec<_>, _>>();
792 let Ok(where_predicates) = where_predicates else { return };
794 // now get all predicates in the same types as the where bounds, so we can chain them
795 let predicates_from_where =
796 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
798 // extract all bounds from the source code using their spans
799 let all_matching_bounds_strs = predicates_from_where
800 .filter_map(|bound| match bound {
801 GenericBound::Trait(_, _) => {
802 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
806 .collect::<Vec<String>>();
808 if all_matching_bounds_strs.len() == 0 {
812 let all_bounds_str = all_matching_bounds_strs.join(" + ");
814 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
815 let ty = self.astconv().ast_ty_to_ty( param);
816 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
819 if ty_param_used_in_fn_params {
825 "consider using an impl return type",
826 format!("impl {}", all_bounds_str),
827 Applicability::MaybeIncorrect,
831 pub(in super::super) fn suggest_missing_break_or_return_expr(
833 err: &mut Diagnostic,
834 expr: &'tcx hir::Expr<'tcx>,
835 fn_decl: &hir::FnDecl<'_>,
841 if !expected.is_unit() {
844 let found = self.resolve_vars_with_obligations(found);
846 let in_loop = self.is_loop(id)
847 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
849 let in_local_statement = self.is_local_statement(id)
854 .any(|(parent_id, _)| self.is_local_statement(parent_id));
856 if in_loop && in_local_statement {
857 err.multipart_suggestion(
858 "you might have meant to break the loop with this value",
860 (expr.span.shrink_to_lo(), "break ".to_string()),
861 (expr.span.shrink_to_hi(), ";".to_string()),
863 Applicability::MaybeIncorrect,
868 if let hir::FnRetTy::Return(ty) = fn_decl.output {
869 let ty = self.astconv().ast_ty_to_ty(ty);
870 let bound_vars = self.tcx.late_bound_vars(fn_id);
871 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
872 let ty = match self.tcx.asyncness(fn_id.owner) {
873 hir::IsAsync::Async => self.get_impl_future_output_ty(ty).unwrap_or_else(|| {
874 span_bug!(fn_decl.output.span(), "failed to get output type of async function")
876 hir::IsAsync::NotAsync => ty,
878 let ty = self.normalize(expr.span, ty);
879 if self.can_coerce(found, ty) {
880 err.multipart_suggestion(
881 "you might have meant to return this value",
883 (expr.span.shrink_to_lo(), "return ".to_string()),
884 (expr.span.shrink_to_hi(), ";".to_string()),
886 Applicability::MaybeIncorrect,
892 pub(in super::super) fn suggest_missing_parentheses(
894 err: &mut Diagnostic,
895 expr: &hir::Expr<'_>,
897 let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
898 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
899 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
900 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
907 /// Given an expression type mismatch, peel any `&` expressions until we get to
908 /// a block expression, and then suggest replacing the braces with square braces
909 /// if it was possibly mistaken array syntax.
910 pub(crate) fn suggest_block_to_brackets_peeling_refs(
912 diag: &mut Diagnostic,
913 mut expr: &hir::Expr<'_>,
914 mut expr_ty: Ty<'tcx>,
915 mut expected_ty: Ty<'tcx>,
918 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
920 hir::ExprKind::AddrOf(_, _, inner_expr),
921 ty::Ref(_, inner_expr_ty, _),
922 ty::Ref(_, inner_expected_ty, _),
925 expr_ty = *inner_expr_ty;
926 expected_ty = *inner_expected_ty;
928 (hir::ExprKind::Block(blk, _), _, _) => {
929 self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
937 pub(crate) fn suggest_clone_for_ref(
939 diag: &mut Diagnostic,
940 expr: &hir::Expr<'_>,
942 expected_ty: Ty<'tcx>,
944 if let ty::Ref(_, inner_ty, hir::Mutability::Not) = expr_ty.kind()
945 && let Some(clone_trait_def) = self.tcx.lang_items().clone_trait()
946 && expected_ty == *inner_ty
949 .type_implements_trait(
951 [self.tcx.erase_regions(expected_ty)],
954 .must_apply_modulo_regions()
956 diag.span_suggestion_verbose(
957 expr.span.shrink_to_hi(),
958 "consider using clone here",
960 Applicability::MachineApplicable,
967 pub(crate) fn suggest_copied_or_cloned(
969 diag: &mut Diagnostic,
970 expr: &hir::Expr<'_>,
972 expected_ty: Ty<'tcx>,
974 let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
975 let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
976 if adt_def != expected_adt_def {
980 let mut suggest_copied_or_cloned = || {
981 let expr_inner_ty = substs.type_at(0);
982 let expected_inner_ty = expected_substs.type_at(0);
983 if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
984 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
986 let def_path = self.tcx.def_path_str(adt_def.did());
987 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
988 diag.span_suggestion_verbose(
989 expr.span.shrink_to_hi(),
991 "use `{def_path}::copied` to copy the value inside the `{def_path}`"
994 Applicability::MachineApplicable,
997 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
998 && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1006 diag.span_suggestion_verbose(
1007 expr.span.shrink_to_hi(),
1009 "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
1012 Applicability::MachineApplicable,
1020 if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1021 && adt_def.did() == result_did
1022 // Check that the error types are equal
1023 && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1025 return suggest_copied_or_cloned();
1026 } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1027 && adt_def.did() == option_did
1029 return suggest_copied_or_cloned();
1035 pub(crate) fn suggest_into(
1037 diag: &mut Diagnostic,
1038 expr: &hir::Expr<'_>,
1040 expected_ty: Ty<'tcx>,
1042 let expr = expr.peel_blocks();
1044 // We have better suggestions for scalar interconversions...
1045 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1049 // Don't suggest turning a block into another type (e.g. `{}.into()`)
1050 if matches!(expr.kind, hir::ExprKind::Block(..)) {
1054 // We'll later suggest `.as_ref` when noting the type error,
1055 // so skip if we will suggest that instead.
1056 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1060 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1061 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1063 self.misc(expr.span),
1065 ty::Binder::dummy(self.tcx.mk_trait_ref(
1067 [expr_ty, expected_ty]
1071 let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1072 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1074 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1076 diag.multipart_suggestion(
1077 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1079 Applicability::MaybeIncorrect
1087 /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1088 pub(crate) fn suggest_option_to_bool(
1090 diag: &mut Diagnostic,
1091 expr: &hir::Expr<'_>,
1093 expected_ty: Ty<'tcx>,
1095 if !expected_ty.is_bool() {
1099 let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; };
1100 if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1104 let hir = self.tcx.hir();
1105 let cond_parent = hir.parent_iter(expr.hir_id).find(|(_, node)| {
1106 !matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1109 // `let Some(_) = a.is_some() && b`
1111 // since the user probably just misunderstood how `let else`
1112 // and `&&` work together.
1113 if let Some((_, hir::Node::Local(local))) = cond_parent
1114 && let hir::PatKind::Path(qpath) | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1115 && let hir::QPath::Resolved(None, path) = qpath
1116 && let Some(did) = path.res.opt_def_id()
1117 .and_then(|did| self.tcx.opt_parent(did))
1118 .and_then(|did| self.tcx.opt_parent(did))
1119 && self.tcx.is_diagnostic_item(sym::Option, did)
1124 diag.span_suggestion(
1125 expr.span.shrink_to_hi(),
1126 "use `Option::is_some` to test if the `Option` has a value",
1128 Applicability::MachineApplicable,
1134 /// Suggest wrapping the block in square brackets instead of curly braces
1135 /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1136 pub(crate) fn suggest_block_to_brackets(
1138 diag: &mut Diagnostic,
1139 blk: &hir::Block<'_>,
1141 expected_ty: Ty<'tcx>,
1143 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1144 if self.can_coerce(blk_ty, *elem_ty)
1145 && blk.stmts.is_empty()
1146 && blk.rules == hir::BlockCheckMode::DefaultBlock
1148 let source_map = self.tcx.sess.source_map();
1149 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1150 if snippet.starts_with('{') && snippet.ends_with('}') {
1151 diag.multipart_suggestion_verbose(
1152 "to create an array, use square brackets instead of curly braces",
1157 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1163 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1167 Applicability::MachineApplicable,
1175 #[instrument(skip(self, err))]
1176 pub(crate) fn suggest_floating_point_literal(
1178 err: &mut Diagnostic,
1179 expr: &hir::Expr<'_>,
1180 expected_ty: Ty<'tcx>,
1182 if !expected_ty.is_floating_point() {
1186 ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [start, end], _) => {
1187 err.span_suggestion_verbose(
1188 start.span.shrink_to_hi().with_hi(end.span.lo()),
1189 "remove the unnecessary `.` operator for a floating point literal",
1191 Applicability::MaybeIncorrect,
1195 ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, ..), [start], _) => {
1196 err.span_suggestion_verbose(
1197 expr.span.with_lo(start.span.hi()),
1198 "remove the unnecessary `.` operator for a floating point literal",
1200 Applicability::MaybeIncorrect,
1204 ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, ..), [end], _) => {
1205 err.span_suggestion_verbose(
1206 expr.span.until(end.span),
1207 "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1209 Applicability::MaybeIncorrect,
1213 ExprKind::Lit(Spanned {
1214 node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed),
1217 let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) else { return false; };
1218 if !(snippet.starts_with("0x") || snippet.starts_with("0X")) {
1221 if snippet.len() <= 5 || !snippet.is_char_boundary(snippet.len() - 3) {
1224 let (_, suffix) = snippet.split_at(snippet.len() - 3);
1225 let value = match suffix {
1226 "f32" => (lit - 0xf32) / (16 * 16 * 16),
1227 "f64" => (lit - 0xf64) / (16 * 16 * 16),
1230 err.span_suggestions(
1232 "rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
1233 [format!("0x{value:X} as {suffix}"), format!("{value}_{suffix}")],
1234 Applicability::MaybeIncorrect,
1242 pub(crate) fn suggest_associated_const(
1244 err: &mut Diagnostic,
1245 expr: &hir::Expr<'_>,
1246 expected_ty: Ty<'tcx>,
1248 let Some((DefKind::AssocFn, old_def_id)) = self.typeck_results.borrow().type_dependent_def(expr.hir_id) else {
1251 let old_item_name = self.tcx.item_name(old_def_id);
1252 let capitalized_name = Symbol::intern(&old_item_name.as_str().to_uppercase());
1253 if old_item_name == capitalized_name {
1256 let (item, segment) = match expr.kind {
1257 hir::ExprKind::Path(QPath::Resolved(
1259 hir::Path { segments: [segment], .. },
1261 | hir::ExprKind::Path(QPath::TypeRelative(ty, segment)) => {
1262 let self_ty = self.astconv().ast_ty_to_ty(ty);
1263 if let Ok(pick) = self.probe_for_name(
1265 Ident::new(capitalized_name, segment.ident.span),
1270 ProbeScope::TraitsInScope,
1272 (pick.item, segment)
1277 hir::ExprKind::Path(QPath::Resolved(
1279 hir::Path { segments: [.., segment], .. },
1281 // we resolved through some path that doesn't end in the item name,
1282 // better not do a bad suggestion by accident.
1283 if old_item_name != segment.ident.name {
1286 if let Some(item) = self
1288 .associated_items(self.tcx.parent(old_def_id))
1289 .filter_by_name_unhygienic(capitalized_name)
1299 if item.def_id == old_def_id || self.tcx.def_kind(item.def_id) != DefKind::AssocConst {
1303 let item_ty = self.tcx.type_of(item.def_id);
1304 // FIXME(compiler-errors): This check is *so* rudimentary
1305 if item_ty.needs_subst() {
1308 if self.can_coerce(item_ty, expected_ty) {
1309 err.span_suggestion_verbose(
1311 format!("try referring to the associated const `{capitalized_name}` instead",),
1313 Applicability::MachineApplicable,
1321 fn is_loop(&self, id: hir::HirId) -> bool {
1322 let node = self.tcx.hir().get(id);
1323 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1326 fn is_local_statement(&self, id: hir::HirId) -> bool {
1327 let node = self.tcx.hir().get(id);
1328 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1331 /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1332 /// which is a side-effect of autoref.
1333 pub(crate) fn note_type_is_not_clone(
1335 diag: &mut Diagnostic,
1336 expected_ty: Ty<'tcx>,
1338 expr: &hir::Expr<'_>,
1340 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1341 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1342 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1343 let results = self.typeck_results.borrow();
1344 // First, look for a `Clone::clone` call
1345 if segment.ident.name == sym::clone
1346 && results.type_dependent_def_id(expr.hir_id).map_or(
1349 let assoc_item = self.tcx.associated_item(did);
1350 assoc_item.container == ty::AssocItemContainer::TraitContainer
1351 && assoc_item.container_id(self.tcx) == clone_trait_did
1354 // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1355 // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1356 && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1357 // Check that we're in fact trying to clone into the expected type
1358 && self.can_coerce(*pointee_ty, expected_ty)
1359 && let trait_ref = ty::Binder::dummy(self.tcx.mk_trait_ref(clone_trait_did, [expected_ty]))
1360 // And the expected type doesn't implement `Clone`
1361 && !self.predicate_must_hold_considering_regions(&traits::Obligation::new(
1363 traits::ObligationCause::dummy(),
1371 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1374 let owner = self.tcx.hir().enclosing_body_owner(expr.hir_id);
1375 if let ty::Param(param) = expected_ty.kind()
1376 && let Some(generics) = self.tcx.hir().get_generics(owner)
1378 suggest_constraining_type_params(
1382 vec![(param.name.as_str(), "Clone", Some(clone_trait_did))].into_iter(),
1385 self.suggest_derive(diag, &[(trait_ref.to_predicate(self.tcx), None, None)]);
1390 /// A common error is to add an extra semicolon:
1392 /// ```compile_fail,E0308
1393 /// fn foo() -> usize {
1398 /// This routine checks if the final statement in a block is an
1399 /// expression with an explicit semicolon whose type is compatible
1400 /// with `expected_ty`. If so, it suggests removing the semicolon.
1401 pub(crate) fn consider_removing_semicolon(
1403 blk: &'tcx hir::Block<'tcx>,
1404 expected_ty: Ty<'tcx>,
1405 err: &mut Diagnostic,
1407 if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1408 if let StatementAsExpression::NeedsBoxing = boxed {
1409 err.span_suggestion_verbose(
1411 "consider removing this semicolon and boxing the expression",
1413 Applicability::HasPlaceholders,
1416 err.span_suggestion_short(
1418 "remove this semicolon to return this value",
1420 Applicability::MachineApplicable,