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