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,
26 use errors::DiagnosticBuilder;
27 use fmt_macros::{Parser, Piece, Position};
28 use hir::{intravisit, Local, Pat};
29 use hir::intravisit::{Visitor, NestedVisitorMap};
30 use hir::map::NodeExpr;
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;
37 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
38 use ty::error::ExpectedFound;
40 use ty::fold::TypeFolder;
42 use ty::SubtypePredicate;
43 use util::nodemap::{FxHashMap, FxHashSet};
45 use syntax_pos::{DUMMY_SP, Span};
48 #[derive(Debug, PartialEq, Eq, Hash)]
49 pub struct TraitErrorKey<'tcx> {
51 predicate: ty::Predicate<'tcx>
54 impl<'a, 'gcx, 'tcx> TraitErrorKey<'tcx> {
55 fn from_error(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
56 e: &FulfillmentError<'tcx>) -> Self {
58 infcx.resolve_type_vars_if_possible(&e.obligation.predicate);
60 span: e.obligation.cause.span,
61 predicate: infcx.tcx.erase_regions(&predicate)
66 struct FindLocalByTypeVisitor<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
67 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
68 target_ty: &'a Ty<'tcx>,
69 found_pattern: Option<&'a Pat>,
72 impl<'a, 'gcx, 'tcx> FindLocalByTypeVisitor<'a, 'gcx, 'tcx> {
73 fn is_match(&self, ty: Ty<'tcx>) -> bool {
74 ty == *self.target_ty || match (&ty.sty, &self.target_ty.sty) {
75 (&ty::TyInfer(ty::TyVar(a_vid)), &ty::TyInfer(ty::TyVar(b_vid))) =>
76 self.infcx.type_variables
78 .sub_unified(a_vid, b_vid),
85 impl<'a, 'gcx, 'tcx> Visitor<'a> for FindLocalByTypeVisitor<'a, 'gcx, 'tcx> {
86 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'a> {
87 NestedVisitorMap::None
90 fn visit_local(&mut self, local: &'a Local) {
91 if let Some(&ty) = self.infcx.tables.borrow().node_types.get(&local.id) {
92 let ty = self.infcx.resolve_type_vars_if_possible(&ty);
93 let is_match = ty.walk().any(|t| self.is_match(t));
95 if is_match && self.found_pattern.is_none() {
96 self.found_pattern = Some(&*local.pat);
99 intravisit::walk_local(self, local);
103 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
104 pub fn report_fulfillment_errors(&self, errors: &Vec<FulfillmentError<'tcx>>) {
105 for error in errors {
106 self.report_fulfillment_error(error);
110 fn report_fulfillment_error(&self,
111 error: &FulfillmentError<'tcx>) {
112 let error_key = TraitErrorKey::from_error(self, error);
113 debug!("report_fulfillment_errors({:?}) - key={:?}",
115 if !self.reported_trait_errors.borrow_mut().insert(error_key) {
116 debug!("report_fulfillment_errors: skipping duplicate");
120 FulfillmentErrorCode::CodeSelectionError(ref e) => {
121 self.report_selection_error(&error.obligation, e);
123 FulfillmentErrorCode::CodeProjectionError(ref e) => {
124 self.report_projection_error(&error.obligation, e);
126 FulfillmentErrorCode::CodeAmbiguity => {
127 self.maybe_report_ambiguity(&error.obligation);
129 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
130 self.report_mismatched_types(&error.obligation.cause,
131 expected_found.expected,
132 expected_found.found,
139 fn report_projection_error(&self,
140 obligation: &PredicateObligation<'tcx>,
141 error: &MismatchedProjectionTypes<'tcx>)
144 self.resolve_type_vars_if_possible(&obligation.predicate);
146 if predicate.references_error() {
152 let mut err = &error.err;
153 let mut values = None;
155 // try to find the mismatched types to report the error with.
157 // this can fail if the problem was higher-ranked, in which
158 // cause I have no idea for a good error message.
159 if let ty::Predicate::Projection(ref data) = predicate {
160 let mut selcx = SelectionContext::new(self);
161 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
162 obligation.cause.span,
163 infer::LateBoundRegionConversionTime::HigherRankedType,
165 let normalized = super::normalize_projection_type(
168 obligation.cause.clone(),
171 if let Err(error) = self.eq_types(
172 false, &obligation.cause,
173 data.ty, normalized.value
175 values = Some(infer::ValuePairs::Types(ExpectedFound {
176 expected: normalized.value,
184 let mut diag = struct_span_err!(
185 self.tcx.sess, obligation.cause.span, E0271,
186 "type mismatch resolving `{}`", predicate
188 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
189 self.note_obligation_cause(&mut diag, obligation);
194 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
195 /// returns the fuzzy category of a given type, or None
196 /// if the type can be equated to any type.
197 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
199 ty::TyBool => Some(0),
200 ty::TyChar => Some(1),
201 ty::TyStr => Some(2),
202 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
203 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
204 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
205 ty::TyArray(..) | ty::TySlice(..) => Some(6),
206 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
207 ty::TyDynamic(..) => Some(8),
208 ty::TyClosure(..) => Some(9),
209 ty::TyTuple(..) => Some(10),
210 ty::TyProjection(..) => Some(11),
211 ty::TyParam(..) => Some(12),
212 ty::TyAnon(..) => Some(13),
213 ty::TyNever => Some(14),
214 ty::TyAdt(adt, ..) => match adt.adt_kind() {
215 AdtKind::Struct => Some(15),
216 AdtKind::Union => Some(16),
217 AdtKind::Enum => Some(17),
219 ty::TyInfer(..) | ty::TyError => None
223 match (type_category(a), type_category(b)) {
224 (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
225 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == 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_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
249 let impl_trait_ref = tcx
250 .impl_trait_ref(def_id)
252 .subst(tcx, impl_substs);
254 let impl_self_ty = impl_trait_ref.self_ty();
256 if let Ok(..) = self.can_equate(&trait_self_ty, &impl_self_ty) {
257 self_match_impls.push(def_id);
259 if trait_ref.substs.types().skip(1)
260 .zip(impl_trait_ref.substs.types().skip(1))
261 .all(|(u,v)| self.fuzzy_match_tys(u, v))
263 fuzzy_match_impls.push(def_id);
268 let impl_def_id = if self_match_impls.len() == 1 {
270 } else if fuzzy_match_impls.len() == 1 {
276 if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
283 fn on_unimplemented_note(&self,
284 trait_ref: ty::PolyTraitRef<'tcx>,
285 obligation: &PredicateObligation<'tcx>) -> Option<String> {
286 let def_id = self.impl_similar_to(trait_ref, obligation)
287 .unwrap_or(trait_ref.def_id());
288 let trait_ref = trait_ref.skip_binder();
290 let span = obligation.cause.span;
291 let mut report = None;
292 if let Some(item) = self.tcx
295 .filter(|a| a.check_name("rustc_on_unimplemented"))
298 let err_sp = item.span.substitute_dummy(span);
299 let trait_str = self.tcx.item_path_str(trait_ref.def_id);
300 if let Some(istring) = item.value_str() {
301 let istring = &*istring.as_str();
302 let generics = self.tcx.item_generics(trait_ref.def_id);
303 let generic_map = generics.types.iter().map(|param| {
304 (param.name.as_str().to_string(),
305 trait_ref.substs.type_for_def(param).to_string())
306 }).collect::<FxHashMap<String, String>>();
307 let parser = Parser::new(istring);
308 let mut errored = false;
309 let err: String = parser.filter_map(|p| {
311 Piece::String(s) => Some(s),
312 Piece::NextArgument(a) => match a.position {
313 Position::ArgumentNamed(s) => match generic_map.get(s) {
314 Some(val) => Some(val),
316 span_err!(self.tcx.sess, err_sp, E0272,
317 "the #[rustc_on_unimplemented] \
319 trait definition for {} refers to \
320 non-existent type parameter {}",
327 span_err!(self.tcx.sess, err_sp, E0273,
328 "the #[rustc_on_unimplemented] attribute \
329 on trait definition for {} must have \
330 named format arguments, eg \
331 `#[rustc_on_unimplemented = \
332 \"foo {{T}}\"]`", trait_str);
339 // Report only if the format string checks out
344 span_err!(self.tcx.sess, err_sp, E0274,
345 "the #[rustc_on_unimplemented] attribute on \
346 trait definition for {} must have a value, \
347 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 impl_candidates: Vec<ty::TraitRef<'tcx>>,
387 err: &mut DiagnosticBuilder)
389 if impl_candidates.is_empty() {
393 let end = if impl_candidates.len() <= 5 {
394 impl_candidates.len()
398 err.help(&format!("the following implementations were found:{}{}",
399 &impl_candidates[0..end].iter().map(|candidate| {
400 format!("\n {:?}", candidate)
401 }).collect::<String>(),
402 if impl_candidates.len() > 5 {
403 format!("\nand {} others", impl_candidates.len() - 4)
410 /// Reports that an overflow has occurred and halts compilation. We
411 /// halt compilation unconditionally because it is important that
412 /// overflows never be masked -- they basically represent computations
413 /// whose result could not be truly determined and thus we can't say
414 /// if the program type checks or not -- and they are unusual
415 /// occurrences in any case.
416 pub fn report_overflow_error<T>(&self,
417 obligation: &Obligation<'tcx, T>,
418 suggest_increasing_limit: bool) -> !
419 where T: fmt::Display + TypeFoldable<'tcx>
422 self.resolve_type_vars_if_possible(&obligation.predicate);
423 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
424 "overflow evaluating the requirement `{}`",
427 if suggest_increasing_limit {
428 self.suggest_new_overflow_limit(&mut err);
431 self.note_obligation_cause(&mut err, obligation);
434 self.tcx.sess.abort_if_errors();
438 /// Reports that a cycle was detected which led to overflow and halts
439 /// compilation. This is equivalent to `report_overflow_error` except
440 /// that we can give a more helpful error message (and, in particular,
441 /// we do not suggest increasing the overflow limit, which is not
443 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
444 let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
445 assert!(cycle.len() > 0);
447 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
449 self.report_overflow_error(&cycle[0], false);
452 pub fn report_extra_impl_obligation(&self,
454 item_name: ast::Name,
455 _impl_item_def_id: DefId,
456 trait_item_def_id: DefId,
457 requirement: &fmt::Display,
458 lint_id: Option<ast::NodeId>) // (*)
459 -> DiagnosticBuilder<'tcx>
461 // (*) This parameter is temporary and used only for phasing
462 // in the bug fix to #18937. If it is `Some`, it has a kind of
463 // weird effect -- the diagnostic is reported as a lint, and
464 // the builder which is returned is marked as canceled.
467 struct_span_err!(self.tcx.sess,
470 "impl has stricter requirements than trait");
472 if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
473 err.span_label(trait_item_span,
474 &format!("definition of `{}` from trait", item_name));
479 &format!("impl has extra requirement {}", requirement));
481 if let Some(node_id) = lint_id {
482 self.tcx.sess.add_lint_diagnostic(EXTRA_REQUIREMENT_IN_IMPL,
492 /// Get the parent trait chain start
493 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
495 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
496 let parent_trait_ref = self.resolve_type_vars_if_possible(
497 &data.parent_trait_ref);
498 match self.get_parent_trait_ref(&data.parent_code) {
500 None => Some(format!("{}", parent_trait_ref.0.self_ty())),
507 pub fn report_selection_error(&self,
508 obligation: &PredicateObligation<'tcx>,
509 error: &SelectionError<'tcx>)
511 let span = obligation.cause.span;
513 let mut err = match *error {
514 SelectionError::Unimplemented => {
515 if let ObligationCauseCode::CompareImplMethodObligation {
516 item_name, impl_item_def_id, trait_item_def_id, lint_id
517 } = obligation.cause.code {
518 self.report_extra_impl_obligation(
523 &format!("`{}`", obligation.predicate),
528 match obligation.predicate {
529 ty::Predicate::Trait(ref trait_predicate) => {
530 let trait_predicate =
531 self.resolve_type_vars_if_possible(trait_predicate);
533 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
536 let trait_ref = trait_predicate.to_poly_trait_ref();
537 let (post_message, pre_message) =
538 self.get_parent_trait_ref(&obligation.cause.code)
539 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
540 .unwrap_or((String::new(), String::new()));
541 let mut err = struct_span_err!(
545 "the trait bound `{}` is not satisfied{}",
546 trait_ref.to_predicate(),
549 // Try to report a help message
550 if !trait_ref.has_infer_types() &&
551 self.predicate_can_apply(trait_ref) {
552 // If a where-clause may be useful, remind the
553 // user that they can add it.
555 // don't display an on-unimplemented note, as
556 // these notes will often be of the form
557 // "the type `T` can't be frobnicated"
558 // which is somewhat confusing.
559 err.help(&format!("consider adding a `where {}` bound",
560 trait_ref.to_predicate()));
561 } else if let Some(s) = self.on_unimplemented_note(trait_ref, obligation) {
562 // If it has a custom "#[rustc_on_unimplemented]"
563 // error message, let's display it!
566 // Can't show anything else useful, try to find similar impls.
567 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
568 self.report_similar_impl_candidates(impl_candidates, &mut err);
572 &format!("{}the trait `{}` is not implemented for `{}`",
575 trait_ref.self_ty()));
579 ty::Predicate::Subtype(ref predicate) => {
580 // Errors for Subtype predicates show up as
581 // `FulfillmentErrorCode::CodeSubtypeError`,
582 // not selection error.
583 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
586 ty::Predicate::Equate(ref predicate) => {
587 let predicate = self.resolve_type_vars_if_possible(predicate);
588 let err = self.equality_predicate(&obligation.cause,
589 &predicate).err().unwrap();
590 struct_span_err!(self.tcx.sess, span, E0278,
591 "the requirement `{}` is not satisfied (`{}`)",
595 ty::Predicate::RegionOutlives(ref predicate) => {
596 let predicate = self.resolve_type_vars_if_possible(predicate);
597 let err = self.region_outlives_predicate(&obligation.cause,
598 &predicate).err().unwrap();
599 struct_span_err!(self.tcx.sess, span, E0279,
600 "the requirement `{}` is not satisfied (`{}`)",
604 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
606 self.resolve_type_vars_if_possible(&obligation.predicate);
607 struct_span_err!(self.tcx.sess, span, E0280,
608 "the requirement `{}` is not satisfied",
612 ty::Predicate::ObjectSafe(trait_def_id) => {
613 let violations = self.tcx.object_safety_violations(trait_def_id);
614 self.tcx.report_object_safety_error(span,
619 ty::Predicate::ClosureKind(closure_def_id, kind) => {
620 let found_kind = self.closure_kind(closure_def_id).unwrap();
621 let closure_span = self.tcx.hir.span_if_local(closure_def_id).unwrap();
622 let mut err = struct_span_err!(
623 self.tcx.sess, closure_span, E0525,
624 "expected a closure that implements the `{}` trait, \
625 but this closure only implements `{}`",
629 obligation.cause.span,
630 &format!("the requirement to implement \
631 `{}` derives from here", kind));
636 ty::Predicate::WellFormed(ty) => {
637 // WF predicates cannot themselves make
638 // errors. They can only block due to
639 // ambiguity; otherwise, they always
640 // degenerate into other obligations
642 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
647 OutputTypeParameterMismatch(ref expected_trait_ref, ref actual_trait_ref, ref e) => {
648 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
649 let actual_trait_ref = self.resolve_type_vars_if_possible(&*actual_trait_ref);
650 if actual_trait_ref.self_ty().references_error() {
653 struct_span_err!(self.tcx.sess, span, E0281,
654 "type mismatch: the type `{}` implements the trait `{}`, \
655 but the trait `{}` is required ({})",
656 expected_trait_ref.self_ty(),
662 TraitNotObjectSafe(did) => {
663 let violations = self.tcx.object_safety_violations(did);
664 self.tcx.report_object_safety_error(span, did,
668 self.note_obligation_cause(&mut err, obligation);
673 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
674 pub fn recursive_type_with_infinite_size_error(self,
676 -> DiagnosticBuilder<'tcx>
678 assert!(type_def_id.is_local());
679 let span = self.hir.span_if_local(type_def_id).unwrap();
680 let mut err = struct_span_err!(self.sess, span, E0072,
681 "recursive type `{}` has infinite size",
682 self.item_path_str(type_def_id));
683 err.span_label(span, &format!("recursive type has infinite size"));
684 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
685 at some point to make `{}` representable",
686 self.item_path_str(type_def_id)));
690 pub fn report_object_safety_error(self,
693 violations: Vec<ObjectSafetyViolation>)
694 -> DiagnosticBuilder<'tcx>
696 let trait_str = self.item_path_str(trait_def_id);
697 let mut err = struct_span_err!(
698 self.sess, span, E0038,
699 "the trait `{}` cannot be made into an object",
701 err.span_label(span, &format!(
702 "the trait `{}` cannot be made into an object", trait_str
705 let mut reported_violations = FxHashSet();
706 for violation in violations {
707 if !reported_violations.insert(violation.clone()) {
710 err.note(&violation.error_msg());
716 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
717 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>) {
718 // Unable to successfully determine, probably means
719 // insufficient type information, but could mean
720 // ambiguous impls. The latter *ought* to be a
721 // coherence violation, so we don't report it here.
723 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
725 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
729 // Ambiguity errors are often caused as fallout from earlier
730 // errors. So just ignore them if this infcx is tainted.
731 if self.is_tainted_by_errors() {
736 ty::Predicate::Trait(ref data) => {
737 let trait_ref = data.to_poly_trait_ref();
738 let self_ty = trait_ref.self_ty();
739 if predicate.references_error() {
742 // Typically, this ambiguity should only happen if
743 // there are unresolved type inference variables
744 // (otherwise it would suggest a coherence
745 // failure). But given #21974 that is not necessarily
746 // the case -- we can have multiple where clauses that
747 // are only distinguished by a region, which results
748 // in an ambiguity even when all types are fully
749 // known, since we don't dispatch based on region
752 // This is kind of a hack: it frequently happens that some earlier
753 // error prevents types from being fully inferred, and then we get
754 // a bunch of uninteresting errors saying something like "<generic
755 // #0> doesn't implement Sized". It may even be true that we
756 // could just skip over all checks where the self-ty is an
757 // inference variable, but I was afraid that there might be an
758 // inference variable created, registered as an obligation, and
759 // then never forced by writeback, and hence by skipping here we'd
760 // be ignoring the fact that we don't KNOW the type works
761 // out. Though even that would probably be harmless, given that
762 // we're only talking about builtin traits, which are known to be
763 // inhabited. But in any case I just threw in this check for
764 // has_errors() to be sure that compilation isn't happening
765 // anyway. In that case, why inundate the user.
766 if !self.tcx.sess.has_errors() {
768 self.tcx.lang_items.sized_trait()
769 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
771 self.need_type_info(obligation, self_ty);
773 let mut err = struct_span_err!(self.tcx.sess,
774 obligation.cause.span, E0283,
775 "type annotations required: \
776 cannot resolve `{}`",
778 self.note_obligation_cause(&mut err, obligation);
784 ty::Predicate::WellFormed(ty) => {
785 // Same hacky approach as above to avoid deluging user
786 // with error messages.
787 if !ty.references_error() && !self.tcx.sess.has_errors() {
788 self.need_type_info(obligation, ty);
792 ty::Predicate::Subtype(ref data) => {
793 if data.references_error() || self.tcx.sess.has_errors() {
794 // no need to overload user in such cases
796 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
797 // both must be type variables, or the other would've been instantiated
798 assert!(a.is_ty_var() && b.is_ty_var());
799 self.need_type_info(obligation, a);
804 if !self.tcx.sess.has_errors() {
805 let mut err = struct_span_err!(self.tcx.sess,
806 obligation.cause.span, E0284,
807 "type annotations required: \
808 cannot resolve `{}`",
810 self.note_obligation_cause(&mut err, obligation);
817 /// Returns whether the trait predicate may apply for *some* assignment
818 /// to the type parameters.
819 fn predicate_can_apply(&self, pred: ty::PolyTraitRef<'tcx>) -> bool {
820 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
821 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
822 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
825 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
826 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
828 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
829 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
830 let infcx = self.infcx;
831 self.var_map.entry(ty).or_insert_with(||
833 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
835 ty.super_fold_with(self)
841 let mut selcx = SelectionContext::new(self);
843 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
848 let cleaned_pred = super::project::normalize(
850 ObligationCause::dummy(),
854 let obligation = Obligation::new(
855 ObligationCause::dummy(),
856 cleaned_pred.to_predicate()
859 selcx.evaluate_obligation(&obligation)
863 fn extract_type_name(&self, ty: &'a Ty<'tcx>) -> String {
864 if let ty::TyInfer(ty::TyVar(ty_vid)) = (*ty).sty {
865 let ty_vars = self.type_variables.borrow();
866 if let TypeVariableOrigin::TypeParameterDefinition(_, name) =
867 *ty_vars.var_origin(ty_vid) {
877 fn need_type_info(&self, obligation: &PredicateObligation<'tcx>, ty: Ty<'tcx>) {
878 let ty = self.resolve_type_vars_if_possible(&ty);
879 let name = self.extract_type_name(&ty);
880 let ref cause = obligation.cause;
882 let mut err = struct_span_err!(self.tcx.sess,
885 "type annotations needed");
887 err.span_label(cause.span, &format!("cannot infer type for `{}`", name));
889 let mut local_visitor = FindLocalByTypeVisitor {
895 // #40294: cause.body_id can also be a fn declaration.
896 // Currently, if it's anything other than NodeExpr, we just ignore it
897 match self.tcx.hir.find(cause.body_id) {
898 Some(NodeExpr(expr)) => local_visitor.visit_expr(expr),
902 if let Some(pattern) = local_visitor.found_pattern {
903 let pattern_span = pattern.span;
904 if let Some(simple_name) = pattern.simple_name() {
905 err.span_label(pattern_span,
906 &format!("consider giving `{}` a type",
909 err.span_label(pattern_span, &format!("consider giving a type to pattern"));
916 fn note_obligation_cause<T>(&self,
917 err: &mut DiagnosticBuilder,
918 obligation: &Obligation<'tcx, T>)
919 where T: fmt::Display
921 self.note_obligation_cause_code(err,
922 &obligation.predicate,
923 &obligation.cause.code);
926 fn note_obligation_cause_code<T>(&self,
927 err: &mut DiagnosticBuilder,
929 cause_code: &ObligationCauseCode<'tcx>)
930 where T: fmt::Display
934 ObligationCauseCode::ExprAssignable |
935 ObligationCauseCode::MatchExpressionArm { .. } |
936 ObligationCauseCode::IfExpression |
937 ObligationCauseCode::IfExpressionWithNoElse |
938 ObligationCauseCode::EquatePredicate |
939 ObligationCauseCode::MainFunctionType |
940 ObligationCauseCode::StartFunctionType |
941 ObligationCauseCode::IntrinsicType |
942 ObligationCauseCode::MethodReceiver |
943 ObligationCauseCode::ReturnNoExpression |
944 ObligationCauseCode::MiscObligation => {
946 ObligationCauseCode::SliceOrArrayElem => {
947 err.note("slice and array elements must have `Sized` type");
949 ObligationCauseCode::TupleElem => {
950 err.note("tuple elements must have `Sized` type");
952 ObligationCauseCode::ProjectionWf(data) => {
953 err.note(&format!("required so that the projection `{}` is well-formed",
956 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
957 err.note(&format!("required so that reference `{}` does not outlive its referent",
960 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
961 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
965 ObligationCauseCode::ItemObligation(item_def_id) => {
966 let item_name = tcx.item_path_str(item_def_id);
967 err.note(&format!("required by `{}`", item_name));
969 ObligationCauseCode::ObjectCastObligation(object_ty) => {
970 err.note(&format!("required for the cast to the object type `{}`",
971 self.ty_to_string(object_ty)));
973 ObligationCauseCode::RepeatVec => {
974 err.note("the `Copy` trait is required because the \
975 repeated element will be copied");
977 ObligationCauseCode::VariableType(_) => {
978 err.note("all local variables must have a statically known size");
980 ObligationCauseCode::ReturnType => {
981 err.note("the return type of a function must have a \
982 statically known size");
984 ObligationCauseCode::AssignmentLhsSized => {
985 err.note("the left-hand-side of an assignment must have a statically known size");
987 ObligationCauseCode::StructInitializerSized => {
988 err.note("structs must have a statically known size to be initialized");
990 ObligationCauseCode::FieldSized => {
991 err.note("only the last field of a struct may have a dynamically sized type");
993 ObligationCauseCode::ConstSized => {
994 err.note("constant expressions must have a statically known size");
996 ObligationCauseCode::SharedStatic => {
997 err.note("shared static variables must have a type that implements `Sync`");
999 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1000 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1001 err.note(&format!("required because it appears within the type `{}`",
1002 parent_trait_ref.0.self_ty()));
1003 let parent_predicate = parent_trait_ref.to_predicate();
1004 self.note_obligation_cause_code(err,
1008 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1009 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1011 &format!("required because of the requirements on the impl of `{}` for `{}`",
1013 parent_trait_ref.0.self_ty()));
1014 let parent_predicate = parent_trait_ref.to_predicate();
1015 self.note_obligation_cause_code(err,
1019 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1021 &format!("the requirement `{}` appears on the impl method \
1022 but not on the corresponding trait method",
1028 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1029 let current_limit = self.tcx.sess.recursion_limit.get();
1030 let suggested_limit = current_limit * 2;
1032 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",