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 OnUnimplementedDirective,
20 OutputTypeParameterMismatch,
26 ObjectSafetyViolation,
29 use errors::DiagnosticBuilder;
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, TypeError};
40 use ty::fold::TypeFolder;
42 use ty::SubtypePredicate;
43 use util::nodemap::{FxHashMap, FxHashSet};
45 use syntax_pos::{DUMMY_SP, Span};
47 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
48 pub fn report_fulfillment_errors(&self,
49 errors: &Vec<FulfillmentError<'tcx>>,
50 body_id: Option<hir::BodyId>) {
52 struct ErrorDescriptor<'tcx> {
53 predicate: ty::Predicate<'tcx>,
54 index: Option<usize>, // None if this is an old error
57 let mut error_map : FxHashMap<_, _> =
58 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
59 (span, predicates.iter().map(|predicate| ErrorDescriptor {
60 predicate: predicate.clone(),
65 for (index, error) in errors.iter().enumerate() {
66 error_map.entry(error.obligation.cause.span).or_insert(Vec::new()).push(
68 predicate: error.obligation.predicate.clone(),
72 self.reported_trait_errors.borrow_mut()
73 .entry(error.obligation.cause.span).or_insert(Vec::new())
74 .push(error.obligation.predicate.clone());
77 // We do this in 2 passes because we want to display errors in order, tho
78 // maybe it *is* better to sort errors by span or something.
79 let mut is_suppressed: Vec<bool> = errors.iter().map(|_| false).collect();
80 for (_, error_set) in error_map.iter() {
81 // We want to suppress "duplicate" errors with the same span.
82 for error in error_set {
83 if let Some(index) = error.index {
84 // Suppress errors that are either:
85 // 1) strictly implied by another error.
86 // 2) implied by an error with a smaller index.
87 for error2 in error_set {
88 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
89 // Avoid errors being suppressed by already-suppressed
90 // errors, to prevent all errors from being suppressed
95 if self.error_implies(&error2.predicate, &error.predicate) &&
96 !(error2.index >= error.index &&
97 self.error_implies(&error.predicate, &error2.predicate))
99 info!("skipping {:?} (implied by {:?})", error, error2);
100 is_suppressed[index] = true;
108 for (error, suppressed) in errors.iter().zip(is_suppressed) {
110 self.report_fulfillment_error(error, body_id);
115 // returns if `cond` not occurring implies that `error` does not occur - i.e. that
116 // `error` occurring implies that `cond` occurs.
117 fn error_implies(&self,
118 cond: &ty::Predicate<'tcx>,
119 error: &ty::Predicate<'tcx>)
126 let (cond, error) = match (cond, error) {
127 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
130 // FIXME: make this work in other cases too.
135 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
136 if let ty::Predicate::Trait(implication) = implication {
137 let error = error.to_poly_trait_ref();
138 let implication = implication.to_poly_trait_ref();
139 // FIXME: I'm just not taking associated types at all here.
140 // Eventually I'll need to implement param-env-aware
141 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
142 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
143 if let Ok(_) = self.can_sub(param_env, error, implication) {
144 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
153 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
154 body_id: Option<hir::BodyId>) {
155 debug!("report_fulfillment_errors({:?})", error);
157 FulfillmentErrorCode::CodeSelectionError(ref e) => {
158 self.report_selection_error(&error.obligation, e);
160 FulfillmentErrorCode::CodeProjectionError(ref e) => {
161 self.report_projection_error(&error.obligation, e);
163 FulfillmentErrorCode::CodeAmbiguity => {
164 self.maybe_report_ambiguity(&error.obligation, body_id);
166 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
167 self.report_mismatched_types(&error.obligation.cause,
168 expected_found.expected,
169 expected_found.found,
176 fn report_projection_error(&self,
177 obligation: &PredicateObligation<'tcx>,
178 error: &MismatchedProjectionTypes<'tcx>)
181 self.resolve_type_vars_if_possible(&obligation.predicate);
183 if predicate.references_error() {
189 let mut err = &error.err;
190 let mut values = None;
192 // try to find the mismatched types to report the error with.
194 // this can fail if the problem was higher-ranked, in which
195 // cause I have no idea for a good error message.
196 if let ty::Predicate::Projection(ref data) = predicate {
197 let mut selcx = SelectionContext::new(self);
198 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
199 obligation.cause.span,
200 infer::LateBoundRegionConversionTime::HigherRankedType,
202 let normalized = super::normalize_projection_type(
204 obligation.param_env,
206 obligation.cause.clone(),
209 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
210 .eq(normalized.value, data.ty) {
211 values = Some(infer::ValuePairs::Types(ExpectedFound {
212 expected: normalized.value,
220 let mut diag = struct_span_err!(
221 self.tcx.sess, obligation.cause.span, E0271,
222 "type mismatch resolving `{}`", predicate
224 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
225 self.note_obligation_cause(&mut diag, obligation);
230 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
231 /// returns the fuzzy category of a given type, or None
232 /// if the type can be equated to any type.
233 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
235 ty::TyBool => Some(0),
236 ty::TyChar => Some(1),
237 ty::TyStr => Some(2),
238 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
239 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
240 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
241 ty::TyArray(..) | ty::TySlice(..) => Some(6),
242 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
243 ty::TyDynamic(..) => Some(8),
244 ty::TyClosure(..) => Some(9),
245 ty::TyTuple(..) => Some(10),
246 ty::TyProjection(..) => Some(11),
247 ty::TyParam(..) => Some(12),
248 ty::TyAnon(..) => Some(13),
249 ty::TyNever => Some(14),
250 ty::TyAdt(adt, ..) => match adt.adt_kind() {
251 AdtKind::Struct => Some(15),
252 AdtKind::Union => Some(16),
253 AdtKind::Enum => Some(17),
255 ty::TyGenerator(..) => Some(18),
256 ty::TyInfer(..) | ty::TyError => None
260 match (type_category(a), type_category(b)) {
261 (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
262 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == def_b,
265 // infer and error can be equated to all types
270 fn impl_similar_to(&self,
271 trait_ref: ty::PolyTraitRef<'tcx>,
272 obligation: &PredicateObligation<'tcx>)
276 let param_env = obligation.param_env;
277 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
278 let trait_self_ty = trait_ref.self_ty();
280 let mut self_match_impls = vec![];
281 let mut fuzzy_match_impls = vec![];
283 self.tcx.for_each_relevant_impl(
284 trait_ref.def_id, trait_self_ty, |def_id| {
285 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
286 let impl_trait_ref = tcx
287 .impl_trait_ref(def_id)
289 .subst(tcx, impl_substs);
291 let impl_self_ty = impl_trait_ref.self_ty();
293 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
294 self_match_impls.push(def_id);
296 if trait_ref.substs.types().skip(1)
297 .zip(impl_trait_ref.substs.types().skip(1))
298 .all(|(u,v)| self.fuzzy_match_tys(u, v))
300 fuzzy_match_impls.push(def_id);
305 let impl_def_id = if self_match_impls.len() == 1 {
307 } else if fuzzy_match_impls.len() == 1 {
313 if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
320 fn on_unimplemented_note(
322 trait_ref: ty::PolyTraitRef<'tcx>,
323 obligation: &PredicateObligation<'tcx>) ->
326 let def_id = self.impl_similar_to(trait_ref, obligation)
327 .unwrap_or(trait_ref.def_id());
328 let trait_ref = *trait_ref.skip_binder();
332 let mut flags = vec![];
333 let direct = match obligation.cause.code {
334 ObligationCauseCode::BuiltinDerivedObligation(..) |
335 ObligationCauseCode::ImplDerivedObligation(..) => false,
339 // this is a "direct", user-specified, rather than derived,
341 flags.push(("direct", None));
344 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
345 // FIXME: maybe also have some way of handling methods
346 // from other traits? That would require name resolution,
347 // which we might want to be some sort of hygienic.
349 // Currently I'm leaving it for what I need for `try`.
350 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
351 method = self.tcx.item_name(item).as_str();
352 flags.push(("from_method", None));
353 flags.push(("from_method", Some(&*method)));
357 if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
358 desugaring = k.as_symbol().as_str();
359 flags.push(("from_desugaring", None));
360 flags.push(("from_desugaring", Some(&*desugaring)));
363 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
364 self.tcx, trait_ref.def_id, def_id
366 command.evaluate(self.tcx, trait_ref, &flags)
368 OnUnimplementedNote::empty()
372 fn find_similar_impl_candidates(&self,
373 trait_ref: ty::PolyTraitRef<'tcx>)
374 -> Vec<ty::TraitRef<'tcx>>
376 let simp = fast_reject::simplify_type(self.tcx,
377 trait_ref.skip_binder().self_ty(),
379 let mut impl_candidates = Vec::new();
382 Some(simp) => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
383 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
384 let imp_simp = fast_reject::simplify_type(self.tcx,
387 if let Some(imp_simp) = imp_simp {
388 if simp != imp_simp {
392 impl_candidates.push(imp);
394 None => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
395 impl_candidates.push(
396 self.tcx.impl_trait_ref(def_id).unwrap());
402 fn report_similar_impl_candidates(&self,
403 impl_candidates: Vec<ty::TraitRef<'tcx>>,
404 err: &mut DiagnosticBuilder)
406 if impl_candidates.is_empty() {
410 let end = if impl_candidates.len() <= 5 {
411 impl_candidates.len()
415 err.help(&format!("the following implementations were found:{}{}",
416 &impl_candidates[0..end].iter().map(|candidate| {
417 format!("\n {:?}", candidate)
418 }).collect::<String>(),
419 if impl_candidates.len() > 5 {
420 format!("\nand {} others", impl_candidates.len() - 4)
427 /// Reports that an overflow has occurred and halts compilation. We
428 /// halt compilation unconditionally because it is important that
429 /// overflows never be masked -- they basically represent computations
430 /// whose result could not be truly determined and thus we can't say
431 /// if the program type checks or not -- and they are unusual
432 /// occurrences in any case.
433 pub fn report_overflow_error<T>(&self,
434 obligation: &Obligation<'tcx, T>,
435 suggest_increasing_limit: bool) -> !
436 where T: fmt::Display + TypeFoldable<'tcx>
439 self.resolve_type_vars_if_possible(&obligation.predicate);
440 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
441 "overflow evaluating the requirement `{}`",
444 if suggest_increasing_limit {
445 self.suggest_new_overflow_limit(&mut err);
448 self.note_obligation_cause(&mut err, obligation);
451 self.tcx.sess.abort_if_errors();
455 /// Reports that a cycle was detected which led to overflow and halts
456 /// compilation. This is equivalent to `report_overflow_error` except
457 /// that we can give a more helpful error message (and, in particular,
458 /// we do not suggest increasing the overflow limit, which is not
460 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
461 let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
462 assert!(cycle.len() > 0);
464 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
466 self.report_overflow_error(&cycle[0], false);
469 pub fn report_extra_impl_obligation(&self,
471 item_name: ast::Name,
472 _impl_item_def_id: DefId,
473 trait_item_def_id: DefId,
474 requirement: &fmt::Display,
475 lint_id: Option<ast::NodeId>) // (*)
476 -> DiagnosticBuilder<'tcx>
478 // (*) This parameter is temporary and used only for phasing
479 // in the bug fix to #18937. If it is `Some`, it has a kind of
480 // weird effect -- the diagnostic is reported as a lint, and
481 // the builder which is returned is marked as canceled.
483 let msg = "impl has stricter requirements than trait";
484 let mut err = match lint_id {
486 self.tcx.struct_span_lint_node(EXTRA_REQUIREMENT_IN_IMPL,
492 struct_span_err!(self.tcx.sess,
499 if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
500 let span = self.tcx.sess.codemap().def_span(trait_item_span);
501 err.span_label(span, format!("definition of `{}` from trait", item_name));
506 format!("impl has extra requirement {}", requirement));
512 /// Get the parent trait chain start
513 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
515 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
516 let parent_trait_ref = self.resolve_type_vars_if_possible(
517 &data.parent_trait_ref);
518 match self.get_parent_trait_ref(&data.parent_code) {
520 None => Some(format!("{}", parent_trait_ref.0.self_ty())),
527 pub fn report_selection_error(&self,
528 obligation: &PredicateObligation<'tcx>,
529 error: &SelectionError<'tcx>)
531 let span = obligation.cause.span;
533 let mut err = match *error {
534 SelectionError::Unimplemented => {
535 if let ObligationCauseCode::CompareImplMethodObligation {
536 item_name, impl_item_def_id, trait_item_def_id, lint_id
537 } = obligation.cause.code {
538 self.report_extra_impl_obligation(
543 &format!("`{}`", obligation.predicate),
548 match obligation.predicate {
549 ty::Predicate::Trait(ref trait_predicate) => {
550 let trait_predicate =
551 self.resolve_type_vars_if_possible(trait_predicate);
553 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
556 let trait_ref = trait_predicate.to_poly_trait_ref();
557 let (post_message, pre_message) =
558 self.get_parent_trait_ref(&obligation.cause.code)
559 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
560 .unwrap_or((String::new(), String::new()));
562 let OnUnimplementedNote { message, label }
563 = self.on_unimplemented_note(trait_ref, obligation);
564 let have_alt_message = message.is_some() || label.is_some();
566 let mut err = struct_span_err!(
571 message.unwrap_or_else(|| {
572 format!("the trait bound `{}` is not satisfied{}",
573 trait_ref.to_predicate(), post_message)
576 if let Some(ref s) = label {
577 // If it has a custom "#[rustc_on_unimplemented]"
578 // error message, let's display it as the label!
579 err.span_label(span, s.as_str());
580 err.help(&format!("{}the trait `{}` is not implemented for `{}`",
583 trait_ref.self_ty()));
586 &*format!("{}the trait `{}` is not implemented for `{}`",
589 trait_ref.self_ty()));
592 // Try to report a help message
593 if !trait_ref.has_infer_types() &&
594 self.predicate_can_apply(obligation.param_env, trait_ref) {
595 // If a where-clause may be useful, remind the
596 // user that they can add it.
598 // don't display an on-unimplemented note, as
599 // these notes will often be of the form
600 // "the type `T` can't be frobnicated"
601 // which is somewhat confusing.
602 err.help(&format!("consider adding a `where {}` bound",
603 trait_ref.to_predicate()));
604 } else if !have_alt_message {
605 // Can't show anything else useful, try to find similar impls.
606 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
607 self.report_similar_impl_candidates(impl_candidates, &mut err);
613 ty::Predicate::Subtype(ref predicate) => {
614 // Errors for Subtype predicates show up as
615 // `FulfillmentErrorCode::CodeSubtypeError`,
616 // not selection error.
617 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
620 ty::Predicate::Equate(ref predicate) => {
621 let predicate = self.resolve_type_vars_if_possible(predicate);
622 let err = self.equality_predicate(&obligation.cause,
623 obligation.param_env,
624 &predicate).err().unwrap();
625 struct_span_err!(self.tcx.sess, span, E0278,
626 "the requirement `{}` is not satisfied (`{}`)",
630 ty::Predicate::RegionOutlives(ref predicate) => {
631 let predicate = self.resolve_type_vars_if_possible(predicate);
632 let err = self.region_outlives_predicate(&obligation.cause,
633 &predicate).err().unwrap();
634 struct_span_err!(self.tcx.sess, span, E0279,
635 "the requirement `{}` is not satisfied (`{}`)",
639 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
641 self.resolve_type_vars_if_possible(&obligation.predicate);
642 struct_span_err!(self.tcx.sess, span, E0280,
643 "the requirement `{}` is not satisfied",
647 ty::Predicate::ObjectSafe(trait_def_id) => {
648 let violations = self.tcx.object_safety_violations(trait_def_id);
649 self.tcx.report_object_safety_error(span,
654 ty::Predicate::ClosureKind(closure_def_id, kind) => {
655 let found_kind = self.closure_kind(closure_def_id).unwrap();
656 let closure_span = self.tcx.hir.span_if_local(closure_def_id).unwrap();
657 let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
658 let mut err = struct_span_err!(
659 self.tcx.sess, closure_span, E0525,
660 "expected a closure that implements the `{}` trait, \
661 but this closure only implements `{}`",
666 obligation.cause.span,
667 format!("the requirement to implement `{}` derives from here", kind));
669 // Additional context information explaining why the closure only implements
670 // a particular trait.
671 if let Some(tables) = self.in_progress_tables {
672 let tables = tables.borrow();
673 let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
674 match tables.closure_kinds().get(closure_hir_id) {
675 Some(&(ty::ClosureKind::FnOnce, Some((span, name)))) => {
676 err.span_note(span, &format!(
677 "closure is `FnOnce` because it moves the \
678 variable `{}` out of its environment", name));
680 Some(&(ty::ClosureKind::FnMut, Some((span, name)))) => {
681 err.span_note(span, &format!(
682 "closure is `FnMut` because it mutates the \
683 variable `{}` here", name));
693 ty::Predicate::WellFormed(ty) => {
694 // WF predicates cannot themselves make
695 // errors. They can only block due to
696 // ambiguity; otherwise, they always
697 // degenerate into other obligations
699 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
704 OutputTypeParameterMismatch(ref expected_trait_ref, ref actual_trait_ref, ref e) => {
705 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
706 let actual_trait_ref = self.resolve_type_vars_if_possible(&*actual_trait_ref);
707 if actual_trait_ref.self_ty().references_error() {
710 let expected_trait_ty = expected_trait_ref.self_ty();
711 let found_span = expected_trait_ty.ty_to_def_id().and_then(|did| {
712 self.tcx.hir.span_if_local(did)
715 if let &TypeError::TupleSize(ref expected_found) = e {
716 // Expected `|x| { }`, found `|x, y| { }`
717 self.report_arg_count_mismatch(span,
719 expected_found.expected,
720 expected_found.found,
721 expected_trait_ty.is_closure())
722 } else if let &TypeError::Sorts(ref expected_found) = e {
723 let expected = if let ty::TyTuple(tys, _) = expected_found.expected.sty {
728 let found = if let ty::TyTuple(tys, _) = expected_found.found.sty {
734 if expected != found {
735 // Expected `|| { }`, found `|x, y| { }`
736 // Expected `fn(x) -> ()`, found `|| { }`
737 self.report_arg_count_mismatch(span,
741 expected_trait_ty.is_closure())
743 self.report_type_argument_mismatch(span,
751 self.report_type_argument_mismatch(span,
760 TraitNotObjectSafe(did) => {
761 let violations = self.tcx.object_safety_violations(did);
762 self.tcx.report_object_safety_error(span, did,
766 self.note_obligation_cause(&mut err, obligation);
770 fn report_type_argument_mismatch(&self,
772 found_span: Option<Span>,
773 expected_ty: Ty<'tcx>,
774 expected_ref: ty::PolyTraitRef<'tcx>,
775 found_ref: ty::PolyTraitRef<'tcx>,
776 type_error: &TypeError<'tcx>)
777 -> DiagnosticBuilder<'tcx>
779 let mut err = struct_span_err!(self.tcx.sess, span, E0281,
780 "type mismatch: `{}` implements the trait `{}`, but the trait `{}` is required",
785 err.span_label(span, format!("{}", type_error));
787 if let Some(sp) = found_span {
788 err.span_label(span, format!("requires `{}`", found_ref));
789 err.span_label(sp, format!("implements `{}`", expected_ref));
795 fn report_arg_count_mismatch(&self,
797 found_span: Option<Span>,
801 -> DiagnosticBuilder<'tcx>
803 let mut err = struct_span_err!(self.tcx.sess, span, E0593,
804 "{} takes {} argument{} but {} argument{} {} required",
805 if is_closure { "closure" } else { "function" },
807 if found == 1 { "" } else { "s" },
809 if expected == 1 { "" } else { "s" },
810 if expected == 1 { "is" } else { "are" });
812 err.span_label(span, format!("expected {} that takes {} argument{}",
813 if is_closure { "closure" } else { "function" },
815 if expected == 1 { "" } else { "s" }));
816 if let Some(span) = found_span {
817 err.span_label(span, format!("takes {} argument{}",
819 if found == 1 { "" } else { "s" }));
825 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
826 pub fn recursive_type_with_infinite_size_error(self,
828 -> DiagnosticBuilder<'tcx>
830 assert!(type_def_id.is_local());
831 let span = self.hir.span_if_local(type_def_id).unwrap();
832 let span = self.sess.codemap().def_span(span);
833 let mut err = struct_span_err!(self.sess, span, E0072,
834 "recursive type `{}` has infinite size",
835 self.item_path_str(type_def_id));
836 err.span_label(span, "recursive type has infinite size");
837 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
838 at some point to make `{}` representable",
839 self.item_path_str(type_def_id)));
843 pub fn report_object_safety_error(self,
846 violations: Vec<ObjectSafetyViolation>)
847 -> DiagnosticBuilder<'tcx>
849 let trait_str = self.item_path_str(trait_def_id);
850 let span = self.sess.codemap().def_span(span);
851 let mut err = struct_span_err!(
852 self.sess, span, E0038,
853 "the trait `{}` cannot be made into an object",
855 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
857 let mut reported_violations = FxHashSet();
858 for violation in violations {
859 if !reported_violations.insert(violation.clone()) {
862 err.note(&violation.error_msg());
868 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
869 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
870 body_id: Option<hir::BodyId>) {
871 // Unable to successfully determine, probably means
872 // insufficient type information, but could mean
873 // ambiguous impls. The latter *ought* to be a
874 // coherence violation, so we don't report it here.
876 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
877 let span = obligation.cause.span;
879 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
883 // Ambiguity errors are often caused as fallout from earlier
884 // errors. So just ignore them if this infcx is tainted.
885 if self.is_tainted_by_errors() {
890 ty::Predicate::Trait(ref data) => {
891 let trait_ref = data.to_poly_trait_ref();
892 let self_ty = trait_ref.self_ty();
893 if predicate.references_error() {
896 // Typically, this ambiguity should only happen if
897 // there are unresolved type inference variables
898 // (otherwise it would suggest a coherence
899 // failure). But given #21974 that is not necessarily
900 // the case -- we can have multiple where clauses that
901 // are only distinguished by a region, which results
902 // in an ambiguity even when all types are fully
903 // known, since we don't dispatch based on region
906 // This is kind of a hack: it frequently happens that some earlier
907 // error prevents types from being fully inferred, and then we get
908 // a bunch of uninteresting errors saying something like "<generic
909 // #0> doesn't implement Sized". It may even be true that we
910 // could just skip over all checks where the self-ty is an
911 // inference variable, but I was afraid that there might be an
912 // inference variable created, registered as an obligation, and
913 // then never forced by writeback, and hence by skipping here we'd
914 // be ignoring the fact that we don't KNOW the type works
915 // out. Though even that would probably be harmless, given that
916 // we're only talking about builtin traits, which are known to be
917 // inhabited. But in any case I just threw in this check for
918 // has_errors() to be sure that compilation isn't happening
919 // anyway. In that case, why inundate the user.
920 if !self.tcx.sess.has_errors() {
922 self.tcx.lang_items().sized_trait()
923 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
925 self.need_type_info(body_id, span, self_ty);
927 let mut err = struct_span_err!(self.tcx.sess,
929 "type annotations required: \
930 cannot resolve `{}`",
932 self.note_obligation_cause(&mut err, obligation);
938 ty::Predicate::WellFormed(ty) => {
939 // Same hacky approach as above to avoid deluging user
940 // with error messages.
941 if !ty.references_error() && !self.tcx.sess.has_errors() {
942 self.need_type_info(body_id, span, ty);
946 ty::Predicate::Subtype(ref data) => {
947 if data.references_error() || self.tcx.sess.has_errors() {
948 // no need to overload user in such cases
950 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
951 // both must be type variables, or the other would've been instantiated
952 assert!(a.is_ty_var() && b.is_ty_var());
953 self.need_type_info(body_id,
954 obligation.cause.span,
960 if !self.tcx.sess.has_errors() {
961 let mut err = struct_span_err!(self.tcx.sess,
962 obligation.cause.span, E0284,
963 "type annotations required: \
964 cannot resolve `{}`",
966 self.note_obligation_cause(&mut err, obligation);
973 /// Returns whether the trait predicate may apply for *some* assignment
974 /// to the type parameters.
975 fn predicate_can_apply(&self,
976 param_env: ty::ParamEnv<'tcx>,
977 pred: ty::PolyTraitRef<'tcx>)
979 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
980 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
981 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
984 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
985 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
987 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
988 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
989 let infcx = self.infcx;
990 self.var_map.entry(ty).or_insert_with(||
992 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
994 ty.super_fold_with(self)
1000 let mut selcx = SelectionContext::new(self);
1002 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1004 var_map: FxHashMap()
1007 let cleaned_pred = super::project::normalize(
1010 ObligationCause::dummy(),
1014 let obligation = Obligation::new(
1015 ObligationCause::dummy(),
1017 cleaned_pred.to_predicate()
1020 selcx.evaluate_obligation(&obligation)
1024 fn note_obligation_cause<T>(&self,
1025 err: &mut DiagnosticBuilder,
1026 obligation: &Obligation<'tcx, T>)
1027 where T: fmt::Display
1029 self.note_obligation_cause_code(err,
1030 &obligation.predicate,
1031 &obligation.cause.code);
1034 fn note_obligation_cause_code<T>(&self,
1035 err: &mut DiagnosticBuilder,
1037 cause_code: &ObligationCauseCode<'tcx>)
1038 where T: fmt::Display
1042 ObligationCauseCode::ExprAssignable |
1043 ObligationCauseCode::MatchExpressionArm { .. } |
1044 ObligationCauseCode::IfExpression |
1045 ObligationCauseCode::IfExpressionWithNoElse |
1046 ObligationCauseCode::EquatePredicate |
1047 ObligationCauseCode::MainFunctionType |
1048 ObligationCauseCode::StartFunctionType |
1049 ObligationCauseCode::IntrinsicType |
1050 ObligationCauseCode::MethodReceiver |
1051 ObligationCauseCode::ReturnNoExpression |
1052 ObligationCauseCode::MiscObligation => {
1054 ObligationCauseCode::SliceOrArrayElem => {
1055 err.note("slice and array elements must have `Sized` type");
1057 ObligationCauseCode::TupleElem => {
1058 err.note("only the last element of a tuple may have a dynamically sized type");
1060 ObligationCauseCode::ProjectionWf(data) => {
1061 err.note(&format!("required so that the projection `{}` is well-formed",
1064 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1065 err.note(&format!("required so that reference `{}` does not outlive its referent",
1068 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1069 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1071 region, object_ty));
1073 ObligationCauseCode::ItemObligation(item_def_id) => {
1074 let item_name = tcx.item_path_str(item_def_id);
1075 err.note(&format!("required by `{}`", item_name));
1077 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1078 err.note(&format!("required for the cast to the object type `{}`",
1079 self.ty_to_string(object_ty)));
1081 ObligationCauseCode::RepeatVec => {
1082 err.note("the `Copy` trait is required because the \
1083 repeated element will be copied");
1085 ObligationCauseCode::VariableType(_) => {
1086 err.note("all local variables must have a statically known size");
1088 ObligationCauseCode::SizedReturnType => {
1089 err.note("the return type of a function must have a \
1090 statically known size");
1092 ObligationCauseCode::AssignmentLhsSized => {
1093 err.note("the left-hand-side of an assignment must have a statically known size");
1095 ObligationCauseCode::TupleInitializerSized => {
1096 err.note("tuples must have a statically known size to be initialized");
1098 ObligationCauseCode::StructInitializerSized => {
1099 err.note("structs must have a statically known size to be initialized");
1101 ObligationCauseCode::FieldSized(ref item) => {
1103 AdtKind::Struct => {
1104 err.note("only the last field of a struct may have a dynamically \
1108 err.note("no field of a union may have a dynamically sized type");
1111 err.note("no field of an enum variant may have a dynamically sized type");
1115 ObligationCauseCode::ConstSized => {
1116 err.note("constant expressions must have a statically known size");
1118 ObligationCauseCode::SharedStatic => {
1119 err.note("shared static variables must have a type that implements `Sync`");
1121 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1122 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1123 err.note(&format!("required because it appears within the type `{}`",
1124 parent_trait_ref.0.self_ty()));
1125 let parent_predicate = parent_trait_ref.to_predicate();
1126 self.note_obligation_cause_code(err,
1130 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1131 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1133 &format!("required because of the requirements on the impl of `{}` for `{}`",
1135 parent_trait_ref.0.self_ty()));
1136 let parent_predicate = parent_trait_ref.to_predicate();
1137 self.note_obligation_cause_code(err,
1141 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1143 &format!("the requirement `{}` appears on the impl method \
1144 but not on the corresponding trait method",
1147 ObligationCauseCode::ReturnType(_) |
1148 ObligationCauseCode::BlockTailExpression(_) => (),
1152 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1153 let current_limit = self.tcx.sess.recursion_limit.get();
1154 let suggested_limit = current_limit * 2;
1155 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",