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;
20 use rustc_middle::mir::abstract_const::NotConstEvaluatable;
21 use rustc_middle::ty::error::ExpectedFound;
22 use rustc_middle::ty::fold::TypeFolder;
23 use rustc_middle::ty::{
24 self, fast_reject, AdtKind, SubtypePredicate, ToPolyTraitRef, ToPredicate, Ty, TyCtxt,
25 TypeFoldable, WithConstness,
27 use rustc_session::DiagnosticMessageId;
28 use rustc_span::symbol::{kw, sym};
29 use rustc_span::{ExpnKind, MultiSpan, Span, DUMMY_SP};
33 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
34 use crate::traits::query::normalize::AtExt as _;
35 use on_unimplemented::InferCtxtExt as _;
36 use suggestions::InferCtxtExt as _;
38 pub use rustc_infer::traits::error_reporting::*;
40 pub trait InferCtxtExt<'tcx> {
41 fn report_fulfillment_errors(
43 errors: &[FulfillmentError<'tcx>],
44 body_id: Option<hir::BodyId>,
45 fallback_has_occurred: bool,
48 fn report_overflow_error<T>(
50 obligation: &Obligation<'tcx, T>,
51 suggest_increasing_limit: bool,
54 T: fmt::Display + TypeFoldable<'tcx>;
56 fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !;
58 /// The `root_obligation` parameter should be the `root_obligation` field
59 /// from a `FulfillmentError`. If no `FulfillmentError` is available,
60 /// then it should be the same as `obligation`.
61 fn report_selection_error(
63 obligation: PredicateObligation<'tcx>,
64 root_obligation: &PredicateObligation<'tcx>,
65 error: &SelectionError<'tcx>,
66 fallback_has_occurred: bool,
70 /// Given some node representing a fn-like thing in the HIR map,
71 /// returns a span and `ArgKind` information that describes the
72 /// arguments it expects. This can be supplied to
73 /// `report_arg_count_mismatch`.
74 fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)>;
76 /// Reports an error when the number of arguments needed by a
77 /// trait match doesn't match the number that the expression
79 fn report_arg_count_mismatch(
82 found_span: Option<Span>,
83 expected_args: Vec<ArgKind>,
84 found_args: Vec<ArgKind>,
86 ) -> DiagnosticBuilder<'tcx>;
89 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
90 fn report_fulfillment_errors(
92 errors: &[FulfillmentError<'tcx>],
93 body_id: Option<hir::BodyId>,
94 fallback_has_occurred: bool,
97 struct ErrorDescriptor<'tcx> {
98 predicate: ty::Predicate<'tcx>,
99 index: Option<usize>, // None if this is an old error
102 let mut error_map: FxHashMap<_, Vec<_>> = self
103 .reported_trait_errors
106 .map(|(&span, predicates)| {
111 .map(|&predicate| ErrorDescriptor { predicate, index: None })
117 for (index, error) in errors.iter().enumerate() {
118 // We want to ignore desugarings here: spans are equivalent even
119 // if one is the result of a desugaring and the other is not.
120 let mut span = error.obligation.cause.span;
121 let expn_data = span.ctxt().outer_expn_data();
122 if let ExpnKind::Desugaring(_) = expn_data.kind {
123 span = expn_data.call_site;
126 error_map.entry(span).or_default().push(ErrorDescriptor {
127 predicate: error.obligation.predicate,
131 self.reported_trait_errors
135 .push(error.obligation.predicate);
138 // We do this in 2 passes because we want to display errors in order, though
139 // maybe it *is* better to sort errors by span or something.
140 let mut is_suppressed = vec![false; errors.len()];
141 for (_, error_set) in error_map.iter() {
142 // We want to suppress "duplicate" errors with the same span.
143 for error in error_set {
144 if let Some(index) = error.index {
145 // Suppress errors that are either:
146 // 1) strictly implied by another error.
147 // 2) implied by an error with a smaller index.
148 for error2 in error_set {
149 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
150 // Avoid errors being suppressed by already-suppressed
151 // errors, to prevent all errors from being suppressed
156 if self.error_implies(error2.predicate, error.predicate)
157 && !(error2.index >= error.index
158 && self.error_implies(error.predicate, error2.predicate))
160 info!("skipping {:?} (implied by {:?})", error, error2);
161 is_suppressed[index] = true;
169 for (error, suppressed) in iter::zip(errors, is_suppressed) {
171 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
176 /// Reports that an overflow has occurred and halts compilation. We
177 /// halt compilation unconditionally because it is important that
178 /// overflows never be masked -- they basically represent computations
179 /// whose result could not be truly determined and thus we can't say
180 /// if the program type checks or not -- and they are unusual
181 /// occurrences in any case.
182 fn report_overflow_error<T>(
184 obligation: &Obligation<'tcx, T>,
185 suggest_increasing_limit: bool,
188 T: fmt::Display + TypeFoldable<'tcx>,
190 let predicate = self.resolve_vars_if_possible(obligation.predicate.clone());
191 let mut err = struct_span_err!(
193 obligation.cause.span,
195 "overflow evaluating the requirement `{}`",
199 if suggest_increasing_limit {
200 self.suggest_new_overflow_limit(&mut err);
203 self.note_obligation_cause_code(
205 &obligation.predicate,
206 &obligation.cause.code,
208 &mut Default::default(),
212 self.tcx.sess.abort_if_errors();
216 /// Reports that a cycle was detected which led to overflow and halts
217 /// compilation. This is equivalent to `report_overflow_error` except
218 /// that we can give a more helpful error message (and, in particular,
219 /// we do not suggest increasing the overflow limit, which is not
221 fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
222 let cycle = self.resolve_vars_if_possible(cycle.to_owned());
223 assert!(!cycle.is_empty());
225 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
227 self.report_overflow_error(&cycle[0], false);
230 fn report_selection_error(
232 mut obligation: PredicateObligation<'tcx>,
233 root_obligation: &PredicateObligation<'tcx>,
234 error: &SelectionError<'tcx>,
235 fallback_has_occurred: bool,
239 let mut span = obligation.cause.span;
241 let mut err = match *error {
242 SelectionError::Unimplemented => {
243 // If this obligation was generated as a result of well-formed checking, see if we
244 // can get a better error message by performing HIR-based well formed checking.
245 if let ObligationCauseCode::WellFormed(Some(wf_hir_id)) =
246 root_obligation.cause.code.peel_derives()
249 self.tcx.diagnostic_hir_wf_check((obligation.predicate, *wf_hir_id))
251 obligation.cause = cause;
252 span = obligation.cause.span;
255 if let ObligationCauseCode::CompareImplMethodObligation {
260 | ObligationCauseCode::CompareImplTypeObligation {
264 } = obligation.cause.code
266 self.report_extra_impl_obligation(
271 &format!("`{}`", obligation.predicate),
277 let bound_predicate = obligation.predicate.kind();
278 match bound_predicate.skip_binder() {
279 ty::PredicateKind::Trait(trait_predicate, _) => {
280 let trait_predicate = bound_predicate.rebind(trait_predicate);
281 let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
283 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
286 let trait_ref = trait_predicate.to_poly_trait_ref();
287 let (post_message, pre_message, type_def) = self
288 .get_parent_trait_ref(&obligation.cause.code)
291 format!(" in `{}`", t),
292 format!("within `{}`, ", t),
293 s.map(|s| (format!("within this `{}`", t), s)),
296 .unwrap_or_default();
298 let OnUnimplementedNote { message, label, note, enclosing_scope } =
299 self.on_unimplemented_note(trait_ref, &obligation);
300 let have_alt_message = message.is_some() || label.is_some();
301 let is_try_conversion = self.is_try_conversion(span, trait_ref.def_id());
303 { Some(trait_ref.def_id()) == self.tcx.lang_items().unsize_trait() };
304 let (message, note) = if is_try_conversion {
307 "`?` couldn't convert the error to `{}`",
308 trait_ref.skip_binder().self_ty(),
311 "the question mark operation (`?`) implicitly performs a \
312 conversion on the error value using the `From` trait"
320 let mut err = struct_span_err!(
325 message.unwrap_or_else(|| format!(
326 "the trait bound `{}` is not satisfied{}",
327 trait_ref.without_const().to_predicate(tcx),
332 if is_try_conversion {
333 let none_error = self
335 .get_diagnostic_item(sym::none_error)
336 .map(|def_id| tcx.type_of(def_id));
337 let should_convert_option_to_result =
338 Some(trait_ref.skip_binder().substs.type_at(1)) == none_error;
339 let should_convert_result_to_option =
340 Some(trait_ref.self_ty().skip_binder()) == none_error;
341 if should_convert_option_to_result {
342 err.span_suggestion_verbose(
344 "consider converting the `Option<T>` into a `Result<T, _>` \
345 using `Option::ok_or` or `Option::ok_or_else`",
346 ".ok_or_else(|| /* error value */)".to_string(),
347 Applicability::HasPlaceholders,
349 } else if should_convert_result_to_option {
350 err.span_suggestion_verbose(
352 "consider converting the `Result<T, _>` into an `Option<T>` \
355 Applicability::MachineApplicable,
358 if let Some(ret_span) = self.return_type_span(&obligation) {
362 "expected `{}` because of this",
363 trait_ref.skip_binder().self_ty()
370 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
371 "consider using `()`, or a `Result`".to_owned()
374 "{}the trait `{}` is not implemented for `{}`",
376 trait_ref.print_only_trait_path(),
377 trait_ref.skip_binder().self_ty(),
381 if self.suggest_add_reference_to_arg(
388 self.note_obligation_cause(&mut err, &obligation);
392 if let Some(ref s) = label {
393 // If it has a custom `#[rustc_on_unimplemented]`
394 // error message, let's display it as the label!
395 err.span_label(span, s.as_str());
396 if !matches!(trait_ref.skip_binder().self_ty().kind(), ty::Param(_)) {
397 // When the self type is a type param We don't need to "the trait
398 // `std::marker::Sized` is not implemented for `T`" as we will point
399 // at the type param with a label to suggest constraining it.
400 err.help(&explanation);
403 err.span_label(span, explanation);
405 if let Some((msg, span)) = type_def {
406 err.span_label(span, &msg);
408 if let Some(ref s) = note {
409 // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
410 err.note(s.as_str());
412 if let Some(ref s) = enclosing_scope {
415 .opt_local_def_id(obligation.cause.body_id)
417 tcx.hir().body_owner_def_id(hir::BodyId {
418 hir_id: obligation.cause.body_id,
422 let enclosing_scope_span =
423 tcx.hir().span_with_body(tcx.hir().local_def_id_to_hir_id(body));
425 err.span_label(enclosing_scope_span, s.as_str());
428 self.suggest_dereferences(&obligation, &mut err, trait_ref, points_at_arg);
429 self.suggest_fn_call(&obligation, &mut err, trait_ref, points_at_arg);
430 self.suggest_remove_reference(&obligation, &mut err, trait_ref);
431 self.suggest_semicolon_removal(&obligation, &mut err, span, trait_ref);
432 self.note_version_mismatch(&mut err, &trait_ref);
434 if Some(trait_ref.def_id()) == tcx.lang_items().try_trait() {
435 self.suggest_await_before_try(&mut err, &obligation, trait_ref, span);
438 if self.suggest_impl_trait(&mut err, span, &obligation, trait_ref) {
444 // If the obligation failed due to a missing implementation of the
445 // `Unsize` trait, give a pointer to why that might be the case
447 "all implementations of `Unsize` are provided \
448 automatically by the compiler, see \
449 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
450 for more information",
455 self.tcx.lang_items().fn_trait(),
456 self.tcx.lang_items().fn_mut_trait(),
457 self.tcx.lang_items().fn_once_trait(),
459 .contains(&Some(trait_ref.def_id()));
460 let is_target_feature_fn = if let ty::FnDef(def_id, _) =
461 *trait_ref.skip_binder().self_ty().kind()
463 !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
467 if is_fn_trait && is_target_feature_fn {
469 "`#[target_feature]` functions do not implement the `Fn` traits",
473 // Try to report a help message
474 if !trait_ref.has_infer_types_or_consts()
475 && self.predicate_can_apply(obligation.param_env, trait_ref)
477 // If a where-clause may be useful, remind the
478 // user that they can add it.
480 // don't display an on-unimplemented note, as
481 // these notes will often be of the form
482 // "the type `T` can't be frobnicated"
483 // which is somewhat confusing.
484 self.suggest_restricting_param_bound(
487 obligation.cause.body_id,
489 } else if !have_alt_message {
490 // Can't show anything else useful, try to find similar impls.
491 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
492 self.report_similar_impl_candidates(impl_candidates, &mut err);
495 // Changing mutability doesn't make a difference to whether we have
496 // an `Unsize` impl (Fixes ICE in #71036)
498 self.suggest_change_mut(
506 // If this error is due to `!: Trait` not implemented but `(): Trait` is
507 // implemented, and fallback has occurred, then it could be due to a
508 // variable that used to fallback to `()` now falling back to `!`. Issue a
509 // note informing about the change in behaviour.
510 if trait_predicate.skip_binder().self_ty().is_never()
511 && fallback_has_occurred
513 let predicate = trait_predicate.map_bound(|mut trait_pred| {
514 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
516 &trait_pred.trait_ref.substs[1..],
520 let unit_obligation =
521 obligation.with(predicate.without_const().to_predicate(tcx));
522 if self.predicate_may_hold(&unit_obligation) {
523 err.note("this trait is implemented for `()`.");
525 "this error might have been caused by changes to \
526 Rust's type-inference algorithm (see issue #48950 \
527 <https://github.com/rust-lang/rust/issues/48950> \
528 for more information).",
530 err.help("did you intend to use the type `()` here instead?");
534 // Return early if the trait is Debug or Display and the invocation
535 // originates within a standard library macro, because the output
536 // is otherwise overwhelming and unhelpful (see #85844 for an
540 self.tcx.is_diagnostic_item(sym::debug_trait, trait_ref.def_id());
541 let trait_is_display =
542 self.tcx.is_diagnostic_item(sym::display_trait, trait_ref.def_id());
545 match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
546 Some(macro_def_id) => {
547 let crate_name = tcx.crate_name(macro_def_id.krate);
548 crate_name == sym::std || crate_name == sym::core
553 if in_std_macro && (trait_is_debug || trait_is_display) {
561 ty::PredicateKind::Subtype(predicate) => {
562 // Errors for Subtype predicates show up as
563 // `FulfillmentErrorCode::CodeSubtypeError`,
564 // not selection error.
565 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
568 ty::PredicateKind::RegionOutlives(predicate) => {
569 let predicate = bound_predicate.rebind(predicate);
570 let predicate = self.resolve_vars_if_possible(predicate);
572 .region_outlives_predicate(&obligation.cause, predicate)
579 "the requirement `{}` is not satisfied (`{}`)",
585 ty::PredicateKind::Projection(..) | ty::PredicateKind::TypeOutlives(..) => {
586 let predicate = self.resolve_vars_if_possible(obligation.predicate);
591 "the requirement `{}` is not satisfied",
596 ty::PredicateKind::ObjectSafe(trait_def_id) => {
597 let violations = self.tcx.object_safety_violations(trait_def_id);
598 report_object_safety_error(self.tcx, span, trait_def_id, violations)
601 ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
602 let found_kind = self.closure_kind(closure_substs).unwrap();
604 self.tcx.sess.source_map().guess_head_span(
605 self.tcx.hir().span_if_local(closure_def_id).unwrap(),
608 self.tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local());
609 let mut err = struct_span_err!(
613 "expected a closure that implements the `{}` trait, \
614 but this closure only implements `{}`",
621 format!("this closure implements `{}`, not `{}`", found_kind, kind),
624 obligation.cause.span,
625 format!("the requirement to implement `{}` derives from here", kind),
628 // Additional context information explaining why the closure only implements
629 // a particular trait.
630 if let Some(typeck_results) = self.in_progress_typeck_results {
631 let typeck_results = typeck_results.borrow();
632 match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
633 (ty::ClosureKind::FnOnce, Some((span, place))) => {
637 "closure is `FnOnce` because it moves the \
638 variable `{}` out of its environment",
639 ty::place_to_string_for_capture(tcx, place)
643 (ty::ClosureKind::FnMut, Some((span, place))) => {
647 "closure is `FnMut` because it mutates the \
649 ty::place_to_string_for_capture(tcx, place)
661 ty::PredicateKind::WellFormed(ty) => {
662 if !self.tcx.sess.opts.debugging_opts.chalk {
663 // WF predicates cannot themselves make
664 // errors. They can only block due to
665 // ambiguity; otherwise, they always
666 // degenerate into other obligations
668 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
670 // FIXME: we'll need a better message which takes into account
671 // which bounds actually failed to hold.
672 self.tcx.sess.struct_span_err(
674 &format!("the type `{}` is not well-formed (chalk)", ty),
679 ty::PredicateKind::ConstEvaluatable(..) => {
680 // Errors for `ConstEvaluatable` predicates show up as
681 // `SelectionError::ConstEvalFailure`,
682 // not `Unimplemented`.
685 "const-evaluatable requirement gave wrong error: `{:?}`",
690 ty::PredicateKind::ConstEquate(..) => {
691 // Errors for `ConstEquate` predicates show up as
692 // `SelectionError::ConstEvalFailure`,
693 // not `Unimplemented`.
696 "const-equate requirement gave wrong error: `{:?}`",
701 ty::PredicateKind::TypeWellFormedFromEnv(..) => span_bug!(
703 "TypeWellFormedFromEnv predicate should only exist in the environment"
708 OutputTypeParameterMismatch(found_trait_ref, expected_trait_ref, _) => {
709 let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
710 let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
712 if expected_trait_ref.self_ty().references_error() {
716 let found_trait_ty = match found_trait_ref.self_ty().no_bound_vars() {
721 let found_did = match *found_trait_ty.kind() {
722 ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
723 ty::Adt(def, _) => Some(def.did),
727 let found_span = found_did
728 .and_then(|did| self.tcx.hir().span_if_local(did))
729 .map(|sp| self.tcx.sess.source_map().guess_head_span(sp)); // the sp could be an fn def
731 if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
732 // We check closures twice, with obligations flowing in different directions,
733 // but we want to complain about them only once.
737 self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
739 let found = match found_trait_ref.skip_binder().substs.type_at(1).kind() {
740 ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
741 _ => vec![ArgKind::empty()],
744 let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
745 let expected = match expected_ty.kind() {
746 ty::Tuple(ref tys) => tys
748 .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span)))
750 _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
753 if found.len() == expected.len() {
754 self.report_closure_arg_mismatch(
761 let (closure_span, found) = found_did
763 let node = self.tcx.hir().get_if_local(did)?;
764 let (found_span, found) = self.get_fn_like_arguments(node)?;
765 Some((Some(found_span), found))
767 .unwrap_or((found_span, found));
769 self.report_arg_count_mismatch(
774 found_trait_ty.is_closure(),
779 TraitNotObjectSafe(did) => {
780 let violations = self.tcx.object_safety_violations(did);
781 report_object_safety_error(self.tcx, span, did, violations)
784 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
786 "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
789 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
790 if !self.tcx.features().const_evaluatable_checked {
791 let mut err = self.tcx.sess.struct_span_err(
793 "constant expression depends on a generic parameter",
795 // FIXME(const_generics): we should suggest to the user how they can resolve this
796 // issue. However, this is currently not actually possible
797 // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
799 // Note that with `feature(const_evaluatable_checked)` this case should not
801 err.note("this may fail depending on what value the parameter takes");
806 match obligation.predicate.kind().skip_binder() {
807 ty::PredicateKind::ConstEvaluatable(def, _) => {
809 self.tcx.sess.struct_span_err(span, "unconstrained generic constant");
810 let const_span = self.tcx.def_span(def.did);
811 match self.tcx.sess.source_map().span_to_snippet(const_span) {
812 Ok(snippet) => err.help(&format!(
813 "try adding a `where` bound using this expression: `where [(); {}]:`",
816 _ => err.help("consider adding a `where` bound using this expression"),
823 "unexpected non-ConstEvaluatable predicate, this should not be reachable"
829 // Already reported in the query.
830 SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(ErrorReported)) => {
831 // FIXME(eddyb) remove this once `ErrorReported` becomes a proof token.
832 self.tcx.sess.delay_span_bug(span, "`ErrorReported` without an error");
837 bug!("overflow should be handled before the `report_selection_error` path");
841 self.note_obligation_cause(&mut err, &obligation);
842 self.point_at_returns_when_relevant(&mut err, &obligation);
847 /// Given some node representing a fn-like thing in the HIR map,
848 /// returns a span and `ArgKind` information that describes the
849 /// arguments it expects. This can be supplied to
850 /// `report_arg_count_mismatch`.
851 fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)> {
852 let sm = self.tcx.sess.source_map();
853 let hir = self.tcx.hir();
855 Node::Expr(&hir::Expr {
856 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
859 sm.guess_head_span(span),
864 if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
871 sm.span_to_snippet(pat.span)
873 .map(|snippet| (snippet, "_".to_owned()))
875 .collect::<Option<Vec<_>>>()?,
878 let name = sm.span_to_snippet(arg.pat.span).ok()?;
879 Some(ArgKind::Arg(name, "_".to_owned()))
882 .collect::<Option<Vec<ArgKind>>>()?,
884 Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
885 | Node::ImplItem(&hir::ImplItem {
887 kind: hir::ImplItemKind::Fn(ref sig, _),
890 | Node::TraitItem(&hir::TraitItem {
892 kind: hir::TraitItemKind::Fn(ref sig, _),
895 sm.guess_head_span(span),
899 .map(|arg| match arg.kind {
900 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
902 vec![("_".to_owned(), "_".to_owned()); tys.len()],
904 _ => ArgKind::empty(),
906 .collect::<Vec<ArgKind>>(),
908 Node::Ctor(ref variant_data) => {
909 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id));
910 let span = sm.guess_head_span(span);
911 (span, vec![ArgKind::empty(); variant_data.fields().len()])
913 _ => panic!("non-FnLike node found: {:?}", node),
917 /// Reports an error when the number of arguments needed by a
918 /// trait match doesn't match the number that the expression
920 fn report_arg_count_mismatch(
923 found_span: Option<Span>,
924 expected_args: Vec<ArgKind>,
925 found_args: Vec<ArgKind>,
927 ) -> DiagnosticBuilder<'tcx> {
928 let kind = if is_closure { "closure" } else { "function" };
930 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
931 let arg_length = arguments.len();
932 let distinct = matches!(other, &[ArgKind::Tuple(..)]);
933 match (arg_length, arguments.get(0)) {
934 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
935 format!("a single {}-tuple as argument", fields.len())
940 if distinct && arg_length > 1 { "distinct " } else { "" },
941 pluralize!(arg_length)
946 let expected_str = args_str(&expected_args, &found_args);
947 let found_str = args_str(&found_args, &expected_args);
949 let mut err = struct_span_err!(
953 "{} is expected to take {}, but it takes {}",
959 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
961 if let Some(found_span) = found_span {
962 err.span_label(found_span, format!("takes {}", found_str));
965 // ^^^^^^^^-- def_span
969 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
973 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
975 // Suggest to take and ignore the arguments with expected_args_length `_`s if
976 // found arguments is empty (assume the user just wants to ignore args in this case).
977 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
978 if found_args.is_empty() && is_closure {
979 let underscores = vec!["_"; expected_args.len()].join(", ");
980 err.span_suggestion_verbose(
983 "consider changing the closure to take and ignore the expected argument{}",
984 pluralize!(expected_args.len())
986 format!("|{}|", underscores),
987 Applicability::MachineApplicable,
991 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
992 if fields.len() == expected_args.len() {
995 .map(|(name, _)| name.to_owned())
996 .collect::<Vec<String>>()
998 err.span_suggestion_verbose(
1000 "change the closure to take multiple arguments instead of a single tuple",
1001 format!("|{}|", sugg),
1002 Applicability::MachineApplicable,
1006 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1007 if fields.len() == found_args.len() && is_closure {
1012 .map(|arg| match arg {
1013 ArgKind::Arg(name, _) => name.to_owned(),
1014 _ => "_".to_owned(),
1016 .collect::<Vec<String>>()
1018 // add type annotations if available
1019 if found_args.iter().any(|arg| match arg {
1020 ArgKind::Arg(_, ty) => ty != "_",
1027 .map(|(_, ty)| ty.to_owned())
1028 .collect::<Vec<String>>()
1035 err.span_suggestion_verbose(
1037 "change the closure to accept a tuple instead of individual arguments",
1039 Applicability::MachineApplicable,
1049 trait InferCtxtPrivExt<'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;
1054 fn report_fulfillment_error(
1056 error: &FulfillmentError<'tcx>,
1057 body_id: Option<hir::BodyId>,
1058 fallback_has_occurred: bool,
1061 fn report_projection_error(
1063 obligation: &PredicateObligation<'tcx>,
1064 error: &MismatchedProjectionTypes<'tcx>,
1067 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool;
1069 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>;
1071 fn find_similar_impl_candidates(
1073 trait_ref: ty::PolyTraitRef<'tcx>,
1074 ) -> Vec<ty::TraitRef<'tcx>>;
1076 fn report_similar_impl_candidates(
1078 impl_candidates: Vec<ty::TraitRef<'tcx>>,
1079 err: &mut DiagnosticBuilder<'_>,
1082 /// Gets the parent trait chain start
1083 fn get_parent_trait_ref(
1085 code: &ObligationCauseCode<'tcx>,
1086 ) -> Option<(String, Option<Span>)>;
1088 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1089 /// with the same path as `trait_ref`, a help message about
1090 /// a probable version mismatch is added to `err`
1091 fn note_version_mismatch(
1093 err: &mut DiagnosticBuilder<'_>,
1094 trait_ref: &ty::PolyTraitRef<'tcx>,
1097 /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
1100 /// For this to work, `new_self_ty` must have no escaping bound variables.
1101 fn mk_trait_obligation_with_new_self_ty(
1103 param_env: ty::ParamEnv<'tcx>,
1104 trait_ref: ty::PolyTraitRef<'tcx>,
1105 new_self_ty: Ty<'tcx>,
1106 ) -> PredicateObligation<'tcx>;
1108 fn maybe_report_ambiguity(
1110 obligation: &PredicateObligation<'tcx>,
1111 body_id: Option<hir::BodyId>,
1114 fn predicate_can_apply(
1116 param_env: ty::ParamEnv<'tcx>,
1117 pred: ty::PolyTraitRef<'tcx>,
1120 fn note_obligation_cause(
1122 err: &mut DiagnosticBuilder<'tcx>,
1123 obligation: &PredicateObligation<'tcx>,
1126 fn suggest_unsized_bound_if_applicable(
1128 err: &mut DiagnosticBuilder<'tcx>,
1129 obligation: &PredicateObligation<'tcx>,
1132 fn is_recursive_obligation(
1134 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1135 cause_code: &ObligationCauseCode<'tcx>,
1139 impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> {
1140 // returns if `cond` not occurring implies that `error` does not occur - i.e., that
1141 // `error` occurring implies that `cond` occurs.
1142 fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool {
1147 // FIXME: It should be possible to deal with `ForAll` in a cleaner way.
1148 let bound_error = error.kind();
1149 let (cond, error) = match (cond.kind().skip_binder(), bound_error.skip_binder()) {
1150 (ty::PredicateKind::Trait(..), ty::PredicateKind::Trait(error, _)) => {
1151 (cond, bound_error.rebind(error))
1154 // FIXME: make this work in other cases too.
1159 for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) {
1160 let bound_predicate = obligation.predicate.kind();
1161 if let ty::PredicateKind::Trait(implication, _) = bound_predicate.skip_binder() {
1162 let error = error.to_poly_trait_ref();
1163 let implication = bound_predicate.rebind(implication.trait_ref);
1164 // FIXME: I'm just not taking associated types at all here.
1165 // Eventually I'll need to implement param-env-aware
1166 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
1167 let param_env = ty::ParamEnv::empty();
1168 if self.can_sub(param_env, error, implication).is_ok() {
1169 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
1178 fn report_fulfillment_error(
1180 error: &FulfillmentError<'tcx>,
1181 body_id: Option<hir::BodyId>,
1182 fallback_has_occurred: bool,
1184 debug!("report_fulfillment_error({:?})", error);
1186 FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
1187 self.report_selection_error(
1188 error.obligation.clone(),
1189 &error.root_obligation,
1191 fallback_has_occurred,
1192 error.points_at_arg_span,
1195 FulfillmentErrorCode::CodeProjectionError(ref e) => {
1196 self.report_projection_error(&error.obligation, e);
1198 FulfillmentErrorCode::CodeAmbiguity => {
1199 self.maybe_report_ambiguity(&error.obligation, body_id);
1201 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
1202 self.report_mismatched_types(
1203 &error.obligation.cause,
1204 expected_found.expected,
1205 expected_found.found,
1210 FulfillmentErrorCode::CodeConstEquateError(ref expected_found, ref err) => {
1211 self.report_mismatched_consts(
1212 &error.obligation.cause,
1213 expected_found.expected,
1214 expected_found.found,
1222 fn report_projection_error(
1224 obligation: &PredicateObligation<'tcx>,
1225 error: &MismatchedProjectionTypes<'tcx>,
1227 let predicate = self.resolve_vars_if_possible(obligation.predicate);
1229 if predicate.references_error() {
1235 let mut err = &error.err;
1236 let mut values = None;
1238 // try to find the mismatched types to report the error with.
1240 // this can fail if the problem was higher-ranked, in which
1241 // cause I have no idea for a good error message.
1242 let bound_predicate = predicate.kind();
1243 if let ty::PredicateKind::Projection(data) = bound_predicate.skip_binder() {
1244 let mut selcx = SelectionContext::new(self);
1245 let (data, _) = self.replace_bound_vars_with_fresh_vars(
1246 obligation.cause.span,
1247 infer::LateBoundRegionConversionTime::HigherRankedType,
1248 bound_predicate.rebind(data),
1250 let mut obligations = vec![];
1251 let normalized_ty = super::normalize_projection_type(
1253 obligation.param_env,
1255 obligation.cause.clone(),
1261 "report_projection_error obligation.cause={:?} obligation.param_env={:?}",
1262 obligation.cause, obligation.param_env
1266 "report_projection_error normalized_ty={:?} data.ty={:?}",
1267 normalized_ty, data.ty
1270 let is_normalized_ty_expected = !matches!(
1271 obligation.cause.code.peel_derives(),
1272 ObligationCauseCode::ItemObligation(_)
1273 | ObligationCauseCode::BindingObligation(_, _)
1274 | ObligationCauseCode::ObjectCastObligation(_)
1275 | ObligationCauseCode::OpaqueType
1278 if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
1279 is_normalized_ty_expected,
1283 values = Some(infer::ValuePairs::Types(ExpectedFound::new(
1284 is_normalized_ty_expected,
1294 let msg = format!("type mismatch resolving `{}`", predicate);
1295 let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg);
1296 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
1298 let mut diag = struct_span_err!(
1300 obligation.cause.span,
1302 "type mismatch resolving `{}`",
1305 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
1306 self.note_obligation_cause(&mut diag, obligation);
1312 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1313 /// returns the fuzzy category of a given type, or None
1314 /// if the type can be equated to any type.
1315 fn type_category(t: Ty<'_>) -> Option<u32> {
1317 ty::Bool => Some(0),
1318 ty::Char => Some(1),
1320 ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
1321 ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
1322 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1323 ty::Array(..) | ty::Slice(..) => Some(6),
1324 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1325 ty::Dynamic(..) => Some(8),
1326 ty::Closure(..) => Some(9),
1327 ty::Tuple(..) => Some(10),
1328 ty::Projection(..) => Some(11),
1329 ty::Param(..) => Some(12),
1330 ty::Opaque(..) => Some(13),
1331 ty::Never => Some(14),
1332 ty::Adt(adt, ..) => match adt.adt_kind() {
1333 AdtKind::Struct => Some(15),
1334 AdtKind::Union => Some(16),
1335 AdtKind::Enum => Some(17),
1337 ty::Generator(..) => Some(18),
1338 ty::Foreign(..) => Some(19),
1339 ty::GeneratorWitness(..) => Some(20),
1340 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1344 match (type_category(a), type_category(b)) {
1345 (Some(cat_a), Some(cat_b)) => match (a.kind(), b.kind()) {
1346 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
1347 _ => cat_a == cat_b,
1349 // infer and error can be equated to all types
1354 fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
1355 self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
1356 hir::GeneratorKind::Gen => "a generator",
1357 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
1358 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
1359 hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
1363 fn find_similar_impl_candidates(
1365 trait_ref: ty::PolyTraitRef<'tcx>,
1366 ) -> Vec<ty::TraitRef<'tcx>> {
1367 let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
1368 let all_impls = self.tcx.all_impls(trait_ref.def_id());
1371 Some(simp) => all_impls
1372 .filter_map(|def_id| {
1373 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
1374 let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
1375 if let Some(imp_simp) = imp_simp {
1376 if simp != imp_simp {
1380 if self.tcx.impl_polarity(def_id) == ty::ImplPolarity::Negative {
1387 .filter_map(|def_id| {
1388 if self.tcx.impl_polarity(def_id) == ty::ImplPolarity::Negative {
1391 self.tcx.impl_trait_ref(def_id)
1397 fn report_similar_impl_candidates(
1399 impl_candidates: Vec<ty::TraitRef<'tcx>>,
1400 err: &mut DiagnosticBuilder<'_>,
1402 if impl_candidates.is_empty() {
1406 let len = impl_candidates.len();
1407 let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 };
1409 let normalize = |candidate| {
1410 self.tcx.infer_ctxt().enter(|ref infcx| {
1411 let normalized = infcx
1412 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
1413 .normalize(candidate)
1416 Some(normalized) => format!("\n {}", normalized.value),
1417 None => format!("\n {}", candidate),
1422 // Sort impl candidates so that ordering is consistent for UI tests.
1423 let mut normalized_impl_candidates =
1424 impl_candidates.iter().copied().map(normalize).collect::<Vec<String>>();
1426 // Sort before taking the `..end` range,
1427 // because the ordering of `impl_candidates` may not be deterministic:
1428 // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
1429 normalized_impl_candidates.sort();
1432 "the following implementations were found:{}{}",
1433 normalized_impl_candidates[..end].join(""),
1434 if len > 5 { format!("\nand {} others", len - 4) } else { String::new() }
1438 /// Gets the parent trait chain start
1439 fn get_parent_trait_ref(
1441 code: &ObligationCauseCode<'tcx>,
1442 ) -> Option<(String, Option<Span>)> {
1444 ObligationCauseCode::BuiltinDerivedObligation(data) => {
1445 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
1446 match self.get_parent_trait_ref(&data.parent_code) {
1449 let ty = parent_trait_ref.skip_binder().self_ty();
1450 let span = TyCategory::from_ty(self.tcx, ty)
1451 .map(|(_, def_id)| self.tcx.def_span(def_id));
1452 Some((ty.to_string(), span))
1460 /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
1461 /// with the same path as `trait_ref`, a help message about
1462 /// a probable version mismatch is added to `err`
1463 fn note_version_mismatch(
1465 err: &mut DiagnosticBuilder<'_>,
1466 trait_ref: &ty::PolyTraitRef<'tcx>,
1468 let get_trait_impl = |trait_def_id| {
1469 self.tcx.find_map_relevant_impl(trait_def_id, trait_ref.skip_binder().self_ty(), Some)
1471 let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
1472 let all_traits = self.tcx.all_traits(());
1473 let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
1475 .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
1476 .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
1478 for trait_with_same_path in traits_with_same_path {
1479 if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
1480 let impl_span = self.tcx.def_span(impl_def_id);
1481 err.span_help(impl_span, "trait impl with same name found");
1482 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
1483 let crate_msg = format!(
1484 "perhaps two different versions of crate `{}` are being used?",
1487 err.note(&crate_msg);
1492 fn mk_trait_obligation_with_new_self_ty(
1494 param_env: ty::ParamEnv<'tcx>,
1495 trait_ref: ty::PolyTraitRef<'tcx>,
1496 new_self_ty: Ty<'tcx>,
1497 ) -> PredicateObligation<'tcx> {
1498 assert!(!new_self_ty.has_escaping_bound_vars());
1500 let trait_ref = trait_ref.map_bound_ref(|tr| ty::TraitRef {
1501 substs: self.tcx.mk_substs_trait(new_self_ty, &tr.substs[1..]),
1506 ObligationCause::dummy(),
1508 trait_ref.without_const().to_predicate(self.tcx),
1512 fn maybe_report_ambiguity(
1514 obligation: &PredicateObligation<'tcx>,
1515 body_id: Option<hir::BodyId>,
1517 // Unable to successfully determine, probably means
1518 // insufficient type information, but could mean
1519 // ambiguous impls. The latter *ought* to be a
1520 // coherence violation, so we don't report it here.
1522 let predicate = self.resolve_vars_if_possible(obligation.predicate);
1523 let span = obligation.cause.span;
1526 "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
1527 predicate, obligation, body_id, obligation.cause.code,
1530 // Ambiguity errors are often caused as fallout from earlier
1531 // errors. So just ignore them if this infcx is tainted.
1532 if self.is_tainted_by_errors() {
1536 let bound_predicate = predicate.kind();
1537 let mut err = match bound_predicate.skip_binder() {
1538 ty::PredicateKind::Trait(data, _) => {
1539 let trait_ref = bound_predicate.rebind(data.trait_ref);
1540 debug!("trait_ref {:?}", trait_ref);
1542 if predicate.references_error() {
1545 // Typically, this ambiguity should only happen if
1546 // there are unresolved type inference variables
1547 // (otherwise it would suggest a coherence
1548 // failure). But given #21974 that is not necessarily
1549 // the case -- we can have multiple where clauses that
1550 // are only distinguished by a region, which results
1551 // in an ambiguity even when all types are fully
1552 // known, since we don't dispatch based on region
1555 // Pick the first substitution that still contains inference variables as the one
1556 // we're going to emit an error for. If there are none (see above), fall back to
1557 // the substitution for `Self`.
1559 let substs = data.trait_ref.substs;
1562 .find(|s| s.has_infer_types_or_consts())
1563 .unwrap_or_else(|| substs[0])
1566 // This is kind of a hack: it frequently happens that some earlier
1567 // error prevents types from being fully inferred, and then we get
1568 // a bunch of uninteresting errors saying something like "<generic
1569 // #0> doesn't implement Sized". It may even be true that we
1570 // could just skip over all checks where the self-ty is an
1571 // inference variable, but I was afraid that there might be an
1572 // inference variable created, registered as an obligation, and
1573 // then never forced by writeback, and hence by skipping here we'd
1574 // be ignoring the fact that we don't KNOW the type works
1575 // out. Though even that would probably be harmless, given that
1576 // we're only talking about builtin traits, which are known to be
1577 // inhabited. We used to check for `self.tcx.sess.has_errors()` to
1578 // avoid inundating the user with unnecessary errors, but we now
1579 // check upstream for type errors and don't add the obligations to
1580 // begin with in those cases.
1581 if self.tcx.lang_items().sized_trait() == Some(trait_ref.def_id()) {
1582 self.emit_inference_failure_err(body_id, span, subst, vec![], ErrorCode::E0282)
1586 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
1587 let mut err = self.emit_inference_failure_err(
1594 err.note(&format!("cannot satisfy `{}`", predicate));
1595 if let ObligationCauseCode::ItemObligation(def_id) = obligation.cause.code {
1596 self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
1599 ObligationCauseCode::BindingObligation(ref def_id, _),
1601 (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
1603 let generics = self.tcx.generics_of(*def_id);
1604 if generics.params.iter().any(|p| p.name != kw::SelfUpper)
1605 && !snippet.ends_with('>')
1607 // FIXME: To avoid spurious suggestions in functions where type arguments
1608 // where already supplied, we check the snippet to make sure it doesn't
1609 // end with a turbofish. Ideally we would have access to a `PathSegment`
1610 // instead. Otherwise we would produce the following output:
1612 // error[E0283]: type annotations needed
1613 // --> $DIR/issue-54954.rs:3:24
1615 // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
1616 // | ^^^^^^^^^^^^^^^^^^^^^^^^^^
1618 // | cannot infer type
1619 // | help: consider specifying the type argument
1620 // | in the function call:
1621 // | `Tt::const_val::<[i8; 123]>::<T>`
1623 // LL | const fn const_val<T: Sized>() -> usize {
1624 // | - required by this bound in `Tt::const_val`
1626 // = note: cannot satisfy `_: Tt`
1628 err.span_suggestion_verbose(
1629 span.shrink_to_hi(),
1631 "consider specifying the type argument{} in the function call",
1632 pluralize!(generics.params.len()),
1639 .map(|p| p.name.to_string())
1640 .collect::<Vec<String>>()
1643 Applicability::HasPlaceholders,
1650 ty::PredicateKind::WellFormed(arg) => {
1651 // Same hacky approach as above to avoid deluging user
1652 // with error messages.
1653 if arg.references_error() || self.tcx.sess.has_errors() {
1657 self.emit_inference_failure_err(body_id, span, arg, vec![], ErrorCode::E0282)
1660 ty::PredicateKind::Subtype(data) => {
1661 if data.references_error() || self.tcx.sess.has_errors() {
1662 // no need to overload user in such cases
1665 let SubtypePredicate { a_is_expected: _, a, b } = data;
1666 // both must be type variables, or the other would've been instantiated
1667 assert!(a.is_ty_var() && b.is_ty_var());
1668 self.emit_inference_failure_err(body_id, span, a.into(), vec![], ErrorCode::E0282)
1670 ty::PredicateKind::Projection(data) => {
1671 let self_ty = data.projection_ty.self_ty();
1673 if predicate.references_error() {
1676 if self_ty.needs_infer() && ty.needs_infer() {
1677 // We do this for the `foo.collect()?` case to produce a suggestion.
1678 let mut err = self.emit_inference_failure_err(
1685 err.note(&format!("cannot satisfy `{}`", predicate));
1688 let mut err = struct_span_err!(
1692 "type annotations needed: cannot satisfy `{}`",
1695 err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1701 if self.tcx.sess.has_errors() {
1704 let mut err = struct_span_err!(
1708 "type annotations needed: cannot satisfy `{}`",
1711 err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1715 self.note_obligation_cause(&mut err, obligation);
1719 /// Returns `true` if the trait predicate may apply for *some* assignment
1720 /// to the type parameters.
1721 fn predicate_can_apply(
1723 param_env: ty::ParamEnv<'tcx>,
1724 pred: ty::PolyTraitRef<'tcx>,
1726 struct ParamToVarFolder<'a, 'tcx> {
1727 infcx: &'a InferCtxt<'a, 'tcx>,
1728 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
1731 impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
1732 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1736 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1737 if let ty::Param(ty::ParamTy { name, .. }) = *ty.kind() {
1738 let infcx = self.infcx;
1739 self.var_map.entry(ty).or_insert_with(|| {
1740 infcx.next_ty_var(TypeVariableOrigin {
1741 kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
1746 ty.super_fold_with(self)
1752 let mut selcx = SelectionContext::new(self);
1755 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
1757 let cleaned_pred = super::project::normalize(
1760 ObligationCause::dummy(),
1765 let obligation = Obligation::new(
1766 ObligationCause::dummy(),
1768 cleaned_pred.without_const().to_predicate(selcx.tcx()),
1771 self.predicate_may_hold(&obligation)
1775 fn note_obligation_cause(
1777 err: &mut DiagnosticBuilder<'tcx>,
1778 obligation: &PredicateObligation<'tcx>,
1780 // First, attempt to add note to this error with an async-await-specific
1781 // message, and fall back to regular note otherwise.
1782 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
1783 self.note_obligation_cause_code(
1785 &obligation.predicate,
1786 &obligation.cause.code,
1788 &mut Default::default(),
1790 self.suggest_unsized_bound_if_applicable(err, obligation);
1794 fn suggest_unsized_bound_if_applicable(
1796 err: &mut DiagnosticBuilder<'tcx>,
1797 obligation: &PredicateObligation<'tcx>,
1799 let (pred, item_def_id, span) =
1800 match (obligation.predicate.kind().skip_binder(), obligation.cause.code.peel_derives())
1803 ty::PredicateKind::Trait(pred, _),
1804 &ObligationCauseCode::BindingObligation(item_def_id, span),
1805 ) => (pred, item_def_id, span),
1810 self.tcx.hir().get_if_local(item_def_id),
1811 Some(pred.def_id()) == self.tcx.lang_items().sized_trait(),
1813 (Some(node), true) => node,
1816 let generics = match node.generics() {
1817 Some(generics) => generics,
1820 for param in generics.params {
1821 if param.span != span
1822 || param.bounds.iter().any(|bound| {
1823 bound.trait_ref().and_then(|trait_ref| trait_ref.trait_def_id())
1824 == self.tcx.lang_items().sized_trait()
1835 hir::ItemKind::Enum(..)
1836 | hir::ItemKind::Struct(..)
1837 | hir::ItemKind::Union(..),
1841 // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
1842 // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
1844 let mut visitor = FindTypeParam {
1845 param: param.name.ident().name,
1846 invalid_spans: vec![],
1849 visitor.visit_item(item);
1850 if !visitor.invalid_spans.is_empty() {
1851 let mut multispan: MultiSpan = param.span.into();
1852 multispan.push_span_label(
1854 format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
1856 for sp in visitor.invalid_spans {
1857 multispan.push_span_label(
1860 "...if indirection were used here: `Box<{}>`",
1868 "you could relax the implicit `Sized` bound on `{T}` if it were \
1869 used through indirection like `&{T}` or `Box<{T}>`",
1870 T = param.name.ident(),
1878 let (span, separator) = match param.bounds {
1879 [] => (span.shrink_to_hi(), ":"),
1880 [.., bound] => (bound.span().shrink_to_hi(), " +"),
1882 err.span_suggestion_verbose(
1884 "consider relaxing the implicit `Sized` restriction",
1885 format!("{} ?Sized", separator),
1886 Applicability::MachineApplicable,
1892 fn is_recursive_obligation(
1894 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1895 cause_code: &ObligationCauseCode<'tcx>,
1897 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1898 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
1900 if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
1908 /// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
1909 /// `param: ?Sized` would be a valid constraint.
1910 struct FindTypeParam {
1911 param: rustc_span::Symbol,
1912 invalid_spans: Vec<Span>,
1916 impl<'v> Visitor<'v> for FindTypeParam {
1917 type Map = rustc_hir::intravisit::ErasedMap<'v>;
1919 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
1920 hir::intravisit::NestedVisitorMap::None
1923 fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
1924 // Skip where-clauses, to avoid suggesting indirection for type parameters found there.
1927 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1928 // We collect the spans of all uses of the "bare" type param, like in `field: T` or
1929 // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
1930 // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
1931 // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
1932 // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
1933 // in that case should make what happened clear enough.
1935 hir::TyKind::Ptr(_) | hir::TyKind::Rptr(..) | hir::TyKind::TraitObject(..) => {}
1936 hir::TyKind::Path(hir::QPath::Resolved(None, path))
1937 if path.segments.len() == 1 && path.segments[0].ident.name == self.param =>
1940 self.invalid_spans.push(ty.span);
1943 hir::TyKind::Path(_) => {
1944 let prev = self.nested;
1946 hir::intravisit::walk_ty(self, ty);
1950 hir::intravisit::walk_ty(self, ty);
1956 pub fn recursive_type_with_infinite_size_error(
1961 assert!(type_def_id.is_local());
1962 let span = tcx.hir().span_if_local(type_def_id).unwrap();
1963 let span = tcx.sess.source_map().guess_head_span(span);
1964 let path = tcx.def_path_str(type_def_id);
1966 struct_span_err!(tcx.sess, span, E0072, "recursive type `{}` has infinite size", path);
1967 err.span_label(span, "recursive type has infinite size");
1968 for &span in &spans {
1969 err.span_label(span, "recursive without indirection");
1972 "insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `{}` representable",
1975 if spans.len() <= 4 {
1976 err.multipart_suggestion(
1982 (span.shrink_to_lo(), "Box<".to_string()),
1983 (span.shrink_to_hi(), ">".to_string()),
1988 Applicability::HasPlaceholders,
1996 /// Summarizes information
1999 /// An argument of non-tuple type. Parameters are (name, ty)
2000 Arg(String, String),
2002 /// An argument of tuple type. For a "found" argument, the span is
2003 /// the location in the source of the pattern. For a "expected"
2004 /// argument, it will be None. The vector is a list of (name, ty)
2005 /// strings for the components of the tuple.
2006 Tuple(Option<Span>, Vec<(String, String)>),
2010 fn empty() -> ArgKind {
2011 ArgKind::Arg("_".to_owned(), "_".to_owned())
2014 /// Creates an `ArgKind` from the expected type of an
2015 /// argument. It has no name (`_`) and an optional source span.
2016 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
2018 ty::Tuple(tys) => ArgKind::Tuple(
2020 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
2022 _ => ArgKind::Arg("_".to_owned(), t.to_string()),