4 MismatchedProjectionTypes,
8 OnUnimplementedDirective,
10 OutputTypeParameterMismatch,
16 ObjectSafetyViolation,
20 use errors::{Applicability, DiagnosticBuilder};
23 use hir::def_id::DefId;
24 use infer::{self, InferCtxt};
25 use infer::type_variable::TypeVariableOrigin;
28 use session::DiagnosticMessageId;
29 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
30 use ty::GenericParamDefKind;
31 use ty::error::ExpectedFound;
33 use ty::fold::TypeFolder;
35 use ty::SubtypePredicate;
36 use util::nodemap::{FxHashMap, FxHashSet};
38 use syntax_pos::{DUMMY_SP, Span, ExpnInfo, ExpnFormat};
40 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
41 pub fn report_fulfillment_errors(&self,
42 errors: &[FulfillmentError<'tcx>],
43 body_id: Option<hir::BodyId>,
44 fallback_has_occurred: bool) {
46 struct ErrorDescriptor<'tcx> {
47 predicate: ty::Predicate<'tcx>,
48 index: Option<usize>, // None if this is an old error
51 let mut error_map: FxHashMap<_, Vec<_>> =
52 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
53 (span, predicates.iter().map(|predicate| ErrorDescriptor {
54 predicate: predicate.clone(),
59 for (index, error) in errors.iter().enumerate() {
60 // We want to ignore desugarings here: spans are equivalent even
61 // if one is the result of a desugaring and the other is not.
62 let mut span = error.obligation.cause.span;
63 if let Some(ExpnInfo {
64 format: ExpnFormat::CompilerDesugaring(_),
65 def_site: Some(def_span),
67 }) = span.ctxt().outer().expn_info() {
71 error_map.entry(span).or_default().push(
73 predicate: error.obligation.predicate.clone(),
78 self.reported_trait_errors.borrow_mut()
79 .entry(span).or_default()
80 .push(error.obligation.predicate.clone());
83 // We do this in 2 passes because we want to display errors in order, though
84 // maybe it *is* better to sort errors by span or something.
85 let mut is_suppressed = vec![false; errors.len()];
86 for (_, error_set) in error_map.iter() {
87 // We want to suppress "duplicate" errors with the same span.
88 for error in error_set {
89 if let Some(index) = error.index {
90 // Suppress errors that are either:
91 // 1) strictly implied by another error.
92 // 2) implied by an error with a smaller index.
93 for error2 in error_set {
94 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
95 // Avoid errors being suppressed by already-suppressed
96 // errors, to prevent all errors from being suppressed
101 if self.error_implies(&error2.predicate, &error.predicate) &&
102 !(error2.index >= error.index &&
103 self.error_implies(&error.predicate, &error2.predicate))
105 info!("skipping {:?} (implied by {:?})", error, error2);
106 is_suppressed[index] = true;
114 for (error, suppressed) in errors.iter().zip(is_suppressed) {
116 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
121 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
122 // `error` occurring implies that `cond` occurs.
123 fn error_implies(&self,
124 cond: &ty::Predicate<'tcx>,
125 error: &ty::Predicate<'tcx>)
132 let (cond, error) = match (cond, error) {
133 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
136 // FIXME: make this work in other cases too.
141 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
142 if let ty::Predicate::Trait(implication) = implication {
143 let error = error.to_poly_trait_ref();
144 let implication = implication.to_poly_trait_ref();
145 // FIXME: I'm just not taking associated types at all here.
146 // Eventually I'll need to implement param-env-aware
147 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
148 let param_env = ty::ParamEnv::empty();
149 if self.can_sub(param_env, error, implication).is_ok() {
150 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
159 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
160 body_id: Option<hir::BodyId>,
161 fallback_has_occurred: bool) {
162 debug!("report_fulfillment_errors({:?})", error);
164 FulfillmentErrorCode::CodeSelectionError(ref e) => {
165 self.report_selection_error(&error.obligation, e, fallback_has_occurred);
167 FulfillmentErrorCode::CodeProjectionError(ref e) => {
168 self.report_projection_error(&error.obligation, e);
170 FulfillmentErrorCode::CodeAmbiguity => {
171 self.maybe_report_ambiguity(&error.obligation, body_id);
173 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
174 self.report_mismatched_types(&error.obligation.cause,
175 expected_found.expected,
176 expected_found.found,
183 fn report_projection_error(&self,
184 obligation: &PredicateObligation<'tcx>,
185 error: &MismatchedProjectionTypes<'tcx>)
188 self.resolve_type_vars_if_possible(&obligation.predicate);
190 if predicate.references_error() {
196 let mut err = &error.err;
197 let mut values = None;
199 // try to find the mismatched types to report the error with.
201 // this can fail if the problem was higher-ranked, in which
202 // cause I have no idea for a good error message.
203 if let ty::Predicate::Projection(ref data) = predicate {
204 let mut selcx = SelectionContext::new(self);
205 let (data, _) = self.replace_bound_vars_with_fresh_vars(
206 obligation.cause.span,
207 infer::LateBoundRegionConversionTime::HigherRankedType,
210 let mut obligations = vec![];
211 let normalized_ty = super::normalize_projection_type(
213 obligation.param_env,
215 obligation.cause.clone(),
219 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
220 .eq(normalized_ty, data.ty) {
221 values = Some(infer::ValuePairs::Types(ExpectedFound {
222 expected: normalized_ty,
230 let msg = format!("type mismatch resolving `{}`", predicate);
231 let error_id = (DiagnosticMessageId::ErrorId(271),
232 Some(obligation.cause.span), msg);
233 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
235 let mut diag = struct_span_err!(
236 self.tcx.sess, obligation.cause.span, E0271,
237 "type mismatch resolving `{}`", predicate
239 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
240 self.note_obligation_cause(&mut diag, obligation);
246 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
247 /// returns the fuzzy category of a given type, or None
248 /// if the type can be equated to any type.
249 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
254 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
255 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
256 ty::Ref(..) | ty::RawPtr(..) => Some(5),
257 ty::Array(..) | ty::Slice(..) => Some(6),
258 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
259 ty::Dynamic(..) => Some(8),
260 ty::Closure(..) => Some(9),
261 ty::Tuple(..) => Some(10),
262 ty::Projection(..) => Some(11),
263 ty::Param(..) => Some(12),
264 ty::Opaque(..) => Some(13),
265 ty::Never => Some(14),
266 ty::Adt(adt, ..) => match adt.adt_kind() {
267 AdtKind::Struct => Some(15),
268 AdtKind::Union => Some(16),
269 AdtKind::Enum => Some(17),
271 ty::Generator(..) => Some(18),
272 ty::Foreign(..) => Some(19),
273 ty::GeneratorWitness(..) => Some(20),
274 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
275 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
279 match (type_category(a), type_category(b)) {
280 (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
281 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
284 // infer and error can be equated to all types
289 fn impl_similar_to(&self,
290 trait_ref: ty::PolyTraitRef<'tcx>,
291 obligation: &PredicateObligation<'tcx>)
295 let param_env = obligation.param_env;
296 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
297 let trait_self_ty = trait_ref.self_ty();
299 let mut self_match_impls = vec![];
300 let mut fuzzy_match_impls = vec![];
302 self.tcx.for_each_relevant_impl(
303 trait_ref.def_id, trait_self_ty, |def_id| {
304 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
305 let impl_trait_ref = tcx
306 .impl_trait_ref(def_id)
308 .subst(tcx, impl_substs);
310 let impl_self_ty = impl_trait_ref.self_ty();
312 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
313 self_match_impls.push(def_id);
315 if trait_ref.substs.types().skip(1)
316 .zip(impl_trait_ref.substs.types().skip(1))
317 .all(|(u,v)| self.fuzzy_match_tys(u, v))
319 fuzzy_match_impls.push(def_id);
324 let impl_def_id = if self_match_impls.len() == 1 {
326 } else if fuzzy_match_impls.len() == 1 {
332 if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
339 fn on_unimplemented_note(
341 trait_ref: ty::PolyTraitRef<'tcx>,
342 obligation: &PredicateObligation<'tcx>,
343 ) -> OnUnimplementedNote {
344 let def_id = self.impl_similar_to(trait_ref, obligation)
345 .unwrap_or_else(|| trait_ref.def_id());
346 let trait_ref = *trait_ref.skip_binder();
348 let mut flags = vec![];
349 match obligation.cause.code {
350 ObligationCauseCode::BuiltinDerivedObligation(..) |
351 ObligationCauseCode::ImplDerivedObligation(..) => {}
353 // this is a "direct", user-specified, rather than derived,
355 flags.push(("direct".to_owned(), None));
359 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
360 // FIXME: maybe also have some way of handling methods
361 // from other traits? That would require name resolution,
362 // which we might want to be some sort of hygienic.
364 // Currently I'm leaving it for what I need for `try`.
365 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
366 let method = self.tcx.item_name(item);
367 flags.push(("from_method".to_owned(), None));
368 flags.push(("from_method".to_owned(), Some(method.to_string())));
371 if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
372 flags.push(("parent_trait".to_owned(), Some(t)));
375 if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
376 flags.push(("from_desugaring".to_owned(), None));
377 flags.push(("from_desugaring".to_owned(), Some(k.name().to_string())));
379 let generics = self.tcx.generics_of(def_id);
380 let self_ty = trait_ref.self_ty();
381 // This is also included through the generics list as `Self`,
382 // but the parser won't allow you to use it
383 flags.push(("_Self".to_owned(), Some(self_ty.to_string())));
384 if let Some(def) = self_ty.ty_adt_def() {
385 // We also want to be able to select self's original
386 // signature with no type arguments resolved
387 flags.push(("_Self".to_owned(), Some(self.tcx.type_of(def.did).to_string())));
390 for param in generics.params.iter() {
391 let value = match param.kind {
392 GenericParamDefKind::Type {..} => {
393 trait_ref.substs[param.index as usize].to_string()
395 GenericParamDefKind::Lifetime => continue,
397 let name = param.name.to_string();
398 flags.push((name, Some(value)));
401 if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
402 flags.push(("crate_local".to_owned(), None));
405 // Allow targeting all integers using `{integral}`, even if the exact type was resolved
406 if self_ty.is_integral() {
407 flags.push(("_Self".to_owned(), Some("{integral}".to_owned())));
410 if let ty::Array(aty, len) = self_ty.sty {
411 flags.push(("_Self".to_owned(), Some("[]".to_owned())));
412 flags.push(("_Self".to_owned(), Some(format!("[{}]", aty))));
413 if let Some(def) = aty.ty_adt_def() {
414 // We also want to be able to select the array's type's original
415 // signature with no type arguments resolved
418 Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
421 if let Some(len) = len.val.try_to_scalar().and_then(|scalar| {
422 scalar.to_usize(&tcx).ok()
426 Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
431 Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
437 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
438 self.tcx, trait_ref.def_id, def_id
440 command.evaluate(self.tcx, trait_ref, &flags[..])
442 OnUnimplementedNote::empty()
446 fn find_similar_impl_candidates(&self,
447 trait_ref: ty::PolyTraitRef<'tcx>)
448 -> Vec<ty::TraitRef<'tcx>>
450 let simp = fast_reject::simplify_type(self.tcx,
451 trait_ref.skip_binder().self_ty(),
453 let all_impls = self.tcx.all_impls(trait_ref.def_id());
456 Some(simp) => all_impls.iter().filter_map(|&def_id| {
457 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
458 let imp_simp = fast_reject::simplify_type(self.tcx,
461 if let Some(imp_simp) = imp_simp {
462 if simp != imp_simp {
469 None => all_impls.iter().map(|&def_id|
470 self.tcx.impl_trait_ref(def_id).unwrap()
475 fn report_similar_impl_candidates(&self,
476 mut impl_candidates: Vec<ty::TraitRef<'tcx>>,
477 err: &mut DiagnosticBuilder<'_>)
479 if impl_candidates.is_empty() {
483 let len = impl_candidates.len();
484 let end = if impl_candidates.len() <= 5 {
485 impl_candidates.len()
490 let normalize = |candidate| self.tcx.global_tcx().infer_ctxt().enter(|ref infcx| {
491 let normalized = infcx
492 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
493 .normalize(candidate)
496 Some(normalized) => format!("\n {:?}", normalized.value),
497 None => format!("\n {:?}", candidate),
501 // Sort impl candidates so that ordering is consistent for UI tests.
502 let normalized_impl_candidates = &mut impl_candidates[0..end]
505 .collect::<Vec<String>>();
506 normalized_impl_candidates.sort();
508 err.help(&format!("the following implementations were found:{}{}",
509 normalized_impl_candidates.join(""),
511 format!("\nand {} others", len - 4)
518 /// Reports that an overflow has occurred and halts compilation. We
519 /// halt compilation unconditionally because it is important that
520 /// overflows never be masked -- they basically represent computations
521 /// whose result could not be truly determined and thus we can't say
522 /// if the program type checks or not -- and they are unusual
523 /// occurrences in any case.
524 pub fn report_overflow_error<T>(&self,
525 obligation: &Obligation<'tcx, T>,
526 suggest_increasing_limit: bool) -> !
527 where T: fmt::Display + TypeFoldable<'tcx>
530 self.resolve_type_vars_if_possible(&obligation.predicate);
531 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
532 "overflow evaluating the requirement `{}`",
535 if suggest_increasing_limit {
536 self.suggest_new_overflow_limit(&mut err);
539 self.note_obligation_cause(&mut err, obligation);
542 self.tcx.sess.abort_if_errors();
546 /// Reports that a cycle was detected which led to overflow and halts
547 /// compilation. This is equivalent to `report_overflow_error` except
548 /// that we can give a more helpful error message (and, in particular,
549 /// we do not suggest increasing the overflow limit, which is not
551 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
552 let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
553 assert!(cycle.len() > 0);
555 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
557 self.report_overflow_error(&cycle[0], false);
560 pub fn report_extra_impl_obligation(&self,
562 item_name: ast::Name,
563 _impl_item_def_id: DefId,
564 trait_item_def_id: DefId,
565 requirement: &dyn fmt::Display)
566 -> DiagnosticBuilder<'tcx>
568 let msg = "impl has stricter requirements than trait";
569 let sp = self.tcx.sess.source_map().def_span(error_span);
571 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
573 if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
574 let span = self.tcx.sess.source_map().def_span(trait_item_span);
575 err.span_label(span, format!("definition of `{}` from trait", item_name));
578 err.span_label(sp, format!("impl has extra requirement {}", requirement));
584 /// Get the parent trait chain start
585 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
587 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
588 let parent_trait_ref = self.resolve_type_vars_if_possible(
589 &data.parent_trait_ref);
590 match self.get_parent_trait_ref(&data.parent_code) {
592 None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
599 pub fn report_selection_error(&self,
600 obligation: &PredicateObligation<'tcx>,
601 error: &SelectionError<'tcx>,
602 fallback_has_occurred: bool)
604 let span = obligation.cause.span;
606 let mut err = match *error {
607 SelectionError::Unimplemented => {
608 if let ObligationCauseCode::CompareImplMethodObligation {
609 item_name, impl_item_def_id, trait_item_def_id,
610 } = obligation.cause.code {
611 self.report_extra_impl_obligation(
616 &format!("`{}`", obligation.predicate))
620 match obligation.predicate {
621 ty::Predicate::Trait(ref trait_predicate) => {
622 let trait_predicate =
623 self.resolve_type_vars_if_possible(trait_predicate);
625 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
628 let trait_ref = trait_predicate.to_poly_trait_ref();
629 let (post_message, pre_message) =
630 self.get_parent_trait_ref(&obligation.cause.code)
631 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
632 .unwrap_or_default();
634 let OnUnimplementedNote { message, label, note }
635 = self.on_unimplemented_note(trait_ref, obligation);
636 let have_alt_message = message.is_some() || label.is_some();
638 let mut err = struct_span_err!(
643 message.unwrap_or_else(||
644 format!("the trait bound `{}` is not satisfied{}",
645 trait_ref.to_predicate(), post_message)
649 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
650 "consider using `()`, or a `Result`".to_owned()
652 format!("{}the trait `{}` is not implemented for `{}`",
658 if let Some(ref s) = label {
659 // If it has a custom "#[rustc_on_unimplemented]"
660 // error message, let's display it as the label!
661 err.span_label(span, s.as_str());
662 err.help(&explanation);
664 err.span_label(span, explanation);
666 if let Some(ref s) = note {
667 // If it has a custom "#[rustc_on_unimplemented]" note, let's display it
668 err.note(s.as_str());
671 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
672 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
674 // Try to report a help message
675 if !trait_ref.has_infer_types() &&
676 self.predicate_can_apply(obligation.param_env, trait_ref) {
677 // If a where-clause may be useful, remind the
678 // user that they can add it.
680 // don't display an on-unimplemented note, as
681 // these notes will often be of the form
682 // "the type `T` can't be frobnicated"
683 // which is somewhat confusing.
684 err.help(&format!("consider adding a `where {}` bound",
685 trait_ref.to_predicate()));
686 } else if !have_alt_message {
687 // Can't show anything else useful, try to find similar impls.
688 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
689 self.report_similar_impl_candidates(impl_candidates, &mut err);
692 // If this error is due to `!: Trait` not implemented but `(): Trait` is
693 // implemented, and fallback has occurred, then it could be due to a
694 // variable that used to fallback to `()` now falling back to `!`. Issue a
695 // note informing about the change in behaviour.
696 if trait_predicate.skip_binder().self_ty().is_never()
697 && fallback_has_occurred
699 let predicate = trait_predicate.map_bound(|mut trait_pred| {
700 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
702 &trait_pred.trait_ref.substs[1..],
706 let unit_obligation = Obligation {
707 predicate: ty::Predicate::Trait(predicate),
708 .. obligation.clone()
710 if self.predicate_may_hold(&unit_obligation) {
711 err.note("the trait is implemented for `()`. \
712 Possibly this error has been caused by changes to \
713 Rust's type-inference algorithm \
714 (see: https://github.com/rust-lang/rust/issues/48950 \
715 for more info). Consider whether you meant to use the \
716 type `()` here instead.");
723 ty::Predicate::Subtype(ref predicate) => {
724 // Errors for Subtype predicates show up as
725 // `FulfillmentErrorCode::CodeSubtypeError`,
726 // not selection error.
727 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
730 ty::Predicate::RegionOutlives(ref predicate) => {
731 let predicate = self.resolve_type_vars_if_possible(predicate);
732 let err = self.region_outlives_predicate(&obligation.cause,
733 &predicate).err().unwrap();
734 struct_span_err!(self.tcx.sess, span, E0279,
735 "the requirement `{}` is not satisfied (`{}`)",
739 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
741 self.resolve_type_vars_if_possible(&obligation.predicate);
742 struct_span_err!(self.tcx.sess, span, E0280,
743 "the requirement `{}` is not satisfied",
747 ty::Predicate::ObjectSafe(trait_def_id) => {
748 let violations = self.tcx.global_tcx()
749 .object_safety_violations(trait_def_id);
750 self.tcx.report_object_safety_error(span,
755 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
756 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
757 let closure_span = self.tcx.sess.source_map()
758 .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
759 let node_id = self.tcx.hir().as_local_node_id(closure_def_id).unwrap();
760 let mut err = struct_span_err!(
761 self.tcx.sess, closure_span, E0525,
762 "expected a closure that implements the `{}` trait, \
763 but this closure only implements `{}`",
769 format!("this closure implements `{}`, not `{}`", found_kind, kind));
771 obligation.cause.span,
772 format!("the requirement to implement `{}` derives from here", kind));
774 // Additional context information explaining why the closure only implements
775 // a particular trait.
776 if let Some(tables) = self.in_progress_tables {
777 let tables = tables.borrow();
778 let closure_hir_id = self.tcx.hir().node_to_hir_id(node_id);
779 match (found_kind, tables.closure_kind_origins().get(closure_hir_id)) {
780 (ty::ClosureKind::FnOnce, Some((span, name))) => {
781 err.span_label(*span, format!(
782 "closure is `FnOnce` because it moves the \
783 variable `{}` out of its environment", name));
785 (ty::ClosureKind::FnMut, Some((span, name))) => {
786 err.span_label(*span, format!(
787 "closure is `FnMut` because it mutates the \
788 variable `{}` here", name));
798 ty::Predicate::WellFormed(ty) => {
799 if !self.tcx.sess.opts.debugging_opts.chalk {
800 // WF predicates cannot themselves make
801 // errors. They can only block due to
802 // ambiguity; otherwise, they always
803 // degenerate into other obligations
805 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
807 // FIXME: we'll need a better message which takes into account
808 // which bounds actually failed to hold.
809 self.tcx.sess.struct_span_err(
811 &format!("the type `{}` is not well-formed (chalk)", 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.global_tcx().object_safety_violations(did);
880 self.tcx.report_object_safety_error(span, did, violations)
883 // already reported in the query
884 ConstEvalFailure(_) => {
885 self.tcx.sess.delay_span_bug(span, "constant in type had an ignored error");
890 bug!("overflow should be handled before the `report_selection_error` path");
893 self.note_obligation_cause(&mut err, obligation);
897 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
898 /// suggestion to borrow the initializer in order to use have a slice instead.
899 fn suggest_borrow_on_unsized_slice(&self,
900 code: &ObligationCauseCode<'tcx>,
901 err: &mut DiagnosticBuilder<'tcx>) {
902 if let &ObligationCauseCode::VariableType(node_id) = code {
903 let parent_node = self.tcx.hir().get_parent_node(node_id);
904 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
905 if let Some(ref expr) = local.init {
906 if let hir::ExprKind::Index(_, _) = expr.node {
907 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
908 err.span_suggestion_with_applicability(
910 "consider borrowing here",
911 format!("&{}", snippet),
912 Applicability::MachineApplicable
921 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
922 /// suggest removing these references until we reach a type that implements the trait.
923 fn suggest_remove_reference(&self,
924 obligation: &PredicateObligation<'tcx>,
925 err: &mut DiagnosticBuilder<'tcx>,
926 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>) {
927 let trait_ref = trait_ref.skip_binder();
928 let span = obligation.cause.span;
930 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
931 let refs_number = snippet.chars()
932 .filter(|c| !c.is_whitespace())
933 .take_while(|c| *c == '&')
936 let mut trait_type = trait_ref.self_ty();
938 for refs_remaining in 0..refs_number {
939 if let ty::Ref(_, t_type, _) = trait_type.sty {
942 let substs = self.tcx.mk_substs_trait(trait_type, &[]);
943 let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
944 let new_obligation = Obligation::new(ObligationCause::dummy(),
945 obligation.param_env,
946 new_trait_ref.to_predicate());
948 if self.predicate_may_hold(&new_obligation) {
949 let sp = self.tcx.sess.source_map()
950 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
952 let remove_refs = refs_remaining + 1;
953 let format_str = format!("consider removing {} leading `&`-references",
956 err.span_suggestion_short_with_applicability(
957 sp, &format_str, String::new(), Applicability::MachineApplicable
968 /// Given some node representing a fn-like thing in the HIR map,
969 /// returns a span and `ArgKind` information that describes the
970 /// arguments it expects. This can be supplied to
971 /// `report_arg_count_mismatch`.
972 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
974 Node::Expr(&hir::Expr {
975 node: hir::ExprKind::Closure(_, ref _decl, id, span, _),
978 (self.tcx.sess.source_map().def_span(span), self.tcx.hir().body(id).arguments.iter()
981 node: hir::PatKind::Tuple(args, _),
984 } = arg.pat.clone().into_inner() {
987 args.iter().map(|pat| {
988 let snippet = self.tcx.sess.source_map()
989 .span_to_snippet(pat.span).unwrap();
990 (snippet, "_".to_owned())
991 }).collect::<Vec<_>>(),
994 let name = self.tcx.sess.source_map()
995 .span_to_snippet(arg.pat.span).unwrap();
996 ArgKind::Arg(name, "_".to_owned())
999 .collect::<Vec<ArgKind>>())
1001 Node::Item(&hir::Item {
1003 node: hir::ItemKind::Fn(ref decl, ..),
1006 Node::ImplItem(&hir::ImplItem {
1008 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1011 Node::TraitItem(&hir::TraitItem {
1013 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
1016 (self.tcx.sess.source_map().def_span(span), decl.inputs.iter()
1017 .map(|arg| match arg.clone().node {
1018 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1020 vec![("_".to_owned(), "_".to_owned()); tys.len()]
1022 _ => ArgKind::empty()
1023 }).collect::<Vec<ArgKind>>())
1025 Node::Variant(&hir::Variant {
1027 node: hir::VariantKind {
1028 data: hir::VariantData::Tuple(ref fields, _),
1033 (self.tcx.sess.source_map().def_span(span),
1034 fields.iter().map(|field|
1035 ArgKind::Arg(field.ident.to_string(), "_".to_string())
1036 ).collect::<Vec<_>>())
1038 Node::StructCtor(ref variant_data) => {
1039 (self.tcx.sess.source_map().def_span(self.tcx.hir().span(variant_data.id())),
1040 vec![ArgKind::empty(); variant_data.fields().len()])
1042 _ => panic!("non-FnLike node found: {:?}", node),
1046 /// Reports an error when the number of arguments needed by a
1047 /// trait match doesn't match the number that the expression
1049 pub fn report_arg_count_mismatch(
1052 found_span: Option<Span>,
1053 expected_args: Vec<ArgKind>,
1054 found_args: Vec<ArgKind>,
1056 ) -> DiagnosticBuilder<'tcx> {
1057 let kind = if is_closure { "closure" } else { "function" };
1059 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1060 let arg_length = arguments.len();
1061 let distinct = match &other[..] {
1062 &[ArgKind::Tuple(..)] => true,
1065 match (arg_length, arguments.get(0)) {
1066 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1067 format!("a single {}-tuple as argument", fields.len())
1069 _ => format!("{} {}argument{}",
1071 if distinct && arg_length > 1 { "distinct " } else { "" },
1072 if arg_length == 1 { "" } else { "s" }),
1076 let expected_str = args_str(&expected_args, &found_args);
1077 let found_str = args_str(&found_args, &expected_args);
1079 let mut err = struct_span_err!(
1083 "{} is expected to take {}, but it takes {}",
1089 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1091 if let Some(found_span) = found_span {
1092 err.span_label(found_span, format!("takes {}", found_str));
1095 // ^^^^^^^^-- def_span
1099 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1102 let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) {
1108 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1109 // found arguments is empty (assume the user just wants to ignore args in this case).
1110 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1111 if found_args.is_empty() && is_closure {
1112 let underscores = vec!["_"; expected_args.len()].join(", ");
1113 err.span_suggestion_with_applicability(
1116 "consider changing the closure to take and ignore the expected argument{}",
1117 if expected_args.len() < 2 {
1123 format!("|{}|", underscores),
1124 Applicability::MachineApplicable,
1128 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1129 if fields.len() == expected_args.len() {
1130 let sugg = fields.iter()
1131 .map(|(name, _)| name.to_owned())
1132 .collect::<Vec<String>>()
1134 err.span_suggestion_with_applicability(found_span,
1135 "change the closure to take multiple \
1136 arguments instead of a single tuple",
1137 format!("|{}|", sugg),
1138 Applicability::MachineApplicable);
1141 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1142 if fields.len() == found_args.len() && is_closure {
1146 .map(|arg| match arg {
1147 ArgKind::Arg(name, _) => name.to_owned(),
1148 _ => "_".to_owned(),
1150 .collect::<Vec<String>>()
1152 // add type annotations if available
1153 if found_args.iter().any(|arg| match arg {
1154 ArgKind::Arg(_, ty) => ty != "_",
1159 .map(|(_, ty)| ty.to_owned())
1160 .collect::<Vec<String>>()
1166 err.span_suggestion_with_applicability(
1168 "change the closure to accept a tuple instead of \
1169 individual arguments",
1171 Applicability::MachineApplicable
1180 fn report_closure_arg_mismatch(&self,
1182 found_span: Option<Span>,
1183 expected_ref: ty::PolyTraitRef<'tcx>,
1184 found: ty::PolyTraitRef<'tcx>)
1185 -> DiagnosticBuilder<'tcx>
1187 fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
1188 trait_ref: &ty::TraitRef<'tcx>) -> String {
1189 let inputs = trait_ref.substs.type_at(1);
1190 let sig = if let ty::Tuple(inputs) = inputs.sty {
1192 inputs.iter().cloned(),
1193 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1195 hir::Unsafety::Normal,
1196 ::rustc_target::spec::abi::Abi::Rust
1200 ::std::iter::once(inputs),
1201 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1203 hir::Unsafety::Normal,
1204 ::rustc_target::spec::abi::Abi::Rust
1207 ty::Binder::bind(sig).to_string()
1210 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1211 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1212 "type mismatch in {} arguments",
1213 if argument_is_closure { "closure" } else { "function" });
1215 let found_str = format!(
1216 "expected signature of `{}`",
1217 build_fn_sig_string(self.tcx, found.skip_binder())
1219 err.span_label(span, found_str);
1221 let found_span = found_span.unwrap_or(span);
1222 let expected_str = format!(
1223 "found signature of `{}`",
1224 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1226 err.span_label(found_span, expected_str);
1232 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1233 pub fn recursive_type_with_infinite_size_error(self,
1235 -> DiagnosticBuilder<'tcx>
1237 assert!(type_def_id.is_local());
1238 let span = self.hir().span_if_local(type_def_id).unwrap();
1239 let span = self.sess.source_map().def_span(span);
1240 let mut err = struct_span_err!(self.sess, span, E0072,
1241 "recursive type `{}` has infinite size",
1242 self.item_path_str(type_def_id));
1243 err.span_label(span, "recursive type has infinite size");
1244 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1245 at some point to make `{}` representable",
1246 self.item_path_str(type_def_id)));
1250 pub fn report_object_safety_error(self,
1252 trait_def_id: DefId,
1253 violations: Vec<ObjectSafetyViolation>)
1254 -> DiagnosticBuilder<'tcx>
1256 let trait_str = self.item_path_str(trait_def_id);
1257 let span = self.sess.source_map().def_span(span);
1258 let mut err = struct_span_err!(
1259 self.sess, span, E0038,
1260 "the trait `{}` cannot be made into an object",
1262 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1264 let mut reported_violations = FxHashSet::default();
1265 for violation in violations {
1266 if reported_violations.insert(violation.clone()) {
1267 err.note(&violation.error_msg());
1274 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1275 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1276 body_id: Option<hir::BodyId>) {
1277 // Unable to successfully determine, probably means
1278 // insufficient type information, but could mean
1279 // ambiguous impls. The latter *ought* to be a
1280 // coherence violation, so we don't report it here.
1282 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1283 let span = obligation.cause.span;
1285 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1289 // Ambiguity errors are often caused as fallout from earlier
1290 // errors. So just ignore them if this infcx is tainted.
1291 if self.is_tainted_by_errors() {
1296 ty::Predicate::Trait(ref data) => {
1297 let trait_ref = data.to_poly_trait_ref();
1298 let self_ty = trait_ref.self_ty();
1299 if predicate.references_error() {
1302 // Typically, this ambiguity should only happen if
1303 // there are unresolved type inference variables
1304 // (otherwise it would suggest a coherence
1305 // failure). But given #21974 that is not necessarily
1306 // the case -- we can have multiple where clauses that
1307 // are only distinguished by a region, which results
1308 // in an ambiguity even when all types are fully
1309 // known, since we don't dispatch based on region
1312 // This is kind of a hack: it frequently happens that some earlier
1313 // error prevents types from being fully inferred, and then we get
1314 // a bunch of uninteresting errors saying something like "<generic
1315 // #0> doesn't implement Sized". It may even be true that we
1316 // could just skip over all checks where the self-ty is an
1317 // inference variable, but I was afraid that there might be an
1318 // inference variable created, registered as an obligation, and
1319 // then never forced by writeback, and hence by skipping here we'd
1320 // be ignoring the fact that we don't KNOW the type works
1321 // out. Though even that would probably be harmless, given that
1322 // we're only talking about builtin traits, which are known to be
1323 // inhabited. But in any case I just threw in this check for
1324 // has_errors() to be sure that compilation isn't happening
1325 // anyway. In that case, why inundate the user.
1326 if !self.tcx.sess.has_errors() {
1328 self.tcx.lang_items().sized_trait()
1329 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1331 self.need_type_info_err(body_id, span, self_ty).emit();
1333 let mut err = struct_span_err!(self.tcx.sess,
1335 "type annotations required: \
1336 cannot resolve `{}`",
1338 self.note_obligation_cause(&mut err, obligation);
1344 ty::Predicate::WellFormed(ty) => {
1345 // Same hacky approach as above to avoid deluging user
1346 // with error messages.
1347 if !ty.references_error() && !self.tcx.sess.has_errors() {
1348 self.need_type_info_err(body_id, span, ty).emit();
1352 ty::Predicate::Subtype(ref data) => {
1353 if data.references_error() || self.tcx.sess.has_errors() {
1354 // no need to overload user in such cases
1356 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1357 // both must be type variables, or the other would've been instantiated
1358 assert!(a.is_ty_var() && b.is_ty_var());
1359 self.need_type_info_err(body_id,
1360 obligation.cause.span,
1366 if !self.tcx.sess.has_errors() {
1367 let mut err = struct_span_err!(self.tcx.sess,
1368 obligation.cause.span, E0284,
1369 "type annotations required: \
1370 cannot resolve `{}`",
1372 self.note_obligation_cause(&mut err, obligation);
1379 /// Returns whether the trait predicate may apply for *some* assignment
1380 /// to the type parameters.
1381 fn predicate_can_apply(&self,
1382 param_env: ty::ParamEnv<'tcx>,
1383 pred: ty::PolyTraitRef<'tcx>)
1385 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1386 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1387 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1390 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1391 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1393 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1394 if let ty::Param(ty::ParamTy {name, ..}) = ty.sty {
1395 let infcx = self.infcx;
1396 self.var_map.entry(ty).or_insert_with(||
1398 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1400 ty.super_fold_with(self)
1406 let mut selcx = SelectionContext::new(self);
1408 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1410 var_map: Default::default()
1413 let cleaned_pred = super::project::normalize(
1416 ObligationCause::dummy(),
1420 let obligation = Obligation::new(
1421 ObligationCause::dummy(),
1423 cleaned_pred.to_predicate()
1426 self.predicate_may_hold(&obligation)
1430 fn note_obligation_cause<T>(&self,
1431 err: &mut DiagnosticBuilder<'_>,
1432 obligation: &Obligation<'tcx, T>)
1433 where T: fmt::Display
1435 self.note_obligation_cause_code(err,
1436 &obligation.predicate,
1437 &obligation.cause.code,
1441 fn note_obligation_cause_code<T>(&self,
1442 err: &mut DiagnosticBuilder<'_>,
1444 cause_code: &ObligationCauseCode<'tcx>,
1445 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1446 where T: fmt::Display
1450 ObligationCauseCode::ExprAssignable |
1451 ObligationCauseCode::MatchExpressionArm { .. } |
1452 ObligationCauseCode::IfExpression |
1453 ObligationCauseCode::IfExpressionWithNoElse |
1454 ObligationCauseCode::MainFunctionType |
1455 ObligationCauseCode::StartFunctionType |
1456 ObligationCauseCode::IntrinsicType |
1457 ObligationCauseCode::MethodReceiver |
1458 ObligationCauseCode::ReturnNoExpression |
1459 ObligationCauseCode::MiscObligation => {
1461 ObligationCauseCode::SliceOrArrayElem => {
1462 err.note("slice and array elements must have `Sized` type");
1464 ObligationCauseCode::TupleElem => {
1465 err.note("only the last element of a tuple may have a dynamically sized type");
1467 ObligationCauseCode::ProjectionWf(data) => {
1468 err.note(&format!("required so that the projection `{}` is well-formed",
1471 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1472 err.note(&format!("required so that reference `{}` does not outlive its referent",
1475 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1476 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1478 region, object_ty));
1480 ObligationCauseCode::ItemObligation(item_def_id) => {
1481 let item_name = tcx.item_path_str(item_def_id);
1482 let msg = format!("required by `{}`", item_name);
1484 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1485 let sp = tcx.sess.source_map().def_span(sp);
1486 err.span_note(sp, &msg);
1491 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1492 err.note(&format!("required for the cast to the object type `{}`",
1493 self.ty_to_string(object_ty)));
1495 ObligationCauseCode::RepeatVec => {
1496 err.note("the `Copy` trait is required because the \
1497 repeated element will be copied");
1499 ObligationCauseCode::VariableType(_) => {
1500 err.note("all local variables must have a statically known size");
1501 if !self.tcx.features().unsized_locals {
1502 err.help("unsized locals are gated as an unstable feature");
1505 ObligationCauseCode::SizedArgumentType => {
1506 err.note("all function arguments must have a statically known size");
1507 if !self.tcx.features().unsized_locals {
1508 err.help("unsized locals are gated as an unstable feature");
1511 ObligationCauseCode::SizedReturnType => {
1512 err.note("the return type of a function must have a \
1513 statically known size");
1515 ObligationCauseCode::SizedYieldType => {
1516 err.note("the yield type of a generator must have a \
1517 statically known size");
1519 ObligationCauseCode::AssignmentLhsSized => {
1520 err.note("the left-hand-side of an assignment must have a statically known size");
1522 ObligationCauseCode::TupleInitializerSized => {
1523 err.note("tuples must have a statically known size to be initialized");
1525 ObligationCauseCode::StructInitializerSized => {
1526 err.note("structs must have a statically known size to be initialized");
1528 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
1530 AdtKind::Struct => {
1532 err.note("the last field of a packed struct may only have a \
1533 dynamically sized type if it does not need drop to be run");
1535 err.note("only the last field of a struct may have a dynamically \
1540 err.note("no field of a union may have a dynamically sized type");
1543 err.note("no field of an enum variant may have a dynamically sized type");
1547 ObligationCauseCode::ConstSized => {
1548 err.note("constant expressions must have a statically known size");
1550 ObligationCauseCode::SharedStatic => {
1551 err.note("shared static variables must have a type that implements `Sync`");
1553 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1554 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1555 let ty = parent_trait_ref.skip_binder().self_ty();
1556 err.note(&format!("required because it appears within the type `{}`", ty));
1557 obligated_types.push(ty);
1559 let parent_predicate = parent_trait_ref.to_predicate();
1560 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1561 self.note_obligation_cause_code(err,
1567 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1568 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1570 &format!("required because of the requirements on the impl of `{}` for `{}`",
1572 parent_trait_ref.skip_binder().self_ty()));
1573 let parent_predicate = parent_trait_ref.to_predicate();
1574 self.note_obligation_cause_code(err,
1579 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1581 &format!("the requirement `{}` appears on the impl method \
1582 but not on the corresponding trait method",
1585 ObligationCauseCode::ReturnType(_) |
1586 ObligationCauseCode::BlockTailExpression(_) => (),
1587 ObligationCauseCode::TrivialBound => {
1588 err.help("see issue #48214");
1589 if tcx.sess.opts.unstable_features.is_nightly_build() {
1590 err.help("add #![feature(trivial_bounds)] to the \
1591 crate attributes to enable",
1598 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1599 let current_limit = self.tcx.sess.recursion_limit.get();
1600 let suggested_limit = current_limit * 2;
1601 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1605 fn is_recursive_obligation(&self,
1606 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1607 cause_code: &ObligationCauseCode<'tcx>) -> bool {
1608 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1609 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1611 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1619 /// Summarizes information
1622 /// An argument of non-tuple type. Parameters are (name, ty)
1623 Arg(String, String),
1625 /// An argument of tuple type. For a "found" argument, the span is
1626 /// the locationo in the source of the pattern. For a "expected"
1627 /// argument, it will be None. The vector is a list of (name, ty)
1628 /// strings for the components of the tuple.
1629 Tuple(Option<Span>, Vec<(String, String)>),
1633 fn empty() -> ArgKind {
1634 ArgKind::Arg("_".to_owned(), "_".to_owned())
1637 /// Creates an `ArgKind` from the expected type of an
1638 /// argument. It has no name (`_`) and an optional source span.
1639 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
1641 ty::Tuple(ref tys) => ArgKind::Tuple(
1644 .map(|ty| ("_".to_owned(), ty.sty.to_string()))
1645 .collect::<Vec<_>>()
1647 _ => ArgKind::Arg("_".to_owned(), t.sty.to_string()),