]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs
Auto merge of #95362 - scottmcm:calloc-arrays, r=Mark-Simulacrum
[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     /// ```
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     /// ```
467     /// fn foo() {
468     ///     bar_that_returns_u32()
469     /// }
470     /// ```
471     ///
472     /// This routine checks if the return expression in a block would make sense on its own as a
473     /// statement and the return type has been left as default or has been specified as `()`. If so,
474     /// it suggests adding a semicolon.
475     fn suggest_missing_semicolon(
476         &self,
477         err: &mut Diagnostic,
478         expression: &'tcx hir::Expr<'tcx>,
479         expected: Ty<'tcx>,
480     ) {
481         if expected.is_unit() {
482             // `BlockTailExpression` only relevant if the tail expr would be
483             // useful on its own.
484             match expression.kind {
485                 ExprKind::Call(..)
486                 | ExprKind::MethodCall(..)
487                 | ExprKind::Loop(..)
488                 | ExprKind::If(..)
489                 | ExprKind::Match(..)
490                 | ExprKind::Block(..)
491                     if expression.can_have_side_effects() =>
492                 {
493                     err.span_suggestion(
494                         expression.span.shrink_to_hi(),
495                         "consider using a semicolon here",
496                         ";".to_string(),
497                         Applicability::MachineApplicable,
498                     );
499                 }
500                 _ => (),
501             }
502         }
503     }
504
505     /// A possible error is to forget to add a return type that is needed:
506     ///
507     /// ```
508     /// fn foo() {
509     ///     bar_that_returns_u32()
510     /// }
511     /// ```
512     ///
513     /// This routine checks if the return type is left as default, the method is not part of an
514     /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
515     /// type.
516     pub(in super::super) fn suggest_missing_return_type(
517         &self,
518         err: &mut Diagnostic,
519         fn_decl: &hir::FnDecl<'_>,
520         expected: Ty<'tcx>,
521         found: Ty<'tcx>,
522         can_suggest: bool,
523         fn_id: hir::HirId,
524     ) -> bool {
525         let found =
526             self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
527         // Only suggest changing the return type for methods that
528         // haven't set a return type at all (and aren't `fn main()` or an impl).
529         match (&fn_decl.output, found.is_suggestable(self.tcx), can_suggest, expected.is_unit()) {
530             (&hir::FnRetTy::DefaultReturn(span), true, true, true) => {
531                 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found });
532                 true
533             }
534             (&hir::FnRetTy::DefaultReturn(span), false, true, true) => {
535                 // FIXME: if `found` could be `impl Iterator` or `impl Fn*`, we should suggest
536                 // that.
537                 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
538                 true
539             }
540             (&hir::FnRetTy::DefaultReturn(span), _, false, true) => {
541                 // `fn main()` must return `()`, do not suggest changing return type
542                 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
543                 true
544             }
545             // expectation was caused by something else, not the default return
546             (&hir::FnRetTy::DefaultReturn(_), _, _, false) => false,
547             (&hir::FnRetTy::Return(ref ty), _, _, _) => {
548                 // Only point to return type if the expected type is the return type, as if they
549                 // are not, the expectation must have been caused by something else.
550                 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
551                 let span = ty.span;
552                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
553                 debug!("suggest_missing_return_type: return type {:?}", ty);
554                 debug!("suggest_missing_return_type: expected type {:?}", ty);
555                 let bound_vars = self.tcx.late_bound_vars(fn_id);
556                 let ty = Binder::bind_with_vars(ty, bound_vars);
557                 let ty = self.normalize_associated_types_in(span, ty);
558                 let ty = self.tcx.erase_late_bound_regions(ty);
559                 if self.can_coerce(expected, ty) {
560                     err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
561                     self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
562                     return true;
563                 }
564                 false
565             }
566         }
567     }
568
569     /// check whether the return type is a generic type with a trait bound
570     /// only suggest this if the generic param is not present in the arguments
571     /// if this is true, hint them towards changing the return type to `impl Trait`
572     /// ```
573     /// fn cant_name_it<T: Fn() -> u32>() -> T {
574     ///     || 3
575     /// }
576     /// ```
577     fn try_suggest_return_impl_trait(
578         &self,
579         err: &mut Diagnostic,
580         expected: Ty<'tcx>,
581         found: Ty<'tcx>,
582         fn_id: hir::HirId,
583     ) {
584         // Only apply the suggestion if:
585         //  - the return type is a generic parameter
586         //  - the generic param is not used as a fn param
587         //  - the generic param has at least one bound
588         //  - the generic param doesn't appear in any other bounds where it's not the Self type
589         // Suggest:
590         //  - Changing the return type to be `impl <all bounds>`
591
592         debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
593
594         let ty::Param(expected_ty_as_param) = expected.kind() else { return };
595
596         let fn_node = self.tcx.hir().find(fn_id);
597
598         let Some(hir::Node::Item(hir::Item {
599             kind:
600                 hir::ItemKind::Fn(
601                     hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
602                     hir::Generics { params, predicates, .. },
603                     _body_id,
604                 ),
605             ..
606         })) = fn_node else { return };
607
608         if params.get(expected_ty_as_param.index as usize).is_none() {
609             return;
610         };
611
612         // get all where BoundPredicates here, because they are used in to cases below
613         let where_predicates = predicates
614             .iter()
615             .filter_map(|p| match p {
616                 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
617                     bounds,
618                     bounded_ty,
619                     ..
620                 }) => {
621                     // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
622                     let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
623                     Some((ty, bounds))
624                 }
625                 _ => None,
626             })
627             .map(|(ty, bounds)| match ty.kind() {
628                 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
629                 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
630                 _ => match ty.contains(expected) {
631                     true => Err(()),
632                     false => Ok(None),
633                 },
634             })
635             .collect::<Result<Vec<_>, _>>();
636
637         let Ok(where_predicates) = where_predicates else { return };
638
639         // now get all predicates in the same types as the where bounds, so we can chain them
640         let predicates_from_where =
641             where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
642
643         // extract all bounds from the source code using their spans
644         let all_matching_bounds_strs = predicates_from_where
645             .filter_map(|bound| match bound {
646                 GenericBound::Trait(_, _) => {
647                     self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
648                 }
649                 _ => None,
650             })
651             .collect::<Vec<String>>();
652
653         if all_matching_bounds_strs.len() == 0 {
654             return;
655         }
656
657         let all_bounds_str = all_matching_bounds_strs.join(" + ");
658
659         let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
660                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
661                 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
662             });
663
664         if ty_param_used_in_fn_params {
665             return;
666         }
667
668         err.span_suggestion(
669             fn_return.span(),
670             "consider using an impl return type",
671             format!("impl {}", all_bounds_str),
672             Applicability::MaybeIncorrect,
673         );
674     }
675
676     pub(in super::super) fn suggest_missing_break_or_return_expr(
677         &self,
678         err: &mut Diagnostic,
679         expr: &'tcx hir::Expr<'tcx>,
680         fn_decl: &hir::FnDecl<'_>,
681         expected: Ty<'tcx>,
682         found: Ty<'tcx>,
683         id: hir::HirId,
684         fn_id: hir::HirId,
685     ) {
686         if !expected.is_unit() {
687             return;
688         }
689         let found = self.resolve_vars_with_obligations(found);
690
691         let in_loop = self.is_loop(id)
692             || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
693
694         let in_local_statement = self.is_local_statement(id)
695             || self
696                 .tcx
697                 .hir()
698                 .parent_iter(id)
699                 .any(|(parent_id, _)| self.is_local_statement(parent_id));
700
701         if in_loop && in_local_statement {
702             err.multipart_suggestion(
703                 "you might have meant to break the loop with this value",
704                 vec![
705                     (expr.span.shrink_to_lo(), "break ".to_string()),
706                     (expr.span.shrink_to_hi(), ";".to_string()),
707                 ],
708                 Applicability::MaybeIncorrect,
709             );
710             return;
711         }
712
713         if let hir::FnRetTy::Return(ty) = fn_decl.output {
714             let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
715             let bound_vars = self.tcx.late_bound_vars(fn_id);
716             let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
717             let ty = self.normalize_associated_types_in(expr.span, ty);
718             let ty = match self.tcx.asyncness(fn_id.owner) {
719                 hir::IsAsync::Async => self
720                     .tcx
721                     .infer_ctxt()
722                     .enter(|infcx| {
723                         infcx.get_impl_future_output_ty(ty).unwrap_or_else(|| {
724                             span_bug!(
725                                 fn_decl.output.span(),
726                                 "failed to get output type of async function"
727                             )
728                         })
729                     })
730                     .skip_binder(),
731                 hir::IsAsync::NotAsync => ty,
732             };
733             if self.can_coerce(found, ty) {
734                 err.multipart_suggestion(
735                     "you might have meant to return this value",
736                     vec![
737                         (expr.span.shrink_to_lo(), "return ".to_string()),
738                         (expr.span.shrink_to_hi(), ";".to_string()),
739                     ],
740                     Applicability::MaybeIncorrect,
741                 );
742             }
743         }
744     }
745
746     pub(in super::super) fn suggest_missing_parentheses(
747         &self,
748         err: &mut Diagnostic,
749         expr: &hir::Expr<'_>,
750     ) {
751         let sp = self.tcx.sess.source_map().start_point(expr.span);
752         if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
753             // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
754             self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp);
755         }
756     }
757
758     /// Given an expression type mismatch, peel any `&` expressions until we get to
759     /// a block expression, and then suggest replacing the braces with square braces
760     /// if it was possibly mistaken array syntax.
761     pub(crate) fn suggest_block_to_brackets_peeling_refs(
762         &self,
763         diag: &mut Diagnostic,
764         mut expr: &hir::Expr<'_>,
765         mut expr_ty: Ty<'tcx>,
766         mut expected_ty: Ty<'tcx>,
767     ) {
768         loop {
769             match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
770                 (
771                     hir::ExprKind::AddrOf(_, _, inner_expr),
772                     ty::Ref(_, inner_expr_ty, _),
773                     ty::Ref(_, inner_expected_ty, _),
774                 ) => {
775                     expr = *inner_expr;
776                     expr_ty = *inner_expr_ty;
777                     expected_ty = *inner_expected_ty;
778                 }
779                 (hir::ExprKind::Block(blk, _), _, _) => {
780                     self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
781                     break;
782                 }
783                 _ => break,
784             }
785         }
786     }
787
788     /// Suggest wrapping the block in square brackets instead of curly braces
789     /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
790     pub(crate) fn suggest_block_to_brackets(
791         &self,
792         diag: &mut Diagnostic,
793         blk: &hir::Block<'_>,
794         blk_ty: Ty<'tcx>,
795         expected_ty: Ty<'tcx>,
796     ) {
797         if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
798             if self.can_coerce(blk_ty, *elem_ty)
799                 && blk.stmts.is_empty()
800                 && blk.rules == hir::BlockCheckMode::DefaultBlock
801             {
802                 let source_map = self.tcx.sess.source_map();
803                 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
804                     if snippet.starts_with('{') && snippet.ends_with('}') {
805                         diag.multipart_suggestion_verbose(
806                             "to create an array, use square brackets instead of curly braces",
807                             vec![
808                                 (
809                                     blk.span
810                                         .shrink_to_lo()
811                                         .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
812                                     "[".to_string(),
813                                 ),
814                                 (
815                                     blk.span
816                                         .shrink_to_hi()
817                                         .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
818                                     "]".to_string(),
819                                 ),
820                             ],
821                             Applicability::MachineApplicable,
822                         );
823                     }
824                 }
825             }
826         }
827     }
828
829     fn is_loop(&self, id: hir::HirId) -> bool {
830         let node = self.tcx.hir().get(id);
831         matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
832     }
833
834     fn is_local_statement(&self, id: hir::HirId) -> bool {
835         let node = self.tcx.hir().get(id);
836         matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
837     }
838
839     /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
840     /// which is a side-effect of autoref.
841     pub(crate) fn note_type_is_not_clone(
842         &self,
843         diag: &mut Diagnostic,
844         expected_ty: Ty<'tcx>,
845         found_ty: Ty<'tcx>,
846         expr: &hir::Expr<'_>,
847     ) {
848         let hir::ExprKind::MethodCall(segment, &[ref callee_expr], _) = expr.kind else { return; };
849         let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
850         let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
851         let results = self.typeck_results.borrow();
852         // First, look for a `Clone::clone` call
853         if segment.ident.name == sym::clone
854             && results.type_dependent_def_id(expr.hir_id).map_or(
855                 false,
856                 |did| {
857                     self.tcx.associated_item(did).container
858                         == ty::AssocItemContainer::TraitContainer(clone_trait_did)
859                 },
860             )
861             // If that clone call hasn't already dereferenced the self type (i.e. don't give this
862             // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
863             && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
864             // Check that we're in fact trying to clone into the expected type
865             && self.can_coerce(*pointee_ty, expected_ty)
866             // And the expected type doesn't implement `Clone`
867             && !self.predicate_must_hold_considering_regions(&traits::Obligation {
868                 cause: traits::ObligationCause::dummy(),
869                 param_env: self.param_env,
870                 recursion_depth: 0,
871                 predicate: ty::Binder::dummy(ty::TraitRef {
872                     def_id: clone_trait_did,
873                     substs: self.tcx.mk_substs([expected_ty.into()].iter()),
874                 })
875                 .without_const()
876                 .to_predicate(self.tcx),
877             })
878         {
879             diag.span_note(
880                 callee_expr.span,
881                 &format!(
882                     "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
883                 ),
884             );
885         }
886     }
887 }