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;
38 use session::DiagnosticMessageId;
39 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
40 use ty::GenericParamDefKind;
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, ExpnInfo, ExpnFormat};
50 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
51 pub fn report_fulfillment_errors(&self,
52 errors: &[FulfillmentError<'tcx>],
53 body_id: Option<hir::BodyId>,
54 fallback_has_occurred: bool) {
56 struct ErrorDescriptor<'tcx> {
57 predicate: ty::Predicate<'tcx>,
58 index: Option<usize>, // None if this is an old error
61 let mut error_map: FxHashMap<_, Vec<_>> =
62 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
63 (span, predicates.iter().map(|predicate| ErrorDescriptor {
64 predicate: predicate.clone(),
69 for (index, error) in errors.iter().enumerate() {
70 // We want to ignore desugarings here: spans are equivalent even
71 // if one is the result of a desugaring and the other is not.
72 let mut span = error.obligation.cause.span;
73 if let Some(ExpnInfo {
74 format: ExpnFormat::CompilerDesugaring(_),
75 def_site: Some(def_span),
77 }) = span.ctxt().outer().expn_info() {
81 error_map.entry(span).or_default().push(
83 predicate: error.obligation.predicate.clone(),
88 self.reported_trait_errors.borrow_mut()
89 .entry(span).or_default()
90 .push(error.obligation.predicate.clone());
93 // We do this in 2 passes because we want to display errors in order, though
94 // maybe it *is* better to sort errors by span or something.
95 let mut is_suppressed = vec![false; errors.len()];
96 for (_, error_set) in error_map.iter() {
97 // We want to suppress "duplicate" errors with the same span.
98 for error in error_set {
99 if let Some(index) = error.index {
100 // Suppress errors that are either:
101 // 1) strictly implied by another error.
102 // 2) implied by an error with a smaller index.
103 for error2 in error_set {
104 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
105 // Avoid errors being suppressed by already-suppressed
106 // errors, to prevent all errors from being suppressed
111 if self.error_implies(&error2.predicate, &error.predicate) &&
112 !(error2.index >= error.index &&
113 self.error_implies(&error.predicate, &error2.predicate))
115 info!("skipping {:?} (implied by {:?})", error, error2);
116 is_suppressed[index] = true;
124 for (error, suppressed) in errors.iter().zip(is_suppressed) {
126 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
131 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
132 // `error` occurring implies that `cond` occurs.
133 fn error_implies(&self,
134 cond: &ty::Predicate<'tcx>,
135 error: &ty::Predicate<'tcx>)
142 let (cond, error) = match (cond, error) {
143 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
146 // FIXME: make this work in other cases too.
151 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
152 if let ty::Predicate::Trait(implication) = implication {
153 let error = error.to_poly_trait_ref();
154 let implication = implication.to_poly_trait_ref();
155 // FIXME: I'm just not taking associated types at all here.
156 // Eventually I'll need to implement param-env-aware
157 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
158 let param_env = ty::ParamEnv::empty();
159 if self.can_sub(param_env, error, implication).is_ok() {
160 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
169 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
170 body_id: Option<hir::BodyId>,
171 fallback_has_occurred: bool) {
172 debug!("report_fulfillment_errors({:?})", error);
174 FulfillmentErrorCode::CodeSelectionError(ref e) => {
175 self.report_selection_error(&error.obligation, e, fallback_has_occurred);
177 FulfillmentErrorCode::CodeProjectionError(ref e) => {
178 self.report_projection_error(&error.obligation, e);
180 FulfillmentErrorCode::CodeAmbiguity => {
181 self.maybe_report_ambiguity(&error.obligation, body_id);
183 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
184 self.report_mismatched_types(&error.obligation.cause,
185 expected_found.expected,
186 expected_found.found,
193 fn report_projection_error(&self,
194 obligation: &PredicateObligation<'tcx>,
195 error: &MismatchedProjectionTypes<'tcx>)
198 self.resolve_type_vars_if_possible(&obligation.predicate);
200 if predicate.references_error() {
206 let mut err = &error.err;
207 let mut values = None;
209 // try to find the mismatched types to report the error with.
211 // this can fail if the problem was higher-ranked, in which
212 // cause I have no idea for a good error message.
213 if let ty::Predicate::Projection(ref data) = predicate {
214 let mut selcx = SelectionContext::new(self);
215 let (data, _) = self.replace_bound_vars_with_fresh_vars(
216 obligation.cause.span,
217 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);
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::Placeholder(..) | ty::Bound(..) | 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)));
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.global_tcx()
759 .object_safety_violations(trait_def_id);
760 self.tcx.report_object_safety_error(span,
765 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
766 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
767 let closure_span = self.tcx.sess.source_map()
768 .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
769 let node_id = self.tcx.hir().as_local_node_id(closure_def_id).unwrap();
770 let mut err = struct_span_err!(
771 self.tcx.sess, closure_span, E0525,
772 "expected a closure that implements the `{}` trait, \
773 but this closure only implements `{}`",
779 format!("this closure implements `{}`, not `{}`", found_kind, kind));
781 obligation.cause.span,
782 format!("the requirement to implement `{}` derives from here", kind));
784 // Additional context information explaining why the closure only implements
785 // a particular trait.
786 if let Some(tables) = self.in_progress_tables {
787 let tables = tables.borrow();
788 let closure_hir_id = self.tcx.hir().node_to_hir_id(node_id);
789 match (found_kind, tables.closure_kind_origins().get(closure_hir_id)) {
790 (ty::ClosureKind::FnOnce, Some((span, name))) => {
791 err.span_label(*span, format!(
792 "closure is `FnOnce` because it moves the \
793 variable `{}` out of its environment", name));
795 (ty::ClosureKind::FnMut, Some((span, name))) => {
796 err.span_label(*span, format!(
797 "closure is `FnMut` because it mutates the \
798 variable `{}` here", name));
808 ty::Predicate::WellFormed(ty) => {
809 // WF predicates cannot themselves make
810 // errors. They can only block due to
811 // ambiguity; otherwise, they always
812 // degenerate into other obligations
814 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
817 ty::Predicate::ConstEvaluatable(..) => {
818 // Errors for `ConstEvaluatable` predicates show up as
819 // `SelectionError::ConstEvalFailure`,
820 // not `Unimplemented`.
822 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
827 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
828 let found_trait_ref = self.resolve_type_vars_if_possible(&*found_trait_ref);
829 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
831 if expected_trait_ref.self_ty().references_error() {
835 let found_trait_ty = found_trait_ref.self_ty();
837 let found_did = match found_trait_ty.sty {
838 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
839 ty::Adt(def, _) => Some(def.did),
843 let found_span = found_did.and_then(|did|
844 self.tcx.hir().span_if_local(did)
845 ).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
847 let found = match found_trait_ref.skip_binder().substs.type_at(1).sty {
848 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
849 _ => vec![ArgKind::empty()],
852 let expected = match expected_trait_ref.skip_binder().substs.type_at(1).sty {
853 ty::Tuple(ref tys) => tys.iter()
854 .map(|t| ArgKind::from_expected_ty(t, Some(span))).collect(),
855 ref sty => vec![ArgKind::Arg("_".to_owned(), sty.to_string())],
858 if found.len() == expected.len() {
859 self.report_closure_arg_mismatch(span,
864 let (closure_span, found) = found_did
865 .and_then(|did| self.tcx.hir().get_if_local(did))
867 let (found_span, found) = self.get_fn_like_arguments(node);
868 (Some(found_span), found)
869 }).unwrap_or((found_span, found));
871 self.report_arg_count_mismatch(span,
875 found_trait_ty.is_closure())
879 TraitNotObjectSafe(did) => {
880 let violations = self.tcx.global_tcx().object_safety_violations(did);
881 self.tcx.report_object_safety_error(span, did, violations)
884 // already reported in the query
885 ConstEvalFailure(_) => {
886 self.tcx.sess.delay_span_bug(span, "constant in type had an ignored error");
891 bug!("overflow should be handled before the `report_selection_error` path");
894 self.note_obligation_cause(&mut err, obligation);
898 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
899 /// suggestion to borrow the initializer in order to use have a slice instead.
900 fn suggest_borrow_on_unsized_slice(&self,
901 code: &ObligationCauseCode<'tcx>,
902 err: &mut DiagnosticBuilder<'tcx>) {
903 if let &ObligationCauseCode::VariableType(node_id) = code {
904 let parent_node = self.tcx.hir().get_parent_node(node_id);
905 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
906 if let Some(ref expr) = local.init {
907 if let hir::ExprKind::Index(_, _) = expr.node {
908 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
909 err.span_suggestion_with_applicability(
911 "consider borrowing here",
912 format!("&{}", snippet),
913 Applicability::MachineApplicable
922 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
923 /// suggest removing these references until we reach a type that implements the trait.
924 fn suggest_remove_reference(&self,
925 obligation: &PredicateObligation<'tcx>,
926 err: &mut DiagnosticBuilder<'tcx>,
927 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>) {
928 let trait_ref = trait_ref.skip_binder();
929 let span = obligation.cause.span;
931 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
932 let refs_number = snippet.chars()
933 .filter(|c| !c.is_whitespace())
934 .take_while(|c| *c == '&')
937 let mut trait_type = trait_ref.self_ty();
939 for refs_remaining in 0..refs_number {
940 if let ty::Ref(_, t_type, _) = trait_type.sty {
943 let substs = self.tcx.mk_substs_trait(trait_type, &[]);
944 let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
945 let new_obligation = Obligation::new(ObligationCause::dummy(),
946 obligation.param_env,
947 new_trait_ref.to_predicate());
949 if self.predicate_may_hold(&new_obligation) {
950 let sp = self.tcx.sess.source_map()
951 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
953 let remove_refs = refs_remaining + 1;
954 let format_str = format!("consider removing {} leading `&`-references",
957 err.span_suggestion_short_with_applicability(
958 sp, &format_str, String::new(), Applicability::MachineApplicable
969 /// Given some node representing a fn-like thing in the HIR map,
970 /// returns a span and `ArgKind` information that describes the
971 /// arguments it expects. This can be supplied to
972 /// `report_arg_count_mismatch`.
973 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
975 Node::Expr(&hir::Expr {
976 node: hir::ExprKind::Closure(_, ref _decl, id, span, _),
979 (self.tcx.sess.source_map().def_span(span), self.tcx.hir().body(id).arguments.iter()
982 node: hir::PatKind::Tuple(args, _),
985 } = arg.pat.clone().into_inner() {
988 args.iter().map(|pat| {
989 let snippet = self.tcx.sess.source_map()
990 .span_to_snippet(pat.span).unwrap();
991 (snippet, "_".to_owned())
992 }).collect::<Vec<_>>(),
995 let name = self.tcx.sess.source_map()
996 .span_to_snippet(arg.pat.span).unwrap();
997 ArgKind::Arg(name, "_".to_owned())
1000 .collect::<Vec<ArgKind>>())
1002 Node::Item(&hir::Item {
1004 node: hir::ItemKind::Fn(ref decl, ..),
1007 Node::ImplItem(&hir::ImplItem {
1009 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1012 Node::TraitItem(&hir::TraitItem {
1014 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1017 (self.tcx.sess.source_map().def_span(span), decl.inputs.iter()
1018 .map(|arg| match arg.clone().node {
1019 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1021 vec![("_".to_owned(), "_".to_owned()); tys.len()]
1023 _ => ArgKind::empty()
1024 }).collect::<Vec<ArgKind>>())
1026 Node::Variant(&hir::Variant {
1028 node: hir::VariantKind {
1029 data: hir::VariantData::Tuple(ref fields, _),
1034 (self.tcx.sess.source_map().def_span(span),
1035 fields.iter().map(|field|
1036 ArgKind::Arg(field.ident.to_string(), "_".to_string())
1037 ).collect::<Vec<_>>())
1039 Node::StructCtor(ref variant_data) => {
1040 (self.tcx.sess.source_map().def_span(self.tcx.hir().span(variant_data.id())),
1041 vec![ArgKind::empty(); variant_data.fields().len()])
1043 _ => panic!("non-FnLike node found: {:?}", node),
1047 /// Reports an error when the number of arguments needed by a
1048 /// trait match doesn't match the number that the expression
1050 pub fn report_arg_count_mismatch(
1053 found_span: Option<Span>,
1054 expected_args: Vec<ArgKind>,
1055 found_args: Vec<ArgKind>,
1057 ) -> DiagnosticBuilder<'tcx> {
1058 let kind = if is_closure { "closure" } else { "function" };
1060 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1061 let arg_length = arguments.len();
1062 let distinct = match &other[..] {
1063 &[ArgKind::Tuple(..)] => true,
1066 match (arg_length, arguments.get(0)) {
1067 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1068 format!("a single {}-tuple as argument", fields.len())
1070 _ => format!("{} {}argument{}",
1072 if distinct && arg_length > 1 { "distinct " } else { "" },
1073 if arg_length == 1 { "" } else { "s" }),
1077 let expected_str = args_str(&expected_args, &found_args);
1078 let found_str = args_str(&found_args, &expected_args);
1080 let mut err = struct_span_err!(
1084 "{} is expected to take {}, but it takes {}",
1090 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1092 if let Some(found_span) = found_span {
1093 err.span_label(found_span, format!("takes {}", found_str));
1096 // ^^^^^^^^-- def_span
1100 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1103 let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) {
1109 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1110 // found arguments is empty (assume the user just wants to ignore args in this case).
1111 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1112 if found_args.is_empty() && is_closure {
1113 let underscores = vec!["_"; expected_args.len()].join(", ");
1114 err.span_suggestion_with_applicability(
1117 "consider changing the closure to take and ignore the expected argument{}",
1118 if expected_args.len() < 2 {
1124 format!("|{}|", underscores),
1125 Applicability::MachineApplicable,
1129 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1130 if fields.len() == expected_args.len() {
1131 let sugg = fields.iter()
1132 .map(|(name, _)| name.to_owned())
1133 .collect::<Vec<String>>()
1135 err.span_suggestion_with_applicability(found_span,
1136 "change the closure to take multiple \
1137 arguments instead of a single tuple",
1138 format!("|{}|", sugg),
1139 Applicability::MachineApplicable);
1142 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1143 if fields.len() == found_args.len() && is_closure {
1147 .map(|arg| match arg {
1148 ArgKind::Arg(name, _) => name.to_owned(),
1149 _ => "_".to_owned(),
1151 .collect::<Vec<String>>()
1153 // add type annotations if available
1154 if found_args.iter().any(|arg| match arg {
1155 ArgKind::Arg(_, ty) => ty != "_",
1160 .map(|(_, ty)| ty.to_owned())
1161 .collect::<Vec<String>>()
1167 err.span_suggestion_with_applicability(
1169 "change the closure to accept a tuple instead of \
1170 individual arguments",
1172 Applicability::MachineApplicable
1181 fn report_closure_arg_mismatch(&self,
1183 found_span: Option<Span>,
1184 expected_ref: ty::PolyTraitRef<'tcx>,
1185 found: ty::PolyTraitRef<'tcx>)
1186 -> DiagnosticBuilder<'tcx>
1188 fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
1189 trait_ref: &ty::TraitRef<'tcx>) -> String {
1190 let inputs = trait_ref.substs.type_at(1);
1191 let sig = if let ty::Tuple(inputs) = inputs.sty {
1193 inputs.iter().cloned(),
1194 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1196 hir::Unsafety::Normal,
1197 ::rustc_target::spec::abi::Abi::Rust
1201 ::std::iter::once(inputs),
1202 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1204 hir::Unsafety::Normal,
1205 ::rustc_target::spec::abi::Abi::Rust
1208 ty::Binder::bind(sig).to_string()
1211 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1212 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1213 "type mismatch in {} arguments",
1214 if argument_is_closure { "closure" } else { "function" });
1216 let found_str = format!(
1217 "expected signature of `{}`",
1218 build_fn_sig_string(self.tcx, found.skip_binder())
1220 err.span_label(span, found_str);
1222 let found_span = found_span.unwrap_or(span);
1223 let expected_str = format!(
1224 "found signature of `{}`",
1225 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1227 err.span_label(found_span, expected_str);
1233 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1234 pub fn recursive_type_with_infinite_size_error(self,
1236 -> DiagnosticBuilder<'tcx>
1238 assert!(type_def_id.is_local());
1239 let span = self.hir().span_if_local(type_def_id).unwrap();
1240 let span = self.sess.source_map().def_span(span);
1241 let mut err = struct_span_err!(self.sess, span, E0072,
1242 "recursive type `{}` has infinite size",
1243 self.item_path_str(type_def_id));
1244 err.span_label(span, "recursive type has infinite size");
1245 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1246 at some point to make `{}` representable",
1247 self.item_path_str(type_def_id)));
1251 pub fn report_object_safety_error(self,
1253 trait_def_id: DefId,
1254 violations: Vec<ObjectSafetyViolation>)
1255 -> DiagnosticBuilder<'tcx>
1257 let trait_str = self.item_path_str(trait_def_id);
1258 let span = self.sess.source_map().def_span(span);
1259 let mut err = struct_span_err!(
1260 self.sess, span, E0038,
1261 "the trait `{}` cannot be made into an object",
1263 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1265 let mut reported_violations = FxHashSet::default();
1266 for violation in violations {
1267 if reported_violations.insert(violation.clone()) {
1268 err.note(&violation.error_msg());
1275 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1276 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1277 body_id: Option<hir::BodyId>) {
1278 // Unable to successfully determine, probably means
1279 // insufficient type information, but could mean
1280 // ambiguous impls. The latter *ought* to be a
1281 // coherence violation, so we don't report it here.
1283 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1284 let span = obligation.cause.span;
1286 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1290 // Ambiguity errors are often caused as fallout from earlier
1291 // errors. So just ignore them if this infcx is tainted.
1292 if self.is_tainted_by_errors() {
1297 ty::Predicate::Trait(ref data) => {
1298 let trait_ref = data.to_poly_trait_ref();
1299 let self_ty = trait_ref.self_ty();
1300 if predicate.references_error() {
1303 // Typically, this ambiguity should only happen if
1304 // there are unresolved type inference variables
1305 // (otherwise it would suggest a coherence
1306 // failure). But given #21974 that is not necessarily
1307 // the case -- we can have multiple where clauses that
1308 // are only distinguished by a region, which results
1309 // in an ambiguity even when all types are fully
1310 // known, since we don't dispatch based on region
1313 // This is kind of a hack: it frequently happens that some earlier
1314 // error prevents types from being fully inferred, and then we get
1315 // a bunch of uninteresting errors saying something like "<generic
1316 // #0> doesn't implement Sized". It may even be true that we
1317 // could just skip over all checks where the self-ty is an
1318 // inference variable, but I was afraid that there might be an
1319 // inference variable created, registered as an obligation, and
1320 // then never forced by writeback, and hence by skipping here we'd
1321 // be ignoring the fact that we don't KNOW the type works
1322 // out. Though even that would probably be harmless, given that
1323 // we're only talking about builtin traits, which are known to be
1324 // inhabited. But in any case I just threw in this check for
1325 // has_errors() to be sure that compilation isn't happening
1326 // anyway. In that case, why inundate the user.
1327 if !self.tcx.sess.has_errors() {
1329 self.tcx.lang_items().sized_trait()
1330 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1332 self.need_type_info_err(body_id, span, self_ty).emit();
1334 let mut err = struct_span_err!(self.tcx.sess,
1336 "type annotations required: \
1337 cannot resolve `{}`",
1339 self.note_obligation_cause(&mut err, obligation);
1345 ty::Predicate::WellFormed(ty) => {
1346 // Same hacky approach as above to avoid deluging user
1347 // with error messages.
1348 if !ty.references_error() && !self.tcx.sess.has_errors() {
1349 self.need_type_info_err(body_id, span, ty).emit();
1353 ty::Predicate::Subtype(ref data) => {
1354 if data.references_error() || self.tcx.sess.has_errors() {
1355 // no need to overload user in such cases
1357 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1358 // both must be type variables, or the other would've been instantiated
1359 assert!(a.is_ty_var() && b.is_ty_var());
1360 self.need_type_info_err(body_id,
1361 obligation.cause.span,
1367 if !self.tcx.sess.has_errors() {
1368 let mut err = struct_span_err!(self.tcx.sess,
1369 obligation.cause.span, E0284,
1370 "type annotations required: \
1371 cannot resolve `{}`",
1373 self.note_obligation_cause(&mut err, obligation);
1380 /// Returns whether the trait predicate may apply for *some* assignment
1381 /// to the type parameters.
1382 fn predicate_can_apply(&self,
1383 param_env: ty::ParamEnv<'tcx>,
1384 pred: ty::PolyTraitRef<'tcx>)
1386 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1387 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1388 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1391 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1392 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1394 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1395 if let ty::Param(ty::ParamTy {name, ..}) = ty.sty {
1396 let infcx = self.infcx;
1397 self.var_map.entry(ty).or_insert_with(||
1399 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1401 ty.super_fold_with(self)
1407 let mut selcx = SelectionContext::new(self);
1409 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1411 var_map: Default::default()
1414 let cleaned_pred = super::project::normalize(
1417 ObligationCause::dummy(),
1421 let obligation = Obligation::new(
1422 ObligationCause::dummy(),
1424 cleaned_pred.to_predicate()
1427 self.predicate_may_hold(&obligation)
1431 fn note_obligation_cause<T>(&self,
1432 err: &mut DiagnosticBuilder<'_>,
1433 obligation: &Obligation<'tcx, T>)
1434 where T: fmt::Display
1436 self.note_obligation_cause_code(err,
1437 &obligation.predicate,
1438 &obligation.cause.code,
1442 fn note_obligation_cause_code<T>(&self,
1443 err: &mut DiagnosticBuilder<'_>,
1445 cause_code: &ObligationCauseCode<'tcx>,
1446 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1447 where T: fmt::Display
1451 ObligationCauseCode::ExprAssignable |
1452 ObligationCauseCode::MatchExpressionArm { .. } |
1453 ObligationCauseCode::IfExpression |
1454 ObligationCauseCode::IfExpressionWithNoElse |
1455 ObligationCauseCode::MainFunctionType |
1456 ObligationCauseCode::StartFunctionType |
1457 ObligationCauseCode::IntrinsicType |
1458 ObligationCauseCode::MethodReceiver |
1459 ObligationCauseCode::ReturnNoExpression |
1460 ObligationCauseCode::MiscObligation => {
1462 ObligationCauseCode::SliceOrArrayElem => {
1463 err.note("slice and array elements must have `Sized` type");
1465 ObligationCauseCode::TupleElem => {
1466 err.note("only the last element of a tuple may have a dynamically sized type");
1468 ObligationCauseCode::ProjectionWf(data) => {
1469 err.note(&format!("required so that the projection `{}` is well-formed",
1472 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1473 err.note(&format!("required so that reference `{}` does not outlive its referent",
1476 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1477 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1479 region, object_ty));
1481 ObligationCauseCode::ItemObligation(item_def_id) => {
1482 let item_name = tcx.item_path_str(item_def_id);
1483 let msg = format!("required by `{}`", item_name);
1485 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1486 let sp = tcx.sess.source_map().def_span(sp);
1487 err.span_note(sp, &msg);
1492 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1493 err.note(&format!("required for the cast to the object type `{}`",
1494 self.ty_to_string(object_ty)));
1496 ObligationCauseCode::RepeatVec => {
1497 err.note("the `Copy` trait is required because the \
1498 repeated element will be copied");
1500 ObligationCauseCode::VariableType(_) => {
1501 err.note("all local variables must have a statically known size");
1502 if !self.tcx.features().unsized_locals {
1503 err.help("unsized locals are gated as an unstable feature");
1506 ObligationCauseCode::SizedArgumentType => {
1507 err.note("all function arguments must have a statically known size");
1508 if !self.tcx.features().unsized_locals {
1509 err.help("unsized locals are gated as an unstable feature");
1512 ObligationCauseCode::SizedReturnType => {
1513 err.note("the return type of a function must have a \
1514 statically known size");
1516 ObligationCauseCode::SizedYieldType => {
1517 err.note("the yield type of a generator must have a \
1518 statically known size");
1520 ObligationCauseCode::AssignmentLhsSized => {
1521 err.note("the left-hand-side of an assignment must have a statically known size");
1523 ObligationCauseCode::TupleInitializerSized => {
1524 err.note("tuples must have a statically known size to be initialized");
1526 ObligationCauseCode::StructInitializerSized => {
1527 err.note("structs must have a statically known size to be initialized");
1529 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
1531 AdtKind::Struct => {
1533 err.note("the last field of a packed struct may only have a \
1534 dynamically sized type if it does not need drop to be run");
1536 err.note("only the last field of a struct may have a dynamically \
1541 err.note("no field of a union may have a dynamically sized type");
1544 err.note("no field of an enum variant may have a dynamically sized type");
1548 ObligationCauseCode::ConstSized => {
1549 err.note("constant expressions must have a statically known size");
1551 ObligationCauseCode::SharedStatic => {
1552 err.note("shared static variables must have a type that implements `Sync`");
1554 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1555 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1556 let ty = parent_trait_ref.skip_binder().self_ty();
1557 err.note(&format!("required because it appears within the type `{}`", ty));
1558 obligated_types.push(ty);
1560 let parent_predicate = parent_trait_ref.to_predicate();
1561 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1562 self.note_obligation_cause_code(err,
1568 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1569 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1571 &format!("required because of the requirements on the impl of `{}` for `{}`",
1573 parent_trait_ref.skip_binder().self_ty()));
1574 let parent_predicate = parent_trait_ref.to_predicate();
1575 self.note_obligation_cause_code(err,
1580 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1582 &format!("the requirement `{}` appears on the impl method \
1583 but not on the corresponding trait method",
1586 ObligationCauseCode::ReturnType(_) |
1587 ObligationCauseCode::BlockTailExpression(_) => (),
1588 ObligationCauseCode::TrivialBound => {
1589 err.help("see issue #48214");
1590 if tcx.sess.opts.unstable_features.is_nightly_build() {
1591 err.help("add #![feature(trivial_bounds)] to the \
1592 crate attributes to enable",
1599 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1600 let current_limit = self.tcx.sess.recursion_limit.get();
1601 let suggested_limit = current_limit * 2;
1602 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1606 fn is_recursive_obligation(&self,
1607 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1608 cause_code: &ObligationCauseCode<'tcx>) -> bool {
1609 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1610 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1612 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1620 /// Summarizes information
1623 /// An argument of non-tuple type. Parameters are (name, ty)
1624 Arg(String, String),
1626 /// An argument of tuple type. For a "found" argument, the span is
1627 /// the locationo in the source of the pattern. For a "expected"
1628 /// argument, it will be None. The vector is a list of (name, ty)
1629 /// strings for the components of the tuple.
1630 Tuple(Option<Span>, Vec<(String, String)>),
1634 fn empty() -> ArgKind {
1635 ArgKind::Arg("_".to_owned(), "_".to_owned())
1638 /// Creates an `ArgKind` from the expected type of an
1639 /// argument. It has no name (`_`) and an optional source span.
1640 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
1642 ty::Tuple(ref tys) => ArgKind::Tuple(
1645 .map(|ty| ("_".to_owned(), ty.sty.to_string()))
1646 .collect::<Vec<_>>()
1648 _ => ArgKind::Arg("_".to_owned(), t.sty.to_string()),