2 DefIdOrName, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation,
6 use crate::autoderef::Autoderef;
7 use crate::infer::InferCtxt;
8 use crate::traits::normalize_to;
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_data_structures::stack::ensure_sufficient_stack;
15 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
16 ErrorGuaranteed, MultiSpan, Style,
19 use rustc_hir::def::DefKind;
20 use rustc_hir::def_id::DefId;
21 use rustc_hir::intravisit::Visitor;
22 use rustc_hir::lang_items::LangItem;
23 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
24 use rustc_infer::infer::error_reporting::TypeErrCtxt;
25 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
26 use rustc_infer::infer::LateBoundRegionConversionTime;
27 use rustc_middle::hir::map;
28 use rustc_middle::ty::{
29 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
30 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, IsSuggestable,
31 ToPredicate, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
33 use rustc_middle::ty::{TypeAndMut, TypeckResults};
34 use rustc_span::symbol::{sym, Ident, Symbol};
35 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
36 use rustc_target::spec::abi;
39 use super::InferCtxtPrivExt;
40 use crate::infer::InferCtxtExt as _;
41 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
42 use rustc_middle::ty::print::with_no_trimmed_paths;
45 pub enum GeneratorInteriorOrUpvar {
46 // span of interior type
47 Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
52 // This type provides a uniform interface to retrieve data on generators, whether it originated from
53 // the local crate being compiled or from a foreign crate.
55 pub enum GeneratorData<'tcx, 'a> {
56 Local(&'a TypeckResults<'tcx>),
57 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
60 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
61 // Try to get information about variables captured by the generator that matches a type we are
62 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
64 fn try_get_upvar_span<F>(
66 infer_context: &InferCtxt<'tcx>,
69 ) -> Option<GeneratorInteriorOrUpvar>
71 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
74 GeneratorData::Local(typeck_results) => {
75 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
76 upvars.iter().find_map(|(upvar_id, upvar)| {
77 let upvar_ty = typeck_results.node_type(*upvar_id);
78 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
79 if ty_matches(ty::Binder::dummy(upvar_ty)) {
80 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
87 GeneratorData::Foreign(_) => None,
91 // Try to get the span of a type being awaited on that matches the type we are looking with the
92 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
94 fn get_from_await_ty<F>(
96 visitor: AwaitsVisitor,
101 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
104 GeneratorData::Local(typeck_results) => visitor
107 .map(|id| hir.expect_expr(id))
109 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
111 .map(|expr| expr.span),
112 GeneratorData::Foreign(generator_diagnostic_data) => visitor
115 .map(|id| hir.expect_expr(id))
117 ty_matches(ty::Binder::dummy(
118 generator_diagnostic_data
120 .get(&await_expr.hir_id.local_id)
121 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
123 .map_or_else::<Ty<'tcx>, _, _>(
125 generator_diagnostic_data
127 .get(&await_expr.hir_id.local_id)
131 "node_type: no type for node `{}`",
132 ty::tls::with(|tcx| tcx
134 .node_to_string(await_expr.hir_id))
142 .map(|expr| expr.span),
146 /// Get the type, expression, span and optional scope span of all types
147 /// that are live across the yield of this generator
148 fn get_generator_interior_types(
150 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
152 GeneratorData::Local(typeck_result) => {
153 typeck_result.generator_interior_types.as_deref()
155 GeneratorData::Foreign(generator_diagnostic_data) => {
156 generator_diagnostic_data.generator_interior_types.as_deref()
161 // Used to get the source of the data, note we don't have as much information for generators
162 // originated from foreign crates
163 fn is_foreign(&self) -> bool {
165 GeneratorData::Local(_) => false,
166 GeneratorData::Foreign(_) => true,
171 // This trait is public to expose the diagnostics methods to clippy.
172 pub trait TypeErrCtxtExt<'tcx> {
173 fn suggest_restricting_param_bound(
175 err: &mut Diagnostic,
176 trait_pred: ty::PolyTraitPredicate<'tcx>,
177 associated_item: Option<(&'static str, Ty<'tcx>)>,
181 fn suggest_dereferences(
183 obligation: &PredicateObligation<'tcx>,
184 err: &mut Diagnostic,
185 trait_pred: ty::PolyTraitPredicate<'tcx>,
188 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
192 obligation: &PredicateObligation<'tcx>,
193 err: &mut Diagnostic,
194 trait_pred: ty::PolyTraitPredicate<'tcx>,
197 fn suggest_add_reference_to_arg(
199 obligation: &PredicateObligation<'tcx>,
200 err: &mut Diagnostic,
201 trait_pred: ty::PolyTraitPredicate<'tcx>,
202 has_custom_message: bool,
205 fn suggest_borrowing_for_object_cast(
207 err: &mut Diagnostic,
208 obligation: &PredicateObligation<'tcx>,
213 fn suggest_remove_reference(
215 obligation: &PredicateObligation<'tcx>,
216 err: &mut Diagnostic,
217 trait_pred: ty::PolyTraitPredicate<'tcx>,
220 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
222 fn suggest_change_mut(
224 obligation: &PredicateObligation<'tcx>,
225 err: &mut Diagnostic,
226 trait_pred: ty::PolyTraitPredicate<'tcx>,
229 fn suggest_semicolon_removal(
231 obligation: &PredicateObligation<'tcx>,
232 err: &mut Diagnostic,
234 trait_pred: ty::PolyTraitPredicate<'tcx>,
237 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
239 fn suggest_impl_trait(
241 err: &mut Diagnostic,
243 obligation: &PredicateObligation<'tcx>,
244 trait_pred: ty::PolyTraitPredicate<'tcx>,
247 fn point_at_returns_when_relevant(
249 err: &mut Diagnostic,
250 obligation: &PredicateObligation<'tcx>,
253 fn report_closure_arg_mismatch(
256 found_span: Option<Span>,
257 found: ty::PolyTraitRef<'tcx>,
258 expected: ty::PolyTraitRef<'tcx>,
259 cause: &ObligationCauseCode<'tcx>,
260 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
262 fn note_conflicting_closure_bounds(
264 cause: &ObligationCauseCode<'tcx>,
265 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
268 fn suggest_fully_qualified_path(
270 err: &mut Diagnostic,
276 fn maybe_note_obligation_cause_for_async_await(
278 err: &mut Diagnostic,
279 obligation: &PredicateObligation<'tcx>,
282 fn note_obligation_cause_for_async_await(
284 err: &mut Diagnostic,
285 interior_or_upvar_span: GeneratorInteriorOrUpvar,
287 outer_generator: Option<DefId>,
288 trait_pred: ty::TraitPredicate<'tcx>,
290 typeck_results: Option<&ty::TypeckResults<'tcx>>,
291 obligation: &PredicateObligation<'tcx>,
292 next_code: Option<&ObligationCauseCode<'tcx>>,
295 fn note_obligation_cause_code<T>(
297 err: &mut Diagnostic,
299 param_env: ty::ParamEnv<'tcx>,
300 cause_code: &ObligationCauseCode<'tcx>,
301 obligated_types: &mut Vec<Ty<'tcx>>,
302 seen_requirements: &mut FxHashSet<DefId>,
304 T: fmt::Display + ToPredicate<'tcx, T>;
306 /// Suggest to await before try: future? => future.await?
307 fn suggest_await_before_try(
309 err: &mut Diagnostic,
310 obligation: &PredicateObligation<'tcx>,
311 trait_pred: ty::PolyTraitPredicate<'tcx>,
315 fn suggest_floating_point_literal(
317 obligation: &PredicateObligation<'tcx>,
318 err: &mut Diagnostic,
319 trait_ref: &ty::PolyTraitRef<'tcx>,
324 obligation: &PredicateObligation<'tcx>,
325 err: &mut Diagnostic,
326 trait_pred: ty::PolyTraitPredicate<'tcx>,
329 fn suggest_dereferencing_index(
331 obligation: &PredicateObligation<'tcx>,
332 err: &mut Diagnostic,
333 trait_pred: ty::PolyTraitPredicate<'tcx>,
337 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
339 generics.tail_span_for_predicate_suggestion(),
340 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
344 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
345 /// it can also be an `impl Trait` param that needs to be decomposed to a type
346 /// param for cleaner code.
347 fn suggest_restriction<'tcx>(
350 hir_generics: &hir::Generics<'tcx>,
352 err: &mut Diagnostic,
353 fn_sig: Option<&hir::FnSig<'_>>,
354 projection: Option<&ty::ProjectionTy<'_>>,
355 trait_pred: ty::PolyTraitPredicate<'tcx>,
356 // When we are dealing with a trait, `super_traits` will be `Some`:
357 // Given `trait T: A + B + C {}`
358 // - ^^^^^^^^^ GenericBounds
361 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
363 if hir_generics.where_clause_span.from_expansion()
364 || hir_generics.where_clause_span.desugaring_kind().is_some()
368 let Some(item_id) = hir_id.as_owner() else { return; };
369 let generics = tcx.generics_of(item_id);
370 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
371 if let Some((param, bound_str, fn_sig)) =
372 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
373 // Shenanigans to get the `Trait` from the `impl Trait`.
374 ty::Param(param) => {
375 let param_def = generics.type_param(param, tcx);
376 if param_def.kind.is_synthetic() {
378 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
379 return Some((param_def, bound_str, sig));
386 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
387 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
390 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
393 if !trait_pred.is_suggestable(tcx, false) {
396 // We know we have an `impl Trait` that doesn't satisfy a required projection.
398 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
399 // types. There should be at least one, but there might be *more* than one. In that
400 // case we could just ignore it and try to identify which one needs the restriction,
401 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
403 let mut ty_spans = vec![];
404 for input in fn_sig.decl.inputs {
405 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
408 // The type param `T: Trait` we will suggest to introduce.
409 let type_param = format!("{}: {}", type_param_name, bound_str);
412 if let Some(span) = hir_generics.span_for_param_suggestion() {
413 (span, format!(", {}", type_param))
415 (hir_generics.span, format!("<{}>", type_param))
417 // `fn foo(t: impl Trait)`
418 // ^ suggest `where <T as Trait>::A: Bound`
419 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
421 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
423 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
424 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
425 // `fn foo(t: impl Trait<A: Bound>)` instead.
426 err.multipart_suggestion(
427 "introduce a type parameter with a trait bound instead of using `impl Trait`",
429 Applicability::MaybeIncorrect,
432 if !trait_pred.is_suggestable(tcx, false) {
435 // Trivial case: `T` needs an extra bound: `T: Bound`.
436 let (sp, suggestion) = match (
440 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
443 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
444 (None, Some((ident, []))) => (
445 ident.span.shrink_to_hi(),
446 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
448 (_, Some((_, [.., bounds]))) => (
449 bounds.span().shrink_to_hi(),
450 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
452 (Some(_), Some((_, []))) => (
453 hir_generics.span.shrink_to_hi(),
454 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
458 err.span_suggestion_verbose(
460 &format!("consider further restricting {}", msg),
462 Applicability::MachineApplicable,
467 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
468 fn suggest_restricting_param_bound(
470 mut err: &mut Diagnostic,
471 trait_pred: ty::PolyTraitPredicate<'tcx>,
472 associated_ty: Option<(&'static str, Ty<'tcx>)>,
475 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
477 let self_ty = trait_pred.skip_binder().self_ty();
478 let (param_ty, projection) = match self_ty.kind() {
479 ty::Param(_) => (true, None),
480 ty::Projection(projection) => (false, Some(projection)),
484 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
485 // don't suggest `T: Sized + ?Sized`.
486 let mut hir_id = body_id;
487 while let Some(node) = self.tcx.hir().find(hir_id) {
489 hir::Node::Item(hir::Item {
491 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
493 }) if self_ty == self.tcx.types.self_param => {
495 // Restricting `Self` for a single method.
505 Some((ident, bounds)),
510 hir::Node::TraitItem(hir::TraitItem {
512 kind: hir::TraitItemKind::Fn(..),
514 }) if self_ty == self.tcx.types.self_param => {
516 // Restricting `Self` for a single method.
518 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
524 hir::Node::TraitItem(hir::TraitItem {
526 kind: hir::TraitItemKind::Fn(fn_sig, ..),
529 | hir::Node::ImplItem(hir::ImplItem {
531 kind: hir::ImplItemKind::Fn(fn_sig, ..),
534 | hir::Node::Item(hir::Item {
535 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
536 }) if projection.is_some() => {
537 // Missing restriction on associated type of type parameter (unmet projection).
542 "the associated type",
551 hir::Node::Item(hir::Item {
553 hir::ItemKind::Trait(_, _, generics, ..)
554 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
556 }) if projection.is_some() => {
557 // Missing restriction on associated type of type parameter (unmet projection).
562 "the associated type",
572 hir::Node::Item(hir::Item {
574 hir::ItemKind::Struct(_, generics)
575 | hir::ItemKind::Enum(_, generics)
576 | hir::ItemKind::Union(_, generics)
577 | hir::ItemKind::Trait(_, _, generics, ..)
578 | hir::ItemKind::Impl(hir::Impl { generics, .. })
579 | hir::ItemKind::Fn(_, generics, _)
580 | hir::ItemKind::TyAlias(_, generics)
581 | hir::ItemKind::TraitAlias(generics, _)
582 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
585 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
586 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
589 // We skip the 0'th subst (self) because we do not want
590 // to consider the predicate as not suggestible if the
591 // self type is an arg position `impl Trait` -- instead,
592 // we handle that by adding ` + Bound` below.
593 // FIXME(compiler-errors): It would be nice to do the same
594 // this that we do in `suggest_restriction` and pull the
595 // `impl Trait` into a new generic if it shows up somewhere
596 // else in the predicate.
597 if !trait_pred.skip_binder().trait_ref.substs[1..]
599 .all(|g| g.is_suggestable(self.tcx, false))
603 // Missing generic type parameter bound.
604 let param_name = self_ty.to_string();
605 let mut constraint = with_no_trimmed_paths!(
606 trait_pred.print_modifiers_and_trait_path().to_string()
609 if let Some((name, term)) = associated_ty {
610 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
611 // That should be extracted into a helper function.
612 if constraint.ends_with('>') {
613 constraint = format!(
615 &constraint[..constraint.len() - 1],
620 constraint.push_str(&format!("<{} = {}>", name, term));
624 if suggest_constraining_type_param(
630 Some(trait_pred.def_id()),
636 hir::Node::Item(hir::Item {
638 hir::ItemKind::Struct(_, generics)
639 | hir::ItemKind::Enum(_, generics)
640 | hir::ItemKind::Union(_, generics)
641 | hir::ItemKind::Trait(_, _, generics, ..)
642 | hir::ItemKind::Impl(hir::Impl { generics, .. })
643 | hir::ItemKind::Fn(_, generics, _)
644 | hir::ItemKind::TyAlias(_, generics)
645 | hir::ItemKind::TraitAlias(generics, _)
646 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
649 // Missing generic type parameter bound.
650 if suggest_arbitrary_trait_bound(
660 hir::Node::Crate(..) => return,
665 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
669 /// When after several dereferencing, the reference satisfies the trait
670 /// binding. This function provides dereference suggestion for this
671 /// specific situation.
672 fn suggest_dereferences(
674 obligation: &PredicateObligation<'tcx>,
675 err: &mut Diagnostic,
676 trait_pred: ty::PolyTraitPredicate<'tcx>,
678 // It only make sense when suggesting dereferences for arguments
679 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code()
680 else { return false; };
681 let Some(typeck_results) = &self.typeck_results
682 else { return false; };
683 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
684 else { return false; };
685 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
686 else { return false; };
688 let span = obligation.cause.span;
689 let mut real_trait_pred = trait_pred;
690 let mut code = obligation.cause.code();
691 while let Some((parent_code, parent_trait_pred)) = code.parent() {
693 if let Some(parent_trait_pred) = parent_trait_pred {
694 real_trait_pred = parent_trait_pred;
697 let real_ty = real_trait_pred.self_ty();
698 // We `erase_late_bound_regions` here because `make_subregion` does not handle
699 // `ReLateBound`, and we don't particularly care about the regions.
701 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
707 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
708 let mut autoderef = Autoderef::new(
710 obligation.param_env,
711 obligation.cause.body_id,
715 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
717 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
719 // Remapping bound vars here
720 let real_trait_pred_and_ty =
721 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
722 let obligation = self.mk_trait_obligation_with_new_self_ty(
723 obligation.param_env,
724 real_trait_pred_and_ty,
726 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
729 // Don't care about `&mut` because `DerefMut` is used less
730 // often and user will not expect autoderef happens.
731 if let Some(hir::Node::Expr(hir::Expr {
733 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
735 })) = self.tcx.hir().find(*arg_hir_id)
737 let derefs = "*".repeat(steps);
738 err.span_suggestion_verbose(
739 expr.span.shrink_to_lo(),
740 "consider dereferencing here",
742 Applicability::MachineApplicable,
747 } else if real_trait_pred != trait_pred {
748 // This branch addresses #87437.
750 // Remapping bound vars here
751 let real_trait_pred_and_base_ty =
752 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
753 let obligation = self.mk_trait_obligation_with_new_self_ty(
754 obligation.param_env,
755 real_trait_pred_and_base_ty,
757 if self.predicate_may_hold(&obligation) {
758 err.span_suggestion_verbose(
760 "consider dereferencing here",
762 Applicability::MachineApplicable,
772 /// Given a closure's `DefId`, return the given name of the closure.
774 /// This doesn't account for reassignments, but it's only used for suggestions.
775 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
776 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
777 // Get the local name of this closure. This can be inaccurate because
778 // of the possibility of reassignment, but this should be good enough.
780 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
790 let hir = self.tcx.hir();
791 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
792 let parent_node = hir.get_parent_node(hir_id);
793 match hir.find(parent_node) {
794 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
795 get_name(err, &local.pat.kind)
797 // Different to previous arm because one is `&hir::Local` and the other
798 // is `P<hir::Local>`.
799 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
804 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
805 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
806 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
809 obligation: &PredicateObligation<'tcx>,
810 err: &mut Diagnostic,
811 trait_pred: ty::PolyTraitPredicate<'tcx>,
813 if let ty::PredicateKind::Trait(trait_pred) = obligation.predicate.kind().skip_binder()
814 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
816 // Don't suggest calling to turn an unsized type into a sized type
820 // This is duplicated from `extract_callable_info` in typeck, which
821 // relies on autoderef, so we can't use it here.
822 let found = trait_pred.self_ty().skip_binder().peel_refs();
823 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
825 ty::FnPtr(fn_sig) => {
826 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
828 ty::FnDef(def_id, _) => {
829 let fn_sig = found.fn_sig(self.tcx);
830 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
832 ty::Closure(def_id, substs) => {
833 let fn_sig = substs.as_closure().sig();
835 DefIdOrName::DefId(def_id),
837 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
840 ty::Opaque(def_id, substs) => {
841 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
842 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
843 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
844 // args tuple will always be substs[1]
845 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
848 DefIdOrName::DefId(def_id),
849 pred.kind().rebind(proj.term.ty().unwrap()),
850 pred.kind().rebind(args.as_slice()),
857 ty::Dynamic(data, _, ty::Dyn) => {
858 data.iter().find_map(|pred| {
859 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
860 && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
861 // for existential projection, substs are shifted over by 1
862 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
865 DefIdOrName::Name("trait object"),
866 pred.rebind(proj.term.ty().unwrap()),
867 pred.rebind(args.as_slice()),
875 obligation.param_env.caller_bounds().iter().find_map(|pred| {
876 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
877 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
878 && proj.projection_ty.self_ty() == found
879 // args tuple will always be substs[1]
880 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
883 DefIdOrName::Name("type parameter"),
884 pred.kind().rebind(proj.term.ty().unwrap()),
885 pred.kind().rebind(args.as_slice()),
893 }) else { return false; };
894 let output = self.replace_bound_vars_with_fresh_vars(
895 obligation.cause.span,
896 LateBoundRegionConversionTime::FnCall,
899 let inputs = inputs.skip_binder().iter().map(|ty| {
900 self.replace_bound_vars_with_fresh_vars(
901 obligation.cause.span,
902 LateBoundRegionConversionTime::FnCall,
907 // Remapping bound vars here
908 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
911 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
912 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
916 // Get the name of the callable and the arguments to be used in the suggestion.
917 let hir = self.tcx.hir();
919 let msg = match def_id_or_name {
920 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
921 DefKind::Ctor(CtorOf::Struct, _) => {
922 "use parentheses to construct this tuple struct".to_string()
924 DefKind::Ctor(CtorOf::Variant, _) => {
925 "use parentheses to construct this tuple variant".to_string()
927 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
929 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
934 if ty.is_suggestable(self.tcx, false) {
935 format!("/* {ty} */")
937 "/* value */".to_string()
943 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
944 && obligation.cause.span.can_be_used_for_suggestions()
946 // When the obligation error has been ensured to have been caused by
947 // an argument, the `obligation.cause.span` points at the expression
948 // of the argument, so we can provide a suggestion. Otherwise, we give
949 // a more general note.
950 err.span_suggestion_verbose(
951 obligation.cause.span.shrink_to_hi(),
954 Applicability::HasPlaceholders,
956 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
957 let name = match hir.get_if_local(def_id) {
958 Some(hir::Node::Expr(hir::Expr {
959 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
962 err.span_label(*fn_decl_span, "consider calling this closure");
963 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
968 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
969 err.span_label(ident.span, "consider calling this function");
972 Some(hir::Node::Ctor(..)) => {
973 let name = self.tcx.def_path_str(def_id);
975 self.tcx.def_span(def_id),
976 format!("consider calling the constructor for `{}`", name),
982 err.help(&format!("{msg}: `{name}({args})`"));
987 fn suggest_add_reference_to_arg(
989 obligation: &PredicateObligation<'tcx>,
990 err: &mut Diagnostic,
991 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
992 has_custom_message: bool,
994 let span = obligation.cause.span;
996 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
997 obligation.cause.code()
1000 } else if let ObligationCauseCode::ItemObligation(_)
1001 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1003 obligation.cause.code()
1004 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1005 span.ctxt().outer_expn_data().kind
1007 obligation.cause.code()
1012 // List of traits for which it would be nonsensical to suggest borrowing.
1013 // For instance, immutable references are always Copy, so suggesting to
1014 // borrow would always succeed, but it's probably not what the user wanted.
1015 let mut never_suggest_borrow: Vec<_> =
1016 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1018 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1021 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1022 never_suggest_borrow.push(def_id);
1025 let param_env = obligation.param_env;
1027 // Try to apply the original trait binding obligation by borrowing.
1028 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1029 blacklist: &[DefId]|
1031 if blacklist.contains(&old_pred.def_id()) {
1034 // We map bounds to `&T` and `&mut T`
1035 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1038 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1041 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1044 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1048 let mk_result = |trait_pred_and_new_ty| {
1050 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1051 self.predicate_must_hold_modulo_regions(&obligation)
1053 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1054 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1056 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1057 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1058 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1061 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1062 matches!(mutability, hir::Mutability::Mut),
1068 if imm_ref_self_ty_satisfies_pred
1069 || mut_ref_self_ty_satisfies_pred
1070 || ref_inner_ty_satisfies_pred
1072 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1073 // We don't want a borrowing suggestion on the fields in structs,
1076 // the_foos: Vec<Foo>
1080 span.ctxt().outer_expn_data().kind,
1081 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1085 if snippet.starts_with('&') {
1086 // This is already a literal borrow and the obligation is failing
1087 // somewhere else in the obligation chain. Do not suggest non-sense.
1090 // We have a very specific type of error, where just borrowing this argument
1091 // might solve the problem. In cases like this, the important part is the
1092 // original type obligation, not the last one that failed, which is arbitrary.
1093 // Because of this, we modify the error to refer to the original obligation and
1094 // return early in the caller.
1096 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1097 if has_custom_message {
1101 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1106 "the trait `{}` is not implemented for `{}`",
1107 old_pred.print_modifiers_and_trait_path(),
1108 old_pred.self_ty().skip_binder(),
1112 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1113 err.span_suggestions(
1114 span.shrink_to_lo(),
1115 "consider borrowing here",
1116 ["&".to_string(), "&mut ".to_string()],
1117 Applicability::MaybeIncorrect,
1120 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1121 err.span_suggestion_verbose(
1122 span.shrink_to_lo(),
1124 "consider{} borrowing here",
1125 if is_mut { " mutably" } else { "" }
1127 format!("&{}", if is_mut { "mut " } else { "" }),
1128 Applicability::MaybeIncorrect,
1137 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1138 try_borrowing(cause.derived.parent_trait_pred, &[])
1139 } else if let ObligationCauseCode::BindingObligation(_, _)
1140 | ObligationCauseCode::ItemObligation(_)
1141 | ObligationCauseCode::ExprItemObligation(..)
1142 | ObligationCauseCode::ExprBindingObligation(..) = code
1144 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1150 // Suggest borrowing the type
1151 fn suggest_borrowing_for_object_cast(
1153 err: &mut Diagnostic,
1154 obligation: &PredicateObligation<'tcx>,
1156 object_ty: Ty<'tcx>,
1158 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1159 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1161 for predicate in predicates.iter() {
1162 if !self.predicate_must_hold_modulo_regions(
1163 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1169 err.span_suggestion(
1170 obligation.cause.span.shrink_to_lo(),
1172 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1175 Applicability::MaybeIncorrect,
1179 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1180 /// suggest removing these references until we reach a type that implements the trait.
1181 fn suggest_remove_reference(
1183 obligation: &PredicateObligation<'tcx>,
1184 err: &mut Diagnostic,
1185 trait_pred: ty::PolyTraitPredicate<'tcx>,
1187 let span = obligation.cause.span;
1189 let mut suggested = false;
1190 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1192 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1193 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1194 // Do not suggest removal of borrow from type arguments.
1198 // Skipping binder here, remapping below
1199 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1201 for refs_remaining in 0..refs_number {
1202 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1205 suggested_ty = *inner_ty;
1207 // Remapping bound vars here
1208 let trait_pred_and_suggested_ty =
1209 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1211 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1212 obligation.param_env,
1213 trait_pred_and_suggested_ty,
1216 if self.predicate_may_hold(&new_obligation) {
1221 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1223 let remove_refs = refs_remaining + 1;
1225 let msg = if remove_refs == 1 {
1226 "consider removing the leading `&`-reference".to_string()
1228 format!("consider removing {} leading `&`-references", remove_refs)
1231 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1240 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1241 let span = obligation.cause.span;
1243 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1244 let hir = self.tcx.hir();
1245 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1246 if let hir::Node::Expr(expr) = node {
1247 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1248 // and if not maybe suggest doing something else? If we kept the expression around we
1249 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1250 // it is from the local crate.
1251 err.span_suggestion(
1253 "remove the `.await`",
1255 Applicability::MachineApplicable,
1257 // FIXME: account for associated `async fn`s.
1258 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1259 if let ty::PredicateKind::Trait(pred) =
1260 obligation.predicate.kind().skip_binder()
1264 &format!("this call returns `{}`", pred.self_ty()),
1267 if let Some(typeck_results) = &self.typeck_results
1268 && let ty = typeck_results.expr_ty_adjusted(base)
1269 && let ty::FnDef(def_id, _substs) = ty.kind()
1270 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1271 hir.get_if_local(*def_id)
1274 "alternatively, consider making `fn {}` asynchronous",
1277 if vis_span.is_empty() {
1278 err.span_suggestion_verbose(
1279 span.shrink_to_lo(),
1282 Applicability::MaybeIncorrect,
1285 err.span_suggestion_verbose(
1286 vis_span.shrink_to_hi(),
1289 Applicability::MaybeIncorrect,
1299 /// Check if the trait bound is implemented for a different mutability and note it in the
1301 fn suggest_change_mut(
1303 obligation: &PredicateObligation<'tcx>,
1304 err: &mut Diagnostic,
1305 trait_pred: ty::PolyTraitPredicate<'tcx>,
1307 let points_at_arg = matches!(
1308 obligation.cause.code(),
1309 ObligationCauseCode::FunctionArgumentObligation { .. },
1312 let span = obligation.cause.span;
1313 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1315 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1316 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1317 // Do not suggest removal of borrow from type arguments.
1320 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1321 if trait_pred.has_non_region_infer() {
1322 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1323 // unresolved bindings.
1327 // Skipping binder here, remapping below
1328 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1330 let suggested_ty = match mutability {
1331 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1332 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1335 // Remapping bound vars here
1336 let trait_pred_and_suggested_ty =
1337 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1339 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1340 obligation.param_env,
1341 trait_pred_and_suggested_ty,
1343 let suggested_ty_would_satisfy_obligation =
1344 self.predicate_must_hold_modulo_regions(&new_obligation);
1345 if suggested_ty_would_satisfy_obligation {
1350 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1351 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1352 err.span_suggestion_verbose(
1354 "consider changing this borrow's mutability",
1356 Applicability::MachineApplicable,
1360 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1361 trait_pred.print_modifiers_and_trait_path(),
1363 trait_pred.skip_binder().self_ty(),
1371 fn suggest_semicolon_removal(
1373 obligation: &PredicateObligation<'tcx>,
1374 err: &mut Diagnostic,
1376 trait_pred: ty::PolyTraitPredicate<'tcx>,
1378 let hir = self.tcx.hir();
1379 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1380 let node = hir.find(parent_node);
1381 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1382 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1383 && sig.decl.output.span().overlaps(span)
1384 && blk.expr.is_none()
1385 && trait_pred.self_ty().skip_binder().is_unit()
1386 && let Some(stmt) = blk.stmts.last()
1387 && let hir::StmtKind::Semi(expr) = stmt.kind
1388 // Only suggest this if the expression behind the semicolon implements the predicate
1389 && let Some(typeck_results) = &self.typeck_results
1390 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1391 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1392 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1398 "this expression has type `{}`, which implements `{}`",
1400 trait_pred.print_modifiers_and_trait_path()
1403 err.span_suggestion(
1404 self.tcx.sess.source_map().end_point(stmt.span),
1405 "remove this semicolon",
1407 Applicability::MachineApplicable
1414 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1415 let hir = self.tcx.hir();
1416 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1417 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1421 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1424 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1425 /// applicable and signal that the error has been expanded appropriately and needs to be
1427 fn suggest_impl_trait(
1429 err: &mut Diagnostic,
1431 obligation: &PredicateObligation<'tcx>,
1432 trait_pred: ty::PolyTraitPredicate<'tcx>,
1434 match obligation.cause.code().peel_derives() {
1435 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1436 ObligationCauseCode::SizedReturnType => {}
1440 let hir = self.tcx.hir();
1441 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1442 let node = hir.find(fn_hir_id);
1443 let Some(hir::Node::Item(hir::Item {
1444 kind: hir::ItemKind::Fn(sig, _, body_id),
1450 let body = hir.body(*body_id);
1451 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1452 let ty = trait_pred.skip_binder().self_ty();
1453 let is_object_safe = match ty.kind() {
1454 ty::Dynamic(predicates, _, ty::Dyn) => {
1455 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1458 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1460 // We only want to suggest `impl Trait` to `dyn Trait`s.
1461 // For example, `fn foo() -> str` needs to be filtered out.
1465 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1469 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1470 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1471 // Recursively look for `TraitObject` types and if there's only one, use that span to
1472 // suggest `impl Trait`.
1474 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1475 // otherwise suggest using `Box<dyn Trait>` or an enum.
1476 let mut visitor = ReturnsVisitor::default();
1477 visitor.visit_body(&body);
1479 let typeck_results = self.typeck_results.as_ref().unwrap();
1480 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1482 let ret_types = visitor
1485 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1486 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1487 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1489 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1491 let ty = self.resolve_vars_if_possible(ty);
1493 !matches!(ty.kind(), ty::Error(_))
1494 && last_ty.map_or(true, |last_ty| {
1495 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1496 // *after* in the dependency graph.
1497 match (ty.kind(), last_ty.kind()) {
1498 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1499 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1500 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1502 Infer(InferTy::FreshFloatTy(_)),
1503 Infer(InferTy::FreshFloatTy(_)),
1508 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1511 let mut spans_and_needs_box = vec![];
1513 match liberated_sig.output().kind() {
1514 ty::Dynamic(predicates, _, ty::Dyn) => {
1515 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1516 let param_env = ty::ParamEnv::empty();
1518 if !only_never_return {
1519 for (expr_span, return_ty) in ret_types {
1520 let self_ty_satisfies_dyn_predicates = |self_ty| {
1521 predicates.iter().all(|predicate| {
1522 let pred = predicate.with_self_ty(self.tcx, self_ty);
1523 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1524 self.predicate_may_hold(&obl)
1528 if let ty::Adt(def, substs) = return_ty.kind()
1530 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1532 spans_and_needs_box.push((expr_span, false));
1533 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1534 spans_and_needs_box.push((expr_span, true));
1544 let sm = self.tcx.sess.source_map();
1545 if !ret_ty.span.overlaps(span) {
1548 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1549 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1555 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1556 let name = liberated_sig.output().to_string();
1558 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1559 if !name.starts_with("dyn ") {
1565 err.code(error_code!(E0746));
1566 err.set_primary_message("return type cannot have an unboxed trait object");
1567 err.children.clear();
1568 let impl_trait_msg = "for information on `impl Trait`, see \
1569 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1570 #returning-types-that-implement-traits>";
1571 let trait_obj_msg = "for information on trait objects, see \
1572 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1573 #using-trait-objects-that-allow-for-values-of-different-types>";
1575 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1576 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1577 if only_never_return {
1578 // No return paths, probably using `panic!()` or similar.
1579 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1580 suggest_trait_object_return_type_alternatives(
1586 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1587 // Suggest `-> impl Trait`.
1588 err.span_suggestion(
1591 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1592 which implements `{1}`",
1595 format!("impl {}", trait_obj),
1596 Applicability::MachineApplicable,
1598 err.note(impl_trait_msg);
1601 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1602 err.multipart_suggestion(
1603 "return a boxed trait object instead",
1605 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1606 (span.shrink_to_hi(), ">".to_string()),
1608 Applicability::MaybeIncorrect,
1610 for (span, needs_box) in spans_and_needs_box {
1612 err.multipart_suggestion(
1613 "... and box this value",
1615 (span.shrink_to_lo(), "Box::new(".to_string()),
1616 (span.shrink_to_hi(), ")".to_string()),
1618 Applicability::MaybeIncorrect,
1623 // This is currently not possible to trigger because E0038 takes precedence, but
1624 // leave it in for completeness in case anything changes in an earlier stage.
1626 "if trait `{}` were object-safe, you could return a trait object",
1630 err.note(trait_obj_msg);
1632 "if all the returned values were of the same type you could use `impl {}` as the \
1636 err.note(impl_trait_msg);
1637 err.note("you can create a new `enum` with a variant for each returned type");
1642 fn point_at_returns_when_relevant(
1644 err: &mut Diagnostic,
1645 obligation: &PredicateObligation<'tcx>,
1647 match obligation.cause.code().peel_derives() {
1648 ObligationCauseCode::SizedReturnType => {}
1652 let hir = self.tcx.hir();
1653 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1654 let node = hir.find(parent_node);
1655 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1658 let body = hir.body(*body_id);
1659 // Point at all the `return`s in the function as they have failed trait bounds.
1660 let mut visitor = ReturnsVisitor::default();
1661 visitor.visit_body(&body);
1662 let typeck_results = self.typeck_results.as_ref().unwrap();
1663 for expr in &visitor.returns {
1664 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1665 let ty = self.resolve_vars_if_possible(returned_ty);
1666 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1672 fn report_closure_arg_mismatch(
1675 found_span: Option<Span>,
1676 found: ty::PolyTraitRef<'tcx>,
1677 expected: ty::PolyTraitRef<'tcx>,
1678 cause: &ObligationCauseCode<'tcx>,
1679 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1680 pub(crate) fn build_fn_sig_ty<'tcx>(
1681 infcx: &InferCtxt<'tcx>,
1682 trait_ref: ty::PolyTraitRef<'tcx>,
1684 let inputs = trait_ref.skip_binder().substs.type_at(1);
1685 let sig = match inputs.kind() {
1687 if infcx.tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1689 infcx.tcx.mk_fn_sig(
1691 infcx.next_ty_var(TypeVariableOrigin {
1693 kind: TypeVariableOriginKind::MiscVariable,
1696 hir::Unsafety::Normal,
1700 _ => infcx.tcx.mk_fn_sig(
1701 std::iter::once(inputs),
1702 infcx.next_ty_var(TypeVariableOrigin {
1704 kind: TypeVariableOriginKind::MiscVariable,
1707 hir::Unsafety::Normal,
1712 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1715 let argument_kind = match expected.skip_binder().self_ty().kind() {
1716 ty::Closure(..) => "closure",
1717 ty::Generator(..) => "generator",
1720 let mut err = struct_span_err!(
1724 "type mismatch in {argument_kind} arguments",
1727 err.span_label(span, "expected due to this");
1729 let found_span = found_span.unwrap_or(span);
1730 err.span_label(found_span, "found signature defined here");
1732 let expected = build_fn_sig_ty(self, expected);
1733 let found = build_fn_sig_ty(self, found);
1735 let (expected_str, found_str) = self.cmp(expected, found);
1737 let signature_kind = format!("{argument_kind} signature");
1738 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1740 self.note_conflicting_closure_bounds(cause, &mut err);
1745 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1746 // requirements, which will always cause a closure to have a type error.
1747 fn note_conflicting_closure_bounds(
1749 cause: &ObligationCauseCode<'tcx>,
1750 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1752 // First, look for an `ExprBindingObligation`, which means we can get
1753 // the unsubstituted predicate list of the called function. And check
1754 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1755 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1756 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1757 && let Some(pred) = predicates.predicates.get(*idx)
1758 && let ty::PredicateKind::Trait(trait_pred) = pred.kind().skip_binder()
1759 && ty::ClosureKind::from_def_id(self.tcx, trait_pred.def_id()).is_some()
1762 self.tcx.anonymize_late_bound_regions(pred.kind().rebind(trait_pred.self_ty()));
1763 let expected_substs = self
1765 .anonymize_late_bound_regions(pred.kind().rebind(trait_pred.trait_ref.substs));
1767 // Find another predicate whose self-type is equal to the expected self type,
1768 // but whose substs don't match.
1769 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1771 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1772 ty::PredicateKind::Trait(trait_pred)
1773 if ty::ClosureKind::from_def_id(self.tcx, trait_pred.def_id())
1776 // Make sure that the self type matches
1777 // (i.e. constraining this closure)
1779 == self.tcx.anonymize_late_bound_regions(
1780 pred.kind().rebind(trait_pred.self_ty()),
1782 // But the substs don't match (i.e. incompatible args)
1784 != self.tcx.anonymize_late_bound_regions(
1785 pred.kind().rebind(trait_pred.trait_ref.substs),
1792 // If we found one, then it's very likely the cause of the error.
1793 if let Some((_, (_, other_pred_span))) = other_pred {
1796 "closure inferred to have a different signature due to this bound",
1802 fn suggest_fully_qualified_path(
1804 err: &mut Diagnostic,
1809 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1810 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1812 "{}s cannot be accessed directly on a `trait`, they can only be \
1813 accessed through a specific `impl`",
1814 assoc_item.kind.as_def_kind().descr(item_def_id)
1816 err.span_suggestion(
1818 "use the fully qualified path to an implementation",
1819 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1820 Applicability::HasPlaceholders,
1826 /// Adds an async-await specific note to the diagnostic when the future does not implement
1827 /// an auto trait because of a captured type.
1830 /// note: future does not implement `Qux` as this value is used across an await
1831 /// --> $DIR/issue-64130-3-other.rs:17:5
1833 /// LL | let x = Foo;
1834 /// | - has type `Foo`
1835 /// LL | baz().await;
1836 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1838 /// | - `x` is later dropped here
1841 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1842 /// is "replaced" with a different message and a more specific error.
1845 /// error: future cannot be sent between threads safely
1846 /// --> $DIR/issue-64130-2-send.rs:21:5
1848 /// LL | fn is_send<T: Send>(t: T) { }
1849 /// | ---- required by this bound in `is_send`
1851 /// LL | is_send(bar());
1852 /// | ^^^^^^^ future returned by `bar` is not send
1854 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1855 /// implemented for `Foo`
1856 /// note: future is not send as this value is used across an await
1857 /// --> $DIR/issue-64130-2-send.rs:15:5
1859 /// LL | let x = Foo;
1860 /// | - has type `Foo`
1861 /// LL | baz().await;
1862 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1864 /// | - `x` is later dropped here
1867 /// Returns `true` if an async-await specific note was added to the diagnostic.
1868 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1869 fn maybe_note_obligation_cause_for_async_await(
1871 err: &mut Diagnostic,
1872 obligation: &PredicateObligation<'tcx>,
1874 let hir = self.tcx.hir();
1876 // Attempt to detect an async-await error by looking at the obligation causes, looking
1877 // for a generator to be present.
1879 // When a future does not implement a trait because of a captured type in one of the
1880 // generators somewhere in the call stack, then the result is a chain of obligations.
1882 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1883 // future is passed as an argument to a function C which requires a `Send` type, then the
1884 // chain looks something like this:
1886 // - `BuiltinDerivedObligation` with a generator witness (B)
1887 // - `BuiltinDerivedObligation` with a generator (B)
1888 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1889 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1890 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1891 // - `BuiltinDerivedObligation` with a generator witness (A)
1892 // - `BuiltinDerivedObligation` with a generator (A)
1893 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1894 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1895 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1896 // - `BindingObligation` with `impl_send (Send requirement)
1898 // The first obligation in the chain is the most useful and has the generator that captured
1899 // the type. The last generator (`outer_generator` below) has information about where the
1900 // bound was introduced. At least one generator should be present for this diagnostic to be
1902 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1903 ty::PredicateKind::Trait(p) => (Some(p), Some(p.self_ty())),
1906 let mut generator = None;
1907 let mut outer_generator = None;
1908 let mut next_code = Some(obligation.cause.code());
1910 let mut seen_upvar_tys_infer_tuple = false;
1912 while let Some(code) = next_code {
1915 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1916 next_code = Some(parent_code);
1918 ObligationCauseCode::ImplDerivedObligation(cause) => {
1919 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1921 parent_trait_ref = ?cause.derived.parent_trait_pred,
1922 self_ty.kind = ?ty.kind(),
1927 ty::Generator(did, ..) => {
1928 generator = generator.or(Some(did));
1929 outer_generator = Some(did);
1931 ty::GeneratorWitness(..) => {}
1932 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1933 // By introducing a tuple of upvar types into the chain of obligations
1934 // of a generator, the first non-generator item is now the tuple itself,
1935 // we shall ignore this.
1937 seen_upvar_tys_infer_tuple = true;
1939 _ if generator.is_none() => {
1940 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1941 target_ty = Some(ty);
1946 next_code = Some(&cause.derived.parent_code);
1948 ObligationCauseCode::DerivedObligation(derived_obligation)
1949 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1950 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1952 parent_trait_ref = ?derived_obligation.parent_trait_pred,
1953 self_ty.kind = ?ty.kind(),
1957 ty::Generator(did, ..) => {
1958 generator = generator.or(Some(did));
1959 outer_generator = Some(did);
1961 ty::GeneratorWitness(..) => {}
1962 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1963 // By introducing a tuple of upvar types into the chain of obligations
1964 // of a generator, the first non-generator item is now the tuple itself,
1965 // we shall ignore this.
1967 seen_upvar_tys_infer_tuple = true;
1969 _ if generator.is_none() => {
1970 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1971 target_ty = Some(ty);
1976 next_code = Some(&derived_obligation.parent_code);
1982 // Only continue if a generator was found.
1983 debug!(?generator, ?trait_ref, ?target_ty);
1984 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1988 let span = self.tcx.def_span(generator_did);
1990 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1993 ?generator_did_root,
1994 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
1998 let generator_body = generator_did
2000 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2001 .map(|body_id| hir.body(body_id));
2004 .generator_kind(generator_did)
2005 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
2007 let mut visitor = AwaitsVisitor::default();
2008 if let Some(body) = generator_body {
2009 visitor.visit_body(body);
2011 debug!(awaits = ?visitor.awaits);
2013 // Look for a type inside the generator interior that matches the target type to get
2015 let target_ty_erased = self.tcx.erase_regions(target_ty);
2016 let ty_matches = |ty| -> bool {
2017 // Careful: the regions for types that appear in the
2018 // generator interior are not generally known, so we
2019 // want to erase them when comparing (and anyway,
2020 // `Send` and other bounds are generally unaffected by
2021 // the choice of region). When erasing regions, we
2022 // also have to erase late-bound regions. This is
2023 // because the types that appear in the generator
2024 // interior generally contain "bound regions" to
2025 // represent regions that are part of the suspended
2026 // generator frame. Bound regions are preserved by
2027 // `erase_regions` and so we must also call
2028 // `erase_late_bound_regions`.
2029 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2030 let ty_erased = self.tcx.erase_regions(ty_erased);
2031 let eq = ty_erased == target_ty_erased;
2032 debug!(?ty_erased, ?target_ty_erased, ?eq);
2036 // Get the typeck results from the infcx if the generator is the function we are currently
2037 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2038 // cycles. If we can't use resolved types because the generator comes from another crate,
2039 // we still provide a targeted error but without all the relevant spans.
2040 let generator_data = match &self.typeck_results {
2041 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2042 _ if generator_did.is_local() => {
2043 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2045 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2046 GeneratorData::Foreign(generator_diag_data)
2051 let mut interior_or_upvar_span = None;
2053 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2054 debug!(?from_awaited_ty);
2056 // The generator interior types share the same binders
2057 if let Some(cause) =
2058 generator_data.get_generator_interior_types().skip_binder().iter().find(
2059 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2060 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2064 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2066 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2068 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2072 if interior_or_upvar_span.is_none() {
2073 interior_or_upvar_span =
2074 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2077 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2078 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2081 debug!(?interior_or_upvar_span);
2082 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2083 let typeck_results = match generator_data {
2084 GeneratorData::Local(typeck_results) => Some(typeck_results),
2085 GeneratorData::Foreign(_) => None,
2087 self.note_obligation_cause_for_async_await(
2089 interior_or_upvar_span,
2104 /// Unconditionally adds the diagnostic note described in
2105 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2106 #[instrument(level = "debug", skip_all)]
2107 fn note_obligation_cause_for_async_await(
2109 err: &mut Diagnostic,
2110 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2112 outer_generator: Option<DefId>,
2113 trait_pred: ty::TraitPredicate<'tcx>,
2114 target_ty: Ty<'tcx>,
2115 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2116 obligation: &PredicateObligation<'tcx>,
2117 next_code: Option<&ObligationCauseCode<'tcx>>,
2119 let source_map = self.tcx.sess.source_map();
2121 let (await_or_yield, an_await_or_yield) =
2122 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2123 let future_or_generator = if is_async { "future" } else { "generator" };
2125 // Special case the primary error message when send or sync is the trait that was
2127 let hir = self.tcx.hir();
2128 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2129 self.tcx.get_diagnostic_name(trait_pred.def_id())
2131 let (trait_name, trait_verb) =
2132 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2135 err.set_primary_message(format!(
2136 "{} cannot be {} between threads safely",
2137 future_or_generator, trait_verb
2140 let original_span = err.span.primary_span().unwrap();
2141 let mut span = MultiSpan::from_span(original_span);
2143 let message = outer_generator
2144 .and_then(|generator_did| {
2145 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2146 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2147 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2149 .parent(generator_did)
2151 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2152 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2154 format!("future returned by `{}` is not {}", name, trait_name)
2156 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2157 format!("future created by async block is not {}", trait_name)
2159 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2160 format!("future created by async closure is not {}", trait_name)
2164 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2166 span.push_span_label(original_span, message);
2169 format!("is not {}", trait_name)
2171 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2174 let mut explain_yield = |interior_span: Span,
2176 scope_span: Option<Span>| {
2177 let mut span = MultiSpan::from_span(yield_span);
2178 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
2179 // #70935: If snippet contains newlines, display "the value" instead
2180 // so that we do not emit complex diagnostics.
2181 let snippet = &format!("`{}`", snippet);
2182 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
2183 // note: future is not `Send` as this value is used across an await
2184 // --> $DIR/issue-70935-complex-spans.rs:13:9
2186 // LL | baz(|| async {
2187 // | ______________-
2190 // LL | | foo(tx.clone());
2192 // | | - ^^^^^^ await occurs here, with value maybe used later
2194 // | has type `closure` which is not `Send`
2195 // note: value is later dropped here
2199 span.push_span_label(
2201 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2203 span.push_span_label(
2205 format!("has type `{}` which {}", target_ty, trait_explanation),
2207 // If available, use the scope span to annotate the drop location.
2208 let mut scope_note = None;
2209 if let Some(scope_span) = scope_span {
2210 let scope_span = source_map.end_point(scope_span);
2212 let msg = format!("{} is later dropped here", snippet);
2213 if source_map.is_multiline(yield_span.between(scope_span)) {
2214 span.push_span_label(scope_span, msg);
2216 scope_note = Some((scope_span, msg));
2222 "{} {} as this value is used across {}",
2223 future_or_generator, trait_explanation, an_await_or_yield
2226 if let Some((span, msg)) = scope_note {
2227 err.span_note(span, &msg);
2231 match interior_or_upvar_span {
2232 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2233 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2234 if let Some(await_span) = from_awaited_ty {
2235 // The type causing this obligation is one being awaited at await_span.
2236 let mut span = MultiSpan::from_span(await_span);
2237 span.push_span_label(
2240 "await occurs here on type `{}`, which {}",
2241 target_ty, trait_explanation
2247 "future {not_trait} as it awaits another future which {not_trait}",
2248 not_trait = trait_explanation
2252 // Look at the last interior type to get a span for the `.await`.
2254 generator_interior_types = ?format_args!(
2255 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2258 explain_yield(interior_span, yield_span, scope_span);
2261 if let Some(expr_id) = expr {
2262 let expr = hir.expect_expr(expr_id);
2263 debug!("target_ty evaluated from {:?}", expr);
2265 let parent = hir.get_parent_node(expr_id);
2266 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2267 let parent_span = hir.span(parent);
2268 let parent_did = parent.owner.to_def_id();
2271 // fn foo(&self) -> i32 {}
2274 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2277 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2279 .expr_adjustments(expr)
2281 .any(|adj| adj.is_region_borrow())
2287 // struct Foo(*const u8);
2288 // bar(Foo(std::ptr::null())).await;
2289 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2291 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2292 let is_raw_borrow_inside_fn_like_call =
2293 match self.tcx.def_kind(parent_did) {
2294 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2297 if let Some(typeck_results) = typeck_results {
2298 if (typeck_results.is_method_call(e) && is_region_borrow)
2299 || is_raw_borrow_inside_fn_like_call
2303 "consider moving this into a `let` \
2304 binding to create a shorter lived borrow",
2312 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2313 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2314 let refers_to_non_sync = match target_ty.kind() {
2315 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2316 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2322 let (span_label, span_note) = match refers_to_non_sync {
2323 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2324 // include suggestions to make `T: Sync` so that `&T: Send`
2327 "has type `{}` which {}, because `{}` is not `Sync`",
2328 target_ty, trait_explanation, ref_ty
2331 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2336 format!("has type `{}` which {}", target_ty, trait_explanation),
2337 format!("captured value {}", trait_explanation),
2341 let mut span = MultiSpan::from_span(upvar_span);
2342 span.push_span_label(upvar_span, span_label);
2343 err.span_note(span, &span_note);
2347 // Add a note for the item obligation that remains - normally a note pointing to the
2348 // bound that introduced the obligation (e.g. `T: Send`).
2350 self.note_obligation_cause_code(
2352 &obligation.predicate,
2353 obligation.param_env,
2356 &mut Default::default(),
2360 fn note_obligation_cause_code<T>(
2362 err: &mut Diagnostic,
2364 param_env: ty::ParamEnv<'tcx>,
2365 cause_code: &ObligationCauseCode<'tcx>,
2366 obligated_types: &mut Vec<Ty<'tcx>>,
2367 seen_requirements: &mut FxHashSet<DefId>,
2373 ObligationCauseCode::ExprAssignable
2374 | ObligationCauseCode::MatchExpressionArm { .. }
2375 | ObligationCauseCode::Pattern { .. }
2376 | ObligationCauseCode::IfExpression { .. }
2377 | ObligationCauseCode::IfExpressionWithNoElse
2378 | ObligationCauseCode::MainFunctionType
2379 | ObligationCauseCode::StartFunctionType
2380 | ObligationCauseCode::IntrinsicType
2381 | ObligationCauseCode::MethodReceiver
2382 | ObligationCauseCode::ReturnNoExpression
2383 | ObligationCauseCode::UnifyReceiver(..)
2384 | ObligationCauseCode::OpaqueType
2385 | ObligationCauseCode::MiscObligation
2386 | ObligationCauseCode::WellFormed(..)
2387 | ObligationCauseCode::MatchImpl(..)
2388 | ObligationCauseCode::ReturnType
2389 | ObligationCauseCode::ReturnValue(_)
2390 | ObligationCauseCode::BlockTailExpression(_)
2391 | ObligationCauseCode::AwaitableExpr(_)
2392 | ObligationCauseCode::ForLoopIterator
2393 | ObligationCauseCode::QuestionMark
2394 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2395 | ObligationCauseCode::LetElse
2396 | ObligationCauseCode::BinOp { .. }
2397 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2398 | ObligationCauseCode::RustCall => {}
2399 ObligationCauseCode::SliceOrArrayElem => {
2400 err.note("slice and array elements must have `Sized` type");
2402 ObligationCauseCode::TupleElem => {
2403 err.note("only the last element of a tuple may have a dynamically sized type");
2405 ObligationCauseCode::ProjectionWf(data) => {
2406 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2408 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2410 "required so that reference `{}` does not outlive its referent",
2414 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2416 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2420 ObligationCauseCode::ItemObligation(_)
2421 | ObligationCauseCode::ExprItemObligation(..) => {
2422 // We hold the `DefId` of the item introducing the obligation, but displaying it
2423 // doesn't add user usable information. It always point at an associated item.
2425 ObligationCauseCode::BindingObligation(item_def_id, span)
2426 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2427 let item_name = tcx.def_path_str(item_def_id);
2428 let mut multispan = MultiSpan::from(span);
2429 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2430 let sm = tcx.sess.source_map();
2432 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2433 (Ok(l), Ok(r)) => l.line == r.line,
2436 if !ident.span.is_dummy() && !ident.span.overlaps(span) && !same_line {
2437 multispan.push_span_label(ident.span, "required by a bound in this");
2440 let descr = format!("required by a bound in `{}`", item_name);
2441 if !span.is_dummy() {
2442 let msg = format!("required by this bound in `{}`", item_name);
2443 multispan.push_span_label(span, msg);
2444 err.span_note(multispan, &descr);
2446 err.span_note(tcx.def_span(item_def_id), &descr);
2449 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2451 "required for the cast from `{}` to the object type `{}`",
2452 self.ty_to_string(concrete_ty),
2453 self.ty_to_string(object_ty)
2456 ObligationCauseCode::Coercion { source: _, target } => {
2457 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2459 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2461 "the `Copy` trait is required because this value will be copied for each element of the array",
2466 "consider creating a new `const` item and initializing it with the result \
2467 of the function call to be used in the repeat position, like \
2468 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2472 if self.tcx.sess.is_nightly_build() && is_const_fn {
2474 "create an inline `const` block, see RFC #2920 \
2475 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2479 ObligationCauseCode::VariableType(hir_id) => {
2480 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2481 match self.tcx.hir().find(parent_node) {
2482 Some(Node::Local(hir::Local {
2483 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2486 // When encountering an assignment of an unsized trait, like
2487 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2488 // order to use have a slice instead.
2489 err.span_suggestion_verbose(
2490 span.shrink_to_lo(),
2491 "consider borrowing here",
2493 Applicability::MachineApplicable,
2495 err.note("all local variables must have a statically known size");
2497 Some(Node::Param(param)) => {
2498 err.span_suggestion_verbose(
2499 param.ty_span.shrink_to_lo(),
2500 "function arguments must have a statically known size, borrowed types \
2501 always have a known size",
2503 Applicability::MachineApplicable,
2507 err.note("all local variables must have a statically known size");
2510 if !self.tcx.features().unsized_locals {
2511 err.help("unsized locals are gated as an unstable feature");
2514 ObligationCauseCode::SizedArgumentType(sp) => {
2515 if let Some(span) = sp {
2516 err.span_suggestion_verbose(
2517 span.shrink_to_lo(),
2518 "function arguments must have a statically known size, borrowed types \
2519 always have a known size",
2521 Applicability::MachineApplicable,
2524 err.note("all function arguments must have a statically known size");
2526 if tcx.sess.opts.unstable_features.is_nightly_build()
2527 && !self.tcx.features().unsized_fn_params
2529 err.help("unsized fn params are gated as an unstable feature");
2532 ObligationCauseCode::SizedReturnType => {
2533 err.note("the return type of a function must have a statically known size");
2535 ObligationCauseCode::SizedYieldType => {
2536 err.note("the yield type of a generator must have a statically known size");
2538 ObligationCauseCode::SizedBoxType => {
2539 err.note("the type of a box expression must have a statically known size");
2541 ObligationCauseCode::AssignmentLhsSized => {
2542 err.note("the left-hand-side of an assignment must have a statically known size");
2544 ObligationCauseCode::TupleInitializerSized => {
2545 err.note("tuples must have a statically known size to be initialized");
2547 ObligationCauseCode::StructInitializerSized => {
2548 err.note("structs must have a statically known size to be initialized");
2550 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2552 AdtKind::Struct => {
2555 "the last field of a packed struct may only have a \
2556 dynamically sized type if it does not need drop to be run",
2560 "only the last field of a struct may have a dynamically sized type",
2565 err.note("no field of a union may have a dynamically sized type");
2568 err.note("no field of an enum variant may have a dynamically sized type");
2571 err.help("change the field's type to have a statically known size");
2572 err.span_suggestion(
2573 span.shrink_to_lo(),
2574 "borrowed types always have a statically known size",
2576 Applicability::MachineApplicable,
2578 err.multipart_suggestion(
2579 "the `Box` type always has a statically known size and allocates its contents \
2582 (span.shrink_to_lo(), "Box<".to_string()),
2583 (span.shrink_to_hi(), ">".to_string()),
2585 Applicability::MachineApplicable,
2588 ObligationCauseCode::ConstSized => {
2589 err.note("constant expressions must have a statically known size");
2591 ObligationCauseCode::InlineAsmSized => {
2592 err.note("all inline asm arguments must have a statically known size");
2594 ObligationCauseCode::ConstPatternStructural => {
2595 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2597 ObligationCauseCode::SharedStatic => {
2598 err.note("shared static variables must have a type that implements `Sync`");
2600 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2601 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2602 let ty = parent_trait_ref.skip_binder().self_ty();
2603 if parent_trait_ref.references_error() {
2604 // NOTE(eddyb) this was `.cancel()`, but `err`
2605 // is borrowed, so we can't fully defuse it.
2606 err.downgrade_to_delayed_bug();
2610 // If the obligation for a tuple is set directly by a Generator or Closure,
2611 // then the tuple must be the one containing capture types.
2612 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2615 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2617 let parent_trait_ref =
2618 self.resolve_vars_if_possible(data.parent_trait_pred);
2619 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2620 matches!(nested_ty.kind(), ty::Generator(..))
2621 || matches!(nested_ty.kind(), ty::Closure(..))
2627 let from_generator = tcx.require_lang_item(LangItem::FromGenerator, None);
2629 // Don't print the tuple of capture types
2631 if !is_upvar_tys_infer_tuple {
2632 let msg = format!("required because it appears within the type `{}`", ty);
2634 ty::Adt(def, _) => {
2635 // `gen_future` is used in all async functions; it doesn't add any additional info.
2636 if self.tcx.is_diagnostic_item(sym::gen_future, def.did()) {
2639 match self.tcx.opt_item_ident(def.did()) {
2640 Some(ident) => err.span_note(ident.span, &msg),
2641 None => err.note(&msg),
2644 ty::Opaque(def_id, _) => {
2645 // Avoid printing the future from `core::future::from_generator`, it's not helpful
2646 if tcx.parent(*def_id) == from_generator {
2650 // If the previous type is `from_generator`, this is the future generated by the body of an async function.
2651 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2652 let is_future = tcx.ty_is_opaque_future(ty);
2656 "note_obligation_cause_code: check for async fn"
2659 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2660 ty::Opaque(last_def_id, _) => {
2661 tcx.parent(*last_def_id) == from_generator
2668 err.span_note(self.tcx.def_span(def_id), &msg)
2670 ty::GeneratorWitness(bound_tys) => {
2671 use std::fmt::Write;
2673 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2674 // Maybe we should just remove this note altogether?
2675 // FIXME: only print types which don't meet the trait requirement
2677 "required because it captures the following types: ".to_owned();
2678 for ty in bound_tys.skip_binder() {
2679 write!(msg, "`{}`, ", ty).unwrap();
2681 err.note(msg.trim_end_matches(", "))
2683 ty::Generator(def_id, _, _) => {
2684 let sp = self.tcx.def_span(def_id);
2686 // Special-case this to say "async block" instead of `[static generator]`.
2687 let kind = tcx.generator_kind(def_id).unwrap();
2690 &format!("required because it's used within this {}", kind),
2693 ty::Closure(def_id, _) => err.span_note(
2694 self.tcx.def_span(def_id),
2695 &format!("required because it's used within this closure"),
2697 _ => err.note(&msg),
2702 obligated_types.push(ty);
2704 let parent_predicate = parent_trait_ref;
2705 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2706 // #74711: avoid a stack overflow
2707 ensure_sufficient_stack(|| {
2708 self.note_obligation_cause_code(
2718 ensure_sufficient_stack(|| {
2719 self.note_obligation_cause_code(
2723 cause_code.peel_derives(),
2730 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2731 let mut parent_trait_pred =
2732 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2733 parent_trait_pred.remap_constness_diag(param_env);
2734 let parent_def_id = parent_trait_pred.def_id();
2735 let (self_ty, file) =
2736 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2738 "required for `{self_ty}` to implement `{}`",
2739 parent_trait_pred.print_modifiers_and_trait_path()
2741 let mut is_auto_trait = false;
2742 match self.tcx.hir().get_if_local(data.impl_def_id) {
2743 Some(Node::Item(hir::Item {
2744 kind: hir::ItemKind::Trait(is_auto, ..),
2748 // FIXME: we should do something else so that it works even on crate foreign
2750 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2751 err.span_note(ident.span, &msg)
2753 Some(Node::Item(hir::Item {
2754 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2757 let mut spans = Vec::with_capacity(2);
2758 if let Some(trait_ref) = of_trait {
2759 spans.push(trait_ref.path.span);
2761 spans.push(self_ty.span);
2762 err.span_note(spans, &msg)
2764 _ => err.note(&msg),
2767 if let Some(file) = file {
2769 "the full type name has been written to '{}'",
2773 let mut parent_predicate = parent_trait_pred;
2774 let mut data = &data.derived;
2776 seen_requirements.insert(parent_def_id);
2778 // We don't want to point at the ADT saying "required because it appears within
2779 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2780 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2783 let child_trait_ref =
2784 self.resolve_vars_if_possible(derived.parent_trait_pred);
2785 let child_def_id = child_trait_ref.def_id();
2786 if seen_requirements.insert(child_def_id) {
2790 parent_predicate = child_trait_ref.to_predicate(tcx);
2791 parent_trait_pred = child_trait_ref;
2794 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2795 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2796 let child_trait_pred =
2797 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2798 let child_def_id = child_trait_pred.def_id();
2799 if seen_requirements.insert(child_def_id) {
2803 data = &child.derived;
2804 parent_predicate = child_trait_pred.to_predicate(tcx);
2805 parent_trait_pred = child_trait_pred;
2809 "{} redundant requirement{} hidden",
2813 let (self_ty, file) =
2814 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2816 "required for `{self_ty}` to implement `{}`",
2817 parent_trait_pred.print_modifiers_and_trait_path()
2819 if let Some(file) = file {
2821 "the full type name has been written to '{}'",
2826 // #74711: avoid a stack overflow
2827 ensure_sufficient_stack(|| {
2828 self.note_obligation_cause_code(
2838 ObligationCauseCode::DerivedObligation(ref data) => {
2839 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2840 let parent_predicate = parent_trait_ref;
2841 // #74711: avoid a stack overflow
2842 ensure_sufficient_stack(|| {
2843 self.note_obligation_cause_code(
2853 ObligationCauseCode::FunctionArgumentObligation {
2858 let hir = self.tcx.hir();
2859 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2860 hir.find(arg_hir_id)
2862 let parent_id = hir.get_parent_item(arg_hir_id);
2863 let typeck_results: &TypeckResults<'tcx> = match &self.typeck_results {
2864 Some(t) if t.hir_owner == parent_id => t,
2865 _ => self.tcx.typeck(parent_id.def_id),
2867 let expr = expr.peel_blocks();
2868 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
2869 let span = expr.span;
2870 if Some(span) != err.span.primary_span() {
2873 if ty.references_error() {
2876 format!("this tail expression is of type `{:?}`", ty)
2881 if let Some(Node::Expr(hir::Expr {
2883 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2884 | hir::ExprKind::MethodCall(
2885 hir::PathSegment { ident: Ident { span, .. }, .. },
2889 })) = hir.find(call_hir_id)
2891 if Some(*span) != err.span.primary_span() {
2892 err.span_label(*span, "required by a bound introduced by this call");
2895 ensure_sufficient_stack(|| {
2896 self.note_obligation_cause_code(
2906 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2907 let item_name = self.tcx.item_name(trait_item_def_id);
2909 "the requirement `{}` appears on the `impl`'s {kind} `{}` but not on the \
2910 corresponding trait's {kind}",
2911 predicate, item_name,
2915 .opt_item_ident(trait_item_def_id)
2917 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2918 let mut assoc_span: MultiSpan = sp.into();
2919 assoc_span.push_span_label(
2921 format!("this trait's {kind} doesn't have the requirement `{}`", predicate),
2923 if let Some(ident) = self
2925 .opt_associated_item(trait_item_def_id)
2926 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2928 assoc_span.push_span_label(ident.span, "in this trait");
2930 err.span_note(assoc_span, &msg);
2932 ObligationCauseCode::TrivialBound => {
2933 err.help("see issue #48214");
2934 if tcx.sess.opts.unstable_features.is_nightly_build() {
2935 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2938 ObligationCauseCode::OpaqueReturnType(expr_info) => {
2939 if let Some((expr_ty, expr_span)) = expr_info {
2940 let expr_ty = self.resolve_vars_if_possible(expr_ty);
2943 format!("return type was inferred to be `{expr_ty}` here"),
2951 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2953 fn suggest_await_before_try(
2955 err: &mut Diagnostic,
2956 obligation: &PredicateObligation<'tcx>,
2957 trait_pred: ty::PolyTraitPredicate<'tcx>,
2960 let body_hir_id = obligation.cause.body_id;
2961 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2963 if let Some(body_id) =
2964 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2966 let body = self.tcx.hir().body(body_id);
2967 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2968 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2970 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2971 let impls_future = self.type_implements_trait(
2973 [self.tcx.erase_late_bound_regions(self_ty)],
2974 obligation.param_env,
2976 if !impls_future.must_apply_modulo_regions() {
2980 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2981 // `<T as Future>::Output`
2982 let projection_ty = trait_pred.map_bound(|trait_pred| {
2983 self.tcx.mk_projection(
2985 // Future::Output has no substs
2986 self.tcx.mk_substs_trait(trait_pred.self_ty(), []),
2989 let projection_ty = normalize_to(
2990 &mut SelectionContext::new(self),
2991 obligation.param_env,
2992 obligation.cause.clone(),
2998 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3000 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3001 obligation.param_env,
3002 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3004 debug!(try_trait_obligation = ?try_obligation);
3005 if self.predicate_may_hold(&try_obligation)
3006 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3007 && snippet.ends_with('?')
3009 err.span_suggestion_verbose(
3010 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3011 "consider `await`ing on the `Future`",
3013 Applicability::MaybeIncorrect,
3020 fn suggest_floating_point_literal(
3022 obligation: &PredicateObligation<'tcx>,
3023 err: &mut Diagnostic,
3024 trait_ref: &ty::PolyTraitRef<'tcx>,
3026 let rhs_span = match obligation.cause.code() {
3027 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3030 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3031 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3033 err.span_suggestion_verbose(
3034 rhs_span.shrink_to_hi(),
3035 "consider using a floating-point literal by writing it with `.0`",
3037 Applicability::MaybeIncorrect,
3044 obligation: &PredicateObligation<'tcx>,
3045 err: &mut Diagnostic,
3046 trait_pred: ty::PolyTraitPredicate<'tcx>,
3048 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3051 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3052 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3056 let is_derivable_trait = match diagnostic_name {
3057 sym::Default => !adt.is_enum(),
3058 sym::PartialEq | sym::PartialOrd => {
3059 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3060 trait_pred.skip_binder().self_ty() == rhs_ty
3062 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3065 is_derivable_trait &&
3066 // Ensure all fields impl the trait.
3067 adt.all_fields().all(|field| {
3068 let field_ty = field.ty(self.tcx, substs);
3069 let trait_substs = match diagnostic_name {
3070 sym::PartialEq | sym::PartialOrd => {
3075 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3076 trait_ref: self.tcx.mk_trait_ref(
3077 trait_pred.def_id(),
3078 [field_ty].into_iter().chain(trait_substs),
3082 let field_obl = Obligation::new(
3084 obligation.cause.clone(),
3085 obligation.param_env,
3088 self.predicate_must_hold_modulo_regions(&field_obl)
3092 err.span_suggestion_verbose(
3093 self.tcx.def_span(adt.did()).shrink_to_lo(),
3095 "consider annotating `{}` with `#[derive({})]`",
3096 trait_pred.skip_binder().self_ty(),
3099 format!("#[derive({})]\n", diagnostic_name),
3100 Applicability::MaybeIncorrect,
3105 fn suggest_dereferencing_index(
3107 obligation: &PredicateObligation<'tcx>,
3108 err: &mut Diagnostic,
3109 trait_pred: ty::PolyTraitPredicate<'tcx>,
3111 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3112 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3113 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3114 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3115 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3117 err.span_suggestion_verbose(
3118 obligation.cause.span.shrink_to_lo(),
3119 "dereference this index",
3121 Applicability::MachineApplicable,
3127 /// Collect all the returned expressions within the input expression.
3128 /// Used to point at the return spans when we want to suggest some change to them.
3130 pub struct ReturnsVisitor<'v> {
3131 pub returns: Vec<&'v hir::Expr<'v>>,
3132 in_block_tail: bool,
3135 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3136 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3137 // Visit every expression to detect `return` paths, either through the function's tail
3138 // expression or `return` statements. We walk all nodes to find `return` statements, but
3139 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3140 // they're in the return path of the function body.
3142 hir::ExprKind::Ret(Some(ex)) => {
3143 self.returns.push(ex);
3145 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3146 self.in_block_tail = false;
3147 for stmt in block.stmts {
3148 hir::intravisit::walk_stmt(self, stmt);
3150 self.in_block_tail = true;
3151 if let Some(expr) = block.expr {
3152 self.visit_expr(expr);
3155 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3156 self.visit_expr(then);
3157 if let Some(el) = else_opt {
3158 self.visit_expr(el);
3161 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3163 self.visit_expr(arm.body);
3166 // We need to walk to find `return`s in the entire body.
3167 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3168 _ => self.returns.push(ex),
3172 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3173 assert!(!self.in_block_tail);
3174 if body.generator_kind().is_none() {
3175 if let hir::ExprKind::Block(block, None) = body.value.kind {
3176 if block.expr.is_some() {
3177 self.in_block_tail = true;
3181 hir::intravisit::walk_body(self, body);
3185 /// Collect all the awaited expressions within the input expression.
3187 struct AwaitsVisitor {
3188 awaits: Vec<hir::HirId>,
3191 impl<'v> Visitor<'v> for AwaitsVisitor {
3192 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3193 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3194 self.awaits.push(id)
3196 hir::intravisit::walk_expr(self, ex)
3200 pub trait NextTypeParamName {
3201 fn next_type_param_name(&self, name: Option<&str>) -> String;
3204 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3205 fn next_type_param_name(&self, name: Option<&str>) -> String {
3206 // This is the list of possible parameter names that we might suggest.
3207 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3208 let name = name.as_deref();
3209 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3210 let used_names = self
3212 .filter_map(|p| match p.name {
3213 hir::ParamName::Plain(ident) => Some(ident.name),
3216 .collect::<Vec<_>>();
3220 .find(|n| !used_names.contains(&Symbol::intern(n)))
3221 .unwrap_or(&"ParamName")
3226 fn suggest_trait_object_return_type_alternatives(
3227 err: &mut Diagnostic,
3230 is_object_safe: bool,
3232 err.span_suggestion(
3234 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3237 Applicability::MaybeIncorrect,
3239 err.span_suggestion(
3242 "use `impl {}` as the return type if all return paths have the same type but you \
3243 want to expose only the trait in the signature",
3246 format!("impl {}", trait_obj),
3247 Applicability::MaybeIncorrect,
3250 err.multipart_suggestion(
3252 "use a boxed trait object if all return paths implement trait `{}`",
3256 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3257 (ret_ty.shrink_to_hi(), ">".to_string()),
3259 Applicability::MaybeIncorrect,
3264 /// Collect the spans that we see the generic param `param_did`
3265 struct ReplaceImplTraitVisitor<'a> {
3266 ty_spans: &'a mut Vec<Span>,
3270 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3271 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3272 if let hir::TyKind::Path(hir::QPath::Resolved(
3274 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3277 if self.param_did == *segment_did {
3278 // `fn foo(t: impl Trait)`
3279 // ^^^^^^^^^^ get this to suggest `T` instead
3281 // There might be more than one `impl Trait`.
3282 self.ty_spans.push(t.span);
3287 hir::intravisit::walk_ty(self, t);
3291 // Replace `param` with `replace_ty`
3292 struct ReplaceImplTraitFolder<'tcx> {
3294 param: &'tcx ty::GenericParamDef,
3295 replace_ty: Ty<'tcx>,
3298 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3299 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3300 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3301 if self.param.index == *index {
3302 return self.replace_ty;
3305 t.super_fold_with(self)
3308 fn tcx(&self) -> TyCtxt<'tcx> {