1 // ignore-tidy-filelength
3 use super::{DefIdOrName, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation};
5 use crate::autoderef::Autoderef;
6 use crate::infer::InferCtxt;
7 use crate::traits::{NormalizeExt, ObligationCtxt};
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_data_structures::stack::ensure_sufficient_stack;
14 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
15 ErrorGuaranteed, MultiSpan, Style,
18 use rustc_hir::def::DefKind;
19 use rustc_hir::def_id::DefId;
20 use rustc_hir::intravisit::Visitor;
21 use rustc_hir::lang_items::LangItem;
22 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
23 use rustc_infer::infer::error_reporting::TypeErrCtxt;
24 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
25 use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime};
26 use rustc_middle::hir::map;
27 use rustc_middle::ty::error::TypeError::{self, Sorts};
28 use rustc_middle::ty::relate::TypeRelation;
29 use rustc_middle::ty::{
30 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
31 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, InternalSubsts,
32 IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder,
33 TypeSuperFoldable, TypeVisitable, TypeckResults,
35 use rustc_span::symbol::{sym, Ident, Symbol};
36 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
37 use rustc_target::spec::abi;
40 use super::method_chain::CollectAllMismatches;
41 use super::InferCtxtPrivExt;
42 use crate::infer::InferCtxtExt as _;
43 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
44 use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
47 pub enum GeneratorInteriorOrUpvar {
48 // span of interior type
49 Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
54 // This type provides a uniform interface to retrieve data on generators, whether it originated from
55 // the local crate being compiled or from a foreign crate.
57 pub enum GeneratorData<'tcx, 'a> {
58 Local(&'a TypeckResults<'tcx>),
59 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
62 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
63 // Try to get information about variables captured by the generator that matches a type we are
64 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
66 fn try_get_upvar_span<F>(
68 infer_context: &InferCtxt<'tcx>,
71 ) -> Option<GeneratorInteriorOrUpvar>
73 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
76 GeneratorData::Local(typeck_results) => {
77 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
78 upvars.iter().find_map(|(upvar_id, upvar)| {
79 let upvar_ty = typeck_results.node_type(*upvar_id);
80 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
81 if ty_matches(ty::Binder::dummy(upvar_ty)) {
82 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
89 GeneratorData::Foreign(_) => None,
93 // Try to get the span of a type being awaited on that matches the type we are looking with the
94 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
96 fn get_from_await_ty<F>(
98 visitor: AwaitsVisitor,
103 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
106 GeneratorData::Local(typeck_results) => visitor
109 .map(|id| hir.expect_expr(id))
111 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
113 .map(|expr| expr.span),
114 GeneratorData::Foreign(generator_diagnostic_data) => visitor
117 .map(|id| hir.expect_expr(id))
119 ty_matches(ty::Binder::dummy(
120 generator_diagnostic_data
122 .get(&await_expr.hir_id.local_id)
123 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
125 .map_or_else::<Ty<'tcx>, _, _>(
127 generator_diagnostic_data
129 .get(&await_expr.hir_id.local_id)
133 "node_type: no type for node `{}`",
134 ty::tls::with(|tcx| tcx
136 .node_to_string(await_expr.hir_id))
144 .map(|expr| expr.span),
148 /// Get the type, expression, span and optional scope span of all types
149 /// that are live across the yield of this generator
150 fn get_generator_interior_types(
152 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
154 GeneratorData::Local(typeck_result) => {
155 typeck_result.generator_interior_types.as_deref()
157 GeneratorData::Foreign(generator_diagnostic_data) => {
158 generator_diagnostic_data.generator_interior_types.as_deref()
163 // Used to get the source of the data, note we don't have as much information for generators
164 // originated from foreign crates
165 fn is_foreign(&self) -> bool {
167 GeneratorData::Local(_) => false,
168 GeneratorData::Foreign(_) => true,
173 // This trait is public to expose the diagnostics methods to clippy.
174 pub trait TypeErrCtxtExt<'tcx> {
175 fn suggest_restricting_param_bound(
177 err: &mut Diagnostic,
178 trait_pred: ty::PolyTraitPredicate<'tcx>,
179 associated_item: Option<(&'static str, Ty<'tcx>)>,
183 fn suggest_dereferences(
185 obligation: &PredicateObligation<'tcx>,
186 err: &mut Diagnostic,
187 trait_pred: ty::PolyTraitPredicate<'tcx>,
190 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
194 obligation: &PredicateObligation<'tcx>,
195 err: &mut Diagnostic,
196 trait_pred: ty::PolyTraitPredicate<'tcx>,
199 fn suggest_add_reference_to_arg(
201 obligation: &PredicateObligation<'tcx>,
202 err: &mut Diagnostic,
203 trait_pred: ty::PolyTraitPredicate<'tcx>,
204 has_custom_message: bool,
207 fn suggest_borrowing_for_object_cast(
209 err: &mut Diagnostic,
210 obligation: &PredicateObligation<'tcx>,
215 fn suggest_remove_reference(
217 obligation: &PredicateObligation<'tcx>,
218 err: &mut Diagnostic,
219 trait_pred: ty::PolyTraitPredicate<'tcx>,
222 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
224 fn suggest_change_mut(
226 obligation: &PredicateObligation<'tcx>,
227 err: &mut Diagnostic,
228 trait_pred: ty::PolyTraitPredicate<'tcx>,
231 fn suggest_semicolon_removal(
233 obligation: &PredicateObligation<'tcx>,
234 err: &mut Diagnostic,
236 trait_pred: ty::PolyTraitPredicate<'tcx>,
239 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
241 fn suggest_impl_trait(
243 err: &mut Diagnostic,
245 obligation: &PredicateObligation<'tcx>,
246 trait_pred: ty::PolyTraitPredicate<'tcx>,
249 fn point_at_returns_when_relevant(
251 err: &mut Diagnostic,
252 obligation: &PredicateObligation<'tcx>,
255 fn report_closure_arg_mismatch(
258 found_span: Option<Span>,
259 found: ty::PolyTraitRef<'tcx>,
260 expected: ty::PolyTraitRef<'tcx>,
261 cause: &ObligationCauseCode<'tcx>,
262 found_node: Option<Node<'_>>,
263 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
265 fn note_conflicting_closure_bounds(
267 cause: &ObligationCauseCode<'tcx>,
268 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
271 fn suggest_fully_qualified_path(
273 err: &mut Diagnostic,
279 fn maybe_note_obligation_cause_for_async_await(
281 err: &mut Diagnostic,
282 obligation: &PredicateObligation<'tcx>,
285 fn note_obligation_cause_for_async_await(
287 err: &mut Diagnostic,
288 interior_or_upvar_span: GeneratorInteriorOrUpvar,
290 outer_generator: Option<DefId>,
291 trait_pred: ty::TraitPredicate<'tcx>,
293 typeck_results: Option<&ty::TypeckResults<'tcx>>,
294 obligation: &PredicateObligation<'tcx>,
295 next_code: Option<&ObligationCauseCode<'tcx>>,
298 fn note_obligation_cause_code<T>(
300 err: &mut Diagnostic,
302 param_env: ty::ParamEnv<'tcx>,
303 cause_code: &ObligationCauseCode<'tcx>,
304 obligated_types: &mut Vec<Ty<'tcx>>,
305 seen_requirements: &mut FxHashSet<DefId>,
307 T: ToPredicate<'tcx>;
309 /// Suggest to await before try: future? => future.await?
310 fn suggest_await_before_try(
312 err: &mut Diagnostic,
313 obligation: &PredicateObligation<'tcx>,
314 trait_pred: ty::PolyTraitPredicate<'tcx>,
318 fn suggest_floating_point_literal(
320 obligation: &PredicateObligation<'tcx>,
321 err: &mut Diagnostic,
322 trait_ref: &ty::PolyTraitRef<'tcx>,
327 obligation: &PredicateObligation<'tcx>,
328 err: &mut Diagnostic,
329 trait_pred: ty::PolyTraitPredicate<'tcx>,
332 fn suggest_dereferencing_index(
334 obligation: &PredicateObligation<'tcx>,
335 err: &mut Diagnostic,
336 trait_pred: ty::PolyTraitPredicate<'tcx>,
338 fn function_argument_obligation(
341 err: &mut Diagnostic,
342 parent_code: &ObligationCauseCode<'tcx>,
343 param_env: ty::ParamEnv<'tcx>,
344 predicate: ty::Predicate<'tcx>,
349 expr: &hir::Expr<'_>,
350 typeck_results: &TypeckResults<'tcx>,
351 type_diffs: Vec<TypeError<'tcx>>,
352 param_env: ty::ParamEnv<'tcx>,
353 err: &mut Diagnostic,
357 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
359 generics.tail_span_for_predicate_suggestion(),
360 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
364 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
365 /// it can also be an `impl Trait` param that needs to be decomposed to a type
366 /// param for cleaner code.
367 fn suggest_restriction<'tcx>(
370 hir_generics: &hir::Generics<'tcx>,
372 err: &mut Diagnostic,
373 fn_sig: Option<&hir::FnSig<'_>>,
374 projection: Option<&ty::AliasTy<'_>>,
375 trait_pred: ty::PolyTraitPredicate<'tcx>,
376 // When we are dealing with a trait, `super_traits` will be `Some`:
377 // Given `trait T: A + B + C {}`
378 // - ^^^^^^^^^ GenericBounds
381 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
383 if hir_generics.where_clause_span.from_expansion()
384 || hir_generics.where_clause_span.desugaring_kind().is_some()
388 let Some(item_id) = hir_id.as_owner() else { return; };
389 let generics = tcx.generics_of(item_id);
390 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
391 if let Some((param, bound_str, fn_sig)) =
392 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
393 // Shenanigans to get the `Trait` from the `impl Trait`.
394 ty::Param(param) => {
395 let param_def = generics.type_param(param, tcx);
396 if param_def.kind.is_synthetic() {
398 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
399 return Some((param_def, bound_str, sig));
406 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
407 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
410 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
413 if !trait_pred.is_suggestable(tcx, false) {
416 // We know we have an `impl Trait` that doesn't satisfy a required projection.
418 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
419 // types. There should be at least one, but there might be *more* than one. In that
420 // case we could just ignore it and try to identify which one needs the restriction,
421 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
423 let mut ty_spans = vec![];
424 for input in fn_sig.decl.inputs {
425 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
428 // The type param `T: Trait` we will suggest to introduce.
429 let type_param = format!("{}: {}", type_param_name, bound_str);
432 if let Some(span) = hir_generics.span_for_param_suggestion() {
433 (span, format!(", {}", type_param))
435 (hir_generics.span, format!("<{}>", type_param))
437 // `fn foo(t: impl Trait)`
438 // ^ suggest `where <T as Trait>::A: Bound`
439 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
441 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
443 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
444 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
445 // `fn foo(t: impl Trait<A: Bound>)` instead.
446 err.multipart_suggestion(
447 "introduce a type parameter with a trait bound instead of using `impl Trait`",
449 Applicability::MaybeIncorrect,
452 if !trait_pred.is_suggestable(tcx, false) {
455 // Trivial case: `T` needs an extra bound: `T: Bound`.
456 let (sp, suggestion) = match (
460 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
463 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
464 (None, Some((ident, []))) => (
465 ident.span.shrink_to_hi(),
466 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
468 (_, Some((_, [.., bounds]))) => (
469 bounds.span().shrink_to_hi(),
470 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
472 (Some(_), Some((_, []))) => (
473 hir_generics.span.shrink_to_hi(),
474 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
478 err.span_suggestion_verbose(
480 &format!("consider further restricting {}", msg),
482 Applicability::MachineApplicable,
487 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
488 fn suggest_restricting_param_bound(
490 mut err: &mut Diagnostic,
491 trait_pred: ty::PolyTraitPredicate<'tcx>,
492 associated_ty: Option<(&'static str, Ty<'tcx>)>,
495 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
497 let self_ty = trait_pred.skip_binder().self_ty();
498 let (param_ty, projection) = match self_ty.kind() {
499 ty::Param(_) => (true, None),
500 ty::Alias(ty::Projection, projection) => (false, Some(projection)),
504 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
505 // don't suggest `T: Sized + ?Sized`.
506 let mut hir_id = body_id;
507 while let Some(node) = self.tcx.hir().find(hir_id) {
509 hir::Node::Item(hir::Item {
511 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
513 }) if self_ty == self.tcx.types.self_param => {
515 // Restricting `Self` for a single method.
525 Some((ident, bounds)),
530 hir::Node::TraitItem(hir::TraitItem {
532 kind: hir::TraitItemKind::Fn(..),
534 }) if self_ty == self.tcx.types.self_param => {
536 // Restricting `Self` for a single method.
538 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
544 hir::Node::TraitItem(hir::TraitItem {
546 kind: hir::TraitItemKind::Fn(fn_sig, ..),
549 | hir::Node::ImplItem(hir::ImplItem {
551 kind: hir::ImplItemKind::Fn(fn_sig, ..),
554 | hir::Node::Item(hir::Item {
555 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
556 }) if projection.is_some() => {
557 // Missing restriction on associated type of type parameter (unmet projection).
562 "the associated type",
571 hir::Node::Item(hir::Item {
573 hir::ItemKind::Trait(_, _, generics, ..)
574 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
576 }) if projection.is_some() => {
577 // Missing restriction on associated type of type parameter (unmet projection).
582 "the associated type",
592 hir::Node::Item(hir::Item {
594 hir::ItemKind::Struct(_, generics)
595 | hir::ItemKind::Enum(_, generics)
596 | hir::ItemKind::Union(_, generics)
597 | hir::ItemKind::Trait(_, _, generics, ..)
598 | hir::ItemKind::Impl(hir::Impl { generics, .. })
599 | hir::ItemKind::Fn(_, generics, _)
600 | hir::ItemKind::TyAlias(_, generics)
601 | hir::ItemKind::TraitAlias(generics, _)
602 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
605 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
606 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
609 // We skip the 0'th subst (self) because we do not want
610 // to consider the predicate as not suggestible if the
611 // self type is an arg position `impl Trait` -- instead,
612 // we handle that by adding ` + Bound` below.
613 // FIXME(compiler-errors): It would be nice to do the same
614 // this that we do in `suggest_restriction` and pull the
615 // `impl Trait` into a new generic if it shows up somewhere
616 // else in the predicate.
617 if !trait_pred.skip_binder().trait_ref.substs[1..]
619 .all(|g| g.is_suggestable(self.tcx, false))
623 // Missing generic type parameter bound.
624 let param_name = self_ty.to_string();
625 let mut constraint = with_no_trimmed_paths!(
626 trait_pred.print_modifiers_and_trait_path().to_string()
629 if let Some((name, term)) = associated_ty {
630 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
631 // That should be extracted into a helper function.
632 if constraint.ends_with('>') {
633 constraint = format!(
635 &constraint[..constraint.len() - 1],
640 constraint.push_str(&format!("<{} = {}>", name, term));
644 if suggest_constraining_type_param(
650 Some(trait_pred.def_id()),
656 hir::Node::Item(hir::Item {
658 hir::ItemKind::Struct(_, generics)
659 | hir::ItemKind::Enum(_, generics)
660 | hir::ItemKind::Union(_, generics)
661 | hir::ItemKind::Trait(_, _, generics, ..)
662 | hir::ItemKind::Impl(hir::Impl { generics, .. })
663 | hir::ItemKind::Fn(_, generics, _)
664 | hir::ItemKind::TyAlias(_, generics)
665 | hir::ItemKind::TraitAlias(generics, _)
666 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
669 // Missing generic type parameter bound.
670 if suggest_arbitrary_trait_bound(
680 hir::Node::Crate(..) => return,
685 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
689 /// When after several dereferencing, the reference satisfies the trait
690 /// binding. This function provides dereference suggestion for this
691 /// specific situation.
692 fn suggest_dereferences(
694 obligation: &PredicateObligation<'tcx>,
695 err: &mut Diagnostic,
696 trait_pred: ty::PolyTraitPredicate<'tcx>,
698 // It only make sense when suggesting dereferences for arguments
699 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = obligation.cause.code()
700 else { return false; };
701 let Some(typeck_results) = &self.typeck_results
702 else { return false; };
703 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
704 else { return false; };
705 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
706 else { return false; };
708 let span = obligation.cause.span;
709 let mut real_trait_pred = trait_pred;
710 let mut code = obligation.cause.code();
711 while let Some((parent_code, parent_trait_pred)) = code.parent() {
713 if let Some(parent_trait_pred) = parent_trait_pred {
714 real_trait_pred = parent_trait_pred;
717 let real_ty = real_trait_pred.self_ty();
718 // We `erase_late_bound_regions` here because `make_subregion` does not handle
719 // `ReLateBound`, and we don't particularly care about the regions.
721 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
727 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
728 let mut autoderef = Autoderef::new(
730 obligation.param_env,
731 obligation.cause.body_id,
735 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
737 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
739 // Remapping bound vars here
740 let real_trait_pred_and_ty =
741 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
742 let obligation = self.mk_trait_obligation_with_new_self_ty(
743 obligation.param_env,
744 real_trait_pred_and_ty,
746 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
749 // Don't care about `&mut` because `DerefMut` is used less
750 // often and user will not expect autoderef happens.
751 if let Some(hir::Node::Expr(hir::Expr {
753 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
755 })) = self.tcx.hir().find(*arg_hir_id)
757 let derefs = "*".repeat(steps);
758 err.span_suggestion_verbose(
759 expr.span.shrink_to_lo(),
760 "consider dereferencing here",
762 Applicability::MachineApplicable,
767 } else if real_trait_pred != trait_pred {
768 // This branch addresses #87437.
770 // Remapping bound vars here
771 let real_trait_pred_and_base_ty =
772 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
773 let obligation = self.mk_trait_obligation_with_new_self_ty(
774 obligation.param_env,
775 real_trait_pred_and_base_ty,
777 if self.predicate_may_hold(&obligation) {
778 let call_node = self.tcx.hir().get(*call_hir_id);
779 let msg = "consider dereferencing here";
780 let is_receiver = matches!(
782 Node::Expr(hir::Expr {
783 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
786 if receiver_expr.hir_id == *arg_hir_id
789 err.multipart_suggestion_verbose(
792 (span.shrink_to_lo(), "(*".to_string()),
793 (span.shrink_to_hi(), ")".to_string()),
795 Applicability::MachineApplicable,
798 err.span_suggestion_verbose(
802 Applicability::MachineApplicable,
813 /// Given a closure's `DefId`, return the given name of the closure.
815 /// This doesn't account for reassignments, but it's only used for suggestions.
816 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
817 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
818 // Get the local name of this closure. This can be inaccurate because
819 // of the possibility of reassignment, but this should be good enough.
821 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
831 let hir = self.tcx.hir();
832 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
833 let parent_node = hir.get_parent_node(hir_id);
834 match hir.find(parent_node) {
835 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
836 get_name(err, &local.pat.kind)
838 // Different to previous arm because one is `&hir::Local` and the other
839 // is `P<hir::Local>`.
840 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
845 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
846 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
847 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
850 obligation: &PredicateObligation<'tcx>,
851 err: &mut Diagnostic,
852 trait_pred: ty::PolyTraitPredicate<'tcx>,
854 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
855 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
857 // Don't suggest calling to turn an unsized type into a sized type
861 // This is duplicated from `extract_callable_info` in typeck, which
862 // relies on autoderef, so we can't use it here.
863 let found = trait_pred.self_ty().skip_binder().peel_refs();
864 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
866 ty::FnPtr(fn_sig) => {
867 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
869 ty::FnDef(def_id, _) => {
870 let fn_sig = found.fn_sig(self.tcx);
871 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
873 ty::Closure(def_id, substs) => {
874 let fn_sig = substs.as_closure().sig();
876 DefIdOrName::DefId(def_id),
878 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
881 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
882 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
883 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
884 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
885 // args tuple will always be substs[1]
886 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
889 DefIdOrName::DefId(def_id),
890 pred.kind().rebind(proj.term.ty().unwrap()),
891 pred.kind().rebind(args.as_slice()),
898 ty::Dynamic(data, _, ty::Dyn) => {
899 data.iter().find_map(|pred| {
900 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
901 && Some(proj.def_id) == self.tcx.lang_items().fn_once_output()
902 // for existential projection, substs are shifted over by 1
903 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
906 DefIdOrName::Name("trait object"),
907 pred.rebind(proj.term.ty().unwrap()),
908 pred.rebind(args.as_slice()),
916 obligation.param_env.caller_bounds().iter().find_map(|pred| {
917 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
918 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
919 && proj.projection_ty.self_ty() == found
920 // args tuple will always be substs[1]
921 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
924 DefIdOrName::Name("type parameter"),
925 pred.kind().rebind(proj.term.ty().unwrap()),
926 pred.kind().rebind(args.as_slice()),
934 }) else { return false; };
935 let output = self.replace_bound_vars_with_fresh_vars(
936 obligation.cause.span,
937 LateBoundRegionConversionTime::FnCall,
940 let inputs = inputs.skip_binder().iter().map(|ty| {
941 self.replace_bound_vars_with_fresh_vars(
942 obligation.cause.span,
943 LateBoundRegionConversionTime::FnCall,
948 // Remapping bound vars here
949 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
952 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
953 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
957 // Get the name of the callable and the arguments to be used in the suggestion.
958 let hir = self.tcx.hir();
960 let msg = match def_id_or_name {
961 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
962 DefKind::Ctor(CtorOf::Struct, _) => {
963 "use parentheses to construct this tuple struct".to_string()
965 DefKind::Ctor(CtorOf::Variant, _) => {
966 "use parentheses to construct this tuple variant".to_string()
968 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
970 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
975 if ty.is_suggestable(self.tcx, false) {
976 format!("/* {ty} */")
978 "/* value */".to_string()
984 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
985 && obligation.cause.span.can_be_used_for_suggestions()
987 // When the obligation error has been ensured to have been caused by
988 // an argument, the `obligation.cause.span` points at the expression
989 // of the argument, so we can provide a suggestion. Otherwise, we give
990 // a more general note.
991 err.span_suggestion_verbose(
992 obligation.cause.span.shrink_to_hi(),
995 Applicability::HasPlaceholders,
997 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
998 let name = match hir.get_if_local(def_id) {
999 Some(hir::Node::Expr(hir::Expr {
1000 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
1003 err.span_label(*fn_decl_span, "consider calling this closure");
1004 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
1009 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
1010 err.span_label(ident.span, "consider calling this function");
1013 Some(hir::Node::Ctor(..)) => {
1014 let name = self.tcx.def_path_str(def_id);
1016 self.tcx.def_span(def_id),
1017 format!("consider calling the constructor for `{}`", name),
1023 err.help(&format!("{msg}: `{name}({args})`"));
1028 fn suggest_add_reference_to_arg(
1030 obligation: &PredicateObligation<'tcx>,
1031 err: &mut Diagnostic,
1032 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1033 has_custom_message: bool,
1035 let span = obligation.cause.span;
1037 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
1038 obligation.cause.code()
1041 } else if let ObligationCauseCode::ItemObligation(_)
1042 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1044 obligation.cause.code()
1045 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1046 span.ctxt().outer_expn_data().kind
1048 obligation.cause.code()
1053 // List of traits for which it would be nonsensical to suggest borrowing.
1054 // For instance, immutable references are always Copy, so suggesting to
1055 // borrow would always succeed, but it's probably not what the user wanted.
1056 let mut never_suggest_borrow: Vec<_> =
1057 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1059 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1062 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1063 never_suggest_borrow.push(def_id);
1066 let param_env = obligation.param_env;
1068 // Try to apply the original trait binding obligation by borrowing.
1069 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1070 blacklist: &[DefId]|
1072 if blacklist.contains(&old_pred.def_id()) {
1075 // We map bounds to `&T` and `&mut T`
1076 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1079 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1082 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1085 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1089 let mk_result = |trait_pred_and_new_ty| {
1091 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1092 self.predicate_must_hold_modulo_regions(&obligation)
1094 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1095 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1097 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1098 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1099 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1102 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1103 mutability.is_mut(),
1109 if imm_ref_self_ty_satisfies_pred
1110 || mut_ref_self_ty_satisfies_pred
1111 || ref_inner_ty_satisfies_pred
1113 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1114 // We don't want a borrowing suggestion on the fields in structs,
1117 // the_foos: Vec<Foo>
1121 span.ctxt().outer_expn_data().kind,
1122 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1126 if snippet.starts_with('&') {
1127 // This is already a literal borrow and the obligation is failing
1128 // somewhere else in the obligation chain. Do not suggest non-sense.
1131 // We have a very specific type of error, where just borrowing this argument
1132 // might solve the problem. In cases like this, the important part is the
1133 // original type obligation, not the last one that failed, which is arbitrary.
1134 // Because of this, we modify the error to refer to the original obligation and
1135 // return early in the caller.
1137 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1138 if has_custom_message {
1142 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1147 "the trait `{}` is not implemented for `{}`",
1148 old_pred.print_modifiers_and_trait_path(),
1149 old_pred.self_ty().skip_binder(),
1153 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1154 err.span_suggestions(
1155 span.shrink_to_lo(),
1156 "consider borrowing here",
1157 ["&".to_string(), "&mut ".to_string()],
1158 Applicability::MaybeIncorrect,
1161 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1162 err.span_suggestion_verbose(
1163 span.shrink_to_lo(),
1165 "consider{} borrowing here",
1166 if is_mut { " mutably" } else { "" }
1168 format!("&{}", if is_mut { "mut " } else { "" }),
1169 Applicability::MaybeIncorrect,
1178 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1179 try_borrowing(cause.derived.parent_trait_pred, &[])
1180 } else if let ObligationCauseCode::BindingObligation(_, _)
1181 | ObligationCauseCode::ItemObligation(_)
1182 | ObligationCauseCode::ExprItemObligation(..)
1183 | ObligationCauseCode::ExprBindingObligation(..) = code
1185 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1191 // Suggest borrowing the type
1192 fn suggest_borrowing_for_object_cast(
1194 err: &mut Diagnostic,
1195 obligation: &PredicateObligation<'tcx>,
1197 object_ty: Ty<'tcx>,
1199 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1200 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1202 for predicate in predicates.iter() {
1203 if !self.predicate_must_hold_modulo_regions(
1204 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1210 err.span_suggestion(
1211 obligation.cause.span.shrink_to_lo(),
1213 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1216 Applicability::MaybeIncorrect,
1220 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1221 /// suggest removing these references until we reach a type that implements the trait.
1222 fn suggest_remove_reference(
1224 obligation: &PredicateObligation<'tcx>,
1225 err: &mut Diagnostic,
1226 trait_pred: ty::PolyTraitPredicate<'tcx>,
1228 let span = obligation.cause.span;
1230 let mut suggested = false;
1231 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1233 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1234 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1235 // Do not suggest removal of borrow from type arguments.
1239 // Skipping binder here, remapping below
1240 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1242 for refs_remaining in 0..refs_number {
1243 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1246 suggested_ty = *inner_ty;
1248 // Remapping bound vars here
1249 let trait_pred_and_suggested_ty =
1250 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1252 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1253 obligation.param_env,
1254 trait_pred_and_suggested_ty,
1257 if self.predicate_may_hold(&new_obligation) {
1262 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1264 let remove_refs = refs_remaining + 1;
1266 let msg = if remove_refs == 1 {
1267 "consider removing the leading `&`-reference".to_string()
1269 format!("consider removing {} leading `&`-references", remove_refs)
1272 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1281 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1282 let span = obligation.cause.span;
1284 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1285 let hir = self.tcx.hir();
1286 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1287 if let hir::Node::Expr(expr) = node {
1288 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1289 // and if not maybe suggest doing something else? If we kept the expression around we
1290 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1291 // it is from the local crate.
1292 err.span_suggestion(
1294 "remove the `.await`",
1296 Applicability::MachineApplicable,
1298 // FIXME: account for associated `async fn`s.
1299 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1300 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1301 obligation.predicate.kind().skip_binder()
1305 &format!("this call returns `{}`", pred.self_ty()),
1308 if let Some(typeck_results) = &self.typeck_results
1309 && let ty = typeck_results.expr_ty_adjusted(base)
1310 && let ty::FnDef(def_id, _substs) = ty.kind()
1311 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1312 hir.get_if_local(*def_id)
1315 "alternatively, consider making `fn {}` asynchronous",
1318 if vis_span.is_empty() {
1319 err.span_suggestion_verbose(
1320 span.shrink_to_lo(),
1323 Applicability::MaybeIncorrect,
1326 err.span_suggestion_verbose(
1327 vis_span.shrink_to_hi(),
1330 Applicability::MaybeIncorrect,
1340 /// Check if the trait bound is implemented for a different mutability and note it in the
1342 fn suggest_change_mut(
1344 obligation: &PredicateObligation<'tcx>,
1345 err: &mut Diagnostic,
1346 trait_pred: ty::PolyTraitPredicate<'tcx>,
1348 let points_at_arg = matches!(
1349 obligation.cause.code(),
1350 ObligationCauseCode::FunctionArgumentObligation { .. },
1353 let span = obligation.cause.span;
1354 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1356 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1357 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1358 // Do not suggest removal of borrow from type arguments.
1361 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1362 if trait_pred.has_non_region_infer() {
1363 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1364 // unresolved bindings.
1368 // Skipping binder here, remapping below
1369 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1371 let suggested_ty = match mutability {
1372 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1373 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1376 // Remapping bound vars here
1377 let trait_pred_and_suggested_ty =
1378 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1380 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1381 obligation.param_env,
1382 trait_pred_and_suggested_ty,
1384 let suggested_ty_would_satisfy_obligation = self
1385 .evaluate_obligation_no_overflow(&new_obligation)
1386 .must_apply_modulo_regions();
1387 if suggested_ty_would_satisfy_obligation {
1392 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1393 if points_at_arg && mutability.is_not() && refs_number > 0 {
1394 err.span_suggestion_verbose(
1396 "consider changing this borrow's mutability",
1398 Applicability::MachineApplicable,
1402 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1403 trait_pred.print_modifiers_and_trait_path(),
1405 trait_pred.skip_binder().self_ty(),
1413 fn suggest_semicolon_removal(
1415 obligation: &PredicateObligation<'tcx>,
1416 err: &mut Diagnostic,
1418 trait_pred: ty::PolyTraitPredicate<'tcx>,
1420 let hir = self.tcx.hir();
1421 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1422 let node = hir.find(parent_node);
1423 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1424 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1425 && sig.decl.output.span().overlaps(span)
1426 && blk.expr.is_none()
1427 && trait_pred.self_ty().skip_binder().is_unit()
1428 && let Some(stmt) = blk.stmts.last()
1429 && let hir::StmtKind::Semi(expr) = stmt.kind
1430 // Only suggest this if the expression behind the semicolon implements the predicate
1431 && let Some(typeck_results) = &self.typeck_results
1432 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1433 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1434 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1440 "this expression has type `{}`, which implements `{}`",
1442 trait_pred.print_modifiers_and_trait_path()
1445 err.span_suggestion(
1446 self.tcx.sess.source_map().end_point(stmt.span),
1447 "remove this semicolon",
1449 Applicability::MachineApplicable
1456 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1457 let hir = self.tcx.hir();
1458 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1459 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1463 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1466 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1467 /// applicable and signal that the error has been expanded appropriately and needs to be
1469 fn suggest_impl_trait(
1471 err: &mut Diagnostic,
1473 obligation: &PredicateObligation<'tcx>,
1474 trait_pred: ty::PolyTraitPredicate<'tcx>,
1476 match obligation.cause.code().peel_derives() {
1477 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1478 ObligationCauseCode::SizedReturnType => {}
1482 let hir = self.tcx.hir();
1483 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1484 let node = hir.find(fn_hir_id);
1485 let Some(hir::Node::Item(hir::Item {
1486 kind: hir::ItemKind::Fn(sig, _, body_id),
1492 let body = hir.body(*body_id);
1493 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1494 let ty = trait_pred.skip_binder().self_ty();
1495 let is_object_safe = match ty.kind() {
1496 ty::Dynamic(predicates, _, ty::Dyn) => {
1497 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1500 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1502 // We only want to suggest `impl Trait` to `dyn Trait`s.
1503 // For example, `fn foo() -> str` needs to be filtered out.
1507 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1511 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1512 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1513 // Recursively look for `TraitObject` types and if there's only one, use that span to
1514 // suggest `impl Trait`.
1516 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1517 // otherwise suggest using `Box<dyn Trait>` or an enum.
1518 let mut visitor = ReturnsVisitor::default();
1519 visitor.visit_body(&body);
1521 let typeck_results = self.typeck_results.as_ref().unwrap();
1522 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1524 let ret_types = visitor
1527 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1528 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1529 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1531 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1533 let ty = self.resolve_vars_if_possible(ty);
1535 !matches!(ty.kind(), ty::Error(_))
1536 && last_ty.map_or(true, |last_ty| {
1537 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1538 // *after* in the dependency graph.
1539 match (ty.kind(), last_ty.kind()) {
1540 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1541 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1542 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1544 Infer(InferTy::FreshFloatTy(_)),
1545 Infer(InferTy::FreshFloatTy(_)),
1550 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1553 let mut spans_and_needs_box = vec![];
1555 match liberated_sig.output().kind() {
1556 ty::Dynamic(predicates, _, ty::Dyn) => {
1557 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1558 let param_env = ty::ParamEnv::empty();
1560 if !only_never_return {
1561 for (expr_span, return_ty) in ret_types {
1562 let self_ty_satisfies_dyn_predicates = |self_ty| {
1563 predicates.iter().all(|predicate| {
1564 let pred = predicate.with_self_ty(self.tcx, self_ty);
1565 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1566 self.predicate_may_hold(&obl)
1570 if let ty::Adt(def, substs) = return_ty.kind()
1572 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1574 spans_and_needs_box.push((expr_span, false));
1575 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1576 spans_and_needs_box.push((expr_span, true));
1586 let sm = self.tcx.sess.source_map();
1587 if !ret_ty.span.overlaps(span) {
1590 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1591 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1597 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1598 let name = liberated_sig.output().to_string();
1600 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1601 if !name.starts_with("dyn ") {
1607 err.code(error_code!(E0746));
1608 err.set_primary_message("return type cannot have an unboxed trait object");
1609 err.children.clear();
1610 let impl_trait_msg = "for information on `impl Trait`, see \
1611 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1612 #returning-types-that-implement-traits>";
1613 let trait_obj_msg = "for information on trait objects, see \
1614 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1615 #using-trait-objects-that-allow-for-values-of-different-types>";
1617 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1618 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1619 if only_never_return {
1620 // No return paths, probably using `panic!()` or similar.
1621 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1622 suggest_trait_object_return_type_alternatives(
1628 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1629 // Suggest `-> impl Trait`.
1630 err.span_suggestion(
1633 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1634 which implements `{1}`",
1637 format!("impl {}", trait_obj),
1638 Applicability::MachineApplicable,
1640 err.note(impl_trait_msg);
1643 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1644 err.multipart_suggestion(
1645 "return a boxed trait object instead",
1647 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1648 (span.shrink_to_hi(), ">".to_string()),
1650 Applicability::MaybeIncorrect,
1652 for (span, needs_box) in spans_and_needs_box {
1654 err.multipart_suggestion(
1655 "... and box this value",
1657 (span.shrink_to_lo(), "Box::new(".to_string()),
1658 (span.shrink_to_hi(), ")".to_string()),
1660 Applicability::MaybeIncorrect,
1665 // This is currently not possible to trigger because E0038 takes precedence, but
1666 // leave it in for completeness in case anything changes in an earlier stage.
1668 "if trait `{}` were object-safe, you could return a trait object",
1672 err.note(trait_obj_msg);
1674 "if all the returned values were of the same type you could use `impl {}` as the \
1678 err.note(impl_trait_msg);
1679 err.note("you can create a new `enum` with a variant for each returned type");
1684 fn point_at_returns_when_relevant(
1686 err: &mut Diagnostic,
1687 obligation: &PredicateObligation<'tcx>,
1689 match obligation.cause.code().peel_derives() {
1690 ObligationCauseCode::SizedReturnType => {}
1694 let hir = self.tcx.hir();
1695 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1696 let node = hir.find(parent_node);
1697 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1700 let body = hir.body(*body_id);
1701 // Point at all the `return`s in the function as they have failed trait bounds.
1702 let mut visitor = ReturnsVisitor::default();
1703 visitor.visit_body(&body);
1704 let typeck_results = self.typeck_results.as_ref().unwrap();
1705 for expr in &visitor.returns {
1706 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1707 let ty = self.resolve_vars_if_possible(returned_ty);
1708 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1714 fn report_closure_arg_mismatch(
1717 found_span: Option<Span>,
1718 found: ty::PolyTraitRef<'tcx>,
1719 expected: ty::PolyTraitRef<'tcx>,
1720 cause: &ObligationCauseCode<'tcx>,
1721 found_node: Option<Node<'_>>,
1722 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1723 pub(crate) fn build_fn_sig_ty<'tcx>(
1724 infcx: &InferCtxt<'tcx>,
1725 trait_ref: ty::PolyTraitRef<'tcx>,
1727 let inputs = trait_ref.skip_binder().substs.type_at(1);
1728 let sig = match inputs.kind() {
1729 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1730 infcx.tcx.mk_fn_sig(
1732 infcx.next_ty_var(TypeVariableOrigin {
1734 kind: TypeVariableOriginKind::MiscVariable,
1737 hir::Unsafety::Normal,
1741 _ => infcx.tcx.mk_fn_sig(
1742 std::iter::once(inputs),
1743 infcx.next_ty_var(TypeVariableOrigin {
1745 kind: TypeVariableOriginKind::MiscVariable,
1748 hir::Unsafety::Normal,
1753 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1756 let argument_kind = match expected.skip_binder().self_ty().kind() {
1757 ty::Closure(..) => "closure",
1758 ty::Generator(..) => "generator",
1761 let mut err = struct_span_err!(
1765 "type mismatch in {argument_kind} arguments",
1768 err.span_label(span, "expected due to this");
1770 let found_span = found_span.unwrap_or(span);
1771 err.span_label(found_span, "found signature defined here");
1773 let expected = build_fn_sig_ty(self, expected);
1774 let found = build_fn_sig_ty(self, found);
1776 let (expected_str, found_str) = self.cmp(expected, found);
1778 let signature_kind = format!("{argument_kind} signature");
1779 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1781 self.note_conflicting_closure_bounds(cause, &mut err);
1783 if let Some(found_node) = found_node {
1784 hint_missing_borrow(span, found_span, found, expected, found_node, &mut err);
1790 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1791 // requirements, which will always cause a closure to have a type error.
1792 fn note_conflicting_closure_bounds(
1794 cause: &ObligationCauseCode<'tcx>,
1795 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1797 // First, look for an `ExprBindingObligation`, which means we can get
1798 // the unsubstituted predicate list of the called function. And check
1799 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1800 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1801 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1802 && let Some(pred) = predicates.predicates.get(*idx)
1803 && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
1804 && self.tcx.is_fn_trait(trait_pred.def_id())
1807 self.tcx.anonymize_late_bound_regions(pred.kind().rebind(trait_pred.self_ty()));
1808 let expected_substs = self
1810 .anonymize_late_bound_regions(pred.kind().rebind(trait_pred.trait_ref.substs));
1812 // Find another predicate whose self-type is equal to the expected self type,
1813 // but whose substs don't match.
1814 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1816 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1817 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
1818 if self.tcx.is_fn_trait(trait_pred.def_id())
1820 // Make sure that the self type matches
1821 // (i.e. constraining this closure)
1823 == self.tcx.anonymize_late_bound_regions(
1824 pred.kind().rebind(trait_pred.self_ty()),
1826 // But the substs don't match (i.e. incompatible args)
1828 != self.tcx.anonymize_late_bound_regions(
1829 pred.kind().rebind(trait_pred.trait_ref.substs),
1836 // If we found one, then it's very likely the cause of the error.
1837 if let Some((_, (_, other_pred_span))) = other_pred {
1840 "closure inferred to have a different signature due to this bound",
1846 fn suggest_fully_qualified_path(
1848 err: &mut Diagnostic,
1853 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1854 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1856 "{}s cannot be accessed directly on a `trait`, they can only be \
1857 accessed through a specific `impl`",
1858 assoc_item.kind.as_def_kind().descr(item_def_id)
1860 err.span_suggestion(
1862 "use the fully qualified path to an implementation",
1863 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1864 Applicability::HasPlaceholders,
1870 /// Adds an async-await specific note to the diagnostic when the future does not implement
1871 /// an auto trait because of a captured type.
1874 /// note: future does not implement `Qux` as this value is used across an await
1875 /// --> $DIR/issue-64130-3-other.rs:17:5
1877 /// LL | let x = Foo;
1878 /// | - has type `Foo`
1879 /// LL | baz().await;
1880 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1882 /// | - `x` is later dropped here
1885 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1886 /// is "replaced" with a different message and a more specific error.
1889 /// error: future cannot be sent between threads safely
1890 /// --> $DIR/issue-64130-2-send.rs:21:5
1892 /// LL | fn is_send<T: Send>(t: T) { }
1893 /// | ---- required by this bound in `is_send`
1895 /// LL | is_send(bar());
1896 /// | ^^^^^^^ future returned by `bar` is not send
1898 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1899 /// implemented for `Foo`
1900 /// note: future is not send as this value is used across an await
1901 /// --> $DIR/issue-64130-2-send.rs:15:5
1903 /// LL | let x = Foo;
1904 /// | - has type `Foo`
1905 /// LL | baz().await;
1906 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1908 /// | - `x` is later dropped here
1911 /// Returns `true` if an async-await specific note was added to the diagnostic.
1912 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1913 fn maybe_note_obligation_cause_for_async_await(
1915 err: &mut Diagnostic,
1916 obligation: &PredicateObligation<'tcx>,
1918 let hir = self.tcx.hir();
1920 // Attempt to detect an async-await error by looking at the obligation causes, looking
1921 // for a generator to be present.
1923 // When a future does not implement a trait because of a captured type in one of the
1924 // generators somewhere in the call stack, then the result is a chain of obligations.
1926 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1927 // future is passed as an argument to a function C which requires a `Send` type, then the
1928 // chain looks something like this:
1930 // - `BuiltinDerivedObligation` with a generator witness (B)
1931 // - `BuiltinDerivedObligation` with a generator (B)
1932 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1933 // - `BuiltinDerivedObligation` with a generator witness (A)
1934 // - `BuiltinDerivedObligation` with a generator (A)
1935 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1936 // - `BindingObligation` with `impl_send (Send requirement)
1938 // The first obligation in the chain is the most useful and has the generator that captured
1939 // the type. The last generator (`outer_generator` below) has information about where the
1940 // bound was introduced. At least one generator should be present for this diagnostic to be
1942 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1943 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
1946 let mut generator = None;
1947 let mut outer_generator = None;
1948 let mut next_code = Some(obligation.cause.code());
1950 let mut seen_upvar_tys_infer_tuple = false;
1952 while let Some(code) = next_code {
1955 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1956 next_code = Some(parent_code);
1958 ObligationCauseCode::ImplDerivedObligation(cause) => {
1959 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1961 parent_trait_ref = ?cause.derived.parent_trait_pred,
1962 self_ty.kind = ?ty.kind(),
1967 ty::Generator(did, ..) => {
1968 generator = generator.or(Some(did));
1969 outer_generator = Some(did);
1971 ty::GeneratorWitness(..) => {}
1972 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1973 // By introducing a tuple of upvar types into the chain of obligations
1974 // of a generator, the first non-generator item is now the tuple itself,
1975 // we shall ignore this.
1977 seen_upvar_tys_infer_tuple = true;
1979 _ if generator.is_none() => {
1980 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1981 target_ty = Some(ty);
1986 next_code = Some(&cause.derived.parent_code);
1988 ObligationCauseCode::DerivedObligation(derived_obligation)
1989 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1990 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1992 parent_trait_ref = ?derived_obligation.parent_trait_pred,
1993 self_ty.kind = ?ty.kind(),
1997 ty::Generator(did, ..) => {
1998 generator = generator.or(Some(did));
1999 outer_generator = Some(did);
2001 ty::GeneratorWitness(..) => {}
2002 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2003 // By introducing a tuple of upvar types into the chain of obligations
2004 // of a generator, the first non-generator item is now the tuple itself,
2005 // we shall ignore this.
2007 seen_upvar_tys_infer_tuple = true;
2009 _ if generator.is_none() => {
2010 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2011 target_ty = Some(ty);
2016 next_code = Some(&derived_obligation.parent_code);
2022 // Only continue if a generator was found.
2023 debug!(?generator, ?trait_ref, ?target_ty);
2024 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
2028 let span = self.tcx.def_span(generator_did);
2030 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
2033 ?generator_did_root,
2034 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2038 let generator_body = generator_did
2040 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2041 .map(|body_id| hir.body(body_id));
2042 let mut visitor = AwaitsVisitor::default();
2043 if let Some(body) = generator_body {
2044 visitor.visit_body(body);
2046 debug!(awaits = ?visitor.awaits);
2048 // Look for a type inside the generator interior that matches the target type to get
2050 let target_ty_erased = self.tcx.erase_regions(target_ty);
2051 let ty_matches = |ty| -> bool {
2052 // Careful: the regions for types that appear in the
2053 // generator interior are not generally known, so we
2054 // want to erase them when comparing (and anyway,
2055 // `Send` and other bounds are generally unaffected by
2056 // the choice of region). When erasing regions, we
2057 // also have to erase late-bound regions. This is
2058 // because the types that appear in the generator
2059 // interior generally contain "bound regions" to
2060 // represent regions that are part of the suspended
2061 // generator frame. Bound regions are preserved by
2062 // `erase_regions` and so we must also call
2063 // `erase_late_bound_regions`.
2064 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2065 let ty_erased = self.tcx.erase_regions(ty_erased);
2066 let eq = ty_erased == target_ty_erased;
2067 debug!(?ty_erased, ?target_ty_erased, ?eq);
2071 // Get the typeck results from the infcx if the generator is the function we are currently
2072 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2073 // cycles. If we can't use resolved types because the generator comes from another crate,
2074 // we still provide a targeted error but without all the relevant spans.
2075 let generator_data = match &self.typeck_results {
2076 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2077 _ if generator_did.is_local() => {
2078 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2080 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2081 GeneratorData::Foreign(generator_diag_data)
2086 let mut interior_or_upvar_span = None;
2088 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2089 debug!(?from_awaited_ty);
2091 // The generator interior types share the same binders
2092 if let Some(cause) =
2093 generator_data.get_generator_interior_types().skip_binder().iter().find(
2094 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2095 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2099 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2101 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2103 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2107 if interior_or_upvar_span.is_none() {
2108 interior_or_upvar_span =
2109 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2112 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2113 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2116 debug!(?interior_or_upvar_span);
2117 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2118 let is_async = self.tcx.generator_is_async(generator_did);
2119 let typeck_results = match generator_data {
2120 GeneratorData::Local(typeck_results) => Some(typeck_results),
2121 GeneratorData::Foreign(_) => None,
2123 self.note_obligation_cause_for_async_await(
2125 interior_or_upvar_span,
2140 /// Unconditionally adds the diagnostic note described in
2141 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2142 #[instrument(level = "debug", skip_all)]
2143 fn note_obligation_cause_for_async_await(
2145 err: &mut Diagnostic,
2146 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2148 outer_generator: Option<DefId>,
2149 trait_pred: ty::TraitPredicate<'tcx>,
2150 target_ty: Ty<'tcx>,
2151 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2152 obligation: &PredicateObligation<'tcx>,
2153 next_code: Option<&ObligationCauseCode<'tcx>>,
2155 let source_map = self.tcx.sess.source_map();
2157 let (await_or_yield, an_await_or_yield) =
2158 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2159 let future_or_generator = if is_async { "future" } else { "generator" };
2161 // Special case the primary error message when send or sync is the trait that was
2163 let hir = self.tcx.hir();
2164 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2165 self.tcx.get_diagnostic_name(trait_pred.def_id())
2167 let (trait_name, trait_verb) =
2168 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2171 err.set_primary_message(format!(
2172 "{} cannot be {} between threads safely",
2173 future_or_generator, trait_verb
2176 let original_span = err.span.primary_span().unwrap();
2177 let mut span = MultiSpan::from_span(original_span);
2179 let message = outer_generator
2180 .and_then(|generator_did| {
2181 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2182 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2183 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2185 .parent(generator_did)
2187 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2188 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2190 format!("future returned by `{}` is not {}", name, trait_name)
2192 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2193 format!("future created by async block is not {}", trait_name)
2195 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2196 format!("future created by async closure is not {}", trait_name)
2200 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2202 span.push_span_label(original_span, message);
2205 format!("is not {}", trait_name)
2207 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2210 let mut explain_yield =
2211 |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
2212 let mut span = MultiSpan::from_span(yield_span);
2213 let snippet = match source_map.span_to_snippet(interior_span) {
2214 // #70935: If snippet contains newlines, display "the value" instead
2215 // so that we do not emit complex diagnostics.
2216 Ok(snippet) if !snippet.contains('\n') => format!("`{}`", snippet),
2217 _ => "the value".to_string(),
2219 // note: future is not `Send` as this value is used across an await
2220 // --> $DIR/issue-70935-complex-spans.rs:13:9
2222 // LL | baz(|| async {
2223 // | ______________-
2226 // LL | | foo(tx.clone());
2228 // | | - ^^^^^^ await occurs here, with value maybe used later
2230 // | has type `closure` which is not `Send`
2231 // note: value is later dropped here
2235 span.push_span_label(
2237 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2239 span.push_span_label(
2241 format!("has type `{}` which {}", target_ty, trait_explanation),
2243 if let Some(scope_span) = scope_span {
2244 let scope_span = source_map.end_point(scope_span);
2246 let msg = format!("{} is later dropped here", snippet);
2247 span.push_span_label(scope_span, msg);
2252 "{} {} as this value is used across {}",
2253 future_or_generator, trait_explanation, an_await_or_yield
2257 match interior_or_upvar_span {
2258 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2259 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2260 if let Some(await_span) = from_awaited_ty {
2261 // The type causing this obligation is one being awaited at await_span.
2262 let mut span = MultiSpan::from_span(await_span);
2263 span.push_span_label(
2266 "await occurs here on type `{}`, which {}",
2267 target_ty, trait_explanation
2273 "future {not_trait} as it awaits another future which {not_trait}",
2274 not_trait = trait_explanation
2278 // Look at the last interior type to get a span for the `.await`.
2280 generator_interior_types = ?format_args!(
2281 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2284 explain_yield(interior_span, yield_span, scope_span);
2287 if let Some(expr_id) = expr {
2288 let expr = hir.expect_expr(expr_id);
2289 debug!("target_ty evaluated from {:?}", expr);
2291 let parent = hir.get_parent_node(expr_id);
2292 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2293 let parent_span = hir.span(parent);
2294 let parent_did = parent.owner.to_def_id();
2297 // fn foo(&self) -> i32 {}
2300 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2303 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2305 .expr_adjustments(expr)
2307 .any(|adj| adj.is_region_borrow())
2313 // struct Foo(*const u8);
2314 // bar(Foo(std::ptr::null())).await;
2315 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2317 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2318 let is_raw_borrow_inside_fn_like_call =
2319 match self.tcx.def_kind(parent_did) {
2320 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2323 if let Some(typeck_results) = typeck_results {
2324 if (typeck_results.is_method_call(e) && is_region_borrow)
2325 || is_raw_borrow_inside_fn_like_call
2329 "consider moving this into a `let` \
2330 binding to create a shorter lived borrow",
2338 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2339 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2340 let refers_to_non_sync = match target_ty.kind() {
2341 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2342 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2348 let (span_label, span_note) = match refers_to_non_sync {
2349 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2350 // include suggestions to make `T: Sync` so that `&T: Send`
2353 "has type `{}` which {}, because `{}` is not `Sync`",
2354 target_ty, trait_explanation, ref_ty
2357 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2362 format!("has type `{}` which {}", target_ty, trait_explanation),
2363 format!("captured value {}", trait_explanation),
2367 let mut span = MultiSpan::from_span(upvar_span);
2368 span.push_span_label(upvar_span, span_label);
2369 err.span_note(span, &span_note);
2373 // Add a note for the item obligation that remains - normally a note pointing to the
2374 // bound that introduced the obligation (e.g. `T: Send`).
2376 self.note_obligation_cause_code(
2378 obligation.predicate,
2379 obligation.param_env,
2382 &mut Default::default(),
2386 fn note_obligation_cause_code<T>(
2388 err: &mut Diagnostic,
2390 param_env: ty::ParamEnv<'tcx>,
2391 cause_code: &ObligationCauseCode<'tcx>,
2392 obligated_types: &mut Vec<Ty<'tcx>>,
2393 seen_requirements: &mut FxHashSet<DefId>,
2395 T: ToPredicate<'tcx>,
2398 let predicate = predicate.to_predicate(tcx);
2400 ObligationCauseCode::ExprAssignable
2401 | ObligationCauseCode::MatchExpressionArm { .. }
2402 | ObligationCauseCode::Pattern { .. }
2403 | ObligationCauseCode::IfExpression { .. }
2404 | ObligationCauseCode::IfExpressionWithNoElse
2405 | ObligationCauseCode::MainFunctionType
2406 | ObligationCauseCode::StartFunctionType
2407 | ObligationCauseCode::IntrinsicType
2408 | ObligationCauseCode::MethodReceiver
2409 | ObligationCauseCode::ReturnNoExpression
2410 | ObligationCauseCode::UnifyReceiver(..)
2411 | ObligationCauseCode::OpaqueType
2412 | ObligationCauseCode::MiscObligation
2413 | ObligationCauseCode::WellFormed(..)
2414 | ObligationCauseCode::MatchImpl(..)
2415 | ObligationCauseCode::ReturnType
2416 | ObligationCauseCode::ReturnValue(_)
2417 | ObligationCauseCode::BlockTailExpression(_)
2418 | ObligationCauseCode::AwaitableExpr(_)
2419 | ObligationCauseCode::ForLoopIterator
2420 | ObligationCauseCode::QuestionMark
2421 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2422 | ObligationCauseCode::LetElse
2423 | ObligationCauseCode::BinOp { .. }
2424 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2425 | ObligationCauseCode::RustCall => {}
2426 ObligationCauseCode::SliceOrArrayElem => {
2427 err.note("slice and array elements must have `Sized` type");
2429 ObligationCauseCode::TupleElem => {
2430 err.note("only the last element of a tuple may have a dynamically sized type");
2432 ObligationCauseCode::ProjectionWf(data) => {
2433 err.note(&format!("required so that the projection `{data}` is well-formed"));
2435 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2437 "required so that reference `{ref_ty}` does not outlive its referent"
2440 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2442 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2446 ObligationCauseCode::ItemObligation(_)
2447 | ObligationCauseCode::ExprItemObligation(..) => {
2448 // We hold the `DefId` of the item introducing the obligation, but displaying it
2449 // doesn't add user usable information. It always point at an associated item.
2451 ObligationCauseCode::BindingObligation(item_def_id, span)
2452 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2453 let item_name = tcx.def_path_str(item_def_id);
2454 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2455 let mut multispan = MultiSpan::from(span);
2456 let sm = tcx.sess.source_map();
2457 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2459 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2460 (Ok(l), Ok(r)) => l.line == r.line,
2463 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2464 multispan.push_span_label(ident.span, "required by a bound in this");
2467 let descr = format!("required by a bound in `{item_name}`");
2468 if span.is_visible(sm) {
2469 let msg = format!("required by this bound in `{short_item_name}`");
2470 multispan.push_span_label(span, msg);
2471 err.span_note(multispan, &descr);
2473 err.span_note(tcx.def_span(item_def_id), &descr);
2476 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2478 "required for the cast from `{}` to the object type `{}`",
2479 self.ty_to_string(concrete_ty),
2480 self.ty_to_string(object_ty)
2483 ObligationCauseCode::Coercion { source: _, target } => {
2484 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2486 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2488 "the `Copy` trait is required because this value will be copied for each element of the array",
2493 "consider creating a new `const` item and initializing it with the result \
2494 of the function call to be used in the repeat position, like \
2495 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2499 if self.tcx.sess.is_nightly_build() && is_const_fn {
2501 "create an inline `const` block, see RFC #2920 \
2502 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2506 ObligationCauseCode::VariableType(hir_id) => {
2507 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2508 match self.tcx.hir().find(parent_node) {
2509 Some(Node::Local(hir::Local {
2510 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2513 // When encountering an assignment of an unsized trait, like
2514 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2515 // order to use have a slice instead.
2516 err.span_suggestion_verbose(
2517 span.shrink_to_lo(),
2518 "consider borrowing here",
2520 Applicability::MachineApplicable,
2522 err.note("all local variables must have a statically known size");
2524 Some(Node::Param(param)) => {
2525 err.span_suggestion_verbose(
2526 param.ty_span.shrink_to_lo(),
2527 "function arguments must have a statically known size, borrowed types \
2528 always have a known size",
2530 Applicability::MachineApplicable,
2534 err.note("all local variables must have a statically known size");
2537 if !self.tcx.features().unsized_locals {
2538 err.help("unsized locals are gated as an unstable feature");
2541 ObligationCauseCode::SizedArgumentType(sp) => {
2542 if let Some(span) = sp {
2543 err.span_suggestion_verbose(
2544 span.shrink_to_lo(),
2545 "function arguments must have a statically known size, borrowed types \
2546 always have a known size",
2548 Applicability::MachineApplicable,
2551 err.note("all function arguments must have a statically known size");
2553 if tcx.sess.opts.unstable_features.is_nightly_build()
2554 && !self.tcx.features().unsized_fn_params
2556 err.help("unsized fn params are gated as an unstable feature");
2559 ObligationCauseCode::SizedReturnType => {
2560 err.note("the return type of a function must have a statically known size");
2562 ObligationCauseCode::SizedYieldType => {
2563 err.note("the yield type of a generator must have a statically known size");
2565 ObligationCauseCode::SizedBoxType => {
2566 err.note("the type of a box expression must have a statically known size");
2568 ObligationCauseCode::AssignmentLhsSized => {
2569 err.note("the left-hand-side of an assignment must have a statically known size");
2571 ObligationCauseCode::TupleInitializerSized => {
2572 err.note("tuples must have a statically known size to be initialized");
2574 ObligationCauseCode::StructInitializerSized => {
2575 err.note("structs must have a statically known size to be initialized");
2577 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2579 AdtKind::Struct => {
2582 "the last field of a packed struct may only have a \
2583 dynamically sized type if it does not need drop to be run",
2587 "only the last field of a struct may have a dynamically sized type",
2592 err.note("no field of a union may have a dynamically sized type");
2595 err.note("no field of an enum variant may have a dynamically sized type");
2598 err.help("change the field's type to have a statically known size");
2599 err.span_suggestion(
2600 span.shrink_to_lo(),
2601 "borrowed types always have a statically known size",
2603 Applicability::MachineApplicable,
2605 err.multipart_suggestion(
2606 "the `Box` type always has a statically known size and allocates its contents \
2609 (span.shrink_to_lo(), "Box<".to_string()),
2610 (span.shrink_to_hi(), ">".to_string()),
2612 Applicability::MachineApplicable,
2615 ObligationCauseCode::ConstSized => {
2616 err.note("constant expressions must have a statically known size");
2618 ObligationCauseCode::InlineAsmSized => {
2619 err.note("all inline asm arguments must have a statically known size");
2621 ObligationCauseCode::ConstPatternStructural => {
2622 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2624 ObligationCauseCode::SharedStatic => {
2625 err.note("shared static variables must have a type that implements `Sync`");
2627 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2628 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2629 let ty = parent_trait_ref.skip_binder().self_ty();
2630 if parent_trait_ref.references_error() {
2631 // NOTE(eddyb) this was `.cancel()`, but `err`
2632 // is borrowed, so we can't fully defuse it.
2633 err.downgrade_to_delayed_bug();
2637 // If the obligation for a tuple is set directly by a Generator or Closure,
2638 // then the tuple must be the one containing capture types.
2639 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2642 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2644 let parent_trait_ref =
2645 self.resolve_vars_if_possible(data.parent_trait_pred);
2646 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2647 matches!(nested_ty.kind(), ty::Generator(..))
2648 || matches!(nested_ty.kind(), ty::Closure(..))
2654 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2656 // Don't print the tuple of capture types
2658 if !is_upvar_tys_infer_tuple {
2659 let msg = format!("required because it appears within the type `{}`", ty);
2661 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2662 Some(ident) => err.span_note(ident.span, &msg),
2663 None => err.note(&msg),
2665 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
2666 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2667 if tcx.parent(*def_id) == identity_future {
2671 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2672 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2673 let is_future = tcx.ty_is_opaque_future(ty);
2677 "note_obligation_cause_code: check for async fn"
2680 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2681 ty::Generator(last_def_id, ..) => {
2682 tcx.generator_is_async(*last_def_id)
2689 err.span_note(self.tcx.def_span(def_id), &msg)
2691 ty::GeneratorWitness(bound_tys) => {
2692 use std::fmt::Write;
2694 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2695 // Maybe we should just remove this note altogether?
2696 // FIXME: only print types which don't meet the trait requirement
2698 "required because it captures the following types: ".to_owned();
2699 for ty in bound_tys.skip_binder() {
2700 write!(msg, "`{}`, ", ty).unwrap();
2702 err.note(msg.trim_end_matches(", "))
2704 ty::Generator(def_id, _, _) => {
2705 let sp = self.tcx.def_span(def_id);
2707 // Special-case this to say "async block" instead of `[static generator]`.
2708 let kind = tcx.generator_kind(def_id).unwrap().descr();
2711 &format!("required because it's used within this {}", kind),
2714 ty::Closure(def_id, _) => err.span_note(
2715 self.tcx.def_span(def_id),
2716 &format!("required because it's used within this closure"),
2718 _ => err.note(&msg),
2723 obligated_types.push(ty);
2725 let parent_predicate = parent_trait_ref;
2726 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2727 // #74711: avoid a stack overflow
2728 ensure_sufficient_stack(|| {
2729 self.note_obligation_cause_code(
2739 ensure_sufficient_stack(|| {
2740 self.note_obligation_cause_code(
2744 cause_code.peel_derives(),
2751 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2752 let mut parent_trait_pred =
2753 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2754 parent_trait_pred.remap_constness_diag(param_env);
2755 let parent_def_id = parent_trait_pred.def_id();
2756 let (self_ty, file) =
2757 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2759 "required for `{self_ty}` to implement `{}`",
2760 parent_trait_pred.print_modifiers_and_trait_path()
2762 let mut is_auto_trait = false;
2763 match self.tcx.hir().get_if_local(data.impl_def_id) {
2764 Some(Node::Item(hir::Item {
2765 kind: hir::ItemKind::Trait(is_auto, ..),
2769 // FIXME: we should do something else so that it works even on crate foreign
2771 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2772 err.span_note(ident.span, &msg)
2774 Some(Node::Item(hir::Item {
2775 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2778 let mut spans = Vec::with_capacity(2);
2779 if let Some(trait_ref) = of_trait {
2780 spans.push(trait_ref.path.span);
2782 spans.push(self_ty.span);
2783 err.span_note(spans, &msg)
2785 _ => err.note(&msg),
2788 if let Some(file) = file {
2790 "the full type name has been written to '{}'",
2794 let mut parent_predicate = parent_trait_pred;
2795 let mut data = &data.derived;
2797 seen_requirements.insert(parent_def_id);
2799 // We don't want to point at the ADT saying "required because it appears within
2800 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2801 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2804 let child_trait_ref =
2805 self.resolve_vars_if_possible(derived.parent_trait_pred);
2806 let child_def_id = child_trait_ref.def_id();
2807 if seen_requirements.insert(child_def_id) {
2811 parent_predicate = child_trait_ref.to_predicate(tcx);
2812 parent_trait_pred = child_trait_ref;
2815 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2816 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2817 let child_trait_pred =
2818 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2819 let child_def_id = child_trait_pred.def_id();
2820 if seen_requirements.insert(child_def_id) {
2824 data = &child.derived;
2825 parent_predicate = child_trait_pred.to_predicate(tcx);
2826 parent_trait_pred = child_trait_pred;
2830 "{} redundant requirement{} hidden",
2834 let (self_ty, file) =
2835 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2837 "required for `{self_ty}` to implement `{}`",
2838 parent_trait_pred.print_modifiers_and_trait_path()
2840 if let Some(file) = file {
2842 "the full type name has been written to '{}'",
2847 // #74711: avoid a stack overflow
2848 ensure_sufficient_stack(|| {
2849 self.note_obligation_cause_code(
2859 ObligationCauseCode::DerivedObligation(ref data) => {
2860 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2861 let parent_predicate = parent_trait_ref;
2862 // #74711: avoid a stack overflow
2863 ensure_sufficient_stack(|| {
2864 self.note_obligation_cause_code(
2874 ObligationCauseCode::FunctionArgumentObligation {
2880 self.function_argument_obligation(
2888 ensure_sufficient_stack(|| {
2889 self.note_obligation_cause_code(
2899 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2900 let item_name = self.tcx.item_name(trait_item_def_id);
2902 "the requirement `{predicate}` appears on the `impl`'s {kind} \
2903 `{item_name}` but not on the corresponding trait's {kind}",
2907 .opt_item_ident(trait_item_def_id)
2909 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2910 let mut assoc_span: MultiSpan = sp.into();
2911 assoc_span.push_span_label(
2913 format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
2915 if let Some(ident) = self
2917 .opt_associated_item(trait_item_def_id)
2918 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2920 assoc_span.push_span_label(ident.span, "in this trait");
2922 err.span_note(assoc_span, &msg);
2924 ObligationCauseCode::TrivialBound => {
2925 err.help("see issue #48214");
2926 if tcx.sess.opts.unstable_features.is_nightly_build() {
2927 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2930 ObligationCauseCode::OpaqueReturnType(expr_info) => {
2931 if let Some((expr_ty, expr_span)) = expr_info {
2932 let expr_ty = with_forced_trimmed_paths!(self.ty_to_string(expr_ty));
2935 format!("return type was inferred to be `{expr_ty}` here"),
2943 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2945 fn suggest_await_before_try(
2947 err: &mut Diagnostic,
2948 obligation: &PredicateObligation<'tcx>,
2949 trait_pred: ty::PolyTraitPredicate<'tcx>,
2952 let body_hir_id = obligation.cause.body_id;
2953 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2955 if let Some(body_id) =
2956 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2958 let body = self.tcx.hir().body(body_id);
2959 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2960 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2962 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2963 let impls_future = self.type_implements_trait(
2965 [self.tcx.erase_late_bound_regions(self_ty)],
2966 obligation.param_env,
2968 if !impls_future.must_apply_modulo_regions() {
2972 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2973 // `<T as Future>::Output`
2974 let projection_ty = trait_pred.map_bound(|trait_pred| {
2975 self.tcx.mk_projection(
2977 // Future::Output has no substs
2978 [trait_pred.self_ty()],
2981 let InferOk { value: projection_ty, .. } =
2982 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
2985 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
2987 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2988 obligation.param_env,
2989 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
2991 debug!(try_trait_obligation = ?try_obligation);
2992 if self.predicate_may_hold(&try_obligation)
2993 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2994 && snippet.ends_with('?')
2996 err.span_suggestion_verbose(
2997 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2998 "consider `await`ing on the `Future`",
3000 Applicability::MaybeIncorrect,
3007 fn suggest_floating_point_literal(
3009 obligation: &PredicateObligation<'tcx>,
3010 err: &mut Diagnostic,
3011 trait_ref: &ty::PolyTraitRef<'tcx>,
3013 let rhs_span = match obligation.cause.code() {
3014 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3017 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3018 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3020 err.span_suggestion_verbose(
3021 rhs_span.shrink_to_hi(),
3022 "consider using a floating-point literal by writing it with `.0`",
3024 Applicability::MaybeIncorrect,
3031 obligation: &PredicateObligation<'tcx>,
3032 err: &mut Diagnostic,
3033 trait_pred: ty::PolyTraitPredicate<'tcx>,
3035 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3038 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3039 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3043 let is_derivable_trait = match diagnostic_name {
3044 sym::Default => !adt.is_enum(),
3045 sym::PartialEq | sym::PartialOrd => {
3046 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3047 trait_pred.skip_binder().self_ty() == rhs_ty
3049 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3052 is_derivable_trait &&
3053 // Ensure all fields impl the trait.
3054 adt.all_fields().all(|field| {
3055 let field_ty = field.ty(self.tcx, substs);
3056 let trait_substs = match diagnostic_name {
3057 sym::PartialEq | sym::PartialOrd => {
3062 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3063 trait_ref: self.tcx.mk_trait_ref(
3064 trait_pred.def_id(),
3065 [field_ty].into_iter().chain(trait_substs),
3069 let field_obl = Obligation::new(
3071 obligation.cause.clone(),
3072 obligation.param_env,
3075 self.predicate_must_hold_modulo_regions(&field_obl)
3079 err.span_suggestion_verbose(
3080 self.tcx.def_span(adt.did()).shrink_to_lo(),
3082 "consider annotating `{}` with `#[derive({})]`",
3083 trait_pred.skip_binder().self_ty(),
3086 format!("#[derive({})]\n", diagnostic_name),
3087 Applicability::MaybeIncorrect,
3092 fn suggest_dereferencing_index(
3094 obligation: &PredicateObligation<'tcx>,
3095 err: &mut Diagnostic,
3096 trait_pred: ty::PolyTraitPredicate<'tcx>,
3098 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3099 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3100 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3101 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3102 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3104 err.span_suggestion_verbose(
3105 obligation.cause.span.shrink_to_lo(),
3106 "dereference this index",
3108 Applicability::MachineApplicable,
3112 fn function_argument_obligation(
3115 err: &mut Diagnostic,
3116 parent_code: &ObligationCauseCode<'tcx>,
3117 param_env: ty::ParamEnv<'tcx>,
3118 predicate: ty::Predicate<'tcx>,
3122 let hir = tcx.hir();
3123 if let Some(Node::Expr(expr)) = hir.find(arg_hir_id) {
3124 let parent_id = hir.get_parent_item(arg_hir_id);
3125 let typeck_results: &TypeckResults<'tcx> = match &self.typeck_results {
3126 Some(t) if t.hir_owner == parent_id => t,
3127 _ => self.tcx.typeck(parent_id.def_id),
3129 if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
3130 let expr = expr.peel_blocks();
3131 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
3132 let span = expr.span;
3133 if Some(span) != err.span.primary_span() {
3136 if ty.references_error() {
3139 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3140 format!("this tail expression is of type `{ty}`")
3146 // FIXME: visit the ty to see if there's any closure involved, and if there is,
3147 // check whether its evaluated return type is the same as the one corresponding
3148 // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3149 // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3150 let mut type_diffs = vec![];
3152 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
3153 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
3154 && let Some(pred) = predicates.predicates.get(*idx)
3155 && let Ok(trait_pred) = pred.kind().try_map_bound(|pred| match pred {
3156 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) => Ok(trait_pred),
3160 let mut c = CollectAllMismatches {
3165 if let Ok(trait_predicate) = predicate.kind().try_map_bound(|pred| match pred {
3166 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) => Ok(trait_pred),
3169 if let Ok(_) = c.relate(trait_pred, trait_predicate) {
3170 type_diffs = c.errors;
3174 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3175 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3176 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3177 && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3178 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3179 && let Some(binding_expr) = local.init
3181 // If the expression we're calling on is a binding, we want to point at the
3182 // `let` when talking about the type. Otherwise we'll point at every part
3183 // of the method chain with the type.
3184 self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
3186 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
3189 let call_node = hir.find(call_hir_id);
3190 if let Some(Node::Expr(hir::Expr {
3191 kind: hir::ExprKind::MethodCall(path, rcvr, ..), ..
3194 if Some(rcvr.span) == err.span.primary_span() {
3195 err.replace_span_with(path.ident.span);
3198 if let Some(Node::Expr(hir::Expr {
3200 hir::ExprKind::Call(hir::Expr { span, .. }, _)
3201 | hir::ExprKind::MethodCall(hir::PathSegment { ident: Ident { span, .. }, .. }, ..),
3203 })) = hir.find(call_hir_id)
3205 if Some(*span) != err.span.primary_span() {
3206 err.span_label(*span, "required by a bound introduced by this call");
3213 expr: &hir::Expr<'_>,
3214 typeck_results: &TypeckResults<'tcx>,
3215 type_diffs: Vec<TypeError<'tcx>>,
3216 param_env: ty::ParamEnv<'tcx>,
3217 err: &mut Diagnostic,
3219 let mut primary_spans = vec![];
3220 let mut span_labels = vec![];
3224 let mut assocs = vec![];
3225 // We still want to point at the different methods even if there hasn't
3226 // been a change of assoc type.
3227 let mut call_spans = vec![];
3228 let mut expr = expr;
3229 let mut prev_ty = self.resolve_vars_if_possible(
3230 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3232 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) = expr.kind {
3233 // Point at every method call in the chain with the resulting type.
3234 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3235 // ^^^^^^ ^^^^^^^^^^^
3237 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
3238 call_spans.push(span);
3240 let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
3241 for diff in &type_diffs {
3242 let Sorts(expected_found) = diff else { continue; };
3243 let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; };
3246 TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span };
3247 let trait_def_id = proj.trait_def_id(self.tcx);
3248 // Make `Self` be equivalent to the type of the call chain
3249 // expression we're looking at now, so that we can tell what
3250 // for example `Iterator::Item` is at this point in the chain.
3251 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
3253 ty::GenericParamDefKind::Type { .. } => {
3254 if param.index == 0 {
3255 return prev_ty.into();
3258 ty::GenericParamDefKind::Lifetime
3259 | ty::GenericParamDefKind::Const { .. } => {}
3261 self.var_for_def(span, param)
3263 // This will hold the resolved type of the associated type, if the
3264 // current expression implements the trait that associated type is
3265 // in. For example, this would be what `Iterator::Item` is here.
3266 let ty_var = self.infcx.next_ty_var(origin);
3267 // This corresponds to `<ExprTy as Iterator>::Item = _`.
3268 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
3269 ty::Clause::Projection(ty::ProjectionPredicate {
3270 projection_ty: tcx.mk_alias_ty(proj.def_id, substs),
3271 term: ty_var.into(),
3274 // Add `<ExprTy as Iterator>::Item = _` obligation.
3275 ocx.register_obligation(Obligation::misc(
3282 if ocx.select_where_possible().is_empty() {
3283 // `ty_var` now holds the type that `Item` is for `ExprTy`.
3284 let ty_var = self.resolve_vars_if_possible(ty_var);
3285 assocs_in_this_method.push(Some((span, (proj.def_id, ty_var))));
3287 // `<ExprTy as Iterator>` didn't select, so likely we've
3288 // reached the end of the iterator chain, like the originating
3290 // Keep the space consistent for later zipping.
3291 assocs_in_this_method.push(None);
3294 assocs.push(assocs_in_this_method);
3295 prev_ty = self.resolve_vars_if_possible(
3296 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3299 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3300 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3301 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3302 && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3303 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3304 && let Some(binding_expr) = local.init
3306 // We've reached the root of the method call chain and it is a
3307 // binding. Get the binding creation and try to continue the chain.
3308 expr = binding_expr;
3311 // We want the type before deref coercions, otherwise we talk about `&[_]`
3312 // instead of `Vec<_>`.
3313 if let Some(ty) = typeck_results.expr_ty_opt(expr) {
3314 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3315 // Point at the root expression
3316 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3318 span_labels.push((expr.span, format!("this expression has type `{ty}`")));
3320 // Only show this if it is not a "trivial" expression (not a method
3321 // chain) and there are associated types to talk about.
3322 let mut assocs = assocs.into_iter().peekable();
3323 while let Some(assocs_in_method) = assocs.next() {
3324 let Some(prev_assoc_in_method) = assocs.peek() else {
3325 for entry in assocs_in_method {
3326 let Some((span, (assoc, ty))) = entry else { continue; };
3327 if type_diffs.iter().any(|diff| {
3328 let Sorts(expected_found) = diff else { return false; };
3329 self.can_eq(param_env, expected_found.found, ty).is_ok()
3331 // FIXME: this doesn't quite work for `Iterator::collect`
3332 // because we have `Vec<i32>` and `()`, but we'd want `i32`
3333 // to point at the `.into_iter()` call, but as long as we
3334 // still point at the other method calls that might have
3335 // introduced the issue, this is fine for now.
3336 primary_spans.push(span);
3340 with_forced_trimmed_paths!(format!(
3341 "`{}` is `{ty}` here",
3342 self.tcx.def_path_str(assoc),
3348 for (entry, prev_entry) in
3349 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
3351 match (entry, prev_entry) {
3352 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
3353 let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
3355 let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
3357 if type_diffs.iter().any(|diff| {
3358 let Sorts(expected_found) = diff else { return false; };
3359 self.can_eq(param_env, expected_found.found, ty).is_ok()
3361 primary_spans.push(span);
3364 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
3366 span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
3369 (Some((span, (assoc, ty))), None) => {
3372 with_forced_trimmed_paths!(format!(
3373 "`{}` is `{}` here",
3374 self.tcx.def_path_str(assoc),
3375 self.ty_to_string(ty),
3379 (None, Some(_)) | (None, None) => {}
3383 for span in call_spans {
3384 if span_labels.iter().find(|(s, _)| *s == span).is_none() {
3385 // Ensure we are showing the entire chain, even if the assoc types
3387 span_labels.push((span, String::new()));
3390 if !primary_spans.is_empty() {
3391 let mut multi_span: MultiSpan = primary_spans.into();
3392 for (span, label) in span_labels {
3393 multi_span.push_span_label(span, label);
3398 "the method call chain might not have had the expected \
3406 /// Add a hint to add a missing borrow or remove an unnecessary one.
3407 fn hint_missing_borrow<'tcx>(
3412 found_node: Node<'_>,
3413 err: &mut Diagnostic,
3415 let found_args = match found.kind() {
3416 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3418 span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
3421 let expected_args = match expected.kind() {
3422 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3424 span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
3428 let fn_decl = found_node
3430 .unwrap_or_else(|| span_bug!(found_span, "found node must be a function"));
3432 let arg_spans = fn_decl.inputs.iter().map(|ty| ty.span);
3434 fn get_deref_type_and_refs<'tcx>(mut ty: Ty<'tcx>) -> (Ty<'tcx>, usize) {
3437 while let ty::Ref(_, new_ty, _) = ty.kind() {
3445 let mut to_borrow = Vec::new();
3446 let mut remove_borrow = Vec::new();
3448 for ((found_arg, expected_arg), arg_span) in found_args.zip(expected_args).zip(arg_spans) {
3449 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
3450 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
3452 if found_ty == expected_ty {
3453 if found_refs < expected_refs {
3454 to_borrow.push((arg_span, expected_arg.to_string()));
3455 } else if found_refs > expected_refs {
3456 remove_borrow.push((arg_span, expected_arg.to_string()));
3461 if !to_borrow.is_empty() {
3462 err.multipart_suggestion(
3463 "consider borrowing the argument",
3465 Applicability::MaybeIncorrect,
3469 if !remove_borrow.is_empty() {
3470 err.multipart_suggestion(
3471 "do not borrow the argument",
3473 Applicability::MaybeIncorrect,
3478 /// Collect all the returned expressions within the input expression.
3479 /// Used to point at the return spans when we want to suggest some change to them.
3481 pub struct ReturnsVisitor<'v> {
3482 pub returns: Vec<&'v hir::Expr<'v>>,
3483 in_block_tail: bool,
3486 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3487 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3488 // Visit every expression to detect `return` paths, either through the function's tail
3489 // expression or `return` statements. We walk all nodes to find `return` statements, but
3490 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3491 // they're in the return path of the function body.
3493 hir::ExprKind::Ret(Some(ex)) => {
3494 self.returns.push(ex);
3496 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3497 self.in_block_tail = false;
3498 for stmt in block.stmts {
3499 hir::intravisit::walk_stmt(self, stmt);
3501 self.in_block_tail = true;
3502 if let Some(expr) = block.expr {
3503 self.visit_expr(expr);
3506 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3507 self.visit_expr(then);
3508 if let Some(el) = else_opt {
3509 self.visit_expr(el);
3512 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3514 self.visit_expr(arm.body);
3517 // We need to walk to find `return`s in the entire body.
3518 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3519 _ => self.returns.push(ex),
3523 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3524 assert!(!self.in_block_tail);
3525 if body.generator_kind().is_none() {
3526 if let hir::ExprKind::Block(block, None) = body.value.kind {
3527 if block.expr.is_some() {
3528 self.in_block_tail = true;
3532 hir::intravisit::walk_body(self, body);
3536 /// Collect all the awaited expressions within the input expression.
3538 struct AwaitsVisitor {
3539 awaits: Vec<hir::HirId>,
3542 impl<'v> Visitor<'v> for AwaitsVisitor {
3543 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3544 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3545 self.awaits.push(id)
3547 hir::intravisit::walk_expr(self, ex)
3551 pub trait NextTypeParamName {
3552 fn next_type_param_name(&self, name: Option<&str>) -> String;
3555 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3556 fn next_type_param_name(&self, name: Option<&str>) -> String {
3557 // This is the list of possible parameter names that we might suggest.
3558 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3559 let name = name.as_deref();
3560 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3561 let used_names = self
3563 .filter_map(|p| match p.name {
3564 hir::ParamName::Plain(ident) => Some(ident.name),
3567 .collect::<Vec<_>>();
3571 .find(|n| !used_names.contains(&Symbol::intern(n)))
3572 .unwrap_or(&"ParamName")
3577 fn suggest_trait_object_return_type_alternatives(
3578 err: &mut Diagnostic,
3581 is_object_safe: bool,
3583 err.span_suggestion(
3585 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3588 Applicability::MaybeIncorrect,
3590 err.span_suggestion(
3593 "use `impl {}` as the return type if all return paths have the same type but you \
3594 want to expose only the trait in the signature",
3597 format!("impl {}", trait_obj),
3598 Applicability::MaybeIncorrect,
3601 err.multipart_suggestion(
3603 "use a boxed trait object if all return paths implement trait `{}`",
3607 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3608 (ret_ty.shrink_to_hi(), ">".to_string()),
3610 Applicability::MaybeIncorrect,
3615 /// Collect the spans that we see the generic param `param_did`
3616 struct ReplaceImplTraitVisitor<'a> {
3617 ty_spans: &'a mut Vec<Span>,
3621 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3622 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3623 if let hir::TyKind::Path(hir::QPath::Resolved(
3625 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3628 if self.param_did == *segment_did {
3629 // `fn foo(t: impl Trait)`
3630 // ^^^^^^^^^^ get this to suggest `T` instead
3632 // There might be more than one `impl Trait`.
3633 self.ty_spans.push(t.span);
3638 hir::intravisit::walk_ty(self, t);
3642 // Replace `param` with `replace_ty`
3643 struct ReplaceImplTraitFolder<'tcx> {
3645 param: &'tcx ty::GenericParamDef,
3646 replace_ty: Ty<'tcx>,
3649 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3650 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3651 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3652 if self.param.index == *index {
3653 return self.replace_ty;
3656 t.super_fold_with(self)
3659 fn tcx(&self) -> TyCtxt<'tcx> {