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