1 // ignore-tidy-filelength
4 DefIdOrName, FindExprBySpan, Obligation, ObligationCause, ObligationCauseCode,
8 use crate::infer::InferCtxt;
9 use crate::traits::{NormalizeExt, ObligationCtxt};
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_data_structures::stack::ensure_sufficient_stack;
15 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
16 ErrorGuaranteed, MultiSpan, Style,
19 use rustc_hir::def::DefKind;
20 use rustc_hir::def_id::DefId;
21 use rustc_hir::intravisit::Visitor;
22 use rustc_hir::lang_items::LangItem;
23 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
24 use rustc_hir::{Expr, HirId};
25 use rustc_infer::infer::error_reporting::TypeErrCtxt;
26 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
27 use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime};
28 use rustc_middle::hir::map;
29 use rustc_middle::ty::error::TypeError::{self, Sorts};
30 use rustc_middle::ty::relate::TypeRelation;
31 use rustc_middle::ty::{
32 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
33 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, InternalSubsts,
34 IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder,
35 TypeSuperFoldable, TypeVisitable, TypeckResults,
37 use rustc_span::def_id::LocalDefId;
38 use rustc_span::symbol::{sym, Ident, Symbol};
39 use rustc_span::{BytePos, DesugaringKind, ExpnKind, MacroKind, Span, DUMMY_SP};
40 use rustc_target::spec::abi;
43 use super::method_chain::CollectAllMismatches;
44 use super::InferCtxtPrivExt;
45 use crate::infer::InferCtxtExt as _;
46 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
47 use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
50 pub enum GeneratorInteriorOrUpvar {
51 // span of interior type
52 Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
57 // This type provides a uniform interface to retrieve data on generators, whether it originated from
58 // the local crate being compiled or from a foreign crate.
60 pub enum GeneratorData<'tcx, 'a> {
61 Local(&'a TypeckResults<'tcx>),
62 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
65 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
66 // Try to get information about variables captured by the generator that matches a type we are
67 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
69 fn try_get_upvar_span<F>(
71 infer_context: &InferCtxt<'tcx>,
74 ) -> Option<GeneratorInteriorOrUpvar>
76 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
79 GeneratorData::Local(typeck_results) => {
80 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
81 upvars.iter().find_map(|(upvar_id, upvar)| {
82 let upvar_ty = typeck_results.node_type(*upvar_id);
83 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
84 if ty_matches(ty::Binder::dummy(upvar_ty)) {
85 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
92 GeneratorData::Foreign(_) => None,
96 // Try to get the span of a type being awaited on that matches the type we are looking with the
97 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
99 fn get_from_await_ty<F>(
101 visitor: AwaitsVisitor,
106 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
109 GeneratorData::Local(typeck_results) => visitor
112 .map(|id| hir.expect_expr(id))
114 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
116 .map(|expr| expr.span),
117 GeneratorData::Foreign(generator_diagnostic_data) => visitor
120 .map(|id| hir.expect_expr(id))
122 ty_matches(ty::Binder::dummy(
123 generator_diagnostic_data
125 .get(&await_expr.hir_id.local_id)
126 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
128 .map_or_else::<Ty<'tcx>, _, _>(
130 generator_diagnostic_data
132 .get(&await_expr.hir_id.local_id)
136 "node_type: no type for node `{}`",
137 ty::tls::with(|tcx| tcx
139 .node_to_string(await_expr.hir_id))
147 .map(|expr| expr.span),
151 /// Get the type, expression, span and optional scope span of all types
152 /// that are live across the yield of this generator
153 fn get_generator_interior_types(
155 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
157 GeneratorData::Local(typeck_result) => {
158 typeck_result.generator_interior_types.as_deref()
160 GeneratorData::Foreign(generator_diagnostic_data) => {
161 generator_diagnostic_data.generator_interior_types.as_deref()
166 // Used to get the source of the data, note we don't have as much information for generators
167 // originated from foreign crates
168 fn is_foreign(&self) -> bool {
170 GeneratorData::Local(_) => false,
171 GeneratorData::Foreign(_) => true,
176 // This trait is public to expose the diagnostics methods to clippy.
177 pub trait TypeErrCtxtExt<'tcx> {
178 fn suggest_restricting_param_bound(
180 err: &mut Diagnostic,
181 trait_pred: ty::PolyTraitPredicate<'tcx>,
182 associated_item: Option<(&'static str, Ty<'tcx>)>,
186 fn suggest_dereferences(
188 obligation: &PredicateObligation<'tcx>,
189 err: &mut Diagnostic,
190 trait_pred: ty::PolyTraitPredicate<'tcx>,
193 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
197 obligation: &PredicateObligation<'tcx>,
198 err: &mut Diagnostic,
199 trait_pred: ty::PolyTraitPredicate<'tcx>,
202 fn check_for_binding_assigned_block_without_tail_expression(
204 obligation: &PredicateObligation<'tcx>,
205 err: &mut Diagnostic,
206 trait_pred: ty::PolyTraitPredicate<'tcx>,
209 fn suggest_add_clone_to_arg(
211 obligation: &PredicateObligation<'tcx>,
212 err: &mut Diagnostic,
213 trait_pred: ty::PolyTraitPredicate<'tcx>,
216 fn extract_callable_info(
219 param_env: ty::ParamEnv<'tcx>,
221 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)>;
223 fn suggest_add_reference_to_arg(
225 obligation: &PredicateObligation<'tcx>,
226 err: &mut Diagnostic,
227 trait_pred: ty::PolyTraitPredicate<'tcx>,
228 has_custom_message: bool,
231 fn suggest_borrowing_for_object_cast(
233 err: &mut Diagnostic,
234 obligation: &PredicateObligation<'tcx>,
239 fn suggest_remove_reference(
241 obligation: &PredicateObligation<'tcx>,
242 err: &mut Diagnostic,
243 trait_pred: ty::PolyTraitPredicate<'tcx>,
246 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
248 fn suggest_change_mut(
250 obligation: &PredicateObligation<'tcx>,
251 err: &mut Diagnostic,
252 trait_pred: ty::PolyTraitPredicate<'tcx>,
255 fn suggest_semicolon_removal(
257 obligation: &PredicateObligation<'tcx>,
258 err: &mut Diagnostic,
260 trait_pred: ty::PolyTraitPredicate<'tcx>,
263 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
265 fn suggest_impl_trait(
267 err: &mut Diagnostic,
269 obligation: &PredicateObligation<'tcx>,
270 trait_pred: ty::PolyTraitPredicate<'tcx>,
273 fn point_at_returns_when_relevant(
275 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
276 obligation: &PredicateObligation<'tcx>,
279 fn report_closure_arg_mismatch(
282 found_span: Option<Span>,
283 found: ty::PolyTraitRef<'tcx>,
284 expected: ty::PolyTraitRef<'tcx>,
285 cause: &ObligationCauseCode<'tcx>,
286 found_node: Option<Node<'_>>,
287 param_env: ty::ParamEnv<'tcx>,
288 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
290 fn note_conflicting_closure_bounds(
292 cause: &ObligationCauseCode<'tcx>,
293 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
296 fn suggest_fully_qualified_path(
298 err: &mut Diagnostic,
304 fn maybe_note_obligation_cause_for_async_await(
306 err: &mut Diagnostic,
307 obligation: &PredicateObligation<'tcx>,
310 fn note_obligation_cause_for_async_await(
312 err: &mut Diagnostic,
313 interior_or_upvar_span: GeneratorInteriorOrUpvar,
315 outer_generator: Option<DefId>,
316 trait_pred: ty::TraitPredicate<'tcx>,
318 typeck_results: Option<&ty::TypeckResults<'tcx>>,
319 obligation: &PredicateObligation<'tcx>,
320 next_code: Option<&ObligationCauseCode<'tcx>>,
323 fn note_obligation_cause_code<T>(
325 err: &mut Diagnostic,
327 param_env: ty::ParamEnv<'tcx>,
328 cause_code: &ObligationCauseCode<'tcx>,
329 obligated_types: &mut Vec<Ty<'tcx>>,
330 seen_requirements: &mut FxHashSet<DefId>,
332 T: ToPredicate<'tcx>;
334 /// Suggest to await before try: future? => future.await?
335 fn suggest_await_before_try(
337 err: &mut Diagnostic,
338 obligation: &PredicateObligation<'tcx>,
339 trait_pred: ty::PolyTraitPredicate<'tcx>,
343 fn suggest_floating_point_literal(
345 obligation: &PredicateObligation<'tcx>,
346 err: &mut Diagnostic,
347 trait_ref: &ty::PolyTraitRef<'tcx>,
352 obligation: &PredicateObligation<'tcx>,
353 err: &mut Diagnostic,
354 trait_pred: ty::PolyTraitPredicate<'tcx>,
357 fn suggest_dereferencing_index(
359 obligation: &PredicateObligation<'tcx>,
360 err: &mut Diagnostic,
361 trait_pred: ty::PolyTraitPredicate<'tcx>,
363 fn note_function_argument_obligation(
366 err: &mut Diagnostic,
367 parent_code: &ObligationCauseCode<'tcx>,
368 param_env: ty::ParamEnv<'tcx>,
369 predicate: ty::Predicate<'tcx>,
374 expr: &hir::Expr<'_>,
375 typeck_results: &TypeckResults<'tcx>,
376 type_diffs: Vec<TypeError<'tcx>>,
377 param_env: ty::ParamEnv<'tcx>,
378 err: &mut Diagnostic,
380 fn probe_assoc_types_at_expr(
382 type_diffs: &[TypeError<'tcx>],
386 param_env: ty::ParamEnv<'tcx>,
387 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>>;
390 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
392 generics.tail_span_for_predicate_suggestion(),
393 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
397 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
398 /// it can also be an `impl Trait` param that needs to be decomposed to a type
399 /// param for cleaner code.
400 fn suggest_restriction<'tcx>(
403 hir_generics: &hir::Generics<'tcx>,
405 err: &mut Diagnostic,
406 fn_sig: Option<&hir::FnSig<'_>>,
407 projection: Option<&ty::AliasTy<'_>>,
408 trait_pred: ty::PolyTraitPredicate<'tcx>,
409 // When we are dealing with a trait, `super_traits` will be `Some`:
410 // Given `trait T: A + B + C {}`
411 // - ^^^^^^^^^ GenericBounds
414 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
416 if hir_generics.where_clause_span.from_expansion()
417 || hir_generics.where_clause_span.desugaring_kind().is_some()
421 let Some(item_id) = hir_id.as_owner() else { return; };
422 let generics = tcx.generics_of(item_id);
423 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
424 if let Some((param, bound_str, fn_sig)) =
425 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
426 // Shenanigans to get the `Trait` from the `impl Trait`.
427 ty::Param(param) => {
428 let param_def = generics.type_param(param, tcx);
429 if param_def.kind.is_synthetic() {
431 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
432 return Some((param_def, bound_str, sig));
439 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
440 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
443 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
446 if !trait_pred.is_suggestable(tcx, false) {
449 // We know we have an `impl Trait` that doesn't satisfy a required projection.
451 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
452 // types. There should be at least one, but there might be *more* than one. In that
453 // case we could just ignore it and try to identify which one needs the restriction,
454 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
456 let mut ty_spans = vec![];
457 for input in fn_sig.decl.inputs {
458 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
461 // The type param `T: Trait` we will suggest to introduce.
462 let type_param = format!("{}: {}", type_param_name, bound_str);
465 if let Some(span) = hir_generics.span_for_param_suggestion() {
466 (span, format!(", {}", type_param))
468 (hir_generics.span, format!("<{}>", type_param))
470 // `fn foo(t: impl Trait)`
471 // ^ suggest `where <T as Trait>::A: Bound`
472 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
474 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
476 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
477 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
478 // `fn foo(t: impl Trait<A: Bound>)` instead.
479 err.multipart_suggestion(
480 "introduce a type parameter with a trait bound instead of using `impl Trait`",
482 Applicability::MaybeIncorrect,
485 if !trait_pred.is_suggestable(tcx, false) {
488 // Trivial case: `T` needs an extra bound: `T: Bound`.
489 let (sp, suggestion) = match (
493 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
496 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
497 (None, Some((ident, []))) => (
498 ident.span.shrink_to_hi(),
499 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
501 (_, Some((_, [.., bounds]))) => (
502 bounds.span().shrink_to_hi(),
503 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
505 (Some(_), Some((_, []))) => (
506 hir_generics.span.shrink_to_hi(),
507 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
511 err.span_suggestion_verbose(
513 &format!("consider further restricting {}", msg),
515 Applicability::MachineApplicable,
520 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
521 fn suggest_restricting_param_bound(
523 mut err: &mut Diagnostic,
524 trait_pred: ty::PolyTraitPredicate<'tcx>,
525 associated_ty: Option<(&'static str, Ty<'tcx>)>,
528 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
530 let self_ty = trait_pred.skip_binder().self_ty();
531 let (param_ty, projection) = match self_ty.kind() {
532 ty::Param(_) => (true, None),
533 ty::Alias(ty::Projection, projection) => (false, Some(projection)),
537 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
538 // don't suggest `T: Sized + ?Sized`.
539 let mut body_id = body_id;
540 while let Some(node) = self.tcx.hir().find_by_def_id(body_id) {
541 let hir_id = self.tcx.hir().local_def_id_to_hir_id(body_id);
543 hir::Node::Item(hir::Item {
545 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
547 }) if self_ty == self.tcx.types.self_param => {
549 // Restricting `Self` for a single method.
559 Some((ident, bounds)),
564 hir::Node::TraitItem(hir::TraitItem {
566 kind: hir::TraitItemKind::Fn(..),
568 }) if self_ty == self.tcx.types.self_param => {
570 // Restricting `Self` for a single method.
572 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
578 hir::Node::TraitItem(hir::TraitItem {
580 kind: hir::TraitItemKind::Fn(fn_sig, ..),
583 | hir::Node::ImplItem(hir::ImplItem {
585 kind: hir::ImplItemKind::Fn(fn_sig, ..),
588 | hir::Node::Item(hir::Item {
589 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
590 }) if projection.is_some() => {
591 // Missing restriction on associated type of type parameter (unmet projection).
596 "the associated type",
605 hir::Node::Item(hir::Item {
607 hir::ItemKind::Trait(_, _, generics, ..)
608 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
610 }) if projection.is_some() => {
611 // Missing restriction on associated type of type parameter (unmet projection).
616 "the associated type",
626 hir::Node::Item(hir::Item {
628 hir::ItemKind::Struct(_, generics)
629 | hir::ItemKind::Enum(_, generics)
630 | hir::ItemKind::Union(_, generics)
631 | hir::ItemKind::Trait(_, _, generics, ..)
632 | hir::ItemKind::Impl(hir::Impl { generics, .. })
633 | hir::ItemKind::Fn(_, generics, _)
634 | hir::ItemKind::TyAlias(_, generics)
635 | hir::ItemKind::TraitAlias(generics, _)
636 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
639 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
640 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
643 // We skip the 0'th subst (self) because we do not want
644 // to consider the predicate as not suggestible if the
645 // self type is an arg position `impl Trait` -- instead,
646 // we handle that by adding ` + Bound` below.
647 // FIXME(compiler-errors): It would be nice to do the same
648 // this that we do in `suggest_restriction` and pull the
649 // `impl Trait` into a new generic if it shows up somewhere
650 // else in the predicate.
651 if !trait_pred.skip_binder().trait_ref.substs[1..]
653 .all(|g| g.is_suggestable(self.tcx, false))
657 // Missing generic type parameter bound.
658 let param_name = self_ty.to_string();
659 let mut constraint = with_no_trimmed_paths!(
660 trait_pred.print_modifiers_and_trait_path().to_string()
663 if let Some((name, term)) = associated_ty {
664 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
665 // That should be extracted into a helper function.
666 if constraint.ends_with('>') {
667 constraint = format!(
669 &constraint[..constraint.len() - 1],
674 constraint.push_str(&format!("<{} = {}>", name, term));
678 if suggest_constraining_type_param(
684 Some(trait_pred.def_id()),
690 hir::Node::Item(hir::Item {
692 hir::ItemKind::Struct(_, generics)
693 | hir::ItemKind::Enum(_, generics)
694 | hir::ItemKind::Union(_, generics)
695 | hir::ItemKind::Trait(_, _, generics, ..)
696 | hir::ItemKind::Impl(hir::Impl { generics, .. })
697 | hir::ItemKind::Fn(_, generics, _)
698 | hir::ItemKind::TyAlias(_, generics)
699 | hir::ItemKind::TraitAlias(generics, _)
700 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
703 // Missing generic type parameter bound.
704 if suggest_arbitrary_trait_bound(
714 hir::Node::Crate(..) => return,
718 body_id = self.tcx.local_parent(body_id);
722 /// When after several dereferencing, the reference satisfies the trait
723 /// binding. This function provides dereference suggestion for this
724 /// specific situation.
725 fn suggest_dereferences(
727 obligation: &PredicateObligation<'tcx>,
728 err: &mut Diagnostic,
729 trait_pred: ty::PolyTraitPredicate<'tcx>,
731 // It only make sense when suggesting dereferences for arguments
732 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = obligation.cause.code()
733 else { return false; };
734 let Some(typeck_results) = &self.typeck_results
735 else { return false; };
736 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
737 else { return false; };
738 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
739 else { return false; };
741 let span = obligation.cause.span;
742 let mut real_trait_pred = trait_pred;
743 let mut code = obligation.cause.code();
744 while let Some((parent_code, parent_trait_pred)) = code.parent() {
746 if let Some(parent_trait_pred) = parent_trait_pred {
747 real_trait_pred = parent_trait_pred;
750 let real_ty = real_trait_pred.self_ty();
751 // We `erase_late_bound_regions` here because `make_subregion` does not handle
752 // `ReLateBound`, and we don't particularly care about the regions.
754 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
760 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
761 let autoderef = (self.autoderef_steps)(base_ty);
763 autoderef.into_iter().enumerate().find_map(|(steps, (ty, obligations))| {
765 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
767 // Remapping bound vars here
768 let real_trait_pred_and_ty =
769 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
770 let obligation = self.mk_trait_obligation_with_new_self_ty(
771 obligation.param_env,
772 real_trait_pred_and_ty,
776 .chain([&obligation])
777 .all(|obligation| self.predicate_may_hold(obligation))
786 // Don't care about `&mut` because `DerefMut` is used less
787 // often and user will not expect autoderef happens.
788 if let Some(hir::Node::Expr(hir::Expr {
790 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
792 })) = self.tcx.hir().find(*arg_hir_id)
794 let derefs = "*".repeat(steps);
795 err.span_suggestion_verbose(
796 expr.span.shrink_to_lo(),
797 "consider dereferencing here",
799 Applicability::MachineApplicable,
804 } else if real_trait_pred != trait_pred {
805 // This branch addresses #87437.
807 // Remapping bound vars here
808 let real_trait_pred_and_base_ty =
809 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
810 let obligation = self.mk_trait_obligation_with_new_self_ty(
811 obligation.param_env,
812 real_trait_pred_and_base_ty,
814 if self.predicate_may_hold(&obligation) {
815 let call_node = self.tcx.hir().get(*call_hir_id);
816 let msg = "consider dereferencing here";
817 let is_receiver = matches!(
819 Node::Expr(hir::Expr {
820 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
823 if receiver_expr.hir_id == *arg_hir_id
826 err.multipart_suggestion_verbose(
829 (span.shrink_to_lo(), "(*".to_string()),
830 (span.shrink_to_hi(), ")".to_string()),
832 Applicability::MachineApplicable,
835 err.span_suggestion_verbose(
839 Applicability::MachineApplicable,
850 /// Given a closure's `DefId`, return the given name of the closure.
852 /// This doesn't account for reassignments, but it's only used for suggestions.
853 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
854 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
855 // Get the local name of this closure. This can be inaccurate because
856 // of the possibility of reassignment, but this should be good enough.
858 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
868 let hir = self.tcx.hir();
869 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
870 match hir.find_parent(hir_id) {
871 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
872 get_name(err, &local.pat.kind)
874 // Different to previous arm because one is `&hir::Local` and the other
875 // is `P<hir::Local>`.
876 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
881 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
882 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
883 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
886 obligation: &PredicateObligation<'tcx>,
887 err: &mut Diagnostic,
888 trait_pred: ty::PolyTraitPredicate<'tcx>,
890 // It doesn't make sense to make this suggestion outside of typeck...
891 // (also autoderef will ICE...)
892 if self.typeck_results.is_none() {
896 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
897 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
899 // Don't suggest calling to turn an unsized type into a sized type
903 let self_ty = self.replace_bound_vars_with_fresh_vars(
905 LateBoundRegionConversionTime::FnCall,
906 trait_pred.self_ty(),
909 let body_hir_id = self.tcx.hir().local_def_id_to_hir_id(obligation.cause.body_id);
910 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(
912 obligation.param_env,
914 ) else { return false; };
916 // Remapping bound vars here
917 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
920 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
921 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
925 // Get the name of the callable and the arguments to be used in the suggestion.
926 let hir = self.tcx.hir();
928 let msg = match def_id_or_name {
929 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
930 DefKind::Ctor(CtorOf::Struct, _) => {
931 "use parentheses to construct this tuple struct".to_string()
933 DefKind::Ctor(CtorOf::Variant, _) => {
934 "use parentheses to construct this tuple variant".to_string()
936 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
938 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
944 if ty.is_suggestable(self.tcx, false) {
945 format!("/* {ty} */")
947 "/* value */".to_string()
953 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
954 && obligation.cause.span.can_be_used_for_suggestions()
956 // When the obligation error has been ensured to have been caused by
957 // an argument, the `obligation.cause.span` points at the expression
958 // of the argument, so we can provide a suggestion. Otherwise, we give
959 // a more general note.
960 err.span_suggestion_verbose(
961 obligation.cause.span.shrink_to_hi(),
964 Applicability::HasPlaceholders,
966 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
967 let name = match hir.get_if_local(def_id) {
968 Some(hir::Node::Expr(hir::Expr {
969 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
972 err.span_label(*fn_decl_span, "consider calling this closure");
973 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
978 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
979 err.span_label(ident.span, "consider calling this function");
982 Some(hir::Node::Ctor(..)) => {
983 let name = self.tcx.def_path_str(def_id);
985 self.tcx.def_span(def_id),
986 format!("consider calling the constructor for `{}`", name),
992 err.help(&format!("{msg}: `{name}({args})`"));
997 fn check_for_binding_assigned_block_without_tail_expression(
999 obligation: &PredicateObligation<'tcx>,
1000 err: &mut Diagnostic,
1001 trait_pred: ty::PolyTraitPredicate<'tcx>,
1003 let mut span = obligation.cause.span;
1004 while span.from_expansion() {
1005 // Remove all the desugaring and macro contexts.
1008 let mut expr_finder = FindExprBySpan::new(span);
1009 let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { return; };
1010 let body = self.tcx.hir().body(body_id);
1011 expr_finder.visit_expr(body.value);
1012 let Some(expr) = expr_finder.result else { return; };
1013 let Some(typeck) = &self.typeck_results else { return; };
1014 let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { return; };
1018 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; };
1019 let hir::def::Res::Local(hir_id) = path.res else { return; };
1020 let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else {
1023 let Some(hir::Node::Local(hir::Local {
1027 })) = self.tcx.hir().find_parent(pat.hir_id) else { return; };
1028 let hir::ExprKind::Block(block, None) = init.kind else { return; };
1029 if block.expr.is_some() {
1032 let [.., stmt] = block.stmts else {
1033 err.span_label(block.span, "this empty block is missing a tail expression");
1036 let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; };
1037 let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1038 err.span_label(block.span, "this block is missing a tail expression");
1041 let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
1042 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1044 let new_obligation =
1045 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1046 if self.predicate_must_hold_modulo_regions(&new_obligation) {
1047 err.span_suggestion_short(
1048 stmt.span.with_lo(tail_expr.span.hi()),
1049 "remove this semicolon",
1051 Applicability::MachineApplicable,
1054 err.span_label(block.span, "this block is missing a tail expression");
1058 fn suggest_add_clone_to_arg(
1060 obligation: &PredicateObligation<'tcx>,
1061 err: &mut Diagnostic,
1062 trait_pred: ty::PolyTraitPredicate<'tcx>,
1064 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
1065 let ty = self.tcx.erase_late_bound_regions(self_ty);
1066 let Some(generics) = self.tcx.hir().get_generics(obligation.cause.body_id) else { return false };
1067 let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
1068 let ty::Param(param) = inner_ty.kind() else { return false };
1069 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() else { return false };
1070 let arg_node = self.tcx.hir().get(*arg_hir_id);
1071 let Node::Expr(Expr { kind: hir::ExprKind::Path(_), ..}) = arg_node else { return false };
1073 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None);
1074 let has_clone = |ty| {
1075 self.type_implements_trait(clone_trait, [ty], obligation.param_env)
1076 .must_apply_modulo_regions()
1079 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1080 obligation.param_env,
1081 trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1084 if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1085 if !has_clone(param.to_ty(self.tcx)) {
1086 suggest_constraining_type_param(
1090 param.name.as_str(),
1095 err.span_suggestion_verbose(
1096 obligation.cause.span.shrink_to_hi(),
1097 "consider using clone here",
1098 ".clone()".to_string(),
1099 Applicability::MaybeIncorrect,
1106 /// Extracts information about a callable type for diagnostics. This is a
1107 /// heuristic -- it doesn't necessarily mean that a type is always callable,
1108 /// because the callable type must also be well-formed to be called.
1109 // FIXME(vincenzopalazzo): move the HirId to a LocalDefId
1110 fn extract_callable_info(
1113 param_env: ty::ParamEnv<'tcx>,
1115 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1116 // Autoderef is useful here because sometimes we box callables, etc.
1117 let Some((def_id_or_name, output, inputs)) = (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| {
1118 match *found.kind() {
1119 ty::FnPtr(fn_sig) =>
1120 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
1121 ty::FnDef(def_id, _) => {
1122 let fn_sig = found.fn_sig(self.tcx);
1123 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1125 ty::Closure(def_id, substs) => {
1126 let fn_sig = substs.as_closure().sig();
1127 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
1129 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
1130 self.tcx.item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
1131 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
1132 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
1133 // args tuple will always be substs[1]
1134 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
1137 DefIdOrName::DefId(def_id),
1138 pred.kind().rebind(proj.term.ty().unwrap()),
1139 pred.kind().rebind(args.as_slice()),
1146 ty::Dynamic(data, _, ty::Dyn) => {
1147 data.iter().find_map(|pred| {
1148 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1149 && Some(proj.def_id) == self.tcx.lang_items().fn_once_output()
1150 // for existential projection, substs are shifted over by 1
1151 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
1154 DefIdOrName::Name("trait object"),
1155 pred.rebind(proj.term.ty().unwrap()),
1156 pred.rebind(args.as_slice()),
1163 ty::Param(param) => {
1164 let generics = self.tcx.generics_of(hir_id.owner.to_def_id());
1165 let name = if generics.count() > param.index as usize
1166 && let def = generics.param_at(param.index as usize, self.tcx)
1167 && matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1168 && def.name == param.name
1170 DefIdOrName::DefId(def.def_id)
1172 DefIdOrName::Name("type parameter")
1174 param_env.caller_bounds().iter().find_map(|pred| {
1175 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
1176 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
1177 && proj.projection_ty.self_ty() == found
1178 // args tuple will always be substs[1]
1179 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
1183 pred.kind().rebind(proj.term.ty().unwrap()),
1184 pred.kind().rebind(args.as_slice()),
1193 }) else { return None; };
1195 let output = self.replace_bound_vars_with_fresh_vars(
1197 LateBoundRegionConversionTime::FnCall,
1204 self.replace_bound_vars_with_fresh_vars(
1206 LateBoundRegionConversionTime::FnCall,
1212 // We don't want to register any extra obligations, which should be
1213 // implied by wf, but also because that would possibly result in
1214 // erroneous errors later on.
1215 let InferOk { value: output, obligations: _ } =
1216 self.at(&ObligationCause::dummy(), param_env).normalize(output);
1218 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1221 fn suggest_add_reference_to_arg(
1223 obligation: &PredicateObligation<'tcx>,
1224 err: &mut Diagnostic,
1225 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1226 has_custom_message: bool,
1228 let span = obligation.cause.span;
1230 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
1231 obligation.cause.code()
1234 } else if let ObligationCauseCode::ItemObligation(_)
1235 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1237 obligation.cause.code()
1238 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1239 span.ctxt().outer_expn_data().kind
1241 obligation.cause.code()
1246 // List of traits for which it would be nonsensical to suggest borrowing.
1247 // For instance, immutable references are always Copy, so suggesting to
1248 // borrow would always succeed, but it's probably not what the user wanted.
1249 let mut never_suggest_borrow: Vec<_> =
1250 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1252 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1255 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1256 never_suggest_borrow.push(def_id);
1259 let param_env = obligation.param_env;
1261 // Try to apply the original trait binding obligation by borrowing.
1262 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1263 blacklist: &[DefId]|
1265 if blacklist.contains(&old_pred.def_id()) {
1268 // We map bounds to `&T` and `&mut T`
1269 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1272 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1275 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1278 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1282 let mk_result = |trait_pred_and_new_ty| {
1284 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1285 self.predicate_must_hold_modulo_regions(&obligation)
1287 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1288 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1290 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1291 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1292 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1295 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1296 mutability.is_mut(),
1302 if imm_ref_self_ty_satisfies_pred
1303 || mut_ref_self_ty_satisfies_pred
1304 || ref_inner_ty_satisfies_pred
1306 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1307 // We don't want a borrowing suggestion on the fields in structs,
1310 // the_foos: Vec<Foo>
1314 span.ctxt().outer_expn_data().kind,
1315 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1319 if snippet.starts_with('&') {
1320 // This is already a literal borrow and the obligation is failing
1321 // somewhere else in the obligation chain. Do not suggest non-sense.
1324 // We have a very specific type of error, where just borrowing this argument
1325 // might solve the problem. In cases like this, the important part is the
1326 // original type obligation, not the last one that failed, which is arbitrary.
1327 // Because of this, we modify the error to refer to the original obligation and
1328 // return early in the caller.
1330 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1331 if has_custom_message {
1335 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1340 "the trait `{}` is not implemented for `{}`",
1341 old_pred.print_modifiers_and_trait_path(),
1342 old_pred.self_ty().skip_binder(),
1346 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1347 err.span_suggestions(
1348 span.shrink_to_lo(),
1349 "consider borrowing here",
1350 ["&".to_string(), "&mut ".to_string()],
1351 Applicability::MaybeIncorrect,
1354 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1355 err.span_suggestion_verbose(
1356 span.shrink_to_lo(),
1358 "consider{} borrowing here",
1359 if is_mut { " mutably" } else { "" }
1361 format!("&{}", if is_mut { "mut " } else { "" }),
1362 Applicability::MaybeIncorrect,
1371 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1372 try_borrowing(cause.derived.parent_trait_pred, &[])
1373 } else if let ObligationCauseCode::BindingObligation(_, _)
1374 | ObligationCauseCode::ItemObligation(_)
1375 | ObligationCauseCode::ExprItemObligation(..)
1376 | ObligationCauseCode::ExprBindingObligation(..) = code
1378 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1384 // Suggest borrowing the type
1385 fn suggest_borrowing_for_object_cast(
1387 err: &mut Diagnostic,
1388 obligation: &PredicateObligation<'tcx>,
1390 object_ty: Ty<'tcx>,
1392 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1393 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1395 for predicate in predicates.iter() {
1396 if !self.predicate_must_hold_modulo_regions(
1397 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1403 err.span_suggestion(
1404 obligation.cause.span.shrink_to_lo(),
1406 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1409 Applicability::MaybeIncorrect,
1413 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1414 /// suggest removing these references until we reach a type that implements the trait.
1415 fn suggest_remove_reference(
1417 obligation: &PredicateObligation<'tcx>,
1418 err: &mut Diagnostic,
1419 trait_pred: ty::PolyTraitPredicate<'tcx>,
1421 let mut span = obligation.cause.span;
1422 let mut trait_pred = trait_pred;
1423 let mut code = obligation.cause.code();
1424 while let Some((c, Some(parent_trait_pred))) = code.parent() {
1425 // We want the root obligation, in order to detect properly handle
1426 // `for _ in &mut &mut vec![] {}`.
1428 trait_pred = parent_trait_pred;
1430 while span.desugaring_kind().is_some() {
1431 // Remove all the hir desugaring contexts while maintaining the macro contexts.
1434 let mut expr_finder = super::FindExprBySpan::new(span);
1435 let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else {
1438 let body = self.tcx.hir().body(body_id);
1439 expr_finder.visit_expr(body.value);
1440 let mut maybe_suggest = |suggested_ty, count, suggestions| {
1441 // Remapping bound vars here
1442 let trait_pred_and_suggested_ty =
1443 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1445 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1446 obligation.param_env,
1447 trait_pred_and_suggested_ty,
1450 if self.predicate_may_hold(&new_obligation) {
1451 let msg = if count == 1 {
1452 "consider removing the leading `&`-reference".to_string()
1454 format!("consider removing {count} leading `&`-references")
1457 err.multipart_suggestion_verbose(
1460 Applicability::MachineApplicable,
1468 // Maybe suggest removal of borrows from types in type parameters, like in
1469 // `src/test/ui/not-panic/not-panic-safe.rs`.
1471 let mut suggestions = vec![];
1472 // Skipping binder here, remapping below
1473 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1474 if let Some(mut hir_ty) = expr_finder.ty_result {
1475 while let hir::TyKind::Ref(_, mut_ty) = &hir_ty.kind {
1477 let span = hir_ty.span.until(mut_ty.ty.span);
1478 suggestions.push((span, String::new()));
1480 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1483 suggested_ty = *inner_ty;
1487 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1493 // Maybe suggest removal of borrows from expressions, like in `for i in &&&foo {}`.
1494 let Some(mut expr) = expr_finder.result else { return false; };
1496 let mut suggestions = vec![];
1497 // Skipping binder here, remapping below
1498 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1500 while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
1502 let span = if expr.span.eq_ctxt(borrowed.span) {
1503 expr.span.until(borrowed.span)
1505 expr.span.with_hi(expr.span.lo() + BytePos(1))
1507 suggestions.push((span, String::new()));
1509 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1512 suggested_ty = *inner_ty;
1516 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1520 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1521 && let hir::def::Res::Local(hir_id) = path.res
1522 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(hir_id)
1523 && let Some(hir::Node::Local(local)) = self.tcx.hir().find_parent(binding.hir_id)
1524 && let None = local.ty
1525 && let Some(binding_expr) = local.init
1527 expr = binding_expr;
1535 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1536 let span = obligation.cause.span;
1538 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1539 let hir = self.tcx.hir();
1540 if let Some(hir::Node::Expr(expr)) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1541 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1542 // and if not maybe suggest doing something else? If we kept the expression around we
1543 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1544 // it is from the local crate.
1545 err.span_suggestion(
1547 "remove the `.await`",
1549 Applicability::MachineApplicable,
1551 // FIXME: account for associated `async fn`s.
1552 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1553 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1554 obligation.predicate.kind().skip_binder()
1556 err.span_label(*span, &format!("this call returns `{}`", pred.self_ty()));
1558 if let Some(typeck_results) = &self.typeck_results
1559 && let ty = typeck_results.expr_ty_adjusted(base)
1560 && let ty::FnDef(def_id, _substs) = ty.kind()
1561 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1562 hir.get_if_local(*def_id)
1565 "alternatively, consider making `fn {}` asynchronous",
1568 if vis_span.is_empty() {
1569 err.span_suggestion_verbose(
1570 span.shrink_to_lo(),
1573 Applicability::MaybeIncorrect,
1576 err.span_suggestion_verbose(
1577 vis_span.shrink_to_hi(),
1580 Applicability::MaybeIncorrect,
1589 /// Check if the trait bound is implemented for a different mutability and note it in the
1591 fn suggest_change_mut(
1593 obligation: &PredicateObligation<'tcx>,
1594 err: &mut Diagnostic,
1595 trait_pred: ty::PolyTraitPredicate<'tcx>,
1597 let points_at_arg = matches!(
1598 obligation.cause.code(),
1599 ObligationCauseCode::FunctionArgumentObligation { .. },
1602 let span = obligation.cause.span;
1603 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1605 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1606 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1607 // Do not suggest removal of borrow from type arguments.
1610 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1611 if trait_pred.has_non_region_infer() {
1612 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1613 // unresolved bindings.
1617 // Skipping binder here, remapping below
1618 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1620 let suggested_ty = match mutability {
1621 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1622 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1625 // Remapping bound vars here
1626 let trait_pred_and_suggested_ty =
1627 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1629 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1630 obligation.param_env,
1631 trait_pred_and_suggested_ty,
1633 let suggested_ty_would_satisfy_obligation = self
1634 .evaluate_obligation_no_overflow(&new_obligation)
1635 .must_apply_modulo_regions();
1636 if suggested_ty_would_satisfy_obligation {
1641 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1642 if points_at_arg && mutability.is_not() && refs_number > 0 {
1643 // If we have a call like foo(&mut buf), then don't suggest foo(&mut mut buf)
1645 .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
1650 err.span_suggestion_verbose(
1652 "consider changing this borrow's mutability",
1654 Applicability::MachineApplicable,
1658 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1659 trait_pred.print_modifiers_and_trait_path(),
1661 trait_pred.skip_binder().self_ty(),
1669 fn suggest_semicolon_removal(
1671 obligation: &PredicateObligation<'tcx>,
1672 err: &mut Diagnostic,
1674 trait_pred: ty::PolyTraitPredicate<'tcx>,
1676 let hir = self.tcx.hir();
1677 let node = hir.find_by_def_id(obligation.cause.body_id);
1678 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1679 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1680 && sig.decl.output.span().overlaps(span)
1681 && blk.expr.is_none()
1682 && trait_pred.self_ty().skip_binder().is_unit()
1683 && let Some(stmt) = blk.stmts.last()
1684 && let hir::StmtKind::Semi(expr) = stmt.kind
1685 // Only suggest this if the expression behind the semicolon implements the predicate
1686 && let Some(typeck_results) = &self.typeck_results
1687 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1688 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1689 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1695 "this expression has type `{}`, which implements `{}`",
1697 trait_pred.print_modifiers_and_trait_path()
1700 err.span_suggestion(
1701 self.tcx.sess.source_map().end_point(stmt.span),
1702 "remove this semicolon",
1704 Applicability::MachineApplicable
1711 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1712 let hir = self.tcx.hir();
1713 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find_by_def_id(obligation.cause.body_id) else {
1717 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1720 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1721 /// applicable and signal that the error has been expanded appropriately and needs to be
1723 fn suggest_impl_trait(
1725 err: &mut Diagnostic,
1727 obligation: &PredicateObligation<'tcx>,
1728 trait_pred: ty::PolyTraitPredicate<'tcx>,
1730 match obligation.cause.code().peel_derives() {
1731 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1732 ObligationCauseCode::SizedReturnType => {}
1736 let hir = self.tcx.hir();
1737 let fn_hir_id = hir.local_def_id_to_hir_id(obligation.cause.body_id);
1738 let node = hir.find_by_def_id(obligation.cause.body_id);
1739 let Some(hir::Node::Item(hir::Item {
1740 kind: hir::ItemKind::Fn(sig, _, body_id),
1746 let body = hir.body(*body_id);
1747 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1748 let ty = trait_pred.skip_binder().self_ty();
1749 let is_object_safe = match ty.kind() {
1750 ty::Dynamic(predicates, _, ty::Dyn) => {
1751 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1754 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1756 // We only want to suggest `impl Trait` to `dyn Trait`s.
1757 // For example, `fn foo() -> str` needs to be filtered out.
1761 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1765 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1766 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1767 // Recursively look for `TraitObject` types and if there's only one, use that span to
1768 // suggest `impl Trait`.
1770 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1771 // otherwise suggest using `Box<dyn Trait>` or an enum.
1772 let mut visitor = ReturnsVisitor::default();
1773 visitor.visit_body(&body);
1775 let typeck_results = self.typeck_results.as_ref().unwrap();
1776 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1778 let ret_types = visitor
1781 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1782 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1783 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1785 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1787 let ty = self.resolve_vars_if_possible(ty);
1789 !matches!(ty.kind(), ty::Error(_))
1790 && last_ty.map_or(true, |last_ty| {
1791 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1792 // *after* in the dependency graph.
1793 match (ty.kind(), last_ty.kind()) {
1794 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1795 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1796 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1798 Infer(InferTy::FreshFloatTy(_)),
1799 Infer(InferTy::FreshFloatTy(_)),
1804 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1807 let mut spans_and_needs_box = vec![];
1809 match liberated_sig.output().kind() {
1810 ty::Dynamic(predicates, _, ty::Dyn) => {
1811 let cause = ObligationCause::misc(ret_ty.span, obligation.cause.body_id);
1812 let param_env = ty::ParamEnv::empty();
1814 if !only_never_return {
1815 for (expr_span, return_ty) in ret_types {
1816 let self_ty_satisfies_dyn_predicates = |self_ty| {
1817 predicates.iter().all(|predicate| {
1818 let pred = predicate.with_self_ty(self.tcx, self_ty);
1819 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1820 self.predicate_may_hold(&obl)
1824 if let ty::Adt(def, substs) = return_ty.kind()
1826 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1828 spans_and_needs_box.push((expr_span, false));
1829 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1830 spans_and_needs_box.push((expr_span, true));
1840 let sm = self.tcx.sess.source_map();
1841 if !ret_ty.span.overlaps(span) {
1844 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1845 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1851 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1852 let name = liberated_sig.output().to_string();
1854 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1855 if !name.starts_with("dyn ") {
1861 err.code(error_code!(E0746));
1862 err.set_primary_message("return type cannot have an unboxed trait object");
1863 err.children.clear();
1864 let impl_trait_msg = "for information on `impl Trait`, see \
1865 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1866 #returning-types-that-implement-traits>";
1867 let trait_obj_msg = "for information on trait objects, see \
1868 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1869 #using-trait-objects-that-allow-for-values-of-different-types>";
1871 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1872 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1873 if only_never_return {
1874 // No return paths, probably using `panic!()` or similar.
1875 // Suggest `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1876 suggest_trait_object_return_type_alternatives(
1882 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1883 // Suggest `-> impl Trait`.
1884 err.span_suggestion(
1887 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1888 which implements `{1}`",
1891 format!("impl {}", trait_obj),
1892 Applicability::MachineApplicable,
1894 err.note(impl_trait_msg);
1897 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1898 err.multipart_suggestion(
1899 "return a boxed trait object instead",
1901 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1902 (span.shrink_to_hi(), ">".to_string()),
1904 Applicability::MaybeIncorrect,
1906 for (span, needs_box) in spans_and_needs_box {
1908 err.multipart_suggestion(
1909 "... and box this value",
1911 (span.shrink_to_lo(), "Box::new(".to_string()),
1912 (span.shrink_to_hi(), ")".to_string()),
1914 Applicability::MaybeIncorrect,
1919 // This is currently not possible to trigger because E0038 takes precedence, but
1920 // leave it in for completeness in case anything changes in an earlier stage.
1922 "if trait `{}` were object-safe, you could return a trait object",
1926 err.note(trait_obj_msg);
1928 "if all the returned values were of the same type you could use `impl {}` as the \
1932 err.note(impl_trait_msg);
1933 err.note("you can create a new `enum` with a variant for each returned type");
1938 fn point_at_returns_when_relevant(
1940 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1941 obligation: &PredicateObligation<'tcx>,
1943 match obligation.cause.code().peel_derives() {
1944 ObligationCauseCode::SizedReturnType => {}
1948 let hir = self.tcx.hir();
1949 let node = hir.find_by_def_id(obligation.cause.body_id);
1950 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1953 let body = hir.body(*body_id);
1954 // Point at all the `return`s in the function as they have failed trait bounds.
1955 let mut visitor = ReturnsVisitor::default();
1956 visitor.visit_body(&body);
1957 let typeck_results = self.typeck_results.as_ref().unwrap();
1958 for expr in &visitor.returns {
1959 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1960 let ty = self.resolve_vars_if_possible(returned_ty);
1961 if ty.references_error() {
1962 // don't print out the [type error] here
1967 &format!("this returned value is of type `{}`", ty),
1975 fn report_closure_arg_mismatch(
1978 found_span: Option<Span>,
1979 found: ty::PolyTraitRef<'tcx>,
1980 expected: ty::PolyTraitRef<'tcx>,
1981 cause: &ObligationCauseCode<'tcx>,
1982 found_node: Option<Node<'_>>,
1983 param_env: ty::ParamEnv<'tcx>,
1984 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1985 pub(crate) fn build_fn_sig_ty<'tcx>(
1986 infcx: &InferCtxt<'tcx>,
1987 trait_ref: ty::PolyTraitRef<'tcx>,
1989 let inputs = trait_ref.skip_binder().substs.type_at(1);
1990 let sig = match inputs.kind() {
1991 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1992 infcx.tcx.mk_fn_sig(
1994 infcx.next_ty_var(TypeVariableOrigin {
1996 kind: TypeVariableOriginKind::MiscVariable,
1999 hir::Unsafety::Normal,
2003 _ => infcx.tcx.mk_fn_sig(
2004 std::iter::once(inputs),
2005 infcx.next_ty_var(TypeVariableOrigin {
2007 kind: TypeVariableOriginKind::MiscVariable,
2010 hir::Unsafety::Normal,
2015 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
2018 let argument_kind = match expected.skip_binder().self_ty().kind() {
2019 ty::Closure(..) => "closure",
2020 ty::Generator(..) => "generator",
2023 let mut err = struct_span_err!(
2027 "type mismatch in {argument_kind} arguments",
2030 err.span_label(span, "expected due to this");
2032 let found_span = found_span.unwrap_or(span);
2033 err.span_label(found_span, "found signature defined here");
2035 let expected = build_fn_sig_ty(self, expected);
2036 let found = build_fn_sig_ty(self, found);
2038 let (expected_str, found_str) = self.cmp(expected, found);
2040 let signature_kind = format!("{argument_kind} signature");
2041 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
2043 self.note_conflicting_closure_bounds(cause, &mut err);
2045 if let Some(found_node) = found_node {
2046 hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
2052 // Add a note if there are two `Fn`-family bounds that have conflicting argument
2053 // requirements, which will always cause a closure to have a type error.
2054 fn note_conflicting_closure_bounds(
2056 cause: &ObligationCauseCode<'tcx>,
2057 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2059 // First, look for an `ExprBindingObligation`, which means we can get
2060 // the unsubstituted predicate list of the called function. And check
2061 // that the predicate that we failed to satisfy is a `Fn`-like trait.
2062 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
2063 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
2064 && let Some(pred) = predicates.predicates.get(*idx)
2065 && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
2066 && self.tcx.is_fn_trait(trait_pred.def_id())
2069 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
2070 let expected_substs = self
2072 .anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.substs));
2074 // Find another predicate whose self-type is equal to the expected self type,
2075 // but whose substs don't match.
2076 let other_pred = predicates.into_iter()
2078 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
2079 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
2080 if self.tcx.is_fn_trait(trait_pred.def_id())
2082 // Make sure that the self type matches
2083 // (i.e. constraining this closure)
2085 == self.tcx.anonymize_bound_vars(
2086 pred.kind().rebind(trait_pred.self_ty()),
2088 // But the substs don't match (i.e. incompatible args)
2090 != self.tcx.anonymize_bound_vars(
2091 pred.kind().rebind(trait_pred.trait_ref.substs),
2098 // If we found one, then it's very likely the cause of the error.
2099 if let Some((_, (_, other_pred_span))) = other_pred {
2102 "closure inferred to have a different signature due to this bound",
2108 fn suggest_fully_qualified_path(
2110 err: &mut Diagnostic,
2115 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
2116 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
2118 "{}s cannot be accessed directly on a `trait`, they can only be \
2119 accessed through a specific `impl`",
2120 assoc_item.kind.as_def_kind().descr(item_def_id)
2122 err.span_suggestion(
2124 "use the fully qualified path to an implementation",
2125 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
2126 Applicability::HasPlaceholders,
2132 /// Adds an async-await specific note to the diagnostic when the future does not implement
2133 /// an auto trait because of a captured type.
2136 /// note: future does not implement `Qux` as this value is used across an await
2137 /// --> $DIR/issue-64130-3-other.rs:17:5
2139 /// LL | let x = Foo;
2140 /// | - has type `Foo`
2141 /// LL | baz().await;
2142 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2144 /// | - `x` is later dropped here
2147 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2148 /// is "replaced" with a different message and a more specific error.
2151 /// error: future cannot be sent between threads safely
2152 /// --> $DIR/issue-64130-2-send.rs:21:5
2154 /// LL | fn is_send<T: Send>(t: T) { }
2155 /// | ---- required by this bound in `is_send`
2157 /// LL | is_send(bar());
2158 /// | ^^^^^^^ future returned by `bar` is not send
2160 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2161 /// implemented for `Foo`
2162 /// note: future is not send as this value is used across an await
2163 /// --> $DIR/issue-64130-2-send.rs:15:5
2165 /// LL | let x = Foo;
2166 /// | - has type `Foo`
2167 /// LL | baz().await;
2168 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2170 /// | - `x` is later dropped here
2173 /// Returns `true` if an async-await specific note was added to the diagnostic.
2174 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
2175 fn maybe_note_obligation_cause_for_async_await(
2177 err: &mut Diagnostic,
2178 obligation: &PredicateObligation<'tcx>,
2180 let hir = self.tcx.hir();
2182 // Attempt to detect an async-await error by looking at the obligation causes, looking
2183 // for a generator to be present.
2185 // When a future does not implement a trait because of a captured type in one of the
2186 // generators somewhere in the call stack, then the result is a chain of obligations.
2188 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
2189 // future is passed as an argument to a function C which requires a `Send` type, then the
2190 // chain looks something like this:
2192 // - `BuiltinDerivedObligation` with a generator witness (B)
2193 // - `BuiltinDerivedObligation` with a generator (B)
2194 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2195 // - `BuiltinDerivedObligation` with a generator witness (A)
2196 // - `BuiltinDerivedObligation` with a generator (A)
2197 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2198 // - `BindingObligation` with `impl_send (Send requirement)
2200 // The first obligation in the chain is the most useful and has the generator that captured
2201 // the type. The last generator (`outer_generator` below) has information about where the
2202 // bound was introduced. At least one generator should be present for this diagnostic to be
2204 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
2205 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
2208 let mut generator = None;
2209 let mut outer_generator = None;
2210 let mut next_code = Some(obligation.cause.code());
2212 let mut seen_upvar_tys_infer_tuple = false;
2214 while let Some(code) = next_code {
2217 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
2218 next_code = Some(parent_code);
2220 ObligationCauseCode::ImplDerivedObligation(cause) => {
2221 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
2223 parent_trait_ref = ?cause.derived.parent_trait_pred,
2224 self_ty.kind = ?ty.kind(),
2229 ty::Generator(did, ..) | ty::GeneratorWitnessMIR(did, _) => {
2230 generator = generator.or(Some(did));
2231 outer_generator = Some(did);
2233 ty::GeneratorWitness(..) => {}
2234 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2235 // By introducing a tuple of upvar types into the chain of obligations
2236 // of a generator, the first non-generator item is now the tuple itself,
2237 // we shall ignore this.
2239 seen_upvar_tys_infer_tuple = true;
2241 _ if generator.is_none() => {
2242 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
2243 target_ty = Some(ty);
2248 next_code = Some(&cause.derived.parent_code);
2250 ObligationCauseCode::DerivedObligation(derived_obligation)
2251 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
2252 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
2254 parent_trait_ref = ?derived_obligation.parent_trait_pred,
2255 self_ty.kind = ?ty.kind(),
2259 ty::Generator(did, ..) | ty::GeneratorWitnessMIR(did, ..) => {
2260 generator = generator.or(Some(did));
2261 outer_generator = Some(did);
2263 ty::GeneratorWitness(..) => {}
2264 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2265 // By introducing a tuple of upvar types into the chain of obligations
2266 // of a generator, the first non-generator item is now the tuple itself,
2267 // we shall ignore this.
2269 seen_upvar_tys_infer_tuple = true;
2271 _ if generator.is_none() => {
2272 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2273 target_ty = Some(ty);
2278 next_code = Some(&derived_obligation.parent_code);
2284 // Only continue if a generator was found.
2285 debug!(?generator, ?trait_ref, ?target_ty);
2286 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
2290 let span = self.tcx.def_span(generator_did);
2292 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
2295 ?generator_did_root,
2296 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2300 let generator_body = generator_did
2302 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2303 .map(|body_id| hir.body(body_id));
2304 let mut visitor = AwaitsVisitor::default();
2305 if let Some(body) = generator_body {
2306 visitor.visit_body(body);
2308 debug!(awaits = ?visitor.awaits);
2310 // Look for a type inside the generator interior that matches the target type to get
2312 let target_ty_erased = self.tcx.erase_regions(target_ty);
2313 let ty_matches = |ty| -> bool {
2314 // Careful: the regions for types that appear in the
2315 // generator interior are not generally known, so we
2316 // want to erase them when comparing (and anyway,
2317 // `Send` and other bounds are generally unaffected by
2318 // the choice of region). When erasing regions, we
2319 // also have to erase late-bound regions. This is
2320 // because the types that appear in the generator
2321 // interior generally contain "bound regions" to
2322 // represent regions that are part of the suspended
2323 // generator frame. Bound regions are preserved by
2324 // `erase_regions` and so we must also call
2325 // `erase_late_bound_regions`.
2326 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2327 let ty_erased = self.tcx.erase_regions(ty_erased);
2328 let eq = ty_erased == target_ty_erased;
2329 debug!(?ty_erased, ?target_ty_erased, ?eq);
2333 // Get the typeck results from the infcx if the generator is the function we are currently
2334 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2335 // cycles. If we can't use resolved types because the generator comes from another crate,
2336 // we still provide a targeted error but without all the relevant spans.
2337 let generator_data = match &self.typeck_results {
2338 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2339 _ if generator_did.is_local() => {
2340 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2342 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2343 GeneratorData::Foreign(generator_diag_data)
2348 let generator_within_in_progress_typeck = match &self.typeck_results {
2349 Some(t) => t.hir_owner.to_def_id() == generator_did_root,
2353 let mut interior_or_upvar_span = None;
2355 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2356 debug!(?from_awaited_ty);
2358 // The generator interior types share the same binders
2359 if let Some(cause) =
2360 generator_data.get_generator_interior_types().skip_binder().iter().find(
2361 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2362 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2366 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2368 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2370 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2373 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2374 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span, None));
2376 } else if self.tcx.sess.opts.unstable_opts.drop_tracking_mir
2377 // Avoid disclosing internal information to downstream crates.
2378 && generator_did.is_local()
2379 // Try to avoid cycles.
2380 && !generator_within_in_progress_typeck
2382 let generator_info = &self.tcx.mir_generator_witnesses(generator_did);
2383 debug!(?generator_info);
2385 'find_source: for (variant, source_info) in
2386 generator_info.variant_fields.iter().zip(&generator_info.variant_source_info)
2389 for &local in variant {
2390 let decl = &generator_info.field_tys[local];
2392 if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
2393 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2394 decl.source_info.span,
2395 Some((None, source_info.span, None, from_awaited_ty)),
2403 if interior_or_upvar_span.is_none() {
2404 interior_or_upvar_span =
2405 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2408 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2409 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2412 debug!(?interior_or_upvar_span);
2413 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2414 let is_async = self.tcx.generator_is_async(generator_did);
2415 let typeck_results = match generator_data {
2416 GeneratorData::Local(typeck_results) => Some(typeck_results),
2417 GeneratorData::Foreign(_) => None,
2419 self.note_obligation_cause_for_async_await(
2421 interior_or_upvar_span,
2436 /// Unconditionally adds the diagnostic note described in
2437 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2438 #[instrument(level = "debug", skip_all)]
2439 fn note_obligation_cause_for_async_await(
2441 err: &mut Diagnostic,
2442 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2444 outer_generator: Option<DefId>,
2445 trait_pred: ty::TraitPredicate<'tcx>,
2446 target_ty: Ty<'tcx>,
2447 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2448 obligation: &PredicateObligation<'tcx>,
2449 next_code: Option<&ObligationCauseCode<'tcx>>,
2451 let source_map = self.tcx.sess.source_map();
2453 let (await_or_yield, an_await_or_yield) =
2454 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2455 let future_or_generator = if is_async { "future" } else { "generator" };
2457 // Special case the primary error message when send or sync is the trait that was
2459 let hir = self.tcx.hir();
2460 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2461 self.tcx.get_diagnostic_name(trait_pred.def_id())
2463 let (trait_name, trait_verb) =
2464 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2467 err.set_primary_message(format!(
2468 "{} cannot be {} between threads safely",
2469 future_or_generator, trait_verb
2472 let original_span = err.span.primary_span().unwrap();
2473 let mut span = MultiSpan::from_span(original_span);
2475 let message = outer_generator
2476 .and_then(|generator_did| {
2477 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2478 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2479 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2481 .parent(generator_did)
2483 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2484 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2486 format!("future returned by `{}` is not {}", name, trait_name)
2488 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2489 format!("future created by async block is not {}", trait_name)
2491 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2492 format!("future created by async closure is not {}", trait_name)
2496 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2498 span.push_span_label(original_span, message);
2501 format!("is not {}", trait_name)
2503 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2506 let mut explain_yield =
2507 |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
2508 let mut span = MultiSpan::from_span(yield_span);
2509 let snippet = match source_map.span_to_snippet(interior_span) {
2510 // #70935: If snippet contains newlines, display "the value" instead
2511 // so that we do not emit complex diagnostics.
2512 Ok(snippet) if !snippet.contains('\n') => format!("`{}`", snippet),
2513 _ => "the value".to_string(),
2515 // note: future is not `Send` as this value is used across an await
2516 // --> $DIR/issue-70935-complex-spans.rs:13:9
2518 // LL | baz(|| async {
2519 // | ______________-
2522 // LL | | foo(tx.clone());
2524 // | | - ^^^^^^ await occurs here, with value maybe used later
2526 // | has type `closure` which is not `Send`
2527 // note: value is later dropped here
2531 span.push_span_label(
2533 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2535 span.push_span_label(
2537 format!("has type `{}` which {}", target_ty, trait_explanation),
2539 if let Some(scope_span) = scope_span {
2540 let scope_span = source_map.end_point(scope_span);
2542 let msg = format!("{} is later dropped here", snippet);
2543 span.push_span_label(scope_span, msg);
2548 "{} {} as this value is used across {}",
2549 future_or_generator, trait_explanation, an_await_or_yield
2553 match interior_or_upvar_span {
2554 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2555 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2556 if let Some(await_span) = from_awaited_ty {
2557 // The type causing this obligation is one being awaited at await_span.
2558 let mut span = MultiSpan::from_span(await_span);
2559 span.push_span_label(
2562 "await occurs here on type `{}`, which {}",
2563 target_ty, trait_explanation
2569 "future {not_trait} as it awaits another future which {not_trait}",
2570 not_trait = trait_explanation
2574 // Look at the last interior type to get a span for the `.await`.
2576 generator_interior_types = ?format_args!(
2577 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2580 explain_yield(interior_span, yield_span, scope_span);
2583 if let Some(expr_id) = expr {
2584 let expr = hir.expect_expr(expr_id);
2585 debug!("target_ty evaluated from {:?}", expr);
2587 let parent = hir.parent_id(expr_id);
2588 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2589 let parent_span = hir.span(parent);
2590 let parent_did = parent.owner.to_def_id();
2593 // fn foo(&self) -> i32 {}
2596 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2599 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2601 .expr_adjustments(expr)
2603 .any(|adj| adj.is_region_borrow())
2609 // struct Foo(*const u8);
2610 // bar(Foo(std::ptr::null())).await;
2611 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2613 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2614 let is_raw_borrow_inside_fn_like_call =
2615 match self.tcx.def_kind(parent_did) {
2616 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2619 if let Some(typeck_results) = typeck_results {
2620 if (typeck_results.is_method_call(e) && is_region_borrow)
2621 || is_raw_borrow_inside_fn_like_call
2625 "consider moving this into a `let` \
2626 binding to create a shorter lived borrow",
2634 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2635 // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
2636 let non_send = match target_ty.kind() {
2637 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(&obligation) {
2638 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2644 let (span_label, span_note) = match non_send {
2645 // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
2646 // include suggestions to make `T: Sync` so that `&T: Send`,
2647 // or to make `T: Send` so that `&mut T: Send`
2648 Some((ref_ty, is_mut)) => {
2649 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2650 let ref_kind = if is_mut { "&mut" } else { "&" };
2653 "has type `{}` which {}, because `{}` is not `{}`",
2654 target_ty, trait_explanation, ref_ty, ref_ty_trait
2657 "captured value {} because `{}` references cannot be sent unless their referent is `{}`",
2658 trait_explanation, ref_kind, ref_ty_trait
2663 format!("has type `{}` which {}", target_ty, trait_explanation),
2664 format!("captured value {}", trait_explanation),
2668 let mut span = MultiSpan::from_span(upvar_span);
2669 span.push_span_label(upvar_span, span_label);
2670 err.span_note(span, &span_note);
2674 // Add a note for the item obligation that remains - normally a note pointing to the
2675 // bound that introduced the obligation (e.g. `T: Send`).
2677 self.note_obligation_cause_code(
2679 obligation.predicate,
2680 obligation.param_env,
2683 &mut Default::default(),
2687 fn note_obligation_cause_code<T>(
2689 err: &mut Diagnostic,
2691 param_env: ty::ParamEnv<'tcx>,
2692 cause_code: &ObligationCauseCode<'tcx>,
2693 obligated_types: &mut Vec<Ty<'tcx>>,
2694 seen_requirements: &mut FxHashSet<DefId>,
2696 T: ToPredicate<'tcx>,
2699 let predicate = predicate.to_predicate(tcx);
2701 ObligationCauseCode::ExprAssignable
2702 | ObligationCauseCode::MatchExpressionArm { .. }
2703 | ObligationCauseCode::Pattern { .. }
2704 | ObligationCauseCode::IfExpression { .. }
2705 | ObligationCauseCode::IfExpressionWithNoElse
2706 | ObligationCauseCode::MainFunctionType
2707 | ObligationCauseCode::StartFunctionType
2708 | ObligationCauseCode::IntrinsicType
2709 | ObligationCauseCode::MethodReceiver
2710 | ObligationCauseCode::ReturnNoExpression
2711 | ObligationCauseCode::UnifyReceiver(..)
2712 | ObligationCauseCode::OpaqueType
2713 | ObligationCauseCode::MiscObligation
2714 | ObligationCauseCode::WellFormed(..)
2715 | ObligationCauseCode::MatchImpl(..)
2716 | ObligationCauseCode::ReturnType
2717 | ObligationCauseCode::ReturnValue(_)
2718 | ObligationCauseCode::BlockTailExpression(_)
2719 | ObligationCauseCode::AwaitableExpr(_)
2720 | ObligationCauseCode::ForLoopIterator
2721 | ObligationCauseCode::QuestionMark
2722 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2723 | ObligationCauseCode::LetElse
2724 | ObligationCauseCode::BinOp { .. }
2725 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2726 | ObligationCauseCode::RustCall => {}
2727 ObligationCauseCode::SliceOrArrayElem => {
2728 err.note("slice and array elements must have `Sized` type");
2730 ObligationCauseCode::TupleElem => {
2731 err.note("only the last element of a tuple may have a dynamically sized type");
2733 ObligationCauseCode::ProjectionWf(data) => {
2734 err.note(&format!("required so that the projection `{data}` is well-formed"));
2736 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2738 "required so that reference `{ref_ty}` does not outlive its referent"
2741 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2743 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2747 ObligationCauseCode::ItemObligation(_)
2748 | ObligationCauseCode::ExprItemObligation(..) => {
2749 // We hold the `DefId` of the item introducing the obligation, but displaying it
2750 // doesn't add user usable information. It always point at an associated item.
2752 ObligationCauseCode::BindingObligation(item_def_id, span)
2753 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2754 let item_name = tcx.def_path_str(item_def_id);
2755 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2756 let mut multispan = MultiSpan::from(span);
2757 let sm = tcx.sess.source_map();
2758 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2760 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2761 (Ok(l), Ok(r)) => l.line == r.line,
2764 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2765 multispan.push_span_label(ident.span, "required by a bound in this");
2768 let descr = format!("required by a bound in `{item_name}`");
2769 if span.is_visible(sm) {
2770 let msg = format!("required by this bound in `{short_item_name}`");
2771 multispan.push_span_label(span, msg);
2772 err.span_note(multispan, &descr);
2774 err.span_note(tcx.def_span(item_def_id), &descr);
2777 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2778 let (concrete_ty, concrete_file) =
2779 self.tcx.short_ty_string(self.resolve_vars_if_possible(concrete_ty));
2780 let (object_ty, object_file) =
2781 self.tcx.short_ty_string(self.resolve_vars_if_possible(object_ty));
2782 err.note(&with_forced_trimmed_paths!(format!(
2783 "required for the cast from `{concrete_ty}` to the object type `{object_ty}`",
2785 if let Some(file) = concrete_file {
2787 "the full name for the casted type has been written to '{}'",
2791 if let Some(file) = object_file {
2793 "the full name for the object type has been written to '{}'",
2798 ObligationCauseCode::Coercion { source: _, target } => {
2799 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2801 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2803 "the `Copy` trait is required because this value will be copied for each element of the array",
2808 "consider creating a new `const` item and initializing it with the result \
2809 of the function call to be used in the repeat position, like \
2810 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2814 if self.tcx.sess.is_nightly_build() && is_const_fn {
2816 "create an inline `const` block, see RFC #2920 \
2817 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2821 ObligationCauseCode::VariableType(hir_id) => {
2822 let parent_node = self.tcx.hir().parent_id(hir_id);
2823 match self.tcx.hir().find(parent_node) {
2824 Some(Node::Local(hir::Local { ty: Some(ty), .. })) => {
2825 err.span_suggestion_verbose(
2826 ty.span.shrink_to_lo(),
2827 "consider borrowing here",
2829 Applicability::MachineApplicable,
2831 err.note("all local variables must have a statically known size");
2833 Some(Node::Local(hir::Local {
2834 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2837 // When encountering an assignment of an unsized trait, like
2838 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2839 // order to use have a slice instead.
2840 err.span_suggestion_verbose(
2841 span.shrink_to_lo(),
2842 "consider borrowing here",
2844 Applicability::MachineApplicable,
2846 err.note("all local variables must have a statically known size");
2848 Some(Node::Param(param)) => {
2849 err.span_suggestion_verbose(
2850 param.ty_span.shrink_to_lo(),
2851 "function arguments must have a statically known size, borrowed types \
2852 always have a known size",
2854 Applicability::MachineApplicable,
2858 err.note("all local variables must have a statically known size");
2861 if !self.tcx.features().unsized_locals {
2862 err.help("unsized locals are gated as an unstable feature");
2865 ObligationCauseCode::SizedArgumentType(sp) => {
2866 if let Some(span) = sp {
2867 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder()
2868 && let ty::Clause::Trait(trait_pred) = clause
2869 && let ty::Dynamic(..) = trait_pred.self_ty().kind()
2871 let span = if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2872 && snippet.starts_with("dyn ")
2874 let pos = snippet.len() - snippet[3..].trim_start().len();
2875 span.with_hi(span.lo() + BytePos(pos as u32))
2879 err.span_suggestion_verbose(
2881 "you can use `impl Trait` as the argument type",
2882 "impl ".to_string(),
2883 Applicability::MaybeIncorrect,
2886 err.span_suggestion_verbose(
2887 span.shrink_to_lo(),
2888 "function arguments must have a statically known size, borrowed types \
2889 always have a known size",
2891 Applicability::MachineApplicable,
2894 err.note("all function arguments must have a statically known size");
2896 if tcx.sess.opts.unstable_features.is_nightly_build()
2897 && !self.tcx.features().unsized_fn_params
2899 err.help("unsized fn params are gated as an unstable feature");
2902 ObligationCauseCode::SizedReturnType => {
2903 err.note("the return type of a function must have a statically known size");
2905 ObligationCauseCode::SizedYieldType => {
2906 err.note("the yield type of a generator must have a statically known size");
2908 ObligationCauseCode::SizedBoxType => {
2909 err.note("the type of a box expression must have a statically known size");
2911 ObligationCauseCode::AssignmentLhsSized => {
2912 err.note("the left-hand-side of an assignment must have a statically known size");
2914 ObligationCauseCode::TupleInitializerSized => {
2915 err.note("tuples must have a statically known size to be initialized");
2917 ObligationCauseCode::StructInitializerSized => {
2918 err.note("structs must have a statically known size to be initialized");
2920 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2922 AdtKind::Struct => {
2925 "the last field of a packed struct may only have a \
2926 dynamically sized type if it does not need drop to be run",
2930 "only the last field of a struct may have a dynamically sized type",
2935 err.note("no field of a union may have a dynamically sized type");
2938 err.note("no field of an enum variant may have a dynamically sized type");
2941 err.help("change the field's type to have a statically known size");
2942 err.span_suggestion(
2943 span.shrink_to_lo(),
2944 "borrowed types always have a statically known size",
2946 Applicability::MachineApplicable,
2948 err.multipart_suggestion(
2949 "the `Box` type always has a statically known size and allocates its contents \
2952 (span.shrink_to_lo(), "Box<".to_string()),
2953 (span.shrink_to_hi(), ">".to_string()),
2955 Applicability::MachineApplicable,
2958 ObligationCauseCode::ConstSized => {
2959 err.note("constant expressions must have a statically known size");
2961 ObligationCauseCode::InlineAsmSized => {
2962 err.note("all inline asm arguments must have a statically known size");
2964 ObligationCauseCode::ConstPatternStructural => {
2965 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2967 ObligationCauseCode::SharedStatic => {
2968 err.note("shared static variables must have a type that implements `Sync`");
2970 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2971 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2972 let ty = parent_trait_ref.skip_binder().self_ty();
2973 if parent_trait_ref.references_error() {
2974 // NOTE(eddyb) this was `.cancel()`, but `err`
2975 // is borrowed, so we can't fully defuse it.
2976 err.downgrade_to_delayed_bug();
2980 // If the obligation for a tuple is set directly by a Generator or Closure,
2981 // then the tuple must be the one containing capture types.
2982 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2985 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2987 let parent_trait_ref =
2988 self.resolve_vars_if_possible(data.parent_trait_pred);
2989 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2990 matches!(nested_ty.kind(), ty::Generator(..))
2991 || matches!(nested_ty.kind(), ty::Closure(..))
2997 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2999 // Don't print the tuple of capture types
3001 if !is_upvar_tys_infer_tuple {
3002 let msg = with_forced_trimmed_paths!(format!(
3003 "required because it appears within the type `{ty}`",
3006 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
3007 Some(ident) => err.span_note(ident.span, &msg),
3008 None => err.note(&msg),
3010 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
3011 // Avoid printing the future from `core::future::identity_future`, it's not helpful
3012 if tcx.parent(*def_id) == identity_future {
3016 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
3017 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
3018 let is_future = tcx.ty_is_opaque_future(ty);
3022 "note_obligation_cause_code: check for async fn"
3025 && obligated_types.last().map_or(false, |ty| match ty.kind() {
3026 ty::Generator(last_def_id, ..) => {
3027 tcx.generator_is_async(*last_def_id)
3034 err.span_note(self.tcx.def_span(def_id), &msg)
3036 ty::GeneratorWitness(bound_tys) => {
3037 use std::fmt::Write;
3039 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
3040 // Maybe we should just remove this note altogether?
3041 // FIXME: only print types which don't meet the trait requirement
3043 "required because it captures the following types: ".to_owned();
3044 for ty in bound_tys.skip_binder() {
3045 with_forced_trimmed_paths!(write!(msg, "`{}`, ", ty).unwrap());
3047 err.note(msg.trim_end_matches(", "))
3049 ty::GeneratorWitnessMIR(def_id, substs) => {
3050 use std::fmt::Write;
3052 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
3053 // Maybe we should just remove this note altogether?
3054 // FIXME: only print types which don't meet the trait requirement
3056 "required because it captures the following types: ".to_owned();
3057 for bty in tcx.generator_hidden_types(*def_id) {
3058 let ty = bty.subst(tcx, substs);
3059 write!(msg, "`{}`, ", ty).unwrap();
3061 err.note(msg.trim_end_matches(", "))
3063 ty::Generator(def_id, _, _) => {
3064 let sp = self.tcx.def_span(def_id);
3066 // Special-case this to say "async block" instead of `[static generator]`.
3067 let kind = tcx.generator_kind(def_id).unwrap().descr();
3070 with_forced_trimmed_paths!(&format!(
3071 "required because it's used within this {kind}",
3075 ty::Closure(def_id, _) => err.span_note(
3076 self.tcx.def_span(def_id),
3077 "required because it's used within this closure",
3079 _ => err.note(&msg),
3084 obligated_types.push(ty);
3086 let parent_predicate = parent_trait_ref;
3087 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
3088 // #74711: avoid a stack overflow
3089 ensure_sufficient_stack(|| {
3090 self.note_obligation_cause_code(
3100 ensure_sufficient_stack(|| {
3101 self.note_obligation_cause_code(
3105 cause_code.peel_derives(),
3112 ObligationCauseCode::ImplDerivedObligation(ref data) => {
3113 let mut parent_trait_pred =
3114 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
3115 parent_trait_pred.remap_constness_diag(param_env);
3116 let parent_def_id = parent_trait_pred.def_id();
3117 let (self_ty, file) =
3118 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
3120 "required for `{self_ty}` to implement `{}`",
3121 parent_trait_pred.print_modifiers_and_trait_path()
3123 let mut is_auto_trait = false;
3124 match self.tcx.hir().get_if_local(data.impl_def_id) {
3125 Some(Node::Item(hir::Item {
3126 kind: hir::ItemKind::Trait(is_auto, ..),
3130 // FIXME: we should do something else so that it works even on crate foreign
3132 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
3133 err.span_note(ident.span, &msg);
3135 Some(Node::Item(hir::Item {
3136 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
3139 let mut spans = Vec::with_capacity(2);
3140 if let Some(trait_ref) = of_trait {
3141 spans.push(trait_ref.path.span);
3143 spans.push(self_ty.span);
3144 let mut spans: MultiSpan = spans.into();
3146 self_ty.span.ctxt().outer_expn_data().kind,
3147 ExpnKind::Macro(MacroKind::Derive, _)
3149 of_trait.as_ref().map(|t| t.path.span.ctxt().outer_expn_data().kind),
3150 Some(ExpnKind::Macro(MacroKind::Derive, _))
3152 spans.push_span_label(
3154 "unsatisfied trait bound introduced in this `derive` macro",
3156 } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
3157 spans.push_span_label(
3159 "unsatisfied trait bound introduced here",
3162 err.span_note(spans, &msg);
3169 if let Some(file) = file {
3171 "the full type name has been written to '{}'",
3175 let mut parent_predicate = parent_trait_pred;
3176 let mut data = &data.derived;
3178 seen_requirements.insert(parent_def_id);
3180 // We don't want to point at the ADT saying "required because it appears within
3181 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
3182 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
3185 let child_trait_ref =
3186 self.resolve_vars_if_possible(derived.parent_trait_pred);
3187 let child_def_id = child_trait_ref.def_id();
3188 if seen_requirements.insert(child_def_id) {
3192 parent_predicate = child_trait_ref.to_predicate(tcx);
3193 parent_trait_pred = child_trait_ref;
3196 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
3197 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
3198 let child_trait_pred =
3199 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
3200 let child_def_id = child_trait_pred.def_id();
3201 if seen_requirements.insert(child_def_id) {
3205 data = &child.derived;
3206 parent_predicate = child_trait_pred.to_predicate(tcx);
3207 parent_trait_pred = child_trait_pred;
3211 "{} redundant requirement{} hidden",
3215 let (self_ty, file) =
3216 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
3218 "required for `{self_ty}` to implement `{}`",
3219 parent_trait_pred.print_modifiers_and_trait_path()
3221 if let Some(file) = file {
3223 "the full type name has been written to '{}'",
3228 // #74711: avoid a stack overflow
3229 ensure_sufficient_stack(|| {
3230 self.note_obligation_cause_code(
3240 ObligationCauseCode::DerivedObligation(ref data) => {
3241 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3242 let parent_predicate = parent_trait_ref;
3243 // #74711: avoid a stack overflow
3244 ensure_sufficient_stack(|| {
3245 self.note_obligation_cause_code(
3255 ObligationCauseCode::FunctionArgumentObligation {
3261 self.note_function_argument_obligation(
3269 ensure_sufficient_stack(|| {
3270 self.note_obligation_cause_code(
3280 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
3281 let item_name = self.tcx.item_name(trait_item_def_id);
3283 "the requirement `{predicate}` appears on the `impl`'s {kind} \
3284 `{item_name}` but not on the corresponding trait's {kind}",
3288 .opt_item_ident(trait_item_def_id)
3290 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
3291 let mut assoc_span: MultiSpan = sp.into();
3292 assoc_span.push_span_label(
3294 format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
3296 if let Some(ident) = self
3298 .opt_associated_item(trait_item_def_id)
3299 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
3301 assoc_span.push_span_label(ident.span, "in this trait");
3303 err.span_note(assoc_span, &msg);
3305 ObligationCauseCode::TrivialBound => {
3306 err.help("see issue #48214");
3307 if tcx.sess.opts.unstable_features.is_nightly_build() {
3308 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
3311 ObligationCauseCode::OpaqueReturnType(expr_info) => {
3312 if let Some((expr_ty, expr_span)) = expr_info {
3313 let expr_ty = with_forced_trimmed_paths!(self.ty_to_string(expr_ty));
3316 with_forced_trimmed_paths!(format!(
3317 "return type was inferred to be `{expr_ty}` here",
3326 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
3328 fn suggest_await_before_try(
3330 err: &mut Diagnostic,
3331 obligation: &PredicateObligation<'tcx>,
3332 trait_pred: ty::PolyTraitPredicate<'tcx>,
3335 if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) {
3336 let body = self.tcx.hir().body(body_id);
3337 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
3338 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
3340 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3341 let impls_future = self.type_implements_trait(
3343 [self.tcx.erase_late_bound_regions(self_ty)],
3344 obligation.param_env,
3346 if !impls_future.must_apply_modulo_regions() {
3350 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3351 // `<T as Future>::Output`
3352 let projection_ty = trait_pred.map_bound(|trait_pred| {
3353 self.tcx.mk_projection(
3355 // Future::Output has no substs
3356 [trait_pred.self_ty()],
3359 let InferOk { value: projection_ty, .. } =
3360 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3363 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3365 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3366 obligation.param_env,
3367 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3369 debug!(try_trait_obligation = ?try_obligation);
3370 if self.predicate_may_hold(&try_obligation)
3371 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3372 && snippet.ends_with('?')
3374 err.span_suggestion_verbose(
3375 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3376 "consider `await`ing on the `Future`",
3378 Applicability::MaybeIncorrect,
3385 fn suggest_floating_point_literal(
3387 obligation: &PredicateObligation<'tcx>,
3388 err: &mut Diagnostic,
3389 trait_ref: &ty::PolyTraitRef<'tcx>,
3391 let rhs_span = match obligation.cause.code() {
3392 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3395 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3396 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3398 err.span_suggestion_verbose(
3399 rhs_span.shrink_to_hi(),
3400 "consider using a floating-point literal by writing it with `.0`",
3402 Applicability::MaybeIncorrect,
3409 obligation: &PredicateObligation<'tcx>,
3410 err: &mut Diagnostic,
3411 trait_pred: ty::PolyTraitPredicate<'tcx>,
3413 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3416 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3417 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3421 let is_derivable_trait = match diagnostic_name {
3422 sym::Default => !adt.is_enum(),
3423 sym::PartialEq | sym::PartialOrd => {
3424 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3425 trait_pred.skip_binder().self_ty() == rhs_ty
3427 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3430 is_derivable_trait &&
3431 // Ensure all fields impl the trait.
3432 adt.all_fields().all(|field| {
3433 let field_ty = field.ty(self.tcx, substs);
3434 let trait_substs = match diagnostic_name {
3435 sym::PartialEq | sym::PartialOrd => {
3440 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3441 trait_ref: self.tcx.mk_trait_ref(
3442 trait_pred.def_id(),
3443 [field_ty].into_iter().chain(trait_substs),
3447 let field_obl = Obligation::new(
3449 obligation.cause.clone(),
3450 obligation.param_env,
3453 self.predicate_must_hold_modulo_regions(&field_obl)
3457 err.span_suggestion_verbose(
3458 self.tcx.def_span(adt.did()).shrink_to_lo(),
3460 "consider annotating `{}` with `#[derive({})]`",
3461 trait_pred.skip_binder().self_ty(),
3464 format!("#[derive({})]\n", diagnostic_name),
3465 Applicability::MaybeIncorrect,
3470 fn suggest_dereferencing_index(
3472 obligation: &PredicateObligation<'tcx>,
3473 err: &mut Diagnostic,
3474 trait_pred: ty::PolyTraitPredicate<'tcx>,
3476 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3477 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3478 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3479 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3480 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3482 err.span_suggestion_verbose(
3483 obligation.cause.span.shrink_to_lo(),
3484 "dereference this index",
3486 Applicability::MachineApplicable,
3490 fn note_function_argument_obligation(
3493 err: &mut Diagnostic,
3494 parent_code: &ObligationCauseCode<'tcx>,
3495 param_env: ty::ParamEnv<'tcx>,
3496 failed_pred: ty::Predicate<'tcx>,
3500 let hir = tcx.hir();
3501 if let Some(Node::Expr(expr)) = hir.find(arg_hir_id)
3502 && let Some(typeck_results) = &self.typeck_results
3504 if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
3505 let expr = expr.peel_blocks();
3506 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
3507 let span = expr.span;
3508 if Some(span) != err.span.primary_span() {
3511 if ty.references_error() {
3514 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3515 format!("this tail expression is of type `{ty}`")
3521 // FIXME: visit the ty to see if there's any closure involved, and if there is,
3522 // check whether its evaluated return type is the same as the one corresponding
3523 // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3524 // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3525 let mut type_diffs = vec![];
3527 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
3528 && let Some(node_substs) = typeck_results.node_substs_opt(call_hir_id)
3529 && let where_clauses = self.tcx.predicates_of(def_id).instantiate(self.tcx, node_substs)
3530 && let Some(where_pred) = where_clauses.predicates.get(*idx)
3532 if let Some(where_pred) = where_pred.to_opt_poly_trait_pred()
3533 && let Some(failed_pred) = failed_pred.to_opt_poly_trait_pred()
3535 let mut c = CollectAllMismatches {
3540 if let Ok(_) = c.relate(where_pred, failed_pred) {
3541 type_diffs = c.errors;
3543 } else if let Some(where_pred) = where_pred.to_opt_poly_projection_pred()
3544 && let Some(failed_pred) = failed_pred.to_opt_poly_projection_pred()
3545 && let Some(found) = failed_pred.skip_binder().term.ty()
3548 Sorts(ty::error::ExpectedFound {
3549 expected: self.tcx.mk_ty(ty::Alias(ty::Projection, where_pred.skip_binder().projection_ty)),
3555 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3556 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3557 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3558 && let parent_hir_id = self.tcx.hir().parent_id(binding.hir_id)
3559 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3560 && let Some(binding_expr) = local.init
3562 // If the expression we're calling on is a binding, we want to point at the
3563 // `let` when talking about the type. Otherwise we'll point at every part
3564 // of the method chain with the type.
3565 self.point_at_chain(binding_expr, &typeck_results, type_diffs, param_env, err);
3567 self.point_at_chain(expr, &typeck_results, type_diffs, param_env, err);
3570 let call_node = hir.find(call_hir_id);
3571 if let Some(Node::Expr(hir::Expr {
3572 kind: hir::ExprKind::MethodCall(path, rcvr, ..), ..
3575 if Some(rcvr.span) == err.span.primary_span() {
3576 err.replace_span_with(path.ident.span, true);
3579 if let Some(Node::Expr(hir::Expr {
3581 hir::ExprKind::Call(hir::Expr { span, .. }, _)
3582 | hir::ExprKind::MethodCall(hir::PathSegment { ident: Ident { span, .. }, .. }, ..),
3584 })) = hir.find(call_hir_id)
3586 if Some(*span) != err.span.primary_span() {
3587 err.span_label(*span, "required by a bound introduced by this call");
3594 expr: &hir::Expr<'_>,
3595 typeck_results: &TypeckResults<'tcx>,
3596 type_diffs: Vec<TypeError<'tcx>>,
3597 param_env: ty::ParamEnv<'tcx>,
3598 err: &mut Diagnostic,
3600 let mut primary_spans = vec![];
3601 let mut span_labels = vec![];
3605 let mut print_root_expr = true;
3606 let mut assocs = vec![];
3607 let mut expr = expr;
3608 let mut prev_ty = self.resolve_vars_if_possible(
3609 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3611 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) = expr.kind {
3612 // Point at every method call in the chain with the resulting type.
3613 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3614 // ^^^^^^ ^^^^^^^^^^^
3616 let assocs_in_this_method =
3617 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
3618 assocs.push(assocs_in_this_method);
3619 prev_ty = self.resolve_vars_if_possible(
3620 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3623 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3624 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3625 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3626 && let Some(parent) = self.tcx.hir().find_parent(binding.hir_id)
3628 // We've reached the root of the method call chain...
3629 if let hir::Node::Local(local) = parent
3630 && let Some(binding_expr) = local.init
3632 // ...and it is a binding. Get the binding creation and continue the chain.
3633 expr = binding_expr;
3635 if let hir::Node::Param(param) = parent {
3636 // ...and it is a an fn argument.
3637 let prev_ty = self.resolve_vars_if_possible(
3638 typeck_results.node_type_opt(param.hir_id).unwrap_or(tcx.ty_error()),
3640 let assocs_in_this_method = self.probe_assoc_types_at_expr(&type_diffs, param.ty_span, prev_ty, param.hir_id, param_env);
3641 if assocs_in_this_method.iter().any(|a| a.is_some()) {
3642 assocs.push(assocs_in_this_method);
3643 print_root_expr = false;
3649 // We want the type before deref coercions, otherwise we talk about `&[_]`
3650 // instead of `Vec<_>`.
3651 if let Some(ty) = typeck_results.expr_ty_opt(expr) && print_root_expr {
3652 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3653 // Point at the root expression
3654 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3656 span_labels.push((expr.span, format!("this expression has type `{ty}`")));
3658 // Only show this if it is not a "trivial" expression (not a method
3659 // chain) and there are associated types to talk about.
3660 let mut assocs = assocs.into_iter().peekable();
3661 while let Some(assocs_in_method) = assocs.next() {
3662 let Some(prev_assoc_in_method) = assocs.peek() else {
3663 for entry in assocs_in_method {
3664 let Some((span, (assoc, ty))) = entry else { continue; };
3665 if primary_spans.is_empty() || type_diffs.iter().any(|diff| {
3666 let Sorts(expected_found) = diff else { return false; };
3667 self.can_eq(param_env, expected_found.found, ty).is_ok()
3669 // FIXME: this doesn't quite work for `Iterator::collect`
3670 // because we have `Vec<i32>` and `()`, but we'd want `i32`
3671 // to point at the `.into_iter()` call, but as long as we
3672 // still point at the other method calls that might have
3673 // introduced the issue, this is fine for now.
3674 primary_spans.push(span);
3678 with_forced_trimmed_paths!(format!(
3679 "`{}` is `{ty}` here",
3680 self.tcx.def_path_str(assoc),
3686 for (entry, prev_entry) in
3687 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
3689 match (entry, prev_entry) {
3690 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
3691 let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
3693 let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
3694 if self.can_eq(param_env, ty, *prev_ty).is_err() {
3695 if type_diffs.iter().any(|diff| {
3696 let Sorts(expected_found) = diff else { return false; };
3697 self.can_eq(param_env, expected_found.found, ty).is_ok()
3699 primary_spans.push(span);
3702 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
3704 span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
3707 (Some((span, (assoc, ty))), None) => {
3710 with_forced_trimmed_paths!(format!(
3711 "`{}` is `{}` here",
3712 self.tcx.def_path_str(assoc),
3713 self.ty_to_string(ty),
3717 (None, Some(_)) | (None, None) => {}
3721 if !primary_spans.is_empty() {
3722 let mut multi_span: MultiSpan = primary_spans.into();
3723 for (span, label) in span_labels {
3724 multi_span.push_span_label(span, label);
3728 "the method call chain might not have had the expected associated types",
3733 fn probe_assoc_types_at_expr(
3735 type_diffs: &[TypeError<'tcx>],
3738 body_id: hir::HirId,
3739 param_env: ty::ParamEnv<'tcx>,
3740 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
3741 let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
3742 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
3743 for diff in type_diffs {
3744 let Sorts(expected_found) = diff else { continue; };
3745 let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; };
3747 let origin = TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span };
3748 let trait_def_id = proj.trait_def_id(self.tcx);
3749 // Make `Self` be equivalent to the type of the call chain
3750 // expression we're looking at now, so that we can tell what
3751 // for example `Iterator::Item` is at this point in the chain.
3752 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
3754 ty::GenericParamDefKind::Type { .. } => {
3755 if param.index == 0 {
3756 return prev_ty.into();
3759 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Const { .. } => {}
3761 self.var_for_def(span, param)
3763 // This will hold the resolved type of the associated type, if the
3764 // current expression implements the trait that associated type is
3765 // in. For example, this would be what `Iterator::Item` is here.
3766 let ty_var = self.infcx.next_ty_var(origin);
3767 // This corresponds to `<ExprTy as Iterator>::Item = _`.
3768 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::Projection(
3769 ty::ProjectionPredicate {
3770 projection_ty: self.tcx.mk_alias_ty(proj.def_id, substs),
3771 term: ty_var.into(),
3774 let body_def_id = self.tcx.hir().enclosing_body_owner(body_id);
3775 // Add `<ExprTy as Iterator>::Item = _` obligation.
3776 ocx.register_obligation(Obligation::misc(
3783 if ocx.select_where_possible().is_empty() {
3784 // `ty_var` now holds the type that `Item` is for `ExprTy`.
3785 let ty_var = self.resolve_vars_if_possible(ty_var);
3786 assocs_in_this_method.push(Some((span, (proj.def_id, ty_var))));
3788 // `<ExprTy as Iterator>` didn't select, so likely we've
3789 // reached the end of the iterator chain, like the originating
3791 // Keep the space consistent for later zipping.
3792 assocs_in_this_method.push(None);
3795 assocs_in_this_method
3799 /// Add a hint to add a missing borrow or remove an unnecessary one.
3800 fn hint_missing_borrow<'tcx>(
3801 infcx: &InferCtxt<'tcx>,
3802 param_env: ty::ParamEnv<'tcx>,
3806 found_node: Node<'_>,
3807 err: &mut Diagnostic,
3809 let found_args = match found.kind() {
3810 ty::FnPtr(f) => infcx.replace_bound_vars_with_placeholders(*f).inputs().iter(),
3812 span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
3815 let expected_args = match expected.kind() {
3816 ty::FnPtr(f) => infcx.replace_bound_vars_with_placeholders(*f).inputs().iter(),
3818 span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
3822 // This could be a variant constructor, for example.
3823 let Some(fn_decl) = found_node.fn_decl() else { return; };
3825 let args = fn_decl.inputs.iter().map(|ty| ty);
3827 fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
3828 let mut refs = vec![];
3830 while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
3838 let mut to_borrow = Vec::new();
3839 let mut remove_borrow = Vec::new();
3841 for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
3842 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
3843 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
3845 if infcx.can_eq(param_env, found_ty, expected_ty).is_ok() {
3846 // FIXME: This could handle more exotic cases like mutability mismatches too!
3847 if found_refs.len() < expected_refs.len()
3848 && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
3851 arg.span.shrink_to_lo(),
3852 expected_refs[..expected_refs.len() - found_refs.len()]
3854 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3855 .collect::<Vec<_>>()
3858 } else if found_refs.len() > expected_refs.len() {
3859 let mut span = arg.span.shrink_to_lo();
3860 let mut left = found_refs.len() - expected_refs.len();
3862 while let hir::TyKind::Ref(_, mut_ty) = &ty.kind && left > 0 {
3863 span = span.with_hi(mut_ty.ty.span.lo());
3867 let sugg = if left == 0 {
3868 (span, String::new())
3870 (arg.span, expected_arg.to_string())
3872 remove_borrow.push(sugg);
3877 if !to_borrow.is_empty() {
3878 err.multipart_suggestion_verbose(
3879 "consider borrowing the argument",
3881 Applicability::MaybeIncorrect,
3885 if !remove_borrow.is_empty() {
3886 err.multipart_suggestion_verbose(
3887 "do not borrow the argument",
3889 Applicability::MaybeIncorrect,
3894 /// Collect all the returned expressions within the input expression.
3895 /// Used to point at the return spans when we want to suggest some change to them.
3897 pub struct ReturnsVisitor<'v> {
3898 pub returns: Vec<&'v hir::Expr<'v>>,
3899 in_block_tail: bool,
3902 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3903 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3904 // Visit every expression to detect `return` paths, either through the function's tail
3905 // expression or `return` statements. We walk all nodes to find `return` statements, but
3906 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3907 // they're in the return path of the function body.
3909 hir::ExprKind::Ret(Some(ex)) => {
3910 self.returns.push(ex);
3912 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3913 self.in_block_tail = false;
3914 for stmt in block.stmts {
3915 hir::intravisit::walk_stmt(self, stmt);
3917 self.in_block_tail = true;
3918 if let Some(expr) = block.expr {
3919 self.visit_expr(expr);
3922 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3923 self.visit_expr(then);
3924 if let Some(el) = else_opt {
3925 self.visit_expr(el);
3928 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3930 self.visit_expr(arm.body);
3933 // We need to walk to find `return`s in the entire body.
3934 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3935 _ => self.returns.push(ex),
3939 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3940 assert!(!self.in_block_tail);
3941 if body.generator_kind().is_none() {
3942 if let hir::ExprKind::Block(block, None) = body.value.kind {
3943 if block.expr.is_some() {
3944 self.in_block_tail = true;
3948 hir::intravisit::walk_body(self, body);
3952 /// Collect all the awaited expressions within the input expression.
3954 struct AwaitsVisitor {
3955 awaits: Vec<hir::HirId>,
3958 impl<'v> Visitor<'v> for AwaitsVisitor {
3959 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3960 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3961 self.awaits.push(id)
3963 hir::intravisit::walk_expr(self, ex)
3967 pub trait NextTypeParamName {
3968 fn next_type_param_name(&self, name: Option<&str>) -> String;
3971 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3972 fn next_type_param_name(&self, name: Option<&str>) -> String {
3973 // This is the list of possible parameter names that we might suggest.
3974 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3975 let name = name.as_deref();
3976 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3977 let used_names = self
3979 .filter_map(|p| match p.name {
3980 hir::ParamName::Plain(ident) => Some(ident.name),
3983 .collect::<Vec<_>>();
3987 .find(|n| !used_names.contains(&Symbol::intern(n)))
3988 .unwrap_or(&"ParamName")
3993 fn suggest_trait_object_return_type_alternatives(
3994 err: &mut Diagnostic,
3997 is_object_safe: bool,
3999 err.span_suggestion(
4002 "use `impl {}` as the return type if all return paths have the same type but you \
4003 want to expose only the trait in the signature",
4006 format!("impl {}", trait_obj),
4007 Applicability::MaybeIncorrect,
4010 err.multipart_suggestion(
4012 "use a boxed trait object if all return paths implement trait `{}`",
4016 (ret_ty.shrink_to_lo(), "Box<".to_string()),
4017 (ret_ty.shrink_to_hi(), ">".to_string()),
4019 Applicability::MaybeIncorrect,
4024 /// Collect the spans that we see the generic param `param_did`
4025 struct ReplaceImplTraitVisitor<'a> {
4026 ty_spans: &'a mut Vec<Span>,
4030 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
4031 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
4032 if let hir::TyKind::Path(hir::QPath::Resolved(
4034 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
4037 if self.param_did == *segment_did {
4038 // `fn foo(t: impl Trait)`
4039 // ^^^^^^^^^^ get this to suggest `T` instead
4041 // There might be more than one `impl Trait`.
4042 self.ty_spans.push(t.span);
4047 hir::intravisit::walk_ty(self, t);
4051 // Replace `param` with `replace_ty`
4052 struct ReplaceImplTraitFolder<'tcx> {
4054 param: &'tcx ty::GenericParamDef,
4055 replace_ty: Ty<'tcx>,
4058 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
4059 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
4060 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
4061 if self.param.index == *index {
4062 return self.replace_ty;
4065 t.super_fold_with(self)
4068 fn tcx(&self) -> TyCtxt<'tcx> {