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};
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, 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_reference_to_arg(
211 obligation: &PredicateObligation<'tcx>,
212 err: &mut Diagnostic,
213 trait_pred: ty::PolyTraitPredicate<'tcx>,
214 has_custom_message: bool,
217 fn suggest_borrowing_for_object_cast(
219 err: &mut Diagnostic,
220 obligation: &PredicateObligation<'tcx>,
225 fn suggest_remove_reference(
227 obligation: &PredicateObligation<'tcx>,
228 err: &mut Diagnostic,
229 trait_pred: ty::PolyTraitPredicate<'tcx>,
232 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
234 fn suggest_change_mut(
236 obligation: &PredicateObligation<'tcx>,
237 err: &mut Diagnostic,
238 trait_pred: ty::PolyTraitPredicate<'tcx>,
241 fn suggest_semicolon_removal(
243 obligation: &PredicateObligation<'tcx>,
244 err: &mut Diagnostic,
246 trait_pred: ty::PolyTraitPredicate<'tcx>,
249 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
251 fn suggest_impl_trait(
253 err: &mut Diagnostic,
255 obligation: &PredicateObligation<'tcx>,
256 trait_pred: ty::PolyTraitPredicate<'tcx>,
259 fn point_at_returns_when_relevant(
261 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
262 obligation: &PredicateObligation<'tcx>,
265 fn report_closure_arg_mismatch(
268 found_span: Option<Span>,
269 found: ty::PolyTraitRef<'tcx>,
270 expected: ty::PolyTraitRef<'tcx>,
271 cause: &ObligationCauseCode<'tcx>,
272 found_node: Option<Node<'_>>,
273 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
275 fn note_conflicting_closure_bounds(
277 cause: &ObligationCauseCode<'tcx>,
278 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
281 fn suggest_fully_qualified_path(
283 err: &mut Diagnostic,
289 fn maybe_note_obligation_cause_for_async_await(
291 err: &mut Diagnostic,
292 obligation: &PredicateObligation<'tcx>,
295 fn note_obligation_cause_for_async_await(
297 err: &mut Diagnostic,
298 interior_or_upvar_span: GeneratorInteriorOrUpvar,
300 outer_generator: Option<DefId>,
301 trait_pred: ty::TraitPredicate<'tcx>,
303 typeck_results: Option<&ty::TypeckResults<'tcx>>,
304 obligation: &PredicateObligation<'tcx>,
305 next_code: Option<&ObligationCauseCode<'tcx>>,
308 fn note_obligation_cause_code<T>(
310 err: &mut Diagnostic,
312 param_env: ty::ParamEnv<'tcx>,
313 cause_code: &ObligationCauseCode<'tcx>,
314 obligated_types: &mut Vec<Ty<'tcx>>,
315 seen_requirements: &mut FxHashSet<DefId>,
317 T: ToPredicate<'tcx>;
319 /// Suggest to await before try: future? => future.await?
320 fn suggest_await_before_try(
322 err: &mut Diagnostic,
323 obligation: &PredicateObligation<'tcx>,
324 trait_pred: ty::PolyTraitPredicate<'tcx>,
328 fn suggest_floating_point_literal(
330 obligation: &PredicateObligation<'tcx>,
331 err: &mut Diagnostic,
332 trait_ref: &ty::PolyTraitRef<'tcx>,
337 obligation: &PredicateObligation<'tcx>,
338 err: &mut Diagnostic,
339 trait_pred: ty::PolyTraitPredicate<'tcx>,
342 fn suggest_dereferencing_index(
344 obligation: &PredicateObligation<'tcx>,
345 err: &mut Diagnostic,
346 trait_pred: ty::PolyTraitPredicate<'tcx>,
348 fn note_function_argument_obligation(
351 err: &mut Diagnostic,
352 parent_code: &ObligationCauseCode<'tcx>,
353 param_env: ty::ParamEnv<'tcx>,
354 predicate: ty::Predicate<'tcx>,
359 expr: &hir::Expr<'_>,
360 typeck_results: &TypeckResults<'tcx>,
361 type_diffs: Vec<TypeError<'tcx>>,
362 param_env: ty::ParamEnv<'tcx>,
363 err: &mut Diagnostic,
365 fn probe_assoc_types_at_expr(
367 type_diffs: &[TypeError<'tcx>],
371 param_env: ty::ParamEnv<'tcx>,
372 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>>;
375 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
377 generics.tail_span_for_predicate_suggestion(),
378 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
382 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
383 /// it can also be an `impl Trait` param that needs to be decomposed to a type
384 /// param for cleaner code.
385 fn suggest_restriction<'tcx>(
388 hir_generics: &hir::Generics<'tcx>,
390 err: &mut Diagnostic,
391 fn_sig: Option<&hir::FnSig<'_>>,
392 projection: Option<&ty::AliasTy<'_>>,
393 trait_pred: ty::PolyTraitPredicate<'tcx>,
394 // When we are dealing with a trait, `super_traits` will be `Some`:
395 // Given `trait T: A + B + C {}`
396 // - ^^^^^^^^^ GenericBounds
399 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
401 if hir_generics.where_clause_span.from_expansion()
402 || hir_generics.where_clause_span.desugaring_kind().is_some()
406 let Some(item_id) = hir_id.as_owner() else { return; };
407 let generics = tcx.generics_of(item_id);
408 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
409 if let Some((param, bound_str, fn_sig)) =
410 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
411 // Shenanigans to get the `Trait` from the `impl Trait`.
412 ty::Param(param) => {
413 let param_def = generics.type_param(param, tcx);
414 if param_def.kind.is_synthetic() {
416 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
417 return Some((param_def, bound_str, sig));
424 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
425 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
428 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
431 if !trait_pred.is_suggestable(tcx, false) {
434 // We know we have an `impl Trait` that doesn't satisfy a required projection.
436 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
437 // types. There should be at least one, but there might be *more* than one. In that
438 // case we could just ignore it and try to identify which one needs the restriction,
439 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
441 let mut ty_spans = vec![];
442 for input in fn_sig.decl.inputs {
443 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
446 // The type param `T: Trait` we will suggest to introduce.
447 let type_param = format!("{}: {}", type_param_name, bound_str);
450 if let Some(span) = hir_generics.span_for_param_suggestion() {
451 (span, format!(", {}", type_param))
453 (hir_generics.span, format!("<{}>", type_param))
455 // `fn foo(t: impl Trait)`
456 // ^ suggest `where <T as Trait>::A: Bound`
457 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
459 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
461 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
462 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
463 // `fn foo(t: impl Trait<A: Bound>)` instead.
464 err.multipart_suggestion(
465 "introduce a type parameter with a trait bound instead of using `impl Trait`",
467 Applicability::MaybeIncorrect,
470 if !trait_pred.is_suggestable(tcx, false) {
473 // Trivial case: `T` needs an extra bound: `T: Bound`.
474 let (sp, suggestion) = match (
478 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
481 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
482 (None, Some((ident, []))) => (
483 ident.span.shrink_to_hi(),
484 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
486 (_, Some((_, [.., bounds]))) => (
487 bounds.span().shrink_to_hi(),
488 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
490 (Some(_), Some((_, []))) => (
491 hir_generics.span.shrink_to_hi(),
492 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
496 err.span_suggestion_verbose(
498 &format!("consider further restricting {}", msg),
500 Applicability::MachineApplicable,
505 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
506 fn suggest_restricting_param_bound(
508 mut err: &mut Diagnostic,
509 trait_pred: ty::PolyTraitPredicate<'tcx>,
510 associated_ty: Option<(&'static str, Ty<'tcx>)>,
513 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
515 let self_ty = trait_pred.skip_binder().self_ty();
516 let (param_ty, projection) = match self_ty.kind() {
517 ty::Param(_) => (true, None),
518 ty::Alias(ty::Projection, projection) => (false, Some(projection)),
522 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
523 // don't suggest `T: Sized + ?Sized`.
524 let mut hir_id = body_id;
525 while let Some(node) = self.tcx.hir().find(hir_id) {
527 hir::Node::Item(hir::Item {
529 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
531 }) if self_ty == self.tcx.types.self_param => {
533 // Restricting `Self` for a single method.
543 Some((ident, bounds)),
548 hir::Node::TraitItem(hir::TraitItem {
550 kind: hir::TraitItemKind::Fn(..),
552 }) if self_ty == self.tcx.types.self_param => {
554 // Restricting `Self` for a single method.
556 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
562 hir::Node::TraitItem(hir::TraitItem {
564 kind: hir::TraitItemKind::Fn(fn_sig, ..),
567 | hir::Node::ImplItem(hir::ImplItem {
569 kind: hir::ImplItemKind::Fn(fn_sig, ..),
572 | hir::Node::Item(hir::Item {
573 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
574 }) if projection.is_some() => {
575 // Missing restriction on associated type of type parameter (unmet projection).
580 "the associated type",
589 hir::Node::Item(hir::Item {
591 hir::ItemKind::Trait(_, _, generics, ..)
592 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
594 }) if projection.is_some() => {
595 // Missing restriction on associated type of type parameter (unmet projection).
600 "the associated type",
610 hir::Node::Item(hir::Item {
612 hir::ItemKind::Struct(_, generics)
613 | hir::ItemKind::Enum(_, generics)
614 | hir::ItemKind::Union(_, generics)
615 | hir::ItemKind::Trait(_, _, generics, ..)
616 | hir::ItemKind::Impl(hir::Impl { generics, .. })
617 | hir::ItemKind::Fn(_, generics, _)
618 | hir::ItemKind::TyAlias(_, generics)
619 | hir::ItemKind::TraitAlias(generics, _)
620 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
623 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
624 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
627 // We skip the 0'th subst (self) because we do not want
628 // to consider the predicate as not suggestible if the
629 // self type is an arg position `impl Trait` -- instead,
630 // we handle that by adding ` + Bound` below.
631 // FIXME(compiler-errors): It would be nice to do the same
632 // this that we do in `suggest_restriction` and pull the
633 // `impl Trait` into a new generic if it shows up somewhere
634 // else in the predicate.
635 if !trait_pred.skip_binder().trait_ref.substs[1..]
637 .all(|g| g.is_suggestable(self.tcx, false))
641 // Missing generic type parameter bound.
642 let param_name = self_ty.to_string();
643 let mut constraint = with_no_trimmed_paths!(
644 trait_pred.print_modifiers_and_trait_path().to_string()
647 if let Some((name, term)) = associated_ty {
648 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
649 // That should be extracted into a helper function.
650 if constraint.ends_with('>') {
651 constraint = format!(
653 &constraint[..constraint.len() - 1],
658 constraint.push_str(&format!("<{} = {}>", name, term));
662 if suggest_constraining_type_param(
668 Some(trait_pred.def_id()),
674 hir::Node::Item(hir::Item {
676 hir::ItemKind::Struct(_, generics)
677 | hir::ItemKind::Enum(_, generics)
678 | hir::ItemKind::Union(_, generics)
679 | hir::ItemKind::Trait(_, _, generics, ..)
680 | hir::ItemKind::Impl(hir::Impl { generics, .. })
681 | hir::ItemKind::Fn(_, generics, _)
682 | hir::ItemKind::TyAlias(_, generics)
683 | hir::ItemKind::TraitAlias(generics, _)
684 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
687 // Missing generic type parameter bound.
688 if suggest_arbitrary_trait_bound(
698 hir::Node::Crate(..) => return,
703 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
707 /// When after several dereferencing, the reference satisfies the trait
708 /// binding. This function provides dereference suggestion for this
709 /// specific situation.
710 fn suggest_dereferences(
712 obligation: &PredicateObligation<'tcx>,
713 err: &mut Diagnostic,
714 trait_pred: ty::PolyTraitPredicate<'tcx>,
716 // It only make sense when suggesting dereferences for arguments
717 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = obligation.cause.code()
718 else { return false; };
719 let Some(typeck_results) = &self.typeck_results
720 else { return false; };
721 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
722 else { return false; };
723 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
724 else { return false; };
726 let span = obligation.cause.span;
727 let mut real_trait_pred = trait_pred;
728 let mut code = obligation.cause.code();
729 while let Some((parent_code, parent_trait_pred)) = code.parent() {
731 if let Some(parent_trait_pred) = parent_trait_pred {
732 real_trait_pred = parent_trait_pred;
735 let real_ty = real_trait_pred.self_ty();
736 // We `erase_late_bound_regions` here because `make_subregion` does not handle
737 // `ReLateBound`, and we don't particularly care about the regions.
739 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
745 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
746 let mut autoderef = Autoderef::new(
748 obligation.param_env,
749 obligation.cause.body_id,
753 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
755 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
757 // Remapping bound vars here
758 let real_trait_pred_and_ty =
759 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
760 let obligation = self.mk_trait_obligation_with_new_self_ty(
761 obligation.param_env,
762 real_trait_pred_and_ty,
764 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
767 // Don't care about `&mut` because `DerefMut` is used less
768 // often and user will not expect autoderef happens.
769 if let Some(hir::Node::Expr(hir::Expr {
771 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
773 })) = self.tcx.hir().find(*arg_hir_id)
775 let derefs = "*".repeat(steps);
776 err.span_suggestion_verbose(
777 expr.span.shrink_to_lo(),
778 "consider dereferencing here",
780 Applicability::MachineApplicable,
785 } else if real_trait_pred != trait_pred {
786 // This branch addresses #87437.
788 // Remapping bound vars here
789 let real_trait_pred_and_base_ty =
790 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
791 let obligation = self.mk_trait_obligation_with_new_self_ty(
792 obligation.param_env,
793 real_trait_pred_and_base_ty,
795 if self.predicate_may_hold(&obligation) {
796 let call_node = self.tcx.hir().get(*call_hir_id);
797 let msg = "consider dereferencing here";
798 let is_receiver = matches!(
800 Node::Expr(hir::Expr {
801 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
804 if receiver_expr.hir_id == *arg_hir_id
807 err.multipart_suggestion_verbose(
810 (span.shrink_to_lo(), "(*".to_string()),
811 (span.shrink_to_hi(), ")".to_string()),
813 Applicability::MachineApplicable,
816 err.span_suggestion_verbose(
820 Applicability::MachineApplicable,
831 /// Given a closure's `DefId`, return the given name of the closure.
833 /// This doesn't account for reassignments, but it's only used for suggestions.
834 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
835 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
836 // Get the local name of this closure. This can be inaccurate because
837 // of the possibility of reassignment, but this should be good enough.
839 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
849 let hir = self.tcx.hir();
850 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
851 match hir.find_parent(hir_id) {
852 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
853 get_name(err, &local.pat.kind)
855 // Different to previous arm because one is `&hir::Local` and the other
856 // is `P<hir::Local>`.
857 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
862 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
863 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
864 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
867 obligation: &PredicateObligation<'tcx>,
868 err: &mut Diagnostic,
869 trait_pred: ty::PolyTraitPredicate<'tcx>,
871 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
872 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
874 // Don't suggest calling to turn an unsized type into a sized type
878 // This is duplicated from `extract_callable_info` in typeck, which
879 // relies on autoderef, so we can't use it here.
880 let found = trait_pred.self_ty().skip_binder().peel_refs();
881 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
883 ty::FnPtr(fn_sig) => {
884 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
886 ty::FnDef(def_id, _) => {
887 let fn_sig = found.fn_sig(self.tcx);
888 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
890 ty::Closure(def_id, substs) => {
891 let fn_sig = substs.as_closure().sig();
893 DefIdOrName::DefId(def_id),
895 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
898 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
899 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
900 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
901 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
902 // args tuple will always be substs[1]
903 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
906 DefIdOrName::DefId(def_id),
907 pred.kind().rebind(proj.term.ty().unwrap()),
908 pred.kind().rebind(args.as_slice()),
915 ty::Dynamic(data, _, ty::Dyn) => {
916 data.iter().find_map(|pred| {
917 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
918 && Some(proj.def_id) == self.tcx.lang_items().fn_once_output()
919 // for existential projection, substs are shifted over by 1
920 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
923 DefIdOrName::Name("trait object"),
924 pred.rebind(proj.term.ty().unwrap()),
925 pred.rebind(args.as_slice()),
933 obligation.param_env.caller_bounds().iter().find_map(|pred| {
934 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
935 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
936 && proj.projection_ty.self_ty() == found
937 // args tuple will always be substs[1]
938 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
941 DefIdOrName::Name("type parameter"),
942 pred.kind().rebind(proj.term.ty().unwrap()),
943 pred.kind().rebind(args.as_slice()),
951 }) else { return false; };
952 let output = self.replace_bound_vars_with_fresh_vars(
953 obligation.cause.span,
954 LateBoundRegionConversionTime::FnCall,
957 let inputs = inputs.skip_binder().iter().map(|ty| {
958 self.replace_bound_vars_with_fresh_vars(
959 obligation.cause.span,
960 LateBoundRegionConversionTime::FnCall,
965 // Remapping bound vars here
966 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
969 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
970 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
974 // Get the name of the callable and the arguments to be used in the suggestion.
975 let hir = self.tcx.hir();
977 let msg = match def_id_or_name {
978 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
979 DefKind::Ctor(CtorOf::Struct, _) => {
980 "use parentheses to construct this tuple struct".to_string()
982 DefKind::Ctor(CtorOf::Variant, _) => {
983 "use parentheses to construct this tuple variant".to_string()
985 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
987 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
992 if ty.is_suggestable(self.tcx, false) {
993 format!("/* {ty} */")
995 "/* value */".to_string()
1001 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
1002 && obligation.cause.span.can_be_used_for_suggestions()
1004 // When the obligation error has been ensured to have been caused by
1005 // an argument, the `obligation.cause.span` points at the expression
1006 // of the argument, so we can provide a suggestion. Otherwise, we give
1007 // a more general note.
1008 err.span_suggestion_verbose(
1009 obligation.cause.span.shrink_to_hi(),
1011 format!("({args})"),
1012 Applicability::HasPlaceholders,
1014 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
1015 let name = match hir.get_if_local(def_id) {
1016 Some(hir::Node::Expr(hir::Expr {
1017 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
1020 err.span_label(*fn_decl_span, "consider calling this closure");
1021 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
1026 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
1027 err.span_label(ident.span, "consider calling this function");
1030 Some(hir::Node::Ctor(..)) => {
1031 let name = self.tcx.def_path_str(def_id);
1033 self.tcx.def_span(def_id),
1034 format!("consider calling the constructor for `{}`", name),
1040 err.help(&format!("{msg}: `{name}({args})`"));
1045 fn check_for_binding_assigned_block_without_tail_expression(
1047 obligation: &PredicateObligation<'tcx>,
1048 err: &mut Diagnostic,
1049 trait_pred: ty::PolyTraitPredicate<'tcx>,
1051 let mut span = obligation.cause.span;
1052 while span.from_expansion() {
1053 // Remove all the desugaring and macro contexts.
1056 let mut expr_finder = FindExprBySpan::new(span);
1057 let Some(hir::Node::Expr(body)) = self.tcx.hir().find(obligation.cause.body_id) else { return; };
1058 expr_finder.visit_expr(&body);
1059 let Some(expr) = expr_finder.result else { return; };
1060 let Some(typeck) = &self.typeck_results else { return; };
1061 let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { return; };
1065 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; };
1066 let hir::def::Res::Local(hir_id) = path.res else { return; };
1067 let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else {
1070 let Some(hir::Node::Local(hir::Local {
1074 })) = self.tcx.hir().find_parent(pat.hir_id) else { return; };
1075 let hir::ExprKind::Block(block, None) = init.kind else { return; };
1076 if block.expr.is_some() {
1079 let [.., stmt] = block.stmts else {
1080 err.span_label(block.span, "this empty block is missing a tail expression");
1083 let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; };
1084 let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1085 err.span_label(block.span, "this block is missing a tail expression");
1088 let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
1089 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1091 let new_obligation =
1092 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1093 if self.predicate_must_hold_modulo_regions(&new_obligation) {
1094 err.span_suggestion_short(
1095 stmt.span.with_lo(tail_expr.span.hi()),
1096 "remove this semicolon",
1098 Applicability::MachineApplicable,
1101 err.span_label(block.span, "this block is missing a tail expression");
1105 fn suggest_add_reference_to_arg(
1107 obligation: &PredicateObligation<'tcx>,
1108 err: &mut Diagnostic,
1109 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1110 has_custom_message: bool,
1112 let span = obligation.cause.span;
1114 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
1115 obligation.cause.code()
1118 } else if let ObligationCauseCode::ItemObligation(_)
1119 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1121 obligation.cause.code()
1122 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1123 span.ctxt().outer_expn_data().kind
1125 obligation.cause.code()
1130 // List of traits for which it would be nonsensical to suggest borrowing.
1131 // For instance, immutable references are always Copy, so suggesting to
1132 // borrow would always succeed, but it's probably not what the user wanted.
1133 let mut never_suggest_borrow: Vec<_> =
1134 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1136 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1139 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1140 never_suggest_borrow.push(def_id);
1143 let param_env = obligation.param_env;
1145 // Try to apply the original trait binding obligation by borrowing.
1146 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1147 blacklist: &[DefId]|
1149 if blacklist.contains(&old_pred.def_id()) {
1152 // We map bounds to `&T` and `&mut T`
1153 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1156 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1159 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1162 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1166 let mk_result = |trait_pred_and_new_ty| {
1168 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1169 self.predicate_must_hold_modulo_regions(&obligation)
1171 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1172 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1174 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1175 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1176 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1179 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1180 mutability.is_mut(),
1186 if imm_ref_self_ty_satisfies_pred
1187 || mut_ref_self_ty_satisfies_pred
1188 || ref_inner_ty_satisfies_pred
1190 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1191 // We don't want a borrowing suggestion on the fields in structs,
1194 // the_foos: Vec<Foo>
1198 span.ctxt().outer_expn_data().kind,
1199 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1203 if snippet.starts_with('&') {
1204 // This is already a literal borrow and the obligation is failing
1205 // somewhere else in the obligation chain. Do not suggest non-sense.
1208 // We have a very specific type of error, where just borrowing this argument
1209 // might solve the problem. In cases like this, the important part is the
1210 // original type obligation, not the last one that failed, which is arbitrary.
1211 // Because of this, we modify the error to refer to the original obligation and
1212 // return early in the caller.
1214 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1215 if has_custom_message {
1219 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1224 "the trait `{}` is not implemented for `{}`",
1225 old_pred.print_modifiers_and_trait_path(),
1226 old_pred.self_ty().skip_binder(),
1230 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1231 err.span_suggestions(
1232 span.shrink_to_lo(),
1233 "consider borrowing here",
1234 ["&".to_string(), "&mut ".to_string()],
1235 Applicability::MaybeIncorrect,
1238 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1239 err.span_suggestion_verbose(
1240 span.shrink_to_lo(),
1242 "consider{} borrowing here",
1243 if is_mut { " mutably" } else { "" }
1245 format!("&{}", if is_mut { "mut " } else { "" }),
1246 Applicability::MaybeIncorrect,
1255 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1256 try_borrowing(cause.derived.parent_trait_pred, &[])
1257 } else if let ObligationCauseCode::BindingObligation(_, _)
1258 | ObligationCauseCode::ItemObligation(_)
1259 | ObligationCauseCode::ExprItemObligation(..)
1260 | ObligationCauseCode::ExprBindingObligation(..) = code
1262 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1268 // Suggest borrowing the type
1269 fn suggest_borrowing_for_object_cast(
1271 err: &mut Diagnostic,
1272 obligation: &PredicateObligation<'tcx>,
1274 object_ty: Ty<'tcx>,
1276 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1277 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1279 for predicate in predicates.iter() {
1280 if !self.predicate_must_hold_modulo_regions(
1281 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1287 err.span_suggestion(
1288 obligation.cause.span.shrink_to_lo(),
1290 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1293 Applicability::MaybeIncorrect,
1297 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1298 /// suggest removing these references until we reach a type that implements the trait.
1299 fn suggest_remove_reference(
1301 obligation: &PredicateObligation<'tcx>,
1302 err: &mut Diagnostic,
1303 trait_pred: ty::PolyTraitPredicate<'tcx>,
1305 let span = obligation.cause.span;
1307 let mut suggested = false;
1308 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1310 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1311 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1312 // Do not suggest removal of borrow from type arguments.
1316 // Skipping binder here, remapping below
1317 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1319 for refs_remaining in 0..refs_number {
1320 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1323 suggested_ty = *inner_ty;
1325 // Remapping bound vars here
1326 let trait_pred_and_suggested_ty =
1327 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1329 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1330 obligation.param_env,
1331 trait_pred_and_suggested_ty,
1334 if self.predicate_may_hold(&new_obligation) {
1339 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1341 let remove_refs = refs_remaining + 1;
1343 let msg = if remove_refs == 1 {
1344 "consider removing the leading `&`-reference".to_string()
1346 format!("consider removing {} leading `&`-references", remove_refs)
1349 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1358 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1359 let span = obligation.cause.span;
1361 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1362 let hir = self.tcx.hir();
1363 if let Some(hir::Node::Expr(expr)) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1364 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1365 // and if not maybe suggest doing something else? If we kept the expression around we
1366 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1367 // it is from the local crate.
1368 err.span_suggestion(
1370 "remove the `.await`",
1372 Applicability::MachineApplicable,
1374 // FIXME: account for associated `async fn`s.
1375 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1376 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1377 obligation.predicate.kind().skip_binder()
1379 err.span_label(*span, &format!("this call returns `{}`", pred.self_ty()));
1381 if let Some(typeck_results) = &self.typeck_results
1382 && let ty = typeck_results.expr_ty_adjusted(base)
1383 && let ty::FnDef(def_id, _substs) = ty.kind()
1384 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1385 hir.get_if_local(*def_id)
1388 "alternatively, consider making `fn {}` asynchronous",
1391 if vis_span.is_empty() {
1392 err.span_suggestion_verbose(
1393 span.shrink_to_lo(),
1396 Applicability::MaybeIncorrect,
1399 err.span_suggestion_verbose(
1400 vis_span.shrink_to_hi(),
1403 Applicability::MaybeIncorrect,
1412 /// Check if the trait bound is implemented for a different mutability and note it in the
1414 fn suggest_change_mut(
1416 obligation: &PredicateObligation<'tcx>,
1417 err: &mut Diagnostic,
1418 trait_pred: ty::PolyTraitPredicate<'tcx>,
1420 let points_at_arg = matches!(
1421 obligation.cause.code(),
1422 ObligationCauseCode::FunctionArgumentObligation { .. },
1425 let span = obligation.cause.span;
1426 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1428 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1429 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1430 // Do not suggest removal of borrow from type arguments.
1433 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1434 if trait_pred.has_non_region_infer() {
1435 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1436 // unresolved bindings.
1440 // Skipping binder here, remapping below
1441 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1443 let suggested_ty = match mutability {
1444 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1445 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1448 // Remapping bound vars here
1449 let trait_pred_and_suggested_ty =
1450 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1452 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1453 obligation.param_env,
1454 trait_pred_and_suggested_ty,
1456 let suggested_ty_would_satisfy_obligation = self
1457 .evaluate_obligation_no_overflow(&new_obligation)
1458 .must_apply_modulo_regions();
1459 if suggested_ty_would_satisfy_obligation {
1464 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1465 if points_at_arg && mutability.is_not() && refs_number > 0 {
1466 err.span_suggestion_verbose(
1468 "consider changing this borrow's mutability",
1470 Applicability::MachineApplicable,
1474 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1475 trait_pred.print_modifiers_and_trait_path(),
1477 trait_pred.skip_binder().self_ty(),
1485 fn suggest_semicolon_removal(
1487 obligation: &PredicateObligation<'tcx>,
1488 err: &mut Diagnostic,
1490 trait_pred: ty::PolyTraitPredicate<'tcx>,
1492 let hir = self.tcx.hir();
1493 let parent_node = hir.parent_id(obligation.cause.body_id);
1494 let node = hir.find(parent_node);
1495 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1496 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1497 && sig.decl.output.span().overlaps(span)
1498 && blk.expr.is_none()
1499 && trait_pred.self_ty().skip_binder().is_unit()
1500 && let Some(stmt) = blk.stmts.last()
1501 && let hir::StmtKind::Semi(expr) = stmt.kind
1502 // Only suggest this if the expression behind the semicolon implements the predicate
1503 && let Some(typeck_results) = &self.typeck_results
1504 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1505 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1506 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1512 "this expression has type `{}`, which implements `{}`",
1514 trait_pred.print_modifiers_and_trait_path()
1517 err.span_suggestion(
1518 self.tcx.sess.source_map().end_point(stmt.span),
1519 "remove this semicolon",
1521 Applicability::MachineApplicable
1528 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1529 let hir = self.tcx.hir();
1530 let parent_node = hir.parent_id(obligation.cause.body_id);
1531 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1535 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1538 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1539 /// applicable and signal that the error has been expanded appropriately and needs to be
1541 fn suggest_impl_trait(
1543 err: &mut Diagnostic,
1545 obligation: &PredicateObligation<'tcx>,
1546 trait_pred: ty::PolyTraitPredicate<'tcx>,
1548 match obligation.cause.code().peel_derives() {
1549 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1550 ObligationCauseCode::SizedReturnType => {}
1554 let hir = self.tcx.hir();
1555 let fn_hir_id = hir.parent_id(obligation.cause.body_id);
1556 let node = hir.find(fn_hir_id);
1557 let Some(hir::Node::Item(hir::Item {
1558 kind: hir::ItemKind::Fn(sig, _, body_id),
1564 let body = hir.body(*body_id);
1565 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1566 let ty = trait_pred.skip_binder().self_ty();
1567 let is_object_safe = match ty.kind() {
1568 ty::Dynamic(predicates, _, ty::Dyn) => {
1569 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1572 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1574 // We only want to suggest `impl Trait` to `dyn Trait`s.
1575 // For example, `fn foo() -> str` needs to be filtered out.
1579 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1583 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1584 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1585 // Recursively look for `TraitObject` types and if there's only one, use that span to
1586 // suggest `impl Trait`.
1588 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1589 // otherwise suggest using `Box<dyn Trait>` or an enum.
1590 let mut visitor = ReturnsVisitor::default();
1591 visitor.visit_body(&body);
1593 let typeck_results = self.typeck_results.as_ref().unwrap();
1594 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1596 let ret_types = visitor
1599 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1600 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1601 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1603 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1605 let ty = self.resolve_vars_if_possible(ty);
1607 !matches!(ty.kind(), ty::Error(_))
1608 && last_ty.map_or(true, |last_ty| {
1609 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1610 // *after* in the dependency graph.
1611 match (ty.kind(), last_ty.kind()) {
1612 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1613 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1614 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1616 Infer(InferTy::FreshFloatTy(_)),
1617 Infer(InferTy::FreshFloatTy(_)),
1622 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1625 let mut spans_and_needs_box = vec![];
1627 match liberated_sig.output().kind() {
1628 ty::Dynamic(predicates, _, ty::Dyn) => {
1629 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1630 let param_env = ty::ParamEnv::empty();
1632 if !only_never_return {
1633 for (expr_span, return_ty) in ret_types {
1634 let self_ty_satisfies_dyn_predicates = |self_ty| {
1635 predicates.iter().all(|predicate| {
1636 let pred = predicate.with_self_ty(self.tcx, self_ty);
1637 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1638 self.predicate_may_hold(&obl)
1642 if let ty::Adt(def, substs) = return_ty.kind()
1644 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1646 spans_and_needs_box.push((expr_span, false));
1647 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1648 spans_and_needs_box.push((expr_span, true));
1658 let sm = self.tcx.sess.source_map();
1659 if !ret_ty.span.overlaps(span) {
1662 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1663 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1669 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1670 let name = liberated_sig.output().to_string();
1672 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1673 if !name.starts_with("dyn ") {
1679 err.code(error_code!(E0746));
1680 err.set_primary_message("return type cannot have an unboxed trait object");
1681 err.children.clear();
1682 let impl_trait_msg = "for information on `impl Trait`, see \
1683 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1684 #returning-types-that-implement-traits>";
1685 let trait_obj_msg = "for information on trait objects, see \
1686 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1687 #using-trait-objects-that-allow-for-values-of-different-types>";
1689 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1690 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1691 if only_never_return {
1692 // No return paths, probably using `panic!()` or similar.
1693 // Suggest `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1694 suggest_trait_object_return_type_alternatives(
1700 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1701 // Suggest `-> impl Trait`.
1702 err.span_suggestion(
1705 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1706 which implements `{1}`",
1709 format!("impl {}", trait_obj),
1710 Applicability::MachineApplicable,
1712 err.note(impl_trait_msg);
1715 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1716 err.multipart_suggestion(
1717 "return a boxed trait object instead",
1719 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1720 (span.shrink_to_hi(), ">".to_string()),
1722 Applicability::MaybeIncorrect,
1724 for (span, needs_box) in spans_and_needs_box {
1726 err.multipart_suggestion(
1727 "... and box this value",
1729 (span.shrink_to_lo(), "Box::new(".to_string()),
1730 (span.shrink_to_hi(), ")".to_string()),
1732 Applicability::MaybeIncorrect,
1737 // This is currently not possible to trigger because E0038 takes precedence, but
1738 // leave it in for completeness in case anything changes in an earlier stage.
1740 "if trait `{}` were object-safe, you could return a trait object",
1744 err.note(trait_obj_msg);
1746 "if all the returned values were of the same type you could use `impl {}` as the \
1750 err.note(impl_trait_msg);
1751 err.note("you can create a new `enum` with a variant for each returned type");
1756 fn point_at_returns_when_relevant(
1758 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1759 obligation: &PredicateObligation<'tcx>,
1761 match obligation.cause.code().peel_derives() {
1762 ObligationCauseCode::SizedReturnType => {}
1766 let hir = self.tcx.hir();
1767 let parent_node = hir.parent_id(obligation.cause.body_id);
1768 let node = hir.find(parent_node);
1769 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1772 let body = hir.body(*body_id);
1773 // Point at all the `return`s in the function as they have failed trait bounds.
1774 let mut visitor = ReturnsVisitor::default();
1775 visitor.visit_body(&body);
1776 let typeck_results = self.typeck_results.as_ref().unwrap();
1777 for expr in &visitor.returns {
1778 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1779 let ty = self.resolve_vars_if_possible(returned_ty);
1780 if ty.references_error() {
1781 // don't print out the [type error] here
1786 &format!("this returned value is of type `{}`", ty),
1794 fn report_closure_arg_mismatch(
1797 found_span: Option<Span>,
1798 found: ty::PolyTraitRef<'tcx>,
1799 expected: ty::PolyTraitRef<'tcx>,
1800 cause: &ObligationCauseCode<'tcx>,
1801 found_node: Option<Node<'_>>,
1802 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1803 pub(crate) fn build_fn_sig_ty<'tcx>(
1804 infcx: &InferCtxt<'tcx>,
1805 trait_ref: ty::PolyTraitRef<'tcx>,
1807 let inputs = trait_ref.skip_binder().substs.type_at(1);
1808 let sig = match inputs.kind() {
1809 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1810 infcx.tcx.mk_fn_sig(
1812 infcx.next_ty_var(TypeVariableOrigin {
1814 kind: TypeVariableOriginKind::MiscVariable,
1817 hir::Unsafety::Normal,
1821 _ => infcx.tcx.mk_fn_sig(
1822 std::iter::once(inputs),
1823 infcx.next_ty_var(TypeVariableOrigin {
1825 kind: TypeVariableOriginKind::MiscVariable,
1828 hir::Unsafety::Normal,
1833 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1836 let argument_kind = match expected.skip_binder().self_ty().kind() {
1837 ty::Closure(..) => "closure",
1838 ty::Generator(..) => "generator",
1841 let mut err = struct_span_err!(
1845 "type mismatch in {argument_kind} arguments",
1848 err.span_label(span, "expected due to this");
1850 let found_span = found_span.unwrap_or(span);
1851 err.span_label(found_span, "found signature defined here");
1853 let expected = build_fn_sig_ty(self, expected);
1854 let found = build_fn_sig_ty(self, found);
1856 let (expected_str, found_str) = self.cmp(expected, found);
1858 let signature_kind = format!("{argument_kind} signature");
1859 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1861 self.note_conflicting_closure_bounds(cause, &mut err);
1863 if let Some(found_node) = found_node {
1864 hint_missing_borrow(span, found, expected, found_node, &mut err);
1870 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1871 // requirements, which will always cause a closure to have a type error.
1872 fn note_conflicting_closure_bounds(
1874 cause: &ObligationCauseCode<'tcx>,
1875 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1877 // First, look for an `ExprBindingObligation`, which means we can get
1878 // the unsubstituted predicate list of the called function. And check
1879 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1880 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1881 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1882 && let Some(pred) = predicates.predicates.get(*idx)
1883 && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
1884 && self.tcx.is_fn_trait(trait_pred.def_id())
1887 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
1888 let expected_substs = self
1890 .anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.substs));
1892 // Find another predicate whose self-type is equal to the expected self type,
1893 // but whose substs don't match.
1894 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1896 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1897 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
1898 if self.tcx.is_fn_trait(trait_pred.def_id())
1900 // Make sure that the self type matches
1901 // (i.e. constraining this closure)
1903 == self.tcx.anonymize_bound_vars(
1904 pred.kind().rebind(trait_pred.self_ty()),
1906 // But the substs don't match (i.e. incompatible args)
1908 != self.tcx.anonymize_bound_vars(
1909 pred.kind().rebind(trait_pred.trait_ref.substs),
1916 // If we found one, then it's very likely the cause of the error.
1917 if let Some((_, (_, other_pred_span))) = other_pred {
1920 "closure inferred to have a different signature due to this bound",
1926 fn suggest_fully_qualified_path(
1928 err: &mut Diagnostic,
1933 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1934 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1936 "{}s cannot be accessed directly on a `trait`, they can only be \
1937 accessed through a specific `impl`",
1938 assoc_item.kind.as_def_kind().descr(item_def_id)
1940 err.span_suggestion(
1942 "use the fully qualified path to an implementation",
1943 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1944 Applicability::HasPlaceholders,
1950 /// Adds an async-await specific note to the diagnostic when the future does not implement
1951 /// an auto trait because of a captured type.
1954 /// note: future does not implement `Qux` as this value is used across an await
1955 /// --> $DIR/issue-64130-3-other.rs:17:5
1957 /// LL | let x = Foo;
1958 /// | - has type `Foo`
1959 /// LL | baz().await;
1960 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1962 /// | - `x` is later dropped here
1965 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1966 /// is "replaced" with a different message and a more specific error.
1969 /// error: future cannot be sent between threads safely
1970 /// --> $DIR/issue-64130-2-send.rs:21:5
1972 /// LL | fn is_send<T: Send>(t: T) { }
1973 /// | ---- required by this bound in `is_send`
1975 /// LL | is_send(bar());
1976 /// | ^^^^^^^ future returned by `bar` is not send
1978 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1979 /// implemented for `Foo`
1980 /// note: future is not send as this value is used across an await
1981 /// --> $DIR/issue-64130-2-send.rs:15:5
1983 /// LL | let x = Foo;
1984 /// | - has type `Foo`
1985 /// LL | baz().await;
1986 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1988 /// | - `x` is later dropped here
1991 /// Returns `true` if an async-await specific note was added to the diagnostic.
1992 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1993 fn maybe_note_obligation_cause_for_async_await(
1995 err: &mut Diagnostic,
1996 obligation: &PredicateObligation<'tcx>,
1998 let hir = self.tcx.hir();
2000 // Attempt to detect an async-await error by looking at the obligation causes, looking
2001 // for a generator to be present.
2003 // When a future does not implement a trait because of a captured type in one of the
2004 // generators somewhere in the call stack, then the result is a chain of obligations.
2006 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
2007 // future is passed as an argument to a function C which requires a `Send` type, then the
2008 // chain looks something like this:
2010 // - `BuiltinDerivedObligation` with a generator witness (B)
2011 // - `BuiltinDerivedObligation` with a generator (B)
2012 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2013 // - `BuiltinDerivedObligation` with a generator witness (A)
2014 // - `BuiltinDerivedObligation` with a generator (A)
2015 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2016 // - `BindingObligation` with `impl_send (Send requirement)
2018 // The first obligation in the chain is the most useful and has the generator that captured
2019 // the type. The last generator (`outer_generator` below) has information about where the
2020 // bound was introduced. At least one generator should be present for this diagnostic to be
2022 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
2023 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
2026 let mut generator = None;
2027 let mut outer_generator = None;
2028 let mut next_code = Some(obligation.cause.code());
2030 let mut seen_upvar_tys_infer_tuple = false;
2032 while let Some(code) = next_code {
2035 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
2036 next_code = Some(parent_code);
2038 ObligationCauseCode::ImplDerivedObligation(cause) => {
2039 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
2041 parent_trait_ref = ?cause.derived.parent_trait_pred,
2042 self_ty.kind = ?ty.kind(),
2047 ty::Generator(did, ..) => {
2048 generator = generator.or(Some(did));
2049 outer_generator = Some(did);
2051 ty::GeneratorWitness(..) => {}
2052 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2053 // By introducing a tuple of upvar types into the chain of obligations
2054 // of a generator, the first non-generator item is now the tuple itself,
2055 // we shall ignore this.
2057 seen_upvar_tys_infer_tuple = true;
2059 _ if generator.is_none() => {
2060 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
2061 target_ty = Some(ty);
2066 next_code = Some(&cause.derived.parent_code);
2068 ObligationCauseCode::DerivedObligation(derived_obligation)
2069 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
2070 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
2072 parent_trait_ref = ?derived_obligation.parent_trait_pred,
2073 self_ty.kind = ?ty.kind(),
2077 ty::Generator(did, ..) => {
2078 generator = generator.or(Some(did));
2079 outer_generator = Some(did);
2081 ty::GeneratorWitness(..) => {}
2082 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2083 // By introducing a tuple of upvar types into the chain of obligations
2084 // of a generator, the first non-generator item is now the tuple itself,
2085 // we shall ignore this.
2087 seen_upvar_tys_infer_tuple = true;
2089 _ if generator.is_none() => {
2090 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2091 target_ty = Some(ty);
2096 next_code = Some(&derived_obligation.parent_code);
2102 // Only continue if a generator was found.
2103 debug!(?generator, ?trait_ref, ?target_ty);
2104 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
2108 let span = self.tcx.def_span(generator_did);
2110 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
2113 ?generator_did_root,
2114 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2118 let generator_body = generator_did
2120 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2121 .map(|body_id| hir.body(body_id));
2122 let mut visitor = AwaitsVisitor::default();
2123 if let Some(body) = generator_body {
2124 visitor.visit_body(body);
2126 debug!(awaits = ?visitor.awaits);
2128 // Look for a type inside the generator interior that matches the target type to get
2130 let target_ty_erased = self.tcx.erase_regions(target_ty);
2131 let ty_matches = |ty| -> bool {
2132 // Careful: the regions for types that appear in the
2133 // generator interior are not generally known, so we
2134 // want to erase them when comparing (and anyway,
2135 // `Send` and other bounds are generally unaffected by
2136 // the choice of region). When erasing regions, we
2137 // also have to erase late-bound regions. This is
2138 // because the types that appear in the generator
2139 // interior generally contain "bound regions" to
2140 // represent regions that are part of the suspended
2141 // generator frame. Bound regions are preserved by
2142 // `erase_regions` and so we must also call
2143 // `erase_late_bound_regions`.
2144 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2145 let ty_erased = self.tcx.erase_regions(ty_erased);
2146 let eq = ty_erased == target_ty_erased;
2147 debug!(?ty_erased, ?target_ty_erased, ?eq);
2151 // Get the typeck results from the infcx if the generator is the function we are currently
2152 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2153 // cycles. If we can't use resolved types because the generator comes from another crate,
2154 // we still provide a targeted error but without all the relevant spans.
2155 let generator_data = match &self.typeck_results {
2156 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2157 _ if generator_did.is_local() => {
2158 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2160 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2161 GeneratorData::Foreign(generator_diag_data)
2166 let mut interior_or_upvar_span = None;
2168 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2169 debug!(?from_awaited_ty);
2171 // The generator interior types share the same binders
2172 if let Some(cause) =
2173 generator_data.get_generator_interior_types().skip_binder().iter().find(
2174 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2175 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2179 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2181 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2183 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2187 if interior_or_upvar_span.is_none() {
2188 interior_or_upvar_span =
2189 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2192 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2193 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2196 debug!(?interior_or_upvar_span);
2197 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2198 let is_async = self.tcx.generator_is_async(generator_did);
2199 let typeck_results = match generator_data {
2200 GeneratorData::Local(typeck_results) => Some(typeck_results),
2201 GeneratorData::Foreign(_) => None,
2203 self.note_obligation_cause_for_async_await(
2205 interior_or_upvar_span,
2220 /// Unconditionally adds the diagnostic note described in
2221 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2222 #[instrument(level = "debug", skip_all)]
2223 fn note_obligation_cause_for_async_await(
2225 err: &mut Diagnostic,
2226 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2228 outer_generator: Option<DefId>,
2229 trait_pred: ty::TraitPredicate<'tcx>,
2230 target_ty: Ty<'tcx>,
2231 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2232 obligation: &PredicateObligation<'tcx>,
2233 next_code: Option<&ObligationCauseCode<'tcx>>,
2235 let source_map = self.tcx.sess.source_map();
2237 let (await_or_yield, an_await_or_yield) =
2238 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2239 let future_or_generator = if is_async { "future" } else { "generator" };
2241 // Special case the primary error message when send or sync is the trait that was
2243 let hir = self.tcx.hir();
2244 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2245 self.tcx.get_diagnostic_name(trait_pred.def_id())
2247 let (trait_name, trait_verb) =
2248 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2251 err.set_primary_message(format!(
2252 "{} cannot be {} between threads safely",
2253 future_or_generator, trait_verb
2256 let original_span = err.span.primary_span().unwrap();
2257 let mut span = MultiSpan::from_span(original_span);
2259 let message = outer_generator
2260 .and_then(|generator_did| {
2261 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2262 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2263 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2265 .parent(generator_did)
2267 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2268 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2270 format!("future returned by `{}` is not {}", name, trait_name)
2272 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2273 format!("future created by async block is not {}", trait_name)
2275 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2276 format!("future created by async closure is not {}", trait_name)
2280 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2282 span.push_span_label(original_span, message);
2285 format!("is not {}", trait_name)
2287 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2290 let mut explain_yield =
2291 |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
2292 let mut span = MultiSpan::from_span(yield_span);
2293 let snippet = match source_map.span_to_snippet(interior_span) {
2294 // #70935: If snippet contains newlines, display "the value" instead
2295 // so that we do not emit complex diagnostics.
2296 Ok(snippet) if !snippet.contains('\n') => format!("`{}`", snippet),
2297 _ => "the value".to_string(),
2299 // note: future is not `Send` as this value is used across an await
2300 // --> $DIR/issue-70935-complex-spans.rs:13:9
2302 // LL | baz(|| async {
2303 // | ______________-
2306 // LL | | foo(tx.clone());
2308 // | | - ^^^^^^ await occurs here, with value maybe used later
2310 // | has type `closure` which is not `Send`
2311 // note: value is later dropped here
2315 span.push_span_label(
2317 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2319 span.push_span_label(
2321 format!("has type `{}` which {}", target_ty, trait_explanation),
2323 if let Some(scope_span) = scope_span {
2324 let scope_span = source_map.end_point(scope_span);
2326 let msg = format!("{} is later dropped here", snippet);
2327 span.push_span_label(scope_span, msg);
2332 "{} {} as this value is used across {}",
2333 future_or_generator, trait_explanation, an_await_or_yield
2337 match interior_or_upvar_span {
2338 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2339 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2340 if let Some(await_span) = from_awaited_ty {
2341 // The type causing this obligation is one being awaited at await_span.
2342 let mut span = MultiSpan::from_span(await_span);
2343 span.push_span_label(
2346 "await occurs here on type `{}`, which {}",
2347 target_ty, trait_explanation
2353 "future {not_trait} as it awaits another future which {not_trait}",
2354 not_trait = trait_explanation
2358 // Look at the last interior type to get a span for the `.await`.
2360 generator_interior_types = ?format_args!(
2361 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2364 explain_yield(interior_span, yield_span, scope_span);
2367 if let Some(expr_id) = expr {
2368 let expr = hir.expect_expr(expr_id);
2369 debug!("target_ty evaluated from {:?}", expr);
2371 let parent = hir.parent_id(expr_id);
2372 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2373 let parent_span = hir.span(parent);
2374 let parent_did = parent.owner.to_def_id();
2377 // fn foo(&self) -> i32 {}
2380 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2383 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2385 .expr_adjustments(expr)
2387 .any(|adj| adj.is_region_borrow())
2393 // struct Foo(*const u8);
2394 // bar(Foo(std::ptr::null())).await;
2395 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2397 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2398 let is_raw_borrow_inside_fn_like_call =
2399 match self.tcx.def_kind(parent_did) {
2400 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2403 if let Some(typeck_results) = typeck_results {
2404 if (typeck_results.is_method_call(e) && is_region_borrow)
2405 || is_raw_borrow_inside_fn_like_call
2409 "consider moving this into a `let` \
2410 binding to create a shorter lived borrow",
2418 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2419 // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
2420 let non_send = match target_ty.kind() {
2421 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(&obligation) {
2422 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2428 let (span_label, span_note) = match non_send {
2429 // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
2430 // include suggestions to make `T: Sync` so that `&T: Send`,
2431 // or to make `T: Send` so that `&mut T: Send`
2432 Some((ref_ty, is_mut)) => {
2433 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2434 let ref_kind = if is_mut { "&mut" } else { "&" };
2437 "has type `{}` which {}, because `{}` is not `{}`",
2438 target_ty, trait_explanation, ref_ty, ref_ty_trait
2441 "captured value {} because `{}` references cannot be sent unless their referent is `{}`",
2442 trait_explanation, ref_kind, ref_ty_trait
2447 format!("has type `{}` which {}", target_ty, trait_explanation),
2448 format!("captured value {}", trait_explanation),
2452 let mut span = MultiSpan::from_span(upvar_span);
2453 span.push_span_label(upvar_span, span_label);
2454 err.span_note(span, &span_note);
2458 // Add a note for the item obligation that remains - normally a note pointing to the
2459 // bound that introduced the obligation (e.g. `T: Send`).
2461 self.note_obligation_cause_code(
2463 obligation.predicate,
2464 obligation.param_env,
2467 &mut Default::default(),
2471 fn note_obligation_cause_code<T>(
2473 err: &mut Diagnostic,
2475 param_env: ty::ParamEnv<'tcx>,
2476 cause_code: &ObligationCauseCode<'tcx>,
2477 obligated_types: &mut Vec<Ty<'tcx>>,
2478 seen_requirements: &mut FxHashSet<DefId>,
2480 T: ToPredicate<'tcx>,
2483 let predicate = predicate.to_predicate(tcx);
2485 ObligationCauseCode::ExprAssignable
2486 | ObligationCauseCode::MatchExpressionArm { .. }
2487 | ObligationCauseCode::Pattern { .. }
2488 | ObligationCauseCode::IfExpression { .. }
2489 | ObligationCauseCode::IfExpressionWithNoElse
2490 | ObligationCauseCode::MainFunctionType
2491 | ObligationCauseCode::StartFunctionType
2492 | ObligationCauseCode::IntrinsicType
2493 | ObligationCauseCode::MethodReceiver
2494 | ObligationCauseCode::ReturnNoExpression
2495 | ObligationCauseCode::UnifyReceiver(..)
2496 | ObligationCauseCode::OpaqueType
2497 | ObligationCauseCode::MiscObligation
2498 | ObligationCauseCode::WellFormed(..)
2499 | ObligationCauseCode::MatchImpl(..)
2500 | ObligationCauseCode::ReturnType
2501 | ObligationCauseCode::ReturnValue(_)
2502 | ObligationCauseCode::BlockTailExpression(_)
2503 | ObligationCauseCode::AwaitableExpr(_)
2504 | ObligationCauseCode::ForLoopIterator
2505 | ObligationCauseCode::QuestionMark
2506 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2507 | ObligationCauseCode::LetElse
2508 | ObligationCauseCode::BinOp { .. }
2509 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2510 | ObligationCauseCode::RustCall => {}
2511 ObligationCauseCode::SliceOrArrayElem => {
2512 err.note("slice and array elements must have `Sized` type");
2514 ObligationCauseCode::TupleElem => {
2515 err.note("only the last element of a tuple may have a dynamically sized type");
2517 ObligationCauseCode::ProjectionWf(data) => {
2518 err.note(&format!("required so that the projection `{data}` is well-formed"));
2520 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2522 "required so that reference `{ref_ty}` does not outlive its referent"
2525 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2527 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2531 ObligationCauseCode::ItemObligation(_)
2532 | ObligationCauseCode::ExprItemObligation(..) => {
2533 // We hold the `DefId` of the item introducing the obligation, but displaying it
2534 // doesn't add user usable information. It always point at an associated item.
2536 ObligationCauseCode::BindingObligation(item_def_id, span)
2537 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2538 let item_name = tcx.def_path_str(item_def_id);
2539 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2540 let mut multispan = MultiSpan::from(span);
2541 let sm = tcx.sess.source_map();
2542 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2544 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2545 (Ok(l), Ok(r)) => l.line == r.line,
2548 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2549 multispan.push_span_label(ident.span, "required by a bound in this");
2552 let descr = format!("required by a bound in `{item_name}`");
2553 if span.is_visible(sm) {
2554 let msg = format!("required by this bound in `{short_item_name}`");
2555 multispan.push_span_label(span, msg);
2556 err.span_note(multispan, &descr);
2558 err.span_note(tcx.def_span(item_def_id), &descr);
2561 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2563 "required for the cast from `{}` to the object type `{}`",
2564 self.ty_to_string(concrete_ty),
2565 self.ty_to_string(object_ty)
2568 ObligationCauseCode::Coercion { source: _, target } => {
2569 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2571 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2573 "the `Copy` trait is required because this value will be copied for each element of the array",
2578 "consider creating a new `const` item and initializing it with the result \
2579 of the function call to be used in the repeat position, like \
2580 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2584 if self.tcx.sess.is_nightly_build() && is_const_fn {
2586 "create an inline `const` block, see RFC #2920 \
2587 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2591 ObligationCauseCode::VariableType(hir_id) => {
2592 let parent_node = self.tcx.hir().parent_id(hir_id);
2593 match self.tcx.hir().find(parent_node) {
2594 Some(Node::Local(hir::Local { ty: Some(ty), .. })) => {
2595 err.span_suggestion_verbose(
2596 ty.span.shrink_to_lo(),
2597 "consider borrowing here",
2599 Applicability::MachineApplicable,
2601 err.note("all local variables must have a statically known size");
2603 Some(Node::Local(hir::Local {
2604 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2607 // When encountering an assignment of an unsized trait, like
2608 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2609 // order to use have a slice instead.
2610 err.span_suggestion_verbose(
2611 span.shrink_to_lo(),
2612 "consider borrowing here",
2614 Applicability::MachineApplicable,
2616 err.note("all local variables must have a statically known size");
2618 Some(Node::Param(param)) => {
2619 err.span_suggestion_verbose(
2620 param.ty_span.shrink_to_lo(),
2621 "function arguments must have a statically known size, borrowed types \
2622 always have a known size",
2624 Applicability::MachineApplicable,
2628 err.note("all local variables must have a statically known size");
2631 if !self.tcx.features().unsized_locals {
2632 err.help("unsized locals are gated as an unstable feature");
2635 ObligationCauseCode::SizedArgumentType(sp) => {
2636 if let Some(span) = sp {
2637 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder()
2638 && let ty::Clause::Trait(trait_pred) = clause
2639 && let ty::Dynamic(..) = trait_pred.self_ty().kind()
2641 let span = if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2642 && snippet.starts_with("dyn ")
2644 let pos = snippet.len() - snippet[3..].trim_start().len();
2645 span.with_hi(span.lo() + BytePos(pos as u32))
2649 err.span_suggestion_verbose(
2651 "you can use `impl Trait` as the argument type",
2652 "impl ".to_string(),
2653 Applicability::MaybeIncorrect,
2656 err.span_suggestion_verbose(
2657 span.shrink_to_lo(),
2658 "function arguments must have a statically known size, borrowed types \
2659 always have a known size",
2661 Applicability::MachineApplicable,
2664 err.note("all function arguments must have a statically known size");
2666 if tcx.sess.opts.unstable_features.is_nightly_build()
2667 && !self.tcx.features().unsized_fn_params
2669 err.help("unsized fn params are gated as an unstable feature");
2672 ObligationCauseCode::SizedReturnType => {
2673 err.note("the return type of a function must have a statically known size");
2675 ObligationCauseCode::SizedYieldType => {
2676 err.note("the yield type of a generator must have a statically known size");
2678 ObligationCauseCode::SizedBoxType => {
2679 err.note("the type of a box expression must have a statically known size");
2681 ObligationCauseCode::AssignmentLhsSized => {
2682 err.note("the left-hand-side of an assignment must have a statically known size");
2684 ObligationCauseCode::TupleInitializerSized => {
2685 err.note("tuples must have a statically known size to be initialized");
2687 ObligationCauseCode::StructInitializerSized => {
2688 err.note("structs must have a statically known size to be initialized");
2690 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2692 AdtKind::Struct => {
2695 "the last field of a packed struct may only have a \
2696 dynamically sized type if it does not need drop to be run",
2700 "only the last field of a struct may have a dynamically sized type",
2705 err.note("no field of a union may have a dynamically sized type");
2708 err.note("no field of an enum variant may have a dynamically sized type");
2711 err.help("change the field's type to have a statically known size");
2712 err.span_suggestion(
2713 span.shrink_to_lo(),
2714 "borrowed types always have a statically known size",
2716 Applicability::MachineApplicable,
2718 err.multipart_suggestion(
2719 "the `Box` type always has a statically known size and allocates its contents \
2722 (span.shrink_to_lo(), "Box<".to_string()),
2723 (span.shrink_to_hi(), ">".to_string()),
2725 Applicability::MachineApplicable,
2728 ObligationCauseCode::ConstSized => {
2729 err.note("constant expressions must have a statically known size");
2731 ObligationCauseCode::InlineAsmSized => {
2732 err.note("all inline asm arguments must have a statically known size");
2734 ObligationCauseCode::ConstPatternStructural => {
2735 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2737 ObligationCauseCode::SharedStatic => {
2738 err.note("shared static variables must have a type that implements `Sync`");
2740 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2741 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2742 let ty = parent_trait_ref.skip_binder().self_ty();
2743 if parent_trait_ref.references_error() {
2744 // NOTE(eddyb) this was `.cancel()`, but `err`
2745 // is borrowed, so we can't fully defuse it.
2746 err.downgrade_to_delayed_bug();
2750 // If the obligation for a tuple is set directly by a Generator or Closure,
2751 // then the tuple must be the one containing capture types.
2752 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2755 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2757 let parent_trait_ref =
2758 self.resolve_vars_if_possible(data.parent_trait_pred);
2759 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2760 matches!(nested_ty.kind(), ty::Generator(..))
2761 || matches!(nested_ty.kind(), ty::Closure(..))
2767 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2769 // Don't print the tuple of capture types
2771 if !is_upvar_tys_infer_tuple {
2772 let msg = with_forced_trimmed_paths!(format!(
2773 "required because it appears within the type `{ty}`",
2776 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2777 Some(ident) => err.span_note(ident.span, &msg),
2778 None => err.note(&msg),
2780 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
2781 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2782 if tcx.parent(*def_id) == identity_future {
2786 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2787 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2788 let is_future = tcx.ty_is_opaque_future(ty);
2792 "note_obligation_cause_code: check for async fn"
2795 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2796 ty::Generator(last_def_id, ..) => {
2797 tcx.generator_is_async(*last_def_id)
2804 err.span_note(self.tcx.def_span(def_id), &msg)
2806 ty::GeneratorWitness(bound_tys) => {
2807 use std::fmt::Write;
2809 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2810 // Maybe we should just remove this note altogether?
2811 // FIXME: only print types which don't meet the trait requirement
2813 "required because it captures the following types: ".to_owned();
2814 for ty in bound_tys.skip_binder() {
2815 with_forced_trimmed_paths!(write!(msg, "`{}`, ", ty).unwrap());
2817 err.note(msg.trim_end_matches(", "))
2819 ty::Generator(def_id, _, _) => {
2820 let sp = self.tcx.def_span(def_id);
2822 // Special-case this to say "async block" instead of `[static generator]`.
2823 let kind = tcx.generator_kind(def_id).unwrap().descr();
2826 with_forced_trimmed_paths!(&format!(
2827 "required because it's used within this {kind}",
2831 ty::Closure(def_id, _) => err.span_note(
2832 self.tcx.def_span(def_id),
2833 "required because it's used within this closure",
2835 _ => err.note(&msg),
2840 obligated_types.push(ty);
2842 let parent_predicate = parent_trait_ref;
2843 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2844 // #74711: avoid a stack overflow
2845 ensure_sufficient_stack(|| {
2846 self.note_obligation_cause_code(
2856 ensure_sufficient_stack(|| {
2857 self.note_obligation_cause_code(
2861 cause_code.peel_derives(),
2868 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2869 let mut parent_trait_pred =
2870 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2871 parent_trait_pred.remap_constness_diag(param_env);
2872 let parent_def_id = parent_trait_pred.def_id();
2873 let (self_ty, file) =
2874 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2876 "required for `{self_ty}` to implement `{}`",
2877 parent_trait_pred.print_modifiers_and_trait_path()
2879 let mut is_auto_trait = false;
2880 match self.tcx.hir().get_if_local(data.impl_def_id) {
2881 Some(Node::Item(hir::Item {
2882 kind: hir::ItemKind::Trait(is_auto, ..),
2886 // FIXME: we should do something else so that it works even on crate foreign
2888 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2889 err.span_note(ident.span, &msg)
2891 Some(Node::Item(hir::Item {
2892 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2895 let mut spans = Vec::with_capacity(2);
2896 if let Some(trait_ref) = of_trait {
2897 spans.push(trait_ref.path.span);
2899 spans.push(self_ty.span);
2900 err.span_note(spans, &msg)
2902 _ => err.note(&msg),
2905 if let Some(file) = file {
2907 "the full type name has been written to '{}'",
2911 let mut parent_predicate = parent_trait_pred;
2912 let mut data = &data.derived;
2914 seen_requirements.insert(parent_def_id);
2916 // We don't want to point at the ADT saying "required because it appears within
2917 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2918 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2921 let child_trait_ref =
2922 self.resolve_vars_if_possible(derived.parent_trait_pred);
2923 let child_def_id = child_trait_ref.def_id();
2924 if seen_requirements.insert(child_def_id) {
2928 parent_predicate = child_trait_ref.to_predicate(tcx);
2929 parent_trait_pred = child_trait_ref;
2932 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2933 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2934 let child_trait_pred =
2935 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2936 let child_def_id = child_trait_pred.def_id();
2937 if seen_requirements.insert(child_def_id) {
2941 data = &child.derived;
2942 parent_predicate = child_trait_pred.to_predicate(tcx);
2943 parent_trait_pred = child_trait_pred;
2947 "{} redundant requirement{} hidden",
2951 let (self_ty, file) =
2952 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2954 "required for `{self_ty}` to implement `{}`",
2955 parent_trait_pred.print_modifiers_and_trait_path()
2957 if let Some(file) = file {
2959 "the full type name has been written to '{}'",
2964 // #74711: avoid a stack overflow
2965 ensure_sufficient_stack(|| {
2966 self.note_obligation_cause_code(
2976 ObligationCauseCode::DerivedObligation(ref data) => {
2977 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2978 let parent_predicate = parent_trait_ref;
2979 // #74711: avoid a stack overflow
2980 ensure_sufficient_stack(|| {
2981 self.note_obligation_cause_code(
2991 ObligationCauseCode::FunctionArgumentObligation {
2997 self.note_function_argument_obligation(
3005 ensure_sufficient_stack(|| {
3006 self.note_obligation_cause_code(
3016 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
3017 let item_name = self.tcx.item_name(trait_item_def_id);
3019 "the requirement `{predicate}` appears on the `impl`'s {kind} \
3020 `{item_name}` but not on the corresponding trait's {kind}",
3024 .opt_item_ident(trait_item_def_id)
3026 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
3027 let mut assoc_span: MultiSpan = sp.into();
3028 assoc_span.push_span_label(
3030 format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
3032 if let Some(ident) = self
3034 .opt_associated_item(trait_item_def_id)
3035 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
3037 assoc_span.push_span_label(ident.span, "in this trait");
3039 err.span_note(assoc_span, &msg);
3041 ObligationCauseCode::TrivialBound => {
3042 err.help("see issue #48214");
3043 if tcx.sess.opts.unstable_features.is_nightly_build() {
3044 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
3047 ObligationCauseCode::OpaqueReturnType(expr_info) => {
3048 if let Some((expr_ty, expr_span)) = expr_info {
3049 let expr_ty = with_forced_trimmed_paths!(self.ty_to_string(expr_ty));
3052 with_forced_trimmed_paths!(format!(
3053 "return type was inferred to be `{expr_ty}` here",
3062 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
3064 fn suggest_await_before_try(
3066 err: &mut Diagnostic,
3067 obligation: &PredicateObligation<'tcx>,
3068 trait_pred: ty::PolyTraitPredicate<'tcx>,
3071 let body_hir_id = obligation.cause.body_id;
3072 let item_id = self.tcx.hir().parent_id(body_hir_id);
3074 if let Some(body_id) =
3075 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
3077 let body = self.tcx.hir().body(body_id);
3078 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
3079 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
3081 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3082 let impls_future = self.type_implements_trait(
3084 [self.tcx.erase_late_bound_regions(self_ty)],
3085 obligation.param_env,
3087 if !impls_future.must_apply_modulo_regions() {
3091 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3092 // `<T as Future>::Output`
3093 let projection_ty = trait_pred.map_bound(|trait_pred| {
3094 self.tcx.mk_projection(
3096 // Future::Output has no substs
3097 [trait_pred.self_ty()],
3100 let InferOk { value: projection_ty, .. } =
3101 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3104 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3106 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3107 obligation.param_env,
3108 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3110 debug!(try_trait_obligation = ?try_obligation);
3111 if self.predicate_may_hold(&try_obligation)
3112 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3113 && snippet.ends_with('?')
3115 err.span_suggestion_verbose(
3116 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3117 "consider `await`ing on the `Future`",
3119 Applicability::MaybeIncorrect,
3126 fn suggest_floating_point_literal(
3128 obligation: &PredicateObligation<'tcx>,
3129 err: &mut Diagnostic,
3130 trait_ref: &ty::PolyTraitRef<'tcx>,
3132 let rhs_span = match obligation.cause.code() {
3133 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3136 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3137 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3139 err.span_suggestion_verbose(
3140 rhs_span.shrink_to_hi(),
3141 "consider using a floating-point literal by writing it with `.0`",
3143 Applicability::MaybeIncorrect,
3150 obligation: &PredicateObligation<'tcx>,
3151 err: &mut Diagnostic,
3152 trait_pred: ty::PolyTraitPredicate<'tcx>,
3154 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3157 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3158 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3162 let is_derivable_trait = match diagnostic_name {
3163 sym::Default => !adt.is_enum(),
3164 sym::PartialEq | sym::PartialOrd => {
3165 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3166 trait_pred.skip_binder().self_ty() == rhs_ty
3168 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3171 is_derivable_trait &&
3172 // Ensure all fields impl the trait.
3173 adt.all_fields().all(|field| {
3174 let field_ty = field.ty(self.tcx, substs);
3175 let trait_substs = match diagnostic_name {
3176 sym::PartialEq | sym::PartialOrd => {
3181 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3182 trait_ref: self.tcx.mk_trait_ref(
3183 trait_pred.def_id(),
3184 [field_ty].into_iter().chain(trait_substs),
3188 let field_obl = Obligation::new(
3190 obligation.cause.clone(),
3191 obligation.param_env,
3194 self.predicate_must_hold_modulo_regions(&field_obl)
3198 err.span_suggestion_verbose(
3199 self.tcx.def_span(adt.did()).shrink_to_lo(),
3201 "consider annotating `{}` with `#[derive({})]`",
3202 trait_pred.skip_binder().self_ty(),
3205 format!("#[derive({})]\n", diagnostic_name),
3206 Applicability::MaybeIncorrect,
3211 fn suggest_dereferencing_index(
3213 obligation: &PredicateObligation<'tcx>,
3214 err: &mut Diagnostic,
3215 trait_pred: ty::PolyTraitPredicate<'tcx>,
3217 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3218 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3219 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3220 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3221 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3223 err.span_suggestion_verbose(
3224 obligation.cause.span.shrink_to_lo(),
3225 "dereference this index",
3227 Applicability::MachineApplicable,
3231 fn note_function_argument_obligation(
3234 err: &mut Diagnostic,
3235 parent_code: &ObligationCauseCode<'tcx>,
3236 param_env: ty::ParamEnv<'tcx>,
3237 failed_pred: ty::Predicate<'tcx>,
3241 let hir = tcx.hir();
3242 if let Some(Node::Expr(expr)) = hir.find(arg_hir_id)
3243 && let Some(typeck_results) = &self.typeck_results
3245 if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
3246 let expr = expr.peel_blocks();
3247 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
3248 let span = expr.span;
3249 if Some(span) != err.span.primary_span() {
3252 if ty.references_error() {
3255 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3256 format!("this tail expression is of type `{ty}`")
3262 // FIXME: visit the ty to see if there's any closure involved, and if there is,
3263 // check whether its evaluated return type is the same as the one corresponding
3264 // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3265 // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3266 let mut type_diffs = vec![];
3268 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
3269 && let Some(node_substs) = typeck_results.node_substs_opt(call_hir_id)
3270 && let where_clauses = self.tcx.predicates_of(def_id).instantiate(self.tcx, node_substs)
3271 && let Some(where_pred) = where_clauses.predicates.get(*idx)
3273 if let Some(where_pred) = where_pred.to_opt_poly_trait_pred()
3274 && let Some(failed_pred) = failed_pred.to_opt_poly_trait_pred()
3276 let mut c = CollectAllMismatches {
3281 if let Ok(_) = c.relate(where_pred, failed_pred) {
3282 type_diffs = c.errors;
3284 } else if let Some(where_pred) = where_pred.to_opt_poly_projection_pred()
3285 && let Some(failed_pred) = failed_pred.to_opt_poly_projection_pred()
3286 && let Some(found) = failed_pred.skip_binder().term.ty()
3289 Sorts(ty::error::ExpectedFound {
3290 expected: self.tcx.mk_ty(ty::Alias(ty::Projection, where_pred.skip_binder().projection_ty)),
3296 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3297 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3298 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3299 && let parent_hir_id = self.tcx.hir().parent_id(binding.hir_id)
3300 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3301 && let Some(binding_expr) = local.init
3303 // If the expression we're calling on is a binding, we want to point at the
3304 // `let` when talking about the type. Otherwise we'll point at every part
3305 // of the method chain with the type.
3306 self.point_at_chain(binding_expr, &typeck_results, type_diffs, param_env, err);
3308 self.point_at_chain(expr, &typeck_results, type_diffs, param_env, err);
3311 let call_node = hir.find(call_hir_id);
3312 if let Some(Node::Expr(hir::Expr {
3313 kind: hir::ExprKind::MethodCall(path, rcvr, ..), ..
3316 if Some(rcvr.span) == err.span.primary_span() {
3317 err.replace_span_with(path.ident.span, true);
3320 if let Some(Node::Expr(hir::Expr {
3322 hir::ExprKind::Call(hir::Expr { span, .. }, _)
3323 | hir::ExprKind::MethodCall(hir::PathSegment { ident: Ident { span, .. }, .. }, ..),
3325 })) = hir.find(call_hir_id)
3327 if Some(*span) != err.span.primary_span() {
3328 err.span_label(*span, "required by a bound introduced by this call");
3335 expr: &hir::Expr<'_>,
3336 typeck_results: &TypeckResults<'tcx>,
3337 type_diffs: Vec<TypeError<'tcx>>,
3338 param_env: ty::ParamEnv<'tcx>,
3339 err: &mut Diagnostic,
3341 let mut primary_spans = vec![];
3342 let mut span_labels = vec![];
3346 let mut print_root_expr = true;
3347 let mut assocs = vec![];
3348 let mut expr = expr;
3349 let mut prev_ty = self.resolve_vars_if_possible(
3350 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3352 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) = expr.kind {
3353 // Point at every method call in the chain with the resulting type.
3354 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3355 // ^^^^^^ ^^^^^^^^^^^
3357 let assocs_in_this_method =
3358 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
3359 assocs.push(assocs_in_this_method);
3360 prev_ty = self.resolve_vars_if_possible(
3361 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3364 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3365 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3366 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3367 && let Some(parent) = self.tcx.hir().find_parent(binding.hir_id)
3369 // We've reached the root of the method call chain...
3370 if let hir::Node::Local(local) = parent
3371 && let Some(binding_expr) = local.init
3373 // ...and it is a binding. Get the binding creation and continue the chain.
3374 expr = binding_expr;
3376 if let hir::Node::Param(param) = parent {
3377 // ...and it is a an fn argument.
3378 let prev_ty = self.resolve_vars_if_possible(
3379 typeck_results.node_type_opt(param.hir_id).unwrap_or(tcx.ty_error()),
3381 let assocs_in_this_method = self.probe_assoc_types_at_expr(&type_diffs, param.ty_span, prev_ty, param.hir_id, param_env);
3382 if assocs_in_this_method.iter().any(|a| a.is_some()) {
3383 assocs.push(assocs_in_this_method);
3384 print_root_expr = false;
3390 // We want the type before deref coercions, otherwise we talk about `&[_]`
3391 // instead of `Vec<_>`.
3392 if let Some(ty) = typeck_results.expr_ty_opt(expr) && print_root_expr {
3393 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3394 // Point at the root expression
3395 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3397 span_labels.push((expr.span, format!("this expression has type `{ty}`")));
3399 // Only show this if it is not a "trivial" expression (not a method
3400 // chain) and there are associated types to talk about.
3401 let mut assocs = assocs.into_iter().peekable();
3402 while let Some(assocs_in_method) = assocs.next() {
3403 let Some(prev_assoc_in_method) = assocs.peek() else {
3404 for entry in assocs_in_method {
3405 let Some((span, (assoc, ty))) = entry else { continue; };
3406 if primary_spans.is_empty() || type_diffs.iter().any(|diff| {
3407 let Sorts(expected_found) = diff else { return false; };
3408 self.can_eq(param_env, expected_found.found, ty).is_ok()
3410 // FIXME: this doesn't quite work for `Iterator::collect`
3411 // because we have `Vec<i32>` and `()`, but we'd want `i32`
3412 // to point at the `.into_iter()` call, but as long as we
3413 // still point at the other method calls that might have
3414 // introduced the issue, this is fine for now.
3415 primary_spans.push(span);
3419 with_forced_trimmed_paths!(format!(
3420 "`{}` is `{ty}` here",
3421 self.tcx.def_path_str(assoc),
3427 for (entry, prev_entry) in
3428 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
3430 match (entry, prev_entry) {
3431 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
3432 let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
3434 let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
3435 if self.can_eq(param_env, ty, *prev_ty).is_err() {
3436 if type_diffs.iter().any(|diff| {
3437 let Sorts(expected_found) = diff else { return false; };
3438 self.can_eq(param_env, expected_found.found, ty).is_ok()
3440 primary_spans.push(span);
3443 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
3445 span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
3448 (Some((span, (assoc, ty))), None) => {
3451 with_forced_trimmed_paths!(format!(
3452 "`{}` is `{}` here",
3453 self.tcx.def_path_str(assoc),
3454 self.ty_to_string(ty),
3458 (None, Some(_)) | (None, None) => {}
3462 if !primary_spans.is_empty() {
3463 let mut multi_span: MultiSpan = primary_spans.into();
3464 for (span, label) in span_labels {
3465 multi_span.push_span_label(span, label);
3469 "the method call chain might not have had the expected associated types",
3474 fn probe_assoc_types_at_expr(
3476 type_diffs: &[TypeError<'tcx>],
3479 body_id: hir::HirId,
3480 param_env: ty::ParamEnv<'tcx>,
3481 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
3482 let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
3483 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
3484 for diff in type_diffs {
3485 let Sorts(expected_found) = diff else { continue; };
3486 let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; };
3488 let origin = TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span };
3489 let trait_def_id = proj.trait_def_id(self.tcx);
3490 // Make `Self` be equivalent to the type of the call chain
3491 // expression we're looking at now, so that we can tell what
3492 // for example `Iterator::Item` is at this point in the chain.
3493 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
3495 ty::GenericParamDefKind::Type { .. } => {
3496 if param.index == 0 {
3497 return prev_ty.into();
3500 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Const { .. } => {}
3502 self.var_for_def(span, param)
3504 // This will hold the resolved type of the associated type, if the
3505 // current expression implements the trait that associated type is
3506 // in. For example, this would be what `Iterator::Item` is here.
3507 let ty_var = self.infcx.next_ty_var(origin);
3508 // This corresponds to `<ExprTy as Iterator>::Item = _`.
3509 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::Projection(
3510 ty::ProjectionPredicate {
3511 projection_ty: self.tcx.mk_alias_ty(proj.def_id, substs),
3512 term: ty_var.into(),
3515 // Add `<ExprTy as Iterator>::Item = _` obligation.
3516 ocx.register_obligation(Obligation::misc(
3517 self.tcx, span, body_id, param_env, projection,
3519 if ocx.select_where_possible().is_empty() {
3520 // `ty_var` now holds the type that `Item` is for `ExprTy`.
3521 let ty_var = self.resolve_vars_if_possible(ty_var);
3522 assocs_in_this_method.push(Some((span, (proj.def_id, ty_var))));
3524 // `<ExprTy as Iterator>` didn't select, so likely we've
3525 // reached the end of the iterator chain, like the originating
3527 // Keep the space consistent for later zipping.
3528 assocs_in_this_method.push(None);
3531 assocs_in_this_method
3535 /// Add a hint to add a missing borrow or remove an unnecessary one.
3536 fn hint_missing_borrow<'tcx>(
3540 found_node: Node<'_>,
3541 err: &mut Diagnostic,
3543 let found_args = match found.kind() {
3544 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3546 span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
3549 let expected_args = match expected.kind() {
3550 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3552 span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
3556 // This could be a variant constructor, for example.
3557 let Some(fn_decl) = found_node.fn_decl() else { return; };
3559 let arg_spans = fn_decl.inputs.iter().map(|ty| ty.span);
3561 fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, usize) {
3564 while let ty::Ref(_, new_ty, _) = ty.kind() {
3572 let mut to_borrow = Vec::new();
3573 let mut remove_borrow = Vec::new();
3575 for ((found_arg, expected_arg), arg_span) in found_args.zip(expected_args).zip(arg_spans) {
3576 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
3577 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
3579 if found_ty == expected_ty {
3580 if found_refs < expected_refs {
3581 to_borrow.push((arg_span, expected_arg.to_string()));
3582 } else if found_refs > expected_refs {
3583 remove_borrow.push((arg_span, expected_arg.to_string()));
3588 if !to_borrow.is_empty() {
3589 err.multipart_suggestion(
3590 "consider borrowing the argument",
3592 Applicability::MaybeIncorrect,
3596 if !remove_borrow.is_empty() {
3597 err.multipart_suggestion(
3598 "do not borrow the argument",
3600 Applicability::MaybeIncorrect,
3605 /// Collect all the returned expressions within the input expression.
3606 /// Used to point at the return spans when we want to suggest some change to them.
3608 pub struct ReturnsVisitor<'v> {
3609 pub returns: Vec<&'v hir::Expr<'v>>,
3610 in_block_tail: bool,
3613 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3614 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3615 // Visit every expression to detect `return` paths, either through the function's tail
3616 // expression or `return` statements. We walk all nodes to find `return` statements, but
3617 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3618 // they're in the return path of the function body.
3620 hir::ExprKind::Ret(Some(ex)) => {
3621 self.returns.push(ex);
3623 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3624 self.in_block_tail = false;
3625 for stmt in block.stmts {
3626 hir::intravisit::walk_stmt(self, stmt);
3628 self.in_block_tail = true;
3629 if let Some(expr) = block.expr {
3630 self.visit_expr(expr);
3633 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3634 self.visit_expr(then);
3635 if let Some(el) = else_opt {
3636 self.visit_expr(el);
3639 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3641 self.visit_expr(arm.body);
3644 // We need to walk to find `return`s in the entire body.
3645 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3646 _ => self.returns.push(ex),
3650 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3651 assert!(!self.in_block_tail);
3652 if body.generator_kind().is_none() {
3653 if let hir::ExprKind::Block(block, None) = body.value.kind {
3654 if block.expr.is_some() {
3655 self.in_block_tail = true;
3659 hir::intravisit::walk_body(self, body);
3663 /// Collect all the awaited expressions within the input expression.
3665 struct AwaitsVisitor {
3666 awaits: Vec<hir::HirId>,
3669 impl<'v> Visitor<'v> for AwaitsVisitor {
3670 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3671 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3672 self.awaits.push(id)
3674 hir::intravisit::walk_expr(self, ex)
3678 pub trait NextTypeParamName {
3679 fn next_type_param_name(&self, name: Option<&str>) -> String;
3682 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3683 fn next_type_param_name(&self, name: Option<&str>) -> String {
3684 // This is the list of possible parameter names that we might suggest.
3685 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3686 let name = name.as_deref();
3687 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3688 let used_names = self
3690 .filter_map(|p| match p.name {
3691 hir::ParamName::Plain(ident) => Some(ident.name),
3694 .collect::<Vec<_>>();
3698 .find(|n| !used_names.contains(&Symbol::intern(n)))
3699 .unwrap_or(&"ParamName")
3704 fn suggest_trait_object_return_type_alternatives(
3705 err: &mut Diagnostic,
3708 is_object_safe: bool,
3710 err.span_suggestion(
3713 "use `impl {}` as the return type if all return paths have the same type but you \
3714 want to expose only the trait in the signature",
3717 format!("impl {}", trait_obj),
3718 Applicability::MaybeIncorrect,
3721 err.multipart_suggestion(
3723 "use a boxed trait object if all return paths implement trait `{}`",
3727 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3728 (ret_ty.shrink_to_hi(), ">".to_string()),
3730 Applicability::MaybeIncorrect,
3735 /// Collect the spans that we see the generic param `param_did`
3736 struct ReplaceImplTraitVisitor<'a> {
3737 ty_spans: &'a mut Vec<Span>,
3741 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3742 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3743 if let hir::TyKind::Path(hir::QPath::Resolved(
3745 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3748 if self.param_did == *segment_did {
3749 // `fn foo(t: impl Trait)`
3750 // ^^^^^^^^^^ get this to suggest `T` instead
3752 // There might be more than one `impl Trait`.
3753 self.ty_spans.push(t.span);
3758 hir::intravisit::walk_ty(self, t);
3762 // Replace `param` with `replace_ty`
3763 struct ReplaceImplTraitFolder<'tcx> {
3765 param: &'tcx ty::GenericParamDef,
3766 replace_ty: Ty<'tcx>,
3769 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3770 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3771 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3772 if self.param.index == *index {
3773 return self.replace_ty;
3776 t.super_fold_with(self)
3779 fn tcx(&self) -> TyCtxt<'tcx> {