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.
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.
14 MismatchedProjectionTypes,
18 OutputTypeParameterMismatch,
23 ObjectSafetyViolation,
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;
33 use ty::fold::TypeFolder;
34 use ty::subst::{self, Subst, TypeSpace};
35 use util::nodemap::{FnvHashMap, FnvHashSet};
40 use syntax::attr::{AttributeMethods, AttrMetaMethods};
42 use errors::DiagnosticBuilder;
44 #[derive(Debug, PartialEq, Eq, Hash)]
45 pub struct TraitErrorKey<'tcx> {
47 warning_node_id: Option<ast::NodeId>,
48 predicate: ty::Predicate<'tcx>
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 {
56 infcx.resolve_type_vars_if_possible(&e.obligation.predicate);
58 span: e.obligation.cause.span,
59 predicate: infcx.tcx.erase_regions(&predicate),
60 warning_node_id: warning_node_id
65 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
66 pub fn report_fulfillment_errors(&self, errors: &Vec<FulfillmentError<'tcx>>) {
68 self.report_fulfillment_error(error, None);
72 pub fn report_fulfillment_errors_as_warnings(&self,
73 errors: &Vec<FulfillmentError<'tcx>>,
74 node_id: ast::NodeId) {
76 self.report_fulfillment_error(error, Some(node_id));
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={:?}",
86 if !self.reported_trait_errors.borrow_mut().insert(error_key) {
87 debug!("report_fulfillment_errors: skipping duplicate");
91 FulfillmentErrorCode::CodeSelectionError(ref e) => {
92 self.report_selection_error(&error.obligation, e, warning_node_id);
94 FulfillmentErrorCode::CodeProjectionError(ref e) => {
95 self.report_projection_error(&error.obligation, e, warning_node_id);
97 FulfillmentErrorCode::CodeAmbiguity => {
98 self.maybe_report_ambiguity(&error.obligation);
103 fn report_projection_error(&self,
104 obligation: &PredicateObligation<'tcx>,
105 error: &MismatchedProjectionTypes<'tcx>,
106 warning_node_id: Option<ast::NodeId>)
109 self.resolve_type_vars_if_possible(&obligation.predicate);
111 if predicate.references_error() {
114 if let Some(warning_node_id) = warning_node_id {
115 self.tcx.sess.add_lint(
116 ::lint::builtin::UNSIZED_IN_TUPLE,
118 obligation.cause.span,
119 format!("type mismatch resolving `{}`: {}",
125 let origin = TypeOrigin::Misc(obligation.cause.span);
127 let mut err = &error.err;
128 let mut values = None;
130 // try to find the mismatched types to report the error with.
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,
140 let normalized = super::normalize_projection_type(
143 obligation.cause.clone(),
146 let origin = TypeOrigin::Misc(obligation.cause.span);
147 if let Err(error) = self.eq_types(
149 data.ty, normalized.value
151 values = Some(infer::ValuePairs::Types(ExpectedFound {
152 expected: normalized.value,
160 let mut diag = type_err!(
166 "type mismatch resolving `{}`",
168 self.note_obligation_cause(&mut diag, obligation);
173 fn impl_substs(&self,
175 obligation: PredicateObligation<'tcx>)
176 -> subst::Substs<'tcx> {
179 let ity = tcx.lookup_item_type(did);
181 (ity.generics.types.get_slice(TypeSpace),
182 ity.generics.regions.get_slice(TypeSpace),
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,
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> {
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
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, _)) =>
228 // infer and error can be equated to all types
233 fn impl_similar_to(&self,
234 trait_ref: ty::PolyTraitRef<'tcx>,
235 obligation: &PredicateObligation<'tcx>)
240 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
241 let trait_self_ty = trait_ref.self_ty();
243 let mut self_match_impls = vec![];
244 let mut fuzzy_match_impls = vec![];
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)
251 .subst(tcx, &self.impl_substs(def_id, obligation.clone()));
253 let impl_self_ty = impl_trait_ref.self_ty();
255 if let Ok(..) = self.can_equate(&trait_self_ty, &impl_self_ty) {
256 self_match_impls.push(def_id);
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))
262 fuzzy_match_impls.push(def_id);
267 let impl_def_id = if self_match_impls.len() == 1 {
269 } else if fuzzy_match_impls.len() == 1 {
275 if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
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();
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)
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| {
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),
314 span_err!(self.tcx.sess, err_sp, E0272,
315 "the #[rustc_on_unimplemented] \
317 trait definition for {} refers to \
318 non-existent type parameter {}",
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);
337 // Report only if the format string checks out
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\"]`",
354 fn find_similar_impl_candidates(&self,
355 trait_ref: ty::PolyTraitRef<'tcx>)
356 -> Vec<ty::TraitRef<'tcx>>
358 let simp = fast_reject::simplify_type(self.tcx,
359 trait_ref.skip_binder().self_ty(),
361 let mut impl_candidates = Vec::new();
362 let trait_def = self.tcx.lookup_trait_def(trait_ref.def_id());
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,
370 if let Some(imp_simp) = imp_simp {
371 if simp != imp_simp {
375 impl_candidates.push(imp);
377 None => trait_def.for_each_impl(self.tcx, |def_id| {
378 impl_candidates.push(
379 self.tcx.impl_trait_ref(def_id).unwrap());
385 fn report_similar_impl_candidates(&self,
386 trait_ref: ty::PolyTraitRef<'tcx>,
387 err: &mut DiagnosticBuilder)
389 let simp = fast_reject::simplify_type(self.tcx,
390 trait_ref.skip_binder().self_ty(),
392 let mut impl_candidates = Vec::new();
393 let trait_def = self.tcx.lookup_trait_def(trait_ref.def_id());
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,
401 if let Some(imp_simp) = imp_simp {
402 if simp != imp_simp {
406 impl_candidates.push(imp);
408 None => trait_def.for_each_impl(self.tcx, |def_id| {
409 impl_candidates.push(
410 self.tcx.impl_trait_ref(def_id).unwrap());
414 if impl_candidates.is_empty() {
418 err.help(&format!("the following implementations were found:"));
420 let end = cmp::min(4, impl_candidates.len());
421 for candidate in &impl_candidates[0..end] {
422 err.help(&format!(" {:?}", candidate));
424 if impl_candidates.len() > 4 {
425 err.help(&format!("and {} others", impl_candidates.len()-4));
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>
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 `{}`",
446 if suggest_increasing_limit {
447 self.suggest_new_overflow_limit(&mut err);
450 self.note_obligation_cause(&mut err, obligation);
453 self.tcx.sess.abort_if_errors();
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
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);
466 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
468 self.report_overflow_error(&cycle[0], false);
471 pub fn report_selection_error(&self,
472 obligation: &PredicateObligation<'tcx>,
473 error: &SelectionError<'tcx>,
474 warning_node_id: Option<ast::NodeId>)
476 let span = obligation.cause.span;
477 let mut err = match *error {
478 SelectionError::Unimplemented => {
479 if let ObligationCauseCode::CompareImplMethodObligation = obligation.cause.code {
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);
487 match obligation.predicate {
488 ty::Predicate::Trait(ref trait_predicate) => {
489 let trait_predicate =
490 self.resolve_type_vars_if_possible(trait_predicate);
492 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
495 let trait_ref = trait_predicate.to_poly_trait_ref();
497 if let Some(warning_node_id) = warning_node_id {
498 self.tcx.sess.add_lint(
499 ::lint::builtin::UNSIZED_IN_TUPLE,
501 obligation.cause.span,
502 format!("the trait bound `{}` is not satisfied",
503 trait_ref.to_predicate()));
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());
512 // Try to report a help message
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.
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,
527 // If it has a custom "#[rustc_on_unimplemented]"
528 // error message, let's display it!
531 // If we can't show anything useful, try to find
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);
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 (`{}`)",
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 (`{}`)",
561 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
563 self.resolve_type_vars_if_possible(&obligation.predicate);
564 struct_span_err!(self.tcx.sess, span, E0280,
565 "the requirement `{}` is not satisfied",
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,
575 if let Some(err) = err {
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 `{}`",
592 obligation.cause.span,
593 &format!("the requirement to implement \
594 `{}` derives from here", kind));
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
605 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
608 ty::Predicate::Rfc1592(ref data) => {
610 obligation.cause.span,
611 "RFC1592 predicate not satisfied for {:?}",
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() {
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(),
633 TraitNotObjectSafe(did) => {
634 let violations = self.tcx.object_safety_violations(did);
635 let err = self.tcx.report_object_safety_error(span, did,
638 if let Some(err) = err {
645 self.note_obligation_cause(&mut err, obligation);
650 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
651 pub fn recursive_type_with_infinite_size_error(self,
653 -> DiagnosticBuilder<'tcx>
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)));
666 pub fn report_object_safety_error(self,
669 warning_node_id: Option<ast::NodeId>,
670 violations: Vec<ObjectSafetyViolation>)
671 -> Option<DiagnosticBuilder<'tcx>>
673 let mut err = match warning_node_id {
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)))
683 let mut reported_violations = FnvHashSet();
684 for violation in violations {
685 if !reported_violations.insert(violation.clone()) {
689 let note = match violation {
690 ObjectSafetyViolation::SizedSelf => {
691 "the trait cannot require that `Self : Sized`"
694 ObjectSafetyViolation::SupertraitSelf => {
695 "the trait cannot use `Self` as a type parameter \
696 in the supertrait listing"
699 ObjectSafetyViolation::Method(method,
700 MethodViolationCode::StaticMethod) => {
701 buf = format!("method `{}` has no receiver",
706 ObjectSafetyViolation::Method(method,
707 MethodViolationCode::ReferencesSelf) => {
708 buf = format!("method `{}` references the `Self` type \
709 in its arguments or return type",
714 ObjectSafetyViolation::Method(method,
715 MethodViolationCode::Generic) => {
716 buf = format!("method `{}` has generic type parameters",
721 match (warning_node_id, &mut err) {
722 (Some(node_id), &mut None) => {
724 ::lint::builtin::OBJECT_UNSAFE_FRAGMENT,
729 (None, &mut Some(ref mut err)) => {
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.
746 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
748 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
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() {
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() {
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
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() {
791 self.tcx.lang_items.sized_trait()
792 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
794 self.need_type_info(obligation.cause.span, self_ty);
796 let mut err = struct_span_err!(self.tcx.sess,
797 obligation.cause.span, E0283,
798 "type annotations required: \
799 cannot resolve `{}`",
801 self.note_obligation_cause(&mut err, obligation);
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);
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 `{}`",
823 self.note_obligation_cause(&mut err, obligation);
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>>
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 }
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())
846 ty.super_fold_with(self)
852 let mut selcx = SelectionContext::new(self);
854 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
856 var_map: FnvHashMap()
859 let cleaned_pred = super::project::normalize(
861 ObligationCause::dummy(),
865 let obligation = Obligation::new(
866 ObligationCause::dummy(),
867 cleaned_pred.to_predicate()
870 selcx.evaluate_obligation(&obligation)
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",
882 fn note_obligation_cause<T>(&self,
883 err: &mut DiagnosticBuilder,
884 obligation: &Obligation<'tcx, T>)
885 where T: fmt::Display
887 self.note_obligation_cause_code(err,
888 &obligation.predicate,
889 &obligation.cause.code);
892 fn note_obligation_cause_code<T>(&self,
893 err: &mut DiagnosticBuilder,
895 cause_code: &ObligationCauseCode<'tcx>)
896 where T: fmt::Display
900 ObligationCauseCode::MiscObligation => { }
901 ObligationCauseCode::SliceOrArrayElem => {
902 err.note("slice and array elements must have `Sized` type");
904 ObligationCauseCode::TupleElem => {
905 err.note("tuple elements must have `Sized` type");
907 ObligationCauseCode::ProjectionWf(data) => {
908 err.note(&format!("required so that the projection `{}` is well-formed",
911 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
912 err.note(&format!("required so that reference `{}` does not outlive its referent",
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));
919 ObligationCauseCode::ObjectCastObligation(object_ty) => {
920 err.note(&format!("required for the cast to the object type `{}`",
921 self.ty_to_string(object_ty)));
923 ObligationCauseCode::RepeatVec => {
924 err.note("the `Copy` trait is required because the \
925 repeated element will be copied");
927 ObligationCauseCode::VariableType(_) => {
928 err.note("all local variables must have a statically known size");
930 ObligationCauseCode::ReturnType => {
931 err.note("the return type of a function must have a \
932 statically known size");
934 ObligationCauseCode::AssignmentLhsSized => {
935 err.note("the left-hand-side of an assignment must have a statically known size");
937 ObligationCauseCode::StructInitializerSized => {
938 err.note("structs must have a statically known size to be initialized");
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);
945 &format!("the closure that captures `{}` requires that all captured variables \
946 implement the trait `{}`",
950 ObligationCauseCode::FieldSized => {
951 err.note("only the last field of a struct or enum variant \
952 may have a dynamically sized type");
954 ObligationCauseCode::ConstSized => {
955 err.note("constant expressions must have a statically known size");
957 ObligationCauseCode::SharedStatic => {
958 err.note("shared static variables must have a type that implements `Sync`");
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,
969 ObligationCauseCode::ImplDerivedObligation(ref data) => {
970 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
972 &format!("required because of the requirements on the impl of `{}` for `{}`",
974 parent_trait_ref.0.self_ty()));
975 let parent_predicate = parent_trait_ref.to_predicate();
976 self.note_obligation_cause_code(err,
980 ObligationCauseCode::CompareImplMethodObligation => {
982 &format!("the requirement `{}` appears on the impl method \
983 but not on the corresponding trait method",
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;
993 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",