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,
24 ObjectSafetyViolation,
27 use errors::DiagnosticBuilder;
28 use fmt_macros::{Parser, Piece, Position};
30 use hir::def_id::DefId;
31 use infer::{self, InferCtxt};
32 use infer::type_variable::TypeVariableOrigin;
33 use rustc::lint::builtin::EXTRA_REQUIREMENT_IN_IMPL;
36 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
37 use ty::error::{ExpectedFound, TypeError};
39 use ty::fold::TypeFolder;
41 use ty::SubtypePredicate;
42 use util::nodemap::{FxHashMap, FxHashSet};
44 use syntax_pos::{DUMMY_SP, Span};
46 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
47 pub fn report_fulfillment_errors(&self,
48 errors: &Vec<FulfillmentError<'tcx>>,
49 body_id: Option<hir::BodyId>) {
51 struct ErrorDescriptor<'tcx> {
52 predicate: ty::Predicate<'tcx>,
53 index: Option<usize>, // None if this is an old error
56 let mut error_map : FxHashMap<_, _> =
57 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
58 (span, predicates.iter().map(|predicate| ErrorDescriptor {
59 predicate: predicate.clone(),
64 for (index, error) in errors.iter().enumerate() {
65 error_map.entry(error.obligation.cause.span).or_insert(Vec::new()).push(
67 predicate: error.obligation.predicate.clone(),
71 self.reported_trait_errors.borrow_mut()
72 .entry(error.obligation.cause.span).or_insert(Vec::new())
73 .push(error.obligation.predicate.clone());
76 // We do this in 2 passes because we want to display errors in order, tho
77 // maybe it *is* better to sort errors by span or something.
78 let mut is_suppressed: Vec<bool> = errors.iter().map(|_| false).collect();
79 for (_, error_set) in error_map.iter() {
80 // We want to suppress "duplicate" errors with the same span.
81 for error in error_set {
82 if let Some(index) = error.index {
83 // Suppress errors that are either:
84 // 1) strictly implied by another error.
85 // 2) implied by an error with a smaller index.
86 for error2 in error_set {
87 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
88 // Avoid errors being suppressed by already-suppressed
89 // errors, to prevent all errors from being suppressed
94 if self.error_implies(&error2.predicate, &error.predicate) &&
95 !(error2.index >= error.index &&
96 self.error_implies(&error.predicate, &error2.predicate))
98 info!("skipping {:?} (implied by {:?})", error, error2);
99 is_suppressed[index] = true;
107 for (error, suppressed) in errors.iter().zip(is_suppressed) {
109 self.report_fulfillment_error(error, body_id);
114 // returns if `cond` not occurring implies that `error` does not occur - i.e. that
115 // `error` occurring implies that `cond` occurs.
116 fn error_implies(&self,
117 cond: &ty::Predicate<'tcx>,
118 error: &ty::Predicate<'tcx>)
125 let (cond, error) = match (cond, error) {
126 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
129 // FIXME: make this work in other cases too.
134 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
135 if let ty::Predicate::Trait(implication) = implication {
136 let error = error.to_poly_trait_ref();
137 let implication = implication.to_poly_trait_ref();
138 // FIXME: I'm just not taking associated types at all here.
139 // Eventually I'll need to implement param-env-aware
140 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
141 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
142 if let Ok(_) = self.can_sub(param_env, error, implication) {
143 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
152 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
153 body_id: Option<hir::BodyId>) {
154 debug!("report_fulfillment_errors({:?})", error);
156 FulfillmentErrorCode::CodeSelectionError(ref e) => {
157 self.report_selection_error(&error.obligation, e);
159 FulfillmentErrorCode::CodeProjectionError(ref e) => {
160 self.report_projection_error(&error.obligation, e);
162 FulfillmentErrorCode::CodeAmbiguity => {
163 self.maybe_report_ambiguity(&error.obligation, body_id);
165 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
166 self.report_mismatched_types(&error.obligation.cause,
167 expected_found.expected,
168 expected_found.found,
175 fn report_projection_error(&self,
176 obligation: &PredicateObligation<'tcx>,
177 error: &MismatchedProjectionTypes<'tcx>)
180 self.resolve_type_vars_if_possible(&obligation.predicate);
182 if predicate.references_error() {
188 let mut err = &error.err;
189 let mut values = None;
191 // try to find the mismatched types to report the error with.
193 // this can fail if the problem was higher-ranked, in which
194 // cause I have no idea for a good error message.
195 if let ty::Predicate::Projection(ref data) = predicate {
196 let mut selcx = SelectionContext::new(self);
197 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
198 obligation.cause.span,
199 infer::LateBoundRegionConversionTime::HigherRankedType,
201 let normalized = super::normalize_projection_type(
203 obligation.param_env,
205 obligation.cause.clone(),
208 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
209 .eq(normalized.value, data.ty) {
210 values = Some(infer::ValuePairs::Types(ExpectedFound {
211 expected: normalized.value,
219 let mut diag = struct_span_err!(
220 self.tcx.sess, obligation.cause.span, E0271,
221 "type mismatch resolving `{}`", predicate
223 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
224 self.note_obligation_cause(&mut diag, obligation);
229 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
230 /// returns the fuzzy category of a given type, or None
231 /// if the type can be equated to any type.
232 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
234 ty::TyBool => Some(0),
235 ty::TyChar => Some(1),
236 ty::TyStr => Some(2),
237 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
238 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
239 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
240 ty::TyArray(..) | ty::TySlice(..) => Some(6),
241 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
242 ty::TyDynamic(..) => Some(8),
243 ty::TyClosure(..) => Some(9),
244 ty::TyTuple(..) => Some(10),
245 ty::TyProjection(..) => Some(11),
246 ty::TyParam(..) => Some(12),
247 ty::TyAnon(..) => Some(13),
248 ty::TyNever => Some(14),
249 ty::TyAdt(adt, ..) => match adt.adt_kind() {
250 AdtKind::Struct => Some(15),
251 AdtKind::Union => Some(16),
252 AdtKind::Enum => Some(17),
254 ty::TyInfer(..) | ty::TyError => None
258 match (type_category(a), type_category(b)) {
259 (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
260 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == def_b,
263 // infer and error can be equated to all types
268 fn impl_similar_to(&self,
269 trait_ref: ty::PolyTraitRef<'tcx>,
270 obligation: &PredicateObligation<'tcx>)
274 let param_env = obligation.param_env;
275 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
276 let trait_self_ty = trait_ref.self_ty();
278 let mut self_match_impls = vec![];
279 let mut fuzzy_match_impls = vec![];
281 self.tcx.for_each_relevant_impl(
282 trait_ref.def_id, trait_self_ty, |def_id| {
283 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
284 let impl_trait_ref = tcx
285 .impl_trait_ref(def_id)
287 .subst(tcx, impl_substs);
289 let impl_self_ty = impl_trait_ref.self_ty();
291 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
292 self_match_impls.push(def_id);
294 if trait_ref.substs.types().skip(1)
295 .zip(impl_trait_ref.substs.types().skip(1))
296 .all(|(u,v)| self.fuzzy_match_tys(u, v))
298 fuzzy_match_impls.push(def_id);
303 let impl_def_id = if self_match_impls.len() == 1 {
305 } else if fuzzy_match_impls.len() == 1 {
311 if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
318 fn on_unimplemented_note(&self,
319 trait_ref: ty::PolyTraitRef<'tcx>,
320 obligation: &PredicateObligation<'tcx>) -> Option<String> {
321 let def_id = self.impl_similar_to(trait_ref, obligation)
322 .unwrap_or(trait_ref.def_id());
323 let trait_ref = trait_ref.skip_binder();
325 let span = obligation.cause.span;
326 let mut report = None;
327 if let Some(item) = self.tcx
330 .filter(|a| a.check_name("rustc_on_unimplemented"))
333 let name = self.tcx.item_name(def_id).as_str();
334 let err_sp = item.span.substitute_dummy(span);
335 let trait_str = self.tcx.item_path_str(trait_ref.def_id);
336 if let Some(istring) = item.value_str() {
337 let istring = &*istring.as_str();
338 let generics = self.tcx.generics_of(trait_ref.def_id);
339 let generic_map = generics.types.iter().map(|param| {
340 (param.name.as_str().to_string(),
341 trait_ref.substs.type_for_def(param).to_string())
342 }).collect::<FxHashMap<String, String>>();
343 let parser = Parser::new(istring);
344 let mut errored = false;
345 let err: String = parser.filter_map(|p| {
347 Piece::String(s) => Some(s),
348 Piece::NextArgument(a) => match a.position {
349 Position::ArgumentNamed(s) => match generic_map.get(s) {
350 Some(val) => Some(val),
351 None if s == name => {
355 span_err!(self.tcx.sess, err_sp, E0272,
356 "the #[rustc_on_unimplemented] attribute on trait \
357 definition for {} refers to non-existent type \
365 span_err!(self.tcx.sess, err_sp, E0273,
366 "the #[rustc_on_unimplemented] attribute on trait \
367 definition for {} must have named format arguments, eg \
368 `#[rustc_on_unimplemented = \"foo {{T}}\"]`",
376 // Report only if the format string checks out
381 span_err!(self.tcx.sess, err_sp, E0274,
382 "the #[rustc_on_unimplemented] attribute on \
383 trait definition for {} must have a value, \
384 eg `#[rustc_on_unimplemented = \"foo\"]`",
391 fn find_similar_impl_candidates(&self,
392 trait_ref: ty::PolyTraitRef<'tcx>)
393 -> Vec<ty::TraitRef<'tcx>>
395 let simp = fast_reject::simplify_type(self.tcx,
396 trait_ref.skip_binder().self_ty(),
398 let mut impl_candidates = Vec::new();
401 Some(simp) => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
402 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
403 let imp_simp = fast_reject::simplify_type(self.tcx,
406 if let Some(imp_simp) = imp_simp {
407 if simp != imp_simp {
411 impl_candidates.push(imp);
413 None => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
414 impl_candidates.push(
415 self.tcx.impl_trait_ref(def_id).unwrap());
421 fn report_similar_impl_candidates(&self,
422 impl_candidates: Vec<ty::TraitRef<'tcx>>,
423 err: &mut DiagnosticBuilder)
425 if impl_candidates.is_empty() {
429 let end = if impl_candidates.len() <= 5 {
430 impl_candidates.len()
434 err.help(&format!("the following implementations were found:{}{}",
435 &impl_candidates[0..end].iter().map(|candidate| {
436 format!("\n {:?}", candidate)
437 }).collect::<String>(),
438 if impl_candidates.len() > 5 {
439 format!("\nand {} others", impl_candidates.len() - 4)
446 /// Reports that an overflow has occurred and halts compilation. We
447 /// halt compilation unconditionally because it is important that
448 /// overflows never be masked -- they basically represent computations
449 /// whose result could not be truly determined and thus we can't say
450 /// if the program type checks or not -- and they are unusual
451 /// occurrences in any case.
452 pub fn report_overflow_error<T>(&self,
453 obligation: &Obligation<'tcx, T>,
454 suggest_increasing_limit: bool) -> !
455 where T: fmt::Display + TypeFoldable<'tcx>
458 self.resolve_type_vars_if_possible(&obligation.predicate);
459 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
460 "overflow evaluating the requirement `{}`",
463 if suggest_increasing_limit {
464 self.suggest_new_overflow_limit(&mut err);
467 self.note_obligation_cause(&mut err, obligation);
470 self.tcx.sess.abort_if_errors();
474 /// Reports that a cycle was detected which led to overflow and halts
475 /// compilation. This is equivalent to `report_overflow_error` except
476 /// that we can give a more helpful error message (and, in particular,
477 /// we do not suggest increasing the overflow limit, which is not
479 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
480 let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
481 assert!(cycle.len() > 0);
483 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
485 self.report_overflow_error(&cycle[0], false);
488 pub fn report_extra_impl_obligation(&self,
490 item_name: ast::Name,
491 _impl_item_def_id: DefId,
492 trait_item_def_id: DefId,
493 requirement: &fmt::Display,
494 lint_id: Option<ast::NodeId>) // (*)
495 -> DiagnosticBuilder<'tcx>
497 // (*) This parameter is temporary and used only for phasing
498 // in the bug fix to #18937. If it is `Some`, it has a kind of
499 // weird effect -- the diagnostic is reported as a lint, and
500 // the builder which is returned is marked as canceled.
502 let msg = "impl has stricter requirements than trait";
503 let mut err = match lint_id {
505 self.tcx.struct_span_lint_node(EXTRA_REQUIREMENT_IN_IMPL,
511 struct_span_err!(self.tcx.sess,
518 if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
519 let span = self.tcx.sess.codemap().def_span(trait_item_span);
520 err.span_label(span, format!("definition of `{}` from trait", item_name));
525 format!("impl has extra requirement {}", requirement));
531 /// Get the parent trait chain start
532 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
534 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
535 let parent_trait_ref = self.resolve_type_vars_if_possible(
536 &data.parent_trait_ref);
537 match self.get_parent_trait_ref(&data.parent_code) {
539 None => Some(format!("{}", parent_trait_ref.0.self_ty())),
546 pub fn report_selection_error(&self,
547 obligation: &PredicateObligation<'tcx>,
548 error: &SelectionError<'tcx>)
550 let span = obligation.cause.span;
552 let mut err = match *error {
553 SelectionError::Unimplemented => {
554 if let ObligationCauseCode::CompareImplMethodObligation {
555 item_name, impl_item_def_id, trait_item_def_id, lint_id
556 } = obligation.cause.code {
557 self.report_extra_impl_obligation(
562 &format!("`{}`", obligation.predicate),
567 match obligation.predicate {
568 ty::Predicate::Trait(ref trait_predicate) => {
569 let trait_predicate =
570 self.resolve_type_vars_if_possible(trait_predicate);
572 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
575 let trait_ref = trait_predicate.to_poly_trait_ref();
576 let (post_message, pre_message) =
577 self.get_parent_trait_ref(&obligation.cause.code)
578 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
579 .unwrap_or((String::new(), String::new()));
580 let mut err = struct_span_err!(
584 "the trait bound `{}` is not satisfied{}",
585 trait_ref.to_predicate(),
588 let unimplemented_note = self.on_unimplemented_note(trait_ref, obligation);
589 if let Some(ref s) = unimplemented_note {
590 // If it has a custom "#[rustc_on_unimplemented]"
591 // error message, let's display it as the label!
592 err.span_label(span, s.as_str());
593 err.help(&format!("{}the trait `{}` is not implemented for `{}`",
596 trait_ref.self_ty()));
599 &*format!("{}the trait `{}` is not implemented for `{}`",
602 trait_ref.self_ty()));
605 // Try to report a help message
606 if !trait_ref.has_infer_types() &&
607 self.predicate_can_apply(obligation.param_env, trait_ref) {
608 // If a where-clause may be useful, remind the
609 // user that they can add it.
611 // don't display an on-unimplemented note, as
612 // these notes will often be of the form
613 // "the type `T` can't be frobnicated"
614 // which is somewhat confusing.
615 err.help(&format!("consider adding a `where {}` bound",
616 trait_ref.to_predicate()));
617 } else if unimplemented_note.is_none() {
618 // Can't show anything else useful, try to find similar impls.
619 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
620 self.report_similar_impl_candidates(impl_candidates, &mut err);
626 ty::Predicate::Subtype(ref predicate) => {
627 // Errors for Subtype predicates show up as
628 // `FulfillmentErrorCode::CodeSubtypeError`,
629 // not selection error.
630 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
633 ty::Predicate::Equate(ref predicate) => {
634 let predicate = self.resolve_type_vars_if_possible(predicate);
635 let err = self.equality_predicate(&obligation.cause,
636 obligation.param_env,
637 &predicate).err().unwrap();
638 struct_span_err!(self.tcx.sess, span, E0278,
639 "the requirement `{}` is not satisfied (`{}`)",
643 ty::Predicate::RegionOutlives(ref predicate) => {
644 let predicate = self.resolve_type_vars_if_possible(predicate);
645 let err = self.region_outlives_predicate(&obligation.cause,
646 &predicate).err().unwrap();
647 struct_span_err!(self.tcx.sess, span, E0279,
648 "the requirement `{}` is not satisfied (`{}`)",
652 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
654 self.resolve_type_vars_if_possible(&obligation.predicate);
655 struct_span_err!(self.tcx.sess, span, E0280,
656 "the requirement `{}` is not satisfied",
660 ty::Predicate::ObjectSafe(trait_def_id) => {
661 let violations = self.tcx.object_safety_violations(trait_def_id);
662 self.tcx.report_object_safety_error(span,
667 ty::Predicate::ClosureKind(closure_def_id, kind) => {
668 let found_kind = self.closure_kind(closure_def_id).unwrap();
669 let closure_span = self.tcx.hir.span_if_local(closure_def_id).unwrap();
670 let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
671 let mut err = struct_span_err!(
672 self.tcx.sess, closure_span, E0525,
673 "expected a closure that implements the `{}` trait, \
674 but this closure only implements `{}`",
679 obligation.cause.span,
680 format!("the requirement to implement `{}` derives from here", kind));
682 // Additional context information explaining why the closure only implements
683 // a particular trait.
684 if let Some(tables) = self.in_progress_tables {
685 let tables = tables.borrow();
686 let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
687 match tables.closure_kinds().get(closure_hir_id) {
688 Some(&(ty::ClosureKind::FnOnce, Some((span, name)))) => {
689 err.span_note(span, &format!(
690 "closure is `FnOnce` because it moves the \
691 variable `{}` out of its environment", name));
693 Some(&(ty::ClosureKind::FnMut, Some((span, name)))) => {
694 err.span_note(span, &format!(
695 "closure is `FnMut` because it mutates the \
696 variable `{}` here", name));
706 ty::Predicate::WellFormed(ty) => {
707 // WF predicates cannot themselves make
708 // errors. They can only block due to
709 // ambiguity; otherwise, they always
710 // degenerate into other obligations
712 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
717 OutputTypeParameterMismatch(ref expected_trait_ref, ref actual_trait_ref, ref e) => {
718 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
719 let actual_trait_ref = self.resolve_type_vars_if_possible(&*actual_trait_ref);
720 if actual_trait_ref.self_ty().references_error() {
723 let expected_trait_ty = expected_trait_ref.self_ty();
724 let found_span = expected_trait_ty.ty_to_def_id().and_then(|did| {
725 self.tcx.hir.span_if_local(did)
728 if let &TypeError::TupleSize(ref expected_found) = e {
729 // Expected `|x| { }`, found `|x, y| { }`
730 self.report_arg_count_mismatch(span,
732 expected_found.expected,
733 expected_found.found,
734 expected_trait_ty.is_closure())
735 } else if let &TypeError::Sorts(ref expected_found) = e {
736 let expected = if let ty::TyTuple(tys, _) = expected_found.expected.sty {
741 let found = if let ty::TyTuple(tys, _) = expected_found.found.sty {
747 if expected != found {
748 // Expected `|| { }`, found `|x, y| { }`
749 // Expected `fn(x) -> ()`, found `|| { }`
750 self.report_arg_count_mismatch(span,
754 expected_trait_ty.is_closure())
756 self.report_type_argument_mismatch(span,
764 self.report_type_argument_mismatch(span,
773 TraitNotObjectSafe(did) => {
774 let violations = self.tcx.object_safety_violations(did);
775 self.tcx.report_object_safety_error(span, did,
779 self.note_obligation_cause(&mut err, obligation);
783 fn report_type_argument_mismatch(&self,
785 found_span: Option<Span>,
786 expected_ty: Ty<'tcx>,
787 expected_ref: ty::PolyTraitRef<'tcx>,
788 found_ref: ty::PolyTraitRef<'tcx>,
789 type_error: &TypeError<'tcx>)
790 -> DiagnosticBuilder<'tcx>
792 let mut err = struct_span_err!(self.tcx.sess, span, E0281,
793 "type mismatch: `{}` implements the trait `{}`, but the trait `{}` is required",
798 err.span_label(span, format!("{}", type_error));
800 if let Some(sp) = found_span {
801 err.span_label(span, format!("requires `{}`", found_ref));
802 err.span_label(sp, format!("implements `{}`", expected_ref));
808 fn report_arg_count_mismatch(&self,
810 found_span: Option<Span>,
814 -> DiagnosticBuilder<'tcx>
816 let mut err = struct_span_err!(self.tcx.sess, span, E0593,
817 "{} takes {} argument{} but {} argument{} {} required",
818 if is_closure { "closure" } else { "function" },
820 if found == 1 { "" } else { "s" },
822 if expected == 1 { "" } else { "s" },
823 if expected == 1 { "is" } else { "are" });
825 err.span_label(span, format!("expected {} that takes {} argument{}",
826 if is_closure { "closure" } else { "function" },
828 if expected == 1 { "" } else { "s" }));
829 if let Some(span) = found_span {
830 err.span_label(span, format!("takes {} argument{}",
832 if found == 1 { "" } else { "s" }));
838 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
839 pub fn recursive_type_with_infinite_size_error(self,
841 -> DiagnosticBuilder<'tcx>
843 assert!(type_def_id.is_local());
844 let span = self.hir.span_if_local(type_def_id).unwrap();
845 let span = self.sess.codemap().def_span(span);
846 let mut err = struct_span_err!(self.sess, span, E0072,
847 "recursive type `{}` has infinite size",
848 self.item_path_str(type_def_id));
849 err.span_label(span, "recursive type has infinite size");
850 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
851 at some point to make `{}` representable",
852 self.item_path_str(type_def_id)));
856 pub fn report_object_safety_error(self,
859 violations: Vec<ObjectSafetyViolation>)
860 -> DiagnosticBuilder<'tcx>
862 let trait_str = self.item_path_str(trait_def_id);
863 let span = self.sess.codemap().def_span(span);
864 let mut err = struct_span_err!(
865 self.sess, span, E0038,
866 "the trait `{}` cannot be made into an object",
868 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
870 let mut reported_violations = FxHashSet();
871 for violation in violations {
872 if !reported_violations.insert(violation.clone()) {
875 err.note(&violation.error_msg());
881 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
882 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
883 body_id: Option<hir::BodyId>) {
884 // Unable to successfully determine, probably means
885 // insufficient type information, but could mean
886 // ambiguous impls. The latter *ought* to be a
887 // coherence violation, so we don't report it here.
889 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
890 let span = obligation.cause.span;
892 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
896 // Ambiguity errors are often caused as fallout from earlier
897 // errors. So just ignore them if this infcx is tainted.
898 if self.is_tainted_by_errors() {
903 ty::Predicate::Trait(ref data) => {
904 let trait_ref = data.to_poly_trait_ref();
905 let self_ty = trait_ref.self_ty();
906 if predicate.references_error() {
909 // Typically, this ambiguity should only happen if
910 // there are unresolved type inference variables
911 // (otherwise it would suggest a coherence
912 // failure). But given #21974 that is not necessarily
913 // the case -- we can have multiple where clauses that
914 // are only distinguished by a region, which results
915 // in an ambiguity even when all types are fully
916 // known, since we don't dispatch based on region
919 // This is kind of a hack: it frequently happens that some earlier
920 // error prevents types from being fully inferred, and then we get
921 // a bunch of uninteresting errors saying something like "<generic
922 // #0> doesn't implement Sized". It may even be true that we
923 // could just skip over all checks where the self-ty is an
924 // inference variable, but I was afraid that there might be an
925 // inference variable created, registered as an obligation, and
926 // then never forced by writeback, and hence by skipping here we'd
927 // be ignoring the fact that we don't KNOW the type works
928 // out. Though even that would probably be harmless, given that
929 // we're only talking about builtin traits, which are known to be
930 // inhabited. But in any case I just threw in this check for
931 // has_errors() to be sure that compilation isn't happening
932 // anyway. In that case, why inundate the user.
933 if !self.tcx.sess.has_errors() {
935 self.tcx.lang_items.sized_trait()
936 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
938 self.need_type_info(body_id, span, self_ty);
940 let mut err = struct_span_err!(self.tcx.sess,
942 "type annotations required: \
943 cannot resolve `{}`",
945 self.note_obligation_cause(&mut err, obligation);
951 ty::Predicate::WellFormed(ty) => {
952 // Same hacky approach as above to avoid deluging user
953 // with error messages.
954 if !ty.references_error() && !self.tcx.sess.has_errors() {
955 self.need_type_info(body_id, span, ty);
959 ty::Predicate::Subtype(ref data) => {
960 if data.references_error() || self.tcx.sess.has_errors() {
961 // no need to overload user in such cases
963 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
964 // both must be type variables, or the other would've been instantiated
965 assert!(a.is_ty_var() && b.is_ty_var());
966 self.need_type_info(body_id,
967 obligation.cause.span,
973 if !self.tcx.sess.has_errors() {
974 let mut err = struct_span_err!(self.tcx.sess,
975 obligation.cause.span, E0284,
976 "type annotations required: \
977 cannot resolve `{}`",
979 self.note_obligation_cause(&mut err, obligation);
986 /// Returns whether the trait predicate may apply for *some* assignment
987 /// to the type parameters.
988 fn predicate_can_apply(&self,
989 param_env: ty::ParamEnv<'tcx>,
990 pred: ty::PolyTraitRef<'tcx>)
992 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
993 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
994 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
997 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
998 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1000 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1001 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
1002 let infcx = self.infcx;
1003 self.var_map.entry(ty).or_insert_with(||
1005 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1007 ty.super_fold_with(self)
1013 let mut selcx = SelectionContext::new(self);
1015 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1017 var_map: FxHashMap()
1020 let cleaned_pred = super::project::normalize(
1023 ObligationCause::dummy(),
1027 let obligation = Obligation::new(
1028 ObligationCause::dummy(),
1030 cleaned_pred.to_predicate()
1033 selcx.evaluate_obligation(&obligation)
1037 fn note_obligation_cause<T>(&self,
1038 err: &mut DiagnosticBuilder,
1039 obligation: &Obligation<'tcx, T>)
1040 where T: fmt::Display
1042 self.note_obligation_cause_code(err,
1043 &obligation.predicate,
1044 &obligation.cause.code);
1047 fn note_obligation_cause_code<T>(&self,
1048 err: &mut DiagnosticBuilder,
1050 cause_code: &ObligationCauseCode<'tcx>)
1051 where T: fmt::Display
1055 ObligationCauseCode::ExprAssignable |
1056 ObligationCauseCode::MatchExpressionArm { .. } |
1057 ObligationCauseCode::IfExpression |
1058 ObligationCauseCode::IfExpressionWithNoElse |
1059 ObligationCauseCode::EquatePredicate |
1060 ObligationCauseCode::MainFunctionType |
1061 ObligationCauseCode::StartFunctionType |
1062 ObligationCauseCode::IntrinsicType |
1063 ObligationCauseCode::MethodReceiver |
1064 ObligationCauseCode::ReturnNoExpression |
1065 ObligationCauseCode::MiscObligation => {
1067 ObligationCauseCode::SliceOrArrayElem => {
1068 err.note("slice and array elements must have `Sized` type");
1070 ObligationCauseCode::TupleElem => {
1071 err.note("only the last element of a tuple may have a dynamically sized type");
1073 ObligationCauseCode::ProjectionWf(data) => {
1074 err.note(&format!("required so that the projection `{}` is well-formed",
1077 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1078 err.note(&format!("required so that reference `{}` does not outlive its referent",
1081 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1082 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1084 region, object_ty));
1086 ObligationCauseCode::ItemObligation(item_def_id) => {
1087 let item_name = tcx.item_path_str(item_def_id);
1088 err.note(&format!("required by `{}`", item_name));
1090 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1091 err.note(&format!("required for the cast to the object type `{}`",
1092 self.ty_to_string(object_ty)));
1094 ObligationCauseCode::RepeatVec => {
1095 err.note("the `Copy` trait is required because the \
1096 repeated element will be copied");
1098 ObligationCauseCode::VariableType(_) => {
1099 err.note("all local variables must have a statically known size");
1101 ObligationCauseCode::SizedReturnType => {
1102 err.note("the return type of a function must have a \
1103 statically known size");
1105 ObligationCauseCode::AssignmentLhsSized => {
1106 err.note("the left-hand-side of an assignment must have a statically known size");
1108 ObligationCauseCode::TupleInitializerSized => {
1109 err.note("tuples must have a statically known size to be initialized");
1111 ObligationCauseCode::StructInitializerSized => {
1112 err.note("structs must have a statically known size to be initialized");
1114 ObligationCauseCode::FieldSized => {
1115 err.note("only the last field of a struct or an union may have a dynamically \
1118 ObligationCauseCode::ConstSized => {
1119 err.note("constant expressions must have a statically known size");
1121 ObligationCauseCode::SharedStatic => {
1122 err.note("shared static variables must have a type that implements `Sync`");
1124 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1125 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1126 err.note(&format!("required because it appears within the type `{}`",
1127 parent_trait_ref.0.self_ty()));
1128 let parent_predicate = parent_trait_ref.to_predicate();
1129 self.note_obligation_cause_code(err,
1133 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1134 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1136 &format!("required because of the requirements on the impl of `{}` for `{}`",
1138 parent_trait_ref.0.self_ty()));
1139 let parent_predicate = parent_trait_ref.to_predicate();
1140 self.note_obligation_cause_code(err,
1144 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1146 &format!("the requirement `{}` appears on the impl method \
1147 but not on the corresponding trait method",
1150 ObligationCauseCode::ReturnType(_) |
1151 ObligationCauseCode::BlockTailExpression(_) => (),
1155 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1156 let current_limit = self.tcx.sess.recursion_limit.get();
1157 let suggested_limit = current_limit * 2;
1159 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",