1 // ignore-tidy-filelength
4 DefIdOrName, FindExprBySpan, Obligation, ObligationCause, ObligationCauseCode,
8 use crate::infer::InferCtxt;
9 use crate::traits::{NormalizeExt, ObligationCtxt};
12 use hir::{Expr, HirId};
13 use rustc_data_structures::fx::FxHashSet;
14 use rustc_data_structures::stack::ensure_sufficient_stack;
16 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
17 ErrorGuaranteed, MultiSpan, Style,
20 use rustc_hir::def::DefKind;
21 use rustc_hir::def_id::DefId;
22 use rustc_hir::intravisit::Visitor;
23 use rustc_hir::lang_items::LangItem;
24 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
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::symbol::{sym, Ident, Symbol};
38 use rustc_span::{BytePos, DesugaringKind, ExpnKind, MacroKind, Span, DUMMY_SP};
39 use rustc_target::spec::abi;
42 use super::method_chain::CollectAllMismatches;
43 use super::InferCtxtPrivExt;
44 use crate::infer::InferCtxtExt as _;
45 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
46 use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
49 pub enum GeneratorInteriorOrUpvar {
50 // span of interior type
51 Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
56 // This type provides a uniform interface to retrieve data on generators, whether it originated from
57 // the local crate being compiled or from a foreign crate.
59 pub enum GeneratorData<'tcx, 'a> {
60 Local(&'a TypeckResults<'tcx>),
61 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
64 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
65 // Try to get information about variables captured by the generator that matches a type we are
66 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
68 fn try_get_upvar_span<F>(
70 infer_context: &InferCtxt<'tcx>,
73 ) -> Option<GeneratorInteriorOrUpvar>
75 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
78 GeneratorData::Local(typeck_results) => {
79 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
80 upvars.iter().find_map(|(upvar_id, upvar)| {
81 let upvar_ty = typeck_results.node_type(*upvar_id);
82 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
83 if ty_matches(ty::Binder::dummy(upvar_ty)) {
84 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
91 GeneratorData::Foreign(_) => None,
95 // Try to get the span of a type being awaited on that matches the type we are looking with the
96 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
98 fn get_from_await_ty<F>(
100 visitor: AwaitsVisitor,
105 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
108 GeneratorData::Local(typeck_results) => visitor
111 .map(|id| hir.expect_expr(id))
113 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
115 .map(|expr| expr.span),
116 GeneratorData::Foreign(generator_diagnostic_data) => visitor
119 .map(|id| hir.expect_expr(id))
121 ty_matches(ty::Binder::dummy(
122 generator_diagnostic_data
124 .get(&await_expr.hir_id.local_id)
125 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
127 .map_or_else::<Ty<'tcx>, _, _>(
129 generator_diagnostic_data
131 .get(&await_expr.hir_id.local_id)
135 "node_type: no type for node `{}`",
136 ty::tls::with(|tcx| tcx
138 .node_to_string(await_expr.hir_id))
146 .map(|expr| expr.span),
150 /// Get the type, expression, span and optional scope span of all types
151 /// that are live across the yield of this generator
152 fn get_generator_interior_types(
154 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
156 GeneratorData::Local(typeck_result) => {
157 typeck_result.generator_interior_types.as_deref()
159 GeneratorData::Foreign(generator_diagnostic_data) => {
160 generator_diagnostic_data.generator_interior_types.as_deref()
165 // Used to get the source of the data, note we don't have as much information for generators
166 // originated from foreign crates
167 fn is_foreign(&self) -> bool {
169 GeneratorData::Local(_) => false,
170 GeneratorData::Foreign(_) => true,
175 // This trait is public to expose the diagnostics methods to clippy.
176 pub trait TypeErrCtxtExt<'tcx> {
177 fn suggest_restricting_param_bound(
179 err: &mut Diagnostic,
180 trait_pred: ty::PolyTraitPredicate<'tcx>,
181 associated_item: Option<(&'static str, Ty<'tcx>)>,
185 fn suggest_dereferences(
187 obligation: &PredicateObligation<'tcx>,
188 err: &mut Diagnostic,
189 trait_pred: ty::PolyTraitPredicate<'tcx>,
192 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
196 obligation: &PredicateObligation<'tcx>,
197 err: &mut Diagnostic,
198 trait_pred: ty::PolyTraitPredicate<'tcx>,
201 fn check_for_binding_assigned_block_without_tail_expression(
203 obligation: &PredicateObligation<'tcx>,
204 err: &mut Diagnostic,
205 trait_pred: ty::PolyTraitPredicate<'tcx>,
208 fn suggest_add_clone_to_arg(
210 obligation: &PredicateObligation<'tcx>,
211 err: &mut Diagnostic,
212 trait_pred: ty::PolyTraitPredicate<'tcx>,
215 fn extract_callable_info(
218 param_env: ty::ParamEnv<'tcx>,
220 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)>;
222 fn suggest_add_reference_to_arg(
224 obligation: &PredicateObligation<'tcx>,
225 err: &mut Diagnostic,
226 trait_pred: ty::PolyTraitPredicate<'tcx>,
227 has_custom_message: bool,
230 fn suggest_borrowing_for_object_cast(
232 err: &mut Diagnostic,
233 obligation: &PredicateObligation<'tcx>,
238 fn suggest_remove_reference(
240 obligation: &PredicateObligation<'tcx>,
241 err: &mut Diagnostic,
242 trait_pred: ty::PolyTraitPredicate<'tcx>,
245 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
247 fn suggest_change_mut(
249 obligation: &PredicateObligation<'tcx>,
250 err: &mut Diagnostic,
251 trait_pred: ty::PolyTraitPredicate<'tcx>,
254 fn suggest_semicolon_removal(
256 obligation: &PredicateObligation<'tcx>,
257 err: &mut Diagnostic,
259 trait_pred: ty::PolyTraitPredicate<'tcx>,
262 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
264 fn suggest_impl_trait(
266 err: &mut Diagnostic,
268 obligation: &PredicateObligation<'tcx>,
269 trait_pred: ty::PolyTraitPredicate<'tcx>,
272 fn point_at_returns_when_relevant(
274 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
275 obligation: &PredicateObligation<'tcx>,
278 fn report_closure_arg_mismatch(
281 found_span: Option<Span>,
282 found: ty::PolyTraitRef<'tcx>,
283 expected: ty::PolyTraitRef<'tcx>,
284 cause: &ObligationCauseCode<'tcx>,
285 found_node: Option<Node<'_>>,
286 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
288 fn note_conflicting_closure_bounds(
290 cause: &ObligationCauseCode<'tcx>,
291 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
294 fn suggest_fully_qualified_path(
296 err: &mut Diagnostic,
302 fn maybe_note_obligation_cause_for_async_await(
304 err: &mut Diagnostic,
305 obligation: &PredicateObligation<'tcx>,
308 fn note_obligation_cause_for_async_await(
310 err: &mut Diagnostic,
311 interior_or_upvar_span: GeneratorInteriorOrUpvar,
313 outer_generator: Option<DefId>,
314 trait_pred: ty::TraitPredicate<'tcx>,
316 typeck_results: Option<&ty::TypeckResults<'tcx>>,
317 obligation: &PredicateObligation<'tcx>,
318 next_code: Option<&ObligationCauseCode<'tcx>>,
321 fn note_obligation_cause_code<T>(
323 err: &mut Diagnostic,
325 param_env: ty::ParamEnv<'tcx>,
326 cause_code: &ObligationCauseCode<'tcx>,
327 obligated_types: &mut Vec<Ty<'tcx>>,
328 seen_requirements: &mut FxHashSet<DefId>,
330 T: ToPredicate<'tcx>;
332 /// Suggest to await before try: future? => future.await?
333 fn suggest_await_before_try(
335 err: &mut Diagnostic,
336 obligation: &PredicateObligation<'tcx>,
337 trait_pred: ty::PolyTraitPredicate<'tcx>,
341 fn suggest_floating_point_literal(
343 obligation: &PredicateObligation<'tcx>,
344 err: &mut Diagnostic,
345 trait_ref: &ty::PolyTraitRef<'tcx>,
350 obligation: &PredicateObligation<'tcx>,
351 err: &mut Diagnostic,
352 trait_pred: ty::PolyTraitPredicate<'tcx>,
355 fn suggest_dereferencing_index(
357 obligation: &PredicateObligation<'tcx>,
358 err: &mut Diagnostic,
359 trait_pred: ty::PolyTraitPredicate<'tcx>,
361 fn note_function_argument_obligation(
364 err: &mut Diagnostic,
365 parent_code: &ObligationCauseCode<'tcx>,
366 param_env: ty::ParamEnv<'tcx>,
367 predicate: ty::Predicate<'tcx>,
372 expr: &hir::Expr<'_>,
373 typeck_results: &TypeckResults<'tcx>,
374 type_diffs: Vec<TypeError<'tcx>>,
375 param_env: ty::ParamEnv<'tcx>,
376 err: &mut Diagnostic,
378 fn probe_assoc_types_at_expr(
380 type_diffs: &[TypeError<'tcx>],
384 param_env: ty::ParamEnv<'tcx>,
385 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>>;
388 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
390 generics.tail_span_for_predicate_suggestion(),
391 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
395 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
396 /// it can also be an `impl Trait` param that needs to be decomposed to a type
397 /// param for cleaner code.
398 fn suggest_restriction<'tcx>(
401 hir_generics: &hir::Generics<'tcx>,
403 err: &mut Diagnostic,
404 fn_sig: Option<&hir::FnSig<'_>>,
405 projection: Option<&ty::AliasTy<'_>>,
406 trait_pred: ty::PolyTraitPredicate<'tcx>,
407 // When we are dealing with a trait, `super_traits` will be `Some`:
408 // Given `trait T: A + B + C {}`
409 // - ^^^^^^^^^ GenericBounds
412 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
414 if hir_generics.where_clause_span.from_expansion()
415 || hir_generics.where_clause_span.desugaring_kind().is_some()
419 let Some(item_id) = hir_id.as_owner() else { return; };
420 let generics = tcx.generics_of(item_id);
421 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
422 if let Some((param, bound_str, fn_sig)) =
423 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
424 // Shenanigans to get the `Trait` from the `impl Trait`.
425 ty::Param(param) => {
426 let param_def = generics.type_param(param, tcx);
427 if param_def.kind.is_synthetic() {
429 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
430 return Some((param_def, bound_str, sig));
437 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
438 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
441 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
444 if !trait_pred.is_suggestable(tcx, false) {
447 // We know we have an `impl Trait` that doesn't satisfy a required projection.
449 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
450 // types. There should be at least one, but there might be *more* than one. In that
451 // case we could just ignore it and try to identify which one needs the restriction,
452 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
454 let mut ty_spans = vec![];
455 for input in fn_sig.decl.inputs {
456 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
459 // The type param `T: Trait` we will suggest to introduce.
460 let type_param = format!("{}: {}", type_param_name, bound_str);
463 if let Some(span) = hir_generics.span_for_param_suggestion() {
464 (span, format!(", {}", type_param))
466 (hir_generics.span, format!("<{}>", type_param))
468 // `fn foo(t: impl Trait)`
469 // ^ suggest `where <T as Trait>::A: Bound`
470 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
472 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
474 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
475 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
476 // `fn foo(t: impl Trait<A: Bound>)` instead.
477 err.multipart_suggestion(
478 "introduce a type parameter with a trait bound instead of using `impl Trait`",
480 Applicability::MaybeIncorrect,
483 if !trait_pred.is_suggestable(tcx, false) {
486 // Trivial case: `T` needs an extra bound: `T: Bound`.
487 let (sp, suggestion) = match (
491 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
494 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
495 (None, Some((ident, []))) => (
496 ident.span.shrink_to_hi(),
497 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
499 (_, Some((_, [.., bounds]))) => (
500 bounds.span().shrink_to_hi(),
501 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
503 (Some(_), Some((_, []))) => (
504 hir_generics.span.shrink_to_hi(),
505 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
509 err.span_suggestion_verbose(
511 &format!("consider further restricting {}", msg),
513 Applicability::MachineApplicable,
518 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
519 fn suggest_restricting_param_bound(
521 mut err: &mut Diagnostic,
522 trait_pred: ty::PolyTraitPredicate<'tcx>,
523 associated_ty: Option<(&'static str, Ty<'tcx>)>,
526 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
528 let self_ty = trait_pred.skip_binder().self_ty();
529 let (param_ty, projection) = match self_ty.kind() {
530 ty::Param(_) => (true, None),
531 ty::Alias(ty::Projection, projection) => (false, Some(projection)),
535 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
536 // don't suggest `T: Sized + ?Sized`.
537 let mut hir_id = body_id;
538 while let Some(node) = self.tcx.hir().find(hir_id) {
540 hir::Node::Item(hir::Item {
542 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
544 }) if self_ty == self.tcx.types.self_param => {
546 // Restricting `Self` for a single method.
556 Some((ident, bounds)),
561 hir::Node::TraitItem(hir::TraitItem {
563 kind: hir::TraitItemKind::Fn(..),
565 }) if self_ty == self.tcx.types.self_param => {
567 // Restricting `Self` for a single method.
569 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
575 hir::Node::TraitItem(hir::TraitItem {
577 kind: hir::TraitItemKind::Fn(fn_sig, ..),
580 | hir::Node::ImplItem(hir::ImplItem {
582 kind: hir::ImplItemKind::Fn(fn_sig, ..),
585 | hir::Node::Item(hir::Item {
586 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
587 }) if projection.is_some() => {
588 // Missing restriction on associated type of type parameter (unmet projection).
593 "the associated type",
602 hir::Node::Item(hir::Item {
604 hir::ItemKind::Trait(_, _, generics, ..)
605 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
607 }) if projection.is_some() => {
608 // Missing restriction on associated type of type parameter (unmet projection).
613 "the associated type",
623 hir::Node::Item(hir::Item {
625 hir::ItemKind::Struct(_, generics)
626 | hir::ItemKind::Enum(_, generics)
627 | hir::ItemKind::Union(_, generics)
628 | hir::ItemKind::Trait(_, _, generics, ..)
629 | hir::ItemKind::Impl(hir::Impl { generics, .. })
630 | hir::ItemKind::Fn(_, generics, _)
631 | hir::ItemKind::TyAlias(_, generics)
632 | hir::ItemKind::TraitAlias(generics, _)
633 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
636 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
637 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
640 // We skip the 0'th subst (self) because we do not want
641 // to consider the predicate as not suggestible if the
642 // self type is an arg position `impl Trait` -- instead,
643 // we handle that by adding ` + Bound` below.
644 // FIXME(compiler-errors): It would be nice to do the same
645 // this that we do in `suggest_restriction` and pull the
646 // `impl Trait` into a new generic if it shows up somewhere
647 // else in the predicate.
648 if !trait_pred.skip_binder().trait_ref.substs[1..]
650 .all(|g| g.is_suggestable(self.tcx, false))
654 // Missing generic type parameter bound.
655 let param_name = self_ty.to_string();
656 let mut constraint = with_no_trimmed_paths!(
657 trait_pred.print_modifiers_and_trait_path().to_string()
660 if let Some((name, term)) = associated_ty {
661 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
662 // That should be extracted into a helper function.
663 if constraint.ends_with('>') {
664 constraint = format!(
666 &constraint[..constraint.len() - 1],
671 constraint.push_str(&format!("<{} = {}>", name, term));
675 if suggest_constraining_type_param(
681 Some(trait_pred.def_id()),
687 hir::Node::Item(hir::Item {
689 hir::ItemKind::Struct(_, generics)
690 | hir::ItemKind::Enum(_, generics)
691 | hir::ItemKind::Union(_, generics)
692 | hir::ItemKind::Trait(_, _, generics, ..)
693 | hir::ItemKind::Impl(hir::Impl { generics, .. })
694 | hir::ItemKind::Fn(_, generics, _)
695 | hir::ItemKind::TyAlias(_, generics)
696 | hir::ItemKind::TraitAlias(generics, _)
697 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
700 // Missing generic type parameter bound.
701 if suggest_arbitrary_trait_bound(
711 hir::Node::Crate(..) => return,
716 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
720 /// When after several dereferencing, the reference satisfies the trait
721 /// binding. This function provides dereference suggestion for this
722 /// specific situation.
723 fn suggest_dereferences(
725 obligation: &PredicateObligation<'tcx>,
726 err: &mut Diagnostic,
727 trait_pred: ty::PolyTraitPredicate<'tcx>,
729 // It only make sense when suggesting dereferences for arguments
730 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = obligation.cause.code()
731 else { return false; };
732 let Some(typeck_results) = &self.typeck_results
733 else { return false; };
734 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
735 else { return false; };
736 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
737 else { return false; };
739 let span = obligation.cause.span;
740 let mut real_trait_pred = trait_pred;
741 let mut code = obligation.cause.code();
742 while let Some((parent_code, parent_trait_pred)) = code.parent() {
744 if let Some(parent_trait_pred) = parent_trait_pred {
745 real_trait_pred = parent_trait_pred;
748 let real_ty = real_trait_pred.self_ty();
749 // We `erase_late_bound_regions` here because `make_subregion` does not handle
750 // `ReLateBound`, and we don't particularly care about the regions.
752 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
758 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
759 let autoderef = (self.autoderef_steps)(base_ty);
761 autoderef.into_iter().enumerate().find_map(|(steps, (ty, obligations))| {
763 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
765 // Remapping bound vars here
766 let real_trait_pred_and_ty =
767 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
768 let obligation = self.mk_trait_obligation_with_new_self_ty(
769 obligation.param_env,
770 real_trait_pred_and_ty,
774 .chain([&obligation])
775 .all(|obligation| self.predicate_may_hold(obligation))
784 // Don't care about `&mut` because `DerefMut` is used less
785 // often and user will not expect autoderef happens.
786 if let Some(hir::Node::Expr(hir::Expr {
788 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
790 })) = self.tcx.hir().find(*arg_hir_id)
792 let derefs = "*".repeat(steps);
793 err.span_suggestion_verbose(
794 expr.span.shrink_to_lo(),
795 "consider dereferencing here",
797 Applicability::MachineApplicable,
802 } else if real_trait_pred != trait_pred {
803 // This branch addresses #87437.
805 // Remapping bound vars here
806 let real_trait_pred_and_base_ty =
807 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
808 let obligation = self.mk_trait_obligation_with_new_self_ty(
809 obligation.param_env,
810 real_trait_pred_and_base_ty,
812 if self.predicate_may_hold(&obligation) {
813 let call_node = self.tcx.hir().get(*call_hir_id);
814 let msg = "consider dereferencing here";
815 let is_receiver = matches!(
817 Node::Expr(hir::Expr {
818 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
821 if receiver_expr.hir_id == *arg_hir_id
824 err.multipart_suggestion_verbose(
827 (span.shrink_to_lo(), "(*".to_string()),
828 (span.shrink_to_hi(), ")".to_string()),
830 Applicability::MachineApplicable,
833 err.span_suggestion_verbose(
837 Applicability::MachineApplicable,
848 /// Given a closure's `DefId`, return the given name of the closure.
850 /// This doesn't account for reassignments, but it's only used for suggestions.
851 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
852 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
853 // Get the local name of this closure. This can be inaccurate because
854 // of the possibility of reassignment, but this should be good enough.
856 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
866 let hir = self.tcx.hir();
867 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
868 match hir.find_parent(hir_id) {
869 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
870 get_name(err, &local.pat.kind)
872 // Different to previous arm because one is `&hir::Local` and the other
873 // is `P<hir::Local>`.
874 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
879 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
880 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
881 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
884 obligation: &PredicateObligation<'tcx>,
885 err: &mut Diagnostic,
886 trait_pred: ty::PolyTraitPredicate<'tcx>,
888 // It doesn't make sense to make this suggestion outside of typeck...
889 // (also autoderef will ICE...)
890 if self.typeck_results.is_none() {
894 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
895 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
897 // Don't suggest calling to turn an unsized type into a sized type
901 let self_ty = self.replace_bound_vars_with_fresh_vars(
903 LateBoundRegionConversionTime::FnCall,
904 trait_pred.self_ty(),
907 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(
908 obligation.cause.body_id,
909 obligation.param_env,
911 ) else { return false; };
913 // Remapping bound vars here
914 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
917 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
918 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
922 // Get the name of the callable and the arguments to be used in the suggestion.
923 let hir = self.tcx.hir();
925 let msg = match def_id_or_name {
926 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
927 DefKind::Ctor(CtorOf::Struct, _) => {
928 "use parentheses to construct this tuple struct".to_string()
930 DefKind::Ctor(CtorOf::Variant, _) => {
931 "use parentheses to construct this tuple variant".to_string()
933 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
935 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
941 if ty.is_suggestable(self.tcx, false) {
942 format!("/* {ty} */")
944 "/* value */".to_string()
950 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
951 && obligation.cause.span.can_be_used_for_suggestions()
953 // When the obligation error has been ensured to have been caused by
954 // an argument, the `obligation.cause.span` points at the expression
955 // of the argument, so we can provide a suggestion. Otherwise, we give
956 // a more general note.
957 err.span_suggestion_verbose(
958 obligation.cause.span.shrink_to_hi(),
961 Applicability::HasPlaceholders,
963 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
964 let name = match hir.get_if_local(def_id) {
965 Some(hir::Node::Expr(hir::Expr {
966 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
969 err.span_label(*fn_decl_span, "consider calling this closure");
970 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
975 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
976 err.span_label(ident.span, "consider calling this function");
979 Some(hir::Node::Ctor(..)) => {
980 let name = self.tcx.def_path_str(def_id);
982 self.tcx.def_span(def_id),
983 format!("consider calling the constructor for `{}`", name),
989 err.help(&format!("{msg}: `{name}({args})`"));
994 fn check_for_binding_assigned_block_without_tail_expression(
996 obligation: &PredicateObligation<'tcx>,
997 err: &mut Diagnostic,
998 trait_pred: ty::PolyTraitPredicate<'tcx>,
1000 let mut span = obligation.cause.span;
1001 while span.from_expansion() {
1002 // Remove all the desugaring and macro contexts.
1005 let mut expr_finder = FindExprBySpan::new(span);
1006 let Some(hir::Node::Expr(body)) = self.tcx.hir().find(obligation.cause.body_id) else { return; };
1007 expr_finder.visit_expr(&body);
1008 let Some(expr) = expr_finder.result else { return; };
1009 let Some(typeck) = &self.typeck_results else { return; };
1010 let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { return; };
1014 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; };
1015 let hir::def::Res::Local(hir_id) = path.res else { return; };
1016 let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else {
1019 let Some(hir::Node::Local(hir::Local {
1023 })) = self.tcx.hir().find_parent(pat.hir_id) else { return; };
1024 let hir::ExprKind::Block(block, None) = init.kind else { return; };
1025 if block.expr.is_some() {
1028 let [.., stmt] = block.stmts else {
1029 err.span_label(block.span, "this empty block is missing a tail expression");
1032 let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; };
1033 let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1034 err.span_label(block.span, "this block is missing a tail expression");
1037 let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
1038 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1040 let new_obligation =
1041 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1042 if self.predicate_must_hold_modulo_regions(&new_obligation) {
1043 err.span_suggestion_short(
1044 stmt.span.with_lo(tail_expr.span.hi()),
1045 "remove this semicolon",
1047 Applicability::MachineApplicable,
1050 err.span_label(block.span, "this block is missing a tail expression");
1054 fn suggest_add_clone_to_arg(
1056 obligation: &PredicateObligation<'tcx>,
1057 err: &mut Diagnostic,
1058 trait_pred: ty::PolyTraitPredicate<'tcx>,
1060 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
1061 let ty = self.tcx.erase_late_bound_regions(self_ty);
1062 let owner = self.tcx.hir().get_parent_item(obligation.cause.body_id);
1063 let Some(generics) = self.tcx.hir().get_generics(owner.def_id) else { return false };
1064 let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
1065 let ty::Param(param) = inner_ty.kind() else { return false };
1066 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() else { return false };
1067 let arg_node = self.tcx.hir().get(*arg_hir_id);
1068 let Node::Expr(Expr { kind: hir::ExprKind::Path(_), ..}) = arg_node else { return false };
1070 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None);
1071 let has_clone = |ty| {
1072 self.type_implements_trait(clone_trait, [ty], obligation.param_env)
1073 .must_apply_modulo_regions()
1076 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1077 obligation.param_env,
1078 trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1081 if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1082 if !has_clone(param.to_ty(self.tcx)) {
1083 suggest_constraining_type_param(
1087 param.name.as_str(),
1092 err.span_suggestion_verbose(
1093 obligation.cause.span.shrink_to_hi(),
1094 "consider using clone here",
1095 ".clone()".to_string(),
1096 Applicability::MaybeIncorrect,
1103 /// Extracts information about a callable type for diagnostics. This is a
1104 /// heuristic -- it doesn't necessarily mean that a type is always callable,
1105 /// because the callable type must also be well-formed to be called.
1106 fn extract_callable_info(
1109 param_env: ty::ParamEnv<'tcx>,
1111 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1112 // Autoderef is useful here because sometimes we box callables, etc.
1113 let Some((def_id_or_name, output, inputs)) = (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| {
1114 match *found.kind() {
1115 ty::FnPtr(fn_sig) =>
1116 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
1117 ty::FnDef(def_id, _) => {
1118 let fn_sig = found.fn_sig(self.tcx);
1119 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1121 ty::Closure(def_id, substs) => {
1122 let fn_sig = substs.as_closure().sig();
1123 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
1125 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
1126 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
1127 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
1128 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
1129 // args tuple will always be substs[1]
1130 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
1133 DefIdOrName::DefId(def_id),
1134 pred.kind().rebind(proj.term.ty().unwrap()),
1135 pred.kind().rebind(args.as_slice()),
1142 ty::Dynamic(data, _, ty::Dyn) => {
1143 data.iter().find_map(|pred| {
1144 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1145 && Some(proj.def_id) == self.tcx.lang_items().fn_once_output()
1146 // for existential projection, substs are shifted over by 1
1147 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
1150 DefIdOrName::Name("trait object"),
1151 pred.rebind(proj.term.ty().unwrap()),
1152 pred.rebind(args.as_slice()),
1159 ty::Param(param) => {
1160 let generics = self.tcx.generics_of(hir_id.owner.to_def_id());
1161 let name = if generics.count() > param.index as usize
1162 && let def = generics.param_at(param.index as usize, self.tcx)
1163 && matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1164 && def.name == param.name
1166 DefIdOrName::DefId(def.def_id)
1168 DefIdOrName::Name("type parameter")
1170 param_env.caller_bounds().iter().find_map(|pred| {
1171 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
1172 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
1173 && proj.projection_ty.self_ty() == found
1174 // args tuple will always be substs[1]
1175 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
1179 pred.kind().rebind(proj.term.ty().unwrap()),
1180 pred.kind().rebind(args.as_slice()),
1189 }) else { return None; };
1191 let output = self.replace_bound_vars_with_fresh_vars(
1193 LateBoundRegionConversionTime::FnCall,
1200 self.replace_bound_vars_with_fresh_vars(
1202 LateBoundRegionConversionTime::FnCall,
1208 // We don't want to register any extra obligations, which should be
1209 // implied by wf, but also because that would possibly result in
1210 // erroneous errors later on.
1211 let InferOk { value: output, obligations: _ } =
1212 self.at(&ObligationCause::dummy(), param_env).normalize(output);
1214 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1217 fn suggest_add_reference_to_arg(
1219 obligation: &PredicateObligation<'tcx>,
1220 err: &mut Diagnostic,
1221 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1222 has_custom_message: bool,
1224 let span = obligation.cause.span;
1226 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
1227 obligation.cause.code()
1230 } else if let ObligationCauseCode::ItemObligation(_)
1231 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1233 obligation.cause.code()
1234 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1235 span.ctxt().outer_expn_data().kind
1237 obligation.cause.code()
1242 // List of traits for which it would be nonsensical to suggest borrowing.
1243 // For instance, immutable references are always Copy, so suggesting to
1244 // borrow would always succeed, but it's probably not what the user wanted.
1245 let mut never_suggest_borrow: Vec<_> =
1246 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1248 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1251 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1252 never_suggest_borrow.push(def_id);
1255 let param_env = obligation.param_env;
1257 // Try to apply the original trait binding obligation by borrowing.
1258 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1259 blacklist: &[DefId]|
1261 if blacklist.contains(&old_pred.def_id()) {
1264 // We map bounds to `&T` and `&mut T`
1265 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1268 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1271 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1274 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1278 let mk_result = |trait_pred_and_new_ty| {
1280 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1281 self.predicate_must_hold_modulo_regions(&obligation)
1283 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1284 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1286 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1287 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1288 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1291 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1292 mutability.is_mut(),
1298 if imm_ref_self_ty_satisfies_pred
1299 || mut_ref_self_ty_satisfies_pred
1300 || ref_inner_ty_satisfies_pred
1302 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1303 // We don't want a borrowing suggestion on the fields in structs,
1306 // the_foos: Vec<Foo>
1310 span.ctxt().outer_expn_data().kind,
1311 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1315 if snippet.starts_with('&') {
1316 // This is already a literal borrow and the obligation is failing
1317 // somewhere else in the obligation chain. Do not suggest non-sense.
1320 // We have a very specific type of error, where just borrowing this argument
1321 // might solve the problem. In cases like this, the important part is the
1322 // original type obligation, not the last one that failed, which is arbitrary.
1323 // Because of this, we modify the error to refer to the original obligation and
1324 // return early in the caller.
1326 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1327 if has_custom_message {
1331 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1336 "the trait `{}` is not implemented for `{}`",
1337 old_pred.print_modifiers_and_trait_path(),
1338 old_pred.self_ty().skip_binder(),
1342 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1343 err.span_suggestions(
1344 span.shrink_to_lo(),
1345 "consider borrowing here",
1346 ["&".to_string(), "&mut ".to_string()],
1347 Applicability::MaybeIncorrect,
1350 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1351 err.span_suggestion_verbose(
1352 span.shrink_to_lo(),
1354 "consider{} borrowing here",
1355 if is_mut { " mutably" } else { "" }
1357 format!("&{}", if is_mut { "mut " } else { "" }),
1358 Applicability::MaybeIncorrect,
1367 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1368 try_borrowing(cause.derived.parent_trait_pred, &[])
1369 } else if let ObligationCauseCode::BindingObligation(_, _)
1370 | ObligationCauseCode::ItemObligation(_)
1371 | ObligationCauseCode::ExprItemObligation(..)
1372 | ObligationCauseCode::ExprBindingObligation(..) = code
1374 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1380 // Suggest borrowing the type
1381 fn suggest_borrowing_for_object_cast(
1383 err: &mut Diagnostic,
1384 obligation: &PredicateObligation<'tcx>,
1386 object_ty: Ty<'tcx>,
1388 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1389 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1391 for predicate in predicates.iter() {
1392 if !self.predicate_must_hold_modulo_regions(
1393 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1399 err.span_suggestion(
1400 obligation.cause.span.shrink_to_lo(),
1402 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1405 Applicability::MaybeIncorrect,
1409 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1410 /// suggest removing these references until we reach a type that implements the trait.
1411 fn suggest_remove_reference(
1413 obligation: &PredicateObligation<'tcx>,
1414 err: &mut Diagnostic,
1415 trait_pred: ty::PolyTraitPredicate<'tcx>,
1417 let mut span = obligation.cause.span;
1418 let mut trait_pred = trait_pred;
1419 let mut code = obligation.cause.code();
1420 while let Some((c, Some(parent_trait_pred))) = code.parent() {
1421 // We want the root obligation, in order to detect properly handle
1422 // `for _ in &mut &mut vec![] {}`.
1424 trait_pred = parent_trait_pred;
1426 while span.desugaring_kind().is_some() {
1427 // Remove all the hir desugaring contexts while maintaining the macro contexts.
1430 let mut expr_finder = super::FindExprBySpan::new(span);
1431 let Some(hir::Node::Expr(body)) = self.tcx.hir().find(obligation.cause.body_id) else {
1434 expr_finder.visit_expr(&body);
1435 let mut maybe_suggest = |suggested_ty, count, suggestions| {
1436 // Remapping bound vars here
1437 let trait_pred_and_suggested_ty =
1438 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1440 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1441 obligation.param_env,
1442 trait_pred_and_suggested_ty,
1445 if self.predicate_may_hold(&new_obligation) {
1446 let msg = if count == 1 {
1447 "consider removing the leading `&`-reference".to_string()
1449 format!("consider removing {count} leading `&`-references")
1452 err.multipart_suggestion_verbose(
1455 Applicability::MachineApplicable,
1463 // Maybe suggest removal of borrows from types in type parameters, like in
1464 // `src/test/ui/not-panic/not-panic-safe.rs`.
1466 let mut suggestions = vec![];
1467 // Skipping binder here, remapping below
1468 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1469 if let Some(mut hir_ty) = expr_finder.ty_result {
1470 while let hir::TyKind::Ref(_, mut_ty) = &hir_ty.kind {
1472 let span = hir_ty.span.until(mut_ty.ty.span);
1473 suggestions.push((span, String::new()));
1475 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1478 suggested_ty = *inner_ty;
1482 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1488 // Maybe suggest removal of borrows from expressions, like in `for i in &&&foo {}`.
1489 let Some(mut expr) = expr_finder.result else { return false; };
1491 let mut suggestions = vec![];
1492 // Skipping binder here, remapping below
1493 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1495 while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
1497 let span = if expr.span.eq_ctxt(borrowed.span) {
1498 expr.span.until(borrowed.span)
1500 expr.span.with_hi(expr.span.lo() + BytePos(1))
1502 suggestions.push((span, String::new()));
1504 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1507 suggested_ty = *inner_ty;
1511 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1515 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1516 && let hir::def::Res::Local(hir_id) = path.res
1517 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(hir_id)
1518 && let Some(hir::Node::Local(local)) = self.tcx.hir().find_parent(binding.hir_id)
1519 && let None = local.ty
1520 && let Some(binding_expr) = local.init
1522 expr = binding_expr;
1530 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1531 let span = obligation.cause.span;
1533 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1534 let hir = self.tcx.hir();
1535 if let Some(hir::Node::Expr(expr)) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1536 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1537 // and if not maybe suggest doing something else? If we kept the expression around we
1538 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1539 // it is from the local crate.
1540 err.span_suggestion(
1542 "remove the `.await`",
1544 Applicability::MachineApplicable,
1546 // FIXME: account for associated `async fn`s.
1547 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1548 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1549 obligation.predicate.kind().skip_binder()
1551 err.span_label(*span, &format!("this call returns `{}`", pred.self_ty()));
1553 if let Some(typeck_results) = &self.typeck_results
1554 && let ty = typeck_results.expr_ty_adjusted(base)
1555 && let ty::FnDef(def_id, _substs) = ty.kind()
1556 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1557 hir.get_if_local(*def_id)
1560 "alternatively, consider making `fn {}` asynchronous",
1563 if vis_span.is_empty() {
1564 err.span_suggestion_verbose(
1565 span.shrink_to_lo(),
1568 Applicability::MaybeIncorrect,
1571 err.span_suggestion_verbose(
1572 vis_span.shrink_to_hi(),
1575 Applicability::MaybeIncorrect,
1584 /// Check if the trait bound is implemented for a different mutability and note it in the
1586 fn suggest_change_mut(
1588 obligation: &PredicateObligation<'tcx>,
1589 err: &mut Diagnostic,
1590 trait_pred: ty::PolyTraitPredicate<'tcx>,
1592 let points_at_arg = matches!(
1593 obligation.cause.code(),
1594 ObligationCauseCode::FunctionArgumentObligation { .. },
1597 let span = obligation.cause.span;
1598 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1600 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1601 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1602 // Do not suggest removal of borrow from type arguments.
1605 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1606 if trait_pred.has_non_region_infer() {
1607 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1608 // unresolved bindings.
1612 // Skipping binder here, remapping below
1613 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1615 let suggested_ty = match mutability {
1616 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1617 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1620 // Remapping bound vars here
1621 let trait_pred_and_suggested_ty =
1622 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1624 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1625 obligation.param_env,
1626 trait_pred_and_suggested_ty,
1628 let suggested_ty_would_satisfy_obligation = self
1629 .evaluate_obligation_no_overflow(&new_obligation)
1630 .must_apply_modulo_regions();
1631 if suggested_ty_would_satisfy_obligation {
1636 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1637 if points_at_arg && mutability.is_not() && refs_number > 0 {
1638 // If we have a call like foo(&mut buf), then don't suggest foo(&mut mut buf)
1640 .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
1645 err.span_suggestion_verbose(
1647 "consider changing this borrow's mutability",
1649 Applicability::MachineApplicable,
1653 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1654 trait_pred.print_modifiers_and_trait_path(),
1656 trait_pred.skip_binder().self_ty(),
1664 fn suggest_semicolon_removal(
1666 obligation: &PredicateObligation<'tcx>,
1667 err: &mut Diagnostic,
1669 trait_pred: ty::PolyTraitPredicate<'tcx>,
1671 let hir = self.tcx.hir();
1672 let parent_node = hir.parent_id(obligation.cause.body_id);
1673 let node = hir.find(parent_node);
1674 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1675 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1676 && sig.decl.output.span().overlaps(span)
1677 && blk.expr.is_none()
1678 && trait_pred.self_ty().skip_binder().is_unit()
1679 && let Some(stmt) = blk.stmts.last()
1680 && let hir::StmtKind::Semi(expr) = stmt.kind
1681 // Only suggest this if the expression behind the semicolon implements the predicate
1682 && let Some(typeck_results) = &self.typeck_results
1683 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1684 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1685 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1691 "this expression has type `{}`, which implements `{}`",
1693 trait_pred.print_modifiers_and_trait_path()
1696 err.span_suggestion(
1697 self.tcx.sess.source_map().end_point(stmt.span),
1698 "remove this semicolon",
1700 Applicability::MachineApplicable
1707 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1708 let hir = self.tcx.hir();
1709 let parent_node = hir.parent_id(obligation.cause.body_id);
1710 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1714 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1717 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1718 /// applicable and signal that the error has been expanded appropriately and needs to be
1720 fn suggest_impl_trait(
1722 err: &mut Diagnostic,
1724 obligation: &PredicateObligation<'tcx>,
1725 trait_pred: ty::PolyTraitPredicate<'tcx>,
1727 match obligation.cause.code().peel_derives() {
1728 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1729 ObligationCauseCode::SizedReturnType => {}
1733 let hir = self.tcx.hir();
1734 let fn_hir_id = hir.parent_id(obligation.cause.body_id);
1735 let node = hir.find(fn_hir_id);
1736 let Some(hir::Node::Item(hir::Item {
1737 kind: hir::ItemKind::Fn(sig, _, body_id),
1743 let body = hir.body(*body_id);
1744 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1745 let ty = trait_pred.skip_binder().self_ty();
1746 let is_object_safe = match ty.kind() {
1747 ty::Dynamic(predicates, _, ty::Dyn) => {
1748 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1751 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1753 // We only want to suggest `impl Trait` to `dyn Trait`s.
1754 // For example, `fn foo() -> str` needs to be filtered out.
1758 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1762 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1763 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1764 // Recursively look for `TraitObject` types and if there's only one, use that span to
1765 // suggest `impl Trait`.
1767 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1768 // otherwise suggest using `Box<dyn Trait>` or an enum.
1769 let mut visitor = ReturnsVisitor::default();
1770 visitor.visit_body(&body);
1772 let typeck_results = self.typeck_results.as_ref().unwrap();
1773 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1775 let ret_types = visitor
1778 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1779 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1780 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1782 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1784 let ty = self.resolve_vars_if_possible(ty);
1786 !matches!(ty.kind(), ty::Error(_))
1787 && last_ty.map_or(true, |last_ty| {
1788 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1789 // *after* in the dependency graph.
1790 match (ty.kind(), last_ty.kind()) {
1791 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1792 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1793 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1795 Infer(InferTy::FreshFloatTy(_)),
1796 Infer(InferTy::FreshFloatTy(_)),
1801 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1804 let mut spans_and_needs_box = vec![];
1806 match liberated_sig.output().kind() {
1807 ty::Dynamic(predicates, _, ty::Dyn) => {
1808 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1809 let param_env = ty::ParamEnv::empty();
1811 if !only_never_return {
1812 for (expr_span, return_ty) in ret_types {
1813 let self_ty_satisfies_dyn_predicates = |self_ty| {
1814 predicates.iter().all(|predicate| {
1815 let pred = predicate.with_self_ty(self.tcx, self_ty);
1816 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1817 self.predicate_may_hold(&obl)
1821 if let ty::Adt(def, substs) = return_ty.kind()
1823 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1825 spans_and_needs_box.push((expr_span, false));
1826 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1827 spans_and_needs_box.push((expr_span, true));
1837 let sm = self.tcx.sess.source_map();
1838 if !ret_ty.span.overlaps(span) {
1841 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1842 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1848 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1849 let name = liberated_sig.output().to_string();
1851 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1852 if !name.starts_with("dyn ") {
1858 err.code(error_code!(E0746));
1859 err.set_primary_message("return type cannot have an unboxed trait object");
1860 err.children.clear();
1861 let impl_trait_msg = "for information on `impl Trait`, see \
1862 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1863 #returning-types-that-implement-traits>";
1864 let trait_obj_msg = "for information on trait objects, see \
1865 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1866 #using-trait-objects-that-allow-for-values-of-different-types>";
1868 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1869 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1870 if only_never_return {
1871 // No return paths, probably using `panic!()` or similar.
1872 // Suggest `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1873 suggest_trait_object_return_type_alternatives(
1879 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1880 // Suggest `-> impl Trait`.
1881 err.span_suggestion(
1884 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1885 which implements `{1}`",
1888 format!("impl {}", trait_obj),
1889 Applicability::MachineApplicable,
1891 err.note(impl_trait_msg);
1894 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1895 err.multipart_suggestion(
1896 "return a boxed trait object instead",
1898 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1899 (span.shrink_to_hi(), ">".to_string()),
1901 Applicability::MaybeIncorrect,
1903 for (span, needs_box) in spans_and_needs_box {
1905 err.multipart_suggestion(
1906 "... and box this value",
1908 (span.shrink_to_lo(), "Box::new(".to_string()),
1909 (span.shrink_to_hi(), ")".to_string()),
1911 Applicability::MaybeIncorrect,
1916 // This is currently not possible to trigger because E0038 takes precedence, but
1917 // leave it in for completeness in case anything changes in an earlier stage.
1919 "if trait `{}` were object-safe, you could return a trait object",
1923 err.note(trait_obj_msg);
1925 "if all the returned values were of the same type you could use `impl {}` as the \
1929 err.note(impl_trait_msg);
1930 err.note("you can create a new `enum` with a variant for each returned type");
1935 fn point_at_returns_when_relevant(
1937 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1938 obligation: &PredicateObligation<'tcx>,
1940 match obligation.cause.code().peel_derives() {
1941 ObligationCauseCode::SizedReturnType => {}
1945 let hir = self.tcx.hir();
1946 let parent_node = hir.parent_id(obligation.cause.body_id);
1947 let node = hir.find(parent_node);
1948 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1951 let body = hir.body(*body_id);
1952 // Point at all the `return`s in the function as they have failed trait bounds.
1953 let mut visitor = ReturnsVisitor::default();
1954 visitor.visit_body(&body);
1955 let typeck_results = self.typeck_results.as_ref().unwrap();
1956 for expr in &visitor.returns {
1957 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1958 let ty = self.resolve_vars_if_possible(returned_ty);
1959 if ty.references_error() {
1960 // don't print out the [type error] here
1965 &format!("this returned value is of type `{}`", ty),
1973 fn report_closure_arg_mismatch(
1976 found_span: Option<Span>,
1977 found: ty::PolyTraitRef<'tcx>,
1978 expected: ty::PolyTraitRef<'tcx>,
1979 cause: &ObligationCauseCode<'tcx>,
1980 found_node: Option<Node<'_>>,
1981 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1982 pub(crate) fn build_fn_sig_ty<'tcx>(
1983 infcx: &InferCtxt<'tcx>,
1984 trait_ref: ty::PolyTraitRef<'tcx>,
1986 let inputs = trait_ref.skip_binder().substs.type_at(1);
1987 let sig = match inputs.kind() {
1988 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1989 infcx.tcx.mk_fn_sig(
1991 infcx.next_ty_var(TypeVariableOrigin {
1993 kind: TypeVariableOriginKind::MiscVariable,
1996 hir::Unsafety::Normal,
2000 _ => infcx.tcx.mk_fn_sig(
2001 std::iter::once(inputs),
2002 infcx.next_ty_var(TypeVariableOrigin {
2004 kind: TypeVariableOriginKind::MiscVariable,
2007 hir::Unsafety::Normal,
2012 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
2015 let argument_kind = match expected.skip_binder().self_ty().kind() {
2016 ty::Closure(..) => "closure",
2017 ty::Generator(..) => "generator",
2020 let mut err = struct_span_err!(
2024 "type mismatch in {argument_kind} arguments",
2027 err.span_label(span, "expected due to this");
2029 let found_span = found_span.unwrap_or(span);
2030 err.span_label(found_span, "found signature defined here");
2032 let expected = build_fn_sig_ty(self, expected);
2033 let found = build_fn_sig_ty(self, found);
2035 let (expected_str, found_str) = self.cmp(expected, found);
2037 let signature_kind = format!("{argument_kind} signature");
2038 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
2040 self.note_conflicting_closure_bounds(cause, &mut err);
2042 if let Some(found_node) = found_node {
2043 hint_missing_borrow(span, found, expected, found_node, &mut err);
2049 // Add a note if there are two `Fn`-family bounds that have conflicting argument
2050 // requirements, which will always cause a closure to have a type error.
2051 fn note_conflicting_closure_bounds(
2053 cause: &ObligationCauseCode<'tcx>,
2054 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2056 // First, look for an `ExprBindingObligation`, which means we can get
2057 // the unsubstituted predicate list of the called function. And check
2058 // that the predicate that we failed to satisfy is a `Fn`-like trait.
2059 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
2060 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
2061 && let Some(pred) = predicates.predicates.get(*idx)
2062 && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
2063 && self.tcx.is_fn_trait(trait_pred.def_id())
2066 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
2067 let expected_substs = self
2069 .anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.substs));
2071 // Find another predicate whose self-type is equal to the expected self type,
2072 // but whose substs don't match.
2073 let other_pred = predicates.into_iter()
2075 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
2076 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
2077 if self.tcx.is_fn_trait(trait_pred.def_id())
2079 // Make sure that the self type matches
2080 // (i.e. constraining this closure)
2082 == self.tcx.anonymize_bound_vars(
2083 pred.kind().rebind(trait_pred.self_ty()),
2085 // But the substs don't match (i.e. incompatible args)
2087 != self.tcx.anonymize_bound_vars(
2088 pred.kind().rebind(trait_pred.trait_ref.substs),
2095 // If we found one, then it's very likely the cause of the error.
2096 if let Some((_, (_, other_pred_span))) = other_pred {
2099 "closure inferred to have a different signature due to this bound",
2105 fn suggest_fully_qualified_path(
2107 err: &mut Diagnostic,
2112 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
2113 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
2115 "{}s cannot be accessed directly on a `trait`, they can only be \
2116 accessed through a specific `impl`",
2117 assoc_item.kind.as_def_kind().descr(item_def_id)
2119 err.span_suggestion(
2121 "use the fully qualified path to an implementation",
2122 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
2123 Applicability::HasPlaceholders,
2129 /// Adds an async-await specific note to the diagnostic when the future does not implement
2130 /// an auto trait because of a captured type.
2133 /// note: future does not implement `Qux` as this value is used across an await
2134 /// --> $DIR/issue-64130-3-other.rs:17:5
2136 /// LL | let x = Foo;
2137 /// | - has type `Foo`
2138 /// LL | baz().await;
2139 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2141 /// | - `x` is later dropped here
2144 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
2145 /// is "replaced" with a different message and a more specific error.
2148 /// error: future cannot be sent between threads safely
2149 /// --> $DIR/issue-64130-2-send.rs:21:5
2151 /// LL | fn is_send<T: Send>(t: T) { }
2152 /// | ---- required by this bound in `is_send`
2154 /// LL | is_send(bar());
2155 /// | ^^^^^^^ future returned by `bar` is not send
2157 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
2158 /// implemented for `Foo`
2159 /// note: future is not send as this value is used across an await
2160 /// --> $DIR/issue-64130-2-send.rs:15:5
2162 /// LL | let x = Foo;
2163 /// | - has type `Foo`
2164 /// LL | baz().await;
2165 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
2167 /// | - `x` is later dropped here
2170 /// Returns `true` if an async-await specific note was added to the diagnostic.
2171 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
2172 fn maybe_note_obligation_cause_for_async_await(
2174 err: &mut Diagnostic,
2175 obligation: &PredicateObligation<'tcx>,
2177 let hir = self.tcx.hir();
2179 // Attempt to detect an async-await error by looking at the obligation causes, looking
2180 // for a generator to be present.
2182 // When a future does not implement a trait because of a captured type in one of the
2183 // generators somewhere in the call stack, then the result is a chain of obligations.
2185 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
2186 // future is passed as an argument to a function C which requires a `Send` type, then the
2187 // chain looks something like this:
2189 // - `BuiltinDerivedObligation` with a generator witness (B)
2190 // - `BuiltinDerivedObligation` with a generator (B)
2191 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
2192 // - `BuiltinDerivedObligation` with a generator witness (A)
2193 // - `BuiltinDerivedObligation` with a generator (A)
2194 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
2195 // - `BindingObligation` with `impl_send (Send requirement)
2197 // The first obligation in the chain is the most useful and has the generator that captured
2198 // the type. The last generator (`outer_generator` below) has information about where the
2199 // bound was introduced. At least one generator should be present for this diagnostic to be
2201 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
2202 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
2205 let mut generator = None;
2206 let mut outer_generator = None;
2207 let mut next_code = Some(obligation.cause.code());
2209 let mut seen_upvar_tys_infer_tuple = false;
2211 while let Some(code) = next_code {
2214 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
2215 next_code = Some(parent_code);
2217 ObligationCauseCode::ImplDerivedObligation(cause) => {
2218 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
2220 parent_trait_ref = ?cause.derived.parent_trait_pred,
2221 self_ty.kind = ?ty.kind(),
2226 ty::Generator(did, ..) => {
2227 generator = generator.or(Some(did));
2228 outer_generator = Some(did);
2230 ty::GeneratorWitness(..) => {}
2231 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2232 // By introducing a tuple of upvar types into the chain of obligations
2233 // of a generator, the first non-generator item is now the tuple itself,
2234 // we shall ignore this.
2236 seen_upvar_tys_infer_tuple = true;
2238 _ if generator.is_none() => {
2239 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
2240 target_ty = Some(ty);
2245 next_code = Some(&cause.derived.parent_code);
2247 ObligationCauseCode::DerivedObligation(derived_obligation)
2248 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
2249 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
2251 parent_trait_ref = ?derived_obligation.parent_trait_pred,
2252 self_ty.kind = ?ty.kind(),
2256 ty::Generator(did, ..) => {
2257 generator = generator.or(Some(did));
2258 outer_generator = Some(did);
2260 ty::GeneratorWitness(..) => {}
2261 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2262 // By introducing a tuple of upvar types into the chain of obligations
2263 // of a generator, the first non-generator item is now the tuple itself,
2264 // we shall ignore this.
2266 seen_upvar_tys_infer_tuple = true;
2268 _ if generator.is_none() => {
2269 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2270 target_ty = Some(ty);
2275 next_code = Some(&derived_obligation.parent_code);
2281 // Only continue if a generator was found.
2282 debug!(?generator, ?trait_ref, ?target_ty);
2283 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
2287 let span = self.tcx.def_span(generator_did);
2289 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
2292 ?generator_did_root,
2293 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2297 let generator_body = generator_did
2299 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2300 .map(|body_id| hir.body(body_id));
2301 let mut visitor = AwaitsVisitor::default();
2302 if let Some(body) = generator_body {
2303 visitor.visit_body(body);
2305 debug!(awaits = ?visitor.awaits);
2307 // Look for a type inside the generator interior that matches the target type to get
2309 let target_ty_erased = self.tcx.erase_regions(target_ty);
2310 let ty_matches = |ty| -> bool {
2311 // Careful: the regions for types that appear in the
2312 // generator interior are not generally known, so we
2313 // want to erase them when comparing (and anyway,
2314 // `Send` and other bounds are generally unaffected by
2315 // the choice of region). When erasing regions, we
2316 // also have to erase late-bound regions. This is
2317 // because the types that appear in the generator
2318 // interior generally contain "bound regions" to
2319 // represent regions that are part of the suspended
2320 // generator frame. Bound regions are preserved by
2321 // `erase_regions` and so we must also call
2322 // `erase_late_bound_regions`.
2323 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2324 let ty_erased = self.tcx.erase_regions(ty_erased);
2325 let eq = ty_erased == target_ty_erased;
2326 debug!(?ty_erased, ?target_ty_erased, ?eq);
2330 // Get the typeck results from the infcx if the generator is the function we are currently
2331 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2332 // cycles. If we can't use resolved types because the generator comes from another crate,
2333 // we still provide a targeted error but without all the relevant spans.
2334 let generator_data = match &self.typeck_results {
2335 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2336 _ if generator_did.is_local() => {
2337 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2339 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2340 GeneratorData::Foreign(generator_diag_data)
2345 let mut interior_or_upvar_span = None;
2347 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2348 debug!(?from_awaited_ty);
2350 // The generator interior types share the same binders
2351 if let Some(cause) =
2352 generator_data.get_generator_interior_types().skip_binder().iter().find(
2353 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2354 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2358 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2360 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2362 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2366 if interior_or_upvar_span.is_none() {
2367 interior_or_upvar_span =
2368 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2371 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2372 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2375 debug!(?interior_or_upvar_span);
2376 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2377 let is_async = self.tcx.generator_is_async(generator_did);
2378 let typeck_results = match generator_data {
2379 GeneratorData::Local(typeck_results) => Some(typeck_results),
2380 GeneratorData::Foreign(_) => None,
2382 self.note_obligation_cause_for_async_await(
2384 interior_or_upvar_span,
2399 /// Unconditionally adds the diagnostic note described in
2400 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2401 #[instrument(level = "debug", skip_all)]
2402 fn note_obligation_cause_for_async_await(
2404 err: &mut Diagnostic,
2405 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2407 outer_generator: Option<DefId>,
2408 trait_pred: ty::TraitPredicate<'tcx>,
2409 target_ty: Ty<'tcx>,
2410 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2411 obligation: &PredicateObligation<'tcx>,
2412 next_code: Option<&ObligationCauseCode<'tcx>>,
2414 let source_map = self.tcx.sess.source_map();
2416 let (await_or_yield, an_await_or_yield) =
2417 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2418 let future_or_generator = if is_async { "future" } else { "generator" };
2420 // Special case the primary error message when send or sync is the trait that was
2422 let hir = self.tcx.hir();
2423 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2424 self.tcx.get_diagnostic_name(trait_pred.def_id())
2426 let (trait_name, trait_verb) =
2427 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2430 err.set_primary_message(format!(
2431 "{} cannot be {} between threads safely",
2432 future_or_generator, trait_verb
2435 let original_span = err.span.primary_span().unwrap();
2436 let mut span = MultiSpan::from_span(original_span);
2438 let message = outer_generator
2439 .and_then(|generator_did| {
2440 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2441 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2442 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2444 .parent(generator_did)
2446 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2447 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2449 format!("future returned by `{}` is not {}", name, trait_name)
2451 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2452 format!("future created by async block is not {}", trait_name)
2454 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2455 format!("future created by async closure is not {}", trait_name)
2459 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2461 span.push_span_label(original_span, message);
2464 format!("is not {}", trait_name)
2466 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2469 let mut explain_yield =
2470 |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
2471 let mut span = MultiSpan::from_span(yield_span);
2472 let snippet = match source_map.span_to_snippet(interior_span) {
2473 // #70935: If snippet contains newlines, display "the value" instead
2474 // so that we do not emit complex diagnostics.
2475 Ok(snippet) if !snippet.contains('\n') => format!("`{}`", snippet),
2476 _ => "the value".to_string(),
2478 // note: future is not `Send` as this value is used across an await
2479 // --> $DIR/issue-70935-complex-spans.rs:13:9
2481 // LL | baz(|| async {
2482 // | ______________-
2485 // LL | | foo(tx.clone());
2487 // | | - ^^^^^^ await occurs here, with value maybe used later
2489 // | has type `closure` which is not `Send`
2490 // note: value is later dropped here
2494 span.push_span_label(
2496 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2498 span.push_span_label(
2500 format!("has type `{}` which {}", target_ty, trait_explanation),
2502 if let Some(scope_span) = scope_span {
2503 let scope_span = source_map.end_point(scope_span);
2505 let msg = format!("{} is later dropped here", snippet);
2506 span.push_span_label(scope_span, msg);
2511 "{} {} as this value is used across {}",
2512 future_or_generator, trait_explanation, an_await_or_yield
2516 match interior_or_upvar_span {
2517 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2518 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2519 if let Some(await_span) = from_awaited_ty {
2520 // The type causing this obligation is one being awaited at await_span.
2521 let mut span = MultiSpan::from_span(await_span);
2522 span.push_span_label(
2525 "await occurs here on type `{}`, which {}",
2526 target_ty, trait_explanation
2532 "future {not_trait} as it awaits another future which {not_trait}",
2533 not_trait = trait_explanation
2537 // Look at the last interior type to get a span for the `.await`.
2539 generator_interior_types = ?format_args!(
2540 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2543 explain_yield(interior_span, yield_span, scope_span);
2546 if let Some(expr_id) = expr {
2547 let expr = hir.expect_expr(expr_id);
2548 debug!("target_ty evaluated from {:?}", expr);
2550 let parent = hir.parent_id(expr_id);
2551 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2552 let parent_span = hir.span(parent);
2553 let parent_did = parent.owner.to_def_id();
2556 // fn foo(&self) -> i32 {}
2559 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2562 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2564 .expr_adjustments(expr)
2566 .any(|adj| adj.is_region_borrow())
2572 // struct Foo(*const u8);
2573 // bar(Foo(std::ptr::null())).await;
2574 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2576 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2577 let is_raw_borrow_inside_fn_like_call =
2578 match self.tcx.def_kind(parent_did) {
2579 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2582 if let Some(typeck_results) = typeck_results {
2583 if (typeck_results.is_method_call(e) && is_region_borrow)
2584 || is_raw_borrow_inside_fn_like_call
2588 "consider moving this into a `let` \
2589 binding to create a shorter lived borrow",
2597 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2598 // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
2599 let non_send = match target_ty.kind() {
2600 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(&obligation) {
2601 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2607 let (span_label, span_note) = match non_send {
2608 // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
2609 // include suggestions to make `T: Sync` so that `&T: Send`,
2610 // or to make `T: Send` so that `&mut T: Send`
2611 Some((ref_ty, is_mut)) => {
2612 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2613 let ref_kind = if is_mut { "&mut" } else { "&" };
2616 "has type `{}` which {}, because `{}` is not `{}`",
2617 target_ty, trait_explanation, ref_ty, ref_ty_trait
2620 "captured value {} because `{}` references cannot be sent unless their referent is `{}`",
2621 trait_explanation, ref_kind, ref_ty_trait
2626 format!("has type `{}` which {}", target_ty, trait_explanation),
2627 format!("captured value {}", trait_explanation),
2631 let mut span = MultiSpan::from_span(upvar_span);
2632 span.push_span_label(upvar_span, span_label);
2633 err.span_note(span, &span_note);
2637 // Add a note for the item obligation that remains - normally a note pointing to the
2638 // bound that introduced the obligation (e.g. `T: Send`).
2640 self.note_obligation_cause_code(
2642 obligation.predicate,
2643 obligation.param_env,
2646 &mut Default::default(),
2650 fn note_obligation_cause_code<T>(
2652 err: &mut Diagnostic,
2654 param_env: ty::ParamEnv<'tcx>,
2655 cause_code: &ObligationCauseCode<'tcx>,
2656 obligated_types: &mut Vec<Ty<'tcx>>,
2657 seen_requirements: &mut FxHashSet<DefId>,
2659 T: ToPredicate<'tcx>,
2662 let predicate = predicate.to_predicate(tcx);
2664 ObligationCauseCode::ExprAssignable
2665 | ObligationCauseCode::MatchExpressionArm { .. }
2666 | ObligationCauseCode::Pattern { .. }
2667 | ObligationCauseCode::IfExpression { .. }
2668 | ObligationCauseCode::IfExpressionWithNoElse
2669 | ObligationCauseCode::MainFunctionType
2670 | ObligationCauseCode::StartFunctionType
2671 | ObligationCauseCode::IntrinsicType
2672 | ObligationCauseCode::MethodReceiver
2673 | ObligationCauseCode::ReturnNoExpression
2674 | ObligationCauseCode::UnifyReceiver(..)
2675 | ObligationCauseCode::OpaqueType
2676 | ObligationCauseCode::MiscObligation
2677 | ObligationCauseCode::WellFormed(..)
2678 | ObligationCauseCode::MatchImpl(..)
2679 | ObligationCauseCode::ReturnType
2680 | ObligationCauseCode::ReturnValue(_)
2681 | ObligationCauseCode::BlockTailExpression(_)
2682 | ObligationCauseCode::AwaitableExpr(_)
2683 | ObligationCauseCode::ForLoopIterator
2684 | ObligationCauseCode::QuestionMark
2685 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2686 | ObligationCauseCode::LetElse
2687 | ObligationCauseCode::BinOp { .. }
2688 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2689 | ObligationCauseCode::RustCall => {}
2690 ObligationCauseCode::SliceOrArrayElem => {
2691 err.note("slice and array elements must have `Sized` type");
2693 ObligationCauseCode::TupleElem => {
2694 err.note("only the last element of a tuple may have a dynamically sized type");
2696 ObligationCauseCode::ProjectionWf(data) => {
2697 err.note(&format!("required so that the projection `{data}` is well-formed"));
2699 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2701 "required so that reference `{ref_ty}` does not outlive its referent"
2704 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2706 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2710 ObligationCauseCode::ItemObligation(_)
2711 | ObligationCauseCode::ExprItemObligation(..) => {
2712 // We hold the `DefId` of the item introducing the obligation, but displaying it
2713 // doesn't add user usable information. It always point at an associated item.
2715 ObligationCauseCode::BindingObligation(item_def_id, span)
2716 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2717 let item_name = tcx.def_path_str(item_def_id);
2718 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2719 let mut multispan = MultiSpan::from(span);
2720 let sm = tcx.sess.source_map();
2721 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2723 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2724 (Ok(l), Ok(r)) => l.line == r.line,
2727 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2728 multispan.push_span_label(ident.span, "required by a bound in this");
2731 let descr = format!("required by a bound in `{item_name}`");
2732 if span.is_visible(sm) {
2733 let msg = format!("required by this bound in `{short_item_name}`");
2734 multispan.push_span_label(span, msg);
2735 err.span_note(multispan, &descr);
2737 err.span_note(tcx.def_span(item_def_id), &descr);
2740 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2741 let (concrete_ty, concrete_file) =
2742 self.tcx.short_ty_string(self.resolve_vars_if_possible(concrete_ty));
2743 let (object_ty, object_file) =
2744 self.tcx.short_ty_string(self.resolve_vars_if_possible(object_ty));
2745 err.note(&with_forced_trimmed_paths!(format!(
2746 "required for the cast from `{concrete_ty}` to the object type `{object_ty}`",
2748 if let Some(file) = concrete_file {
2750 "the full name for the casted type has been written to '{}'",
2754 if let Some(file) = object_file {
2756 "the full name for the object type has been written to '{}'",
2761 ObligationCauseCode::Coercion { source: _, target } => {
2762 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2764 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2766 "the `Copy` trait is required because this value will be copied for each element of the array",
2771 "consider creating a new `const` item and initializing it with the result \
2772 of the function call to be used in the repeat position, like \
2773 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2777 if self.tcx.sess.is_nightly_build() && is_const_fn {
2779 "create an inline `const` block, see RFC #2920 \
2780 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2784 ObligationCauseCode::VariableType(hir_id) => {
2785 let parent_node = self.tcx.hir().parent_id(hir_id);
2786 match self.tcx.hir().find(parent_node) {
2787 Some(Node::Local(hir::Local { ty: Some(ty), .. })) => {
2788 err.span_suggestion_verbose(
2789 ty.span.shrink_to_lo(),
2790 "consider borrowing here",
2792 Applicability::MachineApplicable,
2794 err.note("all local variables must have a statically known size");
2796 Some(Node::Local(hir::Local {
2797 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2800 // When encountering an assignment of an unsized trait, like
2801 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2802 // order to use have a slice instead.
2803 err.span_suggestion_verbose(
2804 span.shrink_to_lo(),
2805 "consider borrowing here",
2807 Applicability::MachineApplicable,
2809 err.note("all local variables must have a statically known size");
2811 Some(Node::Param(param)) => {
2812 err.span_suggestion_verbose(
2813 param.ty_span.shrink_to_lo(),
2814 "function arguments must have a statically known size, borrowed types \
2815 always have a known size",
2817 Applicability::MachineApplicable,
2821 err.note("all local variables must have a statically known size");
2824 if !self.tcx.features().unsized_locals {
2825 err.help("unsized locals are gated as an unstable feature");
2828 ObligationCauseCode::SizedArgumentType(sp) => {
2829 if let Some(span) = sp {
2830 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder()
2831 && let ty::Clause::Trait(trait_pred) = clause
2832 && let ty::Dynamic(..) = trait_pred.self_ty().kind()
2834 let span = if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2835 && snippet.starts_with("dyn ")
2837 let pos = snippet.len() - snippet[3..].trim_start().len();
2838 span.with_hi(span.lo() + BytePos(pos as u32))
2842 err.span_suggestion_verbose(
2844 "you can use `impl Trait` as the argument type",
2845 "impl ".to_string(),
2846 Applicability::MaybeIncorrect,
2849 err.span_suggestion_verbose(
2850 span.shrink_to_lo(),
2851 "function arguments must have a statically known size, borrowed types \
2852 always have a known size",
2854 Applicability::MachineApplicable,
2857 err.note("all function arguments must have a statically known size");
2859 if tcx.sess.opts.unstable_features.is_nightly_build()
2860 && !self.tcx.features().unsized_fn_params
2862 err.help("unsized fn params are gated as an unstable feature");
2865 ObligationCauseCode::SizedReturnType => {
2866 err.note("the return type of a function must have a statically known size");
2868 ObligationCauseCode::SizedYieldType => {
2869 err.note("the yield type of a generator must have a statically known size");
2871 ObligationCauseCode::SizedBoxType => {
2872 err.note("the type of a box expression must have a statically known size");
2874 ObligationCauseCode::AssignmentLhsSized => {
2875 err.note("the left-hand-side of an assignment must have a statically known size");
2877 ObligationCauseCode::TupleInitializerSized => {
2878 err.note("tuples must have a statically known size to be initialized");
2880 ObligationCauseCode::StructInitializerSized => {
2881 err.note("structs must have a statically known size to be initialized");
2883 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2885 AdtKind::Struct => {
2888 "the last field of a packed struct may only have a \
2889 dynamically sized type if it does not need drop to be run",
2893 "only the last field of a struct may have a dynamically sized type",
2898 err.note("no field of a union may have a dynamically sized type");
2901 err.note("no field of an enum variant may have a dynamically sized type");
2904 err.help("change the field's type to have a statically known size");
2905 err.span_suggestion(
2906 span.shrink_to_lo(),
2907 "borrowed types always have a statically known size",
2909 Applicability::MachineApplicable,
2911 err.multipart_suggestion(
2912 "the `Box` type always has a statically known size and allocates its contents \
2915 (span.shrink_to_lo(), "Box<".to_string()),
2916 (span.shrink_to_hi(), ">".to_string()),
2918 Applicability::MachineApplicable,
2921 ObligationCauseCode::ConstSized => {
2922 err.note("constant expressions must have a statically known size");
2924 ObligationCauseCode::InlineAsmSized => {
2925 err.note("all inline asm arguments must have a statically known size");
2927 ObligationCauseCode::ConstPatternStructural => {
2928 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2930 ObligationCauseCode::SharedStatic => {
2931 err.note("shared static variables must have a type that implements `Sync`");
2933 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2934 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2935 let ty = parent_trait_ref.skip_binder().self_ty();
2936 if parent_trait_ref.references_error() {
2937 // NOTE(eddyb) this was `.cancel()`, but `err`
2938 // is borrowed, so we can't fully defuse it.
2939 err.downgrade_to_delayed_bug();
2943 // If the obligation for a tuple is set directly by a Generator or Closure,
2944 // then the tuple must be the one containing capture types.
2945 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2948 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2950 let parent_trait_ref =
2951 self.resolve_vars_if_possible(data.parent_trait_pred);
2952 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2953 matches!(nested_ty.kind(), ty::Generator(..))
2954 || matches!(nested_ty.kind(), ty::Closure(..))
2960 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2962 // Don't print the tuple of capture types
2964 if !is_upvar_tys_infer_tuple {
2965 let msg = with_forced_trimmed_paths!(format!(
2966 "required because it appears within the type `{ty}`",
2969 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2970 Some(ident) => err.span_note(ident.span, &msg),
2971 None => err.note(&msg),
2973 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
2974 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2975 if tcx.parent(*def_id) == identity_future {
2979 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2980 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2981 let is_future = tcx.ty_is_opaque_future(ty);
2985 "note_obligation_cause_code: check for async fn"
2988 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2989 ty::Generator(last_def_id, ..) => {
2990 tcx.generator_is_async(*last_def_id)
2997 err.span_note(self.tcx.def_span(def_id), &msg)
2999 ty::GeneratorWitness(bound_tys) => {
3000 use std::fmt::Write;
3002 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
3003 // Maybe we should just remove this note altogether?
3004 // FIXME: only print types which don't meet the trait requirement
3006 "required because it captures the following types: ".to_owned();
3007 for ty in bound_tys.skip_binder() {
3008 with_forced_trimmed_paths!(write!(msg, "`{}`, ", ty).unwrap());
3010 err.note(msg.trim_end_matches(", "))
3012 ty::Generator(def_id, _, _) => {
3013 let sp = self.tcx.def_span(def_id);
3015 // Special-case this to say "async block" instead of `[static generator]`.
3016 let kind = tcx.generator_kind(def_id).unwrap().descr();
3019 with_forced_trimmed_paths!(&format!(
3020 "required because it's used within this {kind}",
3024 ty::Closure(def_id, _) => err.span_note(
3025 self.tcx.def_span(def_id),
3026 "required because it's used within this closure",
3028 _ => err.note(&msg),
3033 obligated_types.push(ty);
3035 let parent_predicate = parent_trait_ref;
3036 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
3037 // #74711: avoid a stack overflow
3038 ensure_sufficient_stack(|| {
3039 self.note_obligation_cause_code(
3049 ensure_sufficient_stack(|| {
3050 self.note_obligation_cause_code(
3054 cause_code.peel_derives(),
3061 ObligationCauseCode::ImplDerivedObligation(ref data) => {
3062 let mut parent_trait_pred =
3063 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
3064 parent_trait_pred.remap_constness_diag(param_env);
3065 let parent_def_id = parent_trait_pred.def_id();
3066 let (self_ty, file) =
3067 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
3069 "required for `{self_ty}` to implement `{}`",
3070 parent_trait_pred.print_modifiers_and_trait_path()
3072 let mut is_auto_trait = false;
3073 match self.tcx.hir().get_if_local(data.impl_def_id) {
3074 Some(Node::Item(hir::Item {
3075 kind: hir::ItemKind::Trait(is_auto, ..),
3079 // FIXME: we should do something else so that it works even on crate foreign
3081 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
3082 err.span_note(ident.span, &msg);
3084 Some(Node::Item(hir::Item {
3085 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
3088 let mut spans = Vec::with_capacity(2);
3089 if let Some(trait_ref) = of_trait {
3090 spans.push(trait_ref.path.span);
3092 spans.push(self_ty.span);
3093 let mut spans: MultiSpan = spans.into();
3095 self_ty.span.ctxt().outer_expn_data().kind,
3096 ExpnKind::Macro(MacroKind::Derive, _)
3098 of_trait.as_ref().map(|t| t.path.span.ctxt().outer_expn_data().kind),
3099 Some(ExpnKind::Macro(MacroKind::Derive, _))
3101 spans.push_span_label(
3103 "unsatisfied trait bound introduced in this `derive` macro",
3105 } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
3106 spans.push_span_label(
3108 "unsatisfied trait bound introduced here",
3111 err.span_note(spans, &msg);
3118 if let Some(file) = file {
3120 "the full type name has been written to '{}'",
3124 let mut parent_predicate = parent_trait_pred;
3125 let mut data = &data.derived;
3127 seen_requirements.insert(parent_def_id);
3129 // We don't want to point at the ADT saying "required because it appears within
3130 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
3131 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
3134 let child_trait_ref =
3135 self.resolve_vars_if_possible(derived.parent_trait_pred);
3136 let child_def_id = child_trait_ref.def_id();
3137 if seen_requirements.insert(child_def_id) {
3141 parent_predicate = child_trait_ref.to_predicate(tcx);
3142 parent_trait_pred = child_trait_ref;
3145 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
3146 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
3147 let child_trait_pred =
3148 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
3149 let child_def_id = child_trait_pred.def_id();
3150 if seen_requirements.insert(child_def_id) {
3154 data = &child.derived;
3155 parent_predicate = child_trait_pred.to_predicate(tcx);
3156 parent_trait_pred = child_trait_pred;
3160 "{} redundant requirement{} hidden",
3164 let (self_ty, file) =
3165 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
3167 "required for `{self_ty}` to implement `{}`",
3168 parent_trait_pred.print_modifiers_and_trait_path()
3170 if let Some(file) = file {
3172 "the full type name has been written to '{}'",
3177 // #74711: avoid a stack overflow
3178 ensure_sufficient_stack(|| {
3179 self.note_obligation_cause_code(
3189 ObligationCauseCode::DerivedObligation(ref data) => {
3190 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3191 let parent_predicate = parent_trait_ref;
3192 // #74711: avoid a stack overflow
3193 ensure_sufficient_stack(|| {
3194 self.note_obligation_cause_code(
3204 ObligationCauseCode::FunctionArgumentObligation {
3210 self.note_function_argument_obligation(
3218 ensure_sufficient_stack(|| {
3219 self.note_obligation_cause_code(
3229 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
3230 let item_name = self.tcx.item_name(trait_item_def_id);
3232 "the requirement `{predicate}` appears on the `impl`'s {kind} \
3233 `{item_name}` but not on the corresponding trait's {kind}",
3237 .opt_item_ident(trait_item_def_id)
3239 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
3240 let mut assoc_span: MultiSpan = sp.into();
3241 assoc_span.push_span_label(
3243 format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
3245 if let Some(ident) = self
3247 .opt_associated_item(trait_item_def_id)
3248 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
3250 assoc_span.push_span_label(ident.span, "in this trait");
3252 err.span_note(assoc_span, &msg);
3254 ObligationCauseCode::TrivialBound => {
3255 err.help("see issue #48214");
3256 if tcx.sess.opts.unstable_features.is_nightly_build() {
3257 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
3260 ObligationCauseCode::OpaqueReturnType(expr_info) => {
3261 if let Some((expr_ty, expr_span)) = expr_info {
3262 let expr_ty = with_forced_trimmed_paths!(self.ty_to_string(expr_ty));
3265 with_forced_trimmed_paths!(format!(
3266 "return type was inferred to be `{expr_ty}` here",
3275 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
3277 fn suggest_await_before_try(
3279 err: &mut Diagnostic,
3280 obligation: &PredicateObligation<'tcx>,
3281 trait_pred: ty::PolyTraitPredicate<'tcx>,
3284 let body_hir_id = obligation.cause.body_id;
3285 let item_id = self.tcx.hir().parent_id(body_hir_id);
3287 if let Some(body_id) =
3288 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
3290 let body = self.tcx.hir().body(body_id);
3291 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
3292 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
3294 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3295 let impls_future = self.type_implements_trait(
3297 [self.tcx.erase_late_bound_regions(self_ty)],
3298 obligation.param_env,
3300 if !impls_future.must_apply_modulo_regions() {
3304 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3305 // `<T as Future>::Output`
3306 let projection_ty = trait_pred.map_bound(|trait_pred| {
3307 self.tcx.mk_projection(
3309 // Future::Output has no substs
3310 [trait_pred.self_ty()],
3313 let InferOk { value: projection_ty, .. } =
3314 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3317 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3319 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3320 obligation.param_env,
3321 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3323 debug!(try_trait_obligation = ?try_obligation);
3324 if self.predicate_may_hold(&try_obligation)
3325 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3326 && snippet.ends_with('?')
3328 err.span_suggestion_verbose(
3329 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3330 "consider `await`ing on the `Future`",
3332 Applicability::MaybeIncorrect,
3339 fn suggest_floating_point_literal(
3341 obligation: &PredicateObligation<'tcx>,
3342 err: &mut Diagnostic,
3343 trait_ref: &ty::PolyTraitRef<'tcx>,
3345 let rhs_span = match obligation.cause.code() {
3346 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3349 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3350 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3352 err.span_suggestion_verbose(
3353 rhs_span.shrink_to_hi(),
3354 "consider using a floating-point literal by writing it with `.0`",
3356 Applicability::MaybeIncorrect,
3363 obligation: &PredicateObligation<'tcx>,
3364 err: &mut Diagnostic,
3365 trait_pred: ty::PolyTraitPredicate<'tcx>,
3367 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3370 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3371 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3375 let is_derivable_trait = match diagnostic_name {
3376 sym::Default => !adt.is_enum(),
3377 sym::PartialEq | sym::PartialOrd => {
3378 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3379 trait_pred.skip_binder().self_ty() == rhs_ty
3381 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3384 is_derivable_trait &&
3385 // Ensure all fields impl the trait.
3386 adt.all_fields().all(|field| {
3387 let field_ty = field.ty(self.tcx, substs);
3388 let trait_substs = match diagnostic_name {
3389 sym::PartialEq | sym::PartialOrd => {
3394 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3395 trait_ref: self.tcx.mk_trait_ref(
3396 trait_pred.def_id(),
3397 [field_ty].into_iter().chain(trait_substs),
3401 let field_obl = Obligation::new(
3403 obligation.cause.clone(),
3404 obligation.param_env,
3407 self.predicate_must_hold_modulo_regions(&field_obl)
3411 err.span_suggestion_verbose(
3412 self.tcx.def_span(adt.did()).shrink_to_lo(),
3414 "consider annotating `{}` with `#[derive({})]`",
3415 trait_pred.skip_binder().self_ty(),
3418 format!("#[derive({})]\n", diagnostic_name),
3419 Applicability::MaybeIncorrect,
3424 fn suggest_dereferencing_index(
3426 obligation: &PredicateObligation<'tcx>,
3427 err: &mut Diagnostic,
3428 trait_pred: ty::PolyTraitPredicate<'tcx>,
3430 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3431 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3432 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3433 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3434 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3436 err.span_suggestion_verbose(
3437 obligation.cause.span.shrink_to_lo(),
3438 "dereference this index",
3440 Applicability::MachineApplicable,
3444 fn note_function_argument_obligation(
3447 err: &mut Diagnostic,
3448 parent_code: &ObligationCauseCode<'tcx>,
3449 param_env: ty::ParamEnv<'tcx>,
3450 failed_pred: ty::Predicate<'tcx>,
3454 let hir = tcx.hir();
3455 if let Some(Node::Expr(expr)) = hir.find(arg_hir_id)
3456 && let Some(typeck_results) = &self.typeck_results
3458 if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
3459 let expr = expr.peel_blocks();
3460 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
3461 let span = expr.span;
3462 if Some(span) != err.span.primary_span() {
3465 if ty.references_error() {
3468 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3469 format!("this tail expression is of type `{ty}`")
3475 // FIXME: visit the ty to see if there's any closure involved, and if there is,
3476 // check whether its evaluated return type is the same as the one corresponding
3477 // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3478 // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3479 let mut type_diffs = vec![];
3481 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
3482 && let Some(node_substs) = typeck_results.node_substs_opt(call_hir_id)
3483 && let where_clauses = self.tcx.predicates_of(def_id).instantiate(self.tcx, node_substs)
3484 && let Some(where_pred) = where_clauses.predicates.get(*idx)
3486 if let Some(where_pred) = where_pred.to_opt_poly_trait_pred()
3487 && let Some(failed_pred) = failed_pred.to_opt_poly_trait_pred()
3489 let mut c = CollectAllMismatches {
3494 if let Ok(_) = c.relate(where_pred, failed_pred) {
3495 type_diffs = c.errors;
3497 } else if let Some(where_pred) = where_pred.to_opt_poly_projection_pred()
3498 && let Some(failed_pred) = failed_pred.to_opt_poly_projection_pred()
3499 && let Some(found) = failed_pred.skip_binder().term.ty()
3502 Sorts(ty::error::ExpectedFound {
3503 expected: self.tcx.mk_ty(ty::Alias(ty::Projection, where_pred.skip_binder().projection_ty)),
3509 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3510 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3511 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3512 && let parent_hir_id = self.tcx.hir().parent_id(binding.hir_id)
3513 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3514 && let Some(binding_expr) = local.init
3516 // If the expression we're calling on is a binding, we want to point at the
3517 // `let` when talking about the type. Otherwise we'll point at every part
3518 // of the method chain with the type.
3519 self.point_at_chain(binding_expr, &typeck_results, type_diffs, param_env, err);
3521 self.point_at_chain(expr, &typeck_results, type_diffs, param_env, err);
3524 let call_node = hir.find(call_hir_id);
3525 if let Some(Node::Expr(hir::Expr {
3526 kind: hir::ExprKind::MethodCall(path, rcvr, ..), ..
3529 if Some(rcvr.span) == err.span.primary_span() {
3530 err.replace_span_with(path.ident.span, true);
3533 if let Some(Node::Expr(hir::Expr {
3535 hir::ExprKind::Call(hir::Expr { span, .. }, _)
3536 | hir::ExprKind::MethodCall(hir::PathSegment { ident: Ident { span, .. }, .. }, ..),
3538 })) = hir.find(call_hir_id)
3540 if Some(*span) != err.span.primary_span() {
3541 err.span_label(*span, "required by a bound introduced by this call");
3548 expr: &hir::Expr<'_>,
3549 typeck_results: &TypeckResults<'tcx>,
3550 type_diffs: Vec<TypeError<'tcx>>,
3551 param_env: ty::ParamEnv<'tcx>,
3552 err: &mut Diagnostic,
3554 let mut primary_spans = vec![];
3555 let mut span_labels = vec![];
3559 let mut print_root_expr = true;
3560 let mut assocs = vec![];
3561 let mut expr = expr;
3562 let mut prev_ty = self.resolve_vars_if_possible(
3563 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3565 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) = expr.kind {
3566 // Point at every method call in the chain with the resulting type.
3567 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3568 // ^^^^^^ ^^^^^^^^^^^
3570 let assocs_in_this_method =
3571 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
3572 assocs.push(assocs_in_this_method);
3573 prev_ty = self.resolve_vars_if_possible(
3574 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3577 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3578 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3579 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3580 && let Some(parent) = self.tcx.hir().find_parent(binding.hir_id)
3582 // We've reached the root of the method call chain...
3583 if let hir::Node::Local(local) = parent
3584 && let Some(binding_expr) = local.init
3586 // ...and it is a binding. Get the binding creation and continue the chain.
3587 expr = binding_expr;
3589 if let hir::Node::Param(param) = parent {
3590 // ...and it is a an fn argument.
3591 let prev_ty = self.resolve_vars_if_possible(
3592 typeck_results.node_type_opt(param.hir_id).unwrap_or(tcx.ty_error()),
3594 let assocs_in_this_method = self.probe_assoc_types_at_expr(&type_diffs, param.ty_span, prev_ty, param.hir_id, param_env);
3595 if assocs_in_this_method.iter().any(|a| a.is_some()) {
3596 assocs.push(assocs_in_this_method);
3597 print_root_expr = false;
3603 // We want the type before deref coercions, otherwise we talk about `&[_]`
3604 // instead of `Vec<_>`.
3605 if let Some(ty) = typeck_results.expr_ty_opt(expr) && print_root_expr {
3606 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3607 // Point at the root expression
3608 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3610 span_labels.push((expr.span, format!("this expression has type `{ty}`")));
3612 // Only show this if it is not a "trivial" expression (not a method
3613 // chain) and there are associated types to talk about.
3614 let mut assocs = assocs.into_iter().peekable();
3615 while let Some(assocs_in_method) = assocs.next() {
3616 let Some(prev_assoc_in_method) = assocs.peek() else {
3617 for entry in assocs_in_method {
3618 let Some((span, (assoc, ty))) = entry else { continue; };
3619 if primary_spans.is_empty() || type_diffs.iter().any(|diff| {
3620 let Sorts(expected_found) = diff else { return false; };
3621 self.can_eq(param_env, expected_found.found, ty).is_ok()
3623 // FIXME: this doesn't quite work for `Iterator::collect`
3624 // because we have `Vec<i32>` and `()`, but we'd want `i32`
3625 // to point at the `.into_iter()` call, but as long as we
3626 // still point at the other method calls that might have
3627 // introduced the issue, this is fine for now.
3628 primary_spans.push(span);
3632 with_forced_trimmed_paths!(format!(
3633 "`{}` is `{ty}` here",
3634 self.tcx.def_path_str(assoc),
3640 for (entry, prev_entry) in
3641 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
3643 match (entry, prev_entry) {
3644 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
3645 let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
3647 let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
3648 if self.can_eq(param_env, ty, *prev_ty).is_err() {
3649 if type_diffs.iter().any(|diff| {
3650 let Sorts(expected_found) = diff else { return false; };
3651 self.can_eq(param_env, expected_found.found, ty).is_ok()
3653 primary_spans.push(span);
3656 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
3658 span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
3661 (Some((span, (assoc, ty))), None) => {
3664 with_forced_trimmed_paths!(format!(
3665 "`{}` is `{}` here",
3666 self.tcx.def_path_str(assoc),
3667 self.ty_to_string(ty),
3671 (None, Some(_)) | (None, None) => {}
3675 if !primary_spans.is_empty() {
3676 let mut multi_span: MultiSpan = primary_spans.into();
3677 for (span, label) in span_labels {
3678 multi_span.push_span_label(span, label);
3682 "the method call chain might not have had the expected associated types",
3687 fn probe_assoc_types_at_expr(
3689 type_diffs: &[TypeError<'tcx>],
3692 body_id: hir::HirId,
3693 param_env: ty::ParamEnv<'tcx>,
3694 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
3695 let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
3696 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
3697 for diff in type_diffs {
3698 let Sorts(expected_found) = diff else { continue; };
3699 let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; };
3701 let origin = TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span };
3702 let trait_def_id = proj.trait_def_id(self.tcx);
3703 // Make `Self` be equivalent to the type of the call chain
3704 // expression we're looking at now, so that we can tell what
3705 // for example `Iterator::Item` is at this point in the chain.
3706 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
3708 ty::GenericParamDefKind::Type { .. } => {
3709 if param.index == 0 {
3710 return prev_ty.into();
3713 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Const { .. } => {}
3715 self.var_for_def(span, param)
3717 // This will hold the resolved type of the associated type, if the
3718 // current expression implements the trait that associated type is
3719 // in. For example, this would be what `Iterator::Item` is here.
3720 let ty_var = self.infcx.next_ty_var(origin);
3721 // This corresponds to `<ExprTy as Iterator>::Item = _`.
3722 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::Projection(
3723 ty::ProjectionPredicate {
3724 projection_ty: self.tcx.mk_alias_ty(proj.def_id, substs),
3725 term: ty_var.into(),
3728 // Add `<ExprTy as Iterator>::Item = _` obligation.
3729 ocx.register_obligation(Obligation::misc(
3730 self.tcx, span, body_id, param_env, projection,
3732 if ocx.select_where_possible().is_empty() {
3733 // `ty_var` now holds the type that `Item` is for `ExprTy`.
3734 let ty_var = self.resolve_vars_if_possible(ty_var);
3735 assocs_in_this_method.push(Some((span, (proj.def_id, ty_var))));
3737 // `<ExprTy as Iterator>` didn't select, so likely we've
3738 // reached the end of the iterator chain, like the originating
3740 // Keep the space consistent for later zipping.
3741 assocs_in_this_method.push(None);
3744 assocs_in_this_method
3748 /// Add a hint to add a missing borrow or remove an unnecessary one.
3749 fn hint_missing_borrow<'tcx>(
3753 found_node: Node<'_>,
3754 err: &mut Diagnostic,
3756 let found_args = match found.kind() {
3757 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3759 span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
3762 let expected_args = match expected.kind() {
3763 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3765 span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
3769 // This could be a variant constructor, for example.
3770 let Some(fn_decl) = found_node.fn_decl() else { return; };
3772 let arg_spans = fn_decl.inputs.iter().map(|ty| ty.span);
3774 fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, usize) {
3777 while let ty::Ref(_, new_ty, _) = ty.kind() {
3785 let mut to_borrow = Vec::new();
3786 let mut remove_borrow = Vec::new();
3788 for ((found_arg, expected_arg), arg_span) in found_args.zip(expected_args).zip(arg_spans) {
3789 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
3790 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
3792 if found_ty == expected_ty {
3793 if found_refs < expected_refs {
3794 to_borrow.push((arg_span, expected_arg.to_string()));
3795 } else if found_refs > expected_refs {
3796 remove_borrow.push((arg_span, expected_arg.to_string()));
3801 if !to_borrow.is_empty() {
3802 err.multipart_suggestion(
3803 "consider borrowing the argument",
3805 Applicability::MaybeIncorrect,
3809 if !remove_borrow.is_empty() {
3810 err.multipart_suggestion(
3811 "do not borrow the argument",
3813 Applicability::MaybeIncorrect,
3818 /// Collect all the returned expressions within the input expression.
3819 /// Used to point at the return spans when we want to suggest some change to them.
3821 pub struct ReturnsVisitor<'v> {
3822 pub returns: Vec<&'v hir::Expr<'v>>,
3823 in_block_tail: bool,
3826 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3827 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3828 // Visit every expression to detect `return` paths, either through the function's tail
3829 // expression or `return` statements. We walk all nodes to find `return` statements, but
3830 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3831 // they're in the return path of the function body.
3833 hir::ExprKind::Ret(Some(ex)) => {
3834 self.returns.push(ex);
3836 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3837 self.in_block_tail = false;
3838 for stmt in block.stmts {
3839 hir::intravisit::walk_stmt(self, stmt);
3841 self.in_block_tail = true;
3842 if let Some(expr) = block.expr {
3843 self.visit_expr(expr);
3846 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3847 self.visit_expr(then);
3848 if let Some(el) = else_opt {
3849 self.visit_expr(el);
3852 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3854 self.visit_expr(arm.body);
3857 // We need to walk to find `return`s in the entire body.
3858 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3859 _ => self.returns.push(ex),
3863 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3864 assert!(!self.in_block_tail);
3865 if body.generator_kind().is_none() {
3866 if let hir::ExprKind::Block(block, None) = body.value.kind {
3867 if block.expr.is_some() {
3868 self.in_block_tail = true;
3872 hir::intravisit::walk_body(self, body);
3876 /// Collect all the awaited expressions within the input expression.
3878 struct AwaitsVisitor {
3879 awaits: Vec<hir::HirId>,
3882 impl<'v> Visitor<'v> for AwaitsVisitor {
3883 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3884 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3885 self.awaits.push(id)
3887 hir::intravisit::walk_expr(self, ex)
3891 pub trait NextTypeParamName {
3892 fn next_type_param_name(&self, name: Option<&str>) -> String;
3895 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3896 fn next_type_param_name(&self, name: Option<&str>) -> String {
3897 // This is the list of possible parameter names that we might suggest.
3898 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3899 let name = name.as_deref();
3900 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3901 let used_names = self
3903 .filter_map(|p| match p.name {
3904 hir::ParamName::Plain(ident) => Some(ident.name),
3907 .collect::<Vec<_>>();
3911 .find(|n| !used_names.contains(&Symbol::intern(n)))
3912 .unwrap_or(&"ParamName")
3917 fn suggest_trait_object_return_type_alternatives(
3918 err: &mut Diagnostic,
3921 is_object_safe: bool,
3923 err.span_suggestion(
3926 "use `impl {}` as the return type if all return paths have the same type but you \
3927 want to expose only the trait in the signature",
3930 format!("impl {}", trait_obj),
3931 Applicability::MaybeIncorrect,
3934 err.multipart_suggestion(
3936 "use a boxed trait object if all return paths implement trait `{}`",
3940 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3941 (ret_ty.shrink_to_hi(), ">".to_string()),
3943 Applicability::MaybeIncorrect,
3948 /// Collect the spans that we see the generic param `param_did`
3949 struct ReplaceImplTraitVisitor<'a> {
3950 ty_spans: &'a mut Vec<Span>,
3954 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3955 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3956 if let hir::TyKind::Path(hir::QPath::Resolved(
3958 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3961 if self.param_did == *segment_did {
3962 // `fn foo(t: impl Trait)`
3963 // ^^^^^^^^^^ get this to suggest `T` instead
3965 // There might be more than one `impl Trait`.
3966 self.ty_spans.push(t.span);
3971 hir::intravisit::walk_ty(self, t);
3975 // Replace `param` with `replace_ty`
3976 struct ReplaceImplTraitFolder<'tcx> {
3978 param: &'tcx ty::GenericParamDef,
3979 replace_ty: Ty<'tcx>,
3982 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3983 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3984 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3985 if self.param.index == *index {
3986 return self.replace_ty;
3989 t.super_fold_with(self)
3992 fn tcx(&self) -> TyCtxt<'tcx> {