1 // ignore-tidy-filelength
4 DefIdOrName, FindExprBySpan, Obligation, ObligationCause, ObligationCauseCode,
8 use crate::autoderef::Autoderef;
9 use crate::infer::InferCtxt;
10 use crate::traits::{NormalizeExt, ObligationCtxt};
13 use hir::{Expr, HirId};
14 use rustc_data_structures::fx::FxHashSet;
15 use rustc_data_structures::stack::ensure_sufficient_stack;
17 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
18 ErrorGuaranteed, MultiSpan, Style,
21 use rustc_hir::def::DefKind;
22 use rustc_hir::def_id::DefId;
23 use rustc_hir::intravisit::Visitor;
24 use rustc_hir::lang_items::LangItem;
25 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
26 use rustc_infer::infer::error_reporting::TypeErrCtxt;
27 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
28 use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime};
29 use rustc_middle::hir::map;
30 use rustc_middle::ty::error::TypeError::{self, Sorts};
31 use rustc_middle::ty::relate::TypeRelation;
32 use rustc_middle::ty::{
33 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
34 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, InternalSubsts,
35 IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder,
36 TypeSuperFoldable, TypeVisitable, TypeckResults,
38 use rustc_span::symbol::{sym, Ident, Symbol};
39 use rustc_span::{BytePos, DesugaringKind, ExpnKind, MacroKind, Span, DUMMY_SP};
40 use rustc_target::spec::abi;
43 use super::method_chain::CollectAllMismatches;
44 use super::InferCtxtPrivExt;
45 use crate::infer::InferCtxtExt as _;
46 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
47 use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
50 pub enum GeneratorInteriorOrUpvar {
51 // span of interior type
52 Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
57 // This type provides a uniform interface to retrieve data on generators, whether it originated from
58 // the local crate being compiled or from a foreign crate.
60 pub enum GeneratorData<'tcx, 'a> {
61 Local(&'a TypeckResults<'tcx>),
62 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
65 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
66 // Try to get information about variables captured by the generator that matches a type we are
67 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
69 fn try_get_upvar_span<F>(
71 infer_context: &InferCtxt<'tcx>,
74 ) -> Option<GeneratorInteriorOrUpvar>
76 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
79 GeneratorData::Local(typeck_results) => {
80 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
81 upvars.iter().find_map(|(upvar_id, upvar)| {
82 let upvar_ty = typeck_results.node_type(*upvar_id);
83 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
84 if ty_matches(ty::Binder::dummy(upvar_ty)) {
85 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
92 GeneratorData::Foreign(_) => None,
96 // Try to get the span of a type being awaited on that matches the type we are looking with the
97 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
99 fn get_from_await_ty<F>(
101 visitor: AwaitsVisitor,
106 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
109 GeneratorData::Local(typeck_results) => visitor
112 .map(|id| hir.expect_expr(id))
114 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
116 .map(|expr| expr.span),
117 GeneratorData::Foreign(generator_diagnostic_data) => visitor
120 .map(|id| hir.expect_expr(id))
122 ty_matches(ty::Binder::dummy(
123 generator_diagnostic_data
125 .get(&await_expr.hir_id.local_id)
126 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
128 .map_or_else::<Ty<'tcx>, _, _>(
130 generator_diagnostic_data
132 .get(&await_expr.hir_id.local_id)
136 "node_type: no type for node `{}`",
137 ty::tls::with(|tcx| tcx
139 .node_to_string(await_expr.hir_id))
147 .map(|expr| expr.span),
151 /// Get the type, expression, span and optional scope span of all types
152 /// that are live across the yield of this generator
153 fn get_generator_interior_types(
155 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
157 GeneratorData::Local(typeck_result) => {
158 typeck_result.generator_interior_types.as_deref()
160 GeneratorData::Foreign(generator_diagnostic_data) => {
161 generator_diagnostic_data.generator_interior_types.as_deref()
166 // Used to get the source of the data, note we don't have as much information for generators
167 // originated from foreign crates
168 fn is_foreign(&self) -> bool {
170 GeneratorData::Local(_) => false,
171 GeneratorData::Foreign(_) => true,
176 // This trait is public to expose the diagnostics methods to clippy.
177 pub trait TypeErrCtxtExt<'tcx> {
178 fn suggest_restricting_param_bound(
180 err: &mut Diagnostic,
181 trait_pred: ty::PolyTraitPredicate<'tcx>,
182 associated_item: Option<(&'static str, Ty<'tcx>)>,
186 fn suggest_dereferences(
188 obligation: &PredicateObligation<'tcx>,
189 err: &mut Diagnostic,
190 trait_pred: ty::PolyTraitPredicate<'tcx>,
193 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
197 obligation: &PredicateObligation<'tcx>,
198 err: &mut Diagnostic,
199 trait_pred: ty::PolyTraitPredicate<'tcx>,
202 fn check_for_binding_assigned_block_without_tail_expression(
204 obligation: &PredicateObligation<'tcx>,
205 err: &mut Diagnostic,
206 trait_pred: ty::PolyTraitPredicate<'tcx>,
209 fn suggest_add_clone_to_arg(
211 obligation: &PredicateObligation<'tcx>,
212 err: &mut Diagnostic,
213 trait_pred: ty::PolyTraitPredicate<'tcx>,
216 fn suggest_add_reference_to_arg(
218 obligation: &PredicateObligation<'tcx>,
219 err: &mut Diagnostic,
220 trait_pred: ty::PolyTraitPredicate<'tcx>,
221 has_custom_message: bool,
224 fn suggest_borrowing_for_object_cast(
226 err: &mut Diagnostic,
227 obligation: &PredicateObligation<'tcx>,
232 fn suggest_remove_reference(
234 obligation: &PredicateObligation<'tcx>,
235 err: &mut Diagnostic,
236 trait_pred: ty::PolyTraitPredicate<'tcx>,
239 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
241 fn suggest_change_mut(
243 obligation: &PredicateObligation<'tcx>,
244 err: &mut Diagnostic,
245 trait_pred: ty::PolyTraitPredicate<'tcx>,
248 fn suggest_semicolon_removal(
250 obligation: &PredicateObligation<'tcx>,
251 err: &mut Diagnostic,
253 trait_pred: ty::PolyTraitPredicate<'tcx>,
256 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
258 fn suggest_impl_trait(
260 err: &mut Diagnostic,
262 obligation: &PredicateObligation<'tcx>,
263 trait_pred: ty::PolyTraitPredicate<'tcx>,
266 fn point_at_returns_when_relevant(
268 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
269 obligation: &PredicateObligation<'tcx>,
272 fn report_closure_arg_mismatch(
275 found_span: Option<Span>,
276 found: ty::PolyTraitRef<'tcx>,
277 expected: ty::PolyTraitRef<'tcx>,
278 cause: &ObligationCauseCode<'tcx>,
279 found_node: Option<Node<'_>>,
280 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
282 fn note_conflicting_closure_bounds(
284 cause: &ObligationCauseCode<'tcx>,
285 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
288 fn suggest_fully_qualified_path(
290 err: &mut Diagnostic,
296 fn maybe_note_obligation_cause_for_async_await(
298 err: &mut Diagnostic,
299 obligation: &PredicateObligation<'tcx>,
302 fn note_obligation_cause_for_async_await(
304 err: &mut Diagnostic,
305 interior_or_upvar_span: GeneratorInteriorOrUpvar,
307 outer_generator: Option<DefId>,
308 trait_pred: ty::TraitPredicate<'tcx>,
310 typeck_results: Option<&ty::TypeckResults<'tcx>>,
311 obligation: &PredicateObligation<'tcx>,
312 next_code: Option<&ObligationCauseCode<'tcx>>,
315 fn note_obligation_cause_code<T>(
317 err: &mut Diagnostic,
319 param_env: ty::ParamEnv<'tcx>,
320 cause_code: &ObligationCauseCode<'tcx>,
321 obligated_types: &mut Vec<Ty<'tcx>>,
322 seen_requirements: &mut FxHashSet<DefId>,
324 T: ToPredicate<'tcx>;
326 /// Suggest to await before try: future? => future.await?
327 fn suggest_await_before_try(
329 err: &mut Diagnostic,
330 obligation: &PredicateObligation<'tcx>,
331 trait_pred: ty::PolyTraitPredicate<'tcx>,
335 fn suggest_floating_point_literal(
337 obligation: &PredicateObligation<'tcx>,
338 err: &mut Diagnostic,
339 trait_ref: &ty::PolyTraitRef<'tcx>,
344 obligation: &PredicateObligation<'tcx>,
345 err: &mut Diagnostic,
346 trait_pred: ty::PolyTraitPredicate<'tcx>,
349 fn suggest_dereferencing_index(
351 obligation: &PredicateObligation<'tcx>,
352 err: &mut Diagnostic,
353 trait_pred: ty::PolyTraitPredicate<'tcx>,
355 fn note_function_argument_obligation(
358 err: &mut Diagnostic,
359 parent_code: &ObligationCauseCode<'tcx>,
360 param_env: ty::ParamEnv<'tcx>,
361 predicate: ty::Predicate<'tcx>,
366 expr: &hir::Expr<'_>,
367 typeck_results: &TypeckResults<'tcx>,
368 type_diffs: Vec<TypeError<'tcx>>,
369 param_env: ty::ParamEnv<'tcx>,
370 err: &mut Diagnostic,
372 fn probe_assoc_types_at_expr(
374 type_diffs: &[TypeError<'tcx>],
378 param_env: ty::ParamEnv<'tcx>,
379 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>>;
382 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
384 generics.tail_span_for_predicate_suggestion(),
385 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
389 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
390 /// it can also be an `impl Trait` param that needs to be decomposed to a type
391 /// param for cleaner code.
392 fn suggest_restriction<'tcx>(
395 hir_generics: &hir::Generics<'tcx>,
397 err: &mut Diagnostic,
398 fn_sig: Option<&hir::FnSig<'_>>,
399 projection: Option<&ty::AliasTy<'_>>,
400 trait_pred: ty::PolyTraitPredicate<'tcx>,
401 // When we are dealing with a trait, `super_traits` will be `Some`:
402 // Given `trait T: A + B + C {}`
403 // - ^^^^^^^^^ GenericBounds
406 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
408 if hir_generics.where_clause_span.from_expansion()
409 || hir_generics.where_clause_span.desugaring_kind().is_some()
413 let Some(item_id) = hir_id.as_owner() else { return; };
414 let generics = tcx.generics_of(item_id);
415 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
416 if let Some((param, bound_str, fn_sig)) =
417 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
418 // Shenanigans to get the `Trait` from the `impl Trait`.
419 ty::Param(param) => {
420 let param_def = generics.type_param(param, tcx);
421 if param_def.kind.is_synthetic() {
423 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
424 return Some((param_def, bound_str, sig));
431 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
432 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
435 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
438 if !trait_pred.is_suggestable(tcx, false) {
441 // We know we have an `impl Trait` that doesn't satisfy a required projection.
443 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
444 // types. There should be at least one, but there might be *more* than one. In that
445 // case we could just ignore it and try to identify which one needs the restriction,
446 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
448 let mut ty_spans = vec![];
449 for input in fn_sig.decl.inputs {
450 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
453 // The type param `T: Trait` we will suggest to introduce.
454 let type_param = format!("{}: {}", type_param_name, bound_str);
457 if let Some(span) = hir_generics.span_for_param_suggestion() {
458 (span, format!(", {}", type_param))
460 (hir_generics.span, format!("<{}>", type_param))
462 // `fn foo(t: impl Trait)`
463 // ^ suggest `where <T as Trait>::A: Bound`
464 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
466 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
468 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
469 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
470 // `fn foo(t: impl Trait<A: Bound>)` instead.
471 err.multipart_suggestion(
472 "introduce a type parameter with a trait bound instead of using `impl Trait`",
474 Applicability::MaybeIncorrect,
477 if !trait_pred.is_suggestable(tcx, false) {
480 // Trivial case: `T` needs an extra bound: `T: Bound`.
481 let (sp, suggestion) = match (
485 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
488 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
489 (None, Some((ident, []))) => (
490 ident.span.shrink_to_hi(),
491 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
493 (_, Some((_, [.., bounds]))) => (
494 bounds.span().shrink_to_hi(),
495 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
497 (Some(_), Some((_, []))) => (
498 hir_generics.span.shrink_to_hi(),
499 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
503 err.span_suggestion_verbose(
505 &format!("consider further restricting {}", msg),
507 Applicability::MachineApplicable,
512 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
513 fn suggest_restricting_param_bound(
515 mut err: &mut Diagnostic,
516 trait_pred: ty::PolyTraitPredicate<'tcx>,
517 associated_ty: Option<(&'static str, Ty<'tcx>)>,
520 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
522 let self_ty = trait_pred.skip_binder().self_ty();
523 let (param_ty, projection) = match self_ty.kind() {
524 ty::Param(_) => (true, None),
525 ty::Alias(ty::Projection, projection) => (false, Some(projection)),
529 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
530 // don't suggest `T: Sized + ?Sized`.
531 let mut hir_id = body_id;
532 while let Some(node) = self.tcx.hir().find(hir_id) {
534 hir::Node::Item(hir::Item {
536 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
538 }) if self_ty == self.tcx.types.self_param => {
540 // Restricting `Self` for a single method.
550 Some((ident, bounds)),
555 hir::Node::TraitItem(hir::TraitItem {
557 kind: hir::TraitItemKind::Fn(..),
559 }) if self_ty == self.tcx.types.self_param => {
561 // Restricting `Self` for a single method.
563 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
569 hir::Node::TraitItem(hir::TraitItem {
571 kind: hir::TraitItemKind::Fn(fn_sig, ..),
574 | hir::Node::ImplItem(hir::ImplItem {
576 kind: hir::ImplItemKind::Fn(fn_sig, ..),
579 | hir::Node::Item(hir::Item {
580 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
581 }) if projection.is_some() => {
582 // Missing restriction on associated type of type parameter (unmet projection).
587 "the associated type",
596 hir::Node::Item(hir::Item {
598 hir::ItemKind::Trait(_, _, generics, ..)
599 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
601 }) if projection.is_some() => {
602 // Missing restriction on associated type of type parameter (unmet projection).
607 "the associated type",
617 hir::Node::Item(hir::Item {
619 hir::ItemKind::Struct(_, generics)
620 | hir::ItemKind::Enum(_, generics)
621 | hir::ItemKind::Union(_, generics)
622 | hir::ItemKind::Trait(_, _, generics, ..)
623 | hir::ItemKind::Impl(hir::Impl { generics, .. })
624 | hir::ItemKind::Fn(_, generics, _)
625 | hir::ItemKind::TyAlias(_, generics)
626 | hir::ItemKind::TraitAlias(generics, _)
627 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
630 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
631 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
634 // We skip the 0'th subst (self) because we do not want
635 // to consider the predicate as not suggestible if the
636 // self type is an arg position `impl Trait` -- instead,
637 // we handle that by adding ` + Bound` below.
638 // FIXME(compiler-errors): It would be nice to do the same
639 // this that we do in `suggest_restriction` and pull the
640 // `impl Trait` into a new generic if it shows up somewhere
641 // else in the predicate.
642 if !trait_pred.skip_binder().trait_ref.substs[1..]
644 .all(|g| g.is_suggestable(self.tcx, false))
648 // Missing generic type parameter bound.
649 let param_name = self_ty.to_string();
650 let mut constraint = with_no_trimmed_paths!(
651 trait_pred.print_modifiers_and_trait_path().to_string()
654 if let Some((name, term)) = associated_ty {
655 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
656 // That should be extracted into a helper function.
657 if constraint.ends_with('>') {
658 constraint = format!(
660 &constraint[..constraint.len() - 1],
665 constraint.push_str(&format!("<{} = {}>", name, term));
669 if suggest_constraining_type_param(
675 Some(trait_pred.def_id()),
681 hir::Node::Item(hir::Item {
683 hir::ItemKind::Struct(_, generics)
684 | hir::ItemKind::Enum(_, generics)
685 | hir::ItemKind::Union(_, generics)
686 | hir::ItemKind::Trait(_, _, generics, ..)
687 | hir::ItemKind::Impl(hir::Impl { generics, .. })
688 | hir::ItemKind::Fn(_, generics, _)
689 | hir::ItemKind::TyAlias(_, generics)
690 | hir::ItemKind::TraitAlias(generics, _)
691 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
694 // Missing generic type parameter bound.
695 if suggest_arbitrary_trait_bound(
705 hir::Node::Crate(..) => return,
710 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
714 /// When after several dereferencing, the reference satisfies the trait
715 /// binding. This function provides dereference suggestion for this
716 /// specific situation.
717 fn suggest_dereferences(
719 obligation: &PredicateObligation<'tcx>,
720 err: &mut Diagnostic,
721 trait_pred: ty::PolyTraitPredicate<'tcx>,
723 // It only make sense when suggesting dereferences for arguments
724 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = obligation.cause.code()
725 else { return false; };
726 let Some(typeck_results) = &self.typeck_results
727 else { return false; };
728 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
729 else { return false; };
730 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
731 else { return false; };
733 let span = obligation.cause.span;
734 let mut real_trait_pred = trait_pred;
735 let mut code = obligation.cause.code();
736 while let Some((parent_code, parent_trait_pred)) = code.parent() {
738 if let Some(parent_trait_pred) = parent_trait_pred {
739 real_trait_pred = parent_trait_pred;
742 let real_ty = real_trait_pred.self_ty();
743 // We `erase_late_bound_regions` here because `make_subregion` does not handle
744 // `ReLateBound`, and we don't particularly care about the regions.
746 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
752 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
753 let mut autoderef = Autoderef::new(
755 obligation.param_env,
756 obligation.cause.body_id,
760 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
762 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
764 // Remapping bound vars here
765 let real_trait_pred_and_ty =
766 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
767 let obligation = self.mk_trait_obligation_with_new_self_ty(
768 obligation.param_env,
769 real_trait_pred_and_ty,
771 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
774 // Don't care about `&mut` because `DerefMut` is used less
775 // often and user will not expect autoderef happens.
776 if let Some(hir::Node::Expr(hir::Expr {
778 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
780 })) = self.tcx.hir().find(*arg_hir_id)
782 let derefs = "*".repeat(steps);
783 err.span_suggestion_verbose(
784 expr.span.shrink_to_lo(),
785 "consider dereferencing here",
787 Applicability::MachineApplicable,
792 } else if real_trait_pred != trait_pred {
793 // This branch addresses #87437.
795 // Remapping bound vars here
796 let real_trait_pred_and_base_ty =
797 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
798 let obligation = self.mk_trait_obligation_with_new_self_ty(
799 obligation.param_env,
800 real_trait_pred_and_base_ty,
802 if self.predicate_may_hold(&obligation) {
803 let call_node = self.tcx.hir().get(*call_hir_id);
804 let msg = "consider dereferencing here";
805 let is_receiver = matches!(
807 Node::Expr(hir::Expr {
808 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
811 if receiver_expr.hir_id == *arg_hir_id
814 err.multipart_suggestion_verbose(
817 (span.shrink_to_lo(), "(*".to_string()),
818 (span.shrink_to_hi(), ")".to_string()),
820 Applicability::MachineApplicable,
823 err.span_suggestion_verbose(
827 Applicability::MachineApplicable,
838 /// Given a closure's `DefId`, return the given name of the closure.
840 /// This doesn't account for reassignments, but it's only used for suggestions.
841 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
842 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
843 // Get the local name of this closure. This can be inaccurate because
844 // of the possibility of reassignment, but this should be good enough.
846 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
856 let hir = self.tcx.hir();
857 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
858 match hir.find_parent(hir_id) {
859 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
860 get_name(err, &local.pat.kind)
862 // Different to previous arm because one is `&hir::Local` and the other
863 // is `P<hir::Local>`.
864 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
869 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
870 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
871 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
874 obligation: &PredicateObligation<'tcx>,
875 err: &mut Diagnostic,
876 trait_pred: ty::PolyTraitPredicate<'tcx>,
878 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
879 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
881 // Don't suggest calling to turn an unsized type into a sized type
885 // This is duplicated from `extract_callable_info` in typeck, which
886 // relies on autoderef, so we can't use it here.
887 let found = trait_pred.self_ty().skip_binder().peel_refs();
888 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
890 ty::FnPtr(fn_sig) => {
891 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
893 ty::FnDef(def_id, _) => {
894 let fn_sig = found.fn_sig(self.tcx);
895 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
897 ty::Closure(def_id, substs) => {
898 let fn_sig = substs.as_closure().sig();
900 DefIdOrName::DefId(def_id),
902 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
905 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
906 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
907 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
908 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
909 // args tuple will always be substs[1]
910 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
913 DefIdOrName::DefId(def_id),
914 pred.kind().rebind(proj.term.ty().unwrap()),
915 pred.kind().rebind(args.as_slice()),
922 ty::Dynamic(data, _, ty::Dyn) => {
923 data.iter().find_map(|pred| {
924 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
925 && Some(proj.def_id) == self.tcx.lang_items().fn_once_output()
926 // for existential projection, substs are shifted over by 1
927 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
930 DefIdOrName::Name("trait object"),
931 pred.rebind(proj.term.ty().unwrap()),
932 pred.rebind(args.as_slice()),
940 obligation.param_env.caller_bounds().iter().find_map(|pred| {
941 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
942 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
943 && proj.projection_ty.self_ty() == found
944 // args tuple will always be substs[1]
945 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
948 DefIdOrName::Name("type parameter"),
949 pred.kind().rebind(proj.term.ty().unwrap()),
950 pred.kind().rebind(args.as_slice()),
958 }) else { return false; };
959 let output = self.replace_bound_vars_with_fresh_vars(
960 obligation.cause.span,
961 LateBoundRegionConversionTime::FnCall,
964 let inputs = inputs.skip_binder().iter().map(|ty| {
965 self.replace_bound_vars_with_fresh_vars(
966 obligation.cause.span,
967 LateBoundRegionConversionTime::FnCall,
972 // Remapping bound vars here
973 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
976 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
977 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
981 // Get the name of the callable and the arguments to be used in the suggestion.
982 let hir = self.tcx.hir();
984 let msg = match def_id_or_name {
985 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
986 DefKind::Ctor(CtorOf::Struct, _) => {
987 "use parentheses to construct this tuple struct".to_string()
989 DefKind::Ctor(CtorOf::Variant, _) => {
990 "use parentheses to construct this tuple variant".to_string()
992 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
994 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
999 if ty.is_suggestable(self.tcx, false) {
1000 format!("/* {ty} */")
1002 "/* value */".to_string()
1005 .collect::<Vec<_>>()
1008 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
1009 && obligation.cause.span.can_be_used_for_suggestions()
1011 // When the obligation error has been ensured to have been caused by
1012 // an argument, the `obligation.cause.span` points at the expression
1013 // of the argument, so we can provide a suggestion. Otherwise, we give
1014 // a more general note.
1015 err.span_suggestion_verbose(
1016 obligation.cause.span.shrink_to_hi(),
1018 format!("({args})"),
1019 Applicability::HasPlaceholders,
1021 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
1022 let name = match hir.get_if_local(def_id) {
1023 Some(hir::Node::Expr(hir::Expr {
1024 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
1027 err.span_label(*fn_decl_span, "consider calling this closure");
1028 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
1033 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
1034 err.span_label(ident.span, "consider calling this function");
1037 Some(hir::Node::Ctor(..)) => {
1038 let name = self.tcx.def_path_str(def_id);
1040 self.tcx.def_span(def_id),
1041 format!("consider calling the constructor for `{}`", name),
1047 err.help(&format!("{msg}: `{name}({args})`"));
1052 fn check_for_binding_assigned_block_without_tail_expression(
1054 obligation: &PredicateObligation<'tcx>,
1055 err: &mut Diagnostic,
1056 trait_pred: ty::PolyTraitPredicate<'tcx>,
1058 let mut span = obligation.cause.span;
1059 while span.from_expansion() {
1060 // Remove all the desugaring and macro contexts.
1063 let mut expr_finder = FindExprBySpan::new(span);
1064 let Some(hir::Node::Expr(body)) = self.tcx.hir().find(obligation.cause.body_id) else { return; };
1065 expr_finder.visit_expr(&body);
1066 let Some(expr) = expr_finder.result else { return; };
1067 let Some(typeck) = &self.typeck_results else { return; };
1068 let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { return; };
1072 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; };
1073 let hir::def::Res::Local(hir_id) = path.res else { return; };
1074 let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else {
1077 let Some(hir::Node::Local(hir::Local {
1081 })) = self.tcx.hir().find_parent(pat.hir_id) else { return; };
1082 let hir::ExprKind::Block(block, None) = init.kind else { return; };
1083 if block.expr.is_some() {
1086 let [.., stmt] = block.stmts else {
1087 err.span_label(block.span, "this empty block is missing a tail expression");
1090 let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; };
1091 let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1092 err.span_label(block.span, "this block is missing a tail expression");
1095 let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
1096 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1098 let new_obligation =
1099 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1100 if self.predicate_must_hold_modulo_regions(&new_obligation) {
1101 err.span_suggestion_short(
1102 stmt.span.with_lo(tail_expr.span.hi()),
1103 "remove this semicolon",
1105 Applicability::MachineApplicable,
1108 err.span_label(block.span, "this block is missing a tail expression");
1112 fn suggest_add_clone_to_arg(
1114 obligation: &PredicateObligation<'tcx>,
1115 err: &mut Diagnostic,
1116 trait_pred: ty::PolyTraitPredicate<'tcx>,
1118 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
1119 let ty = self.tcx.erase_late_bound_regions(self_ty);
1120 let owner = self.tcx.hir().get_parent_item(obligation.cause.body_id);
1121 let Some(generics) = self.tcx.hir().get_generics(owner.def_id) else { return false };
1122 let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
1123 let ty::Param(param) = inner_ty.kind() else { return false };
1124 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() else { return false };
1125 let arg_node = self.tcx.hir().get(*arg_hir_id);
1126 let Node::Expr(Expr { kind: hir::ExprKind::Path(_), ..}) = arg_node else { return false };
1128 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None);
1129 let has_clone = |ty| {
1130 self.type_implements_trait(clone_trait, [ty], obligation.param_env)
1131 .must_apply_modulo_regions()
1134 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1135 obligation.param_env,
1136 trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1139 if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1140 if !has_clone(param.to_ty(self.tcx)) {
1141 suggest_constraining_type_param(
1145 param.name.as_str(),
1150 err.span_suggestion_verbose(
1151 obligation.cause.span.shrink_to_hi(),
1152 "consider using clone here",
1153 ".clone()".to_string(),
1154 Applicability::MaybeIncorrect,
1161 fn suggest_add_reference_to_arg(
1163 obligation: &PredicateObligation<'tcx>,
1164 err: &mut Diagnostic,
1165 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1166 has_custom_message: bool,
1168 let span = obligation.cause.span;
1170 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
1171 obligation.cause.code()
1174 } else if let ObligationCauseCode::ItemObligation(_)
1175 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1177 obligation.cause.code()
1178 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1179 span.ctxt().outer_expn_data().kind
1181 obligation.cause.code()
1186 // List of traits for which it would be nonsensical to suggest borrowing.
1187 // For instance, immutable references are always Copy, so suggesting to
1188 // borrow would always succeed, but it's probably not what the user wanted.
1189 let mut never_suggest_borrow: Vec<_> =
1190 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1192 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1195 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1196 never_suggest_borrow.push(def_id);
1199 let param_env = obligation.param_env;
1201 // Try to apply the original trait binding obligation by borrowing.
1202 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1203 blacklist: &[DefId]|
1205 if blacklist.contains(&old_pred.def_id()) {
1208 // We map bounds to `&T` and `&mut T`
1209 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1212 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1215 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1218 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1222 let mk_result = |trait_pred_and_new_ty| {
1224 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1225 self.predicate_must_hold_modulo_regions(&obligation)
1227 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1228 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1230 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1231 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1232 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1235 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1236 mutability.is_mut(),
1242 if imm_ref_self_ty_satisfies_pred
1243 || mut_ref_self_ty_satisfies_pred
1244 || ref_inner_ty_satisfies_pred
1246 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1247 // We don't want a borrowing suggestion on the fields in structs,
1250 // the_foos: Vec<Foo>
1254 span.ctxt().outer_expn_data().kind,
1255 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1259 if snippet.starts_with('&') {
1260 // This is already a literal borrow and the obligation is failing
1261 // somewhere else in the obligation chain. Do not suggest non-sense.
1264 // We have a very specific type of error, where just borrowing this argument
1265 // might solve the problem. In cases like this, the important part is the
1266 // original type obligation, not the last one that failed, which is arbitrary.
1267 // Because of this, we modify the error to refer to the original obligation and
1268 // return early in the caller.
1270 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1271 if has_custom_message {
1275 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1280 "the trait `{}` is not implemented for `{}`",
1281 old_pred.print_modifiers_and_trait_path(),
1282 old_pred.self_ty().skip_binder(),
1286 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1287 err.span_suggestions(
1288 span.shrink_to_lo(),
1289 "consider borrowing here",
1290 ["&".to_string(), "&mut ".to_string()],
1291 Applicability::MaybeIncorrect,
1294 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1295 err.span_suggestion_verbose(
1296 span.shrink_to_lo(),
1298 "consider{} borrowing here",
1299 if is_mut { " mutably" } else { "" }
1301 format!("&{}", if is_mut { "mut " } else { "" }),
1302 Applicability::MaybeIncorrect,
1311 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1312 try_borrowing(cause.derived.parent_trait_pred, &[])
1313 } else if let ObligationCauseCode::BindingObligation(_, _)
1314 | ObligationCauseCode::ItemObligation(_)
1315 | ObligationCauseCode::ExprItemObligation(..)
1316 | ObligationCauseCode::ExprBindingObligation(..) = code
1318 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1324 // Suggest borrowing the type
1325 fn suggest_borrowing_for_object_cast(
1327 err: &mut Diagnostic,
1328 obligation: &PredicateObligation<'tcx>,
1330 object_ty: Ty<'tcx>,
1332 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1333 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1335 for predicate in predicates.iter() {
1336 if !self.predicate_must_hold_modulo_regions(
1337 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1343 err.span_suggestion(
1344 obligation.cause.span.shrink_to_lo(),
1346 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1349 Applicability::MaybeIncorrect,
1353 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1354 /// suggest removing these references until we reach a type that implements the trait.
1355 fn suggest_remove_reference(
1357 obligation: &PredicateObligation<'tcx>,
1358 err: &mut Diagnostic,
1359 trait_pred: ty::PolyTraitPredicate<'tcx>,
1361 let span = obligation.cause.span;
1363 let mut suggested = false;
1364 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1366 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1367 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1368 // Do not suggest removal of borrow from type arguments.
1372 // Skipping binder here, remapping below
1373 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1375 for refs_remaining in 0..refs_number {
1376 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1379 suggested_ty = *inner_ty;
1381 // Remapping bound vars here
1382 let trait_pred_and_suggested_ty =
1383 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1385 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1386 obligation.param_env,
1387 trait_pred_and_suggested_ty,
1390 if self.predicate_may_hold(&new_obligation) {
1395 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1397 let remove_refs = refs_remaining + 1;
1399 let msg = if remove_refs == 1 {
1400 "consider removing the leading `&`-reference".to_string()
1402 format!("consider removing {} leading `&`-references", remove_refs)
1405 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1414 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1415 let span = obligation.cause.span;
1417 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1418 let hir = self.tcx.hir();
1419 if let Some(hir::Node::Expr(expr)) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1420 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1421 // and if not maybe suggest doing something else? If we kept the expression around we
1422 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1423 // it is from the local crate.
1424 err.span_suggestion(
1426 "remove the `.await`",
1428 Applicability::MachineApplicable,
1430 // FIXME: account for associated `async fn`s.
1431 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1432 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1433 obligation.predicate.kind().skip_binder()
1435 err.span_label(*span, &format!("this call returns `{}`", pred.self_ty()));
1437 if let Some(typeck_results) = &self.typeck_results
1438 && let ty = typeck_results.expr_ty_adjusted(base)
1439 && let ty::FnDef(def_id, _substs) = ty.kind()
1440 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1441 hir.get_if_local(*def_id)
1444 "alternatively, consider making `fn {}` asynchronous",
1447 if vis_span.is_empty() {
1448 err.span_suggestion_verbose(
1449 span.shrink_to_lo(),
1452 Applicability::MaybeIncorrect,
1455 err.span_suggestion_verbose(
1456 vis_span.shrink_to_hi(),
1459 Applicability::MaybeIncorrect,
1468 /// Check if the trait bound is implemented for a different mutability and note it in the
1470 fn suggest_change_mut(
1472 obligation: &PredicateObligation<'tcx>,
1473 err: &mut Diagnostic,
1474 trait_pred: ty::PolyTraitPredicate<'tcx>,
1476 let points_at_arg = matches!(
1477 obligation.cause.code(),
1478 ObligationCauseCode::FunctionArgumentObligation { .. },
1481 let span = obligation.cause.span;
1482 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1484 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1485 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1486 // Do not suggest removal of borrow from type arguments.
1489 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1490 if trait_pred.has_non_region_infer() {
1491 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1492 // unresolved bindings.
1496 // Skipping binder here, remapping below
1497 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1499 let suggested_ty = match mutability {
1500 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1501 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1504 // Remapping bound vars here
1505 let trait_pred_and_suggested_ty =
1506 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1508 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1509 obligation.param_env,
1510 trait_pred_and_suggested_ty,
1512 let suggested_ty_would_satisfy_obligation = self
1513 .evaluate_obligation_no_overflow(&new_obligation)
1514 .must_apply_modulo_regions();
1515 if suggested_ty_would_satisfy_obligation {
1520 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1521 if points_at_arg && mutability.is_not() && refs_number > 0 {
1522 // If we have a call like foo(&mut buf), then don't suggest foo(&mut mut buf)
1524 .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
1529 err.span_suggestion_verbose(
1531 "consider changing this borrow's mutability",
1533 Applicability::MachineApplicable,
1537 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1538 trait_pred.print_modifiers_and_trait_path(),
1540 trait_pred.skip_binder().self_ty(),
1548 fn suggest_semicolon_removal(
1550 obligation: &PredicateObligation<'tcx>,
1551 err: &mut Diagnostic,
1553 trait_pred: ty::PolyTraitPredicate<'tcx>,
1555 let hir = self.tcx.hir();
1556 let parent_node = hir.parent_id(obligation.cause.body_id);
1557 let node = hir.find(parent_node);
1558 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1559 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1560 && sig.decl.output.span().overlaps(span)
1561 && blk.expr.is_none()
1562 && trait_pred.self_ty().skip_binder().is_unit()
1563 && let Some(stmt) = blk.stmts.last()
1564 && let hir::StmtKind::Semi(expr) = stmt.kind
1565 // Only suggest this if the expression behind the semicolon implements the predicate
1566 && let Some(typeck_results) = &self.typeck_results
1567 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1568 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1569 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1575 "this expression has type `{}`, which implements `{}`",
1577 trait_pred.print_modifiers_and_trait_path()
1580 err.span_suggestion(
1581 self.tcx.sess.source_map().end_point(stmt.span),
1582 "remove this semicolon",
1584 Applicability::MachineApplicable
1591 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1592 let hir = self.tcx.hir();
1593 let parent_node = hir.parent_id(obligation.cause.body_id);
1594 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1598 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1601 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1602 /// applicable and signal that the error has been expanded appropriately and needs to be
1604 fn suggest_impl_trait(
1606 err: &mut Diagnostic,
1608 obligation: &PredicateObligation<'tcx>,
1609 trait_pred: ty::PolyTraitPredicate<'tcx>,
1611 match obligation.cause.code().peel_derives() {
1612 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1613 ObligationCauseCode::SizedReturnType => {}
1617 let hir = self.tcx.hir();
1618 let fn_hir_id = hir.parent_id(obligation.cause.body_id);
1619 let node = hir.find(fn_hir_id);
1620 let Some(hir::Node::Item(hir::Item {
1621 kind: hir::ItemKind::Fn(sig, _, body_id),
1627 let body = hir.body(*body_id);
1628 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1629 let ty = trait_pred.skip_binder().self_ty();
1630 let is_object_safe = match ty.kind() {
1631 ty::Dynamic(predicates, _, ty::Dyn) => {
1632 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1635 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1637 // We only want to suggest `impl Trait` to `dyn Trait`s.
1638 // For example, `fn foo() -> str` needs to be filtered out.
1642 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1646 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1647 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1648 // Recursively look for `TraitObject` types and if there's only one, use that span to
1649 // suggest `impl Trait`.
1651 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1652 // otherwise suggest using `Box<dyn Trait>` or an enum.
1653 let mut visitor = ReturnsVisitor::default();
1654 visitor.visit_body(&body);
1656 let typeck_results = self.typeck_results.as_ref().unwrap();
1657 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1659 let ret_types = visitor
1662 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1663 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1664 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1666 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1668 let ty = self.resolve_vars_if_possible(ty);
1670 !matches!(ty.kind(), ty::Error(_))
1671 && last_ty.map_or(true, |last_ty| {
1672 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1673 // *after* in the dependency graph.
1674 match (ty.kind(), last_ty.kind()) {
1675 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1676 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1677 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1679 Infer(InferTy::FreshFloatTy(_)),
1680 Infer(InferTy::FreshFloatTy(_)),
1685 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1688 let mut spans_and_needs_box = vec![];
1690 match liberated_sig.output().kind() {
1691 ty::Dynamic(predicates, _, ty::Dyn) => {
1692 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1693 let param_env = ty::ParamEnv::empty();
1695 if !only_never_return {
1696 for (expr_span, return_ty) in ret_types {
1697 let self_ty_satisfies_dyn_predicates = |self_ty| {
1698 predicates.iter().all(|predicate| {
1699 let pred = predicate.with_self_ty(self.tcx, self_ty);
1700 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1701 self.predicate_may_hold(&obl)
1705 if let ty::Adt(def, substs) = return_ty.kind()
1707 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1709 spans_and_needs_box.push((expr_span, false));
1710 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1711 spans_and_needs_box.push((expr_span, true));
1721 let sm = self.tcx.sess.source_map();
1722 if !ret_ty.span.overlaps(span) {
1725 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1726 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1732 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1733 let name = liberated_sig.output().to_string();
1735 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1736 if !name.starts_with("dyn ") {
1742 err.code(error_code!(E0746));
1743 err.set_primary_message("return type cannot have an unboxed trait object");
1744 err.children.clear();
1745 let impl_trait_msg = "for information on `impl Trait`, see \
1746 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1747 #returning-types-that-implement-traits>";
1748 let trait_obj_msg = "for information on trait objects, see \
1749 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1750 #using-trait-objects-that-allow-for-values-of-different-types>";
1752 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1753 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1754 if only_never_return {
1755 // No return paths, probably using `panic!()` or similar.
1756 // Suggest `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1757 suggest_trait_object_return_type_alternatives(
1763 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1764 // Suggest `-> impl Trait`.
1765 err.span_suggestion(
1768 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1769 which implements `{1}`",
1772 format!("impl {}", trait_obj),
1773 Applicability::MachineApplicable,
1775 err.note(impl_trait_msg);
1778 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1779 err.multipart_suggestion(
1780 "return a boxed trait object instead",
1782 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1783 (span.shrink_to_hi(), ">".to_string()),
1785 Applicability::MaybeIncorrect,
1787 for (span, needs_box) in spans_and_needs_box {
1789 err.multipart_suggestion(
1790 "... and box this value",
1792 (span.shrink_to_lo(), "Box::new(".to_string()),
1793 (span.shrink_to_hi(), ")".to_string()),
1795 Applicability::MaybeIncorrect,
1800 // This is currently not possible to trigger because E0038 takes precedence, but
1801 // leave it in for completeness in case anything changes in an earlier stage.
1803 "if trait `{}` were object-safe, you could return a trait object",
1807 err.note(trait_obj_msg);
1809 "if all the returned values were of the same type you could use `impl {}` as the \
1813 err.note(impl_trait_msg);
1814 err.note("you can create a new `enum` with a variant for each returned type");
1819 fn point_at_returns_when_relevant(
1821 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1822 obligation: &PredicateObligation<'tcx>,
1824 match obligation.cause.code().peel_derives() {
1825 ObligationCauseCode::SizedReturnType => {}
1829 let hir = self.tcx.hir();
1830 let parent_node = hir.parent_id(obligation.cause.body_id);
1831 let node = hir.find(parent_node);
1832 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1835 let body = hir.body(*body_id);
1836 // Point at all the `return`s in the function as they have failed trait bounds.
1837 let mut visitor = ReturnsVisitor::default();
1838 visitor.visit_body(&body);
1839 let typeck_results = self.typeck_results.as_ref().unwrap();
1840 for expr in &visitor.returns {
1841 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1842 let ty = self.resolve_vars_if_possible(returned_ty);
1843 if ty.references_error() {
1844 // don't print out the [type error] here
1849 &format!("this returned value is of type `{}`", ty),
1857 fn report_closure_arg_mismatch(
1860 found_span: Option<Span>,
1861 found: ty::PolyTraitRef<'tcx>,
1862 expected: ty::PolyTraitRef<'tcx>,
1863 cause: &ObligationCauseCode<'tcx>,
1864 found_node: Option<Node<'_>>,
1865 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1866 pub(crate) fn build_fn_sig_ty<'tcx>(
1867 infcx: &InferCtxt<'tcx>,
1868 trait_ref: ty::PolyTraitRef<'tcx>,
1870 let inputs = trait_ref.skip_binder().substs.type_at(1);
1871 let sig = match inputs.kind() {
1872 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1873 infcx.tcx.mk_fn_sig(
1875 infcx.next_ty_var(TypeVariableOrigin {
1877 kind: TypeVariableOriginKind::MiscVariable,
1880 hir::Unsafety::Normal,
1884 _ => infcx.tcx.mk_fn_sig(
1885 std::iter::once(inputs),
1886 infcx.next_ty_var(TypeVariableOrigin {
1888 kind: TypeVariableOriginKind::MiscVariable,
1891 hir::Unsafety::Normal,
1896 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1899 let argument_kind = match expected.skip_binder().self_ty().kind() {
1900 ty::Closure(..) => "closure",
1901 ty::Generator(..) => "generator",
1904 let mut err = struct_span_err!(
1908 "type mismatch in {argument_kind} arguments",
1911 err.span_label(span, "expected due to this");
1913 let found_span = found_span.unwrap_or(span);
1914 err.span_label(found_span, "found signature defined here");
1916 let expected = build_fn_sig_ty(self, expected);
1917 let found = build_fn_sig_ty(self, found);
1919 let (expected_str, found_str) = self.cmp(expected, found);
1921 let signature_kind = format!("{argument_kind} signature");
1922 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1924 self.note_conflicting_closure_bounds(cause, &mut err);
1926 if let Some(found_node) = found_node {
1927 hint_missing_borrow(span, found, expected, found_node, &mut err);
1933 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1934 // requirements, which will always cause a closure to have a type error.
1935 fn note_conflicting_closure_bounds(
1937 cause: &ObligationCauseCode<'tcx>,
1938 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1940 // First, look for an `ExprBindingObligation`, which means we can get
1941 // the unsubstituted predicate list of the called function. And check
1942 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1943 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1944 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1945 && let Some(pred) = predicates.predicates.get(*idx)
1946 && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
1947 && self.tcx.is_fn_trait(trait_pred.def_id())
1950 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
1951 let expected_substs = self
1953 .anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.substs));
1955 // Find another predicate whose self-type is equal to the expected self type,
1956 // but whose substs don't match.
1957 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1959 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1960 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
1961 if self.tcx.is_fn_trait(trait_pred.def_id())
1963 // Make sure that the self type matches
1964 // (i.e. constraining this closure)
1966 == self.tcx.anonymize_bound_vars(
1967 pred.kind().rebind(trait_pred.self_ty()),
1969 // But the substs don't match (i.e. incompatible args)
1971 != self.tcx.anonymize_bound_vars(
1972 pred.kind().rebind(trait_pred.trait_ref.substs),
1979 // If we found one, then it's very likely the cause of the error.
1980 if let Some((_, (_, other_pred_span))) = other_pred {
1983 "closure inferred to have a different signature due to this bound",
1989 fn suggest_fully_qualified_path(
1991 err: &mut Diagnostic,
1996 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1997 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1999 "{}s cannot be accessed directly on a `trait`, they can only be \
2000 accessed through a specific `impl`",
2001 assoc_item.kind.as_def_kind().descr(item_def_id)
2003 err.span_suggestion(
2005 "use the fully qualified path to an implementation",
2006 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
2007 Applicability::HasPlaceholders,
2013 /// Adds an async-await specific note to the diagnostic when the future does not implement
2014 /// an auto trait because of a captured type.
2017 /// note: future does not implement `Qux` as this value is used across an await
2018 /// --> $DIR/issue-64130-3-other.rs:17:5
2020 /// LL | let x = Foo;
2021 /// | - has type `Foo`
2022 /// LL | baz().await;
2023 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2025 /// | - `x` is later dropped here
2028 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2029 /// is "replaced" with a different message and a more specific error.
2032 /// error: future cannot be sent between threads safely
2033 /// --> $DIR/issue-64130-2-send.rs:21:5
2035 /// LL | fn is_send<T: Send>(t: T) { }
2036 /// | ---- required by this bound in `is_send`
2038 /// LL | is_send(bar());
2039 /// | ^^^^^^^ future returned by `bar` is not send
2041 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2042 /// implemented for `Foo`
2043 /// note: future is not send as this value is used across an await
2044 /// --> $DIR/issue-64130-2-send.rs:15:5
2046 /// LL | let x = Foo;
2047 /// | - has type `Foo`
2048 /// LL | baz().await;
2049 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2051 /// | - `x` is later dropped here
2054 /// Returns `true` if an async-await specific note was added to the diagnostic.
2055 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
2056 fn maybe_note_obligation_cause_for_async_await(
2058 err: &mut Diagnostic,
2059 obligation: &PredicateObligation<'tcx>,
2061 let hir = self.tcx.hir();
2063 // Attempt to detect an async-await error by looking at the obligation causes, looking
2064 // for a generator to be present.
2066 // When a future does not implement a trait because of a captured type in one of the
2067 // generators somewhere in the call stack, then the result is a chain of obligations.
2069 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
2070 // future is passed as an argument to a function C which requires a `Send` type, then the
2071 // chain looks something like this:
2073 // - `BuiltinDerivedObligation` with a generator witness (B)
2074 // - `BuiltinDerivedObligation` with a generator (B)
2075 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2076 // - `BuiltinDerivedObligation` with a generator witness (A)
2077 // - `BuiltinDerivedObligation` with a generator (A)
2078 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2079 // - `BindingObligation` with `impl_send (Send requirement)
2081 // The first obligation in the chain is the most useful and has the generator that captured
2082 // the type. The last generator (`outer_generator` below) has information about where the
2083 // bound was introduced. At least one generator should be present for this diagnostic to be
2085 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
2086 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
2089 let mut generator = None;
2090 let mut outer_generator = None;
2091 let mut next_code = Some(obligation.cause.code());
2093 let mut seen_upvar_tys_infer_tuple = false;
2095 while let Some(code) = next_code {
2098 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
2099 next_code = Some(parent_code);
2101 ObligationCauseCode::ImplDerivedObligation(cause) => {
2102 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
2104 parent_trait_ref = ?cause.derived.parent_trait_pred,
2105 self_ty.kind = ?ty.kind(),
2110 ty::Generator(did, ..) => {
2111 generator = generator.or(Some(did));
2112 outer_generator = Some(did);
2114 ty::GeneratorWitness(..) => {}
2115 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2116 // By introducing a tuple of upvar types into the chain of obligations
2117 // of a generator, the first non-generator item is now the tuple itself,
2118 // we shall ignore this.
2120 seen_upvar_tys_infer_tuple = true;
2122 _ if generator.is_none() => {
2123 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
2124 target_ty = Some(ty);
2129 next_code = Some(&cause.derived.parent_code);
2131 ObligationCauseCode::DerivedObligation(derived_obligation)
2132 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
2133 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
2135 parent_trait_ref = ?derived_obligation.parent_trait_pred,
2136 self_ty.kind = ?ty.kind(),
2140 ty::Generator(did, ..) => {
2141 generator = generator.or(Some(did));
2142 outer_generator = Some(did);
2144 ty::GeneratorWitness(..) => {}
2145 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2146 // By introducing a tuple of upvar types into the chain of obligations
2147 // of a generator, the first non-generator item is now the tuple itself,
2148 // we shall ignore this.
2150 seen_upvar_tys_infer_tuple = true;
2152 _ if generator.is_none() => {
2153 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2154 target_ty = Some(ty);
2159 next_code = Some(&derived_obligation.parent_code);
2165 // Only continue if a generator was found.
2166 debug!(?generator, ?trait_ref, ?target_ty);
2167 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
2171 let span = self.tcx.def_span(generator_did);
2173 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
2176 ?generator_did_root,
2177 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2181 let generator_body = generator_did
2183 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2184 .map(|body_id| hir.body(body_id));
2185 let mut visitor = AwaitsVisitor::default();
2186 if let Some(body) = generator_body {
2187 visitor.visit_body(body);
2189 debug!(awaits = ?visitor.awaits);
2191 // Look for a type inside the generator interior that matches the target type to get
2193 let target_ty_erased = self.tcx.erase_regions(target_ty);
2194 let ty_matches = |ty| -> bool {
2195 // Careful: the regions for types that appear in the
2196 // generator interior are not generally known, so we
2197 // want to erase them when comparing (and anyway,
2198 // `Send` and other bounds are generally unaffected by
2199 // the choice of region). When erasing regions, we
2200 // also have to erase late-bound regions. This is
2201 // because the types that appear in the generator
2202 // interior generally contain "bound regions" to
2203 // represent regions that are part of the suspended
2204 // generator frame. Bound regions are preserved by
2205 // `erase_regions` and so we must also call
2206 // `erase_late_bound_regions`.
2207 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2208 let ty_erased = self.tcx.erase_regions(ty_erased);
2209 let eq = ty_erased == target_ty_erased;
2210 debug!(?ty_erased, ?target_ty_erased, ?eq);
2214 // Get the typeck results from the infcx if the generator is the function we are currently
2215 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2216 // cycles. If we can't use resolved types because the generator comes from another crate,
2217 // we still provide a targeted error but without all the relevant spans.
2218 let generator_data = match &self.typeck_results {
2219 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2220 _ if generator_did.is_local() => {
2221 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2223 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2224 GeneratorData::Foreign(generator_diag_data)
2229 let mut interior_or_upvar_span = None;
2231 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2232 debug!(?from_awaited_ty);
2234 // The generator interior types share the same binders
2235 if let Some(cause) =
2236 generator_data.get_generator_interior_types().skip_binder().iter().find(
2237 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2238 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2242 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2244 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2246 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2250 if interior_or_upvar_span.is_none() {
2251 interior_or_upvar_span =
2252 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2255 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2256 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2259 debug!(?interior_or_upvar_span);
2260 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2261 let is_async = self.tcx.generator_is_async(generator_did);
2262 let typeck_results = match generator_data {
2263 GeneratorData::Local(typeck_results) => Some(typeck_results),
2264 GeneratorData::Foreign(_) => None,
2266 self.note_obligation_cause_for_async_await(
2268 interior_or_upvar_span,
2283 /// Unconditionally adds the diagnostic note described in
2284 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2285 #[instrument(level = "debug", skip_all)]
2286 fn note_obligation_cause_for_async_await(
2288 err: &mut Diagnostic,
2289 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2291 outer_generator: Option<DefId>,
2292 trait_pred: ty::TraitPredicate<'tcx>,
2293 target_ty: Ty<'tcx>,
2294 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2295 obligation: &PredicateObligation<'tcx>,
2296 next_code: Option<&ObligationCauseCode<'tcx>>,
2298 let source_map = self.tcx.sess.source_map();
2300 let (await_or_yield, an_await_or_yield) =
2301 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2302 let future_or_generator = if is_async { "future" } else { "generator" };
2304 // Special case the primary error message when send or sync is the trait that was
2306 let hir = self.tcx.hir();
2307 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2308 self.tcx.get_diagnostic_name(trait_pred.def_id())
2310 let (trait_name, trait_verb) =
2311 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2314 err.set_primary_message(format!(
2315 "{} cannot be {} between threads safely",
2316 future_or_generator, trait_verb
2319 let original_span = err.span.primary_span().unwrap();
2320 let mut span = MultiSpan::from_span(original_span);
2322 let message = outer_generator
2323 .and_then(|generator_did| {
2324 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2325 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2326 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2328 .parent(generator_did)
2330 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2331 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2333 format!("future returned by `{}` is not {}", name, trait_name)
2335 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2336 format!("future created by async block is not {}", trait_name)
2338 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2339 format!("future created by async closure is not {}", trait_name)
2343 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2345 span.push_span_label(original_span, message);
2348 format!("is not {}", trait_name)
2350 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2353 let mut explain_yield =
2354 |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
2355 let mut span = MultiSpan::from_span(yield_span);
2356 let snippet = match source_map.span_to_snippet(interior_span) {
2357 // #70935: If snippet contains newlines, display "the value" instead
2358 // so that we do not emit complex diagnostics.
2359 Ok(snippet) if !snippet.contains('\n') => format!("`{}`", snippet),
2360 _ => "the value".to_string(),
2362 // note: future is not `Send` as this value is used across an await
2363 // --> $DIR/issue-70935-complex-spans.rs:13:9
2365 // LL | baz(|| async {
2366 // | ______________-
2369 // LL | | foo(tx.clone());
2371 // | | - ^^^^^^ await occurs here, with value maybe used later
2373 // | has type `closure` which is not `Send`
2374 // note: value is later dropped here
2378 span.push_span_label(
2380 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2382 span.push_span_label(
2384 format!("has type `{}` which {}", target_ty, trait_explanation),
2386 if let Some(scope_span) = scope_span {
2387 let scope_span = source_map.end_point(scope_span);
2389 let msg = format!("{} is later dropped here", snippet);
2390 span.push_span_label(scope_span, msg);
2395 "{} {} as this value is used across {}",
2396 future_or_generator, trait_explanation, an_await_or_yield
2400 match interior_or_upvar_span {
2401 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2402 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2403 if let Some(await_span) = from_awaited_ty {
2404 // The type causing this obligation is one being awaited at await_span.
2405 let mut span = MultiSpan::from_span(await_span);
2406 span.push_span_label(
2409 "await occurs here on type `{}`, which {}",
2410 target_ty, trait_explanation
2416 "future {not_trait} as it awaits another future which {not_trait}",
2417 not_trait = trait_explanation
2421 // Look at the last interior type to get a span for the `.await`.
2423 generator_interior_types = ?format_args!(
2424 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2427 explain_yield(interior_span, yield_span, scope_span);
2430 if let Some(expr_id) = expr {
2431 let expr = hir.expect_expr(expr_id);
2432 debug!("target_ty evaluated from {:?}", expr);
2434 let parent = hir.parent_id(expr_id);
2435 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2436 let parent_span = hir.span(parent);
2437 let parent_did = parent.owner.to_def_id();
2440 // fn foo(&self) -> i32 {}
2443 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2446 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2448 .expr_adjustments(expr)
2450 .any(|adj| adj.is_region_borrow())
2456 // struct Foo(*const u8);
2457 // bar(Foo(std::ptr::null())).await;
2458 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2460 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2461 let is_raw_borrow_inside_fn_like_call =
2462 match self.tcx.def_kind(parent_did) {
2463 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2466 if let Some(typeck_results) = typeck_results {
2467 if (typeck_results.is_method_call(e) && is_region_borrow)
2468 || is_raw_borrow_inside_fn_like_call
2472 "consider moving this into a `let` \
2473 binding to create a shorter lived borrow",
2481 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2482 // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
2483 let non_send = match target_ty.kind() {
2484 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(&obligation) {
2485 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2491 let (span_label, span_note) = match non_send {
2492 // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
2493 // include suggestions to make `T: Sync` so that `&T: Send`,
2494 // or to make `T: Send` so that `&mut T: Send`
2495 Some((ref_ty, is_mut)) => {
2496 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2497 let ref_kind = if is_mut { "&mut" } else { "&" };
2500 "has type `{}` which {}, because `{}` is not `{}`",
2501 target_ty, trait_explanation, ref_ty, ref_ty_trait
2504 "captured value {} because `{}` references cannot be sent unless their referent is `{}`",
2505 trait_explanation, ref_kind, ref_ty_trait
2510 format!("has type `{}` which {}", target_ty, trait_explanation),
2511 format!("captured value {}", trait_explanation),
2515 let mut span = MultiSpan::from_span(upvar_span);
2516 span.push_span_label(upvar_span, span_label);
2517 err.span_note(span, &span_note);
2521 // Add a note for the item obligation that remains - normally a note pointing to the
2522 // bound that introduced the obligation (e.g. `T: Send`).
2524 self.note_obligation_cause_code(
2526 obligation.predicate,
2527 obligation.param_env,
2530 &mut Default::default(),
2534 fn note_obligation_cause_code<T>(
2536 err: &mut Diagnostic,
2538 param_env: ty::ParamEnv<'tcx>,
2539 cause_code: &ObligationCauseCode<'tcx>,
2540 obligated_types: &mut Vec<Ty<'tcx>>,
2541 seen_requirements: &mut FxHashSet<DefId>,
2543 T: ToPredicate<'tcx>,
2546 let predicate = predicate.to_predicate(tcx);
2548 ObligationCauseCode::ExprAssignable
2549 | ObligationCauseCode::MatchExpressionArm { .. }
2550 | ObligationCauseCode::Pattern { .. }
2551 | ObligationCauseCode::IfExpression { .. }
2552 | ObligationCauseCode::IfExpressionWithNoElse
2553 | ObligationCauseCode::MainFunctionType
2554 | ObligationCauseCode::StartFunctionType
2555 | ObligationCauseCode::IntrinsicType
2556 | ObligationCauseCode::MethodReceiver
2557 | ObligationCauseCode::ReturnNoExpression
2558 | ObligationCauseCode::UnifyReceiver(..)
2559 | ObligationCauseCode::OpaqueType
2560 | ObligationCauseCode::MiscObligation
2561 | ObligationCauseCode::WellFormed(..)
2562 | ObligationCauseCode::MatchImpl(..)
2563 | ObligationCauseCode::ReturnType
2564 | ObligationCauseCode::ReturnValue(_)
2565 | ObligationCauseCode::BlockTailExpression(_)
2566 | ObligationCauseCode::AwaitableExpr(_)
2567 | ObligationCauseCode::ForLoopIterator
2568 | ObligationCauseCode::QuestionMark
2569 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2570 | ObligationCauseCode::LetElse
2571 | ObligationCauseCode::BinOp { .. }
2572 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2573 | ObligationCauseCode::RustCall => {}
2574 ObligationCauseCode::SliceOrArrayElem => {
2575 err.note("slice and array elements must have `Sized` type");
2577 ObligationCauseCode::TupleElem => {
2578 err.note("only the last element of a tuple may have a dynamically sized type");
2580 ObligationCauseCode::ProjectionWf(data) => {
2581 err.note(&format!("required so that the projection `{data}` is well-formed"));
2583 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2585 "required so that reference `{ref_ty}` does not outlive its referent"
2588 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2590 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2594 ObligationCauseCode::ItemObligation(_)
2595 | ObligationCauseCode::ExprItemObligation(..) => {
2596 // We hold the `DefId` of the item introducing the obligation, but displaying it
2597 // doesn't add user usable information. It always point at an associated item.
2599 ObligationCauseCode::BindingObligation(item_def_id, span)
2600 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2601 let item_name = tcx.def_path_str(item_def_id);
2602 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2603 let mut multispan = MultiSpan::from(span);
2604 let sm = tcx.sess.source_map();
2605 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2607 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2608 (Ok(l), Ok(r)) => l.line == r.line,
2611 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2612 multispan.push_span_label(ident.span, "required by a bound in this");
2615 let descr = format!("required by a bound in `{item_name}`");
2616 if span.is_visible(sm) {
2617 let msg = format!("required by this bound in `{short_item_name}`");
2618 multispan.push_span_label(span, msg);
2619 err.span_note(multispan, &descr);
2621 err.span_note(tcx.def_span(item_def_id), &descr);
2624 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2626 "required for the cast from `{}` to the object type `{}`",
2627 self.ty_to_string(concrete_ty),
2628 self.ty_to_string(object_ty)
2631 ObligationCauseCode::Coercion { source: _, target } => {
2632 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2634 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2636 "the `Copy` trait is required because this value will be copied for each element of the array",
2641 "consider creating a new `const` item and initializing it with the result \
2642 of the function call to be used in the repeat position, like \
2643 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2647 if self.tcx.sess.is_nightly_build() && is_const_fn {
2649 "create an inline `const` block, see RFC #2920 \
2650 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2654 ObligationCauseCode::VariableType(hir_id) => {
2655 let parent_node = self.tcx.hir().parent_id(hir_id);
2656 match self.tcx.hir().find(parent_node) {
2657 Some(Node::Local(hir::Local { ty: Some(ty), .. })) => {
2658 err.span_suggestion_verbose(
2659 ty.span.shrink_to_lo(),
2660 "consider borrowing here",
2662 Applicability::MachineApplicable,
2664 err.note("all local variables must have a statically known size");
2666 Some(Node::Local(hir::Local {
2667 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2670 // When encountering an assignment of an unsized trait, like
2671 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2672 // order to use have a slice instead.
2673 err.span_suggestion_verbose(
2674 span.shrink_to_lo(),
2675 "consider borrowing here",
2677 Applicability::MachineApplicable,
2679 err.note("all local variables must have a statically known size");
2681 Some(Node::Param(param)) => {
2682 err.span_suggestion_verbose(
2683 param.ty_span.shrink_to_lo(),
2684 "function arguments must have a statically known size, borrowed types \
2685 always have a known size",
2687 Applicability::MachineApplicable,
2691 err.note("all local variables must have a statically known size");
2694 if !self.tcx.features().unsized_locals {
2695 err.help("unsized locals are gated as an unstable feature");
2698 ObligationCauseCode::SizedArgumentType(sp) => {
2699 if let Some(span) = sp {
2700 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder()
2701 && let ty::Clause::Trait(trait_pred) = clause
2702 && let ty::Dynamic(..) = trait_pred.self_ty().kind()
2704 let span = if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2705 && snippet.starts_with("dyn ")
2707 let pos = snippet.len() - snippet[3..].trim_start().len();
2708 span.with_hi(span.lo() + BytePos(pos as u32))
2712 err.span_suggestion_verbose(
2714 "you can use `impl Trait` as the argument type",
2715 "impl ".to_string(),
2716 Applicability::MaybeIncorrect,
2719 err.span_suggestion_verbose(
2720 span.shrink_to_lo(),
2721 "function arguments must have a statically known size, borrowed types \
2722 always have a known size",
2724 Applicability::MachineApplicable,
2727 err.note("all function arguments must have a statically known size");
2729 if tcx.sess.opts.unstable_features.is_nightly_build()
2730 && !self.tcx.features().unsized_fn_params
2732 err.help("unsized fn params are gated as an unstable feature");
2735 ObligationCauseCode::SizedReturnType => {
2736 err.note("the return type of a function must have a statically known size");
2738 ObligationCauseCode::SizedYieldType => {
2739 err.note("the yield type of a generator must have a statically known size");
2741 ObligationCauseCode::SizedBoxType => {
2742 err.note("the type of a box expression must have a statically known size");
2744 ObligationCauseCode::AssignmentLhsSized => {
2745 err.note("the left-hand-side of an assignment must have a statically known size");
2747 ObligationCauseCode::TupleInitializerSized => {
2748 err.note("tuples must have a statically known size to be initialized");
2750 ObligationCauseCode::StructInitializerSized => {
2751 err.note("structs must have a statically known size to be initialized");
2753 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2755 AdtKind::Struct => {
2758 "the last field of a packed struct may only have a \
2759 dynamically sized type if it does not need drop to be run",
2763 "only the last field of a struct may have a dynamically sized type",
2768 err.note("no field of a union may have a dynamically sized type");
2771 err.note("no field of an enum variant may have a dynamically sized type");
2774 err.help("change the field's type to have a statically known size");
2775 err.span_suggestion(
2776 span.shrink_to_lo(),
2777 "borrowed types always have a statically known size",
2779 Applicability::MachineApplicable,
2781 err.multipart_suggestion(
2782 "the `Box` type always has a statically known size and allocates its contents \
2785 (span.shrink_to_lo(), "Box<".to_string()),
2786 (span.shrink_to_hi(), ">".to_string()),
2788 Applicability::MachineApplicable,
2791 ObligationCauseCode::ConstSized => {
2792 err.note("constant expressions must have a statically known size");
2794 ObligationCauseCode::InlineAsmSized => {
2795 err.note("all inline asm arguments must have a statically known size");
2797 ObligationCauseCode::ConstPatternStructural => {
2798 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2800 ObligationCauseCode::SharedStatic => {
2801 err.note("shared static variables must have a type that implements `Sync`");
2803 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2804 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2805 let ty = parent_trait_ref.skip_binder().self_ty();
2806 if parent_trait_ref.references_error() {
2807 // NOTE(eddyb) this was `.cancel()`, but `err`
2808 // is borrowed, so we can't fully defuse it.
2809 err.downgrade_to_delayed_bug();
2813 // If the obligation for a tuple is set directly by a Generator or Closure,
2814 // then the tuple must be the one containing capture types.
2815 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2818 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2820 let parent_trait_ref =
2821 self.resolve_vars_if_possible(data.parent_trait_pred);
2822 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2823 matches!(nested_ty.kind(), ty::Generator(..))
2824 || matches!(nested_ty.kind(), ty::Closure(..))
2830 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2832 // Don't print the tuple of capture types
2834 if !is_upvar_tys_infer_tuple {
2835 let msg = with_forced_trimmed_paths!(format!(
2836 "required because it appears within the type `{ty}`",
2839 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2840 Some(ident) => err.span_note(ident.span, &msg),
2841 None => err.note(&msg),
2843 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
2844 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2845 if tcx.parent(*def_id) == identity_future {
2849 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2850 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2851 let is_future = tcx.ty_is_opaque_future(ty);
2855 "note_obligation_cause_code: check for async fn"
2858 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2859 ty::Generator(last_def_id, ..) => {
2860 tcx.generator_is_async(*last_def_id)
2867 err.span_note(self.tcx.def_span(def_id), &msg)
2869 ty::GeneratorWitness(bound_tys) => {
2870 use std::fmt::Write;
2872 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2873 // Maybe we should just remove this note altogether?
2874 // FIXME: only print types which don't meet the trait requirement
2876 "required because it captures the following types: ".to_owned();
2877 for ty in bound_tys.skip_binder() {
2878 with_forced_trimmed_paths!(write!(msg, "`{}`, ", ty).unwrap());
2880 err.note(msg.trim_end_matches(", "))
2882 ty::Generator(def_id, _, _) => {
2883 let sp = self.tcx.def_span(def_id);
2885 // Special-case this to say "async block" instead of `[static generator]`.
2886 let kind = tcx.generator_kind(def_id).unwrap().descr();
2889 with_forced_trimmed_paths!(&format!(
2890 "required because it's used within this {kind}",
2894 ty::Closure(def_id, _) => err.span_note(
2895 self.tcx.def_span(def_id),
2896 "required because it's used within this closure",
2898 _ => err.note(&msg),
2903 obligated_types.push(ty);
2905 let parent_predicate = parent_trait_ref;
2906 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2907 // #74711: avoid a stack overflow
2908 ensure_sufficient_stack(|| {
2909 self.note_obligation_cause_code(
2919 ensure_sufficient_stack(|| {
2920 self.note_obligation_cause_code(
2924 cause_code.peel_derives(),
2931 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2932 let mut parent_trait_pred =
2933 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2934 parent_trait_pred.remap_constness_diag(param_env);
2935 let parent_def_id = parent_trait_pred.def_id();
2936 let (self_ty, file) =
2937 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2939 "required for `{self_ty}` to implement `{}`",
2940 parent_trait_pred.print_modifiers_and_trait_path()
2942 let mut is_auto_trait = false;
2943 match self.tcx.hir().get_if_local(data.impl_def_id) {
2944 Some(Node::Item(hir::Item {
2945 kind: hir::ItemKind::Trait(is_auto, ..),
2949 // FIXME: we should do something else so that it works even on crate foreign
2951 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2952 err.span_note(ident.span, &msg);
2954 Some(Node::Item(hir::Item {
2955 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2958 let mut spans = Vec::with_capacity(2);
2959 if let Some(trait_ref) = of_trait {
2960 spans.push(trait_ref.path.span);
2962 spans.push(self_ty.span);
2963 let mut spans: MultiSpan = spans.into();
2965 self_ty.span.ctxt().outer_expn_data().kind,
2966 ExpnKind::Macro(MacroKind::Derive, _)
2968 of_trait.as_ref().map(|t| t.path.span.ctxt().outer_expn_data().kind),
2969 Some(ExpnKind::Macro(MacroKind::Derive, _))
2971 spans.push_span_label(
2973 "unsatisfied trait bound introduced in this `derive` macro",
2975 } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
2976 spans.push_span_label(
2978 "unsatisfied trait bound introduced here",
2981 err.span_note(spans, &msg);
2988 if let Some(file) = file {
2990 "the full type name has been written to '{}'",
2994 let mut parent_predicate = parent_trait_pred;
2995 let mut data = &data.derived;
2997 seen_requirements.insert(parent_def_id);
2999 // We don't want to point at the ADT saying "required because it appears within
3000 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
3001 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
3004 let child_trait_ref =
3005 self.resolve_vars_if_possible(derived.parent_trait_pred);
3006 let child_def_id = child_trait_ref.def_id();
3007 if seen_requirements.insert(child_def_id) {
3011 parent_predicate = child_trait_ref.to_predicate(tcx);
3012 parent_trait_pred = child_trait_ref;
3015 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
3016 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
3017 let child_trait_pred =
3018 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
3019 let child_def_id = child_trait_pred.def_id();
3020 if seen_requirements.insert(child_def_id) {
3024 data = &child.derived;
3025 parent_predicate = child_trait_pred.to_predicate(tcx);
3026 parent_trait_pred = child_trait_pred;
3030 "{} redundant requirement{} hidden",
3034 let (self_ty, file) =
3035 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
3037 "required for `{self_ty}` to implement `{}`",
3038 parent_trait_pred.print_modifiers_and_trait_path()
3040 if let Some(file) = file {
3042 "the full type name has been written to '{}'",
3047 // #74711: avoid a stack overflow
3048 ensure_sufficient_stack(|| {
3049 self.note_obligation_cause_code(
3059 ObligationCauseCode::DerivedObligation(ref data) => {
3060 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3061 let parent_predicate = parent_trait_ref;
3062 // #74711: avoid a stack overflow
3063 ensure_sufficient_stack(|| {
3064 self.note_obligation_cause_code(
3074 ObligationCauseCode::FunctionArgumentObligation {
3080 self.note_function_argument_obligation(
3088 ensure_sufficient_stack(|| {
3089 self.note_obligation_cause_code(
3099 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
3100 let item_name = self.tcx.item_name(trait_item_def_id);
3102 "the requirement `{predicate}` appears on the `impl`'s {kind} \
3103 `{item_name}` but not on the corresponding trait's {kind}",
3107 .opt_item_ident(trait_item_def_id)
3109 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
3110 let mut assoc_span: MultiSpan = sp.into();
3111 assoc_span.push_span_label(
3113 format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
3115 if let Some(ident) = self
3117 .opt_associated_item(trait_item_def_id)
3118 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
3120 assoc_span.push_span_label(ident.span, "in this trait");
3122 err.span_note(assoc_span, &msg);
3124 ObligationCauseCode::TrivialBound => {
3125 err.help("see issue #48214");
3126 if tcx.sess.opts.unstable_features.is_nightly_build() {
3127 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
3130 ObligationCauseCode::OpaqueReturnType(expr_info) => {
3131 if let Some((expr_ty, expr_span)) = expr_info {
3132 let expr_ty = with_forced_trimmed_paths!(self.ty_to_string(expr_ty));
3135 with_forced_trimmed_paths!(format!(
3136 "return type was inferred to be `{expr_ty}` here",
3145 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
3147 fn suggest_await_before_try(
3149 err: &mut Diagnostic,
3150 obligation: &PredicateObligation<'tcx>,
3151 trait_pred: ty::PolyTraitPredicate<'tcx>,
3154 let body_hir_id = obligation.cause.body_id;
3155 let item_id = self.tcx.hir().parent_id(body_hir_id);
3157 if let Some(body_id) =
3158 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
3160 let body = self.tcx.hir().body(body_id);
3161 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
3162 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
3164 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3165 let impls_future = self.type_implements_trait(
3167 [self.tcx.erase_late_bound_regions(self_ty)],
3168 obligation.param_env,
3170 if !impls_future.must_apply_modulo_regions() {
3174 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3175 // `<T as Future>::Output`
3176 let projection_ty = trait_pred.map_bound(|trait_pred| {
3177 self.tcx.mk_projection(
3179 // Future::Output has no substs
3180 [trait_pred.self_ty()],
3183 let InferOk { value: projection_ty, .. } =
3184 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3187 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3189 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3190 obligation.param_env,
3191 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3193 debug!(try_trait_obligation = ?try_obligation);
3194 if self.predicate_may_hold(&try_obligation)
3195 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3196 && snippet.ends_with('?')
3198 err.span_suggestion_verbose(
3199 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3200 "consider `await`ing on the `Future`",
3202 Applicability::MaybeIncorrect,
3209 fn suggest_floating_point_literal(
3211 obligation: &PredicateObligation<'tcx>,
3212 err: &mut Diagnostic,
3213 trait_ref: &ty::PolyTraitRef<'tcx>,
3215 let rhs_span = match obligation.cause.code() {
3216 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3219 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3220 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3222 err.span_suggestion_verbose(
3223 rhs_span.shrink_to_hi(),
3224 "consider using a floating-point literal by writing it with `.0`",
3226 Applicability::MaybeIncorrect,
3233 obligation: &PredicateObligation<'tcx>,
3234 err: &mut Diagnostic,
3235 trait_pred: ty::PolyTraitPredicate<'tcx>,
3237 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3240 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3241 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3245 let is_derivable_trait = match diagnostic_name {
3246 sym::Default => !adt.is_enum(),
3247 sym::PartialEq | sym::PartialOrd => {
3248 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3249 trait_pred.skip_binder().self_ty() == rhs_ty
3251 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3254 is_derivable_trait &&
3255 // Ensure all fields impl the trait.
3256 adt.all_fields().all(|field| {
3257 let field_ty = field.ty(self.tcx, substs);
3258 let trait_substs = match diagnostic_name {
3259 sym::PartialEq | sym::PartialOrd => {
3264 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3265 trait_ref: self.tcx.mk_trait_ref(
3266 trait_pred.def_id(),
3267 [field_ty].into_iter().chain(trait_substs),
3271 let field_obl = Obligation::new(
3273 obligation.cause.clone(),
3274 obligation.param_env,
3277 self.predicate_must_hold_modulo_regions(&field_obl)
3281 err.span_suggestion_verbose(
3282 self.tcx.def_span(adt.did()).shrink_to_lo(),
3284 "consider annotating `{}` with `#[derive({})]`",
3285 trait_pred.skip_binder().self_ty(),
3288 format!("#[derive({})]\n", diagnostic_name),
3289 Applicability::MaybeIncorrect,
3294 fn suggest_dereferencing_index(
3296 obligation: &PredicateObligation<'tcx>,
3297 err: &mut Diagnostic,
3298 trait_pred: ty::PolyTraitPredicate<'tcx>,
3300 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3301 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3302 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3303 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3304 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3306 err.span_suggestion_verbose(
3307 obligation.cause.span.shrink_to_lo(),
3308 "dereference this index",
3310 Applicability::MachineApplicable,
3314 fn note_function_argument_obligation(
3317 err: &mut Diagnostic,
3318 parent_code: &ObligationCauseCode<'tcx>,
3319 param_env: ty::ParamEnv<'tcx>,
3320 failed_pred: ty::Predicate<'tcx>,
3324 let hir = tcx.hir();
3325 if let Some(Node::Expr(expr)) = hir.find(arg_hir_id)
3326 && let Some(typeck_results) = &self.typeck_results
3328 if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
3329 let expr = expr.peel_blocks();
3330 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
3331 let span = expr.span;
3332 if Some(span) != err.span.primary_span() {
3335 if ty.references_error() {
3338 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3339 format!("this tail expression is of type `{ty}`")
3345 // FIXME: visit the ty to see if there's any closure involved, and if there is,
3346 // check whether its evaluated return type is the same as the one corresponding
3347 // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3348 // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3349 let mut type_diffs = vec![];
3351 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
3352 && let Some(node_substs) = typeck_results.node_substs_opt(call_hir_id)
3353 && let where_clauses = self.tcx.predicates_of(def_id).instantiate(self.tcx, node_substs)
3354 && let Some(where_pred) = where_clauses.predicates.get(*idx)
3356 if let Some(where_pred) = where_pred.to_opt_poly_trait_pred()
3357 && let Some(failed_pred) = failed_pred.to_opt_poly_trait_pred()
3359 let mut c = CollectAllMismatches {
3364 if let Ok(_) = c.relate(where_pred, failed_pred) {
3365 type_diffs = c.errors;
3367 } else if let Some(where_pred) = where_pred.to_opt_poly_projection_pred()
3368 && let Some(failed_pred) = failed_pred.to_opt_poly_projection_pred()
3369 && let Some(found) = failed_pred.skip_binder().term.ty()
3372 Sorts(ty::error::ExpectedFound {
3373 expected: self.tcx.mk_ty(ty::Alias(ty::Projection, where_pred.skip_binder().projection_ty)),
3379 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3380 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3381 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3382 && let parent_hir_id = self.tcx.hir().parent_id(binding.hir_id)
3383 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3384 && let Some(binding_expr) = local.init
3386 // If the expression we're calling on is a binding, we want to point at the
3387 // `let` when talking about the type. Otherwise we'll point at every part
3388 // of the method chain with the type.
3389 self.point_at_chain(binding_expr, &typeck_results, type_diffs, param_env, err);
3391 self.point_at_chain(expr, &typeck_results, type_diffs, param_env, err);
3394 let call_node = hir.find(call_hir_id);
3395 if let Some(Node::Expr(hir::Expr {
3396 kind: hir::ExprKind::MethodCall(path, rcvr, ..), ..
3399 if Some(rcvr.span) == err.span.primary_span() {
3400 err.replace_span_with(path.ident.span, true);
3403 if let Some(Node::Expr(hir::Expr {
3405 hir::ExprKind::Call(hir::Expr { span, .. }, _)
3406 | hir::ExprKind::MethodCall(hir::PathSegment { ident: Ident { span, .. }, .. }, ..),
3408 })) = hir.find(call_hir_id)
3410 if Some(*span) != err.span.primary_span() {
3411 err.span_label(*span, "required by a bound introduced by this call");
3418 expr: &hir::Expr<'_>,
3419 typeck_results: &TypeckResults<'tcx>,
3420 type_diffs: Vec<TypeError<'tcx>>,
3421 param_env: ty::ParamEnv<'tcx>,
3422 err: &mut Diagnostic,
3424 let mut primary_spans = vec![];
3425 let mut span_labels = vec![];
3429 let mut print_root_expr = true;
3430 let mut assocs = vec![];
3431 let mut expr = expr;
3432 let mut prev_ty = self.resolve_vars_if_possible(
3433 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3435 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) = expr.kind {
3436 // Point at every method call in the chain with the resulting type.
3437 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3438 // ^^^^^^ ^^^^^^^^^^^
3440 let assocs_in_this_method =
3441 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
3442 assocs.push(assocs_in_this_method);
3443 prev_ty = self.resolve_vars_if_possible(
3444 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3447 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3448 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3449 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3450 && let Some(parent) = self.tcx.hir().find_parent(binding.hir_id)
3452 // We've reached the root of the method call chain...
3453 if let hir::Node::Local(local) = parent
3454 && let Some(binding_expr) = local.init
3456 // ...and it is a binding. Get the binding creation and continue the chain.
3457 expr = binding_expr;
3459 if let hir::Node::Param(param) = parent {
3460 // ...and it is a an fn argument.
3461 let prev_ty = self.resolve_vars_if_possible(
3462 typeck_results.node_type_opt(param.hir_id).unwrap_or(tcx.ty_error()),
3464 let assocs_in_this_method = self.probe_assoc_types_at_expr(&type_diffs, param.ty_span, prev_ty, param.hir_id, param_env);
3465 if assocs_in_this_method.iter().any(|a| a.is_some()) {
3466 assocs.push(assocs_in_this_method);
3467 print_root_expr = false;
3473 // We want the type before deref coercions, otherwise we talk about `&[_]`
3474 // instead of `Vec<_>`.
3475 if let Some(ty) = typeck_results.expr_ty_opt(expr) && print_root_expr {
3476 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3477 // Point at the root expression
3478 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3480 span_labels.push((expr.span, format!("this expression has type `{ty}`")));
3482 // Only show this if it is not a "trivial" expression (not a method
3483 // chain) and there are associated types to talk about.
3484 let mut assocs = assocs.into_iter().peekable();
3485 while let Some(assocs_in_method) = assocs.next() {
3486 let Some(prev_assoc_in_method) = assocs.peek() else {
3487 for entry in assocs_in_method {
3488 let Some((span, (assoc, ty))) = entry else { continue; };
3489 if primary_spans.is_empty() || type_diffs.iter().any(|diff| {
3490 let Sorts(expected_found) = diff else { return false; };
3491 self.can_eq(param_env, expected_found.found, ty).is_ok()
3493 // FIXME: this doesn't quite work for `Iterator::collect`
3494 // because we have `Vec<i32>` and `()`, but we'd want `i32`
3495 // to point at the `.into_iter()` call, but as long as we
3496 // still point at the other method calls that might have
3497 // introduced the issue, this is fine for now.
3498 primary_spans.push(span);
3502 with_forced_trimmed_paths!(format!(
3503 "`{}` is `{ty}` here",
3504 self.tcx.def_path_str(assoc),
3510 for (entry, prev_entry) in
3511 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
3513 match (entry, prev_entry) {
3514 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
3515 let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
3517 let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
3518 if self.can_eq(param_env, ty, *prev_ty).is_err() {
3519 if type_diffs.iter().any(|diff| {
3520 let Sorts(expected_found) = diff else { return false; };
3521 self.can_eq(param_env, expected_found.found, ty).is_ok()
3523 primary_spans.push(span);
3526 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
3528 span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
3531 (Some((span, (assoc, ty))), None) => {
3534 with_forced_trimmed_paths!(format!(
3535 "`{}` is `{}` here",
3536 self.tcx.def_path_str(assoc),
3537 self.ty_to_string(ty),
3541 (None, Some(_)) | (None, None) => {}
3545 if !primary_spans.is_empty() {
3546 let mut multi_span: MultiSpan = primary_spans.into();
3547 for (span, label) in span_labels {
3548 multi_span.push_span_label(span, label);
3552 "the method call chain might not have had the expected associated types",
3557 fn probe_assoc_types_at_expr(
3559 type_diffs: &[TypeError<'tcx>],
3562 body_id: hir::HirId,
3563 param_env: ty::ParamEnv<'tcx>,
3564 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
3565 let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
3566 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
3567 for diff in type_diffs {
3568 let Sorts(expected_found) = diff else { continue; };
3569 let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; };
3571 let origin = TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span };
3572 let trait_def_id = proj.trait_def_id(self.tcx);
3573 // Make `Self` be equivalent to the type of the call chain
3574 // expression we're looking at now, so that we can tell what
3575 // for example `Iterator::Item` is at this point in the chain.
3576 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
3578 ty::GenericParamDefKind::Type { .. } => {
3579 if param.index == 0 {
3580 return prev_ty.into();
3583 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Const { .. } => {}
3585 self.var_for_def(span, param)
3587 // This will hold the resolved type of the associated type, if the
3588 // current expression implements the trait that associated type is
3589 // in. For example, this would be what `Iterator::Item` is here.
3590 let ty_var = self.infcx.next_ty_var(origin);
3591 // This corresponds to `<ExprTy as Iterator>::Item = _`.
3592 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::Projection(
3593 ty::ProjectionPredicate {
3594 projection_ty: self.tcx.mk_alias_ty(proj.def_id, substs),
3595 term: ty_var.into(),
3598 // Add `<ExprTy as Iterator>::Item = _` obligation.
3599 ocx.register_obligation(Obligation::misc(
3600 self.tcx, span, body_id, param_env, projection,
3602 if ocx.select_where_possible().is_empty() {
3603 // `ty_var` now holds the type that `Item` is for `ExprTy`.
3604 let ty_var = self.resolve_vars_if_possible(ty_var);
3605 assocs_in_this_method.push(Some((span, (proj.def_id, ty_var))));
3607 // `<ExprTy as Iterator>` didn't select, so likely we've
3608 // reached the end of the iterator chain, like the originating
3610 // Keep the space consistent for later zipping.
3611 assocs_in_this_method.push(None);
3614 assocs_in_this_method
3618 /// Add a hint to add a missing borrow or remove an unnecessary one.
3619 fn hint_missing_borrow<'tcx>(
3623 found_node: Node<'_>,
3624 err: &mut Diagnostic,
3626 let found_args = match found.kind() {
3627 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3629 span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
3632 let expected_args = match expected.kind() {
3633 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3635 span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
3639 // This could be a variant constructor, for example.
3640 let Some(fn_decl) = found_node.fn_decl() else { return; };
3642 let arg_spans = fn_decl.inputs.iter().map(|ty| ty.span);
3644 fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, usize) {
3647 while let ty::Ref(_, new_ty, _) = ty.kind() {
3655 let mut to_borrow = Vec::new();
3656 let mut remove_borrow = Vec::new();
3658 for ((found_arg, expected_arg), arg_span) in found_args.zip(expected_args).zip(arg_spans) {
3659 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
3660 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
3662 if found_ty == expected_ty {
3663 if found_refs < expected_refs {
3664 to_borrow.push((arg_span, expected_arg.to_string()));
3665 } else if found_refs > expected_refs {
3666 remove_borrow.push((arg_span, expected_arg.to_string()));
3671 if !to_borrow.is_empty() {
3672 err.multipart_suggestion(
3673 "consider borrowing the argument",
3675 Applicability::MaybeIncorrect,
3679 if !remove_borrow.is_empty() {
3680 err.multipart_suggestion(
3681 "do not borrow the argument",
3683 Applicability::MaybeIncorrect,
3688 /// Collect all the returned expressions within the input expression.
3689 /// Used to point at the return spans when we want to suggest some change to them.
3691 pub struct ReturnsVisitor<'v> {
3692 pub returns: Vec<&'v hir::Expr<'v>>,
3693 in_block_tail: bool,
3696 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3697 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3698 // Visit every expression to detect `return` paths, either through the function's tail
3699 // expression or `return` statements. We walk all nodes to find `return` statements, but
3700 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3701 // they're in the return path of the function body.
3703 hir::ExprKind::Ret(Some(ex)) => {
3704 self.returns.push(ex);
3706 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3707 self.in_block_tail = false;
3708 for stmt in block.stmts {
3709 hir::intravisit::walk_stmt(self, stmt);
3711 self.in_block_tail = true;
3712 if let Some(expr) = block.expr {
3713 self.visit_expr(expr);
3716 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3717 self.visit_expr(then);
3718 if let Some(el) = else_opt {
3719 self.visit_expr(el);
3722 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3724 self.visit_expr(arm.body);
3727 // We need to walk to find `return`s in the entire body.
3728 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3729 _ => self.returns.push(ex),
3733 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3734 assert!(!self.in_block_tail);
3735 if body.generator_kind().is_none() {
3736 if let hir::ExprKind::Block(block, None) = body.value.kind {
3737 if block.expr.is_some() {
3738 self.in_block_tail = true;
3742 hir::intravisit::walk_body(self, body);
3746 /// Collect all the awaited expressions within the input expression.
3748 struct AwaitsVisitor {
3749 awaits: Vec<hir::HirId>,
3752 impl<'v> Visitor<'v> for AwaitsVisitor {
3753 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3754 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3755 self.awaits.push(id)
3757 hir::intravisit::walk_expr(self, ex)
3761 pub trait NextTypeParamName {
3762 fn next_type_param_name(&self, name: Option<&str>) -> String;
3765 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3766 fn next_type_param_name(&self, name: Option<&str>) -> String {
3767 // This is the list of possible parameter names that we might suggest.
3768 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3769 let name = name.as_deref();
3770 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3771 let used_names = self
3773 .filter_map(|p| match p.name {
3774 hir::ParamName::Plain(ident) => Some(ident.name),
3777 .collect::<Vec<_>>();
3781 .find(|n| !used_names.contains(&Symbol::intern(n)))
3782 .unwrap_or(&"ParamName")
3787 fn suggest_trait_object_return_type_alternatives(
3788 err: &mut Diagnostic,
3791 is_object_safe: bool,
3793 err.span_suggestion(
3796 "use `impl {}` as the return type if all return paths have the same type but you \
3797 want to expose only the trait in the signature",
3800 format!("impl {}", trait_obj),
3801 Applicability::MaybeIncorrect,
3804 err.multipart_suggestion(
3806 "use a boxed trait object if all return paths implement trait `{}`",
3810 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3811 (ret_ty.shrink_to_hi(), ">".to_string()),
3813 Applicability::MaybeIncorrect,
3818 /// Collect the spans that we see the generic param `param_did`
3819 struct ReplaceImplTraitVisitor<'a> {
3820 ty_spans: &'a mut Vec<Span>,
3824 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3825 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3826 if let hir::TyKind::Path(hir::QPath::Resolved(
3828 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3831 if self.param_did == *segment_did {
3832 // `fn foo(t: impl Trait)`
3833 // ^^^^^^^^^^ get this to suggest `T` instead
3835 // There might be more than one `impl Trait`.
3836 self.ty_spans.push(t.span);
3841 hir::intravisit::walk_ty(self, t);
3845 // Replace `param` with `replace_ty`
3846 struct ReplaceImplTraitFolder<'tcx> {
3848 param: &'tcx ty::GenericParamDef,
3849 replace_ty: Ty<'tcx>,
3852 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3853 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3854 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3855 if self.param.index == *index {
3856 return self.replace_ty;
3859 t.super_fold_with(self)
3862 fn tcx(&self) -> TyCtxt<'tcx> {