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;
38 use session::DiagnosticMessageId;
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 msg = format!("type mismatch resolving `{}`", predicate);
223 let error_id = (DiagnosticMessageId::ErrorId(271),
224 Some(obligation.cause.span), msg.clone());
225 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
227 let mut diag = struct_span_err!(
228 self.tcx.sess, obligation.cause.span, E0271,
229 "type mismatch resolving `{}`", predicate
231 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
232 self.note_obligation_cause(&mut diag, obligation);
238 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
239 /// returns the fuzzy category of a given type, or None
240 /// if the type can be equated to any type.
241 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
243 ty::TyBool => Some(0),
244 ty::TyChar => Some(1),
245 ty::TyStr => Some(2),
246 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
247 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
248 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
249 ty::TyArray(..) | ty::TySlice(..) => Some(6),
250 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
251 ty::TyDynamic(..) => Some(8),
252 ty::TyClosure(..) => Some(9),
253 ty::TyTuple(..) => Some(10),
254 ty::TyProjection(..) => Some(11),
255 ty::TyParam(..) => Some(12),
256 ty::TyAnon(..) => Some(13),
257 ty::TyNever => Some(14),
258 ty::TyAdt(adt, ..) => match adt.adt_kind() {
259 AdtKind::Struct => Some(15),
260 AdtKind::Union => Some(16),
261 AdtKind::Enum => Some(17),
263 ty::TyGenerator(..) => Some(18),
264 ty::TyForeign(..) => Some(19),
265 ty::TyGeneratorWitness(..) => Some(20),
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".to_string(), 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".to_string(), None));
363 flags.push(("from_method".to_string(), Some(method.to_string())));
367 if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
368 desugaring = k.as_symbol().as_str();
369 flags.push(("from_desugaring".to_string(), None));
370 flags.push(("from_desugaring".to_string(), Some(desugaring.to_string())));
372 let generics = self.tcx.generics_of(def_id);
373 let self_ty = trait_ref.self_ty();
374 let self_ty_str = self_ty.to_string();
375 flags.push(("_Self".to_string(), Some(self_ty_str.clone())));
377 for param in generics.types.iter() {
378 let name = param.name.as_str().to_string();
379 let ty = trait_ref.substs.type_for_def(param);
380 let ty_str = ty.to_string();
381 flags.push((name.clone(),
382 Some(ty_str.clone())));
385 if let Some(true) = self_ty.ty_to_def_id().map(|def_id| def_id.is_local()) {
386 flags.push(("crate_local".to_string(), None));
389 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
390 self.tcx, trait_ref.def_id, def_id
392 command.evaluate(self.tcx, trait_ref, &flags[..])
394 OnUnimplementedNote::empty()
398 fn find_similar_impl_candidates(&self,
399 trait_ref: ty::PolyTraitRef<'tcx>)
400 -> Vec<ty::TraitRef<'tcx>>
402 let simp = fast_reject::simplify_type(self.tcx,
403 trait_ref.skip_binder().self_ty(),
405 let mut impl_candidates = Vec::new();
408 Some(simp) => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
409 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
410 let imp_simp = fast_reject::simplify_type(self.tcx,
413 if let Some(imp_simp) = imp_simp {
414 if simp != imp_simp {
418 impl_candidates.push(imp);
420 None => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
421 impl_candidates.push(
422 self.tcx.impl_trait_ref(def_id).unwrap());
428 fn report_similar_impl_candidates(&self,
429 impl_candidates: Vec<ty::TraitRef<'tcx>>,
430 err: &mut DiagnosticBuilder)
432 if impl_candidates.is_empty() {
436 let end = if impl_candidates.len() <= 5 {
437 impl_candidates.len()
441 err.help(&format!("the following implementations were found:{}{}",
442 &impl_candidates[0..end].iter().map(|candidate| {
443 format!("\n {:?}", candidate)
444 }).collect::<String>(),
445 if impl_candidates.len() > 5 {
446 format!("\nand {} others", impl_candidates.len() - 4)
453 /// Reports that an overflow has occurred and halts compilation. We
454 /// halt compilation unconditionally because it is important that
455 /// overflows never be masked -- they basically represent computations
456 /// whose result could not be truly determined and thus we can't say
457 /// if the program type checks or not -- and they are unusual
458 /// occurrences in any case.
459 pub fn report_overflow_error<T>(&self,
460 obligation: &Obligation<'tcx, T>,
461 suggest_increasing_limit: bool) -> !
462 where T: fmt::Display + TypeFoldable<'tcx>
465 self.resolve_type_vars_if_possible(&obligation.predicate);
466 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
467 "overflow evaluating the requirement `{}`",
470 if suggest_increasing_limit {
471 self.suggest_new_overflow_limit(&mut err);
474 self.note_obligation_cause(&mut err, obligation);
477 self.tcx.sess.abort_if_errors();
481 /// Reports that a cycle was detected which led to overflow and halts
482 /// compilation. This is equivalent to `report_overflow_error` except
483 /// that we can give a more helpful error message (and, in particular,
484 /// we do not suggest increasing the overflow limit, which is not
486 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
487 let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
488 assert!(cycle.len() > 0);
490 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
492 self.report_overflow_error(&cycle[0], false);
495 pub fn report_extra_impl_obligation(&self,
497 item_name: ast::Name,
498 _impl_item_def_id: DefId,
499 trait_item_def_id: DefId,
500 requirement: &fmt::Display)
501 -> DiagnosticBuilder<'tcx>
503 let msg = "impl has stricter requirements than trait";
504 let sp = self.tcx.sess.codemap().def_span(error_span);
506 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
508 if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
509 let span = self.tcx.sess.codemap().def_span(trait_item_span);
510 err.span_label(span, format!("definition of `{}` from trait", item_name));
513 err.span_label(sp, format!("impl has extra requirement {}", requirement));
519 /// Get the parent trait chain start
520 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
522 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
523 let parent_trait_ref = self.resolve_type_vars_if_possible(
524 &data.parent_trait_ref);
525 match self.get_parent_trait_ref(&data.parent_code) {
527 None => Some(format!("{}", parent_trait_ref.0.self_ty())),
534 pub fn report_selection_error(&self,
535 obligation: &PredicateObligation<'tcx>,
536 error: &SelectionError<'tcx>)
538 let span = obligation.cause.span;
540 let mut err = match *error {
541 SelectionError::Unimplemented => {
542 if let ObligationCauseCode::CompareImplMethodObligation {
543 item_name, impl_item_def_id, trait_item_def_id,
544 } = obligation.cause.code {
545 self.report_extra_impl_obligation(
550 &format!("`{}`", obligation.predicate))
554 match obligation.predicate {
555 ty::Predicate::Trait(ref trait_predicate) => {
556 let trait_predicate =
557 self.resolve_type_vars_if_possible(trait_predicate);
559 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
562 let trait_ref = trait_predicate.to_poly_trait_ref();
563 let (post_message, pre_message) =
564 self.get_parent_trait_ref(&obligation.cause.code)
565 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
566 .unwrap_or((String::new(), String::new()));
568 let OnUnimplementedNote { message, label, note }
569 = self.on_unimplemented_note(trait_ref, obligation);
570 let have_alt_message = message.is_some() || label.is_some();
572 let mut err = struct_span_err!(
577 message.unwrap_or_else(|| {
578 format!("the trait bound `{}` is not satisfied{}",
579 trait_ref.to_predicate(), post_message)
582 if let Some(ref s) = label {
583 // If it has a custom "#[rustc_on_unimplemented]"
584 // error message, let's display it as the label!
585 err.span_label(span, s.as_str());
586 err.help(&format!("{}the trait `{}` is not implemented for `{}`",
589 trait_ref.self_ty()));
592 &*format!("{}the trait `{}` is not implemented for `{}`",
595 trait_ref.self_ty()));
597 if let Some(ref s) = note {
598 // If it has a custom "#[rustc_on_unimplemented]" note, let's display it
599 err.note(s.as_str());
602 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
604 // Try to report a help message
605 if !trait_ref.has_infer_types() &&
606 self.predicate_can_apply(obligation.param_env, trait_ref) {
607 // If a where-clause may be useful, remind the
608 // user that they can add it.
610 // don't display an on-unimplemented note, as
611 // these notes will often be of the form
612 // "the type `T` can't be frobnicated"
613 // which is somewhat confusing.
614 err.help(&format!("consider adding a `where {}` bound",
615 trait_ref.to_predicate()));
616 } else if !have_alt_message {
617 // Can't show anything else useful, try to find similar impls.
618 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
619 self.report_similar_impl_candidates(impl_candidates, &mut err);
625 ty::Predicate::Subtype(ref predicate) => {
626 // Errors for Subtype predicates show up as
627 // `FulfillmentErrorCode::CodeSubtypeError`,
628 // not selection error.
629 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
632 ty::Predicate::Equate(ref predicate) => {
633 let predicate = self.resolve_type_vars_if_possible(predicate);
634 let err = self.equality_predicate(&obligation.cause,
635 obligation.param_env,
636 &predicate).err().unwrap();
637 struct_span_err!(self.tcx.sess, span, E0278,
638 "the requirement `{}` is not satisfied (`{}`)",
642 ty::Predicate::RegionOutlives(ref predicate) => {
643 let predicate = self.resolve_type_vars_if_possible(predicate);
644 let err = self.region_outlives_predicate(&obligation.cause,
645 &predicate).err().unwrap();
646 struct_span_err!(self.tcx.sess, span, E0279,
647 "the requirement `{}` is not satisfied (`{}`)",
651 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
653 self.resolve_type_vars_if_possible(&obligation.predicate);
654 struct_span_err!(self.tcx.sess, span, E0280,
655 "the requirement `{}` is not satisfied",
659 ty::Predicate::ObjectSafe(trait_def_id) => {
660 let violations = self.tcx.object_safety_violations(trait_def_id);
661 self.tcx.report_object_safety_error(span,
666 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
667 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
668 let closure_span = self.tcx.sess.codemap()
669 .def_span(self.tcx.hir.span_if_local(closure_def_id).unwrap());
670 let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
671 let mut err = struct_span_err!(
672 self.tcx.sess, closure_span, E0525,
673 "expected a closure that implements the `{}` trait, \
674 but this closure only implements `{}`",
680 format!("this closure implements `{}`, not `{}`", found_kind, kind));
682 obligation.cause.span,
683 format!("the requirement to implement `{}` derives from here", kind));
685 // Additional context information explaining why the closure only implements
686 // a particular trait.
687 if let Some(tables) = self.in_progress_tables {
688 let tables = tables.borrow();
689 let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
690 match (found_kind, tables.closure_kind_origins().get(closure_hir_id)) {
691 (ty::ClosureKind::FnOnce, Some((span, name))) => {
692 err.span_label(*span, format!(
693 "closure is `FnOnce` because it moves the \
694 variable `{}` out of its environment", name));
696 (ty::ClosureKind::FnMut, Some((span, name))) => {
697 err.span_label(*span, format!(
698 "closure is `FnMut` because it mutates the \
699 variable `{}` here", name));
709 ty::Predicate::WellFormed(ty) => {
710 // WF predicates cannot themselves make
711 // errors. They can only block due to
712 // ambiguity; otherwise, they always
713 // degenerate into other obligations
715 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
718 ty::Predicate::ConstEvaluatable(..) => {
719 // Errors for `ConstEvaluatable` predicates show up as
720 // `SelectionError::ConstEvalFailure`,
721 // not `Unimplemented`.
723 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
728 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
729 let found_trait_ref = self.resolve_type_vars_if_possible(&*found_trait_ref);
730 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
731 if expected_trait_ref.self_ty().references_error() {
734 let found_trait_ty = found_trait_ref.self_ty();
736 let found_did = found_trait_ty.ty_to_def_id();
737 let found_span = found_did.and_then(|did| {
738 self.tcx.hir.span_if_local(did)
739 }).map(|sp| self.tcx.sess.codemap().def_span(sp)); // the sp could be an fn def
741 let found = match found_trait_ref.skip_binder().substs.type_at(1).sty {
742 ty::TyTuple(ref tys, _) => tys.iter()
743 .map(|_| ArgKind::empty()).collect::<Vec<_>>(),
744 _ => vec![ArgKind::empty()],
746 let expected = match expected_trait_ref.skip_binder().substs.type_at(1).sty {
747 ty::TyTuple(ref tys, _) => tys.iter()
748 .map(|t| match t.sty {
749 ty::TypeVariants::TyTuple(ref tys, _) => ArgKind::Tuple(
752 .map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
755 _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),
757 ref sty => vec![ArgKind::Arg("_".to_owned(), format!("{}", sty))],
759 if found.len()== expected.len() {
760 self.report_closure_arg_mismatch(span,
765 let (closure_span, found) = found_did
766 .and_then(|did| self.tcx.hir.get_if_local(did))
768 let (found_span, found) = self.get_fn_like_arguments(node);
769 (Some(found_span), found)
770 }).unwrap_or((found_span, found));
772 self.report_arg_count_mismatch(span,
776 found_trait_ty.is_closure())
780 TraitNotObjectSafe(did) => {
781 let violations = self.tcx.object_safety_violations(did);
782 self.tcx.report_object_safety_error(span, did,
786 ConstEvalFailure(ref err) => {
787 if let const_val::ErrKind::TypeckError = err.kind {
790 err.struct_error(self.tcx, span, "constant expression")
793 self.note_obligation_cause(&mut err, obligation);
797 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
798 /// suggestion to borrow the initializer in order to use have a slice instead.
799 fn suggest_borrow_on_unsized_slice(&self,
800 code: &ObligationCauseCode<'tcx>,
801 err: &mut DiagnosticBuilder<'tcx>) {
802 if let &ObligationCauseCode::VariableType(node_id) = code {
803 let parent_node = self.tcx.hir.get_parent_node(node_id);
804 if let Some(hir::map::NodeLocal(ref local)) = self.tcx.hir.find(parent_node) {
805 if let Some(ref expr) = local.init {
806 if let hir::ExprIndex(_, _) = expr.node {
807 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(expr.span) {
808 err.span_suggestion(expr.span,
809 "consider borrowing here",
810 format!("&{}", snippet));
818 fn get_fn_like_arguments(&self, node: hir::map::Node) -> (Span, Vec<ArgKind>) {
820 hir::map::NodeExpr(&hir::Expr {
821 node: hir::ExprClosure(_, ref _decl, id, span, _),
824 (self.tcx.sess.codemap().def_span(span), self.tcx.hir.body(id).arguments.iter()
827 node: hir::PatKind::Tuple(args, _),
830 } = arg.pat.clone().into_inner() {
833 args.iter().map(|pat| {
834 let snippet = self.tcx.sess.codemap()
835 .span_to_snippet(pat.span).unwrap();
836 (snippet, "_".to_owned())
837 }).collect::<Vec<_>>(),
840 let name = self.tcx.sess.codemap()
841 .span_to_snippet(arg.pat.span).unwrap();
842 ArgKind::Arg(name, "_".to_owned())
845 .collect::<Vec<ArgKind>>())
847 hir::map::NodeItem(&hir::Item {
849 node: hir::ItemFn(ref decl, ..),
852 hir::map::NodeImplItem(&hir::ImplItem {
854 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
857 hir::map::NodeTraitItem(&hir::TraitItem {
859 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
862 (self.tcx.sess.codemap().def_span(span), decl.inputs.iter()
863 .map(|arg| match arg.clone().into_inner().node {
864 hir::TyTup(ref tys) => ArgKind::Tuple(
867 .map(|_| ("_".to_owned(), "_".to_owned()))
868 .collect::<Vec<_>>(),
870 _ => ArgKind::Arg("_".to_owned(), "_".to_owned())
871 }).collect::<Vec<ArgKind>>())
873 _ => panic!("non-FnLike node found: {:?}", node),
877 fn report_arg_count_mismatch(
880 found_span: Option<Span>,
881 expected_args: Vec<ArgKind>,
882 found_args: Vec<ArgKind>,
884 ) -> DiagnosticBuilder<'tcx> {
885 let kind = if is_closure { "closure" } else { "function" };
887 let args_str = |arguments: &Vec<ArgKind>, other: &Vec<ArgKind>| {
888 let arg_length = arguments.len();
889 let distinct = match &other[..] {
890 &[ArgKind::Tuple(..)] => true,
893 match (arg_length, arguments.get(0)) {
894 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
895 format!("a single {}-tuple as argument", fields.len())
897 _ => format!("{} {}argument{}",
899 if distinct && arg_length > 1 { "distinct " } else { "" },
900 if arg_length == 1 { "" } else { "s" }),
904 let expected_str = args_str(&expected_args, &found_args);
905 let found_str = args_str(&found_args, &expected_args);
907 let mut err = struct_span_err!(
911 "{} is expected to take {}, but it takes {}",
917 err.span_label(span, format!( "expected {} that takes {}", kind, expected_str));
919 if let Some(found_span) = found_span {
920 err.span_label(found_span, format!("takes {}", found_str));
922 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
923 if fields.len() == expected_args.len() {
924 let sugg = fields.iter()
925 .map(|(name, _)| name.to_owned())
926 .collect::<Vec<String>>().join(", ");
927 err.span_suggestion(found_span,
928 "change the closure to take multiple arguments instead of \
930 format!("|{}|", sugg));
933 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
934 if fields.len() == found_args.len() && is_closure {
938 .map(|arg| match arg {
939 ArgKind::Arg(name, _) => name.to_owned(),
942 .collect::<Vec<String>>()
944 // add type annotations if available
945 if found_args.iter().any(|arg| match arg {
946 ArgKind::Arg(_, ty) => ty != "_",
951 .map(|(_, ty)| ty.to_owned())
952 .collect::<Vec<String>>()
958 err.span_suggestion(found_span,
959 "change the closure to accept a tuple instead of \
960 individual arguments",
969 fn report_closure_arg_mismatch(&self,
971 found_span: Option<Span>,
972 expected_ref: ty::PolyTraitRef<'tcx>,
973 found: ty::PolyTraitRef<'tcx>)
974 -> DiagnosticBuilder<'tcx>
976 fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
977 trait_ref: &ty::TraitRef<'tcx>) -> String {
978 let inputs = trait_ref.substs.type_at(1);
979 let sig = if let ty::TyTuple(inputs, _) = inputs.sty {
981 inputs.iter().map(|&x| x),
982 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
984 hir::Unsafety::Normal,
985 ::syntax::abi::Abi::Rust
989 ::std::iter::once(inputs),
990 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
992 hir::Unsafety::Normal,
993 ::syntax::abi::Abi::Rust
996 format!("{}", ty::Binder(sig))
999 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1000 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1001 "type mismatch in {} arguments",
1002 if argument_is_closure { "closure" } else { "function" });
1004 let found_str = format!(
1005 "expected signature of `{}`",
1006 build_fn_sig_string(self.tcx, found.skip_binder())
1008 err.span_label(span, found_str);
1010 let found_span = found_span.unwrap_or(span);
1011 let expected_str = format!(
1012 "found signature of `{}`",
1013 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1015 err.span_label(found_span, expected_str);
1021 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1022 pub fn recursive_type_with_infinite_size_error(self,
1024 -> DiagnosticBuilder<'tcx>
1026 assert!(type_def_id.is_local());
1027 let span = self.hir.span_if_local(type_def_id).unwrap();
1028 let span = self.sess.codemap().def_span(span);
1029 let mut err = struct_span_err!(self.sess, span, E0072,
1030 "recursive type `{}` has infinite size",
1031 self.item_path_str(type_def_id));
1032 err.span_label(span, "recursive type has infinite size");
1033 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1034 at some point to make `{}` representable",
1035 self.item_path_str(type_def_id)));
1039 pub fn report_object_safety_error(self,
1041 trait_def_id: DefId,
1042 violations: Vec<ObjectSafetyViolation>)
1043 -> DiagnosticBuilder<'tcx>
1045 let trait_str = self.item_path_str(trait_def_id);
1046 let span = self.sess.codemap().def_span(span);
1047 let mut err = struct_span_err!(
1048 self.sess, span, E0038,
1049 "the trait `{}` cannot be made into an object",
1051 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1053 let mut reported_violations = FxHashSet();
1054 for violation in violations {
1055 if !reported_violations.insert(violation.clone()) {
1058 err.note(&violation.error_msg());
1064 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1065 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1066 body_id: Option<hir::BodyId>) {
1067 // Unable to successfully determine, probably means
1068 // insufficient type information, but could mean
1069 // ambiguous impls. The latter *ought* to be a
1070 // coherence violation, so we don't report it here.
1072 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1073 let span = obligation.cause.span;
1075 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1079 // Ambiguity errors are often caused as fallout from earlier
1080 // errors. So just ignore them if this infcx is tainted.
1081 if self.is_tainted_by_errors() {
1086 ty::Predicate::Trait(ref data) => {
1087 let trait_ref = data.to_poly_trait_ref();
1088 let self_ty = trait_ref.self_ty();
1089 if predicate.references_error() {
1092 // Typically, this ambiguity should only happen if
1093 // there are unresolved type inference variables
1094 // (otherwise it would suggest a coherence
1095 // failure). But given #21974 that is not necessarily
1096 // the case -- we can have multiple where clauses that
1097 // are only distinguished by a region, which results
1098 // in an ambiguity even when all types are fully
1099 // known, since we don't dispatch based on region
1102 // This is kind of a hack: it frequently happens that some earlier
1103 // error prevents types from being fully inferred, and then we get
1104 // a bunch of uninteresting errors saying something like "<generic
1105 // #0> doesn't implement Sized". It may even be true that we
1106 // could just skip over all checks where the self-ty is an
1107 // inference variable, but I was afraid that there might be an
1108 // inference variable created, registered as an obligation, and
1109 // then never forced by writeback, and hence by skipping here we'd
1110 // be ignoring the fact that we don't KNOW the type works
1111 // out. Though even that would probably be harmless, given that
1112 // we're only talking about builtin traits, which are known to be
1113 // inhabited. But in any case I just threw in this check for
1114 // has_errors() to be sure that compilation isn't happening
1115 // anyway. In that case, why inundate the user.
1116 if !self.tcx.sess.has_errors() {
1118 self.tcx.lang_items().sized_trait()
1119 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1121 self.need_type_info(body_id, span, self_ty);
1123 let mut err = struct_span_err!(self.tcx.sess,
1125 "type annotations required: \
1126 cannot resolve `{}`",
1128 self.note_obligation_cause(&mut err, obligation);
1134 ty::Predicate::WellFormed(ty) => {
1135 // Same hacky approach as above to avoid deluging user
1136 // with error messages.
1137 if !ty.references_error() && !self.tcx.sess.has_errors() {
1138 self.need_type_info(body_id, span, ty);
1142 ty::Predicate::Subtype(ref data) => {
1143 if data.references_error() || self.tcx.sess.has_errors() {
1144 // no need to overload user in such cases
1146 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1147 // both must be type variables, or the other would've been instantiated
1148 assert!(a.is_ty_var() && b.is_ty_var());
1149 self.need_type_info(body_id,
1150 obligation.cause.span,
1156 if !self.tcx.sess.has_errors() {
1157 let mut err = struct_span_err!(self.tcx.sess,
1158 obligation.cause.span, E0284,
1159 "type annotations required: \
1160 cannot resolve `{}`",
1162 self.note_obligation_cause(&mut err, obligation);
1169 /// Returns whether the trait predicate may apply for *some* assignment
1170 /// to the type parameters.
1171 fn predicate_can_apply(&self,
1172 param_env: ty::ParamEnv<'tcx>,
1173 pred: ty::PolyTraitRef<'tcx>)
1175 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1176 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1177 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1180 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1181 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1183 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1184 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
1185 let infcx = self.infcx;
1186 self.var_map.entry(ty).or_insert_with(||
1188 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1190 ty.super_fold_with(self)
1196 let mut selcx = SelectionContext::new(self);
1198 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1200 var_map: FxHashMap()
1203 let cleaned_pred = super::project::normalize(
1206 ObligationCause::dummy(),
1210 let obligation = Obligation::new(
1211 ObligationCause::dummy(),
1213 cleaned_pred.to_predicate()
1216 selcx.evaluate_obligation(&obligation)
1220 fn note_obligation_cause<T>(&self,
1221 err: &mut DiagnosticBuilder,
1222 obligation: &Obligation<'tcx, T>)
1223 where T: fmt::Display
1225 self.note_obligation_cause_code(err,
1226 &obligation.predicate,
1227 &obligation.cause.code,
1231 fn note_obligation_cause_code<T>(&self,
1232 err: &mut DiagnosticBuilder,
1234 cause_code: &ObligationCauseCode<'tcx>,
1235 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1236 where T: fmt::Display
1240 ObligationCauseCode::ExprAssignable |
1241 ObligationCauseCode::MatchExpressionArm { .. } |
1242 ObligationCauseCode::IfExpression |
1243 ObligationCauseCode::IfExpressionWithNoElse |
1244 ObligationCauseCode::EquatePredicate |
1245 ObligationCauseCode::MainFunctionType |
1246 ObligationCauseCode::StartFunctionType |
1247 ObligationCauseCode::IntrinsicType |
1248 ObligationCauseCode::MethodReceiver |
1249 ObligationCauseCode::ReturnNoExpression |
1250 ObligationCauseCode::MiscObligation => {
1252 ObligationCauseCode::SliceOrArrayElem => {
1253 err.note("slice and array elements must have `Sized` type");
1255 ObligationCauseCode::TupleElem => {
1256 err.note("only the last element of a tuple may have a dynamically sized type");
1258 ObligationCauseCode::ProjectionWf(data) => {
1259 err.note(&format!("required so that the projection `{}` is well-formed",
1262 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1263 err.note(&format!("required so that reference `{}` does not outlive its referent",
1266 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1267 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1269 region, object_ty));
1271 ObligationCauseCode::ItemObligation(item_def_id) => {
1272 let item_name = tcx.item_path_str(item_def_id);
1273 let msg = format!("required by `{}`", item_name);
1274 if let Some(sp) = tcx.hir.span_if_local(item_def_id) {
1275 let sp = tcx.sess.codemap().def_span(sp);
1276 err.span_note(sp, &msg);
1281 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1282 err.note(&format!("required for the cast to the object type `{}`",
1283 self.ty_to_string(object_ty)));
1285 ObligationCauseCode::RepeatVec => {
1286 err.note("the `Copy` trait is required because the \
1287 repeated element will be copied");
1289 ObligationCauseCode::VariableType(_) => {
1290 err.note("all local variables must have a statically known size");
1292 ObligationCauseCode::SizedReturnType => {
1293 err.note("the return type of a function must have a \
1294 statically known size");
1296 ObligationCauseCode::SizedYieldType => {
1297 err.note("the yield type of a generator must have a \
1298 statically known size");
1300 ObligationCauseCode::AssignmentLhsSized => {
1301 err.note("the left-hand-side of an assignment must have a statically known size");
1303 ObligationCauseCode::TupleInitializerSized => {
1304 err.note("tuples must have a statically known size to be initialized");
1306 ObligationCauseCode::StructInitializerSized => {
1307 err.note("structs must have a statically known size to be initialized");
1309 ObligationCauseCode::FieldSized(ref item) => {
1311 AdtKind::Struct => {
1312 err.note("only the last field of a struct may have a dynamically \
1316 err.note("no field of a union may have a dynamically sized type");
1319 err.note("no field of an enum variant may have a dynamically sized type");
1323 ObligationCauseCode::ConstSized => {
1324 err.note("constant expressions must have a statically known size");
1326 ObligationCauseCode::SharedStatic => {
1327 err.note("shared static variables must have a type that implements `Sync`");
1329 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1330 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1331 let ty = parent_trait_ref.0.self_ty();
1332 err.note(&format!("required because it appears within the type `{}`", ty));
1333 obligated_types.push(ty);
1335 let parent_predicate = parent_trait_ref.to_predicate();
1336 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1337 self.note_obligation_cause_code(err,
1343 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1344 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1346 &format!("required because of the requirements on the impl of `{}` for `{}`",
1348 parent_trait_ref.0.self_ty()));
1349 let parent_predicate = parent_trait_ref.to_predicate();
1350 self.note_obligation_cause_code(err,
1355 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1357 &format!("the requirement `{}` appears on the impl method \
1358 but not on the corresponding trait method",
1361 ObligationCauseCode::ReturnType(_) |
1362 ObligationCauseCode::BlockTailExpression(_) => (),
1366 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1367 let current_limit = self.tcx.sess.recursion_limit.get();
1368 let suggested_limit = current_limit * 2;
1369 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1373 fn is_recursive_obligation(&self,
1374 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1375 cause_code: &ObligationCauseCode<'tcx>) -> bool {
1376 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1377 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1378 for obligated_type in obligated_types {
1379 if obligated_type == &parent_trait_ref.0.self_ty() {
1389 Arg(String, String),
1390 Tuple(Span, Vec<(String, String)>),
1394 fn empty() -> ArgKind {
1395 ArgKind::Arg("_".to_owned(), "_".to_owned())