]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/error_reporting.rs
Rollup merge of #67285 - ohadravid:indicate-origin-of-where-type-parameter, r=estebank
[rust.git] / src / librustc / traits / error_reporting.rs
1 use super::{
2     ConstEvalFailure,
3     EvaluationResult,
4     FulfillmentError,
5     FulfillmentErrorCode,
6     MismatchedProjectionTypes,
7     ObjectSafetyViolation,
8     Obligation,
9     ObligationCause,
10     ObligationCauseCode,
11     OnUnimplementedDirective,
12     OnUnimplementedNote,
13     OutputTypeParameterMismatch,
14     Overflow,
15     PredicateObligation,
16     SelectionContext,
17     SelectionError,
18     TraitNotObjectSafe,
19 };
20
21 use crate::hir;
22 use crate::hir::Node;
23 use crate::hir::def_id::DefId;
24 use crate::infer::{self, InferCtxt};
25 use crate::infer::error_reporting::TypeAnnotationNeeded as ErrorCode;
26 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
27 use crate::session::DiagnosticMessageId;
28 use crate::ty::{self, AdtKind, DefIdTree, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
29 use crate::ty::TypeckTables;
30 use crate::ty::GenericParamDefKind;
31 use crate::ty::error::ExpectedFound;
32 use crate::ty::fast_reject;
33 use crate::ty::fold::TypeFolder;
34 use crate::ty::subst::Subst;
35 use crate::ty::SubtypePredicate;
36 use crate::util::nodemap::{FxHashMap, FxHashSet};
37
38 use errors::{Applicability, DiagnosticBuilder, pluralize, Style};
39 use std::fmt;
40 use syntax::ast;
41 use syntax::symbol::{sym, kw};
42 use syntax_pos::{DUMMY_SP, Span, ExpnKind, MultiSpan};
43 use rustc::hir::def_id::LOCAL_CRATE;
44 use syntax_pos::source_map::SourceMap;
45
46 use rustc_error_codes::*;
47
48 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
49     pub fn report_fulfillment_errors(
50         &self,
51         errors: &[FulfillmentError<'tcx>],
52         body_id: Option<hir::BodyId>,
53         fallback_has_occurred: bool,
54     ) {
55         #[derive(Debug)]
56         struct ErrorDescriptor<'tcx> {
57             predicate: ty::Predicate<'tcx>,
58             index: Option<usize>, // None if this is an old error
59         }
60
61         let mut error_map: FxHashMap<_, Vec<_>> =
62             self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
63                 (span, predicates.iter().map(|predicate| ErrorDescriptor {
64                     predicate: predicate.clone(),
65                     index: None
66                 }).collect())
67             }).collect();
68
69         for (index, error) in errors.iter().enumerate() {
70             // We want to ignore desugarings here: spans are equivalent even
71             // if one is the result of a desugaring and the other is not.
72             let mut span = error.obligation.cause.span;
73             let expn_data = span.ctxt().outer_expn_data();
74             if let ExpnKind::Desugaring(_) = expn_data.kind {
75                 span = expn_data.call_site;
76             }
77
78             error_map.entry(span).or_default().push(
79                 ErrorDescriptor {
80                     predicate: error.obligation.predicate.clone(),
81                     index: Some(index)
82                 }
83             );
84
85             self.reported_trait_errors.borrow_mut()
86                 .entry(span).or_default()
87                 .push(error.obligation.predicate.clone());
88         }
89
90         // We do this in 2 passes because we want to display errors in order, though
91         // maybe it *is* better to sort errors by span or something.
92         let mut is_suppressed = vec![false; errors.len()];
93         for (_, error_set) in error_map.iter() {
94             // We want to suppress "duplicate" errors with the same span.
95             for error in error_set {
96                 if let Some(index) = error.index {
97                     // Suppress errors that are either:
98                     // 1) strictly implied by another error.
99                     // 2) implied by an error with a smaller index.
100                     for error2 in error_set {
101                         if error2.index.map_or(false, |index2| is_suppressed[index2]) {
102                             // Avoid errors being suppressed by already-suppressed
103                             // errors, to prevent all errors from being suppressed
104                             // at once.
105                             continue
106                         }
107
108                         if self.error_implies(&error2.predicate, &error.predicate) &&
109                             !(error2.index >= error.index &&
110                               self.error_implies(&error.predicate, &error2.predicate))
111                         {
112                             info!("skipping {:?} (implied by {:?})", error, error2);
113                             is_suppressed[index] = true;
114                             break
115                         }
116                     }
117                 }
118             }
119         }
120
121         for (error, suppressed) in errors.iter().zip(is_suppressed) {
122             if !suppressed {
123                 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
124             }
125         }
126     }
127
128     // returns if `cond` not occurring implies that `error` does not occur - i.e., that
129     // `error` occurring implies that `cond` occurs.
130     fn error_implies(
131         &self,
132         cond: &ty::Predicate<'tcx>,
133         error: &ty::Predicate<'tcx>,
134     ) -> bool {
135         if cond == error {
136             return true
137         }
138
139         let (cond, error) = match (cond, error) {
140             (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
141                 => (cond, error),
142             _ => {
143                 // FIXME: make this work in other cases too.
144                 return false
145             }
146         };
147
148         for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
149             if let ty::Predicate::Trait(implication) = implication {
150                 let error = error.to_poly_trait_ref();
151                 let implication = implication.to_poly_trait_ref();
152                 // FIXME: I'm just not taking associated types at all here.
153                 // Eventually I'll need to implement param-env-aware
154                 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
155                 let param_env = ty::ParamEnv::empty();
156                 if self.can_sub(param_env, error, implication).is_ok() {
157                     debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
158                     return true
159                 }
160             }
161         }
162
163         false
164     }
165
166     fn report_fulfillment_error(
167         &self,
168         error: &FulfillmentError<'tcx>,
169         body_id: Option<hir::BodyId>,
170         fallback_has_occurred: bool,
171     ) {
172         debug!("report_fulfillment_error({:?})", error);
173         match error.code {
174             FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
175                 self.report_selection_error(
176                     &error.obligation,
177                     selection_error,
178                     fallback_has_occurred,
179                     error.points_at_arg_span,
180                 );
181             }
182             FulfillmentErrorCode::CodeProjectionError(ref e) => {
183                 self.report_projection_error(&error.obligation, e);
184             }
185             FulfillmentErrorCode::CodeAmbiguity => {
186                 self.maybe_report_ambiguity(&error.obligation, body_id);
187             }
188             FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
189                 self.report_mismatched_types(
190                     &error.obligation.cause,
191                     expected_found.expected,
192                     expected_found.found,
193                     err.clone(),
194                 ).emit();
195             }
196         }
197     }
198
199     fn report_projection_error(
200         &self,
201         obligation: &PredicateObligation<'tcx>,
202         error: &MismatchedProjectionTypes<'tcx>,
203     ) {
204         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
205
206         if predicate.references_error() {
207             return
208         }
209
210         self.probe(|_| {
211             let err_buf;
212             let mut err = &error.err;
213             let mut values = None;
214
215             // try to find the mismatched types to report the error with.
216             //
217             // this can fail if the problem was higher-ranked, in which
218             // cause I have no idea for a good error message.
219             if let ty::Predicate::Projection(ref data) = predicate {
220                 let mut selcx = SelectionContext::new(self);
221                 let (data, _) = self.replace_bound_vars_with_fresh_vars(
222                     obligation.cause.span,
223                     infer::LateBoundRegionConversionTime::HigherRankedType,
224                     data
225                 );
226                 let mut obligations = vec![];
227                 let normalized_ty = super::normalize_projection_type(
228                     &mut selcx,
229                     obligation.param_env,
230                     data.projection_ty,
231                     obligation.cause.clone(),
232                     0,
233                     &mut obligations
234                 );
235
236                 debug!("report_projection_error obligation.cause={:?} obligation.param_env={:?}",
237                        obligation.cause, obligation.param_env);
238
239                 debug!("report_projection_error normalized_ty={:?} data.ty={:?}",
240                        normalized_ty, data.ty);
241
242                 let is_normalized_ty_expected = match &obligation.cause.code {
243                     ObligationCauseCode::ItemObligation(_) |
244                     ObligationCauseCode::BindingObligation(_, _) |
245                     ObligationCauseCode::ObjectCastObligation(_) => false,
246                     _ => true,
247                 };
248
249                 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
250                     .eq_exp(is_normalized_ty_expected, normalized_ty, data.ty)
251                 {
252                     values = Some(infer::ValuePairs::Types(
253                         ExpectedFound::new(is_normalized_ty_expected, normalized_ty, data.ty)));
254
255                     err_buf = error;
256                     err = &err_buf;
257                 }
258             }
259
260             let msg = format!("type mismatch resolving `{}`", predicate);
261             let error_id = (
262                 DiagnosticMessageId::ErrorId(271),
263                 Some(obligation.cause.span),
264                 msg,
265             );
266             let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
267             if fresh {
268                 let mut diag = struct_span_err!(
269                     self.tcx.sess,
270                     obligation.cause.span,
271                     E0271,
272                     "type mismatch resolving `{}`",
273                     predicate
274                 );
275                 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
276                 self.note_obligation_cause(&mut diag, obligation);
277                 diag.emit();
278             }
279         });
280     }
281
282     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
283         /// returns the fuzzy category of a given type, or None
284         /// if the type can be equated to any type.
285         fn type_category(t: Ty<'_>) -> Option<u32> {
286             match t.kind {
287                 ty::Bool => Some(0),
288                 ty::Char => Some(1),
289                 ty::Str => Some(2),
290                 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
291                 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
292                 ty::Ref(..) | ty::RawPtr(..) => Some(5),
293                 ty::Array(..) | ty::Slice(..) => Some(6),
294                 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
295                 ty::Dynamic(..) => Some(8),
296                 ty::Closure(..) => Some(9),
297                 ty::Tuple(..) => Some(10),
298                 ty::Projection(..) => Some(11),
299                 ty::Param(..) => Some(12),
300                 ty::Opaque(..) => Some(13),
301                 ty::Never => Some(14),
302                 ty::Adt(adt, ..) => match adt.adt_kind() {
303                     AdtKind::Struct => Some(15),
304                     AdtKind::Union => Some(16),
305                     AdtKind::Enum => Some(17),
306                 },
307                 ty::Generator(..) => Some(18),
308                 ty::Foreign(..) => Some(19),
309                 ty::GeneratorWitness(..) => Some(20),
310                 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
311                 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
312             }
313         }
314
315         match (type_category(a), type_category(b)) {
316             (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
317                 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
318                 _ => cat_a == cat_b
319             },
320             // infer and error can be equated to all types
321             _ => true
322         }
323     }
324
325     fn impl_similar_to(&self,
326                        trait_ref: ty::PolyTraitRef<'tcx>,
327                        obligation: &PredicateObligation<'tcx>)
328                        -> Option<DefId>
329     {
330         let tcx = self.tcx;
331         let param_env = obligation.param_env;
332         let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
333         let trait_self_ty = trait_ref.self_ty();
334
335         let mut self_match_impls = vec![];
336         let mut fuzzy_match_impls = vec![];
337
338         self.tcx.for_each_relevant_impl(
339             trait_ref.def_id, trait_self_ty, |def_id| {
340                 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
341                 let impl_trait_ref = tcx
342                     .impl_trait_ref(def_id)
343                     .unwrap()
344                     .subst(tcx, impl_substs);
345
346                 let impl_self_ty = impl_trait_ref.self_ty();
347
348                 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
349                     self_match_impls.push(def_id);
350
351                     if trait_ref.substs.types().skip(1)
352                         .zip(impl_trait_ref.substs.types().skip(1))
353                         .all(|(u,v)| self.fuzzy_match_tys(u, v))
354                     {
355                         fuzzy_match_impls.push(def_id);
356                     }
357                 }
358             });
359
360         let impl_def_id = if self_match_impls.len() == 1 {
361             self_match_impls[0]
362         } else if fuzzy_match_impls.len() == 1 {
363             fuzzy_match_impls[0]
364         } else {
365             return None
366         };
367
368         tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented).then_some(impl_def_id)
369     }
370
371     fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
372         self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| {
373             match gen_kind {
374                 hir::GeneratorKind::Gen => "a generator",
375                 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
376                 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
377                 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
378             }
379         })
380     }
381
382     /// Used to set on_unimplemented's `ItemContext`
383     /// to be the enclosing (async) block/function/closure
384     fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str> {
385         let hir = &self.tcx.hir();
386         let node = hir.find(hir_id)?;
387         if let hir::Node::Item(
388             hir::Item{kind: hir::ItemKind::Fn(sig, _, body_id), .. }) = &node {
389             self.describe_generator(*body_id).or_else(||
390                 Some(if let hir::FnHeader{ asyncness: hir::IsAsync::Async, .. } = sig.header {
391                     "an async function"
392                 } else {
393                     "a function"
394                 })
395             )
396         } else if let hir::Node::Expr(hir::Expr {
397             kind: hir::ExprKind::Closure(_is_move, _, body_id, _, gen_movability), .. }) = &node {
398             self.describe_generator(*body_id).or_else(||
399                 Some(if gen_movability.is_some() {
400                     "an async closure"
401                 } else {
402                     "a closure"
403                 })
404             )
405         } else if let hir::Node::Expr(hir::Expr { .. }) = &node {
406             let parent_hid = hir.get_parent_node(hir_id);
407             if parent_hid != hir_id {
408                 return self.describe_enclosure(parent_hid);
409             } else {
410                 None
411             }
412         } else {
413             None
414         }
415     }
416
417     fn on_unimplemented_note(
418         &self,
419         trait_ref: ty::PolyTraitRef<'tcx>,
420         obligation: &PredicateObligation<'tcx>,
421     ) -> OnUnimplementedNote {
422         let def_id = self.impl_similar_to(trait_ref, obligation)
423             .unwrap_or_else(|| trait_ref.def_id());
424         let trait_ref = *trait_ref.skip_binder();
425
426         let mut flags = vec![];
427         flags.push((sym::item_context,
428             self.describe_enclosure(obligation.cause.body_id).map(|s|s.to_owned())));
429
430         match obligation.cause.code {
431             ObligationCauseCode::BuiltinDerivedObligation(..) |
432             ObligationCauseCode::ImplDerivedObligation(..) => {}
433             _ => {
434                 // this is a "direct", user-specified, rather than derived,
435                 // obligation.
436                 flags.push((sym::direct, None));
437             }
438         }
439
440         if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
441             // FIXME: maybe also have some way of handling methods
442             // from other traits? That would require name resolution,
443             // which we might want to be some sort of hygienic.
444             //
445             // Currently I'm leaving it for what I need for `try`.
446             if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
447                 let method = self.tcx.item_name(item);
448                 flags.push((sym::from_method, None));
449                 flags.push((sym::from_method, Some(method.to_string())));
450             }
451         }
452         if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
453             flags.push((sym::parent_trait, Some(t)));
454         }
455
456         if let Some(k) = obligation.cause.span.desugaring_kind() {
457             flags.push((sym::from_desugaring, None));
458             flags.push((sym::from_desugaring, Some(format!("{:?}", k))));
459         }
460         let generics = self.tcx.generics_of(def_id);
461         let self_ty = trait_ref.self_ty();
462         // This is also included through the generics list as `Self`,
463         // but the parser won't allow you to use it
464         flags.push((sym::_Self, Some(self_ty.to_string())));
465         if let Some(def) = self_ty.ty_adt_def() {
466             // We also want to be able to select self's original
467             // signature with no type arguments resolved
468             flags.push((sym::_Self, Some(self.tcx.type_of(def.did).to_string())));
469         }
470
471         for param in generics.params.iter() {
472             let value = match param.kind {
473                 GenericParamDefKind::Type { .. } |
474                 GenericParamDefKind::Const => {
475                     trait_ref.substs[param.index as usize].to_string()
476                 },
477                 GenericParamDefKind::Lifetime => continue,
478             };
479             let name = param.name;
480             flags.push((name, Some(value)));
481         }
482
483         if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
484             flags.push((sym::crate_local, None));
485         }
486
487         // Allow targeting all integers using `{integral}`, even if the exact type was resolved
488         if self_ty.is_integral() {
489             flags.push((sym::_Self, Some("{integral}".to_owned())));
490         }
491
492         if let ty::Array(aty, len) = self_ty.kind {
493             flags.push((sym::_Self, Some("[]".to_owned())));
494             flags.push((sym::_Self, Some(format!("[{}]", aty))));
495             if let Some(def) = aty.ty_adt_def() {
496                 // We also want to be able to select the array's type's original
497                 // signature with no type arguments resolved
498                 flags.push((
499                     sym::_Self,
500                     Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
501                 ));
502                 let tcx = self.tcx;
503                 if let Some(len) = len.try_eval_usize(tcx, ty::ParamEnv::empty()) {
504                     flags.push((
505                         sym::_Self,
506                         Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
507                     ));
508                 } else {
509                     flags.push((
510                         sym::_Self,
511                         Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
512                     ));
513                 }
514             }
515         }
516
517         if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
518             self.tcx, trait_ref.def_id, def_id
519         ) {
520             command.evaluate(self.tcx, trait_ref, &flags[..])
521         } else {
522             OnUnimplementedNote::default()
523         }
524     }
525
526     fn find_similar_impl_candidates(
527         &self,
528         trait_ref: ty::PolyTraitRef<'tcx>,
529     ) -> Vec<ty::TraitRef<'tcx>> {
530         let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
531         let all_impls = self.tcx.all_impls(trait_ref.def_id());
532
533         match simp {
534             Some(simp) => all_impls.iter().filter_map(|&def_id| {
535                 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
536                 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
537                 if let Some(imp_simp) = imp_simp {
538                     if simp != imp_simp {
539                         return None
540                     }
541                 }
542
543                 Some(imp)
544             }).collect(),
545             None => all_impls.iter().map(|&def_id|
546                 self.tcx.impl_trait_ref(def_id).unwrap()
547             ).collect()
548         }
549     }
550
551     fn report_similar_impl_candidates(
552         &self,
553         impl_candidates: Vec<ty::TraitRef<'tcx>>,
554         err: &mut DiagnosticBuilder<'_>,
555     ) {
556         if impl_candidates.is_empty() {
557             return;
558         }
559
560         let len = impl_candidates.len();
561         let end = if impl_candidates.len() <= 5 {
562             impl_candidates.len()
563         } else {
564             4
565         };
566
567         let normalize = |candidate| self.tcx.infer_ctxt().enter(|ref infcx| {
568             let normalized = infcx
569                 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
570                 .normalize(candidate)
571                 .ok();
572             match normalized {
573                 Some(normalized) => format!("\n  {:?}", normalized.value),
574                 None => format!("\n  {:?}", candidate),
575             }
576         });
577
578         // Sort impl candidates so that ordering is consistent for UI tests.
579         let mut normalized_impl_candidates = impl_candidates
580             .iter()
581             .map(normalize)
582             .collect::<Vec<String>>();
583
584         // Sort before taking the `..end` range,
585         // because the ordering of `impl_candidates` may not be deterministic:
586         // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
587         normalized_impl_candidates.sort();
588
589         err.help(&format!("the following implementations were found:{}{}",
590                           normalized_impl_candidates[..end].join(""),
591                           if len > 5 {
592                               format!("\nand {} others", len - 4)
593                           } else {
594                               String::new()
595                           }
596                           ));
597     }
598
599     /// Reports that an overflow has occurred and halts compilation. We
600     /// halt compilation unconditionally because it is important that
601     /// overflows never be masked -- they basically represent computations
602     /// whose result could not be truly determined and thus we can't say
603     /// if the program type checks or not -- and they are unusual
604     /// occurrences in any case.
605     pub fn report_overflow_error<T>(
606         &self,
607         obligation: &Obligation<'tcx, T>,
608         suggest_increasing_limit: bool,
609     ) -> !
610         where T: fmt::Display + TypeFoldable<'tcx>
611     {
612         let predicate =
613             self.resolve_vars_if_possible(&obligation.predicate);
614         let mut err = struct_span_err!(
615             self.tcx.sess,
616             obligation.cause.span,
617             E0275,
618             "overflow evaluating the requirement `{}`",
619             predicate
620         );
621
622         if suggest_increasing_limit {
623             self.suggest_new_overflow_limit(&mut err);
624         }
625
626         self.note_obligation_cause_code(
627             &mut err,
628             &obligation.predicate,
629             &obligation.cause.code,
630             &mut vec![],
631         );
632
633         err.emit();
634         self.tcx.sess.abort_if_errors();
635         bug!();
636     }
637
638     /// Reports that a cycle was detected which led to overflow and halts
639     /// compilation. This is equivalent to `report_overflow_error` except
640     /// that we can give a more helpful error message (and, in particular,
641     /// we do not suggest increasing the overflow limit, which is not
642     /// going to help).
643     pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
644         let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
645         assert!(cycle.len() > 0);
646
647         debug!("report_overflow_error_cycle: cycle={:?}", cycle);
648
649         self.report_overflow_error(&cycle[0], false);
650     }
651
652     pub fn report_extra_impl_obligation(&self,
653                                         error_span: Span,
654                                         item_name: ast::Name,
655                                         _impl_item_def_id: DefId,
656                                         trait_item_def_id: DefId,
657                                         requirement: &dyn fmt::Display)
658                                         -> DiagnosticBuilder<'tcx>
659     {
660         let msg = "impl has stricter requirements than trait";
661         let sp = self.tcx.sess.source_map().def_span(error_span);
662
663         let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
664
665         if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
666             let span = self.tcx.sess.source_map().def_span(trait_item_span);
667             err.span_label(span, format!("definition of `{}` from trait", item_name));
668         }
669
670         err.span_label(sp, format!("impl has extra requirement {}", requirement));
671
672         err
673     }
674
675
676     /// Gets the parent trait chain start
677     fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
678         match code {
679             &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
680                 let parent_trait_ref = self.resolve_vars_if_possible(
681                     &data.parent_trait_ref);
682                 match self.get_parent_trait_ref(&data.parent_code) {
683                     Some(t) => Some(t),
684                     None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
685                 }
686             }
687             _ => None,
688         }
689     }
690
691     pub fn report_selection_error(
692         &self,
693         obligation: &PredicateObligation<'tcx>,
694         error: &SelectionError<'tcx>,
695         fallback_has_occurred: bool,
696         points_at_arg: bool,
697     ) {
698         let tcx = self.tcx;
699         let span = obligation.cause.span;
700
701         let mut err = match *error {
702             SelectionError::Unimplemented => {
703                 if let ObligationCauseCode::CompareImplMethodObligation {
704                     item_name, impl_item_def_id, trait_item_def_id,
705                 } = obligation.cause.code {
706                     self.report_extra_impl_obligation(
707                         span,
708                         item_name,
709                         impl_item_def_id,
710                         trait_item_def_id,
711                         &format!("`{}`", obligation.predicate))
712                         .emit();
713                     return;
714                 }
715                 match obligation.predicate {
716                     ty::Predicate::Trait(ref trait_predicate) => {
717                         let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
718
719                         if self.tcx.sess.has_errors() && trait_predicate.references_error() {
720                             return;
721                         }
722                         let trait_ref = trait_predicate.to_poly_trait_ref();
723                         let (
724                             post_message,
725                             pre_message,
726                         ) = self.get_parent_trait_ref(&obligation.cause.code)
727                             .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
728                             .unwrap_or_default();
729
730                         let OnUnimplementedNote {
731                             message,
732                             label,
733                             note,
734                             enclosing_scope,
735                         } = self.on_unimplemented_note(trait_ref, obligation);
736                         let have_alt_message = message.is_some() || label.is_some();
737                         let is_try = self.tcx.sess.source_map().span_to_snippet(span)
738                             .map(|s| &s == "?")
739                             .unwrap_or(false);
740                         let is_from =
741                             format!("{}", trait_ref.print_only_trait_path())
742                             .starts_with("std::convert::From<");
743                         let (message, note) = if is_try && is_from {
744                             (Some(format!(
745                                 "`?` couldn't convert the error to `{}`",
746                                 trait_ref.self_ty(),
747                             )), Some(
748                                 "the question mark operation (`?`) implicitly performs a \
749                                  conversion on the error value using the `From` trait".to_owned()
750                             ))
751                         } else {
752                             (message, note)
753                         };
754
755                         let mut err = struct_span_err!(
756                             self.tcx.sess,
757                             span,
758                             E0277,
759                             "{}",
760                             message.unwrap_or_else(|| format!(
761                                 "the trait bound `{}` is not satisfied{}",
762                                 trait_ref.to_predicate(),
763                                 post_message,
764                             )));
765
766                         let explanation =
767                             if obligation.cause.code == ObligationCauseCode::MainFunctionType {
768                                 "consider using `()`, or a `Result`".to_owned()
769                             } else {
770                                 format!(
771                                     "{}the trait `{}` is not implemented for `{}`",
772                                     pre_message,
773                                     trait_ref.print_only_trait_path(),
774                                     trait_ref.self_ty(),
775                                 )
776                             };
777
778                         if self.suggest_add_reference_to_arg(
779                             &obligation,
780                             &mut err,
781                             &trait_ref,
782                             points_at_arg,
783                             have_alt_message,
784                         ) {
785                             self.note_obligation_cause(&mut err, obligation);
786                             err.emit();
787                             return;
788                         }
789                         if let Some(ref s) = label {
790                             // If it has a custom `#[rustc_on_unimplemented]`
791                             // error message, let's display it as the label!
792                             err.span_label(span, s.as_str());
793                             err.help(&explanation);
794                         } else {
795                             err.span_label(span, explanation);
796                         }
797                         if let Some(ref s) = note {
798                             // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
799                             err.note(s.as_str());
800                         }
801                         if let Some(ref s) = enclosing_scope {
802                             let enclosing_scope_span = tcx.def_span(
803                                 tcx.hir()
804                                     .opt_local_def_id(obligation.cause.body_id)
805                                     .unwrap_or_else(|| {
806                                         tcx.hir().body_owner_def_id(hir::BodyId {
807                                             hir_id: obligation.cause.body_id,
808                                         })
809                                     }),
810                             );
811
812                             err.span_label(enclosing_scope_span, s.as_str());
813                         }
814
815                         self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
816                         self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
817                         self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
818                         self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
819                         self.note_version_mismatch(&mut err, &trait_ref);
820
821                         // Try to report a help message
822                         if !trait_ref.has_infer_types() &&
823                             self.predicate_can_apply(obligation.param_env, trait_ref) {
824                             // If a where-clause may be useful, remind the
825                             // user that they can add it.
826                             //
827                             // don't display an on-unimplemented note, as
828                             // these notes will often be of the form
829                             //     "the type `T` can't be frobnicated"
830                             // which is somewhat confusing.
831                             self.suggest_restricting_param_bound(
832                                 &mut err,
833                                 &trait_ref,
834                                 obligation.cause.body_id,
835                             );
836                         } else {
837                             if !have_alt_message {
838                                 // Can't show anything else useful, try to find similar impls.
839                                 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
840                                 self.report_similar_impl_candidates(impl_candidates, &mut err);
841                             }
842                             self.suggest_change_mut(
843                                 &obligation,
844                                 &mut err,
845                                 &trait_ref,
846                                 points_at_arg,
847                             );
848                         }
849
850                         // If this error is due to `!: Trait` not implemented but `(): Trait` is
851                         // implemented, and fallback has occurred, then it could be due to a
852                         // variable that used to fallback to `()` now falling back to `!`. Issue a
853                         // note informing about the change in behaviour.
854                         if trait_predicate.skip_binder().self_ty().is_never()
855                             && fallback_has_occurred
856                         {
857                             let predicate = trait_predicate.map_bound(|mut trait_pred| {
858                                 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
859                                     self.tcx.mk_unit(),
860                                     &trait_pred.trait_ref.substs[1..],
861                                 );
862                                 trait_pred
863                             });
864                             let unit_obligation = Obligation {
865                                 predicate: ty::Predicate::Trait(predicate),
866                                 .. obligation.clone()
867                             };
868                             if self.predicate_may_hold(&unit_obligation) {
869                                 err.note("the trait is implemented for `()`. \
870                                          Possibly this error has been caused by changes to \
871                                          Rust's type-inference algorithm \
872                                          (see: https://github.com/rust-lang/rust/issues/48950 \
873                                          for more info). Consider whether you meant to use the \
874                                          type `()` here instead.");
875                             }
876                         }
877
878                         err
879                     }
880
881                     ty::Predicate::Subtype(ref predicate) => {
882                         // Errors for Subtype predicates show up as
883                         // `FulfillmentErrorCode::CodeSubtypeError`,
884                         // not selection error.
885                         span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
886                     }
887
888                     ty::Predicate::RegionOutlives(ref predicate) => {
889                         let predicate = self.resolve_vars_if_possible(predicate);
890                         let err = self.region_outlives_predicate(&obligation.cause,
891                                                                  &predicate).err().unwrap();
892                         struct_span_err!(
893                             self.tcx.sess, span, E0279,
894                             "the requirement `{}` is not satisfied (`{}`)",
895                             predicate, err,
896                         )
897                     }
898
899                     ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
900                         let predicate =
901                             self.resolve_vars_if_possible(&obligation.predicate);
902                         struct_span_err!(self.tcx.sess, span, E0280,
903                             "the requirement `{}` is not satisfied",
904                             predicate)
905                     }
906
907                     ty::Predicate::ObjectSafe(trait_def_id) => {
908                         let violations = self.tcx.object_safety_violations(trait_def_id);
909                         self.tcx.report_object_safety_error(
910                             span,
911                             trait_def_id,
912                             violations,
913                         )
914                     }
915
916                     ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
917                         let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
918                         let closure_span = self.tcx.sess.source_map()
919                             .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
920                         let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
921                         let mut err = struct_span_err!(
922                             self.tcx.sess, closure_span, E0525,
923                             "expected a closure that implements the `{}` trait, \
924                              but this closure only implements `{}`",
925                             kind,
926                             found_kind);
927
928                         err.span_label(
929                             closure_span,
930                             format!("this closure implements `{}`, not `{}`", found_kind, kind));
931                         err.span_label(
932                             obligation.cause.span,
933                             format!("the requirement to implement `{}` derives from here", kind));
934
935                         // Additional context information explaining why the closure only implements
936                         // a particular trait.
937                         if let Some(tables) = self.in_progress_tables {
938                             let tables = tables.borrow();
939                             match (found_kind, tables.closure_kind_origins().get(hir_id)) {
940                                 (ty::ClosureKind::FnOnce, Some((span, name))) => {
941                                     err.span_label(*span, format!(
942                                         "closure is `FnOnce` because it moves the \
943                                          variable `{}` out of its environment", name));
944                                 },
945                                 (ty::ClosureKind::FnMut, Some((span, name))) => {
946                                     err.span_label(*span, format!(
947                                         "closure is `FnMut` because it mutates the \
948                                          variable `{}` here", name));
949                                 },
950                                 _ => {}
951                             }
952                         }
953
954                         err.emit();
955                         return;
956                     }
957
958                     ty::Predicate::WellFormed(ty) => {
959                         if !self.tcx.sess.opts.debugging_opts.chalk {
960                             // WF predicates cannot themselves make
961                             // errors. They can only block due to
962                             // ambiguity; otherwise, they always
963                             // degenerate into other obligations
964                             // (which may fail).
965                             span_bug!(span, "WF predicate not satisfied for {:?}", ty);
966                         } else {
967                             // FIXME: we'll need a better message which takes into account
968                             // which bounds actually failed to hold.
969                             self.tcx.sess.struct_span_err(
970                                 span,
971                                 &format!("the type `{}` is not well-formed (chalk)", ty)
972                             )
973                         }
974                     }
975
976                     ty::Predicate::ConstEvaluatable(..) => {
977                         // Errors for `ConstEvaluatable` predicates show up as
978                         // `SelectionError::ConstEvalFailure`,
979                         // not `Unimplemented`.
980                         span_bug!(span,
981                             "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
982                     }
983                 }
984             }
985
986             OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
987                 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
988                 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
989
990                 if expected_trait_ref.self_ty().references_error() {
991                     return;
992                 }
993
994                 let found_trait_ty = found_trait_ref.self_ty();
995
996                 let found_did = match found_trait_ty.kind {
997                     ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
998                     ty::Adt(def, _) => Some(def.did),
999                     _ => None,
1000                 };
1001
1002                 let found_span = found_did.and_then(|did|
1003                     self.tcx.hir().span_if_local(did)
1004                 ).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
1005
1006                 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
1007                     // We check closures twice, with obligations flowing in different directions,
1008                     // but we want to complain about them only once.
1009                     return;
1010                 }
1011
1012                 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
1013
1014                 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
1015                     ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
1016                     _ => vec![ArgKind::empty()],
1017                 };
1018
1019                 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
1020                 let expected = match expected_ty.kind {
1021                     ty::Tuple(ref tys) => tys.iter()
1022                         .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span))).collect(),
1023                     _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
1024                 };
1025
1026                 if found.len() == expected.len() {
1027                     self.report_closure_arg_mismatch(span,
1028                                                      found_span,
1029                                                      found_trait_ref,
1030                                                      expected_trait_ref)
1031                 } else {
1032                     let (closure_span, found) = found_did
1033                         .and_then(|did| self.tcx.hir().get_if_local(did))
1034                         .map(|node| {
1035                             let (found_span, found) = self.get_fn_like_arguments(node);
1036                             (Some(found_span), found)
1037                         }).unwrap_or((found_span, found));
1038
1039                     self.report_arg_count_mismatch(span,
1040                                                    closure_span,
1041                                                    expected,
1042                                                    found,
1043                                                    found_trait_ty.is_closure())
1044                 }
1045             }
1046
1047             TraitNotObjectSafe(did) => {
1048                 let violations = self.tcx.object_safety_violations(did);
1049                 self.tcx.report_object_safety_error(span, did, violations)
1050             }
1051
1052             // already reported in the query
1053             ConstEvalFailure(err) => {
1054                 self.tcx.sess.delay_span_bug(
1055                     span,
1056                     &format!("constant in type had an ignored error: {:?}", err),
1057                 );
1058                 return;
1059             }
1060
1061             Overflow => {
1062                 bug!("overflow should be handled before the `report_selection_error` path");
1063             }
1064         };
1065
1066         self.note_obligation_cause(&mut err, obligation);
1067
1068         err.emit();
1069     }
1070
1071     /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1072     /// with the same path as `trait_ref`, a help message about
1073     /// a probable version mismatch is added to `err`
1074     fn note_version_mismatch(
1075         &self,
1076         err: &mut DiagnosticBuilder<'_>,
1077         trait_ref: &ty::PolyTraitRef<'tcx>,
1078     ) {
1079         let get_trait_impl = |trait_def_id| {
1080             let mut trait_impl = None;
1081             self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
1082                 if trait_impl.is_none() {
1083                     trait_impl = Some(impl_def_id);
1084                 }
1085             });
1086             trait_impl
1087         };
1088         let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1089         let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1090         let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1091             .iter()
1092             .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1093             .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1094             .collect();
1095         for trait_with_same_path in traits_with_same_path {
1096             if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1097                 let impl_span = self.tcx.def_span(impl_def_id);
1098                 err.span_help(impl_span, "trait impl with same name found");
1099                 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1100                 let crate_msg = format!(
1101                     "Perhaps two different versions of crate `{}` are being used?",
1102                     trait_crate
1103                 );
1104                 err.note(&crate_msg);
1105             }
1106         }
1107     }
1108     fn suggest_restricting_param_bound(
1109         &self,
1110         mut err: &mut DiagnosticBuilder<'_>,
1111         trait_ref: &ty::PolyTraitRef<'_>,
1112         body_id: hir::HirId,
1113     ) {
1114         let self_ty = trait_ref.self_ty();
1115         let (param_ty, projection) = match &self_ty.kind {
1116             ty::Param(_) => (true, None),
1117             ty::Projection(projection) => (false, Some(projection)),
1118             _ => return,
1119         };
1120
1121         let suggest_restriction = |
1122             generics: &hir::Generics,
1123             msg,
1124             err: &mut DiagnosticBuilder<'_>,
1125         | {
1126             let span = generics.where_clause.span_for_predicates_or_empty_place();
1127             if !span.from_expansion() && span.desugaring_kind().is_none() {
1128                 err.span_suggestion(
1129                     generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
1130                     &format!("consider further restricting {}", msg),
1131                     format!(
1132                         "{} {} ",
1133                         if !generics.where_clause.predicates.is_empty() {
1134                             ","
1135                         } else {
1136                             " where"
1137                         },
1138                         trait_ref.to_predicate(),
1139                     ),
1140                     Applicability::MachineApplicable,
1141                 );
1142             }
1143         };
1144
1145         // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
1146         //        don't suggest `T: Sized + ?Sized`.
1147         let mut hir_id = body_id;
1148         while let Some(node) = self.tcx.hir().find(hir_id) {
1149             match node {
1150                 hir::Node::TraitItem(hir::TraitItem {
1151                     generics,
1152                     kind: hir::TraitItemKind::Method(..), ..
1153                 }) if param_ty && self_ty == self.tcx.types.self_param => {
1154                     // Restricting `Self` for a single method.
1155                     suggest_restriction(&generics, "`Self`", err);
1156                     return;
1157                 }
1158
1159                 hir::Node::Item(hir::Item {
1160                     kind: hir::ItemKind::Fn(_, generics, _), ..
1161                 }) |
1162                 hir::Node::TraitItem(hir::TraitItem {
1163                     generics,
1164                     kind: hir::TraitItemKind::Method(..), ..
1165                 }) |
1166                 hir::Node::ImplItem(hir::ImplItem {
1167                     generics,
1168                     kind: hir::ImplItemKind::Method(..), ..
1169                 }) |
1170                 hir::Node::Item(hir::Item {
1171                     kind: hir::ItemKind::Trait(_, _, generics, _, _), ..
1172                 }) |
1173                 hir::Node::Item(hir::Item {
1174                     kind: hir::ItemKind::Impl(_, _, _, generics, ..), ..
1175                 }) if projection.is_some() => {
1176                     // Missing associated type bound.
1177                     suggest_restriction(&generics, "the associated type", err);
1178                     return;
1179                 }
1180
1181                 hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(_, generics), span, .. }) |
1182                 hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(_, generics), span, .. }) |
1183                 hir::Node::Item(hir::Item { kind: hir::ItemKind::Union(_, generics), span, .. }) |
1184                 hir::Node::Item(hir::Item {
1185                     kind: hir::ItemKind::Trait(_, _, generics, ..), span, ..
1186                 }) |
1187                 hir::Node::Item(hir::Item {
1188                     kind: hir::ItemKind::Impl(_, _, _, generics, ..), span, ..
1189                 }) |
1190                 hir::Node::Item(hir::Item {
1191                     kind: hir::ItemKind::Fn(_, generics, _), span, ..
1192                 }) |
1193                 hir::Node::Item(hir::Item {
1194                     kind: hir::ItemKind::TyAlias(_, generics), span, ..
1195                 }) |
1196                 hir::Node::Item(hir::Item {
1197                     kind: hir::ItemKind::TraitAlias(generics, _), span, ..
1198                 }) |
1199                 hir::Node::Item(hir::Item {
1200                     kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }), span, ..
1201                 }) |
1202                 hir::Node::TraitItem(hir::TraitItem { generics, span, .. }) |
1203                 hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
1204                 if param_ty => {
1205                     // Missing generic type parameter bound.
1206                     let param_name = self_ty.to_string();
1207                     let constraint = trait_ref.print_only_trait_path().to_string();
1208                     if suggest_constraining_type_param(
1209                         generics,
1210                         &mut err,
1211                         &param_name,
1212                         &constraint,
1213                         self.tcx.sess.source_map(),
1214                         *span,
1215                     ) {
1216                         return;
1217                     }
1218                 }
1219
1220                 hir::Node::Crate => return,
1221
1222                 _ => {}
1223             }
1224
1225             hir_id = self.tcx.hir().get_parent_item(hir_id);
1226         }
1227     }
1228
1229     /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
1230     /// suggestion to borrow the initializer in order to use have a slice instead.
1231     fn suggest_borrow_on_unsized_slice(
1232         &self,
1233         code: &ObligationCauseCode<'tcx>,
1234         err: &mut DiagnosticBuilder<'tcx>,
1235     ) {
1236         if let &ObligationCauseCode::VariableType(hir_id) = code {
1237             let parent_node = self.tcx.hir().get_parent_node(hir_id);
1238             if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
1239                 if let Some(ref expr) = local.init {
1240                     if let hir::ExprKind::Index(_, _) = expr.kind {
1241                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
1242                             err.span_suggestion(
1243                                 expr.span,
1244                                 "consider borrowing here",
1245                                 format!("&{}", snippet),
1246                                 Applicability::MachineApplicable
1247                             );
1248                         }
1249                     }
1250                 }
1251             }
1252         }
1253     }
1254
1255     fn mk_obligation_for_def_id(
1256         &self,
1257         def_id: DefId,
1258         output_ty: Ty<'tcx>,
1259         cause: ObligationCause<'tcx>,
1260         param_env: ty::ParamEnv<'tcx>,
1261     ) -> PredicateObligation<'tcx> {
1262         let new_trait_ref = ty::TraitRef {
1263             def_id,
1264             substs: self.tcx.mk_substs_trait(output_ty, &[]),
1265         };
1266         Obligation::new(cause, param_env, new_trait_ref.to_predicate())
1267     }
1268
1269     /// Given a closure's `DefId`, return the given name of the closure.
1270     ///
1271     /// This doesn't account for reassignments, but it's only used for suggestions.
1272     fn get_closure_name(
1273         &self,
1274         def_id: DefId,
1275         err: &mut DiagnosticBuilder<'_>,
1276         msg: &str,
1277     ) -> Option<String> {
1278         let get_name = |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind| -> Option<String> {
1279             // Get the local name of this closure. This can be inaccurate because
1280             // of the possibility of reassignment, but this should be good enough.
1281             match &kind {
1282                 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
1283                     Some(format!("{}", name))
1284                 }
1285                 _ => {
1286                     err.note(&msg);
1287                     None
1288                 }
1289             }
1290         };
1291
1292         let hir = self.tcx.hir();
1293         let hir_id = hir.as_local_hir_id(def_id)?;
1294         let parent_node = hir.get_parent_node(hir_id);
1295         match hir.find(parent_node) {
1296             Some(hir::Node::Stmt(hir::Stmt {
1297                 kind: hir::StmtKind::Local(local), ..
1298             })) => get_name(err, &local.pat.kind),
1299             // Different to previous arm because one is `&hir::Local` and the other
1300             // is `P<hir::Local>`.
1301             Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
1302             _ => return None,
1303         }
1304     }
1305
1306     /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1307     /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
1308     /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1309     fn suggest_fn_call(
1310         &self,
1311         obligation: &PredicateObligation<'tcx>,
1312         err: &mut DiagnosticBuilder<'_>,
1313         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1314         points_at_arg: bool,
1315     ) {
1316         let self_ty = trait_ref.self_ty();
1317         let (def_id, output_ty, callable) = match self_ty.kind {
1318             ty::Closure(def_id, substs) => {
1319                 (def_id, self.closure_sig(def_id, substs).output(), "closure")
1320             }
1321             ty::FnDef(def_id, _) => {
1322                 (def_id, self_ty.fn_sig(self.tcx).output(), "function")
1323             }
1324             _ => return,
1325         };
1326         let msg = format!("use parentheses to call the {}", callable);
1327
1328         let obligation = self.mk_obligation_for_def_id(
1329             trait_ref.def_id(),
1330             output_ty.skip_binder(),
1331             obligation.cause.clone(),
1332             obligation.param_env,
1333         );
1334
1335         match self.evaluate_obligation(&obligation) {
1336             Ok(EvaluationResult::EvaluatedToOk) |
1337             Ok(EvaluationResult::EvaluatedToOkModuloRegions) |
1338             Ok(EvaluationResult::EvaluatedToAmbig) => {}
1339             _ => return,
1340         }
1341         let hir = self.tcx.hir();
1342         // Get the name of the callable and the arguments to be used in the suggestion.
1343         let snippet = match hir.get_if_local(def_id) {
1344             Some(hir::Node::Expr(hir::Expr {
1345                 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
1346                 ..
1347             })) => {
1348                 err.span_label(*span, "consider calling this closure");
1349                 let name = match self.get_closure_name(def_id, err, &msg) {
1350                     Some(name) => name,
1351                     None => return,
1352                 };
1353                 let args = decl.inputs.iter()
1354                     .map(|_| "_")
1355                     .collect::<Vec<_>>()
1356                     .join(", ");
1357                 format!("{}({})", name, args)
1358             }
1359             Some(hir::Node::Item(hir::Item {
1360                 ident,
1361                 kind: hir::ItemKind::Fn(.., body_id),
1362                 ..
1363             })) => {
1364                 err.span_label(ident.span, "consider calling this function");
1365                 let body = hir.body(*body_id);
1366                 let args = body.params.iter()
1367                     .map(|arg| match &arg.pat.kind {
1368                         hir::PatKind::Binding(_, _, ident, None)
1369                         // FIXME: provide a better suggestion when encountering `SelfLower`, it
1370                         // should suggest a method call.
1371                         if ident.name != kw::SelfLower => ident.to_string(),
1372                         _ => "_".to_string(),
1373                     })
1374                     .collect::<Vec<_>>()
1375                     .join(", ");
1376                 format!("{}({})", ident, args)
1377             }
1378             _ => return,
1379         };
1380         if points_at_arg {
1381             // When the obligation error has been ensured to have been caused by
1382             // an argument, the `obligation.cause.span` points at the expression
1383             // of the argument, so we can provide a suggestion. This is signaled
1384             // by `points_at_arg`. Otherwise, we give a more general note.
1385             err.span_suggestion(
1386                 obligation.cause.span,
1387                 &msg,
1388                 snippet,
1389                 Applicability::HasPlaceholders,
1390             );
1391         } else {
1392             err.help(&format!("{}: `{}`", msg, snippet));
1393         }
1394     }
1395
1396     fn suggest_add_reference_to_arg(
1397         &self,
1398         obligation: &PredicateObligation<'tcx>,
1399         err: &mut DiagnosticBuilder<'tcx>,
1400         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1401         points_at_arg: bool,
1402         has_custom_message: bool,
1403     ) -> bool {
1404         if !points_at_arg {
1405             return false;
1406         }
1407
1408         let span = obligation.cause.span;
1409         let param_env = obligation.param_env;
1410         let trait_ref = trait_ref.skip_binder();
1411
1412         if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
1413             // Try to apply the original trait binding obligation by borrowing.
1414             let self_ty = trait_ref.self_ty();
1415             let found = self_ty.to_string();
1416             let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
1417             let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
1418             let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
1419             let new_obligation = Obligation::new(
1420                 ObligationCause::dummy(),
1421                 param_env,
1422                 new_trait_ref.to_predicate(),
1423             );
1424             if self.predicate_must_hold_modulo_regions(&new_obligation) {
1425                 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1426                     // We have a very specific type of error, where just borrowing this argument
1427                     // might solve the problem. In cases like this, the important part is the
1428                     // original type obligation, not the last one that failed, which is arbitrary.
1429                     // Because of this, we modify the error to refer to the original obligation and
1430                     // return early in the caller.
1431                     let msg = format!(
1432                         "the trait bound `{}: {}` is not satisfied",
1433                         found,
1434                         obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1435                     );
1436                     if has_custom_message {
1437                         err.note(&msg);
1438                     } else {
1439                         err.message = vec![(msg, Style::NoStyle)];
1440                     }
1441                     if snippet.starts_with('&') {
1442                         // This is already a literal borrow and the obligation is failing
1443                         // somewhere else in the obligation chain. Do not suggest non-sense.
1444                         return false;
1445                     }
1446                     err.span_label(span, &format!(
1447                         "expected an implementor of trait `{}`",
1448                         obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
1449                     ));
1450                     err.span_suggestion(
1451                         span,
1452                         "consider borrowing here",
1453                         format!("&{}", snippet),
1454                         Applicability::MaybeIncorrect,
1455                     );
1456                     return true;
1457                 }
1458             }
1459         }
1460         false
1461     }
1462
1463     /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1464     /// suggest removing these references until we reach a type that implements the trait.
1465     fn suggest_remove_reference(
1466         &self,
1467         obligation: &PredicateObligation<'tcx>,
1468         err: &mut DiagnosticBuilder<'tcx>,
1469         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1470     ) {
1471         let trait_ref = trait_ref.skip_binder();
1472         let span = obligation.cause.span;
1473
1474         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1475             let refs_number = snippet.chars()
1476                 .filter(|c| !c.is_whitespace())
1477                 .take_while(|c| *c == '&')
1478                 .count();
1479             if let Some('\'') = snippet.chars()
1480                 .filter(|c| !c.is_whitespace())
1481                 .skip(refs_number)
1482                 .next()
1483             { // Do not suggest removal of borrow from type arguments.
1484                 return;
1485             }
1486
1487             let mut trait_type = trait_ref.self_ty();
1488
1489             for refs_remaining in 0..refs_number {
1490                 if let ty::Ref(_, t_type, _) = trait_type.kind {
1491                     trait_type = t_type;
1492
1493                     let new_obligation = self.mk_obligation_for_def_id(
1494                         trait_ref.def_id,
1495                         trait_type,
1496                         ObligationCause::dummy(),
1497                         obligation.param_env,
1498                     );
1499
1500                     if self.predicate_may_hold(&new_obligation) {
1501                         let sp = self.tcx.sess.source_map()
1502                             .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1503
1504                         let remove_refs = refs_remaining + 1;
1505                         let format_str = format!("consider removing {} leading `&`-references",
1506                                                  remove_refs);
1507
1508                         err.span_suggestion_short(
1509                             sp, &format_str, String::new(), Applicability::MachineApplicable
1510                         );
1511                         break;
1512                     }
1513                 } else {
1514                     break;
1515                 }
1516             }
1517         }
1518     }
1519
1520     /// Check if the trait bound is implemented for a different mutability and note it in the
1521     /// final error.
1522     fn suggest_change_mut(
1523         &self,
1524         obligation: &PredicateObligation<'tcx>,
1525         err: &mut DiagnosticBuilder<'tcx>,
1526         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1527         points_at_arg: bool,
1528     ) {
1529         let span = obligation.cause.span;
1530         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1531             let refs_number = snippet.chars()
1532                 .filter(|c| !c.is_whitespace())
1533                 .take_while(|c| *c == '&')
1534                 .count();
1535             if let Some('\'') = snippet.chars()
1536                 .filter(|c| !c.is_whitespace())
1537                 .skip(refs_number)
1538                 .next()
1539             { // Do not suggest removal of borrow from type arguments.
1540                 return;
1541             }
1542             let trait_ref = self.resolve_vars_if_possible(trait_ref);
1543             if trait_ref.has_infer_types() {
1544                 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1545                 // unresolved bindings.
1546                 return;
1547             }
1548
1549             if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1550                 let trait_type = match mutability {
1551                     hir::Mutability::Mutable => self.tcx.mk_imm_ref(region, t_type),
1552                     hir::Mutability::Immutable => self.tcx.mk_mut_ref(region, t_type),
1553                 };
1554
1555                 let new_obligation = self.mk_obligation_for_def_id(
1556                     trait_ref.skip_binder().def_id,
1557                     trait_type,
1558                     ObligationCause::dummy(),
1559                     obligation.param_env,
1560                 );
1561
1562                 if self.evaluate_obligation_no_overflow(
1563                     &new_obligation,
1564                 ).must_apply_modulo_regions() {
1565                     let sp = self.tcx.sess.source_map()
1566                         .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1567                     if points_at_arg &&
1568                         mutability == hir::Mutability::Immutable &&
1569                         refs_number > 0
1570                     {
1571                         err.span_suggestion(
1572                             sp,
1573                             "consider changing this borrow's mutability",
1574                             "&mut ".to_string(),
1575                             Applicability::MachineApplicable,
1576                         );
1577                     } else {
1578                         err.note(&format!(
1579                             "`{}` is implemented for `{:?}`, but not for `{:?}`",
1580                             trait_ref.print_only_trait_path(),
1581                             trait_type,
1582                             trait_ref.skip_binder().self_ty(),
1583                         ));
1584                     }
1585                 }
1586             }
1587         }
1588     }
1589
1590     fn suggest_semicolon_removal(
1591         &self,
1592         obligation: &PredicateObligation<'tcx>,
1593         err: &mut DiagnosticBuilder<'tcx>,
1594         span: Span,
1595         trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1596     ) {
1597         let hir = self.tcx.hir();
1598         let parent_node = hir.get_parent_node(obligation.cause.body_id);
1599         let node = hir.find(parent_node);
1600         if let Some(hir::Node::Item(hir::Item {
1601             kind: hir::ItemKind::Fn(sig, _, body_id),
1602             ..
1603         })) = node {
1604             let body = hir.body(*body_id);
1605             if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1606                 if sig.decl.output.span().overlaps(span) && blk.expr.is_none() &&
1607                     "()" == &trait_ref.self_ty().to_string()
1608                 {
1609                     // FIXME(estebank): When encountering a method with a trait
1610                     // bound not satisfied in the return type with a body that has
1611                     // no return, suggest removal of semicolon on last statement.
1612                     // Once that is added, close #54771.
1613                     if let Some(ref stmt) = blk.stmts.last() {
1614                         let sp = self.tcx.sess.source_map().end_point(stmt.span);
1615                         err.span_label(sp, "consider removing this semicolon");
1616                     }
1617                 }
1618             }
1619         }
1620     }
1621
1622     /// Given some node representing a fn-like thing in the HIR map,
1623     /// returns a span and `ArgKind` information that describes the
1624     /// arguments it expects. This can be supplied to
1625     /// `report_arg_count_mismatch`.
1626     pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1627         match node {
1628             Node::Expr(&hir::Expr {
1629                 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1630                 ..
1631             }) => {
1632                 (self.tcx.sess.source_map().def_span(span),
1633                  self.tcx.hir().body(id).params.iter()
1634                     .map(|arg| {
1635                         if let hir::Pat {
1636                             kind: hir::PatKind::Tuple(ref args, _),
1637                             span,
1638                             ..
1639                         } = *arg.pat {
1640                             ArgKind::Tuple(
1641                                 Some(span),
1642                                 args.iter().map(|pat| {
1643                                     let snippet = self.tcx.sess.source_map()
1644                                         .span_to_snippet(pat.span).unwrap();
1645                                     (snippet, "_".to_owned())
1646                                 }).collect::<Vec<_>>(),
1647                             )
1648                         } else {
1649                             let name = self.tcx.sess.source_map()
1650                                 .span_to_snippet(arg.pat.span).unwrap();
1651                             ArgKind::Arg(name, "_".to_owned())
1652                         }
1653                     })
1654                     .collect::<Vec<ArgKind>>())
1655             }
1656             Node::Item(&hir::Item {
1657                 span,
1658                 kind: hir::ItemKind::Fn(ref sig, ..),
1659                 ..
1660             }) |
1661             Node::ImplItem(&hir::ImplItem {
1662                 span,
1663                 kind: hir::ImplItemKind::Method(ref sig, _),
1664                 ..
1665             }) |
1666             Node::TraitItem(&hir::TraitItem {
1667                 span,
1668                 kind: hir::TraitItemKind::Method(ref sig, _),
1669                 ..
1670             }) => {
1671                 (self.tcx.sess.source_map().def_span(span), sig.decl.inputs.iter()
1672                         .map(|arg| match arg.clone().kind {
1673                     hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1674                         Some(arg.span),
1675                         vec![("_".to_owned(), "_".to_owned()); tys.len()]
1676                     ),
1677                     _ => ArgKind::empty()
1678                 }).collect::<Vec<ArgKind>>())
1679             }
1680             Node::Ctor(ref variant_data) => {
1681                 let span = variant_data.ctor_hir_id()
1682                     .map(|hir_id| self.tcx.hir().span(hir_id))
1683                     .unwrap_or(DUMMY_SP);
1684                 let span = self.tcx.sess.source_map().def_span(span);
1685
1686                 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1687             }
1688             _ => panic!("non-FnLike node found: {:?}", node),
1689         }
1690     }
1691
1692     /// Reports an error when the number of arguments needed by a
1693     /// trait match doesn't match the number that the expression
1694     /// provides.
1695     pub fn report_arg_count_mismatch(
1696         &self,
1697         span: Span,
1698         found_span: Option<Span>,
1699         expected_args: Vec<ArgKind>,
1700         found_args: Vec<ArgKind>,
1701         is_closure: bool,
1702     ) -> DiagnosticBuilder<'tcx> {
1703         let kind = if is_closure { "closure" } else { "function" };
1704
1705         let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1706             let arg_length = arguments.len();
1707             let distinct = match &other[..] {
1708                 &[ArgKind::Tuple(..)] => true,
1709                 _ => false,
1710             };
1711             match (arg_length, arguments.get(0)) {
1712                 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1713                     format!("a single {}-tuple as argument", fields.len())
1714                 }
1715                 _ => format!("{} {}argument{}",
1716                              arg_length,
1717                              if distinct && arg_length > 1 { "distinct " } else { "" },
1718                              pluralize!(arg_length))
1719             }
1720         };
1721
1722         let expected_str = args_str(&expected_args, &found_args);
1723         let found_str = args_str(&found_args, &expected_args);
1724
1725         let mut err = struct_span_err!(
1726             self.tcx.sess,
1727             span,
1728             E0593,
1729             "{} is expected to take {}, but it takes {}",
1730             kind,
1731             expected_str,
1732             found_str,
1733         );
1734
1735         err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1736
1737         if let Some(found_span) = found_span {
1738             err.span_label(found_span, format!("takes {}", found_str));
1739
1740             // move |_| { ... }
1741             // ^^^^^^^^-- def_span
1742             //
1743             // move |_| { ... }
1744             // ^^^^^-- prefix
1745             let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1746             // move |_| { ... }
1747             //      ^^^-- pipe_span
1748             let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) {
1749                 span
1750             } else {
1751                 found_span
1752             };
1753
1754             // Suggest to take and ignore the arguments with expected_args_length `_`s if
1755             // found arguments is empty (assume the user just wants to ignore args in this case).
1756             // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1757             if found_args.is_empty() && is_closure {
1758                 let underscores = vec!["_"; expected_args.len()].join(", ");
1759                 err.span_suggestion(
1760                     pipe_span,
1761                     &format!(
1762                         "consider changing the closure to take and ignore the expected argument{}",
1763                         if expected_args.len() < 2 {
1764                             ""
1765                         } else {
1766                             "s"
1767                         }
1768                     ),
1769                     format!("|{}|", underscores),
1770                     Applicability::MachineApplicable,
1771                 );
1772             }
1773
1774             if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1775                 if fields.len() == expected_args.len() {
1776                     let sugg = fields.iter()
1777                         .map(|(name, _)| name.to_owned())
1778                         .collect::<Vec<String>>()
1779                         .join(", ");
1780                     err.span_suggestion(
1781                         found_span,
1782                         "change the closure to take multiple arguments instead of a single tuple",
1783                         format!("|{}|", sugg),
1784                         Applicability::MachineApplicable,
1785                     );
1786                 }
1787             }
1788             if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1789                 if fields.len() == found_args.len() && is_closure {
1790                     let sugg = format!(
1791                         "|({}){}|",
1792                         found_args.iter()
1793                             .map(|arg| match arg {
1794                                 ArgKind::Arg(name, _) => name.to_owned(),
1795                                 _ => "_".to_owned(),
1796                             })
1797                             .collect::<Vec<String>>()
1798                             .join(", "),
1799                         // add type annotations if available
1800                         if found_args.iter().any(|arg| match arg {
1801                             ArgKind::Arg(_, ty) => ty != "_",
1802                             _ => false,
1803                         }) {
1804                             format!(": ({})",
1805                                     fields.iter()
1806                                         .map(|(_, ty)| ty.to_owned())
1807                                         .collect::<Vec<String>>()
1808                                         .join(", "))
1809                         } else {
1810                             String::new()
1811                         },
1812                     );
1813                     err.span_suggestion(
1814                         found_span,
1815                         "change the closure to accept a tuple instead of individual arguments",
1816                         sugg,
1817                         Applicability::MachineApplicable,
1818                     );
1819                 }
1820             }
1821         }
1822
1823         err
1824     }
1825
1826     fn report_closure_arg_mismatch(
1827         &self,
1828         span: Span,
1829         found_span: Option<Span>,
1830         expected_ref: ty::PolyTraitRef<'tcx>,
1831         found: ty::PolyTraitRef<'tcx>,
1832     ) -> DiagnosticBuilder<'tcx> {
1833         fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1834             let inputs = trait_ref.substs.type_at(1);
1835             let sig = if let ty::Tuple(inputs) = inputs.kind {
1836                 tcx.mk_fn_sig(
1837                     inputs.iter().map(|k| k.expect_ty()),
1838                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1839                     false,
1840                     hir::Unsafety::Normal,
1841                     ::rustc_target::spec::abi::Abi::Rust
1842                 )
1843             } else {
1844                 tcx.mk_fn_sig(
1845                     ::std::iter::once(inputs),
1846                     tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1847                     false,
1848                     hir::Unsafety::Normal,
1849                     ::rustc_target::spec::abi::Abi::Rust
1850                 )
1851             };
1852             ty::Binder::bind(sig).to_string()
1853         }
1854
1855         let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1856         let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1857                                        "type mismatch in {} arguments",
1858                                        if argument_is_closure { "closure" } else { "function" });
1859
1860         let found_str = format!(
1861             "expected signature of `{}`",
1862             build_fn_sig_string(self.tcx, found.skip_binder())
1863         );
1864         err.span_label(span, found_str);
1865
1866         let found_span = found_span.unwrap_or(span);
1867         let expected_str = format!(
1868             "found signature of `{}`",
1869             build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1870         );
1871         err.span_label(found_span, expected_str);
1872
1873         err
1874     }
1875 }
1876
1877 impl<'tcx> TyCtxt<'tcx> {
1878     pub fn recursive_type_with_infinite_size_error(self,
1879                                                    type_def_id: DefId)
1880                                                    -> DiagnosticBuilder<'tcx>
1881     {
1882         assert!(type_def_id.is_local());
1883         let span = self.hir().span_if_local(type_def_id).unwrap();
1884         let span = self.sess.source_map().def_span(span);
1885         let mut err = struct_span_err!(self.sess, span, E0072,
1886                                        "recursive type `{}` has infinite size",
1887                                        self.def_path_str(type_def_id));
1888         err.span_label(span, "recursive type has infinite size");
1889         err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1890                            at some point to make `{}` representable",
1891                           self.def_path_str(type_def_id)));
1892         err
1893     }
1894
1895     pub fn report_object_safety_error(
1896         self,
1897         span: Span,
1898         trait_def_id: DefId,
1899         violations: Vec<ObjectSafetyViolation>,
1900     ) -> DiagnosticBuilder<'tcx> {
1901         let trait_str = self.def_path_str(trait_def_id);
1902         let span = self.sess.source_map().def_span(span);
1903         let mut err = struct_span_err!(
1904             self.sess, span, E0038,
1905             "the trait `{}` cannot be made into an object",
1906             trait_str);
1907         err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1908
1909         let mut reported_violations = FxHashSet::default();
1910         for violation in violations {
1911             if reported_violations.insert(violation.clone()) {
1912                 match violation.span() {
1913                     Some(span) => err.span_label(span, violation.error_msg()),
1914                     None => err.note(&violation.error_msg()),
1915                 };
1916             }
1917         }
1918
1919         if self.sess.trait_methods_not_found.borrow().contains(&span) {
1920             // Avoid emitting error caused by non-existing method (#58734)
1921             err.cancel();
1922         }
1923
1924         err
1925     }
1926 }
1927
1928 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1929     fn maybe_report_ambiguity(
1930         &self,
1931         obligation: &PredicateObligation<'tcx>,
1932         body_id: Option<hir::BodyId>,
1933     ) {
1934         // Unable to successfully determine, probably means
1935         // insufficient type information, but could mean
1936         // ambiguous impls. The latter *ought* to be a
1937         // coherence violation, so we don't report it here.
1938
1939         let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1940         let span = obligation.cause.span;
1941
1942         debug!(
1943             "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1944             predicate,
1945             obligation,
1946             body_id,
1947             obligation.cause.code,
1948         );
1949
1950         // Ambiguity errors are often caused as fallout from earlier
1951         // errors. So just ignore them if this infcx is tainted.
1952         if self.is_tainted_by_errors() {
1953             return;
1954         }
1955
1956         let mut err = match predicate {
1957             ty::Predicate::Trait(ref data) => {
1958                 let trait_ref = data.to_poly_trait_ref();
1959                 let self_ty = trait_ref.self_ty();
1960                 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1961
1962                 if predicate.references_error() {
1963                     return;
1964                 }
1965                 // Typically, this ambiguity should only happen if
1966                 // there are unresolved type inference variables
1967                 // (otherwise it would suggest a coherence
1968                 // failure). But given #21974 that is not necessarily
1969                 // the case -- we can have multiple where clauses that
1970                 // are only distinguished by a region, which results
1971                 // in an ambiguity even when all types are fully
1972                 // known, since we don't dispatch based on region
1973                 // relationships.
1974
1975                 // This is kind of a hack: it frequently happens that some earlier
1976                 // error prevents types from being fully inferred, and then we get
1977                 // a bunch of uninteresting errors saying something like "<generic
1978                 // #0> doesn't implement Sized".  It may even be true that we
1979                 // could just skip over all checks where the self-ty is an
1980                 // inference variable, but I was afraid that there might be an
1981                 // inference variable created, registered as an obligation, and
1982                 // then never forced by writeback, and hence by skipping here we'd
1983                 // be ignoring the fact that we don't KNOW the type works
1984                 // out. Though even that would probably be harmless, given that
1985                 // we're only talking about builtin traits, which are known to be
1986                 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1987                 // avoid inundating the user with unnecessary errors, but we now
1988                 // check upstream for type errors and dont add the obligations to
1989                 // begin with in those cases.
1990                 if self.tcx.lang_items().sized_trait()
1991                     .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1992                 {
1993                     self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
1994                     return;
1995                 }
1996                 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
1997                 err.note(&format!("cannot resolve `{}`", predicate));
1998                 if let (Ok(ref snippet), ObligationCauseCode::BindingObligation(ref def_id, _)) = (
1999                     self.tcx.sess.source_map().span_to_snippet(span),
2000                     &obligation.cause.code,
2001                 ) {
2002                     let generics = self.tcx.generics_of(*def_id);
2003                     if !generics.params.is_empty() && !snippet.ends_with('>'){
2004                         // FIXME: To avoid spurious suggestions in functions where type arguments
2005                         // where already supplied, we check the snippet to make sure it doesn't
2006                         // end with a turbofish. Ideally we would have access to a `PathSegment`
2007                         // instead. Otherwise we would produce the following output:
2008                         //
2009                         // error[E0283]: type annotations needed
2010                         //   --> $DIR/issue-54954.rs:3:24
2011                         //    |
2012                         // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
2013                         //    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^
2014                         //    |                        |
2015                         //    |                        cannot infer type
2016                         //    |                        help: consider specifying the type argument
2017                         //    |                        in the function call:
2018                         //    |                        `Tt::const_val::<[i8; 123]>::<T>`
2019                         // ...
2020                         // LL |     const fn const_val<T: Sized>() -> usize {
2021                         //    |              --------- - required by this bound in `Tt::const_val`
2022                         //    |
2023                         //    = note: cannot resolve `_: Tt`
2024
2025                         err.span_suggestion(
2026                             span,
2027                             &format!(
2028                                 "consider specifying the type argument{} in the function call",
2029                                 if generics.params.len() > 1 {
2030                                     "s"
2031                                 } else {
2032                                     ""
2033                                 },
2034                             ),
2035                             format!("{}::<{}>", snippet, generics.params.iter()
2036                                 .map(|p| p.name.to_string())
2037                                 .collect::<Vec<String>>()
2038                                 .join(", ")),
2039                             Applicability::HasPlaceholders,
2040                         );
2041                     }
2042                 }
2043                 err
2044             }
2045
2046             ty::Predicate::WellFormed(ty) => {
2047                 // Same hacky approach as above to avoid deluging user
2048                 // with error messages.
2049                 if ty.references_error() || self.tcx.sess.has_errors() {
2050                     return;
2051                 }
2052                 self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
2053             }
2054
2055             ty::Predicate::Subtype(ref data) => {
2056                 if data.references_error() || self.tcx.sess.has_errors() {
2057                     // no need to overload user in such cases
2058                     return
2059                 }
2060                 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
2061                 // both must be type variables, or the other would've been instantiated
2062                 assert!(a.is_ty_var() && b.is_ty_var());
2063                 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
2064             }
2065             ty::Predicate::Projection(ref data) => {
2066                 let trait_ref = data.to_poly_trait_ref(self.tcx);
2067                 let self_ty = trait_ref.self_ty();
2068                 if predicate.references_error() {
2069                     return;
2070                 }
2071                 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
2072                 err.note(&format!("cannot resolve `{}`", predicate));
2073                 err
2074             }
2075
2076             _ => {
2077                 if self.tcx.sess.has_errors() {
2078                     return;
2079                 }
2080                 let mut err = struct_span_err!(
2081                     self.tcx.sess,
2082                     span,
2083                     E0284,
2084                     "type annotations needed: cannot resolve `{}`",
2085                     predicate,
2086                 );
2087                 err.span_label(span, &format!("cannot resolve `{}`", predicate));
2088                 err
2089             }
2090         };
2091         self.note_obligation_cause(&mut err, obligation);
2092         err.emit();
2093     }
2094
2095     /// Returns `true` if the trait predicate may apply for *some* assignment
2096     /// to the type parameters.
2097     fn predicate_can_apply(
2098         &self,
2099         param_env: ty::ParamEnv<'tcx>,
2100         pred: ty::PolyTraitRef<'tcx>,
2101     ) -> bool {
2102         struct ParamToVarFolder<'a, 'tcx> {
2103             infcx: &'a InferCtxt<'a, 'tcx>,
2104             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2105         }
2106
2107         impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
2108             fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx }
2109
2110             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2111                 if let ty::Param(ty::ParamTy {name, .. }) = ty.kind {
2112                     let infcx = self.infcx;
2113                     self.var_map.entry(ty).or_insert_with(||
2114                         infcx.next_ty_var(
2115                             TypeVariableOrigin {
2116                                 kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
2117                                 span: DUMMY_SP,
2118                             }
2119                         )
2120                     )
2121                 } else {
2122                     ty.super_fold_with(self)
2123                 }
2124             }
2125         }
2126
2127         self.probe(|_| {
2128             let mut selcx = SelectionContext::new(self);
2129
2130             let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
2131                 infcx: self,
2132                 var_map: Default::default()
2133             });
2134
2135             let cleaned_pred = super::project::normalize(
2136                 &mut selcx,
2137                 param_env,
2138                 ObligationCause::dummy(),
2139                 &cleaned_pred
2140             ).value;
2141
2142             let obligation = Obligation::new(
2143                 ObligationCause::dummy(),
2144                 param_env,
2145                 cleaned_pred.to_predicate()
2146             );
2147
2148             self.predicate_may_hold(&obligation)
2149         })
2150     }
2151
2152     fn note_obligation_cause(
2153         &self,
2154         err: &mut DiagnosticBuilder<'_>,
2155         obligation: &PredicateObligation<'tcx>,
2156     ) {
2157         // First, attempt to add note to this error with an async-await-specific
2158         // message, and fall back to regular note otherwise.
2159         if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2160             self.note_obligation_cause_code(err, &obligation.predicate, &obligation.cause.code,
2161                                             &mut vec![]);
2162         }
2163     }
2164
2165     /// Adds an async-await specific note to the diagnostic when the future does not implement
2166     /// an auto trait because of a captured type.
2167     ///
2168     /// ```ignore (diagnostic)
2169     /// note: future does not implement `Qux` as this value is used across an await
2170     ///   --> $DIR/issue-64130-3-other.rs:17:5
2171     ///    |
2172     /// LL |     let x = Foo;
2173     ///    |         - has type `Foo`
2174     /// LL |     baz().await;
2175     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2176     /// LL | }
2177     ///    | - `x` is later dropped here
2178     /// ```
2179     ///
2180     /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2181     /// is "replaced" with a different message and a more specific error.
2182     ///
2183     /// ```ignore (diagnostic)
2184     /// error: future cannot be sent between threads safely
2185     ///   --> $DIR/issue-64130-2-send.rs:21:5
2186     ///    |
2187     /// LL | fn is_send<T: Send>(t: T) { }
2188     ///    |    -------    ---- required by this bound in `is_send`
2189     /// ...
2190     /// LL |     is_send(bar());
2191     ///    |     ^^^^^^^ future returned by `bar` is not send
2192     ///    |
2193     ///    = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2194     ///            implemented for `Foo`
2195     /// note: future is not send as this value is used across an await
2196     ///   --> $DIR/issue-64130-2-send.rs:15:5
2197     ///    |
2198     /// LL |     let x = Foo;
2199     ///    |         - has type `Foo`
2200     /// LL |     baz().await;
2201     ///    |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2202     /// LL | }
2203     ///    | - `x` is later dropped here
2204     /// ```
2205     ///
2206     /// Returns `true` if an async-await specific note was added to the diagnostic.
2207     fn maybe_note_obligation_cause_for_async_await(
2208         &self,
2209         err: &mut DiagnosticBuilder<'_>,
2210         obligation: &PredicateObligation<'tcx>,
2211     ) -> bool {
2212         debug!("maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
2213                 obligation.cause.span={:?}", obligation.predicate, obligation.cause.span);
2214         let source_map = self.tcx.sess.source_map();
2215
2216         // Attempt to detect an async-await error by looking at the obligation causes, looking
2217         // for a generator to be present.
2218         //
2219         // When a future does not implement a trait because of a captured type in one of the
2220         // generators somewhere in the call stack, then the result is a chain of obligations.
2221         //
2222         // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
2223         // future is passed as an argument to a function C which requires a `Send` type, then the
2224         // chain looks something like this:
2225         //
2226         // - `BuiltinDerivedObligation` with a generator witness (B)
2227         // - `BuiltinDerivedObligation` with a generator (B)
2228         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
2229         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2230         // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2231         // - `BuiltinDerivedObligation` with a generator witness (A)
2232         // - `BuiltinDerivedObligation` with a generator (A)
2233         // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
2234         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2235         // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2236         // - `BindingObligation` with `impl_send (Send requirement)
2237         //
2238         // The first obligation in the chain is the most useful and has the generator that captured
2239         // the type. The last generator has information about where the bound was introduced. At
2240         // least one generator should be present for this diagnostic to be modified.
2241         let (mut trait_ref, mut target_ty) = match obligation.predicate {
2242             ty::Predicate::Trait(p) =>
2243                 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty())),
2244             _ => (None, None),
2245         };
2246         let mut generator = None;
2247         let mut last_generator = None;
2248         let mut next_code = Some(&obligation.cause.code);
2249         while let Some(code) = next_code {
2250             debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
2251             match code {
2252                 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) |
2253                 ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
2254                     let ty = derived_obligation.parent_trait_ref.self_ty();
2255                     debug!("maybe_note_obligation_cause_for_async_await: \
2256                             parent_trait_ref={:?} self_ty.kind={:?}",
2257                            derived_obligation.parent_trait_ref, ty.kind);
2258
2259                     match ty.kind {
2260                         ty::Generator(did, ..) => {
2261                             generator = generator.or(Some(did));
2262                             last_generator = Some(did);
2263                         },
2264                         ty::GeneratorWitness(..) => {},
2265                         _ if generator.is_none() => {
2266                             trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
2267                             target_ty = Some(ty);
2268                         },
2269                         _ => {},
2270                     }
2271
2272                     next_code = Some(derived_obligation.parent_code.as_ref());
2273                 },
2274                 _ => break,
2275             }
2276         }
2277
2278         // Only continue if a generator was found.
2279         debug!("maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
2280                 target_ty={:?}", generator, trait_ref, target_ty);
2281         let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
2282             (Some(generator_did), Some(trait_ref), Some(target_ty)) =>
2283                 (generator_did, trait_ref, target_ty),
2284             _ => return false,
2285         };
2286
2287         let span = self.tcx.def_span(generator_did);
2288
2289         // Do not ICE on closure typeck (#66868).
2290         if let None = self.tcx.hir().as_local_hir_id(generator_did) {
2291             return false;
2292         }
2293
2294         // Get the tables from the infcx if the generator is the function we are
2295         // currently type-checking; otherwise, get them by performing a query.
2296         // This is needed to avoid cycles.
2297         let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
2298         let generator_did_root = self.tcx.closure_base_def_id(generator_did);
2299         debug!("maybe_note_obligation_cause_for_async_await: generator_did={:?} \
2300              generator_did_root={:?} in_progress_tables.local_id_root={:?} span={:?}",
2301             generator_did, generator_did_root,
2302             in_progress_tables.as_ref().map(|t| t.local_id_root), span);
2303         let query_tables;
2304         let tables: &TypeckTables<'tcx> = match &in_progress_tables {
2305             Some(t) if t.local_id_root == Some(generator_did_root) => t,
2306             _ => {
2307                 query_tables = self.tcx.typeck_tables_of(generator_did);
2308                 &query_tables
2309             }
2310         };
2311
2312         // Look for a type inside the generator interior that matches the target type to get
2313         // a span.
2314         let target_ty_erased = self.tcx.erase_regions(&target_ty);
2315         let target_span = tables.generator_interior_types.iter()
2316             .find(|ty::GeneratorInteriorTypeCause { ty, .. }| {
2317                 // Careful: the regions for types that appear in the
2318                 // generator interior are not generally known, so we
2319                 // want to erase them when comparing (and anyway,
2320                 // `Send` and other bounds are generally unaffected by
2321                 // the choice of region).  When erasing regions, we
2322                 // also have to erase late-bound regions. This is
2323                 // because the types that appear in the generator
2324                 // interior generally contain "bound regions" to
2325                 // represent regions that are part of the suspended
2326                 // generator frame. Bound regions are preserved by
2327                 // `erase_regions` and so we must also call
2328                 // `erase_late_bound_regions`.
2329                 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(*ty));
2330                 let ty_erased = self.tcx.erase_regions(&ty_erased);
2331                 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
2332                 debug!("maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
2333                         target_ty_erased={:?} eq={:?}", ty_erased, target_ty_erased, eq);
2334                 eq
2335             })
2336             .map(|ty::GeneratorInteriorTypeCause { span, scope_span, .. }|
2337                  (span, source_map.span_to_snippet(*span), scope_span));
2338         debug!("maybe_note_obligation_cause_for_async_await: target_ty={:?} \
2339                 generator_interior_types={:?} target_span={:?}",
2340                 target_ty, tables.generator_interior_types, target_span);
2341         if let Some((target_span, Ok(snippet), scope_span)) = target_span {
2342             self.note_obligation_cause_for_async_await(
2343                 err, *target_span, scope_span, snippet, generator_did, last_generator,
2344                 trait_ref, target_ty, tables, obligation, next_code,
2345             );
2346             true
2347         } else {
2348             false
2349         }
2350     }
2351
2352     /// Unconditionally adds the diagnostic note described in
2353     /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2354     fn note_obligation_cause_for_async_await(
2355         &self,
2356         err: &mut DiagnosticBuilder<'_>,
2357         target_span: Span,
2358         scope_span: &Option<Span>,
2359         snippet: String,
2360         first_generator: DefId,
2361         last_generator: Option<DefId>,
2362         trait_ref: ty::TraitRef<'_>,
2363         target_ty: Ty<'tcx>,
2364         tables: &ty::TypeckTables<'_>,
2365         obligation: &PredicateObligation<'tcx>,
2366         next_code: Option<&ObligationCauseCode<'tcx>>,
2367     ) {
2368         let source_map = self.tcx.sess.source_map();
2369
2370         let is_async_fn = self.tcx.parent(first_generator)
2371             .map(|parent_did| self.tcx.asyncness(parent_did))
2372             .map(|parent_asyncness| parent_asyncness == hir::IsAsync::Async)
2373             .unwrap_or(false);
2374         let is_async_move = self.tcx.hir().as_local_hir_id(first_generator)
2375             .and_then(|hir_id| self.tcx.hir().maybe_body_owned_by(hir_id))
2376             .map(|body_id| self.tcx.hir().body(body_id))
2377             .and_then(|body| body.generator_kind())
2378             .map(|generator_kind| match generator_kind {
2379                 hir::GeneratorKind::Async(..) => true,
2380                 _ => false,
2381             })
2382             .unwrap_or(false);
2383         let await_or_yield = if is_async_fn || is_async_move { "await" } else { "yield" };
2384
2385         // Special case the primary error message when send or sync is the trait that was
2386         // not implemented.
2387         let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
2388         let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
2389         let trait_explanation = if is_send || is_sync {
2390             let (trait_name, trait_verb) = if is_send {
2391                 ("`Send`", "sent")
2392             } else {
2393                 ("`Sync`", "shared")
2394             };
2395
2396             err.clear_code();
2397             err.set_primary_message(
2398                 format!("future cannot be {} between threads safely", trait_verb)
2399             );
2400
2401             let original_span = err.span.primary_span().unwrap();
2402             let mut span = MultiSpan::from_span(original_span);
2403
2404             let message = if let Some(name) = last_generator
2405                 .and_then(|generator_did| self.tcx.parent(generator_did))
2406                 .and_then(|parent_did| self.tcx.hir().as_local_hir_id(parent_did))
2407                 .and_then(|parent_hir_id| self.tcx.hir().opt_name(parent_hir_id))
2408             {
2409                 format!("future returned by `{}` is not {}", name, trait_name)
2410             } else {
2411                 format!("future is not {}", trait_name)
2412             };
2413
2414             span.push_span_label(original_span, message);
2415             err.set_span(span);
2416
2417             format!("is not {}", trait_name)
2418         } else {
2419             format!("does not implement `{}`", trait_ref.print_only_trait_path())
2420         };
2421
2422         // Look at the last interior type to get a span for the `.await`.
2423         let await_span = tables.generator_interior_types.iter().map(|i| i.span).last().unwrap();
2424         let mut span = MultiSpan::from_span(await_span);
2425         span.push_span_label(
2426             await_span,
2427             format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet));
2428
2429         span.push_span_label(target_span, format!("has type `{}`", target_ty));
2430
2431         // If available, use the scope span to annotate the drop location.
2432         if let Some(scope_span) = scope_span {
2433             span.push_span_label(
2434                 source_map.end_point(*scope_span),
2435                 format!("`{}` is later dropped here", snippet),
2436             );
2437         }
2438
2439         err.span_note(span, &format!(
2440             "future {} as this value is used across an {}",
2441             trait_explanation,
2442             await_or_yield,
2443         ));
2444
2445         // Add a note for the item obligation that remains - normally a note pointing to the
2446         // bound that introduced the obligation (e.g. `T: Send`).
2447         debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2448         self.note_obligation_cause_code(
2449             err,
2450             &obligation.predicate,
2451             next_code.unwrap(),
2452             &mut Vec::new(),
2453         );
2454     }
2455
2456     fn note_obligation_cause_code<T>(&self,
2457                                      err: &mut DiagnosticBuilder<'_>,
2458                                      predicate: &T,
2459                                      cause_code: &ObligationCauseCode<'tcx>,
2460                                      obligated_types: &mut Vec<&ty::TyS<'tcx>>)
2461         where T: fmt::Display
2462     {
2463         let tcx = self.tcx;
2464         match *cause_code {
2465             ObligationCauseCode::ExprAssignable |
2466             ObligationCauseCode::MatchExpressionArm { .. } |
2467             ObligationCauseCode::MatchExpressionArmPattern { .. } |
2468             ObligationCauseCode::IfExpression { .. } |
2469             ObligationCauseCode::IfExpressionWithNoElse |
2470             ObligationCauseCode::MainFunctionType |
2471             ObligationCauseCode::StartFunctionType |
2472             ObligationCauseCode::IntrinsicType |
2473             ObligationCauseCode::MethodReceiver |
2474             ObligationCauseCode::ReturnNoExpression |
2475             ObligationCauseCode::MiscObligation => {}
2476             ObligationCauseCode::SliceOrArrayElem => {
2477                 err.note("slice and array elements must have `Sized` type");
2478             }
2479             ObligationCauseCode::TupleElem => {
2480                 err.note("only the last element of a tuple may have a dynamically sized type");
2481             }
2482             ObligationCauseCode::ProjectionWf(data) => {
2483                 err.note(&format!(
2484                     "required so that the projection `{}` is well-formed",
2485                     data,
2486                 ));
2487             }
2488             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2489                 err.note(&format!(
2490                     "required so that reference `{}` does not outlive its referent",
2491                     ref_ty,
2492                 ));
2493             }
2494             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2495                 err.note(&format!(
2496                     "required so that the lifetime bound of `{}` for `{}` is satisfied",
2497                     region,
2498                     object_ty,
2499                 ));
2500             }
2501             ObligationCauseCode::ItemObligation(item_def_id) => {
2502                 let item_name = tcx.def_path_str(item_def_id);
2503                 let msg = format!("required by `{}`", item_name);
2504
2505                 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
2506                     let sp = tcx.sess.source_map().def_span(sp);
2507                     err.span_label(sp, &msg);
2508                 } else {
2509                     err.note(&msg);
2510                 }
2511             }
2512             ObligationCauseCode::BindingObligation(item_def_id, span) => {
2513                 let item_name = tcx.def_path_str(item_def_id);
2514                 let msg = format!("required by this bound in `{}`", item_name);
2515                 if let Some(ident) = tcx.opt_item_name(item_def_id) {
2516                     err.span_label(ident.span, "");
2517                 }
2518                 if span != DUMMY_SP {
2519                     err.span_label(span, &msg);
2520                 } else {
2521                     err.note(&msg);
2522                 }
2523             }
2524             ObligationCauseCode::ObjectCastObligation(object_ty) => {
2525                 err.note(&format!("required for the cast to the object type `{}`",
2526                                   self.ty_to_string(object_ty)));
2527             }
2528             ObligationCauseCode::Coercion { source: _, target } => {
2529                 err.note(&format!("required by cast to type `{}`",
2530                                   self.ty_to_string(target)));
2531             }
2532             ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
2533                 err.note("the `Copy` trait is required because the \
2534                           repeated element will be copied");
2535                 if suggest_const_in_array_repeat_expressions {
2536                     err.note("this array initializer can be evaluated at compile-time, for more \
2537                               information, see issue \
2538                               https://github.com/rust-lang/rust/issues/49147");
2539                     if tcx.sess.opts.unstable_features.is_nightly_build() {
2540                         err.help("add `#![feature(const_in_array_repeat_expressions)]` to the \
2541                                   crate attributes to enable");
2542                     }
2543                 }
2544             }
2545             ObligationCauseCode::VariableType(_) => {
2546                 err.note("all local variables must have a statically known size");
2547                 if !self.tcx.features().unsized_locals {
2548                     err.help("unsized locals are gated as an unstable feature");
2549                 }
2550             }
2551             ObligationCauseCode::SizedArgumentType => {
2552                 err.note("all function arguments must have a statically known size");
2553                 if !self.tcx.features().unsized_locals {
2554                     err.help("unsized locals are gated as an unstable feature");
2555                 }
2556             }
2557             ObligationCauseCode::SizedReturnType => {
2558                 err.note("the return type of a function must have a \
2559                           statically known size");
2560             }
2561             ObligationCauseCode::SizedYieldType => {
2562                 err.note("the yield type of a generator must have a \
2563                           statically known size");
2564             }
2565             ObligationCauseCode::AssignmentLhsSized => {
2566                 err.note("the left-hand-side of an assignment must have a statically known size");
2567             }
2568             ObligationCauseCode::TupleInitializerSized => {
2569                 err.note("tuples must have a statically known size to be initialized");
2570             }
2571             ObligationCauseCode::StructInitializerSized => {
2572                 err.note("structs must have a statically known size to be initialized");
2573             }
2574             ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
2575                 match *item {
2576                     AdtKind::Struct => {
2577                         if last {
2578                             err.note("the last field of a packed struct may only have a \
2579                                       dynamically sized type if it does not need drop to be run");
2580                         } else {
2581                             err.note("only the last field of a struct may have a dynamically \
2582                                       sized type");
2583                         }
2584                     }
2585                     AdtKind::Union => {
2586                         err.note("no field of a union may have a dynamically sized type");
2587                     }
2588                     AdtKind::Enum => {
2589                         err.note("no field of an enum variant may have a dynamically sized type");
2590                     }
2591                 }
2592             }
2593             ObligationCauseCode::ConstSized => {
2594                 err.note("constant expressions must have a statically known size");
2595             }
2596             ObligationCauseCode::ConstPatternStructural => {
2597                 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2598             }
2599             ObligationCauseCode::SharedStatic => {
2600                 err.note("shared static variables must have a type that implements `Sync`");
2601             }
2602             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2603                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2604                 let ty = parent_trait_ref.skip_binder().self_ty();
2605                 err.note(&format!("required because it appears within the type `{}`", ty));
2606                 obligated_types.push(ty);
2607
2608                 let parent_predicate = parent_trait_ref.to_predicate();
2609                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2610                     self.note_obligation_cause_code(err,
2611                                                     &parent_predicate,
2612                                                     &data.parent_code,
2613                                                     obligated_types);
2614                 }
2615             }
2616             ObligationCauseCode::ImplDerivedObligation(ref data) => {
2617                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2618                 err.note(
2619                     &format!("required because of the requirements on the impl of `{}` for `{}`",
2620                              parent_trait_ref.print_only_trait_path(),
2621                              parent_trait_ref.skip_binder().self_ty()));
2622                 let parent_predicate = parent_trait_ref.to_predicate();
2623                 self.note_obligation_cause_code(err,
2624                                                 &parent_predicate,
2625                                                 &data.parent_code,
2626                                                 obligated_types);
2627             }
2628             ObligationCauseCode::CompareImplMethodObligation { .. } => {
2629                 err.note(
2630                     &format!("the requirement `{}` appears on the impl method \
2631                               but not on the corresponding trait method",
2632                              predicate));
2633             }
2634             ObligationCauseCode::ReturnType |
2635             ObligationCauseCode::ReturnValue(_) |
2636             ObligationCauseCode::BlockTailExpression(_) => (),
2637             ObligationCauseCode::TrivialBound => {
2638                 err.help("see issue #48214");
2639                 if tcx.sess.opts.unstable_features.is_nightly_build() {
2640                     err.help("add `#![feature(trivial_bounds)]` to the \
2641                               crate attributes to enable",
2642                     );
2643                 }
2644             }
2645             ObligationCauseCode::AssocTypeBound(ref data) => {
2646                 err.span_label(data.original, "associated type defined here");
2647                 if let Some(sp) = data.impl_span {
2648                     err.span_label(sp, "in this `impl` item");
2649                 }
2650                 for sp in &data.bounds {
2651                     err.span_label(*sp, "restricted in this bound");
2652                 }
2653             }
2654         }
2655     }
2656
2657     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2658         let current_limit = self.tcx.sess.recursion_limit.get();
2659         let suggested_limit = current_limit * 2;
2660         err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
2661                           suggested_limit));
2662     }
2663
2664     fn is_recursive_obligation(&self,
2665                                obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2666                                cause_code: &ObligationCauseCode<'tcx>) -> bool {
2667         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2668             let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2669
2670             if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
2671                 return true;
2672             }
2673         }
2674         false
2675     }
2676 }
2677
2678 /// Summarizes information
2679 #[derive(Clone)]
2680 pub enum ArgKind {
2681     /// An argument of non-tuple type. Parameters are (name, ty)
2682     Arg(String, String),
2683
2684     /// An argument of tuple type. For a "found" argument, the span is
2685     /// the locationo in the source of the pattern. For a "expected"
2686     /// argument, it will be None. The vector is a list of (name, ty)
2687     /// strings for the components of the tuple.
2688     Tuple(Option<Span>, Vec<(String, String)>),
2689 }
2690
2691 impl ArgKind {
2692     fn empty() -> ArgKind {
2693         ArgKind::Arg("_".to_owned(), "_".to_owned())
2694     }
2695
2696     /// Creates an `ArgKind` from the expected type of an
2697     /// argument. It has no name (`_`) and an optional source span.
2698     pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2699         match t.kind {
2700             ty::Tuple(ref tys) => ArgKind::Tuple(
2701                 span,
2702                 tys.iter()
2703                    .map(|ty| ("_".to_owned(), ty.to_string()))
2704                    .collect::<Vec<_>>()
2705             ),
2706             _ => ArgKind::Arg("_".to_owned(), t.to_string()),
2707         }
2708     }
2709 }
2710
2711 /// Suggest restricting a type param with a new bound.
2712 pub fn suggest_constraining_type_param(
2713     generics: &hir::Generics,
2714     err: &mut DiagnosticBuilder<'_>,
2715     param_name: &str,
2716     constraint: &str,
2717     source_map: &SourceMap,
2718     span: Span,
2719 ) -> bool {
2720     let restrict_msg = "consider further restricting this bound";
2721     if let Some(param) = generics.params.iter().filter(|p| {
2722         p.name.ident().as_str() == param_name
2723     }).next() {
2724         if param_name.starts_with("impl ") {
2725             // `impl Trait` in argument:
2726             // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
2727             err.span_suggestion(
2728                 param.span,
2729                 restrict_msg,
2730                 // `impl CurrentTrait + MissingTrait`
2731                 format!("{} + {}", param_name, constraint),
2732                 Applicability::MachineApplicable,
2733             );
2734         } else if generics.where_clause.predicates.is_empty() &&
2735                 param.bounds.is_empty()
2736         {
2737             // If there are no bounds whatsoever, suggest adding a constraint
2738             // to the type parameter:
2739             // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
2740             err.span_suggestion(
2741                 param.span,
2742                 "consider restricting this bound",
2743                 format!("{}: {}", param_name, constraint),
2744                 Applicability::MachineApplicable,
2745             );
2746         } else if !generics.where_clause.predicates.is_empty() {
2747             // There is a `where` clause, so suggest expanding it:
2748             // `fn foo<T>(t: T) where T: Debug {}` →
2749             // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
2750             err.span_suggestion(
2751                 generics.where_clause.span().unwrap().shrink_to_hi(),
2752                 &format!("consider further restricting type parameter `{}`", param_name),
2753                 format!(", {}: {}", param_name, constraint),
2754                 Applicability::MachineApplicable,
2755             );
2756         } else {
2757             // If there is no `where` clause lean towards constraining to the
2758             // type parameter:
2759             // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
2760             // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
2761             let sp = param.span.with_hi(span.hi());
2762             let span = source_map.span_through_char(sp, ':');
2763             if sp != param.span && sp != span {
2764                 // Only suggest if we have high certainty that the span
2765                 // covers the colon in `foo<T: Trait>`.
2766                 err.span_suggestion(
2767                     span,
2768                     restrict_msg,
2769                     format!("{}: {} + ", param_name, constraint),
2770                     Applicability::MachineApplicable,
2771                 );
2772             } else {
2773                 err.span_label(
2774                     param.span,
2775                     &format!("consider adding a `where {}: {}` bound", param_name, constraint),
2776                 );
2777             }
2778         }
2779         return true;
2780     }
2781     false
2782 }