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};
19 use rustc_middle::mir::interpret::ErrorHandled;
20 use rustc_middle::ty::error::ExpectedFound;
21 use rustc_middle::ty::fold::TypeFolder;
22 use rustc_middle::ty::{
23 self, fast_reject, AdtKind, SubtypePredicate, ToPolyTraitRef, ToPredicate, Ty, TyCtxt,
24 TypeFoldable, WithConstness,
26 use rustc_session::DiagnosticMessageId;
27 use rustc_span::{ExpnKind, Span, DUMMY_SP};
30 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
31 use crate::traits::query::normalize::AtExt as _;
32 use on_unimplemented::InferCtxtExt as _;
33 use suggestions::InferCtxtExt as _;
35 pub use rustc_infer::traits::error_reporting::*;
37 pub trait InferCtxtExt<'tcx> {
38 fn report_fulfillment_errors(
40 errors: &[FulfillmentError<'tcx>],
41 body_id: Option<hir::BodyId>,
42 fallback_has_occurred: bool,
45 fn report_overflow_error<T>(
47 obligation: &Obligation<'tcx, T>,
48 suggest_increasing_limit: bool,
51 T: fmt::Display + TypeFoldable<'tcx>;
53 fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !;
55 fn report_selection_error(
57 obligation: &PredicateObligation<'tcx>,
58 error: &SelectionError<'tcx>,
59 fallback_has_occurred: bool,
63 /// Given some node representing a fn-like thing in the HIR map,
64 /// returns a span and `ArgKind` information that describes the
65 /// arguments it expects. This can be supplied to
66 /// `report_arg_count_mismatch`.
67 fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)>;
69 /// Reports an error when the number of arguments needed by a
70 /// trait match doesn't match the number that the expression
72 fn report_arg_count_mismatch(
75 found_span: Option<Span>,
76 expected_args: Vec<ArgKind>,
77 found_args: Vec<ArgKind>,
79 ) -> DiagnosticBuilder<'tcx>;
82 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
83 fn report_fulfillment_errors(
85 errors: &[FulfillmentError<'tcx>],
86 body_id: Option<hir::BodyId>,
87 fallback_has_occurred: bool,
90 struct ErrorDescriptor<'tcx> {
91 predicate: ty::Predicate<'tcx>,
92 index: Option<usize>, // None if this is an old error
95 let mut error_map: FxHashMap<_, Vec<_>> = self
96 .reported_trait_errors
99 .map(|(&span, predicates)| {
104 .map(|&predicate| ErrorDescriptor { predicate, index: None })
110 for (index, error) in errors.iter().enumerate() {
111 // We want to ignore desugarings here: spans are equivalent even
112 // if one is the result of a desugaring and the other is not.
113 let mut span = error.obligation.cause.span;
114 let expn_data = span.ctxt().outer_expn_data();
115 if let ExpnKind::Desugaring(_) = expn_data.kind {
116 span = expn_data.call_site;
119 error_map.entry(span).or_default().push(ErrorDescriptor {
120 predicate: error.obligation.predicate,
124 self.reported_trait_errors
128 .push(error.obligation.predicate);
131 // We do this in 2 passes because we want to display errors in order, though
132 // maybe it *is* better to sort errors by span or something.
133 let mut is_suppressed = vec![false; errors.len()];
134 for (_, error_set) in error_map.iter() {
135 // We want to suppress "duplicate" errors with the same span.
136 for error in error_set {
137 if let Some(index) = error.index {
138 // Suppress errors that are either:
139 // 1) strictly implied by another error.
140 // 2) implied by an error with a smaller index.
141 for error2 in error_set {
142 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
143 // Avoid errors being suppressed by already-suppressed
144 // errors, to prevent all errors from being suppressed
149 if self.error_implies(error2.predicate, error.predicate)
150 && !(error2.index >= error.index
151 && self.error_implies(error.predicate, error2.predicate))
153 info!("skipping {:?} (implied by {:?})", error, error2);
154 is_suppressed[index] = true;
162 for (error, suppressed) in errors.iter().zip(is_suppressed) {
164 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
169 /// Reports that an overflow has occurred and halts compilation. We
170 /// halt compilation unconditionally because it is important that
171 /// overflows never be masked -- they basically represent computations
172 /// whose result could not be truly determined and thus we can't say
173 /// if the program type checks or not -- and they are unusual
174 /// occurrences in any case.
175 fn report_overflow_error<T>(
177 obligation: &Obligation<'tcx, T>,
178 suggest_increasing_limit: bool,
181 T: fmt::Display + TypeFoldable<'tcx>,
183 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
184 let mut err = struct_span_err!(
186 obligation.cause.span,
188 "overflow evaluating the requirement `{}`",
192 if suggest_increasing_limit {
193 self.suggest_new_overflow_limit(&mut err);
196 self.note_obligation_cause_code(
198 &obligation.predicate,
199 &obligation.cause.code,
204 self.tcx.sess.abort_if_errors();
208 /// Reports that a cycle was detected which led to overflow and halts
209 /// compilation. This is equivalent to `report_overflow_error` except
210 /// that we can give a more helpful error message (and, in particular,
211 /// we do not suggest increasing the overflow limit, which is not
213 fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
214 let cycle = self.resolve_vars_if_possible(&cycle.to_owned());
215 assert!(!cycle.is_empty());
217 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
219 self.report_overflow_error(&cycle[0], false);
222 fn report_selection_error(
224 obligation: &PredicateObligation<'tcx>,
225 error: &SelectionError<'tcx>,
226 fallback_has_occurred: bool,
230 let span = obligation.cause.span;
232 let mut err = match *error {
233 SelectionError::Unimplemented => {
234 if let ObligationCauseCode::CompareImplMethodObligation {
239 | ObligationCauseCode::CompareImplTypeObligation {
243 } = obligation.cause.code
245 self.report_extra_impl_obligation(
250 &format!("`{}`", obligation.predicate),
255 match obligation.predicate.kind() {
256 ty::PredicateKind::Trait(ref trait_predicate, _) => {
257 let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
259 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
262 let trait_ref = trait_predicate.to_poly_trait_ref();
263 let (post_message, pre_message, type_def) = self
264 .get_parent_trait_ref(&obligation.cause.code)
267 format!(" in `{}`", t),
268 format!("within `{}`, ", t),
269 s.map(|s| (format!("within this `{}`", t), s)),
272 .unwrap_or_default();
274 let OnUnimplementedNote { message, label, note, enclosing_scope } =
275 self.on_unimplemented_note(trait_ref, obligation);
276 let have_alt_message = message.is_some() || label.is_some();
281 .span_to_snippet(span)
284 let is_from = format!("{}", trait_ref.print_only_trait_path())
285 .starts_with("std::convert::From<");
287 { Some(trait_ref.def_id()) == self.tcx.lang_items().unsize_trait() };
288 let (message, note) = if is_try && is_from {
291 "`?` couldn't convert the error to `{}`",
295 "the question mark operation (`?`) implicitly performs a \
296 conversion on the error value using the `From` trait"
304 let mut err = struct_span_err!(
309 message.unwrap_or_else(|| format!(
310 "the trait bound `{}` is not satisfied{}",
311 trait_ref.without_const().to_predicate(tcx),
316 let should_convert_option_to_result =
317 format!("{}", trait_ref.print_only_trait_path())
318 .starts_with("std::convert::From<std::option::NoneError");
319 let should_convert_result_to_option = format!("{}", trait_ref)
320 .starts_with("<std::option::NoneError as std::convert::From<");
321 if is_try && is_from {
322 if should_convert_option_to_result {
323 err.span_suggestion_verbose(
325 "consider converting the `Option<T>` into a `Result<T, _>` \
326 using `Option::ok_or` or `Option::ok_or_else`",
327 ".ok_or_else(|| /* error value */)".to_string(),
328 Applicability::HasPlaceholders,
330 } else if should_convert_result_to_option {
331 err.span_suggestion_verbose(
333 "consider converting the `Result<T, _>` into an `Option<T>` \
336 Applicability::MachineApplicable,
339 if let Some(ret_span) = self.return_type_span(obligation) {
342 &format!("expected `{}` because of this", trait_ref.self_ty()),
348 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
349 "consider using `()`, or a `Result`".to_owned()
352 "{}the trait `{}` is not implemented for `{}`",
354 trait_ref.print_only_trait_path(),
359 if self.suggest_add_reference_to_arg(
366 self.note_obligation_cause(&mut err, obligation);
370 if let Some(ref s) = label {
371 // If it has a custom `#[rustc_on_unimplemented]`
372 // error message, let's display it as the label!
373 err.span_label(span, s.as_str());
374 err.help(&explanation);
376 err.span_label(span, explanation);
378 if let Some((msg, span)) = type_def {
379 err.span_label(span, &msg);
381 if let Some(ref s) = note {
382 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
383 err.note(s.as_str());
385 if let Some(ref s) = enclosing_scope {
386 let enclosing_scope_span = tcx.def_span(
388 .opt_local_def_id(obligation.cause.body_id)
390 tcx.hir().body_owner_def_id(hir::BodyId {
391 hir_id: obligation.cause.body_id,
397 err.span_label(enclosing_scope_span, s.as_str());
400 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
401 self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
402 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
403 self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref);
404 self.note_version_mismatch(&mut err, &trait_ref);
406 if Some(trait_ref.def_id()) == tcx.lang_items().try_trait() {
407 self.suggest_await_before_try(&mut err, &obligation, &trait_ref, span);
410 if self.suggest_impl_trait(&mut err, span, &obligation, &trait_ref) {
416 // If the obligation failed due to a missing implementation of the
417 // `Unsize` trait, give a pointer to why that might be the case
419 "all implementations of `Unsize` are provided \
420 automatically by the compiler, see \
421 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
422 for more information",
426 // Try to report a help message
427 if !trait_ref.has_infer_types_or_consts()
428 && self.predicate_can_apply(obligation.param_env, trait_ref)
430 // If a where-clause may be useful, remind the
431 // user that they can add it.
433 // don't display an on-unimplemented note, as
434 // these notes will often be of the form
435 // "the type `T` can't be frobnicated"
436 // which is somewhat confusing.
437 self.suggest_restricting_param_bound(
440 obligation.cause.body_id,
443 if !have_alt_message {
444 // Can't show anything else useful, try to find similar impls.
445 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
446 self.report_similar_impl_candidates(impl_candidates, &mut err);
448 // Changing mutability doesn't make a difference to whether we have
449 // an `Unsize` impl (Fixes ICE in #71036)
451 self.suggest_change_mut(
460 // If this error is due to `!: Trait` not implemented but `(): Trait` is
461 // implemented, and fallback has occurred, then it could be due to a
462 // variable that used to fallback to `()` now falling back to `!`. Issue a
463 // note informing about the change in behaviour.
464 if trait_predicate.skip_binder().self_ty().is_never()
465 && fallback_has_occurred
467 let predicate = trait_predicate.map_bound(|mut trait_pred| {
468 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
470 &trait_pred.trait_ref.substs[1..],
474 let unit_obligation = Obligation {
475 predicate: ty::PredicateKind::Trait(
477 hir::Constness::NotConst,
479 .to_predicate(self.tcx),
482 if self.predicate_may_hold(&unit_obligation) {
484 "the trait is implemented for `()`. \
485 Possibly this error has been caused by changes to \
486 Rust's type-inference algorithm (see issue #48950 \
487 <https://github.com/rust-lang/rust/issues/48950> \
488 for more information). Consider whether you meant to use \
489 the type `()` here instead.",
497 ty::PredicateKind::Subtype(ref predicate) => {
498 // Errors for Subtype predicates show up as
499 // `FulfillmentErrorCode::CodeSubtypeError`,
500 // not selection error.
501 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
504 ty::PredicateKind::RegionOutlives(ref predicate) => {
505 let predicate = self.resolve_vars_if_possible(predicate);
507 .region_outlives_predicate(&obligation.cause, predicate)
514 "the requirement `{}` is not satisfied (`{}`)",
520 ty::PredicateKind::Projection(..) | ty::PredicateKind::TypeOutlives(..) => {
521 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
526 "the requirement `{}` is not satisfied",
531 &ty::PredicateKind::ObjectSafe(trait_def_id) => {
532 let violations = self.tcx.object_safety_violations(trait_def_id);
533 report_object_safety_error(self.tcx, span, trait_def_id, violations)
536 &ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
537 let found_kind = self.closure_kind(closure_substs).unwrap();
539 self.tcx.sess.source_map().guess_head_span(
540 self.tcx.hir().span_if_local(closure_def_id).unwrap(),
542 let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id.expect_local());
543 let mut err = struct_span_err!(
547 "expected a closure that implements the `{}` trait, \
548 but this closure only implements `{}`",
555 format!("this closure implements `{}`, not `{}`", found_kind, kind),
558 obligation.cause.span,
559 format!("the requirement to implement `{}` derives from here", kind),
562 // Additional context information explaining why the closure only implements
563 // a particular trait.
564 if let Some(tables) = self.in_progress_tables {
565 let tables = tables.borrow();
566 match (found_kind, tables.closure_kind_origins().get(hir_id)) {
567 (ty::ClosureKind::FnOnce, Some((span, name))) => {
571 "closure is `FnOnce` because it moves the \
572 variable `{}` out of its environment",
577 (ty::ClosureKind::FnMut, Some((span, name))) => {
581 "closure is `FnMut` because it mutates the \
595 ty::PredicateKind::WellFormed(ty) => {
596 if !self.tcx.sess.opts.debugging_opts.chalk {
597 // WF predicates cannot themselves make
598 // errors. They can only block due to
599 // ambiguity; otherwise, they always
600 // degenerate into other obligations
602 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
604 // FIXME: we'll need a better message which takes into account
605 // which bounds actually failed to hold.
606 self.tcx.sess.struct_span_err(
608 &format!("the type `{}` is not well-formed (chalk)", ty),
613 ty::PredicateKind::ConstEvaluatable(..) => {
614 // Errors for `ConstEvaluatable` predicates show up as
615 // `SelectionError::ConstEvalFailure`,
616 // not `Unimplemented`.
619 "const-evaluatable requirement gave wrong error: `{:?}`",
624 ty::PredicateKind::ConstEquate(..) => {
625 // Errors for `ConstEquate` predicates show up as
626 // `SelectionError::ConstEvalFailure`,
627 // not `Unimplemented`.
630 "const-equate requirement gave wrong error: `{:?}`",
637 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
638 let found_trait_ref = self.resolve_vars_if_possible(&*found_trait_ref);
639 let expected_trait_ref = self.resolve_vars_if_possible(&*expected_trait_ref);
641 if expected_trait_ref.self_ty().references_error() {
645 let found_trait_ty = found_trait_ref.self_ty();
647 let found_did = match found_trait_ty.kind {
648 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
649 ty::Adt(def, _) => Some(def.did),
653 let found_span = found_did
654 .and_then(|did| self.tcx.hir().span_if_local(did))
655 .map(|sp| self.tcx.sess.source_map().guess_head_span(sp)); // the sp could be an fn def
657 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
658 // We check closures twice, with obligations flowing in different directions,
659 // but we want to complain about them only once.
663 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
665 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind {
666 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
667 _ => vec![ArgKind::empty()],
670 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
671 let expected = match expected_ty.kind {
672 ty::Tuple(ref tys) => tys
674 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span)))
676 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
679 if found.len() == expected.len() {
680 self.report_closure_arg_mismatch(
687 let (closure_span, found) = found_did
689 let node = self.tcx.hir().get_if_local(did)?;
690 let (found_span, found) = self.get_fn_like_arguments(node)?;
691 Some((Some(found_span), found))
693 .unwrap_or((found_span, found));
695 self.report_arg_count_mismatch(
700 found_trait_ty.is_closure(),
705 TraitNotObjectSafe(did) => {
706 let violations = self.tcx.object_safety_violations(did);
707 report_object_safety_error(self.tcx, span, did, violations)
710 ConstEvalFailure(ErrorHandled::TooGeneric) => {
711 // In this instance, we have a const expression containing an unevaluated
712 // generic parameter. We have no idea whether this expression is valid or
713 // not (e.g. it might result in an error), but we don't want to just assume
714 // that it's okay, because that might result in post-monomorphisation time
715 // errors. The onus is really on the caller to provide values that it can
716 // prove are well-formed.
720 .struct_span_err(span, "constant expression depends on a generic parameter");
721 // FIXME(const_generics): we should suggest to the user how they can resolve this
722 // issue. However, this is currently not actually possible
723 // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
724 err.note("this may fail depending on what value the parameter takes");
728 // Already reported in the query.
729 ConstEvalFailure(ErrorHandled::Reported(ErrorReported)) => {
730 // FIXME(eddyb) remove this once `ErrorReported` becomes a proof token.
731 self.tcx.sess.delay_span_bug(span, "`ErrorReported` without an error");
735 // Already reported in the query, but only as a lint.
736 // This shouldn't actually happen for constants used in types, modulo
737 // bugs. The `delay_span_bug` here ensures it won't be ignored.
738 ConstEvalFailure(ErrorHandled::Linted) => {
739 self.tcx.sess.delay_span_bug(span, "constant in type had error reported as lint");
744 bug!("overflow should be handled before the `report_selection_error` path");
748 self.note_obligation_cause(&mut err, obligation);
749 self.point_at_returns_when_relevant(&mut err, &obligation);
754 /// Given some node representing a fn-like thing in the HIR map,
755 /// returns a span and `ArgKind` information that describes the
756 /// arguments it expects. This can be supplied to
757 /// `report_arg_count_mismatch`.
758 fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)> {
759 let sm = self.tcx.sess.source_map();
760 let hir = self.tcx.hir();
762 Node::Expr(&hir::Expr {
763 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
766 sm.guess_head_span(span),
771 if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
778 sm.span_to_snippet(pat.span)
780 .map(|snippet| (snippet, "_".to_owned()))
782 .collect::<Option<Vec<_>>>()?,
785 let name = sm.span_to_snippet(arg.pat.span).ok()?;
786 Some(ArgKind::Arg(name, "_".to_owned()))
789 .collect::<Option<Vec<ArgKind>>>()?,
791 Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
792 | Node::ImplItem(&hir::ImplItem {
794 kind: hir::ImplItemKind::Fn(ref sig, _),
797 | Node::TraitItem(&hir::TraitItem {
799 kind: hir::TraitItemKind::Fn(ref sig, _),
802 sm.guess_head_span(span),
806 .map(|arg| match arg.clone().kind {
807 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
809 vec![("_".to_owned(), "_".to_owned()); tys.len()],
811 _ => ArgKind::empty(),
813 .collect::<Vec<ArgKind>>(),
815 Node::Ctor(ref variant_data) => {
816 let span = variant_data.ctor_hir_id().map(|id| hir.span(id)).unwrap_or(DUMMY_SP);
817 let span = sm.guess_head_span(span);
818 (span, vec![ArgKind::empty(); variant_data.fields().len()])
820 _ => panic!("non-FnLike node found: {:?}", node),
824 /// Reports an error when the number of arguments needed by a
825 /// trait match doesn't match the number that the expression
827 fn report_arg_count_mismatch(
830 found_span: Option<Span>,
831 expected_args: Vec<ArgKind>,
832 found_args: Vec<ArgKind>,
834 ) -> DiagnosticBuilder<'tcx> {
835 let kind = if is_closure { "closure" } else { "function" };
837 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
838 let arg_length = arguments.len();
839 let distinct = match &other[..] {
840 &[ArgKind::Tuple(..)] => true,
843 match (arg_length, arguments.get(0)) {
844 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
845 format!("a single {}-tuple as argument", fields.len())
850 if distinct && arg_length > 1 { "distinct " } else { "" },
851 pluralize!(arg_length)
856 let expected_str = args_str(&expected_args, &found_args);
857 let found_str = args_str(&found_args, &expected_args);
859 let mut err = struct_span_err!(
863 "{} is expected to take {}, but it takes {}",
869 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
871 if let Some(found_span) = found_span {
872 err.span_label(found_span, format!("takes {}", found_str));
875 // ^^^^^^^^-- def_span
879 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
883 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
885 // Suggest to take and ignore the arguments with expected_args_length `_`s if
886 // found arguments is empty (assume the user just wants to ignore args in this case).
887 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
888 if found_args.is_empty() && is_closure {
889 let underscores = vec!["_"; expected_args.len()].join(", ");
890 err.span_suggestion_verbose(
893 "consider changing the closure to take and ignore the expected argument{}",
894 pluralize!(expected_args.len())
896 format!("|{}|", underscores),
897 Applicability::MachineApplicable,
901 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
902 if fields.len() == expected_args.len() {
905 .map(|(name, _)| name.to_owned())
906 .collect::<Vec<String>>()
908 err.span_suggestion_verbose(
910 "change the closure to take multiple arguments instead of a single tuple",
911 format!("|{}|", sugg),
912 Applicability::MachineApplicable,
916 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
917 if fields.len() == found_args.len() && is_closure {
922 .map(|arg| match arg {
923 ArgKind::Arg(name, _) => name.to_owned(),
926 .collect::<Vec<String>>()
928 // add type annotations if available
929 if found_args.iter().any(|arg| match arg {
930 ArgKind::Arg(_, ty) => ty != "_",
937 .map(|(_, ty)| ty.to_owned())
938 .collect::<Vec<String>>()
945 err.span_suggestion_verbose(
947 "change the closure to accept a tuple instead of individual arguments",
949 Applicability::MachineApplicable,
959 trait InferCtxtPrivExt<'tcx> {
960 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
961 // `error` occurring implies that `cond` occurs.
962 fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool;
964 fn report_fulfillment_error(
966 error: &FulfillmentError<'tcx>,
967 body_id: Option<hir::BodyId>,
968 fallback_has_occurred: bool,
971 fn report_projection_error(
973 obligation: &PredicateObligation<'tcx>,
974 error: &MismatchedProjectionTypes<'tcx>,
977 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool;
979 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>;
981 fn find_similar_impl_candidates(
983 trait_ref: ty::PolyTraitRef<'tcx>,
984 ) -> Vec<ty::TraitRef<'tcx>>;
986 fn report_similar_impl_candidates(
988 impl_candidates: Vec<ty::TraitRef<'tcx>>,
989 err: &mut DiagnosticBuilder<'_>,
992 /// Gets the parent trait chain start
993 fn get_parent_trait_ref(
995 code: &ObligationCauseCode<'tcx>,
996 ) -> Option<(String, Option<Span>)>;
998 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
999 /// with the same path as `trait_ref`, a help message about
1000 /// a probable version mismatch is added to `err`
1001 fn note_version_mismatch(
1003 err: &mut DiagnosticBuilder<'_>,
1004 trait_ref: &ty::PolyTraitRef<'tcx>,
1007 /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
1010 /// For this to work, `new_self_ty` must have no escaping bound variables.
1011 fn mk_trait_obligation_with_new_self_ty(
1013 param_env: ty::ParamEnv<'tcx>,
1014 trait_ref: &ty::PolyTraitRef<'tcx>,
1015 new_self_ty: Ty<'tcx>,
1016 ) -> PredicateObligation<'tcx>;
1018 fn maybe_report_ambiguity(
1020 obligation: &PredicateObligation<'tcx>,
1021 body_id: Option<hir::BodyId>,
1024 fn predicate_can_apply(
1026 param_env: ty::ParamEnv<'tcx>,
1027 pred: ty::PolyTraitRef<'tcx>,
1030 fn note_obligation_cause(
1032 err: &mut DiagnosticBuilder<'tcx>,
1033 obligation: &PredicateObligation<'tcx>,
1036 fn suggest_unsized_bound_if_applicable(
1038 err: &mut DiagnosticBuilder<'tcx>,
1039 obligation: &PredicateObligation<'tcx>,
1042 fn is_recursive_obligation(
1044 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1045 cause_code: &ObligationCauseCode<'tcx>,
1049 impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> {
1050 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1051 // `error` occurring implies that `cond` occurs.
1052 fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool {
1057 let (cond, error) = match (cond.kind(), error.kind()) {
1058 (ty::PredicateKind::Trait(..), ty::PredicateKind::Trait(error, _)) => (cond, error),
1060 // FIXME: make this work in other cases too.
1065 for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) {
1066 if let ty::PredicateKind::Trait(implication, _) = obligation.predicate.kind() {
1067 let error = error.to_poly_trait_ref();
1068 let implication = implication.to_poly_trait_ref();
1069 // FIXME: I'm just not taking associated types at all here.
1070 // Eventually I'll need to implement param-env-aware
1071 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
1072 let param_env = ty::ParamEnv::empty();
1073 if self.can_sub(param_env, error, implication).is_ok() {
1074 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
1083 fn report_fulfillment_error(
1085 error: &FulfillmentError<'tcx>,
1086 body_id: Option<hir::BodyId>,
1087 fallback_has_occurred: bool,
1089 debug!("report_fulfillment_error({:?})", error);
1091 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
1092 self.report_selection_error(
1095 fallback_has_occurred,
1096 error.points_at_arg_span,
1099 FulfillmentErrorCode::CodeProjectionError(ref e) => {
1100 self.report_projection_error(&error.obligation, e);
1102 FulfillmentErrorCode::CodeAmbiguity => {
1103 self.maybe_report_ambiguity(&error.obligation, body_id);
1105 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
1106 self.report_mismatched_types(
1107 &error.obligation.cause,
1108 expected_found.expected,
1109 expected_found.found,
1114 FulfillmentErrorCode::CodeConstEquateError(ref expected_found, ref err) => {
1115 self.report_mismatched_consts(
1116 &error.obligation.cause,
1117 expected_found.expected,
1118 expected_found.found,
1126 fn report_projection_error(
1128 obligation: &PredicateObligation<'tcx>,
1129 error: &MismatchedProjectionTypes<'tcx>,
1131 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1133 if predicate.references_error() {
1139 let mut err = &error.err;
1140 let mut values = None;
1142 // try to find the mismatched types to report the error with.
1144 // this can fail if the problem was higher-ranked, in which
1145 // cause I have no idea for a good error message.
1146 if let ty::PredicateKind::Projection(ref data) = predicate.kind() {
1147 let mut selcx = SelectionContext::new(self);
1148 let (data, _) = self.replace_bound_vars_with_fresh_vars(
1149 obligation.cause.span,
1150 infer::LateBoundRegionConversionTime::HigherRankedType,
1153 let mut obligations = vec![];
1154 let normalized_ty = super::normalize_projection_type(
1156 obligation.param_env,
1158 obligation.cause.clone(),
1164 "report_projection_error obligation.cause={:?} obligation.param_env={:?}",
1165 obligation.cause, obligation.param_env
1169 "report_projection_error normalized_ty={:?} data.ty={:?}",
1170 normalized_ty, data.ty
1173 let is_normalized_ty_expected = match &obligation.cause.code {
1174 ObligationCauseCode::ItemObligation(_)
1175 | ObligationCauseCode::BindingObligation(_, _)
1176 | ObligationCauseCode::ObjectCastObligation(_) => false,
1180 if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
1181 is_normalized_ty_expected,
1185 values = Some(infer::ValuePairs::Types(ExpectedFound::new(
1186 is_normalized_ty_expected,
1196 let msg = format!("type mismatch resolving `{}`", predicate);
1197 let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg);
1198 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
1200 let mut diag = struct_span_err!(
1202 obligation.cause.span,
1204 "type mismatch resolving `{}`",
1207 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
1208 self.note_obligation_cause(&mut diag, obligation);
1214 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1215 /// returns the fuzzy category of a given type, or None
1216 /// if the type can be equated to any type.
1217 fn type_category(t: Ty<'_>) -> Option<u32> {
1219 ty::Bool => Some(0),
1220 ty::Char => Some(1),
1222 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
1223 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
1224 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1225 ty::Array(..) | ty::Slice(..) => Some(6),
1226 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1227 ty::Dynamic(..) => Some(8),
1228 ty::Closure(..) => Some(9),
1229 ty::Tuple(..) => Some(10),
1230 ty::Projection(..) => Some(11),
1231 ty::Param(..) => Some(12),
1232 ty::Opaque(..) => Some(13),
1233 ty::Never => Some(14),
1234 ty::Adt(adt, ..) => match adt.adt_kind() {
1235 AdtKind::Struct => Some(15),
1236 AdtKind::Union => Some(16),
1237 AdtKind::Enum => Some(17),
1239 ty::Generator(..) => Some(18),
1240 ty::Foreign(..) => Some(19),
1241 ty::GeneratorWitness(..) => Some(20),
1242 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => None,
1246 match (type_category(a), type_category(b)) {
1247 (Some(cat_a), Some(cat_b)) => match (&a.kind, &b.kind) {
1248 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
1249 _ => cat_a == cat_b,
1251 // infer and error can be equated to all types
1256 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
1257 self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
1258 hir::GeneratorKind::Gen => "a generator",
1259 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
1260 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
1261 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
1265 fn find_similar_impl_candidates(
1267 trait_ref: ty::PolyTraitRef<'tcx>,
1268 ) -> Vec<ty::TraitRef<'tcx>> {
1269 let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
1270 let all_impls = self.tcx.all_impls(trait_ref.def_id());
1273 Some(simp) => all_impls
1274 .filter_map(|def_id| {
1275 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
1276 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
1277 if let Some(imp_simp) = imp_simp {
1278 if simp != imp_simp {
1285 None => all_impls.map(|def_id| self.tcx.impl_trait_ref(def_id).unwrap()).collect(),
1289 fn report_similar_impl_candidates(
1291 impl_candidates: Vec<ty::TraitRef<'tcx>>,
1292 err: &mut DiagnosticBuilder<'_>,
1294 if impl_candidates.is_empty() {
1298 let len = impl_candidates.len();
1299 let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 };
1301 let normalize = |candidate| {
1302 self.tcx.infer_ctxt().enter(|ref infcx| {
1303 let normalized = infcx
1304 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
1305 .normalize(candidate)
1308 Some(normalized) => format!("\n {:?}", normalized.value),
1309 None => format!("\n {:?}", candidate),
1314 // Sort impl candidates so that ordering is consistent for UI tests.
1315 let mut normalized_impl_candidates =
1316 impl_candidates.iter().map(normalize).collect::<Vec<String>>();
1318 // Sort before taking the `..end` range,
1319 // because the ordering of `impl_candidates` may not be deterministic:
1320 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
1321 normalized_impl_candidates.sort();
1324 "the following implementations were found:{}{}",
1325 normalized_impl_candidates[..end].join(""),
1326 if len > 5 { format!("\nand {} others", len - 4) } else { String::new() }
1330 /// Gets the parent trait chain start
1331 fn get_parent_trait_ref(
1333 code: &ObligationCauseCode<'tcx>,
1334 ) -> Option<(String, Option<Span>)> {
1336 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1337 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1338 match self.get_parent_trait_ref(&data.parent_code) {
1341 let ty = parent_trait_ref.skip_binder().self_ty();
1343 TyCategory::from_ty(ty).map(|(_, def_id)| self.tcx.def_span(def_id));
1344 Some((ty.to_string(), span))
1352 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1353 /// with the same path as `trait_ref`, a help message about
1354 /// a probable version mismatch is added to `err`
1355 fn note_version_mismatch(
1357 err: &mut DiagnosticBuilder<'_>,
1358 trait_ref: &ty::PolyTraitRef<'tcx>,
1360 let get_trait_impl = |trait_def_id| {
1361 let mut trait_impl = None;
1362 self.tcx.for_each_relevant_impl(trait_def_id, trait_ref.self_ty(), |impl_def_id| {
1363 if trait_impl.is_none() {
1364 trait_impl = Some(impl_def_id);
1369 let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1370 let all_traits = self.tcx.all_traits(LOCAL_CRATE);
1371 let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1373 .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1374 .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1376 for trait_with_same_path in traits_with_same_path {
1377 if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1378 let impl_span = self.tcx.def_span(impl_def_id);
1379 err.span_help(impl_span, "trait impl with same name found");
1380 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1381 let crate_msg = format!(
1382 "perhaps two different versions of crate `{}` are being used?",
1385 err.note(&crate_msg);
1390 fn mk_trait_obligation_with_new_self_ty(
1392 param_env: ty::ParamEnv<'tcx>,
1393 trait_ref: &ty::PolyTraitRef<'tcx>,
1394 new_self_ty: Ty<'tcx>,
1395 ) -> PredicateObligation<'tcx> {
1396 assert!(!new_self_ty.has_escaping_bound_vars());
1398 let trait_ref = trait_ref.map_bound_ref(|tr| ty::TraitRef {
1399 substs: self.tcx.mk_substs_trait(new_self_ty, &tr.substs[1..]),
1404 ObligationCause::dummy(),
1406 trait_ref.without_const().to_predicate(self.tcx),
1410 fn maybe_report_ambiguity(
1412 obligation: &PredicateObligation<'tcx>,
1413 body_id: Option<hir::BodyId>,
1415 // Unable to successfully determine, probably means
1416 // insufficient type information, but could mean
1417 // ambiguous impls. The latter *ought* to be a
1418 // coherence violation, so we don't report it here.
1420 let predicate = self.resolve_vars_if_possible(&obligation.predicate);
1421 let span = obligation.cause.span;
1424 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1425 predicate, obligation, body_id, obligation.cause.code,
1428 // Ambiguity errors are often caused as fallout from earlier
1429 // errors. So just ignore them if this infcx is tainted.
1430 if self.is_tainted_by_errors() {
1434 let mut err = match predicate.kind() {
1435 ty::PredicateKind::Trait(ref data, _) => {
1436 let trait_ref = data.to_poly_trait_ref();
1437 let self_ty = trait_ref.self_ty();
1438 debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref);
1440 if predicate.references_error() {
1443 // Typically, this ambiguity should only happen if
1444 // there are unresolved type inference variables
1445 // (otherwise it would suggest a coherence
1446 // failure). But given #21974 that is not necessarily
1447 // the case -- we can have multiple where clauses that
1448 // are only distinguished by a region, which results
1449 // in an ambiguity even when all types are fully
1450 // known, since we don't dispatch based on region
1453 // This is kind of a hack: it frequently happens that some earlier
1454 // error prevents types from being fully inferred, and then we get
1455 // a bunch of uninteresting errors saying something like "<generic
1456 // #0> doesn't implement Sized". It may even be true that we
1457 // could just skip over all checks where the self-ty is an
1458 // inference variable, but I was afraid that there might be an
1459 // inference variable created, registered as an obligation, and
1460 // then never forced by writeback, and hence by skipping here we'd
1461 // be ignoring the fact that we don't KNOW the type works
1462 // out. Though even that would probably be harmless, given that
1463 // we're only talking about builtin traits, which are known to be
1464 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1465 // avoid inundating the user with unnecessary errors, but we now
1466 // check upstream for type errors and don't add the obligations to
1467 // begin with in those cases.
1472 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1474 self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0282).emit();
1477 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0283);
1478 err.note(&format!("cannot satisfy `{}`", predicate));
1479 if let ObligationCauseCode::ItemObligation(def_id) = obligation.cause.code {
1480 self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
1483 ObligationCauseCode::BindingObligation(ref def_id, _),
1485 (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
1487 let generics = self.tcx.generics_of(*def_id);
1488 if generics.params.iter().any(|p| p.name.as_str() != "Self")
1489 && !snippet.ends_with('>')
1491 // FIXME: To avoid spurious suggestions in functions where type arguments
1492 // where already supplied, we check the snippet to make sure it doesn't
1493 // end with a turbofish. Ideally we would have access to a `PathSegment`
1494 // instead. Otherwise we would produce the following output:
1496 // error[E0283]: type annotations needed
1497 // --> $DIR/issue-54954.rs:3:24
1499 // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
1500 // | ^^^^^^^^^^^^^^^^^^^^^^^^^^
1502 // | cannot infer type
1503 // | help: consider specifying the type argument
1504 // | in the function call:
1505 // | `Tt::const_val::<[i8; 123]>::<T>`
1507 // LL | const fn const_val<T: Sized>() -> usize {
1508 // | - required by this bound in `Tt::const_val`
1510 // = note: cannot satisfy `_: Tt`
1512 err.span_suggestion_verbose(
1513 span.shrink_to_hi(),
1515 "consider specifying the type argument{} in the function call",
1516 pluralize!(generics.params.len()),
1523 .map(|p| p.name.to_string())
1524 .collect::<Vec<String>>()
1527 Applicability::HasPlaceholders,
1534 ty::PredicateKind::WellFormed(ty) => {
1535 // Same hacky approach as above to avoid deluging user
1536 // with error messages.
1537 if ty.references_error() || self.tcx.sess.has_errors() {
1540 self.need_type_info_err(body_id, span, ty, ErrorCode::E0282)
1543 ty::PredicateKind::Subtype(ref data) => {
1544 if data.references_error() || self.tcx.sess.has_errors() {
1545 // no need to overload user in such cases
1548 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1549 // both must be type variables, or the other would've been instantiated
1550 assert!(a.is_ty_var() && b.is_ty_var());
1551 self.need_type_info_err(body_id, span, a, ErrorCode::E0282)
1553 ty::PredicateKind::Projection(ref data) => {
1554 let trait_ref = data.to_poly_trait_ref(self.tcx);
1555 let self_ty = trait_ref.self_ty();
1556 let ty = data.skip_binder().ty;
1557 if predicate.references_error() {
1560 if self_ty.needs_infer() && ty.needs_infer() {
1561 // We do this for the `foo.collect()?` case to produce a suggestion.
1562 let mut err = self.need_type_info_err(body_id, span, self_ty, ErrorCode::E0284);
1563 err.note(&format!("cannot satisfy `{}`", predicate));
1566 let mut err = struct_span_err!(
1570 "type annotations needed: cannot satisfy `{}`",
1573 err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1579 if self.tcx.sess.has_errors() {
1582 let mut err = struct_span_err!(
1586 "type annotations needed: cannot satisfy `{}`",
1589 err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1593 self.note_obligation_cause(&mut err, obligation);
1597 /// Returns `true` if the trait predicate may apply for *some* assignment
1598 /// to the type parameters.
1599 fn predicate_can_apply(
1601 param_env: ty::ParamEnv<'tcx>,
1602 pred: ty::PolyTraitRef<'tcx>,
1604 struct ParamToVarFolder<'a, 'tcx> {
1605 infcx: &'a InferCtxt<'a, 'tcx>,
1606 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
1609 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
1610 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1614 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1615 if let ty::Param(ty::ParamTy { name, .. }) = ty.kind {
1616 let infcx = self.infcx;
1617 self.var_map.entry(ty).or_insert_with(|| {
1618 infcx.next_ty_var(TypeVariableOrigin {
1619 kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
1624 ty.super_fold_with(self)
1630 let mut selcx = SelectionContext::new(self);
1633 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
1635 let cleaned_pred = super::project::normalize(
1638 ObligationCause::dummy(),
1643 let obligation = Obligation::new(
1644 ObligationCause::dummy(),
1646 cleaned_pred.without_const().to_predicate(selcx.tcx()),
1649 self.predicate_may_hold(&obligation)
1653 fn note_obligation_cause(
1655 err: &mut DiagnosticBuilder<'tcx>,
1656 obligation: &PredicateObligation<'tcx>,
1658 // First, attempt to add note to this error with an async-await-specific
1659 // message, and fall back to regular note otherwise.
1660 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
1661 self.note_obligation_cause_code(
1663 &obligation.predicate,
1664 &obligation.cause.code,
1667 self.suggest_unsized_bound_if_applicable(err, obligation);
1671 fn suggest_unsized_bound_if_applicable(
1673 err: &mut DiagnosticBuilder<'tcx>,
1674 obligation: &PredicateObligation<'tcx>,
1677 ty::PredicateKind::Trait(pred, _),
1678 ObligationCauseCode::BindingObligation(item_def_id, span),
1679 ) = (obligation.predicate.kind(), &obligation.cause.code)
1681 if let (Some(generics), true) = (
1682 self.tcx.hir().get_if_local(*item_def_id).as_ref().and_then(|n| n.generics()),
1683 Some(pred.def_id()) == self.tcx.lang_items().sized_trait(),
1685 for param in generics.params {
1686 if param.span == *span
1687 && !param.bounds.iter().any(|bound| {
1688 bound.trait_ref().and_then(|trait_ref| trait_ref.trait_def_id())
1689 == self.tcx.lang_items().sized_trait()
1692 let (span, separator) = match param.bounds {
1693 [] => (span.shrink_to_hi(), ":"),
1694 [.., bound] => (bound.span().shrink_to_hi(), " +"),
1696 err.span_suggestion_verbose(
1698 "consider relaxing the implicit `Sized` restriction",
1699 format!("{} ?Sized", separator),
1700 Applicability::MachineApplicable,
1709 fn is_recursive_obligation(
1711 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1712 cause_code: &ObligationCauseCode<'tcx>,
1714 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1715 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1717 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1725 pub fn recursive_type_with_infinite_size_error(
1728 ) -> DiagnosticBuilder<'tcx> {
1729 assert!(type_def_id.is_local());
1730 let span = tcx.hir().span_if_local(type_def_id).unwrap();
1731 let span = tcx.sess.source_map().guess_head_span(span);
1732 let mut err = struct_span_err!(
1736 "recursive type `{}` has infinite size",
1737 tcx.def_path_str(type_def_id)
1739 err.span_label(span, "recursive type has infinite size");
1741 "insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1742 at some point to make `{}` representable",
1743 tcx.def_path_str(type_def_id)
1748 /// Summarizes information
1751 /// An argument of non-tuple type. Parameters are (name, ty)
1752 Arg(String, String),
1754 /// An argument of tuple type. For a "found" argument, the span is
1755 /// the locationo in the source of the pattern. For a "expected"
1756 /// argument, it will be None. The vector is a list of (name, ty)
1757 /// strings for the components of the tuple.
1758 Tuple(Option<Span>, Vec<(String, String)>),
1762 fn empty() -> ArgKind {
1763 ArgKind::Arg("_".to_owned(), "_".to_owned())
1766 /// Creates an `ArgKind` from the expected type of an
1767 /// argument. It has no name (`_`) and an optional source span.
1768 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
1770 ty::Tuple(ref tys) => ArgKind::Tuple(
1772 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
1774 _ => ArgKind::Arg("_".to_owned(), t.to_string()),