]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs
ecb0004c334340cc458d8463b98bb5e892b6e8bc
[rust.git] / compiler / rustc_typeck / src / check / fn_ctxt / suggestions.rs
1 use super::FnCtxt;
2 use crate::astconv::AstConv;
3 use crate::errors::{AddReturnTypeSuggestion, ExpectedReturnTypeLabel};
4
5 use rustc_ast::util::parser::ExprPrecedence;
6 use rustc_errors::{Applicability, Diagnostic, MultiSpan};
7 use rustc_hir as hir;
8 use rustc_hir::def::{CtorOf, DefKind};
9 use rustc_hir::lang_items::LangItem;
10 use rustc_hir::{
11     Expr, ExprKind, GenericBound, ItemKind, Node, Path, QPath, Stmt, StmtKind, TyKind,
12     WherePredicate,
13 };
14 use rustc_infer::infer::{self, TyCtxtInferExt};
15 use rustc_infer::traits;
16 use rustc_middle::lint::in_external_macro;
17 use rustc_middle::ty::subst::GenericArgKind;
18 use rustc_middle::ty::{self, Binder, ToPredicate, Ty};
19 use rustc_span::symbol::{kw, sym};
20 use rustc_span::Span;
21 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
22
23 use std::iter;
24
25 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
26     pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
27         err.span_suggestion_short(
28             span.shrink_to_hi(),
29             "consider using a semicolon here",
30             ";".to_string(),
31             Applicability::MachineApplicable,
32         );
33     }
34
35     /// On implicit return expressions with mismatched types, provides the following suggestions:
36     ///
37     /// - Points out the method's return type as the reason for the expected type.
38     /// - Possible missing semicolon.
39     /// - Possible missing return type if the return type is the default, and not `fn main()`.
40     pub fn suggest_mismatched_types_on_tail(
41         &self,
42         err: &mut Diagnostic,
43         expr: &'tcx hir::Expr<'tcx>,
44         expected: Ty<'tcx>,
45         found: Ty<'tcx>,
46         blk_id: hir::HirId,
47     ) -> bool {
48         let expr = expr.peel_drop_temps();
49         // If the expression is from an external macro, then do not suggest
50         // adding a semicolon, because there's nowhere to put it.
51         // See issue #81943.
52         if expr.can_have_side_effects() && !in_external_macro(self.tcx.sess, expr.span) {
53             self.suggest_missing_semicolon(err, expr, expected);
54         }
55         let mut pointing_at_return_type = false;
56         if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
57             let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
58             pointing_at_return_type = self.suggest_missing_return_type(
59                 err,
60                 &fn_decl,
61                 expected,
62                 found,
63                 can_suggest,
64                 fn_id,
65             );
66             self.suggest_missing_break_or_return_expr(
67                 err, expr, &fn_decl, expected, found, blk_id, fn_id,
68             );
69         }
70         pointing_at_return_type
71     }
72
73     /// When encountering an fn-like ctor that needs to unify with a value, check whether calling
74     /// the ctor would successfully solve the type mismatch and if so, suggest it:
75     /// ```compile_fail,E0308
76     /// fn foo(x: usize) -> usize { x }
77     /// let x: usize = foo;  // suggest calling the `foo` function: `foo(42)`
78     /// ```
79     fn suggest_fn_call(
80         &self,
81         err: &mut Diagnostic,
82         expr: &hir::Expr<'_>,
83         expected: Ty<'tcx>,
84         found: Ty<'tcx>,
85     ) -> bool {
86         let hir = self.tcx.hir();
87         let (def_id, sig) = match *found.kind() {
88             ty::FnDef(def_id, _) => (def_id, found.fn_sig(self.tcx)),
89             ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig()),
90             _ => return false,
91         };
92
93         let sig = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, sig).0;
94         let sig = self.normalize_associated_types_in(expr.span, sig);
95         if self.can_coerce(sig.output(), expected) {
96             let (mut sugg_call, applicability) = if sig.inputs().is_empty() {
97                 (String::new(), Applicability::MachineApplicable)
98             } else {
99                 ("...".to_string(), Applicability::HasPlaceholders)
100             };
101             let mut msg = "call this function";
102             match hir.get_if_local(def_id) {
103                 Some(
104                     Node::Item(hir::Item { kind: ItemKind::Fn(.., body_id), .. })
105                     | Node::ImplItem(hir::ImplItem {
106                         kind: hir::ImplItemKind::Fn(_, body_id), ..
107                     })
108                     | Node::TraitItem(hir::TraitItem {
109                         kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Provided(body_id)),
110                         ..
111                     }),
112                 ) => {
113                     let body = hir.body(*body_id);
114                     sugg_call = body
115                         .params
116                         .iter()
117                         .map(|param| match &param.pat.kind {
118                             hir::PatKind::Binding(_, _, ident, None)
119                                 if ident.name != kw::SelfLower =>
120                             {
121                                 ident.to_string()
122                             }
123                             _ => "_".to_string(),
124                         })
125                         .collect::<Vec<_>>()
126                         .join(", ");
127                 }
128                 Some(Node::Expr(hir::Expr {
129                     kind: ExprKind::Closure(_, _, body_id, _, _),
130                     span: full_closure_span,
131                     ..
132                 })) => {
133                     if *full_closure_span == expr.span {
134                         return false;
135                     }
136                     msg = "call this closure";
137                     let body = hir.body(*body_id);
138                     sugg_call = body
139                         .params
140                         .iter()
141                         .map(|param| match &param.pat.kind {
142                             hir::PatKind::Binding(_, _, ident, None)
143                                 if ident.name != kw::SelfLower =>
144                             {
145                                 ident.to_string()
146                             }
147                             _ => "_".to_string(),
148                         })
149                         .collect::<Vec<_>>()
150                         .join(", ");
151                 }
152                 Some(Node::Ctor(hir::VariantData::Tuple(fields, _))) => {
153                     sugg_call = fields.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
154                     match def_id.as_local().map(|def_id| hir.def_kind(def_id)) {
155                         Some(DefKind::Ctor(hir::def::CtorOf::Variant, _)) => {
156                             msg = "instantiate this tuple variant";
157                         }
158                         Some(DefKind::Ctor(CtorOf::Struct, _)) => {
159                             msg = "instantiate this tuple struct";
160                         }
161                         _ => {}
162                     }
163                 }
164                 Some(Node::ForeignItem(hir::ForeignItem {
165                     kind: hir::ForeignItemKind::Fn(_, idents, _),
166                     ..
167                 })) => {
168                     sugg_call = idents
169                         .iter()
170                         .map(|ident| {
171                             if ident.name != kw::SelfLower {
172                                 ident.to_string()
173                             } else {
174                                 "_".to_string()
175                             }
176                         })
177                         .collect::<Vec<_>>()
178                         .join(", ")
179                 }
180                 Some(Node::TraitItem(hir::TraitItem {
181                     kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Required(idents)),
182                     ..
183                 })) => {
184                     sugg_call = idents
185                         .iter()
186                         .map(|ident| {
187                             if ident.name != kw::SelfLower {
188                                 ident.to_string()
189                             } else {
190                                 "_".to_string()
191                             }
192                         })
193                         .collect::<Vec<_>>()
194                         .join(", ")
195                 }
196                 _ => {}
197             }
198             err.span_suggestion_verbose(
199                 expr.span.shrink_to_hi(),
200                 &format!("use parentheses to {}", msg),
201                 format!("({})", sugg_call),
202                 applicability,
203             );
204             return true;
205         }
206         false
207     }
208
209     pub fn suggest_deref_ref_or_into(
210         &self,
211         err: &mut Diagnostic,
212         expr: &hir::Expr<'tcx>,
213         expected: Ty<'tcx>,
214         found: Ty<'tcx>,
215         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
216     ) {
217         let expr = expr.peel_blocks();
218         if let Some((sp, msg, suggestion, applicability, verbose)) =
219             self.check_ref(expr, found, expected)
220         {
221             if verbose {
222                 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
223             } else {
224                 err.span_suggestion(sp, &msg, suggestion, applicability);
225             }
226         } else if let (ty::FnDef(def_id, ..), true) =
227             (&found.kind(), self.suggest_fn_call(err, expr, expected, found))
228         {
229             if let Some(sp) = self.tcx.hir().span_if_local(*def_id) {
230                 let sp = self.sess().source_map().guess_head_span(sp);
231                 err.span_label(sp, &format!("{} defined here", found));
232             }
233         } else if !self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
234             let is_struct_pat_shorthand_field =
235                 self.maybe_get_struct_pattern_shorthand_field(expr).is_some();
236             let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
237             if !methods.is_empty() {
238                 if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) {
239                     let mut suggestions = iter::zip(iter::repeat(&expr_text), &methods)
240                         .filter_map(|(receiver, method)| {
241                             let method_call = format!(".{}()", method.name);
242                             if receiver.ends_with(&method_call) {
243                                 None // do not suggest code that is already there (#53348)
244                             } else {
245                                 let method_call_list = [".to_vec()", ".to_string()"];
246                                 let mut sugg = if receiver.ends_with(".clone()")
247                                     && method_call_list.contains(&method_call.as_str())
248                                 {
249                                     let max_len = receiver.rfind('.').unwrap();
250                                     vec![(
251                                         expr.span,
252                                         format!("{}{}", &receiver[..max_len], method_call),
253                                     )]
254                                 } else {
255                                     if expr.precedence().order()
256                                         < ExprPrecedence::MethodCall.order()
257                                     {
258                                         vec![
259                                             (expr.span.shrink_to_lo(), "(".to_string()),
260                                             (expr.span.shrink_to_hi(), format!("){}", method_call)),
261                                         ]
262                                     } else {
263                                         vec![(expr.span.shrink_to_hi(), method_call)]
264                                     }
265                                 };
266                                 if is_struct_pat_shorthand_field {
267                                     sugg.insert(
268                                         0,
269                                         (expr.span.shrink_to_lo(), format!("{}: ", receiver)),
270                                     );
271                                 }
272                                 Some(sugg)
273                             }
274                         })
275                         .peekable();
276                     if suggestions.peek().is_some() {
277                         err.multipart_suggestions(
278                             "try using a conversion method",
279                             suggestions,
280                             Applicability::MaybeIncorrect,
281                         );
282                     }
283                 }
284             } else if found.to_string().starts_with("Option<")
285                 && expected.to_string() == "Option<&str>"
286             {
287                 if let ty::Adt(_def, subst) = found.kind() {
288                     if subst.len() != 0 {
289                         if let GenericArgKind::Type(ty) = subst[0].unpack() {
290                             let peeled = ty.peel_refs().to_string();
291                             if peeled == "String" {
292                                 let ref_cnt = ty.to_string().len() - peeled.len();
293                                 let result = format!(".map(|x| &*{}x)", "*".repeat(ref_cnt));
294                                 err.span_suggestion_verbose(
295                                     expr.span.shrink_to_hi(),
296                                     "try converting the passed type into a `&str`",
297                                     result,
298                                     Applicability::MaybeIncorrect,
299                                 );
300                             }
301                         }
302                     }
303                 }
304             }
305         }
306     }
307
308     /// When encountering the expected boxed value allocated in the stack, suggest allocating it
309     /// in the heap by calling `Box::new()`.
310     pub(in super::super) fn suggest_boxing_when_appropriate(
311         &self,
312         err: &mut Diagnostic,
313         expr: &hir::Expr<'_>,
314         expected: Ty<'tcx>,
315         found: Ty<'tcx>,
316     ) {
317         if self.tcx.hir().is_inside_const_context(expr.hir_id) {
318             // Do not suggest `Box::new` in const context.
319             return;
320         }
321         if !expected.is_box() || found.is_box() {
322             return;
323         }
324         let boxed_found = self.tcx.mk_box(found);
325         if self.can_coerce(boxed_found, expected) {
326             err.multipart_suggestion(
327                 "store this in the heap by calling `Box::new`",
328                 vec![
329                     (expr.span.shrink_to_lo(), "Box::new(".to_string()),
330                     (expr.span.shrink_to_hi(), ")".to_string()),
331                 ],
332                 Applicability::MachineApplicable,
333             );
334             err.note(
335                 "for more on the distinction between the stack and the heap, read \
336                  https://doc.rust-lang.org/book/ch15-01-box.html, \
337                  https://doc.rust-lang.org/rust-by-example/std/box.html, and \
338                  https://doc.rust-lang.org/std/boxed/index.html",
339             );
340         }
341     }
342
343     /// When encountering a closure that captures variables, where a FnPtr is expected,
344     /// suggest a non-capturing closure
345     pub(in super::super) fn suggest_no_capture_closure(
346         &self,
347         err: &mut Diagnostic,
348         expected: Ty<'tcx>,
349         found: Ty<'tcx>,
350     ) {
351         if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
352             if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
353                 // Report upto four upvars being captured to reduce the amount error messages
354                 // reported back to the user.
355                 let spans_and_labels = upvars
356                     .iter()
357                     .take(4)
358                     .map(|(var_hir_id, upvar)| {
359                         let var_name = self.tcx.hir().name(*var_hir_id).to_string();
360                         let msg = format!("`{}` captured here", var_name);
361                         (upvar.span, msg)
362                     })
363                     .collect::<Vec<_>>();
364
365                 let mut multi_span: MultiSpan =
366                     spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
367                 for (sp, label) in spans_and_labels {
368                     multi_span.push_span_label(sp, label);
369                 }
370                 err.span_note(
371                     multi_span,
372                     "closures can only be coerced to `fn` types if they do not capture any variables"
373                 );
374             }
375         }
376     }
377
378     /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
379     #[instrument(skip(self, err))]
380     pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
381         &self,
382         err: &mut Diagnostic,
383         expr: &hir::Expr<'_>,
384         expected: Ty<'tcx>,
385         found: Ty<'tcx>,
386     ) -> bool {
387         // Handle #68197.
388
389         if self.tcx.hir().is_inside_const_context(expr.hir_id) {
390             // Do not suggest `Box::new` in const context.
391             return false;
392         }
393         let pin_did = self.tcx.lang_items().pin_type();
394         // This guards the `unwrap` and `mk_box` below.
395         if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
396             return false;
397         }
398         let box_found = self.tcx.mk_box(found);
399         let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
400         let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
401         match expected.kind() {
402             ty::Adt(def, _) if Some(def.did()) == pin_did => {
403                 if self.can_coerce(pin_box_found, expected) {
404                     debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
405                     match found.kind() {
406                         ty::Adt(def, _) if def.is_box() => {
407                             err.help("use `Box::pin`");
408                         }
409                         _ => {
410                             err.multipart_suggestion(
411                                 "you need to pin and box this expression",
412                                 vec![
413                                     (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
414                                     (expr.span.shrink_to_hi(), ")".to_string()),
415                                 ],
416                                 Applicability::MaybeIncorrect,
417                             );
418                         }
419                     }
420                     true
421                 } else if self.can_coerce(pin_found, expected) {
422                     match found.kind() {
423                         ty::Adt(def, _) if def.is_box() => {
424                             err.help("use `Box::pin`");
425                             true
426                         }
427                         _ => false,
428                     }
429                 } else {
430                     false
431                 }
432             }
433             ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
434                 // Check if the parent expression is a call to Pin::new.  If it
435                 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
436                 // can suggest Box::pin.
437                 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
438                 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
439                     return false;
440                 };
441                 match fn_name.kind {
442                     ExprKind::Path(QPath::TypeRelative(
443                         hir::Ty {
444                             kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
445                             ..
446                         },
447                         method,
448                     )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
449                         err.span_suggestion(
450                             fn_name.span,
451                             "use `Box::pin` to pin and box this expression",
452                             "Box::pin".to_string(),
453                             Applicability::MachineApplicable,
454                         );
455                         true
456                     }
457                     _ => false,
458                 }
459             }
460             _ => false,
461         }
462     }
463
464     /// A common error is to forget to add a semicolon at the end of a block, e.g.,
465     ///
466     /// ```compile_fail,E0308
467     /// # fn bar_that_returns_u32() -> u32 { 4 }
468     /// fn foo() {
469     ///     bar_that_returns_u32()
470     /// }
471     /// ```
472     ///
473     /// This routine checks if the return expression in a block would make sense on its own as a
474     /// statement and the return type has been left as default or has been specified as `()`. If so,
475     /// it suggests adding a semicolon.
476     fn suggest_missing_semicolon(
477         &self,
478         err: &mut Diagnostic,
479         expression: &'tcx hir::Expr<'tcx>,
480         expected: Ty<'tcx>,
481     ) {
482         if expected.is_unit() {
483             // `BlockTailExpression` only relevant if the tail expr would be
484             // useful on its own.
485             match expression.kind {
486                 ExprKind::Call(..)
487                 | ExprKind::MethodCall(..)
488                 | ExprKind::Loop(..)
489                 | ExprKind::If(..)
490                 | ExprKind::Match(..)
491                 | ExprKind::Block(..)
492                     if expression.can_have_side_effects() =>
493                 {
494                     err.span_suggestion(
495                         expression.span.shrink_to_hi(),
496                         "consider using a semicolon here",
497                         ";".to_string(),
498                         Applicability::MachineApplicable,
499                     );
500                 }
501                 _ => (),
502             }
503         }
504     }
505
506     /// A possible error is to forget to add a return type that is needed:
507     ///
508     /// ```compile_fail,E0308
509     /// # fn bar_that_returns_u32() -> u32 { 4 }
510     /// fn foo() {
511     ///     bar_that_returns_u32()
512     /// }
513     /// ```
514     ///
515     /// This routine checks if the return type is left as default, the method is not part of an
516     /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
517     /// type.
518     pub(in super::super) fn suggest_missing_return_type(
519         &self,
520         err: &mut Diagnostic,
521         fn_decl: &hir::FnDecl<'_>,
522         expected: Ty<'tcx>,
523         found: Ty<'tcx>,
524         can_suggest: bool,
525         fn_id: hir::HirId,
526     ) -> bool {
527         let found =
528             self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
529         // Only suggest changing the return type for methods that
530         // haven't set a return type at all (and aren't `fn main()` or an impl).
531         match (&fn_decl.output, found.is_suggestable(self.tcx), can_suggest, expected.is_unit()) {
532             (&hir::FnRetTy::DefaultReturn(span), true, true, true) => {
533                 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found });
534                 true
535             }
536             (&hir::FnRetTy::DefaultReturn(span), false, true, true) => {
537                 // FIXME: if `found` could be `impl Iterator` or `impl Fn*`, we should suggest
538                 // that.
539                 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
540                 true
541             }
542             (&hir::FnRetTy::DefaultReturn(span), _, false, true) => {
543                 // `fn main()` must return `()`, do not suggest changing return type
544                 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
545                 true
546             }
547             // expectation was caused by something else, not the default return
548             (&hir::FnRetTy::DefaultReturn(_), _, _, false) => false,
549             (&hir::FnRetTy::Return(ref ty), _, _, _) => {
550                 // Only point to return type if the expected type is the return type, as if they
551                 // are not, the expectation must have been caused by something else.
552                 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
553                 let span = ty.span;
554                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
555                 debug!("suggest_missing_return_type: return type {:?}", ty);
556                 debug!("suggest_missing_return_type: expected type {:?}", ty);
557                 let bound_vars = self.tcx.late_bound_vars(fn_id);
558                 let ty = Binder::bind_with_vars(ty, bound_vars);
559                 let ty = self.normalize_associated_types_in(span, ty);
560                 let ty = self.tcx.erase_late_bound_regions(ty);
561                 if self.can_coerce(expected, ty) {
562                     err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
563                     self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
564                     return true;
565                 }
566                 false
567             }
568         }
569     }
570
571     /// check whether the return type is a generic type with a trait bound
572     /// only suggest this if the generic param is not present in the arguments
573     /// if this is true, hint them towards changing the return type to `impl Trait`
574     /// ```compile_fail,E0308
575     /// fn cant_name_it<T: Fn() -> u32>() -> T {
576     ///     || 3
577     /// }
578     /// ```
579     fn try_suggest_return_impl_trait(
580         &self,
581         err: &mut Diagnostic,
582         expected: Ty<'tcx>,
583         found: Ty<'tcx>,
584         fn_id: hir::HirId,
585     ) {
586         // Only apply the suggestion if:
587         //  - the return type is a generic parameter
588         //  - the generic param is not used as a fn param
589         //  - the generic param has at least one bound
590         //  - the generic param doesn't appear in any other bounds where it's not the Self type
591         // Suggest:
592         //  - Changing the return type to be `impl <all bounds>`
593
594         debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
595
596         let ty::Param(expected_ty_as_param) = expected.kind() else { return };
597
598         let fn_node = self.tcx.hir().find(fn_id);
599
600         let Some(hir::Node::Item(hir::Item {
601             kind:
602                 hir::ItemKind::Fn(
603                     hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
604                     hir::Generics { params, predicates, .. },
605                     _body_id,
606                 ),
607             ..
608         })) = fn_node else { return };
609
610         if params.get(expected_ty_as_param.index as usize).is_none() {
611             return;
612         };
613
614         // get all where BoundPredicates here, because they are used in to cases below
615         let where_predicates = predicates
616             .iter()
617             .filter_map(|p| match p {
618                 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
619                     bounds,
620                     bounded_ty,
621                     ..
622                 }) => {
623                     // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
624                     let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
625                     Some((ty, bounds))
626                 }
627                 _ => None,
628             })
629             .map(|(ty, bounds)| match ty.kind() {
630                 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
631                 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
632                 _ => match ty.contains(expected) {
633                     true => Err(()),
634                     false => Ok(None),
635                 },
636             })
637             .collect::<Result<Vec<_>, _>>();
638
639         let Ok(where_predicates) = where_predicates else { return };
640
641         // now get all predicates in the same types as the where bounds, so we can chain them
642         let predicates_from_where =
643             where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
644
645         // extract all bounds from the source code using their spans
646         let all_matching_bounds_strs = predicates_from_where
647             .filter_map(|bound| match bound {
648                 GenericBound::Trait(_, _) => {
649                     self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
650                 }
651                 _ => None,
652             })
653             .collect::<Vec<String>>();
654
655         if all_matching_bounds_strs.len() == 0 {
656             return;
657         }
658
659         let all_bounds_str = all_matching_bounds_strs.join(" + ");
660
661         let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
662                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
663                 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
664             });
665
666         if ty_param_used_in_fn_params {
667             return;
668         }
669
670         err.span_suggestion(
671             fn_return.span(),
672             "consider using an impl return type",
673             format!("impl {}", all_bounds_str),
674             Applicability::MaybeIncorrect,
675         );
676     }
677
678     pub(in super::super) fn suggest_missing_break_or_return_expr(
679         &self,
680         err: &mut Diagnostic,
681         expr: &'tcx hir::Expr<'tcx>,
682         fn_decl: &hir::FnDecl<'_>,
683         expected: Ty<'tcx>,
684         found: Ty<'tcx>,
685         id: hir::HirId,
686         fn_id: hir::HirId,
687     ) {
688         if !expected.is_unit() {
689             return;
690         }
691         let found = self.resolve_vars_with_obligations(found);
692
693         let in_loop = self.is_loop(id)
694             || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
695
696         let in_local_statement = self.is_local_statement(id)
697             || self
698                 .tcx
699                 .hir()
700                 .parent_iter(id)
701                 .any(|(parent_id, _)| self.is_local_statement(parent_id));
702
703         if in_loop && in_local_statement {
704             err.multipart_suggestion(
705                 "you might have meant to break the loop with this value",
706                 vec![
707                     (expr.span.shrink_to_lo(), "break ".to_string()),
708                     (expr.span.shrink_to_hi(), ";".to_string()),
709                 ],
710                 Applicability::MaybeIncorrect,
711             );
712             return;
713         }
714
715         if let hir::FnRetTy::Return(ty) = fn_decl.output {
716             let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
717             let bound_vars = self.tcx.late_bound_vars(fn_id);
718             let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
719             let ty = self.normalize_associated_types_in(expr.span, ty);
720             let ty = match self.tcx.asyncness(fn_id.owner) {
721                 hir::IsAsync::Async => self
722                     .tcx
723                     .infer_ctxt()
724                     .enter(|infcx| {
725                         infcx.get_impl_future_output_ty(ty).unwrap_or_else(|| {
726                             span_bug!(
727                                 fn_decl.output.span(),
728                                 "failed to get output type of async function"
729                             )
730                         })
731                     })
732                     .skip_binder(),
733                 hir::IsAsync::NotAsync => ty,
734             };
735             if self.can_coerce(found, ty) {
736                 err.multipart_suggestion(
737                     "you might have meant to return this value",
738                     vec![
739                         (expr.span.shrink_to_lo(), "return ".to_string()),
740                         (expr.span.shrink_to_hi(), ";".to_string()),
741                     ],
742                     Applicability::MaybeIncorrect,
743                 );
744             }
745         }
746     }
747
748     pub(in super::super) fn suggest_missing_parentheses(
749         &self,
750         err: &mut Diagnostic,
751         expr: &hir::Expr<'_>,
752     ) {
753         let sp = self.tcx.sess.source_map().start_point(expr.span);
754         if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
755             // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
756             self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp);
757         }
758     }
759
760     /// Given an expression type mismatch, peel any `&` expressions until we get to
761     /// a block expression, and then suggest replacing the braces with square braces
762     /// if it was possibly mistaken array syntax.
763     pub(crate) fn suggest_block_to_brackets_peeling_refs(
764         &self,
765         diag: &mut Diagnostic,
766         mut expr: &hir::Expr<'_>,
767         mut expr_ty: Ty<'tcx>,
768         mut expected_ty: Ty<'tcx>,
769     ) {
770         loop {
771             match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
772                 (
773                     hir::ExprKind::AddrOf(_, _, inner_expr),
774                     ty::Ref(_, inner_expr_ty, _),
775                     ty::Ref(_, inner_expected_ty, _),
776                 ) => {
777                     expr = *inner_expr;
778                     expr_ty = *inner_expr_ty;
779                     expected_ty = *inner_expected_ty;
780                 }
781                 (hir::ExprKind::Block(blk, _), _, _) => {
782                     self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
783                     break;
784                 }
785                 _ => break,
786             }
787         }
788     }
789
790     /// Suggest wrapping the block in square brackets instead of curly braces
791     /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
792     pub(crate) fn suggest_block_to_brackets(
793         &self,
794         diag: &mut Diagnostic,
795         blk: &hir::Block<'_>,
796         blk_ty: Ty<'tcx>,
797         expected_ty: Ty<'tcx>,
798     ) {
799         if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
800             if self.can_coerce(blk_ty, *elem_ty)
801                 && blk.stmts.is_empty()
802                 && blk.rules == hir::BlockCheckMode::DefaultBlock
803             {
804                 let source_map = self.tcx.sess.source_map();
805                 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
806                     if snippet.starts_with('{') && snippet.ends_with('}') {
807                         diag.multipart_suggestion_verbose(
808                             "to create an array, use square brackets instead of curly braces",
809                             vec![
810                                 (
811                                     blk.span
812                                         .shrink_to_lo()
813                                         .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
814                                     "[".to_string(),
815                                 ),
816                                 (
817                                     blk.span
818                                         .shrink_to_hi()
819                                         .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
820                                     "]".to_string(),
821                                 ),
822                             ],
823                             Applicability::MachineApplicable,
824                         );
825                     }
826                 }
827             }
828         }
829     }
830
831     fn is_loop(&self, id: hir::HirId) -> bool {
832         let node = self.tcx.hir().get(id);
833         matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
834     }
835
836     fn is_local_statement(&self, id: hir::HirId) -> bool {
837         let node = self.tcx.hir().get(id);
838         matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
839     }
840
841     /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
842     /// which is a side-effect of autoref.
843     pub(crate) fn note_type_is_not_clone(
844         &self,
845         diag: &mut Diagnostic,
846         expected_ty: Ty<'tcx>,
847         found_ty: Ty<'tcx>,
848         expr: &hir::Expr<'_>,
849     ) {
850         let hir::ExprKind::MethodCall(segment, &[ref callee_expr], _) = expr.kind else { return; };
851         let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
852         let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
853         let results = self.typeck_results.borrow();
854         // First, look for a `Clone::clone` call
855         if segment.ident.name == sym::clone
856             && results.type_dependent_def_id(expr.hir_id).map_or(
857                 false,
858                 |did| {
859                     self.tcx.associated_item(did).container
860                         == ty::AssocItemContainer::TraitContainer(clone_trait_did)
861                 },
862             )
863             // If that clone call hasn't already dereferenced the self type (i.e. don't give this
864             // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
865             && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
866             // Check that we're in fact trying to clone into the expected type
867             && self.can_coerce(*pointee_ty, expected_ty)
868             // And the expected type doesn't implement `Clone`
869             && !self.predicate_must_hold_considering_regions(&traits::Obligation {
870                 cause: traits::ObligationCause::dummy(),
871                 param_env: self.param_env,
872                 recursion_depth: 0,
873                 predicate: ty::Binder::dummy(ty::TraitRef {
874                     def_id: clone_trait_did,
875                     substs: self.tcx.mk_substs([expected_ty.into()].iter()),
876                 })
877                 .without_const()
878                 .to_predicate(self.tcx),
879             })
880         {
881             diag.span_note(
882                 callee_expr.span,
883                 &format!(
884                     "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
885                 ),
886             );
887         }
888     }
889 }