]> git.lizzy.rs Git - rust.git/blob - src/librustc_trait_selection/traits/error_reporting/suggestions.rs
Auto merge of #71495 - Amanieu:update_stdarch, r=sfackler
[rust.git] / src / librustc_trait_selection / traits / error_reporting / suggestions.rs
1 use super::{
2     EvaluationResult, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation,
3 };
4
5 use crate::infer::InferCtxt;
6 use crate::traits::error_reporting::suggest_constraining_type_param;
7
8 use rustc_errors::{error_code, struct_span_err, Applicability, DiagnosticBuilder, Style};
9 use rustc_hir as hir;
10 use rustc_hir::def::DefKind;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit::Visitor;
13 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
14 use rustc_middle::ty::TypeckTables;
15 use rustc_middle::ty::{
16     self, AdtKind, DefIdTree, Infer, InferTy, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
17 };
18 use rustc_span::symbol::{kw, sym, Symbol};
19 use rustc_span::{MultiSpan, Span, DUMMY_SP};
20 use std::fmt;
21
22 use super::InferCtxtPrivExt;
23 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
24
25 // This trait is public to expose the diagnostics methods to clippy.
26 pub trait InferCtxtExt<'tcx> {
27     fn suggest_restricting_param_bound(
28         &self,
29         err: &mut DiagnosticBuilder<'_>,
30         trait_ref: ty::PolyTraitRef<'_>,
31         body_id: hir::HirId,
32     );
33
34     fn suggest_borrow_on_unsized_slice(
35         &self,
36         code: &ObligationCauseCode<'tcx>,
37         err: &mut DiagnosticBuilder<'tcx>,
38     );
39
40     fn get_closure_name(
41         &self,
42         def_id: DefId,
43         err: &mut DiagnosticBuilder<'_>,
44         msg: &str,
45     ) -> Option<String>;
46
47     fn suggest_fn_call(
48         &self,
49         obligation: &PredicateObligation<'tcx>,
50         err: &mut DiagnosticBuilder<'_>,
51         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
52         points_at_arg: bool,
53     );
54
55     fn suggest_add_reference_to_arg(
56         &self,
57         obligation: &PredicateObligation<'tcx>,
58         err: &mut DiagnosticBuilder<'tcx>,
59         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
60         points_at_arg: bool,
61         has_custom_message: bool,
62     ) -> bool;
63
64     fn suggest_remove_reference(
65         &self,
66         obligation: &PredicateObligation<'tcx>,
67         err: &mut DiagnosticBuilder<'tcx>,
68         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
69     );
70
71     fn suggest_change_mut(
72         &self,
73         obligation: &PredicateObligation<'tcx>,
74         err: &mut DiagnosticBuilder<'tcx>,
75         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
76         points_at_arg: bool,
77     );
78
79     fn suggest_semicolon_removal(
80         &self,
81         obligation: &PredicateObligation<'tcx>,
82         err: &mut DiagnosticBuilder<'tcx>,
83         span: Span,
84         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
85     );
86
87     fn suggest_impl_trait(
88         &self,
89         err: &mut DiagnosticBuilder<'tcx>,
90         span: Span,
91         obligation: &PredicateObligation<'tcx>,
92         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
93     ) -> bool;
94
95     fn point_at_returns_when_relevant(
96         &self,
97         err: &mut DiagnosticBuilder<'tcx>,
98         obligation: &PredicateObligation<'tcx>,
99     );
100
101     fn report_closure_arg_mismatch(
102         &self,
103         span: Span,
104         found_span: Option<Span>,
105         expected_ref: ty::PolyTraitRef<'tcx>,
106         found: ty::PolyTraitRef<'tcx>,
107     ) -> DiagnosticBuilder<'tcx>;
108
109     fn suggest_fully_qualified_path(
110         &self,
111         err: &mut DiagnosticBuilder<'_>,
112         def_id: DefId,
113         span: Span,
114         trait_ref: DefId,
115     );
116
117     fn maybe_note_obligation_cause_for_async_await(
118         &self,
119         err: &mut DiagnosticBuilder<'_>,
120         obligation: &PredicateObligation<'tcx>,
121     ) -> bool;
122
123     fn note_obligation_cause_for_async_await(
124         &self,
125         err: &mut DiagnosticBuilder<'_>,
126         target_span: Span,
127         scope_span: &Option<Span>,
128         await_span: Span,
129         expr: Option<hir::HirId>,
130         snippet: String,
131         inner_generator_body: Option<&hir::Body<'_>>,
132         outer_generator: Option<DefId>,
133         trait_ref: ty::TraitRef<'_>,
134         target_ty: Ty<'tcx>,
135         tables: &ty::TypeckTables<'_>,
136         obligation: &PredicateObligation<'tcx>,
137         next_code: Option<&ObligationCauseCode<'tcx>>,
138         from_awaited_ty: Option<Span>,
139     );
140
141     fn note_obligation_cause_code<T>(
142         &self,
143         err: &mut DiagnosticBuilder<'_>,
144         predicate: &T,
145         cause_code: &ObligationCauseCode<'tcx>,
146         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
147     ) where
148         T: fmt::Display;
149
150     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>);
151 }
152
153 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
154     (
155         generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
156         format!(
157             "{} {} ",
158             if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
159             pred,
160         ),
161     )
162 }
163
164 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
165 /// it can also be an `impl Trait` param that needs to be decomposed to a type
166 /// param for cleaner code.
167 fn suggest_restriction(
168     generics: &hir::Generics<'_>,
169     msg: &str,
170     err: &mut DiagnosticBuilder<'_>,
171     fn_sig: Option<&hir::FnSig<'_>>,
172     projection: Option<&ty::ProjectionTy<'_>>,
173     trait_ref: ty::PolyTraitRef<'_>,
174 ) {
175     let span = generics.where_clause.span_for_predicates_or_empty_place();
176     if span.from_expansion() || span.desugaring_kind().is_some() {
177         return;
178     }
179     // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
180     if let Some((bound_str, fn_sig)) =
181         fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind {
182             // Shenanigans to get the `Trait` from the `impl Trait`.
183             ty::Param(param) => {
184                 // `fn foo(t: impl Trait)`
185                 //                 ^^^^^ get this string
186                 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
187             }
188             _ => None,
189         })
190     {
191         // We know we have an `impl Trait` that doesn't satisfy a required projection.
192
193         // Find all of the ocurrences of `impl Trait` for `Trait` in the function arguments'
194         // types. There should be at least one, but there might be *more* than one. In that
195         // case we could just ignore it and try to identify which one needs the restriction,
196         // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
197         // where `T: Trait`.
198         let mut ty_spans = vec![];
199         let impl_trait_str = format!("impl {}", bound_str);
200         for input in fn_sig.decl.inputs {
201             if let hir::TyKind::Path(hir::QPath::Resolved(
202                 None,
203                 hir::Path { segments: [segment], .. },
204             )) = input.kind
205             {
206                 if segment.ident.as_str() == impl_trait_str.as_str() {
207                     // `fn foo(t: impl Trait)`
208                     //            ^^^^^^^^^^ get this to suggest `T` instead
209
210                     // There might be more than one `impl Trait`.
211                     ty_spans.push(input.span);
212                 }
213             }
214         }
215
216         let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
217         // The type param `T: Trait` we will suggest to introduce.
218         let type_param = format!("{}: {}", type_param_name, bound_str);
219
220         // FIXME: modify the `trait_ref` instead of string shenanigans.
221         // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
222         let pred = trait_ref.without_const().to_predicate().to_string();
223         let pred = pred.replace(&impl_trait_str, &type_param_name);
224         let mut sugg = vec![
225             match generics
226                 .params
227                 .iter()
228                 .filter(|p| match p.kind {
229                     hir::GenericParamKind::Type {
230                         synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
231                         ..
232                     } => false,
233                     _ => true,
234                 })
235                 .last()
236             {
237                 // `fn foo(t: impl Trait)`
238                 //        ^ suggest `<T: Trait>` here
239                 None => (generics.span, format!("<{}>", type_param)),
240                 // `fn foo<A>(t: impl Trait)`
241                 //        ^^^ suggest `<A, T: Trait>` here
242                 Some(param) => (
243                     param.bounds_span().unwrap_or(param.span).shrink_to_hi(),
244                     format!(", {}", type_param),
245                 ),
246             },
247             // `fn foo(t: impl Trait)`
248             //                       ^ suggest `where <T as Trait>::A: Bound`
249             predicate_constraint(generics, pred),
250         ];
251         sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
252
253         // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
254         // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
255         // `fn foo(t: impl Trait<A: Bound>)` instead.
256         err.multipart_suggestion(
257             "introduce a type parameter with a trait bound instead of using `impl Trait`",
258             sugg,
259             Applicability::MaybeIncorrect,
260         );
261     } else {
262         // Trivial case: `T` needs an extra bound: `T: Bound`.
263         let (sp, sugg) =
264             predicate_constraint(generics, trait_ref.without_const().to_predicate().to_string());
265         let appl = Applicability::MachineApplicable;
266         err.span_suggestion(sp, &format!("consider further restricting {}", msg), sugg, appl);
267     }
268 }
269
270 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
271     fn suggest_restricting_param_bound(
272         &self,
273         mut err: &mut DiagnosticBuilder<'_>,
274         trait_ref: ty::PolyTraitRef<'_>,
275         body_id: hir::HirId,
276     ) {
277         let self_ty = trait_ref.self_ty();
278         let (param_ty, projection) = match &self_ty.kind {
279             ty::Param(_) => (true, None),
280             ty::Projection(projection) => (false, Some(projection)),
281             _ => return,
282         };
283
284         // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
285         //        don't suggest `T: Sized + ?Sized`.
286         let mut hir_id = body_id;
287         while let Some(node) = self.tcx.hir().find(hir_id) {
288             match node {
289                 hir::Node::TraitItem(hir::TraitItem {
290                     generics,
291                     kind: hir::TraitItemKind::Fn(..),
292                     ..
293                 }) if param_ty && self_ty == self.tcx.types.self_param => {
294                     // Restricting `Self` for a single method.
295                     suggest_restriction(&generics, "`Self`", err, None, projection, trait_ref);
296                     return;
297                 }
298
299                 hir::Node::TraitItem(hir::TraitItem {
300                     generics,
301                     kind: hir::TraitItemKind::Fn(fn_sig, ..),
302                     ..
303                 })
304                 | hir::Node::ImplItem(hir::ImplItem {
305                     generics,
306                     kind: hir::ImplItemKind::Fn(fn_sig, ..),
307                     ..
308                 })
309                 | hir::Node::Item(hir::Item {
310                     kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
311                 }) if projection.is_some() => {
312                     // Missing restriction on associated type of type parameter (unmet projection).
313                     suggest_restriction(
314                         &generics,
315                         "the associated type",
316                         err,
317                         Some(fn_sig),
318                         projection,
319                         trait_ref,
320                     );
321                     return;
322                 }
323                 hir::Node::Item(hir::Item {
324                     kind:
325                         hir::ItemKind::Trait(_, _, generics, _, _)
326                         | hir::ItemKind::Impl { generics, .. },
327                     ..
328                 }) if projection.is_some() => {
329                     // Missing restriction on associated type of type parameter (unmet projection).
330                     suggest_restriction(
331                         &generics,
332                         "the associated type",
333                         err,
334                         None,
335                         projection,
336                         trait_ref,
337                     );
338                     return;
339                 }
340
341                 hir::Node::Item(hir::Item {
342                     kind:
343                         hir::ItemKind::Struct(_, generics)
344                         | hir::ItemKind::Enum(_, generics)
345                         | hir::ItemKind::Union(_, generics)
346                         | hir::ItemKind::Trait(_, _, generics, ..)
347                         | hir::ItemKind::Impl { generics, .. }
348                         | hir::ItemKind::Fn(_, generics, _)
349                         | hir::ItemKind::TyAlias(_, generics)
350                         | hir::ItemKind::TraitAlias(generics, _)
351                         | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
352                     ..
353                 })
354                 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
355                 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
356                     if param_ty =>
357                 {
358                     // Missing generic type parameter bound.
359                     let param_name = self_ty.to_string();
360                     let constraint = trait_ref.print_only_trait_path().to_string();
361                     if suggest_constraining_type_param(
362                         self.tcx,
363                         generics,
364                         &mut err,
365                         &param_name,
366                         &constraint,
367                         Some(trait_ref.def_id()),
368                     ) {
369                         return;
370                     }
371                 }
372
373                 hir::Node::Crate(..) => return,
374
375                 _ => {}
376             }
377
378             hir_id = self.tcx.hir().get_parent_item(hir_id);
379         }
380     }
381
382     /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
383     /// suggestion to borrow the initializer in order to use have a slice instead.
384     fn suggest_borrow_on_unsized_slice(
385         &self,
386         code: &ObligationCauseCode<'tcx>,
387         err: &mut DiagnosticBuilder<'tcx>,
388     ) {
389         if let &ObligationCauseCode::VariableType(hir_id) = code {
390             let parent_node = self.tcx.hir().get_parent_node(hir_id);
391             if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
392                 if let Some(ref expr) = local.init {
393                     if let hir::ExprKind::Index(_, _) = expr.kind {
394                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
395                             err.span_suggestion(
396                                 expr.span,
397                                 "consider borrowing here",
398                                 format!("&{}", snippet),
399                                 Applicability::MachineApplicable,
400                             );
401                         }
402                     }
403                 }
404             }
405         }
406     }
407
408     /// Given a closure's `DefId`, return the given name of the closure.
409     ///
410     /// This doesn't account for reassignments, but it's only used for suggestions.
411     fn get_closure_name(
412         &self,
413         def_id: DefId,
414         err: &mut DiagnosticBuilder<'_>,
415         msg: &str,
416     ) -> Option<String> {
417         let get_name =
418             |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
419                 // Get the local name of this closure. This can be inaccurate because
420                 // of the possibility of reassignment, but this should be good enough.
421                 match &kind {
422                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
423                         Some(format!("{}", name))
424                     }
425                     _ => {
426                         err.note(&msg);
427                         None
428                     }
429                 }
430             };
431
432         let hir = self.tcx.hir();
433         let hir_id = hir.as_local_hir_id(def_id.as_local()?);
434         let parent_node = hir.get_parent_node(hir_id);
435         match hir.find(parent_node) {
436             Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
437                 get_name(err, &local.pat.kind)
438             }
439             // Different to previous arm because one is `&hir::Local` and the other
440             // is `P<hir::Local>`.
441             Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
442             _ => None,
443         }
444     }
445
446     /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
447     /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
448     /// it: `bar(foo)` â†’ `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
449     fn suggest_fn_call(
450         &self,
451         obligation: &PredicateObligation<'tcx>,
452         err: &mut DiagnosticBuilder<'_>,
453         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
454         points_at_arg: bool,
455     ) {
456         let self_ty = trait_ref.self_ty();
457         let (def_id, output_ty, callable) = match self_ty.kind {
458             ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
459             ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
460             _ => return,
461         };
462         let msg = format!("use parentheses to call the {}", callable);
463
464         let obligation = self.mk_obligation_for_def_id(
465             trait_ref.def_id(),
466             output_ty.skip_binder(),
467             obligation.cause.clone(),
468             obligation.param_env,
469         );
470
471         match self.evaluate_obligation(&obligation) {
472             Ok(
473                 EvaluationResult::EvaluatedToOk
474                 | EvaluationResult::EvaluatedToOkModuloRegions
475                 | EvaluationResult::EvaluatedToAmbig,
476             ) => {}
477             _ => return,
478         }
479         let hir = self.tcx.hir();
480         // Get the name of the callable and the arguments to be used in the suggestion.
481         let (snippet, sugg) = match hir.get_if_local(def_id) {
482             Some(hir::Node::Expr(hir::Expr {
483                 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
484                 ..
485             })) => {
486                 err.span_label(*span, "consider calling this closure");
487                 let name = match self.get_closure_name(def_id, err, &msg) {
488                     Some(name) => name,
489                     None => return,
490                 };
491                 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
492                 let sugg = format!("({})", args);
493                 (format!("{}{}", name, sugg), sugg)
494             }
495             Some(hir::Node::Item(hir::Item {
496                 ident,
497                 kind: hir::ItemKind::Fn(.., body_id),
498                 ..
499             })) => {
500                 err.span_label(ident.span, "consider calling this function");
501                 let body = hir.body(*body_id);
502                 let args = body
503                     .params
504                     .iter()
505                     .map(|arg| match &arg.pat.kind {
506                         hir::PatKind::Binding(_, _, ident, None)
507                         // FIXME: provide a better suggestion when encountering `SelfLower`, it
508                         // should suggest a method call.
509                         if ident.name != kw::SelfLower => ident.to_string(),
510                         _ => "_".to_string(),
511                     })
512                     .collect::<Vec<_>>()
513                     .join(", ");
514                 let sugg = format!("({})", args);
515                 (format!("{}{}", ident, sugg), sugg)
516             }
517             _ => return,
518         };
519         if points_at_arg {
520             // When the obligation error has been ensured to have been caused by
521             // an argument, the `obligation.cause.span` points at the expression
522             // of the argument, so we can provide a suggestion. This is signaled
523             // by `points_at_arg`. Otherwise, we give a more general note.
524             err.span_suggestion_verbose(
525                 obligation.cause.span.shrink_to_hi(),
526                 &msg,
527                 sugg,
528                 Applicability::HasPlaceholders,
529             );
530         } else {
531             err.help(&format!("{}: `{}`", msg, snippet));
532         }
533     }
534
535     fn suggest_add_reference_to_arg(
536         &self,
537         obligation: &PredicateObligation<'tcx>,
538         err: &mut DiagnosticBuilder<'tcx>,
539         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
540         points_at_arg: bool,
541         has_custom_message: bool,
542     ) -> bool {
543         if !points_at_arg {
544             return false;
545         }
546
547         let span = obligation.cause.span;
548         let param_env = obligation.param_env;
549         let trait_ref = trait_ref.skip_binder();
550
551         if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
552             // Try to apply the original trait binding obligation by borrowing.
553             let self_ty = trait_ref.self_ty();
554             let found = self_ty.to_string();
555             let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
556             let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
557             let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
558             let new_obligation = Obligation::new(
559                 ObligationCause::dummy(),
560                 param_env,
561                 new_trait_ref.without_const().to_predicate(),
562             );
563             if self.predicate_must_hold_modulo_regions(&new_obligation) {
564                 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
565                     // We have a very specific type of error, where just borrowing this argument
566                     // might solve the problem. In cases like this, the important part is the
567                     // original type obligation, not the last one that failed, which is arbitrary.
568                     // Because of this, we modify the error to refer to the original obligation and
569                     // return early in the caller.
570                     let msg = format!(
571                         "the trait bound `{}: {}` is not satisfied",
572                         found,
573                         obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
574                     );
575                     if has_custom_message {
576                         err.note(&msg);
577                     } else {
578                         err.message = vec![(msg, Style::NoStyle)];
579                     }
580                     if snippet.starts_with('&') {
581                         // This is already a literal borrow and the obligation is failing
582                         // somewhere else in the obligation chain. Do not suggest non-sense.
583                         return false;
584                     }
585                     err.span_label(
586                         span,
587                         &format!(
588                             "expected an implementor of trait `{}`",
589                             obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
590                         ),
591                     );
592                     err.span_suggestion(
593                         span,
594                         "consider borrowing here",
595                         format!("&{}", snippet),
596                         Applicability::MaybeIncorrect,
597                     );
598                     return true;
599                 }
600             }
601         }
602         false
603     }
604
605     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
606     /// suggest removing these references until we reach a type that implements the trait.
607     fn suggest_remove_reference(
608         &self,
609         obligation: &PredicateObligation<'tcx>,
610         err: &mut DiagnosticBuilder<'tcx>,
611         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
612     ) {
613         let trait_ref = trait_ref.skip_binder();
614         let span = obligation.cause.span;
615
616         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
617             let refs_number =
618                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
619             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
620                 // Do not suggest removal of borrow from type arguments.
621                 return;
622             }
623
624             let mut trait_type = trait_ref.self_ty();
625
626             for refs_remaining in 0..refs_number {
627                 if let ty::Ref(_, t_type, _) = trait_type.kind {
628                     trait_type = t_type;
629
630                     let new_obligation = self.mk_obligation_for_def_id(
631                         trait_ref.def_id,
632                         trait_type,
633                         ObligationCause::dummy(),
634                         obligation.param_env,
635                     );
636
637                     if self.predicate_may_hold(&new_obligation) {
638                         let sp = self
639                             .tcx
640                             .sess
641                             .source_map()
642                             .span_take_while(span, |c| c.is_whitespace() || *c == '&');
643
644                         let remove_refs = refs_remaining + 1;
645
646                         let msg = if remove_refs == 1 {
647                             "consider removing the leading `&`-reference".to_string()
648                         } else {
649                             format!("consider removing {} leading `&`-references", remove_refs)
650                         };
651
652                         err.span_suggestion_short(
653                             sp,
654                             &msg,
655                             String::new(),
656                             Applicability::MachineApplicable,
657                         );
658                         break;
659                     }
660                 } else {
661                     break;
662                 }
663             }
664         }
665     }
666
667     /// Check if the trait bound is implemented for a different mutability and note it in the
668     /// final error.
669     fn suggest_change_mut(
670         &self,
671         obligation: &PredicateObligation<'tcx>,
672         err: &mut DiagnosticBuilder<'tcx>,
673         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
674         points_at_arg: bool,
675     ) {
676         let span = obligation.cause.span;
677         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
678             let refs_number =
679                 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
680             if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
681                 // Do not suggest removal of borrow from type arguments.
682                 return;
683             }
684             let trait_ref = self.resolve_vars_if_possible(trait_ref);
685             if trait_ref.has_infer_types_or_consts() {
686                 // Do not ICE while trying to find if a reborrow would succeed on a trait with
687                 // unresolved bindings.
688                 return;
689             }
690
691             if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
692                 let trait_type = match mutability {
693                     hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
694                     hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
695                 };
696
697                 let new_obligation = self.mk_obligation_for_def_id(
698                     trait_ref.skip_binder().def_id,
699                     trait_type,
700                     ObligationCause::dummy(),
701                     obligation.param_env,
702                 );
703
704                 if self.evaluate_obligation_no_overflow(&new_obligation).must_apply_modulo_regions()
705                 {
706                     let sp = self
707                         .tcx
708                         .sess
709                         .source_map()
710                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
711                     if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
712                         err.span_suggestion_verbose(
713                             sp,
714                             "consider changing this borrow's mutability",
715                             "&mut ".to_string(),
716                             Applicability::MachineApplicable,
717                         );
718                     } else {
719                         err.note(&format!(
720                             "`{}` is implemented for `{:?}`, but not for `{:?}`",
721                             trait_ref.print_only_trait_path(),
722                             trait_type,
723                             trait_ref.skip_binder().self_ty(),
724                         ));
725                     }
726                 }
727             }
728         }
729     }
730
731     fn suggest_semicolon_removal(
732         &self,
733         obligation: &PredicateObligation<'tcx>,
734         err: &mut DiagnosticBuilder<'tcx>,
735         span: Span,
736         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
737     ) {
738         let hir = self.tcx.hir();
739         let parent_node = hir.get_parent_node(obligation.cause.body_id);
740         let node = hir.find(parent_node);
741         if let Some(hir::Node::Item(hir::Item {
742             kind: hir::ItemKind::Fn(sig, _, body_id), ..
743         })) = node
744         {
745             let body = hir.body(*body_id);
746             if let hir::ExprKind::Block(blk, _) = &body.value.kind {
747                 if sig.decl.output.span().overlaps(span)
748                     && blk.expr.is_none()
749                     && "()" == &trait_ref.self_ty().to_string()
750                 {
751                     // FIXME(estebank): When encountering a method with a trait
752                     // bound not satisfied in the return type with a body that has
753                     // no return, suggest removal of semicolon on last statement.
754                     // Once that is added, close #54771.
755                     if let Some(ref stmt) = blk.stmts.last() {
756                         let sp = self.tcx.sess.source_map().end_point(stmt.span);
757                         err.span_label(sp, "consider removing this semicolon");
758                     }
759                 }
760             }
761         }
762     }
763
764     /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
765     /// applicable and signal that the error has been expanded appropriately and needs to be
766     /// emitted.
767     fn suggest_impl_trait(
768         &self,
769         err: &mut DiagnosticBuilder<'tcx>,
770         span: Span,
771         obligation: &PredicateObligation<'tcx>,
772         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
773     ) -> bool {
774         match obligation.cause.code.peel_derives() {
775             // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
776             ObligationCauseCode::SizedReturnType => {}
777             _ => return false,
778         }
779
780         let hir = self.tcx.hir();
781         let parent_node = hir.get_parent_node(obligation.cause.body_id);
782         let node = hir.find(parent_node);
783         let (sig, body_id) = if let Some(hir::Node::Item(hir::Item {
784             kind: hir::ItemKind::Fn(sig, _, body_id),
785             ..
786         })) = node
787         {
788             (sig, body_id)
789         } else {
790             return false;
791         };
792         let body = hir.body(*body_id);
793         let trait_ref = self.resolve_vars_if_possible(trait_ref);
794         let ty = trait_ref.skip_binder().self_ty();
795         let is_object_safe = match ty.kind {
796             ty::Dynamic(predicates, _) => {
797                 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
798                 predicates
799                     .principal_def_id()
800                     .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
801             }
802             // We only want to suggest `impl Trait` to `dyn Trait`s.
803             // For example, `fn foo() -> str` needs to be filtered out.
804             _ => return false,
805         };
806
807         let ret_ty = if let hir::FnRetTy::Return(ret_ty) = sig.decl.output {
808             ret_ty
809         } else {
810             return false;
811         };
812
813         // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
814         // cases like `fn foo() -> (dyn Trait, i32) {}`.
815         // Recursively look for `TraitObject` types and if there's only one, use that span to
816         // suggest `impl Trait`.
817
818         // Visit to make sure there's a single `return` type to suggest `impl Trait`,
819         // otherwise suggest using `Box<dyn Trait>` or an enum.
820         let mut visitor = ReturnsVisitor::default();
821         visitor.visit_body(&body);
822
823         let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
824
825         let mut ret_types = visitor
826             .returns
827             .iter()
828             .filter_map(|expr| tables.node_type_opt(expr.hir_id))
829             .map(|ty| self.resolve_vars_if_possible(&ty));
830         let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
831             (None, true, true),
832             |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
833              ty| {
834                 let ty = self.resolve_vars_if_possible(&ty);
835                 same &=
836                     ty.kind != ty::Error
837                         && last_ty.map_or(true, |last_ty| {
838                             // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
839                             // *after* in the dependency graph.
840                             match (&ty.kind, &last_ty.kind) {
841                                 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
842                                 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
843                                 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
844                                 | (
845                                     Infer(InferTy::FreshFloatTy(_)),
846                                     Infer(InferTy::FreshFloatTy(_)),
847                                 ) => true,
848                                 _ => ty == last_ty,
849                             }
850                         });
851                 (Some(ty), same, only_never_return && matches!(ty.kind, ty::Never))
852             },
853         );
854         let all_returns_conform_to_trait =
855             if let Some(ty_ret_ty) = tables.node_type_opt(ret_ty.hir_id) {
856                 match ty_ret_ty.kind {
857                     ty::Dynamic(predicates, _) => {
858                         let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
859                         let param_env = ty::ParamEnv::empty();
860                         only_never_return
861                             || ret_types.all(|returned_ty| {
862                                 predicates.iter().all(|predicate| {
863                                     let pred = predicate.with_self_ty(self.tcx, returned_ty);
864                                     let obl = Obligation::new(cause.clone(), param_env, pred);
865                                     self.predicate_may_hold(&obl)
866                                 })
867                             })
868                     }
869                     _ => false,
870                 }
871             } else {
872                 true
873             };
874
875         let sm = self.tcx.sess.source_map();
876         let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
877             // Verify that we're dealing with a return `dyn Trait`
878             ret_ty.span.overlaps(span),
879             &ret_ty.kind,
880             sm.span_to_snippet(ret_ty.span),
881             // If any of the return types does not conform to the trait, then we can't
882             // suggest `impl Trait` nor trait objects: it is a type mismatch error.
883             all_returns_conform_to_trait,
884         ) {
885             snippet
886         } else {
887             return false;
888         };
889         err.code(error_code!(E0746));
890         err.set_primary_message("return type cannot have an unboxed trait object");
891         err.children.clear();
892         let impl_trait_msg = "for information on `impl Trait`, see \
893             <https://doc.rust-lang.org/book/ch10-02-traits.html\
894             #returning-types-that-implement-traits>";
895         let trait_obj_msg = "for information on trait objects, see \
896             <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
897             #using-trait-objects-that-allow-for-values-of-different-types>";
898         let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
899         let trait_obj = if has_dyn { &snippet[4..] } else { &snippet[..] };
900         if only_never_return {
901             // No return paths, probably using `panic!()` or similar.
902             // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
903             suggest_trait_object_return_type_alternatives(
904                 err,
905                 ret_ty.span,
906                 trait_obj,
907                 is_object_safe,
908             );
909         } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
910             // Suggest `-> impl Trait`.
911             err.span_suggestion(
912                 ret_ty.span,
913                 &format!(
914                     "use `impl {1}` as the return type, as all return paths are of type `{}`, \
915                      which implements `{1}`",
916                     last_ty, trait_obj,
917                 ),
918                 format!("impl {}", trait_obj),
919                 Applicability::MachineApplicable,
920             );
921             err.note(impl_trait_msg);
922         } else {
923             if is_object_safe {
924                 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
925                 // Get all the return values and collect their span and suggestion.
926                 if let Some(mut suggestions) = visitor
927                     .returns
928                     .iter()
929                     .map(|expr| {
930                         let snip = sm.span_to_snippet(expr.span).ok()?;
931                         Some((expr.span, format!("Box::new({})", snip)))
932                     })
933                     .collect::<Option<Vec<_>>>()
934                 {
935                     // Add the suggestion for the return type.
936                     suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
937                     err.multipart_suggestion(
938                         "return a boxed trait object instead",
939                         suggestions,
940                         Applicability::MaybeIncorrect,
941                     );
942                 }
943             } else {
944                 // This is currently not possible to trigger because E0038 takes precedence, but
945                 // leave it in for completeness in case anything changes in an earlier stage.
946                 err.note(&format!(
947                     "if trait `{}` was object safe, you could return a trait object",
948                     trait_obj,
949                 ));
950             }
951             err.note(trait_obj_msg);
952             err.note(&format!(
953                 "if all the returned values were of the same type you could use `impl {}` as the \
954                  return type",
955                 trait_obj,
956             ));
957             err.note(impl_trait_msg);
958             err.note("you can create a new `enum` with a variant for each returned type");
959         }
960         true
961     }
962
963     fn point_at_returns_when_relevant(
964         &self,
965         err: &mut DiagnosticBuilder<'tcx>,
966         obligation: &PredicateObligation<'tcx>,
967     ) {
968         match obligation.cause.code.peel_derives() {
969             ObligationCauseCode::SizedReturnType => {}
970             _ => return,
971         }
972
973         let hir = self.tcx.hir();
974         let parent_node = hir.get_parent_node(obligation.cause.body_id);
975         let node = hir.find(parent_node);
976         if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
977             node
978         {
979             let body = hir.body(*body_id);
980             // Point at all the `return`s in the function as they have failed trait bounds.
981             let mut visitor = ReturnsVisitor::default();
982             visitor.visit_body(&body);
983             let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
984             for expr in &visitor.returns {
985                 if let Some(returned_ty) = tables.node_type_opt(expr.hir_id) {
986                     let ty = self.resolve_vars_if_possible(&returned_ty);
987                     err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
988                 }
989             }
990         }
991     }
992
993     fn report_closure_arg_mismatch(
994         &self,
995         span: Span,
996         found_span: Option<Span>,
997         expected_ref: ty::PolyTraitRef<'tcx>,
998         found: ty::PolyTraitRef<'tcx>,
999     ) -> DiagnosticBuilder<'tcx> {
1000         crate fn build_fn_sig_string<'tcx>(
1001             tcx: TyCtxt<'tcx>,
1002             trait_ref: &ty::TraitRef<'tcx>,
1003         ) -> String {
1004             let inputs = trait_ref.substs.type_at(1);
1005             let sig = if let ty::Tuple(inputs) = inputs.kind {
1006                 tcx.mk_fn_sig(
1007                     inputs.iter().map(|k| k.expect_ty()),
1008                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1009                     false,
1010                     hir::Unsafety::Normal,
1011                     ::rustc_target::spec::abi::Abi::Rust,
1012                 )
1013             } else {
1014                 tcx.mk_fn_sig(
1015                     ::std::iter::once(inputs),
1016                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1017                     false,
1018                     hir::Unsafety::Normal,
1019                     ::rustc_target::spec::abi::Abi::Rust,
1020                 )
1021             };
1022             ty::Binder::bind(sig).to_string()
1023         }
1024
1025         let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1026         let mut err = struct_span_err!(
1027             self.tcx.sess,
1028             span,
1029             E0631,
1030             "type mismatch in {} arguments",
1031             if argument_is_closure { "closure" } else { "function" }
1032         );
1033
1034         let found_str = format!(
1035             "expected signature of `{}`",
1036             build_fn_sig_string(self.tcx, found.skip_binder())
1037         );
1038         err.span_label(span, found_str);
1039
1040         let found_span = found_span.unwrap_or(span);
1041         let expected_str = format!(
1042             "found signature of `{}`",
1043             build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1044         );
1045         err.span_label(found_span, expected_str);
1046
1047         err
1048     }
1049
1050     fn suggest_fully_qualified_path(
1051         &self,
1052         err: &mut DiagnosticBuilder<'_>,
1053         def_id: DefId,
1054         span: Span,
1055         trait_ref: DefId,
1056     ) {
1057         if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1058             if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1059                 err.note(&format!(
1060                     "{}s cannot be accessed directly on a `trait`, they can only be \
1061                         accessed through a specific `impl`",
1062                     assoc_item.kind.as_def_kind().descr(def_id)
1063                 ));
1064                 err.span_suggestion(
1065                     span,
1066                     "use the fully qualified path to an implementation",
1067                     format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1068                     Applicability::HasPlaceholders,
1069                 );
1070             }
1071         }
1072     }
1073
1074     /// Adds an async-await specific note to the diagnostic when the future does not implement
1075     /// an auto trait because of a captured type.
1076     ///
1077     /// ```text
1078     /// note: future does not implement `Qux` as this value is used across an await
1079     ///   --> $DIR/issue-64130-3-other.rs:17:5
1080     ///    |
1081     /// LL |     let x = Foo;
1082     ///    |         - has type `Foo`
1083     /// LL |     baz().await;
1084     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1085     /// LL | }
1086     ///    | - `x` is later dropped here
1087     /// ```
1088     ///
1089     /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1090     /// is "replaced" with a different message and a more specific error.
1091     ///
1092     /// ```text
1093     /// error: future cannot be sent between threads safely
1094     ///   --> $DIR/issue-64130-2-send.rs:21:5
1095     ///    |
1096     /// LL | fn is_send<T: Send>(t: T) { }
1097     ///    |               ---- required by this bound in `is_send`
1098     /// ...
1099     /// LL |     is_send(bar());
1100     ///    |     ^^^^^^^ future returned by `bar` is not send
1101     ///    |
1102     ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1103     ///            implemented for `Foo`
1104     /// note: future is not send as this value is used across an await
1105     ///   --> $DIR/issue-64130-2-send.rs:15:5
1106     ///    |
1107     /// LL |     let x = Foo;
1108     ///    |         - has type `Foo`
1109     /// LL |     baz().await;
1110     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1111     /// LL | }
1112     ///    | - `x` is later dropped here
1113     /// ```
1114     ///
1115     /// Returns `true` if an async-await specific note was added to the diagnostic.
1116     fn maybe_note_obligation_cause_for_async_await(
1117         &self,
1118         err: &mut DiagnosticBuilder<'_>,
1119         obligation: &PredicateObligation<'tcx>,
1120     ) -> bool {
1121         debug!(
1122             "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1123                 obligation.cause.span={:?}",
1124             obligation.predicate, obligation.cause.span
1125         );
1126         let source_map = self.tcx.sess.source_map();
1127         let hir = self.tcx.hir();
1128
1129         // Attempt to detect an async-await error by looking at the obligation causes, looking
1130         // for a generator to be present.
1131         //
1132         // When a future does not implement a trait because of a captured type in one of the
1133         // generators somewhere in the call stack, then the result is a chain of obligations.
1134         //
1135         // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
1136         // future is passed as an argument to a function C which requires a `Send` type, then the
1137         // chain looks something like this:
1138         //
1139         // - `BuiltinDerivedObligation` with a generator witness (B)
1140         // - `BuiltinDerivedObligation` with a generator (B)
1141         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1142         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1143         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1144         // - `BuiltinDerivedObligation` with a generator witness (A)
1145         // - `BuiltinDerivedObligation` with a generator (A)
1146         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1147         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1148         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1149         // - `BindingObligation` with `impl_send (Send requirement)
1150         //
1151         // The first obligation in the chain is the most useful and has the generator that captured
1152         // the type. The last generator (`outer_generator` below) has information about where the
1153         // bound was introduced. At least one generator should be present for this diagnostic to be
1154         // modified.
1155         let (mut trait_ref, mut target_ty) = match obligation.predicate {
1156             ty::Predicate::Trait(p, _) => {
1157                 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty()))
1158             }
1159             _ => (None, None),
1160         };
1161         let mut generator = None;
1162         let mut outer_generator = None;
1163         let mut next_code = Some(&obligation.cause.code);
1164         while let Some(code) = next_code {
1165             debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1166             match code {
1167                 ObligationCauseCode::DerivedObligation(derived_obligation)
1168                 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1169                 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1170                     let ty = derived_obligation.parent_trait_ref.self_ty();
1171                     debug!(
1172                         "maybe_note_obligation_cause_for_async_await: \
1173                             parent_trait_ref={:?} self_ty.kind={:?}",
1174                         derived_obligation.parent_trait_ref, ty.kind
1175                     );
1176
1177                     match ty.kind {
1178                         ty::Generator(did, ..) => {
1179                             generator = generator.or(Some(did));
1180                             outer_generator = Some(did);
1181                         }
1182                         ty::GeneratorWitness(..) => {}
1183                         _ if generator.is_none() => {
1184                             trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
1185                             target_ty = Some(ty);
1186                         }
1187                         _ => {}
1188                     }
1189
1190                     next_code = Some(derived_obligation.parent_code.as_ref());
1191                 }
1192                 _ => break,
1193             }
1194         }
1195
1196         // Only continue if a generator was found.
1197         debug!(
1198             "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
1199                 target_ty={:?}",
1200             generator, trait_ref, target_ty
1201         );
1202         let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1203             (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1204                 (generator_did, trait_ref, target_ty)
1205             }
1206             _ => return false,
1207         };
1208
1209         let span = self.tcx.def_span(generator_did);
1210
1211         // Do not ICE on closure typeck (#66868).
1212         if !generator_did.is_local() {
1213             return false;
1214         }
1215
1216         // Get the tables from the infcx if the generator is the function we are
1217         // currently type-checking; otherwise, get them by performing a query.
1218         // This is needed to avoid cycles.
1219         let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
1220         let generator_did_root = self.tcx.closure_base_def_id(generator_did);
1221         debug!(
1222             "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1223              generator_did_root={:?} in_progress_tables.hir_owner={:?} span={:?}",
1224             generator_did,
1225             generator_did_root,
1226             in_progress_tables.as_ref().map(|t| t.hir_owner),
1227             span
1228         );
1229         let query_tables;
1230         let tables: &TypeckTables<'tcx> = match &in_progress_tables {
1231             Some(t) if t.hir_owner.map(|owner| owner.to_def_id()) == Some(generator_did_root) => t,
1232             _ => {
1233                 query_tables = self.tcx.typeck_tables_of(generator_did);
1234                 &query_tables
1235             }
1236         };
1237
1238         let generator_body = generator_did
1239             .as_local()
1240             .map(|def_id| hir.as_local_hir_id(def_id))
1241             .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1242             .map(|body_id| hir.body(body_id));
1243         let mut visitor = AwaitsVisitor::default();
1244         if let Some(body) = generator_body {
1245             visitor.visit_body(body);
1246         }
1247         debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1248
1249         // Look for a type inside the generator interior that matches the target type to get
1250         // a span.
1251         let target_ty_erased = self.tcx.erase_regions(&target_ty);
1252         let ty_matches = |ty| -> bool {
1253             // Careful: the regions for types that appear in the
1254             // generator interior are not generally known, so we
1255             // want to erase them when comparing (and anyway,
1256             // `Send` and other bounds are generally unaffected by
1257             // the choice of region).  When erasing regions, we
1258             // also have to erase late-bound regions. This is
1259             // because the types that appear in the generator
1260             // interior generally contain "bound regions" to
1261             // represent regions that are part of the suspended
1262             // generator frame. Bound regions are preserved by
1263             // `erase_regions` and so we must also call
1264             // `erase_late_bound_regions`.
1265             let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(ty));
1266             let ty_erased = self.tcx.erase_regions(&ty_erased);
1267             let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1268             debug!(
1269                 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1270                     target_ty_erased={:?} eq={:?}",
1271                 ty_erased, target_ty_erased, eq
1272             );
1273             eq
1274         };
1275         let target_span = tables
1276             .generator_interior_types
1277             .iter()
1278             .find(|ty::GeneratorInteriorTypeCause { ty, .. }| ty_matches(ty))
1279             .map(|cause| {
1280                 // Check to see if any awaited expressions have the target type.
1281                 let from_awaited_ty = visitor
1282                     .awaits
1283                     .into_iter()
1284                     .map(|id| hir.expect_expr(id))
1285                     .find(|await_expr| {
1286                         let ty = tables.expr_ty_adjusted(&await_expr);
1287                         debug!(
1288                             "maybe_note_obligation_cause_for_async_await: await_expr={:?}",
1289                             await_expr
1290                         );
1291                         ty_matches(ty)
1292                     })
1293                     .map(|expr| expr.span);
1294                 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1295                     cause;
1296                 (
1297                     span,
1298                     source_map.span_to_snippet(*span),
1299                     scope_span,
1300                     yield_span,
1301                     expr,
1302                     from_awaited_ty,
1303                 )
1304             });
1305
1306         debug!(
1307             "maybe_note_obligation_cause_for_async_await: target_ty={:?} \
1308                 generator_interior_types={:?} target_span={:?}",
1309             target_ty, tables.generator_interior_types, target_span
1310         );
1311         if let Some((target_span, Ok(snippet), scope_span, yield_span, expr, from_awaited_ty)) =
1312             target_span
1313         {
1314             self.note_obligation_cause_for_async_await(
1315                 err,
1316                 *target_span,
1317                 scope_span,
1318                 *yield_span,
1319                 *expr,
1320                 snippet,
1321                 generator_body,
1322                 outer_generator,
1323                 trait_ref,
1324                 target_ty,
1325                 tables,
1326                 obligation,
1327                 next_code,
1328                 from_awaited_ty,
1329             );
1330             true
1331         } else {
1332             false
1333         }
1334     }
1335
1336     /// Unconditionally adds the diagnostic note described in
1337     /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1338     fn note_obligation_cause_for_async_await(
1339         &self,
1340         err: &mut DiagnosticBuilder<'_>,
1341         target_span: Span,
1342         scope_span: &Option<Span>,
1343         yield_span: Span,
1344         expr: Option<hir::HirId>,
1345         snippet: String,
1346         inner_generator_body: Option<&hir::Body<'_>>,
1347         outer_generator: Option<DefId>,
1348         trait_ref: ty::TraitRef<'_>,
1349         target_ty: Ty<'tcx>,
1350         tables: &ty::TypeckTables<'_>,
1351         obligation: &PredicateObligation<'tcx>,
1352         next_code: Option<&ObligationCauseCode<'tcx>>,
1353         from_awaited_ty: Option<Span>,
1354     ) {
1355         let source_map = self.tcx.sess.source_map();
1356
1357         let is_async = inner_generator_body
1358             .and_then(|body| body.generator_kind())
1359             .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1360             .unwrap_or(false);
1361         let (await_or_yield, an_await_or_yield) =
1362             if is_async { ("await", "an await") } else { ("yield", "a yield") };
1363         let future_or_generator = if is_async { "future" } else { "generator" };
1364
1365         // Special case the primary error message when send or sync is the trait that was
1366         // not implemented.
1367         let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
1368         let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
1369         let hir = self.tcx.hir();
1370         let trait_explanation = if is_send || is_sync {
1371             let (trait_name, trait_verb) =
1372                 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1373
1374             err.clear_code();
1375             err.set_primary_message(format!(
1376                 "{} cannot be {} between threads safely",
1377                 future_or_generator, trait_verb
1378             ));
1379
1380             let original_span = err.span.primary_span().unwrap();
1381             let mut span = MultiSpan::from_span(original_span);
1382
1383             let message = outer_generator
1384                 .and_then(|generator_did| {
1385                     Some(match self.tcx.generator_kind(generator_did).unwrap() {
1386                         GeneratorKind::Gen => format!("generator is not {}", trait_name),
1387                         GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1388                             .tcx
1389                             .parent(generator_did)
1390                             .and_then(|parent_did| parent_did.as_local())
1391                             .map(|parent_did| hir.as_local_hir_id(parent_did))
1392                             .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1393                             .map(|name| {
1394                                 format!("future returned by `{}` is not {}", name, trait_name)
1395                             })?,
1396                         GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1397                             format!("future created by async block is not {}", trait_name)
1398                         }
1399                         GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1400                             format!("future created by async closure is not {}", trait_name)
1401                         }
1402                     })
1403                 })
1404                 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1405
1406             span.push_span_label(original_span, message);
1407             err.set_span(span);
1408
1409             format!("is not {}", trait_name)
1410         } else {
1411             format!("does not implement `{}`", trait_ref.print_only_trait_path())
1412         };
1413
1414         if let Some(await_span) = from_awaited_ty {
1415             // The type causing this obligation is one being awaited at await_span.
1416             let mut span = MultiSpan::from_span(await_span);
1417
1418             span.push_span_label(
1419                 await_span,
1420                 format!("await occurs here on type `{}`, which {}", target_ty, trait_explanation),
1421             );
1422
1423             err.span_note(
1424                 span,
1425                 &format!(
1426                     "future {not_trait} as it awaits another future which {not_trait}",
1427                     not_trait = trait_explanation
1428                 ),
1429             );
1430         } else {
1431             // Look at the last interior type to get a span for the `.await`.
1432             debug!(
1433                 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1434                 tables.generator_interior_types
1435             );
1436             let mut span = MultiSpan::from_span(yield_span);
1437             span.push_span_label(
1438                 yield_span,
1439                 format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
1440             );
1441
1442             span.push_span_label(
1443                 target_span,
1444                 format!("has type `{}` which {}", target_ty, trait_explanation),
1445             );
1446
1447             // If available, use the scope span to annotate the drop location.
1448             if let Some(scope_span) = scope_span {
1449                 span.push_span_label(
1450                     source_map.end_point(*scope_span),
1451                     format!("`{}` is later dropped here", snippet),
1452                 );
1453             }
1454
1455             err.span_note(
1456                 span,
1457                 &format!(
1458                     "{} {} as this value is used across {}",
1459                     future_or_generator, trait_explanation, an_await_or_yield
1460                 ),
1461             );
1462         }
1463
1464         if let Some(expr_id) = expr {
1465             let expr = hir.expect_expr(expr_id);
1466             debug!("target_ty evaluated from {:?}", expr);
1467
1468             let parent = hir.get_parent_node(expr_id);
1469             if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1470                 let parent_span = hir.span(parent);
1471                 let parent_did = parent.owner.to_def_id();
1472                 // ```rust
1473                 // impl T {
1474                 //     fn foo(&self) -> i32 {}
1475                 // }
1476                 // T.foo();
1477                 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1478                 // ```
1479                 //
1480                 let is_region_borrow =
1481                     tables.expr_adjustments(expr).iter().any(|adj| adj.is_region_borrow());
1482
1483                 // ```rust
1484                 // struct Foo(*const u8);
1485                 // bar(Foo(std::ptr::null())).await;
1486                 //     ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1487                 // ```
1488                 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1489                 let is_raw_borrow_inside_fn_like_call = match self.tcx.def_kind(parent_did) {
1490                     DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
1491                     _ => false,
1492                 };
1493
1494                 if (tables.is_method_call(e) && is_region_borrow)
1495                     || is_raw_borrow_inside_fn_like_call
1496                 {
1497                     err.span_help(
1498                         parent_span,
1499                         "consider moving this into a `let` \
1500                         binding to create a shorter lived borrow",
1501                     );
1502                 }
1503             }
1504         }
1505
1506         // Add a note for the item obligation that remains - normally a note pointing to the
1507         // bound that introduced the obligation (e.g. `T: Send`).
1508         debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1509         self.note_obligation_cause_code(
1510             err,
1511             &obligation.predicate,
1512             next_code.unwrap(),
1513             &mut Vec::new(),
1514         );
1515     }
1516
1517     fn note_obligation_cause_code<T>(
1518         &self,
1519         err: &mut DiagnosticBuilder<'_>,
1520         predicate: &T,
1521         cause_code: &ObligationCauseCode<'tcx>,
1522         obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1523     ) where
1524         T: fmt::Display,
1525     {
1526         let tcx = self.tcx;
1527         match *cause_code {
1528             ObligationCauseCode::ExprAssignable
1529             | ObligationCauseCode::MatchExpressionArm { .. }
1530             | ObligationCauseCode::Pattern { .. }
1531             | ObligationCauseCode::IfExpression { .. }
1532             | ObligationCauseCode::IfExpressionWithNoElse
1533             | ObligationCauseCode::MainFunctionType
1534             | ObligationCauseCode::StartFunctionType
1535             | ObligationCauseCode::IntrinsicType
1536             | ObligationCauseCode::MethodReceiver
1537             | ObligationCauseCode::ReturnNoExpression
1538             | ObligationCauseCode::MiscObligation => {}
1539             ObligationCauseCode::SliceOrArrayElem => {
1540                 err.note("slice and array elements must have `Sized` type");
1541             }
1542             ObligationCauseCode::TupleElem => {
1543                 err.note("only the last element of a tuple may have a dynamically sized type");
1544             }
1545             ObligationCauseCode::ProjectionWf(data) => {
1546                 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1547             }
1548             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1549                 err.note(&format!(
1550                     "required so that reference `{}` does not outlive its referent",
1551                     ref_ty,
1552                 ));
1553             }
1554             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1555                 err.note(&format!(
1556                     "required so that the lifetime bound of `{}` for `{}` is satisfied",
1557                     region, object_ty,
1558                 ));
1559             }
1560             ObligationCauseCode::ItemObligation(item_def_id) => {
1561                 let item_name = tcx.def_path_str(item_def_id);
1562                 let msg = format!("required by `{}`", item_name);
1563                 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1564                     let sp = tcx.sess.source_map().guess_head_span(sp);
1565                     err.span_label(sp, &msg);
1566                 } else {
1567                     err.note(&msg);
1568                 }
1569             }
1570             ObligationCauseCode::BindingObligation(item_def_id, span) => {
1571                 let item_name = tcx.def_path_str(item_def_id);
1572                 let msg = format!("required by this bound in `{}`", item_name);
1573                 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1574                     let sm = tcx.sess.source_map();
1575                     let same_line =
1576                         match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
1577                             (Ok(l), Ok(r)) => l.line == r.line,
1578                             _ => true,
1579                         };
1580                     if !ident.span.overlaps(span) && !same_line {
1581                         err.span_label(ident.span, "required by a bound in this");
1582                     }
1583                 }
1584                 if span != DUMMY_SP {
1585                     err.span_label(span, &msg);
1586                 } else {
1587                     err.note(&msg);
1588                 }
1589             }
1590             ObligationCauseCode::ObjectCastObligation(object_ty) => {
1591                 err.note(&format!(
1592                     "required for the cast to the object type `{}`",
1593                     self.ty_to_string(object_ty)
1594                 ));
1595             }
1596             ObligationCauseCode::Coercion { source: _, target } => {
1597                 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1598             }
1599             ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
1600                 err.note(
1601                     "the `Copy` trait is required because the repeated element will be copied",
1602                 );
1603                 if suggest_const_in_array_repeat_expressions {
1604                     err.note(
1605                         "this array initializer can be evaluated at compile-time, see issue \
1606                          #48147 <https://github.com/rust-lang/rust/issues/49147> \
1607                          for more information",
1608                     );
1609                     if tcx.sess.opts.unstable_features.is_nightly_build() {
1610                         err.help(
1611                             "add `#![feature(const_in_array_repeat_expressions)]` to the \
1612                              crate attributes to enable",
1613                         );
1614                     }
1615                 }
1616             }
1617             ObligationCauseCode::VariableType(_) => {
1618                 err.note("all local variables must have a statically known size");
1619                 if !self.tcx.features().unsized_locals {
1620                     err.help("unsized locals are gated as an unstable feature");
1621                 }
1622             }
1623             ObligationCauseCode::SizedArgumentType => {
1624                 err.note("all function arguments must have a statically known size");
1625                 if !self.tcx.features().unsized_locals {
1626                     err.help("unsized locals are gated as an unstable feature");
1627                 }
1628             }
1629             ObligationCauseCode::SizedReturnType => {
1630                 err.note("the return type of a function must have a statically known size");
1631             }
1632             ObligationCauseCode::SizedYieldType => {
1633                 err.note("the yield type of a generator must have a statically known size");
1634             }
1635             ObligationCauseCode::AssignmentLhsSized => {
1636                 err.note("the left-hand-side of an assignment must have a statically known size");
1637             }
1638             ObligationCauseCode::TupleInitializerSized => {
1639                 err.note("tuples must have a statically known size to be initialized");
1640             }
1641             ObligationCauseCode::StructInitializerSized => {
1642                 err.note("structs must have a statically known size to be initialized");
1643             }
1644             ObligationCauseCode::FieldSized { adt_kind: ref item, last } => match *item {
1645                 AdtKind::Struct => {
1646                     if last {
1647                         err.note(
1648                             "the last field of a packed struct may only have a \
1649                              dynamically sized type if it does not need drop to be run",
1650                         );
1651                     } else {
1652                         err.note(
1653                             "only the last field of a struct may have a dynamically sized type",
1654                         );
1655                     }
1656                 }
1657                 AdtKind::Union => {
1658                     err.note("no field of a union may have a dynamically sized type");
1659                 }
1660                 AdtKind::Enum => {
1661                     err.note("no field of an enum variant may have a dynamically sized type");
1662                 }
1663             },
1664             ObligationCauseCode::ConstSized => {
1665                 err.note("constant expressions must have a statically known size");
1666             }
1667             ObligationCauseCode::ConstPatternStructural => {
1668                 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
1669             }
1670             ObligationCauseCode::SharedStatic => {
1671                 err.note("shared static variables must have a type that implements `Sync`");
1672             }
1673             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1674                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1675                 let ty = parent_trait_ref.skip_binder().self_ty();
1676                 err.note(&format!("required because it appears within the type `{}`", ty));
1677                 obligated_types.push(ty);
1678
1679                 let parent_predicate = parent_trait_ref.without_const().to_predicate();
1680                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1681                     self.note_obligation_cause_code(
1682                         err,
1683                         &parent_predicate,
1684                         &data.parent_code,
1685                         obligated_types,
1686                     );
1687                 }
1688             }
1689             ObligationCauseCode::ImplDerivedObligation(ref data) => {
1690                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1691                 err.note(&format!(
1692                     "required because of the requirements on the impl of `{}` for `{}`",
1693                     parent_trait_ref.print_only_trait_path(),
1694                     parent_trait_ref.skip_binder().self_ty()
1695                 ));
1696                 let parent_predicate = parent_trait_ref.without_const().to_predicate();
1697                 self.note_obligation_cause_code(
1698                     err,
1699                     &parent_predicate,
1700                     &data.parent_code,
1701                     obligated_types,
1702                 );
1703             }
1704             ObligationCauseCode::DerivedObligation(ref data) => {
1705                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1706                 let parent_predicate = parent_trait_ref.without_const().to_predicate();
1707                 self.note_obligation_cause_code(
1708                     err,
1709                     &parent_predicate,
1710                     &data.parent_code,
1711                     obligated_types,
1712                 );
1713             }
1714             ObligationCauseCode::CompareImplMethodObligation { .. } => {
1715                 err.note(&format!(
1716                     "the requirement `{}` appears on the impl method \
1717                      but not on the corresponding trait method",
1718                     predicate
1719                 ));
1720             }
1721             ObligationCauseCode::CompareImplTypeObligation { .. } => {
1722                 err.note(&format!(
1723                     "the requirement `{}` appears on the associated impl type \
1724                      but not on the corresponding associated trait type",
1725                     predicate
1726                 ));
1727             }
1728             ObligationCauseCode::ReturnType
1729             | ObligationCauseCode::ReturnValue(_)
1730             | ObligationCauseCode::BlockTailExpression(_) => (),
1731             ObligationCauseCode::TrivialBound => {
1732                 err.help("see issue #48214");
1733                 if tcx.sess.opts.unstable_features.is_nightly_build() {
1734                     err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
1735                 }
1736             }
1737         }
1738     }
1739
1740     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1741         let current_limit = self.tcx.sess.recursion_limit.get();
1742         let suggested_limit = current_limit * 2;
1743         err.help(&format!(
1744             "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
1745             suggested_limit, self.tcx.crate_name,
1746         ));
1747     }
1748 }
1749
1750 /// Collect all the returned expressions within the input expression.
1751 /// Used to point at the return spans when we want to suggest some change to them.
1752 #[derive(Default)]
1753 struct ReturnsVisitor<'v> {
1754     returns: Vec<&'v hir::Expr<'v>>,
1755     in_block_tail: bool,
1756 }
1757
1758 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
1759     type Map = hir::intravisit::ErasedMap<'v>;
1760
1761     fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
1762         hir::intravisit::NestedVisitorMap::None
1763     }
1764
1765     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
1766         // Visit every expression to detect `return` paths, either through the function's tail
1767         // expression or `return` statements. We walk all nodes to find `return` statements, but
1768         // we only care about tail expressions when `in_block_tail` is `true`, which means that
1769         // they're in the return path of the function body.
1770         match ex.kind {
1771             hir::ExprKind::Ret(Some(ex)) => {
1772                 self.returns.push(ex);
1773             }
1774             hir::ExprKind::Block(block, _) if self.in_block_tail => {
1775                 self.in_block_tail = false;
1776                 for stmt in block.stmts {
1777                     hir::intravisit::walk_stmt(self, stmt);
1778                 }
1779                 self.in_block_tail = true;
1780                 if let Some(expr) = block.expr {
1781                     self.visit_expr(expr);
1782                 }
1783             }
1784             hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
1785                 for arm in arms {
1786                     self.visit_expr(arm.body);
1787                 }
1788             }
1789             // We need to walk to find `return`s in the entire body.
1790             _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
1791             _ => self.returns.push(ex),
1792         }
1793     }
1794
1795     fn visit_body(&mut self, body: &'v hir::Body<'v>) {
1796         assert!(!self.in_block_tail);
1797         if body.generator_kind().is_none() {
1798             if let hir::ExprKind::Block(block, None) = body.value.kind {
1799                 if block.expr.is_some() {
1800                     self.in_block_tail = true;
1801                 }
1802             }
1803         }
1804         hir::intravisit::walk_body(self, body);
1805     }
1806 }
1807
1808 /// Collect all the awaited expressions within the input expression.
1809 #[derive(Default)]
1810 struct AwaitsVisitor {
1811     awaits: Vec<hir::HirId>,
1812 }
1813
1814 impl<'v> Visitor<'v> for AwaitsVisitor {
1815     type Map = hir::intravisit::ErasedMap<'v>;
1816
1817     fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
1818         hir::intravisit::NestedVisitorMap::None
1819     }
1820
1821     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
1822         if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
1823             self.awaits.push(id)
1824         }
1825         hir::intravisit::walk_expr(self, ex)
1826     }
1827 }
1828
1829 pub trait NextTypeParamName {
1830     fn next_type_param_name(&self, name: Option<&str>) -> String;
1831 }
1832
1833 impl NextTypeParamName for &[hir::GenericParam<'_>] {
1834     fn next_type_param_name(&self, name: Option<&str>) -> String {
1835         // This is the whitelist of possible parameter names that we might suggest.
1836         let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
1837         let name = name.as_ref().map(|s| s.as_str());
1838         let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
1839         let used_names = self
1840             .iter()
1841             .filter_map(|p| match p.name {
1842                 hir::ParamName::Plain(ident) => Some(ident.name),
1843                 _ => None,
1844             })
1845             .collect::<Vec<_>>();
1846
1847         possible_names
1848             .iter()
1849             .find(|n| !used_names.contains(&Symbol::intern(n)))
1850             .unwrap_or(&"ParamName")
1851             .to_string()
1852     }
1853 }
1854
1855 fn suggest_trait_object_return_type_alternatives(
1856     err: &mut DiagnosticBuilder<'tcx>,
1857     ret_ty: Span,
1858     trait_obj: &str,
1859     is_object_safe: bool,
1860 ) {
1861     err.span_suggestion(
1862         ret_ty,
1863         "use some type `T` that is `T: Sized` as the return type if all return paths have the \
1864             same type",
1865         "T".to_string(),
1866         Applicability::MaybeIncorrect,
1867     );
1868     err.span_suggestion(
1869         ret_ty,
1870         &format!(
1871             "use `impl {}` as the return type if all return paths have the same type but you \
1872                 want to expose only the trait in the signature",
1873             trait_obj,
1874         ),
1875         format!("impl {}", trait_obj),
1876         Applicability::MaybeIncorrect,
1877     );
1878     if is_object_safe {
1879         err.span_suggestion(
1880             ret_ty,
1881             &format!(
1882                 "use a boxed trait object if all return paths implement trait `{}`",
1883                 trait_obj,
1884             ),
1885             format!("Box<dyn {}>", trait_obj),
1886             Applicability::MaybeIncorrect,
1887         );
1888     }
1889 }