1 use super::{DefIdOrName, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation};
3 use crate::autoderef::Autoderef;
4 use crate::infer::InferCtxt;
5 use crate::traits::NormalizeExt;
9 use rustc_data_structures::fx::FxHashSet;
10 use rustc_data_structures::stack::ensure_sufficient_stack;
12 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
13 ErrorGuaranteed, MultiSpan, Style,
16 use rustc_hir::def::DefKind;
17 use rustc_hir::def_id::DefId;
18 use rustc_hir::intravisit::Visitor;
19 use rustc_hir::lang_items::LangItem;
20 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
21 use rustc_infer::infer::error_reporting::TypeErrCtxt;
22 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
23 use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime};
24 use rustc_middle::hir::map;
25 use rustc_middle::ty::{
26 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
27 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, IsSuggestable,
28 ToPredicate, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable,
30 use rustc_middle::ty::{TypeAndMut, TypeckResults};
31 use rustc_span::symbol::{sym, Ident, Symbol};
32 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
33 use rustc_target::spec::abi;
36 use super::InferCtxtPrivExt;
37 use crate::infer::InferCtxtExt as _;
38 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
39 use rustc_middle::ty::print::with_no_trimmed_paths;
42 pub enum GeneratorInteriorOrUpvar {
43 // span of interior type
44 Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
49 // This type provides a uniform interface to retrieve data on generators, whether it originated from
50 // the local crate being compiled or from a foreign crate.
52 pub enum GeneratorData<'tcx, 'a> {
53 Local(&'a TypeckResults<'tcx>),
54 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
57 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
58 // Try to get information about variables captured by the generator that matches a type we are
59 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
61 fn try_get_upvar_span<F>(
63 infer_context: &InferCtxt<'tcx>,
66 ) -> Option<GeneratorInteriorOrUpvar>
68 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
71 GeneratorData::Local(typeck_results) => {
72 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
73 upvars.iter().find_map(|(upvar_id, upvar)| {
74 let upvar_ty = typeck_results.node_type(*upvar_id);
75 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
76 if ty_matches(ty::Binder::dummy(upvar_ty)) {
77 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
84 GeneratorData::Foreign(_) => None,
88 // Try to get the span of a type being awaited on that matches the type we are looking with the
89 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
91 fn get_from_await_ty<F>(
93 visitor: AwaitsVisitor,
98 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
101 GeneratorData::Local(typeck_results) => visitor
104 .map(|id| hir.expect_expr(id))
106 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
108 .map(|expr| expr.span),
109 GeneratorData::Foreign(generator_diagnostic_data) => visitor
112 .map(|id| hir.expect_expr(id))
114 ty_matches(ty::Binder::dummy(
115 generator_diagnostic_data
117 .get(&await_expr.hir_id.local_id)
118 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
120 .map_or_else::<Ty<'tcx>, _, _>(
122 generator_diagnostic_data
124 .get(&await_expr.hir_id.local_id)
128 "node_type: no type for node `{}`",
129 ty::tls::with(|tcx| tcx
131 .node_to_string(await_expr.hir_id))
139 .map(|expr| expr.span),
143 /// Get the type, expression, span and optional scope span of all types
144 /// that are live across the yield of this generator
145 fn get_generator_interior_types(
147 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
149 GeneratorData::Local(typeck_result) => {
150 typeck_result.generator_interior_types.as_deref()
152 GeneratorData::Foreign(generator_diagnostic_data) => {
153 generator_diagnostic_data.generator_interior_types.as_deref()
158 // Used to get the source of the data, note we don't have as much information for generators
159 // originated from foreign crates
160 fn is_foreign(&self) -> bool {
162 GeneratorData::Local(_) => false,
163 GeneratorData::Foreign(_) => true,
168 // This trait is public to expose the diagnostics methods to clippy.
169 pub trait TypeErrCtxtExt<'tcx> {
170 fn suggest_restricting_param_bound(
172 err: &mut Diagnostic,
173 trait_pred: ty::PolyTraitPredicate<'tcx>,
174 associated_item: Option<(&'static str, Ty<'tcx>)>,
178 fn suggest_dereferences(
180 obligation: &PredicateObligation<'tcx>,
181 err: &mut Diagnostic,
182 trait_pred: ty::PolyTraitPredicate<'tcx>,
185 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
189 obligation: &PredicateObligation<'tcx>,
190 err: &mut Diagnostic,
191 trait_pred: ty::PolyTraitPredicate<'tcx>,
194 fn suggest_add_reference_to_arg(
196 obligation: &PredicateObligation<'tcx>,
197 err: &mut Diagnostic,
198 trait_pred: ty::PolyTraitPredicate<'tcx>,
199 has_custom_message: bool,
202 fn suggest_borrowing_for_object_cast(
204 err: &mut Diagnostic,
205 obligation: &PredicateObligation<'tcx>,
210 fn suggest_remove_reference(
212 obligation: &PredicateObligation<'tcx>,
213 err: &mut Diagnostic,
214 trait_pred: ty::PolyTraitPredicate<'tcx>,
217 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
219 fn suggest_change_mut(
221 obligation: &PredicateObligation<'tcx>,
222 err: &mut Diagnostic,
223 trait_pred: ty::PolyTraitPredicate<'tcx>,
226 fn suggest_semicolon_removal(
228 obligation: &PredicateObligation<'tcx>,
229 err: &mut Diagnostic,
231 trait_pred: ty::PolyTraitPredicate<'tcx>,
234 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
236 fn suggest_impl_trait(
238 err: &mut Diagnostic,
240 obligation: &PredicateObligation<'tcx>,
241 trait_pred: ty::PolyTraitPredicate<'tcx>,
244 fn point_at_returns_when_relevant(
246 err: &mut Diagnostic,
247 obligation: &PredicateObligation<'tcx>,
250 fn report_closure_arg_mismatch(
253 found_span: Option<Span>,
254 found: ty::PolyTraitRef<'tcx>,
255 expected: ty::PolyTraitRef<'tcx>,
256 cause: &ObligationCauseCode<'tcx>,
257 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
259 fn note_conflicting_closure_bounds(
261 cause: &ObligationCauseCode<'tcx>,
262 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
265 fn suggest_fully_qualified_path(
267 err: &mut Diagnostic,
273 fn maybe_note_obligation_cause_for_async_await(
275 err: &mut Diagnostic,
276 obligation: &PredicateObligation<'tcx>,
279 fn note_obligation_cause_for_async_await(
281 err: &mut Diagnostic,
282 interior_or_upvar_span: GeneratorInteriorOrUpvar,
284 outer_generator: Option<DefId>,
285 trait_pred: ty::TraitPredicate<'tcx>,
287 typeck_results: Option<&ty::TypeckResults<'tcx>>,
288 obligation: &PredicateObligation<'tcx>,
289 next_code: Option<&ObligationCauseCode<'tcx>>,
292 fn note_obligation_cause_code<T>(
294 err: &mut Diagnostic,
296 param_env: ty::ParamEnv<'tcx>,
297 cause_code: &ObligationCauseCode<'tcx>,
298 obligated_types: &mut Vec<Ty<'tcx>>,
299 seen_requirements: &mut FxHashSet<DefId>,
301 T: fmt::Display + ToPredicate<'tcx, T>;
303 /// Suggest to await before try: future? => future.await?
304 fn suggest_await_before_try(
306 err: &mut Diagnostic,
307 obligation: &PredicateObligation<'tcx>,
308 trait_pred: ty::PolyTraitPredicate<'tcx>,
312 fn suggest_floating_point_literal(
314 obligation: &PredicateObligation<'tcx>,
315 err: &mut Diagnostic,
316 trait_ref: &ty::PolyTraitRef<'tcx>,
321 obligation: &PredicateObligation<'tcx>,
322 err: &mut Diagnostic,
323 trait_pred: ty::PolyTraitPredicate<'tcx>,
326 fn suggest_dereferencing_index(
328 obligation: &PredicateObligation<'tcx>,
329 err: &mut Diagnostic,
330 trait_pred: ty::PolyTraitPredicate<'tcx>,
334 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
336 generics.tail_span_for_predicate_suggestion(),
337 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
341 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
342 /// it can also be an `impl Trait` param that needs to be decomposed to a type
343 /// param for cleaner code.
344 fn suggest_restriction<'tcx>(
347 hir_generics: &hir::Generics<'tcx>,
349 err: &mut Diagnostic,
350 fn_sig: Option<&hir::FnSig<'_>>,
351 projection: Option<&ty::ProjectionTy<'_>>,
352 trait_pred: ty::PolyTraitPredicate<'tcx>,
353 // When we are dealing with a trait, `super_traits` will be `Some`:
354 // Given `trait T: A + B + C {}`
355 // - ^^^^^^^^^ GenericBounds
358 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
360 if hir_generics.where_clause_span.from_expansion()
361 || hir_generics.where_clause_span.desugaring_kind().is_some()
365 let Some(item_id) = hir_id.as_owner() else { return; };
366 let generics = tcx.generics_of(item_id);
367 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
368 if let Some((param, bound_str, fn_sig)) =
369 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
370 // Shenanigans to get the `Trait` from the `impl Trait`.
371 ty::Param(param) => {
372 let param_def = generics.type_param(param, tcx);
373 if param_def.kind.is_synthetic() {
375 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
376 return Some((param_def, bound_str, sig));
383 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
384 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
387 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
390 if !trait_pred.is_suggestable(tcx, false) {
393 // We know we have an `impl Trait` that doesn't satisfy a required projection.
395 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
396 // types. There should be at least one, but there might be *more* than one. In that
397 // case we could just ignore it and try to identify which one needs the restriction,
398 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
400 let mut ty_spans = vec![];
401 for input in fn_sig.decl.inputs {
402 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
405 // The type param `T: Trait` we will suggest to introduce.
406 let type_param = format!("{}: {}", type_param_name, bound_str);
409 if let Some(span) = hir_generics.span_for_param_suggestion() {
410 (span, format!(", {}", type_param))
412 (hir_generics.span, format!("<{}>", type_param))
414 // `fn foo(t: impl Trait)`
415 // ^ suggest `where <T as Trait>::A: Bound`
416 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
418 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
420 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
421 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
422 // `fn foo(t: impl Trait<A: Bound>)` instead.
423 err.multipart_suggestion(
424 "introduce a type parameter with a trait bound instead of using `impl Trait`",
426 Applicability::MaybeIncorrect,
429 if !trait_pred.is_suggestable(tcx, false) {
432 // Trivial case: `T` needs an extra bound: `T: Bound`.
433 let (sp, suggestion) = match (
437 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
440 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
441 (None, Some((ident, []))) => (
442 ident.span.shrink_to_hi(),
443 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
445 (_, Some((_, [.., bounds]))) => (
446 bounds.span().shrink_to_hi(),
447 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
449 (Some(_), Some((_, []))) => (
450 hir_generics.span.shrink_to_hi(),
451 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
455 err.span_suggestion_verbose(
457 &format!("consider further restricting {}", msg),
459 Applicability::MachineApplicable,
464 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
465 fn suggest_restricting_param_bound(
467 mut err: &mut Diagnostic,
468 trait_pred: ty::PolyTraitPredicate<'tcx>,
469 associated_ty: Option<(&'static str, Ty<'tcx>)>,
472 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
474 let self_ty = trait_pred.skip_binder().self_ty();
475 let (param_ty, projection) = match self_ty.kind() {
476 ty::Param(_) => (true, None),
477 ty::Projection(projection) => (false, Some(projection)),
481 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
482 // don't suggest `T: Sized + ?Sized`.
483 let mut hir_id = body_id;
484 while let Some(node) = self.tcx.hir().find(hir_id) {
486 hir::Node::Item(hir::Item {
488 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
490 }) if self_ty == self.tcx.types.self_param => {
492 // Restricting `Self` for a single method.
502 Some((ident, bounds)),
507 hir::Node::TraitItem(hir::TraitItem {
509 kind: hir::TraitItemKind::Fn(..),
511 }) if self_ty == self.tcx.types.self_param => {
513 // Restricting `Self` for a single method.
515 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
521 hir::Node::TraitItem(hir::TraitItem {
523 kind: hir::TraitItemKind::Fn(fn_sig, ..),
526 | hir::Node::ImplItem(hir::ImplItem {
528 kind: hir::ImplItemKind::Fn(fn_sig, ..),
531 | hir::Node::Item(hir::Item {
532 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
533 }) if projection.is_some() => {
534 // Missing restriction on associated type of type parameter (unmet projection).
539 "the associated type",
548 hir::Node::Item(hir::Item {
550 hir::ItemKind::Trait(_, _, generics, ..)
551 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
553 }) if projection.is_some() => {
554 // Missing restriction on associated type of type parameter (unmet projection).
559 "the associated type",
569 hir::Node::Item(hir::Item {
571 hir::ItemKind::Struct(_, generics)
572 | hir::ItemKind::Enum(_, generics)
573 | hir::ItemKind::Union(_, generics)
574 | hir::ItemKind::Trait(_, _, generics, ..)
575 | hir::ItemKind::Impl(hir::Impl { generics, .. })
576 | hir::ItemKind::Fn(_, generics, _)
577 | hir::ItemKind::TyAlias(_, generics)
578 | hir::ItemKind::TraitAlias(generics, _)
579 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
582 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
583 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
586 // We skip the 0'th subst (self) because we do not want
587 // to consider the predicate as not suggestible if the
588 // self type is an arg position `impl Trait` -- instead,
589 // we handle that by adding ` + Bound` below.
590 // FIXME(compiler-errors): It would be nice to do the same
591 // this that we do in `suggest_restriction` and pull the
592 // `impl Trait` into a new generic if it shows up somewhere
593 // else in the predicate.
594 if !trait_pred.skip_binder().trait_ref.substs[1..]
596 .all(|g| g.is_suggestable(self.tcx, false))
600 // Missing generic type parameter bound.
601 let param_name = self_ty.to_string();
602 let mut constraint = with_no_trimmed_paths!(
603 trait_pred.print_modifiers_and_trait_path().to_string()
606 if let Some((name, term)) = associated_ty {
607 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
608 // That should be extracted into a helper function.
609 if constraint.ends_with('>') {
610 constraint = format!(
612 &constraint[..constraint.len() - 1],
617 constraint.push_str(&format!("<{} = {}>", name, term));
621 if suggest_constraining_type_param(
627 Some(trait_pred.def_id()),
633 hir::Node::Item(hir::Item {
635 hir::ItemKind::Struct(_, generics)
636 | hir::ItemKind::Enum(_, generics)
637 | hir::ItemKind::Union(_, generics)
638 | hir::ItemKind::Trait(_, _, generics, ..)
639 | hir::ItemKind::Impl(hir::Impl { generics, .. })
640 | hir::ItemKind::Fn(_, generics, _)
641 | hir::ItemKind::TyAlias(_, generics)
642 | hir::ItemKind::TraitAlias(generics, _)
643 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
646 // Missing generic type parameter bound.
647 if suggest_arbitrary_trait_bound(
657 hir::Node::Crate(..) => return,
662 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
666 /// When after several dereferencing, the reference satisfies the trait
667 /// binding. This function provides dereference suggestion for this
668 /// specific situation.
669 fn suggest_dereferences(
671 obligation: &PredicateObligation<'tcx>,
672 err: &mut Diagnostic,
673 trait_pred: ty::PolyTraitPredicate<'tcx>,
675 // It only make sense when suggesting dereferences for arguments
676 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code()
677 else { return false; };
678 let Some(typeck_results) = &self.typeck_results
679 else { return false; };
680 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
681 else { return false; };
682 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
683 else { return false; };
685 let span = obligation.cause.span;
686 let mut real_trait_pred = trait_pred;
687 let mut code = obligation.cause.code();
688 while let Some((parent_code, parent_trait_pred)) = code.parent() {
690 if let Some(parent_trait_pred) = parent_trait_pred {
691 real_trait_pred = parent_trait_pred;
694 let real_ty = real_trait_pred.self_ty();
695 // We `erase_late_bound_regions` here because `make_subregion` does not handle
696 // `ReLateBound`, and we don't particularly care about the regions.
698 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
704 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
705 let mut autoderef = Autoderef::new(
707 obligation.param_env,
708 obligation.cause.body_id,
712 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
714 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
716 // Remapping bound vars here
717 let real_trait_pred_and_ty =
718 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
719 let obligation = self.mk_trait_obligation_with_new_self_ty(
720 obligation.param_env,
721 real_trait_pred_and_ty,
723 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
726 // Don't care about `&mut` because `DerefMut` is used less
727 // often and user will not expect autoderef happens.
728 if let Some(hir::Node::Expr(hir::Expr {
730 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
732 })) = self.tcx.hir().find(*arg_hir_id)
734 let derefs = "*".repeat(steps);
735 err.span_suggestion_verbose(
736 expr.span.shrink_to_lo(),
737 "consider dereferencing here",
739 Applicability::MachineApplicable,
744 } else if real_trait_pred != trait_pred {
745 // This branch addresses #87437.
747 // Remapping bound vars here
748 let real_trait_pred_and_base_ty =
749 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
750 let obligation = self.mk_trait_obligation_with_new_self_ty(
751 obligation.param_env,
752 real_trait_pred_and_base_ty,
754 if self.predicate_may_hold(&obligation) {
755 err.span_suggestion_verbose(
757 "consider dereferencing here",
759 Applicability::MachineApplicable,
769 /// Given a closure's `DefId`, return the given name of the closure.
771 /// This doesn't account for reassignments, but it's only used for suggestions.
772 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
773 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
774 // Get the local name of this closure. This can be inaccurate because
775 // of the possibility of reassignment, but this should be good enough.
777 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
787 let hir = self.tcx.hir();
788 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
789 let parent_node = hir.get_parent_node(hir_id);
790 match hir.find(parent_node) {
791 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
792 get_name(err, &local.pat.kind)
794 // Different to previous arm because one is `&hir::Local` and the other
795 // is `P<hir::Local>`.
796 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
801 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
802 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
803 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
806 obligation: &PredicateObligation<'tcx>,
807 err: &mut Diagnostic,
808 trait_pred: ty::PolyTraitPredicate<'tcx>,
810 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
811 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
813 // Don't suggest calling to turn an unsized type into a sized type
817 // This is duplicated from `extract_callable_info` in typeck, which
818 // relies on autoderef, so we can't use it here.
819 let found = trait_pred.self_ty().skip_binder().peel_refs();
820 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
822 ty::FnPtr(fn_sig) => {
823 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
825 ty::FnDef(def_id, _) => {
826 let fn_sig = found.fn_sig(self.tcx);
827 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
829 ty::Closure(def_id, substs) => {
830 let fn_sig = substs.as_closure().sig();
832 DefIdOrName::DefId(def_id),
834 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
837 ty::Opaque(def_id, substs) => {
838 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
839 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
840 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
841 // args tuple will always be substs[1]
842 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
845 DefIdOrName::DefId(def_id),
846 pred.kind().rebind(proj.term.ty().unwrap()),
847 pred.kind().rebind(args.as_slice()),
854 ty::Dynamic(data, _, ty::Dyn) => {
855 data.iter().find_map(|pred| {
856 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
857 && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
858 // for existential projection, substs are shifted over by 1
859 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
862 DefIdOrName::Name("trait object"),
863 pred.rebind(proj.term.ty().unwrap()),
864 pred.rebind(args.as_slice()),
872 obligation.param_env.caller_bounds().iter().find_map(|pred| {
873 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
874 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
875 && proj.projection_ty.self_ty() == found
876 // args tuple will always be substs[1]
877 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
880 DefIdOrName::Name("type parameter"),
881 pred.kind().rebind(proj.term.ty().unwrap()),
882 pred.kind().rebind(args.as_slice()),
890 }) else { return false; };
891 let output = self.replace_bound_vars_with_fresh_vars(
892 obligation.cause.span,
893 LateBoundRegionConversionTime::FnCall,
896 let inputs = inputs.skip_binder().iter().map(|ty| {
897 self.replace_bound_vars_with_fresh_vars(
898 obligation.cause.span,
899 LateBoundRegionConversionTime::FnCall,
904 // Remapping bound vars here
905 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
908 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
909 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
913 // Get the name of the callable and the arguments to be used in the suggestion.
914 let hir = self.tcx.hir();
916 let msg = match def_id_or_name {
917 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
918 DefKind::Ctor(CtorOf::Struct, _) => {
919 "use parentheses to construct this tuple struct".to_string()
921 DefKind::Ctor(CtorOf::Variant, _) => {
922 "use parentheses to construct this tuple variant".to_string()
924 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
926 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
931 if ty.is_suggestable(self.tcx, false) {
932 format!("/* {ty} */")
934 "/* value */".to_string()
940 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
941 && obligation.cause.span.can_be_used_for_suggestions()
943 // When the obligation error has been ensured to have been caused by
944 // an argument, the `obligation.cause.span` points at the expression
945 // of the argument, so we can provide a suggestion. Otherwise, we give
946 // a more general note.
947 err.span_suggestion_verbose(
948 obligation.cause.span.shrink_to_hi(),
951 Applicability::HasPlaceholders,
953 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
954 let name = match hir.get_if_local(def_id) {
955 Some(hir::Node::Expr(hir::Expr {
956 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
959 err.span_label(*fn_decl_span, "consider calling this closure");
960 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
965 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
966 err.span_label(ident.span, "consider calling this function");
969 Some(hir::Node::Ctor(..)) => {
970 let name = self.tcx.def_path_str(def_id);
972 self.tcx.def_span(def_id),
973 format!("consider calling the constructor for `{}`", name),
979 err.help(&format!("{msg}: `{name}({args})`"));
984 fn suggest_add_reference_to_arg(
986 obligation: &PredicateObligation<'tcx>,
987 err: &mut Diagnostic,
988 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
989 has_custom_message: bool,
991 let span = obligation.cause.span;
993 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
994 obligation.cause.code()
997 } else if let ObligationCauseCode::ItemObligation(_)
998 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1000 obligation.cause.code()
1001 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1002 span.ctxt().outer_expn_data().kind
1004 obligation.cause.code()
1009 // List of traits for which it would be nonsensical to suggest borrowing.
1010 // For instance, immutable references are always Copy, so suggesting to
1011 // borrow would always succeed, but it's probably not what the user wanted.
1012 let mut never_suggest_borrow: Vec<_> =
1013 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1015 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1018 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1019 never_suggest_borrow.push(def_id);
1022 let param_env = obligation.param_env;
1024 // Try to apply the original trait binding obligation by borrowing.
1025 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1026 blacklist: &[DefId]|
1028 if blacklist.contains(&old_pred.def_id()) {
1031 // We map bounds to `&T` and `&mut T`
1032 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1035 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1038 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1041 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1045 let mk_result = |trait_pred_and_new_ty| {
1047 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1048 self.predicate_must_hold_modulo_regions(&obligation)
1050 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1051 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1053 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1054 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1055 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1058 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1059 mutability.is_mut(),
1065 if imm_ref_self_ty_satisfies_pred
1066 || mut_ref_self_ty_satisfies_pred
1067 || ref_inner_ty_satisfies_pred
1069 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1070 // We don't want a borrowing suggestion on the fields in structs,
1073 // the_foos: Vec<Foo>
1077 span.ctxt().outer_expn_data().kind,
1078 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1082 if snippet.starts_with('&') {
1083 // This is already a literal borrow and the obligation is failing
1084 // somewhere else in the obligation chain. Do not suggest non-sense.
1087 // We have a very specific type of error, where just borrowing this argument
1088 // might solve the problem. In cases like this, the important part is the
1089 // original type obligation, not the last one that failed, which is arbitrary.
1090 // Because of this, we modify the error to refer to the original obligation and
1091 // return early in the caller.
1093 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1094 if has_custom_message {
1098 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1103 "the trait `{}` is not implemented for `{}`",
1104 old_pred.print_modifiers_and_trait_path(),
1105 old_pred.self_ty().skip_binder(),
1109 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1110 err.span_suggestions(
1111 span.shrink_to_lo(),
1112 "consider borrowing here",
1113 ["&".to_string(), "&mut ".to_string()],
1114 Applicability::MaybeIncorrect,
1117 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1118 err.span_suggestion_verbose(
1119 span.shrink_to_lo(),
1121 "consider{} borrowing here",
1122 if is_mut { " mutably" } else { "" }
1124 format!("&{}", if is_mut { "mut " } else { "" }),
1125 Applicability::MaybeIncorrect,
1134 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1135 try_borrowing(cause.derived.parent_trait_pred, &[])
1136 } else if let ObligationCauseCode::BindingObligation(_, _)
1137 | ObligationCauseCode::ItemObligation(_)
1138 | ObligationCauseCode::ExprItemObligation(..)
1139 | ObligationCauseCode::ExprBindingObligation(..) = code
1141 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1147 // Suggest borrowing the type
1148 fn suggest_borrowing_for_object_cast(
1150 err: &mut Diagnostic,
1151 obligation: &PredicateObligation<'tcx>,
1153 object_ty: Ty<'tcx>,
1155 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1156 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1158 for predicate in predicates.iter() {
1159 if !self.predicate_must_hold_modulo_regions(
1160 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1166 err.span_suggestion(
1167 obligation.cause.span.shrink_to_lo(),
1169 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1172 Applicability::MaybeIncorrect,
1176 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1177 /// suggest removing these references until we reach a type that implements the trait.
1178 fn suggest_remove_reference(
1180 obligation: &PredicateObligation<'tcx>,
1181 err: &mut Diagnostic,
1182 trait_pred: ty::PolyTraitPredicate<'tcx>,
1184 let span = obligation.cause.span;
1186 let mut suggested = false;
1187 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1189 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1190 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1191 // Do not suggest removal of borrow from type arguments.
1195 // Skipping binder here, remapping below
1196 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1198 for refs_remaining in 0..refs_number {
1199 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1202 suggested_ty = *inner_ty;
1204 // Remapping bound vars here
1205 let trait_pred_and_suggested_ty =
1206 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1208 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1209 obligation.param_env,
1210 trait_pred_and_suggested_ty,
1213 if self.predicate_may_hold(&new_obligation) {
1218 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1220 let remove_refs = refs_remaining + 1;
1222 let msg = if remove_refs == 1 {
1223 "consider removing the leading `&`-reference".to_string()
1225 format!("consider removing {} leading `&`-references", remove_refs)
1228 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1237 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1238 let span = obligation.cause.span;
1240 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1241 let hir = self.tcx.hir();
1242 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1243 if let hir::Node::Expr(expr) = node {
1244 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1245 // and if not maybe suggest doing something else? If we kept the expression around we
1246 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1247 // it is from the local crate.
1248 err.span_suggestion(
1250 "remove the `.await`",
1252 Applicability::MachineApplicable,
1254 // FIXME: account for associated `async fn`s.
1255 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1256 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1257 obligation.predicate.kind().skip_binder()
1261 &format!("this call returns `{}`", pred.self_ty()),
1264 if let Some(typeck_results) = &self.typeck_results
1265 && let ty = typeck_results.expr_ty_adjusted(base)
1266 && let ty::FnDef(def_id, _substs) = ty.kind()
1267 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1268 hir.get_if_local(*def_id)
1271 "alternatively, consider making `fn {}` asynchronous",
1274 if vis_span.is_empty() {
1275 err.span_suggestion_verbose(
1276 span.shrink_to_lo(),
1279 Applicability::MaybeIncorrect,
1282 err.span_suggestion_verbose(
1283 vis_span.shrink_to_hi(),
1286 Applicability::MaybeIncorrect,
1296 /// Check if the trait bound is implemented for a different mutability and note it in the
1298 fn suggest_change_mut(
1300 obligation: &PredicateObligation<'tcx>,
1301 err: &mut Diagnostic,
1302 trait_pred: ty::PolyTraitPredicate<'tcx>,
1304 let points_at_arg = matches!(
1305 obligation.cause.code(),
1306 ObligationCauseCode::FunctionArgumentObligation { .. },
1309 let span = obligation.cause.span;
1310 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1312 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1313 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1314 // Do not suggest removal of borrow from type arguments.
1317 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1318 if trait_pred.has_non_region_infer() {
1319 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1320 // unresolved bindings.
1324 // Skipping binder here, remapping below
1325 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1327 let suggested_ty = match mutability {
1328 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1329 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1332 // Remapping bound vars here
1333 let trait_pred_and_suggested_ty =
1334 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1336 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1337 obligation.param_env,
1338 trait_pred_and_suggested_ty,
1340 let suggested_ty_would_satisfy_obligation = self
1341 .evaluate_obligation_no_overflow(&new_obligation)
1342 .must_apply_modulo_regions();
1343 if suggested_ty_would_satisfy_obligation {
1348 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1349 if points_at_arg && mutability.is_not() && refs_number > 0 {
1350 err.span_suggestion_verbose(
1352 "consider changing this borrow's mutability",
1354 Applicability::MachineApplicable,
1358 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1359 trait_pred.print_modifiers_and_trait_path(),
1361 trait_pred.skip_binder().self_ty(),
1369 fn suggest_semicolon_removal(
1371 obligation: &PredicateObligation<'tcx>,
1372 err: &mut Diagnostic,
1374 trait_pred: ty::PolyTraitPredicate<'tcx>,
1376 let hir = self.tcx.hir();
1377 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1378 let node = hir.find(parent_node);
1379 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1380 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1381 && sig.decl.output.span().overlaps(span)
1382 && blk.expr.is_none()
1383 && trait_pred.self_ty().skip_binder().is_unit()
1384 && let Some(stmt) = blk.stmts.last()
1385 && let hir::StmtKind::Semi(expr) = stmt.kind
1386 // Only suggest this if the expression behind the semicolon implements the predicate
1387 && let Some(typeck_results) = &self.typeck_results
1388 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1389 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1390 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1396 "this expression has type `{}`, which implements `{}`",
1398 trait_pred.print_modifiers_and_trait_path()
1401 err.span_suggestion(
1402 self.tcx.sess.source_map().end_point(stmt.span),
1403 "remove this semicolon",
1405 Applicability::MachineApplicable
1412 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1413 let hir = self.tcx.hir();
1414 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1415 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1419 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1422 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1423 /// applicable and signal that the error has been expanded appropriately and needs to be
1425 fn suggest_impl_trait(
1427 err: &mut Diagnostic,
1429 obligation: &PredicateObligation<'tcx>,
1430 trait_pred: ty::PolyTraitPredicate<'tcx>,
1432 match obligation.cause.code().peel_derives() {
1433 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1434 ObligationCauseCode::SizedReturnType => {}
1438 let hir = self.tcx.hir();
1439 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1440 let node = hir.find(fn_hir_id);
1441 let Some(hir::Node::Item(hir::Item {
1442 kind: hir::ItemKind::Fn(sig, _, body_id),
1448 let body = hir.body(*body_id);
1449 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1450 let ty = trait_pred.skip_binder().self_ty();
1451 let is_object_safe = match ty.kind() {
1452 ty::Dynamic(predicates, _, ty::Dyn) => {
1453 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1456 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1458 // We only want to suggest `impl Trait` to `dyn Trait`s.
1459 // For example, `fn foo() -> str` needs to be filtered out.
1463 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1467 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1468 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1469 // Recursively look for `TraitObject` types and if there's only one, use that span to
1470 // suggest `impl Trait`.
1472 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1473 // otherwise suggest using `Box<dyn Trait>` or an enum.
1474 let mut visitor = ReturnsVisitor::default();
1475 visitor.visit_body(&body);
1477 let typeck_results = self.typeck_results.as_ref().unwrap();
1478 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1480 let ret_types = visitor
1483 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1484 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1485 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1487 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1489 let ty = self.resolve_vars_if_possible(ty);
1491 !matches!(ty.kind(), ty::Error(_))
1492 && last_ty.map_or(true, |last_ty| {
1493 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1494 // *after* in the dependency graph.
1495 match (ty.kind(), last_ty.kind()) {
1496 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1497 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1498 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1500 Infer(InferTy::FreshFloatTy(_)),
1501 Infer(InferTy::FreshFloatTy(_)),
1506 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1509 let mut spans_and_needs_box = vec![];
1511 match liberated_sig.output().kind() {
1512 ty::Dynamic(predicates, _, ty::Dyn) => {
1513 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1514 let param_env = ty::ParamEnv::empty();
1516 if !only_never_return {
1517 for (expr_span, return_ty) in ret_types {
1518 let self_ty_satisfies_dyn_predicates = |self_ty| {
1519 predicates.iter().all(|predicate| {
1520 let pred = predicate.with_self_ty(self.tcx, self_ty);
1521 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1522 self.predicate_may_hold(&obl)
1526 if let ty::Adt(def, substs) = return_ty.kind()
1528 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1530 spans_and_needs_box.push((expr_span, false));
1531 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1532 spans_and_needs_box.push((expr_span, true));
1542 let sm = self.tcx.sess.source_map();
1543 if !ret_ty.span.overlaps(span) {
1546 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1547 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1553 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1554 let name = liberated_sig.output().to_string();
1556 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1557 if !name.starts_with("dyn ") {
1563 err.code(error_code!(E0746));
1564 err.set_primary_message("return type cannot have an unboxed trait object");
1565 err.children.clear();
1566 let impl_trait_msg = "for information on `impl Trait`, see \
1567 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1568 #returning-types-that-implement-traits>";
1569 let trait_obj_msg = "for information on trait objects, see \
1570 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1571 #using-trait-objects-that-allow-for-values-of-different-types>";
1573 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1574 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1575 if only_never_return {
1576 // No return paths, probably using `panic!()` or similar.
1577 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1578 suggest_trait_object_return_type_alternatives(
1584 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1585 // Suggest `-> impl Trait`.
1586 err.span_suggestion(
1589 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1590 which implements `{1}`",
1593 format!("impl {}", trait_obj),
1594 Applicability::MachineApplicable,
1596 err.note(impl_trait_msg);
1599 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1600 err.multipart_suggestion(
1601 "return a boxed trait object instead",
1603 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1604 (span.shrink_to_hi(), ">".to_string()),
1606 Applicability::MaybeIncorrect,
1608 for (span, needs_box) in spans_and_needs_box {
1610 err.multipart_suggestion(
1611 "... and box this value",
1613 (span.shrink_to_lo(), "Box::new(".to_string()),
1614 (span.shrink_to_hi(), ")".to_string()),
1616 Applicability::MaybeIncorrect,
1621 // This is currently not possible to trigger because E0038 takes precedence, but
1622 // leave it in for completeness in case anything changes in an earlier stage.
1624 "if trait `{}` were object-safe, you could return a trait object",
1628 err.note(trait_obj_msg);
1630 "if all the returned values were of the same type you could use `impl {}` as the \
1634 err.note(impl_trait_msg);
1635 err.note("you can create a new `enum` with a variant for each returned type");
1640 fn point_at_returns_when_relevant(
1642 err: &mut Diagnostic,
1643 obligation: &PredicateObligation<'tcx>,
1645 match obligation.cause.code().peel_derives() {
1646 ObligationCauseCode::SizedReturnType => {}
1650 let hir = self.tcx.hir();
1651 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1652 let node = hir.find(parent_node);
1653 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1656 let body = hir.body(*body_id);
1657 // Point at all the `return`s in the function as they have failed trait bounds.
1658 let mut visitor = ReturnsVisitor::default();
1659 visitor.visit_body(&body);
1660 let typeck_results = self.typeck_results.as_ref().unwrap();
1661 for expr in &visitor.returns {
1662 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1663 let ty = self.resolve_vars_if_possible(returned_ty);
1664 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1670 fn report_closure_arg_mismatch(
1673 found_span: Option<Span>,
1674 found: ty::PolyTraitRef<'tcx>,
1675 expected: ty::PolyTraitRef<'tcx>,
1676 cause: &ObligationCauseCode<'tcx>,
1677 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1678 pub(crate) fn build_fn_sig_ty<'tcx>(
1679 infcx: &InferCtxt<'tcx>,
1680 trait_ref: ty::PolyTraitRef<'tcx>,
1682 let inputs = trait_ref.skip_binder().substs.type_at(1);
1683 let sig = match inputs.kind() {
1684 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1685 infcx.tcx.mk_fn_sig(
1687 infcx.next_ty_var(TypeVariableOrigin {
1689 kind: TypeVariableOriginKind::MiscVariable,
1692 hir::Unsafety::Normal,
1696 _ => infcx.tcx.mk_fn_sig(
1697 std::iter::once(inputs),
1698 infcx.next_ty_var(TypeVariableOrigin {
1700 kind: TypeVariableOriginKind::MiscVariable,
1703 hir::Unsafety::Normal,
1708 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1711 let argument_kind = match expected.skip_binder().self_ty().kind() {
1712 ty::Closure(..) => "closure",
1713 ty::Generator(..) => "generator",
1716 let mut err = struct_span_err!(
1720 "type mismatch in {argument_kind} arguments",
1723 err.span_label(span, "expected due to this");
1725 let found_span = found_span.unwrap_or(span);
1726 err.span_label(found_span, "found signature defined here");
1728 let expected = build_fn_sig_ty(self, expected);
1729 let found = build_fn_sig_ty(self, found);
1731 let (expected_str, found_str) = self.cmp(expected, found);
1733 let signature_kind = format!("{argument_kind} signature");
1734 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1736 self.note_conflicting_closure_bounds(cause, &mut err);
1741 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1742 // requirements, which will always cause a closure to have a type error.
1743 fn note_conflicting_closure_bounds(
1745 cause: &ObligationCauseCode<'tcx>,
1746 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1748 // First, look for an `ExprBindingObligation`, which means we can get
1749 // the unsubstituted predicate list of the called function. And check
1750 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1751 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1752 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1753 && let Some(pred) = predicates.predicates.get(*idx)
1754 && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
1755 && self.tcx.is_fn_trait(trait_pred.def_id())
1758 self.tcx.anonymize_late_bound_regions(pred.kind().rebind(trait_pred.self_ty()));
1759 let expected_substs = self
1761 .anonymize_late_bound_regions(pred.kind().rebind(trait_pred.trait_ref.substs));
1763 // Find another predicate whose self-type is equal to the expected self type,
1764 // but whose substs don't match.
1765 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1767 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1768 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
1769 if self.tcx.is_fn_trait(trait_pred.def_id())
1771 // Make sure that the self type matches
1772 // (i.e. constraining this closure)
1774 == self.tcx.anonymize_late_bound_regions(
1775 pred.kind().rebind(trait_pred.self_ty()),
1777 // But the substs don't match (i.e. incompatible args)
1779 != self.tcx.anonymize_late_bound_regions(
1780 pred.kind().rebind(trait_pred.trait_ref.substs),
1787 // If we found one, then it's very likely the cause of the error.
1788 if let Some((_, (_, other_pred_span))) = other_pred {
1791 "closure inferred to have a different signature due to this bound",
1797 fn suggest_fully_qualified_path(
1799 err: &mut Diagnostic,
1804 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1805 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1807 "{}s cannot be accessed directly on a `trait`, they can only be \
1808 accessed through a specific `impl`",
1809 assoc_item.kind.as_def_kind().descr(item_def_id)
1811 err.span_suggestion(
1813 "use the fully qualified path to an implementation",
1814 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1815 Applicability::HasPlaceholders,
1821 /// Adds an async-await specific note to the diagnostic when the future does not implement
1822 /// an auto trait because of a captured type.
1825 /// note: future does not implement `Qux` as this value is used across an await
1826 /// --> $DIR/issue-64130-3-other.rs:17:5
1828 /// LL | let x = Foo;
1829 /// | - has type `Foo`
1830 /// LL | baz().await;
1831 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1833 /// | - `x` is later dropped here
1836 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1837 /// is "replaced" with a different message and a more specific error.
1840 /// error: future cannot be sent between threads safely
1841 /// --> $DIR/issue-64130-2-send.rs:21:5
1843 /// LL | fn is_send<T: Send>(t: T) { }
1844 /// | ---- required by this bound in `is_send`
1846 /// LL | is_send(bar());
1847 /// | ^^^^^^^ future returned by `bar` is not send
1849 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1850 /// implemented for `Foo`
1851 /// note: future is not send as this value is used across an await
1852 /// --> $DIR/issue-64130-2-send.rs:15:5
1854 /// LL | let x = Foo;
1855 /// | - has type `Foo`
1856 /// LL | baz().await;
1857 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1859 /// | - `x` is later dropped here
1862 /// Returns `true` if an async-await specific note was added to the diagnostic.
1863 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1864 fn maybe_note_obligation_cause_for_async_await(
1866 err: &mut Diagnostic,
1867 obligation: &PredicateObligation<'tcx>,
1869 let hir = self.tcx.hir();
1871 // Attempt to detect an async-await error by looking at the obligation causes, looking
1872 // for a generator to be present.
1874 // When a future does not implement a trait because of a captured type in one of the
1875 // generators somewhere in the call stack, then the result is a chain of obligations.
1877 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1878 // future is passed as an argument to a function C which requires a `Send` type, then the
1879 // chain looks something like this:
1881 // - `BuiltinDerivedObligation` with a generator witness (B)
1882 // - `BuiltinDerivedObligation` with a generator (B)
1883 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1884 // - `BuiltinDerivedObligation` with a generator witness (A)
1885 // - `BuiltinDerivedObligation` with a generator (A)
1886 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1887 // - `BindingObligation` with `impl_send (Send requirement)
1889 // The first obligation in the chain is the most useful and has the generator that captured
1890 // the type. The last generator (`outer_generator` below) has information about where the
1891 // bound was introduced. At least one generator should be present for this diagnostic to be
1893 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1894 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
1897 let mut generator = None;
1898 let mut outer_generator = None;
1899 let mut next_code = Some(obligation.cause.code());
1901 let mut seen_upvar_tys_infer_tuple = false;
1903 while let Some(code) = next_code {
1906 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1907 next_code = Some(parent_code);
1909 ObligationCauseCode::ImplDerivedObligation(cause) => {
1910 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1912 parent_trait_ref = ?cause.derived.parent_trait_pred,
1913 self_ty.kind = ?ty.kind(),
1918 ty::Generator(did, ..) => {
1919 generator = generator.or(Some(did));
1920 outer_generator = Some(did);
1922 ty::GeneratorWitness(..) => {}
1923 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1924 // By introducing a tuple of upvar types into the chain of obligations
1925 // of a generator, the first non-generator item is now the tuple itself,
1926 // we shall ignore this.
1928 seen_upvar_tys_infer_tuple = true;
1930 _ if generator.is_none() => {
1931 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1932 target_ty = Some(ty);
1937 next_code = Some(&cause.derived.parent_code);
1939 ObligationCauseCode::DerivedObligation(derived_obligation)
1940 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1941 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1943 parent_trait_ref = ?derived_obligation.parent_trait_pred,
1944 self_ty.kind = ?ty.kind(),
1948 ty::Generator(did, ..) => {
1949 generator = generator.or(Some(did));
1950 outer_generator = Some(did);
1952 ty::GeneratorWitness(..) => {}
1953 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1954 // By introducing a tuple of upvar types into the chain of obligations
1955 // of a generator, the first non-generator item is now the tuple itself,
1956 // we shall ignore this.
1958 seen_upvar_tys_infer_tuple = true;
1960 _ if generator.is_none() => {
1961 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1962 target_ty = Some(ty);
1967 next_code = Some(&derived_obligation.parent_code);
1973 // Only continue if a generator was found.
1974 debug!(?generator, ?trait_ref, ?target_ty);
1975 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1979 let span = self.tcx.def_span(generator_did);
1981 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1984 ?generator_did_root,
1985 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
1989 let generator_body = generator_did
1991 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
1992 .map(|body_id| hir.body(body_id));
1993 let mut visitor = AwaitsVisitor::default();
1994 if let Some(body) = generator_body {
1995 visitor.visit_body(body);
1997 debug!(awaits = ?visitor.awaits);
1999 // Look for a type inside the generator interior that matches the target type to get
2001 let target_ty_erased = self.tcx.erase_regions(target_ty);
2002 let ty_matches = |ty| -> bool {
2003 // Careful: the regions for types that appear in the
2004 // generator interior are not generally known, so we
2005 // want to erase them when comparing (and anyway,
2006 // `Send` and other bounds are generally unaffected by
2007 // the choice of region). When erasing regions, we
2008 // also have to erase late-bound regions. This is
2009 // because the types that appear in the generator
2010 // interior generally contain "bound regions" to
2011 // represent regions that are part of the suspended
2012 // generator frame. Bound regions are preserved by
2013 // `erase_regions` and so we must also call
2014 // `erase_late_bound_regions`.
2015 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2016 let ty_erased = self.tcx.erase_regions(ty_erased);
2017 let eq = ty_erased == target_ty_erased;
2018 debug!(?ty_erased, ?target_ty_erased, ?eq);
2022 // Get the typeck results from the infcx if the generator is the function we are currently
2023 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2024 // cycles. If we can't use resolved types because the generator comes from another crate,
2025 // we still provide a targeted error but without all the relevant spans.
2026 let generator_data = match &self.typeck_results {
2027 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2028 _ if generator_did.is_local() => {
2029 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2031 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2032 GeneratorData::Foreign(generator_diag_data)
2037 let mut interior_or_upvar_span = None;
2039 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2040 debug!(?from_awaited_ty);
2042 // The generator interior types share the same binders
2043 if let Some(cause) =
2044 generator_data.get_generator_interior_types().skip_binder().iter().find(
2045 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2046 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2050 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2052 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2054 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2058 if interior_or_upvar_span.is_none() {
2059 interior_or_upvar_span =
2060 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2063 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2064 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2067 debug!(?interior_or_upvar_span);
2068 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2069 let is_async = self.tcx.generator_is_async(generator_did);
2070 let typeck_results = match generator_data {
2071 GeneratorData::Local(typeck_results) => Some(typeck_results),
2072 GeneratorData::Foreign(_) => None,
2074 self.note_obligation_cause_for_async_await(
2076 interior_or_upvar_span,
2091 /// Unconditionally adds the diagnostic note described in
2092 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2093 #[instrument(level = "debug", skip_all)]
2094 fn note_obligation_cause_for_async_await(
2096 err: &mut Diagnostic,
2097 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2099 outer_generator: Option<DefId>,
2100 trait_pred: ty::TraitPredicate<'tcx>,
2101 target_ty: Ty<'tcx>,
2102 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2103 obligation: &PredicateObligation<'tcx>,
2104 next_code: Option<&ObligationCauseCode<'tcx>>,
2106 let source_map = self.tcx.sess.source_map();
2108 let (await_or_yield, an_await_or_yield) =
2109 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2110 let future_or_generator = if is_async { "future" } else { "generator" };
2112 // Special case the primary error message when send or sync is the trait that was
2114 let hir = self.tcx.hir();
2115 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2116 self.tcx.get_diagnostic_name(trait_pred.def_id())
2118 let (trait_name, trait_verb) =
2119 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2122 err.set_primary_message(format!(
2123 "{} cannot be {} between threads safely",
2124 future_or_generator, trait_verb
2127 let original_span = err.span.primary_span().unwrap();
2128 let mut span = MultiSpan::from_span(original_span);
2130 let message = outer_generator
2131 .and_then(|generator_did| {
2132 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2133 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2134 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2136 .parent(generator_did)
2138 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2139 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2141 format!("future returned by `{}` is not {}", name, trait_name)
2143 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2144 format!("future created by async block is not {}", trait_name)
2146 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2147 format!("future created by async closure is not {}", trait_name)
2151 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2153 span.push_span_label(original_span, message);
2156 format!("is not {}", trait_name)
2158 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2161 let mut explain_yield = |interior_span: Span,
2163 scope_span: Option<Span>| {
2164 let mut span = MultiSpan::from_span(yield_span);
2165 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
2166 // #70935: If snippet contains newlines, display "the value" instead
2167 // so that we do not emit complex diagnostics.
2168 let snippet = &format!("`{}`", snippet);
2169 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
2170 // note: future is not `Send` as this value is used across an await
2171 // --> $DIR/issue-70935-complex-spans.rs:13:9
2173 // LL | baz(|| async {
2174 // | ______________-
2177 // LL | | foo(tx.clone());
2179 // | | - ^^^^^^ await occurs here, with value maybe used later
2181 // | has type `closure` which is not `Send`
2182 // note: value is later dropped here
2186 span.push_span_label(
2188 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2190 span.push_span_label(
2192 format!("has type `{}` which {}", target_ty, trait_explanation),
2194 // If available, use the scope span to annotate the drop location.
2195 let mut scope_note = None;
2196 if let Some(scope_span) = scope_span {
2197 let scope_span = source_map.end_point(scope_span);
2199 let msg = format!("{} is later dropped here", snippet);
2200 if source_map.is_multiline(yield_span.between(scope_span)) {
2201 span.push_span_label(scope_span, msg);
2203 scope_note = Some((scope_span, msg));
2209 "{} {} as this value is used across {}",
2210 future_or_generator, trait_explanation, an_await_or_yield
2213 if let Some((span, msg)) = scope_note {
2214 err.span_note(span, &msg);
2218 match interior_or_upvar_span {
2219 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2220 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2221 if let Some(await_span) = from_awaited_ty {
2222 // The type causing this obligation is one being awaited at await_span.
2223 let mut span = MultiSpan::from_span(await_span);
2224 span.push_span_label(
2227 "await occurs here on type `{}`, which {}",
2228 target_ty, trait_explanation
2234 "future {not_trait} as it awaits another future which {not_trait}",
2235 not_trait = trait_explanation
2239 // Look at the last interior type to get a span for the `.await`.
2241 generator_interior_types = ?format_args!(
2242 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2245 explain_yield(interior_span, yield_span, scope_span);
2248 if let Some(expr_id) = expr {
2249 let expr = hir.expect_expr(expr_id);
2250 debug!("target_ty evaluated from {:?}", expr);
2252 let parent = hir.get_parent_node(expr_id);
2253 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2254 let parent_span = hir.span(parent);
2255 let parent_did = parent.owner.to_def_id();
2258 // fn foo(&self) -> i32 {}
2261 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2264 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2266 .expr_adjustments(expr)
2268 .any(|adj| adj.is_region_borrow())
2274 // struct Foo(*const u8);
2275 // bar(Foo(std::ptr::null())).await;
2276 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2278 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2279 let is_raw_borrow_inside_fn_like_call =
2280 match self.tcx.def_kind(parent_did) {
2281 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2284 if let Some(typeck_results) = typeck_results {
2285 if (typeck_results.is_method_call(e) && is_region_borrow)
2286 || is_raw_borrow_inside_fn_like_call
2290 "consider moving this into a `let` \
2291 binding to create a shorter lived borrow",
2299 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2300 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2301 let refers_to_non_sync = match target_ty.kind() {
2302 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2303 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2309 let (span_label, span_note) = match refers_to_non_sync {
2310 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2311 // include suggestions to make `T: Sync` so that `&T: Send`
2314 "has type `{}` which {}, because `{}` is not `Sync`",
2315 target_ty, trait_explanation, ref_ty
2318 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2323 format!("has type `{}` which {}", target_ty, trait_explanation),
2324 format!("captured value {}", trait_explanation),
2328 let mut span = MultiSpan::from_span(upvar_span);
2329 span.push_span_label(upvar_span, span_label);
2330 err.span_note(span, &span_note);
2334 // Add a note for the item obligation that remains - normally a note pointing to the
2335 // bound that introduced the obligation (e.g. `T: Send`).
2337 self.note_obligation_cause_code(
2339 &obligation.predicate,
2340 obligation.param_env,
2343 &mut Default::default(),
2347 fn note_obligation_cause_code<T>(
2349 err: &mut Diagnostic,
2351 param_env: ty::ParamEnv<'tcx>,
2352 cause_code: &ObligationCauseCode<'tcx>,
2353 obligated_types: &mut Vec<Ty<'tcx>>,
2354 seen_requirements: &mut FxHashSet<DefId>,
2360 ObligationCauseCode::ExprAssignable
2361 | ObligationCauseCode::MatchExpressionArm { .. }
2362 | ObligationCauseCode::Pattern { .. }
2363 | ObligationCauseCode::IfExpression { .. }
2364 | ObligationCauseCode::IfExpressionWithNoElse
2365 | ObligationCauseCode::MainFunctionType
2366 | ObligationCauseCode::StartFunctionType
2367 | ObligationCauseCode::IntrinsicType
2368 | ObligationCauseCode::MethodReceiver
2369 | ObligationCauseCode::ReturnNoExpression
2370 | ObligationCauseCode::UnifyReceiver(..)
2371 | ObligationCauseCode::OpaqueType
2372 | ObligationCauseCode::MiscObligation
2373 | ObligationCauseCode::WellFormed(..)
2374 | ObligationCauseCode::MatchImpl(..)
2375 | ObligationCauseCode::ReturnType
2376 | ObligationCauseCode::ReturnValue(_)
2377 | ObligationCauseCode::BlockTailExpression(_)
2378 | ObligationCauseCode::AwaitableExpr(_)
2379 | ObligationCauseCode::ForLoopIterator
2380 | ObligationCauseCode::QuestionMark
2381 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2382 | ObligationCauseCode::LetElse
2383 | ObligationCauseCode::BinOp { .. }
2384 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2385 | ObligationCauseCode::RustCall => {}
2386 ObligationCauseCode::SliceOrArrayElem => {
2387 err.note("slice and array elements must have `Sized` type");
2389 ObligationCauseCode::TupleElem => {
2390 err.note("only the last element of a tuple may have a dynamically sized type");
2392 ObligationCauseCode::ProjectionWf(data) => {
2393 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2395 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2397 "required so that reference `{}` does not outlive its referent",
2401 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2403 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2407 ObligationCauseCode::ItemObligation(_)
2408 | ObligationCauseCode::ExprItemObligation(..) => {
2409 // We hold the `DefId` of the item introducing the obligation, but displaying it
2410 // doesn't add user usable information. It always point at an associated item.
2412 ObligationCauseCode::BindingObligation(item_def_id, span)
2413 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2414 let item_name = tcx.def_path_str(item_def_id);
2415 let mut multispan = MultiSpan::from(span);
2416 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2417 let sm = tcx.sess.source_map();
2419 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2420 (Ok(l), Ok(r)) => l.line == r.line,
2423 if !ident.span.is_dummy() && !ident.span.overlaps(span) && !same_line {
2424 multispan.push_span_label(ident.span, "required by a bound in this");
2427 let descr = format!("required by a bound in `{}`", item_name);
2428 if !span.is_dummy() {
2429 let msg = format!("required by this bound in `{}`", item_name);
2430 multispan.push_span_label(span, msg);
2431 err.span_note(multispan, &descr);
2433 err.span_note(tcx.def_span(item_def_id), &descr);
2436 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2438 "required for the cast from `{}` to the object type `{}`",
2439 self.ty_to_string(concrete_ty),
2440 self.ty_to_string(object_ty)
2443 ObligationCauseCode::Coercion { source: _, target } => {
2444 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2446 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2448 "the `Copy` trait is required because this value will be copied for each element of the array",
2453 "consider creating a new `const` item and initializing it with the result \
2454 of the function call to be used in the repeat position, like \
2455 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2459 if self.tcx.sess.is_nightly_build() && is_const_fn {
2461 "create an inline `const` block, see RFC #2920 \
2462 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2466 ObligationCauseCode::VariableType(hir_id) => {
2467 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2468 match self.tcx.hir().find(parent_node) {
2469 Some(Node::Local(hir::Local {
2470 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2473 // When encountering an assignment of an unsized trait, like
2474 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2475 // order to use have a slice instead.
2476 err.span_suggestion_verbose(
2477 span.shrink_to_lo(),
2478 "consider borrowing here",
2480 Applicability::MachineApplicable,
2482 err.note("all local variables must have a statically known size");
2484 Some(Node::Param(param)) => {
2485 err.span_suggestion_verbose(
2486 param.ty_span.shrink_to_lo(),
2487 "function arguments must have a statically known size, borrowed types \
2488 always have a known size",
2490 Applicability::MachineApplicable,
2494 err.note("all local variables must have a statically known size");
2497 if !self.tcx.features().unsized_locals {
2498 err.help("unsized locals are gated as an unstable feature");
2501 ObligationCauseCode::SizedArgumentType(sp) => {
2502 if let Some(span) = sp {
2503 err.span_suggestion_verbose(
2504 span.shrink_to_lo(),
2505 "function arguments must have a statically known size, borrowed types \
2506 always have a known size",
2508 Applicability::MachineApplicable,
2511 err.note("all function arguments must have a statically known size");
2513 if tcx.sess.opts.unstable_features.is_nightly_build()
2514 && !self.tcx.features().unsized_fn_params
2516 err.help("unsized fn params are gated as an unstable feature");
2519 ObligationCauseCode::SizedReturnType => {
2520 err.note("the return type of a function must have a statically known size");
2522 ObligationCauseCode::SizedYieldType => {
2523 err.note("the yield type of a generator must have a statically known size");
2525 ObligationCauseCode::SizedBoxType => {
2526 err.note("the type of a box expression must have a statically known size");
2528 ObligationCauseCode::AssignmentLhsSized => {
2529 err.note("the left-hand-side of an assignment must have a statically known size");
2531 ObligationCauseCode::TupleInitializerSized => {
2532 err.note("tuples must have a statically known size to be initialized");
2534 ObligationCauseCode::StructInitializerSized => {
2535 err.note("structs must have a statically known size to be initialized");
2537 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2539 AdtKind::Struct => {
2542 "the last field of a packed struct may only have a \
2543 dynamically sized type if it does not need drop to be run",
2547 "only the last field of a struct may have a dynamically sized type",
2552 err.note("no field of a union may have a dynamically sized type");
2555 err.note("no field of an enum variant may have a dynamically sized type");
2558 err.help("change the field's type to have a statically known size");
2559 err.span_suggestion(
2560 span.shrink_to_lo(),
2561 "borrowed types always have a statically known size",
2563 Applicability::MachineApplicable,
2565 err.multipart_suggestion(
2566 "the `Box` type always has a statically known size and allocates its contents \
2569 (span.shrink_to_lo(), "Box<".to_string()),
2570 (span.shrink_to_hi(), ">".to_string()),
2572 Applicability::MachineApplicable,
2575 ObligationCauseCode::ConstSized => {
2576 err.note("constant expressions must have a statically known size");
2578 ObligationCauseCode::InlineAsmSized => {
2579 err.note("all inline asm arguments must have a statically known size");
2581 ObligationCauseCode::ConstPatternStructural => {
2582 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2584 ObligationCauseCode::SharedStatic => {
2585 err.note("shared static variables must have a type that implements `Sync`");
2587 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2588 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2589 let ty = parent_trait_ref.skip_binder().self_ty();
2590 if parent_trait_ref.references_error() {
2591 // NOTE(eddyb) this was `.cancel()`, but `err`
2592 // is borrowed, so we can't fully defuse it.
2593 err.downgrade_to_delayed_bug();
2597 // If the obligation for a tuple is set directly by a Generator or Closure,
2598 // then the tuple must be the one containing capture types.
2599 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2602 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2604 let parent_trait_ref =
2605 self.resolve_vars_if_possible(data.parent_trait_pred);
2606 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2607 matches!(nested_ty.kind(), ty::Generator(..))
2608 || matches!(nested_ty.kind(), ty::Closure(..))
2614 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2616 // Don't print the tuple of capture types
2618 if !is_upvar_tys_infer_tuple {
2619 let msg = format!("required because it appears within the type `{}`", ty);
2621 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2622 Some(ident) => err.span_note(ident.span, &msg),
2623 None => err.note(&msg),
2625 ty::Opaque(def_id, _) => {
2626 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2627 if tcx.parent(*def_id) == identity_future {
2631 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2632 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2633 let is_future = tcx.ty_is_opaque_future(ty);
2637 "note_obligation_cause_code: check for async fn"
2640 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2641 ty::Generator(last_def_id, ..) => {
2642 tcx.generator_is_async(*last_def_id)
2649 err.span_note(self.tcx.def_span(def_id), &msg)
2651 ty::GeneratorWitness(bound_tys) => {
2652 use std::fmt::Write;
2654 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2655 // Maybe we should just remove this note altogether?
2656 // FIXME: only print types which don't meet the trait requirement
2658 "required because it captures the following types: ".to_owned();
2659 for ty in bound_tys.skip_binder() {
2660 write!(msg, "`{}`, ", ty).unwrap();
2662 err.note(msg.trim_end_matches(", "))
2664 ty::Generator(def_id, _, _) => {
2665 let sp = self.tcx.def_span(def_id);
2667 // Special-case this to say "async block" instead of `[static generator]`.
2668 let kind = tcx.generator_kind(def_id).unwrap().descr();
2671 &format!("required because it's used within this {}", kind),
2674 ty::Closure(def_id, _) => err.span_note(
2675 self.tcx.def_span(def_id),
2676 &format!("required because it's used within this closure"),
2678 _ => err.note(&msg),
2683 obligated_types.push(ty);
2685 let parent_predicate = parent_trait_ref;
2686 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2687 // #74711: avoid a stack overflow
2688 ensure_sufficient_stack(|| {
2689 self.note_obligation_cause_code(
2699 ensure_sufficient_stack(|| {
2700 self.note_obligation_cause_code(
2704 cause_code.peel_derives(),
2711 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2712 let mut parent_trait_pred =
2713 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2714 parent_trait_pred.remap_constness_diag(param_env);
2715 let parent_def_id = parent_trait_pred.def_id();
2716 let (self_ty, file) =
2717 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2719 "required for `{self_ty}` to implement `{}`",
2720 parent_trait_pred.print_modifiers_and_trait_path()
2722 let mut is_auto_trait = false;
2723 match self.tcx.hir().get_if_local(data.impl_def_id) {
2724 Some(Node::Item(hir::Item {
2725 kind: hir::ItemKind::Trait(is_auto, ..),
2729 // FIXME: we should do something else so that it works even on crate foreign
2731 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2732 err.span_note(ident.span, &msg)
2734 Some(Node::Item(hir::Item {
2735 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2738 let mut spans = Vec::with_capacity(2);
2739 if let Some(trait_ref) = of_trait {
2740 spans.push(trait_ref.path.span);
2742 spans.push(self_ty.span);
2743 err.span_note(spans, &msg)
2745 _ => err.note(&msg),
2748 if let Some(file) = file {
2750 "the full type name has been written to '{}'",
2754 let mut parent_predicate = parent_trait_pred;
2755 let mut data = &data.derived;
2757 seen_requirements.insert(parent_def_id);
2759 // We don't want to point at the ADT saying "required because it appears within
2760 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2761 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2764 let child_trait_ref =
2765 self.resolve_vars_if_possible(derived.parent_trait_pred);
2766 let child_def_id = child_trait_ref.def_id();
2767 if seen_requirements.insert(child_def_id) {
2771 parent_predicate = child_trait_ref.to_predicate(tcx);
2772 parent_trait_pred = child_trait_ref;
2775 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2776 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2777 let child_trait_pred =
2778 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2779 let child_def_id = child_trait_pred.def_id();
2780 if seen_requirements.insert(child_def_id) {
2784 data = &child.derived;
2785 parent_predicate = child_trait_pred.to_predicate(tcx);
2786 parent_trait_pred = child_trait_pred;
2790 "{} redundant requirement{} hidden",
2794 let (self_ty, file) =
2795 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2797 "required for `{self_ty}` to implement `{}`",
2798 parent_trait_pred.print_modifiers_and_trait_path()
2800 if let Some(file) = file {
2802 "the full type name has been written to '{}'",
2807 // #74711: avoid a stack overflow
2808 ensure_sufficient_stack(|| {
2809 self.note_obligation_cause_code(
2819 ObligationCauseCode::DerivedObligation(ref data) => {
2820 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2821 let parent_predicate = parent_trait_ref;
2822 // #74711: avoid a stack overflow
2823 ensure_sufficient_stack(|| {
2824 self.note_obligation_cause_code(
2834 ObligationCauseCode::FunctionArgumentObligation {
2839 let hir = self.tcx.hir();
2840 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2841 hir.find(arg_hir_id)
2843 let parent_id = hir.get_parent_item(arg_hir_id);
2844 let typeck_results: &TypeckResults<'tcx> = match &self.typeck_results {
2845 Some(t) if t.hir_owner == parent_id => t,
2846 _ => self.tcx.typeck(parent_id.def_id),
2848 let expr = expr.peel_blocks();
2849 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
2850 let span = expr.span;
2851 if Some(span) != err.span.primary_span() {
2854 if ty.references_error() {
2857 format!("this tail expression is of type `{:?}`", ty)
2862 if let Some(Node::Expr(hir::Expr {
2864 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2865 | hir::ExprKind::MethodCall(
2866 hir::PathSegment { ident: Ident { span, .. }, .. },
2870 })) = hir.find(call_hir_id)
2872 if Some(*span) != err.span.primary_span() {
2873 err.span_label(*span, "required by a bound introduced by this call");
2876 ensure_sufficient_stack(|| {
2877 self.note_obligation_cause_code(
2887 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2888 let item_name = self.tcx.item_name(trait_item_def_id);
2890 "the requirement `{}` appears on the `impl`'s {kind} `{}` but not on the \
2891 corresponding trait's {kind}",
2892 predicate, item_name,
2896 .opt_item_ident(trait_item_def_id)
2898 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2899 let mut assoc_span: MultiSpan = sp.into();
2900 assoc_span.push_span_label(
2902 format!("this trait's {kind} doesn't have the requirement `{}`", predicate),
2904 if let Some(ident) = self
2906 .opt_associated_item(trait_item_def_id)
2907 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2909 assoc_span.push_span_label(ident.span, "in this trait");
2911 err.span_note(assoc_span, &msg);
2913 ObligationCauseCode::TrivialBound => {
2914 err.help("see issue #48214");
2915 if tcx.sess.opts.unstable_features.is_nightly_build() {
2916 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2919 ObligationCauseCode::OpaqueReturnType(expr_info) => {
2920 if let Some((expr_ty, expr_span)) = expr_info {
2921 let expr_ty = self.resolve_vars_if_possible(expr_ty);
2924 format!("return type was inferred to be `{expr_ty}` here"),
2932 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2934 fn suggest_await_before_try(
2936 err: &mut Diagnostic,
2937 obligation: &PredicateObligation<'tcx>,
2938 trait_pred: ty::PolyTraitPredicate<'tcx>,
2941 let body_hir_id = obligation.cause.body_id;
2942 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2944 if let Some(body_id) =
2945 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2947 let body = self.tcx.hir().body(body_id);
2948 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2949 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2951 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2952 let impls_future = self.type_implements_trait(
2954 [self.tcx.erase_late_bound_regions(self_ty)],
2955 obligation.param_env,
2957 if !impls_future.must_apply_modulo_regions() {
2961 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2962 // `<T as Future>::Output`
2963 let projection_ty = trait_pred.map_bound(|trait_pred| {
2964 self.tcx.mk_projection(
2966 // Future::Output has no substs
2967 self.tcx.mk_substs_trait(trait_pred.self_ty(), []),
2970 let InferOk { value: projection_ty, .. } =
2971 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
2974 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
2976 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2977 obligation.param_env,
2978 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
2980 debug!(try_trait_obligation = ?try_obligation);
2981 if self.predicate_may_hold(&try_obligation)
2982 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2983 && snippet.ends_with('?')
2985 err.span_suggestion_verbose(
2986 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2987 "consider `await`ing on the `Future`",
2989 Applicability::MaybeIncorrect,
2996 fn suggest_floating_point_literal(
2998 obligation: &PredicateObligation<'tcx>,
2999 err: &mut Diagnostic,
3000 trait_ref: &ty::PolyTraitRef<'tcx>,
3002 let rhs_span = match obligation.cause.code() {
3003 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3006 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3007 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3009 err.span_suggestion_verbose(
3010 rhs_span.shrink_to_hi(),
3011 "consider using a floating-point literal by writing it with `.0`",
3013 Applicability::MaybeIncorrect,
3020 obligation: &PredicateObligation<'tcx>,
3021 err: &mut Diagnostic,
3022 trait_pred: ty::PolyTraitPredicate<'tcx>,
3024 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3027 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3028 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3032 let is_derivable_trait = match diagnostic_name {
3033 sym::Default => !adt.is_enum(),
3034 sym::PartialEq | sym::PartialOrd => {
3035 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3036 trait_pred.skip_binder().self_ty() == rhs_ty
3038 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3041 is_derivable_trait &&
3042 // Ensure all fields impl the trait.
3043 adt.all_fields().all(|field| {
3044 let field_ty = field.ty(self.tcx, substs);
3045 let trait_substs = match diagnostic_name {
3046 sym::PartialEq | sym::PartialOrd => {
3051 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3052 trait_ref: self.tcx.mk_trait_ref(
3053 trait_pred.def_id(),
3054 [field_ty].into_iter().chain(trait_substs),
3058 let field_obl = Obligation::new(
3060 obligation.cause.clone(),
3061 obligation.param_env,
3064 self.predicate_must_hold_modulo_regions(&field_obl)
3068 err.span_suggestion_verbose(
3069 self.tcx.def_span(adt.did()).shrink_to_lo(),
3071 "consider annotating `{}` with `#[derive({})]`",
3072 trait_pred.skip_binder().self_ty(),
3075 format!("#[derive({})]\n", diagnostic_name),
3076 Applicability::MaybeIncorrect,
3081 fn suggest_dereferencing_index(
3083 obligation: &PredicateObligation<'tcx>,
3084 err: &mut Diagnostic,
3085 trait_pred: ty::PolyTraitPredicate<'tcx>,
3087 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3088 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3089 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3090 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3091 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3093 err.span_suggestion_verbose(
3094 obligation.cause.span.shrink_to_lo(),
3095 "dereference this index",
3097 Applicability::MachineApplicable,
3103 /// Collect all the returned expressions within the input expression.
3104 /// Used to point at the return spans when we want to suggest some change to them.
3106 pub struct ReturnsVisitor<'v> {
3107 pub returns: Vec<&'v hir::Expr<'v>>,
3108 in_block_tail: bool,
3111 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3112 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3113 // Visit every expression to detect `return` paths, either through the function's tail
3114 // expression or `return` statements. We walk all nodes to find `return` statements, but
3115 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3116 // they're in the return path of the function body.
3118 hir::ExprKind::Ret(Some(ex)) => {
3119 self.returns.push(ex);
3121 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3122 self.in_block_tail = false;
3123 for stmt in block.stmts {
3124 hir::intravisit::walk_stmt(self, stmt);
3126 self.in_block_tail = true;
3127 if let Some(expr) = block.expr {
3128 self.visit_expr(expr);
3131 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3132 self.visit_expr(then);
3133 if let Some(el) = else_opt {
3134 self.visit_expr(el);
3137 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3139 self.visit_expr(arm.body);
3142 // We need to walk to find `return`s in the entire body.
3143 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3144 _ => self.returns.push(ex),
3148 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3149 assert!(!self.in_block_tail);
3150 if body.generator_kind().is_none() {
3151 if let hir::ExprKind::Block(block, None) = body.value.kind {
3152 if block.expr.is_some() {
3153 self.in_block_tail = true;
3157 hir::intravisit::walk_body(self, body);
3161 /// Collect all the awaited expressions within the input expression.
3163 struct AwaitsVisitor {
3164 awaits: Vec<hir::HirId>,
3167 impl<'v> Visitor<'v> for AwaitsVisitor {
3168 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3169 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3170 self.awaits.push(id)
3172 hir::intravisit::walk_expr(self, ex)
3176 pub trait NextTypeParamName {
3177 fn next_type_param_name(&self, name: Option<&str>) -> String;
3180 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3181 fn next_type_param_name(&self, name: Option<&str>) -> String {
3182 // This is the list of possible parameter names that we might suggest.
3183 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3184 let name = name.as_deref();
3185 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3186 let used_names = self
3188 .filter_map(|p| match p.name {
3189 hir::ParamName::Plain(ident) => Some(ident.name),
3192 .collect::<Vec<_>>();
3196 .find(|n| !used_names.contains(&Symbol::intern(n)))
3197 .unwrap_or(&"ParamName")
3202 fn suggest_trait_object_return_type_alternatives(
3203 err: &mut Diagnostic,
3206 is_object_safe: bool,
3208 err.span_suggestion(
3210 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3213 Applicability::MaybeIncorrect,
3215 err.span_suggestion(
3218 "use `impl {}` as the return type if all return paths have the same type but you \
3219 want to expose only the trait in the signature",
3222 format!("impl {}", trait_obj),
3223 Applicability::MaybeIncorrect,
3226 err.multipart_suggestion(
3228 "use a boxed trait object if all return paths implement trait `{}`",
3232 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3233 (ret_ty.shrink_to_hi(), ">".to_string()),
3235 Applicability::MaybeIncorrect,
3240 /// Collect the spans that we see the generic param `param_did`
3241 struct ReplaceImplTraitVisitor<'a> {
3242 ty_spans: &'a mut Vec<Span>,
3246 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3247 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3248 if let hir::TyKind::Path(hir::QPath::Resolved(
3250 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3253 if self.param_did == *segment_did {
3254 // `fn foo(t: impl Trait)`
3255 // ^^^^^^^^^^ get this to suggest `T` instead
3257 // There might be more than one `impl Trait`.
3258 self.ty_spans.push(t.span);
3263 hir::intravisit::walk_ty(self, t);
3267 // Replace `param` with `replace_ty`
3268 struct ReplaceImplTraitFolder<'tcx> {
3270 param: &'tcx ty::GenericParamDef,
3271 replace_ty: Ty<'tcx>,
3274 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3275 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3276 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3277 if self.param.index == *index {
3278 return self.replace_ty;
3281 t.super_fold_with(self)
3284 fn tcx(&self) -> TyCtxt<'tcx> {