2 EvaluationResult, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation,
6 use crate::autoderef::Autoderef;
7 use crate::infer::InferCtxt;
8 use crate::traits::normalize_to;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_data_structures::stack::ensure_sufficient_stack;
14 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
15 ErrorGuaranteed, MultiSpan, Style,
18 use rustc_hir::def::DefKind;
19 use rustc_hir::def_id::DefId;
20 use rustc_hir::intravisit::Visitor;
21 use rustc_hir::lang_items::LangItem;
22 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
23 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
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_session::Limit;
32 use rustc_span::def_id::LOCAL_CRATE;
33 use rustc_span::symbol::{kw, sym, Ident, Symbol};
34 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
35 use rustc_target::spec::abi;
38 use super::InferCtxtPrivExt;
39 use crate::infer::InferCtxtExt as _;
40 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
41 use rustc_middle::ty::print::with_no_trimmed_paths;
44 pub enum GeneratorInteriorOrUpvar {
45 // span of interior type
51 // This type provides a uniform interface to retrieve data on generators, whether it originated from
52 // the local crate being compiled or from a foreign crate.
54 pub enum GeneratorData<'tcx, 'a> {
55 Local(&'a TypeckResults<'tcx>),
56 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
59 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
60 // Try to get information about variables captured by the generator that matches a type we are
61 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
63 fn try_get_upvar_span<F>(
65 infer_context: &InferCtxt<'a, 'tcx>,
68 ) -> Option<GeneratorInteriorOrUpvar>
70 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
73 GeneratorData::Local(typeck_results) => {
74 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
75 upvars.iter().find_map(|(upvar_id, upvar)| {
76 let upvar_ty = typeck_results.node_type(*upvar_id);
77 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
78 if ty_matches(ty::Binder::dummy(upvar_ty)) {
79 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
86 GeneratorData::Foreign(_) => None,
90 // Try to get the span of a type being awaited on that matches the type we are looking with the
91 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
93 fn get_from_await_ty<F>(
95 visitor: AwaitsVisitor,
100 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
103 GeneratorData::Local(typeck_results) => visitor
106 .map(|id| hir.expect_expr(id))
108 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
110 .map(|expr| expr.span),
111 GeneratorData::Foreign(generator_diagnostic_data) => visitor
114 .map(|id| hir.expect_expr(id))
116 ty_matches(ty::Binder::dummy(
117 generator_diagnostic_data
119 .get(&await_expr.hir_id.local_id)
120 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
122 .map_or_else::<Ty<'tcx>, _, _>(
124 generator_diagnostic_data
126 .get(&await_expr.hir_id.local_id)
130 "node_type: no type for node `{}`",
131 ty::tls::with(|tcx| tcx
133 .node_to_string(await_expr.hir_id))
141 .map(|expr| expr.span),
145 /// Get the type, expression, span and optional scope span of all types
146 /// that are live across the yield of this generator
147 fn get_generator_interior_types(
149 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
151 GeneratorData::Local(typeck_result) => {
152 typeck_result.generator_interior_types.as_deref()
154 GeneratorData::Foreign(generator_diagnostic_data) => {
155 generator_diagnostic_data.generator_interior_types.as_deref()
160 // Used to get the source of the data, note we don't have as much information for generators
161 // originated from foreign crates
162 fn is_foreign(&self) -> bool {
164 GeneratorData::Local(_) => false,
165 GeneratorData::Foreign(_) => true,
170 // This trait is public to expose the diagnostics methods to clippy.
171 pub trait InferCtxtExt<'tcx> {
172 fn suggest_restricting_param_bound(
174 err: &mut Diagnostic,
175 trait_pred: ty::PolyTraitPredicate<'tcx>,
176 associated_item: Option<(&'static str, Ty<'tcx>)>,
180 fn suggest_dereferences(
182 obligation: &PredicateObligation<'tcx>,
183 err: &mut Diagnostic,
184 trait_pred: ty::PolyTraitPredicate<'tcx>,
187 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
191 obligation: &PredicateObligation<'tcx>,
192 err: &mut Diagnostic,
193 trait_pred: ty::PolyTraitPredicate<'tcx>,
196 fn suggest_add_reference_to_arg(
198 obligation: &PredicateObligation<'tcx>,
199 err: &mut Diagnostic,
200 trait_pred: ty::PolyTraitPredicate<'tcx>,
201 has_custom_message: bool,
204 fn suggest_borrowing_for_object_cast(
206 err: &mut Diagnostic,
207 obligation: &PredicateObligation<'tcx>,
212 fn suggest_remove_reference(
214 obligation: &PredicateObligation<'tcx>,
215 err: &mut Diagnostic,
216 trait_pred: ty::PolyTraitPredicate<'tcx>,
219 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
221 fn suggest_change_mut(
223 obligation: &PredicateObligation<'tcx>,
224 err: &mut Diagnostic,
225 trait_pred: ty::PolyTraitPredicate<'tcx>,
228 fn suggest_semicolon_removal(
230 obligation: &PredicateObligation<'tcx>,
231 err: &mut Diagnostic,
233 trait_pred: ty::PolyTraitPredicate<'tcx>,
236 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
238 fn suggest_impl_trait(
240 err: &mut Diagnostic,
242 obligation: &PredicateObligation<'tcx>,
243 trait_pred: ty::PolyTraitPredicate<'tcx>,
246 fn point_at_returns_when_relevant(
248 err: &mut Diagnostic,
249 obligation: &PredicateObligation<'tcx>,
252 fn report_closure_arg_mismatch(
255 found_span: Option<Span>,
256 found: ty::PolyTraitRef<'tcx>,
257 expected: ty::PolyTraitRef<'tcx>,
258 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
260 fn suggest_fully_qualified_path(
262 err: &mut Diagnostic,
268 fn maybe_note_obligation_cause_for_async_await(
270 err: &mut Diagnostic,
271 obligation: &PredicateObligation<'tcx>,
274 fn note_obligation_cause_for_async_await(
276 err: &mut Diagnostic,
277 interior_or_upvar_span: GeneratorInteriorOrUpvar,
278 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
280 outer_generator: Option<DefId>,
281 trait_pred: ty::TraitPredicate<'tcx>,
283 typeck_results: Option<&ty::TypeckResults<'tcx>>,
284 obligation: &PredicateObligation<'tcx>,
285 next_code: Option<&ObligationCauseCode<'tcx>>,
288 fn note_obligation_cause_code<T>(
290 err: &mut Diagnostic,
292 param_env: ty::ParamEnv<'tcx>,
293 cause_code: &ObligationCauseCode<'tcx>,
294 obligated_types: &mut Vec<Ty<'tcx>>,
295 seen_requirements: &mut FxHashSet<DefId>,
299 fn suggest_new_overflow_limit(&self, err: &mut Diagnostic);
301 /// Suggest to await before try: future? => future.await?
302 fn suggest_await_before_try(
304 err: &mut Diagnostic,
305 obligation: &PredicateObligation<'tcx>,
306 trait_pred: ty::PolyTraitPredicate<'tcx>,
310 fn suggest_floating_point_literal(
312 obligation: &PredicateObligation<'tcx>,
313 err: &mut Diagnostic,
314 trait_ref: &ty::PolyTraitRef<'tcx>,
319 obligation: &PredicateObligation<'tcx>,
320 err: &mut Diagnostic,
321 trait_pred: ty::PolyTraitPredicate<'tcx>,
324 fn suggest_dereferencing_index(
326 obligation: &PredicateObligation<'tcx>,
327 err: &mut Diagnostic,
328 trait_pred: ty::PolyTraitPredicate<'tcx>,
332 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
334 generics.tail_span_for_predicate_suggestion(),
335 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
339 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
340 /// it can also be an `impl Trait` param that needs to be decomposed to a type
341 /// param for cleaner code.
342 fn suggest_restriction<'tcx>(
345 hir_generics: &hir::Generics<'tcx>,
347 err: &mut Diagnostic,
348 fn_sig: Option<&hir::FnSig<'_>>,
349 projection: Option<&ty::ProjectionTy<'_>>,
350 trait_pred: ty::PolyTraitPredicate<'tcx>,
351 // When we are dealing with a trait, `super_traits` will be `Some`:
352 // Given `trait T: A + B + C {}`
353 // - ^^^^^^^^^ GenericBounds
356 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
358 if hir_generics.where_clause_span.from_expansion()
359 || hir_generics.where_clause_span.desugaring_kind().is_some()
363 let Some(item_id) = hir_id.as_owner() else { return; };
364 let generics = tcx.generics_of(item_id);
365 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
366 if let Some((param, bound_str, fn_sig)) =
367 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
368 // Shenanigans to get the `Trait` from the `impl Trait`.
369 ty::Param(param) => {
370 let param_def = generics.type_param(param, tcx);
371 if param_def.kind.is_synthetic() {
373 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
374 return Some((param_def, bound_str, sig));
381 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
382 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
385 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
388 if !trait_pred.is_suggestable(tcx, false) {
391 // We know we have an `impl Trait` that doesn't satisfy a required projection.
393 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
394 // types. There should be at least one, but there might be *more* than one. In that
395 // case we could just ignore it and try to identify which one needs the restriction,
396 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
398 let mut ty_spans = vec![];
399 for input in fn_sig.decl.inputs {
400 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
403 // The type param `T: Trait` we will suggest to introduce.
404 let type_param = format!("{}: {}", type_param_name, bound_str);
407 if let Some(span) = hir_generics.span_for_param_suggestion() {
408 (span, format!(", {}", type_param))
410 (hir_generics.span, format!("<{}>", type_param))
412 // `fn foo(t: impl Trait)`
413 // ^ suggest `where <T as Trait>::A: Bound`
414 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx).to_string()),
416 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
418 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
419 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
420 // `fn foo(t: impl Trait<A: Bound>)` instead.
421 err.multipart_suggestion(
422 "introduce a type parameter with a trait bound instead of using `impl Trait`",
424 Applicability::MaybeIncorrect,
427 if !trait_pred.is_suggestable(tcx, false) {
430 // Trivial case: `T` needs an extra bound: `T: Bound`.
431 let (sp, suggestion) = match (
435 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
439 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx).to_string())
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<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, '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().local_def_id_to_hir_id(self.tcx.hir().get_parent_item(hir_id));
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.in_progress_typeck_results
679 else { return false; };
680 let typeck_results = typeck_results.borrow();
681 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
682 else { return false; };
683 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
684 else { return false; };
686 let span = obligation.cause.span;
687 let mut real_trait_pred = trait_pred;
688 let mut code = obligation.cause.code();
689 while let Some((parent_code, parent_trait_pred)) = code.parent() {
691 if let Some(parent_trait_pred) = parent_trait_pred {
692 real_trait_pred = parent_trait_pred;
695 let real_ty = real_trait_pred.self_ty();
696 // We `erase_late_bound_regions` here because `make_subregion` does not handle
697 // `ReLateBound`, and we don't particularly care about the regions.
699 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
705 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
706 let mut autoderef = Autoderef::new(
708 obligation.param_env,
709 obligation.cause.body_id,
714 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
716 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
718 // Remapping bound vars here
719 let real_trait_pred_and_ty =
720 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
721 let obligation = self.mk_trait_obligation_with_new_self_ty(
722 obligation.param_env,
723 real_trait_pred_and_ty,
725 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
728 // Don't care about `&mut` because `DerefMut` is used less
729 // often and user will not expect autoderef happens.
730 if let Some(hir::Node::Expr(hir::Expr {
732 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
734 })) = self.tcx.hir().find(*arg_hir_id)
736 let derefs = "*".repeat(steps);
737 err.span_suggestion_verbose(
738 expr.span.shrink_to_lo(),
739 "consider dereferencing here",
741 Applicability::MachineApplicable,
746 } else if real_trait_pred != trait_pred {
747 // This branch addresses #87437.
749 // Remapping bound vars here
750 let real_trait_pred_and_base_ty =
751 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
752 let obligation = self.mk_trait_obligation_with_new_self_ty(
753 obligation.param_env,
754 real_trait_pred_and_base_ty,
756 if self.predicate_may_hold(&obligation) {
757 err.span_suggestion_verbose(
759 "consider dereferencing here",
761 Applicability::MachineApplicable,
771 /// Given a closure's `DefId`, return the given name of the closure.
773 /// This doesn't account for reassignments, but it's only used for suggestions.
774 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
775 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
776 // Get the local name of this closure. This can be inaccurate because
777 // of the possibility of reassignment, but this should be good enough.
779 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
789 let hir = self.tcx.hir();
790 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
791 let parent_node = hir.get_parent_node(hir_id);
792 match hir.find(parent_node) {
793 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
794 get_name(err, &local.pat.kind)
796 // Different to previous arm because one is `&hir::Local` and the other
797 // is `P<hir::Local>`.
798 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
803 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
804 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
805 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
808 obligation: &PredicateObligation<'tcx>,
809 err: &mut Diagnostic,
810 trait_pred: ty::PolyTraitPredicate<'tcx>,
812 // Skipping binder here, remapping below
813 let self_ty = trait_pred.self_ty().skip_binder();
815 let (def_id, output_ty, callable) = match *self_ty.kind() {
816 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
817 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
820 let msg = format!("use parentheses to call the {}", callable);
822 // "We should really create a single list of bound vars from the combined vars
823 // from the predicate and function, but instead we just liberate the function bound vars"
824 let output_ty = self.tcx.liberate_late_bound_regions(def_id, output_ty);
826 // Remapping bound vars here
827 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output_ty));
830 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
832 match self.evaluate_obligation(&new_obligation) {
834 EvaluationResult::EvaluatedToOk
835 | EvaluationResult::EvaluatedToOkModuloRegions
836 | EvaluationResult::EvaluatedToOkModuloOpaqueTypes
837 | EvaluationResult::EvaluatedToAmbig,
841 let hir = self.tcx.hir();
842 // Get the name of the callable and the arguments to be used in the suggestion.
843 let (snippet, sugg) = match hir.get_if_local(def_id) {
844 Some(hir::Node::Expr(hir::Expr {
845 kind: hir::ExprKind::Closure(hir::Closure { fn_decl, fn_decl_span, .. }),
848 err.span_label(*fn_decl_span, "consider calling this closure");
849 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
852 let args = fn_decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
853 let sugg = format!("({})", args);
854 (format!("{}{}", name, sugg), sugg)
856 Some(hir::Node::Item(hir::Item {
858 kind: hir::ItemKind::Fn(.., body_id),
861 err.span_label(ident.span, "consider calling this function");
862 let body = hir.body(*body_id);
866 .map(|arg| match &arg.pat.kind {
867 hir::PatKind::Binding(_, _, ident, None)
868 // FIXME: provide a better suggestion when encountering `SelfLower`, it
869 // should suggest a method call.
870 if ident.name != kw::SelfLower => ident.to_string(),
871 _ => "_".to_string(),
875 let sugg = format!("({})", args);
876 (format!("{}{}", ident, sugg), sugg)
880 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
881 && obligation.cause.span.can_be_used_for_suggestions()
883 // When the obligation error has been ensured to have been caused by
884 // an argument, the `obligation.cause.span` points at the expression
885 // of the argument, so we can provide a suggestion. Otherwise, we give
886 // a more general note.
887 err.span_suggestion_verbose(
888 obligation.cause.span.shrink_to_hi(),
891 Applicability::HasPlaceholders,
894 err.help(&format!("{}: `{}`", msg, snippet));
899 fn suggest_add_reference_to_arg(
901 obligation: &PredicateObligation<'tcx>,
902 err: &mut Diagnostic,
903 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
904 has_custom_message: bool,
906 let span = obligation.cause.span;
908 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
909 obligation.cause.code()
912 } else if let ObligationCauseCode::ItemObligation(_)
913 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
915 obligation.cause.code()
916 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
917 span.ctxt().outer_expn_data().kind
919 obligation.cause.code()
924 // List of traits for which it would be nonsensical to suggest borrowing.
925 // For instance, immutable references are always Copy, so suggesting to
926 // borrow would always succeed, but it's probably not what the user wanted.
927 let mut never_suggest_borrow: Vec<_> =
928 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
930 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
933 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
934 never_suggest_borrow.push(def_id);
937 let param_env = obligation.param_env;
939 // Try to apply the original trait binding obligation by borrowing.
940 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
943 if blacklist.contains(&old_pred.def_id()) {
946 // We map bounds to `&T` and `&mut T`
947 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
950 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
953 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
956 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
960 let mk_result = |trait_pred_and_new_ty| {
962 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
963 self.predicate_must_hold_modulo_regions(&obligation)
965 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
966 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
968 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
969 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
970 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
973 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
974 matches!(mutability, hir::Mutability::Mut),
980 if imm_ref_self_ty_satisfies_pred
981 || mut_ref_self_ty_satisfies_pred
982 || ref_inner_ty_satisfies_pred
984 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
985 // We don't want a borrowing suggestion on the fields in structs,
988 // the_foos: Vec<Foo>
992 span.ctxt().outer_expn_data().kind,
993 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
997 if snippet.starts_with('&') {
998 // This is already a literal borrow and the obligation is failing
999 // somewhere else in the obligation chain. Do not suggest non-sense.
1002 // We have a very specific type of error, where just borrowing this argument
1003 // might solve the problem. In cases like this, the important part is the
1004 // original type obligation, not the last one that failed, which is arbitrary.
1005 // Because of this, we modify the error to refer to the original obligation and
1006 // return early in the caller.
1008 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1009 if has_custom_message {
1013 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1018 "the trait `{}` is not implemented for `{}`",
1019 old_pred.print_modifiers_and_trait_path(),
1020 old_pred.self_ty().skip_binder(),
1024 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1025 err.span_suggestions(
1026 span.shrink_to_lo(),
1027 "consider borrowing here",
1028 ["&".to_string(), "&mut ".to_string()].into_iter(),
1029 Applicability::MaybeIncorrect,
1032 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1033 err.span_suggestion_verbose(
1034 span.shrink_to_lo(),
1036 "consider{} borrowing here",
1037 if is_mut { " mutably" } else { "" }
1039 format!("&{}", if is_mut { "mut " } else { "" }),
1040 Applicability::MaybeIncorrect,
1049 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1050 try_borrowing(cause.derived.parent_trait_pred, &[])
1051 } else if let ObligationCauseCode::BindingObligation(_, _)
1052 | ObligationCauseCode::ItemObligation(_)
1053 | ObligationCauseCode::ExprItemObligation(..)
1054 | ObligationCauseCode::ExprBindingObligation(..) = code
1056 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1062 // Suggest borrowing the type
1063 fn suggest_borrowing_for_object_cast(
1065 err: &mut Diagnostic,
1066 obligation: &PredicateObligation<'tcx>,
1068 object_ty: Ty<'tcx>,
1070 let ty::Dynamic(predicates, _) = object_ty.kind() else { return; };
1071 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1073 for predicate in predicates.iter() {
1074 if !self.predicate_must_hold_modulo_regions(
1075 &obligation.with(predicate.with_self_ty(self.tcx, self_ref_ty)),
1081 err.span_suggestion(
1082 obligation.cause.span.shrink_to_lo(),
1084 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1087 Applicability::MaybeIncorrect,
1091 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1092 /// suggest removing these references until we reach a type that implements the trait.
1093 fn suggest_remove_reference(
1095 obligation: &PredicateObligation<'tcx>,
1096 err: &mut Diagnostic,
1097 trait_pred: ty::PolyTraitPredicate<'tcx>,
1099 let span = obligation.cause.span;
1101 let mut suggested = false;
1102 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1104 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1105 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1106 // Do not suggest removal of borrow from type arguments.
1110 // Skipping binder here, remapping below
1111 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1113 for refs_remaining in 0..refs_number {
1114 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1117 suggested_ty = *inner_ty;
1119 // Remapping bound vars here
1120 let trait_pred_and_suggested_ty =
1121 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1123 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1124 obligation.param_env,
1125 trait_pred_and_suggested_ty,
1128 if self.predicate_may_hold(&new_obligation) {
1133 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1135 let remove_refs = refs_remaining + 1;
1137 let msg = if remove_refs == 1 {
1138 "consider removing the leading `&`-reference".to_string()
1140 format!("consider removing {} leading `&`-references", remove_refs)
1143 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1152 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1153 let span = obligation.cause.span;
1155 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1156 let hir = self.tcx.hir();
1157 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1158 if let hir::Node::Expr(expr) = node {
1159 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1160 // and if not maybe suggest doing something else? If we kept the expression around we
1161 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1162 // it is from the local crate.
1163 err.span_suggestion_verbose(
1164 expr.span.shrink_to_hi().with_hi(span.hi()),
1165 "remove the `.await`",
1167 Applicability::MachineApplicable,
1169 // FIXME: account for associated `async fn`s.
1170 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1171 if let ty::PredicateKind::Trait(pred) =
1172 obligation.predicate.kind().skip_binder()
1176 &format!("this call returns `{}`", pred.self_ty()),
1179 if let Some(typeck_results) =
1180 self.in_progress_typeck_results.map(|t| t.borrow())
1181 && let ty = typeck_results.expr_ty_adjusted(base)
1182 && let ty::FnDef(def_id, _substs) = ty.kind()
1183 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1184 hir.get_if_local(*def_id)
1187 "alternatively, consider making `fn {}` asynchronous",
1190 if vis_span.is_empty() {
1191 err.span_suggestion_verbose(
1192 span.shrink_to_lo(),
1195 Applicability::MaybeIncorrect,
1198 err.span_suggestion_verbose(
1199 vis_span.shrink_to_hi(),
1202 Applicability::MaybeIncorrect,
1212 /// Check if the trait bound is implemented for a different mutability and note it in the
1214 fn suggest_change_mut(
1216 obligation: &PredicateObligation<'tcx>,
1217 err: &mut Diagnostic,
1218 trait_pred: ty::PolyTraitPredicate<'tcx>,
1220 let points_at_arg = matches!(
1221 obligation.cause.code(),
1222 ObligationCauseCode::FunctionArgumentObligation { .. },
1225 let span = obligation.cause.span;
1226 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1228 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1229 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1230 // Do not suggest removal of borrow from type arguments.
1233 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1234 if trait_pred.has_infer_types_or_consts() {
1235 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1236 // unresolved bindings.
1240 // Skipping binder here, remapping below
1241 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1243 let suggested_ty = match mutability {
1244 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1245 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1248 // Remapping bound vars here
1249 let trait_pred_and_suggested_ty =
1250 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1252 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1253 obligation.param_env,
1254 trait_pred_and_suggested_ty,
1256 let suggested_ty_would_satisfy_obligation = self
1257 .evaluate_obligation_no_overflow(&new_obligation)
1258 .must_apply_modulo_regions();
1259 if suggested_ty_would_satisfy_obligation {
1264 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1265 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1266 err.span_suggestion_verbose(
1268 "consider changing this borrow's mutability",
1270 Applicability::MachineApplicable,
1274 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1275 trait_pred.print_modifiers_and_trait_path(),
1277 trait_pred.skip_binder().self_ty(),
1285 fn suggest_semicolon_removal(
1287 obligation: &PredicateObligation<'tcx>,
1288 err: &mut Diagnostic,
1290 trait_pred: ty::PolyTraitPredicate<'tcx>,
1292 let hir = self.tcx.hir();
1293 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1294 let node = hir.find(parent_node);
1295 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1296 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1297 && sig.decl.output.span().overlaps(span)
1298 && blk.expr.is_none()
1299 && trait_pred.self_ty().skip_binder().is_unit()
1300 && let Some(stmt) = blk.stmts.last()
1301 && let hir::StmtKind::Semi(expr) = stmt.kind
1302 // Only suggest this if the expression behind the semicolon implements the predicate
1303 && let Some(typeck_results) = self.in_progress_typeck_results
1304 && let Some(ty) = typeck_results.borrow().expr_ty_opt(expr)
1305 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1306 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1312 "this expression has type `{}`, which implements `{}`",
1314 trait_pred.print_modifiers_and_trait_path()
1317 err.span_suggestion(
1318 self.tcx.sess.source_map().end_point(stmt.span),
1319 "remove this semicolon",
1321 Applicability::MachineApplicable
1328 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1329 let hir = self.tcx.hir();
1330 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1331 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1335 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1338 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1339 /// applicable and signal that the error has been expanded appropriately and needs to be
1341 fn suggest_impl_trait(
1343 err: &mut Diagnostic,
1345 obligation: &PredicateObligation<'tcx>,
1346 trait_pred: ty::PolyTraitPredicate<'tcx>,
1348 match obligation.cause.code().peel_derives() {
1349 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1350 ObligationCauseCode::SizedReturnType => {}
1354 let hir = self.tcx.hir();
1355 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1356 let node = hir.find(fn_hir_id);
1357 let Some(hir::Node::Item(hir::Item {
1358 kind: hir::ItemKind::Fn(sig, _, body_id),
1364 let body = hir.body(*body_id);
1365 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1366 let ty = trait_pred.skip_binder().self_ty();
1367 let is_object_safe = match ty.kind() {
1368 ty::Dynamic(predicates, _) => {
1369 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1372 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1374 // We only want to suggest `impl Trait` to `dyn Trait`s.
1375 // For example, `fn foo() -> str` needs to be filtered out.
1379 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1383 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1384 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1385 // Recursively look for `TraitObject` types and if there's only one, use that span to
1386 // suggest `impl Trait`.
1388 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1389 // otherwise suggest using `Box<dyn Trait>` or an enum.
1390 let mut visitor = ReturnsVisitor::default();
1391 visitor.visit_body(&body);
1393 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1394 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1396 let ret_types = visitor
1399 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1400 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1401 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1403 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1405 let ty = self.resolve_vars_if_possible(ty);
1407 !matches!(ty.kind(), ty::Error(_))
1408 && last_ty.map_or(true, |last_ty| {
1409 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1410 // *after* in the dependency graph.
1411 match (ty.kind(), last_ty.kind()) {
1412 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1413 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1414 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1416 Infer(InferTy::FreshFloatTy(_)),
1417 Infer(InferTy::FreshFloatTy(_)),
1422 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1425 let mut spans_and_needs_box = vec![];
1427 match liberated_sig.output().kind() {
1428 ty::Dynamic(predicates, _) => {
1429 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1430 let param_env = ty::ParamEnv::empty();
1432 if !only_never_return {
1433 for (expr_span, return_ty) in ret_types {
1434 let self_ty_satisfies_dyn_predicates = |self_ty| {
1435 predicates.iter().all(|predicate| {
1436 let pred = predicate.with_self_ty(self.tcx, self_ty);
1437 let obl = Obligation::new(cause.clone(), param_env, pred);
1438 self.predicate_may_hold(&obl)
1442 if let ty::Adt(def, substs) = return_ty.kind()
1444 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1446 spans_and_needs_box.push((expr_span, false));
1447 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1448 spans_and_needs_box.push((expr_span, true));
1458 let sm = self.tcx.sess.source_map();
1459 if !ret_ty.span.overlaps(span) {
1462 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1463 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1469 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1470 let name = liberated_sig.output().to_string();
1472 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1473 if !name.starts_with("dyn ") {
1479 err.code(error_code!(E0746));
1480 err.set_primary_message("return type cannot have an unboxed trait object");
1481 err.children.clear();
1482 let impl_trait_msg = "for information on `impl Trait`, see \
1483 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1484 #returning-types-that-implement-traits>";
1485 let trait_obj_msg = "for information on trait objects, see \
1486 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1487 #using-trait-objects-that-allow-for-values-of-different-types>";
1489 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1490 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1491 if only_never_return {
1492 // No return paths, probably using `panic!()` or similar.
1493 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1494 suggest_trait_object_return_type_alternatives(
1500 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1501 // Suggest `-> impl Trait`.
1502 err.span_suggestion(
1505 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1506 which implements `{1}`",
1509 format!("impl {}", trait_obj),
1510 Applicability::MachineApplicable,
1512 err.note(impl_trait_msg);
1515 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1516 err.multipart_suggestion(
1517 "return a boxed trait object instead",
1519 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1520 (span.shrink_to_hi(), ">".to_string()),
1522 Applicability::MaybeIncorrect,
1524 for (span, needs_box) in spans_and_needs_box {
1526 err.multipart_suggestion(
1527 "... and box this value",
1529 (span.shrink_to_lo(), "Box::new(".to_string()),
1530 (span.shrink_to_hi(), ")".to_string()),
1532 Applicability::MaybeIncorrect,
1537 // This is currently not possible to trigger because E0038 takes precedence, but
1538 // leave it in for completeness in case anything changes in an earlier stage.
1540 "if trait `{}` were object-safe, you could return a trait object",
1544 err.note(trait_obj_msg);
1546 "if all the returned values were of the same type you could use `impl {}` as the \
1550 err.note(impl_trait_msg);
1551 err.note("you can create a new `enum` with a variant for each returned type");
1556 fn point_at_returns_when_relevant(
1558 err: &mut Diagnostic,
1559 obligation: &PredicateObligation<'tcx>,
1561 match obligation.cause.code().peel_derives() {
1562 ObligationCauseCode::SizedReturnType => {}
1566 let hir = self.tcx.hir();
1567 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1568 let node = hir.find(parent_node);
1569 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1572 let body = hir.body(*body_id);
1573 // Point at all the `return`s in the function as they have failed trait bounds.
1574 let mut visitor = ReturnsVisitor::default();
1575 visitor.visit_body(&body);
1576 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1577 for expr in &visitor.returns {
1578 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1579 let ty = self.resolve_vars_if_possible(returned_ty);
1580 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1586 fn report_closure_arg_mismatch(
1589 found_span: Option<Span>,
1590 found: ty::PolyTraitRef<'tcx>,
1591 expected: ty::PolyTraitRef<'tcx>,
1592 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1593 pub(crate) fn build_fn_sig_ty<'tcx>(
1594 infcx: &InferCtxt<'_, 'tcx>,
1595 trait_ref: ty::PolyTraitRef<'tcx>,
1597 let inputs = trait_ref.skip_binder().substs.type_at(1);
1598 let sig = match inputs.kind() {
1600 if infcx.tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1602 infcx.tcx.mk_fn_sig(
1604 infcx.next_ty_var(TypeVariableOrigin {
1606 kind: TypeVariableOriginKind::MiscVariable,
1609 hir::Unsafety::Normal,
1613 _ => infcx.tcx.mk_fn_sig(
1614 std::iter::once(inputs),
1615 infcx.next_ty_var(TypeVariableOrigin {
1617 kind: TypeVariableOriginKind::MiscVariable,
1620 hir::Unsafety::Normal,
1625 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1628 let argument_kind = match expected.skip_binder().self_ty().kind() {
1629 ty::Closure(..) => "closure",
1630 ty::Generator(..) => "generator",
1633 let mut err = struct_span_err!(
1637 "type mismatch in {argument_kind} arguments",
1640 err.span_label(span, "expected due to this");
1642 let found_span = found_span.unwrap_or(span);
1643 err.span_label(found_span, "found signature defined here");
1645 let expected = build_fn_sig_ty(self, expected);
1646 let found = build_fn_sig_ty(self, found);
1648 let (expected_str, found_str) = self.cmp(expected, found);
1650 let signature_kind = format!("{argument_kind} signature");
1651 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1656 fn suggest_fully_qualified_path(
1658 err: &mut Diagnostic,
1663 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1664 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1666 "{}s cannot be accessed directly on a `trait`, they can only be \
1667 accessed through a specific `impl`",
1668 assoc_item.kind.as_def_kind().descr(item_def_id)
1670 err.span_suggestion(
1672 "use the fully qualified path to an implementation",
1673 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1674 Applicability::HasPlaceholders,
1680 /// Adds an async-await specific note to the diagnostic when the future does not implement
1681 /// an auto trait because of a captured type.
1684 /// note: future does not implement `Qux` as this value is used across an await
1685 /// --> $DIR/issue-64130-3-other.rs:17:5
1687 /// LL | let x = Foo;
1688 /// | - has type `Foo`
1689 /// LL | baz().await;
1690 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1692 /// | - `x` is later dropped here
1695 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1696 /// is "replaced" with a different message and a more specific error.
1699 /// error: future cannot be sent between threads safely
1700 /// --> $DIR/issue-64130-2-send.rs:21:5
1702 /// LL | fn is_send<T: Send>(t: T) { }
1703 /// | ---- required by this bound in `is_send`
1705 /// LL | is_send(bar());
1706 /// | ^^^^^^^ future returned by `bar` is not send
1708 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1709 /// implemented for `Foo`
1710 /// note: future is not send as this value is used across an await
1711 /// --> $DIR/issue-64130-2-send.rs:15:5
1713 /// LL | let x = Foo;
1714 /// | - has type `Foo`
1715 /// LL | baz().await;
1716 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1718 /// | - `x` is later dropped here
1721 /// Returns `true` if an async-await specific note was added to the diagnostic.
1722 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1723 fn maybe_note_obligation_cause_for_async_await(
1725 err: &mut Diagnostic,
1726 obligation: &PredicateObligation<'tcx>,
1728 let hir = self.tcx.hir();
1730 // Attempt to detect an async-await error by looking at the obligation causes, looking
1731 // for a generator to be present.
1733 // When a future does not implement a trait because of a captured type in one of the
1734 // generators somewhere in the call stack, then the result is a chain of obligations.
1736 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1737 // future is passed as an argument to a function C which requires a `Send` type, then the
1738 // chain looks something like this:
1740 // - `BuiltinDerivedObligation` with a generator witness (B)
1741 // - `BuiltinDerivedObligation` with a generator (B)
1742 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1743 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1744 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1745 // - `BuiltinDerivedObligation` with a generator witness (A)
1746 // - `BuiltinDerivedObligation` with a generator (A)
1747 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1748 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1749 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1750 // - `BindingObligation` with `impl_send (Send requirement)
1752 // The first obligation in the chain is the most useful and has the generator that captured
1753 // the type. The last generator (`outer_generator` below) has information about where the
1754 // bound was introduced. At least one generator should be present for this diagnostic to be
1756 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1757 ty::PredicateKind::Trait(p) => (Some(p), Some(p.self_ty())),
1760 let mut generator = None;
1761 let mut outer_generator = None;
1762 let mut next_code = Some(obligation.cause.code());
1764 let mut seen_upvar_tys_infer_tuple = false;
1766 while let Some(code) = next_code {
1769 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1770 next_code = Some(parent_code);
1772 ObligationCauseCode::ImplDerivedObligation(cause) => {
1773 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1775 parent_trait_ref = ?cause.derived.parent_trait_pred,
1776 self_ty.kind = ?ty.kind(),
1781 ty::Generator(did, ..) => {
1782 generator = generator.or(Some(did));
1783 outer_generator = Some(did);
1785 ty::GeneratorWitness(..) => {}
1786 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1787 // By introducing a tuple of upvar types into the chain of obligations
1788 // of a generator, the first non-generator item is now the tuple itself,
1789 // we shall ignore this.
1791 seen_upvar_tys_infer_tuple = true;
1793 _ if generator.is_none() => {
1794 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1795 target_ty = Some(ty);
1800 next_code = Some(&cause.derived.parent_code);
1802 ObligationCauseCode::DerivedObligation(derived_obligation)
1803 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1804 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1806 parent_trait_ref = ?derived_obligation.parent_trait_pred,
1807 self_ty.kind = ?ty.kind(),
1811 ty::Generator(did, ..) => {
1812 generator = generator.or(Some(did));
1813 outer_generator = Some(did);
1815 ty::GeneratorWitness(..) => {}
1816 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1817 // By introducing a tuple of upvar types into the chain of obligations
1818 // of a generator, the first non-generator item is now the tuple itself,
1819 // we shall ignore this.
1821 seen_upvar_tys_infer_tuple = true;
1823 _ if generator.is_none() => {
1824 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1825 target_ty = Some(ty);
1830 next_code = Some(&derived_obligation.parent_code);
1836 // Only continue if a generator was found.
1837 debug!(?generator, ?trait_ref, ?target_ty);
1838 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1842 let span = self.tcx.def_span(generator_did);
1844 let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1845 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1848 ?generator_did_root,
1849 in_progress_typeck_results.hir_owner = ?in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1853 let generator_body = generator_did
1855 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
1856 .map(|body_id| hir.body(body_id));
1857 let is_async = match generator_did.as_local() {
1858 Some(_) => generator_body
1859 .and_then(|body| body.generator_kind())
1860 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1864 .generator_kind(generator_did)
1865 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1868 let mut visitor = AwaitsVisitor::default();
1869 if let Some(body) = generator_body {
1870 visitor.visit_body(body);
1872 debug!(awaits = ?visitor.awaits);
1874 // Look for a type inside the generator interior that matches the target type to get
1876 let target_ty_erased = self.tcx.erase_regions(target_ty);
1877 let ty_matches = |ty| -> bool {
1878 // Careful: the regions for types that appear in the
1879 // generator interior are not generally known, so we
1880 // want to erase them when comparing (and anyway,
1881 // `Send` and other bounds are generally unaffected by
1882 // the choice of region). When erasing regions, we
1883 // also have to erase late-bound regions. This is
1884 // because the types that appear in the generator
1885 // interior generally contain "bound regions" to
1886 // represent regions that are part of the suspended
1887 // generator frame. Bound regions are preserved by
1888 // `erase_regions` and so we must also call
1889 // `erase_late_bound_regions`.
1890 let ty_erased = self.tcx.erase_late_bound_regions(ty);
1891 let ty_erased = self.tcx.erase_regions(ty_erased);
1892 let eq = ty_erased == target_ty_erased;
1893 debug!(?ty_erased, ?target_ty_erased, ?eq);
1897 let mut interior_or_upvar_span = None;
1898 let mut interior_extra_info = None;
1900 // Get the typeck results from the infcx if the generator is the function we are currently
1901 // type-checking; otherwise, get them by performing a query. This is needed to avoid
1902 // cycles. If we can't use resolved types because the generator comes from another crate,
1903 // we still provide a targeted error but without all the relevant spans.
1904 let generator_data: Option<GeneratorData<'tcx, '_>> = match &in_progress_typeck_results {
1905 Some(t) if t.hir_owner.to_def_id() == generator_did_root => {
1906 Some(GeneratorData::Local(&t))
1908 _ if generator_did.is_local() => {
1909 Some(GeneratorData::Local(self.tcx.typeck(generator_did.expect_local())))
1913 .generator_diagnostic_data(generator_did)
1915 .map(|generator_diag_data| GeneratorData::Foreign(generator_diag_data)),
1918 if let Some(generator_data) = generator_data.as_ref() {
1919 interior_or_upvar_span =
1920 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
1922 // The generator interior types share the same binders
1923 if let Some(cause) =
1924 generator_data.get_generator_interior_types().skip_binder().iter().find(
1925 |ty::GeneratorInteriorTypeCause { ty, .. }| {
1926 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
1930 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
1931 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1934 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1935 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1938 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
1939 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span));
1943 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1944 let typeck_results = generator_data.and_then(|generator_data| match generator_data {
1945 GeneratorData::Local(typeck_results) => Some(typeck_results),
1946 GeneratorData::Foreign(_) => None,
1948 self.note_obligation_cause_for_async_await(
1950 interior_or_upvar_span,
1951 interior_extra_info,
1966 /// Unconditionally adds the diagnostic note described in
1967 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1968 #[instrument(level = "debug", skip_all)]
1969 fn note_obligation_cause_for_async_await(
1971 err: &mut Diagnostic,
1972 interior_or_upvar_span: GeneratorInteriorOrUpvar,
1973 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1975 outer_generator: Option<DefId>,
1976 trait_pred: ty::TraitPredicate<'tcx>,
1977 target_ty: Ty<'tcx>,
1978 typeck_results: Option<&ty::TypeckResults<'tcx>>,
1979 obligation: &PredicateObligation<'tcx>,
1980 next_code: Option<&ObligationCauseCode<'tcx>>,
1982 let source_map = self.tcx.sess.source_map();
1984 let (await_or_yield, an_await_or_yield) =
1985 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1986 let future_or_generator = if is_async { "future" } else { "generator" };
1988 // Special case the primary error message when send or sync is the trait that was
1990 let hir = self.tcx.hir();
1991 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
1992 self.tcx.get_diagnostic_name(trait_pred.def_id())
1994 let (trait_name, trait_verb) =
1995 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1998 err.set_primary_message(format!(
1999 "{} cannot be {} between threads safely",
2000 future_or_generator, trait_verb
2003 let original_span = err.span.primary_span().unwrap();
2004 let mut span = MultiSpan::from_span(original_span);
2006 let message = outer_generator
2007 .and_then(|generator_did| {
2008 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2009 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2010 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2012 .parent(generator_did)
2014 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2015 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2017 format!("future returned by `{}` is not {}", name, trait_name)
2019 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2020 format!("future created by async block is not {}", trait_name)
2022 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2023 format!("future created by async closure is not {}", trait_name)
2027 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2029 span.push_span_label(original_span, message);
2032 format!("is not {}", trait_name)
2034 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2037 let mut explain_yield = |interior_span: Span,
2039 scope_span: Option<Span>| {
2040 let mut span = MultiSpan::from_span(yield_span);
2041 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
2042 // #70935: If snippet contains newlines, display "the value" instead
2043 // so that we do not emit complex diagnostics.
2044 let snippet = &format!("`{}`", snippet);
2045 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
2046 // note: future is not `Send` as this value is used across an await
2047 // --> $DIR/issue-70935-complex-spans.rs:13:9
2049 // LL | baz(|| async {
2050 // | ______________-
2053 // LL | | foo(tx.clone());
2055 // | | - ^^^^^^ await occurs here, with value maybe used later
2057 // | has type `closure` which is not `Send`
2058 // note: value is later dropped here
2062 span.push_span_label(
2064 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2066 span.push_span_label(
2068 format!("has type `{}` which {}", target_ty, trait_explanation),
2070 // If available, use the scope span to annotate the drop location.
2071 let mut scope_note = None;
2072 if let Some(scope_span) = scope_span {
2073 let scope_span = source_map.end_point(scope_span);
2075 let msg = format!("{} is later dropped here", snippet);
2076 if source_map.is_multiline(yield_span.between(scope_span)) {
2077 span.push_span_label(scope_span, msg);
2079 scope_note = Some((scope_span, msg));
2085 "{} {} as this value is used across {}",
2086 future_or_generator, trait_explanation, an_await_or_yield
2089 if let Some((span, msg)) = scope_note {
2090 err.span_note(span, &msg);
2094 match interior_or_upvar_span {
2095 GeneratorInteriorOrUpvar::Interior(interior_span) => {
2096 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2097 if let Some(await_span) = from_awaited_ty {
2098 // The type causing this obligation is one being awaited at await_span.
2099 let mut span = MultiSpan::from_span(await_span);
2100 span.push_span_label(
2103 "await occurs here on type `{}`, which {}",
2104 target_ty, trait_explanation
2110 "future {not_trait} as it awaits another future which {not_trait}",
2111 not_trait = trait_explanation
2115 // Look at the last interior type to get a span for the `.await`.
2117 generator_interior_types = ?format_args!(
2118 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2121 explain_yield(interior_span, yield_span, scope_span);
2124 if let Some(expr_id) = expr {
2125 let expr = hir.expect_expr(expr_id);
2126 debug!("target_ty evaluated from {:?}", expr);
2128 let parent = hir.get_parent_node(expr_id);
2129 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2130 let parent_span = hir.span(parent);
2131 let parent_did = parent.owner.to_def_id();
2134 // fn foo(&self) -> i32 {}
2137 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2140 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2142 .expr_adjustments(expr)
2144 .any(|adj| adj.is_region_borrow())
2150 // struct Foo(*const u8);
2151 // bar(Foo(std::ptr::null())).await;
2152 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2154 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2155 let is_raw_borrow_inside_fn_like_call =
2156 match self.tcx.def_kind(parent_did) {
2157 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2160 if let Some(typeck_results) = typeck_results {
2161 if (typeck_results.is_method_call(e) && is_region_borrow)
2162 || is_raw_borrow_inside_fn_like_call
2166 "consider moving this into a `let` \
2167 binding to create a shorter lived borrow",
2175 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2176 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2177 let refers_to_non_sync = match target_ty.kind() {
2178 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2179 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2185 let (span_label, span_note) = match refers_to_non_sync {
2186 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2187 // include suggestions to make `T: Sync` so that `&T: Send`
2190 "has type `{}` which {}, because `{}` is not `Sync`",
2191 target_ty, trait_explanation, ref_ty
2194 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2199 format!("has type `{}` which {}", target_ty, trait_explanation),
2200 format!("captured value {}", trait_explanation),
2204 let mut span = MultiSpan::from_span(upvar_span);
2205 span.push_span_label(upvar_span, span_label);
2206 err.span_note(span, &span_note);
2210 // Add a note for the item obligation that remains - normally a note pointing to the
2211 // bound that introduced the obligation (e.g. `T: Send`).
2213 self.note_obligation_cause_code(
2215 &obligation.predicate,
2216 obligation.param_env,
2219 &mut Default::default(),
2223 fn note_obligation_cause_code<T>(
2225 err: &mut Diagnostic,
2227 param_env: ty::ParamEnv<'tcx>,
2228 cause_code: &ObligationCauseCode<'tcx>,
2229 obligated_types: &mut Vec<Ty<'tcx>>,
2230 seen_requirements: &mut FxHashSet<DefId>,
2236 ObligationCauseCode::ExprAssignable
2237 | ObligationCauseCode::MatchExpressionArm { .. }
2238 | ObligationCauseCode::Pattern { .. }
2239 | ObligationCauseCode::IfExpression { .. }
2240 | ObligationCauseCode::IfExpressionWithNoElse
2241 | ObligationCauseCode::MainFunctionType
2242 | ObligationCauseCode::StartFunctionType
2243 | ObligationCauseCode::IntrinsicType
2244 | ObligationCauseCode::MethodReceiver
2245 | ObligationCauseCode::ReturnNoExpression
2246 | ObligationCauseCode::UnifyReceiver(..)
2247 | ObligationCauseCode::OpaqueType
2248 | ObligationCauseCode::MiscObligation
2249 | ObligationCauseCode::WellFormed(..)
2250 | ObligationCauseCode::MatchImpl(..)
2251 | ObligationCauseCode::ReturnType
2252 | ObligationCauseCode::ReturnValue(_)
2253 | ObligationCauseCode::BlockTailExpression(_)
2254 | ObligationCauseCode::AwaitableExpr(_)
2255 | ObligationCauseCode::ForLoopIterator
2256 | ObligationCauseCode::QuestionMark
2257 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2258 | ObligationCauseCode::LetElse
2259 | ObligationCauseCode::BinOp { .. } => {}
2260 ObligationCauseCode::SliceOrArrayElem => {
2261 err.note("slice and array elements must have `Sized` type");
2263 ObligationCauseCode::TupleElem => {
2264 err.note("only the last element of a tuple may have a dynamically sized type");
2266 ObligationCauseCode::ProjectionWf(data) => {
2267 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2269 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2271 "required so that reference `{}` does not outlive its referent",
2275 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2277 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2281 ObligationCauseCode::ItemObligation(_)
2282 | ObligationCauseCode::ExprItemObligation(..) => {
2283 // We hold the `DefId` of the item introducing the obligation, but displaying it
2284 // doesn't add user usable information. It always point at an associated item.
2286 ObligationCauseCode::BindingObligation(item_def_id, span)
2287 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2288 let item_name = tcx.def_path_str(item_def_id);
2289 let mut multispan = MultiSpan::from(span);
2290 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2291 let sm = tcx.sess.source_map();
2293 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2294 (Ok(l), Ok(r)) => l.line == r.line,
2297 if !ident.span.overlaps(span) && !same_line {
2298 multispan.push_span_label(ident.span, "required by a bound in this");
2301 let descr = format!("required by a bound in `{}`", item_name);
2302 if span != DUMMY_SP {
2303 let msg = format!("required by this bound in `{}`", item_name);
2304 multispan.push_span_label(span, msg);
2305 err.span_note(multispan, &descr);
2307 err.span_note(tcx.def_span(item_def_id), &descr);
2310 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2312 "required for the cast from `{}` to the object type `{}`",
2313 self.ty_to_string(concrete_ty),
2314 self.ty_to_string(object_ty)
2317 ObligationCauseCode::Coercion { source: _, target } => {
2318 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2320 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2322 "the `Copy` trait is required because this value will be copied for each element of the array",
2327 "consider creating a new `const` item and initializing it with the result \
2328 of the function call to be used in the repeat position, like \
2329 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2333 if self.tcx.sess.is_nightly_build() && is_const_fn {
2335 "create an inline `const` block, see RFC #2920 \
2336 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2340 ObligationCauseCode::VariableType(hir_id) => {
2341 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2342 match self.tcx.hir().find(parent_node) {
2343 Some(Node::Local(hir::Local {
2344 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2347 // When encountering an assignment of an unsized trait, like
2348 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2349 // order to use have a slice instead.
2350 err.span_suggestion_verbose(
2351 span.shrink_to_lo(),
2352 "consider borrowing here",
2354 Applicability::MachineApplicable,
2356 err.note("all local variables must have a statically known size");
2358 Some(Node::Param(param)) => {
2359 err.span_suggestion_verbose(
2360 param.ty_span.shrink_to_lo(),
2361 "function arguments must have a statically known size, borrowed types \
2362 always have a known size",
2364 Applicability::MachineApplicable,
2368 err.note("all local variables must have a statically known size");
2371 if !self.tcx.features().unsized_locals {
2372 err.help("unsized locals are gated as an unstable feature");
2375 ObligationCauseCode::SizedArgumentType(sp) => {
2376 if let Some(span) = sp {
2377 err.span_suggestion_verbose(
2378 span.shrink_to_lo(),
2379 "function arguments must have a statically known size, borrowed types \
2380 always have a known size",
2382 Applicability::MachineApplicable,
2385 err.note("all function arguments must have a statically known size");
2387 if tcx.sess.opts.unstable_features.is_nightly_build()
2388 && !self.tcx.features().unsized_fn_params
2390 err.help("unsized fn params are gated as an unstable feature");
2393 ObligationCauseCode::SizedReturnType => {
2394 err.note("the return type of a function must have a statically known size");
2396 ObligationCauseCode::SizedYieldType => {
2397 err.note("the yield type of a generator must have a statically known size");
2399 ObligationCauseCode::SizedBoxType => {
2400 err.note("the type of a box expression must have a statically known size");
2402 ObligationCauseCode::AssignmentLhsSized => {
2403 err.note("the left-hand-side of an assignment must have a statically known size");
2405 ObligationCauseCode::TupleInitializerSized => {
2406 err.note("tuples must have a statically known size to be initialized");
2408 ObligationCauseCode::StructInitializerSized => {
2409 err.note("structs must have a statically known size to be initialized");
2411 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2413 AdtKind::Struct => {
2416 "the last field of a packed struct may only have a \
2417 dynamically sized type if it does not need drop to be run",
2421 "only the last field of a struct may have a dynamically sized type",
2426 err.note("no field of a union may have a dynamically sized type");
2429 err.note("no field of an enum variant may have a dynamically sized type");
2432 err.help("change the field's type to have a statically known size");
2433 err.span_suggestion(
2434 span.shrink_to_lo(),
2435 "borrowed types always have a statically known size",
2437 Applicability::MachineApplicable,
2439 err.multipart_suggestion(
2440 "the `Box` type always has a statically known size and allocates its contents \
2443 (span.shrink_to_lo(), "Box<".to_string()),
2444 (span.shrink_to_hi(), ">".to_string()),
2446 Applicability::MachineApplicable,
2449 ObligationCauseCode::ConstSized => {
2450 err.note("constant expressions must have a statically known size");
2452 ObligationCauseCode::InlineAsmSized => {
2453 err.note("all inline asm arguments must have a statically known size");
2455 ObligationCauseCode::ConstPatternStructural => {
2456 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2458 ObligationCauseCode::SharedStatic => {
2459 err.note("shared static variables must have a type that implements `Sync`");
2461 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2462 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2463 let ty = parent_trait_ref.skip_binder().self_ty();
2464 if parent_trait_ref.references_error() {
2465 // NOTE(eddyb) this was `.cancel()`, but `err`
2466 // is borrowed, so we can't fully defuse it.
2467 err.downgrade_to_delayed_bug();
2471 // If the obligation for a tuple is set directly by a Generator or Closure,
2472 // then the tuple must be the one containing capture types.
2473 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2476 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2478 let parent_trait_ref =
2479 self.resolve_vars_if_possible(data.parent_trait_pred);
2480 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2481 matches!(nested_ty.kind(), ty::Generator(..))
2482 || matches!(nested_ty.kind(), ty::Closure(..))
2488 let from_generator = tcx.lang_items().from_generator_fn().unwrap();
2490 // Don't print the tuple of capture types
2492 if !is_upvar_tys_infer_tuple {
2493 let msg = format!("required because it appears within the type `{}`", ty);
2495 ty::Adt(def, _) => {
2496 // `gen_future` is used in all async functions; it doesn't add any additional info.
2497 if self.tcx.is_diagnostic_item(sym::gen_future, def.did()) {
2500 match self.tcx.opt_item_ident(def.did()) {
2501 Some(ident) => err.span_note(ident.span, &msg),
2502 None => err.note(&msg),
2505 ty::Opaque(def_id, _) => {
2506 // Avoid printing the future from `core::future::from_generator`, it's not helpful
2507 if tcx.parent(*def_id) == from_generator {
2511 // If the previous type is `from_generator`, this is the future generated by the body of an async function.
2512 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2513 let is_future = tcx.ty_is_opaque_future(ty);
2517 "note_obligation_cause_code: check for async fn"
2520 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2521 ty::Opaque(last_def_id, _) => {
2522 tcx.parent(*last_def_id) == from_generator
2529 err.span_note(self.tcx.def_span(def_id), &msg)
2531 ty::GeneratorWitness(bound_tys) => {
2532 use std::fmt::Write;
2534 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2535 // Maybe we should just remove this note altogether?
2536 // FIXME: only print types which don't meet the trait requirement
2538 "required because it captures the following types: ".to_owned();
2539 for ty in bound_tys.skip_binder() {
2540 write!(msg, "`{}`, ", ty).unwrap();
2542 err.note(msg.trim_end_matches(", "))
2544 ty::Generator(def_id, _, _) => {
2545 let sp = self.tcx.def_span(def_id);
2547 // Special-case this to say "async block" instead of `[static generator]`.
2548 let kind = tcx.generator_kind(def_id).unwrap();
2551 &format!("required because it's used within this {}", kind),
2554 ty::Closure(def_id, _) => err.span_note(
2555 self.tcx.def_span(def_id),
2556 &format!("required because it's used within this closure"),
2558 _ => err.note(&msg),
2563 obligated_types.push(ty);
2565 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2566 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2567 // #74711: avoid a stack overflow
2568 ensure_sufficient_stack(|| {
2569 self.note_obligation_cause_code(
2579 ensure_sufficient_stack(|| {
2580 self.note_obligation_cause_code(
2584 cause_code.peel_derives(),
2591 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2592 let mut parent_trait_pred =
2593 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2594 parent_trait_pred.remap_constness_diag(param_env);
2595 let parent_def_id = parent_trait_pred.def_id();
2597 "required for `{}` to implement `{}`",
2598 parent_trait_pred.skip_binder().self_ty(),
2599 parent_trait_pred.print_modifiers_and_trait_path()
2601 let mut is_auto_trait = false;
2602 match self.tcx.hir().get_if_local(data.impl_def_id) {
2603 Some(Node::Item(hir::Item {
2604 kind: hir::ItemKind::Trait(is_auto, ..),
2608 // FIXME: we should do something else so that it works even on crate foreign
2610 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2611 err.span_note(ident.span, &msg)
2613 Some(Node::Item(hir::Item {
2614 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2617 let mut spans = Vec::with_capacity(2);
2618 if let Some(trait_ref) = of_trait {
2619 spans.push(trait_ref.path.span);
2621 spans.push(self_ty.span);
2622 err.span_note(spans, &msg)
2624 _ => err.note(&msg),
2627 let mut parent_predicate = parent_trait_pred.to_predicate(tcx);
2628 let mut data = &data.derived;
2630 seen_requirements.insert(parent_def_id);
2632 // We don't want to point at the ADT saying "required because it appears within
2633 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2634 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2637 let child_trait_ref =
2638 self.resolve_vars_if_possible(derived.parent_trait_pred);
2639 let child_def_id = child_trait_ref.def_id();
2640 if seen_requirements.insert(child_def_id) {
2644 parent_predicate = child_trait_ref.to_predicate(tcx);
2645 parent_trait_pred = child_trait_ref;
2648 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2649 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2650 let child_trait_pred =
2651 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2652 let child_def_id = child_trait_pred.def_id();
2653 if seen_requirements.insert(child_def_id) {
2657 data = &child.derived;
2658 parent_predicate = child_trait_pred.to_predicate(tcx);
2659 parent_trait_pred = child_trait_pred;
2663 "{} redundant requirement{} hidden",
2668 "required for `{}` to implement `{}`",
2669 parent_trait_pred.skip_binder().self_ty(),
2670 parent_trait_pred.print_modifiers_and_trait_path()
2673 // #74711: avoid a stack overflow
2674 ensure_sufficient_stack(|| {
2675 self.note_obligation_cause_code(
2685 ObligationCauseCode::DerivedObligation(ref data) => {
2686 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2687 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2688 // #74711: avoid a stack overflow
2689 ensure_sufficient_stack(|| {
2690 self.note_obligation_cause_code(
2700 ObligationCauseCode::FunctionArgumentObligation {
2705 let hir = self.tcx.hir();
2706 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2707 hir.find(arg_hir_id)
2709 let in_progress_typeck_results =
2710 self.in_progress_typeck_results.map(|t| t.borrow());
2711 let parent_id = hir.get_parent_item(arg_hir_id);
2712 let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
2713 Some(t) if t.hir_owner == parent_id => t,
2714 _ => self.tcx.typeck(parent_id),
2716 let ty = typeck_results.expr_ty_adjusted(expr);
2717 let span = expr.peel_blocks().span;
2718 if Some(span) != err.span.primary_span() {
2721 &if ty.references_error() {
2724 format!("this tail expression is of type `{:?}`", ty)
2729 if let Some(Node::Expr(hir::Expr {
2731 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2732 | hir::ExprKind::MethodCall(
2733 hir::PathSegment { ident: Ident { span, .. }, .. },
2737 })) = hir.find(call_hir_id)
2739 if Some(*span) != err.span.primary_span() {
2740 err.span_label(*span, "required by a bound introduced by this call");
2743 ensure_sufficient_stack(|| {
2744 self.note_obligation_cause_code(
2754 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2755 let item_name = self.tcx.item_name(trait_item_def_id);
2757 "the requirement `{}` appears on the `impl`'s {kind} `{}` but not on the \
2758 corresponding trait's {kind}",
2759 predicate, item_name,
2763 .opt_item_ident(trait_item_def_id)
2765 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2766 let mut assoc_span: MultiSpan = sp.into();
2767 assoc_span.push_span_label(
2769 format!("this trait's {kind} doesn't have the requirement `{}`", predicate),
2771 if let Some(ident) = self
2773 .opt_associated_item(trait_item_def_id)
2774 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2776 assoc_span.push_span_label(ident.span, "in this trait");
2778 err.span_note(assoc_span, &msg);
2780 ObligationCauseCode::TrivialBound => {
2781 err.help("see issue #48214");
2782 if tcx.sess.opts.unstable_features.is_nightly_build() {
2783 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2786 ObligationCauseCode::OpaqueReturnType(expr_info) => {
2787 if let Some((expr_ty, expr_span)) = expr_info {
2788 let expr_ty = self.resolve_vars_if_possible(expr_ty);
2791 format!("return type was inferred to be `{expr_ty}` here"),
2798 fn suggest_new_overflow_limit(&self, err: &mut Diagnostic) {
2799 let suggested_limit = match self.tcx.recursion_limit() {
2800 Limit(0) => Limit(2),
2804 "consider increasing the recursion limit by adding a \
2805 `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
2807 self.tcx.crate_name(LOCAL_CRATE),
2812 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2814 fn suggest_await_before_try(
2816 err: &mut Diagnostic,
2817 obligation: &PredicateObligation<'tcx>,
2818 trait_pred: ty::PolyTraitPredicate<'tcx>,
2821 let body_hir_id = obligation.cause.body_id;
2822 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2824 if let Some(body_id) =
2825 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2827 let body = self.tcx.hir().body(body_id);
2828 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2829 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2831 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2832 let impls_future = self.type_implements_trait(
2834 self.tcx.erase_late_bound_regions(self_ty),
2836 obligation.param_env,
2838 if !impls_future.must_apply_modulo_regions() {
2842 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2843 // `<T as Future>::Output`
2844 let projection_ty = trait_pred.map_bound(|trait_pred| {
2845 self.tcx.mk_projection(
2847 // Future::Output has no substs
2848 self.tcx.mk_substs_trait(trait_pred.self_ty(), &[]),
2851 let projection_ty = normalize_to(
2852 &mut SelectionContext::new(self),
2853 obligation.param_env,
2854 obligation.cause.clone(),
2860 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
2862 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2863 obligation.param_env,
2864 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
2866 debug!(try_trait_obligation = ?try_obligation);
2867 if self.predicate_may_hold(&try_obligation)
2868 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2869 && snippet.ends_with('?')
2871 err.span_suggestion_verbose(
2872 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2873 "consider `await`ing on the `Future`",
2875 Applicability::MaybeIncorrect,
2882 fn suggest_floating_point_literal(
2884 obligation: &PredicateObligation<'tcx>,
2885 err: &mut Diagnostic,
2886 trait_ref: &ty::PolyTraitRef<'tcx>,
2888 let rhs_span = match obligation.cause.code() {
2889 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
2893 trait_ref.skip_binder().self_ty().kind(),
2894 trait_ref.skip_binder().substs.type_at(1).kind(),
2896 (ty::Float(_), ty::Infer(InferTy::IntVar(_))) => {
2897 err.span_suggestion_verbose(
2898 rhs_span.shrink_to_hi(),
2899 "consider using a floating-point literal by writing it with `.0`",
2901 Applicability::MaybeIncorrect,
2910 obligation: &PredicateObligation<'tcx>,
2911 err: &mut Diagnostic,
2912 trait_pred: ty::PolyTraitPredicate<'tcx>,
2914 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
2917 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
2918 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
2922 let is_derivable_trait = match diagnostic_name {
2923 sym::Default => !adt.is_enum(),
2924 sym::PartialEq | sym::PartialOrd => {
2925 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
2926 trait_pred.skip_binder().self_ty() == rhs_ty
2928 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
2931 is_derivable_trait &&
2932 // Ensure all fields impl the trait.
2933 adt.all_fields().all(|field| {
2934 let field_ty = field.ty(self.tcx, substs);
2935 let trait_substs = match diagnostic_name {
2936 sym::PartialEq | sym::PartialOrd => {
2937 self.tcx.mk_substs_trait(field_ty, &[field_ty.into()])
2939 _ => self.tcx.mk_substs_trait(field_ty, &[]),
2941 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
2942 trait_ref: ty::TraitRef {
2943 substs: trait_substs,
2944 ..trait_pred.skip_binder().trait_ref
2948 let field_obl = Obligation::new(
2949 obligation.cause.clone(),
2950 obligation.param_env,
2951 trait_pred.to_predicate(self.tcx),
2953 self.predicate_must_hold_modulo_regions(&field_obl)
2957 err.span_suggestion_verbose(
2958 self.tcx.def_span(adt.did()).shrink_to_lo(),
2960 "consider annotating `{}` with `#[derive({})]`",
2961 trait_pred.skip_binder().self_ty(),
2964 format!("#[derive({})]\n", diagnostic_name),
2965 Applicability::MaybeIncorrect,
2970 fn suggest_dereferencing_index(
2972 obligation: &PredicateObligation<'tcx>,
2973 err: &mut Diagnostic,
2974 trait_pred: ty::PolyTraitPredicate<'tcx>,
2976 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
2977 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
2978 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
2979 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
2980 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
2982 err.span_suggestion_verbose(
2983 obligation.cause.span.shrink_to_lo(),
2984 "dereference this index",
2986 Applicability::MachineApplicable,
2992 /// Collect all the returned expressions within the input expression.
2993 /// Used to point at the return spans when we want to suggest some change to them.
2995 pub struct ReturnsVisitor<'v> {
2996 pub returns: Vec<&'v hir::Expr<'v>>,
2997 in_block_tail: bool,
3000 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3001 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3002 // Visit every expression to detect `return` paths, either through the function's tail
3003 // expression or `return` statements. We walk all nodes to find `return` statements, but
3004 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3005 // they're in the return path of the function body.
3007 hir::ExprKind::Ret(Some(ex)) => {
3008 self.returns.push(ex);
3010 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3011 self.in_block_tail = false;
3012 for stmt in block.stmts {
3013 hir::intravisit::walk_stmt(self, stmt);
3015 self.in_block_tail = true;
3016 if let Some(expr) = block.expr {
3017 self.visit_expr(expr);
3020 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3021 self.visit_expr(then);
3022 if let Some(el) = else_opt {
3023 self.visit_expr(el);
3026 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3028 self.visit_expr(arm.body);
3031 // We need to walk to find `return`s in the entire body.
3032 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3033 _ => self.returns.push(ex),
3037 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3038 assert!(!self.in_block_tail);
3039 if body.generator_kind().is_none() {
3040 if let hir::ExprKind::Block(block, None) = body.value.kind {
3041 if block.expr.is_some() {
3042 self.in_block_tail = true;
3046 hir::intravisit::walk_body(self, body);
3050 /// Collect all the awaited expressions within the input expression.
3052 struct AwaitsVisitor {
3053 awaits: Vec<hir::HirId>,
3056 impl<'v> Visitor<'v> for AwaitsVisitor {
3057 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3058 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3059 self.awaits.push(id)
3061 hir::intravisit::walk_expr(self, ex)
3065 pub trait NextTypeParamName {
3066 fn next_type_param_name(&self, name: Option<&str>) -> String;
3069 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3070 fn next_type_param_name(&self, name: Option<&str>) -> String {
3071 // This is the list of possible parameter names that we might suggest.
3072 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3073 let name = name.as_deref();
3074 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3075 let used_names = self
3077 .filter_map(|p| match p.name {
3078 hir::ParamName::Plain(ident) => Some(ident.name),
3081 .collect::<Vec<_>>();
3085 .find(|n| !used_names.contains(&Symbol::intern(n)))
3086 .unwrap_or(&"ParamName")
3091 fn suggest_trait_object_return_type_alternatives(
3092 err: &mut Diagnostic,
3095 is_object_safe: bool,
3097 err.span_suggestion(
3099 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3102 Applicability::MaybeIncorrect,
3104 err.span_suggestion(
3107 "use `impl {}` as the return type if all return paths have the same type but you \
3108 want to expose only the trait in the signature",
3111 format!("impl {}", trait_obj),
3112 Applicability::MaybeIncorrect,
3115 err.multipart_suggestion(
3117 "use a boxed trait object if all return paths implement trait `{}`",
3121 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3122 (ret_ty.shrink_to_hi(), ">".to_string()),
3124 Applicability::MaybeIncorrect,
3129 /// Collect the spans that we see the generic param `param_did`
3130 struct ReplaceImplTraitVisitor<'a> {
3131 ty_spans: &'a mut Vec<Span>,
3135 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3136 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3137 if let hir::TyKind::Path(hir::QPath::Resolved(
3139 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3142 if self.param_did == *segment_did {
3143 // `fn foo(t: impl Trait)`
3144 // ^^^^^^^^^^ get this to suggest `T` instead
3146 // There might be more than one `impl Trait`.
3147 self.ty_spans.push(t.span);
3152 hir::intravisit::walk_ty(self, t);
3156 // Replace `param` with `replace_ty`
3157 struct ReplaceImplTraitFolder<'tcx> {
3159 param: &'tcx ty::GenericParamDef,
3160 replace_ty: Ty<'tcx>,
3163 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3164 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3165 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3166 if self.param.index == *index {
3167 return self.replace_ty;
3170 t.super_fold_with(self)
3173 fn tcx(&self) -> TyCtxt<'tcx> {