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