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>,
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: String) -> (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).to_string()),
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, .. })),
444 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx).to_string())
446 (None, Some((ident, []))) => (
447 ident.span.shrink_to_hi(),
448 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
450 (_, Some((_, [.., bounds]))) => (
451 bounds.span().shrink_to_hi(),
452 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
454 (Some(_), Some((_, []))) => (
455 hir_generics.span.shrink_to_hi(),
456 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
460 err.span_suggestion_verbose(
462 &format!("consider further restricting {}", msg),
464 Applicability::MachineApplicable,
469 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
470 fn suggest_restricting_param_bound(
472 mut err: &mut Diagnostic,
473 trait_pred: ty::PolyTraitPredicate<'tcx>,
474 associated_ty: Option<(&'static str, Ty<'tcx>)>,
477 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
479 let self_ty = trait_pred.skip_binder().self_ty();
480 let (param_ty, projection) = match self_ty.kind() {
481 ty::Param(_) => (true, None),
482 ty::Projection(projection) => (false, Some(projection)),
486 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
487 // don't suggest `T: Sized + ?Sized`.
488 let mut hir_id = body_id;
489 while let Some(node) = self.tcx.hir().find(hir_id) {
491 hir::Node::Item(hir::Item {
493 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
495 }) if self_ty == self.tcx.types.self_param => {
497 // Restricting `Self` for a single method.
507 Some((ident, bounds)),
512 hir::Node::TraitItem(hir::TraitItem {
514 kind: hir::TraitItemKind::Fn(..),
516 }) if self_ty == self.tcx.types.self_param => {
518 // Restricting `Self` for a single method.
520 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
526 hir::Node::TraitItem(hir::TraitItem {
528 kind: hir::TraitItemKind::Fn(fn_sig, ..),
531 | hir::Node::ImplItem(hir::ImplItem {
533 kind: hir::ImplItemKind::Fn(fn_sig, ..),
536 | hir::Node::Item(hir::Item {
537 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
538 }) if projection.is_some() => {
539 // Missing restriction on associated type of type parameter (unmet projection).
544 "the associated type",
553 hir::Node::Item(hir::Item {
555 hir::ItemKind::Trait(_, _, generics, ..)
556 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
558 }) if projection.is_some() => {
559 // Missing restriction on associated type of type parameter (unmet projection).
564 "the associated type",
574 hir::Node::Item(hir::Item {
576 hir::ItemKind::Struct(_, generics)
577 | hir::ItemKind::Enum(_, generics)
578 | hir::ItemKind::Union(_, generics)
579 | hir::ItemKind::Trait(_, _, generics, ..)
580 | hir::ItemKind::Impl(hir::Impl { generics, .. })
581 | hir::ItemKind::Fn(_, generics, _)
582 | hir::ItemKind::TyAlias(_, generics)
583 | hir::ItemKind::TraitAlias(generics, _)
584 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
587 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
588 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
591 // We skip the 0'th subst (self) because we do not want
592 // to consider the predicate as not suggestible if the
593 // self type is an arg position `impl Trait` -- instead,
594 // we handle that by adding ` + Bound` below.
595 // FIXME(compiler-errors): It would be nice to do the same
596 // this that we do in `suggest_restriction` and pull the
597 // `impl Trait` into a new generic if it shows up somewhere
598 // else in the predicate.
599 if !trait_pred.skip_binder().trait_ref.substs[1..]
601 .all(|g| g.is_suggestable(self.tcx, false))
605 // Missing generic type parameter bound.
606 let param_name = self_ty.to_string();
607 let mut constraint = with_no_trimmed_paths!(
608 trait_pred.print_modifiers_and_trait_path().to_string()
611 if let Some((name, term)) = associated_ty {
612 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
613 // That should be extracted into a helper function.
614 if constraint.ends_with('>') {
615 constraint = format!(
617 &constraint[..constraint.len() - 1],
622 constraint.push_str(&format!("<{} = {}>", name, term));
626 if suggest_constraining_type_param(
632 Some(trait_pred.def_id()),
638 hir::Node::Item(hir::Item {
640 hir::ItemKind::Struct(_, generics)
641 | hir::ItemKind::Enum(_, generics)
642 | hir::ItemKind::Union(_, generics)
643 | hir::ItemKind::Trait(_, _, generics, ..)
644 | hir::ItemKind::Impl(hir::Impl { generics, .. })
645 | hir::ItemKind::Fn(_, generics, _)
646 | hir::ItemKind::TyAlias(_, generics)
647 | hir::ItemKind::TraitAlias(generics, _)
648 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
651 // Missing generic type parameter bound.
652 if suggest_arbitrary_trait_bound(
662 hir::Node::Crate(..) => return,
667 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
671 /// When after several dereferencing, the reference satisfies the trait
672 /// binding. This function provides dereference suggestion for this
673 /// specific situation.
674 fn suggest_dereferences(
676 obligation: &PredicateObligation<'tcx>,
677 err: &mut Diagnostic,
678 trait_pred: ty::PolyTraitPredicate<'tcx>,
680 // It only make sense when suggesting dereferences for arguments
681 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code()
682 else { return false; };
683 let Some(typeck_results) = &self.typeck_results
684 else { return false; };
685 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
686 else { return false; };
687 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
688 else { return false; };
690 let span = obligation.cause.span;
691 let mut real_trait_pred = trait_pred;
692 let mut code = obligation.cause.code();
693 while let Some((parent_code, parent_trait_pred)) = code.parent() {
695 if let Some(parent_trait_pred) = parent_trait_pred {
696 real_trait_pred = parent_trait_pred;
699 let real_ty = real_trait_pred.self_ty();
700 // We `erase_late_bound_regions` here because `make_subregion` does not handle
701 // `ReLateBound`, and we don't particularly care about the regions.
703 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
709 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
710 let mut autoderef = Autoderef::new(
712 obligation.param_env,
713 obligation.cause.body_id,
717 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
719 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
721 // Remapping bound vars here
722 let real_trait_pred_and_ty =
723 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
724 let obligation = self.mk_trait_obligation_with_new_self_ty(
725 obligation.param_env,
726 real_trait_pred_and_ty,
728 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
731 // Don't care about `&mut` because `DerefMut` is used less
732 // often and user will not expect autoderef happens.
733 if let Some(hir::Node::Expr(hir::Expr {
735 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
737 })) = self.tcx.hir().find(*arg_hir_id)
739 let derefs = "*".repeat(steps);
740 err.span_suggestion_verbose(
741 expr.span.shrink_to_lo(),
742 "consider dereferencing here",
744 Applicability::MachineApplicable,
749 } else if real_trait_pred != trait_pred {
750 // This branch addresses #87437.
752 // Remapping bound vars here
753 let real_trait_pred_and_base_ty =
754 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
755 let obligation = self.mk_trait_obligation_with_new_self_ty(
756 obligation.param_env,
757 real_trait_pred_and_base_ty,
759 if self.predicate_may_hold(&obligation) {
760 err.span_suggestion_verbose(
762 "consider dereferencing here",
764 Applicability::MachineApplicable,
774 /// Given a closure's `DefId`, return the given name of the closure.
776 /// This doesn't account for reassignments, but it's only used for suggestions.
777 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
778 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
779 // Get the local name of this closure. This can be inaccurate because
780 // of the possibility of reassignment, but this should be good enough.
782 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
792 let hir = self.tcx.hir();
793 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
794 let parent_node = hir.get_parent_node(hir_id);
795 match hir.find(parent_node) {
796 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
797 get_name(err, &local.pat.kind)
799 // Different to previous arm because one is `&hir::Local` and the other
800 // is `P<hir::Local>`.
801 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
806 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
807 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
808 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
811 obligation: &PredicateObligation<'tcx>,
812 err: &mut Diagnostic,
813 trait_pred: ty::PolyTraitPredicate<'tcx>,
815 if let ty::PredicateKind::Trait(trait_pred) = obligation.predicate.kind().skip_binder()
816 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
818 // Don't suggest calling to turn an unsized type into a sized type
822 // This is duplicated from `extract_callable_info` in typeck, which
823 // relies on autoderef, so we can't use it here.
824 let found = trait_pred.self_ty().skip_binder().peel_refs();
825 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
827 ty::FnPtr(fn_sig) => {
828 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
830 ty::FnDef(def_id, _) => {
831 let fn_sig = found.fn_sig(self.tcx);
832 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
834 ty::Closure(def_id, substs) => {
835 let fn_sig = substs.as_closure().sig();
837 DefIdOrName::DefId(def_id),
839 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
842 ty::Opaque(def_id, substs) => {
843 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
844 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
845 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
846 // args tuple will always be substs[1]
847 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
850 DefIdOrName::DefId(def_id),
851 pred.kind().rebind(proj.term.ty().unwrap()),
852 pred.kind().rebind(args.as_slice()),
859 ty::Dynamic(data, _, ty::Dyn) => {
860 data.iter().find_map(|pred| {
861 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
862 && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
863 // for existential projection, substs are shifted over by 1
864 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
867 DefIdOrName::Name("trait object"),
868 pred.rebind(proj.term.ty().unwrap()),
869 pred.rebind(args.as_slice()),
877 obligation.param_env.caller_bounds().iter().find_map(|pred| {
878 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
879 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
880 && proj.projection_ty.self_ty() == found
881 // args tuple will always be substs[1]
882 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
885 DefIdOrName::Name("type parameter"),
886 pred.kind().rebind(proj.term.ty().unwrap()),
887 pred.kind().rebind(args.as_slice()),
895 }) else { return false; };
896 let output = self.replace_bound_vars_with_fresh_vars(
897 obligation.cause.span,
898 LateBoundRegionConversionTime::FnCall,
901 let inputs = inputs.skip_binder().iter().map(|ty| {
902 self.replace_bound_vars_with_fresh_vars(
903 obligation.cause.span,
904 LateBoundRegionConversionTime::FnCall,
909 // Remapping bound vars here
910 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
913 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
914 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
918 // Get the name of the callable and the arguments to be used in the suggestion.
919 let hir = self.tcx.hir();
921 let msg = match def_id_or_name {
922 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
923 DefKind::Ctor(CtorOf::Struct, _) => {
924 "use parentheses to construct this tuple struct".to_string()
926 DefKind::Ctor(CtorOf::Variant, _) => {
927 "use parentheses to construct this tuple variant".to_string()
929 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
931 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
936 if ty.is_suggestable(self.tcx, false) {
937 format!("/* {ty} */")
939 "/* value */".to_string()
945 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
946 && obligation.cause.span.can_be_used_for_suggestions()
948 // When the obligation error has been ensured to have been caused by
949 // an argument, the `obligation.cause.span` points at the expression
950 // of the argument, so we can provide a suggestion. Otherwise, we give
951 // a more general note.
952 err.span_suggestion_verbose(
953 obligation.cause.span.shrink_to_hi(),
956 Applicability::HasPlaceholders,
958 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
959 let name = match hir.get_if_local(def_id) {
960 Some(hir::Node::Expr(hir::Expr {
961 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
964 err.span_label(*fn_decl_span, "consider calling this closure");
965 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
970 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
971 err.span_label(ident.span, "consider calling this function");
974 Some(hir::Node::Ctor(..)) => {
975 let name = self.tcx.def_path_str(def_id);
977 self.tcx.def_span(def_id),
978 format!("consider calling the constructor for `{}`", name),
984 err.help(&format!("{msg}: `{name}({args})`"));
989 fn suggest_add_reference_to_arg(
991 obligation: &PredicateObligation<'tcx>,
992 err: &mut Diagnostic,
993 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
994 has_custom_message: bool,
996 let span = obligation.cause.span;
998 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
999 obligation.cause.code()
1002 } else if let ObligationCauseCode::ItemObligation(_)
1003 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1005 obligation.cause.code()
1006 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1007 span.ctxt().outer_expn_data().kind
1009 obligation.cause.code()
1014 // List of traits for which it would be nonsensical to suggest borrowing.
1015 // For instance, immutable references are always Copy, so suggesting to
1016 // borrow would always succeed, but it's probably not what the user wanted.
1017 let mut never_suggest_borrow: Vec<_> =
1018 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1020 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1023 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1024 never_suggest_borrow.push(def_id);
1027 let param_env = obligation.param_env;
1029 // Try to apply the original trait binding obligation by borrowing.
1030 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1031 blacklist: &[DefId]|
1033 if blacklist.contains(&old_pred.def_id()) {
1036 // We map bounds to `&T` and `&mut T`
1037 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1040 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1043 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1046 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1050 let mk_result = |trait_pred_and_new_ty| {
1052 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1053 self.predicate_must_hold_modulo_regions(&obligation)
1055 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1056 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1058 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1059 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1060 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1063 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1064 matches!(mutability, hir::Mutability::Mut),
1070 if imm_ref_self_ty_satisfies_pred
1071 || mut_ref_self_ty_satisfies_pred
1072 || ref_inner_ty_satisfies_pred
1074 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1075 // We don't want a borrowing suggestion on the fields in structs,
1078 // the_foos: Vec<Foo>
1082 span.ctxt().outer_expn_data().kind,
1083 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1087 if snippet.starts_with('&') {
1088 // This is already a literal borrow and the obligation is failing
1089 // somewhere else in the obligation chain. Do not suggest non-sense.
1092 // We have a very specific type of error, where just borrowing this argument
1093 // might solve the problem. In cases like this, the important part is the
1094 // original type obligation, not the last one that failed, which is arbitrary.
1095 // Because of this, we modify the error to refer to the original obligation and
1096 // return early in the caller.
1098 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1099 if has_custom_message {
1103 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1108 "the trait `{}` is not implemented for `{}`",
1109 old_pred.print_modifiers_and_trait_path(),
1110 old_pred.self_ty().skip_binder(),
1114 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1115 err.span_suggestions(
1116 span.shrink_to_lo(),
1117 "consider borrowing here",
1118 ["&".to_string(), "&mut ".to_string()],
1119 Applicability::MaybeIncorrect,
1122 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1123 err.span_suggestion_verbose(
1124 span.shrink_to_lo(),
1126 "consider{} borrowing here",
1127 if is_mut { " mutably" } else { "" }
1129 format!("&{}", if is_mut { "mut " } else { "" }),
1130 Applicability::MaybeIncorrect,
1139 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1140 try_borrowing(cause.derived.parent_trait_pred, &[])
1141 } else if let ObligationCauseCode::BindingObligation(_, _)
1142 | ObligationCauseCode::ItemObligation(_)
1143 | ObligationCauseCode::ExprItemObligation(..)
1144 | ObligationCauseCode::ExprBindingObligation(..) = code
1146 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1152 // Suggest borrowing the type
1153 fn suggest_borrowing_for_object_cast(
1155 err: &mut Diagnostic,
1156 obligation: &PredicateObligation<'tcx>,
1158 object_ty: Ty<'tcx>,
1160 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1161 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1163 for predicate in predicates.iter() {
1164 if !self.predicate_must_hold_modulo_regions(
1165 &obligation.with(predicate.with_self_ty(self.tcx, self_ref_ty)),
1171 err.span_suggestion(
1172 obligation.cause.span.shrink_to_lo(),
1174 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1177 Applicability::MaybeIncorrect,
1181 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1182 /// suggest removing these references until we reach a type that implements the trait.
1183 fn suggest_remove_reference(
1185 obligation: &PredicateObligation<'tcx>,
1186 err: &mut Diagnostic,
1187 trait_pred: ty::PolyTraitPredicate<'tcx>,
1189 let span = obligation.cause.span;
1191 let mut suggested = false;
1192 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1194 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1195 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1196 // Do not suggest removal of borrow from type arguments.
1200 // Skipping binder here, remapping below
1201 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1203 for refs_remaining in 0..refs_number {
1204 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1207 suggested_ty = *inner_ty;
1209 // Remapping bound vars here
1210 let trait_pred_and_suggested_ty =
1211 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1213 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1214 obligation.param_env,
1215 trait_pred_and_suggested_ty,
1218 if self.predicate_may_hold(&new_obligation) {
1223 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1225 let remove_refs = refs_remaining + 1;
1227 let msg = if remove_refs == 1 {
1228 "consider removing the leading `&`-reference".to_string()
1230 format!("consider removing {} leading `&`-references", remove_refs)
1233 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1242 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1243 let span = obligation.cause.span;
1245 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1246 let hir = self.tcx.hir();
1247 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1248 if let hir::Node::Expr(expr) = node {
1249 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1250 // and if not maybe suggest doing something else? If we kept the expression around we
1251 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1252 // it is from the local crate.
1253 err.span_suggestion(
1255 "remove the `.await`",
1257 Applicability::MachineApplicable,
1259 // FIXME: account for associated `async fn`s.
1260 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1261 if let ty::PredicateKind::Trait(pred) =
1262 obligation.predicate.kind().skip_binder()
1266 &format!("this call returns `{}`", pred.self_ty()),
1269 if let Some(typeck_results) = &self.typeck_results
1270 && let ty = typeck_results.expr_ty_adjusted(base)
1271 && let ty::FnDef(def_id, _substs) = ty.kind()
1272 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1273 hir.get_if_local(*def_id)
1276 "alternatively, consider making `fn {}` asynchronous",
1279 if vis_span.is_empty() {
1280 err.span_suggestion_verbose(
1281 span.shrink_to_lo(),
1284 Applicability::MaybeIncorrect,
1287 err.span_suggestion_verbose(
1288 vis_span.shrink_to_hi(),
1291 Applicability::MaybeIncorrect,
1301 /// Check if the trait bound is implemented for a different mutability and note it in the
1303 fn suggest_change_mut(
1305 obligation: &PredicateObligation<'tcx>,
1306 err: &mut Diagnostic,
1307 trait_pred: ty::PolyTraitPredicate<'tcx>,
1309 let points_at_arg = matches!(
1310 obligation.cause.code(),
1311 ObligationCauseCode::FunctionArgumentObligation { .. },
1314 let span = obligation.cause.span;
1315 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1317 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1318 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1319 // Do not suggest removal of borrow from type arguments.
1322 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1323 if trait_pred.has_non_region_infer() {
1324 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1325 // unresolved bindings.
1329 // Skipping binder here, remapping below
1330 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1332 let suggested_ty = match mutability {
1333 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1334 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1337 // Remapping bound vars here
1338 let trait_pred_and_suggested_ty =
1339 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1341 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1342 obligation.param_env,
1343 trait_pred_and_suggested_ty,
1345 let suggested_ty_would_satisfy_obligation = self
1346 .evaluate_obligation_no_overflow(&new_obligation)
1347 .must_apply_modulo_regions();
1348 if suggested_ty_would_satisfy_obligation {
1353 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1354 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1355 err.span_suggestion_verbose(
1357 "consider changing this borrow's mutability",
1359 Applicability::MachineApplicable,
1363 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1364 trait_pred.print_modifiers_and_trait_path(),
1366 trait_pred.skip_binder().self_ty(),
1374 fn suggest_semicolon_removal(
1376 obligation: &PredicateObligation<'tcx>,
1377 err: &mut Diagnostic,
1379 trait_pred: ty::PolyTraitPredicate<'tcx>,
1381 let hir = self.tcx.hir();
1382 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1383 let node = hir.find(parent_node);
1384 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1385 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1386 && sig.decl.output.span().overlaps(span)
1387 && blk.expr.is_none()
1388 && trait_pred.self_ty().skip_binder().is_unit()
1389 && let Some(stmt) = blk.stmts.last()
1390 && let hir::StmtKind::Semi(expr) = stmt.kind
1391 // Only suggest this if the expression behind the semicolon implements the predicate
1392 && let Some(typeck_results) = &self.typeck_results
1393 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1394 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1395 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1401 "this expression has type `{}`, which implements `{}`",
1403 trait_pred.print_modifiers_and_trait_path()
1406 err.span_suggestion(
1407 self.tcx.sess.source_map().end_point(stmt.span),
1408 "remove this semicolon",
1410 Applicability::MachineApplicable
1417 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1418 let hir = self.tcx.hir();
1419 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1420 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1424 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1427 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1428 /// applicable and signal that the error has been expanded appropriately and needs to be
1430 fn suggest_impl_trait(
1432 err: &mut Diagnostic,
1434 obligation: &PredicateObligation<'tcx>,
1435 trait_pred: ty::PolyTraitPredicate<'tcx>,
1437 match obligation.cause.code().peel_derives() {
1438 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1439 ObligationCauseCode::SizedReturnType => {}
1443 let hir = self.tcx.hir();
1444 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1445 let node = hir.find(fn_hir_id);
1446 let Some(hir::Node::Item(hir::Item {
1447 kind: hir::ItemKind::Fn(sig, _, body_id),
1453 let body = hir.body(*body_id);
1454 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1455 let ty = trait_pred.skip_binder().self_ty();
1456 let is_object_safe = match ty.kind() {
1457 ty::Dynamic(predicates, _, ty::Dyn) => {
1458 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1461 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1463 // We only want to suggest `impl Trait` to `dyn Trait`s.
1464 // For example, `fn foo() -> str` needs to be filtered out.
1468 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1472 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1473 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1474 // Recursively look for `TraitObject` types and if there's only one, use that span to
1475 // suggest `impl Trait`.
1477 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1478 // otherwise suggest using `Box<dyn Trait>` or an enum.
1479 let mut visitor = ReturnsVisitor::default();
1480 visitor.visit_body(&body);
1482 let typeck_results = self.typeck_results.as_ref().unwrap();
1483 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1485 let ret_types = visitor
1488 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1489 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1490 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1492 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1494 let ty = self.resolve_vars_if_possible(ty);
1496 !matches!(ty.kind(), ty::Error(_))
1497 && last_ty.map_or(true, |last_ty| {
1498 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1499 // *after* in the dependency graph.
1500 match (ty.kind(), last_ty.kind()) {
1501 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1502 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1503 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1505 Infer(InferTy::FreshFloatTy(_)),
1506 Infer(InferTy::FreshFloatTy(_)),
1511 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1514 let mut spans_and_needs_box = vec![];
1516 match liberated_sig.output().kind() {
1517 ty::Dynamic(predicates, _, ty::Dyn) => {
1518 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1519 let param_env = ty::ParamEnv::empty();
1521 if !only_never_return {
1522 for (expr_span, return_ty) in ret_types {
1523 let self_ty_satisfies_dyn_predicates = |self_ty| {
1524 predicates.iter().all(|predicate| {
1525 let pred = predicate.with_self_ty(self.tcx, self_ty);
1526 let obl = Obligation::new(cause.clone(), param_env, pred);
1527 self.predicate_may_hold(&obl)
1531 if let ty::Adt(def, substs) = return_ty.kind()
1533 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1535 spans_and_needs_box.push((expr_span, false));
1536 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1537 spans_and_needs_box.push((expr_span, true));
1547 let sm = self.tcx.sess.source_map();
1548 if !ret_ty.span.overlaps(span) {
1551 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1552 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1558 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1559 let name = liberated_sig.output().to_string();
1561 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1562 if !name.starts_with("dyn ") {
1568 err.code(error_code!(E0746));
1569 err.set_primary_message("return type cannot have an unboxed trait object");
1570 err.children.clear();
1571 let impl_trait_msg = "for information on `impl Trait`, see \
1572 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1573 #returning-types-that-implement-traits>";
1574 let trait_obj_msg = "for information on trait objects, see \
1575 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1576 #using-trait-objects-that-allow-for-values-of-different-types>";
1578 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1579 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1580 if only_never_return {
1581 // No return paths, probably using `panic!()` or similar.
1582 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1583 suggest_trait_object_return_type_alternatives(
1589 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1590 // Suggest `-> impl Trait`.
1591 err.span_suggestion(
1594 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1595 which implements `{1}`",
1598 format!("impl {}", trait_obj),
1599 Applicability::MachineApplicable,
1601 err.note(impl_trait_msg);
1604 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1605 err.multipart_suggestion(
1606 "return a boxed trait object instead",
1608 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1609 (span.shrink_to_hi(), ">".to_string()),
1611 Applicability::MaybeIncorrect,
1613 for (span, needs_box) in spans_and_needs_box {
1615 err.multipart_suggestion(
1616 "... and box this value",
1618 (span.shrink_to_lo(), "Box::new(".to_string()),
1619 (span.shrink_to_hi(), ")".to_string()),
1621 Applicability::MaybeIncorrect,
1626 // This is currently not possible to trigger because E0038 takes precedence, but
1627 // leave it in for completeness in case anything changes in an earlier stage.
1629 "if trait `{}` were object-safe, you could return a trait object",
1633 err.note(trait_obj_msg);
1635 "if all the returned values were of the same type you could use `impl {}` as the \
1639 err.note(impl_trait_msg);
1640 err.note("you can create a new `enum` with a variant for each returned type");
1645 fn point_at_returns_when_relevant(
1647 err: &mut Diagnostic,
1648 obligation: &PredicateObligation<'tcx>,
1650 match obligation.cause.code().peel_derives() {
1651 ObligationCauseCode::SizedReturnType => {}
1655 let hir = self.tcx.hir();
1656 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1657 let node = hir.find(parent_node);
1658 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1661 let body = hir.body(*body_id);
1662 // Point at all the `return`s in the function as they have failed trait bounds.
1663 let mut visitor = ReturnsVisitor::default();
1664 visitor.visit_body(&body);
1665 let typeck_results = self.typeck_results.as_ref().unwrap();
1666 for expr in &visitor.returns {
1667 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1668 let ty = self.resolve_vars_if_possible(returned_ty);
1669 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1675 fn report_closure_arg_mismatch(
1678 found_span: Option<Span>,
1679 found: ty::PolyTraitRef<'tcx>,
1680 expected: ty::PolyTraitRef<'tcx>,
1681 cause: &ObligationCauseCode<'tcx>,
1682 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1683 pub(crate) fn build_fn_sig_ty<'tcx>(
1684 infcx: &InferCtxt<'tcx>,
1685 trait_ref: ty::PolyTraitRef<'tcx>,
1687 let inputs = trait_ref.skip_binder().substs.type_at(1);
1688 let sig = match inputs.kind() {
1690 if infcx.tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1692 infcx.tcx.mk_fn_sig(
1694 infcx.next_ty_var(TypeVariableOrigin {
1696 kind: TypeVariableOriginKind::MiscVariable,
1699 hir::Unsafety::Normal,
1703 _ => infcx.tcx.mk_fn_sig(
1704 std::iter::once(inputs),
1705 infcx.next_ty_var(TypeVariableOrigin {
1707 kind: TypeVariableOriginKind::MiscVariable,
1710 hir::Unsafety::Normal,
1715 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1718 let argument_kind = match expected.skip_binder().self_ty().kind() {
1719 ty::Closure(..) => "closure",
1720 ty::Generator(..) => "generator",
1723 let mut err = struct_span_err!(
1727 "type mismatch in {argument_kind} arguments",
1730 err.span_label(span, "expected due to this");
1732 let found_span = found_span.unwrap_or(span);
1733 err.span_label(found_span, "found signature defined here");
1735 let expected = build_fn_sig_ty(self, expected);
1736 let found = build_fn_sig_ty(self, found);
1738 let (expected_str, found_str) = self.cmp(expected, found);
1740 let signature_kind = format!("{argument_kind} signature");
1741 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1743 self.note_conflicting_closure_bounds(cause, &mut err);
1748 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1749 // requirements, which will always cause a closure to have a type error.
1750 fn note_conflicting_closure_bounds(
1752 cause: &ObligationCauseCode<'tcx>,
1753 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1755 // First, look for an `ExprBindingObligation`, which means we can get
1756 // the unsubstituted predicate list of the called function. And check
1757 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1758 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1759 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1760 && let Some(pred) = predicates.predicates.get(*idx)
1761 && let ty::PredicateKind::Trait(trait_pred) = pred.kind().skip_binder()
1762 && ty::ClosureKind::from_def_id(self.tcx, trait_pred.def_id()).is_some()
1765 self.tcx.anonymize_late_bound_regions(pred.kind().rebind(trait_pred.self_ty()));
1766 let expected_substs = self
1768 .anonymize_late_bound_regions(pred.kind().rebind(trait_pred.trait_ref.substs));
1770 // Find another predicate whose self-type is equal to the expected self type,
1771 // but whose substs don't match.
1772 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1774 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1775 ty::PredicateKind::Trait(trait_pred)
1776 if ty::ClosureKind::from_def_id(self.tcx, trait_pred.def_id())
1779 // Make sure that the self type matches
1780 // (i.e. constraining this closure)
1782 == self.tcx.anonymize_late_bound_regions(
1783 pred.kind().rebind(trait_pred.self_ty()),
1785 // But the substs don't match (i.e. incompatible args)
1787 != self.tcx.anonymize_late_bound_regions(
1788 pred.kind().rebind(trait_pred.trait_ref.substs),
1795 // If we found one, then it's very likely the cause of the error.
1796 if let Some((_, (_, other_pred_span))) = other_pred {
1799 "closure inferred to have a different signature due to this bound",
1805 fn suggest_fully_qualified_path(
1807 err: &mut Diagnostic,
1812 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1813 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1815 "{}s cannot be accessed directly on a `trait`, they can only be \
1816 accessed through a specific `impl`",
1817 assoc_item.kind.as_def_kind().descr(item_def_id)
1819 err.span_suggestion(
1821 "use the fully qualified path to an implementation",
1822 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1823 Applicability::HasPlaceholders,
1829 /// Adds an async-await specific note to the diagnostic when the future does not implement
1830 /// an auto trait because of a captured type.
1833 /// note: future does not implement `Qux` as this value is used across an await
1834 /// --> $DIR/issue-64130-3-other.rs:17:5
1836 /// LL | let x = Foo;
1837 /// | - has type `Foo`
1838 /// LL | baz().await;
1839 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1841 /// | - `x` is later dropped here
1844 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1845 /// is "replaced" with a different message and a more specific error.
1848 /// error: future cannot be sent between threads safely
1849 /// --> $DIR/issue-64130-2-send.rs:21:5
1851 /// LL | fn is_send<T: Send>(t: T) { }
1852 /// | ---- required by this bound in `is_send`
1854 /// LL | is_send(bar());
1855 /// | ^^^^^^^ future returned by `bar` is not send
1857 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1858 /// implemented for `Foo`
1859 /// note: future is not send as this value is used across an await
1860 /// --> $DIR/issue-64130-2-send.rs:15:5
1862 /// LL | let x = Foo;
1863 /// | - has type `Foo`
1864 /// LL | baz().await;
1865 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1867 /// | - `x` is later dropped here
1870 /// Returns `true` if an async-await specific note was added to the diagnostic.
1871 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1872 fn maybe_note_obligation_cause_for_async_await(
1874 err: &mut Diagnostic,
1875 obligation: &PredicateObligation<'tcx>,
1877 let hir = self.tcx.hir();
1879 // Attempt to detect an async-await error by looking at the obligation causes, looking
1880 // for a generator to be present.
1882 // When a future does not implement a trait because of a captured type in one of the
1883 // generators somewhere in the call stack, then the result is a chain of obligations.
1885 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1886 // future is passed as an argument to a function C which requires a `Send` type, then the
1887 // chain looks something like this:
1889 // - `BuiltinDerivedObligation` with a generator witness (B)
1890 // - `BuiltinDerivedObligation` with a generator (B)
1891 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1892 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1893 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1894 // - `BuiltinDerivedObligation` with a generator witness (A)
1895 // - `BuiltinDerivedObligation` with a generator (A)
1896 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1897 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1898 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1899 // - `BindingObligation` with `impl_send (Send requirement)
1901 // The first obligation in the chain is the most useful and has the generator that captured
1902 // the type. The last generator (`outer_generator` below) has information about where the
1903 // bound was introduced. At least one generator should be present for this diagnostic to be
1905 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1906 ty::PredicateKind::Trait(p) => (Some(p), Some(p.self_ty())),
1909 let mut generator = None;
1910 let mut outer_generator = None;
1911 let mut next_code = Some(obligation.cause.code());
1913 let mut seen_upvar_tys_infer_tuple = false;
1915 while let Some(code) = next_code {
1918 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1919 next_code = Some(parent_code);
1921 ObligationCauseCode::ImplDerivedObligation(cause) => {
1922 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1924 parent_trait_ref = ?cause.derived.parent_trait_pred,
1925 self_ty.kind = ?ty.kind(),
1930 ty::Generator(did, ..) => {
1931 generator = generator.or(Some(did));
1932 outer_generator = Some(did);
1934 ty::GeneratorWitness(..) => {}
1935 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1936 // By introducing a tuple of upvar types into the chain of obligations
1937 // of a generator, the first non-generator item is now the tuple itself,
1938 // we shall ignore this.
1940 seen_upvar_tys_infer_tuple = true;
1942 _ if generator.is_none() => {
1943 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1944 target_ty = Some(ty);
1949 next_code = Some(&cause.derived.parent_code);
1951 ObligationCauseCode::DerivedObligation(derived_obligation)
1952 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1953 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1955 parent_trait_ref = ?derived_obligation.parent_trait_pred,
1956 self_ty.kind = ?ty.kind(),
1960 ty::Generator(did, ..) => {
1961 generator = generator.or(Some(did));
1962 outer_generator = Some(did);
1964 ty::GeneratorWitness(..) => {}
1965 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1966 // By introducing a tuple of upvar types into the chain of obligations
1967 // of a generator, the first non-generator item is now the tuple itself,
1968 // we shall ignore this.
1970 seen_upvar_tys_infer_tuple = true;
1972 _ if generator.is_none() => {
1973 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1974 target_ty = Some(ty);
1979 next_code = Some(&derived_obligation.parent_code);
1985 // Only continue if a generator was found.
1986 debug!(?generator, ?trait_ref, ?target_ty);
1987 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1991 let span = self.tcx.def_span(generator_did);
1993 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1996 ?generator_did_root,
1997 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2001 let generator_body = generator_did
2003 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2004 .map(|body_id| hir.body(body_id));
2007 .generator_kind(generator_did)
2008 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
2010 let mut visitor = AwaitsVisitor::default();
2011 if let Some(body) = generator_body {
2012 visitor.visit_body(body);
2014 debug!(awaits = ?visitor.awaits);
2016 // Look for a type inside the generator interior that matches the target type to get
2018 let target_ty_erased = self.tcx.erase_regions(target_ty);
2019 let ty_matches = |ty| -> bool {
2020 // Careful: the regions for types that appear in the
2021 // generator interior are not generally known, so we
2022 // want to erase them when comparing (and anyway,
2023 // `Send` and other bounds are generally unaffected by
2024 // the choice of region). When erasing regions, we
2025 // also have to erase late-bound regions. This is
2026 // because the types that appear in the generator
2027 // interior generally contain "bound regions" to
2028 // represent regions that are part of the suspended
2029 // generator frame. Bound regions are preserved by
2030 // `erase_regions` and so we must also call
2031 // `erase_late_bound_regions`.
2032 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2033 let ty_erased = self.tcx.erase_regions(ty_erased);
2034 let eq = ty_erased == target_ty_erased;
2035 debug!(?ty_erased, ?target_ty_erased, ?eq);
2039 // Get the typeck results from the infcx if the generator is the function we are currently
2040 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2041 // cycles. If we can't use resolved types because the generator comes from another crate,
2042 // we still provide a targeted error but without all the relevant spans.
2043 let generator_data = match &self.typeck_results {
2044 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2045 _ if generator_did.is_local() => {
2046 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2048 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2049 GeneratorData::Foreign(generator_diag_data)
2054 let mut interior_or_upvar_span = None;
2056 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2057 debug!(?from_awaited_ty);
2059 // The generator interior types share the same binders
2060 if let Some(cause) =
2061 generator_data.get_generator_interior_types().skip_binder().iter().find(
2062 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2063 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2067 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2069 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2071 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2075 if interior_or_upvar_span.is_none() {
2076 interior_or_upvar_span =
2077 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2080 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2081 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2084 debug!(?interior_or_upvar_span);
2085 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2086 let typeck_results = match generator_data {
2087 GeneratorData::Local(typeck_results) => Some(typeck_results),
2088 GeneratorData::Foreign(_) => None,
2090 self.note_obligation_cause_for_async_await(
2092 interior_or_upvar_span,
2107 /// Unconditionally adds the diagnostic note described in
2108 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2109 #[instrument(level = "debug", skip_all)]
2110 fn note_obligation_cause_for_async_await(
2112 err: &mut Diagnostic,
2113 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2115 outer_generator: Option<DefId>,
2116 trait_pred: ty::TraitPredicate<'tcx>,
2117 target_ty: Ty<'tcx>,
2118 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2119 obligation: &PredicateObligation<'tcx>,
2120 next_code: Option<&ObligationCauseCode<'tcx>>,
2122 let source_map = self.tcx.sess.source_map();
2124 let (await_or_yield, an_await_or_yield) =
2125 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2126 let future_or_generator = if is_async { "future" } else { "generator" };
2128 // Special case the primary error message when send or sync is the trait that was
2130 let hir = self.tcx.hir();
2131 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2132 self.tcx.get_diagnostic_name(trait_pred.def_id())
2134 let (trait_name, trait_verb) =
2135 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2138 err.set_primary_message(format!(
2139 "{} cannot be {} between threads safely",
2140 future_or_generator, trait_verb
2143 let original_span = err.span.primary_span().unwrap();
2144 let mut span = MultiSpan::from_span(original_span);
2146 let message = outer_generator
2147 .and_then(|generator_did| {
2148 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2149 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2150 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2152 .parent(generator_did)
2154 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2155 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2157 format!("future returned by `{}` is not {}", name, trait_name)
2159 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2160 format!("future created by async block is not {}", trait_name)
2162 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2163 format!("future created by async closure is not {}", trait_name)
2167 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2169 span.push_span_label(original_span, message);
2172 format!("is not {}", trait_name)
2174 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2177 let mut explain_yield = |interior_span: Span,
2179 scope_span: Option<Span>| {
2180 let mut span = MultiSpan::from_span(yield_span);
2181 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
2182 // #70935: If snippet contains newlines, display "the value" instead
2183 // so that we do not emit complex diagnostics.
2184 let snippet = &format!("`{}`", snippet);
2185 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
2186 // note: future is not `Send` as this value is used across an await
2187 // --> $DIR/issue-70935-complex-spans.rs:13:9
2189 // LL | baz(|| async {
2190 // | ______________-
2193 // LL | | foo(tx.clone());
2195 // | | - ^^^^^^ await occurs here, with value maybe used later
2197 // | has type `closure` which is not `Send`
2198 // note: value is later dropped here
2202 span.push_span_label(
2204 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2206 span.push_span_label(
2208 format!("has type `{}` which {}", target_ty, trait_explanation),
2210 // If available, use the scope span to annotate the drop location.
2211 let mut scope_note = None;
2212 if let Some(scope_span) = scope_span {
2213 let scope_span = source_map.end_point(scope_span);
2215 let msg = format!("{} is later dropped here", snippet);
2216 if source_map.is_multiline(yield_span.between(scope_span)) {
2217 span.push_span_label(scope_span, msg);
2219 scope_note = Some((scope_span, msg));
2225 "{} {} as this value is used across {}",
2226 future_or_generator, trait_explanation, an_await_or_yield
2229 if let Some((span, msg)) = scope_note {
2230 err.span_note(span, &msg);
2234 match interior_or_upvar_span {
2235 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2236 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2237 if let Some(await_span) = from_awaited_ty {
2238 // The type causing this obligation is one being awaited at await_span.
2239 let mut span = MultiSpan::from_span(await_span);
2240 span.push_span_label(
2243 "await occurs here on type `{}`, which {}",
2244 target_ty, trait_explanation
2250 "future {not_trait} as it awaits another future which {not_trait}",
2251 not_trait = trait_explanation
2255 // Look at the last interior type to get a span for the `.await`.
2257 generator_interior_types = ?format_args!(
2258 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2261 explain_yield(interior_span, yield_span, scope_span);
2264 if let Some(expr_id) = expr {
2265 let expr = hir.expect_expr(expr_id);
2266 debug!("target_ty evaluated from {:?}", expr);
2268 let parent = hir.get_parent_node(expr_id);
2269 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2270 let parent_span = hir.span(parent);
2271 let parent_did = parent.owner.to_def_id();
2274 // fn foo(&self) -> i32 {}
2277 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2280 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2282 .expr_adjustments(expr)
2284 .any(|adj| adj.is_region_borrow())
2290 // struct Foo(*const u8);
2291 // bar(Foo(std::ptr::null())).await;
2292 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2294 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2295 let is_raw_borrow_inside_fn_like_call =
2296 match self.tcx.def_kind(parent_did) {
2297 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2300 if let Some(typeck_results) = typeck_results {
2301 if (typeck_results.is_method_call(e) && is_region_borrow)
2302 || is_raw_borrow_inside_fn_like_call
2306 "consider moving this into a `let` \
2307 binding to create a shorter lived borrow",
2315 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2316 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2317 let refers_to_non_sync = match target_ty.kind() {
2318 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2319 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2325 let (span_label, span_note) = match refers_to_non_sync {
2326 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2327 // include suggestions to make `T: Sync` so that `&T: Send`
2330 "has type `{}` which {}, because `{}` is not `Sync`",
2331 target_ty, trait_explanation, ref_ty
2334 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2339 format!("has type `{}` which {}", target_ty, trait_explanation),
2340 format!("captured value {}", trait_explanation),
2344 let mut span = MultiSpan::from_span(upvar_span);
2345 span.push_span_label(upvar_span, span_label);
2346 err.span_note(span, &span_note);
2350 // Add a note for the item obligation that remains - normally a note pointing to the
2351 // bound that introduced the obligation (e.g. `T: Send`).
2353 self.note_obligation_cause_code(
2355 &obligation.predicate,
2356 obligation.param_env,
2359 &mut Default::default(),
2363 fn note_obligation_cause_code<T>(
2365 err: &mut Diagnostic,
2367 param_env: ty::ParamEnv<'tcx>,
2368 cause_code: &ObligationCauseCode<'tcx>,
2369 obligated_types: &mut Vec<Ty<'tcx>>,
2370 seen_requirements: &mut FxHashSet<DefId>,
2376 ObligationCauseCode::ExprAssignable
2377 | ObligationCauseCode::MatchExpressionArm { .. }
2378 | ObligationCauseCode::Pattern { .. }
2379 | ObligationCauseCode::IfExpression { .. }
2380 | ObligationCauseCode::IfExpressionWithNoElse
2381 | ObligationCauseCode::MainFunctionType
2382 | ObligationCauseCode::StartFunctionType
2383 | ObligationCauseCode::IntrinsicType
2384 | ObligationCauseCode::MethodReceiver
2385 | ObligationCauseCode::ReturnNoExpression
2386 | ObligationCauseCode::UnifyReceiver(..)
2387 | ObligationCauseCode::OpaqueType
2388 | ObligationCauseCode::MiscObligation
2389 | ObligationCauseCode::WellFormed(..)
2390 | ObligationCauseCode::MatchImpl(..)
2391 | ObligationCauseCode::ReturnType
2392 | ObligationCauseCode::ReturnValue(_)
2393 | ObligationCauseCode::BlockTailExpression(_)
2394 | ObligationCauseCode::AwaitableExpr(_)
2395 | ObligationCauseCode::ForLoopIterator
2396 | ObligationCauseCode::QuestionMark
2397 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2398 | ObligationCauseCode::LetElse
2399 | ObligationCauseCode::BinOp { .. }
2400 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2401 | ObligationCauseCode::RustCall => {}
2402 ObligationCauseCode::SliceOrArrayElem => {
2403 err.note("slice and array elements must have `Sized` type");
2405 ObligationCauseCode::TupleElem => {
2406 err.note("only the last element of a tuple may have a dynamically sized type");
2408 ObligationCauseCode::ProjectionWf(data) => {
2409 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2411 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2413 "required so that reference `{}` does not outlive its referent",
2417 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2419 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2423 ObligationCauseCode::ItemObligation(_)
2424 | ObligationCauseCode::ExprItemObligation(..) => {
2425 // We hold the `DefId` of the item introducing the obligation, but displaying it
2426 // doesn't add user usable information. It always point at an associated item.
2428 ObligationCauseCode::BindingObligation(item_def_id, span)
2429 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2430 let item_name = tcx.def_path_str(item_def_id);
2431 let mut multispan = MultiSpan::from(span);
2432 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2433 let sm = tcx.sess.source_map();
2435 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2436 (Ok(l), Ok(r)) => l.line == r.line,
2439 if !ident.span.overlaps(span) && !same_line {
2440 multispan.push_span_label(ident.span, "required by a bound in this");
2443 let descr = format!("required by a bound in `{}`", item_name);
2444 if span != DUMMY_SP {
2445 let msg = format!("required by this bound in `{}`", item_name);
2446 multispan.push_span_label(span, msg);
2447 err.span_note(multispan, &descr);
2449 err.span_note(tcx.def_span(item_def_id), &descr);
2452 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2454 "required for the cast from `{}` to the object type `{}`",
2455 self.ty_to_string(concrete_ty),
2456 self.ty_to_string(object_ty)
2459 ObligationCauseCode::Coercion { source: _, target } => {
2460 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2462 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2464 "the `Copy` trait is required because this value will be copied for each element of the array",
2469 "consider creating a new `const` item and initializing it with the result \
2470 of the function call to be used in the repeat position, like \
2471 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2475 if self.tcx.sess.is_nightly_build() && is_const_fn {
2477 "create an inline `const` block, see RFC #2920 \
2478 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2482 ObligationCauseCode::VariableType(hir_id) => {
2483 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2484 match self.tcx.hir().find(parent_node) {
2485 Some(Node::Local(hir::Local {
2486 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2489 // When encountering an assignment of an unsized trait, like
2490 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2491 // order to use have a slice instead.
2492 err.span_suggestion_verbose(
2493 span.shrink_to_lo(),
2494 "consider borrowing here",
2496 Applicability::MachineApplicable,
2498 err.note("all local variables must have a statically known size");
2500 Some(Node::Param(param)) => {
2501 err.span_suggestion_verbose(
2502 param.ty_span.shrink_to_lo(),
2503 "function arguments must have a statically known size, borrowed types \
2504 always have a known size",
2506 Applicability::MachineApplicable,
2510 err.note("all local variables must have a statically known size");
2513 if !self.tcx.features().unsized_locals {
2514 err.help("unsized locals are gated as an unstable feature");
2517 ObligationCauseCode::SizedArgumentType(sp) => {
2518 if let Some(span) = sp {
2519 err.span_suggestion_verbose(
2520 span.shrink_to_lo(),
2521 "function arguments must have a statically known size, borrowed types \
2522 always have a known size",
2524 Applicability::MachineApplicable,
2527 err.note("all function arguments must have a statically known size");
2529 if tcx.sess.opts.unstable_features.is_nightly_build()
2530 && !self.tcx.features().unsized_fn_params
2532 err.help("unsized fn params are gated as an unstable feature");
2535 ObligationCauseCode::SizedReturnType => {
2536 err.note("the return type of a function must have a statically known size");
2538 ObligationCauseCode::SizedYieldType => {
2539 err.note("the yield type of a generator must have a statically known size");
2541 ObligationCauseCode::SizedBoxType => {
2542 err.note("the type of a box expression must have a statically known size");
2544 ObligationCauseCode::AssignmentLhsSized => {
2545 err.note("the left-hand-side of an assignment must have a statically known size");
2547 ObligationCauseCode::TupleInitializerSized => {
2548 err.note("tuples must have a statically known size to be initialized");
2550 ObligationCauseCode::StructInitializerSized => {
2551 err.note("structs must have a statically known size to be initialized");
2553 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2555 AdtKind::Struct => {
2558 "the last field of a packed struct may only have a \
2559 dynamically sized type if it does not need drop to be run",
2563 "only the last field of a struct may have a dynamically sized type",
2568 err.note("no field of a union may have a dynamically sized type");
2571 err.note("no field of an enum variant may have a dynamically sized type");
2574 err.help("change the field's type to have a statically known size");
2575 err.span_suggestion(
2576 span.shrink_to_lo(),
2577 "borrowed types always have a statically known size",
2579 Applicability::MachineApplicable,
2581 err.multipart_suggestion(
2582 "the `Box` type always has a statically known size and allocates its contents \
2585 (span.shrink_to_lo(), "Box<".to_string()),
2586 (span.shrink_to_hi(), ">".to_string()),
2588 Applicability::MachineApplicable,
2591 ObligationCauseCode::ConstSized => {
2592 err.note("constant expressions must have a statically known size");
2594 ObligationCauseCode::InlineAsmSized => {
2595 err.note("all inline asm arguments must have a statically known size");
2597 ObligationCauseCode::ConstPatternStructural => {
2598 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2600 ObligationCauseCode::SharedStatic => {
2601 err.note("shared static variables must have a type that implements `Sync`");
2603 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2604 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2605 let ty = parent_trait_ref.skip_binder().self_ty();
2606 if parent_trait_ref.references_error() {
2607 // NOTE(eddyb) this was `.cancel()`, but `err`
2608 // is borrowed, so we can't fully defuse it.
2609 err.downgrade_to_delayed_bug();
2613 // If the obligation for a tuple is set directly by a Generator or Closure,
2614 // then the tuple must be the one containing capture types.
2615 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2618 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2620 let parent_trait_ref =
2621 self.resolve_vars_if_possible(data.parent_trait_pred);
2622 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2623 matches!(nested_ty.kind(), ty::Generator(..))
2624 || matches!(nested_ty.kind(), ty::Closure(..))
2630 let from_generator = tcx.lang_items().from_generator_fn().unwrap();
2632 // Don't print the tuple of capture types
2634 if !is_upvar_tys_infer_tuple {
2635 let msg = format!("required because it appears within the type `{}`", ty);
2637 ty::Adt(def, _) => {
2638 // `gen_future` is used in all async functions; it doesn't add any additional info.
2639 if self.tcx.is_diagnostic_item(sym::gen_future, def.did()) {
2642 match self.tcx.opt_item_ident(def.did()) {
2643 Some(ident) => err.span_note(ident.span, &msg),
2644 None => err.note(&msg),
2647 ty::Opaque(def_id, _) => {
2648 // Avoid printing the future from `core::future::from_generator`, it's not helpful
2649 if tcx.parent(*def_id) == from_generator {
2653 // If the previous type is `from_generator`, this is the future generated by the body of an async function.
2654 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2655 let is_future = tcx.ty_is_opaque_future(ty);
2659 "note_obligation_cause_code: check for async fn"
2662 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2663 ty::Opaque(last_def_id, _) => {
2664 tcx.parent(*last_def_id) == from_generator
2671 err.span_note(self.tcx.def_span(def_id), &msg)
2673 ty::GeneratorWitness(bound_tys) => {
2674 use std::fmt::Write;
2676 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2677 // Maybe we should just remove this note altogether?
2678 // FIXME: only print types which don't meet the trait requirement
2680 "required because it captures the following types: ".to_owned();
2681 for ty in bound_tys.skip_binder() {
2682 write!(msg, "`{}`, ", ty).unwrap();
2684 err.note(msg.trim_end_matches(", "))
2686 ty::Generator(def_id, _, _) => {
2687 let sp = self.tcx.def_span(def_id);
2689 // Special-case this to say "async block" instead of `[static generator]`.
2690 let kind = tcx.generator_kind(def_id).unwrap();
2693 &format!("required because it's used within this {}", kind),
2696 ty::Closure(def_id, _) => err.span_note(
2697 self.tcx.def_span(def_id),
2698 &format!("required because it's used within this closure"),
2700 _ => err.note(&msg),
2705 obligated_types.push(ty);
2707 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2708 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2709 // #74711: avoid a stack overflow
2710 ensure_sufficient_stack(|| {
2711 self.note_obligation_cause_code(
2721 ensure_sufficient_stack(|| {
2722 self.note_obligation_cause_code(
2726 cause_code.peel_derives(),
2733 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2734 let mut parent_trait_pred =
2735 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2736 parent_trait_pred.remap_constness_diag(param_env);
2737 let parent_def_id = parent_trait_pred.def_id();
2739 "required for `{}` to implement `{}`",
2740 parent_trait_pred.skip_binder().self_ty(),
2741 parent_trait_pred.print_modifiers_and_trait_path()
2743 let mut is_auto_trait = false;
2744 match self.tcx.hir().get_if_local(data.impl_def_id) {
2745 Some(Node::Item(hir::Item {
2746 kind: hir::ItemKind::Trait(is_auto, ..),
2750 // FIXME: we should do something else so that it works even on crate foreign
2752 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2753 err.span_note(ident.span, &msg)
2755 Some(Node::Item(hir::Item {
2756 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2759 let mut spans = Vec::with_capacity(2);
2760 if let Some(trait_ref) = of_trait {
2761 spans.push(trait_ref.path.span);
2763 spans.push(self_ty.span);
2764 err.span_note(spans, &msg)
2766 _ => err.note(&msg),
2769 let mut parent_predicate = parent_trait_pred.to_predicate(tcx);
2770 let mut data = &data.derived;
2772 seen_requirements.insert(parent_def_id);
2774 // We don't want to point at the ADT saying "required because it appears within
2775 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2776 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2779 let child_trait_ref =
2780 self.resolve_vars_if_possible(derived.parent_trait_pred);
2781 let child_def_id = child_trait_ref.def_id();
2782 if seen_requirements.insert(child_def_id) {
2786 parent_predicate = child_trait_ref.to_predicate(tcx);
2787 parent_trait_pred = child_trait_ref;
2790 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2791 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2792 let child_trait_pred =
2793 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2794 let child_def_id = child_trait_pred.def_id();
2795 if seen_requirements.insert(child_def_id) {
2799 data = &child.derived;
2800 parent_predicate = child_trait_pred.to_predicate(tcx);
2801 parent_trait_pred = child_trait_pred;
2805 "{} redundant requirement{} hidden",
2810 "required for `{}` to implement `{}`",
2811 parent_trait_pred.skip_binder().self_ty(),
2812 parent_trait_pred.print_modifiers_and_trait_path()
2815 // #74711: avoid a stack overflow
2816 ensure_sufficient_stack(|| {
2817 self.note_obligation_cause_code(
2827 ObligationCauseCode::DerivedObligation(ref data) => {
2828 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2829 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2830 // #74711: avoid a stack overflow
2831 ensure_sufficient_stack(|| {
2832 self.note_obligation_cause_code(
2842 ObligationCauseCode::FunctionArgumentObligation {
2847 let hir = self.tcx.hir();
2848 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2849 hir.find(arg_hir_id)
2851 let parent_id = hir.get_parent_item(arg_hir_id);
2852 let typeck_results: &TypeckResults<'tcx> = match &self.typeck_results {
2853 Some(t) if t.hir_owner == parent_id => t,
2854 _ => self.tcx.typeck(parent_id.def_id),
2856 let expr = expr.peel_blocks();
2857 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
2858 let span = expr.span;
2859 if Some(span) != err.span.primary_span() {
2862 if ty.references_error() {
2865 format!("this tail expression is of type `{:?}`", ty)
2870 if let Some(Node::Expr(hir::Expr {
2872 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2873 | hir::ExprKind::MethodCall(
2874 hir::PathSegment { ident: Ident { span, .. }, .. },
2878 })) = hir.find(call_hir_id)
2880 if Some(*span) != err.span.primary_span() {
2881 err.span_label(*span, "required by a bound introduced by this call");
2884 ensure_sufficient_stack(|| {
2885 self.note_obligation_cause_code(
2895 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2896 let item_name = self.tcx.item_name(trait_item_def_id);
2898 "the requirement `{}` appears on the `impl`'s {kind} `{}` but not on the \
2899 corresponding trait's {kind}",
2900 predicate, item_name,
2904 .opt_item_ident(trait_item_def_id)
2906 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2907 let mut assoc_span: MultiSpan = sp.into();
2908 assoc_span.push_span_label(
2910 format!("this trait's {kind} doesn't have the requirement `{}`", predicate),
2912 if let Some(ident) = self
2914 .opt_associated_item(trait_item_def_id)
2915 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2917 assoc_span.push_span_label(ident.span, "in this trait");
2919 err.span_note(assoc_span, &msg);
2921 ObligationCauseCode::TrivialBound => {
2922 err.help("see issue #48214");
2923 if tcx.sess.opts.unstable_features.is_nightly_build() {
2924 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2927 ObligationCauseCode::OpaqueReturnType(expr_info) => {
2928 if let Some((expr_ty, expr_span)) = expr_info {
2929 let expr_ty = self.resolve_vars_if_possible(expr_ty);
2932 format!("return type was inferred to be `{expr_ty}` here"),
2940 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2942 fn suggest_await_before_try(
2944 err: &mut Diagnostic,
2945 obligation: &PredicateObligation<'tcx>,
2946 trait_pred: ty::PolyTraitPredicate<'tcx>,
2949 let body_hir_id = obligation.cause.body_id;
2950 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2952 if let Some(body_id) =
2953 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2955 let body = self.tcx.hir().body(body_id);
2956 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2957 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2959 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2960 let impls_future = self.type_implements_trait(
2962 self.tcx.erase_late_bound_regions(self_ty),
2964 obligation.param_env,
2966 if !impls_future.must_apply_modulo_regions() {
2970 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2971 // `<T as Future>::Output`
2972 let projection_ty = trait_pred.map_bound(|trait_pred| {
2973 self.tcx.mk_projection(
2975 // Future::Output has no substs
2976 self.tcx.mk_substs_trait(trait_pred.self_ty(), &[]),
2979 let projection_ty = normalize_to(
2980 &mut SelectionContext::new(self),
2981 obligation.param_env,
2982 obligation.cause.clone(),
2988 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
2990 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2991 obligation.param_env,
2992 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
2994 debug!(try_trait_obligation = ?try_obligation);
2995 if self.predicate_may_hold(&try_obligation)
2996 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2997 && snippet.ends_with('?')
2999 err.span_suggestion_verbose(
3000 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3001 "consider `await`ing on the `Future`",
3003 Applicability::MaybeIncorrect,
3010 fn suggest_floating_point_literal(
3012 obligation: &PredicateObligation<'tcx>,
3013 err: &mut Diagnostic,
3014 trait_ref: &ty::PolyTraitRef<'tcx>,
3016 let rhs_span = match obligation.cause.code() {
3017 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3020 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3021 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3023 err.span_suggestion_verbose(
3024 rhs_span.shrink_to_hi(),
3025 "consider using a floating-point literal by writing it with `.0`",
3027 Applicability::MaybeIncorrect,
3034 obligation: &PredicateObligation<'tcx>,
3035 err: &mut Diagnostic,
3036 trait_pred: ty::PolyTraitPredicate<'tcx>,
3038 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3041 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3042 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3046 let is_derivable_trait = match diagnostic_name {
3047 sym::Default => !adt.is_enum(),
3048 sym::PartialEq | sym::PartialOrd => {
3049 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3050 trait_pred.skip_binder().self_ty() == rhs_ty
3052 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3055 is_derivable_trait &&
3056 // Ensure all fields impl the trait.
3057 adt.all_fields().all(|field| {
3058 let field_ty = field.ty(self.tcx, substs);
3059 let trait_substs = match diagnostic_name {
3060 sym::PartialEq | sym::PartialOrd => {
3061 self.tcx.mk_substs_trait(field_ty, &[field_ty.into()])
3063 _ => self.tcx.mk_substs_trait(field_ty, &[]),
3065 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3066 trait_ref: ty::TraitRef {
3067 substs: trait_substs,
3068 ..trait_pred.skip_binder().trait_ref
3072 let field_obl = Obligation::new(
3073 obligation.cause.clone(),
3074 obligation.param_env,
3075 trait_pred.to_predicate(self.tcx),
3077 self.predicate_must_hold_modulo_regions(&field_obl)
3081 err.span_suggestion_verbose(
3082 self.tcx.def_span(adt.did()).shrink_to_lo(),
3084 "consider annotating `{}` with `#[derive({})]`",
3085 trait_pred.skip_binder().self_ty(),
3088 format!("#[derive({})]\n", diagnostic_name),
3089 Applicability::MaybeIncorrect,
3094 fn suggest_dereferencing_index(
3096 obligation: &PredicateObligation<'tcx>,
3097 err: &mut Diagnostic,
3098 trait_pred: ty::PolyTraitPredicate<'tcx>,
3100 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3101 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3102 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3103 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3104 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3106 err.span_suggestion_verbose(
3107 obligation.cause.span.shrink_to_lo(),
3108 "dereference this index",
3110 Applicability::MachineApplicable,
3116 /// Collect all the returned expressions within the input expression.
3117 /// Used to point at the return spans when we want to suggest some change to them.
3119 pub struct ReturnsVisitor<'v> {
3120 pub returns: Vec<&'v hir::Expr<'v>>,
3121 in_block_tail: bool,
3124 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3125 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3126 // Visit every expression to detect `return` paths, either through the function's tail
3127 // expression or `return` statements. We walk all nodes to find `return` statements, but
3128 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3129 // they're in the return path of the function body.
3131 hir::ExprKind::Ret(Some(ex)) => {
3132 self.returns.push(ex);
3134 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3135 self.in_block_tail = false;
3136 for stmt in block.stmts {
3137 hir::intravisit::walk_stmt(self, stmt);
3139 self.in_block_tail = true;
3140 if let Some(expr) = block.expr {
3141 self.visit_expr(expr);
3144 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3145 self.visit_expr(then);
3146 if let Some(el) = else_opt {
3147 self.visit_expr(el);
3150 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3152 self.visit_expr(arm.body);
3155 // We need to walk to find `return`s in the entire body.
3156 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3157 _ => self.returns.push(ex),
3161 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3162 assert!(!self.in_block_tail);
3163 if body.generator_kind().is_none() {
3164 if let hir::ExprKind::Block(block, None) = body.value.kind {
3165 if block.expr.is_some() {
3166 self.in_block_tail = true;
3170 hir::intravisit::walk_body(self, body);
3174 /// Collect all the awaited expressions within the input expression.
3176 struct AwaitsVisitor {
3177 awaits: Vec<hir::HirId>,
3180 impl<'v> Visitor<'v> for AwaitsVisitor {
3181 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3182 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3183 self.awaits.push(id)
3185 hir::intravisit::walk_expr(self, ex)
3189 pub trait NextTypeParamName {
3190 fn next_type_param_name(&self, name: Option<&str>) -> String;
3193 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3194 fn next_type_param_name(&self, name: Option<&str>) -> String {
3195 // This is the list of possible parameter names that we might suggest.
3196 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3197 let name = name.as_deref();
3198 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3199 let used_names = self
3201 .filter_map(|p| match p.name {
3202 hir::ParamName::Plain(ident) => Some(ident.name),
3205 .collect::<Vec<_>>();
3209 .find(|n| !used_names.contains(&Symbol::intern(n)))
3210 .unwrap_or(&"ParamName")
3215 fn suggest_trait_object_return_type_alternatives(
3216 err: &mut Diagnostic,
3219 is_object_safe: bool,
3221 err.span_suggestion(
3223 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3226 Applicability::MaybeIncorrect,
3228 err.span_suggestion(
3231 "use `impl {}` as the return type if all return paths have the same type but you \
3232 want to expose only the trait in the signature",
3235 format!("impl {}", trait_obj),
3236 Applicability::MaybeIncorrect,
3239 err.multipart_suggestion(
3241 "use a boxed trait object if all return paths implement trait `{}`",
3245 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3246 (ret_ty.shrink_to_hi(), ">".to_string()),
3248 Applicability::MaybeIncorrect,
3253 /// Collect the spans that we see the generic param `param_did`
3254 struct ReplaceImplTraitVisitor<'a> {
3255 ty_spans: &'a mut Vec<Span>,
3259 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3260 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3261 if let hir::TyKind::Path(hir::QPath::Resolved(
3263 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3266 if self.param_did == *segment_did {
3267 // `fn foo(t: impl Trait)`
3268 // ^^^^^^^^^^ get this to suggest `T` instead
3270 // There might be more than one `impl Trait`.
3271 self.ty_spans.push(t.span);
3276 hir::intravisit::walk_ty(self, t);
3280 // Replace `param` with `replace_ty`
3281 struct ReplaceImplTraitFolder<'tcx> {
3283 param: &'tcx ty::GenericParamDef,
3284 replace_ty: Ty<'tcx>,
3287 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3288 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3289 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3290 if self.param.index == *index {
3291 return self.replace_ty;
3294 t.super_fold_with(self)
3297 fn tcx(&self) -> TyCtxt<'tcx> {