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
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,
286 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
288 outer_generator: Option<DefId>,
289 trait_pred: ty::TraitPredicate<'tcx>,
291 typeck_results: Option<&ty::TypeckResults<'tcx>>,
292 obligation: &PredicateObligation<'tcx>,
293 next_code: Option<&ObligationCauseCode<'tcx>>,
296 fn note_obligation_cause_code<T>(
298 err: &mut Diagnostic,
300 param_env: ty::ParamEnv<'tcx>,
301 cause_code: &ObligationCauseCode<'tcx>,
302 obligated_types: &mut Vec<Ty<'tcx>>,
303 seen_requirements: &mut FxHashSet<DefId>,
307 /// Suggest to await before try: future? => future.await?
308 fn suggest_await_before_try(
310 err: &mut Diagnostic,
311 obligation: &PredicateObligation<'tcx>,
312 trait_pred: ty::PolyTraitPredicate<'tcx>,
316 fn suggest_floating_point_literal(
318 obligation: &PredicateObligation<'tcx>,
319 err: &mut Diagnostic,
320 trait_ref: &ty::PolyTraitRef<'tcx>,
325 obligation: &PredicateObligation<'tcx>,
326 err: &mut Diagnostic,
327 trait_pred: ty::PolyTraitPredicate<'tcx>,
330 fn suggest_dereferencing_index(
332 obligation: &PredicateObligation<'tcx>,
333 err: &mut Diagnostic,
334 trait_pred: ty::PolyTraitPredicate<'tcx>,
338 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
340 generics.tail_span_for_predicate_suggestion(),
341 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
345 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
346 /// it can also be an `impl Trait` param that needs to be decomposed to a type
347 /// param for cleaner code.
348 fn suggest_restriction<'tcx>(
351 hir_generics: &hir::Generics<'tcx>,
353 err: &mut Diagnostic,
354 fn_sig: Option<&hir::FnSig<'_>>,
355 projection: Option<&ty::ProjectionTy<'_>>,
356 trait_pred: ty::PolyTraitPredicate<'tcx>,
357 // When we are dealing with a trait, `super_traits` will be `Some`:
358 // Given `trait T: A + B + C {}`
359 // - ^^^^^^^^^ GenericBounds
362 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
364 if hir_generics.where_clause_span.from_expansion()
365 || hir_generics.where_clause_span.desugaring_kind().is_some()
369 let Some(item_id) = hir_id.as_owner() else { return; };
370 let generics = tcx.generics_of(item_id);
371 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
372 if let Some((param, bound_str, fn_sig)) =
373 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
374 // Shenanigans to get the `Trait` from the `impl Trait`.
375 ty::Param(param) => {
376 let param_def = generics.type_param(param, tcx);
377 if param_def.kind.is_synthetic() {
379 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
380 return Some((param_def, bound_str, sig));
387 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
388 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
391 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
394 if !trait_pred.is_suggestable(tcx, false) {
397 // We know we have an `impl Trait` that doesn't satisfy a required projection.
399 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
400 // types. There should be at least one, but there might be *more* than one. In that
401 // case we could just ignore it and try to identify which one needs the restriction,
402 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
404 let mut ty_spans = vec![];
405 for input in fn_sig.decl.inputs {
406 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
409 // The type param `T: Trait` we will suggest to introduce.
410 let type_param = format!("{}: {}", type_param_name, bound_str);
413 if let Some(span) = hir_generics.span_for_param_suggestion() {
414 (span, format!(", {}", type_param))
416 (hir_generics.span, format!("<{}>", type_param))
418 // `fn foo(t: impl Trait)`
419 // ^ suggest `where <T as Trait>::A: Bound`
420 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx).to_string()),
422 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
424 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
425 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
426 // `fn foo(t: impl Trait<A: Bound>)` instead.
427 err.multipart_suggestion(
428 "introduce a type parameter with a trait bound instead of using `impl Trait`",
430 Applicability::MaybeIncorrect,
433 if !trait_pred.is_suggestable(tcx, false) {
436 // Trivial case: `T` needs an extra bound: `T: Bound`.
437 let (sp, suggestion) = match (
441 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
445 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx).to_string())
447 (None, Some((ident, []))) => (
448 ident.span.shrink_to_hi(),
449 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
451 (_, Some((_, [.., bounds]))) => (
452 bounds.span().shrink_to_hi(),
453 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
455 (Some(_), Some((_, []))) => (
456 hir_generics.span.shrink_to_hi(),
457 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
461 err.span_suggestion_verbose(
463 &format!("consider further restricting {}", msg),
465 Applicability::MachineApplicable,
470 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
471 fn suggest_restricting_param_bound(
473 mut err: &mut Diagnostic,
474 trait_pred: ty::PolyTraitPredicate<'tcx>,
475 associated_ty: Option<(&'static str, Ty<'tcx>)>,
478 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
480 let self_ty = trait_pred.skip_binder().self_ty();
481 let (param_ty, projection) = match self_ty.kind() {
482 ty::Param(_) => (true, None),
483 ty::Projection(projection) => (false, Some(projection)),
487 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
488 // don't suggest `T: Sized + ?Sized`.
489 let mut hir_id = body_id;
490 while let Some(node) = self.tcx.hir().find(hir_id) {
492 hir::Node::Item(hir::Item {
494 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
496 }) if self_ty == self.tcx.types.self_param => {
498 // Restricting `Self` for a single method.
508 Some((ident, bounds)),
513 hir::Node::TraitItem(hir::TraitItem {
515 kind: hir::TraitItemKind::Fn(..),
517 }) if self_ty == self.tcx.types.self_param => {
519 // Restricting `Self` for a single method.
521 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
527 hir::Node::TraitItem(hir::TraitItem {
529 kind: hir::TraitItemKind::Fn(fn_sig, ..),
532 | hir::Node::ImplItem(hir::ImplItem {
534 kind: hir::ImplItemKind::Fn(fn_sig, ..),
537 | hir::Node::Item(hir::Item {
538 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
539 }) if projection.is_some() => {
540 // Missing restriction on associated type of type parameter (unmet projection).
545 "the associated type",
554 hir::Node::Item(hir::Item {
556 hir::ItemKind::Trait(_, _, generics, ..)
557 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
559 }) if projection.is_some() => {
560 // Missing restriction on associated type of type parameter (unmet projection).
565 "the associated type",
575 hir::Node::Item(hir::Item {
577 hir::ItemKind::Struct(_, generics)
578 | hir::ItemKind::Enum(_, generics)
579 | hir::ItemKind::Union(_, generics)
580 | hir::ItemKind::Trait(_, _, generics, ..)
581 | hir::ItemKind::Impl(hir::Impl { generics, .. })
582 | hir::ItemKind::Fn(_, generics, _)
583 | hir::ItemKind::TyAlias(_, generics)
584 | hir::ItemKind::TraitAlias(generics, _)
585 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
588 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
589 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
592 // We skip the 0'th subst (self) because we do not want
593 // to consider the predicate as not suggestible if the
594 // self type is an arg position `impl Trait` -- instead,
595 // we handle that by adding ` + Bound` below.
596 // FIXME(compiler-errors): It would be nice to do the same
597 // this that we do in `suggest_restriction` and pull the
598 // `impl Trait` into a new generic if it shows up somewhere
599 // else in the predicate.
600 if !trait_pred.skip_binder().trait_ref.substs[1..]
602 .all(|g| g.is_suggestable(self.tcx, false))
606 // Missing generic type parameter bound.
607 let param_name = self_ty.to_string();
608 let mut constraint = with_no_trimmed_paths!(
609 trait_pred.print_modifiers_and_trait_path().to_string()
612 if let Some((name, term)) = associated_ty {
613 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
614 // That should be extracted into a helper function.
615 if constraint.ends_with('>') {
616 constraint = format!(
618 &constraint[..constraint.len() - 1],
623 constraint.push_str(&format!("<{} = {}>", name, term));
627 if suggest_constraining_type_param(
633 Some(trait_pred.def_id()),
639 hir::Node::Item(hir::Item {
641 hir::ItemKind::Struct(_, generics)
642 | hir::ItemKind::Enum(_, generics)
643 | hir::ItemKind::Union(_, generics)
644 | hir::ItemKind::Trait(_, _, generics, ..)
645 | hir::ItemKind::Impl(hir::Impl { generics, .. })
646 | hir::ItemKind::Fn(_, generics, _)
647 | hir::ItemKind::TyAlias(_, generics)
648 | hir::ItemKind::TraitAlias(generics, _)
649 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
652 // Missing generic type parameter bound.
653 if suggest_arbitrary_trait_bound(
663 hir::Node::Crate(..) => return,
668 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
672 /// When after several dereferencing, the reference satisfies the trait
673 /// binding. This function provides dereference suggestion for this
674 /// specific situation.
675 fn suggest_dereferences(
677 obligation: &PredicateObligation<'tcx>,
678 err: &mut Diagnostic,
679 trait_pred: ty::PolyTraitPredicate<'tcx>,
681 // It only make sense when suggesting dereferences for arguments
682 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code()
683 else { return false; };
684 let Some(typeck_results) = &self.typeck_results
685 else { return false; };
686 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
687 else { return false; };
688 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
689 else { return false; };
691 let span = obligation.cause.span;
692 let mut real_trait_pred = trait_pred;
693 let mut code = obligation.cause.code();
694 while let Some((parent_code, parent_trait_pred)) = code.parent() {
696 if let Some(parent_trait_pred) = parent_trait_pred {
697 real_trait_pred = parent_trait_pred;
700 let real_ty = real_trait_pred.self_ty();
701 // We `erase_late_bound_regions` here because `make_subregion` does not handle
702 // `ReLateBound`, and we don't particularly care about the regions.
704 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
710 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
711 let mut autoderef = Autoderef::new(
713 obligation.param_env,
714 obligation.cause.body_id,
718 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
720 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
722 // Remapping bound vars here
723 let real_trait_pred_and_ty =
724 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
725 let obligation = self.mk_trait_obligation_with_new_self_ty(
726 obligation.param_env,
727 real_trait_pred_and_ty,
729 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
732 // Don't care about `&mut` because `DerefMut` is used less
733 // often and user will not expect autoderef happens.
734 if let Some(hir::Node::Expr(hir::Expr {
736 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
738 })) = self.tcx.hir().find(*arg_hir_id)
740 let derefs = "*".repeat(steps);
741 err.span_suggestion_verbose(
742 expr.span.shrink_to_lo(),
743 "consider dereferencing here",
745 Applicability::MachineApplicable,
750 } else if real_trait_pred != trait_pred {
751 // This branch addresses #87437.
753 // Remapping bound vars here
754 let real_trait_pred_and_base_ty =
755 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
756 let obligation = self.mk_trait_obligation_with_new_self_ty(
757 obligation.param_env,
758 real_trait_pred_and_base_ty,
760 if self.predicate_may_hold(&obligation) {
761 err.span_suggestion_verbose(
763 "consider dereferencing here",
765 Applicability::MachineApplicable,
775 /// Given a closure's `DefId`, return the given name of the closure.
777 /// This doesn't account for reassignments, but it's only used for suggestions.
778 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
779 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
780 // Get the local name of this closure. This can be inaccurate because
781 // of the possibility of reassignment, but this should be good enough.
783 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
793 let hir = self.tcx.hir();
794 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
795 let parent_node = hir.get_parent_node(hir_id);
796 match hir.find(parent_node) {
797 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
798 get_name(err, &local.pat.kind)
800 // Different to previous arm because one is `&hir::Local` and the other
801 // is `P<hir::Local>`.
802 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
807 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
808 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
809 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
812 obligation: &PredicateObligation<'tcx>,
813 err: &mut Diagnostic,
814 trait_pred: ty::PolyTraitPredicate<'tcx>,
816 if let ty::PredicateKind::Trait(trait_pred) = obligation.predicate.kind().skip_binder()
817 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
819 // Don't suggest calling to turn an unsized type into a sized type
823 // This is duplicated from `extract_callable_info` in typeck, which
824 // relies on autoderef, so we can't use it here.
825 let found = trait_pred.self_ty().skip_binder().peel_refs();
826 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
828 ty::FnPtr(fn_sig) => {
829 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
831 ty::FnDef(def_id, _) => {
832 let fn_sig = found.fn_sig(self.tcx);
833 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
835 ty::Closure(def_id, substs) => {
836 let fn_sig = substs.as_closure().sig();
838 DefIdOrName::DefId(def_id),
840 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
843 ty::Opaque(def_id, substs) => {
844 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
845 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
846 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
847 // args tuple will always be substs[1]
848 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
851 DefIdOrName::DefId(def_id),
852 pred.kind().rebind(proj.term.ty().unwrap()),
853 pred.kind().rebind(args.as_slice()),
860 ty::Dynamic(data, _, ty::Dyn) => {
861 data.iter().find_map(|pred| {
862 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
863 && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
864 // for existential projection, substs are shifted over by 1
865 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
868 DefIdOrName::Name("trait object"),
869 pred.rebind(proj.term.ty().unwrap()),
870 pred.rebind(args.as_slice()),
878 obligation.param_env.caller_bounds().iter().find_map(|pred| {
879 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
880 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
881 && proj.projection_ty.self_ty() == found
882 // args tuple will always be substs[1]
883 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
886 DefIdOrName::Name("type parameter"),
887 pred.kind().rebind(proj.term.ty().unwrap()),
888 pred.kind().rebind(args.as_slice()),
896 }) else { return false; };
897 let output = self.replace_bound_vars_with_fresh_vars(
898 obligation.cause.span,
899 LateBoundRegionConversionTime::FnCall,
902 let inputs = inputs.skip_binder().iter().map(|ty| {
903 self.replace_bound_vars_with_fresh_vars(
904 obligation.cause.span,
905 LateBoundRegionConversionTime::FnCall,
910 // Remapping bound vars here
911 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
914 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
915 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
919 // Get the name of the callable and the arguments to be used in the suggestion.
920 let hir = self.tcx.hir();
922 let msg = match def_id_or_name {
923 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
924 DefKind::Ctor(CtorOf::Struct, _) => {
925 "use parentheses to construct this tuple struct".to_string()
927 DefKind::Ctor(CtorOf::Variant, _) => {
928 "use parentheses to construct this tuple variant".to_string()
930 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
932 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
937 if ty.is_suggestable(self.tcx, false) {
938 format!("/* {ty} */")
940 "/* value */".to_string()
946 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
947 && obligation.cause.span.can_be_used_for_suggestions()
949 // When the obligation error has been ensured to have been caused by
950 // an argument, the `obligation.cause.span` points at the expression
951 // of the argument, so we can provide a suggestion. Otherwise, we give
952 // a more general note.
953 err.span_suggestion_verbose(
954 obligation.cause.span.shrink_to_hi(),
957 Applicability::HasPlaceholders,
959 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
960 let name = match hir.get_if_local(def_id) {
961 Some(hir::Node::Expr(hir::Expr {
962 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
965 err.span_label(*fn_decl_span, "consider calling this closure");
966 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
971 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
972 err.span_label(ident.span, "consider calling this function");
975 Some(hir::Node::Ctor(..)) => {
976 let name = self.tcx.def_path_str(def_id);
978 self.tcx.def_span(def_id),
979 format!("consider calling the constructor for `{}`", name),
985 err.help(&format!("{msg}: `{name}({args})`"));
990 fn suggest_add_reference_to_arg(
992 obligation: &PredicateObligation<'tcx>,
993 err: &mut Diagnostic,
994 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
995 has_custom_message: bool,
997 let span = obligation.cause.span;
999 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
1000 obligation.cause.code()
1003 } else if let ObligationCauseCode::ItemObligation(_)
1004 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1006 obligation.cause.code()
1007 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1008 span.ctxt().outer_expn_data().kind
1010 obligation.cause.code()
1015 // List of traits for which it would be nonsensical to suggest borrowing.
1016 // For instance, immutable references are always Copy, so suggesting to
1017 // borrow would always succeed, but it's probably not what the user wanted.
1018 let mut never_suggest_borrow: Vec<_> =
1019 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1021 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1024 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1025 never_suggest_borrow.push(def_id);
1028 let param_env = obligation.param_env;
1030 // Try to apply the original trait binding obligation by borrowing.
1031 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1032 blacklist: &[DefId]|
1034 if blacklist.contains(&old_pred.def_id()) {
1037 // We map bounds to `&T` and `&mut T`
1038 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1041 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1044 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1047 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1051 let mk_result = |trait_pred_and_new_ty| {
1053 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1054 self.predicate_must_hold_modulo_regions(&obligation)
1056 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1057 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1059 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1060 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1061 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1064 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1065 matches!(mutability, hir::Mutability::Mut),
1071 if imm_ref_self_ty_satisfies_pred
1072 || mut_ref_self_ty_satisfies_pred
1073 || ref_inner_ty_satisfies_pred
1075 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1076 // We don't want a borrowing suggestion on the fields in structs,
1079 // the_foos: Vec<Foo>
1083 span.ctxt().outer_expn_data().kind,
1084 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1088 if snippet.starts_with('&') {
1089 // This is already a literal borrow and the obligation is failing
1090 // somewhere else in the obligation chain. Do not suggest non-sense.
1093 // We have a very specific type of error, where just borrowing this argument
1094 // might solve the problem. In cases like this, the important part is the
1095 // original type obligation, not the last one that failed, which is arbitrary.
1096 // Because of this, we modify the error to refer to the original obligation and
1097 // return early in the caller.
1099 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1100 if has_custom_message {
1104 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1109 "the trait `{}` is not implemented for `{}`",
1110 old_pred.print_modifiers_and_trait_path(),
1111 old_pred.self_ty().skip_binder(),
1115 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1116 err.span_suggestions(
1117 span.shrink_to_lo(),
1118 "consider borrowing here",
1119 ["&".to_string(), "&mut ".to_string()],
1120 Applicability::MaybeIncorrect,
1123 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1124 err.span_suggestion_verbose(
1125 span.shrink_to_lo(),
1127 "consider{} borrowing here",
1128 if is_mut { " mutably" } else { "" }
1130 format!("&{}", if is_mut { "mut " } else { "" }),
1131 Applicability::MaybeIncorrect,
1140 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1141 try_borrowing(cause.derived.parent_trait_pred, &[])
1142 } else if let ObligationCauseCode::BindingObligation(_, _)
1143 | ObligationCauseCode::ItemObligation(_)
1144 | ObligationCauseCode::ExprItemObligation(..)
1145 | ObligationCauseCode::ExprBindingObligation(..) = code
1147 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1153 // Suggest borrowing the type
1154 fn suggest_borrowing_for_object_cast(
1156 err: &mut Diagnostic,
1157 obligation: &PredicateObligation<'tcx>,
1159 object_ty: Ty<'tcx>,
1161 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1162 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1164 for predicate in predicates.iter() {
1165 if !self.predicate_must_hold_modulo_regions(
1166 &obligation.with(predicate.with_self_ty(self.tcx, self_ref_ty)),
1172 err.span_suggestion(
1173 obligation.cause.span.shrink_to_lo(),
1175 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1178 Applicability::MaybeIncorrect,
1182 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1183 /// suggest removing these references until we reach a type that implements the trait.
1184 fn suggest_remove_reference(
1186 obligation: &PredicateObligation<'tcx>,
1187 err: &mut Diagnostic,
1188 trait_pred: ty::PolyTraitPredicate<'tcx>,
1190 let span = obligation.cause.span;
1192 let mut suggested = false;
1193 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1195 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1196 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1197 // Do not suggest removal of borrow from type arguments.
1201 // Skipping binder here, remapping below
1202 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1204 for refs_remaining in 0..refs_number {
1205 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1208 suggested_ty = *inner_ty;
1210 // Remapping bound vars here
1211 let trait_pred_and_suggested_ty =
1212 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1214 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1215 obligation.param_env,
1216 trait_pred_and_suggested_ty,
1219 if self.predicate_may_hold(&new_obligation) {
1224 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1226 let remove_refs = refs_remaining + 1;
1228 let msg = if remove_refs == 1 {
1229 "consider removing the leading `&`-reference".to_string()
1231 format!("consider removing {} leading `&`-references", remove_refs)
1234 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1243 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1244 let span = obligation.cause.span;
1246 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1247 let hir = self.tcx.hir();
1248 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1249 if let hir::Node::Expr(expr) = node {
1250 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1251 // and if not maybe suggest doing something else? If we kept the expression around we
1252 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1253 // it is from the local crate.
1254 err.span_suggestion(
1256 "remove the `.await`",
1258 Applicability::MachineApplicable,
1260 // FIXME: account for associated `async fn`s.
1261 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1262 if let ty::PredicateKind::Trait(pred) =
1263 obligation.predicate.kind().skip_binder()
1267 &format!("this call returns `{}`", pred.self_ty()),
1270 if let Some(typeck_results) = &self.typeck_results
1271 && let ty = typeck_results.expr_ty_adjusted(base)
1272 && let ty::FnDef(def_id, _substs) = ty.kind()
1273 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1274 hir.get_if_local(*def_id)
1277 "alternatively, consider making `fn {}` asynchronous",
1280 if vis_span.is_empty() {
1281 err.span_suggestion_verbose(
1282 span.shrink_to_lo(),
1285 Applicability::MaybeIncorrect,
1288 err.span_suggestion_verbose(
1289 vis_span.shrink_to_hi(),
1292 Applicability::MaybeIncorrect,
1302 /// Check if the trait bound is implemented for a different mutability and note it in the
1304 fn suggest_change_mut(
1306 obligation: &PredicateObligation<'tcx>,
1307 err: &mut Diagnostic,
1308 trait_pred: ty::PolyTraitPredicate<'tcx>,
1310 let points_at_arg = matches!(
1311 obligation.cause.code(),
1312 ObligationCauseCode::FunctionArgumentObligation { .. },
1315 let span = obligation.cause.span;
1316 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1318 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1319 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1320 // Do not suggest removal of borrow from type arguments.
1323 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1324 if trait_pred.has_non_region_infer() {
1325 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1326 // unresolved bindings.
1330 // Skipping binder here, remapping below
1331 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1333 let suggested_ty = match mutability {
1334 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1335 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1338 // Remapping bound vars here
1339 let trait_pred_and_suggested_ty =
1340 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1342 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1343 obligation.param_env,
1344 trait_pred_and_suggested_ty,
1346 let suggested_ty_would_satisfy_obligation = self
1347 .evaluate_obligation_no_overflow(&new_obligation)
1348 .must_apply_modulo_regions();
1349 if suggested_ty_would_satisfy_obligation {
1354 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1355 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1356 err.span_suggestion_verbose(
1358 "consider changing this borrow's mutability",
1360 Applicability::MachineApplicable,
1364 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1365 trait_pred.print_modifiers_and_trait_path(),
1367 trait_pred.skip_binder().self_ty(),
1375 fn suggest_semicolon_removal(
1377 obligation: &PredicateObligation<'tcx>,
1378 err: &mut Diagnostic,
1380 trait_pred: ty::PolyTraitPredicate<'tcx>,
1382 let hir = self.tcx.hir();
1383 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1384 let node = hir.find(parent_node);
1385 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1386 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1387 && sig.decl.output.span().overlaps(span)
1388 && blk.expr.is_none()
1389 && trait_pred.self_ty().skip_binder().is_unit()
1390 && let Some(stmt) = blk.stmts.last()
1391 && let hir::StmtKind::Semi(expr) = stmt.kind
1392 // Only suggest this if the expression behind the semicolon implements the predicate
1393 && let Some(typeck_results) = &self.typeck_results
1394 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1395 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1396 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1402 "this expression has type `{}`, which implements `{}`",
1404 trait_pred.print_modifiers_and_trait_path()
1407 err.span_suggestion(
1408 self.tcx.sess.source_map().end_point(stmt.span),
1409 "remove this semicolon",
1411 Applicability::MachineApplicable
1418 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1419 let hir = self.tcx.hir();
1420 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1421 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1425 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1428 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1429 /// applicable and signal that the error has been expanded appropriately and needs to be
1431 fn suggest_impl_trait(
1433 err: &mut Diagnostic,
1435 obligation: &PredicateObligation<'tcx>,
1436 trait_pred: ty::PolyTraitPredicate<'tcx>,
1438 match obligation.cause.code().peel_derives() {
1439 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1440 ObligationCauseCode::SizedReturnType => {}
1444 let hir = self.tcx.hir();
1445 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1446 let node = hir.find(fn_hir_id);
1447 let Some(hir::Node::Item(hir::Item {
1448 kind: hir::ItemKind::Fn(sig, _, body_id),
1454 let body = hir.body(*body_id);
1455 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1456 let ty = trait_pred.skip_binder().self_ty();
1457 let is_object_safe = match ty.kind() {
1458 ty::Dynamic(predicates, _, ty::Dyn) => {
1459 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1462 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1464 // We only want to suggest `impl Trait` to `dyn Trait`s.
1465 // For example, `fn foo() -> str` needs to be filtered out.
1469 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1473 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1474 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1475 // Recursively look for `TraitObject` types and if there's only one, use that span to
1476 // suggest `impl Trait`.
1478 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1479 // otherwise suggest using `Box<dyn Trait>` or an enum.
1480 let mut visitor = ReturnsVisitor::default();
1481 visitor.visit_body(&body);
1483 let typeck_results = self.typeck_results.as_ref().unwrap();
1484 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1486 let ret_types = visitor
1489 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1490 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1491 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1493 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1495 let ty = self.resolve_vars_if_possible(ty);
1497 !matches!(ty.kind(), ty::Error(_))
1498 && last_ty.map_or(true, |last_ty| {
1499 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1500 // *after* in the dependency graph.
1501 match (ty.kind(), last_ty.kind()) {
1502 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1503 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1504 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1506 Infer(InferTy::FreshFloatTy(_)),
1507 Infer(InferTy::FreshFloatTy(_)),
1512 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1515 let mut spans_and_needs_box = vec![];
1517 match liberated_sig.output().kind() {
1518 ty::Dynamic(predicates, _, ty::Dyn) => {
1519 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1520 let param_env = ty::ParamEnv::empty();
1522 if !only_never_return {
1523 for (expr_span, return_ty) in ret_types {
1524 let self_ty_satisfies_dyn_predicates = |self_ty| {
1525 predicates.iter().all(|predicate| {
1526 let pred = predicate.with_self_ty(self.tcx, self_ty);
1527 let obl = Obligation::new(cause.clone(), param_env, pred);
1528 self.predicate_may_hold(&obl)
1532 if let ty::Adt(def, substs) = return_ty.kind()
1534 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1536 spans_and_needs_box.push((expr_span, false));
1537 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1538 spans_and_needs_box.push((expr_span, true));
1548 let sm = self.tcx.sess.source_map();
1549 if !ret_ty.span.overlaps(span) {
1552 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1553 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1559 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1560 let name = liberated_sig.output().to_string();
1562 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1563 if !name.starts_with("dyn ") {
1569 err.code(error_code!(E0746));
1570 err.set_primary_message("return type cannot have an unboxed trait object");
1571 err.children.clear();
1572 let impl_trait_msg = "for information on `impl Trait`, see \
1573 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1574 #returning-types-that-implement-traits>";
1575 let trait_obj_msg = "for information on trait objects, see \
1576 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1577 #using-trait-objects-that-allow-for-values-of-different-types>";
1579 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1580 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1581 if only_never_return {
1582 // No return paths, probably using `panic!()` or similar.
1583 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1584 suggest_trait_object_return_type_alternatives(
1590 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1591 // Suggest `-> impl Trait`.
1592 err.span_suggestion(
1595 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1596 which implements `{1}`",
1599 format!("impl {}", trait_obj),
1600 Applicability::MachineApplicable,
1602 err.note(impl_trait_msg);
1605 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1606 err.multipart_suggestion(
1607 "return a boxed trait object instead",
1609 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1610 (span.shrink_to_hi(), ">".to_string()),
1612 Applicability::MaybeIncorrect,
1614 for (span, needs_box) in spans_and_needs_box {
1616 err.multipart_suggestion(
1617 "... and box this value",
1619 (span.shrink_to_lo(), "Box::new(".to_string()),
1620 (span.shrink_to_hi(), ")".to_string()),
1622 Applicability::MaybeIncorrect,
1627 // This is currently not possible to trigger because E0038 takes precedence, but
1628 // leave it in for completeness in case anything changes in an earlier stage.
1630 "if trait `{}` were object-safe, you could return a trait object",
1634 err.note(trait_obj_msg);
1636 "if all the returned values were of the same type you could use `impl {}` as the \
1640 err.note(impl_trait_msg);
1641 err.note("you can create a new `enum` with a variant for each returned type");
1646 fn point_at_returns_when_relevant(
1648 err: &mut Diagnostic,
1649 obligation: &PredicateObligation<'tcx>,
1651 match obligation.cause.code().peel_derives() {
1652 ObligationCauseCode::SizedReturnType => {}
1656 let hir = self.tcx.hir();
1657 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1658 let node = hir.find(parent_node);
1659 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1662 let body = hir.body(*body_id);
1663 // Point at all the `return`s in the function as they have failed trait bounds.
1664 let mut visitor = ReturnsVisitor::default();
1665 visitor.visit_body(&body);
1666 let typeck_results = self.typeck_results.as_ref().unwrap();
1667 for expr in &visitor.returns {
1668 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1669 let ty = self.resolve_vars_if_possible(returned_ty);
1670 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1676 fn report_closure_arg_mismatch(
1679 found_span: Option<Span>,
1680 found: ty::PolyTraitRef<'tcx>,
1681 expected: ty::PolyTraitRef<'tcx>,
1682 cause: &ObligationCauseCode<'tcx>,
1683 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1684 pub(crate) fn build_fn_sig_ty<'tcx>(
1685 infcx: &InferCtxt<'tcx>,
1686 trait_ref: ty::PolyTraitRef<'tcx>,
1688 let inputs = trait_ref.skip_binder().substs.type_at(1);
1689 let sig = match inputs.kind() {
1691 if infcx.tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1693 infcx.tcx.mk_fn_sig(
1695 infcx.next_ty_var(TypeVariableOrigin {
1697 kind: TypeVariableOriginKind::MiscVariable,
1700 hir::Unsafety::Normal,
1704 _ => infcx.tcx.mk_fn_sig(
1705 std::iter::once(inputs),
1706 infcx.next_ty_var(TypeVariableOrigin {
1708 kind: TypeVariableOriginKind::MiscVariable,
1711 hir::Unsafety::Normal,
1716 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1719 let argument_kind = match expected.skip_binder().self_ty().kind() {
1720 ty::Closure(..) => "closure",
1721 ty::Generator(..) => "generator",
1724 let mut err = struct_span_err!(
1728 "type mismatch in {argument_kind} arguments",
1731 err.span_label(span, "expected due to this");
1733 let found_span = found_span.unwrap_or(span);
1734 err.span_label(found_span, "found signature defined here");
1736 let expected = build_fn_sig_ty(self, expected);
1737 let found = build_fn_sig_ty(self, found);
1739 let (expected_str, found_str) = self.cmp(expected, found);
1741 let signature_kind = format!("{argument_kind} signature");
1742 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1744 self.note_conflicting_closure_bounds(cause, &mut err);
1749 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1750 // requirements, which will always cause a closure to have a type error.
1751 fn note_conflicting_closure_bounds(
1753 cause: &ObligationCauseCode<'tcx>,
1754 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1756 // First, look for an `ExprBindingObligation`, which means we can get
1757 // the unsubstituted predicate list of the called function. And check
1758 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1759 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1760 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1761 && let Some(pred) = predicates.predicates.get(*idx)
1762 && let ty::PredicateKind::Trait(trait_pred) = pred.kind().skip_binder()
1763 && ty::ClosureKind::from_def_id(self.tcx, trait_pred.def_id()).is_some()
1766 self.tcx.anonymize_late_bound_regions(pred.kind().rebind(trait_pred.self_ty()));
1767 let expected_substs = self
1769 .anonymize_late_bound_regions(pred.kind().rebind(trait_pred.trait_ref.substs));
1771 // Find another predicate whose self-type is equal to the expected self type,
1772 // but whose substs don't match.
1773 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1775 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1776 ty::PredicateKind::Trait(trait_pred)
1777 if ty::ClosureKind::from_def_id(self.tcx, trait_pred.def_id())
1780 // Make sure that the self type matches
1781 // (i.e. constraining this closure)
1783 == self.tcx.anonymize_late_bound_regions(
1784 pred.kind().rebind(trait_pred.self_ty()),
1786 // But the substs don't match (i.e. incompatible args)
1788 != self.tcx.anonymize_late_bound_regions(
1789 pred.kind().rebind(trait_pred.trait_ref.substs),
1796 // If we found one, then it's very likely the cause of the error.
1797 if let Some((_, (_, other_pred_span))) = other_pred {
1800 "closure inferred to have a different signature due to this bound",
1806 fn suggest_fully_qualified_path(
1808 err: &mut Diagnostic,
1813 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1814 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1816 "{}s cannot be accessed directly on a `trait`, they can only be \
1817 accessed through a specific `impl`",
1818 assoc_item.kind.as_def_kind().descr(item_def_id)
1820 err.span_suggestion(
1822 "use the fully qualified path to an implementation",
1823 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1824 Applicability::HasPlaceholders,
1830 /// Adds an async-await specific note to the diagnostic when the future does not implement
1831 /// an auto trait because of a captured type.
1834 /// note: future does not implement `Qux` as this value is used across an await
1835 /// --> $DIR/issue-64130-3-other.rs:17:5
1837 /// LL | let x = Foo;
1838 /// | - has type `Foo`
1839 /// LL | baz().await;
1840 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1842 /// | - `x` is later dropped here
1845 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1846 /// is "replaced" with a different message and a more specific error.
1849 /// error: future cannot be sent between threads safely
1850 /// --> $DIR/issue-64130-2-send.rs:21:5
1852 /// LL | fn is_send<T: Send>(t: T) { }
1853 /// | ---- required by this bound in `is_send`
1855 /// LL | is_send(bar());
1856 /// | ^^^^^^^ future returned by `bar` is not send
1858 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1859 /// implemented for `Foo`
1860 /// note: future is not send as this value is used across an await
1861 /// --> $DIR/issue-64130-2-send.rs:15:5
1863 /// LL | let x = Foo;
1864 /// | - has type `Foo`
1865 /// LL | baz().await;
1866 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1868 /// | - `x` is later dropped here
1871 /// Returns `true` if an async-await specific note was added to the diagnostic.
1872 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1873 fn maybe_note_obligation_cause_for_async_await(
1875 err: &mut Diagnostic,
1876 obligation: &PredicateObligation<'tcx>,
1878 let hir = self.tcx.hir();
1880 // Attempt to detect an async-await error by looking at the obligation causes, looking
1881 // for a generator to be present.
1883 // When a future does not implement a trait because of a captured type in one of the
1884 // generators somewhere in the call stack, then the result is a chain of obligations.
1886 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1887 // future is passed as an argument to a function C which requires a `Send` type, then the
1888 // chain looks something like this:
1890 // - `BuiltinDerivedObligation` with a generator witness (B)
1891 // - `BuiltinDerivedObligation` with a generator (B)
1892 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1893 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1894 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1895 // - `BuiltinDerivedObligation` with a generator witness (A)
1896 // - `BuiltinDerivedObligation` with a generator (A)
1897 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1898 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1899 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1900 // - `BindingObligation` with `impl_send (Send requirement)
1902 // The first obligation in the chain is the most useful and has the generator that captured
1903 // the type. The last generator (`outer_generator` below) has information about where the
1904 // bound was introduced. At least one generator should be present for this diagnostic to be
1906 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1907 ty::PredicateKind::Trait(p) => (Some(p), Some(p.self_ty())),
1910 let mut generator = None;
1911 let mut outer_generator = None;
1912 let mut next_code = Some(obligation.cause.code());
1914 let mut seen_upvar_tys_infer_tuple = false;
1916 while let Some(code) = next_code {
1919 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1920 next_code = Some(parent_code);
1922 ObligationCauseCode::ImplDerivedObligation(cause) => {
1923 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1925 parent_trait_ref = ?cause.derived.parent_trait_pred,
1926 self_ty.kind = ?ty.kind(),
1931 ty::Generator(did, ..) => {
1932 generator = generator.or(Some(did));
1933 outer_generator = Some(did);
1935 ty::GeneratorWitness(..) => {}
1936 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1937 // By introducing a tuple of upvar types into the chain of obligations
1938 // of a generator, the first non-generator item is now the tuple itself,
1939 // we shall ignore this.
1941 seen_upvar_tys_infer_tuple = true;
1943 _ if generator.is_none() => {
1944 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1945 target_ty = Some(ty);
1950 next_code = Some(&cause.derived.parent_code);
1952 ObligationCauseCode::DerivedObligation(derived_obligation)
1953 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1954 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1956 parent_trait_ref = ?derived_obligation.parent_trait_pred,
1957 self_ty.kind = ?ty.kind(),
1961 ty::Generator(did, ..) => {
1962 generator = generator.or(Some(did));
1963 outer_generator = Some(did);
1965 ty::GeneratorWitness(..) => {}
1966 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1967 // By introducing a tuple of upvar types into the chain of obligations
1968 // of a generator, the first non-generator item is now the tuple itself,
1969 // we shall ignore this.
1971 seen_upvar_tys_infer_tuple = true;
1973 _ if generator.is_none() => {
1974 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1975 target_ty = Some(ty);
1980 next_code = Some(&derived_obligation.parent_code);
1986 // Only continue if a generator was found.
1987 debug!(?generator, ?trait_ref, ?target_ty);
1988 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1992 let span = self.tcx.def_span(generator_did);
1994 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1997 ?generator_did_root,
1998 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2002 let generator_body = generator_did
2004 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2005 .map(|body_id| hir.body(body_id));
2006 let is_async = match generator_did.as_local() {
2007 Some(_) => generator_body
2008 .and_then(|body| body.generator_kind())
2009 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
2013 .generator_kind(generator_did)
2014 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
2017 let mut visitor = AwaitsVisitor::default();
2018 if let Some(body) = generator_body {
2019 visitor.visit_body(body);
2021 debug!(awaits = ?visitor.awaits);
2023 // Look for a type inside the generator interior that matches the target type to get
2025 let target_ty_erased = self.tcx.erase_regions(target_ty);
2026 let ty_matches = |ty| -> bool {
2027 // Careful: the regions for types that appear in the
2028 // generator interior are not generally known, so we
2029 // want to erase them when comparing (and anyway,
2030 // `Send` and other bounds are generally unaffected by
2031 // the choice of region). When erasing regions, we
2032 // also have to erase late-bound regions. This is
2033 // because the types that appear in the generator
2034 // interior generally contain "bound regions" to
2035 // represent regions that are part of the suspended
2036 // generator frame. Bound regions are preserved by
2037 // `erase_regions` and so we must also call
2038 // `erase_late_bound_regions`.
2039 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2040 let ty_erased = self.tcx.erase_regions(ty_erased);
2041 let eq = ty_erased == target_ty_erased;
2042 debug!(?ty_erased, ?target_ty_erased, ?eq);
2046 let mut interior_or_upvar_span = None;
2047 let mut interior_extra_info = None;
2049 // Get the typeck results from the infcx if the generator is the function we are currently
2050 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2051 // cycles. If we can't use resolved types because the generator comes from another crate,
2052 // we still provide a targeted error but without all the relevant spans.
2053 let generator_data: Option<GeneratorData<'tcx, '_>> = match &self.typeck_results {
2054 Some(t) if t.hir_owner.to_def_id() == generator_did_root => {
2055 Some(GeneratorData::Local(&t))
2057 _ if generator_did.is_local() => {
2058 Some(GeneratorData::Local(self.tcx.typeck(generator_did.expect_local())))
2062 .generator_diagnostic_data(generator_did)
2064 .map(|generator_diag_data| GeneratorData::Foreign(generator_diag_data)),
2067 if let Some(generator_data) = generator_data.as_ref() {
2068 interior_or_upvar_span =
2069 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2071 // The generator interior types share the same binders
2072 if let Some(cause) =
2073 generator_data.get_generator_interior_types().skip_binder().iter().find(
2074 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2075 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2079 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2080 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
2083 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
2084 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
2087 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2088 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span));
2092 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2093 let typeck_results = generator_data.and_then(|generator_data| match generator_data {
2094 GeneratorData::Local(typeck_results) => Some(typeck_results),
2095 GeneratorData::Foreign(_) => None,
2097 self.note_obligation_cause_for_async_await(
2099 interior_or_upvar_span,
2100 interior_extra_info,
2115 /// Unconditionally adds the diagnostic note described in
2116 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2117 #[instrument(level = "debug", skip_all)]
2118 fn note_obligation_cause_for_async_await(
2120 err: &mut Diagnostic,
2121 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2122 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
2124 outer_generator: Option<DefId>,
2125 trait_pred: ty::TraitPredicate<'tcx>,
2126 target_ty: Ty<'tcx>,
2127 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2128 obligation: &PredicateObligation<'tcx>,
2129 next_code: Option<&ObligationCauseCode<'tcx>>,
2131 let source_map = self.tcx.sess.source_map();
2133 let (await_or_yield, an_await_or_yield) =
2134 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2135 let future_or_generator = if is_async { "future" } else { "generator" };
2137 // Special case the primary error message when send or sync is the trait that was
2139 let hir = self.tcx.hir();
2140 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2141 self.tcx.get_diagnostic_name(trait_pred.def_id())
2143 let (trait_name, trait_verb) =
2144 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2147 err.set_primary_message(format!(
2148 "{} cannot be {} between threads safely",
2149 future_or_generator, trait_verb
2152 let original_span = err.span.primary_span().unwrap();
2153 let mut span = MultiSpan::from_span(original_span);
2155 let message = outer_generator
2156 .and_then(|generator_did| {
2157 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2158 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2159 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2161 .parent(generator_did)
2163 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2164 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2166 format!("future returned by `{}` is not {}", name, trait_name)
2168 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2169 format!("future created by async block is not {}", trait_name)
2171 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2172 format!("future created by async closure is not {}", trait_name)
2176 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2178 span.push_span_label(original_span, message);
2181 format!("is not {}", trait_name)
2183 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2186 let mut explain_yield = |interior_span: Span,
2188 scope_span: Option<Span>| {
2189 let mut span = MultiSpan::from_span(yield_span);
2190 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
2191 // #70935: If snippet contains newlines, display "the value" instead
2192 // so that we do not emit complex diagnostics.
2193 let snippet = &format!("`{}`", snippet);
2194 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
2195 // note: future is not `Send` as this value is used across an await
2196 // --> $DIR/issue-70935-complex-spans.rs:13:9
2198 // LL | baz(|| async {
2199 // | ______________-
2202 // LL | | foo(tx.clone());
2204 // | | - ^^^^^^ await occurs here, with value maybe used later
2206 // | has type `closure` which is not `Send`
2207 // note: value is later dropped here
2211 span.push_span_label(
2213 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2215 span.push_span_label(
2217 format!("has type `{}` which {}", target_ty, trait_explanation),
2219 // If available, use the scope span to annotate the drop location.
2220 let mut scope_note = None;
2221 if let Some(scope_span) = scope_span {
2222 let scope_span = source_map.end_point(scope_span);
2224 let msg = format!("{} is later dropped here", snippet);
2225 if source_map.is_multiline(yield_span.between(scope_span)) {
2226 span.push_span_label(scope_span, msg);
2228 scope_note = Some((scope_span, msg));
2234 "{} {} as this value is used across {}",
2235 future_or_generator, trait_explanation, an_await_or_yield
2238 if let Some((span, msg)) = scope_note {
2239 err.span_note(span, &msg);
2243 match interior_or_upvar_span {
2244 GeneratorInteriorOrUpvar::Interior(interior_span) => {
2245 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2246 if let Some(await_span) = from_awaited_ty {
2247 // The type causing this obligation is one being awaited at await_span.
2248 let mut span = MultiSpan::from_span(await_span);
2249 span.push_span_label(
2252 "await occurs here on type `{}`, which {}",
2253 target_ty, trait_explanation
2259 "future {not_trait} as it awaits another future which {not_trait}",
2260 not_trait = trait_explanation
2264 // Look at the last interior type to get a span for the `.await`.
2266 generator_interior_types = ?format_args!(
2267 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2270 explain_yield(interior_span, yield_span, scope_span);
2273 if let Some(expr_id) = expr {
2274 let expr = hir.expect_expr(expr_id);
2275 debug!("target_ty evaluated from {:?}", expr);
2277 let parent = hir.get_parent_node(expr_id);
2278 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2279 let parent_span = hir.span(parent);
2280 let parent_did = parent.owner.to_def_id();
2283 // fn foo(&self) -> i32 {}
2286 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2289 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2291 .expr_adjustments(expr)
2293 .any(|adj| adj.is_region_borrow())
2299 // struct Foo(*const u8);
2300 // bar(Foo(std::ptr::null())).await;
2301 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2303 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2304 let is_raw_borrow_inside_fn_like_call =
2305 match self.tcx.def_kind(parent_did) {
2306 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2309 if let Some(typeck_results) = typeck_results {
2310 if (typeck_results.is_method_call(e) && is_region_borrow)
2311 || is_raw_borrow_inside_fn_like_call
2315 "consider moving this into a `let` \
2316 binding to create a shorter lived borrow",
2324 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2325 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2326 let refers_to_non_sync = match target_ty.kind() {
2327 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2328 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2334 let (span_label, span_note) = match refers_to_non_sync {
2335 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2336 // include suggestions to make `T: Sync` so that `&T: Send`
2339 "has type `{}` which {}, because `{}` is not `Sync`",
2340 target_ty, trait_explanation, ref_ty
2343 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2348 format!("has type `{}` which {}", target_ty, trait_explanation),
2349 format!("captured value {}", trait_explanation),
2353 let mut span = MultiSpan::from_span(upvar_span);
2354 span.push_span_label(upvar_span, span_label);
2355 err.span_note(span, &span_note);
2359 // Add a note for the item obligation that remains - normally a note pointing to the
2360 // bound that introduced the obligation (e.g. `T: Send`).
2362 self.note_obligation_cause_code(
2364 &obligation.predicate,
2365 obligation.param_env,
2368 &mut Default::default(),
2372 fn note_obligation_cause_code<T>(
2374 err: &mut Diagnostic,
2376 param_env: ty::ParamEnv<'tcx>,
2377 cause_code: &ObligationCauseCode<'tcx>,
2378 obligated_types: &mut Vec<Ty<'tcx>>,
2379 seen_requirements: &mut FxHashSet<DefId>,
2385 ObligationCauseCode::ExprAssignable
2386 | ObligationCauseCode::MatchExpressionArm { .. }
2387 | ObligationCauseCode::Pattern { .. }
2388 | ObligationCauseCode::IfExpression { .. }
2389 | ObligationCauseCode::IfExpressionWithNoElse
2390 | ObligationCauseCode::MainFunctionType
2391 | ObligationCauseCode::StartFunctionType
2392 | ObligationCauseCode::IntrinsicType
2393 | ObligationCauseCode::MethodReceiver
2394 | ObligationCauseCode::ReturnNoExpression
2395 | ObligationCauseCode::UnifyReceiver(..)
2396 | ObligationCauseCode::OpaqueType
2397 | ObligationCauseCode::MiscObligation
2398 | ObligationCauseCode::WellFormed(..)
2399 | ObligationCauseCode::MatchImpl(..)
2400 | ObligationCauseCode::ReturnType
2401 | ObligationCauseCode::ReturnValue(_)
2402 | ObligationCauseCode::BlockTailExpression(_)
2403 | ObligationCauseCode::AwaitableExpr(_)
2404 | ObligationCauseCode::ForLoopIterator
2405 | ObligationCauseCode::QuestionMark
2406 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2407 | ObligationCauseCode::LetElse
2408 | ObligationCauseCode::BinOp { .. }
2409 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2410 | ObligationCauseCode::RustCall => {}
2411 ObligationCauseCode::SliceOrArrayElem => {
2412 err.note("slice and array elements must have `Sized` type");
2414 ObligationCauseCode::TupleElem => {
2415 err.note("only the last element of a tuple may have a dynamically sized type");
2417 ObligationCauseCode::ProjectionWf(data) => {
2418 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2420 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2422 "required so that reference `{}` does not outlive its referent",
2426 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2428 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2432 ObligationCauseCode::ItemObligation(_)
2433 | ObligationCauseCode::ExprItemObligation(..) => {
2434 // We hold the `DefId` of the item introducing the obligation, but displaying it
2435 // doesn't add user usable information. It always point at an associated item.
2437 ObligationCauseCode::BindingObligation(item_def_id, span)
2438 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2439 let item_name = tcx.def_path_str(item_def_id);
2440 let mut multispan = MultiSpan::from(span);
2441 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2442 let sm = tcx.sess.source_map();
2444 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2445 (Ok(l), Ok(r)) => l.line == r.line,
2448 if !ident.span.overlaps(span) && !same_line {
2449 multispan.push_span_label(ident.span, "required by a bound in this");
2452 let descr = format!("required by a bound in `{}`", item_name);
2453 if span != DUMMY_SP {
2454 let msg = format!("required by this bound in `{}`", item_name);
2455 multispan.push_span_label(span, msg);
2456 err.span_note(multispan, &descr);
2458 err.span_note(tcx.def_span(item_def_id), &descr);
2461 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2463 "required for the cast from `{}` to the object type `{}`",
2464 self.ty_to_string(concrete_ty),
2465 self.ty_to_string(object_ty)
2468 ObligationCauseCode::Coercion { source: _, target } => {
2469 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2471 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2473 "the `Copy` trait is required because this value will be copied for each element of the array",
2478 "consider creating a new `const` item and initializing it with the result \
2479 of the function call to be used in the repeat position, like \
2480 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2484 if self.tcx.sess.is_nightly_build() && is_const_fn {
2486 "create an inline `const` block, see RFC #2920 \
2487 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2491 ObligationCauseCode::VariableType(hir_id) => {
2492 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2493 match self.tcx.hir().find(parent_node) {
2494 Some(Node::Local(hir::Local {
2495 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2498 // When encountering an assignment of an unsized trait, like
2499 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2500 // order to use have a slice instead.
2501 err.span_suggestion_verbose(
2502 span.shrink_to_lo(),
2503 "consider borrowing here",
2505 Applicability::MachineApplicable,
2507 err.note("all local variables must have a statically known size");
2509 Some(Node::Param(param)) => {
2510 err.span_suggestion_verbose(
2511 param.ty_span.shrink_to_lo(),
2512 "function arguments must have a statically known size, borrowed types \
2513 always have a known size",
2515 Applicability::MachineApplicable,
2519 err.note("all local variables must have a statically known size");
2522 if !self.tcx.features().unsized_locals {
2523 err.help("unsized locals are gated as an unstable feature");
2526 ObligationCauseCode::SizedArgumentType(sp) => {
2527 if let Some(span) = sp {
2528 err.span_suggestion_verbose(
2529 span.shrink_to_lo(),
2530 "function arguments must have a statically known size, borrowed types \
2531 always have a known size",
2533 Applicability::MachineApplicable,
2536 err.note("all function arguments must have a statically known size");
2538 if tcx.sess.opts.unstable_features.is_nightly_build()
2539 && !self.tcx.features().unsized_fn_params
2541 err.help("unsized fn params are gated as an unstable feature");
2544 ObligationCauseCode::SizedReturnType => {
2545 err.note("the return type of a function must have a statically known size");
2547 ObligationCauseCode::SizedYieldType => {
2548 err.note("the yield type of a generator must have a statically known size");
2550 ObligationCauseCode::SizedBoxType => {
2551 err.note("the type of a box expression must have a statically known size");
2553 ObligationCauseCode::AssignmentLhsSized => {
2554 err.note("the left-hand-side of an assignment must have a statically known size");
2556 ObligationCauseCode::TupleInitializerSized => {
2557 err.note("tuples must have a statically known size to be initialized");
2559 ObligationCauseCode::StructInitializerSized => {
2560 err.note("structs must have a statically known size to be initialized");
2562 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2564 AdtKind::Struct => {
2567 "the last field of a packed struct may only have a \
2568 dynamically sized type if it does not need drop to be run",
2572 "only the last field of a struct may have a dynamically sized type",
2577 err.note("no field of a union may have a dynamically sized type");
2580 err.note("no field of an enum variant may have a dynamically sized type");
2583 err.help("change the field's type to have a statically known size");
2584 err.span_suggestion(
2585 span.shrink_to_lo(),
2586 "borrowed types always have a statically known size",
2588 Applicability::MachineApplicable,
2590 err.multipart_suggestion(
2591 "the `Box` type always has a statically known size and allocates its contents \
2594 (span.shrink_to_lo(), "Box<".to_string()),
2595 (span.shrink_to_hi(), ">".to_string()),
2597 Applicability::MachineApplicable,
2600 ObligationCauseCode::ConstSized => {
2601 err.note("constant expressions must have a statically known size");
2603 ObligationCauseCode::InlineAsmSized => {
2604 err.note("all inline asm arguments must have a statically known size");
2606 ObligationCauseCode::ConstPatternStructural => {
2607 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2609 ObligationCauseCode::SharedStatic => {
2610 err.note("shared static variables must have a type that implements `Sync`");
2612 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2613 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2614 let ty = parent_trait_ref.skip_binder().self_ty();
2615 if parent_trait_ref.references_error() {
2616 // NOTE(eddyb) this was `.cancel()`, but `err`
2617 // is borrowed, so we can't fully defuse it.
2618 err.downgrade_to_delayed_bug();
2622 // If the obligation for a tuple is set directly by a Generator or Closure,
2623 // then the tuple must be the one containing capture types.
2624 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2627 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2629 let parent_trait_ref =
2630 self.resolve_vars_if_possible(data.parent_trait_pred);
2631 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2632 matches!(nested_ty.kind(), ty::Generator(..))
2633 || matches!(nested_ty.kind(), ty::Closure(..))
2639 let from_generator = tcx.lang_items().from_generator_fn().unwrap();
2641 // Don't print the tuple of capture types
2643 if !is_upvar_tys_infer_tuple {
2644 let msg = format!("required because it appears within the type `{}`", ty);
2646 ty::Adt(def, _) => {
2647 // `gen_future` is used in all async functions; it doesn't add any additional info.
2648 if self.tcx.is_diagnostic_item(sym::gen_future, def.did()) {
2651 match self.tcx.opt_item_ident(def.did()) {
2652 Some(ident) => err.span_note(ident.span, &msg),
2653 None => err.note(&msg),
2656 ty::Opaque(def_id, _) => {
2657 // Avoid printing the future from `core::future::from_generator`, it's not helpful
2658 if tcx.parent(*def_id) == from_generator {
2662 // If the previous type is `from_generator`, this is the future generated by the body of an async function.
2663 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2664 let is_future = tcx.ty_is_opaque_future(ty);
2668 "note_obligation_cause_code: check for async fn"
2671 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2672 ty::Opaque(last_def_id, _) => {
2673 tcx.parent(*last_def_id) == from_generator
2680 err.span_note(self.tcx.def_span(def_id), &msg)
2682 ty::GeneratorWitness(bound_tys) => {
2683 use std::fmt::Write;
2685 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2686 // Maybe we should just remove this note altogether?
2687 // FIXME: only print types which don't meet the trait requirement
2689 "required because it captures the following types: ".to_owned();
2690 for ty in bound_tys.skip_binder() {
2691 write!(msg, "`{}`, ", ty).unwrap();
2693 err.note(msg.trim_end_matches(", "))
2695 ty::Generator(def_id, _, _) => {
2696 let sp = self.tcx.def_span(def_id);
2698 // Special-case this to say "async block" instead of `[static generator]`.
2699 let kind = tcx.generator_kind(def_id).unwrap();
2702 &format!("required because it's used within this {}", kind),
2705 ty::Closure(def_id, _) => err.span_note(
2706 self.tcx.def_span(def_id),
2707 &format!("required because it's used within this closure"),
2709 _ => err.note(&msg),
2714 obligated_types.push(ty);
2716 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2717 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2718 // #74711: avoid a stack overflow
2719 ensure_sufficient_stack(|| {
2720 self.note_obligation_cause_code(
2730 ensure_sufficient_stack(|| {
2731 self.note_obligation_cause_code(
2735 cause_code.peel_derives(),
2742 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2743 let mut parent_trait_pred =
2744 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2745 parent_trait_pred.remap_constness_diag(param_env);
2746 let parent_def_id = parent_trait_pred.def_id();
2748 "required for `{}` to implement `{}`",
2749 parent_trait_pred.skip_binder().self_ty(),
2750 parent_trait_pred.print_modifiers_and_trait_path()
2752 let mut is_auto_trait = false;
2753 match self.tcx.hir().get_if_local(data.impl_def_id) {
2754 Some(Node::Item(hir::Item {
2755 kind: hir::ItemKind::Trait(is_auto, ..),
2759 // FIXME: we should do something else so that it works even on crate foreign
2761 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2762 err.span_note(ident.span, &msg)
2764 Some(Node::Item(hir::Item {
2765 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2768 let mut spans = Vec::with_capacity(2);
2769 if let Some(trait_ref) = of_trait {
2770 spans.push(trait_ref.path.span);
2772 spans.push(self_ty.span);
2773 err.span_note(spans, &msg)
2775 _ => err.note(&msg),
2778 let mut parent_predicate = parent_trait_pred.to_predicate(tcx);
2779 let mut data = &data.derived;
2781 seen_requirements.insert(parent_def_id);
2783 // We don't want to point at the ADT saying "required because it appears within
2784 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2785 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2788 let child_trait_ref =
2789 self.resolve_vars_if_possible(derived.parent_trait_pred);
2790 let child_def_id = child_trait_ref.def_id();
2791 if seen_requirements.insert(child_def_id) {
2795 parent_predicate = child_trait_ref.to_predicate(tcx);
2796 parent_trait_pred = child_trait_ref;
2799 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2800 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2801 let child_trait_pred =
2802 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2803 let child_def_id = child_trait_pred.def_id();
2804 if seen_requirements.insert(child_def_id) {
2808 data = &child.derived;
2809 parent_predicate = child_trait_pred.to_predicate(tcx);
2810 parent_trait_pred = child_trait_pred;
2814 "{} redundant requirement{} hidden",
2819 "required for `{}` to implement `{}`",
2820 parent_trait_pred.skip_binder().self_ty(),
2821 parent_trait_pred.print_modifiers_and_trait_path()
2824 // #74711: avoid a stack overflow
2825 ensure_sufficient_stack(|| {
2826 self.note_obligation_cause_code(
2836 ObligationCauseCode::DerivedObligation(ref data) => {
2837 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2838 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2839 // #74711: avoid a stack overflow
2840 ensure_sufficient_stack(|| {
2841 self.note_obligation_cause_code(
2851 ObligationCauseCode::FunctionArgumentObligation {
2856 let hir = self.tcx.hir();
2857 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2858 hir.find(arg_hir_id)
2860 let parent_id = hir.get_parent_item(arg_hir_id);
2861 let typeck_results: &TypeckResults<'tcx> = match &self.typeck_results {
2862 Some(t) if t.hir_owner == parent_id => t,
2863 _ => self.tcx.typeck(parent_id.def_id),
2865 let expr = expr.peel_blocks();
2866 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
2867 let span = expr.span;
2868 if Some(span) != err.span.primary_span() {
2871 if ty.references_error() {
2874 format!("this tail expression is of type `{:?}`", ty)
2879 if let Some(Node::Expr(hir::Expr {
2881 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2882 | hir::ExprKind::MethodCall(
2883 hir::PathSegment { ident: Ident { span, .. }, .. },
2887 })) = hir.find(call_hir_id)
2889 if Some(*span) != err.span.primary_span() {
2890 err.span_label(*span, "required by a bound introduced by this call");
2893 ensure_sufficient_stack(|| {
2894 self.note_obligation_cause_code(
2904 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2905 let item_name = self.tcx.item_name(trait_item_def_id);
2907 "the requirement `{}` appears on the `impl`'s {kind} `{}` but not on the \
2908 corresponding trait's {kind}",
2909 predicate, item_name,
2913 .opt_item_ident(trait_item_def_id)
2915 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2916 let mut assoc_span: MultiSpan = sp.into();
2917 assoc_span.push_span_label(
2919 format!("this trait's {kind} doesn't have the requirement `{}`", predicate),
2921 if let Some(ident) = self
2923 .opt_associated_item(trait_item_def_id)
2924 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2926 assoc_span.push_span_label(ident.span, "in this trait");
2928 err.span_note(assoc_span, &msg);
2930 ObligationCauseCode::TrivialBound => {
2931 err.help("see issue #48214");
2932 if tcx.sess.opts.unstable_features.is_nightly_build() {
2933 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2936 ObligationCauseCode::OpaqueReturnType(expr_info) => {
2937 if let Some((expr_ty, expr_span)) = expr_info {
2938 let expr_ty = self.resolve_vars_if_possible(expr_ty);
2941 format!("return type was inferred to be `{expr_ty}` here"),
2949 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2951 fn suggest_await_before_try(
2953 err: &mut Diagnostic,
2954 obligation: &PredicateObligation<'tcx>,
2955 trait_pred: ty::PolyTraitPredicate<'tcx>,
2958 let body_hir_id = obligation.cause.body_id;
2959 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2961 if let Some(body_id) =
2962 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2964 let body = self.tcx.hir().body(body_id);
2965 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2966 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2968 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2969 let impls_future = self.type_implements_trait(
2971 self.tcx.erase_late_bound_regions(self_ty),
2973 obligation.param_env,
2975 if !impls_future.must_apply_modulo_regions() {
2979 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2980 // `<T as Future>::Output`
2981 let projection_ty = trait_pred.map_bound(|trait_pred| {
2982 self.tcx.mk_projection(
2984 // Future::Output has no substs
2985 self.tcx.mk_substs_trait(trait_pred.self_ty(), &[]),
2988 let projection_ty = normalize_to(
2989 &mut SelectionContext::new(self),
2990 obligation.param_env,
2991 obligation.cause.clone(),
2997 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
2999 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3000 obligation.param_env,
3001 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3003 debug!(try_trait_obligation = ?try_obligation);
3004 if self.predicate_may_hold(&try_obligation)
3005 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3006 && snippet.ends_with('?')
3008 err.span_suggestion_verbose(
3009 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3010 "consider `await`ing on the `Future`",
3012 Applicability::MaybeIncorrect,
3019 fn suggest_floating_point_literal(
3021 obligation: &PredicateObligation<'tcx>,
3022 err: &mut Diagnostic,
3023 trait_ref: &ty::PolyTraitRef<'tcx>,
3025 let rhs_span = match obligation.cause.code() {
3026 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3029 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3030 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3032 err.span_suggestion_verbose(
3033 rhs_span.shrink_to_hi(),
3034 "consider using a floating-point literal by writing it with `.0`",
3036 Applicability::MaybeIncorrect,
3043 obligation: &PredicateObligation<'tcx>,
3044 err: &mut Diagnostic,
3045 trait_pred: ty::PolyTraitPredicate<'tcx>,
3047 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3050 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3051 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3055 let is_derivable_trait = match diagnostic_name {
3056 sym::Default => !adt.is_enum(),
3057 sym::PartialEq | sym::PartialOrd => {
3058 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3059 trait_pred.skip_binder().self_ty() == rhs_ty
3061 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3064 is_derivable_trait &&
3065 // Ensure all fields impl the trait.
3066 adt.all_fields().all(|field| {
3067 let field_ty = field.ty(self.tcx, substs);
3068 let trait_substs = match diagnostic_name {
3069 sym::PartialEq | sym::PartialOrd => {
3070 self.tcx.mk_substs_trait(field_ty, &[field_ty.into()])
3072 _ => self.tcx.mk_substs_trait(field_ty, &[]),
3074 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3075 trait_ref: ty::TraitRef {
3076 substs: trait_substs,
3077 ..trait_pred.skip_binder().trait_ref
3081 let field_obl = Obligation::new(
3082 obligation.cause.clone(),
3083 obligation.param_env,
3084 trait_pred.to_predicate(self.tcx),
3086 self.predicate_must_hold_modulo_regions(&field_obl)
3090 err.span_suggestion_verbose(
3091 self.tcx.def_span(adt.did()).shrink_to_lo(),
3093 "consider annotating `{}` with `#[derive({})]`",
3094 trait_pred.skip_binder().self_ty(),
3097 format!("#[derive({})]\n", diagnostic_name),
3098 Applicability::MaybeIncorrect,
3103 fn suggest_dereferencing_index(
3105 obligation: &PredicateObligation<'tcx>,
3106 err: &mut Diagnostic,
3107 trait_pred: ty::PolyTraitPredicate<'tcx>,
3109 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3110 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3111 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3112 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3113 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3115 err.span_suggestion_verbose(
3116 obligation.cause.span.shrink_to_lo(),
3117 "dereference this index",
3119 Applicability::MachineApplicable,
3125 /// Collect all the returned expressions within the input expression.
3126 /// Used to point at the return spans when we want to suggest some change to them.
3128 pub struct ReturnsVisitor<'v> {
3129 pub returns: Vec<&'v hir::Expr<'v>>,
3130 in_block_tail: bool,
3133 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3134 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3135 // Visit every expression to detect `return` paths, either through the function's tail
3136 // expression or `return` statements. We walk all nodes to find `return` statements, but
3137 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3138 // they're in the return path of the function body.
3140 hir::ExprKind::Ret(Some(ex)) => {
3141 self.returns.push(ex);
3143 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3144 self.in_block_tail = false;
3145 for stmt in block.stmts {
3146 hir::intravisit::walk_stmt(self, stmt);
3148 self.in_block_tail = true;
3149 if let Some(expr) = block.expr {
3150 self.visit_expr(expr);
3153 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3154 self.visit_expr(then);
3155 if let Some(el) = else_opt {
3156 self.visit_expr(el);
3159 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3161 self.visit_expr(arm.body);
3164 // We need to walk to find `return`s in the entire body.
3165 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3166 _ => self.returns.push(ex),
3170 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3171 assert!(!self.in_block_tail);
3172 if body.generator_kind().is_none() {
3173 if let hir::ExprKind::Block(block, None) = body.value.kind {
3174 if block.expr.is_some() {
3175 self.in_block_tail = true;
3179 hir::intravisit::walk_body(self, body);
3183 /// Collect all the awaited expressions within the input expression.
3185 struct AwaitsVisitor {
3186 awaits: Vec<hir::HirId>,
3189 impl<'v> Visitor<'v> for AwaitsVisitor {
3190 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3191 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3192 self.awaits.push(id)
3194 hir::intravisit::walk_expr(self, ex)
3198 pub trait NextTypeParamName {
3199 fn next_type_param_name(&self, name: Option<&str>) -> String;
3202 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3203 fn next_type_param_name(&self, name: Option<&str>) -> String {
3204 // This is the list of possible parameter names that we might suggest.
3205 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3206 let name = name.as_deref();
3207 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3208 let used_names = self
3210 .filter_map(|p| match p.name {
3211 hir::ParamName::Plain(ident) => Some(ident.name),
3214 .collect::<Vec<_>>();
3218 .find(|n| !used_names.contains(&Symbol::intern(n)))
3219 .unwrap_or(&"ParamName")
3224 fn suggest_trait_object_return_type_alternatives(
3225 err: &mut Diagnostic,
3228 is_object_safe: bool,
3230 err.span_suggestion(
3232 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3235 Applicability::MaybeIncorrect,
3237 err.span_suggestion(
3240 "use `impl {}` as the return type if all return paths have the same type but you \
3241 want to expose only the trait in the signature",
3244 format!("impl {}", trait_obj),
3245 Applicability::MaybeIncorrect,
3248 err.multipart_suggestion(
3250 "use a boxed trait object if all return paths implement trait `{}`",
3254 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3255 (ret_ty.shrink_to_hi(), ">".to_string()),
3257 Applicability::MaybeIncorrect,
3262 /// Collect the spans that we see the generic param `param_did`
3263 struct ReplaceImplTraitVisitor<'a> {
3264 ty_spans: &'a mut Vec<Span>,
3268 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3269 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3270 if let hir::TyKind::Path(hir::QPath::Resolved(
3272 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3275 if self.param_did == *segment_did {
3276 // `fn foo(t: impl Trait)`
3277 // ^^^^^^^^^^ get this to suggest `T` instead
3279 // There might be more than one `impl Trait`.
3280 self.ty_spans.push(t.span);
3285 hir::intravisit::walk_ty(self, t);
3289 // Replace `param` with `replace_ty`
3290 struct ReplaceImplTraitFolder<'tcx> {
3292 param: &'tcx ty::GenericParamDef,
3293 replace_ty: Ty<'tcx>,
3296 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3297 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3298 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3299 if self.param.index == *index {
3300 return self.replace_ty;
3303 t.super_fold_with(self)
3306 fn tcx(&self) -> TyCtxt<'tcx> {