]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs
Rollup merge of #94091 - GuillaumeGomez:rustdoc-const-computed-value, r=oli-obk
[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 fn_name = match self.tcx.hir().find(parent) {
442                     Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) => fn_name,
443                     _ => return false,
444                 };
445                 match fn_name.kind {
446                     ExprKind::Path(QPath::TypeRelative(
447                         hir::Ty {
448                             kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
449                             ..
450                         },
451                         method,
452                     )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
453                         err.span_suggestion(
454                             fn_name.span,
455                             "use `Box::pin` to pin and box this expression",
456                             "Box::pin".to_string(),
457                             Applicability::MachineApplicable,
458                         );
459                         true
460                     }
461                     _ => false,
462                 }
463             }
464             _ => false,
465         }
466     }
467
468     /// A common error is to forget to add a semicolon at the end of a block, e.g.,
469     ///
470     /// ```
471     /// fn foo() {
472     ///     bar_that_returns_u32()
473     /// }
474     /// ```
475     ///
476     /// This routine checks if the return expression in a block would make sense on its own as a
477     /// statement and the return type has been left as default or has been specified as `()`. If so,
478     /// it suggests adding a semicolon.
479     fn suggest_missing_semicolon(
480         &self,
481         err: &mut DiagnosticBuilder<'_>,
482         expression: &'tcx hir::Expr<'tcx>,
483         expected: Ty<'tcx>,
484     ) {
485         if expected.is_unit() {
486             // `BlockTailExpression` only relevant if the tail expr would be
487             // useful on its own.
488             match expression.kind {
489                 ExprKind::Call(..)
490                 | ExprKind::MethodCall(..)
491                 | ExprKind::Loop(..)
492                 | ExprKind::If(..)
493                 | ExprKind::Match(..)
494                 | ExprKind::Block(..)
495                     if expression.can_have_side_effects() =>
496                 {
497                     err.span_suggestion(
498                         expression.span.shrink_to_hi(),
499                         "consider using a semicolon here",
500                         ";".to_string(),
501                         Applicability::MachineApplicable,
502                     );
503                 }
504                 _ => (),
505             }
506         }
507     }
508
509     /// A possible error is to forget to add a return type that is needed:
510     ///
511     /// ```
512     /// fn foo() {
513     ///     bar_that_returns_u32()
514     /// }
515     /// ```
516     ///
517     /// This routine checks if the return type is left as default, the method is not part of an
518     /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
519     /// type.
520     pub(in super::super) fn suggest_missing_return_type(
521         &self,
522         err: &mut DiagnosticBuilder<'_>,
523         fn_decl: &hir::FnDecl<'_>,
524         expected: Ty<'tcx>,
525         found: Ty<'tcx>,
526         can_suggest: bool,
527         fn_id: hir::HirId,
528     ) -> bool {
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(), can_suggest, expected.is_unit()) {
532             (&hir::FnRetTy::DefaultReturn(span), true, true, true) => {
533                 err.span_suggestion(
534                     span,
535                     "try adding a return type",
536                     format!("-> {} ", self.resolve_vars_with_obligations(found)),
537                     Applicability::MachineApplicable,
538                 );
539                 true
540             }
541             (&hir::FnRetTy::DefaultReturn(span), false, true, true) => {
542                 err.span_label(span, "possibly return type missing here?");
543                 true
544             }
545             (&hir::FnRetTy::DefaultReturn(span), _, false, true) => {
546                 // `fn main()` must return `()`, do not suggest changing return type
547                 err.span_label(span, "expected `()` because of default return type");
548                 true
549             }
550             // expectation was caused by something else, not the default return
551             (&hir::FnRetTy::DefaultReturn(_), _, _, false) => false,
552             (&hir::FnRetTy::Return(ref ty), _, _, _) => {
553                 // Only point to return type if the expected type is the return type, as if they
554                 // are not, the expectation must have been caused by something else.
555                 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
556                 let sp = ty.span;
557                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
558                 debug!("suggest_missing_return_type: return type {:?}", ty);
559                 debug!("suggest_missing_return_type: expected type {:?}", ty);
560                 let bound_vars = self.tcx.late_bound_vars(fn_id);
561                 let ty = Binder::bind_with_vars(ty, bound_vars);
562                 let ty = self.normalize_associated_types_in(sp, ty);
563                 let ty = self.tcx.erase_late_bound_regions(ty);
564                 if self.can_coerce(expected, ty) {
565                     err.span_label(sp, format!("expected `{}` because of return type", expected));
566                     self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
567                     return true;
568                 }
569                 false
570             }
571         }
572     }
573
574     /// check whether the return type is a generic type with a trait bound
575     /// only suggest this if the generic param is not present in the arguments
576     /// if this is true, hint them towards changing the return type to `impl Trait`
577     /// ```
578     /// fn cant_name_it<T: Fn() -> u32>() -> T {
579     ///     || 3
580     /// }
581     /// ```
582     fn try_suggest_return_impl_trait(
583         &self,
584         err: &mut DiagnosticBuilder<'_>,
585         expected: Ty<'tcx>,
586         found: Ty<'tcx>,
587         fn_id: hir::HirId,
588     ) {
589         // Only apply the suggestion if:
590         //  - the return type is a generic parameter
591         //  - the generic param is not used as a fn param
592         //  - the generic param has at least one bound
593         //  - the generic param doesn't appear in any other bounds where it's not the Self type
594         // Suggest:
595         //  - Changing the return type to be `impl <all bounds>`
596
597         debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
598
599         let ty::Param(expected_ty_as_param) = expected.kind() else { return };
600
601         let fn_node = self.tcx.hir().find(fn_id);
602
603         let Some(hir::Node::Item(hir::Item {
604             kind:
605                 hir::ItemKind::Fn(
606                     hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
607                     hir::Generics { params, where_clause, .. },
608                     _body_id,
609                 ),
610             ..
611         })) = fn_node else { return };
612
613         let Some(expected_generic_param) = params.get(expected_ty_as_param.index as usize) else { return };
614
615         // get all where BoundPredicates here, because they are used in to cases below
616         let where_predicates = where_clause
617             .predicates
618             .iter()
619             .filter_map(|p| match p {
620                 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
621                     bounds,
622                     bounded_ty,
623                     ..
624                 }) => {
625                     // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
626                     let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
627                     Some((ty, bounds))
628                 }
629                 _ => None,
630             })
631             .map(|(ty, bounds)| match ty.kind() {
632                 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
633                 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
634                 _ => match ty.contains(expected) {
635                     true => Err(()),
636                     false => Ok(None),
637                 },
638             })
639             .collect::<Result<Vec<_>, _>>();
640
641         let Ok(where_predicates) =  where_predicates else { return };
642
643         // now get all predicates in the same types as the where bounds, so we can chain them
644         let predicates_from_where =
645             where_predicates.iter().flatten().map(|bounds| bounds.iter()).flatten();
646
647         // extract all bounds from the source code using their spans
648         let all_matching_bounds_strs = expected_generic_param
649             .bounds
650             .iter()
651             .chain(predicates_from_where)
652             .filter_map(|bound| match bound {
653                 GenericBound::Trait(_, _) => {
654                     self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
655                 }
656                 _ => None,
657             })
658             .collect::<Vec<String>>();
659
660         if all_matching_bounds_strs.len() == 0 {
661             return;
662         }
663
664         let all_bounds_str = all_matching_bounds_strs.join(" + ");
665
666         let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
667                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
668                 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
669             });
670
671         if ty_param_used_in_fn_params {
672             return;
673         }
674
675         err.span_suggestion(
676             fn_return.span(),
677             "consider using an impl return type",
678             format!("impl {}", all_bounds_str),
679             Applicability::MaybeIncorrect,
680         );
681     }
682
683     pub(in super::super) fn suggest_missing_break_or_return_expr(
684         &self,
685         err: &mut DiagnosticBuilder<'_>,
686         expr: &'tcx hir::Expr<'tcx>,
687         fn_decl: &hir::FnDecl<'_>,
688         expected: Ty<'tcx>,
689         found: Ty<'tcx>,
690         id: hir::HirId,
691         fn_id: hir::HirId,
692     ) {
693         if !expected.is_unit() {
694             return;
695         }
696         let found = self.resolve_vars_with_obligations(found);
697
698         let in_loop = self.is_loop(id)
699             || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
700
701         let in_local_statement = self.is_local_statement(id)
702             || self
703                 .tcx
704                 .hir()
705                 .parent_iter(id)
706                 .any(|(parent_id, _)| self.is_local_statement(parent_id));
707
708         if in_loop && in_local_statement {
709             err.multipart_suggestion(
710                 "you might have meant to break the loop with this value",
711                 vec![
712                     (expr.span.shrink_to_lo(), "break ".to_string()),
713                     (expr.span.shrink_to_hi(), ";".to_string()),
714                 ],
715                 Applicability::MaybeIncorrect,
716             );
717             return;
718         }
719
720         if let hir::FnRetTy::Return(ty) = fn_decl.output {
721             let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
722             let bound_vars = self.tcx.late_bound_vars(fn_id);
723             let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
724             let ty = self.normalize_associated_types_in(expr.span, ty);
725             let ty = match self.tcx.asyncness(fn_id.owner) {
726                 hir::IsAsync::Async => self
727                     .tcx
728                     .infer_ctxt()
729                     .enter(|infcx| {
730                         infcx.get_impl_future_output_ty(ty).unwrap_or_else(|| {
731                             span_bug!(
732                                 fn_decl.output.span(),
733                                 "failed to get output type of async function"
734                             )
735                         })
736                     })
737                     .skip_binder(),
738                 hir::IsAsync::NotAsync => ty,
739             };
740             if self.can_coerce(found, ty) {
741                 err.multipart_suggestion(
742                     "you might have meant to return this value",
743                     vec![
744                         (expr.span.shrink_to_lo(), "return ".to_string()),
745                         (expr.span.shrink_to_hi(), ";".to_string()),
746                     ],
747                     Applicability::MaybeIncorrect,
748                 );
749             }
750         }
751     }
752
753     pub(in super::super) fn suggest_missing_parentheses(
754         &self,
755         err: &mut DiagnosticBuilder<'_>,
756         expr: &hir::Expr<'_>,
757     ) {
758         let sp = self.tcx.sess.source_map().start_point(expr.span);
759         if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
760             // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
761             self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp);
762         }
763     }
764
765     fn is_loop(&self, id: hir::HirId) -> bool {
766         let node = self.tcx.hir().get(id);
767         matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
768     }
769
770     fn is_local_statement(&self, id: hir::HirId) -> bool {
771         let node = self.tcx.hir().get(id);
772         matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
773     }
774 }