2 use crate::astconv::AstConv;
3 use crate::errors::{AddReturnTypeSuggestion, ExpectedReturnTypeLabel};
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_infer::infer::{self, TyCtxtInferExt};
14 use rustc_infer::traits::{self, StatementAsExpression};
15 use rustc_middle::lint::in_external_macro;
16 use rustc_middle::ty::{self, Binder, IsSuggestable, ToPredicate, Ty};
17 use rustc_session::errors::ExprParenthesesNeeded;
18 use rustc_span::symbol::sym;
20 use rustc_trait_selection::infer::InferCtxtExt;
21 use rustc_trait_selection::traits::error_reporting::DefIdOrName;
22 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
24 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25 pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
26 err.span_suggestion_short(
28 "consider using a semicolon here",
30 Applicability::MachineApplicable,
34 /// On implicit return expressions with mismatched types, provides the following suggestions:
36 /// - Points out the method's return type as the reason for the expected type.
37 /// - Possible missing semicolon.
38 /// - Possible missing return type if the return type is the default, and not `fn main()`.
39 pub fn suggest_mismatched_types_on_tail(
42 expr: &'tcx hir::Expr<'tcx>,
47 let expr = expr.peel_drop_temps();
48 self.suggest_missing_semicolon(err, expr, expected, false);
49 let mut pointing_at_return_type = false;
50 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
51 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
52 pointing_at_return_type = self.suggest_missing_return_type(
60 self.suggest_missing_break_or_return_expr(
61 err, expr, &fn_decl, expected, found, blk_id, fn_id,
64 pointing_at_return_type
67 /// When encountering an fn-like type, try accessing the output of the type
68 /// and suggesting calling it if it satisfies a predicate (i.e. if the
69 /// output has a method or a field):
70 /// ```compile_fail,E0308
71 /// fn foo(x: usize) -> usize { x }
72 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
74 pub(crate) fn suggest_fn_call(
79 can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
81 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(expr, found)
82 else { return false; };
83 if can_satisfy(output) {
84 let (sugg_call, mut applicability) = match inputs.len() {
85 0 => ("".to_string(), Applicability::MachineApplicable),
90 if ty.is_suggestable(self.tcx, false) {
93 "/* value */".to_string()
98 Applicability::HasPlaceholders,
100 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
103 let msg = match def_id_or_name {
104 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
105 DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
106 DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
107 kind => format!("call this {}", kind.descr(def_id)),
109 DefIdOrName::Name(name) => format!("call this {name}"),
112 let sugg = match expr.kind {
113 hir::ExprKind::Call(..)
114 | hir::ExprKind::Path(..)
115 | hir::ExprKind::Index(..)
116 | hir::ExprKind::Lit(..) => {
117 vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
119 hir::ExprKind::Closure { .. } => {
120 // Might be `{ expr } || { bool }`
121 applicability = Applicability::MaybeIncorrect;
123 (expr.span.shrink_to_lo(), "(".to_string()),
124 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
129 (expr.span.shrink_to_lo(), "(".to_string()),
130 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
135 err.multipart_suggestion_verbose(
136 format!("use parentheses to {msg}"),
145 /// Extracts information about a callable type for diagnostics. This is a
146 /// heuristic -- it doesn't necessarily mean that a type is always callable,
147 /// because the callable type must also be well-formed to be called.
148 pub(in super::super) fn extract_callable_info(
152 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
153 // Autoderef is useful here because sometimes we box callables, etc.
154 let Some((def_id_or_name, output, inputs)) = self.autoderef(expr.span, found).silence_errors().find_map(|(found, _)| {
155 match *found.kind() {
157 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
158 ty::FnDef(def_id, _) => {
159 let fn_sig = found.fn_sig(self.tcx);
160 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
162 ty::Closure(def_id, substs) => {
163 let fn_sig = substs.as_closure().sig();
164 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
166 ty::Opaque(def_id, substs) => {
167 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
168 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
169 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
170 // args tuple will always be substs[1]
171 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
174 DefIdOrName::DefId(def_id),
175 pred.kind().rebind(proj.term.ty().unwrap()),
176 pred.kind().rebind(args.as_slice()),
183 ty::Dynamic(data, _, ty::Dyn) => {
184 data.iter().find_map(|pred| {
185 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
186 && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
187 // for existential projection, substs are shifted over by 1
188 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
191 DefIdOrName::Name("trait object"),
192 pred.rebind(proj.term.ty().unwrap()),
193 pred.rebind(args.as_slice()),
200 ty::Param(param) => {
201 let def_id = self.tcx.generics_of(self.body_id.owner).type_param(¶m, self.tcx).def_id;
202 self.tcx.predicates_of(self.body_id.owner).predicates.iter().find_map(|(pred, _)| {
203 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
204 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
205 && proj.projection_ty.self_ty() == found
206 // args tuple will always be substs[1]
207 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
210 DefIdOrName::DefId(def_id),
211 pred.kind().rebind(proj.term.ty().unwrap()),
212 pred.kind().rebind(args.as_slice()),
221 }) else { return None; };
223 let output = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, output);
228 self.replace_bound_vars_with_fresh_vars(
236 // We don't want to register any extra obligations, which should be
237 // implied by wf, but also because that would possibly result in
238 // erroneous errors later on.
239 let infer::InferOk { value: output, obligations: _ } =
240 self.normalize_associated_types_in_as_infer_ok(expr.span, output);
242 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
245 pub fn suggest_two_fn_call(
247 err: &mut Diagnostic,
248 lhs_expr: &'tcx hir::Expr<'tcx>,
250 rhs_expr: &'tcx hir::Expr<'tcx>,
252 can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
254 let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_expr, lhs_ty)
255 else { return false; };
256 let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_expr, rhs_ty)
257 else { return false; };
259 if can_satisfy(lhs_output_ty, rhs_output_ty) {
260 let mut sugg = vec![];
261 let mut applicability = Applicability::MachineApplicable;
263 for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
264 let (sugg_call, this_applicability) = match inputs.len() {
265 0 => ("".to_string(), Applicability::MachineApplicable),
270 if ty.is_suggestable(self.tcx, false) {
271 format!("/* {ty} */")
273 "/* value */".to_string()
278 Applicability::HasPlaceholders,
280 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
283 applicability = applicability.max(this_applicability);
286 hir::ExprKind::Call(..)
287 | hir::ExprKind::Path(..)
288 | hir::ExprKind::Index(..)
289 | hir::ExprKind::Lit(..) => {
290 sugg.extend([(expr.span.shrink_to_hi(), format!("({sugg_call})"))]);
292 hir::ExprKind::Closure { .. } => {
293 // Might be `{ expr } || { bool }`
294 applicability = Applicability::MaybeIncorrect;
296 (expr.span.shrink_to_lo(), "(".to_string()),
297 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
302 (expr.span.shrink_to_lo(), "(".to_string()),
303 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
309 err.multipart_suggestion_verbose(
310 format!("use parentheses to call these"),
321 pub fn suggest_deref_ref_or_into(
323 err: &mut Diagnostic,
324 expr: &hir::Expr<'tcx>,
327 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
329 let expr = expr.peel_blocks();
330 if let Some((sp, msg, suggestion, applicability, verbose)) =
331 self.check_ref(expr, found, expected)
334 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
336 err.span_suggestion(sp, &msg, suggestion, applicability);
339 } else if self.suggest_else_fn_with_closure(err, expr, found, expected)
342 } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected))
343 && let ty::FnDef(def_id, ..) = &found.kind()
344 && let Some(sp) = self.tcx.hir().span_if_local(*def_id)
346 err.span_label(sp, format!("{found} defined here"));
348 } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
351 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
352 if !methods.is_empty() {
353 let mut suggestions = methods.iter()
354 .filter_map(|conversion_method| {
355 let receiver_method_ident = expr.method_ident();
356 if let Some(method_ident) = receiver_method_ident
357 && method_ident.name == conversion_method.name
359 return None // do not suggest code that is already there (#53348)
362 let method_call_list = [sym::to_vec, sym::to_string];
363 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
364 && receiver_method.ident.name == sym::clone
365 && method_call_list.contains(&conversion_method.name)
366 // If receiver is `.clone()` and found type has one of those methods,
367 // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
368 // to an owned type (`Vec` or `String`). These conversions clone internally,
369 // so we remove the user's `clone` call.
372 receiver_method.ident.span,
373 conversion_method.name.to_string()
375 } else if expr.precedence().order()
376 < ExprPrecedence::MethodCall.order()
379 (expr.span.shrink_to_lo(), "(".to_string()),
380 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
383 vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
385 let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
386 if let Some(name) = struct_pat_shorthand_field {
389 (expr.span.shrink_to_lo(), format!("{}: ", name)),
395 if suggestions.peek().is_some() {
396 err.multipart_suggestions(
397 "try using a conversion method",
399 Applicability::MaybeIncorrect,
403 } else if let ty::Adt(found_adt, found_substs) = found.kind()
404 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
405 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
406 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
407 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
410 let ty = found_substs.type_at(0);
413 while let ty::Ref(_, inner, _) = peeled.kind() {
417 if let ty::Adt(adt, _) = peeled.kind()
418 && self.tcx.is_diagnostic_item(sym::String, adt.did())
420 err.span_suggestion_verbose(
421 expr.span.shrink_to_hi(),
422 "try converting the passed type into a `&str`",
423 format!(".map(|x| &*{}x)", "*".repeat(ref_cnt)),
424 Applicability::MaybeIncorrect,
434 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
435 /// in the heap by calling `Box::new()`.
436 pub(in super::super) fn suggest_boxing_when_appropriate(
438 err: &mut Diagnostic,
439 expr: &hir::Expr<'_>,
443 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
444 // Do not suggest `Box::new` in const context.
447 if !expected.is_box() || found.is_box() {
450 let boxed_found = self.tcx.mk_box(found);
451 if self.can_coerce(boxed_found, expected) {
452 err.multipart_suggestion(
453 "store this in the heap by calling `Box::new`",
455 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
456 (expr.span.shrink_to_hi(), ")".to_string()),
458 Applicability::MachineApplicable,
461 "for more on the distinction between the stack and the heap, read \
462 https://doc.rust-lang.org/book/ch15-01-box.html, \
463 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
464 https://doc.rust-lang.org/std/boxed/index.html",
472 /// When encountering a closure that captures variables, where a FnPtr is expected,
473 /// suggest a non-capturing closure
474 pub(in super::super) fn suggest_no_capture_closure(
476 err: &mut Diagnostic,
480 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
481 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
482 // Report upto four upvars being captured to reduce the amount error messages
483 // reported back to the user.
484 let spans_and_labels = upvars
487 .map(|(var_hir_id, upvar)| {
488 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
489 let msg = format!("`{}` captured here", var_name);
492 .collect::<Vec<_>>();
494 let mut multi_span: MultiSpan =
495 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
496 for (sp, label) in spans_and_labels {
497 multi_span.push_span_label(sp, label);
501 "closures can only be coerced to `fn` types if they do not capture any variables"
509 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
510 #[instrument(skip(self, err))]
511 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
513 err: &mut Diagnostic,
514 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 let pin_did = self.tcx.lang_items().pin_type();
525 // This guards the `unwrap` and `mk_box` below.
526 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
529 let box_found = self.tcx.mk_box(found);
530 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
531 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
532 match expected.kind() {
533 ty::Adt(def, _) if Some(def.did()) == pin_did => {
534 if self.can_coerce(pin_box_found, expected) {
535 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
537 ty::Adt(def, _) if def.is_box() => {
538 err.help("use `Box::pin`");
541 err.multipart_suggestion(
542 "you need to pin and box this expression",
544 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
545 (expr.span.shrink_to_hi(), ")".to_string()),
547 Applicability::MaybeIncorrect,
552 } else if self.can_coerce(pin_found, expected) {
554 ty::Adt(def, _) if def.is_box() => {
555 err.help("use `Box::pin`");
564 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
565 // Check if the parent expression is a call to Pin::new. If it
566 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
567 // can suggest Box::pin.
568 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
569 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
573 ExprKind::Path(QPath::TypeRelative(
575 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
579 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
582 "use `Box::pin` to pin and box this expression",
584 Applicability::MachineApplicable,
595 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
597 /// ```compile_fail,E0308
598 /// # fn bar_that_returns_u32() -> u32 { 4 }
600 /// bar_that_returns_u32()
604 /// This routine checks if the return expression in a block would make sense on its own as a
605 /// statement and the return type has been left as default or has been specified as `()`. If so,
606 /// it suggests adding a semicolon.
608 /// If the expression is the expression of a closure without block (`|| expr`), a
609 /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
610 pub fn suggest_missing_semicolon(
612 err: &mut Diagnostic,
613 expression: &'tcx hir::Expr<'tcx>,
617 if expected.is_unit() {
618 // `BlockTailExpression` only relevant if the tail expr would be
619 // useful on its own.
620 match expression.kind {
622 | ExprKind::MethodCall(..)
625 | ExprKind::Match(..)
626 | ExprKind::Block(..)
627 if expression.can_have_side_effects()
628 // If the expression is from an external macro, then do not suggest
629 // adding a semicolon, because there's nowhere to put it.
631 && !in_external_macro(self.tcx.sess, expression.span) =>
634 err.multipart_suggestion(
635 "consider using a semicolon here",
637 (expression.span.shrink_to_lo(), "{ ".to_owned()),
638 (expression.span.shrink_to_hi(), "; }".to_owned()),
640 Applicability::MachineApplicable,
644 expression.span.shrink_to_hi(),
645 "consider using a semicolon here",
647 Applicability::MachineApplicable,
656 /// A possible error is to forget to add a return type that is needed:
658 /// ```compile_fail,E0308
659 /// # fn bar_that_returns_u32() -> u32 { 4 }
661 /// bar_that_returns_u32()
665 /// This routine checks if the return type is left as default, the method is not part of an
666 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
668 pub(in super::super) fn suggest_missing_return_type(
670 err: &mut Diagnostic,
671 fn_decl: &hir::FnDecl<'_>,
678 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
679 // Only suggest changing the return type for methods that
680 // haven't set a return type at all (and aren't `fn main()` or an impl).
681 match &fn_decl.output {
682 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
683 // `fn main()` must return `()`, do not suggest changing return type
684 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
687 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
688 if found.is_suggestable(self.tcx, false) {
689 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
691 } else if let ty::Closure(_, substs) = found.kind()
692 // FIXME(compiler-errors): Get better at printing binders...
693 && let closure = substs.as_closure()
694 && closure.sig().is_suggestable(self.tcx, false)
696 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
699 // FIXME: if `found` could be `impl Iterator` we should suggest that.
700 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
704 &hir::FnRetTy::Return(ref ty) => {
705 // Only point to return type if the expected type is the return type, as if they
706 // are not, the expectation must have been caused by something else.
707 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
709 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
710 debug!("suggest_missing_return_type: return type {:?}", ty);
711 debug!("suggest_missing_return_type: expected type {:?}", ty);
712 let bound_vars = self.tcx.late_bound_vars(fn_id);
713 let ty = Binder::bind_with_vars(ty, bound_vars);
714 let ty = self.normalize_associated_types_in(span, ty);
715 let ty = self.tcx.erase_late_bound_regions(ty);
716 if self.can_coerce(expected, ty) {
717 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
718 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
727 /// check whether the return type is a generic type with a trait bound
728 /// only suggest this if the generic param is not present in the arguments
729 /// if this is true, hint them towards changing the return type to `impl Trait`
730 /// ```compile_fail,E0308
731 /// fn cant_name_it<T: Fn() -> u32>() -> T {
735 fn try_suggest_return_impl_trait(
737 err: &mut Diagnostic,
742 // Only apply the suggestion if:
743 // - the return type is a generic parameter
744 // - the generic param is not used as a fn param
745 // - the generic param has at least one bound
746 // - the generic param doesn't appear in any other bounds where it's not the Self type
748 // - Changing the return type to be `impl <all bounds>`
750 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
752 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
754 let fn_node = self.tcx.hir().find(fn_id);
756 let Some(hir::Node::Item(hir::Item {
759 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
760 hir::Generics { params, predicates, .. },
764 })) = fn_node else { return };
766 if params.get(expected_ty_as_param.index as usize).is_none() {
770 // get all where BoundPredicates here, because they are used in to cases below
771 let where_predicates = predicates
773 .filter_map(|p| match p {
774 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
779 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
780 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
785 .map(|(ty, bounds)| match ty.kind() {
786 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
787 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
788 _ => match ty.contains(expected) {
793 .collect::<Result<Vec<_>, _>>();
795 let Ok(where_predicates) = where_predicates else { return };
797 // now get all predicates in the same types as the where bounds, so we can chain them
798 let predicates_from_where =
799 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
801 // extract all bounds from the source code using their spans
802 let all_matching_bounds_strs = predicates_from_where
803 .filter_map(|bound| match bound {
804 GenericBound::Trait(_, _) => {
805 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
809 .collect::<Vec<String>>();
811 if all_matching_bounds_strs.len() == 0 {
815 let all_bounds_str = all_matching_bounds_strs.join(" + ");
817 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
818 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
819 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
822 if ty_param_used_in_fn_params {
828 "consider using an impl return type",
829 format!("impl {}", all_bounds_str),
830 Applicability::MaybeIncorrect,
834 pub(in super::super) fn suggest_missing_break_or_return_expr(
836 err: &mut Diagnostic,
837 expr: &'tcx hir::Expr<'tcx>,
838 fn_decl: &hir::FnDecl<'_>,
844 if !expected.is_unit() {
847 let found = self.resolve_vars_with_obligations(found);
849 let in_loop = self.is_loop(id)
850 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
852 let in_local_statement = self.is_local_statement(id)
857 .any(|(parent_id, _)| self.is_local_statement(parent_id));
859 if in_loop && in_local_statement {
860 err.multipart_suggestion(
861 "you might have meant to break the loop with this value",
863 (expr.span.shrink_to_lo(), "break ".to_string()),
864 (expr.span.shrink_to_hi(), ";".to_string()),
866 Applicability::MaybeIncorrect,
871 if let hir::FnRetTy::Return(ty) = fn_decl.output {
872 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
873 let bound_vars = self.tcx.late_bound_vars(fn_id);
874 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
875 let ty = self.normalize_associated_types_in(expr.span, ty);
876 let ty = match self.tcx.asyncness(fn_id.owner) {
877 hir::IsAsync::Async => {
878 let infcx = self.tcx.infer_ctxt().build();
880 .get_impl_future_output_ty(ty)
883 fn_decl.output.span(),
884 "failed to get output type of async function"
889 hir::IsAsync::NotAsync => ty,
891 if self.can_coerce(found, ty) {
892 err.multipart_suggestion(
893 "you might have meant to return this value",
895 (expr.span.shrink_to_lo(), "return ".to_string()),
896 (expr.span.shrink_to_hi(), ";".to_string()),
898 Applicability::MaybeIncorrect,
904 pub(in super::super) fn suggest_missing_parentheses(
906 err: &mut Diagnostic,
907 expr: &hir::Expr<'_>,
909 let sp = self.tcx.sess.source_map().start_point(expr.span);
910 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
911 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
912 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
919 /// Given an expression type mismatch, peel any `&` expressions until we get to
920 /// a block expression, and then suggest replacing the braces with square braces
921 /// if it was possibly mistaken array syntax.
922 pub(crate) fn suggest_block_to_brackets_peeling_refs(
924 diag: &mut Diagnostic,
925 mut expr: &hir::Expr<'_>,
926 mut expr_ty: Ty<'tcx>,
927 mut expected_ty: Ty<'tcx>,
930 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
932 hir::ExprKind::AddrOf(_, _, inner_expr),
933 ty::Ref(_, inner_expr_ty, _),
934 ty::Ref(_, inner_expected_ty, _),
937 expr_ty = *inner_expr_ty;
938 expected_ty = *inner_expected_ty;
940 (hir::ExprKind::Block(blk, _), _, _) => {
941 self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
949 pub(crate) fn suggest_copied_or_cloned(
951 diag: &mut Diagnostic,
952 expr: &hir::Expr<'_>,
954 expected_ty: Ty<'tcx>,
956 let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
957 let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
958 if adt_def != expected_adt_def {
962 let mut suggest_copied_or_cloned = || {
963 let expr_inner_ty = substs.type_at(0);
964 let expected_inner_ty = expected_substs.type_at(0);
965 if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
966 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
968 let def_path = self.tcx.def_path_str(adt_def.did());
969 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
970 diag.span_suggestion_verbose(
971 expr.span.shrink_to_hi(),
973 "use `{def_path}::copied` to copy the value inside the `{def_path}`"
976 Applicability::MachineApplicable,
979 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
980 && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
988 diag.span_suggestion_verbose(
989 expr.span.shrink_to_hi(),
991 "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
994 Applicability::MachineApplicable,
1002 if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1003 && adt_def.did() == result_did
1004 // Check that the error types are equal
1005 && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1007 return suggest_copied_or_cloned();
1008 } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1009 && adt_def.did() == option_did
1011 return suggest_copied_or_cloned();
1017 pub(crate) fn suggest_into(
1019 diag: &mut Diagnostic,
1020 expr: &hir::Expr<'_>,
1022 expected_ty: Ty<'tcx>,
1024 let expr = expr.peel_blocks();
1026 // We have better suggestions for scalar interconversions...
1027 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1031 // Don't suggest turning a block into another type (e.g. `{}.into()`)
1032 if matches!(expr.kind, hir::ExprKind::Block(..)) {
1036 // We'll later suggest `.as_ref` when noting the type error,
1037 // so skip if we will suggest that instead.
1038 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1042 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1043 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1044 self.misc(expr.span),
1046 ty::Binder::dummy(ty::TraitRef {
1047 def_id: into_def_id,
1048 substs: self.tcx.mk_substs_trait(expr_ty, &[expected_ty.into()]),
1050 .to_poly_trait_predicate()
1051 .to_predicate(self.tcx),
1054 let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1055 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1057 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1059 diag.multipart_suggestion(
1060 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1062 Applicability::MaybeIncorrect
1070 /// Suggest wrapping the block in square brackets instead of curly braces
1071 /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1072 pub(crate) fn suggest_block_to_brackets(
1074 diag: &mut Diagnostic,
1075 blk: &hir::Block<'_>,
1077 expected_ty: Ty<'tcx>,
1079 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1080 if self.can_coerce(blk_ty, *elem_ty)
1081 && blk.stmts.is_empty()
1082 && blk.rules == hir::BlockCheckMode::DefaultBlock
1084 let source_map = self.tcx.sess.source_map();
1085 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1086 if snippet.starts_with('{') && snippet.ends_with('}') {
1087 diag.multipart_suggestion_verbose(
1088 "to create an array, use square brackets instead of curly braces",
1093 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1099 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1103 Applicability::MachineApplicable,
1111 fn is_loop(&self, id: hir::HirId) -> bool {
1112 let node = self.tcx.hir().get(id);
1113 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1116 fn is_local_statement(&self, id: hir::HirId) -> bool {
1117 let node = self.tcx.hir().get(id);
1118 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1121 /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1122 /// which is a side-effect of autoref.
1123 pub(crate) fn note_type_is_not_clone(
1125 diag: &mut Diagnostic,
1126 expected_ty: Ty<'tcx>,
1128 expr: &hir::Expr<'_>,
1130 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1131 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1132 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1133 let results = self.typeck_results.borrow();
1134 // First, look for a `Clone::clone` call
1135 if segment.ident.name == sym::clone
1136 && results.type_dependent_def_id(expr.hir_id).map_or(
1139 let assoc_item = self.tcx.associated_item(did);
1140 assoc_item.container == ty::AssocItemContainer::TraitContainer
1141 && assoc_item.container_id(self.tcx) == clone_trait_did
1144 // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1145 // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1146 && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1147 // Check that we're in fact trying to clone into the expected type
1148 && self.can_coerce(*pointee_ty, expected_ty)
1149 // And the expected type doesn't implement `Clone`
1150 && !self.predicate_must_hold_considering_regions(&traits::Obligation {
1151 cause: traits::ObligationCause::dummy(),
1152 param_env: self.param_env,
1154 predicate: ty::Binder::dummy(ty::TraitRef {
1155 def_id: clone_trait_did,
1156 substs: self.tcx.mk_substs([expected_ty.into()].iter()),
1159 .to_predicate(self.tcx),
1165 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1171 /// A common error is to add an extra semicolon:
1173 /// ```compile_fail,E0308
1174 /// fn foo() -> usize {
1179 /// This routine checks if the final statement in a block is an
1180 /// expression with an explicit semicolon whose type is compatible
1181 /// with `expected_ty`. If so, it suggests removing the semicolon.
1182 pub(crate) fn consider_removing_semicolon(
1184 blk: &'tcx hir::Block<'tcx>,
1185 expected_ty: Ty<'tcx>,
1186 err: &mut Diagnostic,
1188 if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1189 if let StatementAsExpression::NeedsBoxing = boxed {
1190 err.span_suggestion_verbose(
1192 "consider removing this semicolon and boxing the expression",
1194 Applicability::HasPlaceholders,
1197 err.span_suggestion_short(
1199 "remove this semicolon to return this value",
1201 Applicability::MachineApplicable,