1 pub mod on_unimplemented;
5 ConstEvalFailure, EvaluationResult, FulfillmentError, FulfillmentErrorCode,
6 MismatchedProjectionTypes, Obligation, ObligationCause, ObligationCauseCode,
7 OnUnimplementedDirective, OnUnimplementedNote, OutputTypeParameterMismatch, Overflow,
8 PredicateObligation, SelectionContext, SelectionError, TraitNotObjectSafe,
11 use crate::infer::error_reporting::{TyCategory, TypeAnnotationNeeded as ErrorCode};
12 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
13 use crate::infer::{self, InferCtxt, TyCtxtInferExt};
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorReported};
17 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
18 use rustc_hir::intravisit::Visitor;
20 use rustc_middle::mir::interpret::ErrorHandled;
21 use rustc_middle::ty::error::ExpectedFound;
22 use rustc_middle::ty::fold::TypeFolder;
23 use rustc_middle::ty::subst::GenericArgKind;
24 use rustc_middle::ty::{
25 self, fast_reject, AdtKind, SubtypePredicate, ToPolyTraitRef, ToPredicate, Ty, TyCtxt,
26 TypeFoldable, WithConstness,
28 use rustc_session::DiagnosticMessageId;
29 use rustc_span::symbol::{kw, sym};
30 use rustc_span::{ExpnKind, MultiSpan, Span, DUMMY_SP};
33 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
34 use crate::traits::query::normalize::AtExt as _;
35 use on_unimplemented::InferCtxtExt as _;
36 use suggestions::InferCtxtExt as _;
38 pub use rustc_infer::traits::error_reporting::*;
40 pub trait InferCtxtExt<'tcx> {
41 fn report_fulfillment_errors(
43 errors: &[FulfillmentError<'tcx>],
44 body_id: Option<hir::BodyId>,
45 fallback_has_occurred: bool,
48 fn report_overflow_error<T>(
50 obligation: &Obligation<'tcx, T>,
51 suggest_increasing_limit: bool,
54 T: fmt::Display + TypeFoldable<'tcx>;
56 fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !;
58 fn report_selection_error(
60 obligation: &PredicateObligation<'tcx>,
61 error: &SelectionError<'tcx>,
62 fallback_has_occurred: bool,
66 /// Given some node representing a fn-like thing in the HIR map,
67 /// returns a span and `ArgKind` information that describes the
68 /// arguments it expects. This can be supplied to
69 /// `report_arg_count_mismatch`.
70 fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)>;
72 /// Reports an error when the number of arguments needed by a
73 /// trait match doesn't match the number that the expression
75 fn report_arg_count_mismatch(
78 found_span: Option<Span>,
79 expected_args: Vec<ArgKind>,
80 found_args: Vec<ArgKind>,
82 ) -> DiagnosticBuilder<'tcx>;
85 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
86 fn report_fulfillment_errors(
88 errors: &[FulfillmentError<'tcx>],
89 body_id: Option<hir::BodyId>,
90 fallback_has_occurred: bool,
93 struct ErrorDescriptor<'tcx> {
94 predicate: ty::Predicate<'tcx>,
95 index: Option<usize>, // None if this is an old error
98 let mut error_map: FxHashMap<_, Vec<_>> = self
99 .reported_trait_errors
102 .map(|(&span, predicates)| {
107 .map(|&predicate| ErrorDescriptor { predicate, index: None })
113 for (index, error) in errors.iter().enumerate() {
114 // We want to ignore desugarings here: spans are equivalent even
115 // if one is the result of a desugaring and the other is not.
116 let mut span = error.obligation.cause.span;
117 let expn_data = span.ctxt().outer_expn_data();
118 if let ExpnKind::Desugaring(_) = expn_data.kind {
119 span = expn_data.call_site;
122 error_map.entry(span).or_default().push(ErrorDescriptor {
123 predicate: error.obligation.predicate,
127 self.reported_trait_errors
131 .push(error.obligation.predicate);
134 // We do this in 2 passes because we want to display errors in order, though
135 // maybe it *is* better to sort errors by span or something.
136 let mut is_suppressed = vec![false; errors.len()];
137 for (_, error_set) in error_map.iter() {
138 // We want to suppress "duplicate" errors with the same span.
139 for error in error_set {
140 if let Some(index) = error.index {
141 // Suppress errors that are either:
142 // 1) strictly implied by another error.
143 // 2) implied by an error with a smaller index.
144 for error2 in error_set {
145 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
146 // Avoid errors being suppressed by already-suppressed
147 // errors, to prevent all errors from being suppressed
152 if self.error_implies(error2.predicate, error.predicate)
153 && !(error2.index >= error.index
154 && self.error_implies(error.predicate, error2.predicate))
156 info!("skipping {:?} (implied by {:?})", error, error2);
157 is_suppressed[index] = true;
165 for (error, suppressed) in errors.iter().zip(is_suppressed) {
167 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
172 /// Reports that an overflow has occurred and halts compilation. We
173 /// halt compilation unconditionally because it is important that
174 /// overflows never be masked -- they basically represent computations
175 /// whose result could not be truly determined and thus we can't say
176 /// if the program type checks or not -- and they are unusual
177 /// occurrences in any case.
178 fn report_overflow_error<T>(
180 obligation: &Obligation<'tcx, T>,
181 suggest_increasing_limit: bool,
184 T: fmt::Display + TypeFoldable<'tcx>,
186 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
187 let mut err = struct_span_err!(
189 obligation.cause.span,
191 "overflow evaluating the requirement `{}`",
195 if suggest_increasing_limit {
196 self.suggest_new_overflow_limit(&mut err);
199 self.note_obligation_cause_code(
201 &obligation.predicate,
202 &obligation.cause.code,
207 self.tcx.sess.abort_if_errors();
211 /// Reports that a cycle was detected which led to overflow and halts
212 /// compilation. This is equivalent to `report_overflow_error` except
213 /// that we can give a more helpful error message (and, in particular,
214 /// we do not suggest increasing the overflow limit, which is not
216 fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
217 let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
218 assert!(!cycle.is_empty());
220 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
222 self.report_overflow_error(&cycle[0], false);
225 fn report_selection_error(
227 obligation: &PredicateObligation<'tcx>,
228 error: &SelectionError<'tcx>,
229 fallback_has_occurred: bool,
233 let span = obligation.cause.span;
235 let mut err = match *error {
236 SelectionError::Unimplemented => {
237 if let ObligationCauseCode::CompareImplMethodObligation {
242 | ObligationCauseCode::CompareImplTypeObligation {
246 } = obligation.cause.code
248 self.report_extra_impl_obligation(
253 &format!("`{}`", obligation.predicate),
259 match obligation.predicate.skip_binders() {
260 ty::PredicateAtom::Trait(trait_predicate, _) => {
261 let trait_predicate = ty::Binder::bind(trait_predicate);
262 let trait_predicate = self.resolve_vars_if_possible(&trait_predicate);
264 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
267 let trait_ref = trait_predicate.to_poly_trait_ref();
268 let (post_message, pre_message, type_def) = self
269 .get_parent_trait_ref(&obligation.cause.code)
272 format!(" in `{}`", t),
273 format!("within `{}`, ", t),
274 s.map(|s| (format!("within this `{}`", t), s)),
277 .unwrap_or_default();
279 let OnUnimplementedNote { message, label, note, enclosing_scope } =
280 self.on_unimplemented_note(trait_ref, obligation);
281 let have_alt_message = message.is_some() || label.is_some();
286 .span_to_snippet(span)
289 let is_from = self.tcx.get_diagnostic_item(sym::from_trait)
290 == Some(trait_ref.def_id());
292 { Some(trait_ref.def_id()) == self.tcx.lang_items().unsize_trait() };
293 let (message, note) = if is_try && is_from {
296 "`?` couldn't convert the error to `{}`",
297 trait_ref.skip_binder().self_ty(),
300 "the question mark operation (`?`) implicitly performs a \
301 conversion on the error value using the `From` trait"
309 let mut err = struct_span_err!(
314 message.unwrap_or_else(|| format!(
315 "the trait bound `{}` is not satisfied{}",
316 trait_ref.without_const().to_predicate(tcx),
321 if is_try && is_from {
322 let none_error = self
324 .get_diagnostic_item(sym::none_error)
325 .map(|def_id| tcx.type_of(def_id));
326 let should_convert_option_to_result =
327 Some(trait_ref.skip_binder().substs.type_at(1)) == none_error;
328 let should_convert_result_to_option =
329 Some(trait_ref.self_ty().skip_binder()) == none_error;
330 if should_convert_option_to_result {
331 err.span_suggestion_verbose(
333 "consider converting the `Option<T>` into a `Result<T, _>` \
334 using `Option::ok_or` or `Option::ok_or_else`",
335 ".ok_or_else(|| /* error value */)".to_string(),
336 Applicability::HasPlaceholders,
338 } else if should_convert_result_to_option {
339 err.span_suggestion_verbose(
341 "consider converting the `Result<T, _>` into an `Option<T>` \
344 Applicability::MachineApplicable,
347 if let Some(ret_span) = self.return_type_span(obligation) {
351 "expected `{}` because of this",
352 trait_ref.skip_binder().self_ty()
359 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
360 "consider using `()`, or a `Result`".to_owned()
363 "{}the trait `{}` is not implemented for `{}`",
365 trait_ref.print_only_trait_path(),
366 trait_ref.skip_binder().self_ty(),
370 if self.suggest_add_reference_to_arg(
377 self.note_obligation_cause(&mut err, obligation);
381 if let Some(ref s) = label {
382 // If it has a custom `#[rustc_on_unimplemented]`
383 // error message, let's display it as the label!
384 err.span_label(span, s.as_str());
385 if !matches!(trait_ref.skip_binder().self_ty().kind, ty::Param(_)) {
386 // When the self type is a type param We don't need to "the trait
387 // `std::marker::Sized` is not implemented for `T`" as we will point
388 // at the type param with a label to suggest constraining it.
389 err.help(&explanation);
392 err.span_label(span, explanation);
394 if let Some((msg, span)) = type_def {
395 err.span_label(span, &msg);
397 if let Some(ref s) = note {
398 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
399 err.note(s.as_str());
401 if let Some(ref s) = enclosing_scope {
402 let enclosing_scope_span = tcx.def_span(
404 .opt_local_def_id(obligation.cause.body_id)
406 tcx.hir().body_owner_def_id(hir::BodyId {
407 hir_id: obligation.cause.body_id,
413 err.span_label(enclosing_scope_span, s.as_str());
416 self.suggest_dereferences(&obligation, &mut err, &trait_ref, points_at_arg);
417 self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
418 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
419 self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
420 self.note_version_mismatch(&mut err, &trait_ref);
422 if Some(trait_ref.def_id()) == tcx.lang_items().try_trait() {
423 self.suggest_await_before_try(&mut err, &obligation, &trait_ref, span);
426 if self.suggest_impl_trait(&mut err, span, &obligation, &trait_ref) {
432 // If the obligation failed due to a missing implementation of the
433 // `Unsize` trait, give a pointer to why that might be the case
435 "all implementations of `Unsize` are provided \
436 automatically by the compiler, see \
437 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
438 for more information",
443 self.tcx.lang_items().fn_trait(),
444 self.tcx.lang_items().fn_mut_trait(),
445 self.tcx.lang_items().fn_once_trait(),
447 .contains(&Some(trait_ref.def_id()));
448 let is_target_feature_fn =
449 if let ty::FnDef(def_id, _) = trait_ref.skip_binder().self_ty().kind {
450 !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
454 if is_fn_trait && is_target_feature_fn {
456 "`#[target_feature]` functions do not implement the `Fn` traits",
460 // Try to report a help message
461 if !trait_ref.has_infer_types_or_consts()
462 && self.predicate_can_apply(obligation.param_env, trait_ref)
464 // If a where-clause may be useful, remind the
465 // user that they can add it.
467 // don't display an on-unimplemented note, as
468 // these notes will often be of the form
469 // "the type `T` can't be frobnicated"
470 // which is somewhat confusing.
471 self.suggest_restricting_param_bound(
474 obligation.cause.body_id,
477 if !have_alt_message {
478 // Can't show anything else useful, try to find similar impls.
479 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
480 self.report_similar_impl_candidates(impl_candidates, &mut err);
482 // Changing mutability doesn't make a difference to whether we have
483 // an `Unsize` impl (Fixes ICE in #71036)
485 self.suggest_change_mut(
494 // If this error is due to `!: Trait` not implemented but `(): Trait` is
495 // implemented, and fallback has occurred, then it could be due to a
496 // variable that used to fallback to `()` now falling back to `!`. Issue a
497 // note informing about the change in behaviour.
498 if trait_predicate.skip_binder().self_ty().is_never()
499 && fallback_has_occurred
501 let predicate = trait_predicate.map_bound(|mut trait_pred| {
502 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
504 &trait_pred.trait_ref.substs[1..],
508 let unit_obligation =
509 obligation.with(predicate.without_const().to_predicate(tcx));
510 if self.predicate_may_hold(&unit_obligation) {
512 "the trait is implemented for `()`. \
513 Possibly this error has been caused by changes to \
514 Rust's type-inference algorithm (see issue #48950 \
515 <https://github.com/rust-lang/rust/issues/48950> \
516 for more information). Consider whether you meant to use \
517 the type `()` here instead.",
525 ty::PredicateAtom::Subtype(predicate) => {
526 // Errors for Subtype predicates show up as
527 // `FulfillmentErrorCode::CodeSubtypeError`,
528 // not selection error.
529 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
532 ty::PredicateAtom::RegionOutlives(predicate) => {
533 let predicate = ty::Binder::bind(predicate);
534 let predicate = self.resolve_vars_if_possible(&predicate);
536 .region_outlives_predicate(&obligation.cause, predicate)
543 "the requirement `{}` is not satisfied (`{}`)",
549 ty::PredicateAtom::Projection(..) | ty::PredicateAtom::TypeOutlives(..) => {
550 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
555 "the requirement `{}` is not satisfied",
560 ty::PredicateAtom::ObjectSafe(trait_def_id) => {
561 let violations = self.tcx.object_safety_violations(trait_def_id);
562 report_object_safety_error(self.tcx, span, trait_def_id, violations)
565 ty::PredicateAtom::ClosureKind(closure_def_id, closure_substs, kind) => {
566 let found_kind = self.closure_kind(closure_substs).unwrap();
568 self.tcx.sess.source_map().guess_head_span(
569 self.tcx.hir().span_if_local(closure_def_id).unwrap(),
571 let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id.expect_local());
572 let mut err = struct_span_err!(
576 "expected a closure that implements the `{}` trait, \
577 but this closure only implements `{}`",
584 format!("this closure implements `{}`, not `{}`", found_kind, kind),
587 obligation.cause.span,
588 format!("the requirement to implement `{}` derives from here", kind),
591 // Additional context information explaining why the closure only implements
592 // a particular trait.
593 if let Some(typeck_results) = self.in_progress_typeck_results {
594 let typeck_results = typeck_results.borrow();
595 match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
596 (ty::ClosureKind::FnOnce, Some((span, name))) => {
600 "closure is `FnOnce` because it moves the \
601 variable `{}` out of its environment",
606 (ty::ClosureKind::FnMut, Some((span, name))) => {
610 "closure is `FnMut` because it mutates the \
624 ty::PredicateAtom::WellFormed(ty) => {
625 if !self.tcx.sess.opts.debugging_opts.chalk {
626 // WF predicates cannot themselves make
627 // errors. They can only block due to
628 // ambiguity; otherwise, they always
629 // degenerate into other obligations
631 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
633 // FIXME: we'll need a better message which takes into account
634 // which bounds actually failed to hold.
635 self.tcx.sess.struct_span_err(
637 &format!("the type `{}` is not well-formed (chalk)", ty),
642 ty::PredicateAtom::ConstEvaluatable(..) => {
643 // Errors for `ConstEvaluatable` predicates show up as
644 // `SelectionError::ConstEvalFailure`,
645 // not `Unimplemented`.
648 "const-evaluatable requirement gave wrong error: `{:?}`",
653 ty::PredicateAtom::ConstEquate(..) => {
654 // Errors for `ConstEquate` predicates show up as
655 // `SelectionError::ConstEvalFailure`,
656 // not `Unimplemented`.
659 "const-equate requirement gave wrong error: `{:?}`",
666 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
667 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
668 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
670 if expected_trait_ref.self_ty().references_error() {
674 let found_trait_ty = match found_trait_ref.self_ty().no_bound_vars() {
679 let found_did = match found_trait_ty.kind {
680 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
681 ty::Adt(def, _) => Some(def.did),
685 let found_span = found_did
686 .and_then(|did| self.tcx.hir().span_if_local(did))
687 .map(|sp| self.tcx.sess.source_map().guess_head_span(sp)); // the sp could be an fn def
689 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
690 // We check closures twice, with obligations flowing in different directions,
691 // but we want to complain about them only once.
695 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
697 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
698 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
699 _ => vec![ArgKind::empty()],
702 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
703 let expected = match expected_ty.kind {
704 ty::Tuple(ref tys) => tys
706 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span)))
708 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
711 if found.len() == expected.len() {
712 self.report_closure_arg_mismatch(
719 let (closure_span, found) = found_did
721 let node = self.tcx.hir().get_if_local(did)?;
722 let (found_span, found) = self.get_fn_like_arguments(node)?;
723 Some((Some(found_span), found))
725 .unwrap_or((found_span, found));
727 self.report_arg_count_mismatch(
732 found_trait_ty.is_closure(),
737 TraitNotObjectSafe(did) => {
738 let violations = self.tcx.object_safety_violations(did);
739 report_object_safety_error(self.tcx, span, did, violations)
742 ConstEvalFailure(ErrorHandled::TooGeneric) => {
743 // In this instance, we have a const expression containing an unevaluated
744 // generic parameter. We have no idea whether this expression is valid or
745 // not (e.g. it might result in an error), but we don't want to just assume
746 // that it's okay, because that might result in post-monomorphisation time
747 // errors. The onus is really on the caller to provide values that it can
748 // prove are well-formed.
752 .struct_span_err(span, "constant expression depends on a generic parameter");
753 // FIXME(const_generics): we should suggest to the user how they can resolve this
754 // issue. However, this is currently not actually possible
755 // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
756 err.note("this may fail depending on what value the parameter takes");
760 // Already reported in the query.
761 ConstEvalFailure(ErrorHandled::Reported(ErrorReported)) => {
762 // FIXME(eddyb) remove this once `ErrorReported` becomes a proof token.
763 self.tcx.sess.delay_span_bug(span, "`ErrorReported` without an error");
767 // Already reported in the query, but only as a lint.
768 // This shouldn't actually happen for constants used in types, modulo
769 // bugs. The `delay_span_bug` here ensures it won't be ignored.
770 ConstEvalFailure(ErrorHandled::Linted) => {
771 self.tcx.sess.delay_span_bug(span, "constant in type had error reported as lint");
776 bug!("overflow should be handled before the `report_selection_error` path");
780 self.note_obligation_cause(&mut err, obligation);
781 self.point_at_returns_when_relevant(&mut err, &obligation);
786 /// Given some node representing a fn-like thing in the HIR map,
787 /// returns a span and `ArgKind` information that describes the
788 /// arguments it expects. This can be supplied to
789 /// `report_arg_count_mismatch`.
790 fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)> {
791 let sm = self.tcx.sess.source_map();
792 let hir = self.tcx.hir();
794 Node::Expr(&hir::Expr {
795 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
798 sm.guess_head_span(span),
803 if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
810 sm.span_to_snippet(pat.span)
812 .map(|snippet| (snippet, "_".to_owned()))
814 .collect::<Option<Vec<_>>>()?,
817 let name = sm.span_to_snippet(arg.pat.span).ok()?;
818 Some(ArgKind::Arg(name, "_".to_owned()))
821 .collect::<Option<Vec<ArgKind>>>()?,
823 Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
824 | Node::ImplItem(&hir::ImplItem {
826 kind: hir::ImplItemKind::Fn(ref sig, _),
829 | Node::TraitItem(&hir::TraitItem {
831 kind: hir::TraitItemKind::Fn(ref sig, _),
834 sm.guess_head_span(span),
838 .map(|arg| match arg.clone().kind {
839 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
841 vec![("_".to_owned(), "_".to_owned()); tys.len()],
843 _ => ArgKind::empty(),
845 .collect::<Vec<ArgKind>>(),
847 Node::Ctor(ref variant_data) => {
848 let span = variant_data.ctor_hir_id().map(|id| hir.span(id)).unwrap_or(DUMMY_SP);
849 let span = sm.guess_head_span(span);
850 (span, vec![ArgKind::empty(); variant_data.fields().len()])
852 _ => panic!("non-FnLike node found: {:?}", node),
856 /// Reports an error when the number of arguments needed by a
857 /// trait match doesn't match the number that the expression
859 fn report_arg_count_mismatch(
862 found_span: Option<Span>,
863 expected_args: Vec<ArgKind>,
864 found_args: Vec<ArgKind>,
866 ) -> DiagnosticBuilder<'tcx> {
867 let kind = if is_closure { "closure" } else { "function" };
869 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
870 let arg_length = arguments.len();
871 let distinct = match &other[..] {
872 &[ArgKind::Tuple(..)] => true,
875 match (arg_length, arguments.get(0)) {
876 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
877 format!("a single {}-tuple as argument", fields.len())
882 if distinct && arg_length > 1 { "distinct " } else { "" },
883 pluralize!(arg_length)
888 let expected_str = args_str(&expected_args, &found_args);
889 let found_str = args_str(&found_args, &expected_args);
891 let mut err = struct_span_err!(
895 "{} is expected to take {}, but it takes {}",
901 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
903 if let Some(found_span) = found_span {
904 err.span_label(found_span, format!("takes {}", found_str));
907 // ^^^^^^^^-- def_span
911 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
915 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
917 // Suggest to take and ignore the arguments with expected_args_length `_`s if
918 // found arguments is empty (assume the user just wants to ignore args in this case).
919 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
920 if found_args.is_empty() && is_closure {
921 let underscores = vec!["_"; expected_args.len()].join(", ");
922 err.span_suggestion_verbose(
925 "consider changing the closure to take and ignore the expected argument{}",
926 pluralize!(expected_args.len())
928 format!("|{}|", underscores),
929 Applicability::MachineApplicable,
933 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
934 if fields.len() == expected_args.len() {
937 .map(|(name, _)| name.to_owned())
938 .collect::<Vec<String>>()
940 err.span_suggestion_verbose(
942 "change the closure to take multiple arguments instead of a single tuple",
943 format!("|{}|", sugg),
944 Applicability::MachineApplicable,
948 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
949 if fields.len() == found_args.len() && is_closure {
954 .map(|arg| match arg {
955 ArgKind::Arg(name, _) => name.to_owned(),
958 .collect::<Vec<String>>()
960 // add type annotations if available
961 if found_args.iter().any(|arg| match arg {
962 ArgKind::Arg(_, ty) => ty != "_",
969 .map(|(_, ty)| ty.to_owned())
970 .collect::<Vec<String>>()
977 err.span_suggestion_verbose(
979 "change the closure to accept a tuple instead of individual arguments",
981 Applicability::MachineApplicable,
991 trait InferCtxtPrivExt<'tcx> {
992 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
993 // `error` occurring implies that `cond` occurs.
994 fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool;
996 fn report_fulfillment_error(
998 error: &FulfillmentError<'tcx>,
999 body_id: Option<hir::BodyId>,
1000 fallback_has_occurred: bool,
1003 fn report_projection_error(
1005 obligation: &PredicateObligation<'tcx>,
1006 error: &MismatchedProjectionTypes<'tcx>,
1009 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool;
1011 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>;
1013 fn find_similar_impl_candidates(
1015 trait_ref: ty::PolyTraitRef<'tcx>,
1016 ) -> Vec<ty::TraitRef<'tcx>>;
1018 fn report_similar_impl_candidates(
1020 impl_candidates: Vec<ty::TraitRef<'tcx>>,
1021 err: &mut DiagnosticBuilder<'_>,
1024 /// Gets the parent trait chain start
1025 fn get_parent_trait_ref(
1027 code: &ObligationCauseCode<'tcx>,
1028 ) -> Option<(String, Option<Span>)>;
1030 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1031 /// with the same path as `trait_ref`, a help message about
1032 /// a probable version mismatch is added to `err`
1033 fn note_version_mismatch(
1035 err: &mut DiagnosticBuilder<'_>,
1036 trait_ref: &ty::PolyTraitRef<'tcx>,
1039 /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
1042 /// For this to work, `new_self_ty` must have no escaping bound variables.
1043 fn mk_trait_obligation_with_new_self_ty(
1045 param_env: ty::ParamEnv<'tcx>,
1046 trait_ref: &ty::PolyTraitRef<'tcx>,
1047 new_self_ty: Ty<'tcx>,
1048 ) -> PredicateObligation<'tcx>;
1050 fn maybe_report_ambiguity(
1052 obligation: &PredicateObligation<'tcx>,
1053 body_id: Option<hir::BodyId>,
1056 fn predicate_can_apply(
1058 param_env: ty::ParamEnv<'tcx>,
1059 pred: ty::PolyTraitRef<'tcx>,
1062 fn note_obligation_cause(
1064 err: &mut DiagnosticBuilder<'tcx>,
1065 obligation: &PredicateObligation<'tcx>,
1068 fn suggest_unsized_bound_if_applicable(
1070 err: &mut DiagnosticBuilder<'tcx>,
1071 obligation: &PredicateObligation<'tcx>,
1074 fn is_recursive_obligation(
1076 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1077 cause_code: &ObligationCauseCode<'tcx>,
1081 impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> {
1082 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1083 // `error` occurring implies that `cond` occurs.
1084 fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool {
1089 // FIXME: It should be possible to deal with `ForAll` in a cleaner way.
1090 let (cond, error) = match (cond.skip_binders(), error.skip_binders()) {
1091 (ty::PredicateAtom::Trait(..), ty::PredicateAtom::Trait(error, _)) => {
1092 (cond, ty::Binder::bind(error))
1095 // FIXME: make this work in other cases too.
1100 for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) {
1101 if let ty::PredicateAtom::Trait(implication, _) = obligation.predicate.skip_binders() {
1102 let error = error.to_poly_trait_ref();
1103 let implication = ty::Binder::bind(implication.trait_ref);
1104 // FIXME: I'm just not taking associated types at all here.
1105 // Eventually I'll need to implement param-env-aware
1106 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
1107 let param_env = ty::ParamEnv::empty();
1108 if self.can_sub(param_env, error, implication).is_ok() {
1109 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
1118 fn report_fulfillment_error(
1120 error: &FulfillmentError<'tcx>,
1121 body_id: Option<hir::BodyId>,
1122 fallback_has_occurred: bool,
1124 debug!("report_fulfillment_error({:?})", error);
1126 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
1127 self.report_selection_error(
1130 fallback_has_occurred,
1131 error.points_at_arg_span,
1134 FulfillmentErrorCode::CodeProjectionError(ref e) => {
1135 self.report_projection_error(&error.obligation, e);
1137 FulfillmentErrorCode::CodeAmbiguity => {
1138 self.maybe_report_ambiguity(&error.obligation, body_id);
1140 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
1141 self.report_mismatched_types(
1142 &error.obligation.cause,
1143 expected_found.expected,
1144 expected_found.found,
1149 FulfillmentErrorCode::CodeConstEquateError(ref expected_found, ref err) => {
1150 self.report_mismatched_consts(
1151 &error.obligation.cause,
1152 expected_found.expected,
1153 expected_found.found,
1161 fn report_projection_error(
1163 obligation: &PredicateObligation<'tcx>,
1164 error: &MismatchedProjectionTypes<'tcx>,
1166 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1168 if predicate.references_error() {
1174 let mut err = &error.err;
1175 let mut values = None;
1177 // try to find the mismatched types to report the error with.
1179 // this can fail if the problem was higher-ranked, in which
1180 // cause I have no idea for a good error message.
1181 if let ty::PredicateAtom::Projection(data) = predicate.skip_binders() {
1182 let mut selcx = SelectionContext::new(self);
1183 let (data, _) = self.replace_bound_vars_with_fresh_vars(
1184 obligation.cause.span,
1185 infer::LateBoundRegionConversionTime::HigherRankedType,
1186 &ty::Binder::bind(data),
1188 let mut obligations = vec![];
1189 let normalized_ty = super::normalize_projection_type(
1191 obligation.param_env,
1193 obligation.cause.clone(),
1199 "report_projection_error obligation.cause={:?} obligation.param_env={:?}",
1200 obligation.cause, obligation.param_env
1204 "report_projection_error normalized_ty={:?} data.ty={:?}",
1205 normalized_ty, data.ty
1208 let is_normalized_ty_expected = match &obligation.cause.code {
1209 ObligationCauseCode::ItemObligation(_)
1210 | ObligationCauseCode::BindingObligation(_, _)
1211 | ObligationCauseCode::ObjectCastObligation(_) => false,
1215 if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
1216 is_normalized_ty_expected,
1220 values = Some(infer::ValuePairs::Types(ExpectedFound::new(
1221 is_normalized_ty_expected,
1231 let msg = format!("type mismatch resolving `{}`", predicate);
1232 let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg);
1233 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
1235 let mut diag = struct_span_err!(
1237 obligation.cause.span,
1239 "type mismatch resolving `{}`",
1242 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
1243 self.note_obligation_cause(&mut diag, obligation);
1249 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1250 /// returns the fuzzy category of a given type, or None
1251 /// if the type can be equated to any type.
1252 fn type_category(t: Ty<'_>) -> Option<u32> {
1254 ty::Bool => Some(0),
1255 ty::Char => Some(1),
1257 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
1258 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
1259 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1260 ty::Array(..) | ty::Slice(..) => Some(6),
1261 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1262 ty::Dynamic(..) => Some(8),
1263 ty::Closure(..) => Some(9),
1264 ty::Tuple(..) => Some(10),
1265 ty::Projection(..) => Some(11),
1266 ty::Param(..) => Some(12),
1267 ty::Opaque(..) => Some(13),
1268 ty::Never => Some(14),
1269 ty::Adt(adt, ..) => match adt.adt_kind() {
1270 AdtKind::Struct => Some(15),
1271 AdtKind::Union => Some(16),
1272 AdtKind::Enum => Some(17),
1274 ty::Generator(..) => Some(18),
1275 ty::Foreign(..) => Some(19),
1276 ty::GeneratorWitness(..) => Some(20),
1277 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1281 match (type_category(a), type_category(b)) {
1282 (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
1283 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
1284 _ => cat_a == cat_b,
1286 // infer and error can be equated to all types
1291 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
1292 self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
1293 hir::GeneratorKind::Gen => "a generator",
1294 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
1295 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
1296 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
1300 fn find_similar_impl_candidates(
1302 trait_ref: ty::PolyTraitRef<'tcx>,
1303 ) -> Vec<ty::TraitRef<'tcx>> {
1304 let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
1305 let all_impls = self.tcx.all_impls(trait_ref.def_id());
1308 Some(simp) => all_impls
1309 .filter_map(|def_id| {
1310 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
1311 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
1312 if let Some(imp_simp) = imp_simp {
1313 if simp != imp_simp {
1320 None => all_impls.map(|def_id| self.tcx.impl_trait_ref(def_id).unwrap()).collect(),
1324 fn report_similar_impl_candidates(
1326 impl_candidates: Vec<ty::TraitRef<'tcx>>,
1327 err: &mut DiagnosticBuilder<'_>,
1329 if impl_candidates.is_empty() {
1333 let len = impl_candidates.len();
1334 let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 };
1336 let normalize = |candidate| {
1337 self.tcx.infer_ctxt().enter(|ref infcx| {
1338 let normalized = infcx
1339 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
1340 .normalize(candidate)
1343 Some(normalized) => format!("\n {:?}", normalized.value),
1344 None => format!("\n {:?}", candidate),
1349 // Sort impl candidates so that ordering is consistent for UI tests.
1350 let mut normalized_impl_candidates =
1351 impl_candidates.iter().map(normalize).collect::<Vec<String>>();
1353 // Sort before taking the `..end` range,
1354 // because the ordering of `impl_candidates` may not be deterministic:
1355 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
1356 normalized_impl_candidates.sort();
1359 "the following implementations were found:{}{}",
1360 normalized_impl_candidates[..end].join(""),
1361 if len > 5 { format!("\nand {} others", len - 4) } else { String::new() }
1365 /// Gets the parent trait chain start
1366 fn get_parent_trait_ref(
1368 code: &ObligationCauseCode<'tcx>,
1369 ) -> Option<(String, Option<Span>)> {
1371 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1372 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1373 match self.get_parent_trait_ref(&data.parent_code) {
1376 let ty = parent_trait_ref.skip_binder().self_ty();
1378 TyCategory::from_ty(ty).map(|(_, def_id)| self.tcx.def_span(def_id));
1379 Some((ty.to_string(), span))
1387 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1388 /// with the same path as `trait_ref`, a help message about
1389 /// a probable version mismatch is added to `err`
1390 fn note_version_mismatch(
1392 err: &mut DiagnosticBuilder<'_>,
1393 trait_ref: &ty::PolyTraitRef<'tcx>,
1395 let get_trait_impl = |trait_def_id| {
1396 let mut trait_impl = None;
1397 self.tcx.for_each_relevant_impl(
1399 trait_ref.skip_binder().self_ty(),
1401 if trait_impl.is_none() {
1402 trait_impl = Some(impl_def_id);
1408 let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1409 let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1410 let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1412 .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1413 .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1415 for trait_with_same_path in traits_with_same_path {
1416 if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1417 let impl_span = self.tcx.def_span(impl_def_id);
1418 err.span_help(impl_span, "trait impl with same name found");
1419 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1420 let crate_msg = format!(
1421 "perhaps two different versions of crate `{}` are being used?",
1424 err.note(&crate_msg);
1429 fn mk_trait_obligation_with_new_self_ty(
1431 param_env: ty::ParamEnv<'tcx>,
1432 trait_ref: &ty::PolyTraitRef<'tcx>,
1433 new_self_ty: Ty<'tcx>,
1434 ) -> PredicateObligation<'tcx> {
1435 assert!(!new_self_ty.has_escaping_bound_vars());
1437 let trait_ref = trait_ref.map_bound_ref(|tr| ty::TraitRef {
1438 substs: self.tcx.mk_substs_trait(new_self_ty, &tr.substs[1..]),
1443 ObligationCause::dummy(),
1445 trait_ref.without_const().to_predicate(self.tcx),
1449 fn maybe_report_ambiguity(
1451 obligation: &PredicateObligation<'tcx>,
1452 body_id: Option<hir::BodyId>,
1454 // Unable to successfully determine, probably means
1455 // insufficient type information, but could mean
1456 // ambiguous impls. The latter *ought* to be a
1457 // coherence violation, so we don't report it here.
1459 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1460 let span = obligation.cause.span;
1463 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1464 predicate, obligation, body_id, obligation.cause.code,
1467 // Ambiguity errors are often caused as fallout from earlier
1468 // errors. So just ignore them if this infcx is tainted.
1469 if self.is_tainted_by_errors() {
1473 let mut err = match predicate.skip_binders() {
1474 ty::PredicateAtom::Trait(data, _) => {
1475 let trait_ref = ty::Binder::bind(data.trait_ref);
1476 let self_ty = trait_ref.skip_binder().self_ty();
1477 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1479 if predicate.references_error() {
1482 // Typically, this ambiguity should only happen if
1483 // there are unresolved type inference variables
1484 // (otherwise it would suggest a coherence
1485 // failure). But given #21974 that is not necessarily
1486 // the case -- we can have multiple where clauses that
1487 // are only distinguished by a region, which results
1488 // in an ambiguity even when all types are fully
1489 // known, since we don't dispatch based on region
1492 // This is kind of a hack: it frequently happens that some earlier
1493 // error prevents types from being fully inferred, and then we get
1494 // a bunch of uninteresting errors saying something like "<generic
1495 // #0> doesn't implement Sized". It may even be true that we
1496 // could just skip over all checks where the self-ty is an
1497 // inference variable, but I was afraid that there might be an
1498 // inference variable created, registered as an obligation, and
1499 // then never forced by writeback, and hence by skipping here we'd
1500 // be ignoring the fact that we don't KNOW the type works
1501 // out. Though even that would probably be harmless, given that
1502 // we're only talking about builtin traits, which are known to be
1503 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1504 // avoid inundating the user with unnecessary errors, but we now
1505 // check upstream for type errors and don't add the obligations to
1506 // begin with in those cases.
1511 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1513 self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
1516 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
1517 err.note(&format!("cannot satisfy `{}`", predicate));
1518 if let ObligationCauseCode::ItemObligation(def_id) = obligation.cause.code {
1519 self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
1522 ObligationCauseCode::BindingObligation(ref def_id, _),
1524 (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
1526 let generics = self.tcx.generics_of(*def_id);
1527 if generics.params.iter().any(|p| p.name != kw::SelfUpper)
1528 && !snippet.ends_with('>')
1530 // FIXME: To avoid spurious suggestions in functions where type arguments
1531 // where already supplied, we check the snippet to make sure it doesn't
1532 // end with a turbofish. Ideally we would have access to a `PathSegment`
1533 // instead. Otherwise we would produce the following output:
1535 // error[E0283]: type annotations needed
1536 // --> $DIR/issue-54954.rs:3:24
1538 // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
1539 // | ^^^^^^^^^^^^^^^^^^^^^^^^^^
1541 // | cannot infer type
1542 // | help: consider specifying the type argument
1543 // | in the function call:
1544 // | `Tt::const_val::<[i8; 123]>::<T>`
1546 // LL | const fn const_val<T: Sized>() -> usize {
1547 // | - required by this bound in `Tt::const_val`
1549 // = note: cannot satisfy `_: Tt`
1551 err.span_suggestion_verbose(
1552 span.shrink_to_hi(),
1554 "consider specifying the type argument{} in the function call",
1555 pluralize!(generics.params.len()),
1562 .map(|p| p.name.to_string())
1563 .collect::<Vec<String>>()
1566 Applicability::HasPlaceholders,
1573 ty::PredicateAtom::WellFormed(arg) => {
1574 // Same hacky approach as above to avoid deluging user
1575 // with error messages.
1576 if arg.references_error() || self.tcx.sess.has_errors() {
1580 match arg.unpack() {
1581 GenericArgKind::Lifetime(lt) => {
1582 span_bug!(span, "unexpected well formed predicate: {:?}", lt)
1584 GenericArgKind::Type(ty) => {
1585 self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
1587 GenericArgKind::Const(ct) => {
1588 self.need_type_info_err_const(body_id, span, ct, ErrorCode::E0282)
1593 ty::PredicateAtom::Subtype(data) => {
1594 if data.references_error() || self.tcx.sess.has_errors() {
1595 // no need to overload user in such cases
1598 let SubtypePredicate { a_is_expected: _, a, b } = data;
1599 // both must be type variables, or the other would've been instantiated
1600 assert!(a.is_ty_var() && b.is_ty_var());
1601 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
1603 ty::PredicateAtom::Projection(data) => {
1604 let trait_ref = ty::Binder::bind(data).to_poly_trait_ref(self.tcx);
1605 let self_ty = trait_ref.skip_binder().self_ty();
1607 if predicate.references_error() {
1610 if self_ty.needs_infer() && ty.needs_infer() {
1611 // We do this for the `foo.collect()?` case to produce a suggestion.
1612 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
1613 err.note(&format!("cannot satisfy `{}`", predicate));
1616 let mut err = struct_span_err!(
1620 "type annotations needed: cannot satisfy `{}`",
1623 err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1629 if self.tcx.sess.has_errors() {
1632 let mut err = struct_span_err!(
1636 "type annotations needed: cannot satisfy `{}`",
1639 err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1643 self.note_obligation_cause(&mut err, obligation);
1647 /// Returns `true` if the trait predicate may apply for *some* assignment
1648 /// to the type parameters.
1649 fn predicate_can_apply(
1651 param_env: ty::ParamEnv<'tcx>,
1652 pred: ty::PolyTraitRef<'tcx>,
1654 struct ParamToVarFolder<'a, 'tcx> {
1655 infcx: &'a InferCtxt<'a, 'tcx>,
1656 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
1659 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
1660 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1664 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1665 if let ty::Param(ty::ParamTy { name, .. }) = ty.kind {
1666 let infcx = self.infcx;
1667 self.var_map.entry(ty).or_insert_with(|| {
1668 infcx.next_ty_var(TypeVariableOrigin {
1669 kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
1674 ty.super_fold_with(self)
1680 let mut selcx = SelectionContext::new(self);
1683 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
1685 let cleaned_pred = super::project::normalize(
1688 ObligationCause::dummy(),
1693 let obligation = Obligation::new(
1694 ObligationCause::dummy(),
1696 cleaned_pred.without_const().to_predicate(selcx.tcx()),
1699 self.predicate_may_hold(&obligation)
1703 fn note_obligation_cause(
1705 err: &mut DiagnosticBuilder<'tcx>,
1706 obligation: &PredicateObligation<'tcx>,
1708 // First, attempt to add note to this error with an async-await-specific
1709 // message, and fall back to regular note otherwise.
1710 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
1711 self.note_obligation_cause_code(
1713 &obligation.predicate,
1714 &obligation.cause.code,
1717 self.suggest_unsized_bound_if_applicable(err, obligation);
1721 fn suggest_unsized_bound_if_applicable(
1723 err: &mut DiagnosticBuilder<'tcx>,
1724 obligation: &PredicateObligation<'tcx>,
1726 let (pred, item_def_id, span) =
1727 match (obligation.predicate.skip_binders(), obligation.cause.code.peel_derives()) {
1729 ty::PredicateAtom::Trait(pred, _),
1730 &ObligationCauseCode::BindingObligation(item_def_id, span),
1731 ) => (pred, item_def_id, span),
1736 self.tcx.hir().get_if_local(item_def_id),
1737 Some(pred.def_id()) == self.tcx.lang_items().sized_trait(),
1739 (Some(node), true) => node,
1742 let generics = match node.generics() {
1743 Some(generics) => generics,
1746 for param in generics.params {
1747 if param.span != span
1748 || param.bounds.iter().any(|bound| {
1749 bound.trait_ref().and_then(|trait_ref| trait_ref.trait_def_id())
1750 == self.tcx.lang_items().sized_trait()
1761 hir::ItemKind::Enum(..)
1762 | hir::ItemKind::Struct(..)
1763 | hir::ItemKind::Union(..),
1767 // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
1768 // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
1770 let mut visitor = FindTypeParam {
1771 param: param.name.ident().name,
1772 invalid_spans: vec![],
1775 visitor.visit_item(item);
1776 if !visitor.invalid_spans.is_empty() {
1777 let mut multispan: MultiSpan = param.span.into();
1778 multispan.push_span_label(
1780 format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
1782 for sp in visitor.invalid_spans {
1783 multispan.push_span_label(
1786 "...if indirection was used here: `Box<{}>`",
1794 "you could relax the implicit `Sized` bound on `{T}` if it were \
1795 used through indirection like `&{T}` or `Box<{T}>`",
1796 T = param.name.ident(),
1804 let (span, separator) = match param.bounds {
1805 [] => (span.shrink_to_hi(), ":"),
1806 [.., bound] => (bound.span().shrink_to_hi(), " +"),
1808 err.span_suggestion_verbose(
1810 "consider relaxing the implicit `Sized` restriction",
1811 format!("{} ?Sized", separator),
1812 Applicability::MachineApplicable,
1818 fn is_recursive_obligation(
1820 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1821 cause_code: &ObligationCauseCode<'tcx>,
1823 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1824 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1826 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1834 /// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
1835 /// `param: ?Sized` would be a valid constraint.
1836 struct FindTypeParam {
1837 param: rustc_span::Symbol,
1838 invalid_spans: Vec<Span>,
1842 impl<'v> Visitor<'v> for FindTypeParam {
1843 type Map = rustc_hir::intravisit::ErasedMap<'v>;
1845 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
1846 hir::intravisit::NestedVisitorMap::None
1849 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1850 // We collect the spans of all uses of the "bare" type param, like in `field: T` or
1851 // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
1852 // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
1853 // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
1854 // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
1855 // in that case should make what happened clear enough.
1857 hir::TyKind::Ptr(_) | hir::TyKind::Rptr(..) | hir::TyKind::TraitObject(..) => {}
1858 hir::TyKind::Path(hir::QPath::Resolved(None, path))
1859 if path.segments.len() == 1 && path.segments[0].ident.name == self.param =>
1862 self.invalid_spans.push(ty.span);
1865 hir::TyKind::Path(_) => {
1866 let prev = self.nested;
1868 hir::intravisit::walk_ty(self, ty);
1872 hir::intravisit::walk_ty(self, ty);
1878 pub fn recursive_type_with_infinite_size_error(
1883 assert!(type_def_id.is_local());
1884 let span = tcx.hir().span_if_local(type_def_id).unwrap();
1885 let span = tcx.sess.source_map().guess_head_span(span);
1886 let path = tcx.def_path_str(type_def_id);
1888 struct_span_err!(tcx.sess, span, E0072, "recursive type `{}` has infinite size", path);
1889 err.span_label(span, "recursive type has infinite size");
1890 for &span in &spans {
1891 err.span_label(span, "recursive without indirection");
1894 "insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `{}` representable",
1897 if spans.len() <= 4 {
1898 err.multipart_suggestion(
1904 (span.shrink_to_lo(), "Box<".to_string()),
1905 (span.shrink_to_hi(), ">".to_string()),
1910 Applicability::HasPlaceholders,
1918 /// Summarizes information
1921 /// An argument of non-tuple type. Parameters are (name, ty)
1922 Arg(String, String),
1924 /// An argument of tuple type. For a "found" argument, the span is
1925 /// the locationo in the source of the pattern. For a "expected"
1926 /// argument, it will be None. The vector is a list of (name, ty)
1927 /// strings for the components of the tuple.
1928 Tuple(Option<Span>, Vec<(String, String)>),
1932 fn empty() -> ArgKind {
1933 ArgKind::Arg("_".to_owned(), "_".to_owned())
1936 /// Creates an `ArgKind` from the expected type of an
1937 /// argument. It has no name (`_`) and an optional source span.
1938 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
1940 ty::Tuple(ref tys) => ArgKind::Tuple(
1942 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
1944 _ => ArgKind::Arg("_".to_owned(), t.to_string()),