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