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