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