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};
32 use hir::def_id::DefId;
33 use infer::{self, InferCtxt};
34 use infer::type_variable::TypeVariableOrigin;
37 use session::DiagnosticMessageId;
38 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
39 use ty::GenericParamDefKind;
40 use ty::error::ExpectedFound;
42 use ty::fold::TypeFolder;
44 use ty::SubtypePredicate;
45 use util::nodemap::{FxHashMap, FxHashSet};
47 use syntax_pos::{DUMMY_SP, Span};
49 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
50 pub fn report_fulfillment_errors(&self,
51 errors: &[FulfillmentError<'tcx>],
52 body_id: Option<hir::BodyId>,
53 fallback_has_occurred: bool) {
55 struct ErrorDescriptor<'tcx> {
56 predicate: ty::Predicate<'tcx>,
57 index: Option<usize>, // None if this is an old error
60 let mut error_map : FxHashMap<_, Vec<_>> =
61 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
62 (span, predicates.iter().map(|predicate| ErrorDescriptor {
63 predicate: predicate.clone(),
68 for (index, error) in errors.iter().enumerate() {
69 error_map.entry(error.obligation.cause.span).or_default().push(
71 predicate: error.obligation.predicate.clone(),
75 self.reported_trait_errors.borrow_mut()
76 .entry(error.obligation.cause.span).or_default()
77 .push(error.obligation.predicate.clone());
80 // We do this in 2 passes because we want to display errors in order, tho
81 // maybe it *is* better to sort errors by span or something.
82 let mut is_suppressed: Vec<bool> = errors.iter().map(|_| false).collect();
83 for (_, error_set) in error_map.iter() {
84 // We want to suppress "duplicate" errors with the same span.
85 for error in error_set {
86 if let Some(index) = error.index {
87 // Suppress errors that are either:
88 // 1) strictly implied by another error.
89 // 2) implied by an error with a smaller index.
90 for error2 in error_set {
91 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
92 // Avoid errors being suppressed by already-suppressed
93 // errors, to prevent all errors from being suppressed
98 if self.error_implies(&error2.predicate, &error.predicate) &&
99 !(error2.index >= error.index &&
100 self.error_implies(&error.predicate, &error2.predicate))
102 info!("skipping {:?} (implied by {:?})", error, error2);
103 is_suppressed[index] = true;
111 for (error, suppressed) in errors.iter().zip(is_suppressed) {
113 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
118 // returns if `cond` not occurring implies that `error` does not occur - i.e. that
119 // `error` occurring implies that `cond` occurs.
120 fn error_implies(&self,
121 cond: &ty::Predicate<'tcx>,
122 error: &ty::Predicate<'tcx>)
129 let (cond, error) = match (cond, error) {
130 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
133 // FIXME: make this work in other cases too.
138 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
139 if let ty::Predicate::Trait(implication) = implication {
140 let error = error.to_poly_trait_ref();
141 let implication = implication.to_poly_trait_ref();
142 // FIXME: I'm just not taking associated types at all here.
143 // Eventually I'll need to implement param-env-aware
144 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
145 let param_env = ty::ParamEnv::empty();
146 if self.can_sub(param_env, error, implication).is_ok() {
147 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
156 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
157 body_id: Option<hir::BodyId>,
158 fallback_has_occurred: bool) {
159 debug!("report_fulfillment_errors({:?})", error);
161 FulfillmentErrorCode::CodeSelectionError(ref e) => {
162 self.report_selection_error(&error.obligation, e, fallback_has_occurred);
164 FulfillmentErrorCode::CodeProjectionError(ref e) => {
165 self.report_projection_error(&error.obligation, e);
167 FulfillmentErrorCode::CodeAmbiguity => {
168 self.maybe_report_ambiguity(&error.obligation, body_id);
170 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
171 self.report_mismatched_types(&error.obligation.cause,
172 expected_found.expected,
173 expected_found.found,
180 fn report_projection_error(&self,
181 obligation: &PredicateObligation<'tcx>,
182 error: &MismatchedProjectionTypes<'tcx>)
185 self.resolve_type_vars_if_possible(&obligation.predicate);
187 if predicate.references_error() {
193 let mut err = &error.err;
194 let mut values = None;
196 // try to find the mismatched types to report the error with.
198 // this can fail if the problem was higher-ranked, in which
199 // cause I have no idea for a good error message.
200 if let ty::Predicate::Projection(ref data) = predicate {
201 let mut selcx = SelectionContext::new(self);
202 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
203 obligation.cause.span,
204 infer::LateBoundRegionConversionTime::HigherRankedType,
206 let mut obligations = vec![];
207 let normalized_ty = super::normalize_projection_type(
209 obligation.param_env,
211 obligation.cause.clone(),
215 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
216 .eq(normalized_ty, data.ty) {
217 values = Some(infer::ValuePairs::Types(ExpectedFound {
218 expected: normalized_ty,
226 let msg = format!("type mismatch resolving `{}`", predicate);
227 let error_id = (DiagnosticMessageId::ErrorId(271),
228 Some(obligation.cause.span), msg.clone());
229 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
231 let mut diag = struct_span_err!(
232 self.tcx.sess, obligation.cause.span, E0271,
233 "type mismatch resolving `{}`", predicate
235 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
236 self.note_obligation_cause(&mut diag, obligation);
242 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
243 /// returns the fuzzy category of a given type, or None
244 /// if the type can be equated to any type.
245 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
247 ty::TyBool => Some(0),
248 ty::TyChar => Some(1),
249 ty::TyStr => Some(2),
250 ty::TyInt(..) | ty::TyUint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
251 ty::TyFloat(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
252 ty::Ref(..) | ty::RawPtr(..) => Some(5),
253 ty::Array(..) | ty::Slice(..) => Some(6),
254 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
255 ty::Dynamic(..) => Some(8),
256 ty::Closure(..) => Some(9),
257 ty::Tuple(..) => Some(10),
258 ty::Projection(..) => Some(11),
259 ty::TyParam(..) => Some(12),
260 ty::Anon(..) => Some(13),
261 ty::Never => Some(14),
262 ty::Adt(adt, ..) => match adt.adt_kind() {
263 AdtKind::Struct => Some(15),
264 AdtKind::Union => Some(16),
265 AdtKind::Enum => Some(17),
267 ty::Generator(..) => Some(18),
268 ty::TyForeign(..) => Some(19),
269 ty::GeneratorWitness(..) => Some(20),
270 ty::Infer(..) | ty::Error => None
274 match (type_category(a), type_category(b)) {
275 (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
276 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
279 // infer and error can be equated to all types
284 fn impl_similar_to(&self,
285 trait_ref: ty::PolyTraitRef<'tcx>,
286 obligation: &PredicateObligation<'tcx>)
290 let param_env = obligation.param_env;
291 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
292 let trait_self_ty = trait_ref.self_ty();
294 let mut self_match_impls = vec![];
295 let mut fuzzy_match_impls = vec![];
297 self.tcx.for_each_relevant_impl(
298 trait_ref.def_id, trait_self_ty, |def_id| {
299 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
300 let impl_trait_ref = tcx
301 .impl_trait_ref(def_id)
303 .subst(tcx, impl_substs);
305 let impl_self_ty = impl_trait_ref.self_ty();
307 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
308 self_match_impls.push(def_id);
310 if trait_ref.substs.types().skip(1)
311 .zip(impl_trait_ref.substs.types().skip(1))
312 .all(|(u,v)| self.fuzzy_match_tys(u, v))
314 fuzzy_match_impls.push(def_id);
319 let impl_def_id = if self_match_impls.len() == 1 {
321 } else if fuzzy_match_impls.len() == 1 {
327 if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
334 fn on_unimplemented_note(
336 trait_ref: ty::PolyTraitRef<'tcx>,
337 obligation: &PredicateObligation<'tcx>) ->
340 let def_id = self.impl_similar_to(trait_ref, obligation)
341 .unwrap_or(trait_ref.def_id());
342 let trait_ref = *trait_ref.skip_binder();
344 let mut flags = vec![];
345 match obligation.cause.code {
346 ObligationCauseCode::BuiltinDerivedObligation(..) |
347 ObligationCauseCode::ImplDerivedObligation(..) => {}
349 // this is a "direct", user-specified, rather than derived,
351 flags.push(("direct".to_string(), None));
355 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
356 // FIXME: maybe also have some way of handling methods
357 // from other traits? That would require name resolution,
358 // which we might want to be some sort of hygienic.
360 // Currently I'm leaving it for what I need for `try`.
361 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
362 let method = self.tcx.item_name(item);
363 flags.push(("from_method".to_string(), None));
364 flags.push(("from_method".to_string(), Some(method.to_string())));
368 if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
369 flags.push(("from_desugaring".to_string(), None));
370 flags.push(("from_desugaring".to_string(), Some(k.name().to_string())));
372 let generics = self.tcx.generics_of(def_id);
373 let self_ty = trait_ref.self_ty();
374 // This is also included through the generics list as `Self`,
375 // but the parser won't allow you to use it
376 flags.push(("_Self".to_string(), Some(self_ty.to_string())));
377 if let Some(def) = self_ty.ty_adt_def() {
378 // We also want to be able to select self's original
379 // signature with no type arguments resolved
380 flags.push(("_Self".to_string(), Some(self.tcx.type_of(def.did).to_string())));
383 for param in generics.params.iter() {
384 let value = match param.kind {
385 GenericParamDefKind::Type {..} => {
386 trait_ref.substs[param.index as usize].to_string()
388 GenericParamDefKind::Lifetime => continue,
390 let name = param.name.to_string();
391 flags.push((name, Some(value)));
394 if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
395 flags.push(("crate_local".to_string(), None));
398 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
399 self.tcx, trait_ref.def_id, def_id
401 command.evaluate(self.tcx, trait_ref, &flags[..])
403 OnUnimplementedNote::empty()
407 fn find_similar_impl_candidates(&self,
408 trait_ref: ty::PolyTraitRef<'tcx>)
409 -> Vec<ty::TraitRef<'tcx>>
411 let simp = fast_reject::simplify_type(self.tcx,
412 trait_ref.skip_binder().self_ty(),
414 let mut impl_candidates = Vec::new();
417 Some(simp) => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
418 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
419 let imp_simp = fast_reject::simplify_type(self.tcx,
422 if let Some(imp_simp) = imp_simp {
423 if simp != imp_simp {
427 impl_candidates.push(imp);
429 None => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
430 impl_candidates.push(
431 self.tcx.impl_trait_ref(def_id).unwrap());
437 fn report_similar_impl_candidates(&self,
438 mut impl_candidates: Vec<ty::TraitRef<'tcx>>,
439 err: &mut DiagnosticBuilder)
441 if impl_candidates.is_empty() {
445 let len = impl_candidates.len();
446 let end = if impl_candidates.len() <= 5 {
447 impl_candidates.len()
452 let normalize = |candidate| self.tcx.global_tcx().infer_ctxt().enter(|ref infcx| {
453 let normalized = infcx
454 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
455 .normalize(candidate)
458 Some(normalized) => format!("\n {:?}", normalized.value),
459 None => format!("\n {:?}", candidate),
463 // Sort impl candidates so that ordering is consistent for UI tests.
464 let normalized_impl_candidates = &mut impl_candidates[0..end]
467 .collect::<Vec<String>>();
468 normalized_impl_candidates.sort();
470 err.help(&format!("the following implementations were found:{}{}",
471 normalized_impl_candidates.join(""),
473 format!("\nand {} others", len - 4)
480 /// Reports that an overflow has occurred and halts compilation. We
481 /// halt compilation unconditionally because it is important that
482 /// overflows never be masked -- they basically represent computations
483 /// whose result could not be truly determined and thus we can't say
484 /// if the program type checks or not -- and they are unusual
485 /// occurrences in any case.
486 pub fn report_overflow_error<T>(&self,
487 obligation: &Obligation<'tcx, T>,
488 suggest_increasing_limit: bool) -> !
489 where T: fmt::Display + TypeFoldable<'tcx>
492 self.resolve_type_vars_if_possible(&obligation.predicate);
493 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
494 "overflow evaluating the requirement `{}`",
497 if suggest_increasing_limit {
498 self.suggest_new_overflow_limit(&mut err);
501 self.note_obligation_cause(&mut err, obligation);
504 self.tcx.sess.abort_if_errors();
508 /// Reports that a cycle was detected which led to overflow and halts
509 /// compilation. This is equivalent to `report_overflow_error` except
510 /// that we can give a more helpful error message (and, in particular,
511 /// we do not suggest increasing the overflow limit, which is not
513 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
514 let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
515 assert!(cycle.len() > 0);
517 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
519 self.report_overflow_error(&cycle[0], false);
522 pub fn report_extra_impl_obligation(&self,
524 item_name: ast::Name,
525 _impl_item_def_id: DefId,
526 trait_item_def_id: DefId,
527 requirement: &dyn fmt::Display)
528 -> DiagnosticBuilder<'tcx>
530 let msg = "impl has stricter requirements than trait";
531 let sp = self.tcx.sess.source_map().def_span(error_span);
533 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
535 if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
536 let span = self.tcx.sess.source_map().def_span(trait_item_span);
537 err.span_label(span, format!("definition of `{}` from trait", item_name));
540 err.span_label(sp, format!("impl has extra requirement {}", requirement));
546 /// Get the parent trait chain start
547 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
549 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
550 let parent_trait_ref = self.resolve_type_vars_if_possible(
551 &data.parent_trait_ref);
552 match self.get_parent_trait_ref(&data.parent_code) {
554 None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
561 pub fn report_selection_error(&self,
562 obligation: &PredicateObligation<'tcx>,
563 error: &SelectionError<'tcx>,
564 fallback_has_occurred: bool)
566 let span = obligation.cause.span;
568 let mut err = match *error {
569 SelectionError::Unimplemented => {
570 if let ObligationCauseCode::CompareImplMethodObligation {
571 item_name, impl_item_def_id, trait_item_def_id,
572 } = obligation.cause.code {
573 self.report_extra_impl_obligation(
578 &format!("`{}`", obligation.predicate))
582 match obligation.predicate {
583 ty::Predicate::Trait(ref trait_predicate) => {
584 let trait_predicate =
585 self.resolve_type_vars_if_possible(trait_predicate);
587 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
590 let trait_ref = trait_predicate.to_poly_trait_ref();
591 let (post_message, pre_message) =
592 self.get_parent_trait_ref(&obligation.cause.code)
593 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
594 .unwrap_or((String::new(), String::new()));
596 let OnUnimplementedNote { message, label, note }
597 = self.on_unimplemented_note(trait_ref, obligation);
598 let have_alt_message = message.is_some() || label.is_some();
600 let mut err = struct_span_err!(
605 message.unwrap_or_else(|| {
606 format!("the trait bound `{}` is not satisfied{}",
607 trait_ref.to_predicate(), post_message)
611 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
612 "consider using `()`, or a `Result`".to_owned()
614 format!("{}the trait `{}` is not implemented for `{}`",
620 if let Some(ref s) = label {
621 // If it has a custom "#[rustc_on_unimplemented]"
622 // error message, let's display it as the label!
623 err.span_label(span, s.as_str());
624 err.help(&explanation);
626 err.span_label(span, explanation);
628 if let Some(ref s) = note {
629 // If it has a custom "#[rustc_on_unimplemented]" note, let's display it
630 err.note(s.as_str());
633 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
634 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
636 // Try to report a help message
637 if !trait_ref.has_infer_types() &&
638 self.predicate_can_apply(obligation.param_env, trait_ref) {
639 // If a where-clause may be useful, remind the
640 // user that they can add it.
642 // don't display an on-unimplemented note, as
643 // these notes will often be of the form
644 // "the type `T` can't be frobnicated"
645 // which is somewhat confusing.
646 err.help(&format!("consider adding a `where {}` bound",
647 trait_ref.to_predicate()));
648 } else if !have_alt_message {
649 // Can't show anything else useful, try to find similar impls.
650 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
651 self.report_similar_impl_candidates(impl_candidates, &mut err);
654 // If this error is due to `!: Trait` not implemented but `(): Trait` is
655 // implemented, and fallback has occurred, then it could be due to a
656 // variable that used to fallback to `()` now falling back to `!`. Issue a
657 // note informing about the change in behaviour.
658 if trait_predicate.skip_binder().self_ty().is_never()
659 && fallback_has_occurred
661 let predicate = trait_predicate.map_bound(|mut trait_pred| {
662 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
664 &trait_pred.trait_ref.substs[1..],
668 let unit_obligation = Obligation {
669 predicate: ty::Predicate::Trait(predicate),
670 .. obligation.clone()
672 if self.predicate_may_hold(&unit_obligation) {
673 err.note("the trait is implemented for `()`. \
674 Possibly this error has been caused by changes to \
675 Rust's type-inference algorithm \
676 (see: https://github.com/rust-lang/rust/issues/48950 \
677 for more info). Consider whether you meant to use the \
678 type `()` here instead.");
685 ty::Predicate::Subtype(ref predicate) => {
686 // Errors for Subtype predicates show up as
687 // `FulfillmentErrorCode::CodeSubtypeError`,
688 // not selection error.
689 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
692 ty::Predicate::RegionOutlives(ref predicate) => {
693 let predicate = self.resolve_type_vars_if_possible(predicate);
694 let err = self.region_outlives_predicate(&obligation.cause,
695 &predicate).err().unwrap();
696 struct_span_err!(self.tcx.sess, span, E0279,
697 "the requirement `{}` is not satisfied (`{}`)",
701 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
703 self.resolve_type_vars_if_possible(&obligation.predicate);
704 struct_span_err!(self.tcx.sess, span, E0280,
705 "the requirement `{}` is not satisfied",
709 ty::Predicate::ObjectSafe(trait_def_id) => {
710 let violations = self.tcx.object_safety_violations(trait_def_id);
711 self.tcx.report_object_safety_error(span,
716 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
717 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
718 let closure_span = self.tcx.sess.source_map()
719 .def_span(self.tcx.hir.span_if_local(closure_def_id).unwrap());
720 let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
721 let mut err = struct_span_err!(
722 self.tcx.sess, closure_span, E0525,
723 "expected a closure that implements the `{}` trait, \
724 but this closure only implements `{}`",
730 format!("this closure implements `{}`, not `{}`", found_kind, kind));
732 obligation.cause.span,
733 format!("the requirement to implement `{}` derives from here", kind));
735 // Additional context information explaining why the closure only implements
736 // a particular trait.
737 if let Some(tables) = self.in_progress_tables {
738 let tables = tables.borrow();
739 let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
740 match (found_kind, tables.closure_kind_origins().get(closure_hir_id)) {
741 (ty::ClosureKind::FnOnce, Some((span, name))) => {
742 err.span_label(*span, format!(
743 "closure is `FnOnce` because it moves the \
744 variable `{}` out of its environment", name));
746 (ty::ClosureKind::FnMut, Some((span, name))) => {
747 err.span_label(*span, format!(
748 "closure is `FnMut` because it mutates the \
749 variable `{}` here", name));
759 ty::Predicate::WellFormed(ty) => {
760 // WF predicates cannot themselves make
761 // errors. They can only block due to
762 // ambiguity; otherwise, they always
763 // degenerate into other obligations
765 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
768 ty::Predicate::ConstEvaluatable(..) => {
769 // Errors for `ConstEvaluatable` predicates show up as
770 // `SelectionError::ConstEvalFailure`,
771 // not `Unimplemented`.
773 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
778 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
779 let found_trait_ref = self.resolve_type_vars_if_possible(&*found_trait_ref);
780 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
781 if expected_trait_ref.self_ty().references_error() {
784 let found_trait_ty = found_trait_ref.self_ty();
786 let found_did = match found_trait_ty.sty {
787 ty::Closure(did, _) |
789 ty::FnDef(did, _) => Some(did),
790 ty::Adt(def, _) => Some(def.did),
793 let found_span = found_did.and_then(|did| {
794 self.tcx.hir.span_if_local(did)
795 }).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
797 let found = match found_trait_ref.skip_binder().substs.type_at(1).sty {
798 ty::Tuple(ref tys) => tys.iter()
799 .map(|_| ArgKind::empty()).collect::<Vec<_>>(),
800 _ => vec![ArgKind::empty()],
802 let expected = match expected_trait_ref.skip_binder().substs.type_at(1).sty {
803 ty::Tuple(ref tys) => tys.iter()
804 .map(|t| match t.sty {
805 ty::TyKind::Tuple(ref tys) => ArgKind::Tuple(
808 .map(|ty| ("_".to_owned(), ty.sty.to_string()))
811 _ => ArgKind::Arg("_".to_owned(), t.sty.to_string()),
813 ref sty => vec![ArgKind::Arg("_".to_owned(), sty.to_string())],
815 if found.len() == expected.len() {
816 self.report_closure_arg_mismatch(span,
821 let (closure_span, found) = found_did
822 .and_then(|did| self.tcx.hir.get_if_local(did))
824 let (found_span, found) = self.get_fn_like_arguments(node);
825 (Some(found_span), found)
826 }).unwrap_or((found_span, found));
828 self.report_arg_count_mismatch(span,
832 found_trait_ty.is_closure())
836 TraitNotObjectSafe(did) => {
837 let violations = self.tcx.object_safety_violations(did);
838 self.tcx.report_object_safety_error(span, did,
842 ConstEvalFailure(ref err) => {
843 match err.struct_error(
845 "could not evaluate constant expression",
853 bug!("overflow should be handled before the `report_selection_error` path");
856 self.note_obligation_cause(&mut err, obligation);
860 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
861 /// suggestion to borrow the initializer in order to use have a slice instead.
862 fn suggest_borrow_on_unsized_slice(&self,
863 code: &ObligationCauseCode<'tcx>,
864 err: &mut DiagnosticBuilder<'tcx>) {
865 if let &ObligationCauseCode::VariableType(node_id) = code {
866 let parent_node = self.tcx.hir.get_parent_node(node_id);
867 if let Some(hir::map::NodeLocal(ref local)) = self.tcx.hir.find(parent_node) {
868 if let Some(ref expr) = local.init {
869 if let hir::ExprKind::Index(_, _) = expr.node {
870 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
871 err.span_suggestion_with_applicability(
873 "consider borrowing here",
874 format!("&{}", snippet),
875 Applicability::MachineApplicable
884 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
885 /// suggest removing these references until we reach a type that implements the trait.
886 fn suggest_remove_reference(&self,
887 obligation: &PredicateObligation<'tcx>,
888 err: &mut DiagnosticBuilder<'tcx>,
889 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>) {
890 let trait_ref = trait_ref.skip_binder();
891 let span = obligation.cause.span;
893 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
894 let refs_number = snippet.chars()
895 .filter(|c| !c.is_whitespace())
896 .take_while(|c| *c == '&')
899 let mut trait_type = trait_ref.self_ty();
901 for refs_remaining in 0..refs_number {
902 if let ty::TyKind::Ref(_, t_type, _) = trait_type.sty {
905 let substs = self.tcx.mk_substs_trait(trait_type, &[]);
906 let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
907 let new_obligation = Obligation::new(ObligationCause::dummy(),
908 obligation.param_env,
909 new_trait_ref.to_predicate());
911 if self.predicate_may_hold(&new_obligation) {
912 let sp = self.tcx.sess.source_map()
913 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
915 let remove_refs = refs_remaining + 1;
916 let format_str = format!("consider removing {} leading `&`-references",
919 err.span_suggestion_short_with_applicability(
920 sp, &format_str, String::from(""), Applicability::MachineApplicable
931 /// Given some node representing a fn-like thing in the HIR map,
932 /// returns a span and `ArgKind` information that describes the
933 /// arguments it expects. This can be supplied to
934 /// `report_arg_count_mismatch`.
935 pub fn get_fn_like_arguments(&self, node: hir::map::Node) -> (Span, Vec<ArgKind>) {
937 hir::map::NodeExpr(&hir::Expr {
938 node: hir::ExprKind::Closure(_, ref _decl, id, span, _),
941 (self.tcx.sess.source_map().def_span(span), self.tcx.hir.body(id).arguments.iter()
944 node: hir::PatKind::Tuple(args, _),
947 } = arg.pat.clone().into_inner() {
950 args.iter().map(|pat| {
951 let snippet = self.tcx.sess.source_map()
952 .span_to_snippet(pat.span).unwrap();
953 (snippet, "_".to_owned())
954 }).collect::<Vec<_>>(),
957 let name = self.tcx.sess.source_map()
958 .span_to_snippet(arg.pat.span).unwrap();
959 ArgKind::Arg(name, "_".to_owned())
962 .collect::<Vec<ArgKind>>())
964 hir::map::NodeItem(&hir::Item {
966 node: hir::ItemKind::Fn(ref decl, ..),
969 hir::map::NodeImplItem(&hir::ImplItem {
971 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
974 hir::map::NodeTraitItem(&hir::TraitItem {
976 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
979 (self.tcx.sess.source_map().def_span(span), decl.inputs.iter()
980 .map(|arg| match arg.clone().node {
981 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
984 .map(|_| ("_".to_owned(), "_".to_owned()))
985 .collect::<Vec<_>>(),
987 _ => ArgKind::Arg("_".to_owned(), "_".to_owned())
988 }).collect::<Vec<ArgKind>>())
990 hir::map::NodeVariant(&hir::Variant {
992 node: hir::VariantKind {
993 data: hir::VariantData::Tuple(ref fields, _),
998 (self.tcx.sess.source_map().def_span(span),
999 fields.iter().map(|field| {
1000 ArgKind::Arg(field.ident.to_string(), "_".to_string())
1001 }).collect::<Vec<_>>())
1003 hir::map::NodeStructCtor(ref variant_data) => {
1004 (self.tcx.sess.source_map().def_span(self.tcx.hir.span(variant_data.id())),
1005 variant_data.fields()
1006 .iter().map(|_| ArgKind::Arg("_".to_owned(), "_".to_owned()))
1009 _ => panic!("non-FnLike node found: {:?}", node),
1013 /// Reports an error when the number of arguments needed by a
1014 /// trait match doesn't match the number that the expression
1016 pub fn report_arg_count_mismatch(
1019 found_span: Option<Span>,
1020 expected_args: Vec<ArgKind>,
1021 found_args: Vec<ArgKind>,
1023 ) -> DiagnosticBuilder<'tcx> {
1024 let kind = if is_closure { "closure" } else { "function" };
1026 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1027 let arg_length = arguments.len();
1028 let distinct = match &other[..] {
1029 &[ArgKind::Tuple(..)] => true,
1032 match (arg_length, arguments.get(0)) {
1033 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1034 format!("a single {}-tuple as argument", fields.len())
1036 _ => format!("{} {}argument{}",
1038 if distinct && arg_length > 1 { "distinct " } else { "" },
1039 if arg_length == 1 { "" } else { "s" }),
1043 let expected_str = args_str(&expected_args, &found_args);
1044 let found_str = args_str(&found_args, &expected_args);
1046 let mut err = struct_span_err!(
1050 "{} is expected to take {}, but it takes {}",
1056 err.span_label(span, format!( "expected {} that takes {}", kind, expected_str));
1058 if let Some(found_span) = found_span {
1059 err.span_label(found_span, format!("takes {}", found_str));
1061 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1062 // found arguments is empty (assume the user just wants to ignore args in this case).
1063 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1064 if found_args.is_empty() && is_closure {
1065 let underscores = "_".repeat(expected_args.len())
1067 .filter(|s| !s.is_empty())
1068 .collect::<Vec<_>>()
1070 err.span_suggestion_with_applicability(
1073 "consider changing the closure to take and ignore the expected argument{}",
1074 if expected_args.len() < 2 {
1080 format!("|{}|", underscores),
1081 Applicability::MachineApplicable,
1085 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1086 if fields.len() == expected_args.len() {
1087 let sugg = fields.iter()
1088 .map(|(name, _)| name.to_owned())
1089 .collect::<Vec<String>>().join(", ");
1090 err.span_suggestion_with_applicability(found_span,
1091 "change the closure to take multiple \
1092 arguments instead of a single tuple",
1093 format!("|{}|", sugg),
1094 Applicability::MachineApplicable);
1097 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1098 if fields.len() == found_args.len() && is_closure {
1102 .map(|arg| match arg {
1103 ArgKind::Arg(name, _) => name.to_owned(),
1104 _ => "_".to_owned(),
1106 .collect::<Vec<String>>()
1108 // add type annotations if available
1109 if found_args.iter().any(|arg| match arg {
1110 ArgKind::Arg(_, ty) => ty != "_",
1115 .map(|(_, ty)| ty.to_owned())
1116 .collect::<Vec<String>>()
1122 err.span_suggestion_with_applicability(
1124 "change the closure to accept a tuple instead of \
1125 individual arguments",
1127 Applicability::MachineApplicable
1136 fn report_closure_arg_mismatch(&self,
1138 found_span: Option<Span>,
1139 expected_ref: ty::PolyTraitRef<'tcx>,
1140 found: ty::PolyTraitRef<'tcx>)
1141 -> DiagnosticBuilder<'tcx>
1143 fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
1144 trait_ref: &ty::TraitRef<'tcx>) -> String {
1145 let inputs = trait_ref.substs.type_at(1);
1146 let sig = if let ty::Tuple(inputs) = inputs.sty {
1148 inputs.iter().map(|&x| x),
1149 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1151 hir::Unsafety::Normal,
1152 ::rustc_target::spec::abi::Abi::Rust
1156 ::std::iter::once(inputs),
1157 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1159 hir::Unsafety::Normal,
1160 ::rustc_target::spec::abi::Abi::Rust
1163 ty::Binder::bind(sig).to_string()
1166 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1167 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1168 "type mismatch in {} arguments",
1169 if argument_is_closure { "closure" } else { "function" });
1171 let found_str = format!(
1172 "expected signature of `{}`",
1173 build_fn_sig_string(self.tcx, found.skip_binder())
1175 err.span_label(span, found_str);
1177 let found_span = found_span.unwrap_or(span);
1178 let expected_str = format!(
1179 "found signature of `{}`",
1180 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1182 err.span_label(found_span, expected_str);
1188 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1189 pub fn recursive_type_with_infinite_size_error(self,
1191 -> DiagnosticBuilder<'tcx>
1193 assert!(type_def_id.is_local());
1194 let span = self.hir.span_if_local(type_def_id).unwrap();
1195 let span = self.sess.source_map().def_span(span);
1196 let mut err = struct_span_err!(self.sess, span, E0072,
1197 "recursive type `{}` has infinite size",
1198 self.item_path_str(type_def_id));
1199 err.span_label(span, "recursive type has infinite size");
1200 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1201 at some point to make `{}` representable",
1202 self.item_path_str(type_def_id)));
1206 pub fn report_object_safety_error(self,
1208 trait_def_id: DefId,
1209 violations: Vec<ObjectSafetyViolation>)
1210 -> DiagnosticBuilder<'tcx>
1212 let trait_str = self.item_path_str(trait_def_id);
1213 let span = self.sess.source_map().def_span(span);
1214 let mut err = struct_span_err!(
1215 self.sess, span, E0038,
1216 "the trait `{}` cannot be made into an object",
1218 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1220 let mut reported_violations = FxHashSet();
1221 for violation in violations {
1222 if !reported_violations.insert(violation.clone()) {
1225 err.note(&violation.error_msg());
1231 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1232 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1233 body_id: Option<hir::BodyId>) {
1234 // Unable to successfully determine, probably means
1235 // insufficient type information, but could mean
1236 // ambiguous impls. The latter *ought* to be a
1237 // coherence violation, so we don't report it here.
1239 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1240 let span = obligation.cause.span;
1242 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1246 // Ambiguity errors are often caused as fallout from earlier
1247 // errors. So just ignore them if this infcx is tainted.
1248 if self.is_tainted_by_errors() {
1253 ty::Predicate::Trait(ref data) => {
1254 let trait_ref = data.to_poly_trait_ref();
1255 let self_ty = trait_ref.self_ty();
1256 if predicate.references_error() {
1259 // Typically, this ambiguity should only happen if
1260 // there are unresolved type inference variables
1261 // (otherwise it would suggest a coherence
1262 // failure). But given #21974 that is not necessarily
1263 // the case -- we can have multiple where clauses that
1264 // are only distinguished by a region, which results
1265 // in an ambiguity even when all types are fully
1266 // known, since we don't dispatch based on region
1269 // This is kind of a hack: it frequently happens that some earlier
1270 // error prevents types from being fully inferred, and then we get
1271 // a bunch of uninteresting errors saying something like "<generic
1272 // #0> doesn't implement Sized". It may even be true that we
1273 // could just skip over all checks where the self-ty is an
1274 // inference variable, but I was afraid that there might be an
1275 // inference variable created, registered as an obligation, and
1276 // then never forced by writeback, and hence by skipping here we'd
1277 // be ignoring the fact that we don't KNOW the type works
1278 // out. Though even that would probably be harmless, given that
1279 // we're only talking about builtin traits, which are known to be
1280 // inhabited. But in any case I just threw in this check for
1281 // has_errors() to be sure that compilation isn't happening
1282 // anyway. In that case, why inundate the user.
1283 if !self.tcx.sess.has_errors() {
1285 self.tcx.lang_items().sized_trait()
1286 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1288 self.need_type_info_err(body_id, span, self_ty).emit();
1290 let mut err = struct_span_err!(self.tcx.sess,
1292 "type annotations required: \
1293 cannot resolve `{}`",
1295 self.note_obligation_cause(&mut err, obligation);
1301 ty::Predicate::WellFormed(ty) => {
1302 // Same hacky approach as above to avoid deluging user
1303 // with error messages.
1304 if !ty.references_error() && !self.tcx.sess.has_errors() {
1305 self.need_type_info_err(body_id, span, ty).emit();
1309 ty::Predicate::Subtype(ref data) => {
1310 if data.references_error() || self.tcx.sess.has_errors() {
1311 // no need to overload user in such cases
1313 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1314 // both must be type variables, or the other would've been instantiated
1315 assert!(a.is_ty_var() && b.is_ty_var());
1316 self.need_type_info_err(body_id,
1317 obligation.cause.span,
1323 if !self.tcx.sess.has_errors() {
1324 let mut err = struct_span_err!(self.tcx.sess,
1325 obligation.cause.span, E0284,
1326 "type annotations required: \
1327 cannot resolve `{}`",
1329 self.note_obligation_cause(&mut err, obligation);
1336 /// Returns whether the trait predicate may apply for *some* assignment
1337 /// to the type parameters.
1338 fn predicate_can_apply(&self,
1339 param_env: ty::ParamEnv<'tcx>,
1340 pred: ty::PolyTraitRef<'tcx>)
1342 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1343 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1344 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1347 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1348 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1350 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1351 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
1352 let infcx = self.infcx;
1353 self.var_map.entry(ty).or_insert_with(||
1355 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1357 ty.super_fold_with(self)
1363 let mut selcx = SelectionContext::new(self);
1365 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1367 var_map: FxHashMap()
1370 let cleaned_pred = super::project::normalize(
1373 ObligationCause::dummy(),
1377 let obligation = Obligation::new(
1378 ObligationCause::dummy(),
1380 cleaned_pred.to_predicate()
1383 self.predicate_may_hold(&obligation)
1387 fn note_obligation_cause<T>(&self,
1388 err: &mut DiagnosticBuilder,
1389 obligation: &Obligation<'tcx, T>)
1390 where T: fmt::Display
1392 self.note_obligation_cause_code(err,
1393 &obligation.predicate,
1394 &obligation.cause.code,
1398 fn note_obligation_cause_code<T>(&self,
1399 err: &mut DiagnosticBuilder,
1401 cause_code: &ObligationCauseCode<'tcx>,
1402 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1403 where T: fmt::Display
1407 ObligationCauseCode::ExprAssignable |
1408 ObligationCauseCode::MatchExpressionArm { .. } |
1409 ObligationCauseCode::IfExpression |
1410 ObligationCauseCode::IfExpressionWithNoElse |
1411 ObligationCauseCode::MainFunctionType |
1412 ObligationCauseCode::StartFunctionType |
1413 ObligationCauseCode::IntrinsicType |
1414 ObligationCauseCode::MethodReceiver |
1415 ObligationCauseCode::ReturnNoExpression |
1416 ObligationCauseCode::MiscObligation => {
1418 ObligationCauseCode::SliceOrArrayElem => {
1419 err.note("slice and array elements must have `Sized` type");
1421 ObligationCauseCode::TupleElem => {
1422 err.note("only the last element of a tuple may have a dynamically sized type");
1424 ObligationCauseCode::ProjectionWf(data) => {
1425 err.note(&format!("required so that the projection `{}` is well-formed",
1428 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1429 err.note(&format!("required so that reference `{}` does not outlive its referent",
1432 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1433 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1435 region, object_ty));
1437 ObligationCauseCode::ItemObligation(item_def_id) => {
1438 let item_name = tcx.item_path_str(item_def_id);
1439 let msg = format!("required by `{}`", item_name);
1440 if let Some(sp) = tcx.hir.span_if_local(item_def_id) {
1441 let sp = tcx.sess.source_map().def_span(sp);
1442 err.span_note(sp, &msg);
1447 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1448 err.note(&format!("required for the cast to the object type `{}`",
1449 self.ty_to_string(object_ty)));
1451 ObligationCauseCode::RepeatVec => {
1452 err.note("the `Copy` trait is required because the \
1453 repeated element will be copied");
1455 ObligationCauseCode::VariableType(_) => {
1456 err.note("all local variables must have a statically known size");
1457 if !self.tcx.features().unsized_locals {
1458 err.help("unsized locals are gated as an unstable feature");
1461 ObligationCauseCode::SizedArgumentType => {
1462 err.note("all function arguments must have a statically known size");
1463 if !self.tcx.features().unsized_locals {
1464 err.help("unsized locals are gated as an unstable feature");
1467 ObligationCauseCode::SizedReturnType => {
1468 err.note("the return type of a function must have a \
1469 statically known size");
1471 ObligationCauseCode::SizedYieldType => {
1472 err.note("the yield type of a generator must have a \
1473 statically known size");
1475 ObligationCauseCode::AssignmentLhsSized => {
1476 err.note("the left-hand-side of an assignment must have a statically known size");
1478 ObligationCauseCode::TupleInitializerSized => {
1479 err.note("tuples must have a statically known size to be initialized");
1481 ObligationCauseCode::StructInitializerSized => {
1482 err.note("structs must have a statically known size to be initialized");
1484 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
1486 AdtKind::Struct => {
1488 err.note("the last field of a packed struct may only have a \
1489 dynamically sized type if it does not need drop to be run");
1491 err.note("only the last field of a struct may have a dynamically \
1496 err.note("no field of a union may have a dynamically sized type");
1499 err.note("no field of an enum variant may have a dynamically sized type");
1503 ObligationCauseCode::ConstSized => {
1504 err.note("constant expressions must have a statically known size");
1506 ObligationCauseCode::SharedStatic => {
1507 err.note("shared static variables must have a type that implements `Sync`");
1509 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1510 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1511 let ty = parent_trait_ref.skip_binder().self_ty();
1512 err.note(&format!("required because it appears within the type `{}`", ty));
1513 obligated_types.push(ty);
1515 let parent_predicate = parent_trait_ref.to_predicate();
1516 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1517 self.note_obligation_cause_code(err,
1523 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1524 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1526 &format!("required because of the requirements on the impl of `{}` for `{}`",
1528 parent_trait_ref.skip_binder().self_ty()));
1529 let parent_predicate = parent_trait_ref.to_predicate();
1530 self.note_obligation_cause_code(err,
1535 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1537 &format!("the requirement `{}` appears on the impl method \
1538 but not on the corresponding trait method",
1541 ObligationCauseCode::ReturnType(_) |
1542 ObligationCauseCode::BlockTailExpression(_) => (),
1543 ObligationCauseCode::TrivialBound => {
1544 err.help("see issue #48214");
1545 if tcx.sess.opts.unstable_features.is_nightly_build() {
1546 err.help("add #![feature(trivial_bounds)] to the \
1547 crate attributes to enable",
1554 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1555 let current_limit = self.tcx.sess.recursion_limit.get();
1556 let suggested_limit = current_limit * 2;
1557 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1561 fn is_recursive_obligation(&self,
1562 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1563 cause_code: &ObligationCauseCode<'tcx>) -> bool {
1564 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1565 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1566 for obligated_type in obligated_types {
1567 if obligated_type == &parent_trait_ref.skip_binder().self_ty() {
1576 /// Summarizes information
1578 /// An argument of non-tuple type. Parameters are (name, ty)
1579 Arg(String, String),
1581 /// An argument of tuple type. For a "found" argument, the span is
1582 /// the locationo in the source of the pattern. For a "expected"
1583 /// argument, it will be None. The vector is a list of (name, ty)
1584 /// strings for the components of the tuple.
1585 Tuple(Option<Span>, Vec<(String, String)>),
1589 fn empty() -> ArgKind {
1590 ArgKind::Arg("_".to_owned(), "_".to_owned())
1593 /// Creates an `ArgKind` from the expected type of an
1594 /// argument. This has no name (`_`) and no source spans..
1595 pub fn from_expected_ty(t: Ty<'_>) -> ArgKind {
1597 ty::Tuple(ref tys) => ArgKind::Tuple(
1600 .map(|ty| ("_".to_owned(), ty.sty.to_string()))
1601 .collect::<Vec<_>>()
1603 _ => ArgKind::Arg("_".to_owned(), t.sty.to_string()),