]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/error_reporting.rs
33ca1d05cad7e0f68d4857bea4f3089ea0308291
[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     OutputTypeParameterMismatch,
19     TraitNotObjectSafe,
20     PredicateObligation,
21     SelectionContext,
22     SelectionError,
23     ObjectSafetyViolation,
24     MethodViolationCode,
25 };
26
27 use fmt_macros::{Parser, Piece, Position};
28 use hir::def_id::DefId;
29 use infer::{self, InferCtxt, TypeOrigin};
30 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
31 use ty::error::ExpectedFound;
32 use ty::fast_reject;
33 use ty::fold::TypeFolder;
34 use ty::subst::{self, Subst, TypeSpace};
35 use util::nodemap::{FnvHashMap, FnvHashSet};
36
37 use std::cmp;
38 use std::fmt;
39 use syntax::ast;
40 use syntax::attr::{AttributeMethods, AttrMetaMethods};
41 use syntax_pos::Span;
42 use errors::DiagnosticBuilder;
43
44 #[derive(Debug, PartialEq, Eq, Hash)]
45 pub struct TraitErrorKey<'tcx> {
46     span: Span,
47     warning_node_id: Option<ast::NodeId>,
48     predicate: ty::Predicate<'tcx>
49 }
50
51 impl<'a, 'gcx, 'tcx> TraitErrorKey<'tcx> {
52     fn from_error(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
53                   e: &FulfillmentError<'tcx>,
54                   warning_node_id: Option<ast::NodeId>) -> Self {
55         let predicate =
56             infcx.resolve_type_vars_if_possible(&e.obligation.predicate);
57         TraitErrorKey {
58             span: e.obligation.cause.span,
59             predicate: infcx.tcx.erase_regions(&predicate),
60             warning_node_id: warning_node_id
61         }
62     }
63 }
64
65 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
66     pub fn report_fulfillment_errors(&self, errors: &Vec<FulfillmentError<'tcx>>) {
67         for error in errors {
68             self.report_fulfillment_error(error, None);
69         }
70     }
71
72     pub fn report_fulfillment_errors_as_warnings(&self,
73                                                  errors: &Vec<FulfillmentError<'tcx>>,
74                                                  node_id: ast::NodeId) {
75         for error in errors {
76             self.report_fulfillment_error(error, Some(node_id));
77         }
78     }
79
80     fn report_fulfillment_error(&self,
81                                 error: &FulfillmentError<'tcx>,
82                                 warning_node_id: Option<ast::NodeId>) {
83         let error_key = TraitErrorKey::from_error(self, error, warning_node_id);
84         debug!("report_fulfillment_errors({:?}) - key={:?}",
85                error, error_key);
86         if !self.reported_trait_errors.borrow_mut().insert(error_key) {
87             debug!("report_fulfillment_errors: skipping duplicate");
88             return;
89         }
90         match error.code {
91             FulfillmentErrorCode::CodeSelectionError(ref e) => {
92                 self.report_selection_error(&error.obligation, e, warning_node_id);
93             }
94             FulfillmentErrorCode::CodeProjectionError(ref e) => {
95                 self.report_projection_error(&error.obligation, e, warning_node_id);
96             }
97             FulfillmentErrorCode::CodeAmbiguity => {
98                 self.maybe_report_ambiguity(&error.obligation);
99             }
100         }
101     }
102
103     fn report_projection_error(&self,
104                                obligation: &PredicateObligation<'tcx>,
105                                error: &MismatchedProjectionTypes<'tcx>,
106                                warning_node_id: Option<ast::NodeId>)
107     {
108         let predicate =
109             self.resolve_type_vars_if_possible(&obligation.predicate);
110
111         if predicate.references_error() {
112             return
113         }
114         if let Some(warning_node_id) = warning_node_id {
115             self.tcx.sess.add_lint(
116                 ::lint::builtin::UNSIZED_IN_TUPLE,
117                 warning_node_id,
118                 obligation.cause.span,
119                 format!("type mismatch resolving `{}`: {}",
120                         predicate,
121                         error.err));
122             return
123         }
124         self.probe(|_| {
125             let origin = TypeOrigin::Misc(obligation.cause.span);
126             let err_buf;
127             let mut err = &error.err;
128             let mut values = None;
129
130             // try to find the mismatched types to report the error with.
131             //
132             // this can fail if the problem was higher-ranked, in which
133             // cause I have no idea for a good error message.
134             if let ty::Predicate::Projection(ref data) = predicate {
135                 let mut selcx = SelectionContext::new(self);
136                 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
137                     obligation.cause.span,
138                     infer::LateBoundRegionConversionTime::HigherRankedType,
139                     data);
140                 let normalized = super::normalize_projection_type(
141                     &mut selcx,
142                     data.projection_ty,
143                     obligation.cause.clone(),
144                     0
145                 );
146                 let origin = TypeOrigin::Misc(obligation.cause.span);
147                 if let Err(error) = self.eq_types(
148                     false, origin,
149                     data.ty, normalized.value
150                 ) {
151                     values = Some(infer::ValuePairs::Types(ExpectedFound {
152                         expected: normalized.value,
153                         found: data.ty,
154                     }));
155                     err_buf = error;
156                     err = &err_buf;
157                 }
158             }
159
160             let mut diag = type_err!(
161                 self,
162                 origin,
163                 values,
164                 err,
165                 E0271,
166                 "type mismatch resolving `{}`",
167                 predicate);
168             self.note_obligation_cause(&mut diag, obligation);
169             diag.emit();
170         });
171     }
172
173     fn impl_substs(&self,
174                    did: DefId,
175                    obligation: PredicateObligation<'tcx>)
176                    -> subst::Substs<'tcx> {
177         let tcx = self.tcx;
178
179         let ity = tcx.lookup_item_type(did);
180         let (tps, rps, _) =
181             (ity.generics.types.get_slice(TypeSpace),
182              ity.generics.regions.get_slice(TypeSpace),
183              ity.ty);
184
185         let rps = self.region_vars_for_defs(obligation.cause.span, rps);
186         let mut substs = subst::Substs::new(
187             subst::VecPerParamSpace::empty(),
188             subst::VecPerParamSpace::new(rps, Vec::new(), Vec::new()));
189         self.type_vars_for_defs(obligation.cause.span,
190                                 TypeSpace,
191                                 &mut substs,
192                                 tps);
193         substs
194     }
195
196     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
197         /// returns the fuzzy category of a given type, or None
198         /// if the type can be equated to any type.
199         fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
200             match t.sty {
201                 ty::TyBool => Some(0),
202                 ty::TyChar => Some(1),
203                 ty::TyStr => Some(2),
204                 ty::TyInt(..) | ty::TyUint(..) |
205                 ty::TyInfer(ty::IntVar(..)) => Some(3),
206                 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
207                 ty::TyEnum(..) => Some(5),
208                 ty::TyStruct(..) => Some(6),
209                 ty::TyBox(..) | ty::TyRef(..) | ty::TyRawPtr(..) => Some(7),
210                 ty::TyArray(..) | ty::TySlice(..) => Some(8),
211                 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(9),
212                 ty::TyTrait(..) => Some(10),
213                 ty::TyClosure(..) => Some(11),
214                 ty::TyTuple(..) => Some(12),
215                 ty::TyProjection(..) => Some(13),
216                 ty::TyParam(..) => Some(14),
217                 ty::TyInfer(..) | ty::TyError => None
218             }
219         }
220
221         match (type_category(a), type_category(b)) {
222             (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
223                 (&ty::TyStruct(def_a, _), &ty::TyStruct(def_b, _)) |
224                 (&ty::TyEnum(def_a, _), &ty::TyEnum(def_b, _)) =>
225                     def_a == def_b,
226                 _ => cat_a == cat_b
227             },
228             // infer and error can be equated to all types
229             _ => true
230         }
231     }
232
233     fn impl_similar_to(&self,
234                        trait_ref: ty::PolyTraitRef<'tcx>,
235                        obligation: &PredicateObligation<'tcx>)
236                        -> Option<DefId>
237     {
238         let tcx = self.tcx;
239
240         let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
241         let trait_self_ty = trait_ref.self_ty();
242
243         let mut self_match_impls = vec![];
244         let mut fuzzy_match_impls = vec![];
245
246         self.tcx.lookup_trait_def(trait_ref.def_id)
247             .for_each_relevant_impl(self.tcx, trait_self_ty, |def_id| {
248                 let impl_trait_ref = tcx
249                     .impl_trait_ref(def_id)
250                     .unwrap()
251                     .subst(tcx, &self.impl_substs(def_id, obligation.clone()));
252
253                 let impl_self_ty = impl_trait_ref.self_ty();
254
255                 if let Ok(..) = self.can_equate(&trait_self_ty, &impl_self_ty) {
256                     self_match_impls.push(def_id);
257
258                     if trait_ref.substs.types.get_slice(TypeSpace).iter()
259                         .zip(impl_trait_ref.substs.types.get_slice(TypeSpace))
260                         .all(|(u,v)| self.fuzzy_match_tys(u, v))
261                     {
262                         fuzzy_match_impls.push(def_id);
263                     }
264                 }
265             });
266
267         let impl_def_id = if self_match_impls.len() == 1 {
268             self_match_impls[0]
269         } else if fuzzy_match_impls.len() == 1 {
270             fuzzy_match_impls[0]
271         } else {
272             return None
273         };
274
275         if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
276             Some(impl_def_id)
277         } else {
278             None
279         }
280     }
281
282     fn on_unimplemented_note(&self,
283                              trait_ref: ty::PolyTraitRef<'tcx>,
284                              obligation: &PredicateObligation<'tcx>) -> Option<String> {
285         let def_id = self.impl_similar_to(trait_ref, obligation)
286             .unwrap_or(trait_ref.def_id());
287         let trait_ref = trait_ref.skip_binder();
288
289         let span = obligation.cause.span;
290         let mut report = None;
291         for item in self.tcx.get_attrs(def_id).iter() {
292             if item.check_name("rustc_on_unimplemented") {
293                 let err_sp = item.meta().span.substitute_dummy(span);
294                 let def = self.tcx.lookup_trait_def(trait_ref.def_id);
295                 let trait_str = def.trait_ref.to_string();
296                 if let Some(ref istring) = item.value_str() {
297                     let mut generic_map = def.generics.types.iter_enumerated()
298                                              .map(|(param, i, gen)| {
299                                                    (gen.name.as_str().to_string(),
300                                                     trait_ref.substs.types.get(param, i)
301                                                              .to_string())
302                                                   }).collect::<FnvHashMap<String, String>>();
303                     generic_map.insert("Self".to_string(),
304                                        trait_ref.self_ty().to_string());
305                     let parser = Parser::new(&istring);
306                     let mut errored = false;
307                     let err: String = parser.filter_map(|p| {
308                         match p {
309                             Piece::String(s) => Some(s),
310                             Piece::NextArgument(a) => match a.position {
311                                 Position::ArgumentNamed(s) => match generic_map.get(s) {
312                                     Some(val) => Some(val),
313                                     None => {
314                                         span_err!(self.tcx.sess, err_sp, E0272,
315                                                        "the #[rustc_on_unimplemented] \
316                                                                 attribute on \
317                                                                 trait definition for {} refers to \
318                                                                 non-existent type parameter {}",
319                                                                trait_str, s);
320                                         errored = true;
321                                         None
322                                     }
323                                 },
324                                 _ => {
325                                     span_err!(self.tcx.sess, err_sp, E0273,
326                                               "the #[rustc_on_unimplemented] attribute \
327                                                on trait definition for {} must have \
328                                                named format arguments, eg \
329                                                `#[rustc_on_unimplemented = \
330                                                 \"foo {{T}}\"]`", trait_str);
331                                     errored = true;
332                                     None
333                                 }
334                             }
335                         }
336                     }).collect();
337                     // Report only if the format string checks out
338                     if !errored {
339                         report = Some(err);
340                     }
341                 } else {
342                     span_err!(self.tcx.sess, err_sp, E0274,
343                                             "the #[rustc_on_unimplemented] attribute on \
344                                                      trait definition for {} must have a value, \
345                                                      eg `#[rustc_on_unimplemented = \"foo\"]`",
346                                                      trait_str);
347                 }
348                 break;
349             }
350         }
351         report
352     }
353
354     fn find_similar_impl_candidates(&self,
355                                     trait_ref: ty::PolyTraitRef<'tcx>)
356                                     -> Vec<ty::TraitRef<'tcx>>
357     {
358         let simp = fast_reject::simplify_type(self.tcx,
359                                               trait_ref.skip_binder().self_ty(),
360                                               true);
361         let mut impl_candidates = Vec::new();
362         let trait_def = self.tcx.lookup_trait_def(trait_ref.def_id());
363
364         match simp {
365             Some(simp) => trait_def.for_each_impl(self.tcx, |def_id| {
366                 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
367                 let imp_simp = fast_reject::simplify_type(self.tcx,
368                                                           imp.self_ty(),
369                                                           true);
370                 if let Some(imp_simp) = imp_simp {
371                     if simp != imp_simp {
372                         return;
373                     }
374                 }
375                 impl_candidates.push(imp);
376             }),
377             None => trait_def.for_each_impl(self.tcx, |def_id| {
378                 impl_candidates.push(
379                     self.tcx.impl_trait_ref(def_id).unwrap());
380             })
381         };
382         impl_candidates
383     }
384
385     fn report_similar_impl_candidates(&self,
386                                       trait_ref: ty::PolyTraitRef<'tcx>,
387                                       err: &mut DiagnosticBuilder)
388     {
389         let simp = fast_reject::simplify_type(self.tcx,
390                                               trait_ref.skip_binder().self_ty(),
391                                               true);
392         let mut impl_candidates = Vec::new();
393         let trait_def = self.tcx.lookup_trait_def(trait_ref.def_id());
394
395         match simp {
396             Some(simp) => trait_def.for_each_impl(self.tcx, |def_id| {
397                 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
398                 let imp_simp = fast_reject::simplify_type(self.tcx,
399                                                           imp.self_ty(),
400                                                           true);
401                 if let Some(imp_simp) = imp_simp {
402                     if simp != imp_simp {
403                         return;
404                     }
405                 }
406                 impl_candidates.push(imp);
407             }),
408             None => trait_def.for_each_impl(self.tcx, |def_id| {
409                 impl_candidates.push(
410                     self.tcx.impl_trait_ref(def_id).unwrap());
411             })
412         };
413
414         if impl_candidates.is_empty() {
415             return;
416         }
417
418         err.help(&format!("the following implementations were found:"));
419
420         let end = cmp::min(4, impl_candidates.len());
421         for candidate in &impl_candidates[0..end] {
422             err.help(&format!("  {:?}", candidate));
423         }
424         if impl_candidates.len() > 4 {
425             err.help(&format!("and {} others", impl_candidates.len()-4));
426         }
427     }
428
429     /// Reports that an overflow has occurred and halts compilation. We
430     /// halt compilation unconditionally because it is important that
431     /// overflows never be masked -- they basically represent computations
432     /// whose result could not be truly determined and thus we can't say
433     /// if the program type checks or not -- and they are unusual
434     /// occurrences in any case.
435     pub fn report_overflow_error<T>(&self,
436                                     obligation: &Obligation<'tcx, T>,
437                                     suggest_increasing_limit: bool) -> !
438         where T: fmt::Display + TypeFoldable<'tcx>
439     {
440         let predicate =
441             self.resolve_type_vars_if_possible(&obligation.predicate);
442         let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
443                                        "overflow evaluating the requirement `{}`",
444                                        predicate);
445
446         if suggest_increasing_limit {
447             self.suggest_new_overflow_limit(&mut err);
448         }
449
450         self.note_obligation_cause(&mut err, obligation);
451
452         err.emit();
453         self.tcx.sess.abort_if_errors();
454         bug!();
455     }
456
457     /// Reports that a cycle was detected which led to overflow and halts
458     /// compilation. This is equivalent to `report_overflow_error` except
459     /// that we can give a more helpful error message (and, in particular,
460     /// we do not suggest increasing the overflow limit, which is not
461     /// going to help).
462     pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
463         let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
464         assert!(cycle.len() > 0);
465
466         debug!("report_overflow_error_cycle: cycle={:?}", cycle);
467
468         self.report_overflow_error(&cycle[0], false);
469     }
470
471     pub fn report_selection_error(&self,
472                                   obligation: &PredicateObligation<'tcx>,
473                                   error: &SelectionError<'tcx>,
474                                   warning_node_id: Option<ast::NodeId>)
475     {
476         let span = obligation.cause.span;
477         let mut err = match *error {
478             SelectionError::Unimplemented => {
479                 if let ObligationCauseCode::CompareImplMethodObligation = obligation.cause.code {
480                     span_err!(
481                         self.tcx.sess, span, E0276,
482                         "the requirement `{}` appears on the impl \
483                          method but not on the corresponding trait method",
484                         obligation.predicate);
485                     return;
486                 } else {
487                     match obligation.predicate {
488                         ty::Predicate::Trait(ref trait_predicate) => {
489                             let trait_predicate =
490                                 self.resolve_type_vars_if_possible(trait_predicate);
491
492                             if self.tcx.sess.has_errors() && trait_predicate.references_error() {
493                                 return;
494                             } else {
495                                 let trait_ref = trait_predicate.to_poly_trait_ref();
496
497                                 if let Some(warning_node_id) = warning_node_id {
498                                     self.tcx.sess.add_lint(
499                                         ::lint::builtin::UNSIZED_IN_TUPLE,
500                                         warning_node_id,
501                                         obligation.cause.span,
502                                         format!("the trait bound `{}` is not satisfied",
503                                                 trait_ref.to_predicate()));
504                                     return;
505                                 }
506
507                                 let mut err = struct_span_err!(
508                                     self.tcx.sess, span, E0277,
509                                     "the trait bound `{}` is not satisfied",
510                                     trait_ref.to_predicate());
511
512                                 // Try to report a help message
513
514                                 if !trait_ref.has_infer_types() &&
515                                     self.predicate_can_apply(trait_ref) {
516                                     // If a where-clause may be useful, remind the
517                                     // user that they can add it.
518                                     //
519                                     // don't display an on-unimplemented note, as
520                                     // these notes will often be of the form
521                                     //     "the type `T` can't be frobnicated"
522                                     // which is somewhat confusing.
523                                     err.help(&format!("consider adding a `where {}` bound",
524                                                       trait_ref.to_predicate()));
525                                 } else if let Some(s) = self.on_unimplemented_note(trait_ref,
526                                                                                    obligation) {
527                                     // If it has a custom "#[rustc_on_unimplemented]"
528                                     // error message, let's display it!
529                                     err.note(&s);
530                                 } else {
531                                     // If we can't show anything useful, try to find
532                                     // similar impls.
533                                     let impl_candidates =
534                                         self.find_similar_impl_candidates(trait_ref);
535                                     if impl_candidates.len() > 0 {
536                                         self.report_similar_impl_candidates(trait_ref, &mut err);
537                                     }
538                                 }
539                                 err
540                             }
541                         }
542
543                         ty::Predicate::Equate(ref predicate) => {
544                             let predicate = self.resolve_type_vars_if_possible(predicate);
545                             let err = self.equality_predicate(span,
546                                                               &predicate).err().unwrap();
547                             struct_span_err!(self.tcx.sess, span, E0278,
548                                 "the requirement `{}` is not satisfied (`{}`)",
549                                 predicate, err)
550                         }
551
552                         ty::Predicate::RegionOutlives(ref predicate) => {
553                             let predicate = self.resolve_type_vars_if_possible(predicate);
554                             let err = self.region_outlives_predicate(span,
555                                                                      &predicate).err().unwrap();
556                             struct_span_err!(self.tcx.sess, span, E0279,
557                                 "the requirement `{}` is not satisfied (`{}`)",
558                                 predicate, err)
559                         }
560
561                         ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
562                             let predicate =
563                                 self.resolve_type_vars_if_possible(&obligation.predicate);
564                             struct_span_err!(self.tcx.sess, span, E0280,
565                                 "the requirement `{}` is not satisfied",
566                                 predicate)
567                         }
568
569                         ty::Predicate::ObjectSafe(trait_def_id) => {
570                             let violations = self.tcx.object_safety_violations(trait_def_id);
571                             let err = self.tcx.report_object_safety_error(span,
572                                                                           trait_def_id,
573                                                                           warning_node_id,
574                                                                           violations);
575                             if let Some(err) = err {
576                                 err
577                             } else {
578                                 return;
579                             }
580                         }
581
582                         ty::Predicate::ClosureKind(closure_def_id, kind) => {
583                             let found_kind = self.closure_kind(closure_def_id).unwrap();
584                             let closure_span = self.tcx.map.span_if_local(closure_def_id).unwrap();
585                             let mut err = struct_span_err!(
586                                 self.tcx.sess, closure_span, E0525,
587                                 "expected a closure that implements the `{}` trait, \
588                                  but this closure only implements `{}`",
589                                 kind,
590                                 found_kind);
591                             err.span_note(
592                                 obligation.cause.span,
593                                 &format!("the requirement to implement \
594                                           `{}` derives from here", kind));
595                             err.emit();
596                             return;
597                         }
598
599                         ty::Predicate::WellFormed(ty) => {
600                             // WF predicates cannot themselves make
601                             // errors. They can only block due to
602                             // ambiguity; otherwise, they always
603                             // degenerate into other obligations
604                             // (which may fail).
605                             span_bug!(span, "WF predicate not satisfied for {:?}", ty);
606                         }
607
608                         ty::Predicate::Rfc1592(ref data) => {
609                             span_bug!(
610                                 obligation.cause.span,
611                                 "RFC1592 predicate not satisfied for {:?}",
612                                 data);
613                         }
614                     }
615                 }
616             }
617
618             OutputTypeParameterMismatch(ref expected_trait_ref, ref actual_trait_ref, ref e) => {
619                 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
620                 let actual_trait_ref = self.resolve_type_vars_if_possible(&*actual_trait_ref);
621                 if actual_trait_ref.self_ty().references_error() {
622                     return;
623                 }
624                 struct_span_err!(self.tcx.sess, span, E0281,
625                     "type mismatch: the type `{}` implements the trait `{}`, \
626                      but the trait `{}` is required ({})",
627                     expected_trait_ref.self_ty(),
628                     expected_trait_ref,
629                     actual_trait_ref,
630                     e)
631             }
632
633             TraitNotObjectSafe(did) => {
634                 let violations = self.tcx.object_safety_violations(did);
635                 let err = self.tcx.report_object_safety_error(span, did,
636                                                               warning_node_id,
637                                                               violations);
638                 if let Some(err) = err {
639                     err
640                 } else {
641                     return;
642                 }
643             }
644         };
645         self.note_obligation_cause(&mut err, obligation);
646         err.emit();
647     }
648 }
649
650 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
651     pub fn recursive_type_with_infinite_size_error(self,
652                                                    type_def_id: DefId)
653                                                    -> DiagnosticBuilder<'tcx>
654     {
655         assert!(type_def_id.is_local());
656         let span = self.map.span_if_local(type_def_id).unwrap();
657         let mut err = struct_span_err!(self.sess, span, E0072,
658                                        "recursive type `{}` has infinite size",
659                                        self.item_path_str(type_def_id));
660         err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
661                            at some point to make `{}` representable",
662                           self.item_path_str(type_def_id)));
663         err
664     }
665
666     pub fn report_object_safety_error(self,
667                                       span: Span,
668                                       trait_def_id: DefId,
669                                       warning_node_id: Option<ast::NodeId>,
670                                       violations: Vec<ObjectSafetyViolation>)
671                                       -> Option<DiagnosticBuilder<'tcx>>
672     {
673         let mut err = match warning_node_id {
674             Some(_) => None,
675             None => {
676                 Some(struct_span_err!(
677                     self.sess, span, E0038,
678                     "the trait `{}` cannot be made into an object",
679                     self.item_path_str(trait_def_id)))
680             }
681         };
682
683         let mut reported_violations = FnvHashSet();
684         for violation in violations {
685             if !reported_violations.insert(violation.clone()) {
686                 continue;
687             }
688             let buf;
689             let note = match violation {
690                 ObjectSafetyViolation::SizedSelf => {
691                     "the trait cannot require that `Self : Sized`"
692                 }
693
694                 ObjectSafetyViolation::SupertraitSelf => {
695                     "the trait cannot use `Self` as a type parameter \
696                          in the supertrait listing"
697                 }
698
699                 ObjectSafetyViolation::Method(method,
700                                               MethodViolationCode::StaticMethod) => {
701                     buf = format!("method `{}` has no receiver",
702                                   method.name);
703                     &buf
704                 }
705
706                 ObjectSafetyViolation::Method(method,
707                                               MethodViolationCode::ReferencesSelf) => {
708                     buf = format!("method `{}` references the `Self` type \
709                                        in its arguments or return type",
710                                   method.name);
711                     &buf
712                 }
713
714                 ObjectSafetyViolation::Method(method,
715                                               MethodViolationCode::Generic) => {
716                     buf = format!("method `{}` has generic type parameters",
717                                   method.name);
718                     &buf
719                 }
720             };
721             match (warning_node_id, &mut err) {
722                 (Some(node_id), &mut None) => {
723                     self.sess.add_lint(
724                         ::lint::builtin::OBJECT_UNSAFE_FRAGMENT,
725                         node_id,
726                         span,
727                         note.to_string());
728                 }
729                 (None, &mut Some(ref mut err)) => {
730                     err.note(note);
731                 }
732                 _ => unreachable!()
733             }
734         }
735         err
736     }
737 }
738
739 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
740     fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>) {
741         // Unable to successfully determine, probably means
742         // insufficient type information, but could mean
743         // ambiguous impls. The latter *ought* to be a
744         // coherence violation, so we don't report it here.
745
746         let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
747
748         debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
749                predicate,
750                obligation);
751
752         // Ambiguity errors are often caused as fallout from earlier
753         // errors. So just ignore them if this infcx is tainted.
754         if self.is_tainted_by_errors() {
755             return;
756         }
757
758         match predicate {
759             ty::Predicate::Trait(ref data) => {
760                 let trait_ref = data.to_poly_trait_ref();
761                 let self_ty = trait_ref.self_ty();
762                 let all_types = &trait_ref.substs().types;
763                 if all_types.references_error() {
764                 } else {
765                     // Typically, this ambiguity should only happen if
766                     // there are unresolved type inference variables
767                     // (otherwise it would suggest a coherence
768                     // failure). But given #21974 that is not necessarily
769                     // the case -- we can have multiple where clauses that
770                     // are only distinguished by a region, which results
771                     // in an ambiguity even when all types are fully
772                     // known, since we don't dispatch based on region
773                     // relationships.
774
775                     // This is kind of a hack: it frequently happens that some earlier
776                     // error prevents types from being fully inferred, and then we get
777                     // a bunch of uninteresting errors saying something like "<generic
778                     // #0> doesn't implement Sized".  It may even be true that we
779                     // could just skip over all checks where the self-ty is an
780                     // inference variable, but I was afraid that there might be an
781                     // inference variable created, registered as an obligation, and
782                     // then never forced by writeback, and hence by skipping here we'd
783                     // be ignoring the fact that we don't KNOW the type works
784                     // out. Though even that would probably be harmless, given that
785                     // we're only talking about builtin traits, which are known to be
786                     // inhabited. But in any case I just threw in this check for
787                     // has_errors() to be sure that compilation isn't happening
788                     // anyway. In that case, why inundate the user.
789                     if !self.tcx.sess.has_errors() {
790                         if
791                             self.tcx.lang_items.sized_trait()
792                             .map_or(false, |sized_id| sized_id == trait_ref.def_id())
793                         {
794                             self.need_type_info(obligation.cause.span, self_ty);
795                         } else {
796                             let mut err = struct_span_err!(self.tcx.sess,
797                                                            obligation.cause.span, E0283,
798                                                            "type annotations required: \
799                                                             cannot resolve `{}`",
800                                                            predicate);
801                             self.note_obligation_cause(&mut err, obligation);
802                             err.emit();
803                         }
804                     }
805                 }
806             }
807
808             ty::Predicate::WellFormed(ty) => {
809                 // Same hacky approach as above to avoid deluging user
810                 // with error messages.
811                 if !ty.references_error() && !self.tcx.sess.has_errors() {
812                     self.need_type_info(obligation.cause.span, ty);
813                 }
814             }
815
816             _ => {
817                 if !self.tcx.sess.has_errors() {
818                     let mut err = struct_span_err!(self.tcx.sess,
819                                                    obligation.cause.span, E0284,
820                                                    "type annotations required: \
821                                                     cannot resolve `{}`",
822                                                    predicate);
823                     self.note_obligation_cause(&mut err, obligation);
824                     err.emit();
825                 }
826             }
827         }
828     }
829
830     /// Returns whether the trait predicate may apply for *some* assignment
831     /// to the type parameters.
832     fn predicate_can_apply(&self, pred: ty::PolyTraitRef<'tcx>) -> bool {
833         struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
834             infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
835             var_map: FnvHashMap<Ty<'tcx>, Ty<'tcx>>
836         }
837
838         impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
839             fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
840
841             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
842                 if let ty::TyParam(..) = ty.sty {
843                     let infcx = self.infcx;
844                     self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var())
845                 } else {
846                     ty.super_fold_with(self)
847                 }
848             }
849         }
850
851         self.probe(|_| {
852             let mut selcx = SelectionContext::new(self);
853
854             let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
855                 infcx: self,
856                 var_map: FnvHashMap()
857             });
858
859             let cleaned_pred = super::project::normalize(
860                 &mut selcx,
861                 ObligationCause::dummy(),
862                 &cleaned_pred
863             ).value;
864
865             let obligation = Obligation::new(
866                 ObligationCause::dummy(),
867                 cleaned_pred.to_predicate()
868             );
869
870             selcx.evaluate_obligation(&obligation)
871         })
872     }
873
874
875     fn need_type_info(&self, span: Span, ty: Ty<'tcx>) {
876         span_err!(self.tcx.sess, span, E0282,
877                   "unable to infer enough type information about `{}`; \
878                    type annotations or generic parameter binding required",
879                   ty);
880     }
881
882     fn note_obligation_cause<T>(&self,
883                                 err: &mut DiagnosticBuilder,
884                                 obligation: &Obligation<'tcx, T>)
885         where T: fmt::Display
886     {
887         self.note_obligation_cause_code(err,
888                                         &obligation.predicate,
889                                         &obligation.cause.code);
890     }
891
892     fn note_obligation_cause_code<T>(&self,
893                                      err: &mut DiagnosticBuilder,
894                                      predicate: &T,
895                                      cause_code: &ObligationCauseCode<'tcx>)
896         where T: fmt::Display
897     {
898         let tcx = self.tcx;
899         match *cause_code {
900             ObligationCauseCode::MiscObligation => { }
901             ObligationCauseCode::SliceOrArrayElem => {
902                 err.note("slice and array elements must have `Sized` type");
903             }
904             ObligationCauseCode::TupleElem => {
905                 err.note("tuple elements must have `Sized` type");
906             }
907             ObligationCauseCode::ProjectionWf(data) => {
908                 err.note(&format!("required so that the projection `{}` is well-formed",
909                                   data));
910             }
911             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
912                 err.note(&format!("required so that reference `{}` does not outlive its referent",
913                                   ref_ty));
914             }
915             ObligationCauseCode::ItemObligation(item_def_id) => {
916                 let item_name = tcx.item_path_str(item_def_id);
917                 err.note(&format!("required by `{}`", item_name));
918             }
919             ObligationCauseCode::ObjectCastObligation(object_ty) => {
920                 err.note(&format!("required for the cast to the object type `{}`",
921                                   self.ty_to_string(object_ty)));
922             }
923             ObligationCauseCode::RepeatVec => {
924                 err.note("the `Copy` trait is required because the \
925                           repeated element will be copied");
926             }
927             ObligationCauseCode::VariableType(_) => {
928                 err.note("all local variables must have a statically known size");
929             }
930             ObligationCauseCode::ReturnType => {
931                 err.note("the return type of a function must have a \
932                           statically known size");
933             }
934             ObligationCauseCode::AssignmentLhsSized => {
935                 err.note("the left-hand-side of an assignment must have a statically known size");
936             }
937             ObligationCauseCode::StructInitializerSized => {
938                 err.note("structs must have a statically known size to be initialized");
939             }
940             ObligationCauseCode::ClosureCapture(var_id, _, builtin_bound) => {
941                 let def_id = tcx.lang_items.from_builtin_kind(builtin_bound).unwrap();
942                 let trait_name = tcx.item_path_str(def_id);
943                 let name = tcx.local_var_name_str(var_id);
944                 err.note(
945                     &format!("the closure that captures `{}` requires that all captured variables \
946                               implement the trait `{}`",
947                              name,
948                              trait_name));
949             }
950             ObligationCauseCode::FieldSized => {
951                 err.note("only the last field of a struct or enum variant \
952                           may have a dynamically sized type");
953             }
954             ObligationCauseCode::ConstSized => {
955                 err.note("constant expressions must have a statically known size");
956             }
957             ObligationCauseCode::SharedStatic => {
958                 err.note("shared static variables must have a type that implements `Sync`");
959             }
960             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
961                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
962                 err.note(&format!("required because it appears within the type `{}`",
963                                   parent_trait_ref.0.self_ty()));
964                 let parent_predicate = parent_trait_ref.to_predicate();
965                 self.note_obligation_cause_code(err,
966                                                 &parent_predicate,
967                                                 &data.parent_code);
968             }
969             ObligationCauseCode::ImplDerivedObligation(ref data) => {
970                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
971                 err.note(
972                     &format!("required because of the requirements on the impl of `{}` for `{}`",
973                              parent_trait_ref,
974                              parent_trait_ref.0.self_ty()));
975                 let parent_predicate = parent_trait_ref.to_predicate();
976                 self.note_obligation_cause_code(err,
977                                                 &parent_predicate,
978                                                 &data.parent_code);
979             }
980             ObligationCauseCode::CompareImplMethodObligation => {
981                 err.note(
982                     &format!("the requirement `{}` appears on the impl method \
983                               but not on the corresponding trait method",
984                              predicate));
985             }
986         }
987     }
988
989     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
990         let current_limit = self.tcx.sess.recursion_limit.get();
991         let suggested_limit = current_limit * 2;
992         err.note(&format!(
993                           "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
994                           suggested_limit));
995     }
996 }