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 session::DiagnosticMessageId;
40 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
41 use ty::error::ExpectedFound;
43 use ty::fold::TypeFolder;
45 use ty::SubtypePredicate;
46 use util::nodemap::{FxHashMap, FxHashSet};
48 use syntax_pos::{DUMMY_SP, Span};
50 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
51 pub fn report_fulfillment_errors(&self,
52 errors: &Vec<FulfillmentError<'tcx>>,
53 body_id: Option<hir::BodyId>) {
55 struct ErrorDescriptor<'tcx> {
56 predicate: ty::Predicate<'tcx>,
57 index: Option<usize>, // None if this is an old error
60 let mut error_map : FxHashMap<_, _> =
61 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
62 (span, predicates.iter().map(|predicate| ErrorDescriptor {
63 predicate: predicate.clone(),
68 for (index, error) in errors.iter().enumerate() {
69 error_map.entry(error.obligation.cause.span).or_insert(Vec::new()).push(
71 predicate: error.obligation.predicate.clone(),
75 self.reported_trait_errors.borrow_mut()
76 .entry(error.obligation.cause.span).or_insert(Vec::new())
77 .push(error.obligation.predicate.clone());
80 // We do this in 2 passes because we want to display errors in order, tho
81 // maybe it *is* better to sort errors by span or something.
82 let mut is_suppressed: Vec<bool> = errors.iter().map(|_| false).collect();
83 for (_, error_set) in error_map.iter() {
84 // We want to suppress "duplicate" errors with the same span.
85 for error in error_set {
86 if let Some(index) = error.index {
87 // Suppress errors that are either:
88 // 1) strictly implied by another error.
89 // 2) implied by an error with a smaller index.
90 for error2 in error_set {
91 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
92 // Avoid errors being suppressed by already-suppressed
93 // errors, to prevent all errors from being suppressed
98 if self.error_implies(&error2.predicate, &error.predicate) &&
99 !(error2.index >= error.index &&
100 self.error_implies(&error.predicate, &error2.predicate))
102 info!("skipping {:?} (implied by {:?})", error, error2);
103 is_suppressed[index] = true;
111 for (error, suppressed) in errors.iter().zip(is_suppressed) {
113 self.report_fulfillment_error(error, body_id);
118 // returns if `cond` not occurring implies that `error` does not occur - i.e. that
119 // `error` occurring implies that `cond` occurs.
120 fn error_implies(&self,
121 cond: &ty::Predicate<'tcx>,
122 error: &ty::Predicate<'tcx>)
129 let (cond, error) = match (cond, error) {
130 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
133 // FIXME: make this work in other cases too.
138 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
139 if let ty::Predicate::Trait(implication) = implication {
140 let error = error.to_poly_trait_ref();
141 let implication = implication.to_poly_trait_ref();
142 // FIXME: I'm just not taking associated types at all here.
143 // Eventually I'll need to implement param-env-aware
144 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
145 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
146 if let Ok(_) = self.can_sub(param_env, error, implication) {
147 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
156 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
157 body_id: Option<hir::BodyId>) {
158 debug!("report_fulfillment_errors({:?})", error);
160 FulfillmentErrorCode::CodeSelectionError(ref e) => {
161 self.report_selection_error(&error.obligation, e);
163 FulfillmentErrorCode::CodeProjectionError(ref e) => {
164 self.report_projection_error(&error.obligation, e);
166 FulfillmentErrorCode::CodeAmbiguity => {
167 self.maybe_report_ambiguity(&error.obligation, body_id);
169 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
170 self.report_mismatched_types(&error.obligation.cause,
171 expected_found.expected,
172 expected_found.found,
179 fn report_projection_error(&self,
180 obligation: &PredicateObligation<'tcx>,
181 error: &MismatchedProjectionTypes<'tcx>)
184 self.resolve_type_vars_if_possible(&obligation.predicate);
186 if predicate.references_error() {
192 let mut err = &error.err;
193 let mut values = None;
195 // try to find the mismatched types to report the error with.
197 // this can fail if the problem was higher-ranked, in which
198 // cause I have no idea for a good error message.
199 if let ty::Predicate::Projection(ref data) = predicate {
200 let mut selcx = SelectionContext::new(self);
201 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
202 obligation.cause.span,
203 infer::LateBoundRegionConversionTime::HigherRankedType,
205 let normalized = super::normalize_projection_type(
207 obligation.param_env,
209 obligation.cause.clone(),
212 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
213 .eq(normalized.value, data.ty) {
214 values = Some(infer::ValuePairs::Types(ExpectedFound {
215 expected: normalized.value,
223 let msg = format!("type mismatch resolving `{}`", predicate);
224 let error_id = (DiagnosticMessageId::ErrorId(271),
225 Some(obligation.cause.span), msg.clone());
226 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
228 let mut diag = struct_span_err!(
229 self.tcx.sess, obligation.cause.span, E0271,
230 "type mismatch resolving `{}`", predicate
232 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
233 self.note_obligation_cause(&mut diag, obligation);
239 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
240 /// returns the fuzzy category of a given type, or None
241 /// if the type can be equated to any type.
242 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
244 ty::TyBool => Some(0),
245 ty::TyChar => Some(1),
246 ty::TyStr => Some(2),
247 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
248 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
249 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
250 ty::TyArray(..) | ty::TySlice(..) => Some(6),
251 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
252 ty::TyDynamic(..) => Some(8),
253 ty::TyClosure(..) => Some(9),
254 ty::TyTuple(..) => Some(10),
255 ty::TyProjection(..) => Some(11),
256 ty::TyParam(..) => Some(12),
257 ty::TyAnon(..) => Some(13),
258 ty::TyNever => Some(14),
259 ty::TyAdt(adt, ..) => match adt.adt_kind() {
260 AdtKind::Struct => Some(15),
261 AdtKind::Union => Some(16),
262 AdtKind::Enum => Some(17),
264 ty::TyGenerator(..) => Some(18),
265 ty::TyForeign(..) => Some(19),
266 ty::TyInfer(..) | ty::TyError => None
270 match (type_category(a), type_category(b)) {
271 (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
272 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == def_b,
275 // infer and error can be equated to all types
280 fn impl_similar_to(&self,
281 trait_ref: ty::PolyTraitRef<'tcx>,
282 obligation: &PredicateObligation<'tcx>)
286 let param_env = obligation.param_env;
287 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
288 let trait_self_ty = trait_ref.self_ty();
290 let mut self_match_impls = vec![];
291 let mut fuzzy_match_impls = vec![];
293 self.tcx.for_each_relevant_impl(
294 trait_ref.def_id, trait_self_ty, |def_id| {
295 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
296 let impl_trait_ref = tcx
297 .impl_trait_ref(def_id)
299 .subst(tcx, impl_substs);
301 let impl_self_ty = impl_trait_ref.self_ty();
303 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
304 self_match_impls.push(def_id);
306 if trait_ref.substs.types().skip(1)
307 .zip(impl_trait_ref.substs.types().skip(1))
308 .all(|(u,v)| self.fuzzy_match_tys(u, v))
310 fuzzy_match_impls.push(def_id);
315 let impl_def_id = if self_match_impls.len() == 1 {
317 } else if fuzzy_match_impls.len() == 1 {
323 if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
330 fn on_unimplemented_note(
332 trait_ref: ty::PolyTraitRef<'tcx>,
333 obligation: &PredicateObligation<'tcx>) ->
336 let def_id = self.impl_similar_to(trait_ref, obligation)
337 .unwrap_or(trait_ref.def_id());
338 let trait_ref = *trait_ref.skip_binder();
342 let mut flags = vec![];
343 let direct = match obligation.cause.code {
344 ObligationCauseCode::BuiltinDerivedObligation(..) |
345 ObligationCauseCode::ImplDerivedObligation(..) => false,
349 // this is a "direct", user-specified, rather than derived,
351 flags.push(("direct", None));
354 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
355 // FIXME: maybe also have some way of handling methods
356 // from other traits? That would require name resolution,
357 // which we might want to be some sort of hygienic.
359 // Currently I'm leaving it for what I need for `try`.
360 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
361 method = self.tcx.item_name(item);
362 flags.push(("from_method", None));
363 flags.push(("from_method", Some(&*method)));
367 if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
368 desugaring = k.as_symbol().as_str();
369 flags.push(("from_desugaring", None));
370 flags.push(("from_desugaring", Some(&*desugaring)));
373 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
374 self.tcx, trait_ref.def_id, def_id
376 command.evaluate(self.tcx, trait_ref, &flags)
378 OnUnimplementedNote::empty()
382 fn find_similar_impl_candidates(&self,
383 trait_ref: ty::PolyTraitRef<'tcx>)
384 -> Vec<ty::TraitRef<'tcx>>
386 let simp = fast_reject::simplify_type(self.tcx,
387 trait_ref.skip_binder().self_ty(),
389 let mut impl_candidates = Vec::new();
392 Some(simp) => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
393 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
394 let imp_simp = fast_reject::simplify_type(self.tcx,
397 if let Some(imp_simp) = imp_simp {
398 if simp != imp_simp {
402 impl_candidates.push(imp);
404 None => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
405 impl_candidates.push(
406 self.tcx.impl_trait_ref(def_id).unwrap());
412 fn report_similar_impl_candidates(&self,
413 impl_candidates: Vec<ty::TraitRef<'tcx>>,
414 err: &mut DiagnosticBuilder)
416 if impl_candidates.is_empty() {
420 let end = if impl_candidates.len() <= 5 {
421 impl_candidates.len()
425 err.help(&format!("the following implementations were found:{}{}",
426 &impl_candidates[0..end].iter().map(|candidate| {
427 format!("\n {:?}", candidate)
428 }).collect::<String>(),
429 if impl_candidates.len() > 5 {
430 format!("\nand {} others", impl_candidates.len() - 4)
437 /// Reports that an overflow has occurred and halts compilation. We
438 /// halt compilation unconditionally because it is important that
439 /// overflows never be masked -- they basically represent computations
440 /// whose result could not be truly determined and thus we can't say
441 /// if the program type checks or not -- and they are unusual
442 /// occurrences in any case.
443 pub fn report_overflow_error<T>(&self,
444 obligation: &Obligation<'tcx, T>,
445 suggest_increasing_limit: bool) -> !
446 where T: fmt::Display + TypeFoldable<'tcx>
449 self.resolve_type_vars_if_possible(&obligation.predicate);
450 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
451 "overflow evaluating the requirement `{}`",
454 if suggest_increasing_limit {
455 self.suggest_new_overflow_limit(&mut err);
458 self.note_obligation_cause(&mut err, obligation);
461 self.tcx.sess.abort_if_errors();
465 /// Reports that a cycle was detected which led to overflow and halts
466 /// compilation. This is equivalent to `report_overflow_error` except
467 /// that we can give a more helpful error message (and, in particular,
468 /// we do not suggest increasing the overflow limit, which is not
470 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
471 let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
472 assert!(cycle.len() > 0);
474 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
476 self.report_overflow_error(&cycle[0], false);
479 pub fn report_extra_impl_obligation(&self,
481 item_name: ast::Name,
482 _impl_item_def_id: DefId,
483 trait_item_def_id: DefId,
484 requirement: &fmt::Display,
485 lint_id: Option<ast::NodeId>) // (*)
486 -> DiagnosticBuilder<'tcx>
488 // (*) This parameter is temporary and used only for phasing
489 // in the bug fix to #18937. If it is `Some`, it has a kind of
490 // weird effect -- the diagnostic is reported as a lint, and
491 // the builder which is returned is marked as canceled.
493 let msg = "impl has stricter requirements than trait";
494 let mut err = match lint_id {
496 self.tcx.struct_span_lint_node(EXTRA_REQUIREMENT_IN_IMPL,
502 struct_span_err!(self.tcx.sess,
509 if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
510 let span = self.tcx.sess.codemap().def_span(trait_item_span);
511 err.span_label(span, format!("definition of `{}` from trait", item_name));
516 format!("impl has extra requirement {}", requirement));
522 /// Get the parent trait chain start
523 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
525 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
526 let parent_trait_ref = self.resolve_type_vars_if_possible(
527 &data.parent_trait_ref);
528 match self.get_parent_trait_ref(&data.parent_code) {
530 None => Some(format!("{}", parent_trait_ref.0.self_ty())),
537 pub fn report_selection_error(&self,
538 obligation: &PredicateObligation<'tcx>,
539 error: &SelectionError<'tcx>)
541 let span = obligation.cause.span;
543 let mut err = match *error {
544 SelectionError::Unimplemented => {
545 if let ObligationCauseCode::CompareImplMethodObligation {
546 item_name, impl_item_def_id, trait_item_def_id, lint_id
547 } = obligation.cause.code {
548 self.report_extra_impl_obligation(
553 &format!("`{}`", obligation.predicate),
558 match obligation.predicate {
559 ty::Predicate::Trait(ref trait_predicate) => {
560 let trait_predicate =
561 self.resolve_type_vars_if_possible(trait_predicate);
563 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
566 let trait_ref = trait_predicate.to_poly_trait_ref();
567 let (post_message, pre_message) =
568 self.get_parent_trait_ref(&obligation.cause.code)
569 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
570 .unwrap_or((String::new(), String::new()));
572 let OnUnimplementedNote { message, label }
573 = self.on_unimplemented_note(trait_ref, obligation);
574 let have_alt_message = message.is_some() || label.is_some();
576 let mut err = struct_span_err!(
581 message.unwrap_or_else(|| {
582 format!("the trait bound `{}` is not satisfied{}",
583 trait_ref.to_predicate(), post_message)
586 if let Some(ref s) = label {
587 // If it has a custom "#[rustc_on_unimplemented]"
588 // error message, let's display it as the label!
589 err.span_label(span, s.as_str());
590 err.help(&format!("{}the trait `{}` is not implemented for `{}`",
593 trait_ref.self_ty()));
596 &*format!("{}the trait `{}` is not implemented for `{}`",
599 trait_ref.self_ty()));
602 // Try to report a help message
603 if !trait_ref.has_infer_types() &&
604 self.predicate_can_apply(obligation.param_env, trait_ref) {
605 // If a where-clause may be useful, remind the
606 // user that they can add it.
608 // don't display an on-unimplemented note, as
609 // these notes will often be of the form
610 // "the type `T` can't be frobnicated"
611 // which is somewhat confusing.
612 err.help(&format!("consider adding a `where {}` bound",
613 trait_ref.to_predicate()));
614 } else if !have_alt_message {
615 // Can't show anything else useful, try to find similar impls.
616 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
617 self.report_similar_impl_candidates(impl_candidates, &mut err);
623 ty::Predicate::Subtype(ref predicate) => {
624 // Errors for Subtype predicates show up as
625 // `FulfillmentErrorCode::CodeSubtypeError`,
626 // not selection error.
627 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
630 ty::Predicate::Equate(ref predicate) => {
631 let predicate = self.resolve_type_vars_if_possible(predicate);
632 let err = self.equality_predicate(&obligation.cause,
633 obligation.param_env,
634 &predicate).err().unwrap();
635 struct_span_err!(self.tcx.sess, span, E0278,
636 "the requirement `{}` is not satisfied (`{}`)",
640 ty::Predicate::RegionOutlives(ref predicate) => {
641 let predicate = self.resolve_type_vars_if_possible(predicate);
642 let err = self.region_outlives_predicate(&obligation.cause,
643 &predicate).err().unwrap();
644 struct_span_err!(self.tcx.sess, span, E0279,
645 "the requirement `{}` is not satisfied (`{}`)",
649 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
651 self.resolve_type_vars_if_possible(&obligation.predicate);
652 struct_span_err!(self.tcx.sess, span, E0280,
653 "the requirement `{}` is not satisfied",
657 ty::Predicate::ObjectSafe(trait_def_id) => {
658 let violations = self.tcx.object_safety_violations(trait_def_id);
659 self.tcx.report_object_safety_error(span,
664 ty::Predicate::ClosureKind(closure_def_id, kind) => {
665 let found_kind = self.closure_kind(closure_def_id).unwrap();
666 let closure_span = self.tcx.hir.span_if_local(closure_def_id).unwrap();
667 let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
668 let mut err = struct_span_err!(
669 self.tcx.sess, closure_span, E0525,
670 "expected a closure that implements the `{}` trait, \
671 but this closure only implements `{}`",
676 obligation.cause.span,
677 format!("the requirement to implement `{}` derives from here", kind));
679 // Additional context information explaining why the closure only implements
680 // a particular trait.
681 if let Some(tables) = self.in_progress_tables {
682 let tables = tables.borrow();
683 let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
684 match tables.closure_kinds().get(closure_hir_id) {
685 Some(&(ty::ClosureKind::FnOnce, Some((span, name)))) => {
686 err.span_note(span, &format!(
687 "closure is `FnOnce` because it moves the \
688 variable `{}` out of its environment", name));
690 Some(&(ty::ClosureKind::FnMut, Some((span, name)))) => {
691 err.span_note(span, &format!(
692 "closure is `FnMut` because it mutates the \
693 variable `{}` here", name));
703 ty::Predicate::WellFormed(ty) => {
704 // WF predicates cannot themselves make
705 // errors. They can only block due to
706 // ambiguity; otherwise, they always
707 // degenerate into other obligations
709 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
712 ty::Predicate::ConstEvaluatable(..) => {
713 // Errors for `ConstEvaluatable` predicates show up as
714 // `SelectionError::ConstEvalFailure`,
715 // not `Unimplemented`.
717 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
722 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
723 let found_trait_ref = self.resolve_type_vars_if_possible(&*found_trait_ref);
724 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
725 if expected_trait_ref.self_ty().references_error() {
728 let found_trait_ty = found_trait_ref.self_ty();
730 let found_did = found_trait_ty.ty_to_def_id();
731 let found_span = found_did.and_then(|did| {
732 self.tcx.hir.span_if_local(did)
736 match found_trait_ref.skip_binder().substs.type_at(1).sty {
737 ty::TyTuple(ref tys, _) => tys.len(),
740 let (expected_tys, expected_ty_count) =
741 match expected_trait_ref.skip_binder().substs.type_at(1).sty {
742 ty::TyTuple(ref tys, _) =>
743 (tys.iter().map(|t| &t.sty).collect(), tys.len()),
744 ref sty => (vec![sty], 1),
746 if found_ty_count == expected_ty_count {
747 self.report_closure_arg_mismatch(span,
752 let expected_tuple = if expected_ty_count == 1 {
753 expected_tys.first().and_then(|t| {
754 if let &&ty::TyTuple(ref tuptys, _) = t {
764 // FIXME(#44150): Expand this to "N args expected but a N-tuple found."
765 // Type of the 1st expected argument is somehow provided as type of a
766 // found one in that case.
769 // [1i32, 2, 3].sort_by(|(a, b)| ..)
771 // // expected_trait_ref: std::ops::FnMut<(&i32, &i32)>
772 // // found_trait_ref: std::ops::FnMut<(&i32,)>
775 let (closure_span, closure_args) = found_did
776 .and_then(|did| self.tcx.hir.get_if_local(did))
778 if let hir::map::NodeExpr(
780 node: hir::ExprClosure(_, ref decl, id, span, _),
784 let ty_snips = decl.inputs.iter()
786 self.tcx.sess.codemap().span_to_snippet(ty.span).ok()
788 // filter out dummy spans
789 if snip == "," || snip == "|" {
796 .collect::<Vec<Option<String>>>();
798 let body = self.tcx.hir.body(id);
799 let pat_snips = body.arguments.iter()
801 self.tcx.sess.codemap().span_to_snippet(arg.pat.span).ok())
802 .collect::<Option<Vec<String>>>();
804 Some((span, pat_snips, ty_snips))
809 .map(|(span, pat, ty)| (Some(span), Some((pat, ty))))
810 .unwrap_or((None, None));
811 let closure_args = closure_args.and_then(|(pat, ty)| Some((pat?, ty)));
813 self.report_arg_count_mismatch(
815 closure_span.or(found_span),
820 found_trait_ty.is_closure()
825 TraitNotObjectSafe(did) => {
826 let violations = self.tcx.object_safety_violations(did);
827 self.tcx.report_object_safety_error(span, did,
831 ConstEvalFailure(ref err) => {
832 if let const_val::ErrKind::TypeckError = err.kind {
835 err.struct_error(self.tcx, span, "constant expression")
838 self.note_obligation_cause(&mut err, obligation);
842 fn report_arg_count_mismatch(
845 found_span: Option<Span>,
847 expected_tuple: Option<usize>,
849 closure_args: Option<(Vec<String>, Vec<Option<String>>)>,
851 ) -> DiagnosticBuilder<'tcx> {
852 use std::borrow::Cow;
854 let kind = if is_closure { "closure" } else { "function" };
856 let args_str = |n, distinct| format!(
859 if distinct && n >= 2 { "distinct " } else { "" },
860 if n == 1 { "" } else { "s" },
863 let expected_str = if let Some(n) = expected_tuple {
864 assert!(expected == 1);
865 if closure_args.as_ref().map(|&(ref pats, _)| pats.len()) == Some(n) {
866 Cow::from("a single tuple as argument")
868 // be verbose when numbers differ
869 Cow::from(format!("a single {}-tuple as argument", n))
872 Cow::from(args_str(expected, false))
875 let found_str = if expected_tuple.is_some() {
876 args_str(found, true)
878 args_str(found, false)
882 let mut err = struct_span_err!(self.tcx.sess, span, E0593,
883 "{} is expected to take {}, but it takes {}",
892 "expected {} that takes {}",
898 if let Some(span) = found_span {
899 if let (Some(expected_tuple), Some((pats, tys))) = (expected_tuple, closure_args) {
900 if expected_tuple != found || pats.len() != found {
901 err.span_label(span, format!("takes {}", found_str));
907 // add type annotations if available
908 if tys.iter().any(|ty| ty.is_some()) {
911 tys.into_iter().map(|ty| if let Some(ty) = ty {
915 }).collect::<Vec<String>>().join(", ")
924 "consider changing the closure to accept a tuple",
929 err.span_label(span, format!("takes {}", found_str));
936 fn report_closure_arg_mismatch(&self,
938 found_span: Option<Span>,
939 expected_ref: ty::PolyTraitRef<'tcx>,
940 found: ty::PolyTraitRef<'tcx>)
941 -> DiagnosticBuilder<'tcx>
943 fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
944 trait_ref: &ty::TraitRef<'tcx>) -> String {
945 let inputs = trait_ref.substs.type_at(1);
946 let sig = if let ty::TyTuple(inputs, _) = inputs.sty {
948 inputs.iter().map(|&x| x),
949 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
951 hir::Unsafety::Normal,
952 ::syntax::abi::Abi::Rust
956 ::std::iter::once(inputs),
957 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
959 hir::Unsafety::Normal,
960 ::syntax::abi::Abi::Rust
963 format!("{}", ty::Binder(sig))
966 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
967 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
968 "type mismatch in {} arguments",
969 if argument_is_closure { "closure" } else { "function" });
971 let found_str = format!(
972 "expected signature of `{}`",
973 build_fn_sig_string(self.tcx, found.skip_binder())
975 err.span_label(span, found_str);
977 let found_span = found_span.unwrap_or(span);
978 let expected_str = format!(
979 "found signature of `{}`",
980 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
982 err.span_label(found_span, expected_str);
988 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
989 pub fn recursive_type_with_infinite_size_error(self,
991 -> DiagnosticBuilder<'tcx>
993 assert!(type_def_id.is_local());
994 let span = self.hir.span_if_local(type_def_id).unwrap();
995 let span = self.sess.codemap().def_span(span);
996 let mut err = struct_span_err!(self.sess, span, E0072,
997 "recursive type `{}` has infinite size",
998 self.item_path_str(type_def_id));
999 err.span_label(span, "recursive type has infinite size");
1000 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1001 at some point to make `{}` representable",
1002 self.item_path_str(type_def_id)));
1006 pub fn report_object_safety_error(self,
1008 trait_def_id: DefId,
1009 violations: Vec<ObjectSafetyViolation>)
1010 -> DiagnosticBuilder<'tcx>
1012 let trait_str = self.item_path_str(trait_def_id);
1013 let span = self.sess.codemap().def_span(span);
1014 let mut err = struct_span_err!(
1015 self.sess, span, E0038,
1016 "the trait `{}` cannot be made into an object",
1018 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1020 let mut reported_violations = FxHashSet();
1021 for violation in violations {
1022 if !reported_violations.insert(violation.clone()) {
1025 err.note(&violation.error_msg());
1031 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1032 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1033 body_id: Option<hir::BodyId>) {
1034 // Unable to successfully determine, probably means
1035 // insufficient type information, but could mean
1036 // ambiguous impls. The latter *ought* to be a
1037 // coherence violation, so we don't report it here.
1039 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1040 let span = obligation.cause.span;
1042 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1046 // Ambiguity errors are often caused as fallout from earlier
1047 // errors. So just ignore them if this infcx is tainted.
1048 if self.is_tainted_by_errors() {
1053 ty::Predicate::Trait(ref data) => {
1054 let trait_ref = data.to_poly_trait_ref();
1055 let self_ty = trait_ref.self_ty();
1056 if predicate.references_error() {
1059 // Typically, this ambiguity should only happen if
1060 // there are unresolved type inference variables
1061 // (otherwise it would suggest a coherence
1062 // failure). But given #21974 that is not necessarily
1063 // the case -- we can have multiple where clauses that
1064 // are only distinguished by a region, which results
1065 // in an ambiguity even when all types are fully
1066 // known, since we don't dispatch based on region
1069 // This is kind of a hack: it frequently happens that some earlier
1070 // error prevents types from being fully inferred, and then we get
1071 // a bunch of uninteresting errors saying something like "<generic
1072 // #0> doesn't implement Sized". It may even be true that we
1073 // could just skip over all checks where the self-ty is an
1074 // inference variable, but I was afraid that there might be an
1075 // inference variable created, registered as an obligation, and
1076 // then never forced by writeback, and hence by skipping here we'd
1077 // be ignoring the fact that we don't KNOW the type works
1078 // out. Though even that would probably be harmless, given that
1079 // we're only talking about builtin traits, which are known to be
1080 // inhabited. But in any case I just threw in this check for
1081 // has_errors() to be sure that compilation isn't happening
1082 // anyway. In that case, why inundate the user.
1083 if !self.tcx.sess.has_errors() {
1085 self.tcx.lang_items().sized_trait()
1086 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1088 self.need_type_info(body_id, span, self_ty);
1090 let mut err = struct_span_err!(self.tcx.sess,
1092 "type annotations required: \
1093 cannot resolve `{}`",
1095 self.note_obligation_cause(&mut err, obligation);
1101 ty::Predicate::WellFormed(ty) => {
1102 // Same hacky approach as above to avoid deluging user
1103 // with error messages.
1104 if !ty.references_error() && !self.tcx.sess.has_errors() {
1105 self.need_type_info(body_id, span, ty);
1109 ty::Predicate::Subtype(ref data) => {
1110 if data.references_error() || self.tcx.sess.has_errors() {
1111 // no need to overload user in such cases
1113 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1114 // both must be type variables, or the other would've been instantiated
1115 assert!(a.is_ty_var() && b.is_ty_var());
1116 self.need_type_info(body_id,
1117 obligation.cause.span,
1123 if !self.tcx.sess.has_errors() {
1124 let mut err = struct_span_err!(self.tcx.sess,
1125 obligation.cause.span, E0284,
1126 "type annotations required: \
1127 cannot resolve `{}`",
1129 self.note_obligation_cause(&mut err, obligation);
1136 /// Returns whether the trait predicate may apply for *some* assignment
1137 /// to the type parameters.
1138 fn predicate_can_apply(&self,
1139 param_env: ty::ParamEnv<'tcx>,
1140 pred: ty::PolyTraitRef<'tcx>)
1142 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1143 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1144 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1147 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1148 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1150 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1151 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
1152 let infcx = self.infcx;
1153 self.var_map.entry(ty).or_insert_with(||
1155 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1157 ty.super_fold_with(self)
1163 let mut selcx = SelectionContext::new(self);
1165 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1167 var_map: FxHashMap()
1170 let cleaned_pred = super::project::normalize(
1173 ObligationCause::dummy(),
1177 let obligation = Obligation::new(
1178 ObligationCause::dummy(),
1180 cleaned_pred.to_predicate()
1183 selcx.evaluate_obligation(&obligation)
1187 fn note_obligation_cause<T>(&self,
1188 err: &mut DiagnosticBuilder,
1189 obligation: &Obligation<'tcx, T>)
1190 where T: fmt::Display
1192 self.note_obligation_cause_code(err,
1193 &obligation.predicate,
1194 &obligation.cause.code);
1197 fn note_obligation_cause_code<T>(&self,
1198 err: &mut DiagnosticBuilder,
1200 cause_code: &ObligationCauseCode<'tcx>)
1201 where T: fmt::Display
1205 ObligationCauseCode::ExprAssignable |
1206 ObligationCauseCode::MatchExpressionArm { .. } |
1207 ObligationCauseCode::IfExpression |
1208 ObligationCauseCode::IfExpressionWithNoElse |
1209 ObligationCauseCode::EquatePredicate |
1210 ObligationCauseCode::MainFunctionType |
1211 ObligationCauseCode::StartFunctionType |
1212 ObligationCauseCode::IntrinsicType |
1213 ObligationCauseCode::MethodReceiver |
1214 ObligationCauseCode::ReturnNoExpression |
1215 ObligationCauseCode::MiscObligation => {
1217 ObligationCauseCode::SliceOrArrayElem => {
1218 err.note("slice and array elements must have `Sized` type");
1220 ObligationCauseCode::TupleElem => {
1221 err.note("only the last element of a tuple may have a dynamically sized type");
1223 ObligationCauseCode::ProjectionWf(data) => {
1224 err.note(&format!("required so that the projection `{}` is well-formed",
1227 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1228 err.note(&format!("required so that reference `{}` does not outlive its referent",
1231 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1232 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1234 region, object_ty));
1236 ObligationCauseCode::ItemObligation(item_def_id) => {
1237 let item_name = tcx.item_path_str(item_def_id);
1238 err.note(&format!("required by `{}`", item_name));
1240 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1241 err.note(&format!("required for the cast to the object type `{}`",
1242 self.ty_to_string(object_ty)));
1244 ObligationCauseCode::RepeatVec => {
1245 err.note("the `Copy` trait is required because the \
1246 repeated element will be copied");
1248 ObligationCauseCode::VariableType(_) => {
1249 err.note("all local variables must have a statically known size");
1251 ObligationCauseCode::SizedReturnType => {
1252 err.note("the return type of a function must have a \
1253 statically known size");
1255 ObligationCauseCode::AssignmentLhsSized => {
1256 err.note("the left-hand-side of an assignment must have a statically known size");
1258 ObligationCauseCode::TupleInitializerSized => {
1259 err.note("tuples must have a statically known size to be initialized");
1261 ObligationCauseCode::StructInitializerSized => {
1262 err.note("structs must have a statically known size to be initialized");
1264 ObligationCauseCode::FieldSized(ref item) => {
1266 AdtKind::Struct => {
1267 err.note("only the last field of a struct may have a dynamically \
1271 err.note("no field of a union may have a dynamically sized type");
1274 err.note("no field of an enum variant may have a dynamically sized type");
1278 ObligationCauseCode::ConstSized => {
1279 err.note("constant expressions must have a statically known size");
1281 ObligationCauseCode::SharedStatic => {
1282 err.note("shared static variables must have a type that implements `Sync`");
1284 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1285 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1286 err.note(&format!("required because it appears within the type `{}`",
1287 parent_trait_ref.0.self_ty()));
1288 let parent_predicate = parent_trait_ref.to_predicate();
1289 self.note_obligation_cause_code(err,
1293 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1294 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1296 &format!("required because of the requirements on the impl of `{}` for `{}`",
1298 parent_trait_ref.0.self_ty()));
1299 let parent_predicate = parent_trait_ref.to_predicate();
1300 self.note_obligation_cause_code(err,
1304 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1306 &format!("the requirement `{}` appears on the impl method \
1307 but not on the corresponding trait method",
1310 ObligationCauseCode::ReturnType(_) |
1311 ObligationCauseCode::BlockTailExpression(_) => (),
1315 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1316 let current_limit = self.tcx.sess.recursion_limit.get();
1317 let suggested_limit = current_limit * 2;
1318 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",