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