1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 MismatchedProjectionTypes,
18 OnUnimplementedDirective,
20 OutputTypeParameterMismatch,
26 ObjectSafetyViolation,
30 use errors::{Applicability, DiagnosticBuilder};
33 use hir::def_id::DefId;
34 use infer::{self, InferCtxt};
35 use infer::type_variable::TypeVariableOrigin;
39 use session::DiagnosticMessageId;
40 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
41 use ty::GenericParamDefKind;
42 use ty::error::ExpectedFound;
44 use ty::fold::TypeFolder;
46 use ty::SubtypePredicate;
47 use util::nodemap::{FxHashMap, FxHashSet};
49 use syntax_pos::{DUMMY_SP, Span, ExpnInfo, ExpnFormat};
51 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
52 pub fn report_fulfillment_errors(&self,
53 errors: &[FulfillmentError<'tcx>],
54 body_id: Option<hir::BodyId>,
55 fallback_has_occurred: bool) {
57 struct ErrorDescriptor<'tcx> {
58 predicate: ty::Predicate<'tcx>,
59 index: Option<usize>, // None if this is an old error
62 let mut error_map: FxHashMap<_, Vec<_>> =
63 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
64 (span, predicates.iter().map(|predicate| ErrorDescriptor {
65 predicate: predicate.clone(),
70 for (index, error) in errors.iter().enumerate() {
71 // We want to ignore desugarings here: spans are equivalent even
72 // if one is the result of a desugaring and the other is not.
73 let mut span = error.obligation.cause.span;
74 if let Some(ExpnInfo {
75 format: ExpnFormat::CompilerDesugaring(_),
76 def_site: Some(def_span),
78 }) = span.ctxt().outer().expn_info() {
82 error_map.entry(span).or_default().push(
84 predicate: error.obligation.predicate.clone(),
89 self.reported_trait_errors.borrow_mut()
90 .entry(span).or_default()
91 .push(error.obligation.predicate.clone());
94 // We do this in 2 passes because we want to display errors in order, though
95 // maybe it *is* better to sort errors by span or something.
96 let mut is_suppressed = vec![false; errors.len()];
97 for (_, error_set) in error_map.iter() {
98 // We want to suppress "duplicate" errors with the same span.
99 for error in error_set {
100 if let Some(index) = error.index {
101 // Suppress errors that are either:
102 // 1) strictly implied by another error.
103 // 2) implied by an error with a smaller index.
104 for error2 in error_set {
105 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
106 // Avoid errors being suppressed by already-suppressed
107 // errors, to prevent all errors from being suppressed
112 if self.error_implies(&error2.predicate, &error.predicate) &&
113 !(error2.index >= error.index &&
114 self.error_implies(&error.predicate, &error2.predicate))
116 info!("skipping {:?} (implied by {:?})", error, error2);
117 is_suppressed[index] = true;
125 for (error, suppressed) in errors.iter().zip(is_suppressed) {
127 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
132 // returns if `cond` not occurring implies that `error` does not occur - i.e. that
133 // `error` occurring implies that `cond` occurs.
134 fn error_implies(&self,
135 cond: &ty::Predicate<'tcx>,
136 error: &ty::Predicate<'tcx>)
143 let (cond, error) = match (cond, error) {
144 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
147 // FIXME: make this work in other cases too.
152 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
153 if let ty::Predicate::Trait(implication) = implication {
154 let error = error.to_poly_trait_ref();
155 let implication = implication.to_poly_trait_ref();
156 // FIXME: I'm just not taking associated types at all here.
157 // Eventually I'll need to implement param-env-aware
158 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
159 let param_env = ty::ParamEnv::empty();
160 if self.can_sub(param_env, error, implication).is_ok() {
161 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
170 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
171 body_id: Option<hir::BodyId>,
172 fallback_has_occurred: bool) {
173 debug!("report_fulfillment_errors({:?})", error);
175 FulfillmentErrorCode::CodeSelectionError(ref e) => {
176 self.report_selection_error(&error.obligation, e, fallback_has_occurred);
178 FulfillmentErrorCode::CodeProjectionError(ref e) => {
179 self.report_projection_error(&error.obligation, e);
181 FulfillmentErrorCode::CodeAmbiguity => {
182 self.maybe_report_ambiguity(&error.obligation, body_id);
184 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
185 self.report_mismatched_types(&error.obligation.cause,
186 expected_found.expected,
187 expected_found.found,
194 fn report_projection_error(&self,
195 obligation: &PredicateObligation<'tcx>,
196 error: &MismatchedProjectionTypes<'tcx>)
199 self.resolve_type_vars_if_possible(&obligation.predicate);
201 if predicate.references_error() {
207 let mut err = &error.err;
208 let mut values = None;
210 // try to find the mismatched types to report the error with.
212 // this can fail if the problem was higher-ranked, in which
213 // cause I have no idea for a good error message.
214 if let ty::Predicate::Projection(ref data) = predicate {
215 let mut selcx = SelectionContext::new(self);
216 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
217 obligation.cause.span,
218 infer::LateBoundRegionConversionTime::HigherRankedType,
220 let mut obligations = vec![];
221 let normalized_ty = super::normalize_projection_type(
223 obligation.param_env,
225 obligation.cause.clone(),
229 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
230 .eq(normalized_ty, data.ty) {
231 values = Some(infer::ValuePairs::Types(ExpectedFound {
232 expected: normalized_ty,
240 let msg = format!("type mismatch resolving `{}`", predicate);
241 let error_id = (DiagnosticMessageId::ErrorId(271),
242 Some(obligation.cause.span), msg.clone());
243 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
245 let mut diag = struct_span_err!(
246 self.tcx.sess, obligation.cause.span, E0271,
247 "type mismatch resolving `{}`", predicate
249 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
250 self.note_obligation_cause(&mut diag, obligation);
256 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
257 /// returns the fuzzy category of a given type, or None
258 /// if the type can be equated to any type.
259 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
264 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
265 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
266 ty::Ref(..) | ty::RawPtr(..) => Some(5),
267 ty::Array(..) | ty::Slice(..) => Some(6),
268 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
269 ty::Dynamic(..) => Some(8),
270 ty::Closure(..) => Some(9),
271 ty::Tuple(..) => Some(10),
272 ty::Projection(..) => Some(11),
273 ty::Param(..) => Some(12),
274 ty::Opaque(..) => Some(13),
275 ty::Never => Some(14),
276 ty::Adt(adt, ..) => match adt.adt_kind() {
277 AdtKind::Struct => Some(15),
278 AdtKind::Union => Some(16),
279 AdtKind::Enum => Some(17),
281 ty::Generator(..) => Some(18),
282 ty::Foreign(..) => Some(19),
283 ty::GeneratorWitness(..) => Some(20),
284 ty::Infer(..) | ty::Error => None,
285 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
289 match (type_category(a), type_category(b)) {
290 (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
291 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
294 // infer and error can be equated to all types
299 fn impl_similar_to(&self,
300 trait_ref: ty::PolyTraitRef<'tcx>,
301 obligation: &PredicateObligation<'tcx>)
305 let param_env = obligation.param_env;
306 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
307 let trait_self_ty = trait_ref.self_ty();
309 let mut self_match_impls = vec![];
310 let mut fuzzy_match_impls = vec![];
312 self.tcx.for_each_relevant_impl(
313 trait_ref.def_id, trait_self_ty, |def_id| {
314 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
315 let impl_trait_ref = tcx
316 .impl_trait_ref(def_id)
318 .subst(tcx, impl_substs);
320 let impl_self_ty = impl_trait_ref.self_ty();
322 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
323 self_match_impls.push(def_id);
325 if trait_ref.substs.types().skip(1)
326 .zip(impl_trait_ref.substs.types().skip(1))
327 .all(|(u,v)| self.fuzzy_match_tys(u, v))
329 fuzzy_match_impls.push(def_id);
334 let impl_def_id = if self_match_impls.len() == 1 {
336 } else if fuzzy_match_impls.len() == 1 {
342 if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
349 fn on_unimplemented_note(
351 trait_ref: ty::PolyTraitRef<'tcx>,
352 obligation: &PredicateObligation<'tcx>,
353 ) -> OnUnimplementedNote {
354 let def_id = self.impl_similar_to(trait_ref, obligation)
355 .unwrap_or_else(|| trait_ref.def_id());
356 let trait_ref = *trait_ref.skip_binder();
358 let mut flags = vec![];
359 match obligation.cause.code {
360 ObligationCauseCode::BuiltinDerivedObligation(..) |
361 ObligationCauseCode::ImplDerivedObligation(..) => {}
363 // this is a "direct", user-specified, rather than derived,
365 flags.push(("direct".to_owned(), None));
369 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
370 // FIXME: maybe also have some way of handling methods
371 // from other traits? That would require name resolution,
372 // which we might want to be some sort of hygienic.
374 // Currently I'm leaving it for what I need for `try`.
375 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
376 let method = self.tcx.item_name(item);
377 flags.push(("from_method".to_owned(), None));
378 flags.push(("from_method".to_owned(), Some(method.to_string())));
381 if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
382 flags.push(("parent_trait".to_owned(), Some(t.to_string())));
385 if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
386 flags.push(("from_desugaring".to_owned(), None));
387 flags.push(("from_desugaring".to_owned(), Some(k.name().to_string())));
389 let generics = self.tcx.generics_of(def_id);
390 let self_ty = trait_ref.self_ty();
391 // This is also included through the generics list as `Self`,
392 // but the parser won't allow you to use it
393 flags.push(("_Self".to_owned(), Some(self_ty.to_string())));
394 if let Some(def) = self_ty.ty_adt_def() {
395 // We also want to be able to select self's original
396 // signature with no type arguments resolved
397 flags.push(("_Self".to_owned(), Some(self.tcx.type_of(def.did).to_string())));
400 for param in generics.params.iter() {
401 let value = match param.kind {
402 GenericParamDefKind::Type {..} => {
403 trait_ref.substs[param.index as usize].to_string()
405 GenericParamDefKind::Lifetime => continue,
407 let name = param.name.to_string();
408 flags.push((name, Some(value)));
411 if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
412 flags.push(("crate_local".to_owned(), None));
415 // Allow targeting all integers using `{integral}`, even if the exact type was resolved
416 if self_ty.is_integral() {
417 flags.push(("_Self".to_owned(), Some("{integral}".to_owned())));
420 if let ty::Array(aty, len) = self_ty.sty {
421 flags.push(("_Self".to_owned(), Some("[]".to_owned())));
422 flags.push(("_Self".to_owned(), Some(format!("[{}]", aty))));
423 if let Some(def) = aty.ty_adt_def() {
424 // We also want to be able to select the array's type's original
425 // signature with no type arguments resolved
428 Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
431 if let Some(len) = len.val.try_to_scalar().and_then(|scalar| {
432 scalar.to_usize(tcx).ok()
436 Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
441 Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
447 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
448 self.tcx, trait_ref.def_id, def_id
450 command.evaluate(self.tcx, trait_ref, &flags[..])
452 OnUnimplementedNote::empty()
456 fn find_similar_impl_candidates(&self,
457 trait_ref: ty::PolyTraitRef<'tcx>)
458 -> Vec<ty::TraitRef<'tcx>>
460 let simp = fast_reject::simplify_type(self.tcx,
461 trait_ref.skip_binder().self_ty(),
463 let all_impls = self.tcx.all_impls(trait_ref.def_id());
466 Some(simp) => all_impls.iter().filter_map(|&def_id| {
467 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
468 let imp_simp = fast_reject::simplify_type(self.tcx,
471 if let Some(imp_simp) = imp_simp {
472 if simp != imp_simp {
479 None => all_impls.iter().map(|&def_id|
480 self.tcx.impl_trait_ref(def_id).unwrap()
485 fn report_similar_impl_candidates(&self,
486 mut impl_candidates: Vec<ty::TraitRef<'tcx>>,
487 err: &mut DiagnosticBuilder<'_>)
489 if impl_candidates.is_empty() {
493 let len = impl_candidates.len();
494 let end = if impl_candidates.len() <= 5 {
495 impl_candidates.len()
500 let normalize = |candidate| self.tcx.global_tcx().infer_ctxt().enter(|ref infcx| {
501 let normalized = infcx
502 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
503 .normalize(candidate)
506 Some(normalized) => format!("\n {:?}", normalized.value),
507 None => format!("\n {:?}", candidate),
511 // Sort impl candidates so that ordering is consistent for UI tests.
512 let normalized_impl_candidates = &mut impl_candidates[0..end]
515 .collect::<Vec<String>>();
516 normalized_impl_candidates.sort();
518 err.help(&format!("the following implementations were found:{}{}",
519 normalized_impl_candidates.join(""),
521 format!("\nand {} others", len - 4)
528 /// Reports that an overflow has occurred and halts compilation. We
529 /// halt compilation unconditionally because it is important that
530 /// overflows never be masked -- they basically represent computations
531 /// whose result could not be truly determined and thus we can't say
532 /// if the program type checks or not -- and they are unusual
533 /// occurrences in any case.
534 pub fn report_overflow_error<T>(&self,
535 obligation: &Obligation<'tcx, T>,
536 suggest_increasing_limit: bool) -> !
537 where T: fmt::Display + TypeFoldable<'tcx>
540 self.resolve_type_vars_if_possible(&obligation.predicate);
541 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
542 "overflow evaluating the requirement `{}`",
545 if suggest_increasing_limit {
546 self.suggest_new_overflow_limit(&mut err);
549 self.note_obligation_cause(&mut err, obligation);
552 self.tcx.sess.abort_if_errors();
556 /// Reports that a cycle was detected which led to overflow and halts
557 /// compilation. This is equivalent to `report_overflow_error` except
558 /// that we can give a more helpful error message (and, in particular,
559 /// we do not suggest increasing the overflow limit, which is not
561 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
562 let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
563 assert!(cycle.len() > 0);
565 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
567 self.report_overflow_error(&cycle[0], false);
570 pub fn report_extra_impl_obligation(&self,
572 item_name: ast::Name,
573 _impl_item_def_id: DefId,
574 trait_item_def_id: DefId,
575 requirement: &dyn fmt::Display)
576 -> DiagnosticBuilder<'tcx>
578 let msg = "impl has stricter requirements than trait";
579 let sp = self.tcx.sess.source_map().def_span(error_span);
581 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
583 if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
584 let span = self.tcx.sess.source_map().def_span(trait_item_span);
585 err.span_label(span, format!("definition of `{}` from trait", item_name));
588 err.span_label(sp, format!("impl has extra requirement {}", requirement));
594 /// Get the parent trait chain start
595 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
597 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
598 let parent_trait_ref = self.resolve_type_vars_if_possible(
599 &data.parent_trait_ref);
600 match self.get_parent_trait_ref(&data.parent_code) {
602 None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
609 pub fn report_selection_error(&self,
610 obligation: &PredicateObligation<'tcx>,
611 error: &SelectionError<'tcx>,
612 fallback_has_occurred: bool)
614 let span = obligation.cause.span;
616 let mut err = match *error {
617 SelectionError::Unimplemented => {
618 if let ObligationCauseCode::CompareImplMethodObligation {
619 item_name, impl_item_def_id, trait_item_def_id,
620 } = obligation.cause.code {
621 self.report_extra_impl_obligation(
626 &format!("`{}`", obligation.predicate))
630 match obligation.predicate {
631 ty::Predicate::Trait(ref trait_predicate) => {
632 let trait_predicate =
633 self.resolve_type_vars_if_possible(trait_predicate);
635 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
638 let trait_ref = trait_predicate.to_poly_trait_ref();
639 let (post_message, pre_message) =
640 self.get_parent_trait_ref(&obligation.cause.code)
641 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
642 .unwrap_or_default();
644 let OnUnimplementedNote { message, label, note }
645 = self.on_unimplemented_note(trait_ref, obligation);
646 let have_alt_message = message.is_some() || label.is_some();
648 let mut err = struct_span_err!(
653 message.unwrap_or_else(||
654 format!("the trait bound `{}` is not satisfied{}",
655 trait_ref.to_predicate(), post_message)
659 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
660 "consider using `()`, or a `Result`".to_owned()
662 format!("{}the trait `{}` is not implemented for `{}`",
668 if let Some(ref s) = label {
669 // If it has a custom "#[rustc_on_unimplemented]"
670 // error message, let's display it as the label!
671 err.span_label(span, s.as_str());
672 err.help(&explanation);
674 err.span_label(span, explanation);
676 if let Some(ref s) = note {
677 // If it has a custom "#[rustc_on_unimplemented]" note, let's display it
678 err.note(s.as_str());
681 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
682 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
684 // Try to report a help message
685 if !trait_ref.has_infer_types() &&
686 self.predicate_can_apply(obligation.param_env, trait_ref) {
687 // If a where-clause may be useful, remind the
688 // user that they can add it.
690 // don't display an on-unimplemented note, as
691 // these notes will often be of the form
692 // "the type `T` can't be frobnicated"
693 // which is somewhat confusing.
694 err.help(&format!("consider adding a `where {}` bound",
695 trait_ref.to_predicate()));
696 } else if !have_alt_message {
697 // Can't show anything else useful, try to find similar impls.
698 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
699 self.report_similar_impl_candidates(impl_candidates, &mut err);
702 // If this error is due to `!: Trait` not implemented but `(): Trait` is
703 // implemented, and fallback has occurred, then it could be due to a
704 // variable that used to fallback to `()` now falling back to `!`. Issue a
705 // note informing about the change in behaviour.
706 if trait_predicate.skip_binder().self_ty().is_never()
707 && fallback_has_occurred
709 let predicate = trait_predicate.map_bound(|mut trait_pred| {
710 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
712 &trait_pred.trait_ref.substs[1..],
716 let unit_obligation = Obligation {
717 predicate: ty::Predicate::Trait(predicate),
718 .. obligation.clone()
720 if self.predicate_may_hold(&unit_obligation) {
721 err.note("the trait is implemented for `()`. \
722 Possibly this error has been caused by changes to \
723 Rust's type-inference algorithm \
724 (see: https://github.com/rust-lang/rust/issues/48950 \
725 for more info). Consider whether you meant to use the \
726 type `()` here instead.");
733 ty::Predicate::Subtype(ref predicate) => {
734 // Errors for Subtype predicates show up as
735 // `FulfillmentErrorCode::CodeSubtypeError`,
736 // not selection error.
737 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
740 ty::Predicate::RegionOutlives(ref predicate) => {
741 let predicate = self.resolve_type_vars_if_possible(predicate);
742 let err = self.region_outlives_predicate(&obligation.cause,
743 &predicate).err().unwrap();
744 struct_span_err!(self.tcx.sess, span, E0279,
745 "the requirement `{}` is not satisfied (`{}`)",
749 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
751 self.resolve_type_vars_if_possible(&obligation.predicate);
752 struct_span_err!(self.tcx.sess, span, E0280,
753 "the requirement `{}` is not satisfied",
757 ty::Predicate::ObjectSafe(trait_def_id) => {
758 let violations = self.tcx.object_safety_violations(trait_def_id);
759 self.tcx.report_object_safety_error(span,
764 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
765 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
766 let closure_span = self.tcx.sess.source_map()
767 .def_span(self.tcx.hir.span_if_local(closure_def_id).unwrap());
768 let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
769 let mut err = struct_span_err!(
770 self.tcx.sess, closure_span, E0525,
771 "expected a closure that implements the `{}` trait, \
772 but this closure only implements `{}`",
778 format!("this closure implements `{}`, not `{}`", found_kind, kind));
780 obligation.cause.span,
781 format!("the requirement to implement `{}` derives from here", kind));
783 // Additional context information explaining why the closure only implements
784 // a particular trait.
785 if let Some(tables) = self.in_progress_tables {
786 let tables = tables.borrow();
787 let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
788 match (found_kind, tables.closure_kind_origins().get(closure_hir_id)) {
789 (ty::ClosureKind::FnOnce, Some((span, name))) => {
790 err.span_label(*span, format!(
791 "closure is `FnOnce` because it moves the \
792 variable `{}` out of its environment", name));
794 (ty::ClosureKind::FnMut, Some((span, name))) => {
795 err.span_label(*span, format!(
796 "closure is `FnMut` because it mutates the \
797 variable `{}` here", name));
807 ty::Predicate::WellFormed(ty) => {
808 // WF predicates cannot themselves make
809 // errors. They can only block due to
810 // ambiguity; otherwise, they always
811 // degenerate into other obligations
813 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
816 ty::Predicate::ConstEvaluatable(..) => {
817 // Errors for `ConstEvaluatable` predicates show up as
818 // `SelectionError::ConstEvalFailure`,
819 // not `Unimplemented`.
821 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
826 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
827 let found_trait_ref = self.resolve_type_vars_if_possible(&*found_trait_ref);
828 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
830 if expected_trait_ref.self_ty().references_error() {
834 let found_trait_ty = found_trait_ref.self_ty();
836 let found_did = match found_trait_ty.sty {
837 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
838 ty::Adt(def, _) => Some(def.did),
842 let found_span = found_did.and_then(|did|
843 self.tcx.hir.span_if_local(did)
844 ).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
846 let found = match found_trait_ref.skip_binder().substs.type_at(1).sty {
847 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
848 _ => vec![ArgKind::empty()],
851 let expected = match expected_trait_ref.skip_binder().substs.type_at(1).sty {
852 ty::Tuple(ref tys) => tys.iter()
853 .map(|t| ArgKind::from_expected_ty(t, Some(span))).collect(),
854 ref sty => vec![ArgKind::Arg("_".to_owned(), sty.to_string())],
857 if found.len() == expected.len() {
858 self.report_closure_arg_mismatch(span,
863 let (closure_span, found) = found_did
864 .and_then(|did| self.tcx.hir.get_if_local(did))
866 let (found_span, found) = self.get_fn_like_arguments(node);
867 (Some(found_span), found)
868 }).unwrap_or((found_span, found));
870 self.report_arg_count_mismatch(span,
874 found_trait_ty.is_closure())
878 TraitNotObjectSafe(did) => {
879 let violations = self.tcx.object_safety_violations(did);
880 self.tcx.report_object_safety_error(span, did, violations)
883 ConstEvalFailure(ref err) => {
884 match err.struct_error(
886 "could not evaluate constant expression",
890 self.tcx.sess.delay_span_bug(span,
891 &format!("constant in type had an ignored error: {:?}", err));
898 bug!("overflow should be handled before the `report_selection_error` path");
901 self.note_obligation_cause(&mut err, obligation);
905 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
906 /// suggestion to borrow the initializer in order to use have a slice instead.
907 fn suggest_borrow_on_unsized_slice(&self,
908 code: &ObligationCauseCode<'tcx>,
909 err: &mut DiagnosticBuilder<'tcx>) {
910 if let &ObligationCauseCode::VariableType(node_id) = code {
911 let parent_node = self.tcx.hir.get_parent_node(node_id);
912 if let Some(Node::Local(ref local)) = self.tcx.hir.find(parent_node) {
913 if let Some(ref expr) = local.init {
914 if let hir::ExprKind::Index(_, _) = expr.node {
915 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
916 err.span_suggestion_with_applicability(
918 "consider borrowing here",
919 format!("&{}", snippet),
920 Applicability::MachineApplicable
929 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
930 /// suggest removing these references until we reach a type that implements the trait.
931 fn suggest_remove_reference(&self,
932 obligation: &PredicateObligation<'tcx>,
933 err: &mut DiagnosticBuilder<'tcx>,
934 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>) {
935 let trait_ref = trait_ref.skip_binder();
936 let span = obligation.cause.span;
938 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
939 let refs_number = snippet.chars()
940 .filter(|c| !c.is_whitespace())
941 .take_while(|c| *c == '&')
944 let mut trait_type = trait_ref.self_ty();
946 for refs_remaining in 0..refs_number {
947 if let ty::Ref(_, t_type, _) = trait_type.sty {
950 let substs = self.tcx.mk_substs_trait(trait_type, &[]);
951 let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
952 let new_obligation = Obligation::new(ObligationCause::dummy(),
953 obligation.param_env,
954 new_trait_ref.to_predicate());
956 if self.predicate_may_hold(&new_obligation) {
957 let sp = self.tcx.sess.source_map()
958 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
960 let remove_refs = refs_remaining + 1;
961 let format_str = format!("consider removing {} leading `&`-references",
964 err.span_suggestion_short_with_applicability(
965 sp, &format_str, String::new(), Applicability::MachineApplicable
976 /// Given some node representing a fn-like thing in the HIR map,
977 /// returns a span and `ArgKind` information that describes the
978 /// arguments it expects. This can be supplied to
979 /// `report_arg_count_mismatch`.
980 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
982 Node::Expr(&hir::Expr {
983 node: hir::ExprKind::Closure(_, ref _decl, id, span, _),
986 (self.tcx.sess.source_map().def_span(span), self.tcx.hir.body(id).arguments.iter()
989 node: hir::PatKind::Tuple(args, _),
992 } = arg.pat.clone().into_inner() {
995 args.iter().map(|pat| {
996 let snippet = self.tcx.sess.source_map()
997 .span_to_snippet(pat.span).unwrap();
998 (snippet, "_".to_owned())
999 }).collect::<Vec<_>>(),
1002 let name = self.tcx.sess.source_map()
1003 .span_to_snippet(arg.pat.span).unwrap();
1004 ArgKind::Arg(name, "_".to_owned())
1007 .collect::<Vec<ArgKind>>())
1009 Node::Item(&hir::Item {
1011 node: hir::ItemKind::Fn(ref decl, ..),
1014 Node::ImplItem(&hir::ImplItem {
1016 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1019 Node::TraitItem(&hir::TraitItem {
1021 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1024 (self.tcx.sess.source_map().def_span(span), decl.inputs.iter()
1025 .map(|arg| match arg.clone().node {
1026 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1028 vec![("_".to_owned(), "_".to_owned()); tys.len()]
1030 _ => ArgKind::empty()
1031 }).collect::<Vec<ArgKind>>())
1033 Node::Variant(&hir::Variant {
1035 node: hir::VariantKind {
1036 data: hir::VariantData::Tuple(ref fields, _),
1041 (self.tcx.sess.source_map().def_span(span),
1042 fields.iter().map(|field|
1043 ArgKind::Arg(field.ident.to_string(), "_".to_string())
1044 ).collect::<Vec<_>>())
1046 Node::StructCtor(ref variant_data) => {
1047 (self.tcx.sess.source_map().def_span(self.tcx.hir.span(variant_data.id())),
1048 vec![ArgKind::empty(); variant_data.fields().len()])
1050 _ => panic!("non-FnLike node found: {:?}", node),
1054 /// Reports an error when the number of arguments needed by a
1055 /// trait match doesn't match the number that the expression
1057 pub fn report_arg_count_mismatch(
1060 found_span: Option<Span>,
1061 expected_args: Vec<ArgKind>,
1062 found_args: Vec<ArgKind>,
1064 ) -> DiagnosticBuilder<'tcx> {
1065 let kind = if is_closure { "closure" } else { "function" };
1067 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1068 let arg_length = arguments.len();
1069 let distinct = match &other[..] {
1070 &[ArgKind::Tuple(..)] => true,
1073 match (arg_length, arguments.get(0)) {
1074 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1075 format!("a single {}-tuple as argument", fields.len())
1077 _ => format!("{} {}argument{}",
1079 if distinct && arg_length > 1 { "distinct " } else { "" },
1080 if arg_length == 1 { "" } else { "s" }),
1084 let expected_str = args_str(&expected_args, &found_args);
1085 let found_str = args_str(&found_args, &expected_args);
1087 let mut err = struct_span_err!(
1091 "{} is expected to take {}, but it takes {}",
1097 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1099 if let Some(found_span) = found_span {
1100 err.span_label(found_span, format!("takes {}", found_str));
1102 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1103 // found arguments is empty (assume the user just wants to ignore args in this case).
1104 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1105 if found_args.is_empty() && is_closure {
1106 let underscores = iter::repeat("_")
1107 .take(expected_args.len())
1108 .collect::<Vec<_>>()
1110 err.span_suggestion_with_applicability(
1113 "consider changing the closure to take and ignore the expected argument{}",
1114 if expected_args.len() < 2 {
1120 format!("|{}|", underscores),
1121 Applicability::MachineApplicable,
1125 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1126 if fields.len() == expected_args.len() {
1127 let sugg = fields.iter()
1128 .map(|(name, _)| name.to_owned())
1129 .collect::<Vec<String>>()
1131 err.span_suggestion_with_applicability(found_span,
1132 "change the closure to take multiple \
1133 arguments instead of a single tuple",
1134 format!("|{}|", sugg),
1135 Applicability::MachineApplicable);
1138 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1139 if fields.len() == found_args.len() && is_closure {
1143 .map(|arg| match arg {
1144 ArgKind::Arg(name, _) => name.to_owned(),
1145 _ => "_".to_owned(),
1147 .collect::<Vec<String>>()
1149 // add type annotations if available
1150 if found_args.iter().any(|arg| match arg {
1151 ArgKind::Arg(_, ty) => ty != "_",
1156 .map(|(_, ty)| ty.to_owned())
1157 .collect::<Vec<String>>()
1163 err.span_suggestion_with_applicability(
1165 "change the closure to accept a tuple instead of \
1166 individual arguments",
1168 Applicability::MachineApplicable
1177 fn report_closure_arg_mismatch(&self,
1179 found_span: Option<Span>,
1180 expected_ref: ty::PolyTraitRef<'tcx>,
1181 found: ty::PolyTraitRef<'tcx>)
1182 -> DiagnosticBuilder<'tcx>
1184 fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
1185 trait_ref: &ty::TraitRef<'tcx>) -> String {
1186 let inputs = trait_ref.substs.type_at(1);
1187 let sig = if let ty::Tuple(inputs) = inputs.sty {
1189 inputs.iter().cloned(),
1190 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1192 hir::Unsafety::Normal,
1193 ::rustc_target::spec::abi::Abi::Rust
1197 ::std::iter::once(inputs),
1198 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1200 hir::Unsafety::Normal,
1201 ::rustc_target::spec::abi::Abi::Rust
1204 ty::Binder::bind(sig).to_string()
1207 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1208 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1209 "type mismatch in {} arguments",
1210 if argument_is_closure { "closure" } else { "function" });
1212 let found_str = format!(
1213 "expected signature of `{}`",
1214 build_fn_sig_string(self.tcx, found.skip_binder())
1216 err.span_label(span, found_str);
1218 let found_span = found_span.unwrap_or(span);
1219 let expected_str = format!(
1220 "found signature of `{}`",
1221 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1223 err.span_label(found_span, expected_str);
1229 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1230 pub fn recursive_type_with_infinite_size_error(self,
1232 -> DiagnosticBuilder<'tcx>
1234 assert!(type_def_id.is_local());
1235 let span = self.hir.span_if_local(type_def_id).unwrap();
1236 let span = self.sess.source_map().def_span(span);
1237 let mut err = struct_span_err!(self.sess, span, E0072,
1238 "recursive type `{}` has infinite size",
1239 self.item_path_str(type_def_id));
1240 err.span_label(span, "recursive type has infinite size");
1241 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1242 at some point to make `{}` representable",
1243 self.item_path_str(type_def_id)));
1247 pub fn report_object_safety_error(self,
1249 trait_def_id: DefId,
1250 violations: Vec<ObjectSafetyViolation>)
1251 -> DiagnosticBuilder<'tcx>
1253 let trait_str = self.item_path_str(trait_def_id);
1254 let span = self.sess.source_map().def_span(span);
1255 let mut err = struct_span_err!(
1256 self.sess, span, E0038,
1257 "the trait `{}` cannot be made into an object",
1259 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1261 let mut reported_violations = FxHashSet::default();
1262 for violation in violations {
1263 if reported_violations.insert(violation.clone()) {
1264 err.note(&violation.error_msg());
1271 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1272 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1273 body_id: Option<hir::BodyId>) {
1274 // Unable to successfully determine, probably means
1275 // insufficient type information, but could mean
1276 // ambiguous impls. The latter *ought* to be a
1277 // coherence violation, so we don't report it here.
1279 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1280 let span = obligation.cause.span;
1282 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1286 // Ambiguity errors are often caused as fallout from earlier
1287 // errors. So just ignore them if this infcx is tainted.
1288 if self.is_tainted_by_errors() {
1293 ty::Predicate::Trait(ref data) => {
1294 let trait_ref = data.to_poly_trait_ref();
1295 let self_ty = trait_ref.self_ty();
1296 if predicate.references_error() {
1299 // Typically, this ambiguity should only happen if
1300 // there are unresolved type inference variables
1301 // (otherwise it would suggest a coherence
1302 // failure). But given #21974 that is not necessarily
1303 // the case -- we can have multiple where clauses that
1304 // are only distinguished by a region, which results
1305 // in an ambiguity even when all types are fully
1306 // known, since we don't dispatch based on region
1309 // This is kind of a hack: it frequently happens that some earlier
1310 // error prevents types from being fully inferred, and then we get
1311 // a bunch of uninteresting errors saying something like "<generic
1312 // #0> doesn't implement Sized". It may even be true that we
1313 // could just skip over all checks where the self-ty is an
1314 // inference variable, but I was afraid that there might be an
1315 // inference variable created, registered as an obligation, and
1316 // then never forced by writeback, and hence by skipping here we'd
1317 // be ignoring the fact that we don't KNOW the type works
1318 // out. Though even that would probably be harmless, given that
1319 // we're only talking about builtin traits, which are known to be
1320 // inhabited. But in any case I just threw in this check for
1321 // has_errors() to be sure that compilation isn't happening
1322 // anyway. In that case, why inundate the user.
1323 if !self.tcx.sess.has_errors() {
1325 self.tcx.lang_items().sized_trait()
1326 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1328 self.need_type_info_err(body_id, span, self_ty).emit();
1330 let mut err = struct_span_err!(self.tcx.sess,
1332 "type annotations required: \
1333 cannot resolve `{}`",
1335 self.note_obligation_cause(&mut err, obligation);
1341 ty::Predicate::WellFormed(ty) => {
1342 // Same hacky approach as above to avoid deluging user
1343 // with error messages.
1344 if !ty.references_error() && !self.tcx.sess.has_errors() {
1345 self.need_type_info_err(body_id, span, ty).emit();
1349 ty::Predicate::Subtype(ref data) => {
1350 if data.references_error() || self.tcx.sess.has_errors() {
1351 // no need to overload user in such cases
1353 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1354 // both must be type variables, or the other would've been instantiated
1355 assert!(a.is_ty_var() && b.is_ty_var());
1356 self.need_type_info_err(body_id,
1357 obligation.cause.span,
1363 if !self.tcx.sess.has_errors() {
1364 let mut err = struct_span_err!(self.tcx.sess,
1365 obligation.cause.span, E0284,
1366 "type annotations required: \
1367 cannot resolve `{}`",
1369 self.note_obligation_cause(&mut err, obligation);
1376 /// Returns whether the trait predicate may apply for *some* assignment
1377 /// to the type parameters.
1378 fn predicate_can_apply(&self,
1379 param_env: ty::ParamEnv<'tcx>,
1380 pred: ty::PolyTraitRef<'tcx>)
1382 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1383 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1384 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1387 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1388 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1390 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1391 if let ty::Param(ty::ParamTy {name, ..}) = ty.sty {
1392 let infcx = self.infcx;
1393 self.var_map.entry(ty).or_insert_with(||
1395 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1397 ty.super_fold_with(self)
1403 let mut selcx = SelectionContext::new(self);
1405 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1407 var_map: Default::default()
1410 let cleaned_pred = super::project::normalize(
1413 ObligationCause::dummy(),
1417 let obligation = Obligation::new(
1418 ObligationCause::dummy(),
1420 cleaned_pred.to_predicate()
1423 self.predicate_may_hold(&obligation)
1427 fn note_obligation_cause<T>(&self,
1428 err: &mut DiagnosticBuilder<'_>,
1429 obligation: &Obligation<'tcx, T>)
1430 where T: fmt::Display
1432 self.note_obligation_cause_code(err,
1433 &obligation.predicate,
1434 &obligation.cause.code,
1438 fn note_obligation_cause_code<T>(&self,
1439 err: &mut DiagnosticBuilder<'_>,
1441 cause_code: &ObligationCauseCode<'tcx>,
1442 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1443 where T: fmt::Display
1447 ObligationCauseCode::ExprAssignable |
1448 ObligationCauseCode::MatchExpressionArm { .. } |
1449 ObligationCauseCode::IfExpression |
1450 ObligationCauseCode::IfExpressionWithNoElse |
1451 ObligationCauseCode::MainFunctionType |
1452 ObligationCauseCode::StartFunctionType |
1453 ObligationCauseCode::IntrinsicType |
1454 ObligationCauseCode::MethodReceiver |
1455 ObligationCauseCode::ReturnNoExpression |
1456 ObligationCauseCode::MiscObligation => {
1458 ObligationCauseCode::SliceOrArrayElem => {
1459 err.note("slice and array elements must have `Sized` type");
1461 ObligationCauseCode::TupleElem => {
1462 err.note("only the last element of a tuple may have a dynamically sized type");
1464 ObligationCauseCode::ProjectionWf(data) => {
1465 err.note(&format!("required so that the projection `{}` is well-formed",
1468 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1469 err.note(&format!("required so that reference `{}` does not outlive its referent",
1472 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1473 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1475 region, object_ty));
1477 ObligationCauseCode::ItemObligation(item_def_id) => {
1478 let item_name = tcx.item_path_str(item_def_id);
1479 let msg = format!("required by `{}`", item_name);
1481 if let Some(sp) = tcx.hir.span_if_local(item_def_id) {
1482 let sp = tcx.sess.source_map().def_span(sp);
1483 err.span_note(sp, &msg);
1488 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1489 err.note(&format!("required for the cast to the object type `{}`",
1490 self.ty_to_string(object_ty)));
1492 ObligationCauseCode::RepeatVec => {
1493 err.note("the `Copy` trait is required because the \
1494 repeated element will be copied");
1496 ObligationCauseCode::VariableType(_) => {
1497 err.note("all local variables must have a statically known size");
1498 if !self.tcx.features().unsized_locals {
1499 err.help("unsized locals are gated as an unstable feature");
1502 ObligationCauseCode::SizedArgumentType => {
1503 err.note("all function arguments must have a statically known size");
1504 if !self.tcx.features().unsized_locals {
1505 err.help("unsized locals are gated as an unstable feature");
1508 ObligationCauseCode::SizedReturnType => {
1509 err.note("the return type of a function must have a \
1510 statically known size");
1512 ObligationCauseCode::SizedYieldType => {
1513 err.note("the yield type of a generator must have a \
1514 statically known size");
1516 ObligationCauseCode::AssignmentLhsSized => {
1517 err.note("the left-hand-side of an assignment must have a statically known size");
1519 ObligationCauseCode::TupleInitializerSized => {
1520 err.note("tuples must have a statically known size to be initialized");
1522 ObligationCauseCode::StructInitializerSized => {
1523 err.note("structs must have a statically known size to be initialized");
1525 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
1527 AdtKind::Struct => {
1529 err.note("the last field of a packed struct may only have a \
1530 dynamically sized type if it does not need drop to be run");
1532 err.note("only the last field of a struct may have a dynamically \
1537 err.note("no field of a union may have a dynamically sized type");
1540 err.note("no field of an enum variant may have a dynamically sized type");
1544 ObligationCauseCode::ConstSized => {
1545 err.note("constant expressions must have a statically known size");
1547 ObligationCauseCode::SharedStatic => {
1548 err.note("shared static variables must have a type that implements `Sync`");
1550 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1551 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1552 let ty = parent_trait_ref.skip_binder().self_ty();
1553 err.note(&format!("required because it appears within the type `{}`", ty));
1554 obligated_types.push(ty);
1556 let parent_predicate = parent_trait_ref.to_predicate();
1557 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1558 self.note_obligation_cause_code(err,
1564 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1565 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1567 &format!("required because of the requirements on the impl of `{}` for `{}`",
1569 parent_trait_ref.skip_binder().self_ty()));
1570 let parent_predicate = parent_trait_ref.to_predicate();
1571 self.note_obligation_cause_code(err,
1576 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1578 &format!("the requirement `{}` appears on the impl method \
1579 but not on the corresponding trait method",
1582 ObligationCauseCode::ReturnType(_) |
1583 ObligationCauseCode::BlockTailExpression(_) => (),
1584 ObligationCauseCode::TrivialBound => {
1585 err.help("see issue #48214");
1586 if tcx.sess.opts.unstable_features.is_nightly_build() {
1587 err.help("add #![feature(trivial_bounds)] to the \
1588 crate attributes to enable",
1595 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1596 let current_limit = self.tcx.sess.recursion_limit.get();
1597 let suggested_limit = current_limit * 2;
1598 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1602 fn is_recursive_obligation(&self,
1603 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1604 cause_code: &ObligationCauseCode<'tcx>) -> bool {
1605 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1606 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1608 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1616 /// Summarizes information
1619 /// An argument of non-tuple type. Parameters are (name, ty)
1620 Arg(String, String),
1622 /// An argument of tuple type. For a "found" argument, the span is
1623 /// the locationo in the source of the pattern. For a "expected"
1624 /// argument, it will be None. The vector is a list of (name, ty)
1625 /// strings for the components of the tuple.
1626 Tuple(Option<Span>, Vec<(String, String)>),
1630 fn empty() -> ArgKind {
1631 ArgKind::Arg("_".to_owned(), "_".to_owned())
1634 /// Creates an `ArgKind` from the expected type of an
1635 /// argument. It has no name (`_`) and an optional source span.
1636 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
1638 ty::Tuple(ref tys) => ArgKind::Tuple(
1641 .map(|ty| ("_".to_owned(), ty.sty.to_string()))
1642 .collect::<Vec<_>>()
1644 _ => ArgKind::Arg("_".to_owned(), t.sty.to_string()),