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