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