]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/error_reporting.rs
Auto merge of #48630 - alexcrichton:more-sccache, r=kennytm
[rust.git] / src / librustc / traits / error_reporting.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use super::{
12     FulfillmentError,
13     FulfillmentErrorCode,
14     MismatchedProjectionTypes,
15     Obligation,
16     ObligationCause,
17     ObligationCauseCode,
18     OnUnimplementedDirective,
19     OnUnimplementedNote,
20     OutputTypeParameterMismatch,
21     TraitNotObjectSafe,
22     ConstEvalFailure,
23     PredicateObligation,
24     Reveal,
25     SelectionContext,
26     SelectionError,
27     ObjectSafetyViolation,
28 };
29
30 use errors::DiagnosticBuilder;
31 use hir;
32 use hir::def_id::DefId;
33 use infer::{self, InferCtxt};
34 use infer::type_variable::TypeVariableOrigin;
35 use middle::const_val;
36 use std::fmt;
37 use syntax::ast;
38 use session::DiagnosticMessageId;
39 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
40 use ty::error::ExpectedFound;
41 use ty::fast_reject;
42 use ty::fold::TypeFolder;
43 use ty::subst::Subst;
44 use ty::SubtypePredicate;
45 use util::nodemap::{FxHashMap, FxHashSet};
46
47 use syntax_pos::{DUMMY_SP, Span};
48
49 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
50     pub fn report_fulfillment_errors(&self,
51                                      errors: &Vec<FulfillmentError<'tcx>>,
52                                      body_id: Option<hir::BodyId>) {
53         #[derive(Debug)]
54         struct ErrorDescriptor<'tcx> {
55             predicate: ty::Predicate<'tcx>,
56             index: Option<usize>, // None if this is an old error
57         }
58
59         let mut error_map : FxHashMap<_, _> =
60             self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
61                 (span, predicates.iter().map(|predicate| ErrorDescriptor {
62                     predicate: predicate.clone(),
63                     index: None
64                 }).collect())
65             }).collect();
66
67         for (index, error) in errors.iter().enumerate() {
68             error_map.entry(error.obligation.cause.span).or_insert(Vec::new()).push(
69                 ErrorDescriptor {
70                     predicate: error.obligation.predicate.clone(),
71                     index: Some(index)
72                 });
73
74             self.reported_trait_errors.borrow_mut()
75                 .entry(error.obligation.cause.span).or_insert(Vec::new())
76                 .push(error.obligation.predicate.clone());
77         }
78
79         // We do this in 2 passes because we want to display errors in order, tho
80         // maybe it *is* better to sort errors by span or something.
81         let mut is_suppressed: Vec<bool> = errors.iter().map(|_| false).collect();
82         for (_, error_set) in error_map.iter() {
83             // We want to suppress "duplicate" errors with the same span.
84             for error in error_set {
85                 if let Some(index) = error.index {
86                     // Suppress errors that are either:
87                     // 1) strictly implied by another error.
88                     // 2) implied by an error with a smaller index.
89                     for error2 in error_set {
90                         if error2.index.map_or(false, |index2| is_suppressed[index2]) {
91                             // Avoid errors being suppressed by already-suppressed
92                             // errors, to prevent all errors from being suppressed
93                             // at once.
94                             continue
95                         }
96
97                         if self.error_implies(&error2.predicate, &error.predicate) &&
98                             !(error2.index >= error.index &&
99                               self.error_implies(&error.predicate, &error2.predicate))
100                         {
101                             info!("skipping {:?} (implied by {:?})", error, error2);
102                             is_suppressed[index] = true;
103                             break
104                         }
105                     }
106                 }
107             }
108         }
109
110         for (error, suppressed) in errors.iter().zip(is_suppressed) {
111             if !suppressed {
112                 self.report_fulfillment_error(error, body_id);
113             }
114         }
115     }
116
117     // returns if `cond` not occurring implies that `error` does not occur - i.e. that
118     // `error` occurring implies that `cond` occurs.
119     fn error_implies(&self,
120                      cond: &ty::Predicate<'tcx>,
121                      error: &ty::Predicate<'tcx>)
122                      -> bool
123     {
124         if cond == error {
125             return true
126         }
127
128         let (cond, error) = match (cond, error) {
129             (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
130                 => (cond, error),
131             _ => {
132                 // FIXME: make this work in other cases too.
133                 return false
134             }
135         };
136
137         for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
138             if let ty::Predicate::Trait(implication) = implication {
139                 let error = error.to_poly_trait_ref();
140                 let implication = implication.to_poly_trait_ref();
141                 // FIXME: I'm just not taking associated types at all here.
142                 // Eventually I'll need to implement param-env-aware
143                 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
144                 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
145                 if let Ok(_) = self.can_sub(param_env, error, implication) {
146                     debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
147                     return true
148                 }
149             }
150         }
151
152         false
153     }
154
155     fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
156                                 body_id: Option<hir::BodyId>) {
157         debug!("report_fulfillment_errors({:?})", error);
158         match error.code {
159             FulfillmentErrorCode::CodeSelectionError(ref e) => {
160                 self.report_selection_error(&error.obligation, e);
161             }
162             FulfillmentErrorCode::CodeProjectionError(ref e) => {
163                 self.report_projection_error(&error.obligation, e);
164             }
165             FulfillmentErrorCode::CodeAmbiguity => {
166                 self.maybe_report_ambiguity(&error.obligation, body_id);
167             }
168             FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
169                 self.report_mismatched_types(&error.obligation.cause,
170                                              expected_found.expected,
171                                              expected_found.found,
172                                              err.clone())
173                     .emit();
174             }
175         }
176     }
177
178     fn report_projection_error(&self,
179                                obligation: &PredicateObligation<'tcx>,
180                                error: &MismatchedProjectionTypes<'tcx>)
181     {
182         let predicate =
183             self.resolve_type_vars_if_possible(&obligation.predicate);
184
185         if predicate.references_error() {
186             return
187         }
188
189         self.probe(|_| {
190             let err_buf;
191             let mut err = &error.err;
192             let mut values = None;
193
194             // try to find the mismatched types to report the error with.
195             //
196             // this can fail if the problem was higher-ranked, in which
197             // cause I have no idea for a good error message.
198             if let ty::Predicate::Projection(ref data) = predicate {
199                 let mut selcx = SelectionContext::new(self);
200                 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
201                     obligation.cause.span,
202                     infer::LateBoundRegionConversionTime::HigherRankedType,
203                     data);
204                 let normalized = super::normalize_projection_type(
205                     &mut selcx,
206                     obligation.param_env,
207                     data.projection_ty,
208                     obligation.cause.clone(),
209                     0
210                 );
211                 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
212                                         .eq(normalized.value, data.ty) {
213                     values = Some(infer::ValuePairs::Types(ExpectedFound {
214                         expected: normalized.value,
215                         found: data.ty,
216                     }));
217                     err_buf = error;
218                     err = &err_buf;
219                 }
220             }
221
222             let msg = format!("type mismatch resolving `{}`", predicate);
223             let error_id = (DiagnosticMessageId::ErrorId(271),
224                             Some(obligation.cause.span), msg.clone());
225             let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
226             if fresh {
227                 let mut diag = struct_span_err!(
228                     self.tcx.sess, obligation.cause.span, E0271,
229                     "type mismatch resolving `{}`", predicate
230                 );
231                 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
232                 self.note_obligation_cause(&mut diag, obligation);
233                 diag.emit();
234             }
235         });
236     }
237
238     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
239         /// returns the fuzzy category of a given type, or None
240         /// if the type can be equated to any type.
241         fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
242             match t.sty {
243                 ty::TyBool => Some(0),
244                 ty::TyChar => Some(1),
245                 ty::TyStr => Some(2),
246                 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
247                 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
248                 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
249                 ty::TyArray(..) | ty::TySlice(..) => Some(6),
250                 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
251                 ty::TyDynamic(..) => Some(8),
252                 ty::TyClosure(..) => Some(9),
253                 ty::TyTuple(..) => Some(10),
254                 ty::TyProjection(..) => Some(11),
255                 ty::TyParam(..) => Some(12),
256                 ty::TyAnon(..) => Some(13),
257                 ty::TyNever => Some(14),
258                 ty::TyAdt(adt, ..) => match adt.adt_kind() {
259                     AdtKind::Struct => Some(15),
260                     AdtKind::Union => Some(16),
261                     AdtKind::Enum => Some(17),
262                 },
263                 ty::TyGenerator(..) => Some(18),
264                 ty::TyForeign(..) => Some(19),
265                 ty::TyGeneratorWitness(..) => Some(20),
266                 ty::TyInfer(..) | ty::TyError => None
267             }
268         }
269
270         match (type_category(a), type_category(b)) {
271             (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
272                 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == def_b,
273                 _ => cat_a == cat_b
274             },
275             // infer and error can be equated to all types
276             _ => true
277         }
278     }
279
280     fn impl_similar_to(&self,
281                        trait_ref: ty::PolyTraitRef<'tcx>,
282                        obligation: &PredicateObligation<'tcx>)
283                        -> Option<DefId>
284     {
285         let tcx = self.tcx;
286         let param_env = obligation.param_env;
287         let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
288         let trait_self_ty = trait_ref.self_ty();
289
290         let mut self_match_impls = vec![];
291         let mut fuzzy_match_impls = vec![];
292
293         self.tcx.for_each_relevant_impl(
294             trait_ref.def_id, trait_self_ty, |def_id| {
295                 let impl_substs = self.fresh_substs_for_item(param_env.universe,
296                                                              obligation.cause.span,
297                                                              def_id);
298                 let impl_trait_ref = tcx
299                     .impl_trait_ref(def_id)
300                     .unwrap()
301                     .subst(tcx, impl_substs);
302
303                 let impl_self_ty = impl_trait_ref.self_ty();
304
305                 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
306                     self_match_impls.push(def_id);
307
308                     if trait_ref.substs.types().skip(1)
309                         .zip(impl_trait_ref.substs.types().skip(1))
310                         .all(|(u,v)| self.fuzzy_match_tys(u, v))
311                     {
312                         fuzzy_match_impls.push(def_id);
313                     }
314                 }
315             });
316
317         let impl_def_id = if self_match_impls.len() == 1 {
318             self_match_impls[0]
319         } else if fuzzy_match_impls.len() == 1 {
320             fuzzy_match_impls[0]
321         } else {
322             return None
323         };
324
325         if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
326             Some(impl_def_id)
327         } else {
328             None
329         }
330     }
331
332     fn on_unimplemented_note(
333         &self,
334         trait_ref: ty::PolyTraitRef<'tcx>,
335         obligation: &PredicateObligation<'tcx>) ->
336         OnUnimplementedNote
337     {
338         let def_id = self.impl_similar_to(trait_ref, obligation)
339             .unwrap_or(trait_ref.def_id());
340         let trait_ref = *trait_ref.skip_binder();
341
342         let desugaring;
343         let method;
344         let mut flags = vec![];
345         let direct = match obligation.cause.code {
346             ObligationCauseCode::BuiltinDerivedObligation(..) |
347             ObligationCauseCode::ImplDerivedObligation(..) => false,
348             _ => true
349         };
350         if direct {
351             // this is a "direct", user-specified, rather than derived,
352             // obligation.
353             flags.push(("direct".to_string(), None));
354         }
355
356         if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
357             // FIXME: maybe also have some way of handling methods
358             // from other traits? That would require name resolution,
359             // which we might want to be some sort of hygienic.
360             //
361             // Currently I'm leaving it for what I need for `try`.
362             if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
363                 method = self.tcx.item_name(item);
364                 flags.push(("from_method".to_string(), None));
365                 flags.push(("from_method".to_string(), Some(method.to_string())));
366             }
367         }
368
369         if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
370             desugaring = k.as_symbol().as_str();
371             flags.push(("from_desugaring".to_string(), None));
372             flags.push(("from_desugaring".to_string(), Some(desugaring.to_string())));
373         }
374         let generics = self.tcx.generics_of(def_id);
375         let self_ty = trait_ref.self_ty();
376         let self_ty_str = self_ty.to_string();
377         flags.push(("_Self".to_string(), Some(self_ty_str.clone())));
378
379         for param in generics.types.iter() {
380             let name = param.name.as_str().to_string();
381             let ty = trait_ref.substs.type_for_def(param);
382             let ty_str = ty.to_string();
383             flags.push((name.clone(),
384                         Some(ty_str.clone())));
385         }
386
387         if let Some(true) = self_ty.ty_to_def_id().map(|def_id| def_id.is_local()) {
388             flags.push(("crate_local".to_string(), None));
389         }
390
391         if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
392             self.tcx, trait_ref.def_id, def_id
393         ) {
394             command.evaluate(self.tcx, trait_ref, &flags[..])
395         } else {
396             OnUnimplementedNote::empty()
397         }
398     }
399
400     fn find_similar_impl_candidates(&self,
401                                     trait_ref: ty::PolyTraitRef<'tcx>)
402                                     -> Vec<ty::TraitRef<'tcx>>
403     {
404         let simp = fast_reject::simplify_type(self.tcx,
405                                               trait_ref.skip_binder().self_ty(),
406                                               true);
407         let mut impl_candidates = Vec::new();
408
409         match simp {
410             Some(simp) => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
411                 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
412                 let imp_simp = fast_reject::simplify_type(self.tcx,
413                                                           imp.self_ty(),
414                                                           true);
415                 if let Some(imp_simp) = imp_simp {
416                     if simp != imp_simp {
417                         return;
418                     }
419                 }
420                 impl_candidates.push(imp);
421             }),
422             None => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
423                 impl_candidates.push(
424                     self.tcx.impl_trait_ref(def_id).unwrap());
425             })
426         };
427         impl_candidates
428     }
429
430     fn report_similar_impl_candidates(&self,
431                                       impl_candidates: Vec<ty::TraitRef<'tcx>>,
432                                       err: &mut DiagnosticBuilder)
433     {
434         if impl_candidates.is_empty() {
435             return;
436         }
437
438         let end = if impl_candidates.len() <= 5 {
439             impl_candidates.len()
440         } else {
441             4
442         };
443         err.help(&format!("the following implementations were found:{}{}",
444                           &impl_candidates[0..end].iter().map(|candidate| {
445                               format!("\n  {:?}", candidate)
446                           }).collect::<String>(),
447                           if impl_candidates.len() > 5 {
448                               format!("\nand {} others", impl_candidates.len() - 4)
449                           } else {
450                               "".to_owned()
451                           }
452                           ));
453     }
454
455     /// Reports that an overflow has occurred and halts compilation. We
456     /// halt compilation unconditionally because it is important that
457     /// overflows never be masked -- they basically represent computations
458     /// whose result could not be truly determined and thus we can't say
459     /// if the program type checks or not -- and they are unusual
460     /// occurrences in any case.
461     pub fn report_overflow_error<T>(&self,
462                                     obligation: &Obligation<'tcx, T>,
463                                     suggest_increasing_limit: bool) -> !
464         where T: fmt::Display + TypeFoldable<'tcx>
465     {
466         let predicate =
467             self.resolve_type_vars_if_possible(&obligation.predicate);
468         let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
469                                        "overflow evaluating the requirement `{}`",
470                                        predicate);
471
472         if suggest_increasing_limit {
473             self.suggest_new_overflow_limit(&mut err);
474         }
475
476         self.note_obligation_cause(&mut err, obligation);
477
478         err.emit();
479         self.tcx.sess.abort_if_errors();
480         bug!();
481     }
482
483     /// Reports that a cycle was detected which led to overflow and halts
484     /// compilation. This is equivalent to `report_overflow_error` except
485     /// that we can give a more helpful error message (and, in particular,
486     /// we do not suggest increasing the overflow limit, which is not
487     /// going to help).
488     pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
489         let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
490         assert!(cycle.len() > 0);
491
492         debug!("report_overflow_error_cycle: cycle={:?}", cycle);
493
494         self.report_overflow_error(&cycle[0], false);
495     }
496
497     pub fn report_extra_impl_obligation(&self,
498                                         error_span: Span,
499                                         item_name: ast::Name,
500                                         _impl_item_def_id: DefId,
501                                         trait_item_def_id: DefId,
502                                         requirement: &dyn fmt::Display)
503                                         -> DiagnosticBuilder<'tcx>
504     {
505         let msg = "impl has stricter requirements than trait";
506         let sp = self.tcx.sess.codemap().def_span(error_span);
507
508         let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
509
510         if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
511             let span = self.tcx.sess.codemap().def_span(trait_item_span);
512             err.span_label(span, format!("definition of `{}` from trait", item_name));
513         }
514
515         err.span_label(sp, format!("impl has extra requirement {}", requirement));
516
517         err
518     }
519
520
521     /// Get the parent trait chain start
522     fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
523         match code {
524             &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
525                 let parent_trait_ref = self.resolve_type_vars_if_possible(
526                     &data.parent_trait_ref);
527                 match self.get_parent_trait_ref(&data.parent_code) {
528                     Some(t) => Some(t),
529                     None => Some(format!("{}", parent_trait_ref.0.self_ty())),
530                 }
531             }
532             _ => None,
533         }
534     }
535
536     pub fn report_selection_error(&self,
537                                   obligation: &PredicateObligation<'tcx>,
538                                   error: &SelectionError<'tcx>)
539     {
540         let span = obligation.cause.span;
541
542         let mut err = match *error {
543             SelectionError::Unimplemented => {
544                 if let ObligationCauseCode::CompareImplMethodObligation {
545                     item_name, impl_item_def_id, trait_item_def_id,
546                 } = obligation.cause.code {
547                     self.report_extra_impl_obligation(
548                         span,
549                         item_name,
550                         impl_item_def_id,
551                         trait_item_def_id,
552                         &format!("`{}`", obligation.predicate))
553                         .emit();
554                     return;
555                 }
556                 match obligation.predicate {
557                     ty::Predicate::Trait(ref trait_predicate) => {
558                         let trait_predicate =
559                             self.resolve_type_vars_if_possible(trait_predicate);
560
561                         if self.tcx.sess.has_errors() && trait_predicate.references_error() {
562                             return;
563                         }
564                         let trait_ref = trait_predicate.to_poly_trait_ref();
565                         let (post_message, pre_message) =
566                             self.get_parent_trait_ref(&obligation.cause.code)
567                                 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
568                             .unwrap_or((String::new(), String::new()));
569
570                         let OnUnimplementedNote { message, label, note }
571                             = self.on_unimplemented_note(trait_ref, obligation);
572                         let have_alt_message = message.is_some() || label.is_some();
573
574                         let mut err = struct_span_err!(
575                             self.tcx.sess,
576                             span,
577                             E0277,
578                             "{}",
579                             message.unwrap_or_else(|| {
580                                 format!("the trait bound `{}` is not satisfied{}",
581                                          trait_ref.to_predicate(), post_message)
582                             }));
583
584                         if let Some(ref s) = label {
585                             // If it has a custom "#[rustc_on_unimplemented]"
586                             // error message, let's display it as the label!
587                             err.span_label(span, s.as_str());
588                             err.help(&format!("{}the trait `{}` is not implemented for `{}`",
589                                               pre_message,
590                                               trait_ref,
591                                               trait_ref.self_ty()));
592                         } else {
593                             err.span_label(span,
594                                            &*format!("{}the trait `{}` is not implemented for `{}`",
595                                                      pre_message,
596                                                      trait_ref,
597                                                      trait_ref.self_ty()));
598                         }
599                         if let Some(ref s) = note {
600                             // If it has a custom "#[rustc_on_unimplemented]" note, let's display it
601                             err.note(s.as_str());
602                         }
603
604                         self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
605
606                         // Try to report a help message
607                         if !trait_ref.has_infer_types() &&
608                             self.predicate_can_apply(obligation.param_env, trait_ref) {
609                             // If a where-clause may be useful, remind the
610                             // user that they can add it.
611                             //
612                             // don't display an on-unimplemented note, as
613                             // these notes will often be of the form
614                             //     "the type `T` can't be frobnicated"
615                             // which is somewhat confusing.
616                             err.help(&format!("consider adding a `where {}` bound",
617                                                 trait_ref.to_predicate()));
618                         } else if !have_alt_message {
619                             // Can't show anything else useful, try to find similar impls.
620                             let impl_candidates = self.find_similar_impl_candidates(trait_ref);
621                             self.report_similar_impl_candidates(impl_candidates, &mut err);
622                         }
623
624                         err
625                     }
626
627                     ty::Predicate::Subtype(ref predicate) => {
628                         // Errors for Subtype predicates show up as
629                         // `FulfillmentErrorCode::CodeSubtypeError`,
630                         // not selection error.
631                         span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
632                     }
633
634                     ty::Predicate::Equate(ref predicate) => {
635                         let predicate = self.resolve_type_vars_if_possible(predicate);
636                         let err = self.equality_predicate(&obligation.cause,
637                                                           obligation.param_env,
638                                                           &predicate).err().unwrap();
639                         struct_span_err!(self.tcx.sess, span, E0278,
640                             "the requirement `{}` is not satisfied (`{}`)",
641                             predicate, err)
642                     }
643
644                     ty::Predicate::RegionOutlives(ref predicate) => {
645                         let predicate = self.resolve_type_vars_if_possible(predicate);
646                         let err = self.region_outlives_predicate(&obligation.cause,
647                                                                     &predicate).err().unwrap();
648                         struct_span_err!(self.tcx.sess, span, E0279,
649                             "the requirement `{}` is not satisfied (`{}`)",
650                             predicate, err)
651                     }
652
653                     ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
654                         let predicate =
655                             self.resolve_type_vars_if_possible(&obligation.predicate);
656                         struct_span_err!(self.tcx.sess, span, E0280,
657                             "the requirement `{}` is not satisfied",
658                             predicate)
659                     }
660
661                     ty::Predicate::ObjectSafe(trait_def_id) => {
662                         let violations = self.tcx.object_safety_violations(trait_def_id);
663                         self.tcx.report_object_safety_error(span,
664                                                             trait_def_id,
665                                                             violations)
666                     }
667
668                     ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
669                         let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
670                         let closure_span = self.tcx.sess.codemap()
671                             .def_span(self.tcx.hir.span_if_local(closure_def_id).unwrap());
672                         let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
673                         let mut err = struct_span_err!(
674                             self.tcx.sess, closure_span, E0525,
675                             "expected a closure that implements the `{}` trait, \
676                                 but this closure only implements `{}`",
677                             kind,
678                             found_kind);
679
680                         err.span_label(
681                             closure_span,
682                             format!("this closure implements `{}`, not `{}`", found_kind, kind));
683                         err.span_label(
684                             obligation.cause.span,
685                             format!("the requirement to implement `{}` derives from here", kind));
686
687                         // Additional context information explaining why the closure only implements
688                         // a particular trait.
689                         if let Some(tables) = self.in_progress_tables {
690                             let tables = tables.borrow();
691                             let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
692                             match (found_kind, tables.closure_kind_origins().get(closure_hir_id)) {
693                                 (ty::ClosureKind::FnOnce, Some((span, name))) => {
694                                     err.span_label(*span, format!(
695                                         "closure is `FnOnce` because it moves the \
696                                          variable `{}` out of its environment", name));
697                                 },
698                                 (ty::ClosureKind::FnMut, Some((span, name))) => {
699                                     err.span_label(*span, format!(
700                                         "closure is `FnMut` because it mutates the \
701                                          variable `{}` here", name));
702                                 },
703                                 _ => {}
704                             }
705                         }
706
707                         err.emit();
708                         return;
709                     }
710
711                     ty::Predicate::WellFormed(ty) => {
712                         // WF predicates cannot themselves make
713                         // errors. They can only block due to
714                         // ambiguity; otherwise, they always
715                         // degenerate into other obligations
716                         // (which may fail).
717                         span_bug!(span, "WF predicate not satisfied for {:?}", ty);
718                     }
719
720                     ty::Predicate::ConstEvaluatable(..) => {
721                         // Errors for `ConstEvaluatable` predicates show up as
722                         // `SelectionError::ConstEvalFailure`,
723                         // not `Unimplemented`.
724                         span_bug!(span,
725                             "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
726                     }
727                 }
728             }
729
730             OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
731                 let found_trait_ref = self.resolve_type_vars_if_possible(&*found_trait_ref);
732                 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
733                 if expected_trait_ref.self_ty().references_error() {
734                     return;
735                 }
736                 let found_trait_ty = found_trait_ref.self_ty();
737
738                 let found_did = found_trait_ty.ty_to_def_id();
739                 let found_span = found_did.and_then(|did| {
740                     self.tcx.hir.span_if_local(did)
741                 }).map(|sp| self.tcx.sess.codemap().def_span(sp)); // the sp could be an fn def
742
743                 let found = match found_trait_ref.skip_binder().substs.type_at(1).sty {
744                     ty::TyTuple(ref tys, _) => tys.iter()
745                         .map(|_| ArgKind::empty()).collect::<Vec<_>>(),
746                     _ => vec![ArgKind::empty()],
747                 };
748                 let expected = match expected_trait_ref.skip_binder().substs.type_at(1).sty {
749                     ty::TyTuple(ref tys, _) => tys.iter()
750                         .map(|t| match t.sty {
751                             ty::TypeVariants::TyTuple(ref tys, _) => ArgKind::Tuple(
752                                 Some(span),
753                                 tys.iter()
754                                     .map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
755                                     .collect::<Vec<_>>()
756                             ),
757                             _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),
758                         }).collect(),
759                     ref sty => vec![ArgKind::Arg("_".to_owned(), format!("{}", sty))],
760                 };
761                 if found.len() == expected.len() {
762                     self.report_closure_arg_mismatch(span,
763                                                      found_span,
764                                                      found_trait_ref,
765                                                      expected_trait_ref)
766                 } else {
767                     let (closure_span, found) = found_did
768                         .and_then(|did| self.tcx.hir.get_if_local(did))
769                         .map(|node| {
770                             let (found_span, found) = self.get_fn_like_arguments(node);
771                             (Some(found_span), found)
772                         }).unwrap_or((found_span, found));
773
774                     self.report_arg_count_mismatch(span,
775                                                    closure_span,
776                                                    expected,
777                                                    found,
778                                                    found_trait_ty.is_closure())
779                 }
780             }
781
782             TraitNotObjectSafe(did) => {
783                 let violations = self.tcx.object_safety_violations(did);
784                 self.tcx.report_object_safety_error(span, did,
785                                                     violations)
786             }
787
788             ConstEvalFailure(ref err) => {
789                 if let const_val::ErrKind::TypeckError = err.kind {
790                     return;
791                 }
792                 err.struct_error(self.tcx, span, "constant expression")
793             }
794         };
795         self.note_obligation_cause(&mut err, obligation);
796         err.emit();
797     }
798
799     /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
800     /// suggestion to borrow the initializer in order to use have a slice instead.
801     fn suggest_borrow_on_unsized_slice(&self,
802                                        code: &ObligationCauseCode<'tcx>,
803                                        err: &mut DiagnosticBuilder<'tcx>) {
804         if let &ObligationCauseCode::VariableType(node_id) = code {
805             let parent_node = self.tcx.hir.get_parent_node(node_id);
806             if let Some(hir::map::NodeLocal(ref local)) = self.tcx.hir.find(parent_node) {
807                 if let Some(ref expr) = local.init {
808                     if let hir::ExprIndex(_, _) = expr.node {
809                         if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(expr.span) {
810                             err.span_suggestion(expr.span,
811                                                 "consider borrowing here",
812                                                 format!("&{}", snippet));
813                         }
814                     }
815                 }
816             }
817         }
818     }
819
820     /// Given some node representing a fn-like thing in the HIR map,
821     /// returns a span and `ArgKind` information that describes the
822     /// arguments it expects. This can be supplied to
823     /// `report_arg_count_mismatch`.
824     pub fn get_fn_like_arguments(&self, node: hir::map::Node) -> (Span, Vec<ArgKind>) {
825         match node {
826             hir::map::NodeExpr(&hir::Expr {
827                 node: hir::ExprClosure(_, ref _decl, id, span, _),
828                 ..
829             }) => {
830                 (self.tcx.sess.codemap().def_span(span), self.tcx.hir.body(id).arguments.iter()
831                     .map(|arg| {
832                         if let hir::Pat {
833                             node: hir::PatKind::Tuple(args, _),
834                             span,
835                             ..
836                         } = arg.pat.clone().into_inner() {
837                             ArgKind::Tuple(
838                                 Some(span),
839                                 args.iter().map(|pat| {
840                                     let snippet = self.tcx.sess.codemap()
841                                         .span_to_snippet(pat.span).unwrap();
842                                     (snippet, "_".to_owned())
843                                 }).collect::<Vec<_>>(),
844                             )
845                         } else {
846                             let name = self.tcx.sess.codemap()
847                                 .span_to_snippet(arg.pat.span).unwrap();
848                             ArgKind::Arg(name, "_".to_owned())
849                         }
850                     })
851                     .collect::<Vec<ArgKind>>())
852             }
853             hir::map::NodeItem(&hir::Item {
854                 span,
855                 node: hir::ItemFn(ref decl, ..),
856                 ..
857             }) |
858             hir::map::NodeImplItem(&hir::ImplItem {
859                 span,
860                 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
861                 ..
862             }) |
863             hir::map::NodeTraitItem(&hir::TraitItem {
864                 span,
865                 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
866                 ..
867             }) => {
868                 (self.tcx.sess.codemap().def_span(span), decl.inputs.iter()
869                         .map(|arg| match arg.clone().into_inner().node {
870                     hir::TyTup(ref tys) => ArgKind::Tuple(
871                         Some(arg.span),
872                         tys.iter()
873                             .map(|_| ("_".to_owned(), "_".to_owned()))
874                             .collect::<Vec<_>>(),
875                     ),
876                     _ => ArgKind::Arg("_".to_owned(), "_".to_owned())
877                 }).collect::<Vec<ArgKind>>())
878             }
879             hir::map::NodeVariant(&hir::Variant {
880                 span,
881                 node: hir::Variant_ {
882                     data: hir::VariantData::Tuple(ref fields, _),
883                     ..
884                 },
885                 ..
886             }) => {
887                 (self.tcx.sess.codemap().def_span(span),
888                  fields.iter().map(|field| {
889                      ArgKind::Arg(format!("{}", field.name), "_".to_string())
890                  }).collect::<Vec<_>>())
891             }
892             _ => panic!("non-FnLike node found: {:?}", node),
893         }
894     }
895
896     /// Reports an error when the number of arguments needed by a
897     /// trait match doesn't match the number that the expression
898     /// provides.
899     pub fn report_arg_count_mismatch(
900         &self,
901         span: Span,
902         found_span: Option<Span>,
903         expected_args: Vec<ArgKind>,
904         found_args: Vec<ArgKind>,
905         is_closure: bool,
906     ) -> DiagnosticBuilder<'tcx> {
907         let kind = if is_closure { "closure" } else { "function" };
908
909         let args_str = |arguments: &Vec<ArgKind>, other: &Vec<ArgKind>| {
910             let arg_length = arguments.len();
911             let distinct = match &other[..] {
912                 &[ArgKind::Tuple(..)] => true,
913                 _ => false,
914             };
915             match (arg_length, arguments.get(0)) {
916                 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
917                     format!("a single {}-tuple as argument", fields.len())
918                 }
919                 _ => format!("{} {}argument{}",
920                              arg_length,
921                              if distinct && arg_length > 1 { "distinct " } else { "" },
922                              if arg_length == 1 { "" } else { "s" }),
923             }
924         };
925
926         let expected_str = args_str(&expected_args, &found_args);
927         let found_str = args_str(&found_args, &expected_args);
928
929         let mut err = struct_span_err!(
930             self.tcx.sess,
931             span,
932             E0593,
933             "{} is expected to take {}, but it takes {}",
934             kind,
935             expected_str,
936             found_str,
937         );
938
939         err.span_label(span, format!( "expected {} that takes {}", kind, expected_str));
940
941         if let Some(found_span) = found_span {
942             err.span_label(found_span, format!("takes {}", found_str));
943
944             if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
945                 if fields.len() == expected_args.len() {
946                     let sugg = fields.iter()
947                         .map(|(name, _)| name.to_owned())
948                         .collect::<Vec<String>>().join(", ");
949                     err.span_suggestion(found_span,
950                                         "change the closure to take multiple arguments instead of \
951                                          a single tuple",
952                                         format!("|{}|", sugg));
953                 }
954             }
955             if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
956                 if fields.len() == found_args.len() && is_closure {
957                     let sugg = format!(
958                         "|({}){}|",
959                         found_args.iter()
960                             .map(|arg| match arg {
961                                 ArgKind::Arg(name, _) => name.to_owned(),
962                                 _ => "_".to_owned(),
963                             })
964                             .collect::<Vec<String>>()
965                             .join(", "),
966                         // add type annotations if available
967                         if found_args.iter().any(|arg| match arg {
968                             ArgKind::Arg(_, ty) => ty != "_",
969                             _ => false,
970                         }) {
971                             format!(": ({})",
972                                     fields.iter()
973                                         .map(|(_, ty)| ty.to_owned())
974                                         .collect::<Vec<String>>()
975                                         .join(", "))
976                         } else {
977                             "".to_owned()
978                         },
979                     );
980                     err.span_suggestion(found_span,
981                                         "change the closure to accept a tuple instead of \
982                                          individual arguments",
983                                         sugg);
984                 }
985             }
986         }
987
988         err
989     }
990
991     fn report_closure_arg_mismatch(&self,
992                            span: Span,
993                            found_span: Option<Span>,
994                            expected_ref: ty::PolyTraitRef<'tcx>,
995                            found: ty::PolyTraitRef<'tcx>)
996         -> DiagnosticBuilder<'tcx>
997     {
998         fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
999                                                trait_ref: &ty::TraitRef<'tcx>) -> String {
1000             let inputs = trait_ref.substs.type_at(1);
1001             let sig = if let ty::TyTuple(inputs, _) = inputs.sty {
1002                 tcx.mk_fn_sig(
1003                     inputs.iter().map(|&x| x),
1004                     tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1005                     false,
1006                     hir::Unsafety::Normal,
1007                     ::syntax::abi::Abi::Rust
1008                 )
1009             } else {
1010                 tcx.mk_fn_sig(
1011                     ::std::iter::once(inputs),
1012                     tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1013                     false,
1014                     hir::Unsafety::Normal,
1015                     ::syntax::abi::Abi::Rust
1016                 )
1017             };
1018             format!("{}", ty::Binder(sig))
1019         }
1020
1021         let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1022         let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1023                                        "type mismatch in {} arguments",
1024                                        if argument_is_closure { "closure" } else { "function" });
1025
1026         let found_str = format!(
1027             "expected signature of `{}`",
1028             build_fn_sig_string(self.tcx, found.skip_binder())
1029         );
1030         err.span_label(span, found_str);
1031
1032         let found_span = found_span.unwrap_or(span);
1033         let expected_str = format!(
1034             "found signature of `{}`",
1035             build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1036         );
1037         err.span_label(found_span, expected_str);
1038
1039         err
1040     }
1041 }
1042
1043 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1044     pub fn recursive_type_with_infinite_size_error(self,
1045                                                    type_def_id: DefId)
1046                                                    -> DiagnosticBuilder<'tcx>
1047     {
1048         assert!(type_def_id.is_local());
1049         let span = self.hir.span_if_local(type_def_id).unwrap();
1050         let span = self.sess.codemap().def_span(span);
1051         let mut err = struct_span_err!(self.sess, span, E0072,
1052                                        "recursive type `{}` has infinite size",
1053                                        self.item_path_str(type_def_id));
1054         err.span_label(span, "recursive type has infinite size");
1055         err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1056                            at some point to make `{}` representable",
1057                           self.item_path_str(type_def_id)));
1058         err
1059     }
1060
1061     pub fn report_object_safety_error(self,
1062                                       span: Span,
1063                                       trait_def_id: DefId,
1064                                       violations: Vec<ObjectSafetyViolation>)
1065                                       -> DiagnosticBuilder<'tcx>
1066     {
1067         let trait_str = self.item_path_str(trait_def_id);
1068         let span = self.sess.codemap().def_span(span);
1069         let mut err = struct_span_err!(
1070             self.sess, span, E0038,
1071             "the trait `{}` cannot be made into an object",
1072             trait_str);
1073         err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1074
1075         let mut reported_violations = FxHashSet();
1076         for violation in violations {
1077             if !reported_violations.insert(violation.clone()) {
1078                 continue;
1079             }
1080             err.note(&violation.error_msg());
1081         }
1082         err
1083     }
1084 }
1085
1086 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1087     fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1088                               body_id: Option<hir::BodyId>) {
1089         // Unable to successfully determine, probably means
1090         // insufficient type information, but could mean
1091         // ambiguous impls. The latter *ought* to be a
1092         // coherence violation, so we don't report it here.
1093
1094         let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1095         let span = obligation.cause.span;
1096
1097         debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1098                predicate,
1099                obligation);
1100
1101         // Ambiguity errors are often caused as fallout from earlier
1102         // errors. So just ignore them if this infcx is tainted.
1103         if self.is_tainted_by_errors() {
1104             return;
1105         }
1106
1107         match predicate {
1108             ty::Predicate::Trait(ref data) => {
1109                 let trait_ref = data.to_poly_trait_ref();
1110                 let self_ty = trait_ref.self_ty();
1111                 if predicate.references_error() {
1112                     return;
1113                 }
1114                 // Typically, this ambiguity should only happen if
1115                 // there are unresolved type inference variables
1116                 // (otherwise it would suggest a coherence
1117                 // failure). But given #21974 that is not necessarily
1118                 // the case -- we can have multiple where clauses that
1119                 // are only distinguished by a region, which results
1120                 // in an ambiguity even when all types are fully
1121                 // known, since we don't dispatch based on region
1122                 // relationships.
1123
1124                 // This is kind of a hack: it frequently happens that some earlier
1125                 // error prevents types from being fully inferred, and then we get
1126                 // a bunch of uninteresting errors saying something like "<generic
1127                 // #0> doesn't implement Sized".  It may even be true that we
1128                 // could just skip over all checks where the self-ty is an
1129                 // inference variable, but I was afraid that there might be an
1130                 // inference variable created, registered as an obligation, and
1131                 // then never forced by writeback, and hence by skipping here we'd
1132                 // be ignoring the fact that we don't KNOW the type works
1133                 // out. Though even that would probably be harmless, given that
1134                 // we're only talking about builtin traits, which are known to be
1135                 // inhabited. But in any case I just threw in this check for
1136                 // has_errors() to be sure that compilation isn't happening
1137                 // anyway. In that case, why inundate the user.
1138                 if !self.tcx.sess.has_errors() {
1139                     if
1140                         self.tcx.lang_items().sized_trait()
1141                         .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1142                     {
1143                         self.need_type_info(body_id, span, self_ty);
1144                     } else {
1145                         let mut err = struct_span_err!(self.tcx.sess,
1146                                                         span, E0283,
1147                                                         "type annotations required: \
1148                                                         cannot resolve `{}`",
1149                                                         predicate);
1150                         self.note_obligation_cause(&mut err, obligation);
1151                         err.emit();
1152                     }
1153                 }
1154             }
1155
1156             ty::Predicate::WellFormed(ty) => {
1157                 // Same hacky approach as above to avoid deluging user
1158                 // with error messages.
1159                 if !ty.references_error() && !self.tcx.sess.has_errors() {
1160                     self.need_type_info(body_id, span, ty);
1161                 }
1162             }
1163
1164             ty::Predicate::Subtype(ref data) => {
1165                 if data.references_error() || self.tcx.sess.has_errors() {
1166                     // no need to overload user in such cases
1167                 } else {
1168                     let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1169                     // both must be type variables, or the other would've been instantiated
1170                     assert!(a.is_ty_var() && b.is_ty_var());
1171                     self.need_type_info(body_id,
1172                                         obligation.cause.span,
1173                                         a);
1174                 }
1175             }
1176
1177             _ => {
1178                 if !self.tcx.sess.has_errors() {
1179                     let mut err = struct_span_err!(self.tcx.sess,
1180                                                    obligation.cause.span, E0284,
1181                                                    "type annotations required: \
1182                                                     cannot resolve `{}`",
1183                                                    predicate);
1184                     self.note_obligation_cause(&mut err, obligation);
1185                     err.emit();
1186                 }
1187             }
1188         }
1189     }
1190
1191     /// Returns whether the trait predicate may apply for *some* assignment
1192     /// to the type parameters.
1193     fn predicate_can_apply(&self,
1194                            param_env: ty::ParamEnv<'tcx>,
1195                            pred: ty::PolyTraitRef<'tcx>)
1196                            -> bool {
1197         struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1198             infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1199             param_env: ty::ParamEnv<'tcx>,
1200             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1201         }
1202
1203         impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1204             fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1205
1206             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1207                 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
1208                     let infcx = self.infcx;
1209                     let param_env = self.param_env;
1210                     self.var_map
1211                         .entry(ty)
1212                         .or_insert_with(|| {
1213                             let origin = TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP,
1214                                                                                      name);
1215                             infcx.next_ty_var(param_env.universe, origin)
1216                         })
1217                 } else {
1218                     ty.super_fold_with(self)
1219                 }
1220             }
1221         }
1222
1223         self.probe(|_| {
1224             let mut selcx = SelectionContext::new(self);
1225
1226             let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1227                 infcx: self,
1228                 param_env,
1229                 var_map: FxHashMap()
1230             });
1231
1232             let cleaned_pred = super::project::normalize(
1233                 &mut selcx,
1234                 param_env,
1235                 ObligationCause::dummy(),
1236                 &cleaned_pred
1237             ).value;
1238
1239             let obligation = Obligation::new(
1240                 ObligationCause::dummy(),
1241                 param_env,
1242                 cleaned_pred.to_predicate()
1243             );
1244
1245             selcx.evaluate_obligation(&obligation)
1246         })
1247     }
1248
1249     fn note_obligation_cause<T>(&self,
1250                                 err: &mut DiagnosticBuilder,
1251                                 obligation: &Obligation<'tcx, T>)
1252         where T: fmt::Display
1253     {
1254         self.note_obligation_cause_code(err,
1255                                         &obligation.predicate,
1256                                         &obligation.cause.code,
1257                                         &mut vec![]);
1258     }
1259
1260     fn note_obligation_cause_code<T>(&self,
1261                                      err: &mut DiagnosticBuilder,
1262                                      predicate: &T,
1263                                      cause_code: &ObligationCauseCode<'tcx>,
1264                                      obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1265         where T: fmt::Display
1266     {
1267         let tcx = self.tcx;
1268         match *cause_code {
1269             ObligationCauseCode::ExprAssignable |
1270             ObligationCauseCode::MatchExpressionArm { .. } |
1271             ObligationCauseCode::IfExpression |
1272             ObligationCauseCode::IfExpressionWithNoElse |
1273             ObligationCauseCode::EquatePredicate |
1274             ObligationCauseCode::MainFunctionType |
1275             ObligationCauseCode::StartFunctionType |
1276             ObligationCauseCode::IntrinsicType |
1277             ObligationCauseCode::MethodReceiver |
1278             ObligationCauseCode::ReturnNoExpression |
1279             ObligationCauseCode::MiscObligation => {
1280             }
1281             ObligationCauseCode::SliceOrArrayElem => {
1282                 err.note("slice and array elements must have `Sized` type");
1283             }
1284             ObligationCauseCode::TupleElem => {
1285                 err.note("only the last element of a tuple may have a dynamically sized type");
1286             }
1287             ObligationCauseCode::ProjectionWf(data) => {
1288                 err.note(&format!("required so that the projection `{}` is well-formed",
1289                                   data));
1290             }
1291             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1292                 err.note(&format!("required so that reference `{}` does not outlive its referent",
1293                                   ref_ty));
1294             }
1295             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1296                 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1297                                    is satisfied",
1298                                   region, object_ty));
1299             }
1300             ObligationCauseCode::ItemObligation(item_def_id) => {
1301                 let item_name = tcx.item_path_str(item_def_id);
1302                 let msg = format!("required by `{}`", item_name);
1303                 if let Some(sp) = tcx.hir.span_if_local(item_def_id) {
1304                     let sp = tcx.sess.codemap().def_span(sp);
1305                     err.span_note(sp, &msg);
1306                 } else {
1307                     err.note(&msg);
1308                 }
1309             }
1310             ObligationCauseCode::ObjectCastObligation(object_ty) => {
1311                 err.note(&format!("required for the cast to the object type `{}`",
1312                                   self.ty_to_string(object_ty)));
1313             }
1314             ObligationCauseCode::RepeatVec => {
1315                 err.note("the `Copy` trait is required because the \
1316                           repeated element will be copied");
1317             }
1318             ObligationCauseCode::VariableType(_) => {
1319                 err.note("all local variables must have a statically known size");
1320             }
1321             ObligationCauseCode::SizedReturnType => {
1322                 err.note("the return type of a function must have a \
1323                           statically known size");
1324             }
1325             ObligationCauseCode::SizedYieldType => {
1326                 err.note("the yield type of a generator must have a \
1327                           statically known size");
1328             }
1329             ObligationCauseCode::AssignmentLhsSized => {
1330                 err.note("the left-hand-side of an assignment must have a statically known size");
1331             }
1332             ObligationCauseCode::TupleInitializerSized => {
1333                 err.note("tuples must have a statically known size to be initialized");
1334             }
1335             ObligationCauseCode::StructInitializerSized => {
1336                 err.note("structs must have a statically known size to be initialized");
1337             }
1338             ObligationCauseCode::FieldSized(ref item) => {
1339                 match *item {
1340                     AdtKind::Struct => {
1341                         err.note("only the last field of a struct may have a dynamically \
1342                                   sized type");
1343                     }
1344                     AdtKind::Union => {
1345                         err.note("no field of a union may have a dynamically sized type");
1346                     }
1347                     AdtKind::Enum => {
1348                         err.note("no field of an enum variant may have a dynamically sized type");
1349                     }
1350                 }
1351             }
1352             ObligationCauseCode::ConstSized => {
1353                 err.note("constant expressions must have a statically known size");
1354             }
1355             ObligationCauseCode::SharedStatic => {
1356                 err.note("shared static variables must have a type that implements `Sync`");
1357             }
1358             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1359                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1360                 let ty = parent_trait_ref.0.self_ty();
1361                 err.note(&format!("required because it appears within the type `{}`", ty));
1362                 obligated_types.push(ty);
1363
1364                 let parent_predicate = parent_trait_ref.to_predicate();
1365                 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1366                     self.note_obligation_cause_code(err,
1367                                                     &parent_predicate,
1368                                                     &data.parent_code,
1369                                                     obligated_types);
1370                 }
1371             }
1372             ObligationCauseCode::ImplDerivedObligation(ref data) => {
1373                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1374                 err.note(
1375                     &format!("required because of the requirements on the impl of `{}` for `{}`",
1376                              parent_trait_ref,
1377                              parent_trait_ref.0.self_ty()));
1378                 let parent_predicate = parent_trait_ref.to_predicate();
1379                 self.note_obligation_cause_code(err,
1380                                             &parent_predicate,
1381                                             &data.parent_code,
1382                                             obligated_types);
1383             }
1384             ObligationCauseCode::CompareImplMethodObligation { .. } => {
1385                 err.note(
1386                     &format!("the requirement `{}` appears on the impl method \
1387                               but not on the corresponding trait method",
1388                              predicate));
1389             }
1390             ObligationCauseCode::ReturnType(_) |
1391             ObligationCauseCode::BlockTailExpression(_) => (),
1392         }
1393     }
1394
1395     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1396         let current_limit = self.tcx.sess.recursion_limit.get();
1397         let suggested_limit = current_limit * 2;
1398         err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1399                           suggested_limit));
1400     }
1401
1402     fn is_recursive_obligation(&self,
1403                                    obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1404                                    cause_code: &ObligationCauseCode<'tcx>) -> bool {
1405         if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1406             let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1407             for obligated_type in obligated_types {
1408                 if obligated_type == &parent_trait_ref.0.self_ty() {
1409                     return true;
1410                 }
1411             }
1412         }
1413         return false;
1414     }
1415 }
1416
1417 /// Summarizes information
1418 pub enum ArgKind {
1419     /// An argument of non-tuple type. Parameters are (name, ty)
1420     Arg(String, String),
1421
1422     /// An argument of tuple type. For a "found" argument, the span is
1423     /// the locationo in the source of the pattern. For a "expected"
1424     /// argument, it will be None. The vector is a list of (name, ty)
1425     /// strings for the components of the tuple.
1426     Tuple(Option<Span>, Vec<(String, String)>),
1427 }
1428
1429 impl ArgKind {
1430     fn empty() -> ArgKind {
1431         ArgKind::Arg("_".to_owned(), "_".to_owned())
1432     }
1433
1434     /// Creates an `ArgKind` from the expected type of an
1435     /// argument. This has no name (`_`) and no source spans..
1436     pub fn from_expected_ty(t: Ty<'_>) -> ArgKind {
1437         match t.sty {
1438             ty::TyTuple(ref tys, _) => ArgKind::Tuple(
1439                 None,
1440                 tys.iter()
1441                    .map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
1442                    .collect::<Vec<_>>()
1443             ),
1444             _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),
1445         }
1446     }
1447 }