1 // ignore-tidy-filelength
3 use super::{DefIdOrName, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation};
5 use crate::autoderef::Autoderef;
6 use crate::infer::InferCtxt;
7 use crate::traits::{NormalizeExt, ObligationCtxt};
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_data_structures::stack::ensure_sufficient_stack;
14 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
15 ErrorGuaranteed, MultiSpan, Style,
18 use rustc_hir::def::DefKind;
19 use rustc_hir::def_id::DefId;
20 use rustc_hir::intravisit::Visitor;
21 use rustc_hir::lang_items::LangItem;
22 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
23 use rustc_infer::infer::error_reporting::TypeErrCtxt;
24 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
25 use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime};
26 use rustc_middle::hir::map;
27 use rustc_middle::ty::error::TypeError::{self, Sorts};
28 use rustc_middle::ty::relate::TypeRelation;
29 use rustc_middle::ty::{
30 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
31 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, InternalSubsts,
32 IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder,
33 TypeSuperFoldable, TypeVisitable, TypeckResults,
35 use rustc_span::symbol::{sym, Ident, Symbol};
36 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
37 use rustc_target::spec::abi;
40 use super::method_chain::CollectAllMismatches;
41 use super::InferCtxtPrivExt;
42 use crate::infer::InferCtxtExt as _;
43 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
44 use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
47 pub enum GeneratorInteriorOrUpvar {
48 // span of interior type
49 Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
54 // This type provides a uniform interface to retrieve data on generators, whether it originated from
55 // the local crate being compiled or from a foreign crate.
57 pub enum GeneratorData<'tcx, 'a> {
58 Local(&'a TypeckResults<'tcx>),
59 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
62 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
63 // Try to get information about variables captured by the generator that matches a type we are
64 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
66 fn try_get_upvar_span<F>(
68 infer_context: &InferCtxt<'tcx>,
71 ) -> Option<GeneratorInteriorOrUpvar>
73 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
76 GeneratorData::Local(typeck_results) => {
77 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
78 upvars.iter().find_map(|(upvar_id, upvar)| {
79 let upvar_ty = typeck_results.node_type(*upvar_id);
80 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
81 if ty_matches(ty::Binder::dummy(upvar_ty)) {
82 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
89 GeneratorData::Foreign(_) => None,
93 // Try to get the span of a type being awaited on that matches the type we are looking with the
94 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
96 fn get_from_await_ty<F>(
98 visitor: AwaitsVisitor,
103 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
106 GeneratorData::Local(typeck_results) => visitor
109 .map(|id| hir.expect_expr(id))
111 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
113 .map(|expr| expr.span),
114 GeneratorData::Foreign(generator_diagnostic_data) => visitor
117 .map(|id| hir.expect_expr(id))
119 ty_matches(ty::Binder::dummy(
120 generator_diagnostic_data
122 .get(&await_expr.hir_id.local_id)
123 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
125 .map_or_else::<Ty<'tcx>, _, _>(
127 generator_diagnostic_data
129 .get(&await_expr.hir_id.local_id)
133 "node_type: no type for node `{}`",
134 ty::tls::with(|tcx| tcx
136 .node_to_string(await_expr.hir_id))
144 .map(|expr| expr.span),
148 /// Get the type, expression, span and optional scope span of all types
149 /// that are live across the yield of this generator
150 fn get_generator_interior_types(
152 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
154 GeneratorData::Local(typeck_result) => {
155 typeck_result.generator_interior_types.as_deref()
157 GeneratorData::Foreign(generator_diagnostic_data) => {
158 generator_diagnostic_data.generator_interior_types.as_deref()
163 // Used to get the source of the data, note we don't have as much information for generators
164 // originated from foreign crates
165 fn is_foreign(&self) -> bool {
167 GeneratorData::Local(_) => false,
168 GeneratorData::Foreign(_) => true,
173 // This trait is public to expose the diagnostics methods to clippy.
174 pub trait TypeErrCtxtExt<'tcx> {
175 fn suggest_restricting_param_bound(
177 err: &mut Diagnostic,
178 trait_pred: ty::PolyTraitPredicate<'tcx>,
179 associated_item: Option<(&'static str, Ty<'tcx>)>,
183 fn suggest_dereferences(
185 obligation: &PredicateObligation<'tcx>,
186 err: &mut Diagnostic,
187 trait_pred: ty::PolyTraitPredicate<'tcx>,
190 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
194 obligation: &PredicateObligation<'tcx>,
195 err: &mut Diagnostic,
196 trait_pred: ty::PolyTraitPredicate<'tcx>,
199 fn suggest_add_reference_to_arg(
201 obligation: &PredicateObligation<'tcx>,
202 err: &mut Diagnostic,
203 trait_pred: ty::PolyTraitPredicate<'tcx>,
204 has_custom_message: bool,
207 fn suggest_borrowing_for_object_cast(
209 err: &mut Diagnostic,
210 obligation: &PredicateObligation<'tcx>,
215 fn suggest_remove_reference(
217 obligation: &PredicateObligation<'tcx>,
218 err: &mut Diagnostic,
219 trait_pred: ty::PolyTraitPredicate<'tcx>,
222 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
224 fn suggest_change_mut(
226 obligation: &PredicateObligation<'tcx>,
227 err: &mut Diagnostic,
228 trait_pred: ty::PolyTraitPredicate<'tcx>,
231 fn suggest_semicolon_removal(
233 obligation: &PredicateObligation<'tcx>,
234 err: &mut Diagnostic,
236 trait_pred: ty::PolyTraitPredicate<'tcx>,
239 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
241 fn suggest_impl_trait(
243 err: &mut Diagnostic,
245 obligation: &PredicateObligation<'tcx>,
246 trait_pred: ty::PolyTraitPredicate<'tcx>,
249 fn point_at_returns_when_relevant(
251 err: &mut Diagnostic,
252 obligation: &PredicateObligation<'tcx>,
255 fn report_closure_arg_mismatch(
258 found_span: Option<Span>,
259 found: ty::PolyTraitRef<'tcx>,
260 expected: ty::PolyTraitRef<'tcx>,
261 cause: &ObligationCauseCode<'tcx>,
262 found_node: Option<Node<'_>>,
263 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
265 fn note_conflicting_closure_bounds(
267 cause: &ObligationCauseCode<'tcx>,
268 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
271 fn suggest_fully_qualified_path(
273 err: &mut Diagnostic,
279 fn maybe_note_obligation_cause_for_async_await(
281 err: &mut Diagnostic,
282 obligation: &PredicateObligation<'tcx>,
285 fn note_obligation_cause_for_async_await(
287 err: &mut Diagnostic,
288 interior_or_upvar_span: GeneratorInteriorOrUpvar,
290 outer_generator: Option<DefId>,
291 trait_pred: ty::TraitPredicate<'tcx>,
293 typeck_results: Option<&ty::TypeckResults<'tcx>>,
294 obligation: &PredicateObligation<'tcx>,
295 next_code: Option<&ObligationCauseCode<'tcx>>,
298 fn note_obligation_cause_code<T>(
300 err: &mut Diagnostic,
302 param_env: ty::ParamEnv<'tcx>,
303 cause_code: &ObligationCauseCode<'tcx>,
304 obligated_types: &mut Vec<Ty<'tcx>>,
305 seen_requirements: &mut FxHashSet<DefId>,
307 T: ToPredicate<'tcx>;
309 /// Suggest to await before try: future? => future.await?
310 fn suggest_await_before_try(
312 err: &mut Diagnostic,
313 obligation: &PredicateObligation<'tcx>,
314 trait_pred: ty::PolyTraitPredicate<'tcx>,
318 fn suggest_floating_point_literal(
320 obligation: &PredicateObligation<'tcx>,
321 err: &mut Diagnostic,
322 trait_ref: &ty::PolyTraitRef<'tcx>,
327 obligation: &PredicateObligation<'tcx>,
328 err: &mut Diagnostic,
329 trait_pred: ty::PolyTraitPredicate<'tcx>,
332 fn suggest_dereferencing_index(
334 obligation: &PredicateObligation<'tcx>,
335 err: &mut Diagnostic,
336 trait_pred: ty::PolyTraitPredicate<'tcx>,
338 fn function_argument_obligation(
341 err: &mut Diagnostic,
342 parent_code: &ObligationCauseCode<'tcx>,
343 param_env: ty::ParamEnv<'tcx>,
344 predicate: ty::Predicate<'tcx>,
349 expr: &hir::Expr<'_>,
350 typeck_results: &TypeckResults<'tcx>,
351 type_diffs: Vec<TypeError<'tcx>>,
352 param_env: ty::ParamEnv<'tcx>,
353 err: &mut Diagnostic,
357 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
359 generics.tail_span_for_predicate_suggestion(),
360 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
364 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
365 /// it can also be an `impl Trait` param that needs to be decomposed to a type
366 /// param for cleaner code.
367 fn suggest_restriction<'tcx>(
370 hir_generics: &hir::Generics<'tcx>,
372 err: &mut Diagnostic,
373 fn_sig: Option<&hir::FnSig<'_>>,
374 projection: Option<&ty::AliasTy<'_>>,
375 trait_pred: ty::PolyTraitPredicate<'tcx>,
376 // When we are dealing with a trait, `super_traits` will be `Some`:
377 // Given `trait T: A + B + C {}`
378 // - ^^^^^^^^^ GenericBounds
381 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
383 if hir_generics.where_clause_span.from_expansion()
384 || hir_generics.where_clause_span.desugaring_kind().is_some()
388 let Some(item_id) = hir_id.as_owner() else { return; };
389 let generics = tcx.generics_of(item_id);
390 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
391 if let Some((param, bound_str, fn_sig)) =
392 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
393 // Shenanigans to get the `Trait` from the `impl Trait`.
394 ty::Param(param) => {
395 let param_def = generics.type_param(param, tcx);
396 if param_def.kind.is_synthetic() {
398 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
399 return Some((param_def, bound_str, sig));
406 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
407 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
410 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
413 if !trait_pred.is_suggestable(tcx, false) {
416 // We know we have an `impl Trait` that doesn't satisfy a required projection.
418 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
419 // types. There should be at least one, but there might be *more* than one. In that
420 // case we could just ignore it and try to identify which one needs the restriction,
421 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
423 let mut ty_spans = vec![];
424 for input in fn_sig.decl.inputs {
425 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
428 // The type param `T: Trait` we will suggest to introduce.
429 let type_param = format!("{}: {}", type_param_name, bound_str);
432 if let Some(span) = hir_generics.span_for_param_suggestion() {
433 (span, format!(", {}", type_param))
435 (hir_generics.span, format!("<{}>", type_param))
437 // `fn foo(t: impl Trait)`
438 // ^ suggest `where <T as Trait>::A: Bound`
439 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
441 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
443 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
444 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
445 // `fn foo(t: impl Trait<A: Bound>)` instead.
446 err.multipart_suggestion(
447 "introduce a type parameter with a trait bound instead of using `impl Trait`",
449 Applicability::MaybeIncorrect,
452 if !trait_pred.is_suggestable(tcx, false) {
455 // Trivial case: `T` needs an extra bound: `T: Bound`.
456 let (sp, suggestion) = match (
460 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
463 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
464 (None, Some((ident, []))) => (
465 ident.span.shrink_to_hi(),
466 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
468 (_, Some((_, [.., bounds]))) => (
469 bounds.span().shrink_to_hi(),
470 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
472 (Some(_), Some((_, []))) => (
473 hir_generics.span.shrink_to_hi(),
474 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
478 err.span_suggestion_verbose(
480 &format!("consider further restricting {}", msg),
482 Applicability::MachineApplicable,
487 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
488 fn suggest_restricting_param_bound(
490 mut err: &mut Diagnostic,
491 trait_pred: ty::PolyTraitPredicate<'tcx>,
492 associated_ty: Option<(&'static str, Ty<'tcx>)>,
495 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
497 let self_ty = trait_pred.skip_binder().self_ty();
498 let (param_ty, projection) = match self_ty.kind() {
499 ty::Param(_) => (true, None),
500 ty::Alias(ty::Projection, projection) => (false, Some(projection)),
504 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
505 // don't suggest `T: Sized + ?Sized`.
506 let mut hir_id = body_id;
507 while let Some(node) = self.tcx.hir().find(hir_id) {
509 hir::Node::Item(hir::Item {
511 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
513 }) if self_ty == self.tcx.types.self_param => {
515 // Restricting `Self` for a single method.
525 Some((ident, bounds)),
530 hir::Node::TraitItem(hir::TraitItem {
532 kind: hir::TraitItemKind::Fn(..),
534 }) if self_ty == self.tcx.types.self_param => {
536 // Restricting `Self` for a single method.
538 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
544 hir::Node::TraitItem(hir::TraitItem {
546 kind: hir::TraitItemKind::Fn(fn_sig, ..),
549 | hir::Node::ImplItem(hir::ImplItem {
551 kind: hir::ImplItemKind::Fn(fn_sig, ..),
554 | hir::Node::Item(hir::Item {
555 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
556 }) if projection.is_some() => {
557 // Missing restriction on associated type of type parameter (unmet projection).
562 "the associated type",
571 hir::Node::Item(hir::Item {
573 hir::ItemKind::Trait(_, _, generics, ..)
574 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
576 }) if projection.is_some() => {
577 // Missing restriction on associated type of type parameter (unmet projection).
582 "the associated type",
592 hir::Node::Item(hir::Item {
594 hir::ItemKind::Struct(_, generics)
595 | hir::ItemKind::Enum(_, generics)
596 | hir::ItemKind::Union(_, generics)
597 | hir::ItemKind::Trait(_, _, generics, ..)
598 | hir::ItemKind::Impl(hir::Impl { generics, .. })
599 | hir::ItemKind::Fn(_, generics, _)
600 | hir::ItemKind::TyAlias(_, generics)
601 | hir::ItemKind::TraitAlias(generics, _)
602 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
605 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
606 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
609 // We skip the 0'th subst (self) because we do not want
610 // to consider the predicate as not suggestible if the
611 // self type is an arg position `impl Trait` -- instead,
612 // we handle that by adding ` + Bound` below.
613 // FIXME(compiler-errors): It would be nice to do the same
614 // this that we do in `suggest_restriction` and pull the
615 // `impl Trait` into a new generic if it shows up somewhere
616 // else in the predicate.
617 if !trait_pred.skip_binder().trait_ref.substs[1..]
619 .all(|g| g.is_suggestable(self.tcx, false))
623 // Missing generic type parameter bound.
624 let param_name = self_ty.to_string();
625 let mut constraint = with_no_trimmed_paths!(
626 trait_pred.print_modifiers_and_trait_path().to_string()
629 if let Some((name, term)) = associated_ty {
630 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
631 // That should be extracted into a helper function.
632 if constraint.ends_with('>') {
633 constraint = format!(
635 &constraint[..constraint.len() - 1],
640 constraint.push_str(&format!("<{} = {}>", name, term));
644 if suggest_constraining_type_param(
650 Some(trait_pred.def_id()),
656 hir::Node::Item(hir::Item {
658 hir::ItemKind::Struct(_, generics)
659 | hir::ItemKind::Enum(_, generics)
660 | hir::ItemKind::Union(_, generics)
661 | hir::ItemKind::Trait(_, _, generics, ..)
662 | hir::ItemKind::Impl(hir::Impl { generics, .. })
663 | hir::ItemKind::Fn(_, generics, _)
664 | hir::ItemKind::TyAlias(_, generics)
665 | hir::ItemKind::TraitAlias(generics, _)
666 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
669 // Missing generic type parameter bound.
670 if suggest_arbitrary_trait_bound(
680 hir::Node::Crate(..) => return,
685 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
689 /// When after several dereferencing, the reference satisfies the trait
690 /// binding. This function provides dereference suggestion for this
691 /// specific situation.
692 fn suggest_dereferences(
694 obligation: &PredicateObligation<'tcx>,
695 err: &mut Diagnostic,
696 trait_pred: ty::PolyTraitPredicate<'tcx>,
698 // It only make sense when suggesting dereferences for arguments
699 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code()
700 else { return false; };
701 let Some(typeck_results) = &self.typeck_results
702 else { return false; };
703 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
704 else { return false; };
705 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
706 else { return false; };
708 let span = obligation.cause.span;
709 let mut real_trait_pred = trait_pred;
710 let mut code = obligation.cause.code();
711 while let Some((parent_code, parent_trait_pred)) = code.parent() {
713 if let Some(parent_trait_pred) = parent_trait_pred {
714 real_trait_pred = parent_trait_pred;
717 let real_ty = real_trait_pred.self_ty();
718 // We `erase_late_bound_regions` here because `make_subregion` does not handle
719 // `ReLateBound`, and we don't particularly care about the regions.
721 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
727 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
728 let mut autoderef = Autoderef::new(
730 obligation.param_env,
731 obligation.cause.body_id,
735 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
737 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
739 // Remapping bound vars here
740 let real_trait_pred_and_ty =
741 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
742 let obligation = self.mk_trait_obligation_with_new_self_ty(
743 obligation.param_env,
744 real_trait_pred_and_ty,
746 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
749 // Don't care about `&mut` because `DerefMut` is used less
750 // often and user will not expect autoderef happens.
751 if let Some(hir::Node::Expr(hir::Expr {
753 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
755 })) = self.tcx.hir().find(*arg_hir_id)
757 let derefs = "*".repeat(steps);
758 err.span_suggestion_verbose(
759 expr.span.shrink_to_lo(),
760 "consider dereferencing here",
762 Applicability::MachineApplicable,
767 } else if real_trait_pred != trait_pred {
768 // This branch addresses #87437.
770 // Remapping bound vars here
771 let real_trait_pred_and_base_ty =
772 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
773 let obligation = self.mk_trait_obligation_with_new_self_ty(
774 obligation.param_env,
775 real_trait_pred_and_base_ty,
777 if self.predicate_may_hold(&obligation) {
778 err.span_suggestion_verbose(
780 "consider dereferencing here",
782 Applicability::MachineApplicable,
792 /// Given a closure's `DefId`, return the given name of the closure.
794 /// This doesn't account for reassignments, but it's only used for suggestions.
795 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
796 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
797 // Get the local name of this closure. This can be inaccurate because
798 // of the possibility of reassignment, but this should be good enough.
800 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
810 let hir = self.tcx.hir();
811 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
812 let parent_node = hir.get_parent_node(hir_id);
813 match hir.find(parent_node) {
814 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
815 get_name(err, &local.pat.kind)
817 // Different to previous arm because one is `&hir::Local` and the other
818 // is `P<hir::Local>`.
819 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
824 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
825 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
826 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
829 obligation: &PredicateObligation<'tcx>,
830 err: &mut Diagnostic,
831 trait_pred: ty::PolyTraitPredicate<'tcx>,
833 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
834 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
836 // Don't suggest calling to turn an unsized type into a sized type
840 // This is duplicated from `extract_callable_info` in typeck, which
841 // relies on autoderef, so we can't use it here.
842 let found = trait_pred.self_ty().skip_binder().peel_refs();
843 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
845 ty::FnPtr(fn_sig) => {
846 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
848 ty::FnDef(def_id, _) => {
849 let fn_sig = found.fn_sig(self.tcx);
850 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
852 ty::Closure(def_id, substs) => {
853 let fn_sig = substs.as_closure().sig();
855 DefIdOrName::DefId(def_id),
857 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
860 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs }) => {
861 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
862 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
863 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
864 // args tuple will always be substs[1]
865 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
868 DefIdOrName::DefId(def_id),
869 pred.kind().rebind(proj.term.ty().unwrap()),
870 pred.kind().rebind(args.as_slice()),
877 ty::Dynamic(data, _, ty::Dyn) => {
878 data.iter().find_map(|pred| {
879 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
880 && Some(proj.def_id) == self.tcx.lang_items().fn_once_output()
881 // for existential projection, substs are shifted over by 1
882 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
885 DefIdOrName::Name("trait object"),
886 pred.rebind(proj.term.ty().unwrap()),
887 pred.rebind(args.as_slice()),
895 obligation.param_env.caller_bounds().iter().find_map(|pred| {
896 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
897 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
898 && proj.projection_ty.self_ty() == found
899 // args tuple will always be substs[1]
900 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
903 DefIdOrName::Name("type parameter"),
904 pred.kind().rebind(proj.term.ty().unwrap()),
905 pred.kind().rebind(args.as_slice()),
913 }) else { return false; };
914 let output = self.replace_bound_vars_with_fresh_vars(
915 obligation.cause.span,
916 LateBoundRegionConversionTime::FnCall,
919 let inputs = inputs.skip_binder().iter().map(|ty| {
920 self.replace_bound_vars_with_fresh_vars(
921 obligation.cause.span,
922 LateBoundRegionConversionTime::FnCall,
927 // Remapping bound vars here
928 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
931 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
932 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
936 // Get the name of the callable and the arguments to be used in the suggestion.
937 let hir = self.tcx.hir();
939 let msg = match def_id_or_name {
940 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
941 DefKind::Ctor(CtorOf::Struct, _) => {
942 "use parentheses to construct this tuple struct".to_string()
944 DefKind::Ctor(CtorOf::Variant, _) => {
945 "use parentheses to construct this tuple variant".to_string()
947 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
949 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
954 if ty.is_suggestable(self.tcx, false) {
955 format!("/* {ty} */")
957 "/* value */".to_string()
963 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
964 && obligation.cause.span.can_be_used_for_suggestions()
966 // When the obligation error has been ensured to have been caused by
967 // an argument, the `obligation.cause.span` points at the expression
968 // of the argument, so we can provide a suggestion. Otherwise, we give
969 // a more general note.
970 err.span_suggestion_verbose(
971 obligation.cause.span.shrink_to_hi(),
974 Applicability::HasPlaceholders,
976 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
977 let name = match hir.get_if_local(def_id) {
978 Some(hir::Node::Expr(hir::Expr {
979 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
982 err.span_label(*fn_decl_span, "consider calling this closure");
983 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
988 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
989 err.span_label(ident.span, "consider calling this function");
992 Some(hir::Node::Ctor(..)) => {
993 let name = self.tcx.def_path_str(def_id);
995 self.tcx.def_span(def_id),
996 format!("consider calling the constructor for `{}`", name),
1002 err.help(&format!("{msg}: `{name}({args})`"));
1007 fn suggest_add_reference_to_arg(
1009 obligation: &PredicateObligation<'tcx>,
1010 err: &mut Diagnostic,
1011 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1012 has_custom_message: bool,
1014 let span = obligation.cause.span;
1016 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
1017 obligation.cause.code()
1020 } else if let ObligationCauseCode::ItemObligation(_)
1021 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1023 obligation.cause.code()
1024 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1025 span.ctxt().outer_expn_data().kind
1027 obligation.cause.code()
1032 // List of traits for which it would be nonsensical to suggest borrowing.
1033 // For instance, immutable references are always Copy, so suggesting to
1034 // borrow would always succeed, but it's probably not what the user wanted.
1035 let mut never_suggest_borrow: Vec<_> =
1036 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1038 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1041 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1042 never_suggest_borrow.push(def_id);
1045 let param_env = obligation.param_env;
1047 // Try to apply the original trait binding obligation by borrowing.
1048 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1049 blacklist: &[DefId]|
1051 if blacklist.contains(&old_pred.def_id()) {
1054 // We map bounds to `&T` and `&mut T`
1055 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1058 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1061 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1064 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1068 let mk_result = |trait_pred_and_new_ty| {
1070 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1071 self.predicate_must_hold_modulo_regions(&obligation)
1073 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1074 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1076 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1077 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1078 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1081 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1082 mutability.is_mut(),
1088 if imm_ref_self_ty_satisfies_pred
1089 || mut_ref_self_ty_satisfies_pred
1090 || ref_inner_ty_satisfies_pred
1092 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1093 // We don't want a borrowing suggestion on the fields in structs,
1096 // the_foos: Vec<Foo>
1100 span.ctxt().outer_expn_data().kind,
1101 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1105 if snippet.starts_with('&') {
1106 // This is already a literal borrow and the obligation is failing
1107 // somewhere else in the obligation chain. Do not suggest non-sense.
1110 // We have a very specific type of error, where just borrowing this argument
1111 // might solve the problem. In cases like this, the important part is the
1112 // original type obligation, not the last one that failed, which is arbitrary.
1113 // Because of this, we modify the error to refer to the original obligation and
1114 // return early in the caller.
1116 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1117 if has_custom_message {
1121 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1126 "the trait `{}` is not implemented for `{}`",
1127 old_pred.print_modifiers_and_trait_path(),
1128 old_pred.self_ty().skip_binder(),
1132 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1133 err.span_suggestions(
1134 span.shrink_to_lo(),
1135 "consider borrowing here",
1136 ["&".to_string(), "&mut ".to_string()],
1137 Applicability::MaybeIncorrect,
1140 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1141 err.span_suggestion_verbose(
1142 span.shrink_to_lo(),
1144 "consider{} borrowing here",
1145 if is_mut { " mutably" } else { "" }
1147 format!("&{}", if is_mut { "mut " } else { "" }),
1148 Applicability::MaybeIncorrect,
1157 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1158 try_borrowing(cause.derived.parent_trait_pred, &[])
1159 } else if let ObligationCauseCode::BindingObligation(_, _)
1160 | ObligationCauseCode::ItemObligation(_)
1161 | ObligationCauseCode::ExprItemObligation(..)
1162 | ObligationCauseCode::ExprBindingObligation(..) = code
1164 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1170 // Suggest borrowing the type
1171 fn suggest_borrowing_for_object_cast(
1173 err: &mut Diagnostic,
1174 obligation: &PredicateObligation<'tcx>,
1176 object_ty: Ty<'tcx>,
1178 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1179 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1181 for predicate in predicates.iter() {
1182 if !self.predicate_must_hold_modulo_regions(
1183 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1189 err.span_suggestion(
1190 obligation.cause.span.shrink_to_lo(),
1192 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1195 Applicability::MaybeIncorrect,
1199 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1200 /// suggest removing these references until we reach a type that implements the trait.
1201 fn suggest_remove_reference(
1203 obligation: &PredicateObligation<'tcx>,
1204 err: &mut Diagnostic,
1205 trait_pred: ty::PolyTraitPredicate<'tcx>,
1207 let span = obligation.cause.span;
1209 let mut suggested = false;
1210 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1212 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1213 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1214 // Do not suggest removal of borrow from type arguments.
1218 // Skipping binder here, remapping below
1219 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1221 for refs_remaining in 0..refs_number {
1222 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1225 suggested_ty = *inner_ty;
1227 // Remapping bound vars here
1228 let trait_pred_and_suggested_ty =
1229 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1231 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1232 obligation.param_env,
1233 trait_pred_and_suggested_ty,
1236 if self.predicate_may_hold(&new_obligation) {
1241 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1243 let remove_refs = refs_remaining + 1;
1245 let msg = if remove_refs == 1 {
1246 "consider removing the leading `&`-reference".to_string()
1248 format!("consider removing {} leading `&`-references", remove_refs)
1251 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1260 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1261 let span = obligation.cause.span;
1263 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1264 let hir = self.tcx.hir();
1265 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1266 if let hir::Node::Expr(expr) = node {
1267 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1268 // and if not maybe suggest doing something else? If we kept the expression around we
1269 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1270 // it is from the local crate.
1271 err.span_suggestion(
1273 "remove the `.await`",
1275 Applicability::MachineApplicable,
1277 // FIXME: account for associated `async fn`s.
1278 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1279 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1280 obligation.predicate.kind().skip_binder()
1284 &format!("this call returns `{}`", pred.self_ty()),
1287 if let Some(typeck_results) = &self.typeck_results
1288 && let ty = typeck_results.expr_ty_adjusted(base)
1289 && let ty::FnDef(def_id, _substs) = ty.kind()
1290 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1291 hir.get_if_local(*def_id)
1294 "alternatively, consider making `fn {}` asynchronous",
1297 if vis_span.is_empty() {
1298 err.span_suggestion_verbose(
1299 span.shrink_to_lo(),
1302 Applicability::MaybeIncorrect,
1305 err.span_suggestion_verbose(
1306 vis_span.shrink_to_hi(),
1309 Applicability::MaybeIncorrect,
1319 /// Check if the trait bound is implemented for a different mutability and note it in the
1321 fn suggest_change_mut(
1323 obligation: &PredicateObligation<'tcx>,
1324 err: &mut Diagnostic,
1325 trait_pred: ty::PolyTraitPredicate<'tcx>,
1327 let points_at_arg = matches!(
1328 obligation.cause.code(),
1329 ObligationCauseCode::FunctionArgumentObligation { .. },
1332 let span = obligation.cause.span;
1333 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1335 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1336 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1337 // Do not suggest removal of borrow from type arguments.
1340 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1341 if trait_pred.has_non_region_infer() {
1342 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1343 // unresolved bindings.
1347 // Skipping binder here, remapping below
1348 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1350 let suggested_ty = match mutability {
1351 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1352 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1355 // Remapping bound vars here
1356 let trait_pred_and_suggested_ty =
1357 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1359 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1360 obligation.param_env,
1361 trait_pred_and_suggested_ty,
1363 let suggested_ty_would_satisfy_obligation = self
1364 .evaluate_obligation_no_overflow(&new_obligation)
1365 .must_apply_modulo_regions();
1366 if suggested_ty_would_satisfy_obligation {
1371 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1372 if points_at_arg && mutability.is_not() && refs_number > 0 {
1373 err.span_suggestion_verbose(
1375 "consider changing this borrow's mutability",
1377 Applicability::MachineApplicable,
1381 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1382 trait_pred.print_modifiers_and_trait_path(),
1384 trait_pred.skip_binder().self_ty(),
1392 fn suggest_semicolon_removal(
1394 obligation: &PredicateObligation<'tcx>,
1395 err: &mut Diagnostic,
1397 trait_pred: ty::PolyTraitPredicate<'tcx>,
1399 let hir = self.tcx.hir();
1400 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1401 let node = hir.find(parent_node);
1402 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1403 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1404 && sig.decl.output.span().overlaps(span)
1405 && blk.expr.is_none()
1406 && trait_pred.self_ty().skip_binder().is_unit()
1407 && let Some(stmt) = blk.stmts.last()
1408 && let hir::StmtKind::Semi(expr) = stmt.kind
1409 // Only suggest this if the expression behind the semicolon implements the predicate
1410 && let Some(typeck_results) = &self.typeck_results
1411 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1412 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1413 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1419 "this expression has type `{}`, which implements `{}`",
1421 trait_pred.print_modifiers_and_trait_path()
1424 err.span_suggestion(
1425 self.tcx.sess.source_map().end_point(stmt.span),
1426 "remove this semicolon",
1428 Applicability::MachineApplicable
1435 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1436 let hir = self.tcx.hir();
1437 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1438 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1442 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1445 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1446 /// applicable and signal that the error has been expanded appropriately and needs to be
1448 fn suggest_impl_trait(
1450 err: &mut Diagnostic,
1452 obligation: &PredicateObligation<'tcx>,
1453 trait_pred: ty::PolyTraitPredicate<'tcx>,
1455 match obligation.cause.code().peel_derives() {
1456 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1457 ObligationCauseCode::SizedReturnType => {}
1461 let hir = self.tcx.hir();
1462 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1463 let node = hir.find(fn_hir_id);
1464 let Some(hir::Node::Item(hir::Item {
1465 kind: hir::ItemKind::Fn(sig, _, body_id),
1471 let body = hir.body(*body_id);
1472 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1473 let ty = trait_pred.skip_binder().self_ty();
1474 let is_object_safe = match ty.kind() {
1475 ty::Dynamic(predicates, _, ty::Dyn) => {
1476 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1479 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1481 // We only want to suggest `impl Trait` to `dyn Trait`s.
1482 // For example, `fn foo() -> str` needs to be filtered out.
1486 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1490 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1491 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1492 // Recursively look for `TraitObject` types and if there's only one, use that span to
1493 // suggest `impl Trait`.
1495 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1496 // otherwise suggest using `Box<dyn Trait>` or an enum.
1497 let mut visitor = ReturnsVisitor::default();
1498 visitor.visit_body(&body);
1500 let typeck_results = self.typeck_results.as_ref().unwrap();
1501 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1503 let ret_types = visitor
1506 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1507 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1508 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1510 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1512 let ty = self.resolve_vars_if_possible(ty);
1514 !matches!(ty.kind(), ty::Error(_))
1515 && last_ty.map_or(true, |last_ty| {
1516 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1517 // *after* in the dependency graph.
1518 match (ty.kind(), last_ty.kind()) {
1519 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1520 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1521 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1523 Infer(InferTy::FreshFloatTy(_)),
1524 Infer(InferTy::FreshFloatTy(_)),
1529 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1532 let mut spans_and_needs_box = vec![];
1534 match liberated_sig.output().kind() {
1535 ty::Dynamic(predicates, _, ty::Dyn) => {
1536 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1537 let param_env = ty::ParamEnv::empty();
1539 if !only_never_return {
1540 for (expr_span, return_ty) in ret_types {
1541 let self_ty_satisfies_dyn_predicates = |self_ty| {
1542 predicates.iter().all(|predicate| {
1543 let pred = predicate.with_self_ty(self.tcx, self_ty);
1544 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1545 self.predicate_may_hold(&obl)
1549 if let ty::Adt(def, substs) = return_ty.kind()
1551 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1553 spans_and_needs_box.push((expr_span, false));
1554 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1555 spans_and_needs_box.push((expr_span, true));
1565 let sm = self.tcx.sess.source_map();
1566 if !ret_ty.span.overlaps(span) {
1569 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1570 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1576 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1577 let name = liberated_sig.output().to_string();
1579 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1580 if !name.starts_with("dyn ") {
1586 err.code(error_code!(E0746));
1587 err.set_primary_message("return type cannot have an unboxed trait object");
1588 err.children.clear();
1589 let impl_trait_msg = "for information on `impl Trait`, see \
1590 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1591 #returning-types-that-implement-traits>";
1592 let trait_obj_msg = "for information on trait objects, see \
1593 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1594 #using-trait-objects-that-allow-for-values-of-different-types>";
1596 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1597 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1598 if only_never_return {
1599 // No return paths, probably using `panic!()` or similar.
1600 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1601 suggest_trait_object_return_type_alternatives(
1607 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1608 // Suggest `-> impl Trait`.
1609 err.span_suggestion(
1612 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1613 which implements `{1}`",
1616 format!("impl {}", trait_obj),
1617 Applicability::MachineApplicable,
1619 err.note(impl_trait_msg);
1622 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1623 err.multipart_suggestion(
1624 "return a boxed trait object instead",
1626 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1627 (span.shrink_to_hi(), ">".to_string()),
1629 Applicability::MaybeIncorrect,
1631 for (span, needs_box) in spans_and_needs_box {
1633 err.multipart_suggestion(
1634 "... and box this value",
1636 (span.shrink_to_lo(), "Box::new(".to_string()),
1637 (span.shrink_to_hi(), ")".to_string()),
1639 Applicability::MaybeIncorrect,
1644 // This is currently not possible to trigger because E0038 takes precedence, but
1645 // leave it in for completeness in case anything changes in an earlier stage.
1647 "if trait `{}` were object-safe, you could return a trait object",
1651 err.note(trait_obj_msg);
1653 "if all the returned values were of the same type you could use `impl {}` as the \
1657 err.note(impl_trait_msg);
1658 err.note("you can create a new `enum` with a variant for each returned type");
1663 fn point_at_returns_when_relevant(
1665 err: &mut Diagnostic,
1666 obligation: &PredicateObligation<'tcx>,
1668 match obligation.cause.code().peel_derives() {
1669 ObligationCauseCode::SizedReturnType => {}
1673 let hir = self.tcx.hir();
1674 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1675 let node = hir.find(parent_node);
1676 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1679 let body = hir.body(*body_id);
1680 // Point at all the `return`s in the function as they have failed trait bounds.
1681 let mut visitor = ReturnsVisitor::default();
1682 visitor.visit_body(&body);
1683 let typeck_results = self.typeck_results.as_ref().unwrap();
1684 for expr in &visitor.returns {
1685 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1686 let ty = self.resolve_vars_if_possible(returned_ty);
1687 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1693 fn report_closure_arg_mismatch(
1696 found_span: Option<Span>,
1697 found: ty::PolyTraitRef<'tcx>,
1698 expected: ty::PolyTraitRef<'tcx>,
1699 cause: &ObligationCauseCode<'tcx>,
1700 found_node: Option<Node<'_>>,
1701 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1702 pub(crate) fn build_fn_sig_ty<'tcx>(
1703 infcx: &InferCtxt<'tcx>,
1704 trait_ref: ty::PolyTraitRef<'tcx>,
1706 let inputs = trait_ref.skip_binder().substs.type_at(1);
1707 let sig = match inputs.kind() {
1708 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1709 infcx.tcx.mk_fn_sig(
1711 infcx.next_ty_var(TypeVariableOrigin {
1713 kind: TypeVariableOriginKind::MiscVariable,
1716 hir::Unsafety::Normal,
1720 _ => infcx.tcx.mk_fn_sig(
1721 std::iter::once(inputs),
1722 infcx.next_ty_var(TypeVariableOrigin {
1724 kind: TypeVariableOriginKind::MiscVariable,
1727 hir::Unsafety::Normal,
1732 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1735 let argument_kind = match expected.skip_binder().self_ty().kind() {
1736 ty::Closure(..) => "closure",
1737 ty::Generator(..) => "generator",
1740 let mut err = struct_span_err!(
1744 "type mismatch in {argument_kind} arguments",
1747 err.span_label(span, "expected due to this");
1749 let found_span = found_span.unwrap_or(span);
1750 err.span_label(found_span, "found signature defined here");
1752 let expected = build_fn_sig_ty(self, expected);
1753 let found = build_fn_sig_ty(self, found);
1755 let (expected_str, found_str) = self.cmp(expected, found);
1757 let signature_kind = format!("{argument_kind} signature");
1758 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1760 self.note_conflicting_closure_bounds(cause, &mut err);
1762 if let Some(found_node) = found_node {
1763 hint_missing_borrow(span, found_span, found, expected, found_node, &mut err);
1769 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1770 // requirements, which will always cause a closure to have a type error.
1771 fn note_conflicting_closure_bounds(
1773 cause: &ObligationCauseCode<'tcx>,
1774 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1776 // First, look for an `ExprBindingObligation`, which means we can get
1777 // the unsubstituted predicate list of the called function. And check
1778 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1779 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1780 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1781 && let Some(pred) = predicates.predicates.get(*idx)
1782 && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
1783 && self.tcx.is_fn_trait(trait_pred.def_id())
1786 self.tcx.anonymize_late_bound_regions(pred.kind().rebind(trait_pred.self_ty()));
1787 let expected_substs = self
1789 .anonymize_late_bound_regions(pred.kind().rebind(trait_pred.trait_ref.substs));
1791 // Find another predicate whose self-type is equal to the expected self type,
1792 // but whose substs don't match.
1793 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1795 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1796 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
1797 if self.tcx.is_fn_trait(trait_pred.def_id())
1799 // Make sure that the self type matches
1800 // (i.e. constraining this closure)
1802 == self.tcx.anonymize_late_bound_regions(
1803 pred.kind().rebind(trait_pred.self_ty()),
1805 // But the substs don't match (i.e. incompatible args)
1807 != self.tcx.anonymize_late_bound_regions(
1808 pred.kind().rebind(trait_pred.trait_ref.substs),
1815 // If we found one, then it's very likely the cause of the error.
1816 if let Some((_, (_, other_pred_span))) = other_pred {
1819 "closure inferred to have a different signature due to this bound",
1825 fn suggest_fully_qualified_path(
1827 err: &mut Diagnostic,
1832 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1833 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1835 "{}s cannot be accessed directly on a `trait`, they can only be \
1836 accessed through a specific `impl`",
1837 assoc_item.kind.as_def_kind().descr(item_def_id)
1839 err.span_suggestion(
1841 "use the fully qualified path to an implementation",
1842 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1843 Applicability::HasPlaceholders,
1849 /// Adds an async-await specific note to the diagnostic when the future does not implement
1850 /// an auto trait because of a captured type.
1853 /// note: future does not implement `Qux` as this value is used across an await
1854 /// --> $DIR/issue-64130-3-other.rs:17:5
1856 /// LL | let x = Foo;
1857 /// | - has type `Foo`
1858 /// LL | baz().await;
1859 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1861 /// | - `x` is later dropped here
1864 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1865 /// is "replaced" with a different message and a more specific error.
1868 /// error: future cannot be sent between threads safely
1869 /// --> $DIR/issue-64130-2-send.rs:21:5
1871 /// LL | fn is_send<T: Send>(t: T) { }
1872 /// | ---- required by this bound in `is_send`
1874 /// LL | is_send(bar());
1875 /// | ^^^^^^^ future returned by `bar` is not send
1877 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1878 /// implemented for `Foo`
1879 /// note: future is not send as this value is used across an await
1880 /// --> $DIR/issue-64130-2-send.rs:15:5
1882 /// LL | let x = Foo;
1883 /// | - has type `Foo`
1884 /// LL | baz().await;
1885 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1887 /// | - `x` is later dropped here
1890 /// Returns `true` if an async-await specific note was added to the diagnostic.
1891 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1892 fn maybe_note_obligation_cause_for_async_await(
1894 err: &mut Diagnostic,
1895 obligation: &PredicateObligation<'tcx>,
1897 let hir = self.tcx.hir();
1899 // Attempt to detect an async-await error by looking at the obligation causes, looking
1900 // for a generator to be present.
1902 // When a future does not implement a trait because of a captured type in one of the
1903 // generators somewhere in the call stack, then the result is a chain of obligations.
1905 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1906 // future is passed as an argument to a function C which requires a `Send` type, then the
1907 // chain looks something like this:
1909 // - `BuiltinDerivedObligation` with a generator witness (B)
1910 // - `BuiltinDerivedObligation` with a generator (B)
1911 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1912 // - `BuiltinDerivedObligation` with a generator witness (A)
1913 // - `BuiltinDerivedObligation` with a generator (A)
1914 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1915 // - `BindingObligation` with `impl_send (Send requirement)
1917 // The first obligation in the chain is the most useful and has the generator that captured
1918 // the type. The last generator (`outer_generator` below) has information about where the
1919 // bound was introduced. At least one generator should be present for this diagnostic to be
1921 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1922 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
1925 let mut generator = None;
1926 let mut outer_generator = None;
1927 let mut next_code = Some(obligation.cause.code());
1929 let mut seen_upvar_tys_infer_tuple = false;
1931 while let Some(code) = next_code {
1934 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1935 next_code = Some(parent_code);
1937 ObligationCauseCode::ImplDerivedObligation(cause) => {
1938 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1940 parent_trait_ref = ?cause.derived.parent_trait_pred,
1941 self_ty.kind = ?ty.kind(),
1946 ty::Generator(did, ..) => {
1947 generator = generator.or(Some(did));
1948 outer_generator = Some(did);
1950 ty::GeneratorWitness(..) => {}
1951 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1952 // By introducing a tuple of upvar types into the chain of obligations
1953 // of a generator, the first non-generator item is now the tuple itself,
1954 // we shall ignore this.
1956 seen_upvar_tys_infer_tuple = true;
1958 _ if generator.is_none() => {
1959 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1960 target_ty = Some(ty);
1965 next_code = Some(&cause.derived.parent_code);
1967 ObligationCauseCode::DerivedObligation(derived_obligation)
1968 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1969 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1971 parent_trait_ref = ?derived_obligation.parent_trait_pred,
1972 self_ty.kind = ?ty.kind(),
1976 ty::Generator(did, ..) => {
1977 generator = generator.or(Some(did));
1978 outer_generator = Some(did);
1980 ty::GeneratorWitness(..) => {}
1981 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1982 // By introducing a tuple of upvar types into the chain of obligations
1983 // of a generator, the first non-generator item is now the tuple itself,
1984 // we shall ignore this.
1986 seen_upvar_tys_infer_tuple = true;
1988 _ if generator.is_none() => {
1989 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1990 target_ty = Some(ty);
1995 next_code = Some(&derived_obligation.parent_code);
2001 // Only continue if a generator was found.
2002 debug!(?generator, ?trait_ref, ?target_ty);
2003 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
2007 let span = self.tcx.def_span(generator_did);
2009 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
2012 ?generator_did_root,
2013 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2017 let generator_body = generator_did
2019 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2020 .map(|body_id| hir.body(body_id));
2021 let mut visitor = AwaitsVisitor::default();
2022 if let Some(body) = generator_body {
2023 visitor.visit_body(body);
2025 debug!(awaits = ?visitor.awaits);
2027 // Look for a type inside the generator interior that matches the target type to get
2029 let target_ty_erased = self.tcx.erase_regions(target_ty);
2030 let ty_matches = |ty| -> bool {
2031 // Careful: the regions for types that appear in the
2032 // generator interior are not generally known, so we
2033 // want to erase them when comparing (and anyway,
2034 // `Send` and other bounds are generally unaffected by
2035 // the choice of region). When erasing regions, we
2036 // also have to erase late-bound regions. This is
2037 // because the types that appear in the generator
2038 // interior generally contain "bound regions" to
2039 // represent regions that are part of the suspended
2040 // generator frame. Bound regions are preserved by
2041 // `erase_regions` and so we must also call
2042 // `erase_late_bound_regions`.
2043 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2044 let ty_erased = self.tcx.erase_regions(ty_erased);
2045 let eq = ty_erased == target_ty_erased;
2046 debug!(?ty_erased, ?target_ty_erased, ?eq);
2050 // Get the typeck results from the infcx if the generator is the function we are currently
2051 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2052 // cycles. If we can't use resolved types because the generator comes from another crate,
2053 // we still provide a targeted error but without all the relevant spans.
2054 let generator_data = match &self.typeck_results {
2055 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2056 _ if generator_did.is_local() => {
2057 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2059 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2060 GeneratorData::Foreign(generator_diag_data)
2065 let mut interior_or_upvar_span = None;
2067 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2068 debug!(?from_awaited_ty);
2070 // The generator interior types share the same binders
2071 if let Some(cause) =
2072 generator_data.get_generator_interior_types().skip_binder().iter().find(
2073 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2074 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2078 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2080 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2082 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2086 if interior_or_upvar_span.is_none() {
2087 interior_or_upvar_span =
2088 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2091 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2092 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2095 debug!(?interior_or_upvar_span);
2096 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2097 let is_async = self.tcx.generator_is_async(generator_did);
2098 let typeck_results = match generator_data {
2099 GeneratorData::Local(typeck_results) => Some(typeck_results),
2100 GeneratorData::Foreign(_) => None,
2102 self.note_obligation_cause_for_async_await(
2104 interior_or_upvar_span,
2119 /// Unconditionally adds the diagnostic note described in
2120 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2121 #[instrument(level = "debug", skip_all)]
2122 fn note_obligation_cause_for_async_await(
2124 err: &mut Diagnostic,
2125 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2127 outer_generator: Option<DefId>,
2128 trait_pred: ty::TraitPredicate<'tcx>,
2129 target_ty: Ty<'tcx>,
2130 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2131 obligation: &PredicateObligation<'tcx>,
2132 next_code: Option<&ObligationCauseCode<'tcx>>,
2134 let source_map = self.tcx.sess.source_map();
2136 let (await_or_yield, an_await_or_yield) =
2137 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2138 let future_or_generator = if is_async { "future" } else { "generator" };
2140 // Special case the primary error message when send or sync is the trait that was
2142 let hir = self.tcx.hir();
2143 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2144 self.tcx.get_diagnostic_name(trait_pred.def_id())
2146 let (trait_name, trait_verb) =
2147 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2150 err.set_primary_message(format!(
2151 "{} cannot be {} between threads safely",
2152 future_or_generator, trait_verb
2155 let original_span = err.span.primary_span().unwrap();
2156 let mut span = MultiSpan::from_span(original_span);
2158 let message = outer_generator
2159 .and_then(|generator_did| {
2160 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2161 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2162 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2164 .parent(generator_did)
2166 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2167 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2169 format!("future returned by `{}` is not {}", name, trait_name)
2171 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2172 format!("future created by async block is not {}", trait_name)
2174 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2175 format!("future created by async closure is not {}", trait_name)
2179 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2181 span.push_span_label(original_span, message);
2184 format!("is not {}", trait_name)
2186 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2189 let mut explain_yield =
2190 |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
2191 let mut span = MultiSpan::from_span(yield_span);
2192 let snippet = match source_map.span_to_snippet(interior_span) {
2193 // #70935: If snippet contains newlines, display "the value" instead
2194 // so that we do not emit complex diagnostics.
2195 Ok(snippet) if !snippet.contains('\n') => format!("`{}`", snippet),
2196 _ => "the value".to_string(),
2198 // note: future is not `Send` as this value is used across an await
2199 // --> $DIR/issue-70935-complex-spans.rs:13:9
2201 // LL | baz(|| async {
2202 // | ______________-
2205 // LL | | foo(tx.clone());
2207 // | | - ^^^^^^ await occurs here, with value maybe used later
2209 // | has type `closure` which is not `Send`
2210 // note: value is later dropped here
2214 span.push_span_label(
2216 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2218 span.push_span_label(
2220 format!("has type `{}` which {}", target_ty, trait_explanation),
2222 if let Some(scope_span) = scope_span {
2223 let scope_span = source_map.end_point(scope_span);
2225 let msg = format!("{} is later dropped here", snippet);
2226 span.push_span_label(scope_span, msg);
2231 "{} {} as this value is used across {}",
2232 future_or_generator, trait_explanation, an_await_or_yield
2236 match interior_or_upvar_span {
2237 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2238 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2239 if let Some(await_span) = from_awaited_ty {
2240 // The type causing this obligation is one being awaited at await_span.
2241 let mut span = MultiSpan::from_span(await_span);
2242 span.push_span_label(
2245 "await occurs here on type `{}`, which {}",
2246 target_ty, trait_explanation
2252 "future {not_trait} as it awaits another future which {not_trait}",
2253 not_trait = trait_explanation
2257 // Look at the last interior type to get a span for the `.await`.
2259 generator_interior_types = ?format_args!(
2260 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2263 explain_yield(interior_span, yield_span, scope_span);
2266 if let Some(expr_id) = expr {
2267 let expr = hir.expect_expr(expr_id);
2268 debug!("target_ty evaluated from {:?}", expr);
2270 let parent = hir.get_parent_node(expr_id);
2271 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2272 let parent_span = hir.span(parent);
2273 let parent_did = parent.owner.to_def_id();
2276 // fn foo(&self) -> i32 {}
2279 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2282 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2284 .expr_adjustments(expr)
2286 .any(|adj| adj.is_region_borrow())
2292 // struct Foo(*const u8);
2293 // bar(Foo(std::ptr::null())).await;
2294 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2296 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2297 let is_raw_borrow_inside_fn_like_call =
2298 match self.tcx.def_kind(parent_did) {
2299 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2302 if let Some(typeck_results) = typeck_results {
2303 if (typeck_results.is_method_call(e) && is_region_borrow)
2304 || is_raw_borrow_inside_fn_like_call
2308 "consider moving this into a `let` \
2309 binding to create a shorter lived borrow",
2317 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2318 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2319 let refers_to_non_sync = match target_ty.kind() {
2320 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2321 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2327 let (span_label, span_note) = match refers_to_non_sync {
2328 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2329 // include suggestions to make `T: Sync` so that `&T: Send`
2332 "has type `{}` which {}, because `{}` is not `Sync`",
2333 target_ty, trait_explanation, ref_ty
2336 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2341 format!("has type `{}` which {}", target_ty, trait_explanation),
2342 format!("captured value {}", trait_explanation),
2346 let mut span = MultiSpan::from_span(upvar_span);
2347 span.push_span_label(upvar_span, span_label);
2348 err.span_note(span, &span_note);
2352 // Add a note for the item obligation that remains - normally a note pointing to the
2353 // bound that introduced the obligation (e.g. `T: Send`).
2355 self.note_obligation_cause_code(
2357 obligation.predicate,
2358 obligation.param_env,
2361 &mut Default::default(),
2365 fn note_obligation_cause_code<T>(
2367 err: &mut Diagnostic,
2369 param_env: ty::ParamEnv<'tcx>,
2370 cause_code: &ObligationCauseCode<'tcx>,
2371 obligated_types: &mut Vec<Ty<'tcx>>,
2372 seen_requirements: &mut FxHashSet<DefId>,
2374 T: ToPredicate<'tcx>,
2377 let predicate = predicate.to_predicate(tcx);
2379 ObligationCauseCode::ExprAssignable
2380 | ObligationCauseCode::MatchExpressionArm { .. }
2381 | ObligationCauseCode::Pattern { .. }
2382 | ObligationCauseCode::IfExpression { .. }
2383 | ObligationCauseCode::IfExpressionWithNoElse
2384 | ObligationCauseCode::MainFunctionType
2385 | ObligationCauseCode::StartFunctionType
2386 | ObligationCauseCode::IntrinsicType
2387 | ObligationCauseCode::MethodReceiver
2388 | ObligationCauseCode::ReturnNoExpression
2389 | ObligationCauseCode::UnifyReceiver(..)
2390 | ObligationCauseCode::OpaqueType
2391 | ObligationCauseCode::MiscObligation
2392 | ObligationCauseCode::WellFormed(..)
2393 | ObligationCauseCode::MatchImpl(..)
2394 | ObligationCauseCode::ReturnType
2395 | ObligationCauseCode::ReturnValue(_)
2396 | ObligationCauseCode::BlockTailExpression(_)
2397 | ObligationCauseCode::AwaitableExpr(_)
2398 | ObligationCauseCode::ForLoopIterator
2399 | ObligationCauseCode::QuestionMark
2400 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2401 | ObligationCauseCode::LetElse
2402 | ObligationCauseCode::BinOp { .. }
2403 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2404 | ObligationCauseCode::RustCall => {}
2405 ObligationCauseCode::SliceOrArrayElem => {
2406 err.note("slice and array elements must have `Sized` type");
2408 ObligationCauseCode::TupleElem => {
2409 err.note("only the last element of a tuple may have a dynamically sized type");
2411 ObligationCauseCode::ProjectionWf(data) => {
2412 err.note(&format!("required so that the projection `{data}` is well-formed"));
2414 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2416 "required so that reference `{ref_ty}` does not outlive its referent"
2419 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2421 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2425 ObligationCauseCode::ItemObligation(_)
2426 | ObligationCauseCode::ExprItemObligation(..) => {
2427 // We hold the `DefId` of the item introducing the obligation, but displaying it
2428 // doesn't add user usable information. It always point at an associated item.
2430 ObligationCauseCode::BindingObligation(item_def_id, span)
2431 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2432 let item_name = tcx.def_path_str(item_def_id);
2433 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2434 let mut multispan = MultiSpan::from(span);
2435 let sm = tcx.sess.source_map();
2436 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2438 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2439 (Ok(l), Ok(r)) => l.line == r.line,
2442 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2443 multispan.push_span_label(ident.span, "required by a bound in this");
2446 let descr = format!("required by a bound in `{item_name}`");
2447 if span.is_visible(sm) {
2448 let msg = format!("required by this bound in `{short_item_name}`");
2449 multispan.push_span_label(span, msg);
2450 err.span_note(multispan, &descr);
2452 err.span_note(tcx.def_span(item_def_id), &descr);
2455 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2457 "required for the cast from `{}` to the object type `{}`",
2458 self.ty_to_string(concrete_ty),
2459 self.ty_to_string(object_ty)
2462 ObligationCauseCode::Coercion { source: _, target } => {
2463 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2465 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2467 "the `Copy` trait is required because this value will be copied for each element of the array",
2472 "consider creating a new `const` item and initializing it with the result \
2473 of the function call to be used in the repeat position, like \
2474 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2478 if self.tcx.sess.is_nightly_build() && is_const_fn {
2480 "create an inline `const` block, see RFC #2920 \
2481 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2485 ObligationCauseCode::VariableType(hir_id) => {
2486 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2487 match self.tcx.hir().find(parent_node) {
2488 Some(Node::Local(hir::Local {
2489 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2492 // When encountering an assignment of an unsized trait, like
2493 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2494 // order to use have a slice instead.
2495 err.span_suggestion_verbose(
2496 span.shrink_to_lo(),
2497 "consider borrowing here",
2499 Applicability::MachineApplicable,
2501 err.note("all local variables must have a statically known size");
2503 Some(Node::Param(param)) => {
2504 err.span_suggestion_verbose(
2505 param.ty_span.shrink_to_lo(),
2506 "function arguments must have a statically known size, borrowed types \
2507 always have a known size",
2509 Applicability::MachineApplicable,
2513 err.note("all local variables must have a statically known size");
2516 if !self.tcx.features().unsized_locals {
2517 err.help("unsized locals are gated as an unstable feature");
2520 ObligationCauseCode::SizedArgumentType(sp) => {
2521 if let Some(span) = sp {
2522 err.span_suggestion_verbose(
2523 span.shrink_to_lo(),
2524 "function arguments must have a statically known size, borrowed types \
2525 always have a known size",
2527 Applicability::MachineApplicable,
2530 err.note("all function arguments must have a statically known size");
2532 if tcx.sess.opts.unstable_features.is_nightly_build()
2533 && !self.tcx.features().unsized_fn_params
2535 err.help("unsized fn params are gated as an unstable feature");
2538 ObligationCauseCode::SizedReturnType => {
2539 err.note("the return type of a function must have a statically known size");
2541 ObligationCauseCode::SizedYieldType => {
2542 err.note("the yield type of a generator must have a statically known size");
2544 ObligationCauseCode::SizedBoxType => {
2545 err.note("the type of a box expression must have a statically known size");
2547 ObligationCauseCode::AssignmentLhsSized => {
2548 err.note("the left-hand-side of an assignment must have a statically known size");
2550 ObligationCauseCode::TupleInitializerSized => {
2551 err.note("tuples must have a statically known size to be initialized");
2553 ObligationCauseCode::StructInitializerSized => {
2554 err.note("structs must have a statically known size to be initialized");
2556 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2558 AdtKind::Struct => {
2561 "the last field of a packed struct may only have a \
2562 dynamically sized type if it does not need drop to be run",
2566 "only the last field of a struct may have a dynamically sized type",
2571 err.note("no field of a union may have a dynamically sized type");
2574 err.note("no field of an enum variant may have a dynamically sized type");
2577 err.help("change the field's type to have a statically known size");
2578 err.span_suggestion(
2579 span.shrink_to_lo(),
2580 "borrowed types always have a statically known size",
2582 Applicability::MachineApplicable,
2584 err.multipart_suggestion(
2585 "the `Box` type always has a statically known size and allocates its contents \
2588 (span.shrink_to_lo(), "Box<".to_string()),
2589 (span.shrink_to_hi(), ">".to_string()),
2591 Applicability::MachineApplicable,
2594 ObligationCauseCode::ConstSized => {
2595 err.note("constant expressions must have a statically known size");
2597 ObligationCauseCode::InlineAsmSized => {
2598 err.note("all inline asm arguments must have a statically known size");
2600 ObligationCauseCode::ConstPatternStructural => {
2601 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2603 ObligationCauseCode::SharedStatic => {
2604 err.note("shared static variables must have a type that implements `Sync`");
2606 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2607 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2608 let ty = parent_trait_ref.skip_binder().self_ty();
2609 if parent_trait_ref.references_error() {
2610 // NOTE(eddyb) this was `.cancel()`, but `err`
2611 // is borrowed, so we can't fully defuse it.
2612 err.downgrade_to_delayed_bug();
2616 // If the obligation for a tuple is set directly by a Generator or Closure,
2617 // then the tuple must be the one containing capture types.
2618 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2621 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2623 let parent_trait_ref =
2624 self.resolve_vars_if_possible(data.parent_trait_pred);
2625 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2626 matches!(nested_ty.kind(), ty::Generator(..))
2627 || matches!(nested_ty.kind(), ty::Closure(..))
2633 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2635 // Don't print the tuple of capture types
2637 if !is_upvar_tys_infer_tuple {
2638 let msg = format!("required because it appears within the type `{}`", ty);
2640 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2641 Some(ident) => err.span_note(ident.span, &msg),
2642 None => err.note(&msg),
2644 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs: _ }) => {
2645 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2646 if tcx.parent(*def_id) == identity_future {
2650 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2651 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2652 let is_future = tcx.ty_is_opaque_future(ty);
2656 "note_obligation_cause_code: check for async fn"
2659 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2660 ty::Generator(last_def_id, ..) => {
2661 tcx.generator_is_async(*last_def_id)
2668 err.span_note(self.tcx.def_span(def_id), &msg)
2670 ty::GeneratorWitness(bound_tys) => {
2671 use std::fmt::Write;
2673 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2674 // Maybe we should just remove this note altogether?
2675 // FIXME: only print types which don't meet the trait requirement
2677 "required because it captures the following types: ".to_owned();
2678 for ty in bound_tys.skip_binder() {
2679 write!(msg, "`{}`, ", ty).unwrap();
2681 err.note(msg.trim_end_matches(", "))
2683 ty::Generator(def_id, _, _) => {
2684 let sp = self.tcx.def_span(def_id);
2686 // Special-case this to say "async block" instead of `[static generator]`.
2687 let kind = tcx.generator_kind(def_id).unwrap().descr();
2690 &format!("required because it's used within this {}", kind),
2693 ty::Closure(def_id, _) => err.span_note(
2694 self.tcx.def_span(def_id),
2695 &format!("required because it's used within this closure"),
2697 _ => err.note(&msg),
2702 obligated_types.push(ty);
2704 let parent_predicate = parent_trait_ref;
2705 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2706 // #74711: avoid a stack overflow
2707 ensure_sufficient_stack(|| {
2708 self.note_obligation_cause_code(
2718 ensure_sufficient_stack(|| {
2719 self.note_obligation_cause_code(
2723 cause_code.peel_derives(),
2730 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2731 let mut parent_trait_pred =
2732 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2733 parent_trait_pred.remap_constness_diag(param_env);
2734 let parent_def_id = parent_trait_pred.def_id();
2735 let (self_ty, file) =
2736 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2738 "required for `{self_ty}` to implement `{}`",
2739 parent_trait_pred.print_modifiers_and_trait_path()
2741 let mut is_auto_trait = false;
2742 match self.tcx.hir().get_if_local(data.impl_def_id) {
2743 Some(Node::Item(hir::Item {
2744 kind: hir::ItemKind::Trait(is_auto, ..),
2748 // FIXME: we should do something else so that it works even on crate foreign
2750 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2751 err.span_note(ident.span, &msg)
2753 Some(Node::Item(hir::Item {
2754 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2757 let mut spans = Vec::with_capacity(2);
2758 if let Some(trait_ref) = of_trait {
2759 spans.push(trait_ref.path.span);
2761 spans.push(self_ty.span);
2762 err.span_note(spans, &msg)
2764 _ => err.note(&msg),
2767 if let Some(file) = file {
2769 "the full type name has been written to '{}'",
2773 let mut parent_predicate = parent_trait_pred;
2774 let mut data = &data.derived;
2776 seen_requirements.insert(parent_def_id);
2778 // We don't want to point at the ADT saying "required because it appears within
2779 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2780 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2783 let child_trait_ref =
2784 self.resolve_vars_if_possible(derived.parent_trait_pred);
2785 let child_def_id = child_trait_ref.def_id();
2786 if seen_requirements.insert(child_def_id) {
2790 parent_predicate = child_trait_ref.to_predicate(tcx);
2791 parent_trait_pred = child_trait_ref;
2794 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2795 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2796 let child_trait_pred =
2797 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2798 let child_def_id = child_trait_pred.def_id();
2799 if seen_requirements.insert(child_def_id) {
2803 data = &child.derived;
2804 parent_predicate = child_trait_pred.to_predicate(tcx);
2805 parent_trait_pred = child_trait_pred;
2809 "{} redundant requirement{} hidden",
2813 let (self_ty, file) =
2814 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2816 "required for `{self_ty}` to implement `{}`",
2817 parent_trait_pred.print_modifiers_and_trait_path()
2819 if let Some(file) = file {
2821 "the full type name has been written to '{}'",
2826 // #74711: avoid a stack overflow
2827 ensure_sufficient_stack(|| {
2828 self.note_obligation_cause_code(
2838 ObligationCauseCode::DerivedObligation(ref data) => {
2839 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2840 let parent_predicate = parent_trait_ref;
2841 // #74711: avoid a stack overflow
2842 ensure_sufficient_stack(|| {
2843 self.note_obligation_cause_code(
2853 ObligationCauseCode::FunctionArgumentObligation {
2858 self.function_argument_obligation(
2866 ensure_sufficient_stack(|| {
2867 self.note_obligation_cause_code(
2877 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2878 let item_name = self.tcx.item_name(trait_item_def_id);
2880 "the requirement `{predicate}` appears on the `impl`'s {kind} \
2881 `{item_name}` but not on the corresponding trait's {kind}",
2885 .opt_item_ident(trait_item_def_id)
2887 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2888 let mut assoc_span: MultiSpan = sp.into();
2889 assoc_span.push_span_label(
2891 format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
2893 if let Some(ident) = self
2895 .opt_associated_item(trait_item_def_id)
2896 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2898 assoc_span.push_span_label(ident.span, "in this trait");
2900 err.span_note(assoc_span, &msg);
2902 ObligationCauseCode::TrivialBound => {
2903 err.help("see issue #48214");
2904 if tcx.sess.opts.unstable_features.is_nightly_build() {
2905 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2908 ObligationCauseCode::OpaqueReturnType(expr_info) => {
2909 if let Some((expr_ty, expr_span)) = expr_info {
2910 let expr_ty = with_forced_trimmed_paths!(self.ty_to_string(expr_ty));
2913 format!("return type was inferred to be `{expr_ty}` here"),
2921 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2923 fn suggest_await_before_try(
2925 err: &mut Diagnostic,
2926 obligation: &PredicateObligation<'tcx>,
2927 trait_pred: ty::PolyTraitPredicate<'tcx>,
2930 let body_hir_id = obligation.cause.body_id;
2931 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2933 if let Some(body_id) =
2934 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
2936 let body = self.tcx.hir().body(body_id);
2937 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2938 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2940 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2941 let impls_future = self.type_implements_trait(
2943 [self.tcx.erase_late_bound_regions(self_ty)],
2944 obligation.param_env,
2946 if !impls_future.must_apply_modulo_regions() {
2950 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2951 // `<T as Future>::Output`
2952 let projection_ty = trait_pred.map_bound(|trait_pred| {
2953 self.tcx.mk_projection(
2955 // Future::Output has no substs
2956 self.tcx.mk_substs_trait(trait_pred.self_ty(), []),
2959 let InferOk { value: projection_ty, .. } =
2960 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
2963 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
2965 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2966 obligation.param_env,
2967 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
2969 debug!(try_trait_obligation = ?try_obligation);
2970 if self.predicate_may_hold(&try_obligation)
2971 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2972 && snippet.ends_with('?')
2974 err.span_suggestion_verbose(
2975 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2976 "consider `await`ing on the `Future`",
2978 Applicability::MaybeIncorrect,
2985 fn suggest_floating_point_literal(
2987 obligation: &PredicateObligation<'tcx>,
2988 err: &mut Diagnostic,
2989 trait_ref: &ty::PolyTraitRef<'tcx>,
2991 let rhs_span = match obligation.cause.code() {
2992 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
2995 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
2996 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
2998 err.span_suggestion_verbose(
2999 rhs_span.shrink_to_hi(),
3000 "consider using a floating-point literal by writing it with `.0`",
3002 Applicability::MaybeIncorrect,
3009 obligation: &PredicateObligation<'tcx>,
3010 err: &mut Diagnostic,
3011 trait_pred: ty::PolyTraitPredicate<'tcx>,
3013 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3016 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3017 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3021 let is_derivable_trait = match diagnostic_name {
3022 sym::Default => !adt.is_enum(),
3023 sym::PartialEq | sym::PartialOrd => {
3024 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3025 trait_pred.skip_binder().self_ty() == rhs_ty
3027 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3030 is_derivable_trait &&
3031 // Ensure all fields impl the trait.
3032 adt.all_fields().all(|field| {
3033 let field_ty = field.ty(self.tcx, substs);
3034 let trait_substs = match diagnostic_name {
3035 sym::PartialEq | sym::PartialOrd => {
3040 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3041 trait_ref: self.tcx.mk_trait_ref(
3042 trait_pred.def_id(),
3043 [field_ty].into_iter().chain(trait_substs),
3047 let field_obl = Obligation::new(
3049 obligation.cause.clone(),
3050 obligation.param_env,
3053 self.predicate_must_hold_modulo_regions(&field_obl)
3057 err.span_suggestion_verbose(
3058 self.tcx.def_span(adt.did()).shrink_to_lo(),
3060 "consider annotating `{}` with `#[derive({})]`",
3061 trait_pred.skip_binder().self_ty(),
3064 format!("#[derive({})]\n", diagnostic_name),
3065 Applicability::MaybeIncorrect,
3070 fn suggest_dereferencing_index(
3072 obligation: &PredicateObligation<'tcx>,
3073 err: &mut Diagnostic,
3074 trait_pred: ty::PolyTraitPredicate<'tcx>,
3076 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3077 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3078 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3079 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3080 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3082 err.span_suggestion_verbose(
3083 obligation.cause.span.shrink_to_lo(),
3084 "dereference this index",
3086 Applicability::MachineApplicable,
3090 fn function_argument_obligation(
3093 err: &mut Diagnostic,
3094 parent_code: &ObligationCauseCode<'tcx>,
3095 param_env: ty::ParamEnv<'tcx>,
3096 predicate: ty::Predicate<'tcx>,
3100 let hir = tcx.hir();
3101 if let Some(Node::Expr(expr)) = hir.find(arg_hir_id) {
3102 let parent_id = hir.get_parent_item(arg_hir_id);
3103 let typeck_results: &TypeckResults<'tcx> = match &self.typeck_results {
3104 Some(t) if t.hir_owner == parent_id => t,
3105 _ => self.tcx.typeck(parent_id.def_id),
3107 if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
3108 let expr = expr.peel_blocks();
3109 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
3110 let span = expr.span;
3111 if Some(span) != err.span.primary_span() {
3114 if ty.references_error() {
3117 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3118 format!("this tail expression is of type `{ty}`")
3124 // FIXME: visit the ty to see if there's any closure involved, and if there is,
3125 // check whether its evaluated return type is the same as the one corresponding
3126 // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3127 // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3128 let mut type_diffs = vec![];
3130 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
3131 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
3132 && let Some(pred) = predicates.predicates.get(*idx)
3133 && let Ok(trait_pred) = pred.kind().try_map_bound(|pred| match pred {
3134 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) => Ok(trait_pred),
3138 let mut c = CollectAllMismatches {
3143 if let Ok(trait_predicate) = predicate.kind().try_map_bound(|pred| match pred {
3144 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) => Ok(trait_pred),
3147 if let Ok(_) = c.relate(trait_pred, trait_predicate) {
3148 type_diffs = c.errors;
3152 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3153 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3154 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3155 && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3156 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3157 && let Some(binding_expr) = local.init
3159 // If the expression we're calling on is a binding, we want to point at the
3160 // `let` when talking about the type. Otherwise we'll point at every part
3161 // of the method chain with the type.
3162 self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
3164 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
3167 let call_node = hir.find(call_hir_id);
3168 if let Some(Node::Expr(hir::Expr {
3169 kind: hir::ExprKind::MethodCall(path, rcvr, ..), ..
3172 if Some(rcvr.span) == err.span.primary_span() {
3173 err.replace_span_with(path.ident.span);
3176 if let Some(Node::Expr(hir::Expr {
3178 hir::ExprKind::Call(hir::Expr { span, .. }, _)
3179 | hir::ExprKind::MethodCall(hir::PathSegment { ident: Ident { span, .. }, .. }, ..),
3181 })) = hir.find(call_hir_id)
3183 if Some(*span) != err.span.primary_span() {
3184 err.span_label(*span, "required by a bound introduced by this call");
3191 expr: &hir::Expr<'_>,
3192 typeck_results: &TypeckResults<'tcx>,
3193 type_diffs: Vec<TypeError<'tcx>>,
3194 param_env: ty::ParamEnv<'tcx>,
3195 err: &mut Diagnostic,
3197 let mut primary_spans = vec![];
3198 let mut span_labels = vec![];
3202 let mut assocs = vec![];
3203 // We still want to point at the different methods even if there hasn't
3204 // been a change of assoc type.
3205 let mut call_spans = vec![];
3206 let mut expr = expr;
3207 let mut prev_ty = self.resolve_vars_if_possible(
3208 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3210 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) = expr.kind {
3211 // Point at every method call in the chain with the resulting type.
3212 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3213 // ^^^^^^ ^^^^^^^^^^^
3215 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
3216 call_spans.push(span);
3218 let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
3219 for diff in &type_diffs {
3220 let Sorts(expected_found) = diff else { continue; };
3221 let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; };
3224 TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span };
3225 let trait_def_id = proj.trait_def_id(self.tcx);
3226 // Make `Self` be equivalent to the type of the call chain
3227 // expression we're looking at now, so that we can tell what
3228 // for example `Iterator::Item` is at this point in the chain.
3229 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
3231 ty::GenericParamDefKind::Type { .. } => {
3232 if param.index == 0 {
3233 return prev_ty.into();
3236 ty::GenericParamDefKind::Lifetime
3237 | ty::GenericParamDefKind::Const { .. } => {}
3239 self.var_for_def(span, param)
3241 // This will hold the resolved type of the associated type, if the
3242 // current expression implements the trait that associated type is
3243 // in. For example, this would be what `Iterator::Item` is here.
3244 let ty_var = self.infcx.next_ty_var(origin);
3245 // This corresponds to `<ExprTy as Iterator>::Item = _`.
3246 let trait_ref = ty::Binder::dummy(ty::PredicateKind::Clause(
3247 ty::Clause::Projection(ty::ProjectionPredicate {
3248 projection_ty: ty::AliasTy { substs, def_id: proj.def_id },
3249 term: ty_var.into(),
3252 // Add `<ExprTy as Iterator>::Item = _` obligation.
3253 ocx.register_obligation(Obligation::misc(
3260 if ocx.select_where_possible().is_empty() {
3261 // `ty_var` now holds the type that `Item` is for `ExprTy`.
3262 let ty_var = self.resolve_vars_if_possible(ty_var);
3263 assocs_in_this_method.push(Some((span, (proj.def_id, ty_var))));
3265 // `<ExprTy as Iterator>` didn't select, so likely we've
3266 // reached the end of the iterator chain, like the originating
3268 // Keep the space consistent for later zipping.
3269 assocs_in_this_method.push(None);
3272 assocs.push(assocs_in_this_method);
3273 prev_ty = self.resolve_vars_if_possible(
3274 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3277 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3278 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3279 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3280 && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3281 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3282 && let Some(binding_expr) = local.init
3284 // We've reached the root of the method call chain and it is a
3285 // binding. Get the binding creation and try to continue the chain.
3286 expr = binding_expr;
3289 // We want the type before deref coercions, otherwise we talk about `&[_]`
3290 // instead of `Vec<_>`.
3291 if let Some(ty) = typeck_results.expr_ty_opt(expr) {
3292 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3293 // Point at the root expression
3294 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3296 span_labels.push((expr.span, format!("this expression has type `{ty}`")));
3298 // Only show this if it is not a "trivial" expression (not a method
3299 // chain) and there are associated types to talk about.
3300 let mut assocs = assocs.into_iter().peekable();
3301 while let Some(assocs_in_method) = assocs.next() {
3302 let Some(prev_assoc_in_method) = assocs.peek() else {
3303 for entry in assocs_in_method {
3304 let Some((span, (assoc, ty))) = entry else { continue; };
3305 if type_diffs.iter().any(|diff| {
3306 let Sorts(expected_found) = diff else { return false; };
3307 self.can_eq(param_env, expected_found.found, ty).is_ok()
3309 // FIXME: this doesn't quite work for `Iterator::collect`
3310 // because we have `Vec<i32>` and `()`, but we'd want `i32`
3311 // to point at the `.into_iter()` call, but as long as we
3312 // still point at the other method calls that might have
3313 // introduced the issue, this is fine for now.
3314 primary_spans.push(span);
3318 with_forced_trimmed_paths!(format!(
3319 "`{}` is `{ty}` here",
3320 self.tcx.def_path_str(assoc),
3326 for (entry, prev_entry) in
3327 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
3329 match (entry, prev_entry) {
3330 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
3331 let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
3333 let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
3335 if type_diffs.iter().any(|diff| {
3336 let Sorts(expected_found) = diff else { return false; };
3337 self.can_eq(param_env, expected_found.found, ty).is_ok()
3339 primary_spans.push(span);
3342 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
3344 span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
3347 (Some((span, (assoc, ty))), None) => {
3350 with_forced_trimmed_paths!(format!(
3351 "`{}` is `{}` here",
3352 self.tcx.def_path_str(assoc),
3353 self.ty_to_string(ty),
3357 (None, Some(_)) | (None, None) => {}
3361 for span in call_spans {
3362 if span_labels.iter().find(|(s, _)| *s == span).is_none() {
3363 // Ensure we are showing the entire chain, even if the assoc types
3365 span_labels.push((span, String::new()));
3368 if !primary_spans.is_empty() {
3369 let mut multi_span: MultiSpan = primary_spans.into();
3370 for (span, label) in span_labels {
3371 multi_span.push_span_label(span, label);
3376 "the method call chain might not have had the expected \
3384 /// Add a hint to add a missing borrow or remove an unnecessary one.
3385 fn hint_missing_borrow<'tcx>(
3390 found_node: Node<'_>,
3391 err: &mut Diagnostic,
3393 let found_args = match found.kind() {
3394 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3396 span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
3399 let expected_args = match expected.kind() {
3400 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3402 span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
3406 let fn_decl = found_node
3408 .unwrap_or_else(|| span_bug!(found_span, "found node must be a function"));
3410 let arg_spans = fn_decl.inputs.iter().map(|ty| ty.span);
3412 fn get_deref_type_and_refs<'tcx>(mut ty: Ty<'tcx>) -> (Ty<'tcx>, usize) {
3415 while let ty::Ref(_, new_ty, _) = ty.kind() {
3423 let mut to_borrow = Vec::new();
3424 let mut remove_borrow = Vec::new();
3426 for ((found_arg, expected_arg), arg_span) in found_args.zip(expected_args).zip(arg_spans) {
3427 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
3428 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
3430 if found_ty == expected_ty {
3431 if found_refs < expected_refs {
3432 to_borrow.push((arg_span, expected_arg.to_string()));
3433 } else if found_refs > expected_refs {
3434 remove_borrow.push((arg_span, expected_arg.to_string()));
3439 if !to_borrow.is_empty() {
3440 err.multipart_suggestion(
3441 "consider borrowing the argument",
3443 Applicability::MaybeIncorrect,
3447 if !remove_borrow.is_empty() {
3448 err.multipart_suggestion(
3449 "do not borrow the argument",
3451 Applicability::MaybeIncorrect,
3456 /// Collect all the returned expressions within the input expression.
3457 /// Used to point at the return spans when we want to suggest some change to them.
3459 pub struct ReturnsVisitor<'v> {
3460 pub returns: Vec<&'v hir::Expr<'v>>,
3461 in_block_tail: bool,
3464 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3465 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3466 // Visit every expression to detect `return` paths, either through the function's tail
3467 // expression or `return` statements. We walk all nodes to find `return` statements, but
3468 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3469 // they're in the return path of the function body.
3471 hir::ExprKind::Ret(Some(ex)) => {
3472 self.returns.push(ex);
3474 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3475 self.in_block_tail = false;
3476 for stmt in block.stmts {
3477 hir::intravisit::walk_stmt(self, stmt);
3479 self.in_block_tail = true;
3480 if let Some(expr) = block.expr {
3481 self.visit_expr(expr);
3484 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3485 self.visit_expr(then);
3486 if let Some(el) = else_opt {
3487 self.visit_expr(el);
3490 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3492 self.visit_expr(arm.body);
3495 // We need to walk to find `return`s in the entire body.
3496 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3497 _ => self.returns.push(ex),
3501 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3502 assert!(!self.in_block_tail);
3503 if body.generator_kind().is_none() {
3504 if let hir::ExprKind::Block(block, None) = body.value.kind {
3505 if block.expr.is_some() {
3506 self.in_block_tail = true;
3510 hir::intravisit::walk_body(self, body);
3514 /// Collect all the awaited expressions within the input expression.
3516 struct AwaitsVisitor {
3517 awaits: Vec<hir::HirId>,
3520 impl<'v> Visitor<'v> for AwaitsVisitor {
3521 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3522 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3523 self.awaits.push(id)
3525 hir::intravisit::walk_expr(self, ex)
3529 pub trait NextTypeParamName {
3530 fn next_type_param_name(&self, name: Option<&str>) -> String;
3533 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3534 fn next_type_param_name(&self, name: Option<&str>) -> String {
3535 // This is the list of possible parameter names that we might suggest.
3536 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3537 let name = name.as_deref();
3538 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3539 let used_names = self
3541 .filter_map(|p| match p.name {
3542 hir::ParamName::Plain(ident) => Some(ident.name),
3545 .collect::<Vec<_>>();
3549 .find(|n| !used_names.contains(&Symbol::intern(n)))
3550 .unwrap_or(&"ParamName")
3555 fn suggest_trait_object_return_type_alternatives(
3556 err: &mut Diagnostic,
3559 is_object_safe: bool,
3561 err.span_suggestion(
3563 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
3566 Applicability::MaybeIncorrect,
3568 err.span_suggestion(
3571 "use `impl {}` as the return type if all return paths have the same type but you \
3572 want to expose only the trait in the signature",
3575 format!("impl {}", trait_obj),
3576 Applicability::MaybeIncorrect,
3579 err.multipart_suggestion(
3581 "use a boxed trait object if all return paths implement trait `{}`",
3585 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3586 (ret_ty.shrink_to_hi(), ">".to_string()),
3588 Applicability::MaybeIncorrect,
3593 /// Collect the spans that we see the generic param `param_did`
3594 struct ReplaceImplTraitVisitor<'a> {
3595 ty_spans: &'a mut Vec<Span>,
3599 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3600 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3601 if let hir::TyKind::Path(hir::QPath::Resolved(
3603 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3606 if self.param_did == *segment_did {
3607 // `fn foo(t: impl Trait)`
3608 // ^^^^^^^^^^ get this to suggest `T` instead
3610 // There might be more than one `impl Trait`.
3611 self.ty_spans.push(t.span);
3616 hir::intravisit::walk_ty(self, t);
3620 // Replace `param` with `replace_ty`
3621 struct ReplaceImplTraitFolder<'tcx> {
3623 param: &'tcx ty::GenericParamDef,
3624 replace_ty: Ty<'tcx>,
3627 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3628 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3629 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3630 if self.param.index == *index {
3631 return self.replace_ty;
3634 t.super_fold_with(self)
3637 fn tcx(&self) -> TyCtxt<'tcx> {