6 MismatchedProjectionTypes,
11 OnUnimplementedDirective,
13 OutputTypeParameterMismatch,
23 use crate::hir::def_id::DefId;
24 use crate::infer::{self, InferCtxt};
25 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
26 use crate::session::DiagnosticMessageId;
27 use crate::ty::{self, AdtKind, DefIdTree, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
28 use crate::ty::GenericParamDefKind;
29 use crate::ty::error::ExpectedFound;
30 use crate::ty::fast_reject;
31 use crate::ty::fold::TypeFolder;
32 use crate::ty::subst::Subst;
33 use crate::ty::SubtypePredicate;
34 use crate::util::nodemap::{FxHashMap, FxHashSet};
36 use errors::{Applicability, DiagnosticBuilder, pluralize};
39 use syntax::symbol::{sym, kw};
40 use syntax_pos::{DUMMY_SP, Span, ExpnKind, MultiSpan};
42 use rustc_error_codes::*;
44 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
45 pub fn report_fulfillment_errors(
47 errors: &[FulfillmentError<'tcx>],
48 body_id: Option<hir::BodyId>,
49 fallback_has_occurred: bool,
52 struct ErrorDescriptor<'tcx> {
53 predicate: ty::Predicate<'tcx>,
54 index: Option<usize>, // None if this is an old error
57 let mut error_map: FxHashMap<_, Vec<_>> =
58 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
59 (span, predicates.iter().map(|predicate| ErrorDescriptor {
60 predicate: predicate.clone(),
65 for (index, error) in errors.iter().enumerate() {
66 // We want to ignore desugarings here: spans are equivalent even
67 // if one is the result of a desugaring and the other is not.
68 let mut span = error.obligation.cause.span;
69 let expn_data = span.ctxt().outer_expn_data();
70 if let ExpnKind::Desugaring(_) = expn_data.kind {
71 span = expn_data.call_site;
74 error_map.entry(span).or_default().push(
76 predicate: error.obligation.predicate.clone(),
81 self.reported_trait_errors.borrow_mut()
82 .entry(span).or_default()
83 .push(error.obligation.predicate.clone());
86 // We do this in 2 passes because we want to display errors in order, though
87 // maybe it *is* better to sort errors by span or something.
88 let mut is_suppressed = vec![false; errors.len()];
89 for (_, error_set) in error_map.iter() {
90 // We want to suppress "duplicate" errors with the same span.
91 for error in error_set {
92 if let Some(index) = error.index {
93 // Suppress errors that are either:
94 // 1) strictly implied by another error.
95 // 2) implied by an error with a smaller index.
96 for error2 in error_set {
97 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
98 // Avoid errors being suppressed by already-suppressed
99 // errors, to prevent all errors from being suppressed
104 if self.error_implies(&error2.predicate, &error.predicate) &&
105 !(error2.index >= error.index &&
106 self.error_implies(&error.predicate, &error2.predicate))
108 info!("skipping {:?} (implied by {:?})", error, error2);
109 is_suppressed[index] = true;
117 for (error, suppressed) in errors.iter().zip(is_suppressed) {
119 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
124 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
125 // `error` occurring implies that `cond` occurs.
128 cond: &ty::Predicate<'tcx>,
129 error: &ty::Predicate<'tcx>,
135 let (cond, error) = match (cond, error) {
136 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
139 // FIXME: make this work in other cases too.
144 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
145 if let ty::Predicate::Trait(implication) = implication {
146 let error = error.to_poly_trait_ref();
147 let implication = implication.to_poly_trait_ref();
148 // FIXME: I'm just not taking associated types at all here.
149 // Eventually I'll need to implement param-env-aware
150 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
151 let param_env = ty::ParamEnv::empty();
152 if self.can_sub(param_env, error, implication).is_ok() {
153 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
162 fn report_fulfillment_error(
164 error: &FulfillmentError<'tcx>,
165 body_id: Option<hir::BodyId>,
166 fallback_has_occurred: bool,
168 debug!("report_fulfillment_errors({:?})", error);
170 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
171 self.report_selection_error(
174 fallback_has_occurred,
175 error.points_at_arg_span,
178 FulfillmentErrorCode::CodeProjectionError(ref e) => {
179 self.report_projection_error(&error.obligation, e);
181 FulfillmentErrorCode::CodeAmbiguity => {
182 self.maybe_report_ambiguity(&error.obligation, body_id);
184 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
185 self.report_mismatched_types(
186 &error.obligation.cause,
187 expected_found.expected,
188 expected_found.found,
195 fn report_projection_error(
197 obligation: &PredicateObligation<'tcx>,
198 error: &MismatchedProjectionTypes<'tcx>,
200 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
202 if predicate.references_error() {
208 let mut err = &error.err;
209 let mut values = None;
211 // try to find the mismatched types to report the error with.
213 // this can fail if the problem was higher-ranked, in which
214 // cause I have no idea for a good error message.
215 if let ty::Predicate::Projection(ref data) = predicate {
216 let mut selcx = SelectionContext::new(self);
217 let (data, _) = self.replace_bound_vars_with_fresh_vars(
218 obligation.cause.span,
219 infer::LateBoundRegionConversionTime::HigherRankedType,
222 let mut obligations = vec![];
223 let normalized_ty = super::normalize_projection_type(
225 obligation.param_env,
227 obligation.cause.clone(),
232 debug!("report_projection_error obligation.cause={:?} obligation.param_env={:?}",
233 obligation.cause, obligation.param_env);
235 debug!("report_projection_error normalized_ty={:?} data.ty={:?}",
236 normalized_ty, data.ty);
238 let is_normalized_ty_expected = match &obligation.cause.code {
239 ObligationCauseCode::ItemObligation(_) |
240 ObligationCauseCode::BindingObligation(_, _) |
241 ObligationCauseCode::ObjectCastObligation(_) => false,
245 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
246 .eq_exp(is_normalized_ty_expected, normalized_ty, data.ty)
248 values = Some(infer::ValuePairs::Types(
249 ExpectedFound::new(is_normalized_ty_expected, normalized_ty, data.ty)));
256 let msg = format!("type mismatch resolving `{}`", predicate);
258 DiagnosticMessageId::ErrorId(271),
259 Some(obligation.cause.span),
262 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
264 let mut diag = struct_span_err!(
266 obligation.cause.span,
268 "type mismatch resolving `{}`",
271 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
272 self.note_obligation_cause(&mut diag, obligation);
278 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
279 /// returns the fuzzy category of a given type, or None
280 /// if the type can be equated to any type.
281 fn type_category(t: Ty<'_>) -> Option<u32> {
286 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
287 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
288 ty::Ref(..) | ty::RawPtr(..) => Some(5),
289 ty::Array(..) | ty::Slice(..) => Some(6),
290 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
291 ty::Dynamic(..) => Some(8),
292 ty::Closure(..) => Some(9),
293 ty::Tuple(..) => Some(10),
294 ty::Projection(..) => Some(11),
295 ty::Param(..) => Some(12),
296 ty::Opaque(..) => Some(13),
297 ty::Never => Some(14),
298 ty::Adt(adt, ..) => match adt.adt_kind() {
299 AdtKind::Struct => Some(15),
300 AdtKind::Union => Some(16),
301 AdtKind::Enum => Some(17),
303 ty::Generator(..) => Some(18),
304 ty::Foreign(..) => Some(19),
305 ty::GeneratorWitness(..) => Some(20),
306 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
307 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
311 match (type_category(a), type_category(b)) {
312 (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
313 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
316 // infer and error can be equated to all types
321 fn impl_similar_to(&self,
322 trait_ref: ty::PolyTraitRef<'tcx>,
323 obligation: &PredicateObligation<'tcx>)
327 let param_env = obligation.param_env;
328 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
329 let trait_self_ty = trait_ref.self_ty();
331 let mut self_match_impls = vec![];
332 let mut fuzzy_match_impls = vec![];
334 self.tcx.for_each_relevant_impl(
335 trait_ref.def_id, trait_self_ty, |def_id| {
336 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
337 let impl_trait_ref = tcx
338 .impl_trait_ref(def_id)
340 .subst(tcx, impl_substs);
342 let impl_self_ty = impl_trait_ref.self_ty();
344 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
345 self_match_impls.push(def_id);
347 if trait_ref.substs.types().skip(1)
348 .zip(impl_trait_ref.substs.types().skip(1))
349 .all(|(u,v)| self.fuzzy_match_tys(u, v))
351 fuzzy_match_impls.push(def_id);
356 let impl_def_id = if self_match_impls.len() == 1 {
358 } else if fuzzy_match_impls.len() == 1 {
364 if tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented) {
371 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
372 self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| {
374 hir::GeneratorKind::Gen => "a generator",
375 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
376 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
377 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
382 /// Used to set on_unimplemented's `ItemContext`
383 /// to be the enclosing (async) block/function/closure
384 fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str> {
385 let hir = &self.tcx.hir();
386 let node = hir.find(hir_id)?;
387 if let hir::Node::Item(
388 hir::Item{kind: hir::ItemKind::Fn(sig, _, body_id), .. }) = &node {
389 self.describe_generator(*body_id).or_else(||
390 Some(if let hir::FnHeader{ asyncness: hir::IsAsync::Async, .. } = sig.header {
396 } else if let hir::Node::Expr(hir::Expr {
397 kind: hir::ExprKind::Closure(_is_move, _, body_id, _, gen_movability), .. }) = &node {
398 self.describe_generator(*body_id).or_else(||
399 Some(if gen_movability.is_some() {
405 } else if let hir::Node::Expr(hir::Expr { .. }) = &node {
406 let parent_hid = hir.get_parent_node(hir_id);
407 if parent_hid != hir_id {
408 return self.describe_enclosure(parent_hid);
417 fn on_unimplemented_note(
419 trait_ref: ty::PolyTraitRef<'tcx>,
420 obligation: &PredicateObligation<'tcx>,
421 ) -> OnUnimplementedNote {
422 let def_id = self.impl_similar_to(trait_ref, obligation)
423 .unwrap_or_else(|| trait_ref.def_id());
424 let trait_ref = *trait_ref.skip_binder();
426 let mut flags = vec![];
427 flags.push((sym::item_context,
428 self.describe_enclosure(obligation.cause.body_id).map(|s|s.to_owned())));
430 match obligation.cause.code {
431 ObligationCauseCode::BuiltinDerivedObligation(..) |
432 ObligationCauseCode::ImplDerivedObligation(..) => {}
434 // this is a "direct", user-specified, rather than derived,
436 flags.push((sym::direct, None));
440 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
441 // FIXME: maybe also have some way of handling methods
442 // from other traits? That would require name resolution,
443 // which we might want to be some sort of hygienic.
445 // Currently I'm leaving it for what I need for `try`.
446 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
447 let method = self.tcx.item_name(item);
448 flags.push((sym::from_method, None));
449 flags.push((sym::from_method, Some(method.to_string())));
452 if let Some(t) = self.get_parent_trait_ref(&obligation.cause.code) {
453 flags.push((sym::parent_trait, Some(t)));
456 if let Some(k) = obligation.cause.span.desugaring_kind() {
457 flags.push((sym::from_desugaring, None));
458 flags.push((sym::from_desugaring, Some(format!("{:?}", k))));
460 let generics = self.tcx.generics_of(def_id);
461 let self_ty = trait_ref.self_ty();
462 // This is also included through the generics list as `Self`,
463 // but the parser won't allow you to use it
464 flags.push((sym::_Self, Some(self_ty.to_string())));
465 if let Some(def) = self_ty.ty_adt_def() {
466 // We also want to be able to select self's original
467 // signature with no type arguments resolved
468 flags.push((sym::_Self, Some(self.tcx.type_of(def.did).to_string())));
471 for param in generics.params.iter() {
472 let value = match param.kind {
473 GenericParamDefKind::Type { .. } |
474 GenericParamDefKind::Const => {
475 trait_ref.substs[param.index as usize].to_string()
477 GenericParamDefKind::Lifetime => continue,
479 let name = param.name;
480 flags.push((name, Some(value)));
483 if let Some(true) = self_ty.ty_adt_def().map(|def| def.did.is_local()) {
484 flags.push((sym::crate_local, None));
487 // Allow targeting all integers using `{integral}`, even if the exact type was resolved
488 if self_ty.is_integral() {
489 flags.push((sym::_Self, Some("{integral}".to_owned())));
492 if let ty::Array(aty, len) = self_ty.kind {
493 flags.push((sym::_Self, Some("[]".to_owned())));
494 flags.push((sym::_Self, Some(format!("[{}]", aty))));
495 if let Some(def) = aty.ty_adt_def() {
496 // We also want to be able to select the array's type's original
497 // signature with no type arguments resolved
500 Some(format!("[{}]", self.tcx.type_of(def.did).to_string())),
503 if let Some(len) = len.try_eval_usize(tcx, ty::ParamEnv::empty()) {
506 Some(format!("[{}; {}]", self.tcx.type_of(def.did).to_string(), len)),
511 Some(format!("[{}; _]", self.tcx.type_of(def.did).to_string())),
517 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
518 self.tcx, trait_ref.def_id, def_id
520 command.evaluate(self.tcx, trait_ref, &flags[..])
522 OnUnimplementedNote::empty()
526 fn find_similar_impl_candidates(
528 trait_ref: ty::PolyTraitRef<'tcx>,
529 ) -> Vec<ty::TraitRef<'tcx>> {
530 let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
531 let all_impls = self.tcx.all_impls(trait_ref.def_id());
534 Some(simp) => all_impls.iter().filter_map(|&def_id| {
535 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
536 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
537 if let Some(imp_simp) = imp_simp {
538 if simp != imp_simp {
545 None => all_impls.iter().map(|&def_id|
546 self.tcx.impl_trait_ref(def_id).unwrap()
551 fn report_similar_impl_candidates(
553 impl_candidates: Vec<ty::TraitRef<'tcx>>,
554 err: &mut DiagnosticBuilder<'_>,
556 if impl_candidates.is_empty() {
560 let len = impl_candidates.len();
561 let end = if impl_candidates.len() <= 5 {
562 impl_candidates.len()
567 let normalize = |candidate| self.tcx.infer_ctxt().enter(|ref infcx| {
568 let normalized = infcx
569 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
570 .normalize(candidate)
573 Some(normalized) => format!("\n {:?}", normalized.value),
574 None => format!("\n {:?}", candidate),
578 // Sort impl candidates so that ordering is consistent for UI tests.
579 let mut normalized_impl_candidates = impl_candidates
582 .collect::<Vec<String>>();
584 // Sort before taking the `..end` range,
585 // because the ordering of `impl_candidates` may not be deterministic:
586 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
587 normalized_impl_candidates.sort();
589 err.help(&format!("the following implementations were found:{}{}",
590 normalized_impl_candidates[..end].join(""),
592 format!("\nand {} others", len - 4)
599 /// Reports that an overflow has occurred and halts compilation. We
600 /// halt compilation unconditionally because it is important that
601 /// overflows never be masked -- they basically represent computations
602 /// whose result could not be truly determined and thus we can't say
603 /// if the program type checks or not -- and they are unusual
604 /// occurrences in any case.
605 pub fn report_overflow_error<T>(
607 obligation: &Obligation<'tcx, T>,
608 suggest_increasing_limit: bool,
610 where T: fmt::Display + TypeFoldable<'tcx>
613 self.resolve_vars_if_possible(&obligation.predicate);
614 let mut err = struct_span_err!(
616 obligation.cause.span,
618 "overflow evaluating the requirement `{}`",
622 if suggest_increasing_limit {
623 self.suggest_new_overflow_limit(&mut err);
626 self.note_obligation_cause_code(
628 &obligation.predicate,
629 &obligation.cause.code,
634 self.tcx.sess.abort_if_errors();
638 /// Reports that a cycle was detected which led to overflow and halts
639 /// compilation. This is equivalent to `report_overflow_error` except
640 /// that we can give a more helpful error message (and, in particular,
641 /// we do not suggest increasing the overflow limit, which is not
643 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
644 let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
645 assert!(cycle.len() > 0);
647 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
649 self.report_overflow_error(&cycle[0], false);
652 pub fn report_extra_impl_obligation(&self,
654 item_name: ast::Name,
655 _impl_item_def_id: DefId,
656 trait_item_def_id: DefId,
657 requirement: &dyn fmt::Display)
658 -> DiagnosticBuilder<'tcx>
660 let msg = "impl has stricter requirements than trait";
661 let sp = self.tcx.sess.source_map().def_span(error_span);
663 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
665 if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) {
666 let span = self.tcx.sess.source_map().def_span(trait_item_span);
667 err.span_label(span, format!("definition of `{}` from trait", item_name));
670 err.span_label(sp, format!("impl has extra requirement {}", requirement));
676 /// Gets the parent trait chain start
677 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
679 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
680 let parent_trait_ref = self.resolve_vars_if_possible(
681 &data.parent_trait_ref);
682 match self.get_parent_trait_ref(&data.parent_code) {
684 None => Some(parent_trait_ref.skip_binder().self_ty().to_string()),
691 pub fn report_selection_error(
693 obligation: &PredicateObligation<'tcx>,
694 error: &SelectionError<'tcx>,
695 fallback_has_occurred: bool,
698 let span = obligation.cause.span;
700 let mut err = match *error {
701 SelectionError::Unimplemented => {
702 if let ObligationCauseCode::CompareImplMethodObligation {
703 item_name, impl_item_def_id, trait_item_def_id,
704 } = obligation.cause.code {
705 self.report_extra_impl_obligation(
710 &format!("`{}`", obligation.predicate))
714 match obligation.predicate {
715 ty::Predicate::Trait(ref trait_predicate) => {
716 let trait_predicate =
717 self.resolve_vars_if_possible(trait_predicate);
719 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
722 let trait_ref = trait_predicate.to_poly_trait_ref();
723 let (post_message, pre_message) =
724 self.get_parent_trait_ref(&obligation.cause.code)
725 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
726 .unwrap_or_default();
728 let OnUnimplementedNote { message, label, note }
729 = self.on_unimplemented_note(trait_ref, obligation);
730 let have_alt_message = message.is_some() || label.is_some();
731 let is_try = self.tcx.sess.source_map().span_to_snippet(span)
734 let is_from = format!("{}", trait_ref).starts_with("std::convert::From<");
735 let (message, note) = if is_try && is_from {
737 "`?` couldn't convert the error to `{}`",
740 "the question mark operation (`?`) implicitly performs a \
741 conversion on the error value using the `From` trait".to_owned()
747 let mut err = struct_span_err!(
752 message.unwrap_or_else(|| format!(
753 "the trait bound `{}` is not satisfied{}",
754 trait_ref.to_predicate(),
759 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
760 "consider using `()`, or a `Result`".to_owned()
763 "{}the trait `{}` is not implemented for `{}`",
770 if let Some(ref s) = label {
771 // If it has a custom `#[rustc_on_unimplemented]`
772 // error message, let's display it as the label!
773 err.span_label(span, s.as_str());
774 err.help(&explanation);
776 err.span_label(span, explanation);
778 if let Some(ref s) = note {
779 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
780 err.note(s.as_str());
783 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
784 self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
785 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
786 self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
788 // Try to report a help message
789 if !trait_ref.has_infer_types() &&
790 self.predicate_can_apply(obligation.param_env, trait_ref) {
791 // If a where-clause may be useful, remind the
792 // user that they can add it.
794 // don't display an on-unimplemented note, as
795 // these notes will often be of the form
796 // "the type `T` can't be frobnicated"
797 // which is somewhat confusing.
798 self.suggest_restricting_param_bound(
801 obligation.cause.body_id,
804 if !have_alt_message {
805 // Can't show anything else useful, try to find similar impls.
806 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
807 self.report_similar_impl_candidates(impl_candidates, &mut err);
809 self.suggest_change_mut(
817 // If this error is due to `!: Trait` not implemented but `(): Trait` is
818 // implemented, and fallback has occurred, then it could be due to a
819 // variable that used to fallback to `()` now falling back to `!`. Issue a
820 // note informing about the change in behaviour.
821 if trait_predicate.skip_binder().self_ty().is_never()
822 && fallback_has_occurred
824 let predicate = trait_predicate.map_bound(|mut trait_pred| {
825 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
827 &trait_pred.trait_ref.substs[1..],
831 let unit_obligation = Obligation {
832 predicate: ty::Predicate::Trait(predicate),
833 .. obligation.clone()
835 if self.predicate_may_hold(&unit_obligation) {
836 err.note("the trait is implemented for `()`. \
837 Possibly this error has been caused by changes to \
838 Rust's type-inference algorithm \
839 (see: https://github.com/rust-lang/rust/issues/48950 \
840 for more info). Consider whether you meant to use the \
841 type `()` here instead.");
848 ty::Predicate::Subtype(ref predicate) => {
849 // Errors for Subtype predicates show up as
850 // `FulfillmentErrorCode::CodeSubtypeError`,
851 // not selection error.
852 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
855 ty::Predicate::RegionOutlives(ref predicate) => {
856 let predicate = self.resolve_vars_if_possible(predicate);
857 let err = self.region_outlives_predicate(&obligation.cause,
858 &predicate).err().unwrap();
860 self.tcx.sess, span, E0279,
861 "the requirement `{}` is not satisfied (`{}`)",
866 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
868 self.resolve_vars_if_possible(&obligation.predicate);
869 struct_span_err!(self.tcx.sess, span, E0280,
870 "the requirement `{}` is not satisfied",
874 ty::Predicate::ObjectSafe(trait_def_id) => {
875 let violations = self.tcx.object_safety_violations(trait_def_id);
876 self.tcx.report_object_safety_error(
883 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
884 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
885 let closure_span = self.tcx.sess.source_map()
886 .def_span(self.tcx.hir().span_if_local(closure_def_id).unwrap());
887 let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
888 let mut err = struct_span_err!(
889 self.tcx.sess, closure_span, E0525,
890 "expected a closure that implements the `{}` trait, \
891 but this closure only implements `{}`",
897 format!("this closure implements `{}`, not `{}`", found_kind, kind));
899 obligation.cause.span,
900 format!("the requirement to implement `{}` derives from here", kind));
902 // Additional context information explaining why the closure only implements
903 // a particular trait.
904 if let Some(tables) = self.in_progress_tables {
905 let tables = tables.borrow();
906 match (found_kind, tables.closure_kind_origins().get(hir_id)) {
907 (ty::ClosureKind::FnOnce, Some((span, name))) => {
908 err.span_label(*span, format!(
909 "closure is `FnOnce` because it moves the \
910 variable `{}` out of its environment", name));
912 (ty::ClosureKind::FnMut, Some((span, name))) => {
913 err.span_label(*span, format!(
914 "closure is `FnMut` because it mutates the \
915 variable `{}` here", name));
925 ty::Predicate::WellFormed(ty) => {
926 if !self.tcx.sess.opts.debugging_opts.chalk {
927 // WF predicates cannot themselves make
928 // errors. They can only block due to
929 // ambiguity; otherwise, they always
930 // degenerate into other obligations
932 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
934 // FIXME: we'll need a better message which takes into account
935 // which bounds actually failed to hold.
936 self.tcx.sess.struct_span_err(
938 &format!("the type `{}` is not well-formed (chalk)", ty)
943 ty::Predicate::ConstEvaluatable(..) => {
944 // Errors for `ConstEvaluatable` predicates show up as
945 // `SelectionError::ConstEvalFailure`,
946 // not `Unimplemented`.
948 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
953 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
954 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
955 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
957 if expected_trait_ref.self_ty().references_error() {
961 let found_trait_ty = found_trait_ref.self_ty();
963 let found_did = match found_trait_ty.kind {
964 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
965 ty::Adt(def, _) => Some(def.did),
969 let found_span = found_did.and_then(|did|
970 self.tcx.hir().span_if_local(did)
971 ).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def
973 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
974 // We check closures twice, with obligations flowing in different directions,
975 // but we want to complain about them only once.
979 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
981 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
982 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
983 _ => vec![ArgKind::empty()],
986 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
987 let expected = match expected_ty.kind {
988 ty::Tuple(ref tys) => tys.iter()
989 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span))).collect(),
990 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
993 if found.len() == expected.len() {
994 self.report_closure_arg_mismatch(span,
999 let (closure_span, found) = found_did
1000 .and_then(|did| self.tcx.hir().get_if_local(did))
1002 let (found_span, found) = self.get_fn_like_arguments(node);
1003 (Some(found_span), found)
1004 }).unwrap_or((found_span, found));
1006 self.report_arg_count_mismatch(span,
1010 found_trait_ty.is_closure())
1014 TraitNotObjectSafe(did) => {
1015 let violations = self.tcx.object_safety_violations(did);
1016 self.tcx.report_object_safety_error(span, did, violations)
1019 // already reported in the query
1020 ConstEvalFailure(err) => {
1021 self.tcx.sess.delay_span_bug(
1023 &format!("constant in type had an ignored error: {:?}", err),
1029 bug!("overflow should be handled before the `report_selection_error` path");
1033 self.note_obligation_cause(&mut err, obligation);
1038 fn suggest_restricting_param_bound(
1040 err: &mut DiagnosticBuilder<'_>,
1041 trait_ref: &ty::PolyTraitRef<'_>,
1042 body_id: hir::HirId,
1044 let self_ty = trait_ref.self_ty();
1045 let (param_ty, projection) = match &self_ty.kind {
1046 ty::Param(_) => (true, None),
1047 ty::Projection(projection) => (false, Some(projection)),
1051 let mut suggest_restriction = |generics: &hir::Generics, msg| {
1052 let span = generics.where_clause.span_for_predicates_or_empty_place();
1053 if !span.from_expansion() && span.desugaring_kind().is_none() {
1054 err.span_suggestion(
1055 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
1056 &format!("consider further restricting {}", msg),
1059 if !generics.where_clause.predicates.is_empty() {
1064 trait_ref.to_predicate(),
1066 Applicability::MachineApplicable,
1071 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
1072 // don't suggest `T: Sized + ?Sized`.
1073 let mut hir_id = body_id;
1074 while let Some(node) = self.tcx.hir().find(hir_id) {
1076 hir::Node::TraitItem(hir::TraitItem {
1078 kind: hir::TraitItemKind::Method(..), ..
1079 }) if param_ty && self_ty == self.tcx.types.self_param => {
1080 // Restricting `Self` for a single method.
1081 suggest_restriction(&generics, "`Self`");
1085 hir::Node::Item(hir::Item {
1086 kind: hir::ItemKind::Fn(_, generics, _), ..
1088 hir::Node::TraitItem(hir::TraitItem {
1090 kind: hir::TraitItemKind::Method(..), ..
1092 hir::Node::ImplItem(hir::ImplItem {
1094 kind: hir::ImplItemKind::Method(..), ..
1096 hir::Node::Item(hir::Item {
1097 kind: hir::ItemKind::Trait(_, _, generics, _, _), ..
1099 hir::Node::Item(hir::Item {
1100 kind: hir::ItemKind::Impl(_, _, _, generics, ..), ..
1101 }) if projection.is_some() => {
1102 // Missing associated type bound.
1103 suggest_restriction(&generics, "the associated type");
1107 hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(_, generics), span, .. }) |
1108 hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(_, generics), span, .. }) |
1109 hir::Node::Item(hir::Item { kind: hir::ItemKind::Union(_, generics), span, .. }) |
1110 hir::Node::Item(hir::Item {
1111 kind: hir::ItemKind::Trait(_, _, generics, ..), span, ..
1113 hir::Node::Item(hir::Item {
1114 kind: hir::ItemKind::Impl(_, _, _, generics, ..), span, ..
1116 hir::Node::Item(hir::Item {
1117 kind: hir::ItemKind::Fn(_, generics, _), span, ..
1119 hir::Node::Item(hir::Item {
1120 kind: hir::ItemKind::TyAlias(_, generics), span, ..
1122 hir::Node::Item(hir::Item {
1123 kind: hir::ItemKind::TraitAlias(generics, _), span, ..
1125 hir::Node::Item(hir::Item {
1126 kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }), span, ..
1128 hir::Node::TraitItem(hir::TraitItem { generics, span, .. }) |
1129 hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
1131 // Missing generic type parameter bound.
1132 let restrict_msg = "consider further restricting this bound";
1133 let param_name = self_ty.to_string();
1134 for param in generics.params.iter().filter(|p| {
1135 p.name.ident().as_str() == param_name
1137 if param_name.starts_with("impl ") {
1138 // `impl Trait` in argument:
1139 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
1140 err.span_suggestion(
1143 // `impl CurrentTrait + MissingTrait`
1144 format!("{} + {}", param.name.ident(), trait_ref),
1145 Applicability::MachineApplicable,
1147 } else if generics.where_clause.predicates.is_empty() &&
1148 param.bounds.is_empty()
1150 // If there are no bounds whatsoever, suggest adding a constraint
1151 // to the type parameter:
1152 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
1153 err.span_suggestion(
1155 "consider restricting this bound",
1156 format!("{}", trait_ref.to_predicate()),
1157 Applicability::MachineApplicable,
1159 } else if !generics.where_clause.predicates.is_empty() {
1160 // There is a `where` clause, so suggest expanding it:
1161 // `fn foo<T>(t: T) where T: Debug {}` →
1162 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
1163 err.span_suggestion(
1164 generics.where_clause.span().unwrap().shrink_to_hi(),
1166 "consider further restricting type parameter `{}`",
1169 format!(", {}", trait_ref.to_predicate()),
1170 Applicability::MachineApplicable,
1173 // If there is no `where` clause lean towards constraining to the
1175 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
1176 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
1177 let sp = param.span.with_hi(span.hi());
1178 let span = self.tcx.sess.source_map()
1179 .span_through_char(sp, ':');
1180 if sp != param.span && sp != span {
1181 // Only suggest if we have high certainty that the span
1182 // covers the colon in `foo<T: Trait>`.
1183 err.span_suggestion(span, restrict_msg, format!(
1185 trait_ref.to_predicate(),
1186 ), Applicability::MachineApplicable);
1188 err.span_label(param.span, &format!(
1189 "consider adding a `where {}` bound",
1190 trait_ref.to_predicate(),
1198 hir::Node::Crate => return,
1203 hir_id = self.tcx.hir().get_parent_item(hir_id);
1207 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
1208 /// suggestion to borrow the initializer in order to use have a slice instead.
1209 fn suggest_borrow_on_unsized_slice(
1211 code: &ObligationCauseCode<'tcx>,
1212 err: &mut DiagnosticBuilder<'tcx>,
1214 if let &ObligationCauseCode::VariableType(hir_id) = code {
1215 let parent_node = self.tcx.hir().get_parent_node(hir_id);
1216 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
1217 if let Some(ref expr) = local.init {
1218 if let hir::ExprKind::Index(_, _) = expr.kind {
1219 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
1220 err.span_suggestion(
1222 "consider borrowing here",
1223 format!("&{}", snippet),
1224 Applicability::MachineApplicable
1233 fn mk_obligation_for_def_id(
1236 output_ty: Ty<'tcx>,
1237 cause: ObligationCause<'tcx>,
1238 param_env: ty::ParamEnv<'tcx>,
1239 ) -> PredicateObligation<'tcx> {
1240 let new_trait_ref = ty::TraitRef {
1242 substs: self.tcx.mk_substs_trait(output_ty, &[]),
1244 Obligation::new(cause, param_env, new_trait_ref.to_predicate())
1248 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
1249 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
1250 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
1253 obligation: &PredicateObligation<'tcx>,
1254 err: &mut DiagnosticBuilder<'_>,
1255 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1256 points_at_arg: bool,
1258 let self_ty = trait_ref.self_ty();
1259 let (def_id, output_ty, callable) = match self_ty.kind {
1260 ty::Closure(def_id, substs) => {
1261 (def_id, self.closure_sig(def_id, substs).output(), "closure")
1263 ty::FnDef(def_id, _) => {
1264 (def_id, self_ty.fn_sig(self.tcx).output(), "function")
1268 let msg = format!("use parentheses to call the {}", callable);
1270 let obligation = self.mk_obligation_for_def_id(
1272 output_ty.skip_binder(),
1273 obligation.cause.clone(),
1274 obligation.param_env,
1277 let get_name = |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind| -> Option<String> {
1278 // Get the local name of this closure. This can be inaccurate because
1279 // of the possibility of reassignment, but this should be good enough.
1281 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
1282 Some(format!("{}", name))
1290 match self.evaluate_obligation(&obligation) {
1291 Ok(EvaluationResult::EvaluatedToOk) |
1292 Ok(EvaluationResult::EvaluatedToOkModuloRegions) |
1293 Ok(EvaluationResult::EvaluatedToAmbig) => {}
1296 let hir = self.tcx.hir();
1297 // Get the name of the callable and the arguments to be used in the suggestion.
1298 let snippet = match hir.get_if_local(def_id) {
1299 Some(hir::Node::Expr(hir::Expr {
1300 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
1303 err.span_label(*span, "consider calling this closure");
1304 let hir_id = match hir.as_local_hir_id(def_id) {
1305 Some(hir_id) => hir_id,
1308 let parent_node = hir.get_parent_node(hir_id);
1309 let name = match hir.find(parent_node) {
1310 Some(hir::Node::Stmt(hir::Stmt {
1311 kind: hir::StmtKind::Local(local), ..
1312 })) => match get_name(err, &local.pat.kind) {
1316 // Different to previous arm because one is `&hir::Local` and the other
1317 // is `P<hir::Local>`.
1318 Some(hir::Node::Local(local)) => match get_name(err, &local.pat.kind) {
1324 let args = decl.inputs.iter()
1326 .collect::<Vec<_>>().join(", ");
1327 format!("{}({})", name, args)
1329 Some(hir::Node::Item(hir::Item {
1331 kind: hir::ItemKind::Fn(.., body_id),
1334 err.span_label(ident.span, "consider calling this function");
1335 let body = hir.body(*body_id);
1336 let args = body.params.iter()
1337 .map(|arg| match &arg.pat.kind {
1338 hir::PatKind::Binding(_, _, ident, None)
1339 if ident.name != kw::SelfLower => ident.to_string(),
1340 _ => "_".to_string(),
1341 }).collect::<Vec<_>>().join(", ");
1342 format!("{}({})", ident, args)
1347 // When the obligation error has been ensured to have been caused by
1348 // an argument, the `obligation.cause.span` points at the expression
1349 // of the argument, so we can provide a suggestion. This is signaled
1350 // by `points_at_arg`. Otherwise, we give a more general note.
1351 err.span_suggestion(
1352 obligation.cause.span,
1355 Applicability::HasPlaceholders,
1358 err.help(&format!("{}: `{}`", msg, snippet));
1362 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1363 /// suggest removing these references until we reach a type that implements the trait.
1364 fn suggest_remove_reference(
1366 obligation: &PredicateObligation<'tcx>,
1367 err: &mut DiagnosticBuilder<'tcx>,
1368 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1370 let trait_ref = trait_ref.skip_binder();
1371 let span = obligation.cause.span;
1373 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1374 let refs_number = snippet.chars()
1375 .filter(|c| !c.is_whitespace())
1376 .take_while(|c| *c == '&')
1378 if let Some('\'') = snippet.chars()
1379 .filter(|c| !c.is_whitespace())
1382 { // Do not suggest removal of borrow from type arguments.
1386 let mut trait_type = trait_ref.self_ty();
1388 for refs_remaining in 0..refs_number {
1389 if let ty::Ref(_, t_type, _) = trait_type.kind {
1390 trait_type = t_type;
1392 let new_obligation = self.mk_obligation_for_def_id(
1395 ObligationCause::dummy(),
1396 obligation.param_env,
1399 if self.predicate_may_hold(&new_obligation) {
1400 let sp = self.tcx.sess.source_map()
1401 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1403 let remove_refs = refs_remaining + 1;
1404 let format_str = format!("consider removing {} leading `&`-references",
1407 err.span_suggestion_short(
1408 sp, &format_str, String::new(), Applicability::MachineApplicable
1419 /// Check if the trait bound is implemented for a different mutability and note it in the
1421 fn suggest_change_mut(
1423 obligation: &PredicateObligation<'tcx>,
1424 err: &mut DiagnosticBuilder<'tcx>,
1425 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1426 points_at_arg: bool,
1428 let span = obligation.cause.span;
1429 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1430 let refs_number = snippet.chars()
1431 .filter(|c| !c.is_whitespace())
1432 .take_while(|c| *c == '&')
1434 if let Some('\'') = snippet.chars()
1435 .filter(|c| !c.is_whitespace())
1438 { // Do not suggest removal of borrow from type arguments.
1441 let trait_ref = self.resolve_vars_if_possible(trait_ref);
1442 if trait_ref.has_infer_types() {
1443 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1444 // unresolved bindings.
1448 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1449 let trait_type = match mutability {
1450 hir::Mutability::Mutable => self.tcx.mk_imm_ref(region, t_type),
1451 hir::Mutability::Immutable => self.tcx.mk_mut_ref(region, t_type),
1454 let new_obligation = self.mk_obligation_for_def_id(
1455 trait_ref.skip_binder().def_id,
1457 ObligationCause::dummy(),
1458 obligation.param_env,
1461 if self.evaluate_obligation_no_overflow(
1463 ).must_apply_modulo_regions() {
1464 let sp = self.tcx.sess.source_map()
1465 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1467 mutability == hir::Mutability::Immutable &&
1470 err.span_suggestion(
1472 "consider changing this borrow's mutability",
1473 "&mut ".to_string(),
1474 Applicability::MachineApplicable,
1478 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1481 trait_ref.skip_binder().self_ty(),
1489 fn suggest_semicolon_removal(
1491 obligation: &PredicateObligation<'tcx>,
1492 err: &mut DiagnosticBuilder<'tcx>,
1494 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1496 let hir = self.tcx.hir();
1497 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1498 let node = hir.find(parent_node);
1499 if let Some(hir::Node::Item(hir::Item {
1500 kind: hir::ItemKind::Fn(sig, _, body_id),
1503 let body = hir.body(*body_id);
1504 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1505 if sig.decl.output.span().overlaps(span) && blk.expr.is_none() &&
1506 "()" == &trait_ref.self_ty().to_string()
1508 // FIXME(estebank): When encountering a method with a trait
1509 // bound not satisfied in the return type with a body that has
1510 // no return, suggest removal of semicolon on last statement.
1511 // Once that is added, close #54771.
1512 if let Some(ref stmt) = blk.stmts.last() {
1513 let sp = self.tcx.sess.source_map().end_point(stmt.span);
1514 err.span_label(sp, "consider removing this semicolon");
1521 /// Given some node representing a fn-like thing in the HIR map,
1522 /// returns a span and `ArgKind` information that describes the
1523 /// arguments it expects. This can be supplied to
1524 /// `report_arg_count_mismatch`.
1525 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
1527 Node::Expr(&hir::Expr {
1528 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
1531 (self.tcx.sess.source_map().def_span(span),
1532 self.tcx.hir().body(id).params.iter()
1535 kind: hir::PatKind::Tuple(ref args, _),
1541 args.iter().map(|pat| {
1542 let snippet = self.tcx.sess.source_map()
1543 .span_to_snippet(pat.span).unwrap();
1544 (snippet, "_".to_owned())
1545 }).collect::<Vec<_>>(),
1548 let name = self.tcx.sess.source_map()
1549 .span_to_snippet(arg.pat.span).unwrap();
1550 ArgKind::Arg(name, "_".to_owned())
1553 .collect::<Vec<ArgKind>>())
1555 Node::Item(&hir::Item {
1557 kind: hir::ItemKind::Fn(ref sig, ..),
1560 Node::ImplItem(&hir::ImplItem {
1562 kind: hir::ImplItemKind::Method(ref sig, _),
1565 Node::TraitItem(&hir::TraitItem {
1567 kind: hir::TraitItemKind::Method(ref sig, _),
1570 (self.tcx.sess.source_map().def_span(span), sig.decl.inputs.iter()
1571 .map(|arg| match arg.clone().kind {
1572 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
1574 vec![("_".to_owned(), "_".to_owned()); tys.len()]
1576 _ => ArgKind::empty()
1577 }).collect::<Vec<ArgKind>>())
1579 Node::Ctor(ref variant_data) => {
1580 let span = variant_data.ctor_hir_id()
1581 .map(|hir_id| self.tcx.hir().span(hir_id))
1582 .unwrap_or(DUMMY_SP);
1583 let span = self.tcx.sess.source_map().def_span(span);
1585 (span, vec![ArgKind::empty(); variant_data.fields().len()])
1587 _ => panic!("non-FnLike node found: {:?}", node),
1591 /// Reports an error when the number of arguments needed by a
1592 /// trait match doesn't match the number that the expression
1594 pub fn report_arg_count_mismatch(
1597 found_span: Option<Span>,
1598 expected_args: Vec<ArgKind>,
1599 found_args: Vec<ArgKind>,
1601 ) -> DiagnosticBuilder<'tcx> {
1602 let kind = if is_closure { "closure" } else { "function" };
1604 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
1605 let arg_length = arguments.len();
1606 let distinct = match &other[..] {
1607 &[ArgKind::Tuple(..)] => true,
1610 match (arg_length, arguments.get(0)) {
1611 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1612 format!("a single {}-tuple as argument", fields.len())
1614 _ => format!("{} {}argument{}",
1616 if distinct && arg_length > 1 { "distinct " } else { "" },
1617 pluralize!(arg_length))
1621 let expected_str = args_str(&expected_args, &found_args);
1622 let found_str = args_str(&found_args, &expected_args);
1624 let mut err = struct_span_err!(
1628 "{} is expected to take {}, but it takes {}",
1634 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
1636 if let Some(found_span) = found_span {
1637 err.span_label(found_span, format!("takes {}", found_str));
1640 // ^^^^^^^^-- def_span
1644 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1647 let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) {
1653 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1654 // found arguments is empty (assume the user just wants to ignore args in this case).
1655 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1656 if found_args.is_empty() && is_closure {
1657 let underscores = vec!["_"; expected_args.len()].join(", ");
1658 err.span_suggestion(
1661 "consider changing the closure to take and ignore the expected argument{}",
1662 if expected_args.len() < 2 {
1668 format!("|{}|", underscores),
1669 Applicability::MachineApplicable,
1673 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1674 if fields.len() == expected_args.len() {
1675 let sugg = fields.iter()
1676 .map(|(name, _)| name.to_owned())
1677 .collect::<Vec<String>>()
1679 err.span_suggestion(
1681 "change the closure to take multiple arguments instead of a single tuple",
1682 format!("|{}|", sugg),
1683 Applicability::MachineApplicable,
1687 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1688 if fields.len() == found_args.len() && is_closure {
1692 .map(|arg| match arg {
1693 ArgKind::Arg(name, _) => name.to_owned(),
1694 _ => "_".to_owned(),
1696 .collect::<Vec<String>>()
1698 // add type annotations if available
1699 if found_args.iter().any(|arg| match arg {
1700 ArgKind::Arg(_, ty) => ty != "_",
1705 .map(|(_, ty)| ty.to_owned())
1706 .collect::<Vec<String>>()
1712 err.span_suggestion(
1714 "change the closure to accept a tuple instead of individual arguments",
1716 Applicability::MachineApplicable,
1725 fn report_closure_arg_mismatch(
1728 found_span: Option<Span>,
1729 expected_ref: ty::PolyTraitRef<'tcx>,
1730 found: ty::PolyTraitRef<'tcx>,
1731 ) -> DiagnosticBuilder<'tcx> {
1732 fn build_fn_sig_string<'tcx>(tcx: TyCtxt<'tcx>, trait_ref: &ty::TraitRef<'tcx>) -> String {
1733 let inputs = trait_ref.substs.type_at(1);
1734 let sig = if let ty::Tuple(inputs) = inputs.kind {
1736 inputs.iter().map(|k| k.expect_ty()),
1737 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1739 hir::Unsafety::Normal,
1740 ::rustc_target::spec::abi::Abi::Rust
1744 ::std::iter::once(inputs),
1745 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1747 hir::Unsafety::Normal,
1748 ::rustc_target::spec::abi::Abi::Rust
1751 ty::Binder::bind(sig).to_string()
1754 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1755 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1756 "type mismatch in {} arguments",
1757 if argument_is_closure { "closure" } else { "function" });
1759 let found_str = format!(
1760 "expected signature of `{}`",
1761 build_fn_sig_string(self.tcx, found.skip_binder())
1763 err.span_label(span, found_str);
1765 let found_span = found_span.unwrap_or(span);
1766 let expected_str = format!(
1767 "found signature of `{}`",
1768 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1770 err.span_label(found_span, expected_str);
1776 impl<'tcx> TyCtxt<'tcx> {
1777 pub fn recursive_type_with_infinite_size_error(self,
1779 -> DiagnosticBuilder<'tcx>
1781 assert!(type_def_id.is_local());
1782 let span = self.hir().span_if_local(type_def_id).unwrap();
1783 let span = self.sess.source_map().def_span(span);
1784 let mut err = struct_span_err!(self.sess, span, E0072,
1785 "recursive type `{}` has infinite size",
1786 self.def_path_str(type_def_id));
1787 err.span_label(span, "recursive type has infinite size");
1788 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1789 at some point to make `{}` representable",
1790 self.def_path_str(type_def_id)));
1794 pub fn report_object_safety_error(
1797 trait_def_id: DefId,
1798 violations: Vec<ObjectSafetyViolation>,
1799 ) -> DiagnosticBuilder<'tcx> {
1800 let trait_str = self.def_path_str(trait_def_id);
1801 let span = self.sess.source_map().def_span(span);
1802 let mut err = struct_span_err!(
1803 self.sess, span, E0038,
1804 "the trait `{}` cannot be made into an object",
1806 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1808 let mut reported_violations = FxHashSet::default();
1809 for violation in violations {
1810 if reported_violations.insert(violation.clone()) {
1811 match violation.span() {
1812 Some(span) => err.span_label(span, violation.error_msg()),
1813 None => err.note(&violation.error_msg()),
1818 if self.sess.trait_methods_not_found.borrow().contains(&span) {
1819 // Avoid emitting error caused by non-existing method (#58734)
1827 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1828 fn maybe_report_ambiguity(
1830 obligation: &PredicateObligation<'tcx>,
1831 body_id: Option<hir::BodyId>,
1833 // Unable to successfully determine, probably means
1834 // insufficient type information, but could mean
1835 // ambiguous impls. The latter *ought* to be a
1836 // coherence violation, so we don't report it here.
1838 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1839 let span = obligation.cause.span;
1842 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1846 obligation.cause.code,
1849 // Ambiguity errors are often caused as fallout from earlier
1850 // errors. So just ignore them if this infcx is tainted.
1851 if self.is_tainted_by_errors() {
1856 ty::Predicate::Trait(ref data) => {
1857 let trait_ref = data.to_poly_trait_ref();
1858 let self_ty = trait_ref.self_ty();
1859 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1861 if predicate.references_error() {
1864 // Typically, this ambiguity should only happen if
1865 // there are unresolved type inference variables
1866 // (otherwise it would suggest a coherence
1867 // failure). But given #21974 that is not necessarily
1868 // the case -- we can have multiple where clauses that
1869 // are only distinguished by a region, which results
1870 // in an ambiguity even when all types are fully
1871 // known, since we don't dispatch based on region
1874 // This is kind of a hack: it frequently happens that some earlier
1875 // error prevents types from being fully inferred, and then we get
1876 // a bunch of uninteresting errors saying something like "<generic
1877 // #0> doesn't implement Sized". It may even be true that we
1878 // could just skip over all checks where the self-ty is an
1879 // inference variable, but I was afraid that there might be an
1880 // inference variable created, registered as an obligation, and
1881 // then never forced by writeback, and hence by skipping here we'd
1882 // be ignoring the fact that we don't KNOW the type works
1883 // out. Though even that would probably be harmless, given that
1884 // we're only talking about builtin traits, which are known to be
1885 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1886 // avoid inundating the user with unnecessary errors, but we now
1887 // check upstream for type errors and dont add the obligations to
1888 // begin with in those cases.
1890 self.tcx.lang_items().sized_trait()
1891 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1893 self.need_type_info_err(body_id, span, self_ty).emit();
1895 let mut err = struct_span_err!(
1899 "type annotations needed: cannot resolve `{}`",
1902 self.note_obligation_cause(&mut err, obligation);
1907 ty::Predicate::WellFormed(ty) => {
1908 // Same hacky approach as above to avoid deluging user
1909 // with error messages.
1910 if !ty.references_error() && !self.tcx.sess.has_errors() {
1911 self.need_type_info_err(body_id, span, ty).emit();
1915 ty::Predicate::Subtype(ref data) => {
1916 if data.references_error() || self.tcx.sess.has_errors() {
1917 // no need to overload user in such cases
1919 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1920 // both must be type variables, or the other would've been instantiated
1921 assert!(a.is_ty_var() && b.is_ty_var());
1922 self.need_type_info_err(body_id,
1923 obligation.cause.span,
1929 if !self.tcx.sess.has_errors() {
1930 let mut err = struct_span_err!(
1932 obligation.cause.span,
1934 "type annotations needed: cannot resolve `{}`",
1937 self.note_obligation_cause(&mut err, obligation);
1944 /// Returns `true` if the trait predicate may apply for *some* assignment
1945 /// to the type parameters.
1946 fn predicate_can_apply(
1948 param_env: ty::ParamEnv<'tcx>,
1949 pred: ty::PolyTraitRef<'tcx>,
1951 struct ParamToVarFolder<'a, 'tcx> {
1952 infcx: &'a InferCtxt<'a, 'tcx>,
1953 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
1956 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
1957 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx }
1959 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1960 if let ty::Param(ty::ParamTy {name, .. }) = ty.kind {
1961 let infcx = self.infcx;
1962 self.var_map.entry(ty).or_insert_with(||
1964 TypeVariableOrigin {
1965 kind: TypeVariableOriginKind::TypeParameterDefinition(name),
1971 ty.super_fold_with(self)
1977 let mut selcx = SelectionContext::new(self);
1979 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1981 var_map: Default::default()
1984 let cleaned_pred = super::project::normalize(
1987 ObligationCause::dummy(),
1991 let obligation = Obligation::new(
1992 ObligationCause::dummy(),
1994 cleaned_pred.to_predicate()
1997 self.predicate_may_hold(&obligation)
2001 fn note_obligation_cause(
2003 err: &mut DiagnosticBuilder<'_>,
2004 obligation: &PredicateObligation<'tcx>,
2006 // First, attempt to add note to this error with an async-await-specific
2007 // message, and fall back to regular note otherwise.
2008 if !self.note_obligation_cause_for_async_await(err, obligation) {
2009 self.note_obligation_cause_code(err, &obligation.predicate, &obligation.cause.code,
2014 /// Adds an async-await specific note to the diagnostic:
2016 /// ```ignore (diagnostic)
2017 /// note: future does not implement `std::marker::Send` because this value is used across an
2019 /// --> $DIR/issue-64130-non-send-future-diags.rs:15:5
2021 /// LL | let g = x.lock().unwrap();
2022 /// | - has type `std::sync::MutexGuard<'_, u32>`
2023 /// LL | baz().await;
2024 /// | ^^^^^^^^^^^ await occurs here, with `g` maybe used later
2026 /// | - `g` is later dropped here
2029 /// Returns `true` if an async-await specific note was added to the diagnostic.
2030 fn note_obligation_cause_for_async_await(
2032 err: &mut DiagnosticBuilder<'_>,
2033 obligation: &PredicateObligation<'tcx>,
2035 debug!("note_obligation_cause_for_async_await: obligation.predicate={:?} \
2036 obligation.cause.span={:?}", obligation.predicate, obligation.cause.span);
2037 let source_map = self.tcx.sess.source_map();
2039 // Look into the obligation predicate to determine the type in the generator which meant
2040 // that the predicate was not satisifed.
2041 let (trait_ref, target_ty) = match obligation.predicate {
2042 ty::Predicate::Trait(trait_predicate) =>
2043 (trait_predicate.skip_binder().trait_ref, trait_predicate.skip_binder().self_ty()),
2046 debug!("note_obligation_cause_for_async_await: target_ty={:?}", target_ty);
2048 // Attempt to detect an async-await error by looking at the obligation causes, looking
2049 // for only generators, generator witnesses, opaque types or `std::future::GenFuture` to
2052 // When a future does not implement a trait because of a captured type in one of the
2053 // generators somewhere in the call stack, then the result is a chain of obligations.
2054 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
2055 // future is passed as an argument to a function C which requires a `Send` type, then the
2056 // chain looks something like this:
2058 // - `BuiltinDerivedObligation` with a generator witness (B)
2059 // - `BuiltinDerivedObligation` with a generator (B)
2060 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
2061 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2062 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2063 // - `BuiltinDerivedObligation` with a generator witness (A)
2064 // - `BuiltinDerivedObligation` with a generator (A)
2065 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
2066 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2067 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2068 // - `BindingObligation` with `impl_send (Send requirement)
2070 // The first obligations in the chain can be used to get the details of the type that is
2071 // captured but the entire chain must be inspected to detect this case.
2072 let mut generator = None;
2073 let mut next_code = Some(&obligation.cause.code);
2074 while let Some(code) = next_code {
2075 debug!("note_obligation_cause_for_async_await: code={:?}", code);
2077 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) |
2078 ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
2079 debug!("note_obligation_cause_for_async_await: self_ty.kind={:?}",
2080 derived_obligation.parent_trait_ref.self_ty().kind);
2081 match derived_obligation.parent_trait_ref.self_ty().kind {
2082 ty::Adt(ty::AdtDef { did, .. }, ..) if
2083 self.tcx.is_diagnostic_item(sym::gen_future, *did) => {},
2084 ty::Generator(did, ..) => generator = generator.or(Some(did)),
2085 ty::GeneratorWitness(_) | ty::Opaque(..) => {},
2089 next_code = Some(derived_obligation.parent_code.as_ref());
2091 ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::BindingObligation(..)
2092 if generator.is_some() => break,
2097 let generator_did = generator.expect("can only reach this if there was a generator");
2099 // Only continue to add a note if the generator is from an `async` function.
2100 let parent_node = self.tcx.parent(generator_did)
2101 .and_then(|parent_did| self.tcx.hir().get_if_local(parent_did));
2102 debug!("note_obligation_cause_for_async_await: parent_node={:?}", parent_node);
2103 if let Some(hir::Node::Item(hir::Item {
2104 kind: hir::ItemKind::Fn(sig, _, _),
2107 debug!("note_obligation_cause_for_async_await: header={:?}", sig.header);
2108 if sig.header.asyncness != hir::IsAsync::Async {
2113 let span = self.tcx.def_span(generator_did);
2114 let tables = self.tcx.typeck_tables_of(generator_did);
2115 debug!("note_obligation_cause_for_async_await: generator_did={:?} span={:?} ",
2116 generator_did, span);
2118 // Look for a type inside the generator interior that matches the target type to get
2120 let target_span = tables.generator_interior_types.iter()
2121 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| ty::TyS::same_type(*ty, target_ty))
2122 .map(|ty::GeneratorInteriorTypeCause { span, scope_span, .. }|
2123 (span, source_map.span_to_snippet(*span), scope_span));
2124 if let Some((target_span, Ok(snippet), scope_span)) = target_span {
2125 // Look at the last interior type to get a span for the `.await`.
2126 let await_span = tables.generator_interior_types.iter().map(|i| i.span).last().unwrap();
2127 let mut span = MultiSpan::from_span(await_span);
2128 span.push_span_label(
2129 await_span, format!("await occurs here, with `{}` maybe used later", snippet));
2131 span.push_span_label(*target_span, format!("has type `{}`", target_ty));
2133 // If available, use the scope span to annotate the drop location.
2134 if let Some(scope_span) = scope_span {
2135 span.push_span_label(
2136 source_map.end_point(*scope_span),
2137 format!("`{}` is later dropped here", snippet),
2141 err.span_note(span, &format!(
2142 "future does not implement `{}` as this value is used across an await",
2146 // Add a note for the item obligation that remains - normally a note pointing to the
2147 // bound that introduced the obligation (e.g. `T: Send`).
2148 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2149 self.note_obligation_cause_code(
2151 &obligation.predicate,
2162 fn note_obligation_cause_code<T>(&self,
2163 err: &mut DiagnosticBuilder<'_>,
2165 cause_code: &ObligationCauseCode<'tcx>,
2166 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
2167 where T: fmt::Display
2171 ObligationCauseCode::ExprAssignable |
2172 ObligationCauseCode::MatchExpressionArm { .. } |
2173 ObligationCauseCode::MatchExpressionArmPattern { .. } |
2174 ObligationCauseCode::IfExpression { .. } |
2175 ObligationCauseCode::IfExpressionWithNoElse |
2176 ObligationCauseCode::MainFunctionType |
2177 ObligationCauseCode::StartFunctionType |
2178 ObligationCauseCode::IntrinsicType |
2179 ObligationCauseCode::MethodReceiver |
2180 ObligationCauseCode::ReturnNoExpression |
2181 ObligationCauseCode::MiscObligation => {}
2182 ObligationCauseCode::SliceOrArrayElem => {
2183 err.note("slice and array elements must have `Sized` type");
2185 ObligationCauseCode::TupleElem => {
2186 err.note("only the last element of a tuple may have a dynamically sized type");
2188 ObligationCauseCode::ProjectionWf(data) => {
2190 "required so that the projection `{}` is well-formed",
2194 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2196 "required so that reference `{}` does not outlive its referent",
2200 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2202 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2207 ObligationCauseCode::ItemObligation(item_def_id) => {
2208 let item_name = tcx.def_path_str(item_def_id);
2209 let msg = format!("required by `{}`", item_name);
2211 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
2212 let sp = tcx.sess.source_map().def_span(sp);
2213 err.span_label(sp, &msg);
2218 ObligationCauseCode::BindingObligation(item_def_id, span) => {
2219 let item_name = tcx.def_path_str(item_def_id);
2220 let msg = format!("required by this bound in `{}`", item_name);
2221 if let Some(ident) = tcx.opt_item_name(item_def_id) {
2222 err.span_label(ident.span, "");
2224 if span != DUMMY_SP {
2225 err.span_label(span, &msg);
2230 ObligationCauseCode::ObjectCastObligation(object_ty) => {
2231 err.note(&format!("required for the cast to the object type `{}`",
2232 self.ty_to_string(object_ty)));
2234 ObligationCauseCode::Coercion { source: _, target } => {
2235 err.note(&format!("required by cast to type `{}`",
2236 self.ty_to_string(target)));
2238 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
2239 err.note("the `Copy` trait is required because the \
2240 repeated element will be copied");
2241 if suggest_const_in_array_repeat_expressions {
2242 err.note("this array initializer can be evaluated at compile-time, for more \
2243 information, see issue \
2244 https://github.com/rust-lang/rust/issues/49147");
2245 if tcx.sess.opts.unstable_features.is_nightly_build() {
2246 err.help("add `#![feature(const_in_array_repeat_expressions)]` to the \
2247 crate attributes to enable");
2251 ObligationCauseCode::VariableType(_) => {
2252 err.note("all local variables must have a statically known size");
2253 if !self.tcx.features().unsized_locals {
2254 err.help("unsized locals are gated as an unstable feature");
2257 ObligationCauseCode::SizedArgumentType => {
2258 err.note("all function arguments must have a statically known size");
2259 if !self.tcx.features().unsized_locals {
2260 err.help("unsized locals are gated as an unstable feature");
2263 ObligationCauseCode::SizedReturnType => {
2264 err.note("the return type of a function must have a \
2265 statically known size");
2267 ObligationCauseCode::SizedYieldType => {
2268 err.note("the yield type of a generator must have a \
2269 statically known size");
2271 ObligationCauseCode::AssignmentLhsSized => {
2272 err.note("the left-hand-side of an assignment must have a statically known size");
2274 ObligationCauseCode::TupleInitializerSized => {
2275 err.note("tuples must have a statically known size to be initialized");
2277 ObligationCauseCode::StructInitializerSized => {
2278 err.note("structs must have a statically known size to be initialized");
2280 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => {
2282 AdtKind::Struct => {
2284 err.note("the last field of a packed struct may only have a \
2285 dynamically sized type if it does not need drop to be run");
2287 err.note("only the last field of a struct may have a dynamically \
2292 err.note("no field of a union may have a dynamically sized type");
2295 err.note("no field of an enum variant may have a dynamically sized type");
2299 ObligationCauseCode::ConstSized => {
2300 err.note("constant expressions must have a statically known size");
2302 ObligationCauseCode::ConstPatternStructural => {
2303 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2305 ObligationCauseCode::SharedStatic => {
2306 err.note("shared static variables must have a type that implements `Sync`");
2308 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2309 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2310 let ty = parent_trait_ref.skip_binder().self_ty();
2311 err.note(&format!("required because it appears within the type `{}`", ty));
2312 obligated_types.push(ty);
2314 let parent_predicate = parent_trait_ref.to_predicate();
2315 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2316 self.note_obligation_cause_code(err,
2322 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2323 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2325 &format!("required because of the requirements on the impl of `{}` for `{}`",
2327 parent_trait_ref.skip_binder().self_ty()));
2328 let parent_predicate = parent_trait_ref.to_predicate();
2329 self.note_obligation_cause_code(err,
2334 ObligationCauseCode::CompareImplMethodObligation { .. } => {
2336 &format!("the requirement `{}` appears on the impl method \
2337 but not on the corresponding trait method",
2340 ObligationCauseCode::ReturnType |
2341 ObligationCauseCode::ReturnValue(_) |
2342 ObligationCauseCode::BlockTailExpression(_) => (),
2343 ObligationCauseCode::TrivialBound => {
2344 err.help("see issue #48214");
2345 if tcx.sess.opts.unstable_features.is_nightly_build() {
2346 err.help("add `#![feature(trivial_bounds)]` to the \
2347 crate attributes to enable",
2351 ObligationCauseCode::AssocTypeBound(ref data) => {
2352 err.span_label(data.original, "associated type defined here");
2353 if let Some(sp) = data.impl_span {
2354 err.span_label(sp, "in this `impl` item");
2356 for sp in &data.bounds {
2357 err.span_label(*sp, "restricted in this bound");
2363 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2364 let current_limit = self.tcx.sess.recursion_limit.get();
2365 let suggested_limit = current_limit * 2;
2366 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
2370 fn is_recursive_obligation(&self,
2371 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2372 cause_code: &ObligationCauseCode<'tcx>) -> bool {
2373 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2374 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
2376 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
2384 /// Summarizes information
2387 /// An argument of non-tuple type. Parameters are (name, ty)
2388 Arg(String, String),
2390 /// An argument of tuple type. For a "found" argument, the span is
2391 /// the locationo in the source of the pattern. For a "expected"
2392 /// argument, it will be None. The vector is a list of (name, ty)
2393 /// strings for the components of the tuple.
2394 Tuple(Option<Span>, Vec<(String, String)>),
2398 fn empty() -> ArgKind {
2399 ArgKind::Arg("_".to_owned(), "_".to_owned())
2402 /// Creates an `ArgKind` from the expected type of an
2403 /// argument. It has no name (`_`) and an optional source span.
2404 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2406 ty::Tuple(ref tys) => ArgKind::Tuple(
2409 .map(|ty| ("_".to_owned(), ty.to_string()))
2410 .collect::<Vec<_>>()
2412 _ => ArgKind::Arg("_".to_owned(), t.to_string()),