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,
27 ObjectSafetyViolation,
30 use errors::DiagnosticBuilder;
32 use hir::def_id::DefId;
33 use infer::{self, InferCtxt};
34 use infer::type_variable::TypeVariableOrigin;
35 use middle::const_val;
36 use rustc::lint::builtin::EXTRA_REQUIREMENT_IN_IMPL;
39 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
40 use ty::error::ExpectedFound;
42 use ty::fold::TypeFolder;
44 use ty::SubtypePredicate;
45 use util::nodemap::{FxHashMap, FxHashSet};
47 use syntax_pos::{DUMMY_SP, Span};
49 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
50 pub fn report_fulfillment_errors(&self,
51 errors: &Vec<FulfillmentError<'tcx>>,
52 body_id: Option<hir::BodyId>) {
54 struct ErrorDescriptor<'tcx> {
55 predicate: ty::Predicate<'tcx>,
56 index: Option<usize>, // None if this is an old error
59 let mut error_map : FxHashMap<_, _> =
60 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
61 (span, predicates.iter().map(|predicate| ErrorDescriptor {
62 predicate: predicate.clone(),
67 for (index, error) in errors.iter().enumerate() {
68 error_map.entry(error.obligation.cause.span).or_insert(Vec::new()).push(
70 predicate: error.obligation.predicate.clone(),
74 self.reported_trait_errors.borrow_mut()
75 .entry(error.obligation.cause.span).or_insert(Vec::new())
76 .push(error.obligation.predicate.clone());
79 // We do this in 2 passes because we want to display errors in order, tho
80 // maybe it *is* better to sort errors by span or something.
81 let mut is_suppressed: Vec<bool> = errors.iter().map(|_| false).collect();
82 for (_, error_set) in error_map.iter() {
83 // We want to suppress "duplicate" errors with the same span.
84 for error in error_set {
85 if let Some(index) = error.index {
86 // Suppress errors that are either:
87 // 1) strictly implied by another error.
88 // 2) implied by an error with a smaller index.
89 for error2 in error_set {
90 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
91 // Avoid errors being suppressed by already-suppressed
92 // errors, to prevent all errors from being suppressed
97 if self.error_implies(&error2.predicate, &error.predicate) &&
98 !(error2.index >= error.index &&
99 self.error_implies(&error.predicate, &error2.predicate))
101 info!("skipping {:?} (implied by {:?})", error, error2);
102 is_suppressed[index] = true;
110 for (error, suppressed) in errors.iter().zip(is_suppressed) {
112 self.report_fulfillment_error(error, body_id);
117 // returns if `cond` not occurring implies that `error` does not occur - i.e. that
118 // `error` occurring implies that `cond` occurs.
119 fn error_implies(&self,
120 cond: &ty::Predicate<'tcx>,
121 error: &ty::Predicate<'tcx>)
128 let (cond, error) = match (cond, error) {
129 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
132 // FIXME: make this work in other cases too.
137 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
138 if let ty::Predicate::Trait(implication) = implication {
139 let error = error.to_poly_trait_ref();
140 let implication = implication.to_poly_trait_ref();
141 // FIXME: I'm just not taking associated types at all here.
142 // Eventually I'll need to implement param-env-aware
143 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
144 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
145 if let Ok(_) = self.can_sub(param_env, error, implication) {
146 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
155 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
156 body_id: Option<hir::BodyId>) {
157 debug!("report_fulfillment_errors({:?})", error);
159 FulfillmentErrorCode::CodeSelectionError(ref e) => {
160 self.report_selection_error(&error.obligation, e);
162 FulfillmentErrorCode::CodeProjectionError(ref e) => {
163 self.report_projection_error(&error.obligation, e);
165 FulfillmentErrorCode::CodeAmbiguity => {
166 self.maybe_report_ambiguity(&error.obligation, body_id);
168 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
169 self.report_mismatched_types(&error.obligation.cause,
170 expected_found.expected,
171 expected_found.found,
178 fn report_projection_error(&self,
179 obligation: &PredicateObligation<'tcx>,
180 error: &MismatchedProjectionTypes<'tcx>)
183 self.resolve_type_vars_if_possible(&obligation.predicate);
185 if predicate.references_error() {
191 let mut err = &error.err;
192 let mut values = None;
194 // try to find the mismatched types to report the error with.
196 // this can fail if the problem was higher-ranked, in which
197 // cause I have no idea for a good error message.
198 if let ty::Predicate::Projection(ref data) = predicate {
199 let mut selcx = SelectionContext::new(self);
200 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
201 obligation.cause.span,
202 infer::LateBoundRegionConversionTime::HigherRankedType,
204 let normalized = super::normalize_projection_type(
206 obligation.param_env,
208 obligation.cause.clone(),
211 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
212 .eq(normalized.value, data.ty) {
213 values = Some(infer::ValuePairs::Types(ExpectedFound {
214 expected: normalized.value,
222 let mut diag = struct_span_err!(
223 self.tcx.sess, obligation.cause.span, E0271,
224 "type mismatch resolving `{}`", predicate
226 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
227 self.note_obligation_cause(&mut diag, obligation);
232 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
233 /// returns the fuzzy category of a given type, or None
234 /// if the type can be equated to any type.
235 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
237 ty::TyBool => Some(0),
238 ty::TyChar => Some(1),
239 ty::TyStr => Some(2),
240 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
241 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
242 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
243 ty::TyArray(..) | ty::TySlice(..) => Some(6),
244 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
245 ty::TyDynamic(..) => Some(8),
246 ty::TyClosure(..) => Some(9),
247 ty::TyTuple(..) => Some(10),
248 ty::TyProjection(..) => Some(11),
249 ty::TyParam(..) => Some(12),
250 ty::TyAnon(..) => Some(13),
251 ty::TyNever => Some(14),
252 ty::TyAdt(adt, ..) => match adt.adt_kind() {
253 AdtKind::Struct => Some(15),
254 AdtKind::Union => Some(16),
255 AdtKind::Enum => Some(17),
257 ty::TyGenerator(..) => Some(18),
258 ty::TyForeign(..) => Some(19),
259 ty::TyInfer(..) | ty::TyError => None
263 match (type_category(a), type_category(b)) {
264 (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
265 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == def_b,
268 // infer and error can be equated to all types
273 fn impl_similar_to(&self,
274 trait_ref: ty::PolyTraitRef<'tcx>,
275 obligation: &PredicateObligation<'tcx>)
279 let param_env = obligation.param_env;
280 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
281 let trait_self_ty = trait_ref.self_ty();
283 let mut self_match_impls = vec![];
284 let mut fuzzy_match_impls = vec![];
286 self.tcx.for_each_relevant_impl(
287 trait_ref.def_id, trait_self_ty, |def_id| {
288 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
289 let impl_trait_ref = tcx
290 .impl_trait_ref(def_id)
292 .subst(tcx, impl_substs);
294 let impl_self_ty = impl_trait_ref.self_ty();
296 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
297 self_match_impls.push(def_id);
299 if trait_ref.substs.types().skip(1)
300 .zip(impl_trait_ref.substs.types().skip(1))
301 .all(|(u,v)| self.fuzzy_match_tys(u, v))
303 fuzzy_match_impls.push(def_id);
308 let impl_def_id = if self_match_impls.len() == 1 {
310 } else if fuzzy_match_impls.len() == 1 {
316 if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
323 fn on_unimplemented_note(
325 trait_ref: ty::PolyTraitRef<'tcx>,
326 obligation: &PredicateObligation<'tcx>) ->
329 let def_id = self.impl_similar_to(trait_ref, obligation)
330 .unwrap_or(trait_ref.def_id());
331 let trait_ref = *trait_ref.skip_binder();
335 let mut flags = vec![];
336 let direct = match obligation.cause.code {
337 ObligationCauseCode::BuiltinDerivedObligation(..) |
338 ObligationCauseCode::ImplDerivedObligation(..) => false,
342 // this is a "direct", user-specified, rather than derived,
344 flags.push(("direct", None));
347 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
348 // FIXME: maybe also have some way of handling methods
349 // from other traits? That would require name resolution,
350 // which we might want to be some sort of hygienic.
352 // Currently I'm leaving it for what I need for `try`.
353 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
354 method = self.tcx.item_name(item);
355 flags.push(("from_method", None));
356 flags.push(("from_method", Some(&*method)));
360 if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
361 desugaring = k.as_symbol().as_str();
362 flags.push(("from_desugaring", None));
363 flags.push(("from_desugaring", Some(&*desugaring)));
366 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
367 self.tcx, trait_ref.def_id, def_id
369 command.evaluate(self.tcx, trait_ref, &flags)
371 OnUnimplementedNote::empty()
375 fn find_similar_impl_candidates(&self,
376 trait_ref: ty::PolyTraitRef<'tcx>)
377 -> Vec<ty::TraitRef<'tcx>>
379 let simp = fast_reject::simplify_type(self.tcx,
380 trait_ref.skip_binder().self_ty(),
382 let mut impl_candidates = Vec::new();
385 Some(simp) => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
386 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
387 let imp_simp = fast_reject::simplify_type(self.tcx,
390 if let Some(imp_simp) = imp_simp {
391 if simp != imp_simp {
395 impl_candidates.push(imp);
397 None => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
398 impl_candidates.push(
399 self.tcx.impl_trait_ref(def_id).unwrap());
405 fn report_similar_impl_candidates(&self,
406 impl_candidates: Vec<ty::TraitRef<'tcx>>,
407 err: &mut DiagnosticBuilder)
409 if impl_candidates.is_empty() {
413 let end = if impl_candidates.len() <= 5 {
414 impl_candidates.len()
418 err.help(&format!("the following implementations were found:{}{}",
419 &impl_candidates[0..end].iter().map(|candidate| {
420 format!("\n {:?}", candidate)
421 }).collect::<String>(),
422 if impl_candidates.len() > 5 {
423 format!("\nand {} others", impl_candidates.len() - 4)
430 /// Reports that an overflow has occurred and halts compilation. We
431 /// halt compilation unconditionally because it is important that
432 /// overflows never be masked -- they basically represent computations
433 /// whose result could not be truly determined and thus we can't say
434 /// if the program type checks or not -- and they are unusual
435 /// occurrences in any case.
436 pub fn report_overflow_error<T>(&self,
437 obligation: &Obligation<'tcx, T>,
438 suggest_increasing_limit: bool) -> !
439 where T: fmt::Display + TypeFoldable<'tcx>
442 self.resolve_type_vars_if_possible(&obligation.predicate);
443 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
444 "overflow evaluating the requirement `{}`",
447 if suggest_increasing_limit {
448 self.suggest_new_overflow_limit(&mut err);
451 self.note_obligation_cause(&mut err, obligation);
454 self.tcx.sess.abort_if_errors();
458 /// Reports that a cycle was detected which led to overflow and halts
459 /// compilation. This is equivalent to `report_overflow_error` except
460 /// that we can give a more helpful error message (and, in particular,
461 /// we do not suggest increasing the overflow limit, which is not
463 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
464 let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
465 assert!(cycle.len() > 0);
467 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
469 self.report_overflow_error(&cycle[0], false);
472 pub fn report_extra_impl_obligation(&self,
474 item_name: ast::Name,
475 _impl_item_def_id: DefId,
476 trait_item_def_id: DefId,
477 requirement: &fmt::Display,
478 lint_id: Option<ast::NodeId>) // (*)
479 -> DiagnosticBuilder<'tcx>
481 // (*) This parameter is temporary and used only for phasing
482 // in the bug fix to #18937. If it is `Some`, it has a kind of
483 // weird effect -- the diagnostic is reported as a lint, and
484 // the builder which is returned is marked as canceled.
486 let msg = "impl has stricter requirements than trait";
487 let mut err = match lint_id {
489 self.tcx.struct_span_lint_node(EXTRA_REQUIREMENT_IN_IMPL,
495 struct_span_err!(self.tcx.sess,
502 if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
503 let span = self.tcx.sess.codemap().def_span(trait_item_span);
504 err.span_label(span, format!("definition of `{}` from trait", item_name));
509 format!("impl has extra requirement {}", requirement));
515 /// Get the parent trait chain start
516 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
518 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
519 let parent_trait_ref = self.resolve_type_vars_if_possible(
520 &data.parent_trait_ref);
521 match self.get_parent_trait_ref(&data.parent_code) {
523 None => Some(format!("{}", parent_trait_ref.0.self_ty())),
530 pub fn report_selection_error(&self,
531 obligation: &PredicateObligation<'tcx>,
532 error: &SelectionError<'tcx>)
534 let span = obligation.cause.span;
536 let mut err = match *error {
537 SelectionError::Unimplemented => {
538 if let ObligationCauseCode::CompareImplMethodObligation {
539 item_name, impl_item_def_id, trait_item_def_id, lint_id
540 } = obligation.cause.code {
541 self.report_extra_impl_obligation(
546 &format!("`{}`", obligation.predicate),
551 match obligation.predicate {
552 ty::Predicate::Trait(ref trait_predicate) => {
553 let trait_predicate =
554 self.resolve_type_vars_if_possible(trait_predicate);
556 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
559 let trait_ref = trait_predicate.to_poly_trait_ref();
560 let (post_message, pre_message) =
561 self.get_parent_trait_ref(&obligation.cause.code)
562 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
563 .unwrap_or((String::new(), String::new()));
565 let OnUnimplementedNote { message, label }
566 = self.on_unimplemented_note(trait_ref, obligation);
567 let have_alt_message = message.is_some() || label.is_some();
569 let mut err = struct_span_err!(
574 message.unwrap_or_else(|| {
575 format!("the trait bound `{}` is not satisfied{}",
576 trait_ref.to_predicate(), post_message)
579 if let Some(ref s) = label {
580 // If it has a custom "#[rustc_on_unimplemented]"
581 // error message, let's display it as the label!
582 err.span_label(span, s.as_str());
583 err.help(&format!("{}the trait `{}` is not implemented for `{}`",
586 trait_ref.self_ty()));
589 &*format!("{}the trait `{}` is not implemented for `{}`",
592 trait_ref.self_ty()));
595 // Try to report a help message
596 if !trait_ref.has_infer_types() &&
597 self.predicate_can_apply(obligation.param_env, trait_ref) {
598 // If a where-clause may be useful, remind the
599 // user that they can add it.
601 // don't display an on-unimplemented note, as
602 // these notes will often be of the form
603 // "the type `T` can't be frobnicated"
604 // which is somewhat confusing.
605 err.help(&format!("consider adding a `where {}` bound",
606 trait_ref.to_predicate()));
607 } else if !have_alt_message {
608 // Can't show anything else useful, try to find similar impls.
609 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
610 self.report_similar_impl_candidates(impl_candidates, &mut err);
616 ty::Predicate::Subtype(ref predicate) => {
617 // Errors for Subtype predicates show up as
618 // `FulfillmentErrorCode::CodeSubtypeError`,
619 // not selection error.
620 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
623 ty::Predicate::Equate(ref predicate) => {
624 let predicate = self.resolve_type_vars_if_possible(predicate);
625 let err = self.equality_predicate(&obligation.cause,
626 obligation.param_env,
627 &predicate).err().unwrap();
628 struct_span_err!(self.tcx.sess, span, E0278,
629 "the requirement `{}` is not satisfied (`{}`)",
633 ty::Predicate::RegionOutlives(ref predicate) => {
634 let predicate = self.resolve_type_vars_if_possible(predicate);
635 let err = self.region_outlives_predicate(&obligation.cause,
636 &predicate).err().unwrap();
637 struct_span_err!(self.tcx.sess, span, E0279,
638 "the requirement `{}` is not satisfied (`{}`)",
642 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
644 self.resolve_type_vars_if_possible(&obligation.predicate);
645 struct_span_err!(self.tcx.sess, span, E0280,
646 "the requirement `{}` is not satisfied",
650 ty::Predicate::ObjectSafe(trait_def_id) => {
651 let violations = self.tcx.object_safety_violations(trait_def_id);
652 self.tcx.report_object_safety_error(span,
657 ty::Predicate::ClosureKind(closure_def_id, kind) => {
658 let found_kind = self.closure_kind(closure_def_id).unwrap();
659 let closure_span = self.tcx.hir.span_if_local(closure_def_id).unwrap();
660 let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
661 let mut err = struct_span_err!(
662 self.tcx.sess, closure_span, E0525,
663 "expected a closure that implements the `{}` trait, \
664 but this closure only implements `{}`",
669 obligation.cause.span,
670 format!("the requirement to implement `{}` derives from here", kind));
672 // Additional context information explaining why the closure only implements
673 // a particular trait.
674 if let Some(tables) = self.in_progress_tables {
675 let tables = tables.borrow();
676 let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
677 match tables.closure_kinds().get(closure_hir_id) {
678 Some(&(ty::ClosureKind::FnOnce, Some((span, name)))) => {
679 err.span_note(span, &format!(
680 "closure is `FnOnce` because it moves the \
681 variable `{}` out of its environment", name));
683 Some(&(ty::ClosureKind::FnMut, Some((span, name)))) => {
684 err.span_note(span, &format!(
685 "closure is `FnMut` because it mutates the \
686 variable `{}` here", name));
696 ty::Predicate::WellFormed(ty) => {
697 // WF predicates cannot themselves make
698 // errors. They can only block due to
699 // ambiguity; otherwise, they always
700 // degenerate into other obligations
702 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
705 ty::Predicate::ConstEvaluatable(..) => {
706 // Errors for `ConstEvaluatable` predicates show up as
707 // `SelectionError::ConstEvalFailure`,
708 // not `Unimplemented`.
710 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
715 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
716 let found_trait_ref = self.resolve_type_vars_if_possible(&*found_trait_ref);
717 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
718 if expected_trait_ref.self_ty().references_error() {
721 let found_trait_ty = found_trait_ref.self_ty();
723 let found_did = found_trait_ty.ty_to_def_id();
724 let found_span = found_did.and_then(|did| {
725 self.tcx.hir.span_if_local(did)
729 match found_trait_ref.skip_binder().substs.type_at(1).sty {
730 ty::TyTuple(ref tys, _) => tys.len(),
733 let (expected_tys, expected_ty_count) =
734 match expected_trait_ref.skip_binder().substs.type_at(1).sty {
735 ty::TyTuple(ref tys, _) =>
736 (tys.iter().map(|t| &t.sty).collect(), tys.len()),
737 ref sty => (vec![sty], 1),
739 if found_ty_count == expected_ty_count {
740 self.report_closure_arg_mismatch(span,
745 let expected_tuple = if expected_ty_count == 1 {
746 expected_tys.first().and_then(|t| {
747 if let &&ty::TyTuple(ref tuptys, _) = t {
757 // FIXME(#44150): Expand this to "N args expected but a N-tuple found."
758 // Type of the 1st expected argument is somehow provided as type of a
759 // found one in that case.
762 // [1i32, 2, 3].sort_by(|(a, b)| ..)
764 // // expected_trait_ref: std::ops::FnMut<(&i32, &i32)>
765 // // found_trait_ref: std::ops::FnMut<(&i32,)>
768 let (closure_span, closure_args) = found_did
769 .and_then(|did| self.tcx.hir.get_if_local(did))
771 if let hir::map::NodeExpr(
773 node: hir::ExprClosure(_, ref decl, id, span, _),
777 let ty_snips = decl.inputs.iter()
779 self.tcx.sess.codemap().span_to_snippet(ty.span).ok()
781 // filter out dummy spans
782 if snip == "," || snip == "|" {
789 .collect::<Vec<Option<String>>>();
791 let body = self.tcx.hir.body(id);
792 let pat_snips = body.arguments.iter()
794 self.tcx.sess.codemap().span_to_snippet(arg.pat.span).ok())
795 .collect::<Option<Vec<String>>>();
797 Some((span, pat_snips, ty_snips))
802 .map(|(span, pat, ty)| (Some(span), Some((pat, ty))))
803 .unwrap_or((None, None));
804 let closure_args = closure_args.and_then(|(pat, ty)| Some((pat?, ty)));
806 self.report_arg_count_mismatch(
808 closure_span.or(found_span),
813 found_trait_ty.is_closure()
818 TraitNotObjectSafe(did) => {
819 let violations = self.tcx.object_safety_violations(did);
820 self.tcx.report_object_safety_error(span, did,
824 ConstEvalFailure(ref err) => {
825 if let const_val::ErrKind::TypeckError = err.kind {
828 err.struct_error(self.tcx, span, "constant expression")
831 self.note_obligation_cause(&mut err, obligation);
835 fn report_arg_count_mismatch(
838 found_span: Option<Span>,
840 expected_tuple: Option<usize>,
842 closure_args: Option<(Vec<String>, Vec<Option<String>>)>,
844 ) -> DiagnosticBuilder<'tcx> {
845 use std::borrow::Cow;
847 let kind = if is_closure { "closure" } else { "function" };
849 let args_str = |n, distinct| format!(
852 if distinct && n >= 2 { "distinct " } else { "" },
853 if n == 1 { "" } else { "s" },
856 let expected_str = if let Some(n) = expected_tuple {
857 assert!(expected == 1);
858 if closure_args.as_ref().map(|&(ref pats, _)| pats.len()) == Some(n) {
859 Cow::from("a single tuple as argument")
861 // be verbose when numbers differ
862 Cow::from(format!("a single {}-tuple as argument", n))
865 Cow::from(args_str(expected, false))
868 let found_str = if expected_tuple.is_some() {
869 args_str(found, true)
871 args_str(found, false)
875 let mut err = struct_span_err!(self.tcx.sess, span, E0593,
876 "{} is expected to take {}, but it takes {}",
885 "expected {} that takes {}",
891 if let Some(span) = found_span {
892 if let (Some(expected_tuple), Some((pats, tys))) = (expected_tuple, closure_args) {
893 if expected_tuple != found || pats.len() != found {
894 err.span_label(span, format!("takes {}", found_str));
900 // add type annotations if available
901 if tys.iter().any(|ty| ty.is_some()) {
904 tys.into_iter().map(|ty| if let Some(ty) = ty {
908 }).collect::<Vec<String>>().join(", ")
917 "consider changing the closure to accept a tuple",
922 err.span_label(span, format!("takes {}", found_str));
929 fn report_closure_arg_mismatch(&self,
931 found_span: Option<Span>,
932 expected_ref: ty::PolyTraitRef<'tcx>,
933 found: ty::PolyTraitRef<'tcx>)
934 -> DiagnosticBuilder<'tcx>
936 fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
937 trait_ref: &ty::TraitRef<'tcx>) -> String {
938 let inputs = trait_ref.substs.type_at(1);
939 let sig = if let ty::TyTuple(inputs, _) = inputs.sty {
941 inputs.iter().map(|&x| x),
942 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
944 hir::Unsafety::Normal,
945 ::syntax::abi::Abi::Rust
949 ::std::iter::once(inputs),
950 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
952 hir::Unsafety::Normal,
953 ::syntax::abi::Abi::Rust
956 format!("{}", ty::Binder(sig))
959 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
960 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
961 "type mismatch in {} arguments",
962 if argument_is_closure { "closure" } else { "function" });
964 let found_str = format!(
965 "expected signature of `{}`",
966 build_fn_sig_string(self.tcx, found.skip_binder())
968 err.span_label(span, found_str);
970 let found_span = found_span.unwrap_or(span);
971 let expected_str = format!(
972 "found signature of `{}`",
973 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
975 err.span_label(found_span, expected_str);
981 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
982 pub fn recursive_type_with_infinite_size_error(self,
984 -> DiagnosticBuilder<'tcx>
986 assert!(type_def_id.is_local());
987 let span = self.hir.span_if_local(type_def_id).unwrap();
988 let span = self.sess.codemap().def_span(span);
989 let mut err = struct_span_err!(self.sess, span, E0072,
990 "recursive type `{}` has infinite size",
991 self.item_path_str(type_def_id));
992 err.span_label(span, "recursive type has infinite size");
993 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
994 at some point to make `{}` representable",
995 self.item_path_str(type_def_id)));
999 pub fn report_object_safety_error(self,
1001 trait_def_id: DefId,
1002 violations: Vec<ObjectSafetyViolation>)
1003 -> DiagnosticBuilder<'tcx>
1005 let trait_str = self.item_path_str(trait_def_id);
1006 let span = self.sess.codemap().def_span(span);
1007 let mut err = struct_span_err!(
1008 self.sess, span, E0038,
1009 "the trait `{}` cannot be made into an object",
1011 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1013 let mut reported_violations = FxHashSet();
1014 for violation in violations {
1015 if !reported_violations.insert(violation.clone()) {
1018 err.note(&violation.error_msg());
1024 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1025 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1026 body_id: Option<hir::BodyId>) {
1027 // Unable to successfully determine, probably means
1028 // insufficient type information, but could mean
1029 // ambiguous impls. The latter *ought* to be a
1030 // coherence violation, so we don't report it here.
1032 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1033 let span = obligation.cause.span;
1035 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1039 // Ambiguity errors are often caused as fallout from earlier
1040 // errors. So just ignore them if this infcx is tainted.
1041 if self.is_tainted_by_errors() {
1046 ty::Predicate::Trait(ref data) => {
1047 let trait_ref = data.to_poly_trait_ref();
1048 let self_ty = trait_ref.self_ty();
1049 if predicate.references_error() {
1052 // Typically, this ambiguity should only happen if
1053 // there are unresolved type inference variables
1054 // (otherwise it would suggest a coherence
1055 // failure). But given #21974 that is not necessarily
1056 // the case -- we can have multiple where clauses that
1057 // are only distinguished by a region, which results
1058 // in an ambiguity even when all types are fully
1059 // known, since we don't dispatch based on region
1062 // This is kind of a hack: it frequently happens that some earlier
1063 // error prevents types from being fully inferred, and then we get
1064 // a bunch of uninteresting errors saying something like "<generic
1065 // #0> doesn't implement Sized". It may even be true that we
1066 // could just skip over all checks where the self-ty is an
1067 // inference variable, but I was afraid that there might be an
1068 // inference variable created, registered as an obligation, and
1069 // then never forced by writeback, and hence by skipping here we'd
1070 // be ignoring the fact that we don't KNOW the type works
1071 // out. Though even that would probably be harmless, given that
1072 // we're only talking about builtin traits, which are known to be
1073 // inhabited. But in any case I just threw in this check for
1074 // has_errors() to be sure that compilation isn't happening
1075 // anyway. In that case, why inundate the user.
1076 if !self.tcx.sess.has_errors() {
1078 self.tcx.lang_items().sized_trait()
1079 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1081 self.need_type_info(body_id, span, self_ty);
1083 let mut err = struct_span_err!(self.tcx.sess,
1085 "type annotations required: \
1086 cannot resolve `{}`",
1088 self.note_obligation_cause(&mut err, obligation);
1094 ty::Predicate::WellFormed(ty) => {
1095 // Same hacky approach as above to avoid deluging user
1096 // with error messages.
1097 if !ty.references_error() && !self.tcx.sess.has_errors() {
1098 self.need_type_info(body_id, span, ty);
1102 ty::Predicate::Subtype(ref data) => {
1103 if data.references_error() || self.tcx.sess.has_errors() {
1104 // no need to overload user in such cases
1106 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1107 // both must be type variables, or the other would've been instantiated
1108 assert!(a.is_ty_var() && b.is_ty_var());
1109 self.need_type_info(body_id,
1110 obligation.cause.span,
1116 if !self.tcx.sess.has_errors() {
1117 let mut err = struct_span_err!(self.tcx.sess,
1118 obligation.cause.span, E0284,
1119 "type annotations required: \
1120 cannot resolve `{}`",
1122 self.note_obligation_cause(&mut err, obligation);
1129 /// Returns whether the trait predicate may apply for *some* assignment
1130 /// to the type parameters.
1131 fn predicate_can_apply(&self,
1132 param_env: ty::ParamEnv<'tcx>,
1133 pred: ty::PolyTraitRef<'tcx>)
1135 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1136 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1137 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1140 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1141 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1143 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1144 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
1145 let infcx = self.infcx;
1146 self.var_map.entry(ty).or_insert_with(||
1148 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1150 ty.super_fold_with(self)
1156 let mut selcx = SelectionContext::new(self);
1158 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1160 var_map: FxHashMap()
1163 let cleaned_pred = super::project::normalize(
1166 ObligationCause::dummy(),
1170 let obligation = Obligation::new(
1171 ObligationCause::dummy(),
1173 cleaned_pred.to_predicate()
1176 selcx.evaluate_obligation(&obligation)
1180 fn note_obligation_cause<T>(&self,
1181 err: &mut DiagnosticBuilder,
1182 obligation: &Obligation<'tcx, T>)
1183 where T: fmt::Display
1185 self.note_obligation_cause_code(err,
1186 &obligation.predicate,
1187 &obligation.cause.code);
1190 fn note_obligation_cause_code<T>(&self,
1191 err: &mut DiagnosticBuilder,
1193 cause_code: &ObligationCauseCode<'tcx>)
1194 where T: fmt::Display
1198 ObligationCauseCode::ExprAssignable |
1199 ObligationCauseCode::MatchExpressionArm { .. } |
1200 ObligationCauseCode::IfExpression |
1201 ObligationCauseCode::IfExpressionWithNoElse |
1202 ObligationCauseCode::EquatePredicate |
1203 ObligationCauseCode::MainFunctionType |
1204 ObligationCauseCode::StartFunctionType |
1205 ObligationCauseCode::IntrinsicType |
1206 ObligationCauseCode::MethodReceiver |
1207 ObligationCauseCode::ReturnNoExpression |
1208 ObligationCauseCode::MiscObligation => {
1210 ObligationCauseCode::SliceOrArrayElem => {
1211 err.note("slice and array elements must have `Sized` type");
1213 ObligationCauseCode::TupleElem => {
1214 err.note("only the last element of a tuple may have a dynamically sized type");
1216 ObligationCauseCode::ProjectionWf(data) => {
1217 err.note(&format!("required so that the projection `{}` is well-formed",
1220 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1221 err.note(&format!("required so that reference `{}` does not outlive its referent",
1224 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1225 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1227 region, object_ty));
1229 ObligationCauseCode::ItemObligation(item_def_id) => {
1230 let item_name = tcx.item_path_str(item_def_id);
1231 err.note(&format!("required by `{}`", item_name));
1233 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1234 err.note(&format!("required for the cast to the object type `{}`",
1235 self.ty_to_string(object_ty)));
1237 ObligationCauseCode::RepeatVec => {
1238 err.note("the `Copy` trait is required because the \
1239 repeated element will be copied");
1241 ObligationCauseCode::VariableType(_) => {
1242 err.note("all local variables must have a statically known size");
1244 ObligationCauseCode::SizedReturnType => {
1245 err.note("the return type of a function must have a \
1246 statically known size");
1248 ObligationCauseCode::AssignmentLhsSized => {
1249 err.note("the left-hand-side of an assignment must have a statically known size");
1251 ObligationCauseCode::TupleInitializerSized => {
1252 err.note("tuples must have a statically known size to be initialized");
1254 ObligationCauseCode::StructInitializerSized => {
1255 err.note("structs must have a statically known size to be initialized");
1257 ObligationCauseCode::FieldSized(ref item) => {
1259 AdtKind::Struct => {
1260 err.note("only the last field of a struct may have a dynamically \
1264 err.note("no field of a union may have a dynamically sized type");
1267 err.note("no field of an enum variant may have a dynamically sized type");
1271 ObligationCauseCode::ConstSized => {
1272 err.note("constant expressions must have a statically known size");
1274 ObligationCauseCode::SharedStatic => {
1275 err.note("shared static variables must have a type that implements `Sync`");
1277 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1278 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1279 err.note(&format!("required because it appears within the type `{}`",
1280 parent_trait_ref.0.self_ty()));
1281 let parent_predicate = parent_trait_ref.to_predicate();
1282 self.note_obligation_cause_code(err,
1286 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1287 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1289 &format!("required because of the requirements on the impl of `{}` for `{}`",
1291 parent_trait_ref.0.self_ty()));
1292 let parent_predicate = parent_trait_ref.to_predicate();
1293 self.note_obligation_cause_code(err,
1297 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1299 &format!("the requirement `{}` appears on the impl method \
1300 but not on the corresponding trait method",
1303 ObligationCauseCode::ReturnType(_) |
1304 ObligationCauseCode::BlockTailExpression(_) => (),
1308 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1309 let current_limit = self.tcx.sess.recursion_limit.get();
1310 let suggested_limit = current_limit * 2;
1311 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",