1 // ignore-tidy-filelength
2 use super::{DefIdOrName, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation};
4 use crate::autoderef::Autoderef;
5 use crate::infer::InferCtxt;
6 use crate::traits::{NormalizeExt, ObligationCtxt};
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_data_structures::stack::ensure_sufficient_stack;
13 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
14 ErrorGuaranteed, MultiSpan, Style,
17 use rustc_hir::def::DefKind;
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::intravisit::Visitor;
20 use rustc_hir::lang_items::LangItem;
21 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
22 use rustc_infer::infer::error_reporting::TypeErrCtxt;
23 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
24 use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime};
25 use rustc_middle::hir::map;
26 use rustc_middle::ty::error::TypeError::{self, Sorts};
27 use rustc_middle::ty::relate::TypeRelation;
28 use rustc_middle::ty::{
29 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
30 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, InternalSubsts,
31 IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder,
32 TypeSuperFoldable, TypeVisitable, TypeckResults,
34 use rustc_span::symbol::{sym, Ident, Symbol};
35 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
36 use rustc_target::spec::abi;
39 use super::method_chain::CollectAllMismatches;
40 use super::InferCtxtPrivExt;
41 use crate::infer::InferCtxtExt as _;
42 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
43 use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
46 pub enum GeneratorInteriorOrUpvar {
47 // span of interior type
48 Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
53 // This type provides a uniform interface to retrieve data on generators, whether it originated from
54 // the local crate being compiled or from a foreign crate.
56 pub enum GeneratorData<'tcx, 'a> {
57 Local(&'a TypeckResults<'tcx>),
58 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
61 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
62 // Try to get information about variables captured by the generator that matches a type we are
63 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
65 fn try_get_upvar_span<F>(
67 infer_context: &InferCtxt<'tcx>,
70 ) -> Option<GeneratorInteriorOrUpvar>
72 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
75 GeneratorData::Local(typeck_results) => {
76 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
77 upvars.iter().find_map(|(upvar_id, upvar)| {
78 let upvar_ty = typeck_results.node_type(*upvar_id);
79 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
80 if ty_matches(ty::Binder::dummy(upvar_ty)) {
81 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
88 GeneratorData::Foreign(_) => None,
92 // Try to get the span of a type being awaited on that matches the type we are looking with the
93 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
95 fn get_from_await_ty<F>(
97 visitor: AwaitsVisitor,
102 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
105 GeneratorData::Local(typeck_results) => visitor
108 .map(|id| hir.expect_expr(id))
110 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
112 .map(|expr| expr.span),
113 GeneratorData::Foreign(generator_diagnostic_data) => visitor
116 .map(|id| hir.expect_expr(id))
118 ty_matches(ty::Binder::dummy(
119 generator_diagnostic_data
121 .get(&await_expr.hir_id.local_id)
122 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
124 .map_or_else::<Ty<'tcx>, _, _>(
126 generator_diagnostic_data
128 .get(&await_expr.hir_id.local_id)
132 "node_type: no type for node `{}`",
133 ty::tls::with(|tcx| tcx
135 .node_to_string(await_expr.hir_id))
143 .map(|expr| expr.span),
147 /// Get the type, expression, span and optional scope span of all types
148 /// that are live across the yield of this generator
149 fn get_generator_interior_types(
151 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
153 GeneratorData::Local(typeck_result) => {
154 typeck_result.generator_interior_types.as_deref()
156 GeneratorData::Foreign(generator_diagnostic_data) => {
157 generator_diagnostic_data.generator_interior_types.as_deref()
162 // Used to get the source of the data, note we don't have as much information for generators
163 // originated from foreign crates
164 fn is_foreign(&self) -> bool {
166 GeneratorData::Local(_) => false,
167 GeneratorData::Foreign(_) => true,
172 // This trait is public to expose the diagnostics methods to clippy.
173 pub trait TypeErrCtxtExt<'tcx> {
174 fn suggest_restricting_param_bound(
176 err: &mut Diagnostic,
177 trait_pred: ty::PolyTraitPredicate<'tcx>,
178 associated_item: Option<(&'static str, Ty<'tcx>)>,
182 fn suggest_dereferences(
184 obligation: &PredicateObligation<'tcx>,
185 err: &mut Diagnostic,
186 trait_pred: ty::PolyTraitPredicate<'tcx>,
189 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
193 obligation: &PredicateObligation<'tcx>,
194 err: &mut Diagnostic,
195 trait_pred: ty::PolyTraitPredicate<'tcx>,
198 fn suggest_add_reference_to_arg(
200 obligation: &PredicateObligation<'tcx>,
201 err: &mut Diagnostic,
202 trait_pred: ty::PolyTraitPredicate<'tcx>,
203 has_custom_message: bool,
206 fn suggest_borrowing_for_object_cast(
208 err: &mut Diagnostic,
209 obligation: &PredicateObligation<'tcx>,
214 fn suggest_remove_reference(
216 obligation: &PredicateObligation<'tcx>,
217 err: &mut Diagnostic,
218 trait_pred: ty::PolyTraitPredicate<'tcx>,
221 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
223 fn suggest_change_mut(
225 obligation: &PredicateObligation<'tcx>,
226 err: &mut Diagnostic,
227 trait_pred: ty::PolyTraitPredicate<'tcx>,
230 fn suggest_semicolon_removal(
232 obligation: &PredicateObligation<'tcx>,
233 err: &mut Diagnostic,
235 trait_pred: ty::PolyTraitPredicate<'tcx>,
238 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
240 fn suggest_impl_trait(
242 err: &mut Diagnostic,
244 obligation: &PredicateObligation<'tcx>,
245 trait_pred: ty::PolyTraitPredicate<'tcx>,
248 fn point_at_returns_when_relevant(
250 err: &mut Diagnostic,
251 obligation: &PredicateObligation<'tcx>,
254 fn report_closure_arg_mismatch(
257 found_span: Option<Span>,
258 found: ty::PolyTraitRef<'tcx>,
259 expected: ty::PolyTraitRef<'tcx>,
260 cause: &ObligationCauseCode<'tcx>,
261 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
263 fn note_conflicting_closure_bounds(
265 cause: &ObligationCauseCode<'tcx>,
266 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
269 fn suggest_fully_qualified_path(
271 err: &mut Diagnostic,
277 fn maybe_note_obligation_cause_for_async_await(
279 err: &mut Diagnostic,
280 obligation: &PredicateObligation<'tcx>,
283 fn note_obligation_cause_for_async_await(
285 err: &mut Diagnostic,
286 interior_or_upvar_span: GeneratorInteriorOrUpvar,
288 outer_generator: Option<DefId>,
289 trait_pred: ty::TraitPredicate<'tcx>,
291 typeck_results: Option<&ty::TypeckResults<'tcx>>,
292 obligation: &PredicateObligation<'tcx>,
293 next_code: Option<&ObligationCauseCode<'tcx>>,
296 fn note_obligation_cause_code<T>(
298 err: &mut Diagnostic,
300 param_env: ty::ParamEnv<'tcx>,
301 cause_code: &ObligationCauseCode<'tcx>,
302 obligated_types: &mut Vec<Ty<'tcx>>,
303 seen_requirements: &mut FxHashSet<DefId>,
305 T: ToPredicate<'tcx>;
307 /// Suggest to await before try: future? => future.await?
308 fn suggest_await_before_try(
310 err: &mut Diagnostic,
311 obligation: &PredicateObligation<'tcx>,
312 trait_pred: ty::PolyTraitPredicate<'tcx>,
316 fn suggest_floating_point_literal(
318 obligation: &PredicateObligation<'tcx>,
319 err: &mut Diagnostic,
320 trait_ref: &ty::PolyTraitRef<'tcx>,
325 obligation: &PredicateObligation<'tcx>,
326 err: &mut Diagnostic,
327 trait_pred: ty::PolyTraitPredicate<'tcx>,
330 fn suggest_dereferencing_index(
332 obligation: &PredicateObligation<'tcx>,
333 err: &mut Diagnostic,
334 trait_pred: ty::PolyTraitPredicate<'tcx>,
336 fn function_argument_obligation(
339 err: &mut Diagnostic,
340 parent_code: &ObligationCauseCode<'tcx>,
341 param_env: ty::ParamEnv<'tcx>,
342 predicate: ty::Predicate<'tcx>,
347 expr: &hir::Expr<'_>,
348 typeck_results: &TypeckResults<'tcx>,
349 type_diffs: Vec<TypeError<'tcx>>,
350 param_env: ty::ParamEnv<'tcx>,
351 err: &mut Diagnostic,
355 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
357 generics.tail_span_for_predicate_suggestion(),
358 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
362 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
363 /// it can also be an `impl Trait` param that needs to be decomposed to a type
364 /// param for cleaner code.
365 fn suggest_restriction<'tcx>(
368 hir_generics: &hir::Generics<'tcx>,
370 err: &mut Diagnostic,
371 fn_sig: Option<&hir::FnSig<'_>>,
372 projection: Option<&ty::ProjectionTy<'_>>,
373 trait_pred: ty::PolyTraitPredicate<'tcx>,
374 // When we are dealing with a trait, `super_traits` will be `Some`:
375 // Given `trait T: A + B + C {}`
376 // - ^^^^^^^^^ GenericBounds
379 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
381 if hir_generics.where_clause_span.from_expansion()
382 || hir_generics.where_clause_span.desugaring_kind().is_some()
386 let Some(item_id) = hir_id.as_owner() else { return; };
387 let generics = tcx.generics_of(item_id);
388 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
389 if let Some((param, bound_str, fn_sig)) =
390 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
391 // Shenanigans to get the `Trait` from the `impl Trait`.
392 ty::Param(param) => {
393 let param_def = generics.type_param(param, tcx);
394 if param_def.kind.is_synthetic() {
396 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
397 return Some((param_def, bound_str, sig));
404 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
405 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
408 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
411 if !trait_pred.is_suggestable(tcx, false) {
414 // We know we have an `impl Trait` that doesn't satisfy a required projection.
416 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
417 // types. There should be at least one, but there might be *more* than one. In that
418 // case we could just ignore it and try to identify which one needs the restriction,
419 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
421 let mut ty_spans = vec![];
422 for input in fn_sig.decl.inputs {
423 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
426 // The type param `T: Trait` we will suggest to introduce.
427 let type_param = format!("{}: {}", type_param_name, bound_str);
430 if let Some(span) = hir_generics.span_for_param_suggestion() {
431 (span, format!(", {}", type_param))
433 (hir_generics.span, format!("<{}>", type_param))
435 // `fn foo(t: impl Trait)`
436 // ^ suggest `where <T as Trait>::A: Bound`
437 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
439 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
441 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
442 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
443 // `fn foo(t: impl Trait<A: Bound>)` instead.
444 err.multipart_suggestion(
445 "introduce a type parameter with a trait bound instead of using `impl Trait`",
447 Applicability::MaybeIncorrect,
450 if !trait_pred.is_suggestable(tcx, false) {
453 // Trivial case: `T` needs an extra bound: `T: Bound`.
454 let (sp, suggestion) = match (
458 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
461 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
462 (None, Some((ident, []))) => (
463 ident.span.shrink_to_hi(),
464 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
466 (_, Some((_, [.., bounds]))) => (
467 bounds.span().shrink_to_hi(),
468 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
470 (Some(_), Some((_, []))) => (
471 hir_generics.span.shrink_to_hi(),
472 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
476 err.span_suggestion_verbose(
478 &format!("consider further restricting {}", msg),
480 Applicability::MachineApplicable,
485 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
486 fn suggest_restricting_param_bound(
488 mut err: &mut Diagnostic,
489 trait_pred: ty::PolyTraitPredicate<'tcx>,
490 associated_ty: Option<(&'static str, Ty<'tcx>)>,
493 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
495 let self_ty = trait_pred.skip_binder().self_ty();
496 let (param_ty, projection) = match self_ty.kind() {
497 ty::Param(_) => (true, None),
498 ty::Projection(projection) => (false, Some(projection)),
502 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
503 // don't suggest `T: Sized + ?Sized`.
504 let mut hir_id = body_id;
505 while let Some(node) = self.tcx.hir().find(hir_id) {
507 hir::Node::Item(hir::Item {
509 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
511 }) if self_ty == self.tcx.types.self_param => {
513 // Restricting `Self` for a single method.
523 Some((ident, bounds)),
528 hir::Node::TraitItem(hir::TraitItem {
530 kind: hir::TraitItemKind::Fn(..),
532 }) if self_ty == self.tcx.types.self_param => {
534 // Restricting `Self` for a single method.
536 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
542 hir::Node::TraitItem(hir::TraitItem {
544 kind: hir::TraitItemKind::Fn(fn_sig, ..),
547 | hir::Node::ImplItem(hir::ImplItem {
549 kind: hir::ImplItemKind::Fn(fn_sig, ..),
552 | hir::Node::Item(hir::Item {
553 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
554 }) if projection.is_some() => {
555 // Missing restriction on associated type of type parameter (unmet projection).
560 "the associated type",
569 hir::Node::Item(hir::Item {
571 hir::ItemKind::Trait(_, _, generics, ..)
572 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
574 }) if projection.is_some() => {
575 // Missing restriction on associated type of type parameter (unmet projection).
580 "the associated type",
590 hir::Node::Item(hir::Item {
592 hir::ItemKind::Struct(_, generics)
593 | hir::ItemKind::Enum(_, generics)
594 | hir::ItemKind::Union(_, generics)
595 | hir::ItemKind::Trait(_, _, generics, ..)
596 | hir::ItemKind::Impl(hir::Impl { generics, .. })
597 | hir::ItemKind::Fn(_, generics, _)
598 | hir::ItemKind::TyAlias(_, generics)
599 | hir::ItemKind::TraitAlias(generics, _)
600 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
603 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
604 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
607 // We skip the 0'th subst (self) because we do not want
608 // to consider the predicate as not suggestible if the
609 // self type is an arg position `impl Trait` -- instead,
610 // we handle that by adding ` + Bound` below.
611 // FIXME(compiler-errors): It would be nice to do the same
612 // this that we do in `suggest_restriction` and pull the
613 // `impl Trait` into a new generic if it shows up somewhere
614 // else in the predicate.
615 if !trait_pred.skip_binder().trait_ref.substs[1..]
617 .all(|g| g.is_suggestable(self.tcx, false))
621 // Missing generic type parameter bound.
622 let param_name = self_ty.to_string();
623 let mut constraint = with_no_trimmed_paths!(
624 trait_pred.print_modifiers_and_trait_path().to_string()
627 if let Some((name, term)) = associated_ty {
628 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
629 // That should be extracted into a helper function.
630 if constraint.ends_with('>') {
631 constraint = format!(
633 &constraint[..constraint.len() - 1],
638 constraint.push_str(&format!("<{} = {}>", name, term));
642 if suggest_constraining_type_param(
648 Some(trait_pred.def_id()),
654 hir::Node::Item(hir::Item {
656 hir::ItemKind::Struct(_, generics)
657 | hir::ItemKind::Enum(_, generics)
658 | hir::ItemKind::Union(_, generics)
659 | hir::ItemKind::Trait(_, _, generics, ..)
660 | hir::ItemKind::Impl(hir::Impl { generics, .. })
661 | hir::ItemKind::Fn(_, generics, _)
662 | hir::ItemKind::TyAlias(_, generics)
663 | hir::ItemKind::TraitAlias(generics, _)
664 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
667 // Missing generic type parameter bound.
668 if suggest_arbitrary_trait_bound(
678 hir::Node::Crate(..) => return,
683 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
687 /// When after several dereferencing, the reference satisfies the trait
688 /// binding. This function provides dereference suggestion for this
689 /// specific situation.
690 fn suggest_dereferences(
692 obligation: &PredicateObligation<'tcx>,
693 err: &mut Diagnostic,
694 trait_pred: ty::PolyTraitPredicate<'tcx>,
696 // It only make sense when suggesting dereferences for arguments
697 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code()
698 else { return false; };
699 let Some(typeck_results) = &self.typeck_results
700 else { return false; };
701 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
702 else { return false; };
703 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
704 else { return false; };
706 let span = obligation.cause.span;
707 let mut real_trait_pred = trait_pred;
708 let mut code = obligation.cause.code();
709 while let Some((parent_code, parent_trait_pred)) = code.parent() {
711 if let Some(parent_trait_pred) = parent_trait_pred {
712 real_trait_pred = parent_trait_pred;
715 let real_ty = real_trait_pred.self_ty();
716 // We `erase_late_bound_regions` here because `make_subregion` does not handle
717 // `ReLateBound`, and we don't particularly care about the regions.
719 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
725 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
726 let mut autoderef = Autoderef::new(
728 obligation.param_env,
729 obligation.cause.body_id,
733 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
735 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
737 // Remapping bound vars here
738 let real_trait_pred_and_ty =
739 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
740 let obligation = self.mk_trait_obligation_with_new_self_ty(
741 obligation.param_env,
742 real_trait_pred_and_ty,
744 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
747 // Don't care about `&mut` because `DerefMut` is used less
748 // often and user will not expect autoderef happens.
749 if let Some(hir::Node::Expr(hir::Expr {
751 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
753 })) = self.tcx.hir().find(*arg_hir_id)
755 let derefs = "*".repeat(steps);
756 err.span_suggestion_verbose(
757 expr.span.shrink_to_lo(),
758 "consider dereferencing here",
760 Applicability::MachineApplicable,
765 } else if real_trait_pred != trait_pred {
766 // This branch addresses #87437.
768 // Remapping bound vars here
769 let real_trait_pred_and_base_ty =
770 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
771 let obligation = self.mk_trait_obligation_with_new_self_ty(
772 obligation.param_env,
773 real_trait_pred_and_base_ty,
775 if self.predicate_may_hold(&obligation) {
776 err.span_suggestion_verbose(
778 "consider dereferencing here",
780 Applicability::MachineApplicable,
790 /// Given a closure's `DefId`, return the given name of the closure.
792 /// This doesn't account for reassignments, but it's only used for suggestions.
793 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
794 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
795 // Get the local name of this closure. This can be inaccurate because
796 // of the possibility of reassignment, but this should be good enough.
798 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
808 let hir = self.tcx.hir();
809 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
810 let parent_node = hir.get_parent_node(hir_id);
811 match hir.find(parent_node) {
812 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
813 get_name(err, &local.pat.kind)
815 // Different to previous arm because one is `&hir::Local` and the other
816 // is `P<hir::Local>`.
817 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
822 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
823 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
824 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
827 obligation: &PredicateObligation<'tcx>,
828 err: &mut Diagnostic,
829 trait_pred: ty::PolyTraitPredicate<'tcx>,
831 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
832 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
834 // Don't suggest calling to turn an unsized type into a sized type
838 // This is duplicated from `extract_callable_info` in typeck, which
839 // relies on autoderef, so we can't use it here.
840 let found = trait_pred.self_ty().skip_binder().peel_refs();
841 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
843 ty::FnPtr(fn_sig) => {
844 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
846 ty::FnDef(def_id, _) => {
847 let fn_sig = found.fn_sig(self.tcx);
848 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
850 ty::Closure(def_id, substs) => {
851 let fn_sig = substs.as_closure().sig();
853 DefIdOrName::DefId(def_id),
855 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
858 ty::Opaque(def_id, substs) => {
859 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
860 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
861 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
862 // args tuple will always be substs[1]
863 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
866 DefIdOrName::DefId(def_id),
867 pred.kind().rebind(proj.term.ty().unwrap()),
868 pred.kind().rebind(args.as_slice()),
875 ty::Dynamic(data, _, ty::Dyn) => {
876 data.iter().find_map(|pred| {
877 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
878 && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
879 // for existential projection, substs are shifted over by 1
880 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
883 DefIdOrName::Name("trait object"),
884 pred.rebind(proj.term.ty().unwrap()),
885 pred.rebind(args.as_slice()),
893 obligation.param_env.caller_bounds().iter().find_map(|pred| {
894 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
895 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
896 && proj.projection_ty.self_ty() == found
897 // args tuple will always be substs[1]
898 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
901 DefIdOrName::Name("type parameter"),
902 pred.kind().rebind(proj.term.ty().unwrap()),
903 pred.kind().rebind(args.as_slice()),
911 }) else { return false; };
912 let output = self.replace_bound_vars_with_fresh_vars(
913 obligation.cause.span,
914 LateBoundRegionConversionTime::FnCall,
917 let inputs = inputs.skip_binder().iter().map(|ty| {
918 self.replace_bound_vars_with_fresh_vars(
919 obligation.cause.span,
920 LateBoundRegionConversionTime::FnCall,
925 // Remapping bound vars here
926 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
929 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
930 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
934 // Get the name of the callable and the arguments to be used in the suggestion.
935 let hir = self.tcx.hir();
937 let msg = match def_id_or_name {
938 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
939 DefKind::Ctor(CtorOf::Struct, _) => {
940 "use parentheses to construct this tuple struct".to_string()
942 DefKind::Ctor(CtorOf::Variant, _) => {
943 "use parentheses to construct this tuple variant".to_string()
945 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
947 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
952 if ty.is_suggestable(self.tcx, false) {
953 format!("/* {ty} */")
955 "/* value */".to_string()
961 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
962 && obligation.cause.span.can_be_used_for_suggestions()
964 // When the obligation error has been ensured to have been caused by
965 // an argument, the `obligation.cause.span` points at the expression
966 // of the argument, so we can provide a suggestion. Otherwise, we give
967 // a more general note.
968 err.span_suggestion_verbose(
969 obligation.cause.span.shrink_to_hi(),
972 Applicability::HasPlaceholders,
974 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
975 let name = match hir.get_if_local(def_id) {
976 Some(hir::Node::Expr(hir::Expr {
977 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
980 err.span_label(*fn_decl_span, "consider calling this closure");
981 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
986 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
987 err.span_label(ident.span, "consider calling this function");
990 Some(hir::Node::Ctor(..)) => {
991 let name = self.tcx.def_path_str(def_id);
993 self.tcx.def_span(def_id),
994 format!("consider calling the constructor for `{}`", name),
1000 err.help(&format!("{msg}: `{name}({args})`"));
1005 fn suggest_add_reference_to_arg(
1007 obligation: &PredicateObligation<'tcx>,
1008 err: &mut Diagnostic,
1009 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1010 has_custom_message: bool,
1012 let span = obligation.cause.span;
1014 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
1015 obligation.cause.code()
1018 } else if let ObligationCauseCode::ItemObligation(_)
1019 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1021 obligation.cause.code()
1022 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1023 span.ctxt().outer_expn_data().kind
1025 obligation.cause.code()
1030 // List of traits for which it would be nonsensical to suggest borrowing.
1031 // For instance, immutable references are always Copy, so suggesting to
1032 // borrow would always succeed, but it's probably not what the user wanted.
1033 let mut never_suggest_borrow: Vec<_> =
1034 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1036 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1039 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1040 never_suggest_borrow.push(def_id);
1043 let param_env = obligation.param_env;
1045 // Try to apply the original trait binding obligation by borrowing.
1046 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1047 blacklist: &[DefId]|
1049 if blacklist.contains(&old_pred.def_id()) {
1052 // We map bounds to `&T` and `&mut T`
1053 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1056 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1059 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1062 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1066 let mk_result = |trait_pred_and_new_ty| {
1068 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1069 self.predicate_must_hold_modulo_regions(&obligation)
1071 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1072 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1074 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1075 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1076 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1079 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1080 mutability.is_mut(),
1086 if imm_ref_self_ty_satisfies_pred
1087 || mut_ref_self_ty_satisfies_pred
1088 || ref_inner_ty_satisfies_pred
1090 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1091 // We don't want a borrowing suggestion on the fields in structs,
1094 // the_foos: Vec<Foo>
1098 span.ctxt().outer_expn_data().kind,
1099 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1103 if snippet.starts_with('&') {
1104 // This is already a literal borrow and the obligation is failing
1105 // somewhere else in the obligation chain. Do not suggest non-sense.
1108 // We have a very specific type of error, where just borrowing this argument
1109 // might solve the problem. In cases like this, the important part is the
1110 // original type obligation, not the last one that failed, which is arbitrary.
1111 // Because of this, we modify the error to refer to the original obligation and
1112 // return early in the caller.
1114 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1115 if has_custom_message {
1119 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1124 "the trait `{}` is not implemented for `{}`",
1125 old_pred.print_modifiers_and_trait_path(),
1126 old_pred.self_ty().skip_binder(),
1130 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1131 err.span_suggestions(
1132 span.shrink_to_lo(),
1133 "consider borrowing here",
1134 ["&".to_string(), "&mut ".to_string()],
1135 Applicability::MaybeIncorrect,
1138 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1139 err.span_suggestion_verbose(
1140 span.shrink_to_lo(),
1142 "consider{} borrowing here",
1143 if is_mut { " mutably" } else { "" }
1145 format!("&{}", if is_mut { "mut " } else { "" }),
1146 Applicability::MaybeIncorrect,
1155 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1156 try_borrowing(cause.derived.parent_trait_pred, &[])
1157 } else if let ObligationCauseCode::BindingObligation(_, _)
1158 | ObligationCauseCode::ItemObligation(_)
1159 | ObligationCauseCode::ExprItemObligation(..)
1160 | ObligationCauseCode::ExprBindingObligation(..) = code
1162 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1168 // Suggest borrowing the type
1169 fn suggest_borrowing_for_object_cast(
1171 err: &mut Diagnostic,
1172 obligation: &PredicateObligation<'tcx>,
1174 object_ty: Ty<'tcx>,
1176 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1177 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1179 for predicate in predicates.iter() {
1180 if !self.predicate_must_hold_modulo_regions(
1181 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1187 err.span_suggestion(
1188 obligation.cause.span.shrink_to_lo(),
1190 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1193 Applicability::MaybeIncorrect,
1197 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1198 /// suggest removing these references until we reach a type that implements the trait.
1199 fn suggest_remove_reference(
1201 obligation: &PredicateObligation<'tcx>,
1202 err: &mut Diagnostic,
1203 trait_pred: ty::PolyTraitPredicate<'tcx>,
1205 let span = obligation.cause.span;
1207 let mut suggested = false;
1208 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1210 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1211 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1212 // Do not suggest removal of borrow from type arguments.
1216 // Skipping binder here, remapping below
1217 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1219 for refs_remaining in 0..refs_number {
1220 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1223 suggested_ty = *inner_ty;
1225 // Remapping bound vars here
1226 let trait_pred_and_suggested_ty =
1227 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1229 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1230 obligation.param_env,
1231 trait_pred_and_suggested_ty,
1234 if self.predicate_may_hold(&new_obligation) {
1239 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1241 let remove_refs = refs_remaining + 1;
1243 let msg = if remove_refs == 1 {
1244 "consider removing the leading `&`-reference".to_string()
1246 format!("consider removing {} leading `&`-references", remove_refs)
1249 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1258 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1259 let span = obligation.cause.span;
1261 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1262 let hir = self.tcx.hir();
1263 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1264 if let hir::Node::Expr(expr) = node {
1265 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1266 // and if not maybe suggest doing something else? If we kept the expression around we
1267 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1268 // it is from the local crate.
1269 err.span_suggestion(
1271 "remove the `.await`",
1273 Applicability::MachineApplicable,
1275 // FIXME: account for associated `async fn`s.
1276 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1277 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1278 obligation.predicate.kind().skip_binder()
1282 &format!("this call returns `{}`", pred.self_ty()),
1285 if let Some(typeck_results) = &self.typeck_results
1286 && let ty = typeck_results.expr_ty_adjusted(base)
1287 && let ty::FnDef(def_id, _substs) = ty.kind()
1288 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1289 hir.get_if_local(*def_id)
1292 "alternatively, consider making `fn {}` asynchronous",
1295 if vis_span.is_empty() {
1296 err.span_suggestion_verbose(
1297 span.shrink_to_lo(),
1300 Applicability::MaybeIncorrect,
1303 err.span_suggestion_verbose(
1304 vis_span.shrink_to_hi(),
1307 Applicability::MaybeIncorrect,
1317 /// Check if the trait bound is implemented for a different mutability and note it in the
1319 fn suggest_change_mut(
1321 obligation: &PredicateObligation<'tcx>,
1322 err: &mut Diagnostic,
1323 trait_pred: ty::PolyTraitPredicate<'tcx>,
1325 let points_at_arg = matches!(
1326 obligation.cause.code(),
1327 ObligationCauseCode::FunctionArgumentObligation { .. },
1330 let span = obligation.cause.span;
1331 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1333 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1334 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1335 // Do not suggest removal of borrow from type arguments.
1338 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1339 if trait_pred.has_non_region_infer() {
1340 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1341 // unresolved bindings.
1345 // Skipping binder here, remapping below
1346 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1348 let suggested_ty = match mutability {
1349 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1350 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1353 // Remapping bound vars here
1354 let trait_pred_and_suggested_ty =
1355 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1357 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1358 obligation.param_env,
1359 trait_pred_and_suggested_ty,
1361 let suggested_ty_would_satisfy_obligation = self
1362 .evaluate_obligation_no_overflow(&new_obligation)
1363 .must_apply_modulo_regions();
1364 if suggested_ty_would_satisfy_obligation {
1369 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1370 if points_at_arg && mutability.is_not() && refs_number > 0 {
1371 err.span_suggestion_verbose(
1373 "consider changing this borrow's mutability",
1375 Applicability::MachineApplicable,
1379 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1380 trait_pred.print_modifiers_and_trait_path(),
1382 trait_pred.skip_binder().self_ty(),
1390 fn suggest_semicolon_removal(
1392 obligation: &PredicateObligation<'tcx>,
1393 err: &mut Diagnostic,
1395 trait_pred: ty::PolyTraitPredicate<'tcx>,
1397 let hir = self.tcx.hir();
1398 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1399 let node = hir.find(parent_node);
1400 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1401 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1402 && sig.decl.output.span().overlaps(span)
1403 && blk.expr.is_none()
1404 && trait_pred.self_ty().skip_binder().is_unit()
1405 && let Some(stmt) = blk.stmts.last()
1406 && let hir::StmtKind::Semi(expr) = stmt.kind
1407 // Only suggest this if the expression behind the semicolon implements the predicate
1408 && let Some(typeck_results) = &self.typeck_results
1409 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1410 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1411 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1417 "this expression has type `{}`, which implements `{}`",
1419 trait_pred.print_modifiers_and_trait_path()
1422 err.span_suggestion(
1423 self.tcx.sess.source_map().end_point(stmt.span),
1424 "remove this semicolon",
1426 Applicability::MachineApplicable
1433 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1434 let hir = self.tcx.hir();
1435 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1436 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1440 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1443 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1444 /// applicable and signal that the error has been expanded appropriately and needs to be
1446 fn suggest_impl_trait(
1448 err: &mut Diagnostic,
1450 obligation: &PredicateObligation<'tcx>,
1451 trait_pred: ty::PolyTraitPredicate<'tcx>,
1453 match obligation.cause.code().peel_derives() {
1454 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1455 ObligationCauseCode::SizedReturnType => {}
1459 let hir = self.tcx.hir();
1460 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1461 let node = hir.find(fn_hir_id);
1462 let Some(hir::Node::Item(hir::Item {
1463 kind: hir::ItemKind::Fn(sig, _, body_id),
1469 let body = hir.body(*body_id);
1470 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1471 let ty = trait_pred.skip_binder().self_ty();
1472 let is_object_safe = match ty.kind() {
1473 ty::Dynamic(predicates, _, ty::Dyn) => {
1474 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1477 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1479 // We only want to suggest `impl Trait` to `dyn Trait`s.
1480 // For example, `fn foo() -> str` needs to be filtered out.
1484 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1488 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1489 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1490 // Recursively look for `TraitObject` types and if there's only one, use that span to
1491 // suggest `impl Trait`.
1493 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1494 // otherwise suggest using `Box<dyn Trait>` or an enum.
1495 let mut visitor = ReturnsVisitor::default();
1496 visitor.visit_body(&body);
1498 let typeck_results = self.typeck_results.as_ref().unwrap();
1499 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1501 let ret_types = visitor
1504 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1505 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1506 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1508 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1510 let ty = self.resolve_vars_if_possible(ty);
1512 !matches!(ty.kind(), ty::Error(_))
1513 && last_ty.map_or(true, |last_ty| {
1514 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1515 // *after* in the dependency graph.
1516 match (ty.kind(), last_ty.kind()) {
1517 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1518 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1519 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1521 Infer(InferTy::FreshFloatTy(_)),
1522 Infer(InferTy::FreshFloatTy(_)),
1527 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1530 let mut spans_and_needs_box = vec![];
1532 match liberated_sig.output().kind() {
1533 ty::Dynamic(predicates, _, ty::Dyn) => {
1534 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1535 let param_env = ty::ParamEnv::empty();
1537 if !only_never_return {
1538 for (expr_span, return_ty) in ret_types {
1539 let self_ty_satisfies_dyn_predicates = |self_ty| {
1540 predicates.iter().all(|predicate| {
1541 let pred = predicate.with_self_ty(self.tcx, self_ty);
1542 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1543 self.predicate_may_hold(&obl)
1547 if let ty::Adt(def, substs) = return_ty.kind()
1549 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1551 spans_and_needs_box.push((expr_span, false));
1552 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1553 spans_and_needs_box.push((expr_span, true));
1563 let sm = self.tcx.sess.source_map();
1564 if !ret_ty.span.overlaps(span) {
1567 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1568 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1574 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1575 let name = liberated_sig.output().to_string();
1577 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1578 if !name.starts_with("dyn ") {
1584 err.code(error_code!(E0746));
1585 err.set_primary_message("return type cannot have an unboxed trait object");
1586 err.children.clear();
1587 let impl_trait_msg = "for information on `impl Trait`, see \
1588 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1589 #returning-types-that-implement-traits>";
1590 let trait_obj_msg = "for information on trait objects, see \
1591 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1592 #using-trait-objects-that-allow-for-values-of-different-types>";
1594 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1595 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1596 if only_never_return {
1597 // No return paths, probably using `panic!()` or similar.
1598 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1599 suggest_trait_object_return_type_alternatives(
1605 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1606 // Suggest `-> impl Trait`.
1607 err.span_suggestion(
1610 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1611 which implements `{1}`",
1614 format!("impl {}", trait_obj),
1615 Applicability::MachineApplicable,
1617 err.note(impl_trait_msg);
1620 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1621 err.multipart_suggestion(
1622 "return a boxed trait object instead",
1624 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1625 (span.shrink_to_hi(), ">".to_string()),
1627 Applicability::MaybeIncorrect,
1629 for (span, needs_box) in spans_and_needs_box {
1631 err.multipart_suggestion(
1632 "... and box this value",
1634 (span.shrink_to_lo(), "Box::new(".to_string()),
1635 (span.shrink_to_hi(), ")".to_string()),
1637 Applicability::MaybeIncorrect,
1642 // This is currently not possible to trigger because E0038 takes precedence, but
1643 // leave it in for completeness in case anything changes in an earlier stage.
1645 "if trait `{}` were object-safe, you could return a trait object",
1649 err.note(trait_obj_msg);
1651 "if all the returned values were of the same type you could use `impl {}` as the \
1655 err.note(impl_trait_msg);
1656 err.note("you can create a new `enum` with a variant for each returned type");
1661 fn point_at_returns_when_relevant(
1663 err: &mut Diagnostic,
1664 obligation: &PredicateObligation<'tcx>,
1666 match obligation.cause.code().peel_derives() {
1667 ObligationCauseCode::SizedReturnType => {}
1671 let hir = self.tcx.hir();
1672 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1673 let node = hir.find(parent_node);
1674 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1677 let body = hir.body(*body_id);
1678 // Point at all the `return`s in the function as they have failed trait bounds.
1679 let mut visitor = ReturnsVisitor::default();
1680 visitor.visit_body(&body);
1681 let typeck_results = self.typeck_results.as_ref().unwrap();
1682 for expr in &visitor.returns {
1683 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1684 let ty = self.resolve_vars_if_possible(returned_ty);
1685 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1691 fn report_closure_arg_mismatch(
1694 found_span: Option<Span>,
1695 found: ty::PolyTraitRef<'tcx>,
1696 expected: ty::PolyTraitRef<'tcx>,
1697 cause: &ObligationCauseCode<'tcx>,
1698 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1699 pub(crate) fn build_fn_sig_ty<'tcx>(
1700 infcx: &InferCtxt<'tcx>,
1701 trait_ref: ty::PolyTraitRef<'tcx>,
1703 let inputs = trait_ref.skip_binder().substs.type_at(1);
1704 let sig = match inputs.kind() {
1705 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1706 infcx.tcx.mk_fn_sig(
1708 infcx.next_ty_var(TypeVariableOrigin {
1710 kind: TypeVariableOriginKind::MiscVariable,
1713 hir::Unsafety::Normal,
1717 _ => infcx.tcx.mk_fn_sig(
1718 std::iter::once(inputs),
1719 infcx.next_ty_var(TypeVariableOrigin {
1721 kind: TypeVariableOriginKind::MiscVariable,
1724 hir::Unsafety::Normal,
1729 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1732 let argument_kind = match expected.skip_binder().self_ty().kind() {
1733 ty::Closure(..) => "closure",
1734 ty::Generator(..) => "generator",
1737 let mut err = struct_span_err!(
1741 "type mismatch in {argument_kind} arguments",
1744 err.span_label(span, "expected due to this");
1746 let found_span = found_span.unwrap_or(span);
1747 err.span_label(found_span, "found signature defined here");
1749 let expected = build_fn_sig_ty(self, expected);
1750 let found = build_fn_sig_ty(self, found);
1752 let (expected_str, found_str) = self.cmp(expected, found);
1754 let signature_kind = format!("{argument_kind} signature");
1755 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1757 self.note_conflicting_closure_bounds(cause, &mut err);
1762 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1763 // requirements, which will always cause a closure to have a type error.
1764 fn note_conflicting_closure_bounds(
1766 cause: &ObligationCauseCode<'tcx>,
1767 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1769 // First, look for an `ExprBindingObligation`, which means we can get
1770 // the unsubstituted predicate list of the called function. And check
1771 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1772 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1773 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1774 && let Some(pred) = predicates.predicates.get(*idx)
1775 && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
1776 && self.tcx.is_fn_trait(trait_pred.def_id())
1779 self.tcx.anonymize_late_bound_regions(pred.kind().rebind(trait_pred.self_ty()));
1780 let expected_substs = self
1782 .anonymize_late_bound_regions(pred.kind().rebind(trait_pred.trait_ref.substs));
1784 // Find another predicate whose self-type is equal to the expected self type,
1785 // but whose substs don't match.
1786 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1788 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1789 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
1790 if self.tcx.is_fn_trait(trait_pred.def_id())
1792 // Make sure that the self type matches
1793 // (i.e. constraining this closure)
1795 == self.tcx.anonymize_late_bound_regions(
1796 pred.kind().rebind(trait_pred.self_ty()),
1798 // But the substs don't match (i.e. incompatible args)
1800 != self.tcx.anonymize_late_bound_regions(
1801 pred.kind().rebind(trait_pred.trait_ref.substs),
1808 // If we found one, then it's very likely the cause of the error.
1809 if let Some((_, (_, other_pred_span))) = other_pred {
1812 "closure inferred to have a different signature due to this bound",
1818 fn suggest_fully_qualified_path(
1820 err: &mut Diagnostic,
1825 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1826 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1828 "{}s cannot be accessed directly on a `trait`, they can only be \
1829 accessed through a specific `impl`",
1830 assoc_item.kind.as_def_kind().descr(item_def_id)
1832 err.span_suggestion(
1834 "use the fully qualified path to an implementation",
1835 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1836 Applicability::HasPlaceholders,
1842 /// Adds an async-await specific note to the diagnostic when the future does not implement
1843 /// an auto trait because of a captured type.
1846 /// note: future does not implement `Qux` as this value is used across an await
1847 /// --> $DIR/issue-64130-3-other.rs:17:5
1849 /// LL | let x = Foo;
1850 /// | - has type `Foo`
1851 /// LL | baz().await;
1852 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1854 /// | - `x` is later dropped here
1857 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1858 /// is "replaced" with a different message and a more specific error.
1861 /// error: future cannot be sent between threads safely
1862 /// --> $DIR/issue-64130-2-send.rs:21:5
1864 /// LL | fn is_send<T: Send>(t: T) { }
1865 /// | ---- required by this bound in `is_send`
1867 /// LL | is_send(bar());
1868 /// | ^^^^^^^ future returned by `bar` is not send
1870 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1871 /// implemented for `Foo`
1872 /// note: future is not send as this value is used across an await
1873 /// --> $DIR/issue-64130-2-send.rs:15:5
1875 /// LL | let x = Foo;
1876 /// | - has type `Foo`
1877 /// LL | baz().await;
1878 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1880 /// | - `x` is later dropped here
1883 /// Returns `true` if an async-await specific note was added to the diagnostic.
1884 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1885 fn maybe_note_obligation_cause_for_async_await(
1887 err: &mut Diagnostic,
1888 obligation: &PredicateObligation<'tcx>,
1890 let hir = self.tcx.hir();
1892 // Attempt to detect an async-await error by looking at the obligation causes, looking
1893 // for a generator to be present.
1895 // When a future does not implement a trait because of a captured type in one of the
1896 // generators somewhere in the call stack, then the result is a chain of obligations.
1898 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1899 // future is passed as an argument to a function C which requires a `Send` type, then the
1900 // chain looks something like this:
1902 // - `BuiltinDerivedObligation` with a generator witness (B)
1903 // - `BuiltinDerivedObligation` with a generator (B)
1904 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1905 // - `BuiltinDerivedObligation` with a generator witness (A)
1906 // - `BuiltinDerivedObligation` with a generator (A)
1907 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1908 // - `BindingObligation` with `impl_send (Send requirement)
1910 // The first obligation in the chain is the most useful and has the generator that captured
1911 // the type. The last generator (`outer_generator` below) has information about where the
1912 // bound was introduced. At least one generator should be present for this diagnostic to be
1914 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1915 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
1918 let mut generator = None;
1919 let mut outer_generator = None;
1920 let mut next_code = Some(obligation.cause.code());
1922 let mut seen_upvar_tys_infer_tuple = false;
1924 while let Some(code) = next_code {
1927 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1928 next_code = Some(parent_code);
1930 ObligationCauseCode::ImplDerivedObligation(cause) => {
1931 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1933 parent_trait_ref = ?cause.derived.parent_trait_pred,
1934 self_ty.kind = ?ty.kind(),
1939 ty::Generator(did, ..) => {
1940 generator = generator.or(Some(did));
1941 outer_generator = Some(did);
1943 ty::GeneratorWitness(..) => {}
1944 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1945 // By introducing a tuple of upvar types into the chain of obligations
1946 // of a generator, the first non-generator item is now the tuple itself,
1947 // we shall ignore this.
1949 seen_upvar_tys_infer_tuple = true;
1951 _ if generator.is_none() => {
1952 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1953 target_ty = Some(ty);
1958 next_code = Some(&cause.derived.parent_code);
1960 ObligationCauseCode::DerivedObligation(derived_obligation)
1961 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1962 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1964 parent_trait_ref = ?derived_obligation.parent_trait_pred,
1965 self_ty.kind = ?ty.kind(),
1969 ty::Generator(did, ..) => {
1970 generator = generator.or(Some(did));
1971 outer_generator = Some(did);
1973 ty::GeneratorWitness(..) => {}
1974 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1975 // By introducing a tuple of upvar types into the chain of obligations
1976 // of a generator, the first non-generator item is now the tuple itself,
1977 // we shall ignore this.
1979 seen_upvar_tys_infer_tuple = true;
1981 _ if generator.is_none() => {
1982 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1983 target_ty = Some(ty);
1988 next_code = Some(&derived_obligation.parent_code);
1994 // Only continue if a generator was found.
1995 debug!(?generator, ?trait_ref, ?target_ty);
1996 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
2000 let span = self.tcx.def_span(generator_did);
2002 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
2005 ?generator_did_root,
2006 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2010 let generator_body = generator_did
2012 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2013 .map(|body_id| hir.body(body_id));
2014 let mut visitor = AwaitsVisitor::default();
2015 if let Some(body) = generator_body {
2016 visitor.visit_body(body);
2018 debug!(awaits = ?visitor.awaits);
2020 // Look for a type inside the generator interior that matches the target type to get
2022 let target_ty_erased = self.tcx.erase_regions(target_ty);
2023 let ty_matches = |ty| -> bool {
2024 // Careful: the regions for types that appear in the
2025 // generator interior are not generally known, so we
2026 // want to erase them when comparing (and anyway,
2027 // `Send` and other bounds are generally unaffected by
2028 // the choice of region). When erasing regions, we
2029 // also have to erase late-bound regions. This is
2030 // because the types that appear in the generator
2031 // interior generally contain "bound regions" to
2032 // represent regions that are part of the suspended
2033 // generator frame. Bound regions are preserved by
2034 // `erase_regions` and so we must also call
2035 // `erase_late_bound_regions`.
2036 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2037 let ty_erased = self.tcx.erase_regions(ty_erased);
2038 let eq = ty_erased == target_ty_erased;
2039 debug!(?ty_erased, ?target_ty_erased, ?eq);
2043 // Get the typeck results from the infcx if the generator is the function we are currently
2044 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2045 // cycles. If we can't use resolved types because the generator comes from another crate,
2046 // we still provide a targeted error but without all the relevant spans.
2047 let generator_data = match &self.typeck_results {
2048 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2049 _ if generator_did.is_local() => {
2050 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2052 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2053 GeneratorData::Foreign(generator_diag_data)
2058 let mut interior_or_upvar_span = None;
2060 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2061 debug!(?from_awaited_ty);
2063 // The generator interior types share the same binders
2064 if let Some(cause) =
2065 generator_data.get_generator_interior_types().skip_binder().iter().find(
2066 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2067 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2071 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2073 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2075 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2079 if interior_or_upvar_span.is_none() {
2080 interior_or_upvar_span =
2081 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2084 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2085 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2088 debug!(?interior_or_upvar_span);
2089 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2090 let is_async = self.tcx.generator_is_async(generator_did);
2091 let typeck_results = match generator_data {
2092 GeneratorData::Local(typeck_results) => Some(typeck_results),
2093 GeneratorData::Foreign(_) => None,
2095 self.note_obligation_cause_for_async_await(
2097 interior_or_upvar_span,
2112 /// Unconditionally adds the diagnostic note described in
2113 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2114 #[instrument(level = "debug", skip_all)]
2115 fn note_obligation_cause_for_async_await(
2117 err: &mut Diagnostic,
2118 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2120 outer_generator: Option<DefId>,
2121 trait_pred: ty::TraitPredicate<'tcx>,
2122 target_ty: Ty<'tcx>,
2123 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2124 obligation: &PredicateObligation<'tcx>,
2125 next_code: Option<&ObligationCauseCode<'tcx>>,
2127 let source_map = self.tcx.sess.source_map();
2129 let (await_or_yield, an_await_or_yield) =
2130 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2131 let future_or_generator = if is_async { "future" } else { "generator" };
2133 // Special case the primary error message when send or sync is the trait that was
2135 let hir = self.tcx.hir();
2136 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2137 self.tcx.get_diagnostic_name(trait_pred.def_id())
2139 let (trait_name, trait_verb) =
2140 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2143 err.set_primary_message(format!(
2144 "{} cannot be {} between threads safely",
2145 future_or_generator, trait_verb
2148 let original_span = err.span.primary_span().unwrap();
2149 let mut span = MultiSpan::from_span(original_span);
2151 let message = outer_generator
2152 .and_then(|generator_did| {
2153 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2154 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2155 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2157 .parent(generator_did)
2159 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2160 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2162 format!("future returned by `{}` is not {}", name, trait_name)
2164 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2165 format!("future created by async block is not {}", trait_name)
2167 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2168 format!("future created by async closure is not {}", trait_name)
2172 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2174 span.push_span_label(original_span, message);
2177 format!("is not {}", trait_name)
2179 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2182 let mut explain_yield = |interior_span: Span,
2184 scope_span: Option<Span>| {
2185 let mut span = MultiSpan::from_span(yield_span);
2186 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
2187 // #70935: If snippet contains newlines, display "the value" instead
2188 // so that we do not emit complex diagnostics.
2189 let snippet = &format!("`{}`", snippet);
2190 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
2191 // note: future is not `Send` as this value is used across an await
2192 // --> $DIR/issue-70935-complex-spans.rs:13:9
2194 // LL | baz(|| async {
2195 // | ______________-
2198 // LL | | foo(tx.clone());
2200 // | | - ^^^^^^ await occurs here, with value maybe used later
2202 // | has type `closure` which is not `Send`
2203 // note: value is later dropped here
2207 span.push_span_label(
2209 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2211 span.push_span_label(
2213 format!("has type `{}` which {}", target_ty, trait_explanation),
2215 // If available, use the scope span to annotate the drop location.
2216 let mut scope_note = None;
2217 if let Some(scope_span) = scope_span {
2218 let scope_span = source_map.end_point(scope_span);
2220 let msg = format!("{} is later dropped here", snippet);
2221 if source_map.is_multiline(yield_span.between(scope_span)) {
2222 span.push_span_label(scope_span, msg);
2224 scope_note = Some((scope_span, msg));
2230 "{} {} as this value is used across {}",
2231 future_or_generator, trait_explanation, an_await_or_yield
2234 if let Some((span, msg)) = scope_note {
2235 err.span_note(span, &msg);
2239 match interior_or_upvar_span {
2240 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2241 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2242 if let Some(await_span) = from_awaited_ty {
2243 // The type causing this obligation is one being awaited at await_span.
2244 let mut span = MultiSpan::from_span(await_span);
2245 span.push_span_label(
2248 "await occurs here on type `{}`, which {}",
2249 target_ty, trait_explanation
2255 "future {not_trait} as it awaits another future which {not_trait}",
2256 not_trait = trait_explanation
2260 // Look at the last interior type to get a span for the `.await`.
2262 generator_interior_types = ?format_args!(
2263 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2266 explain_yield(interior_span, yield_span, scope_span);
2269 if let Some(expr_id) = expr {
2270 let expr = hir.expect_expr(expr_id);
2271 debug!("target_ty evaluated from {:?}", expr);
2273 let parent = hir.get_parent_node(expr_id);
2274 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2275 let parent_span = hir.span(parent);
2276 let parent_did = parent.owner.to_def_id();
2279 // fn foo(&self) -> i32 {}
2282 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2285 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2287 .expr_adjustments(expr)
2289 .any(|adj| adj.is_region_borrow())
2295 // struct Foo(*const u8);
2296 // bar(Foo(std::ptr::null())).await;
2297 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2299 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2300 let is_raw_borrow_inside_fn_like_call =
2301 match self.tcx.def_kind(parent_did) {
2302 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2305 if let Some(typeck_results) = typeck_results {
2306 if (typeck_results.is_method_call(e) && is_region_borrow)
2307 || is_raw_borrow_inside_fn_like_call
2311 "consider moving this into a `let` \
2312 binding to create a shorter lived borrow",
2320 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2321 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2322 let refers_to_non_sync = match target_ty.kind() {
2323 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2324 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2330 let (span_label, span_note) = match refers_to_non_sync {
2331 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2332 // include suggestions to make `T: Sync` so that `&T: Send`
2335 "has type `{}` which {}, because `{}` is not `Sync`",
2336 target_ty, trait_explanation, ref_ty
2339 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2344 format!("has type `{}` which {}", target_ty, trait_explanation),
2345 format!("captured value {}", trait_explanation),
2349 let mut span = MultiSpan::from_span(upvar_span);
2350 span.push_span_label(upvar_span, span_label);
2351 err.span_note(span, &span_note);
2355 // Add a note for the item obligation that remains - normally a note pointing to the
2356 // bound that introduced the obligation (e.g. `T: Send`).
2358 self.note_obligation_cause_code(
2360 obligation.predicate,
2361 obligation.param_env,
2364 &mut Default::default(),
2368 fn note_obligation_cause_code<T>(
2370 err: &mut Diagnostic,
2372 param_env: ty::ParamEnv<'tcx>,
2373 cause_code: &ObligationCauseCode<'tcx>,
2374 obligated_types: &mut Vec<Ty<'tcx>>,
2375 seen_requirements: &mut FxHashSet<DefId>,
2377 T: ToPredicate<'tcx>,
2380 let predicate = predicate.to_predicate(tcx);
2382 ObligationCauseCode::ExprAssignable
2383 | ObligationCauseCode::MatchExpressionArm { .. }
2384 | ObligationCauseCode::Pattern { .. }
2385 | ObligationCauseCode::IfExpression { .. }
2386 | ObligationCauseCode::IfExpressionWithNoElse
2387 | ObligationCauseCode::MainFunctionType
2388 | ObligationCauseCode::StartFunctionType
2389 | ObligationCauseCode::IntrinsicType
2390 | ObligationCauseCode::MethodReceiver
2391 | ObligationCauseCode::ReturnNoExpression
2392 | ObligationCauseCode::UnifyReceiver(..)
2393 | ObligationCauseCode::OpaqueType
2394 | ObligationCauseCode::MiscObligation
2395 | ObligationCauseCode::WellFormed(..)
2396 | ObligationCauseCode::MatchImpl(..)
2397 | ObligationCauseCode::ReturnType
2398 | ObligationCauseCode::ReturnValue(_)
2399 | ObligationCauseCode::BlockTailExpression(_)
2400 | ObligationCauseCode::AwaitableExpr(_)
2401 | ObligationCauseCode::ForLoopIterator
2402 | ObligationCauseCode::QuestionMark
2403 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2404 | ObligationCauseCode::LetElse
2405 | ObligationCauseCode::BinOp { .. }
2406 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2407 | ObligationCauseCode::RustCall => {}
2408 ObligationCauseCode::SliceOrArrayElem => {
2409 err.note("slice and array elements must have `Sized` type");
2411 ObligationCauseCode::TupleElem => {
2412 err.note("only the last element of a tuple may have a dynamically sized type");
2414 ObligationCauseCode::ProjectionWf(data) => {
2415 err.note(&format!("required so that the projection `{data}` is well-formed"));
2417 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2419 "required so that reference `{ref_ty}` does not outlive its referent"
2422 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2424 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2428 ObligationCauseCode::ItemObligation(_)
2429 | ObligationCauseCode::ExprItemObligation(..) => {
2430 // We hold the `DefId` of the item introducing the obligation, but displaying it
2431 // doesn't add user usable information. It always point at an associated item.
2433 ObligationCauseCode::BindingObligation(item_def_id, span)
2434 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2435 let item_name = tcx.def_path_str(item_def_id);
2436 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2437 let mut multispan = MultiSpan::from(span);
2438 let sm = tcx.sess.source_map();
2439 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2441 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2442 (Ok(l), Ok(r)) => l.line == r.line,
2445 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2446 multispan.push_span_label(ident.span, "required by a bound in this");
2449 let descr = format!("required by a bound in `{item_name}`");
2450 if span.is_visible(sm) {
2451 let msg = format!("required by this bound in `{short_item_name}`");
2452 multispan.push_span_label(span, msg);
2453 err.span_note(multispan, &descr);
2455 err.span_note(tcx.def_span(item_def_id), &descr);
2458 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2460 "required for the cast from `{}` to the object type `{}`",
2461 self.ty_to_string(concrete_ty),
2462 self.ty_to_string(object_ty)
2465 ObligationCauseCode::Coercion { source: _, target } => {
2466 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2468 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2470 "the `Copy` trait is required because this value will be copied for each element of the array",
2475 "consider creating a new `const` item and initializing it with the result \
2476 of the function call to be used in the repeat position, like \
2477 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2481 if self.tcx.sess.is_nightly_build() && is_const_fn {
2483 "create an inline `const` block, see RFC #2920 \
2484 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2488 ObligationCauseCode::VariableType(hir_id) => {
2489 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2490 match self.tcx.hir().find(parent_node) {
2491 Some(Node::Local(hir::Local {
2492 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2495 // When encountering an assignment of an unsized trait, like
2496 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2497 // order to use have a slice instead.
2498 err.span_suggestion_verbose(
2499 span.shrink_to_lo(),
2500 "consider borrowing here",
2502 Applicability::MachineApplicable,
2504 err.note("all local variables must have a statically known size");
2506 Some(Node::Param(param)) => {
2507 err.span_suggestion_verbose(
2508 param.ty_span.shrink_to_lo(),
2509 "function arguments must have a statically known size, borrowed types \
2510 always have a known size",
2512 Applicability::MachineApplicable,
2516 err.note("all local variables must have a statically known size");
2519 if !self.tcx.features().unsized_locals {
2520 err.help("unsized locals are gated as an unstable feature");
2523 ObligationCauseCode::SizedArgumentType(sp) => {
2524 if let Some(span) = sp {
2525 err.span_suggestion_verbose(
2526 span.shrink_to_lo(),
2527 "function arguments must have a statically known size, borrowed types \
2528 always have a known size",
2530 Applicability::MachineApplicable,
2533 err.note("all function arguments must have a statically known size");
2535 if tcx.sess.opts.unstable_features.is_nightly_build()
2536 && !self.tcx.features().unsized_fn_params
2538 err.help("unsized fn params are gated as an unstable feature");
2541 ObligationCauseCode::SizedReturnType => {
2542 err.note("the return type of a function must have a statically known size");
2544 ObligationCauseCode::SizedYieldType => {
2545 err.note("the yield type of a generator must have a statically known size");
2547 ObligationCauseCode::SizedBoxType => {
2548 err.note("the type of a box expression must have a statically known size");
2550 ObligationCauseCode::AssignmentLhsSized => {
2551 err.note("the left-hand-side of an assignment must have a statically known size");
2553 ObligationCauseCode::TupleInitializerSized => {
2554 err.note("tuples must have a statically known size to be initialized");
2556 ObligationCauseCode::StructInitializerSized => {
2557 err.note("structs must have a statically known size to be initialized");
2559 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2561 AdtKind::Struct => {
2564 "the last field of a packed struct may only have a \
2565 dynamically sized type if it does not need drop to be run",
2569 "only the last field of a struct may have a dynamically sized type",
2574 err.note("no field of a union may have a dynamically sized type");
2577 err.note("no field of an enum variant may have a dynamically sized type");
2580 err.help("change the field's type to have a statically known size");
2581 err.span_suggestion(
2582 span.shrink_to_lo(),
2583 "borrowed types always have a statically known size",
2585 Applicability::MachineApplicable,
2587 err.multipart_suggestion(
2588 "the `Box` type always has a statically known size and allocates its contents \
2591 (span.shrink_to_lo(), "Box<".to_string()),
2592 (span.shrink_to_hi(), ">".to_string()),
2594 Applicability::MachineApplicable,
2597 ObligationCauseCode::ConstSized => {
2598 err.note("constant expressions must have a statically known size");
2600 ObligationCauseCode::InlineAsmSized => {
2601 err.note("all inline asm arguments must have a statically known size");
2603 ObligationCauseCode::ConstPatternStructural => {
2604 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2606 ObligationCauseCode::SharedStatic => {
2607 err.note("shared static variables must have a type that implements `Sync`");
2609 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2610 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2611 let ty = parent_trait_ref.skip_binder().self_ty();
2612 if parent_trait_ref.references_error() {
2613 // NOTE(eddyb) this was `.cancel()`, but `err`
2614 // is borrowed, so we can't fully defuse it.
2615 err.downgrade_to_delayed_bug();
2619 // If the obligation for a tuple is set directly by a Generator or Closure,
2620 // then the tuple must be the one containing capture types.
2621 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2624 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2626 let parent_trait_ref =
2627 self.resolve_vars_if_possible(data.parent_trait_pred);
2628 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2629 matches!(nested_ty.kind(), ty::Generator(..))
2630 || matches!(nested_ty.kind(), ty::Closure(..))
2636 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2638 // Don't print the tuple of capture types
2640 if !is_upvar_tys_infer_tuple {
2641 let msg = format!("required because it appears within the type `{}`", ty);
2643 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2644 Some(ident) => err.span_note(ident.span, &msg),
2645 None => err.note(&msg),
2647 ty::Opaque(def_id, _) => {
2648 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2649 if tcx.parent(*def_id) == identity_future {
2653 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2654 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2655 let is_future = tcx.ty_is_opaque_future(ty);
2659 "note_obligation_cause_code: check for async fn"
2662 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2663 ty::Generator(last_def_id, ..) => {
2664 tcx.generator_is_async(*last_def_id)
2671 err.span_note(self.tcx.def_span(def_id), &msg)
2673 ty::GeneratorWitness(bound_tys) => {
2674 use std::fmt::Write;
2676 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2677 // Maybe we should just remove this note altogether?
2678 // FIXME: only print types which don't meet the trait requirement
2680 "required because it captures the following types: ".to_owned();
2681 for ty in bound_tys.skip_binder() {
2682 write!(msg, "`{}`, ", ty).unwrap();
2684 err.note(msg.trim_end_matches(", "))
2686 ty::Generator(def_id, _, _) => {
2687 let sp = self.tcx.def_span(def_id);
2689 // Special-case this to say "async block" instead of `[static generator]`.
2690 let kind = tcx.generator_kind(def_id).unwrap().descr();
2693 &format!("required because it's used within this {}", kind),
2696 ty::Closure(def_id, _) => err.span_note(
2697 self.tcx.def_span(def_id),
2698 &format!("required because it's used within this closure"),
2700 _ => err.note(&msg),
2705 obligated_types.push(ty);
2707 let parent_predicate = parent_trait_ref;
2708 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2709 // #74711: avoid a stack overflow
2710 ensure_sufficient_stack(|| {
2711 self.note_obligation_cause_code(
2721 ensure_sufficient_stack(|| {
2722 self.note_obligation_cause_code(
2726 cause_code.peel_derives(),
2733 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2734 let mut parent_trait_pred =
2735 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2736 parent_trait_pred.remap_constness_diag(param_env);
2737 let parent_def_id = parent_trait_pred.def_id();
2738 let (self_ty, file) =
2739 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2741 "required for `{self_ty}` to implement `{}`",
2742 parent_trait_pred.print_modifiers_and_trait_path()
2744 let mut is_auto_trait = false;
2745 match self.tcx.hir().get_if_local(data.impl_def_id) {
2746 Some(Node::Item(hir::Item {
2747 kind: hir::ItemKind::Trait(is_auto, ..),
2751 // FIXME: we should do something else so that it works even on crate foreign
2753 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2754 err.span_note(ident.span, &msg)
2756 Some(Node::Item(hir::Item {
2757 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2760 let mut spans = Vec::with_capacity(2);
2761 if let Some(trait_ref) = of_trait {
2762 spans.push(trait_ref.path.span);
2764 spans.push(self_ty.span);
2765 err.span_note(spans, &msg)
2767 _ => err.note(&msg),
2770 if let Some(file) = file {
2772 "the full type name has been written to '{}'",
2776 let mut parent_predicate = parent_trait_pred;
2777 let mut data = &data.derived;
2779 seen_requirements.insert(parent_def_id);
2781 // We don't want to point at the ADT saying "required because it appears within
2782 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2783 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2786 let child_trait_ref =
2787 self.resolve_vars_if_possible(derived.parent_trait_pred);
2788 let child_def_id = child_trait_ref.def_id();
2789 if seen_requirements.insert(child_def_id) {
2793 parent_predicate = child_trait_ref.to_predicate(tcx);
2794 parent_trait_pred = child_trait_ref;
2797 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2798 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2799 let child_trait_pred =
2800 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2801 let child_def_id = child_trait_pred.def_id();
2802 if seen_requirements.insert(child_def_id) {
2806 data = &child.derived;
2807 parent_predicate = child_trait_pred.to_predicate(tcx);
2808 parent_trait_pred = child_trait_pred;
2812 "{} redundant requirement{} hidden",
2816 let (self_ty, file) =
2817 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2819 "required for `{self_ty}` to implement `{}`",
2820 parent_trait_pred.print_modifiers_and_trait_path()
2822 if let Some(file) = file {
2824 "the full type name has been written to '{}'",
2829 // #74711: avoid a stack overflow
2830 ensure_sufficient_stack(|| {
2831 self.note_obligation_cause_code(
2841 ObligationCauseCode::DerivedObligation(ref data) => {
2842 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2843 let parent_predicate = parent_trait_ref;
2844 // #74711: avoid a stack overflow
2845 ensure_sufficient_stack(|| {
2846 self.note_obligation_cause_code(
2856 ObligationCauseCode::FunctionArgumentObligation {
2861 self.function_argument_obligation(
2869 ensure_sufficient_stack(|| {
2870 self.note_obligation_cause_code(
2880 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2881 let item_name = self.tcx.item_name(trait_item_def_id);
2883 "the requirement `{predicate}` appears on the `impl`'s {kind} \
2884 `{item_name}` but not on the corresponding trait's {kind}",
2888 .opt_item_ident(trait_item_def_id)
2890 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2891 let mut assoc_span: MultiSpan = sp.into();
2892 assoc_span.push_span_label(
2894 format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
2896 if let Some(ident) = self
2898 .opt_associated_item(trait_item_def_id)
2899 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2901 assoc_span.push_span_label(ident.span, "in this trait");
2903 err.span_note(assoc_span, &msg);
2905 ObligationCauseCode::TrivialBound => {
2906 err.help("see issue #48214");
2907 if tcx.sess.opts.unstable_features.is_nightly_build() {
2908 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2911 ObligationCauseCode::OpaqueReturnType(expr_info) => {
2912 if let Some((expr_ty, expr_span)) = expr_info {
2913 let expr_ty = with_forced_trimmed_paths!(self.ty_to_string(expr_ty));
2916 format!("return type was inferred to be `{expr_ty}` here"),
2924 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2926 fn suggest_await_before_try(
2928 err: &mut Diagnostic,
2929 obligation: &PredicateObligation<'tcx>,
2930 trait_pred: ty::PolyTraitPredicate<'tcx>,
2933 let body_hir_id = obligation.cause.body_id;
2934 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2936 if let Some(body_id) =
2937 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2939 let body = self.tcx.hir().body(body_id);
2940 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2941 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2943 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2944 let impls_future = self.type_implements_trait(
2946 [self.tcx.erase_late_bound_regions(self_ty)],
2947 obligation.param_env,
2949 if !impls_future.must_apply_modulo_regions() {
2953 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2954 // `<T as Future>::Output`
2955 let projection_ty = trait_pred.map_bound(|trait_pred| {
2956 self.tcx.mk_projection(
2958 // Future::Output has no substs
2959 self.tcx.mk_substs_trait(trait_pred.self_ty(), []),
2962 let InferOk { value: projection_ty, .. } =
2963 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
2966 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
2968 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2969 obligation.param_env,
2970 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
2972 debug!(try_trait_obligation = ?try_obligation);
2973 if self.predicate_may_hold(&try_obligation)
2974 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2975 && snippet.ends_with('?')
2977 err.span_suggestion_verbose(
2978 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2979 "consider `await`ing on the `Future`",
2981 Applicability::MaybeIncorrect,
2988 fn suggest_floating_point_literal(
2990 obligation: &PredicateObligation<'tcx>,
2991 err: &mut Diagnostic,
2992 trait_ref: &ty::PolyTraitRef<'tcx>,
2994 let rhs_span = match obligation.cause.code() {
2995 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
2998 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
2999 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3001 err.span_suggestion_verbose(
3002 rhs_span.shrink_to_hi(),
3003 "consider using a floating-point literal by writing it with `.0`",
3005 Applicability::MaybeIncorrect,
3012 obligation: &PredicateObligation<'tcx>,
3013 err: &mut Diagnostic,
3014 trait_pred: ty::PolyTraitPredicate<'tcx>,
3016 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3019 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3020 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3024 let is_derivable_trait = match diagnostic_name {
3025 sym::Default => !adt.is_enum(),
3026 sym::PartialEq | sym::PartialOrd => {
3027 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3028 trait_pred.skip_binder().self_ty() == rhs_ty
3030 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3033 is_derivable_trait &&
3034 // Ensure all fields impl the trait.
3035 adt.all_fields().all(|field| {
3036 let field_ty = field.ty(self.tcx, substs);
3037 let trait_substs = match diagnostic_name {
3038 sym::PartialEq | sym::PartialOrd => {
3043 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3044 trait_ref: self.tcx.mk_trait_ref(
3045 trait_pred.def_id(),
3046 [field_ty].into_iter().chain(trait_substs),
3050 let field_obl = Obligation::new(
3052 obligation.cause.clone(),
3053 obligation.param_env,
3056 self.predicate_must_hold_modulo_regions(&field_obl)
3060 err.span_suggestion_verbose(
3061 self.tcx.def_span(adt.did()).shrink_to_lo(),
3063 "consider annotating `{}` with `#[derive({})]`",
3064 trait_pred.skip_binder().self_ty(),
3067 format!("#[derive({})]\n", diagnostic_name),
3068 Applicability::MaybeIncorrect,
3073 fn suggest_dereferencing_index(
3075 obligation: &PredicateObligation<'tcx>,
3076 err: &mut Diagnostic,
3077 trait_pred: ty::PolyTraitPredicate<'tcx>,
3079 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3080 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3081 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3082 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3083 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3085 err.span_suggestion_verbose(
3086 obligation.cause.span.shrink_to_lo(),
3087 "dereference this index",
3089 Applicability::MachineApplicable,
3093 fn function_argument_obligation(
3096 err: &mut Diagnostic,
3097 parent_code: &ObligationCauseCode<'tcx>,
3098 param_env: ty::ParamEnv<'tcx>,
3099 predicate: ty::Predicate<'tcx>,
3103 let hir = tcx.hir();
3104 if let Some(Node::Expr(expr)) = hir.find(arg_hir_id) {
3105 let parent_id = hir.get_parent_item(arg_hir_id);
3106 let typeck_results: &TypeckResults<'tcx> = match &self.typeck_results {
3107 Some(t) if t.hir_owner == parent_id => t,
3108 _ => self.tcx.typeck(parent_id.def_id),
3110 if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
3111 let expr = expr.peel_blocks();
3112 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
3113 let span = expr.span;
3114 if Some(span) != err.span.primary_span() {
3117 if ty.references_error() {
3120 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3121 format!("this tail expression is of type `{ty}`")
3127 // FIXME: visit the ty to see if there's any closure involved, and if there is,
3128 // check whether its evaluated return type is the same as the one corresponding
3129 // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3130 // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3131 let mut type_diffs = vec![];
3133 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
3134 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
3135 && let Some(pred) = predicates.predicates.get(*idx)
3136 && let Ok(trait_pred) = pred.kind().try_map_bound(|pred| match pred {
3137 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) => Ok(trait_pred),
3141 let mut c = CollectAllMismatches {
3146 if let Ok(trait_predicate) = predicate.kind().try_map_bound(|pred| match pred {
3147 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) => Ok(trait_pred),
3150 if let Ok(_) = c.relate(trait_pred, trait_predicate) {
3151 type_diffs = c.errors;
3155 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3156 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3157 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3158 && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3159 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3160 && let Some(binding_expr) = local.init
3162 // If the expression we're calling on is a binding, we want to point at the
3163 // `let` when talking about the type. Otherwise we'll point at every part
3164 // of the method chain with the type.
3165 self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
3167 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
3170 let call_node = hir.find(call_hir_id);
3171 if let Some(Node::Expr(hir::Expr {
3172 kind: hir::ExprKind::MethodCall(path, rcvr, ..), ..
3175 if Some(rcvr.span) == err.span.primary_span() {
3176 err.replace_span_with(path.ident.span);
3179 if let Some(Node::Expr(hir::Expr {
3181 hir::ExprKind::Call(hir::Expr { span, .. }, _)
3182 | hir::ExprKind::MethodCall(hir::PathSegment { ident: Ident { span, .. }, .. }, ..),
3184 })) = hir.find(call_hir_id)
3186 if Some(*span) != err.span.primary_span() {
3187 err.span_label(*span, "required by a bound introduced by this call");
3194 expr: &hir::Expr<'_>,
3195 typeck_results: &TypeckResults<'tcx>,
3196 type_diffs: Vec<TypeError<'tcx>>,
3197 param_env: ty::ParamEnv<'tcx>,
3198 err: &mut Diagnostic,
3200 let mut primary_spans = vec![];
3201 let mut span_labels = vec![];
3205 let mut assocs = vec![];
3206 // We still want to point at the different methods even if there hasn't
3207 // been a change of assoc type.
3208 let mut call_spans = vec![];
3209 let mut expr = expr;
3210 let mut prev_ty = self.resolve_vars_if_possible(
3211 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3213 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) = expr.kind {
3214 // Point at every method call in the chain with the resulting type.
3215 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3216 // ^^^^^^ ^^^^^^^^^^^
3218 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
3219 call_spans.push(span);
3221 let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
3222 for diff in &type_diffs {
3223 let Sorts(expected_found) = diff else { continue; };
3224 let ty::Projection(proj) = expected_found.expected.kind() else { continue; };
3227 TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span };
3228 let trait_def_id = proj.trait_def_id(self.tcx);
3229 // Make `Self` be equivalent to the type of the call chain
3230 // expression we're looking at now, so that we can tell what
3231 // for example `Iterator::Item` is at this point in the chain.
3232 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
3234 ty::GenericParamDefKind::Type { .. } => {
3235 if param.index == 0 {
3236 return prev_ty.into();
3239 ty::GenericParamDefKind::Lifetime
3240 | ty::GenericParamDefKind::Const { .. } => {}
3242 self.var_for_def(span, param)
3244 // This will hold the resolved type of the associated type, if the
3245 // current expression implements the trait that associated type is
3246 // in. For example, this would be what `Iterator::Item` is here.
3247 let ty_var = self.infcx.next_ty_var(origin);
3248 // This corresponds to `<ExprTy as Iterator>::Item = _`.
3249 let trait_ref = ty::Binder::dummy(ty::PredicateKind::Clause(
3250 ty::Clause::Projection(ty::ProjectionPredicate {
3251 projection_ty: ty::ProjectionTy { substs, item_def_id: proj.item_def_id },
3252 term: ty_var.into(),
3255 // Add `<ExprTy as Iterator>::Item = _` obligation.
3256 ocx.register_obligation(Obligation::misc(
3263 if ocx.select_where_possible().is_empty() {
3264 // `ty_var` now holds the type that `Item` is for `ExprTy`.
3265 let ty_var = self.resolve_vars_if_possible(ty_var);
3266 assocs_in_this_method.push(Some((span, (proj.item_def_id, ty_var))));
3268 // `<ExprTy as Iterator>` didn't select, so likely we've
3269 // reached the end of the iterator chain, like the originating
3271 // Keep the space consistent for later zipping.
3272 assocs_in_this_method.push(None);
3275 assocs.push(assocs_in_this_method);
3276 prev_ty = self.resolve_vars_if_possible(
3277 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3280 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3281 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3282 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3283 && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3284 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3285 && let Some(binding_expr) = local.init
3287 // We've reached the root of the method call chain and it is a
3288 // binding. Get the binding creation and try to continue the chain.
3289 expr = binding_expr;
3292 // We want the type before deref coercions, otherwise we talk about `&[_]`
3293 // instead of `Vec<_>`.
3294 if let Some(ty) = typeck_results.expr_ty_opt(expr) {
3295 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3296 // Point at the root expression
3297 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3299 span_labels.push((expr.span, format!("this expression has type `{ty}`")));
3301 // Only show this if it is not a "trivial" expression (not a method
3302 // chain) and there are associated types to talk about.
3303 let mut assocs = assocs.into_iter().peekable();
3304 while let Some(assocs_in_method) = assocs.next() {
3305 let Some(prev_assoc_in_method) = assocs.peek() else {
3306 for entry in assocs_in_method {
3307 let Some((span, (assoc, ty))) = entry else { continue; };
3308 if type_diffs.iter().any(|diff| {
3309 let Sorts(expected_found) = diff else { return false; };
3310 self.can_eq(param_env, expected_found.found, ty).is_ok()
3312 // FIXME: this doesn't quite work for `Iterator::collect`
3313 // because we have `Vec<i32>` and `()`, but we'd want `i32`
3314 // to point at the `.into_iter()` call, but as long as we
3315 // still point at the other method calls that might have
3316 // introduced the issue, this is fine for now.
3317 primary_spans.push(span);
3321 with_forced_trimmed_paths!(format!(
3322 "`{}` is `{ty}` here",
3323 self.tcx.def_path_str(assoc),
3329 for (entry, prev_entry) in
3330 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
3332 match (entry, prev_entry) {
3333 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
3334 let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
3336 let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
3338 if type_diffs.iter().any(|diff| {
3339 let Sorts(expected_found) = diff else { return false; };
3340 self.can_eq(param_env, expected_found.found, ty).is_ok()
3342 primary_spans.push(span);
3345 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
3347 span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
3350 (Some((span, (assoc, ty))), None) => {
3353 with_forced_trimmed_paths!(format!(
3354 "`{}` is `{}` here",
3355 self.tcx.def_path_str(assoc),
3356 self.ty_to_string(ty),
3360 (None, Some(_)) | (None, None) => {}
3364 for span in call_spans {
3365 if span_labels.iter().find(|(s, _)| *s == span).is_none() {
3366 // Ensure we are showing the entire chain, even if the assoc types
3368 span_labels.push((span, String::new()));
3371 if !primary_spans.is_empty() {
3372 let mut multi_span: MultiSpan = primary_spans.into();
3373 for (span, label) in span_labels {
3374 multi_span.push_span_label(span, label);
3379 "the method call chain might not have had the expected \
3387 /// Collect all the returned expressions within the input expression.
3388 /// Used to point at the return spans when we want to suggest some change to them.
3390 pub struct ReturnsVisitor<'v> {
3391 pub returns: Vec<&'v hir::Expr<'v>>,
3392 in_block_tail: bool,
3395 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3396 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3397 // Visit every expression to detect `return` paths, either through the function's tail
3398 // expression or `return` statements. We walk all nodes to find `return` statements, but
3399 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3400 // they're in the return path of the function body.
3402 hir::ExprKind::Ret(Some(ex)) => {
3403 self.returns.push(ex);
3405 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3406 self.in_block_tail = false;
3407 for stmt in block.stmts {
3408 hir::intravisit::walk_stmt(self, stmt);
3410 self.in_block_tail = true;
3411 if let Some(expr) = block.expr {
3412 self.visit_expr(expr);
3415 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3416 self.visit_expr(then);
3417 if let Some(el) = else_opt {
3418 self.visit_expr(el);
3421 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3423 self.visit_expr(arm.body);
3426 // We need to walk to find `return`s in the entire body.
3427 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3428 _ => self.returns.push(ex),
3432 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3433 assert!(!self.in_block_tail);
3434 if body.generator_kind().is_none() {
3435 if let hir::ExprKind::Block(block, None) = body.value.kind {
3436 if block.expr.is_some() {
3437 self.in_block_tail = true;
3441 hir::intravisit::walk_body(self, body);
3445 /// Collect all the awaited expressions within the input expression.
3447 struct AwaitsVisitor {
3448 awaits: Vec<hir::HirId>,
3451 impl<'v> Visitor<'v> for AwaitsVisitor {
3452 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3453 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3454 self.awaits.push(id)
3456 hir::intravisit::walk_expr(self, ex)
3460 pub trait NextTypeParamName {
3461 fn next_type_param_name(&self, name: Option<&str>) -> String;
3464 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3465 fn next_type_param_name(&self, name: Option<&str>) -> String {
3466 // This is the list of possible parameter names that we might suggest.
3467 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3468 let name = name.as_deref();
3469 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3470 let used_names = self
3472 .filter_map(|p| match p.name {
3473 hir::ParamName::Plain(ident) => Some(ident.name),
3476 .collect::<Vec<_>>();
3480 .find(|n| !used_names.contains(&Symbol::intern(n)))
3481 .unwrap_or(&"ParamName")
3486 fn suggest_trait_object_return_type_alternatives(
3487 err: &mut Diagnostic,
3490 is_object_safe: bool,
3492 err.span_suggestion(
3494 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3497 Applicability::MaybeIncorrect,
3499 err.span_suggestion(
3502 "use `impl {}` as the return type if all return paths have the same type but you \
3503 want to expose only the trait in the signature",
3506 format!("impl {}", trait_obj),
3507 Applicability::MaybeIncorrect,
3510 err.multipart_suggestion(
3512 "use a boxed trait object if all return paths implement trait `{}`",
3516 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3517 (ret_ty.shrink_to_hi(), ">".to_string()),
3519 Applicability::MaybeIncorrect,
3524 /// Collect the spans that we see the generic param `param_did`
3525 struct ReplaceImplTraitVisitor<'a> {
3526 ty_spans: &'a mut Vec<Span>,
3530 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3531 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3532 if let hir::TyKind::Path(hir::QPath::Resolved(
3534 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3537 if self.param_did == *segment_did {
3538 // `fn foo(t: impl Trait)`
3539 // ^^^^^^^^^^ get this to suggest `T` instead
3541 // There might be more than one `impl Trait`.
3542 self.ty_spans.push(t.span);
3547 hir::intravisit::walk_ty(self, t);
3551 // Replace `param` with `replace_ty`
3552 struct ReplaceImplTraitFolder<'tcx> {
3554 param: &'tcx ty::GenericParamDef,
3555 replace_ty: Ty<'tcx>,
3558 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3559 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3560 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3561 if self.param.index == *index {
3562 return self.replace_ty;
3565 t.super_fold_with(self)
3568 fn tcx(&self) -> TyCtxt<'tcx> {