1 use super::{DefIdOrName, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation};
3 use crate::autoderef::Autoderef;
4 use crate::infer::InferCtxt;
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_data_structures::stack::ensure_sufficient_stack;
11 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
12 ErrorGuaranteed, MultiSpan, Style,
15 use rustc_hir::def::DefKind;
16 use rustc_hir::def_id::DefId;
17 use rustc_hir::intravisit::Visitor;
18 use rustc_hir::lang_items::LangItem;
19 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
20 use rustc_infer::infer::error_reporting::TypeErrCtxt;
21 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
22 use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime};
23 use rustc_middle::hir::map;
24 use rustc_middle::ty::{
25 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
26 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, IsSuggestable,
27 ToPredicate, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
29 use rustc_middle::ty::{TypeAndMut, TypeckResults};
30 use rustc_span::symbol::{sym, Ident, Symbol};
31 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
32 use rustc_target::spec::abi;
35 use super::InferCtxtPrivExt;
36 use crate::infer::InferCtxtExt as _;
37 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
38 use rustc_middle::ty::print::with_no_trimmed_paths;
41 pub enum GeneratorInteriorOrUpvar {
42 // span of interior type
43 Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
48 // This type provides a uniform interface to retrieve data on generators, whether it originated from
49 // the local crate being compiled or from a foreign crate.
51 pub enum GeneratorData<'tcx, 'a> {
52 Local(&'a TypeckResults<'tcx>),
53 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
56 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
57 // Try to get information about variables captured by the generator that matches a type we are
58 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
60 fn try_get_upvar_span<F>(
62 infer_context: &InferCtxt<'tcx>,
65 ) -> Option<GeneratorInteriorOrUpvar>
67 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
70 GeneratorData::Local(typeck_results) => {
71 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
72 upvars.iter().find_map(|(upvar_id, upvar)| {
73 let upvar_ty = typeck_results.node_type(*upvar_id);
74 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
75 if ty_matches(ty::Binder::dummy(upvar_ty)) {
76 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
83 GeneratorData::Foreign(_) => None,
87 // Try to get the span of a type being awaited on that matches the type we are looking with the
88 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
90 fn get_from_await_ty<F>(
92 visitor: AwaitsVisitor,
97 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
100 GeneratorData::Local(typeck_results) => visitor
103 .map(|id| hir.expect_expr(id))
105 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
107 .map(|expr| expr.span),
108 GeneratorData::Foreign(generator_diagnostic_data) => visitor
111 .map(|id| hir.expect_expr(id))
113 ty_matches(ty::Binder::dummy(
114 generator_diagnostic_data
116 .get(&await_expr.hir_id.local_id)
117 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
119 .map_or_else::<Ty<'tcx>, _, _>(
121 generator_diagnostic_data
123 .get(&await_expr.hir_id.local_id)
127 "node_type: no type for node `{}`",
128 ty::tls::with(|tcx| tcx
130 .node_to_string(await_expr.hir_id))
138 .map(|expr| expr.span),
142 /// Get the type, expression, span and optional scope span of all types
143 /// that are live across the yield of this generator
144 fn get_generator_interior_types(
146 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
148 GeneratorData::Local(typeck_result) => {
149 typeck_result.generator_interior_types.as_deref()
151 GeneratorData::Foreign(generator_diagnostic_data) => {
152 generator_diagnostic_data.generator_interior_types.as_deref()
157 // Used to get the source of the data, note we don't have as much information for generators
158 // originated from foreign crates
159 fn is_foreign(&self) -> bool {
161 GeneratorData::Local(_) => false,
162 GeneratorData::Foreign(_) => true,
167 // This trait is public to expose the diagnostics methods to clippy.
168 pub trait TypeErrCtxtExt<'tcx> {
169 fn suggest_restricting_param_bound(
171 err: &mut Diagnostic,
172 trait_pred: ty::PolyTraitPredicate<'tcx>,
173 associated_item: Option<(&'static str, Ty<'tcx>)>,
177 fn suggest_dereferences(
179 obligation: &PredicateObligation<'tcx>,
180 err: &mut Diagnostic,
181 trait_pred: ty::PolyTraitPredicate<'tcx>,
184 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
188 obligation: &PredicateObligation<'tcx>,
189 err: &mut Diagnostic,
190 trait_pred: ty::PolyTraitPredicate<'tcx>,
193 fn suggest_add_reference_to_arg(
195 obligation: &PredicateObligation<'tcx>,
196 err: &mut Diagnostic,
197 trait_pred: ty::PolyTraitPredicate<'tcx>,
198 has_custom_message: bool,
201 fn suggest_borrowing_for_object_cast(
203 err: &mut Diagnostic,
204 obligation: &PredicateObligation<'tcx>,
209 fn suggest_remove_reference(
211 obligation: &PredicateObligation<'tcx>,
212 err: &mut Diagnostic,
213 trait_pred: ty::PolyTraitPredicate<'tcx>,
216 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
218 fn suggest_change_mut(
220 obligation: &PredicateObligation<'tcx>,
221 err: &mut Diagnostic,
222 trait_pred: ty::PolyTraitPredicate<'tcx>,
225 fn suggest_semicolon_removal(
227 obligation: &PredicateObligation<'tcx>,
228 err: &mut Diagnostic,
230 trait_pred: ty::PolyTraitPredicate<'tcx>,
233 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
235 fn suggest_impl_trait(
237 err: &mut Diagnostic,
239 obligation: &PredicateObligation<'tcx>,
240 trait_pred: ty::PolyTraitPredicate<'tcx>,
243 fn point_at_returns_when_relevant(
245 err: &mut Diagnostic,
246 obligation: &PredicateObligation<'tcx>,
249 fn report_closure_arg_mismatch(
252 found_span: Option<Span>,
253 found: ty::PolyTraitRef<'tcx>,
254 expected: ty::PolyTraitRef<'tcx>,
255 cause: &ObligationCauseCode<'tcx>,
256 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
258 fn note_conflicting_closure_bounds(
260 cause: &ObligationCauseCode<'tcx>,
261 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
264 fn suggest_fully_qualified_path(
266 err: &mut Diagnostic,
272 fn maybe_note_obligation_cause_for_async_await(
274 err: &mut Diagnostic,
275 obligation: &PredicateObligation<'tcx>,
278 fn note_obligation_cause_for_async_await(
280 err: &mut Diagnostic,
281 interior_or_upvar_span: GeneratorInteriorOrUpvar,
283 outer_generator: Option<DefId>,
284 trait_pred: ty::TraitPredicate<'tcx>,
286 typeck_results: Option<&ty::TypeckResults<'tcx>>,
287 obligation: &PredicateObligation<'tcx>,
288 next_code: Option<&ObligationCauseCode<'tcx>>,
291 fn note_obligation_cause_code<T>(
293 err: &mut Diagnostic,
295 param_env: ty::ParamEnv<'tcx>,
296 cause_code: &ObligationCauseCode<'tcx>,
297 obligated_types: &mut Vec<Ty<'tcx>>,
298 seen_requirements: &mut FxHashSet<DefId>,
300 T: fmt::Display + ToPredicate<'tcx, T>;
302 /// Suggest to await before try: future? => future.await?
303 fn suggest_await_before_try(
305 err: &mut Diagnostic,
306 obligation: &PredicateObligation<'tcx>,
307 trait_pred: ty::PolyTraitPredicate<'tcx>,
311 fn suggest_floating_point_literal(
313 obligation: &PredicateObligation<'tcx>,
314 err: &mut Diagnostic,
315 trait_ref: &ty::PolyTraitRef<'tcx>,
320 obligation: &PredicateObligation<'tcx>,
321 err: &mut Diagnostic,
322 trait_pred: ty::PolyTraitPredicate<'tcx>,
325 fn suggest_dereferencing_index(
327 obligation: &PredicateObligation<'tcx>,
328 err: &mut Diagnostic,
329 trait_pred: ty::PolyTraitPredicate<'tcx>,
333 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
335 generics.tail_span_for_predicate_suggestion(),
336 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
340 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
341 /// it can also be an `impl Trait` param that needs to be decomposed to a type
342 /// param for cleaner code.
343 fn suggest_restriction<'tcx>(
346 hir_generics: &hir::Generics<'tcx>,
348 err: &mut Diagnostic,
349 fn_sig: Option<&hir::FnSig<'_>>,
350 projection: Option<&ty::ProjectionTy<'_>>,
351 trait_pred: ty::PolyTraitPredicate<'tcx>,
352 // When we are dealing with a trait, `super_traits` will be `Some`:
353 // Given `trait T: A + B + C {}`
354 // - ^^^^^^^^^ GenericBounds
357 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
359 if hir_generics.where_clause_span.from_expansion()
360 || hir_generics.where_clause_span.desugaring_kind().is_some()
364 let Some(item_id) = hir_id.as_owner() else { return; };
365 let generics = tcx.generics_of(item_id);
366 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
367 if let Some((param, bound_str, fn_sig)) =
368 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
369 // Shenanigans to get the `Trait` from the `impl Trait`.
370 ty::Param(param) => {
371 let param_def = generics.type_param(param, tcx);
372 if param_def.kind.is_synthetic() {
374 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
375 return Some((param_def, bound_str, sig));
382 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
383 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
386 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
389 if !trait_pred.is_suggestable(tcx, false) {
392 // We know we have an `impl Trait` that doesn't satisfy a required projection.
394 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
395 // types. There should be at least one, but there might be *more* than one. In that
396 // case we could just ignore it and try to identify which one needs the restriction,
397 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
399 let mut ty_spans = vec![];
400 for input in fn_sig.decl.inputs {
401 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
404 // The type param `T: Trait` we will suggest to introduce.
405 let type_param = format!("{}: {}", type_param_name, bound_str);
408 if let Some(span) = hir_generics.span_for_param_suggestion() {
409 (span, format!(", {}", type_param))
411 (hir_generics.span, format!("<{}>", type_param))
413 // `fn foo(t: impl Trait)`
414 // ^ suggest `where <T as Trait>::A: Bound`
415 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
417 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
419 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
420 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
421 // `fn foo(t: impl Trait<A: Bound>)` instead.
422 err.multipart_suggestion(
423 "introduce a type parameter with a trait bound instead of using `impl Trait`",
425 Applicability::MaybeIncorrect,
428 if !trait_pred.is_suggestable(tcx, false) {
431 // Trivial case: `T` needs an extra bound: `T: Bound`.
432 let (sp, suggestion) = match (
436 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
439 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
440 (None, Some((ident, []))) => (
441 ident.span.shrink_to_hi(),
442 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
444 (_, Some((_, [.., bounds]))) => (
445 bounds.span().shrink_to_hi(),
446 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
448 (Some(_), Some((_, []))) => (
449 hir_generics.span.shrink_to_hi(),
450 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
454 err.span_suggestion_verbose(
456 &format!("consider further restricting {}", msg),
458 Applicability::MachineApplicable,
463 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
464 fn suggest_restricting_param_bound(
466 mut err: &mut Diagnostic,
467 trait_pred: ty::PolyTraitPredicate<'tcx>,
468 associated_ty: Option<(&'static str, Ty<'tcx>)>,
471 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
473 let self_ty = trait_pred.skip_binder().self_ty();
474 let (param_ty, projection) = match self_ty.kind() {
475 ty::Param(_) => (true, None),
476 ty::Projection(projection) => (false, Some(projection)),
480 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
481 // don't suggest `T: Sized + ?Sized`.
482 let mut hir_id = body_id;
483 while let Some(node) = self.tcx.hir().find(hir_id) {
485 hir::Node::Item(hir::Item {
487 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
489 }) if self_ty == self.tcx.types.self_param => {
491 // Restricting `Self` for a single method.
501 Some((ident, bounds)),
506 hir::Node::TraitItem(hir::TraitItem {
508 kind: hir::TraitItemKind::Fn(..),
510 }) if self_ty == self.tcx.types.self_param => {
512 // Restricting `Self` for a single method.
514 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
520 hir::Node::TraitItem(hir::TraitItem {
522 kind: hir::TraitItemKind::Fn(fn_sig, ..),
525 | hir::Node::ImplItem(hir::ImplItem {
527 kind: hir::ImplItemKind::Fn(fn_sig, ..),
530 | hir::Node::Item(hir::Item {
531 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
532 }) if projection.is_some() => {
533 // Missing restriction on associated type of type parameter (unmet projection).
538 "the associated type",
547 hir::Node::Item(hir::Item {
549 hir::ItemKind::Trait(_, _, generics, ..)
550 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
552 }) if projection.is_some() => {
553 // Missing restriction on associated type of type parameter (unmet projection).
558 "the associated type",
568 hir::Node::Item(hir::Item {
570 hir::ItemKind::Struct(_, generics)
571 | hir::ItemKind::Enum(_, generics)
572 | hir::ItemKind::Union(_, generics)
573 | hir::ItemKind::Trait(_, _, generics, ..)
574 | hir::ItemKind::Impl(hir::Impl { generics, .. })
575 | hir::ItemKind::Fn(_, generics, _)
576 | hir::ItemKind::TyAlias(_, generics)
577 | hir::ItemKind::TraitAlias(generics, _)
578 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
581 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
582 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
585 // We skip the 0'th subst (self) because we do not want
586 // to consider the predicate as not suggestible if the
587 // self type is an arg position `impl Trait` -- instead,
588 // we handle that by adding ` + Bound` below.
589 // FIXME(compiler-errors): It would be nice to do the same
590 // this that we do in `suggest_restriction` and pull the
591 // `impl Trait` into a new generic if it shows up somewhere
592 // else in the predicate.
593 if !trait_pred.skip_binder().trait_ref.substs[1..]
595 .all(|g| g.is_suggestable(self.tcx, false))
599 // Missing generic type parameter bound.
600 let param_name = self_ty.to_string();
601 let mut constraint = with_no_trimmed_paths!(
602 trait_pred.print_modifiers_and_trait_path().to_string()
605 if let Some((name, term)) = associated_ty {
606 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
607 // That should be extracted into a helper function.
608 if constraint.ends_with('>') {
609 constraint = format!(
611 &constraint[..constraint.len() - 1],
616 constraint.push_str(&format!("<{} = {}>", name, term));
620 if suggest_constraining_type_param(
626 Some(trait_pred.def_id()),
632 hir::Node::Item(hir::Item {
634 hir::ItemKind::Struct(_, generics)
635 | hir::ItemKind::Enum(_, generics)
636 | hir::ItemKind::Union(_, generics)
637 | hir::ItemKind::Trait(_, _, generics, ..)
638 | hir::ItemKind::Impl(hir::Impl { generics, .. })
639 | hir::ItemKind::Fn(_, generics, _)
640 | hir::ItemKind::TyAlias(_, generics)
641 | hir::ItemKind::TraitAlias(generics, _)
642 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
645 // Missing generic type parameter bound.
646 if suggest_arbitrary_trait_bound(
656 hir::Node::Crate(..) => return,
661 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
665 /// When after several dereferencing, the reference satisfies the trait
666 /// binding. This function provides dereference suggestion for this
667 /// specific situation.
668 fn suggest_dereferences(
670 obligation: &PredicateObligation<'tcx>,
671 err: &mut Diagnostic,
672 trait_pred: ty::PolyTraitPredicate<'tcx>,
674 // It only make sense when suggesting dereferences for arguments
675 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code()
676 else { return false; };
677 let Some(typeck_results) = &self.typeck_results
678 else { return false; };
679 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
680 else { return false; };
681 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
682 else { return false; };
684 let span = obligation.cause.span;
685 let mut real_trait_pred = trait_pred;
686 let mut code = obligation.cause.code();
687 while let Some((parent_code, parent_trait_pred)) = code.parent() {
689 if let Some(parent_trait_pred) = parent_trait_pred {
690 real_trait_pred = parent_trait_pred;
693 let real_ty = real_trait_pred.self_ty();
694 // We `erase_late_bound_regions` here because `make_subregion` does not handle
695 // `ReLateBound`, and we don't particularly care about the regions.
697 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
703 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
704 let mut autoderef = Autoderef::new(
706 obligation.param_env,
707 obligation.cause.body_id,
711 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
713 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
715 // Remapping bound vars here
716 let real_trait_pred_and_ty =
717 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
718 let obligation = self.mk_trait_obligation_with_new_self_ty(
719 obligation.param_env,
720 real_trait_pred_and_ty,
722 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
725 // Don't care about `&mut` because `DerefMut` is used less
726 // often and user will not expect autoderef happens.
727 if let Some(hir::Node::Expr(hir::Expr {
729 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
731 })) = self.tcx.hir().find(*arg_hir_id)
733 let derefs = "*".repeat(steps);
734 err.span_suggestion_verbose(
735 expr.span.shrink_to_lo(),
736 "consider dereferencing here",
738 Applicability::MachineApplicable,
743 } else if real_trait_pred != trait_pred {
744 // This branch addresses #87437.
746 // Remapping bound vars here
747 let real_trait_pred_and_base_ty =
748 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
749 let obligation = self.mk_trait_obligation_with_new_self_ty(
750 obligation.param_env,
751 real_trait_pred_and_base_ty,
753 if self.predicate_may_hold(&obligation) {
754 err.span_suggestion_verbose(
756 "consider dereferencing here",
758 Applicability::MachineApplicable,
768 /// Given a closure's `DefId`, return the given name of the closure.
770 /// This doesn't account for reassignments, but it's only used for suggestions.
771 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
772 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
773 // Get the local name of this closure. This can be inaccurate because
774 // of the possibility of reassignment, but this should be good enough.
776 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
786 let hir = self.tcx.hir();
787 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
788 let parent_node = hir.get_parent_node(hir_id);
789 match hir.find(parent_node) {
790 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
791 get_name(err, &local.pat.kind)
793 // Different to previous arm because one is `&hir::Local` and the other
794 // is `P<hir::Local>`.
795 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
800 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
801 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
802 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
805 obligation: &PredicateObligation<'tcx>,
806 err: &mut Diagnostic,
807 trait_pred: ty::PolyTraitPredicate<'tcx>,
809 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
810 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
812 // Don't suggest calling to turn an unsized type into a sized type
816 // This is duplicated from `extract_callable_info` in typeck, which
817 // relies on autoderef, so we can't use it here.
818 let found = trait_pred.self_ty().skip_binder().peel_refs();
819 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
821 ty::FnPtr(fn_sig) => {
822 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
824 ty::FnDef(def_id, _) => {
825 let fn_sig = found.fn_sig(self.tcx);
826 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
828 ty::Closure(def_id, substs) => {
829 let fn_sig = substs.as_closure().sig();
831 DefIdOrName::DefId(def_id),
833 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
836 ty::Opaque(def_id, substs) => {
837 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
838 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
839 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
840 // args tuple will always be substs[1]
841 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
844 DefIdOrName::DefId(def_id),
845 pred.kind().rebind(proj.term.ty().unwrap()),
846 pred.kind().rebind(args.as_slice()),
853 ty::Dynamic(data, _, ty::Dyn) => {
854 data.iter().find_map(|pred| {
855 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
856 && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
857 // for existential projection, substs are shifted over by 1
858 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
861 DefIdOrName::Name("trait object"),
862 pred.rebind(proj.term.ty().unwrap()),
863 pred.rebind(args.as_slice()),
871 obligation.param_env.caller_bounds().iter().find_map(|pred| {
872 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
873 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
874 && proj.projection_ty.self_ty() == found
875 // args tuple will always be substs[1]
876 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
879 DefIdOrName::Name("type parameter"),
880 pred.kind().rebind(proj.term.ty().unwrap()),
881 pred.kind().rebind(args.as_slice()),
889 }) else { return false; };
890 let output = self.replace_bound_vars_with_fresh_vars(
891 obligation.cause.span,
892 LateBoundRegionConversionTime::FnCall,
895 let inputs = inputs.skip_binder().iter().map(|ty| {
896 self.replace_bound_vars_with_fresh_vars(
897 obligation.cause.span,
898 LateBoundRegionConversionTime::FnCall,
903 // Remapping bound vars here
904 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
907 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
908 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
912 // Get the name of the callable and the arguments to be used in the suggestion.
913 let hir = self.tcx.hir();
915 let msg = match def_id_or_name {
916 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
917 DefKind::Ctor(CtorOf::Struct, _) => {
918 "use parentheses to construct this tuple struct".to_string()
920 DefKind::Ctor(CtorOf::Variant, _) => {
921 "use parentheses to construct this tuple variant".to_string()
923 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
925 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
930 if ty.is_suggestable(self.tcx, false) {
931 format!("/* {ty} */")
933 "/* value */".to_string()
939 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
940 && obligation.cause.span.can_be_used_for_suggestions()
942 // When the obligation error has been ensured to have been caused by
943 // an argument, the `obligation.cause.span` points at the expression
944 // of the argument, so we can provide a suggestion. Otherwise, we give
945 // a more general note.
946 err.span_suggestion_verbose(
947 obligation.cause.span.shrink_to_hi(),
950 Applicability::HasPlaceholders,
952 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
953 let name = match hir.get_if_local(def_id) {
954 Some(hir::Node::Expr(hir::Expr {
955 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
958 err.span_label(*fn_decl_span, "consider calling this closure");
959 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
964 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
965 err.span_label(ident.span, "consider calling this function");
968 Some(hir::Node::Ctor(..)) => {
969 let name = self.tcx.def_path_str(def_id);
971 self.tcx.def_span(def_id),
972 format!("consider calling the constructor for `{}`", name),
978 err.help(&format!("{msg}: `{name}({args})`"));
983 fn suggest_add_reference_to_arg(
985 obligation: &PredicateObligation<'tcx>,
986 err: &mut Diagnostic,
987 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
988 has_custom_message: bool,
990 let span = obligation.cause.span;
992 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
993 obligation.cause.code()
996 } else if let ObligationCauseCode::ItemObligation(_)
997 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
999 obligation.cause.code()
1000 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1001 span.ctxt().outer_expn_data().kind
1003 obligation.cause.code()
1008 // List of traits for which it would be nonsensical to suggest borrowing.
1009 // For instance, immutable references are always Copy, so suggesting to
1010 // borrow would always succeed, but it's probably not what the user wanted.
1011 let mut never_suggest_borrow: Vec<_> =
1012 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1014 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1017 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1018 never_suggest_borrow.push(def_id);
1021 let param_env = obligation.param_env;
1023 // Try to apply the original trait binding obligation by borrowing.
1024 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1025 blacklist: &[DefId]|
1027 if blacklist.contains(&old_pred.def_id()) {
1030 // We map bounds to `&T` and `&mut T`
1031 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1034 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1037 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1040 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1044 let mk_result = |trait_pred_and_new_ty| {
1046 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1047 self.predicate_must_hold_modulo_regions(&obligation)
1049 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1050 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1052 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1053 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1054 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1057 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1058 mutability.is_mut(),
1064 if imm_ref_self_ty_satisfies_pred
1065 || mut_ref_self_ty_satisfies_pred
1066 || ref_inner_ty_satisfies_pred
1068 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1069 // We don't want a borrowing suggestion on the fields in structs,
1072 // the_foos: Vec<Foo>
1076 span.ctxt().outer_expn_data().kind,
1077 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1081 if snippet.starts_with('&') {
1082 // This is already a literal borrow and the obligation is failing
1083 // somewhere else in the obligation chain. Do not suggest non-sense.
1086 // We have a very specific type of error, where just borrowing this argument
1087 // might solve the problem. In cases like this, the important part is the
1088 // original type obligation, not the last one that failed, which is arbitrary.
1089 // Because of this, we modify the error to refer to the original obligation and
1090 // return early in the caller.
1092 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1093 if has_custom_message {
1097 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1102 "the trait `{}` is not implemented for `{}`",
1103 old_pred.print_modifiers_and_trait_path(),
1104 old_pred.self_ty().skip_binder(),
1108 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1109 err.span_suggestions(
1110 span.shrink_to_lo(),
1111 "consider borrowing here",
1112 ["&".to_string(), "&mut ".to_string()],
1113 Applicability::MaybeIncorrect,
1116 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1117 err.span_suggestion_verbose(
1118 span.shrink_to_lo(),
1120 "consider{} borrowing here",
1121 if is_mut { " mutably" } else { "" }
1123 format!("&{}", if is_mut { "mut " } else { "" }),
1124 Applicability::MaybeIncorrect,
1133 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1134 try_borrowing(cause.derived.parent_trait_pred, &[])
1135 } else if let ObligationCauseCode::BindingObligation(_, _)
1136 | ObligationCauseCode::ItemObligation(_)
1137 | ObligationCauseCode::ExprItemObligation(..)
1138 | ObligationCauseCode::ExprBindingObligation(..) = code
1140 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1146 // Suggest borrowing the type
1147 fn suggest_borrowing_for_object_cast(
1149 err: &mut Diagnostic,
1150 obligation: &PredicateObligation<'tcx>,
1152 object_ty: Ty<'tcx>,
1154 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1155 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1157 for predicate in predicates.iter() {
1158 if !self.predicate_must_hold_modulo_regions(
1159 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1165 err.span_suggestion(
1166 obligation.cause.span.shrink_to_lo(),
1168 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1171 Applicability::MaybeIncorrect,
1175 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1176 /// suggest removing these references until we reach a type that implements the trait.
1177 fn suggest_remove_reference(
1179 obligation: &PredicateObligation<'tcx>,
1180 err: &mut Diagnostic,
1181 trait_pred: ty::PolyTraitPredicate<'tcx>,
1183 let span = obligation.cause.span;
1185 let mut suggested = false;
1186 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1188 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1189 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1190 // Do not suggest removal of borrow from type arguments.
1194 // Skipping binder here, remapping below
1195 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1197 for refs_remaining in 0..refs_number {
1198 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1201 suggested_ty = *inner_ty;
1203 // Remapping bound vars here
1204 let trait_pred_and_suggested_ty =
1205 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1207 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1208 obligation.param_env,
1209 trait_pred_and_suggested_ty,
1212 if self.predicate_may_hold(&new_obligation) {
1217 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1219 let remove_refs = refs_remaining + 1;
1221 let msg = if remove_refs == 1 {
1222 "consider removing the leading `&`-reference".to_string()
1224 format!("consider removing {} leading `&`-references", remove_refs)
1227 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1236 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1237 let span = obligation.cause.span;
1239 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1240 let hir = self.tcx.hir();
1241 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1242 if let hir::Node::Expr(expr) = node {
1243 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1244 // and if not maybe suggest doing something else? If we kept the expression around we
1245 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1246 // it is from the local crate.
1247 err.span_suggestion(
1249 "remove the `.await`",
1251 Applicability::MachineApplicable,
1253 // FIXME: account for associated `async fn`s.
1254 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1255 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1256 obligation.predicate.kind().skip_binder()
1260 &format!("this call returns `{}`", pred.self_ty()),
1263 if let Some(typeck_results) = &self.typeck_results
1264 && let ty = typeck_results.expr_ty_adjusted(base)
1265 && let ty::FnDef(def_id, _substs) = ty.kind()
1266 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1267 hir.get_if_local(*def_id)
1270 "alternatively, consider making `fn {}` asynchronous",
1273 if vis_span.is_empty() {
1274 err.span_suggestion_verbose(
1275 span.shrink_to_lo(),
1278 Applicability::MaybeIncorrect,
1281 err.span_suggestion_verbose(
1282 vis_span.shrink_to_hi(),
1285 Applicability::MaybeIncorrect,
1295 /// Check if the trait bound is implemented for a different mutability and note it in the
1297 fn suggest_change_mut(
1299 obligation: &PredicateObligation<'tcx>,
1300 err: &mut Diagnostic,
1301 trait_pred: ty::PolyTraitPredicate<'tcx>,
1303 let points_at_arg = matches!(
1304 obligation.cause.code(),
1305 ObligationCauseCode::FunctionArgumentObligation { .. },
1308 let span = obligation.cause.span;
1309 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1311 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1312 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1313 // Do not suggest removal of borrow from type arguments.
1316 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1317 if trait_pred.has_non_region_infer() {
1318 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1319 // unresolved bindings.
1323 // Skipping binder here, remapping below
1324 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1326 let suggested_ty = match mutability {
1327 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1328 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1331 // Remapping bound vars here
1332 let trait_pred_and_suggested_ty =
1333 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1335 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1336 obligation.param_env,
1337 trait_pred_and_suggested_ty,
1339 let suggested_ty_would_satisfy_obligation = self
1340 .evaluate_obligation_no_overflow(&new_obligation)
1341 .must_apply_modulo_regions();
1342 if suggested_ty_would_satisfy_obligation {
1347 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1348 if points_at_arg && mutability.is_not() && refs_number > 0 {
1349 err.span_suggestion_verbose(
1351 "consider changing this borrow's mutability",
1353 Applicability::MachineApplicable,
1357 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1358 trait_pred.print_modifiers_and_trait_path(),
1360 trait_pred.skip_binder().self_ty(),
1368 fn suggest_semicolon_removal(
1370 obligation: &PredicateObligation<'tcx>,
1371 err: &mut Diagnostic,
1373 trait_pred: ty::PolyTraitPredicate<'tcx>,
1375 let hir = self.tcx.hir();
1376 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1377 let node = hir.find(parent_node);
1378 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1379 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1380 && sig.decl.output.span().overlaps(span)
1381 && blk.expr.is_none()
1382 && trait_pred.self_ty().skip_binder().is_unit()
1383 && let Some(stmt) = blk.stmts.last()
1384 && let hir::StmtKind::Semi(expr) = stmt.kind
1385 // Only suggest this if the expression behind the semicolon implements the predicate
1386 && let Some(typeck_results) = &self.typeck_results
1387 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1388 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1389 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1395 "this expression has type `{}`, which implements `{}`",
1397 trait_pred.print_modifiers_and_trait_path()
1400 err.span_suggestion(
1401 self.tcx.sess.source_map().end_point(stmt.span),
1402 "remove this semicolon",
1404 Applicability::MachineApplicable
1411 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1412 let hir = self.tcx.hir();
1413 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1414 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1418 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1421 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1422 /// applicable and signal that the error has been expanded appropriately and needs to be
1424 fn suggest_impl_trait(
1426 err: &mut Diagnostic,
1428 obligation: &PredicateObligation<'tcx>,
1429 trait_pred: ty::PolyTraitPredicate<'tcx>,
1431 match obligation.cause.code().peel_derives() {
1432 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1433 ObligationCauseCode::SizedReturnType => {}
1437 let hir = self.tcx.hir();
1438 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1439 let node = hir.find(fn_hir_id);
1440 let Some(hir::Node::Item(hir::Item {
1441 kind: hir::ItemKind::Fn(sig, _, body_id),
1447 let body = hir.body(*body_id);
1448 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1449 let ty = trait_pred.skip_binder().self_ty();
1450 let is_object_safe = match ty.kind() {
1451 ty::Dynamic(predicates, _, ty::Dyn) => {
1452 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1455 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1457 // We only want to suggest `impl Trait` to `dyn Trait`s.
1458 // For example, `fn foo() -> str` needs to be filtered out.
1462 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1466 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1467 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1468 // Recursively look for `TraitObject` types and if there's only one, use that span to
1469 // suggest `impl Trait`.
1471 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1472 // otherwise suggest using `Box<dyn Trait>` or an enum.
1473 let mut visitor = ReturnsVisitor::default();
1474 visitor.visit_body(&body);
1476 let typeck_results = self.typeck_results.as_ref().unwrap();
1477 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1479 let ret_types = visitor
1482 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1483 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1484 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1486 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1488 let ty = self.resolve_vars_if_possible(ty);
1490 !matches!(ty.kind(), ty::Error(_))
1491 && last_ty.map_or(true, |last_ty| {
1492 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1493 // *after* in the dependency graph.
1494 match (ty.kind(), last_ty.kind()) {
1495 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1496 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1497 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1499 Infer(InferTy::FreshFloatTy(_)),
1500 Infer(InferTy::FreshFloatTy(_)),
1505 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1508 let mut spans_and_needs_box = vec![];
1510 match liberated_sig.output().kind() {
1511 ty::Dynamic(predicates, _, ty::Dyn) => {
1512 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1513 let param_env = ty::ParamEnv::empty();
1515 if !only_never_return {
1516 for (expr_span, return_ty) in ret_types {
1517 let self_ty_satisfies_dyn_predicates = |self_ty| {
1518 predicates.iter().all(|predicate| {
1519 let pred = predicate.with_self_ty(self.tcx, self_ty);
1520 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1521 self.predicate_may_hold(&obl)
1525 if let ty::Adt(def, substs) = return_ty.kind()
1527 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1529 spans_and_needs_box.push((expr_span, false));
1530 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1531 spans_and_needs_box.push((expr_span, true));
1541 let sm = self.tcx.sess.source_map();
1542 if !ret_ty.span.overlaps(span) {
1545 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1546 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1552 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1553 let name = liberated_sig.output().to_string();
1555 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1556 if !name.starts_with("dyn ") {
1562 err.code(error_code!(E0746));
1563 err.set_primary_message("return type cannot have an unboxed trait object");
1564 err.children.clear();
1565 let impl_trait_msg = "for information on `impl Trait`, see \
1566 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1567 #returning-types-that-implement-traits>";
1568 let trait_obj_msg = "for information on trait objects, see \
1569 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1570 #using-trait-objects-that-allow-for-values-of-different-types>";
1572 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1573 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1574 if only_never_return {
1575 // No return paths, probably using `panic!()` or similar.
1576 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1577 suggest_trait_object_return_type_alternatives(
1583 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1584 // Suggest `-> impl Trait`.
1585 err.span_suggestion(
1588 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1589 which implements `{1}`",
1592 format!("impl {}", trait_obj),
1593 Applicability::MachineApplicable,
1595 err.note(impl_trait_msg);
1598 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1599 err.multipart_suggestion(
1600 "return a boxed trait object instead",
1602 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1603 (span.shrink_to_hi(), ">".to_string()),
1605 Applicability::MaybeIncorrect,
1607 for (span, needs_box) in spans_and_needs_box {
1609 err.multipart_suggestion(
1610 "... and box this value",
1612 (span.shrink_to_lo(), "Box::new(".to_string()),
1613 (span.shrink_to_hi(), ")".to_string()),
1615 Applicability::MaybeIncorrect,
1620 // This is currently not possible to trigger because E0038 takes precedence, but
1621 // leave it in for completeness in case anything changes in an earlier stage.
1623 "if trait `{}` were object-safe, you could return a trait object",
1627 err.note(trait_obj_msg);
1629 "if all the returned values were of the same type you could use `impl {}` as the \
1633 err.note(impl_trait_msg);
1634 err.note("you can create a new `enum` with a variant for each returned type");
1639 fn point_at_returns_when_relevant(
1641 err: &mut Diagnostic,
1642 obligation: &PredicateObligation<'tcx>,
1644 match obligation.cause.code().peel_derives() {
1645 ObligationCauseCode::SizedReturnType => {}
1649 let hir = self.tcx.hir();
1650 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1651 let node = hir.find(parent_node);
1652 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1655 let body = hir.body(*body_id);
1656 // Point at all the `return`s in the function as they have failed trait bounds.
1657 let mut visitor = ReturnsVisitor::default();
1658 visitor.visit_body(&body);
1659 let typeck_results = self.typeck_results.as_ref().unwrap();
1660 for expr in &visitor.returns {
1661 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1662 let ty = self.resolve_vars_if_possible(returned_ty);
1663 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1669 fn report_closure_arg_mismatch(
1672 found_span: Option<Span>,
1673 found: ty::PolyTraitRef<'tcx>,
1674 expected: ty::PolyTraitRef<'tcx>,
1675 cause: &ObligationCauseCode<'tcx>,
1676 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1677 pub(crate) fn build_fn_sig_ty<'tcx>(
1678 infcx: &InferCtxt<'tcx>,
1679 trait_ref: ty::PolyTraitRef<'tcx>,
1681 let inputs = trait_ref.skip_binder().substs.type_at(1);
1682 let sig = match inputs.kind() {
1683 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1684 infcx.tcx.mk_fn_sig(
1686 infcx.next_ty_var(TypeVariableOrigin {
1688 kind: TypeVariableOriginKind::MiscVariable,
1691 hir::Unsafety::Normal,
1695 _ => infcx.tcx.mk_fn_sig(
1696 std::iter::once(inputs),
1697 infcx.next_ty_var(TypeVariableOrigin {
1699 kind: TypeVariableOriginKind::MiscVariable,
1702 hir::Unsafety::Normal,
1707 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1710 let argument_kind = match expected.skip_binder().self_ty().kind() {
1711 ty::Closure(..) => "closure",
1712 ty::Generator(..) => "generator",
1715 let mut err = struct_span_err!(
1719 "type mismatch in {argument_kind} arguments",
1722 err.span_label(span, "expected due to this");
1724 let found_span = found_span.unwrap_or(span);
1725 err.span_label(found_span, "found signature defined here");
1727 let expected = build_fn_sig_ty(self, expected);
1728 let found = build_fn_sig_ty(self, found);
1730 let (expected_str, found_str) = self.cmp(expected, found);
1732 let signature_kind = format!("{argument_kind} signature");
1733 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1735 self.note_conflicting_closure_bounds(cause, &mut err);
1740 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1741 // requirements, which will always cause a closure to have a type error.
1742 fn note_conflicting_closure_bounds(
1744 cause: &ObligationCauseCode<'tcx>,
1745 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1747 // First, look for an `ExprBindingObligation`, which means we can get
1748 // the unsubstituted predicate list of the called function. And check
1749 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1750 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1751 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1752 && let Some(pred) = predicates.predicates.get(*idx)
1753 && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
1754 && self.tcx.is_fn_trait(trait_pred.def_id())
1757 self.tcx.anonymize_late_bound_regions(pred.kind().rebind(trait_pred.self_ty()));
1758 let expected_substs = self
1760 .anonymize_late_bound_regions(pred.kind().rebind(trait_pred.trait_ref.substs));
1762 // Find another predicate whose self-type is equal to the expected self type,
1763 // but whose substs don't match.
1764 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1766 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1767 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
1768 if self.tcx.is_fn_trait(trait_pred.def_id())
1770 // Make sure that the self type matches
1771 // (i.e. constraining this closure)
1773 == self.tcx.anonymize_late_bound_regions(
1774 pred.kind().rebind(trait_pred.self_ty()),
1776 // But the substs don't match (i.e. incompatible args)
1778 != self.tcx.anonymize_late_bound_regions(
1779 pred.kind().rebind(trait_pred.trait_ref.substs),
1786 // If we found one, then it's very likely the cause of the error.
1787 if let Some((_, (_, other_pred_span))) = other_pred {
1790 "closure inferred to have a different signature due to this bound",
1796 fn suggest_fully_qualified_path(
1798 err: &mut Diagnostic,
1803 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1804 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1806 "{}s cannot be accessed directly on a `trait`, they can only be \
1807 accessed through a specific `impl`",
1808 assoc_item.kind.as_def_kind().descr(item_def_id)
1810 err.span_suggestion(
1812 "use the fully qualified path to an implementation",
1813 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1814 Applicability::HasPlaceholders,
1820 /// Adds an async-await specific note to the diagnostic when the future does not implement
1821 /// an auto trait because of a captured type.
1824 /// note: future does not implement `Qux` as this value is used across an await
1825 /// --> $DIR/issue-64130-3-other.rs:17:5
1827 /// LL | let x = Foo;
1828 /// | - has type `Foo`
1829 /// LL | baz().await;
1830 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1832 /// | - `x` is later dropped here
1835 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1836 /// is "replaced" with a different message and a more specific error.
1839 /// error: future cannot be sent between threads safely
1840 /// --> $DIR/issue-64130-2-send.rs:21:5
1842 /// LL | fn is_send<T: Send>(t: T) { }
1843 /// | ---- required by this bound in `is_send`
1845 /// LL | is_send(bar());
1846 /// | ^^^^^^^ future returned by `bar` is not send
1848 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1849 /// implemented for `Foo`
1850 /// note: future is not send as this value is used across an await
1851 /// --> $DIR/issue-64130-2-send.rs:15:5
1853 /// LL | let x = Foo;
1854 /// | - has type `Foo`
1855 /// LL | baz().await;
1856 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1858 /// | - `x` is later dropped here
1861 /// Returns `true` if an async-await specific note was added to the diagnostic.
1862 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1863 fn maybe_note_obligation_cause_for_async_await(
1865 err: &mut Diagnostic,
1866 obligation: &PredicateObligation<'tcx>,
1868 let hir = self.tcx.hir();
1870 // Attempt to detect an async-await error by looking at the obligation causes, looking
1871 // for a generator to be present.
1873 // When a future does not implement a trait because of a captured type in one of the
1874 // generators somewhere in the call stack, then the result is a chain of obligations.
1876 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1877 // future is passed as an argument to a function C which requires a `Send` type, then the
1878 // chain looks something like this:
1880 // - `BuiltinDerivedObligation` with a generator witness (B)
1881 // - `BuiltinDerivedObligation` with a generator (B)
1882 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1883 // - `BuiltinDerivedObligation` with a generator witness (A)
1884 // - `BuiltinDerivedObligation` with a generator (A)
1885 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1886 // - `BindingObligation` with `impl_send (Send requirement)
1888 // The first obligation in the chain is the most useful and has the generator that captured
1889 // the type. The last generator (`outer_generator` below) has information about where the
1890 // bound was introduced. At least one generator should be present for this diagnostic to be
1892 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1893 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
1896 let mut generator = None;
1897 let mut outer_generator = None;
1898 let mut next_code = Some(obligation.cause.code());
1900 let mut seen_upvar_tys_infer_tuple = false;
1902 while let Some(code) = next_code {
1905 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1906 next_code = Some(parent_code);
1908 ObligationCauseCode::ImplDerivedObligation(cause) => {
1909 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1911 parent_trait_ref = ?cause.derived.parent_trait_pred,
1912 self_ty.kind = ?ty.kind(),
1917 ty::Generator(did, ..) => {
1918 generator = generator.or(Some(did));
1919 outer_generator = Some(did);
1921 ty::GeneratorWitness(..) => {}
1922 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1923 // By introducing a tuple of upvar types into the chain of obligations
1924 // of a generator, the first non-generator item is now the tuple itself,
1925 // we shall ignore this.
1927 seen_upvar_tys_infer_tuple = true;
1929 _ if generator.is_none() => {
1930 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1931 target_ty = Some(ty);
1936 next_code = Some(&cause.derived.parent_code);
1938 ObligationCauseCode::DerivedObligation(derived_obligation)
1939 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1940 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1942 parent_trait_ref = ?derived_obligation.parent_trait_pred,
1943 self_ty.kind = ?ty.kind(),
1947 ty::Generator(did, ..) => {
1948 generator = generator.or(Some(did));
1949 outer_generator = Some(did);
1951 ty::GeneratorWitness(..) => {}
1952 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1953 // By introducing a tuple of upvar types into the chain of obligations
1954 // of a generator, the first non-generator item is now the tuple itself,
1955 // we shall ignore this.
1957 seen_upvar_tys_infer_tuple = true;
1959 _ if generator.is_none() => {
1960 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1961 target_ty = Some(ty);
1966 next_code = Some(&derived_obligation.parent_code);
1972 // Only continue if a generator was found.
1973 debug!(?generator, ?trait_ref, ?target_ty);
1974 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1978 let span = self.tcx.def_span(generator_did);
1980 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1983 ?generator_did_root,
1984 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
1988 let generator_body = generator_did
1990 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
1991 .map(|body_id| hir.body(body_id));
1992 let mut visitor = AwaitsVisitor::default();
1993 if let Some(body) = generator_body {
1994 visitor.visit_body(body);
1996 debug!(awaits = ?visitor.awaits);
1998 // Look for a type inside the generator interior that matches the target type to get
2000 let target_ty_erased = self.tcx.erase_regions(target_ty);
2001 let ty_matches = |ty| -> bool {
2002 // Careful: the regions for types that appear in the
2003 // generator interior are not generally known, so we
2004 // want to erase them when comparing (and anyway,
2005 // `Send` and other bounds are generally unaffected by
2006 // the choice of region). When erasing regions, we
2007 // also have to erase late-bound regions. This is
2008 // because the types that appear in the generator
2009 // interior generally contain "bound regions" to
2010 // represent regions that are part of the suspended
2011 // generator frame. Bound regions are preserved by
2012 // `erase_regions` and so we must also call
2013 // `erase_late_bound_regions`.
2014 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2015 let ty_erased = self.tcx.erase_regions(ty_erased);
2016 let eq = ty_erased == target_ty_erased;
2017 debug!(?ty_erased, ?target_ty_erased, ?eq);
2021 // Get the typeck results from the infcx if the generator is the function we are currently
2022 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2023 // cycles. If we can't use resolved types because the generator comes from another crate,
2024 // we still provide a targeted error but without all the relevant spans.
2025 let generator_data = match &self.typeck_results {
2026 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2027 _ if generator_did.is_local() => {
2028 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2030 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2031 GeneratorData::Foreign(generator_diag_data)
2036 let mut interior_or_upvar_span = None;
2038 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2039 debug!(?from_awaited_ty);
2041 // The generator interior types share the same binders
2042 if let Some(cause) =
2043 generator_data.get_generator_interior_types().skip_binder().iter().find(
2044 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2045 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2049 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2051 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2053 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2057 if interior_or_upvar_span.is_none() {
2058 interior_or_upvar_span =
2059 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2062 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2063 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2066 debug!(?interior_or_upvar_span);
2067 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2068 let is_async = self.tcx.generator_is_async(generator_did);
2069 let typeck_results = match generator_data {
2070 GeneratorData::Local(typeck_results) => Some(typeck_results),
2071 GeneratorData::Foreign(_) => None,
2073 self.note_obligation_cause_for_async_await(
2075 interior_or_upvar_span,
2090 /// Unconditionally adds the diagnostic note described in
2091 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2092 #[instrument(level = "debug", skip_all)]
2093 fn note_obligation_cause_for_async_await(
2095 err: &mut Diagnostic,
2096 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2098 outer_generator: Option<DefId>,
2099 trait_pred: ty::TraitPredicate<'tcx>,
2100 target_ty: Ty<'tcx>,
2101 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2102 obligation: &PredicateObligation<'tcx>,
2103 next_code: Option<&ObligationCauseCode<'tcx>>,
2105 let source_map = self.tcx.sess.source_map();
2107 let (await_or_yield, an_await_or_yield) =
2108 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2109 let future_or_generator = if is_async { "future" } else { "generator" };
2111 // Special case the primary error message when send or sync is the trait that was
2113 let hir = self.tcx.hir();
2114 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2115 self.tcx.get_diagnostic_name(trait_pred.def_id())
2117 let (trait_name, trait_verb) =
2118 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2121 err.set_primary_message(format!(
2122 "{} cannot be {} between threads safely",
2123 future_or_generator, trait_verb
2126 let original_span = err.span.primary_span().unwrap();
2127 let mut span = MultiSpan::from_span(original_span);
2129 let message = outer_generator
2130 .and_then(|generator_did| {
2131 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2132 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2133 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2135 .parent(generator_did)
2137 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2138 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2140 format!("future returned by `{}` is not {}", name, trait_name)
2142 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2143 format!("future created by async block is not {}", trait_name)
2145 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2146 format!("future created by async closure is not {}", trait_name)
2150 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2152 span.push_span_label(original_span, message);
2155 format!("is not {}", trait_name)
2157 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2160 let mut explain_yield = |interior_span: Span,
2162 scope_span: Option<Span>| {
2163 let mut span = MultiSpan::from_span(yield_span);
2164 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
2165 // #70935: If snippet contains newlines, display "the value" instead
2166 // so that we do not emit complex diagnostics.
2167 let snippet = &format!("`{}`", snippet);
2168 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
2169 // note: future is not `Send` as this value is used across an await
2170 // --> $DIR/issue-70935-complex-spans.rs:13:9
2172 // LL | baz(|| async {
2173 // | ______________-
2176 // LL | | foo(tx.clone());
2178 // | | - ^^^^^^ await occurs here, with value maybe used later
2180 // | has type `closure` which is not `Send`
2181 // note: value is later dropped here
2185 span.push_span_label(
2187 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2189 span.push_span_label(
2191 format!("has type `{}` which {}", target_ty, trait_explanation),
2193 // If available, use the scope span to annotate the drop location.
2194 let mut scope_note = None;
2195 if let Some(scope_span) = scope_span {
2196 let scope_span = source_map.end_point(scope_span);
2198 let msg = format!("{} is later dropped here", snippet);
2199 if source_map.is_multiline(yield_span.between(scope_span)) {
2200 span.push_span_label(scope_span, msg);
2202 scope_note = Some((scope_span, msg));
2208 "{} {} as this value is used across {}",
2209 future_or_generator, trait_explanation, an_await_or_yield
2212 if let Some((span, msg)) = scope_note {
2213 err.span_note(span, &msg);
2217 match interior_or_upvar_span {
2218 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2219 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2220 if let Some(await_span) = from_awaited_ty {
2221 // The type causing this obligation is one being awaited at await_span.
2222 let mut span = MultiSpan::from_span(await_span);
2223 span.push_span_label(
2226 "await occurs here on type `{}`, which {}",
2227 target_ty, trait_explanation
2233 "future {not_trait} as it awaits another future which {not_trait}",
2234 not_trait = trait_explanation
2238 // Look at the last interior type to get a span for the `.await`.
2240 generator_interior_types = ?format_args!(
2241 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2244 explain_yield(interior_span, yield_span, scope_span);
2247 if let Some(expr_id) = expr {
2248 let expr = hir.expect_expr(expr_id);
2249 debug!("target_ty evaluated from {:?}", expr);
2251 let parent = hir.get_parent_node(expr_id);
2252 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2253 let parent_span = hir.span(parent);
2254 let parent_did = parent.owner.to_def_id();
2257 // fn foo(&self) -> i32 {}
2260 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2263 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2265 .expr_adjustments(expr)
2267 .any(|adj| adj.is_region_borrow())
2273 // struct Foo(*const u8);
2274 // bar(Foo(std::ptr::null())).await;
2275 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2277 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2278 let is_raw_borrow_inside_fn_like_call =
2279 match self.tcx.def_kind(parent_did) {
2280 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2283 if let Some(typeck_results) = typeck_results {
2284 if (typeck_results.is_method_call(e) && is_region_borrow)
2285 || is_raw_borrow_inside_fn_like_call
2289 "consider moving this into a `let` \
2290 binding to create a shorter lived borrow",
2298 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2299 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2300 let refers_to_non_sync = match target_ty.kind() {
2301 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2302 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2308 let (span_label, span_note) = match refers_to_non_sync {
2309 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2310 // include suggestions to make `T: Sync` so that `&T: Send`
2313 "has type `{}` which {}, because `{}` is not `Sync`",
2314 target_ty, trait_explanation, ref_ty
2317 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2322 format!("has type `{}` which {}", target_ty, trait_explanation),
2323 format!("captured value {}", trait_explanation),
2327 let mut span = MultiSpan::from_span(upvar_span);
2328 span.push_span_label(upvar_span, span_label);
2329 err.span_note(span, &span_note);
2333 // Add a note for the item obligation that remains - normally a note pointing to the
2334 // bound that introduced the obligation (e.g. `T: Send`).
2336 self.note_obligation_cause_code(
2338 &obligation.predicate,
2339 obligation.param_env,
2342 &mut Default::default(),
2346 fn note_obligation_cause_code<T>(
2348 err: &mut Diagnostic,
2350 param_env: ty::ParamEnv<'tcx>,
2351 cause_code: &ObligationCauseCode<'tcx>,
2352 obligated_types: &mut Vec<Ty<'tcx>>,
2353 seen_requirements: &mut FxHashSet<DefId>,
2359 ObligationCauseCode::ExprAssignable
2360 | ObligationCauseCode::MatchExpressionArm { .. }
2361 | ObligationCauseCode::Pattern { .. }
2362 | ObligationCauseCode::IfExpression { .. }
2363 | ObligationCauseCode::IfExpressionWithNoElse
2364 | ObligationCauseCode::MainFunctionType
2365 | ObligationCauseCode::StartFunctionType
2366 | ObligationCauseCode::IntrinsicType
2367 | ObligationCauseCode::MethodReceiver
2368 | ObligationCauseCode::ReturnNoExpression
2369 | ObligationCauseCode::UnifyReceiver(..)
2370 | ObligationCauseCode::OpaqueType
2371 | ObligationCauseCode::MiscObligation
2372 | ObligationCauseCode::WellFormed(..)
2373 | ObligationCauseCode::MatchImpl(..)
2374 | ObligationCauseCode::ReturnType
2375 | ObligationCauseCode::ReturnValue(_)
2376 | ObligationCauseCode::BlockTailExpression(_)
2377 | ObligationCauseCode::AwaitableExpr(_)
2378 | ObligationCauseCode::ForLoopIterator
2379 | ObligationCauseCode::QuestionMark
2380 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2381 | ObligationCauseCode::LetElse
2382 | ObligationCauseCode::BinOp { .. }
2383 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2384 | ObligationCauseCode::RustCall => {}
2385 ObligationCauseCode::SliceOrArrayElem => {
2386 err.note("slice and array elements must have `Sized` type");
2388 ObligationCauseCode::TupleElem => {
2389 err.note("only the last element of a tuple may have a dynamically sized type");
2391 ObligationCauseCode::ProjectionWf(data) => {
2392 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2394 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2396 "required so that reference `{}` does not outlive its referent",
2400 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2402 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2406 ObligationCauseCode::ItemObligation(_)
2407 | ObligationCauseCode::ExprItemObligation(..) => {
2408 // We hold the `DefId` of the item introducing the obligation, but displaying it
2409 // doesn't add user usable information. It always point at an associated item.
2411 ObligationCauseCode::BindingObligation(item_def_id, span)
2412 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2413 let item_name = tcx.def_path_str(item_def_id);
2414 let mut multispan = MultiSpan::from(span);
2415 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2416 let sm = tcx.sess.source_map();
2418 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2419 (Ok(l), Ok(r)) => l.line == r.line,
2422 if !ident.span.is_dummy() && !ident.span.overlaps(span) && !same_line {
2423 multispan.push_span_label(ident.span, "required by a bound in this");
2426 let descr = format!("required by a bound in `{}`", item_name);
2427 if !span.is_dummy() {
2428 let msg = format!("required by this bound in `{}`", item_name);
2429 multispan.push_span_label(span, msg);
2430 err.span_note(multispan, &descr);
2432 err.span_note(tcx.def_span(item_def_id), &descr);
2435 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2437 "required for the cast from `{}` to the object type `{}`",
2438 self.ty_to_string(concrete_ty),
2439 self.ty_to_string(object_ty)
2442 ObligationCauseCode::Coercion { source: _, target } => {
2443 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2445 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2447 "the `Copy` trait is required because this value will be copied for each element of the array",
2452 "consider creating a new `const` item and initializing it with the result \
2453 of the function call to be used in the repeat position, like \
2454 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2458 if self.tcx.sess.is_nightly_build() && is_const_fn {
2460 "create an inline `const` block, see RFC #2920 \
2461 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2465 ObligationCauseCode::VariableType(hir_id) => {
2466 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2467 match self.tcx.hir().find(parent_node) {
2468 Some(Node::Local(hir::Local {
2469 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2472 // When encountering an assignment of an unsized trait, like
2473 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2474 // order to use have a slice instead.
2475 err.span_suggestion_verbose(
2476 span.shrink_to_lo(),
2477 "consider borrowing here",
2479 Applicability::MachineApplicable,
2481 err.note("all local variables must have a statically known size");
2483 Some(Node::Param(param)) => {
2484 err.span_suggestion_verbose(
2485 param.ty_span.shrink_to_lo(),
2486 "function arguments must have a statically known size, borrowed types \
2487 always have a known size",
2489 Applicability::MachineApplicable,
2493 err.note("all local variables must have a statically known size");
2496 if !self.tcx.features().unsized_locals {
2497 err.help("unsized locals are gated as an unstable feature");
2500 ObligationCauseCode::SizedArgumentType(sp) => {
2501 if let Some(span) = sp {
2502 err.span_suggestion_verbose(
2503 span.shrink_to_lo(),
2504 "function arguments must have a statically known size, borrowed types \
2505 always have a known size",
2507 Applicability::MachineApplicable,
2510 err.note("all function arguments must have a statically known size");
2512 if tcx.sess.opts.unstable_features.is_nightly_build()
2513 && !self.tcx.features().unsized_fn_params
2515 err.help("unsized fn params are gated as an unstable feature");
2518 ObligationCauseCode::SizedReturnType => {
2519 err.note("the return type of a function must have a statically known size");
2521 ObligationCauseCode::SizedYieldType => {
2522 err.note("the yield type of a generator must have a statically known size");
2524 ObligationCauseCode::SizedBoxType => {
2525 err.note("the type of a box expression must have a statically known size");
2527 ObligationCauseCode::AssignmentLhsSized => {
2528 err.note("the left-hand-side of an assignment must have a statically known size");
2530 ObligationCauseCode::TupleInitializerSized => {
2531 err.note("tuples must have a statically known size to be initialized");
2533 ObligationCauseCode::StructInitializerSized => {
2534 err.note("structs must have a statically known size to be initialized");
2536 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2538 AdtKind::Struct => {
2541 "the last field of a packed struct may only have a \
2542 dynamically sized type if it does not need drop to be run",
2546 "only the last field of a struct may have a dynamically sized type",
2551 err.note("no field of a union may have a dynamically sized type");
2554 err.note("no field of an enum variant may have a dynamically sized type");
2557 err.help("change the field's type to have a statically known size");
2558 err.span_suggestion(
2559 span.shrink_to_lo(),
2560 "borrowed types always have a statically known size",
2562 Applicability::MachineApplicable,
2564 err.multipart_suggestion(
2565 "the `Box` type always has a statically known size and allocates its contents \
2568 (span.shrink_to_lo(), "Box<".to_string()),
2569 (span.shrink_to_hi(), ">".to_string()),
2571 Applicability::MachineApplicable,
2574 ObligationCauseCode::ConstSized => {
2575 err.note("constant expressions must have a statically known size");
2577 ObligationCauseCode::InlineAsmSized => {
2578 err.note("all inline asm arguments must have a statically known size");
2580 ObligationCauseCode::ConstPatternStructural => {
2581 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2583 ObligationCauseCode::SharedStatic => {
2584 err.note("shared static variables must have a type that implements `Sync`");
2586 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2587 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2588 let ty = parent_trait_ref.skip_binder().self_ty();
2589 if parent_trait_ref.references_error() {
2590 // NOTE(eddyb) this was `.cancel()`, but `err`
2591 // is borrowed, so we can't fully defuse it.
2592 err.downgrade_to_delayed_bug();
2596 // If the obligation for a tuple is set directly by a Generator or Closure,
2597 // then the tuple must be the one containing capture types.
2598 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2601 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2603 let parent_trait_ref =
2604 self.resolve_vars_if_possible(data.parent_trait_pred);
2605 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2606 matches!(nested_ty.kind(), ty::Generator(..))
2607 || matches!(nested_ty.kind(), ty::Closure(..))
2613 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2615 // Don't print the tuple of capture types
2617 if !is_upvar_tys_infer_tuple {
2618 let msg = format!("required because it appears within the type `{}`", ty);
2620 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2621 Some(ident) => err.span_note(ident.span, &msg),
2622 None => err.note(&msg),
2624 ty::Opaque(def_id, _) => {
2625 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2626 if tcx.parent(*def_id) == identity_future {
2630 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2631 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2632 let is_future = tcx.ty_is_opaque_future(ty);
2636 "note_obligation_cause_code: check for async fn"
2639 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2640 ty::Generator(last_def_id, ..) => {
2641 tcx.generator_is_async(*last_def_id)
2648 err.span_note(self.tcx.def_span(def_id), &msg)
2650 ty::GeneratorWitness(bound_tys) => {
2651 use std::fmt::Write;
2653 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2654 // Maybe we should just remove this note altogether?
2655 // FIXME: only print types which don't meet the trait requirement
2657 "required because it captures the following types: ".to_owned();
2658 for ty in bound_tys.skip_binder() {
2659 write!(msg, "`{}`, ", ty).unwrap();
2661 err.note(msg.trim_end_matches(", "))
2663 ty::Generator(def_id, _, _) => {
2664 let sp = self.tcx.def_span(def_id);
2666 // Special-case this to say "async block" instead of `[static generator]`.
2667 let kind = tcx.generator_kind(def_id).unwrap().descr();
2670 &format!("required because it's used within this {}", kind),
2673 ty::Closure(def_id, _) => err.span_note(
2674 self.tcx.def_span(def_id),
2675 &format!("required because it's used within this closure"),
2677 _ => err.note(&msg),
2682 obligated_types.push(ty);
2684 let parent_predicate = parent_trait_ref;
2685 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2686 // #74711: avoid a stack overflow
2687 ensure_sufficient_stack(|| {
2688 self.note_obligation_cause_code(
2698 ensure_sufficient_stack(|| {
2699 self.note_obligation_cause_code(
2703 cause_code.peel_derives(),
2710 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2711 let mut parent_trait_pred =
2712 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2713 parent_trait_pred.remap_constness_diag(param_env);
2714 let parent_def_id = parent_trait_pred.def_id();
2715 let (self_ty, file) =
2716 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2718 "required for `{self_ty}` to implement `{}`",
2719 parent_trait_pred.print_modifiers_and_trait_path()
2721 let mut is_auto_trait = false;
2722 match self.tcx.hir().get_if_local(data.impl_def_id) {
2723 Some(Node::Item(hir::Item {
2724 kind: hir::ItemKind::Trait(is_auto, ..),
2728 // FIXME: we should do something else so that it works even on crate foreign
2730 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2731 err.span_note(ident.span, &msg)
2733 Some(Node::Item(hir::Item {
2734 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2737 let mut spans = Vec::with_capacity(2);
2738 if let Some(trait_ref) = of_trait {
2739 spans.push(trait_ref.path.span);
2741 spans.push(self_ty.span);
2742 err.span_note(spans, &msg)
2744 _ => err.note(&msg),
2747 if let Some(file) = file {
2749 "the full type name has been written to '{}'",
2753 let mut parent_predicate = parent_trait_pred;
2754 let mut data = &data.derived;
2756 seen_requirements.insert(parent_def_id);
2758 // We don't want to point at the ADT saying "required because it appears within
2759 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2760 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2763 let child_trait_ref =
2764 self.resolve_vars_if_possible(derived.parent_trait_pred);
2765 let child_def_id = child_trait_ref.def_id();
2766 if seen_requirements.insert(child_def_id) {
2770 parent_predicate = child_trait_ref.to_predicate(tcx);
2771 parent_trait_pred = child_trait_ref;
2774 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2775 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2776 let child_trait_pred =
2777 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2778 let child_def_id = child_trait_pred.def_id();
2779 if seen_requirements.insert(child_def_id) {
2783 data = &child.derived;
2784 parent_predicate = child_trait_pred.to_predicate(tcx);
2785 parent_trait_pred = child_trait_pred;
2789 "{} redundant requirement{} hidden",
2793 let (self_ty, file) =
2794 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2796 "required for `{self_ty}` to implement `{}`",
2797 parent_trait_pred.print_modifiers_and_trait_path()
2799 if let Some(file) = file {
2801 "the full type name has been written to '{}'",
2806 // #74711: avoid a stack overflow
2807 ensure_sufficient_stack(|| {
2808 self.note_obligation_cause_code(
2818 ObligationCauseCode::DerivedObligation(ref data) => {
2819 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2820 let parent_predicate = parent_trait_ref;
2821 // #74711: avoid a stack overflow
2822 ensure_sufficient_stack(|| {
2823 self.note_obligation_cause_code(
2833 ObligationCauseCode::FunctionArgumentObligation {
2838 let hir = self.tcx.hir();
2839 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2840 hir.find(arg_hir_id)
2842 let parent_id = hir.get_parent_item(arg_hir_id);
2843 let typeck_results: &TypeckResults<'tcx> = match &self.typeck_results {
2844 Some(t) if t.hir_owner == parent_id => t,
2845 _ => self.tcx.typeck(parent_id.def_id),
2847 let expr = expr.peel_blocks();
2848 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
2849 let span = expr.span;
2850 if Some(span) != err.span.primary_span() {
2853 if ty.references_error() {
2856 format!("this tail expression is of type `{:?}`", ty)
2861 if let Some(Node::Expr(hir::Expr {
2863 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2864 | hir::ExprKind::MethodCall(
2865 hir::PathSegment { ident: Ident { span, .. }, .. },
2869 })) = hir.find(call_hir_id)
2871 if Some(*span) != err.span.primary_span() {
2872 err.span_label(*span, "required by a bound introduced by this call");
2875 ensure_sufficient_stack(|| {
2876 self.note_obligation_cause_code(
2886 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2887 let item_name = self.tcx.item_name(trait_item_def_id);
2889 "the requirement `{}` appears on the `impl`'s {kind} `{}` but not on the \
2890 corresponding trait's {kind}",
2891 predicate, item_name,
2895 .opt_item_ident(trait_item_def_id)
2897 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2898 let mut assoc_span: MultiSpan = sp.into();
2899 assoc_span.push_span_label(
2901 format!("this trait's {kind} doesn't have the requirement `{}`", predicate),
2903 if let Some(ident) = self
2905 .opt_associated_item(trait_item_def_id)
2906 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2908 assoc_span.push_span_label(ident.span, "in this trait");
2910 err.span_note(assoc_span, &msg);
2912 ObligationCauseCode::TrivialBound => {
2913 err.help("see issue #48214");
2914 if tcx.sess.opts.unstable_features.is_nightly_build() {
2915 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2918 ObligationCauseCode::OpaqueReturnType(expr_info) => {
2919 if let Some((expr_ty, expr_span)) = expr_info {
2920 let expr_ty = self.resolve_vars_if_possible(expr_ty);
2923 format!("return type was inferred to be `{expr_ty}` here"),
2931 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2933 fn suggest_await_before_try(
2935 err: &mut Diagnostic,
2936 obligation: &PredicateObligation<'tcx>,
2937 trait_pred: ty::PolyTraitPredicate<'tcx>,
2940 let body_hir_id = obligation.cause.body_id;
2941 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2943 if let Some(body_id) =
2944 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2946 let body = self.tcx.hir().body(body_id);
2947 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2948 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2950 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2951 let impls_future = self.type_implements_trait(
2953 [self.tcx.erase_late_bound_regions(self_ty)],
2954 obligation.param_env,
2956 if !impls_future.must_apply_modulo_regions() {
2960 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2961 // `<T as Future>::Output`
2962 let projection_ty = trait_pred.map_bound(|trait_pred| {
2963 self.tcx.mk_projection(
2965 // Future::Output has no substs
2966 self.tcx.mk_substs_trait(trait_pred.self_ty(), []),
2969 let InferOk { value: projection_ty, .. } = self
2970 .partially_normalize_associated_types_in(
2971 obligation.cause.clone(),
2972 obligation.param_env,
2977 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
2979 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2980 obligation.param_env,
2981 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
2983 debug!(try_trait_obligation = ?try_obligation);
2984 if self.predicate_may_hold(&try_obligation)
2985 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2986 && snippet.ends_with('?')
2988 err.span_suggestion_verbose(
2989 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2990 "consider `await`ing on the `Future`",
2992 Applicability::MaybeIncorrect,
2999 fn suggest_floating_point_literal(
3001 obligation: &PredicateObligation<'tcx>,
3002 err: &mut Diagnostic,
3003 trait_ref: &ty::PolyTraitRef<'tcx>,
3005 let rhs_span = match obligation.cause.code() {
3006 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3009 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3010 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3012 err.span_suggestion_verbose(
3013 rhs_span.shrink_to_hi(),
3014 "consider using a floating-point literal by writing it with `.0`",
3016 Applicability::MaybeIncorrect,
3023 obligation: &PredicateObligation<'tcx>,
3024 err: &mut Diagnostic,
3025 trait_pred: ty::PolyTraitPredicate<'tcx>,
3027 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3030 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3031 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3035 let is_derivable_trait = match diagnostic_name {
3036 sym::Default => !adt.is_enum(),
3037 sym::PartialEq | sym::PartialOrd => {
3038 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3039 trait_pred.skip_binder().self_ty() == rhs_ty
3041 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3044 is_derivable_trait &&
3045 // Ensure all fields impl the trait.
3046 adt.all_fields().all(|field| {
3047 let field_ty = field.ty(self.tcx, substs);
3048 let trait_substs = match diagnostic_name {
3049 sym::PartialEq | sym::PartialOrd => {
3054 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3055 trait_ref: self.tcx.mk_trait_ref(
3056 trait_pred.def_id(),
3057 [field_ty].into_iter().chain(trait_substs),
3061 let field_obl = Obligation::new(
3063 obligation.cause.clone(),
3064 obligation.param_env,
3067 self.predicate_must_hold_modulo_regions(&field_obl)
3071 err.span_suggestion_verbose(
3072 self.tcx.def_span(adt.did()).shrink_to_lo(),
3074 "consider annotating `{}` with `#[derive({})]`",
3075 trait_pred.skip_binder().self_ty(),
3078 format!("#[derive({})]\n", diagnostic_name),
3079 Applicability::MaybeIncorrect,
3084 fn suggest_dereferencing_index(
3086 obligation: &PredicateObligation<'tcx>,
3087 err: &mut Diagnostic,
3088 trait_pred: ty::PolyTraitPredicate<'tcx>,
3090 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3091 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3092 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3093 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3094 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3096 err.span_suggestion_verbose(
3097 obligation.cause.span.shrink_to_lo(),
3098 "dereference this index",
3100 Applicability::MachineApplicable,
3106 /// Collect all the returned expressions within the input expression.
3107 /// Used to point at the return spans when we want to suggest some change to them.
3109 pub struct ReturnsVisitor<'v> {
3110 pub returns: Vec<&'v hir::Expr<'v>>,
3111 in_block_tail: bool,
3114 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3115 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3116 // Visit every expression to detect `return` paths, either through the function's tail
3117 // expression or `return` statements. We walk all nodes to find `return` statements, but
3118 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3119 // they're in the return path of the function body.
3121 hir::ExprKind::Ret(Some(ex)) => {
3122 self.returns.push(ex);
3124 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3125 self.in_block_tail = false;
3126 for stmt in block.stmts {
3127 hir::intravisit::walk_stmt(self, stmt);
3129 self.in_block_tail = true;
3130 if let Some(expr) = block.expr {
3131 self.visit_expr(expr);
3134 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3135 self.visit_expr(then);
3136 if let Some(el) = else_opt {
3137 self.visit_expr(el);
3140 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3142 self.visit_expr(arm.body);
3145 // We need to walk to find `return`s in the entire body.
3146 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3147 _ => self.returns.push(ex),
3151 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3152 assert!(!self.in_block_tail);
3153 if body.generator_kind().is_none() {
3154 if let hir::ExprKind::Block(block, None) = body.value.kind {
3155 if block.expr.is_some() {
3156 self.in_block_tail = true;
3160 hir::intravisit::walk_body(self, body);
3164 /// Collect all the awaited expressions within the input expression.
3166 struct AwaitsVisitor {
3167 awaits: Vec<hir::HirId>,
3170 impl<'v> Visitor<'v> for AwaitsVisitor {
3171 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3172 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3173 self.awaits.push(id)
3175 hir::intravisit::walk_expr(self, ex)
3179 pub trait NextTypeParamName {
3180 fn next_type_param_name(&self, name: Option<&str>) -> String;
3183 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3184 fn next_type_param_name(&self, name: Option<&str>) -> String {
3185 // This is the list of possible parameter names that we might suggest.
3186 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3187 let name = name.as_deref();
3188 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3189 let used_names = self
3191 .filter_map(|p| match p.name {
3192 hir::ParamName::Plain(ident) => Some(ident.name),
3195 .collect::<Vec<_>>();
3199 .find(|n| !used_names.contains(&Symbol::intern(n)))
3200 .unwrap_or(&"ParamName")
3205 fn suggest_trait_object_return_type_alternatives(
3206 err: &mut Diagnostic,
3209 is_object_safe: bool,
3211 err.span_suggestion(
3213 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3216 Applicability::MaybeIncorrect,
3218 err.span_suggestion(
3221 "use `impl {}` as the return type if all return paths have the same type but you \
3222 want to expose only the trait in the signature",
3225 format!("impl {}", trait_obj),
3226 Applicability::MaybeIncorrect,
3229 err.multipart_suggestion(
3231 "use a boxed trait object if all return paths implement trait `{}`",
3235 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3236 (ret_ty.shrink_to_hi(), ">".to_string()),
3238 Applicability::MaybeIncorrect,
3243 /// Collect the spans that we see the generic param `param_did`
3244 struct ReplaceImplTraitVisitor<'a> {
3245 ty_spans: &'a mut Vec<Span>,
3249 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3250 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3251 if let hir::TyKind::Path(hir::QPath::Resolved(
3253 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3256 if self.param_did == *segment_did {
3257 // `fn foo(t: impl Trait)`
3258 // ^^^^^^^^^^ get this to suggest `T` instead
3260 // There might be more than one `impl Trait`.
3261 self.ty_spans.push(t.span);
3266 hir::intravisit::walk_ty(self, t);
3270 // Replace `param` with `replace_ty`
3271 struct ReplaceImplTraitFolder<'tcx> {
3273 param: &'tcx ty::GenericParamDef,
3274 replace_ty: Ty<'tcx>,
3277 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3278 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3279 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3280 if self.param.index == *index {
3281 return self.replace_ty;
3284 t.super_fold_with(self)
3287 fn tcx(&self) -> TyCtxt<'tcx> {