1 pub mod on_unimplemented;
5 EvaluationResult, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes,
6 Obligation, ObligationCause, ObligationCauseCode, OnUnimplementedDirective,
7 OnUnimplementedNote, OutputTypeParameterMismatch, Overflow, PredicateObligation,
8 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;
18 use rustc_hir::intravisit::Visitor;
19 use rustc_hir::GenericParam;
22 use rustc_middle::thir::abstract_const::NotConstEvaluatable;
23 use rustc_middle::ty::error::ExpectedFound;
24 use rustc_middle::ty::fast_reject::{self, SimplifyParams, StripReferences};
25 use rustc_middle::ty::fold::TypeFolder;
26 use rustc_middle::ty::{
27 self, AdtKind, SubtypePredicate, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable,
29 use rustc_session::DiagnosticMessageId;
30 use rustc_span::symbol::{kw, sym};
31 use rustc_span::{ExpnKind, MultiSpan, Span, DUMMY_SP};
35 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
36 use crate::traits::query::normalize::AtExt as _;
37 use crate::traits::specialize::to_pretty_impl_header;
38 use on_unimplemented::InferCtxtExt as _;
39 use suggestions::InferCtxtExt as _;
41 pub use rustc_infer::traits::error_reporting::*;
43 pub trait InferCtxtExt<'tcx> {
44 fn report_fulfillment_errors(
46 errors: &[FulfillmentError<'tcx>],
47 body_id: Option<hir::BodyId>,
48 fallback_has_occurred: bool,
51 fn report_overflow_error<T>(
53 obligation: &Obligation<'tcx, T>,
54 suggest_increasing_limit: bool,
57 T: fmt::Display + TypeFoldable<'tcx>;
59 fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !;
61 /// The `root_obligation` parameter should be the `root_obligation` field
62 /// from a `FulfillmentError`. If no `FulfillmentError` is available,
63 /// then it should be the same as `obligation`.
64 fn report_selection_error(
66 obligation: PredicateObligation<'tcx>,
67 root_obligation: &PredicateObligation<'tcx>,
68 error: &SelectionError<'tcx>,
69 fallback_has_occurred: bool,
72 /// Given some node representing a fn-like thing in the HIR map,
73 /// returns a span and `ArgKind` information that describes the
74 /// arguments it expects. This can be supplied to
75 /// `report_arg_count_mismatch`.
76 fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)>;
78 /// Reports an error when the number of arguments needed by a
79 /// trait match doesn't match the number that the expression
81 fn report_arg_count_mismatch(
84 found_span: Option<Span>,
85 expected_args: Vec<ArgKind>,
86 found_args: Vec<ArgKind>,
88 ) -> DiagnosticBuilder<'tcx>;
91 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
92 fn report_fulfillment_errors(
94 errors: &[FulfillmentError<'tcx>],
95 body_id: Option<hir::BodyId>,
96 fallback_has_occurred: bool,
99 struct ErrorDescriptor<'tcx> {
100 predicate: ty::Predicate<'tcx>,
101 index: Option<usize>, // None if this is an old error
104 let mut error_map: FxHashMap<_, Vec<_>> = self
105 .reported_trait_errors
108 .map(|(&span, predicates)| {
113 .map(|&predicate| ErrorDescriptor { predicate, index: None })
119 for (index, error) in errors.iter().enumerate() {
120 // We want to ignore desugarings here: spans are equivalent even
121 // if one is the result of a desugaring and the other is not.
122 let mut span = error.obligation.cause.span;
123 let expn_data = span.ctxt().outer_expn_data();
124 if let ExpnKind::Desugaring(_) = expn_data.kind {
125 span = expn_data.call_site;
128 error_map.entry(span).or_default().push(ErrorDescriptor {
129 predicate: error.obligation.predicate,
133 self.reported_trait_errors
137 .push(error.obligation.predicate);
140 // We do this in 2 passes because we want to display errors in order, though
141 // maybe it *is* better to sort errors by span or something.
142 let mut is_suppressed = vec![false; errors.len()];
143 for (_, error_set) in error_map.iter() {
144 // We want to suppress "duplicate" errors with the same span.
145 for error in error_set {
146 if let Some(index) = error.index {
147 // Suppress errors that are either:
148 // 1) strictly implied by another error.
149 // 2) implied by an error with a smaller index.
150 for error2 in error_set {
151 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
152 // Avoid errors being suppressed by already-suppressed
153 // errors, to prevent all errors from being suppressed
158 if self.error_implies(error2.predicate, error.predicate)
159 && !(error2.index >= error.index
160 && self.error_implies(error.predicate, error2.predicate))
162 info!("skipping {:?} (implied by {:?})", error, error2);
163 is_suppressed[index] = true;
171 for (error, suppressed) in iter::zip(errors, is_suppressed) {
173 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
178 /// Reports that an overflow has occurred and halts compilation. We
179 /// halt compilation unconditionally because it is important that
180 /// overflows never be masked -- they basically represent computations
181 /// whose result could not be truly determined and thus we can't say
182 /// if the program type checks or not -- and they are unusual
183 /// occurrences in any case.
184 fn report_overflow_error<T>(
186 obligation: &Obligation<'tcx, T>,
187 suggest_increasing_limit: bool,
190 T: fmt::Display + TypeFoldable<'tcx>,
192 let predicate = self.resolve_vars_if_possible(obligation.predicate.clone());
193 let mut err = struct_span_err!(
195 obligation.cause.span,
197 "overflow evaluating the requirement `{}`",
201 if suggest_increasing_limit {
202 self.suggest_new_overflow_limit(&mut err);
205 self.note_obligation_cause_code(
207 &obligation.predicate,
208 obligation.param_env,
209 obligation.cause.code(),
211 &mut Default::default(),
215 self.tcx.sess.abort_if_errors();
219 /// Reports that a cycle was detected which led to overflow and halts
220 /// compilation. This is equivalent to `report_overflow_error` except
221 /// that we can give a more helpful error message (and, in particular,
222 /// we do not suggest increasing the overflow limit, which is not
224 fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
225 let cycle = self.resolve_vars_if_possible(cycle.to_owned());
226 assert!(!cycle.is_empty());
228 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
230 // The 'deepest' obligation is most likely to have a useful
232 self.report_overflow_error(cycle.iter().max_by_key(|p| p.recursion_depth).unwrap(), false);
235 fn report_selection_error(
237 mut obligation: PredicateObligation<'tcx>,
238 root_obligation: &PredicateObligation<'tcx>,
239 error: &SelectionError<'tcx>,
240 fallback_has_occurred: bool,
243 let mut span = obligation.cause.span;
245 let mut err = match *error {
246 SelectionError::Ambiguous(ref impls) => {
247 let mut err = self.tcx.sess.struct_span_err(
248 obligation.cause.span,
249 &format!("multiple applicable `impl`s for `{}`", obligation.predicate),
251 self.annotate_source_of_ambiguity(&mut err, impls, obligation.predicate);
255 SelectionError::Unimplemented => {
256 // If this obligation was generated as a result of well-formedness checking, see if we
257 // can get a better error message by performing HIR-based well-formedness checking.
258 if let ObligationCauseCode::WellFormed(Some(wf_loc)) =
259 root_obligation.cause.code().peel_derives()
261 if let Some(cause) = self
263 .diagnostic_hir_wf_check((tcx.erase_regions(obligation.predicate), *wf_loc))
265 obligation.cause = cause;
266 span = obligation.cause.span;
269 if let ObligationCauseCode::CompareImplMethodObligation {
273 | ObligationCauseCode::CompareImplTypeObligation {
276 } = *obligation.cause.code()
278 self.report_extra_impl_obligation(
282 &format!("`{}`", obligation.predicate),
288 let bound_predicate = obligation.predicate.kind();
289 match bound_predicate.skip_binder() {
290 ty::PredicateKind::Trait(trait_predicate) => {
291 let trait_predicate = bound_predicate.rebind(trait_predicate);
292 let mut trait_predicate = self.resolve_vars_if_possible(trait_predicate);
294 trait_predicate.remap_constness_diag(obligation.param_env);
295 let predicate_is_const = ty::BoundConstness::ConstIfConst
296 == trait_predicate.skip_binder().constness;
298 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
301 let trait_ref = trait_predicate.to_poly_trait_ref();
302 let (post_message, pre_message, type_def) = self
303 .get_parent_trait_ref(obligation.cause.code())
306 format!(" in `{}`", t),
307 format!("within `{}`, ", t),
308 s.map(|s| (format!("within this `{}`", t), s)),
311 .unwrap_or_default();
313 let OnUnimplementedNote { message, label, note, enclosing_scope } =
314 self.on_unimplemented_note(trait_ref, &obligation);
315 let have_alt_message = message.is_some() || label.is_some();
316 let is_try_conversion = self.is_try_conversion(span, trait_ref.def_id());
318 { Some(trait_ref.def_id()) == self.tcx.lang_items().unsize_trait() };
319 let (message, note) = if is_try_conversion {
322 "`?` couldn't convert the error to `{}`",
323 trait_ref.skip_binder().self_ty(),
326 "the question mark operation (`?`) implicitly performs a \
327 conversion on the error value using the `From` trait"
335 let mut err = struct_span_err!(
340 (!predicate_is_const).then(|| message).flatten().unwrap_or_else(
342 "the trait bound `{}` is not satisfied{}",
343 trait_predicate, post_message,
348 if is_try_conversion {
349 let none_error = self
351 .get_diagnostic_item(sym::none_error)
352 .map(|def_id| tcx.type_of(def_id));
353 let should_convert_option_to_result =
354 Some(trait_ref.skip_binder().substs.type_at(1)) == none_error;
355 let should_convert_result_to_option =
356 Some(trait_ref.self_ty().skip_binder()) == none_error;
357 if should_convert_option_to_result {
358 err.span_suggestion_verbose(
360 "consider converting the `Option<T>` into a `Result<T, _>` \
361 using `Option::ok_or` or `Option::ok_or_else`",
362 ".ok_or_else(|| /* error value */)".to_string(),
363 Applicability::HasPlaceholders,
365 } else if should_convert_result_to_option {
366 err.span_suggestion_verbose(
368 "consider converting the `Result<T, _>` into an `Option<T>` \
371 Applicability::MachineApplicable,
374 if let Some(ret_span) = self.return_type_span(&obligation) {
378 "expected `{}` because of this",
379 trait_ref.skip_binder().self_ty()
385 let explanation = if let ObligationCauseCode::MainFunctionType =
386 obligation.cause.code()
388 "consider using `()`, or a `Result`".to_owned()
391 "{}the trait `{}` is not implemented for `{}`",
393 trait_predicate.print_modifiers_and_trait_path(),
394 trait_ref.skip_binder().self_ty(),
398 if self.suggest_add_reference_to_arg(
404 self.note_obligation_cause(&mut err, &obligation);
408 if let Some(ref s) = label {
409 // If it has a custom `#[rustc_on_unimplemented]`
410 // error message, let's display it as the label!
411 err.span_label(span, s.as_str());
412 if !matches!(trait_ref.skip_binder().self_ty().kind(), ty::Param(_)) {
413 // When the self type is a type param We don't need to "the trait
414 // `std::marker::Sized` is not implemented for `T`" as we will point
415 // at the type param with a label to suggest constraining it.
416 err.help(&explanation);
419 err.span_label(span, explanation);
421 if let Some((msg, span)) = type_def {
422 err.span_label(span, &msg);
424 if let Some(ref s) = note {
425 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
426 err.note(s.as_str());
428 if let Some(ref s) = enclosing_scope {
431 .opt_local_def_id(obligation.cause.body_id)
433 tcx.hir().body_owner_def_id(hir::BodyId {
434 hir_id: obligation.cause.body_id,
438 let enclosing_scope_span =
439 tcx.hir().span_with_body(tcx.hir().local_def_id_to_hir_id(body));
441 err.span_label(enclosing_scope_span, s.as_str());
444 self.suggest_dereferences(&obligation, &mut err, trait_predicate);
445 self.suggest_fn_call(&obligation, &mut err, trait_predicate);
446 self.suggest_remove_reference(&obligation, &mut err, trait_predicate);
447 self.suggest_semicolon_removal(
453 self.note_version_mismatch(&mut err, &trait_ref);
454 self.suggest_remove_await(&obligation, &mut err);
456 if Some(trait_ref.def_id()) == tcx.lang_items().try_trait() {
457 self.suggest_await_before_try(
465 if self.suggest_impl_trait(&mut err, span, &obligation, trait_predicate) {
471 // If the obligation failed due to a missing implementation of the
472 // `Unsize` trait, give a pointer to why that might be the case
474 "all implementations of `Unsize` are provided \
475 automatically by the compiler, see \
476 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
477 for more information",
482 self.tcx.lang_items().fn_trait(),
483 self.tcx.lang_items().fn_mut_trait(),
484 self.tcx.lang_items().fn_once_trait(),
486 .contains(&Some(trait_ref.def_id()));
487 let is_target_feature_fn = if let ty::FnDef(def_id, _) =
488 *trait_ref.skip_binder().self_ty().kind()
490 !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
494 if is_fn_trait && is_target_feature_fn {
496 "`#[target_feature]` functions do not implement the `Fn` traits",
500 // Try to report a help message
501 if !trait_ref.has_infer_types_or_consts()
502 && self.predicate_can_apply(obligation.param_env, trait_ref)
504 // If a where-clause may be useful, remind the
505 // user that they can add it.
507 // don't display an on-unimplemented note, as
508 // these notes will often be of the form
509 // "the type `T` can't be frobnicated"
510 // which is somewhat confusing.
511 self.suggest_restricting_param_bound(
514 obligation.cause.body_id,
516 } else if !have_alt_message {
517 // Can't show anything else useful, try to find similar impls.
518 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
519 self.report_similar_impl_candidates(impl_candidates, &mut err);
522 // Changing mutability doesn't make a difference to whether we have
523 // an `Unsize` impl (Fixes ICE in #71036)
525 self.suggest_change_mut(&obligation, &mut err, trait_predicate);
528 // If this error is due to `!: Trait` not implemented but `(): Trait` is
529 // implemented, and fallback has occurred, then it could be due to a
530 // variable that used to fallback to `()` now falling back to `!`. Issue a
531 // note informing about the change in behaviour.
532 if trait_predicate.skip_binder().self_ty().is_never()
533 && fallback_has_occurred
535 let predicate = trait_predicate.map_bound(|mut trait_pred| {
536 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
538 &trait_pred.trait_ref.substs[1..],
542 let unit_obligation = obligation.with(predicate.to_predicate(tcx));
543 if self.predicate_may_hold(&unit_obligation) {
544 err.note("this trait is implemented for `()`");
546 "this error might have been caused by changes to \
547 Rust's type-inference algorithm (see issue #48950 \
548 <https://github.com/rust-lang/rust/issues/48950> \
549 for more information)",
551 err.help("did you intend to use the type `()` here instead?");
555 // Return early if the trait is Debug or Display and the invocation
556 // originates within a standard library macro, because the output
557 // is otherwise overwhelming and unhelpful (see #85844 for an
561 match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
562 Some(macro_def_id) => {
563 let crate_name = tcx.crate_name(macro_def_id.krate);
564 crate_name == sym::std || crate_name == sym::core
571 self.tcx.get_diagnostic_name(trait_ref.def_id()),
572 Some(sym::Debug | sym::Display)
582 ty::PredicateKind::Subtype(predicate) => {
583 // Errors for Subtype predicates show up as
584 // `FulfillmentErrorCode::CodeSubtypeError`,
585 // not selection error.
586 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
589 ty::PredicateKind::Coerce(predicate) => {
590 // Errors for Coerce predicates show up as
591 // `FulfillmentErrorCode::CodeSubtypeError`,
592 // not selection error.
593 span_bug!(span, "coerce requirement gave wrong error: `{:?}`", predicate)
596 ty::PredicateKind::RegionOutlives(predicate) => {
597 let predicate = bound_predicate.rebind(predicate);
598 let predicate = self.resolve_vars_if_possible(predicate);
600 .region_outlives_predicate(&obligation.cause, predicate)
607 "the requirement `{}` is not satisfied (`{}`)",
613 ty::PredicateKind::Projection(..) | ty::PredicateKind::TypeOutlives(..) => {
614 let predicate = self.resolve_vars_if_possible(obligation.predicate);
619 "the requirement `{}` is not satisfied",
624 ty::PredicateKind::ObjectSafe(trait_def_id) => {
625 let violations = self.tcx.object_safety_violations(trait_def_id);
626 report_object_safety_error(self.tcx, span, trait_def_id, violations)
629 ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
630 let found_kind = self.closure_kind(closure_substs).unwrap();
632 self.tcx.sess.source_map().guess_head_span(
633 self.tcx.hir().span_if_local(closure_def_id).unwrap(),
635 let mut err = struct_span_err!(
639 "expected a closure that implements the `{}` trait, \
640 but this closure only implements `{}`",
647 format!("this closure implements `{}`, not `{}`", found_kind, kind),
650 obligation.cause.span,
651 format!("the requirement to implement `{}` derives from here", kind),
654 // Additional context information explaining why the closure only implements
655 // a particular trait.
656 if let Some(typeck_results) = self.in_progress_typeck_results {
660 .local_def_id_to_hir_id(closure_def_id.expect_local());
661 let typeck_results = typeck_results.borrow();
662 match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
663 (ty::ClosureKind::FnOnce, Some((span, place))) => {
667 "closure is `FnOnce` because it moves the \
668 variable `{}` out of its environment",
669 ty::place_to_string_for_capture(tcx, place)
673 (ty::ClosureKind::FnMut, Some((span, place))) => {
677 "closure is `FnMut` because it mutates the \
679 ty::place_to_string_for_capture(tcx, place)
691 ty::PredicateKind::WellFormed(ty) => {
692 if !self.tcx.sess.opts.debugging_opts.chalk {
693 // WF predicates cannot themselves make
694 // errors. They can only block due to
695 // ambiguity; otherwise, they always
696 // degenerate into other obligations
698 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
700 // FIXME: we'll need a better message which takes into account
701 // which bounds actually failed to hold.
702 self.tcx.sess.struct_span_err(
704 &format!("the type `{}` is not well-formed (chalk)", ty),
709 ty::PredicateKind::ConstEvaluatable(..) => {
710 // Errors for `ConstEvaluatable` predicates show up as
711 // `SelectionError::ConstEvalFailure`,
712 // not `Unimplemented`.
715 "const-evaluatable requirement gave wrong error: `{:?}`",
720 ty::PredicateKind::ConstEquate(..) => {
721 // Errors for `ConstEquate` predicates show up as
722 // `SelectionError::ConstEvalFailure`,
723 // not `Unimplemented`.
726 "const-equate requirement gave wrong error: `{:?}`",
731 ty::PredicateKind::TypeWellFormedFromEnv(..) => span_bug!(
733 "TypeWellFormedFromEnv predicate should only exist in the environment"
738 OutputTypeParameterMismatch(found_trait_ref, expected_trait_ref, _) => {
739 let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
740 let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
742 if expected_trait_ref.self_ty().references_error() {
746 let found_trait_ty = match found_trait_ref.self_ty().no_bound_vars() {
751 let found_did = match *found_trait_ty.kind() {
755 | ty::Generator(did, ..) => Some(did),
756 ty::Adt(def, _) => Some(def.did),
760 let found_span = found_did
761 .and_then(|did| self.tcx.hir().span_if_local(did))
762 .map(|sp| self.tcx.sess.source_map().guess_head_span(sp)); // the sp could be an fn def
764 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
765 // We check closures twice, with obligations flowing in different directions,
766 // but we want to complain about them only once.
770 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
772 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind() {
773 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
774 _ => vec![ArgKind::empty()],
777 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
778 let expected = match expected_ty.kind() {
779 ty::Tuple(ref tys) => tys
781 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span)))
783 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
786 if found.len() == expected.len() {
787 self.report_closure_arg_mismatch(
794 let (closure_span, found) = found_did
796 let node = self.tcx.hir().get_if_local(did)?;
797 let (found_span, found) = self.get_fn_like_arguments(node)?;
798 Some((Some(found_span), found))
800 .unwrap_or((found_span, found));
802 self.report_arg_count_mismatch(
807 found_trait_ty.is_closure(),
812 TraitNotObjectSafe(did) => {
813 let violations = self.tcx.object_safety_violations(did);
814 report_object_safety_error(self.tcx, span, did, violations)
817 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
819 "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
822 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
823 if !self.tcx.features().generic_const_exprs {
824 let mut err = self.tcx.sess.struct_span_err(
826 "constant expression depends on a generic parameter",
828 // FIXME(const_generics): we should suggest to the user how they can resolve this
829 // issue. However, this is currently not actually possible
830 // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
832 // Note that with `feature(generic_const_exprs)` this case should not
834 err.note("this may fail depending on what value the parameter takes");
839 match obligation.predicate.kind().skip_binder() {
840 ty::PredicateKind::ConstEvaluatable(uv) => {
842 self.tcx.sess.struct_span_err(span, "unconstrained generic constant");
843 let const_span = self.tcx.def_span(uv.def.did);
844 match self.tcx.sess.source_map().span_to_snippet(const_span) {
845 Ok(snippet) => err.help(&format!(
846 "try adding a `where` bound using this expression: `where [(); {}]:`",
849 _ => err.help("consider adding a `where` bound using this expression"),
856 "unexpected non-ConstEvaluatable predicate, this should not be reachable"
862 // Already reported in the query.
863 SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(ErrorReported)) => {
864 // FIXME(eddyb) remove this once `ErrorReported` becomes a proof token.
865 self.tcx.sess.delay_span_bug(span, "`ErrorReported` without an error");
870 bug!("overflow should be handled before the `report_selection_error` path");
872 SelectionError::ErrorReporting => {
873 bug!("ErrorReporting Overflow should not reach `report_selection_err` call")
877 self.note_obligation_cause(&mut err, &obligation);
878 self.point_at_returns_when_relevant(&mut err, &obligation);
883 /// Given some node representing a fn-like thing in the HIR map,
884 /// returns a span and `ArgKind` information that describes the
885 /// arguments it expects. This can be supplied to
886 /// `report_arg_count_mismatch`.
887 fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)> {
888 let sm = self.tcx.sess.source_map();
889 let hir = self.tcx.hir();
891 Node::Expr(&hir::Expr {
892 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
895 sm.guess_head_span(span),
900 if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
907 sm.span_to_snippet(pat.span)
909 .map(|snippet| (snippet, "_".to_owned()))
911 .collect::<Option<Vec<_>>>()?,
914 let name = sm.span_to_snippet(arg.pat.span).ok()?;
915 Some(ArgKind::Arg(name, "_".to_owned()))
918 .collect::<Option<Vec<ArgKind>>>()?,
920 Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
921 | Node::ImplItem(&hir::ImplItem {
923 kind: hir::ImplItemKind::Fn(ref sig, _),
926 | Node::TraitItem(&hir::TraitItem {
928 kind: hir::TraitItemKind::Fn(ref sig, _),
931 sm.guess_head_span(span),
935 .map(|arg| match arg.kind {
936 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
938 vec![("_".to_owned(), "_".to_owned()); tys.len()],
940 _ => ArgKind::empty(),
942 .collect::<Vec<ArgKind>>(),
944 Node::Ctor(ref variant_data) => {
945 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id));
946 let span = sm.guess_head_span(span);
947 (span, vec![ArgKind::empty(); variant_data.fields().len()])
949 _ => panic!("non-FnLike node found: {:?}", node),
953 /// Reports an error when the number of arguments needed by a
954 /// trait match doesn't match the number that the expression
956 fn report_arg_count_mismatch(
959 found_span: Option<Span>,
960 expected_args: Vec<ArgKind>,
961 found_args: Vec<ArgKind>,
963 ) -> DiagnosticBuilder<'tcx> {
964 let kind = if is_closure { "closure" } else { "function" };
966 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
967 let arg_length = arguments.len();
968 let distinct = matches!(other, &[ArgKind::Tuple(..)]);
969 match (arg_length, arguments.get(0)) {
970 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
971 format!("a single {}-tuple as argument", fields.len())
976 if distinct && arg_length > 1 { "distinct " } else { "" },
977 pluralize!(arg_length)
982 let expected_str = args_str(&expected_args, &found_args);
983 let found_str = args_str(&found_args, &expected_args);
985 let mut err = struct_span_err!(
989 "{} is expected to take {}, but it takes {}",
995 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
997 if let Some(found_span) = found_span {
998 err.span_label(found_span, format!("takes {}", found_str));
1001 // ^^^^^^^^-- def_span
1005 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
1009 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
1011 // Suggest to take and ignore the arguments with expected_args_length `_`s if
1012 // found arguments is empty (assume the user just wants to ignore args in this case).
1013 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
1014 if found_args.is_empty() && is_closure {
1015 let underscores = vec!["_"; expected_args.len()].join(", ");
1016 err.span_suggestion_verbose(
1019 "consider changing the closure to take and ignore the expected argument{}",
1020 pluralize!(expected_args.len())
1022 format!("|{}|", underscores),
1023 Applicability::MachineApplicable,
1027 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1028 if fields.len() == expected_args.len() {
1031 .map(|(name, _)| name.to_owned())
1032 .collect::<Vec<String>>()
1034 err.span_suggestion_verbose(
1036 "change the closure to take multiple arguments instead of a single tuple",
1037 format!("|{}|", sugg),
1038 Applicability::MachineApplicable,
1042 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1043 if fields.len() == found_args.len() && is_closure {
1048 .map(|arg| match arg {
1049 ArgKind::Arg(name, _) => name.to_owned(),
1050 _ => "_".to_owned(),
1052 .collect::<Vec<String>>()
1054 // add type annotations if available
1055 if found_args.iter().any(|arg| match arg {
1056 ArgKind::Arg(_, ty) => ty != "_",
1063 .map(|(_, ty)| ty.to_owned())
1064 .collect::<Vec<String>>()
1071 err.span_suggestion_verbose(
1073 "change the closure to accept a tuple instead of individual arguments",
1075 Applicability::MachineApplicable,
1085 trait InferCtxtPrivExt<'hir, 'tcx> {
1086 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1087 // `error` occurring implies that `cond` occurs.
1088 fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool;
1090 fn report_fulfillment_error(
1092 error: &FulfillmentError<'tcx>,
1093 body_id: Option<hir::BodyId>,
1094 fallback_has_occurred: bool,
1097 fn report_projection_error(
1099 obligation: &PredicateObligation<'tcx>,
1100 error: &MismatchedProjectionTypes<'tcx>,
1103 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool;
1105 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>;
1107 fn find_similar_impl_candidates(
1109 trait_ref: ty::PolyTraitRef<'tcx>,
1110 ) -> Vec<ty::TraitRef<'tcx>>;
1112 fn report_similar_impl_candidates(
1114 impl_candidates: Vec<ty::TraitRef<'tcx>>,
1115 err: &mut DiagnosticBuilder<'_>,
1118 /// Gets the parent trait chain start
1119 fn get_parent_trait_ref(
1121 code: &ObligationCauseCode<'tcx>,
1122 ) -> Option<(String, Option<Span>)>;
1124 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1125 /// with the same path as `trait_ref`, a help message about
1126 /// a probable version mismatch is added to `err`
1127 fn note_version_mismatch(
1129 err: &mut DiagnosticBuilder<'_>,
1130 trait_ref: &ty::PolyTraitRef<'tcx>,
1133 /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
1136 /// For this to work, `new_self_ty` must have no escaping bound variables.
1137 fn mk_trait_obligation_with_new_self_ty(
1139 param_env: ty::ParamEnv<'tcx>,
1140 trait_ref: ty::PolyTraitPredicate<'tcx>,
1141 new_self_ty: Ty<'tcx>,
1142 ) -> PredicateObligation<'tcx>;
1144 fn maybe_report_ambiguity(
1146 obligation: &PredicateObligation<'tcx>,
1147 body_id: Option<hir::BodyId>,
1150 fn predicate_can_apply(
1152 param_env: ty::ParamEnv<'tcx>,
1153 pred: ty::PolyTraitRef<'tcx>,
1156 fn note_obligation_cause(
1158 err: &mut DiagnosticBuilder<'tcx>,
1159 obligation: &PredicateObligation<'tcx>,
1162 fn suggest_unsized_bound_if_applicable(
1164 err: &mut DiagnosticBuilder<'tcx>,
1165 obligation: &PredicateObligation<'tcx>,
1168 fn annotate_source_of_ambiguity(
1170 err: &mut DiagnosticBuilder<'tcx>,
1172 predicate: ty::Predicate<'tcx>,
1175 fn maybe_suggest_unsized_generics(
1177 err: &mut DiagnosticBuilder<'tcx>,
1182 fn maybe_indirection_for_unsized(
1184 err: &mut DiagnosticBuilder<'tcx>,
1185 item: &'hir Item<'hir>,
1186 param: &'hir GenericParam<'hir>,
1189 fn is_recursive_obligation(
1191 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1192 cause_code: &ObligationCauseCode<'tcx>,
1196 impl<'a, 'tcx> InferCtxtPrivExt<'a, 'tcx> for InferCtxt<'a, 'tcx> {
1197 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1198 // `error` occurring implies that `cond` occurs.
1199 fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool {
1204 // FIXME: It should be possible to deal with `ForAll` in a cleaner way.
1205 let bound_error = error.kind();
1206 let (cond, error) = match (cond.kind().skip_binder(), bound_error.skip_binder()) {
1207 (ty::PredicateKind::Trait(..), ty::PredicateKind::Trait(error)) => {
1208 (cond, bound_error.rebind(error))
1211 // FIXME: make this work in other cases too.
1216 for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) {
1217 let bound_predicate = obligation.predicate.kind();
1218 if let ty::PredicateKind::Trait(implication) = bound_predicate.skip_binder() {
1219 let error = error.to_poly_trait_ref();
1220 let implication = bound_predicate.rebind(implication.trait_ref);
1221 // FIXME: I'm just not taking associated types at all here.
1222 // Eventually I'll need to implement param-env-aware
1223 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
1224 let param_env = ty::ParamEnv::empty();
1225 if self.can_sub(param_env, error, implication).is_ok() {
1226 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
1235 #[instrument(skip(self), level = "debug")]
1236 fn report_fulfillment_error(
1238 error: &FulfillmentError<'tcx>,
1239 body_id: Option<hir::BodyId>,
1240 fallback_has_occurred: bool,
1243 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
1244 self.report_selection_error(
1245 error.obligation.clone(),
1246 &error.root_obligation,
1248 fallback_has_occurred,
1251 FulfillmentErrorCode::CodeProjectionError(ref e) => {
1252 self.report_projection_error(&error.obligation, e);
1254 FulfillmentErrorCode::CodeAmbiguity => {
1255 self.maybe_report_ambiguity(&error.obligation, body_id);
1257 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
1258 self.report_mismatched_types(
1259 &error.obligation.cause,
1260 expected_found.expected,
1261 expected_found.found,
1266 FulfillmentErrorCode::CodeConstEquateError(ref expected_found, ref err) => {
1267 self.report_mismatched_consts(
1268 &error.obligation.cause,
1269 expected_found.expected,
1270 expected_found.found,
1278 fn report_projection_error(
1280 obligation: &PredicateObligation<'tcx>,
1281 error: &MismatchedProjectionTypes<'tcx>,
1283 let predicate = self.resolve_vars_if_possible(obligation.predicate);
1285 if predicate.references_error() {
1291 let mut err = &error.err;
1292 let mut values = None;
1294 // try to find the mismatched types to report the error with.
1296 // this can fail if the problem was higher-ranked, in which
1297 // cause I have no idea for a good error message.
1298 let bound_predicate = predicate.kind();
1299 if let ty::PredicateKind::Projection(data) = bound_predicate.skip_binder() {
1300 let mut selcx = SelectionContext::new(self);
1301 let (data, _) = self.replace_bound_vars_with_fresh_vars(
1302 obligation.cause.span,
1303 infer::LateBoundRegionConversionTime::HigherRankedType,
1304 bound_predicate.rebind(data),
1306 let mut obligations = vec![];
1307 let normalized_ty = super::normalize_projection_type(
1309 obligation.param_env,
1311 obligation.cause.clone(),
1317 "report_projection_error obligation.cause={:?} obligation.param_env={:?}",
1318 obligation.cause, obligation.param_env
1322 "report_projection_error normalized_ty={:?} data.ty={:?}",
1323 normalized_ty, data.term,
1326 let is_normalized_ty_expected = !matches!(
1327 obligation.cause.code().peel_derives(),
1328 ObligationCauseCode::ItemObligation(_)
1329 | ObligationCauseCode::BindingObligation(_, _)
1330 | ObligationCauseCode::ObjectCastObligation(_)
1331 | ObligationCauseCode::OpaqueType
1333 // FIXME(associated_const_equality): Handle Consts here
1334 let data_ty = data.term.ty().unwrap();
1335 if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
1336 is_normalized_ty_expected,
1340 values = Some(infer::ValuePairs::Types(ExpectedFound::new(
1341 is_normalized_ty_expected,
1351 let msg = format!("type mismatch resolving `{}`", predicate);
1352 let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg);
1353 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
1355 let mut diag = struct_span_err!(
1357 obligation.cause.span,
1359 "type mismatch resolving `{}`",
1362 let secondary_span = match predicate.kind().skip_binder() {
1363 ty::PredicateKind::Projection(proj) => self
1365 .opt_associated_item(proj.projection_ty.item_def_id)
1366 .and_then(|trait_assoc_item| {
1368 .trait_of_item(proj.projection_ty.item_def_id)
1369 .map(|id| (trait_assoc_item, id))
1371 .and_then(|(trait_assoc_item, id)| {
1372 self.tcx.find_map_relevant_impl(
1374 proj.projection_ty.self_ty(),
1377 .associated_items(did)
1378 .in_definition_order()
1379 .filter(|assoc| assoc.ident == trait_assoc_item.ident)
1384 .and_then(|item| match self.tcx.hir().get_if_local(item.def_id) {
1386 hir::Node::TraitItem(hir::TraitItem {
1387 kind: hir::TraitItemKind::Type(_, Some(ty)),
1390 | hir::Node::ImplItem(hir::ImplItem {
1391 kind: hir::ImplItemKind::TyAlias(ty),
1395 Some((ty.span, format!("type mismatch resolving `{}`", predicate)))
1401 self.note_type_err(&mut diag, &obligation.cause, secondary_span, values, err, true);
1402 self.note_obligation_cause(&mut diag, obligation);
1408 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1409 /// returns the fuzzy category of a given type, or None
1410 /// if the type can be equated to any type.
1411 fn type_category(t: Ty<'_>) -> Option<u32> {
1413 ty::Bool => Some(0),
1414 ty::Char => Some(1),
1416 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
1417 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
1418 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1419 ty::Array(..) | ty::Slice(..) => Some(6),
1420 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1421 ty::Dynamic(..) => Some(8),
1422 ty::Closure(..) => Some(9),
1423 ty::Tuple(..) => Some(10),
1424 ty::Projection(..) => Some(11),
1425 ty::Param(..) => Some(12),
1426 ty::Opaque(..) => Some(13),
1427 ty::Never => Some(14),
1428 ty::Adt(adt, ..) => match adt.adt_kind() {
1429 AdtKind::Struct => Some(15),
1430 AdtKind::Union => Some(16),
1431 AdtKind::Enum => Some(17),
1433 ty::Generator(..) => Some(18),
1434 ty::Foreign(..) => Some(19),
1435 ty::GeneratorWitness(..) => Some(20),
1436 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1440 match (type_category(a), type_category(b)) {
1441 (Some(cat_a), Some(cat_b)) => match (a.kind(), b.kind()) {
1442 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
1443 _ => cat_a == cat_b,
1445 // infer and error can be equated to all types
1450 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
1451 self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
1452 hir::GeneratorKind::Gen => "a generator",
1453 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
1454 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
1455 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
1459 fn find_similar_impl_candidates(
1461 trait_ref: ty::PolyTraitRef<'tcx>,
1462 ) -> Vec<ty::TraitRef<'tcx>> {
1463 // We simplify params and strip references here.
1465 // This both removes a lot of unhelpful suggestions, e.g.
1466 // when searching for `&Foo: Trait` it doesn't suggestion `impl Trait for &Bar`,
1467 // while also suggesting impls for `&Foo` when we're looking for `Foo: Trait`.
1469 // The second thing isn't necessarily always a good thing, but
1470 // any other simple setup results in a far worse output, so 🤷
1471 let simp = fast_reject::simplify_type(
1473 trait_ref.skip_binder().self_ty(),
1474 SimplifyParams::Yes,
1475 StripReferences::Yes,
1477 let all_impls = self.tcx.all_impls(trait_ref.def_id());
1480 Some(simp) => all_impls
1481 .filter_map(|def_id| {
1482 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
1483 let imp_simp = fast_reject::simplify_type(
1486 SimplifyParams::Yes,
1487 StripReferences::Yes,
1489 if let Some(imp_simp) = imp_simp {
1490 if simp != imp_simp {
1494 if self.tcx.impl_polarity(def_id) == ty::ImplPolarity::Negative {
1501 .filter_map(|def_id| {
1502 if self.tcx.impl_polarity(def_id) == ty::ImplPolarity::Negative {
1505 self.tcx.impl_trait_ref(def_id)
1511 fn report_similar_impl_candidates(
1513 impl_candidates: Vec<ty::TraitRef<'tcx>>,
1514 err: &mut DiagnosticBuilder<'_>,
1516 if impl_candidates.is_empty() {
1520 let len = impl_candidates.len();
1521 let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 };
1523 let normalize = |candidate| {
1524 self.tcx.infer_ctxt().enter(|ref infcx| {
1525 let normalized = infcx
1526 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
1527 .normalize(candidate)
1530 Some(normalized) => format!("\n {}", normalized.value),
1531 None => format!("\n {}", candidate),
1536 // Sort impl candidates so that ordering is consistent for UI tests.
1537 let mut normalized_impl_candidates =
1538 impl_candidates.iter().copied().map(normalize).collect::<Vec<String>>();
1540 // Sort before taking the `..end` range,
1541 // because the ordering of `impl_candidates` may not be deterministic:
1542 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
1543 normalized_impl_candidates.sort();
1546 "the following implementations were found:{}{}",
1547 normalized_impl_candidates[..end].join(""),
1548 if len > 5 { format!("\nand {} others", len - 4) } else { String::new() }
1552 /// Gets the parent trait chain start
1553 fn get_parent_trait_ref(
1555 code: &ObligationCauseCode<'tcx>,
1556 ) -> Option<(String, Option<Span>)> {
1558 ObligationCauseCode::BuiltinDerivedObligation(data) => {
1559 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
1560 match self.get_parent_trait_ref(&data.parent_code) {
1563 let ty = parent_trait_ref.skip_binder().self_ty();
1564 let span = TyCategory::from_ty(self.tcx, ty)
1565 .map(|(_, def_id)| self.tcx.def_span(def_id));
1566 Some((ty.to_string(), span))
1570 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1571 self.get_parent_trait_ref(&parent_code)
1577 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1578 /// with the same path as `trait_ref`, a help message about
1579 /// a probable version mismatch is added to `err`
1580 fn note_version_mismatch(
1582 err: &mut DiagnosticBuilder<'_>,
1583 trait_ref: &ty::PolyTraitRef<'tcx>,
1585 let get_trait_impl = |trait_def_id| {
1586 self.tcx.find_map_relevant_impl(trait_def_id, trait_ref.skip_binder().self_ty(), Some)
1588 let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1589 let traits_with_same_path: std::collections::BTreeSet<_> = self
1592 .filter(|trait_def_id| *trait_def_id != trait_ref.def_id())
1593 .filter(|trait_def_id| self.tcx.def_path_str(*trait_def_id) == required_trait_path)
1595 for trait_with_same_path in traits_with_same_path {
1596 if let Some(impl_def_id) = get_trait_impl(trait_with_same_path) {
1597 let impl_span = self.tcx.def_span(impl_def_id);
1598 err.span_help(impl_span, "trait impl with same name found");
1599 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1600 let crate_msg = format!(
1601 "perhaps two different versions of crate `{}` are being used?",
1604 err.note(&crate_msg);
1609 fn mk_trait_obligation_with_new_self_ty(
1611 param_env: ty::ParamEnv<'tcx>,
1612 trait_ref: ty::PolyTraitPredicate<'tcx>,
1613 new_self_ty: Ty<'tcx>,
1614 ) -> PredicateObligation<'tcx> {
1615 assert!(!new_self_ty.has_escaping_bound_vars());
1617 let trait_pred = trait_ref.map_bound_ref(|tr| ty::TraitPredicate {
1618 trait_ref: ty::TraitRef {
1619 substs: self.tcx.mk_substs_trait(new_self_ty, &tr.trait_ref.substs[1..]),
1625 Obligation::new(ObligationCause::dummy(), param_env, trait_pred.to_predicate(self.tcx))
1628 #[instrument(skip(self), level = "debug")]
1629 fn maybe_report_ambiguity(
1631 obligation: &PredicateObligation<'tcx>,
1632 body_id: Option<hir::BodyId>,
1634 // Unable to successfully determine, probably means
1635 // insufficient type information, but could mean
1636 // ambiguous impls. The latter *ought* to be a
1637 // coherence violation, so we don't report it here.
1639 let predicate = self.resolve_vars_if_possible(obligation.predicate);
1640 let span = obligation.cause.span;
1642 debug!(?predicate, obligation.cause.code = tracing::field::debug(&obligation.cause.code()));
1644 // Ambiguity errors are often caused as fallout from earlier errors.
1645 // We ignore them if this `infcx` is tainted in some cases below.
1647 let bound_predicate = predicate.kind();
1648 let mut err = match bound_predicate.skip_binder() {
1649 ty::PredicateKind::Trait(data) => {
1650 let trait_ref = bound_predicate.rebind(data.trait_ref);
1653 if predicate.references_error() {
1656 // Typically, this ambiguity should only happen if
1657 // there are unresolved type inference variables
1658 // (otherwise it would suggest a coherence
1659 // failure). But given #21974 that is not necessarily
1660 // the case -- we can have multiple where clauses that
1661 // are only distinguished by a region, which results
1662 // in an ambiguity even when all types are fully
1663 // known, since we don't dispatch based on region
1666 // Pick the first substitution that still contains inference variables as the one
1667 // we're going to emit an error for. If there are none (see above), fall back to
1668 // the substitution for `Self`.
1670 let substs = data.trait_ref.substs;
1673 .find(|s| s.has_infer_types_or_consts())
1674 .unwrap_or_else(|| substs[0])
1677 // This is kind of a hack: it frequently happens that some earlier
1678 // error prevents types from being fully inferred, and then we get
1679 // a bunch of uninteresting errors saying something like "<generic
1680 // #0> doesn't implement Sized". It may even be true that we
1681 // could just skip over all checks where the self-ty is an
1682 // inference variable, but I was afraid that there might be an
1683 // inference variable created, registered as an obligation, and
1684 // then never forced by writeback, and hence by skipping here we'd
1685 // be ignoring the fact that we don't KNOW the type works
1686 // out. Though even that would probably be harmless, given that
1687 // we're only talking about builtin traits, which are known to be
1688 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1689 // avoid inundating the user with unnecessary errors, but we now
1690 // check upstream for type errors and don't add the obligations to
1691 // begin with in those cases.
1692 if self.tcx.lang_items().sized_trait() == Some(trait_ref.def_id()) {
1693 if !self.is_tainted_by_errors() {
1694 self.emit_inference_failure_err(
1706 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
1707 let mut err = self.emit_inference_failure_err(
1715 let obligation = Obligation::new(
1716 obligation.cause.clone(),
1717 obligation.param_env,
1718 trait_ref.to_poly_trait_predicate(),
1720 let mut selcx = SelectionContext::with_query_mode(
1722 crate::traits::TraitQueryMode::Standard,
1724 match selcx.select_from_obligation(&obligation) {
1725 Err(SelectionError::Ambiguous(impls)) if impls.len() > 1 => {
1726 self.annotate_source_of_ambiguity(&mut err, &impls, predicate);
1729 if self.is_tainted_by_errors() {
1733 err.note(&format!("cannot satisfy `{}`", predicate));
1737 if let ObligationCauseCode::ItemObligation(def_id) = *obligation.cause.code() {
1738 self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
1741 ObligationCauseCode::BindingObligation(ref def_id, _),
1743 (self.tcx.sess.source_map().span_to_snippet(span), obligation.cause.code())
1745 let generics = self.tcx.generics_of(*def_id);
1746 if generics.params.iter().any(|p| p.name != kw::SelfUpper)
1747 && !snippet.ends_with('>')
1748 && !generics.has_impl_trait()
1749 && !self.tcx.fn_trait_kind_from_lang_item(*def_id).is_some()
1751 // FIXME: To avoid spurious suggestions in functions where type arguments
1752 // where already supplied, we check the snippet to make sure it doesn't
1753 // end with a turbofish. Ideally we would have access to a `PathSegment`
1754 // instead. Otherwise we would produce the following output:
1756 // error[E0283]: type annotations needed
1757 // --> $DIR/issue-54954.rs:3:24
1759 // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
1760 // | ^^^^^^^^^^^^^^^^^^^^^^^^^^
1762 // | cannot infer type
1763 // | help: consider specifying the type argument
1764 // | in the function call:
1765 // | `Tt::const_val::<[i8; 123]>::<T>`
1767 // LL | const fn const_val<T: Sized>() -> usize {
1768 // | - required by this bound in `Tt::const_val`
1770 // = note: cannot satisfy `_: Tt`
1772 err.span_suggestion_verbose(
1773 span.shrink_to_hi(),
1775 "consider specifying the type argument{} in the function call",
1776 pluralize!(generics.params.len()),
1783 .map(|p| p.name.to_string())
1784 .collect::<Vec<String>>()
1787 Applicability::HasPlaceholders,
1794 ty::PredicateKind::WellFormed(arg) => {
1795 // Same hacky approach as above to avoid deluging user
1796 // with error messages.
1797 if arg.references_error()
1798 || self.tcx.sess.has_errors()
1799 || self.is_tainted_by_errors()
1804 self.emit_inference_failure_err(body_id, span, arg, vec![], ErrorCode::E0282)
1807 ty::PredicateKind::Subtype(data) => {
1808 if data.references_error()
1809 || self.tcx.sess.has_errors()
1810 || self.is_tainted_by_errors()
1812 // no need to overload user in such cases
1815 let SubtypePredicate { a_is_expected: _, a, b } = data;
1816 // both must be type variables, or the other would've been instantiated
1817 assert!(a.is_ty_var() && b.is_ty_var());
1818 self.emit_inference_failure_err(body_id, span, a.into(), vec![], ErrorCode::E0282)
1820 ty::PredicateKind::Projection(data) => {
1821 let self_ty = data.projection_ty.self_ty();
1822 let term = data.term;
1823 if predicate.references_error() || self.is_tainted_by_errors() {
1826 if self_ty.needs_infer() && term.needs_infer() {
1827 // We do this for the `foo.collect()?` case to produce a suggestion.
1828 let mut err = self.emit_inference_failure_err(
1835 err.note(&format!("cannot satisfy `{}`", predicate));
1838 let mut err = struct_span_err!(
1842 "type annotations needed: cannot satisfy `{}`",
1845 err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1851 if self.tcx.sess.has_errors() || self.is_tainted_by_errors() {
1854 let mut err = struct_span_err!(
1858 "type annotations needed: cannot satisfy `{}`",
1861 err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1865 self.note_obligation_cause(&mut err, obligation);
1869 fn annotate_source_of_ambiguity(
1871 err: &mut DiagnosticBuilder<'tcx>,
1873 predicate: ty::Predicate<'tcx>,
1875 let mut spans = vec![];
1876 let mut crates = vec![];
1877 let mut post = vec![];
1878 for def_id in impls {
1879 match self.tcx.span_of_impl(*def_id) {
1880 Ok(span) => spans.push(self.tcx.sess.source_map().guess_head_span(span)),
1883 if let Some(header) = to_pretty_impl_header(self.tcx, *def_id) {
1889 let msg = format!("multiple `impl`s satisfying `{}` found", predicate);
1890 let mut crate_names: Vec<_> = crates.iter().map(|n| format!("`{}`", n)).collect();
1892 crate_names.dedup();
1896 if self.is_tainted_by_errors()
1897 && crate_names.len() == 1
1898 && crate_names[0] == "`core`"
1901 // Avoid complaining about other inference issues for expressions like
1902 // `42 >> 1`, where the types are still `{integer}`, but we want to
1903 // Do we need `trait_ref.skip_binder().self_ty().is_numeric() &&` too?
1907 let post = if post.len() > 4 {
1909 ":\n{}\nand {} more",
1910 post.iter().map(|p| format!("- {}", p)).take(4).collect::<Vec<_>>().join("\n"),
1913 } else if post.len() > 1 || (post.len() == 1 && post[0].contains('\n')) {
1914 format!(":\n{}", post.iter().map(|p| format!("- {}", p)).collect::<Vec<_>>().join("\n"),)
1915 } else if post.len() == 1 {
1916 format!(": `{}`", post[0])
1921 match (spans.len(), crates.len(), crate_names.len()) {
1923 err.note(&format!("cannot satisfy `{}`", predicate));
1926 err.note(&format!("{} in the `{}` crate{}", msg, crates[0], post,));
1930 "{} in the following crates: {}{}",
1932 crate_names.join(", "),
1937 let span: MultiSpan = spans.into();
1938 err.span_note(span, &msg);
1941 let span: MultiSpan = spans.into();
1942 err.span_note(span, &msg);
1944 &format!("and another `impl` found in the `{}` crate{}", crates[0], post,),
1948 let span: MultiSpan = spans.into();
1949 err.span_note(span, &msg);
1951 "and more `impl`s found in the following crates: {}{}",
1952 crate_names.join(", "),
1959 /// Returns `true` if the trait predicate may apply for *some* assignment
1960 /// to the type parameters.
1961 fn predicate_can_apply(
1963 param_env: ty::ParamEnv<'tcx>,
1964 pred: ty::PolyTraitRef<'tcx>,
1966 struct ParamToVarFolder<'a, 'tcx> {
1967 infcx: &'a InferCtxt<'a, 'tcx>,
1968 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
1971 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
1972 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1976 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1977 if let ty::Param(ty::ParamTy { name, .. }) = *ty.kind() {
1978 let infcx = self.infcx;
1979 self.var_map.entry(ty).or_insert_with(|| {
1980 infcx.next_ty_var(TypeVariableOrigin {
1981 kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
1986 ty.super_fold_with(self)
1992 let mut selcx = SelectionContext::new(self);
1995 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
1997 let cleaned_pred = super::project::normalize(
2000 ObligationCause::dummy(),
2005 let obligation = Obligation::new(
2006 ObligationCause::dummy(),
2008 cleaned_pred.without_const().to_predicate(selcx.tcx()),
2011 self.predicate_may_hold(&obligation)
2015 fn note_obligation_cause(
2017 err: &mut DiagnosticBuilder<'tcx>,
2018 obligation: &PredicateObligation<'tcx>,
2020 // First, attempt to add note to this error with an async-await-specific
2021 // message, and fall back to regular note otherwise.
2022 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2023 self.note_obligation_cause_code(
2025 &obligation.predicate,
2026 obligation.param_env,
2027 obligation.cause.code(),
2029 &mut Default::default(),
2031 self.suggest_unsized_bound_if_applicable(err, obligation);
2035 fn suggest_unsized_bound_if_applicable(
2037 err: &mut DiagnosticBuilder<'tcx>,
2038 obligation: &PredicateObligation<'tcx>,
2040 let (pred, item_def_id, span) = match (
2041 obligation.predicate.kind().skip_binder(),
2042 obligation.cause.code().peel_derives(),
2045 ty::PredicateKind::Trait(pred),
2046 &ObligationCauseCode::BindingObligation(item_def_id, span),
2047 ) => (pred, item_def_id, span),
2051 "suggest_unsized_bound_if_applicable: pred={:?} item_def_id={:?} span={:?}",
2052 pred, item_def_id, span
2055 self.tcx.hir().get_if_local(item_def_id),
2056 Some(pred.def_id()) == self.tcx.lang_items().sized_trait(),
2058 (Some(node), true) => node,
2061 self.maybe_suggest_unsized_generics(err, span, node);
2064 fn maybe_suggest_unsized_generics<'hir>(
2066 err: &mut DiagnosticBuilder<'tcx>,
2070 let generics = match node.generics() {
2071 Some(generics) => generics,
2074 let sized_trait = self.tcx.lang_items().sized_trait();
2075 debug!("maybe_suggest_unsized_generics: generics.params={:?}", generics.params);
2076 debug!("maybe_suggest_unsized_generics: generics.where_clause={:?}", generics.where_clause);
2077 let param = generics.params.iter().filter(|param| param.span == span).find(|param| {
2078 // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
2079 // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
2083 .all(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) != sized_trait)
2085 let param = match param {
2086 Some(param) => param,
2089 let param_def_id = self.tcx.hir().local_def_id(param.hir_id).to_def_id();
2090 let preds = generics.where_clause.predicates.iter();
2091 let explicitly_sized = preds
2092 .filter_map(|pred| match pred {
2093 hir::WherePredicate::BoundPredicate(bp) => Some(bp),
2096 .filter(|bp| bp.is_param_bound(param_def_id))
2097 .flat_map(|bp| bp.bounds)
2098 .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
2099 if explicitly_sized {
2102 debug!("maybe_suggest_unsized_generics: param={:?}", param);
2106 // Only suggest indirection for uses of type parameters in ADTs.
2108 hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
2112 if self.maybe_indirection_for_unsized(err, item, param) {
2118 // Didn't add an indirection suggestion, so add a general suggestion to relax `Sized`.
2119 let (span, separator) = match param.bounds {
2120 [] => (span.shrink_to_hi(), ":"),
2121 [.., bound] => (bound.span().shrink_to_hi(), " +"),
2123 err.span_suggestion_verbose(
2125 "consider relaxing the implicit `Sized` restriction",
2126 format!("{} ?Sized", separator),
2127 Applicability::MachineApplicable,
2131 fn maybe_indirection_for_unsized<'hir>(
2133 err: &mut DiagnosticBuilder<'tcx>,
2134 item: &'hir Item<'hir>,
2135 param: &'hir GenericParam<'hir>,
2137 // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
2138 // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
2139 // is not. Look for invalid "bare" parameter uses, and suggest using indirection.
2141 FindTypeParam { param: param.name.ident().name, invalid_spans: vec![], nested: false };
2142 visitor.visit_item(item);
2143 if visitor.invalid_spans.is_empty() {
2146 let mut multispan: MultiSpan = param.span.into();
2147 multispan.push_span_label(
2149 format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
2151 for sp in visitor.invalid_spans {
2152 multispan.push_span_label(
2154 format!("...if indirection were used here: `Box<{}>`", param.name.ident()),
2160 "you could relax the implicit `Sized` bound on `{T}` if it were \
2161 used through indirection like `&{T}` or `Box<{T}>`",
2162 T = param.name.ident(),
2168 fn is_recursive_obligation(
2170 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
2171 cause_code: &ObligationCauseCode<'tcx>,
2173 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
2174 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2175 let self_ty = parent_trait_ref.skip_binder().self_ty();
2176 if obligated_types.iter().any(|ot| ot == &self_ty) {
2179 if let ty::Adt(def, substs) = self_ty.kind() {
2180 if let [arg] = &substs[..] {
2181 if let ty::subst::GenericArgKind::Type(ty) = arg.unpack() {
2182 if let ty::Adt(inner_def, _) = ty.kind() {
2183 if inner_def == def {
2195 /// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
2196 /// `param: ?Sized` would be a valid constraint.
2197 struct FindTypeParam {
2198 param: rustc_span::Symbol,
2199 invalid_spans: Vec<Span>,
2203 impl<'v> Visitor<'v> for FindTypeParam {
2204 fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
2205 // Skip where-clauses, to avoid suggesting indirection for type parameters found there.
2208 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
2209 // We collect the spans of all uses of the "bare" type param, like in `field: T` or
2210 // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
2211 // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
2212 // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
2213 // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
2214 // in that case should make what happened clear enough.
2216 hir::TyKind::Ptr(_) | hir::TyKind::Rptr(..) | hir::TyKind::TraitObject(..) => {}
2217 hir::TyKind::Path(hir::QPath::Resolved(None, path))
2218 if path.segments.len() == 1 && path.segments[0].ident.name == self.param =>
2221 debug!("FindTypeParam::visit_ty: ty={:?}", ty);
2222 self.invalid_spans.push(ty.span);
2225 hir::TyKind::Path(_) => {
2226 let prev = self.nested;
2228 hir::intravisit::walk_ty(self, ty);
2232 hir::intravisit::walk_ty(self, ty);
2238 pub fn recursive_type_with_infinite_size_error(
2243 assert!(type_def_id.is_local());
2244 let span = tcx.hir().span_if_local(type_def_id).unwrap();
2245 let span = tcx.sess.source_map().guess_head_span(span);
2246 let path = tcx.def_path_str(type_def_id);
2248 struct_span_err!(tcx.sess, span, E0072, "recursive type `{}` has infinite size", path);
2249 err.span_label(span, "recursive type has infinite size");
2250 for &span in &spans {
2251 err.span_label(span, "recursive without indirection");
2254 "insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `{}` representable",
2257 if spans.len() <= 4 {
2258 err.multipart_suggestion(
2264 (span.shrink_to_lo(), "Box<".to_string()),
2265 (span.shrink_to_hi(), ">".to_string()),
2270 Applicability::HasPlaceholders,
2278 /// Summarizes information
2281 /// An argument of non-tuple type. Parameters are (name, ty)
2282 Arg(String, String),
2284 /// An argument of tuple type. For a "found" argument, the span is
2285 /// the location in the source of the pattern. For an "expected"
2286 /// argument, it will be None. The vector is a list of (name, ty)
2287 /// strings for the components of the tuple.
2288 Tuple(Option<Span>, Vec<(String, String)>),
2292 fn empty() -> ArgKind {
2293 ArgKind::Arg("_".to_owned(), "_".to_owned())
2296 /// Creates an `ArgKind` from the expected type of an
2297 /// argument. It has no name (`_`) and an optional source span.
2298 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2300 ty::Tuple(tys) => ArgKind::Tuple(
2302 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
2304 _ => ArgKind::Arg("_".to_owned(), t.to_string()),