1 // ignore-tidy-filelength
3 use super::{DefIdOrName, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation};
5 use crate::autoderef::Autoderef;
6 use crate::infer::InferCtxt;
7 use crate::traits::{NormalizeExt, ObligationCtxt};
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_data_structures::stack::ensure_sufficient_stack;
14 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
15 ErrorGuaranteed, MultiSpan, Style,
18 use rustc_hir::def::DefKind;
19 use rustc_hir::def_id::DefId;
20 use rustc_hir::intravisit::Visitor;
21 use rustc_hir::lang_items::LangItem;
22 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
23 use rustc_infer::infer::error_reporting::TypeErrCtxt;
24 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
25 use rustc_infer::infer::{InferOk, LateBoundRegionConversionTime};
26 use rustc_middle::hir::map;
27 use rustc_middle::ty::error::TypeError::{self, Sorts};
28 use rustc_middle::ty::relate::TypeRelation;
29 use rustc_middle::ty::{
30 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
31 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, InternalSubsts,
32 IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder,
33 TypeSuperFoldable, TypeVisitable, TypeckResults,
35 use rustc_span::symbol::{sym, Ident, Symbol};
36 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
37 use rustc_target::spec::abi;
40 use super::method_chain::CollectAllMismatches;
41 use super::InferCtxtPrivExt;
42 use crate::infer::InferCtxtExt as _;
43 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
44 use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
47 pub enum GeneratorInteriorOrUpvar {
48 // span of interior type
49 Interior(Span, Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>),
54 // This type provides a uniform interface to retrieve data on generators, whether it originated from
55 // the local crate being compiled or from a foreign crate.
57 pub enum GeneratorData<'tcx, 'a> {
58 Local(&'a TypeckResults<'tcx>),
59 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
62 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
63 // Try to get information about variables captured by the generator that matches a type we are
64 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
66 fn try_get_upvar_span<F>(
68 infer_context: &InferCtxt<'tcx>,
71 ) -> Option<GeneratorInteriorOrUpvar>
73 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
76 GeneratorData::Local(typeck_results) => {
77 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
78 upvars.iter().find_map(|(upvar_id, upvar)| {
79 let upvar_ty = typeck_results.node_type(*upvar_id);
80 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
81 if ty_matches(ty::Binder::dummy(upvar_ty)) {
82 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
89 GeneratorData::Foreign(_) => None,
93 // Try to get the span of a type being awaited on that matches the type we are looking with the
94 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
96 fn get_from_await_ty<F>(
98 visitor: AwaitsVisitor,
103 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
106 GeneratorData::Local(typeck_results) => visitor
109 .map(|id| hir.expect_expr(id))
111 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
113 .map(|expr| expr.span),
114 GeneratorData::Foreign(generator_diagnostic_data) => visitor
117 .map(|id| hir.expect_expr(id))
119 ty_matches(ty::Binder::dummy(
120 generator_diagnostic_data
122 .get(&await_expr.hir_id.local_id)
123 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
125 .map_or_else::<Ty<'tcx>, _, _>(
127 generator_diagnostic_data
129 .get(&await_expr.hir_id.local_id)
133 "node_type: no type for node `{}`",
134 ty::tls::with(|tcx| tcx
136 .node_to_string(await_expr.hir_id))
144 .map(|expr| expr.span),
148 /// Get the type, expression, span and optional scope span of all types
149 /// that are live across the yield of this generator
150 fn get_generator_interior_types(
152 ) -> ty::Binder<'tcx, &[GeneratorInteriorTypeCause<'tcx>]> {
154 GeneratorData::Local(typeck_result) => {
155 typeck_result.generator_interior_types.as_deref()
157 GeneratorData::Foreign(generator_diagnostic_data) => {
158 generator_diagnostic_data.generator_interior_types.as_deref()
163 // Used to get the source of the data, note we don't have as much information for generators
164 // originated from foreign crates
165 fn is_foreign(&self) -> bool {
167 GeneratorData::Local(_) => false,
168 GeneratorData::Foreign(_) => true,
173 // This trait is public to expose the diagnostics methods to clippy.
174 pub trait TypeErrCtxtExt<'tcx> {
175 fn suggest_restricting_param_bound(
177 err: &mut Diagnostic,
178 trait_pred: ty::PolyTraitPredicate<'tcx>,
179 associated_item: Option<(&'static str, Ty<'tcx>)>,
183 fn suggest_dereferences(
185 obligation: &PredicateObligation<'tcx>,
186 err: &mut Diagnostic,
187 trait_pred: ty::PolyTraitPredicate<'tcx>,
190 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol>;
194 obligation: &PredicateObligation<'tcx>,
195 err: &mut Diagnostic,
196 trait_pred: ty::PolyTraitPredicate<'tcx>,
199 fn suggest_add_reference_to_arg(
201 obligation: &PredicateObligation<'tcx>,
202 err: &mut Diagnostic,
203 trait_pred: ty::PolyTraitPredicate<'tcx>,
204 has_custom_message: bool,
207 fn suggest_borrowing_for_object_cast(
209 err: &mut Diagnostic,
210 obligation: &PredicateObligation<'tcx>,
215 fn suggest_remove_reference(
217 obligation: &PredicateObligation<'tcx>,
218 err: &mut Diagnostic,
219 trait_pred: ty::PolyTraitPredicate<'tcx>,
222 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
224 fn suggest_change_mut(
226 obligation: &PredicateObligation<'tcx>,
227 err: &mut Diagnostic,
228 trait_pred: ty::PolyTraitPredicate<'tcx>,
231 fn suggest_semicolon_removal(
233 obligation: &PredicateObligation<'tcx>,
234 err: &mut Diagnostic,
236 trait_pred: ty::PolyTraitPredicate<'tcx>,
239 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
241 fn suggest_impl_trait(
243 err: &mut Diagnostic,
245 obligation: &PredicateObligation<'tcx>,
246 trait_pred: ty::PolyTraitPredicate<'tcx>,
249 fn point_at_returns_when_relevant(
251 err: &mut Diagnostic,
252 obligation: &PredicateObligation<'tcx>,
255 fn report_closure_arg_mismatch(
258 found_span: Option<Span>,
259 found: ty::PolyTraitRef<'tcx>,
260 expected: ty::PolyTraitRef<'tcx>,
261 cause: &ObligationCauseCode<'tcx>,
262 found_node: Option<Node<'_>>,
263 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
265 fn note_conflicting_closure_bounds(
267 cause: &ObligationCauseCode<'tcx>,
268 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
271 fn suggest_fully_qualified_path(
273 err: &mut Diagnostic,
279 fn maybe_note_obligation_cause_for_async_await(
281 err: &mut Diagnostic,
282 obligation: &PredicateObligation<'tcx>,
285 fn note_obligation_cause_for_async_await(
287 err: &mut Diagnostic,
288 interior_or_upvar_span: GeneratorInteriorOrUpvar,
290 outer_generator: Option<DefId>,
291 trait_pred: ty::TraitPredicate<'tcx>,
293 typeck_results: Option<&ty::TypeckResults<'tcx>>,
294 obligation: &PredicateObligation<'tcx>,
295 next_code: Option<&ObligationCauseCode<'tcx>>,
298 fn note_obligation_cause_code<T>(
300 err: &mut Diagnostic,
302 param_env: ty::ParamEnv<'tcx>,
303 cause_code: &ObligationCauseCode<'tcx>,
304 obligated_types: &mut Vec<Ty<'tcx>>,
305 seen_requirements: &mut FxHashSet<DefId>,
307 T: ToPredicate<'tcx>;
309 /// Suggest to await before try: future? => future.await?
310 fn suggest_await_before_try(
312 err: &mut Diagnostic,
313 obligation: &PredicateObligation<'tcx>,
314 trait_pred: ty::PolyTraitPredicate<'tcx>,
318 fn suggest_floating_point_literal(
320 obligation: &PredicateObligation<'tcx>,
321 err: &mut Diagnostic,
322 trait_ref: &ty::PolyTraitRef<'tcx>,
327 obligation: &PredicateObligation<'tcx>,
328 err: &mut Diagnostic,
329 trait_pred: ty::PolyTraitPredicate<'tcx>,
332 fn suggest_dereferencing_index(
334 obligation: &PredicateObligation<'tcx>,
335 err: &mut Diagnostic,
336 trait_pred: ty::PolyTraitPredicate<'tcx>,
338 fn note_function_argument_obligation(
341 err: &mut Diagnostic,
342 parent_code: &ObligationCauseCode<'tcx>,
343 param_env: ty::ParamEnv<'tcx>,
344 predicate: ty::Predicate<'tcx>,
349 expr: &hir::Expr<'_>,
350 typeck_results: &TypeckResults<'tcx>,
351 type_diffs: Vec<TypeError<'tcx>>,
352 param_env: ty::ParamEnv<'tcx>,
353 err: &mut Diagnostic,
355 fn probe_assoc_types_at_expr(
357 type_diffs: &[TypeError<'tcx>],
361 param_env: ty::ParamEnv<'tcx>,
362 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>>;
365 fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
367 generics.tail_span_for_predicate_suggestion(),
368 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
372 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
373 /// it can also be an `impl Trait` param that needs to be decomposed to a type
374 /// param for cleaner code.
375 fn suggest_restriction<'tcx>(
378 hir_generics: &hir::Generics<'tcx>,
380 err: &mut Diagnostic,
381 fn_sig: Option<&hir::FnSig<'_>>,
382 projection: Option<&ty::AliasTy<'_>>,
383 trait_pred: ty::PolyTraitPredicate<'tcx>,
384 // When we are dealing with a trait, `super_traits` will be `Some`:
385 // Given `trait T: A + B + C {}`
386 // - ^^^^^^^^^ GenericBounds
389 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
391 if hir_generics.where_clause_span.from_expansion()
392 || hir_generics.where_clause_span.desugaring_kind().is_some()
396 let Some(item_id) = hir_id.as_owner() else { return; };
397 let generics = tcx.generics_of(item_id);
398 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
399 if let Some((param, bound_str, fn_sig)) =
400 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
401 // Shenanigans to get the `Trait` from the `impl Trait`.
402 ty::Param(param) => {
403 let param_def = generics.type_param(param, tcx);
404 if param_def.kind.is_synthetic() {
406 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
407 return Some((param_def, bound_str, sig));
414 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
415 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
418 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
421 if !trait_pred.is_suggestable(tcx, false) {
424 // We know we have an `impl Trait` that doesn't satisfy a required projection.
426 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
427 // types. There should be at least one, but there might be *more* than one. In that
428 // case we could just ignore it and try to identify which one needs the restriction,
429 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
431 let mut ty_spans = vec![];
432 for input in fn_sig.decl.inputs {
433 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
436 // The type param `T: Trait` we will suggest to introduce.
437 let type_param = format!("{}: {}", type_param_name, bound_str);
440 if let Some(span) = hir_generics.span_for_param_suggestion() {
441 (span, format!(", {}", type_param))
443 (hir_generics.span, format!("<{}>", type_param))
445 // `fn foo(t: impl Trait)`
446 // ^ suggest `where <T as Trait>::A: Bound`
447 predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
449 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
451 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
452 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
453 // `fn foo(t: impl Trait<A: Bound>)` instead.
454 err.multipart_suggestion(
455 "introduce a type parameter with a trait bound instead of using `impl Trait`",
457 Applicability::MaybeIncorrect,
460 if !trait_pred.is_suggestable(tcx, false) {
463 // Trivial case: `T` needs an extra bound: `T: Bound`.
464 let (sp, suggestion) = match (
468 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
471 (_, None) => predicate_constraint(hir_generics, trait_pred.to_predicate(tcx)),
472 (None, Some((ident, []))) => (
473 ident.span.shrink_to_hi(),
474 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
476 (_, Some((_, [.., bounds]))) => (
477 bounds.span().shrink_to_hi(),
478 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
480 (Some(_), Some((_, []))) => (
481 hir_generics.span.shrink_to_hi(),
482 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
486 err.span_suggestion_verbose(
488 &format!("consider further restricting {}", msg),
490 Applicability::MachineApplicable,
495 impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
496 fn suggest_restricting_param_bound(
498 mut err: &mut Diagnostic,
499 trait_pred: ty::PolyTraitPredicate<'tcx>,
500 associated_ty: Option<(&'static str, Ty<'tcx>)>,
503 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
505 let self_ty = trait_pred.skip_binder().self_ty();
506 let (param_ty, projection) = match self_ty.kind() {
507 ty::Param(_) => (true, None),
508 ty::Alias(ty::Projection, projection) => (false, Some(projection)),
512 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
513 // don't suggest `T: Sized + ?Sized`.
514 let mut hir_id = body_id;
515 while let Some(node) = self.tcx.hir().find(hir_id) {
517 hir::Node::Item(hir::Item {
519 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
521 }) if self_ty == self.tcx.types.self_param => {
523 // Restricting `Self` for a single method.
533 Some((ident, bounds)),
538 hir::Node::TraitItem(hir::TraitItem {
540 kind: hir::TraitItemKind::Fn(..),
542 }) if self_ty == self.tcx.types.self_param => {
544 // Restricting `Self` for a single method.
546 self.tcx, hir_id, &generics, "`Self`", err, None, projection, trait_pred,
552 hir::Node::TraitItem(hir::TraitItem {
554 kind: hir::TraitItemKind::Fn(fn_sig, ..),
557 | hir::Node::ImplItem(hir::ImplItem {
559 kind: hir::ImplItemKind::Fn(fn_sig, ..),
562 | hir::Node::Item(hir::Item {
563 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
564 }) if projection.is_some() => {
565 // Missing restriction on associated type of type parameter (unmet projection).
570 "the associated type",
579 hir::Node::Item(hir::Item {
581 hir::ItemKind::Trait(_, _, generics, ..)
582 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
584 }) if projection.is_some() => {
585 // Missing restriction on associated type of type parameter (unmet projection).
590 "the associated type",
600 hir::Node::Item(hir::Item {
602 hir::ItemKind::Struct(_, generics)
603 | hir::ItemKind::Enum(_, generics)
604 | hir::ItemKind::Union(_, generics)
605 | hir::ItemKind::Trait(_, _, generics, ..)
606 | hir::ItemKind::Impl(hir::Impl { generics, .. })
607 | hir::ItemKind::Fn(_, generics, _)
608 | hir::ItemKind::TyAlias(_, generics)
609 | hir::ItemKind::TraitAlias(generics, _)
610 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
613 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
614 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
617 // We skip the 0'th subst (self) because we do not want
618 // to consider the predicate as not suggestible if the
619 // self type is an arg position `impl Trait` -- instead,
620 // we handle that by adding ` + Bound` below.
621 // FIXME(compiler-errors): It would be nice to do the same
622 // this that we do in `suggest_restriction` and pull the
623 // `impl Trait` into a new generic if it shows up somewhere
624 // else in the predicate.
625 if !trait_pred.skip_binder().trait_ref.substs[1..]
627 .all(|g| g.is_suggestable(self.tcx, false))
631 // Missing generic type parameter bound.
632 let param_name = self_ty.to_string();
633 let mut constraint = with_no_trimmed_paths!(
634 trait_pred.print_modifiers_and_trait_path().to_string()
637 if let Some((name, term)) = associated_ty {
638 // FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
639 // That should be extracted into a helper function.
640 if constraint.ends_with('>') {
641 constraint = format!(
643 &constraint[..constraint.len() - 1],
648 constraint.push_str(&format!("<{} = {}>", name, term));
652 if suggest_constraining_type_param(
658 Some(trait_pred.def_id()),
664 hir::Node::Item(hir::Item {
666 hir::ItemKind::Struct(_, generics)
667 | hir::ItemKind::Enum(_, generics)
668 | hir::ItemKind::Union(_, generics)
669 | hir::ItemKind::Trait(_, _, generics, ..)
670 | hir::ItemKind::Impl(hir::Impl { generics, .. })
671 | hir::ItemKind::Fn(_, generics, _)
672 | hir::ItemKind::TyAlias(_, generics)
673 | hir::ItemKind::TraitAlias(generics, _)
674 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
677 // Missing generic type parameter bound.
678 if suggest_arbitrary_trait_bound(
688 hir::Node::Crate(..) => return,
693 hir_id = self.tcx.hir().get_parent_item(hir_id).into();
697 /// When after several dereferencing, the reference satisfies the trait
698 /// binding. This function provides dereference suggestion for this
699 /// specific situation.
700 fn suggest_dereferences(
702 obligation: &PredicateObligation<'tcx>,
703 err: &mut Diagnostic,
704 trait_pred: ty::PolyTraitPredicate<'tcx>,
706 // It only make sense when suggesting dereferences for arguments
707 let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = obligation.cause.code()
708 else { return false; };
709 let Some(typeck_results) = &self.typeck_results
710 else { return false; };
711 let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id)
712 else { return false; };
713 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
714 else { return false; };
716 let span = obligation.cause.span;
717 let mut real_trait_pred = trait_pred;
718 let mut code = obligation.cause.code();
719 while let Some((parent_code, parent_trait_pred)) = code.parent() {
721 if let Some(parent_trait_pred) = parent_trait_pred {
722 real_trait_pred = parent_trait_pred;
725 let real_ty = real_trait_pred.self_ty();
726 // We `erase_late_bound_regions` here because `make_subregion` does not handle
727 // `ReLateBound`, and we don't particularly care about the regions.
729 .can_eq(obligation.param_env, self.tcx.erase_late_bound_regions(real_ty), arg_ty)
735 if let ty::Ref(region, base_ty, mutbl) = *real_ty.skip_binder().kind() {
736 let mut autoderef = Autoderef::new(
738 obligation.param_env,
739 obligation.cause.body_id,
743 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
745 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
747 // Remapping bound vars here
748 let real_trait_pred_and_ty =
749 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
750 let obligation = self.mk_trait_obligation_with_new_self_ty(
751 obligation.param_env,
752 real_trait_pred_and_ty,
754 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
757 // Don't care about `&mut` because `DerefMut` is used less
758 // often and user will not expect autoderef happens.
759 if let Some(hir::Node::Expr(hir::Expr {
761 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr),
763 })) = self.tcx.hir().find(*arg_hir_id)
765 let derefs = "*".repeat(steps);
766 err.span_suggestion_verbose(
767 expr.span.shrink_to_lo(),
768 "consider dereferencing here",
770 Applicability::MachineApplicable,
775 } else if real_trait_pred != trait_pred {
776 // This branch addresses #87437.
778 // Remapping bound vars here
779 let real_trait_pred_and_base_ty =
780 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
781 let obligation = self.mk_trait_obligation_with_new_self_ty(
782 obligation.param_env,
783 real_trait_pred_and_base_ty,
785 if self.predicate_may_hold(&obligation) {
786 let call_node = self.tcx.hir().get(*call_hir_id);
787 let msg = "consider dereferencing here";
788 let is_receiver = matches!(
790 Node::Expr(hir::Expr {
791 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
794 if receiver_expr.hir_id == *arg_hir_id
797 err.multipart_suggestion_verbose(
800 (span.shrink_to_lo(), "(*".to_string()),
801 (span.shrink_to_hi(), ")".to_string()),
803 Applicability::MachineApplicable,
806 err.span_suggestion_verbose(
810 Applicability::MachineApplicable,
821 /// Given a closure's `DefId`, return the given name of the closure.
823 /// This doesn't account for reassignments, but it's only used for suggestions.
824 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<Symbol> {
825 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<Symbol> {
826 // Get the local name of this closure. This can be inaccurate because
827 // of the possibility of reassignment, but this should be good enough.
829 hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, ident, None) => {
839 let hir = self.tcx.hir();
840 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
841 let parent_node = hir.get_parent_node(hir_id);
842 match hir.find(parent_node) {
843 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
844 get_name(err, &local.pat.kind)
846 // Different to previous arm because one is `&hir::Local` and the other
847 // is `P<hir::Local>`.
848 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
853 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
854 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
855 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
858 obligation: &PredicateObligation<'tcx>,
859 err: &mut Diagnostic,
860 trait_pred: ty::PolyTraitPredicate<'tcx>,
862 if let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = obligation.predicate.kind().skip_binder()
863 && Some(trait_pred.def_id()) == self.tcx.lang_items().sized_trait()
865 // Don't suggest calling to turn an unsized type into a sized type
869 // This is duplicated from `extract_callable_info` in typeck, which
870 // relies on autoderef, so we can't use it here.
871 let found = trait_pred.self_ty().skip_binder().peel_refs();
872 let Some((def_id_or_name, output, inputs)) = (match *found.kind()
874 ty::FnPtr(fn_sig) => {
875 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs()))
877 ty::FnDef(def_id, _) => {
878 let fn_sig = found.fn_sig(self.tcx);
879 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
881 ty::Closure(def_id, substs) => {
882 let fn_sig = substs.as_closure().sig();
884 DefIdOrName::DefId(def_id),
886 fn_sig.inputs().map_bound(|inputs| &inputs[1..]),
889 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
890 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
891 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
892 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
893 // args tuple will always be substs[1]
894 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
897 DefIdOrName::DefId(def_id),
898 pred.kind().rebind(proj.term.ty().unwrap()),
899 pred.kind().rebind(args.as_slice()),
906 ty::Dynamic(data, _, ty::Dyn) => {
907 data.iter().find_map(|pred| {
908 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
909 && Some(proj.def_id) == self.tcx.lang_items().fn_once_output()
910 // for existential projection, substs are shifted over by 1
911 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
914 DefIdOrName::Name("trait object"),
915 pred.rebind(proj.term.ty().unwrap()),
916 pred.rebind(args.as_slice()),
924 obligation.param_env.caller_bounds().iter().find_map(|pred| {
925 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
926 && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
927 && proj.projection_ty.self_ty() == found
928 // args tuple will always be substs[1]
929 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
932 DefIdOrName::Name("type parameter"),
933 pred.kind().rebind(proj.term.ty().unwrap()),
934 pred.kind().rebind(args.as_slice()),
942 }) else { return false; };
943 let output = self.replace_bound_vars_with_fresh_vars(
944 obligation.cause.span,
945 LateBoundRegionConversionTime::FnCall,
948 let inputs = inputs.skip_binder().iter().map(|ty| {
949 self.replace_bound_vars_with_fresh_vars(
950 obligation.cause.span,
951 LateBoundRegionConversionTime::FnCall,
956 // Remapping bound vars here
957 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
960 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
961 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
965 // Get the name of the callable and the arguments to be used in the suggestion.
966 let hir = self.tcx.hir();
968 let msg = match def_id_or_name {
969 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
970 DefKind::Ctor(CtorOf::Struct, _) => {
971 "use parentheses to construct this tuple struct".to_string()
973 DefKind::Ctor(CtorOf::Variant, _) => {
974 "use parentheses to construct this tuple variant".to_string()
976 kind => format!("use parentheses to call this {}", kind.descr(def_id)),
978 DefIdOrName::Name(name) => format!("use parentheses to call this {name}"),
983 if ty.is_suggestable(self.tcx, false) {
984 format!("/* {ty} */")
986 "/* value */".to_string()
992 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
993 && obligation.cause.span.can_be_used_for_suggestions()
995 // When the obligation error has been ensured to have been caused by
996 // an argument, the `obligation.cause.span` points at the expression
997 // of the argument, so we can provide a suggestion. Otherwise, we give
998 // a more general note.
999 err.span_suggestion_verbose(
1000 obligation.cause.span.shrink_to_hi(),
1002 format!("({args})"),
1003 Applicability::HasPlaceholders,
1005 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
1006 let name = match hir.get_if_local(def_id) {
1007 Some(hir::Node::Expr(hir::Expr {
1008 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
1011 err.span_label(*fn_decl_span, "consider calling this closure");
1012 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
1017 Some(hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(..), .. })) => {
1018 err.span_label(ident.span, "consider calling this function");
1021 Some(hir::Node::Ctor(..)) => {
1022 let name = self.tcx.def_path_str(def_id);
1024 self.tcx.def_span(def_id),
1025 format!("consider calling the constructor for `{}`", name),
1031 err.help(&format!("{msg}: `{name}({args})`"));
1036 fn suggest_add_reference_to_arg(
1038 obligation: &PredicateObligation<'tcx>,
1039 err: &mut Diagnostic,
1040 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1041 has_custom_message: bool,
1043 let span = obligation.cause.span;
1045 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
1046 obligation.cause.code()
1049 } else if let ObligationCauseCode::ItemObligation(_)
1050 | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1052 obligation.cause.code()
1053 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
1054 span.ctxt().outer_expn_data().kind
1056 obligation.cause.code()
1061 // List of traits for which it would be nonsensical to suggest borrowing.
1062 // For instance, immutable references are always Copy, so suggesting to
1063 // borrow would always succeed, but it's probably not what the user wanted.
1064 let mut never_suggest_borrow: Vec<_> =
1065 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1067 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1070 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1071 never_suggest_borrow.push(def_id);
1074 let param_env = obligation.param_env;
1076 // Try to apply the original trait binding obligation by borrowing.
1077 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1078 blacklist: &[DefId]|
1080 if blacklist.contains(&old_pred.def_id()) {
1083 // We map bounds to `&T` and `&mut T`
1084 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1087 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1090 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1093 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1097 let mk_result = |trait_pred_and_new_ty| {
1099 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1100 self.predicate_must_hold_modulo_regions(&obligation)
1102 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1103 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1105 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1106 if let ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::ExprItemObligation(..) = obligation.cause.code()
1107 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1110 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1111 mutability.is_mut(),
1117 if imm_ref_self_ty_satisfies_pred
1118 || mut_ref_self_ty_satisfies_pred
1119 || ref_inner_ty_satisfies_pred
1121 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1122 // We don't want a borrowing suggestion on the fields in structs,
1125 // the_foos: Vec<Foo>
1129 span.ctxt().outer_expn_data().kind,
1130 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1134 if snippet.starts_with('&') {
1135 // This is already a literal borrow and the obligation is failing
1136 // somewhere else in the obligation chain. Do not suggest non-sense.
1139 // We have a very specific type of error, where just borrowing this argument
1140 // might solve the problem. In cases like this, the important part is the
1141 // original type obligation, not the last one that failed, which is arbitrary.
1142 // Because of this, we modify the error to refer to the original obligation and
1143 // return early in the caller.
1145 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
1146 if has_custom_message {
1150 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
1155 "the trait `{}` is not implemented for `{}`",
1156 old_pred.print_modifiers_and_trait_path(),
1157 old_pred.self_ty().skip_binder(),
1161 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1162 err.span_suggestions(
1163 span.shrink_to_lo(),
1164 "consider borrowing here",
1165 ["&".to_string(), "&mut ".to_string()],
1166 Applicability::MaybeIncorrect,
1169 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1170 err.span_suggestion_verbose(
1171 span.shrink_to_lo(),
1173 "consider{} borrowing here",
1174 if is_mut { " mutably" } else { "" }
1176 format!("&{}", if is_mut { "mut " } else { "" }),
1177 Applicability::MaybeIncorrect,
1186 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
1187 try_borrowing(cause.derived.parent_trait_pred, &[])
1188 } else if let ObligationCauseCode::BindingObligation(_, _)
1189 | ObligationCauseCode::ItemObligation(_)
1190 | ObligationCauseCode::ExprItemObligation(..)
1191 | ObligationCauseCode::ExprBindingObligation(..) = code
1193 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1199 // Suggest borrowing the type
1200 fn suggest_borrowing_for_object_cast(
1202 err: &mut Diagnostic,
1203 obligation: &PredicateObligation<'tcx>,
1205 object_ty: Ty<'tcx>,
1207 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; };
1208 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
1210 for predicate in predicates.iter() {
1211 if !self.predicate_must_hold_modulo_regions(
1212 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1218 err.span_suggestion(
1219 obligation.cause.span.shrink_to_lo(),
1221 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
1224 Applicability::MaybeIncorrect,
1228 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1229 /// suggest removing these references until we reach a type that implements the trait.
1230 fn suggest_remove_reference(
1232 obligation: &PredicateObligation<'tcx>,
1233 err: &mut Diagnostic,
1234 trait_pred: ty::PolyTraitPredicate<'tcx>,
1236 let span = obligation.cause.span;
1238 let mut suggested = false;
1239 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1241 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1242 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1243 // Do not suggest removal of borrow from type arguments.
1247 // Skipping binder here, remapping below
1248 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1250 for refs_remaining in 0..refs_number {
1251 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1254 suggested_ty = *inner_ty;
1256 // Remapping bound vars here
1257 let trait_pred_and_suggested_ty =
1258 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1260 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1261 obligation.param_env,
1262 trait_pred_and_suggested_ty,
1265 if self.predicate_may_hold(&new_obligation) {
1270 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1272 let remove_refs = refs_remaining + 1;
1274 let msg = if remove_refs == 1 {
1275 "consider removing the leading `&`-reference".to_string()
1277 format!("consider removing {} leading `&`-references", remove_refs)
1280 err.span_suggestion_short(sp, &msg, "", Applicability::MachineApplicable);
1289 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1290 let span = obligation.cause.span;
1292 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1293 let hir = self.tcx.hir();
1294 if let Some(hir::Node::Expr(expr)) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1295 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1296 // and if not maybe suggest doing something else? If we kept the expression around we
1297 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1298 // it is from the local crate.
1299 err.span_suggestion(
1301 "remove the `.await`",
1303 Applicability::MachineApplicable,
1305 // FIXME: account for associated `async fn`s.
1306 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1307 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) =
1308 obligation.predicate.kind().skip_binder()
1310 err.span_label(*span, &format!("this call returns `{}`", pred.self_ty()));
1312 if let Some(typeck_results) = &self.typeck_results
1313 && let ty = typeck_results.expr_ty_adjusted(base)
1314 && let ty::FnDef(def_id, _substs) = ty.kind()
1315 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1316 hir.get_if_local(*def_id)
1319 "alternatively, consider making `fn {}` asynchronous",
1322 if vis_span.is_empty() {
1323 err.span_suggestion_verbose(
1324 span.shrink_to_lo(),
1327 Applicability::MaybeIncorrect,
1330 err.span_suggestion_verbose(
1331 vis_span.shrink_to_hi(),
1334 Applicability::MaybeIncorrect,
1343 /// Check if the trait bound is implemented for a different mutability and note it in the
1345 fn suggest_change_mut(
1347 obligation: &PredicateObligation<'tcx>,
1348 err: &mut Diagnostic,
1349 trait_pred: ty::PolyTraitPredicate<'tcx>,
1351 let points_at_arg = matches!(
1352 obligation.cause.code(),
1353 ObligationCauseCode::FunctionArgumentObligation { .. },
1356 let span = obligation.cause.span;
1357 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1359 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1360 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1361 // Do not suggest removal of borrow from type arguments.
1364 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1365 if trait_pred.has_non_region_infer() {
1366 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1367 // unresolved bindings.
1371 // Skipping binder here, remapping below
1372 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1374 let suggested_ty = match mutability {
1375 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1376 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1379 // Remapping bound vars here
1380 let trait_pred_and_suggested_ty =
1381 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1383 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1384 obligation.param_env,
1385 trait_pred_and_suggested_ty,
1387 let suggested_ty_would_satisfy_obligation = self
1388 .evaluate_obligation_no_overflow(&new_obligation)
1389 .must_apply_modulo_regions();
1390 if suggested_ty_would_satisfy_obligation {
1395 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1396 if points_at_arg && mutability.is_not() && refs_number > 0 {
1397 err.span_suggestion_verbose(
1399 "consider changing this borrow's mutability",
1401 Applicability::MachineApplicable,
1405 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1406 trait_pred.print_modifiers_and_trait_path(),
1408 trait_pred.skip_binder().self_ty(),
1416 fn suggest_semicolon_removal(
1418 obligation: &PredicateObligation<'tcx>,
1419 err: &mut Diagnostic,
1421 trait_pred: ty::PolyTraitPredicate<'tcx>,
1423 let hir = self.tcx.hir();
1424 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1425 let node = hir.find(parent_node);
1426 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1427 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1428 && sig.decl.output.span().overlaps(span)
1429 && blk.expr.is_none()
1430 && trait_pred.self_ty().skip_binder().is_unit()
1431 && let Some(stmt) = blk.stmts.last()
1432 && let hir::StmtKind::Semi(expr) = stmt.kind
1433 // Only suggest this if the expression behind the semicolon implements the predicate
1434 && let Some(typeck_results) = &self.typeck_results
1435 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1436 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1437 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1443 "this expression has type `{}`, which implements `{}`",
1445 trait_pred.print_modifiers_and_trait_path()
1448 err.span_suggestion(
1449 self.tcx.sess.source_map().end_point(stmt.span),
1450 "remove this semicolon",
1452 Applicability::MachineApplicable
1459 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1460 let hir = self.tcx.hir();
1461 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1462 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1466 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1469 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1470 /// applicable and signal that the error has been expanded appropriately and needs to be
1472 fn suggest_impl_trait(
1474 err: &mut Diagnostic,
1476 obligation: &PredicateObligation<'tcx>,
1477 trait_pred: ty::PolyTraitPredicate<'tcx>,
1479 match obligation.cause.code().peel_derives() {
1480 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1481 ObligationCauseCode::SizedReturnType => {}
1485 let hir = self.tcx.hir();
1486 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1487 let node = hir.find(fn_hir_id);
1488 let Some(hir::Node::Item(hir::Item {
1489 kind: hir::ItemKind::Fn(sig, _, body_id),
1495 let body = hir.body(*body_id);
1496 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1497 let ty = trait_pred.skip_binder().self_ty();
1498 let is_object_safe = match ty.kind() {
1499 ty::Dynamic(predicates, _, ty::Dyn) => {
1500 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1503 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1505 // We only want to suggest `impl Trait` to `dyn Trait`s.
1506 // For example, `fn foo() -> str` needs to be filtered out.
1510 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1514 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1515 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1516 // Recursively look for `TraitObject` types and if there's only one, use that span to
1517 // suggest `impl Trait`.
1519 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1520 // otherwise suggest using `Box<dyn Trait>` or an enum.
1521 let mut visitor = ReturnsVisitor::default();
1522 visitor.visit_body(&body);
1524 let typeck_results = self.typeck_results.as_ref().unwrap();
1525 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; };
1527 let ret_types = visitor
1530 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1531 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1532 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1534 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1536 let ty = self.resolve_vars_if_possible(ty);
1538 !matches!(ty.kind(), ty::Error(_))
1539 && last_ty.map_or(true, |last_ty| {
1540 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1541 // *after* in the dependency graph.
1542 match (ty.kind(), last_ty.kind()) {
1543 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1544 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1545 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1547 Infer(InferTy::FreshFloatTy(_)),
1548 Infer(InferTy::FreshFloatTy(_)),
1553 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1556 let mut spans_and_needs_box = vec![];
1558 match liberated_sig.output().kind() {
1559 ty::Dynamic(predicates, _, ty::Dyn) => {
1560 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1561 let param_env = ty::ParamEnv::empty();
1563 if !only_never_return {
1564 for (expr_span, return_ty) in ret_types {
1565 let self_ty_satisfies_dyn_predicates = |self_ty| {
1566 predicates.iter().all(|predicate| {
1567 let pred = predicate.with_self_ty(self.tcx, self_ty);
1568 let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred);
1569 self.predicate_may_hold(&obl)
1573 if let ty::Adt(def, substs) = return_ty.kind()
1575 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1577 spans_and_needs_box.push((expr_span, false));
1578 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1579 spans_and_needs_box.push((expr_span, true));
1589 let sm = self.tcx.sess.source_map();
1590 if !ret_ty.span.overlaps(span) {
1593 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1594 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1600 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1601 let name = liberated_sig.output().to_string();
1603 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1604 if !name.starts_with("dyn ") {
1610 err.code(error_code!(E0746));
1611 err.set_primary_message("return type cannot have an unboxed trait object");
1612 err.children.clear();
1613 let impl_trait_msg = "for information on `impl Trait`, see \
1614 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1615 #returning-types-that-implement-traits>";
1616 let trait_obj_msg = "for information on trait objects, see \
1617 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1618 #using-trait-objects-that-allow-for-values-of-different-types>";
1620 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1621 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1622 if only_never_return {
1623 // No return paths, probably using `panic!()` or similar.
1624 // Suggest `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1625 suggest_trait_object_return_type_alternatives(
1631 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1632 // Suggest `-> impl Trait`.
1633 err.span_suggestion(
1636 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1637 which implements `{1}`",
1640 format!("impl {}", trait_obj),
1641 Applicability::MachineApplicable,
1643 err.note(impl_trait_msg);
1646 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1647 err.multipart_suggestion(
1648 "return a boxed trait object instead",
1650 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1651 (span.shrink_to_hi(), ">".to_string()),
1653 Applicability::MaybeIncorrect,
1655 for (span, needs_box) in spans_and_needs_box {
1657 err.multipart_suggestion(
1658 "... and box this value",
1660 (span.shrink_to_lo(), "Box::new(".to_string()),
1661 (span.shrink_to_hi(), ")".to_string()),
1663 Applicability::MaybeIncorrect,
1668 // This is currently not possible to trigger because E0038 takes precedence, but
1669 // leave it in for completeness in case anything changes in an earlier stage.
1671 "if trait `{}` were object-safe, you could return a trait object",
1675 err.note(trait_obj_msg);
1677 "if all the returned values were of the same type you could use `impl {}` as the \
1681 err.note(impl_trait_msg);
1682 err.note("you can create a new `enum` with a variant for each returned type");
1687 fn point_at_returns_when_relevant(
1689 err: &mut Diagnostic,
1690 obligation: &PredicateObligation<'tcx>,
1692 match obligation.cause.code().peel_derives() {
1693 ObligationCauseCode::SizedReturnType => {}
1697 let hir = self.tcx.hir();
1698 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1699 let node = hir.find(parent_node);
1700 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1703 let body = hir.body(*body_id);
1704 // Point at all the `return`s in the function as they have failed trait bounds.
1705 let mut visitor = ReturnsVisitor::default();
1706 visitor.visit_body(&body);
1707 let typeck_results = self.typeck_results.as_ref().unwrap();
1708 for expr in &visitor.returns {
1709 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1710 let ty = self.resolve_vars_if_possible(returned_ty);
1711 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1717 fn report_closure_arg_mismatch(
1720 found_span: Option<Span>,
1721 found: ty::PolyTraitRef<'tcx>,
1722 expected: ty::PolyTraitRef<'tcx>,
1723 cause: &ObligationCauseCode<'tcx>,
1724 found_node: Option<Node<'_>>,
1725 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1726 pub(crate) fn build_fn_sig_ty<'tcx>(
1727 infcx: &InferCtxt<'tcx>,
1728 trait_ref: ty::PolyTraitRef<'tcx>,
1730 let inputs = trait_ref.skip_binder().substs.type_at(1);
1731 let sig = match inputs.kind() {
1732 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => {
1733 infcx.tcx.mk_fn_sig(
1735 infcx.next_ty_var(TypeVariableOrigin {
1737 kind: TypeVariableOriginKind::MiscVariable,
1740 hir::Unsafety::Normal,
1744 _ => infcx.tcx.mk_fn_sig(
1745 std::iter::once(inputs),
1746 infcx.next_ty_var(TypeVariableOrigin {
1748 kind: TypeVariableOriginKind::MiscVariable,
1751 hir::Unsafety::Normal,
1756 infcx.tcx.mk_fn_ptr(trait_ref.rebind(sig))
1759 let argument_kind = match expected.skip_binder().self_ty().kind() {
1760 ty::Closure(..) => "closure",
1761 ty::Generator(..) => "generator",
1764 let mut err = struct_span_err!(
1768 "type mismatch in {argument_kind} arguments",
1771 err.span_label(span, "expected due to this");
1773 let found_span = found_span.unwrap_or(span);
1774 err.span_label(found_span, "found signature defined here");
1776 let expected = build_fn_sig_ty(self, expected);
1777 let found = build_fn_sig_ty(self, found);
1779 let (expected_str, found_str) = self.cmp(expected, found);
1781 let signature_kind = format!("{argument_kind} signature");
1782 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1784 self.note_conflicting_closure_bounds(cause, &mut err);
1786 if let Some(found_node) = found_node {
1787 hint_missing_borrow(span, found, expected, found_node, &mut err);
1793 // Add a note if there are two `Fn`-family bounds that have conflicting argument
1794 // requirements, which will always cause a closure to have a type error.
1795 fn note_conflicting_closure_bounds(
1797 cause: &ObligationCauseCode<'tcx>,
1798 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1800 // First, look for an `ExprBindingObligation`, which means we can get
1801 // the unsubstituted predicate list of the called function. And check
1802 // that the predicate that we failed to satisfy is a `Fn`-like trait.
1803 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = cause
1804 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
1805 && let Some(pred) = predicates.predicates.get(*idx)
1806 && let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder()
1807 && self.tcx.is_fn_trait(trait_pred.def_id())
1810 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
1811 let expected_substs = self
1813 .anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.substs));
1815 // Find another predicate whose self-type is equal to the expected self type,
1816 // but whose substs don't match.
1817 let other_pred = std::iter::zip(&predicates.predicates, &predicates.spans)
1819 .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() {
1820 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
1821 if self.tcx.is_fn_trait(trait_pred.def_id())
1823 // Make sure that the self type matches
1824 // (i.e. constraining this closure)
1826 == self.tcx.anonymize_bound_vars(
1827 pred.kind().rebind(trait_pred.self_ty()),
1829 // But the substs don't match (i.e. incompatible args)
1831 != self.tcx.anonymize_bound_vars(
1832 pred.kind().rebind(trait_pred.trait_ref.substs),
1839 // If we found one, then it's very likely the cause of the error.
1840 if let Some((_, (_, other_pred_span))) = other_pred {
1843 "closure inferred to have a different signature due to this bound",
1849 fn suggest_fully_qualified_path(
1851 err: &mut Diagnostic,
1856 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1857 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1859 "{}s cannot be accessed directly on a `trait`, they can only be \
1860 accessed through a specific `impl`",
1861 assoc_item.kind.as_def_kind().descr(item_def_id)
1863 err.span_suggestion(
1865 "use the fully qualified path to an implementation",
1866 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1867 Applicability::HasPlaceholders,
1873 /// Adds an async-await specific note to the diagnostic when the future does not implement
1874 /// an auto trait because of a captured type.
1877 /// note: future does not implement `Qux` as this value is used across an await
1878 /// --> $DIR/issue-64130-3-other.rs:17:5
1880 /// LL | let x = Foo;
1881 /// | - has type `Foo`
1882 /// LL | baz().await;
1883 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1885 /// | - `x` is later dropped here
1888 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1889 /// is "replaced" with a different message and a more specific error.
1892 /// error: future cannot be sent between threads safely
1893 /// --> $DIR/issue-64130-2-send.rs:21:5
1895 /// LL | fn is_send<T: Send>(t: T) { }
1896 /// | ---- required by this bound in `is_send`
1898 /// LL | is_send(bar());
1899 /// | ^^^^^^^ future returned by `bar` is not send
1901 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1902 /// implemented for `Foo`
1903 /// note: future is not send as this value is used across an await
1904 /// --> $DIR/issue-64130-2-send.rs:15:5
1906 /// LL | let x = Foo;
1907 /// | - has type `Foo`
1908 /// LL | baz().await;
1909 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1911 /// | - `x` is later dropped here
1914 /// Returns `true` if an async-await specific note was added to the diagnostic.
1915 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
1916 fn maybe_note_obligation_cause_for_async_await(
1918 err: &mut Diagnostic,
1919 obligation: &PredicateObligation<'tcx>,
1921 let hir = self.tcx.hir();
1923 // Attempt to detect an async-await error by looking at the obligation causes, looking
1924 // for a generator to be present.
1926 // When a future does not implement a trait because of a captured type in one of the
1927 // generators somewhere in the call stack, then the result is a chain of obligations.
1929 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1930 // future is passed as an argument to a function C which requires a `Send` type, then the
1931 // chain looks something like this:
1933 // - `BuiltinDerivedObligation` with a generator witness (B)
1934 // - `BuiltinDerivedObligation` with a generator (B)
1935 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1936 // - `BuiltinDerivedObligation` with a generator witness (A)
1937 // - `BuiltinDerivedObligation` with a generator (A)
1938 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1939 // - `BindingObligation` with `impl_send (Send requirement)
1941 // The first obligation in the chain is the most useful and has the generator that captured
1942 // the type. The last generator (`outer_generator` below) has information about where the
1943 // bound was introduced. At least one generator should be present for this diagnostic to be
1945 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1946 ty::PredicateKind::Clause(ty::Clause::Trait(p)) => (Some(p), Some(p.self_ty())),
1949 let mut generator = None;
1950 let mut outer_generator = None;
1951 let mut next_code = Some(obligation.cause.code());
1953 let mut seen_upvar_tys_infer_tuple = false;
1955 while let Some(code) = next_code {
1958 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1959 next_code = Some(parent_code);
1961 ObligationCauseCode::ImplDerivedObligation(cause) => {
1962 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1964 parent_trait_ref = ?cause.derived.parent_trait_pred,
1965 self_ty.kind = ?ty.kind(),
1970 ty::Generator(did, ..) => {
1971 generator = generator.or(Some(did));
1972 outer_generator = Some(did);
1974 ty::GeneratorWitness(..) => {}
1975 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1976 // By introducing a tuple of upvar types into the chain of obligations
1977 // of a generator, the first non-generator item is now the tuple itself,
1978 // we shall ignore this.
1980 seen_upvar_tys_infer_tuple = true;
1982 _ if generator.is_none() => {
1983 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1984 target_ty = Some(ty);
1989 next_code = Some(&cause.derived.parent_code);
1991 ObligationCauseCode::DerivedObligation(derived_obligation)
1992 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1993 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1995 parent_trait_ref = ?derived_obligation.parent_trait_pred,
1996 self_ty.kind = ?ty.kind(),
2000 ty::Generator(did, ..) => {
2001 generator = generator.or(Some(did));
2002 outer_generator = Some(did);
2004 ty::GeneratorWitness(..) => {}
2005 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2006 // By introducing a tuple of upvar types into the chain of obligations
2007 // of a generator, the first non-generator item is now the tuple itself,
2008 // we shall ignore this.
2010 seen_upvar_tys_infer_tuple = true;
2012 _ if generator.is_none() => {
2013 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2014 target_ty = Some(ty);
2019 next_code = Some(&derived_obligation.parent_code);
2025 // Only continue if a generator was found.
2026 debug!(?generator, ?trait_ref, ?target_ty);
2027 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
2031 let span = self.tcx.def_span(generator_did);
2033 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
2036 ?generator_did_root,
2037 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2041 let generator_body = generator_did
2043 .and_then(|def_id| hir.maybe_body_owned_by(def_id))
2044 .map(|body_id| hir.body(body_id));
2045 let mut visitor = AwaitsVisitor::default();
2046 if let Some(body) = generator_body {
2047 visitor.visit_body(body);
2049 debug!(awaits = ?visitor.awaits);
2051 // Look for a type inside the generator interior that matches the target type to get
2053 let target_ty_erased = self.tcx.erase_regions(target_ty);
2054 let ty_matches = |ty| -> bool {
2055 // Careful: the regions for types that appear in the
2056 // generator interior are not generally known, so we
2057 // want to erase them when comparing (and anyway,
2058 // `Send` and other bounds are generally unaffected by
2059 // the choice of region). When erasing regions, we
2060 // also have to erase late-bound regions. This is
2061 // because the types that appear in the generator
2062 // interior generally contain "bound regions" to
2063 // represent regions that are part of the suspended
2064 // generator frame. Bound regions are preserved by
2065 // `erase_regions` and so we must also call
2066 // `erase_late_bound_regions`.
2067 let ty_erased = self.tcx.erase_late_bound_regions(ty);
2068 let ty_erased = self.tcx.erase_regions(ty_erased);
2069 let eq = ty_erased == target_ty_erased;
2070 debug!(?ty_erased, ?target_ty_erased, ?eq);
2074 // Get the typeck results from the infcx if the generator is the function we are currently
2075 // type-checking; otherwise, get them by performing a query. This is needed to avoid
2076 // cycles. If we can't use resolved types because the generator comes from another crate,
2077 // we still provide a targeted error but without all the relevant spans.
2078 let generator_data = match &self.typeck_results {
2079 Some(t) if t.hir_owner.to_def_id() == generator_did_root => GeneratorData::Local(&t),
2080 _ if generator_did.is_local() => {
2081 GeneratorData::Local(self.tcx.typeck(generator_did.expect_local()))
2083 _ if let Some(generator_diag_data) = self.tcx.generator_diagnostic_data(generator_did) => {
2084 GeneratorData::Foreign(generator_diag_data)
2089 let mut interior_or_upvar_span = None;
2091 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
2092 debug!(?from_awaited_ty);
2094 // The generator interior types share the same binders
2095 if let Some(cause) =
2096 generator_data.get_generator_interior_types().skip_binder().iter().find(
2097 |ty::GeneratorInteriorTypeCause { ty, .. }| {
2098 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
2102 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
2104 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(
2106 Some((*scope_span, *yield_span, *expr, from_awaited_ty)),
2110 if interior_or_upvar_span.is_none() {
2111 interior_or_upvar_span =
2112 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
2115 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
2116 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span, None));
2119 debug!(?interior_or_upvar_span);
2120 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2121 let is_async = self.tcx.generator_is_async(generator_did);
2122 let typeck_results = match generator_data {
2123 GeneratorData::Local(typeck_results) => Some(typeck_results),
2124 GeneratorData::Foreign(_) => None,
2126 self.note_obligation_cause_for_async_await(
2128 interior_or_upvar_span,
2143 /// Unconditionally adds the diagnostic note described in
2144 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
2145 #[instrument(level = "debug", skip_all)]
2146 fn note_obligation_cause_for_async_await(
2148 err: &mut Diagnostic,
2149 interior_or_upvar_span: GeneratorInteriorOrUpvar,
2151 outer_generator: Option<DefId>,
2152 trait_pred: ty::TraitPredicate<'tcx>,
2153 target_ty: Ty<'tcx>,
2154 typeck_results: Option<&ty::TypeckResults<'tcx>>,
2155 obligation: &PredicateObligation<'tcx>,
2156 next_code: Option<&ObligationCauseCode<'tcx>>,
2158 let source_map = self.tcx.sess.source_map();
2160 let (await_or_yield, an_await_or_yield) =
2161 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2162 let future_or_generator = if is_async { "future" } else { "generator" };
2164 // Special case the primary error message when send or sync is the trait that was
2166 let hir = self.tcx.hir();
2167 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2168 self.tcx.get_diagnostic_name(trait_pred.def_id())
2170 let (trait_name, trait_verb) =
2171 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2174 err.set_primary_message(format!(
2175 "{} cannot be {} between threads safely",
2176 future_or_generator, trait_verb
2179 let original_span = err.span.primary_span().unwrap();
2180 let mut span = MultiSpan::from_span(original_span);
2182 let message = outer_generator
2183 .and_then(|generator_did| {
2184 Some(match self.tcx.generator_kind(generator_did).unwrap() {
2185 GeneratorKind::Gen => format!("generator is not {}", trait_name),
2186 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
2188 .parent(generator_did)
2190 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
2191 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2193 format!("future returned by `{}` is not {}", name, trait_name)
2195 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
2196 format!("future created by async block is not {}", trait_name)
2198 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
2199 format!("future created by async closure is not {}", trait_name)
2203 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
2205 span.push_span_label(original_span, message);
2208 format!("is not {}", trait_name)
2210 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2213 let mut explain_yield =
2214 |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
2215 let mut span = MultiSpan::from_span(yield_span);
2216 let snippet = match source_map.span_to_snippet(interior_span) {
2217 // #70935: If snippet contains newlines, display "the value" instead
2218 // so that we do not emit complex diagnostics.
2219 Ok(snippet) if !snippet.contains('\n') => format!("`{}`", snippet),
2220 _ => "the value".to_string(),
2222 // note: future is not `Send` as this value is used across an await
2223 // --> $DIR/issue-70935-complex-spans.rs:13:9
2225 // LL | baz(|| async {
2226 // | ______________-
2229 // LL | | foo(tx.clone());
2231 // | | - ^^^^^^ await occurs here, with value maybe used later
2233 // | has type `closure` which is not `Send`
2234 // note: value is later dropped here
2238 span.push_span_label(
2240 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
2242 span.push_span_label(
2244 format!("has type `{}` which {}", target_ty, trait_explanation),
2246 if let Some(scope_span) = scope_span {
2247 let scope_span = source_map.end_point(scope_span);
2249 let msg = format!("{} is later dropped here", snippet);
2250 span.push_span_label(scope_span, msg);
2255 "{} {} as this value is used across {}",
2256 future_or_generator, trait_explanation, an_await_or_yield
2260 match interior_or_upvar_span {
2261 GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2262 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2263 if let Some(await_span) = from_awaited_ty {
2264 // The type causing this obligation is one being awaited at await_span.
2265 let mut span = MultiSpan::from_span(await_span);
2266 span.push_span_label(
2269 "await occurs here on type `{}`, which {}",
2270 target_ty, trait_explanation
2276 "future {not_trait} as it awaits another future which {not_trait}",
2277 not_trait = trait_explanation
2281 // Look at the last interior type to get a span for the `.await`.
2283 generator_interior_types = ?format_args!(
2284 "{:#?}", typeck_results.as_ref().map(|t| &t.generator_interior_types)
2287 explain_yield(interior_span, yield_span, scope_span);
2290 if let Some(expr_id) = expr {
2291 let expr = hir.expect_expr(expr_id);
2292 debug!("target_ty evaluated from {:?}", expr);
2294 let parent = hir.get_parent_node(expr_id);
2295 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2296 let parent_span = hir.span(parent);
2297 let parent_did = parent.owner.to_def_id();
2300 // fn foo(&self) -> i32 {}
2303 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2306 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2308 .expr_adjustments(expr)
2310 .any(|adj| adj.is_region_borrow())
2316 // struct Foo(*const u8);
2317 // bar(Foo(std::ptr::null())).await;
2318 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2320 debug!(parent_def_kind = ?self.tcx.def_kind(parent_did));
2321 let is_raw_borrow_inside_fn_like_call =
2322 match self.tcx.def_kind(parent_did) {
2323 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2326 if let Some(typeck_results) = typeck_results {
2327 if (typeck_results.is_method_call(e) && is_region_borrow)
2328 || is_raw_borrow_inside_fn_like_call
2332 "consider moving this into a `let` \
2333 binding to create a shorter lived borrow",
2341 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2342 // `Some((ref_ty, is_mut))` if `target_ty` is `&T` or `&mut T` and fails to impl `Send`
2343 let non_send = match target_ty.kind() {
2344 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(&obligation) {
2345 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2351 let (span_label, span_note) = match non_send {
2352 // if `target_ty` is `&T` or `&mut T` and fails to impl `Send`,
2353 // include suggestions to make `T: Sync` so that `&T: Send`,
2354 // or to make `T: Send` so that `&mut T: Send`
2355 Some((ref_ty, is_mut)) => {
2356 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2357 let ref_kind = if is_mut { "&mut" } else { "&" };
2360 "has type `{}` which {}, because `{}` is not `{}`",
2361 target_ty, trait_explanation, ref_ty, ref_ty_trait
2364 "captured value {} because `{}` references cannot be sent unless their referent is `{}`",
2365 trait_explanation, ref_kind, ref_ty_trait
2370 format!("has type `{}` which {}", target_ty, trait_explanation),
2371 format!("captured value {}", trait_explanation),
2375 let mut span = MultiSpan::from_span(upvar_span);
2376 span.push_span_label(upvar_span, span_label);
2377 err.span_note(span, &span_note);
2381 // Add a note for the item obligation that remains - normally a note pointing to the
2382 // bound that introduced the obligation (e.g. `T: Send`).
2384 self.note_obligation_cause_code(
2386 obligation.predicate,
2387 obligation.param_env,
2390 &mut Default::default(),
2394 fn note_obligation_cause_code<T>(
2396 err: &mut Diagnostic,
2398 param_env: ty::ParamEnv<'tcx>,
2399 cause_code: &ObligationCauseCode<'tcx>,
2400 obligated_types: &mut Vec<Ty<'tcx>>,
2401 seen_requirements: &mut FxHashSet<DefId>,
2403 T: ToPredicate<'tcx>,
2406 let predicate = predicate.to_predicate(tcx);
2408 ObligationCauseCode::ExprAssignable
2409 | ObligationCauseCode::MatchExpressionArm { .. }
2410 | ObligationCauseCode::Pattern { .. }
2411 | ObligationCauseCode::IfExpression { .. }
2412 | ObligationCauseCode::IfExpressionWithNoElse
2413 | ObligationCauseCode::MainFunctionType
2414 | ObligationCauseCode::StartFunctionType
2415 | ObligationCauseCode::IntrinsicType
2416 | ObligationCauseCode::MethodReceiver
2417 | ObligationCauseCode::ReturnNoExpression
2418 | ObligationCauseCode::UnifyReceiver(..)
2419 | ObligationCauseCode::OpaqueType
2420 | ObligationCauseCode::MiscObligation
2421 | ObligationCauseCode::WellFormed(..)
2422 | ObligationCauseCode::MatchImpl(..)
2423 | ObligationCauseCode::ReturnType
2424 | ObligationCauseCode::ReturnValue(_)
2425 | ObligationCauseCode::BlockTailExpression(_)
2426 | ObligationCauseCode::AwaitableExpr(_)
2427 | ObligationCauseCode::ForLoopIterator
2428 | ObligationCauseCode::QuestionMark
2429 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2430 | ObligationCauseCode::LetElse
2431 | ObligationCauseCode::BinOp { .. }
2432 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2433 | ObligationCauseCode::RustCall => {}
2434 ObligationCauseCode::SliceOrArrayElem => {
2435 err.note("slice and array elements must have `Sized` type");
2437 ObligationCauseCode::TupleElem => {
2438 err.note("only the last element of a tuple may have a dynamically sized type");
2440 ObligationCauseCode::ProjectionWf(data) => {
2441 err.note(&format!("required so that the projection `{data}` is well-formed"));
2443 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2445 "required so that reference `{ref_ty}` does not outlive its referent"
2448 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2450 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2454 ObligationCauseCode::ItemObligation(_)
2455 | ObligationCauseCode::ExprItemObligation(..) => {
2456 // We hold the `DefId` of the item introducing the obligation, but displaying it
2457 // doesn't add user usable information. It always point at an associated item.
2459 ObligationCauseCode::BindingObligation(item_def_id, span)
2460 | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
2461 let item_name = tcx.def_path_str(item_def_id);
2462 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2463 let mut multispan = MultiSpan::from(span);
2464 let sm = tcx.sess.source_map();
2465 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2467 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2468 (Ok(l), Ok(r)) => l.line == r.line,
2471 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2472 multispan.push_span_label(ident.span, "required by a bound in this");
2475 let descr = format!("required by a bound in `{item_name}`");
2476 if span.is_visible(sm) {
2477 let msg = format!("required by this bound in `{short_item_name}`");
2478 multispan.push_span_label(span, msg);
2479 err.span_note(multispan, &descr);
2481 err.span_note(tcx.def_span(item_def_id), &descr);
2484 ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
2486 "required for the cast from `{}` to the object type `{}`",
2487 self.ty_to_string(concrete_ty),
2488 self.ty_to_string(object_ty)
2491 ObligationCauseCode::Coercion { source: _, target } => {
2492 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2494 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2496 "the `Copy` trait is required because this value will be copied for each element of the array",
2501 "consider creating a new `const` item and initializing it with the result \
2502 of the function call to be used in the repeat position, like \
2503 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2507 if self.tcx.sess.is_nightly_build() && is_const_fn {
2509 "create an inline `const` block, see RFC #2920 \
2510 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2514 ObligationCauseCode::VariableType(hir_id) => {
2515 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2516 match self.tcx.hir().find(parent_node) {
2517 Some(Node::Local(hir::Local { ty: Some(ty), .. })) => {
2518 err.span_suggestion_verbose(
2519 ty.span.shrink_to_lo(),
2520 "consider borrowing here",
2522 Applicability::MachineApplicable,
2524 err.note("all local variables must have a statically known size");
2526 Some(Node::Local(hir::Local {
2527 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2530 // When encountering an assignment of an unsized trait, like
2531 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2532 // order to use have a slice instead.
2533 err.span_suggestion_verbose(
2534 span.shrink_to_lo(),
2535 "consider borrowing here",
2537 Applicability::MachineApplicable,
2539 err.note("all local variables must have a statically known size");
2541 Some(Node::Param(param)) => {
2542 err.span_suggestion_verbose(
2543 param.ty_span.shrink_to_lo(),
2544 "function arguments must have a statically known size, borrowed types \
2545 always have a known size",
2547 Applicability::MachineApplicable,
2551 err.note("all local variables must have a statically known size");
2554 if !self.tcx.features().unsized_locals {
2555 err.help("unsized locals are gated as an unstable feature");
2558 ObligationCauseCode::SizedArgumentType(sp) => {
2559 if let Some(span) = sp {
2560 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder()
2561 && let ty::Clause::Trait(trait_pred) = clause
2562 && let ty::Dynamic(..) = trait_pred.self_ty().kind()
2564 let span = if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2565 && snippet.starts_with("dyn ")
2567 let pos = snippet.len() - snippet[3..].trim_start().len();
2568 span.with_hi(span.lo() + BytePos(pos as u32))
2572 err.span_suggestion_verbose(
2574 "you can use `impl Trait` as the argument type",
2575 "impl ".to_string(),
2576 Applicability::MaybeIncorrect,
2579 err.span_suggestion_verbose(
2580 span.shrink_to_lo(),
2581 "function arguments must have a statically known size, borrowed types \
2582 always have a known size",
2584 Applicability::MachineApplicable,
2587 err.note("all function arguments must have a statically known size");
2589 if tcx.sess.opts.unstable_features.is_nightly_build()
2590 && !self.tcx.features().unsized_fn_params
2592 err.help("unsized fn params are gated as an unstable feature");
2595 ObligationCauseCode::SizedReturnType => {
2596 err.note("the return type of a function must have a statically known size");
2598 ObligationCauseCode::SizedYieldType => {
2599 err.note("the yield type of a generator must have a statically known size");
2601 ObligationCauseCode::SizedBoxType => {
2602 err.note("the type of a box expression must have a statically known size");
2604 ObligationCauseCode::AssignmentLhsSized => {
2605 err.note("the left-hand-side of an assignment must have a statically known size");
2607 ObligationCauseCode::TupleInitializerSized => {
2608 err.note("tuples must have a statically known size to be initialized");
2610 ObligationCauseCode::StructInitializerSized => {
2611 err.note("structs must have a statically known size to be initialized");
2613 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2615 AdtKind::Struct => {
2618 "the last field of a packed struct may only have a \
2619 dynamically sized type if it does not need drop to be run",
2623 "only the last field of a struct may have a dynamically sized type",
2628 err.note("no field of a union may have a dynamically sized type");
2631 err.note("no field of an enum variant may have a dynamically sized type");
2634 err.help("change the field's type to have a statically known size");
2635 err.span_suggestion(
2636 span.shrink_to_lo(),
2637 "borrowed types always have a statically known size",
2639 Applicability::MachineApplicable,
2641 err.multipart_suggestion(
2642 "the `Box` type always has a statically known size and allocates its contents \
2645 (span.shrink_to_lo(), "Box<".to_string()),
2646 (span.shrink_to_hi(), ">".to_string()),
2648 Applicability::MachineApplicable,
2651 ObligationCauseCode::ConstSized => {
2652 err.note("constant expressions must have a statically known size");
2654 ObligationCauseCode::InlineAsmSized => {
2655 err.note("all inline asm arguments must have a statically known size");
2657 ObligationCauseCode::ConstPatternStructural => {
2658 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2660 ObligationCauseCode::SharedStatic => {
2661 err.note("shared static variables must have a type that implements `Sync`");
2663 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2664 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2665 let ty = parent_trait_ref.skip_binder().self_ty();
2666 if parent_trait_ref.references_error() {
2667 // NOTE(eddyb) this was `.cancel()`, but `err`
2668 // is borrowed, so we can't fully defuse it.
2669 err.downgrade_to_delayed_bug();
2673 // If the obligation for a tuple is set directly by a Generator or Closure,
2674 // then the tuple must be the one containing capture types.
2675 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2678 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2680 let parent_trait_ref =
2681 self.resolve_vars_if_possible(data.parent_trait_pred);
2682 let nested_ty = parent_trait_ref.skip_binder().self_ty();
2683 matches!(nested_ty.kind(), ty::Generator(..))
2684 || matches!(nested_ty.kind(), ty::Closure(..))
2690 let identity_future = tcx.require_lang_item(LangItem::IdentityFuture, None);
2692 // Don't print the tuple of capture types
2694 if !is_upvar_tys_infer_tuple {
2695 let msg = with_forced_trimmed_paths!(format!(
2696 "required because it appears within the type `{ty}`",
2699 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2700 Some(ident) => err.span_note(ident.span, &msg),
2701 None => err.note(&msg),
2703 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
2704 // Avoid printing the future from `core::future::identity_future`, it's not helpful
2705 if tcx.parent(*def_id) == identity_future {
2709 // If the previous type is `identity_future`, this is the future generated by the body of an async function.
2710 // Avoid printing it twice (it was already printed in the `ty::Generator` arm below).
2711 let is_future = tcx.ty_is_opaque_future(ty);
2715 "note_obligation_cause_code: check for async fn"
2718 && obligated_types.last().map_or(false, |ty| match ty.kind() {
2719 ty::Generator(last_def_id, ..) => {
2720 tcx.generator_is_async(*last_def_id)
2727 err.span_note(self.tcx.def_span(def_id), &msg)
2729 ty::GeneratorWitness(bound_tys) => {
2730 use std::fmt::Write;
2732 // FIXME: this is kind of an unusual format for rustc, can we make it more clear?
2733 // Maybe we should just remove this note altogether?
2734 // FIXME: only print types which don't meet the trait requirement
2736 "required because it captures the following types: ".to_owned();
2737 for ty in bound_tys.skip_binder() {
2738 with_forced_trimmed_paths!(write!(msg, "`{}`, ", ty).unwrap());
2740 err.note(msg.trim_end_matches(", "))
2742 ty::Generator(def_id, _, _) => {
2743 let sp = self.tcx.def_span(def_id);
2745 // Special-case this to say "async block" instead of `[static generator]`.
2746 let kind = tcx.generator_kind(def_id).unwrap().descr();
2749 with_forced_trimmed_paths!(&format!(
2750 "required because it's used within this {kind}",
2754 ty::Closure(def_id, _) => err.span_note(
2755 self.tcx.def_span(def_id),
2756 "required because it's used within this closure",
2758 _ => err.note(&msg),
2763 obligated_types.push(ty);
2765 let parent_predicate = parent_trait_ref;
2766 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2767 // #74711: avoid a stack overflow
2768 ensure_sufficient_stack(|| {
2769 self.note_obligation_cause_code(
2779 ensure_sufficient_stack(|| {
2780 self.note_obligation_cause_code(
2784 cause_code.peel_derives(),
2791 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2792 let mut parent_trait_pred =
2793 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2794 parent_trait_pred.remap_constness_diag(param_env);
2795 let parent_def_id = parent_trait_pred.def_id();
2796 let (self_ty, file) =
2797 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2799 "required for `{self_ty}` to implement `{}`",
2800 parent_trait_pred.print_modifiers_and_trait_path()
2802 let mut is_auto_trait = false;
2803 match self.tcx.hir().get_if_local(data.impl_def_id) {
2804 Some(Node::Item(hir::Item {
2805 kind: hir::ItemKind::Trait(is_auto, ..),
2809 // FIXME: we should do something else so that it works even on crate foreign
2811 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2812 err.span_note(ident.span, &msg)
2814 Some(Node::Item(hir::Item {
2815 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2818 let mut spans = Vec::with_capacity(2);
2819 if let Some(trait_ref) = of_trait {
2820 spans.push(trait_ref.path.span);
2822 spans.push(self_ty.span);
2823 err.span_note(spans, &msg)
2825 _ => err.note(&msg),
2828 if let Some(file) = file {
2830 "the full type name has been written to '{}'",
2834 let mut parent_predicate = parent_trait_pred;
2835 let mut data = &data.derived;
2837 seen_requirements.insert(parent_def_id);
2839 // We don't want to point at the ADT saying "required because it appears within
2840 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2841 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2844 let child_trait_ref =
2845 self.resolve_vars_if_possible(derived.parent_trait_pred);
2846 let child_def_id = child_trait_ref.def_id();
2847 if seen_requirements.insert(child_def_id) {
2851 parent_predicate = child_trait_ref.to_predicate(tcx);
2852 parent_trait_pred = child_trait_ref;
2855 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2856 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2857 let child_trait_pred =
2858 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2859 let child_def_id = child_trait_pred.def_id();
2860 if seen_requirements.insert(child_def_id) {
2864 data = &child.derived;
2865 parent_predicate = child_trait_pred.to_predicate(tcx);
2866 parent_trait_pred = child_trait_pred;
2870 "{} redundant requirement{} hidden",
2874 let (self_ty, file) =
2875 self.tcx.short_ty_string(parent_trait_pred.skip_binder().self_ty());
2877 "required for `{self_ty}` to implement `{}`",
2878 parent_trait_pred.print_modifiers_and_trait_path()
2880 if let Some(file) = file {
2882 "the full type name has been written to '{}'",
2887 // #74711: avoid a stack overflow
2888 ensure_sufficient_stack(|| {
2889 self.note_obligation_cause_code(
2899 ObligationCauseCode::DerivedObligation(ref data) => {
2900 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2901 let parent_predicate = parent_trait_ref;
2902 // #74711: avoid a stack overflow
2903 ensure_sufficient_stack(|| {
2904 self.note_obligation_cause_code(
2914 ObligationCauseCode::FunctionArgumentObligation {
2920 self.note_function_argument_obligation(
2928 ensure_sufficient_stack(|| {
2929 self.note_obligation_cause_code(
2939 ObligationCauseCode::CompareImplItemObligation { trait_item_def_id, kind, .. } => {
2940 let item_name = self.tcx.item_name(trait_item_def_id);
2942 "the requirement `{predicate}` appears on the `impl`'s {kind} \
2943 `{item_name}` but not on the corresponding trait's {kind}",
2947 .opt_item_ident(trait_item_def_id)
2949 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2950 let mut assoc_span: MultiSpan = sp.into();
2951 assoc_span.push_span_label(
2953 format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
2955 if let Some(ident) = self
2957 .opt_associated_item(trait_item_def_id)
2958 .and_then(|i| self.tcx.opt_item_ident(i.container_id(self.tcx)))
2960 assoc_span.push_span_label(ident.span, "in this trait");
2962 err.span_note(assoc_span, &msg);
2964 ObligationCauseCode::TrivialBound => {
2965 err.help("see issue #48214");
2966 if tcx.sess.opts.unstable_features.is_nightly_build() {
2967 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2970 ObligationCauseCode::OpaqueReturnType(expr_info) => {
2971 if let Some((expr_ty, expr_span)) = expr_info {
2972 let expr_ty = with_forced_trimmed_paths!(self.ty_to_string(expr_ty));
2975 with_forced_trimmed_paths!(format!(
2976 "return type was inferred to be `{expr_ty}` here",
2985 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
2987 fn suggest_await_before_try(
2989 err: &mut Diagnostic,
2990 obligation: &PredicateObligation<'tcx>,
2991 trait_pred: ty::PolyTraitPredicate<'tcx>,
2994 let body_hir_id = obligation.cause.body_id;
2995 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2997 if let Some(body_id) =
2998 self.tcx.hir().maybe_body_owned_by(self.tcx.hir().local_def_id(item_id))
3000 let body = self.tcx.hir().body(body_id);
3001 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
3002 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
3004 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3005 let impls_future = self.type_implements_trait(
3007 [self.tcx.erase_late_bound_regions(self_ty)],
3008 obligation.param_env,
3010 if !impls_future.must_apply_modulo_regions() {
3014 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3015 // `<T as Future>::Output`
3016 let projection_ty = trait_pred.map_bound(|trait_pred| {
3017 self.tcx.mk_projection(
3019 // Future::Output has no substs
3020 [trait_pred.self_ty()],
3023 let InferOk { value: projection_ty, .. } =
3024 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3027 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3029 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3030 obligation.param_env,
3031 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3033 debug!(try_trait_obligation = ?try_obligation);
3034 if self.predicate_may_hold(&try_obligation)
3035 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3036 && snippet.ends_with('?')
3038 err.span_suggestion_verbose(
3039 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3040 "consider `await`ing on the `Future`",
3042 Applicability::MaybeIncorrect,
3049 fn suggest_floating_point_literal(
3051 obligation: &PredicateObligation<'tcx>,
3052 err: &mut Diagnostic,
3053 trait_ref: &ty::PolyTraitRef<'tcx>,
3055 let rhs_span = match obligation.cause.code() {
3056 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span,
3059 if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind()
3060 && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind()
3062 err.span_suggestion_verbose(
3063 rhs_span.shrink_to_hi(),
3064 "consider using a floating-point literal by writing it with `.0`",
3066 Applicability::MaybeIncorrect,
3073 obligation: &PredicateObligation<'tcx>,
3074 err: &mut Diagnostic,
3075 trait_pred: ty::PolyTraitPredicate<'tcx>,
3077 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3080 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
3081 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
3085 let is_derivable_trait = match diagnostic_name {
3086 sym::Default => !adt.is_enum(),
3087 sym::PartialEq | sym::PartialOrd => {
3088 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
3089 trait_pred.skip_binder().self_ty() == rhs_ty
3091 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3094 is_derivable_trait &&
3095 // Ensure all fields impl the trait.
3096 adt.all_fields().all(|field| {
3097 let field_ty = field.ty(self.tcx, substs);
3098 let trait_substs = match diagnostic_name {
3099 sym::PartialEq | sym::PartialOrd => {
3104 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3105 trait_ref: self.tcx.mk_trait_ref(
3106 trait_pred.def_id(),
3107 [field_ty].into_iter().chain(trait_substs),
3111 let field_obl = Obligation::new(
3113 obligation.cause.clone(),
3114 obligation.param_env,
3117 self.predicate_must_hold_modulo_regions(&field_obl)
3121 err.span_suggestion_verbose(
3122 self.tcx.def_span(adt.did()).shrink_to_lo(),
3124 "consider annotating `{}` with `#[derive({})]`",
3125 trait_pred.skip_binder().self_ty(),
3128 format!("#[derive({})]\n", diagnostic_name),
3129 Applicability::MaybeIncorrect,
3134 fn suggest_dereferencing_index(
3136 obligation: &PredicateObligation<'tcx>,
3137 err: &mut Diagnostic,
3138 trait_pred: ty::PolyTraitPredicate<'tcx>,
3140 if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code()
3141 && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3142 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind()
3143 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3144 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3146 err.span_suggestion_verbose(
3147 obligation.cause.span.shrink_to_lo(),
3148 "dereference this index",
3150 Applicability::MachineApplicable,
3154 fn note_function_argument_obligation(
3157 err: &mut Diagnostic,
3158 parent_code: &ObligationCauseCode<'tcx>,
3159 param_env: ty::ParamEnv<'tcx>,
3160 failed_pred: ty::Predicate<'tcx>,
3164 let hir = tcx.hir();
3165 if let Some(Node::Expr(expr)) = hir.find(arg_hir_id)
3166 && let Some(typeck_results) = &self.typeck_results
3168 if let hir::Expr { kind: hir::ExprKind::Block(..), .. } = expr {
3169 let expr = expr.peel_blocks();
3170 let ty = typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error());
3171 let span = expr.span;
3172 if Some(span) != err.span.primary_span() {
3175 if ty.references_error() {
3178 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3179 format!("this tail expression is of type `{ty}`")
3185 // FIXME: visit the ty to see if there's any closure involved, and if there is,
3186 // check whether its evaluated return type is the same as the one corresponding
3187 // to an associated type (as seen from `trait_pred`) in the predicate. Like in
3188 // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>`
3189 let mut type_diffs = vec![];
3191 if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref()
3192 && let Some(node_substs) = typeck_results.node_substs_opt(call_hir_id)
3193 && let where_clauses = self.tcx.predicates_of(def_id).instantiate(self.tcx, node_substs)
3194 && let Some(where_pred) = where_clauses.predicates.get(*idx)
3196 if let Some(where_pred) = where_pred.to_opt_poly_trait_pred()
3197 && let Some(failed_pred) = failed_pred.to_opt_poly_trait_pred()
3199 let mut c = CollectAllMismatches {
3204 if let Ok(_) = c.relate(where_pred, failed_pred) {
3205 type_diffs = c.errors;
3207 } else if let Some(where_pred) = where_pred.to_opt_poly_projection_pred()
3208 && let Some(failed_pred) = failed_pred.to_opt_poly_projection_pred()
3209 && let Some(found) = failed_pred.skip_binder().term.ty()
3212 Sorts(ty::error::ExpectedFound {
3213 expected: self.tcx.mk_ty(ty::Alias(ty::Projection, where_pred.skip_binder().projection_ty)),
3219 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3220 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3221 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3222 && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3223 && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id)
3224 && let Some(binding_expr) = local.init
3226 // If the expression we're calling on is a binding, we want to point at the
3227 // `let` when talking about the type. Otherwise we'll point at every part
3228 // of the method chain with the type.
3229 self.point_at_chain(binding_expr, &typeck_results, type_diffs, param_env, err);
3231 self.point_at_chain(expr, &typeck_results, type_diffs, param_env, err);
3234 let call_node = hir.find(call_hir_id);
3235 if let Some(Node::Expr(hir::Expr {
3236 kind: hir::ExprKind::MethodCall(path, rcvr, ..), ..
3239 if Some(rcvr.span) == err.span.primary_span() {
3240 err.replace_span_with(path.ident.span);
3243 if let Some(Node::Expr(hir::Expr {
3245 hir::ExprKind::Call(hir::Expr { span, .. }, _)
3246 | hir::ExprKind::MethodCall(hir::PathSegment { ident: Ident { span, .. }, .. }, ..),
3248 })) = hir.find(call_hir_id)
3250 if Some(*span) != err.span.primary_span() {
3251 err.span_label(*span, "required by a bound introduced by this call");
3258 expr: &hir::Expr<'_>,
3259 typeck_results: &TypeckResults<'tcx>,
3260 type_diffs: Vec<TypeError<'tcx>>,
3261 param_env: ty::ParamEnv<'tcx>,
3262 err: &mut Diagnostic,
3264 let mut primary_spans = vec![];
3265 let mut span_labels = vec![];
3269 let mut print_root_expr = true;
3270 let mut assocs = vec![];
3271 let mut expr = expr;
3272 let mut prev_ty = self.resolve_vars_if_possible(
3273 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3275 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, span) = expr.kind {
3276 // Point at every method call in the chain with the resulting type.
3277 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3278 // ^^^^^^ ^^^^^^^^^^^
3280 let assocs_in_this_method =
3281 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
3282 assocs.push(assocs_in_this_method);
3283 prev_ty = self.resolve_vars_if_possible(
3284 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(tcx.ty_error()),
3287 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3288 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
3289 && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id)
3290 && let parent_hir_id = self.tcx.hir().get_parent_node(binding.hir_id)
3291 && let Some(parent) = self.tcx.hir().find(parent_hir_id)
3293 // We've reached the root of the method call chain...
3294 if let hir::Node::Local(local) = parent
3295 && let Some(binding_expr) = local.init
3297 // ...and it is a binding. Get the binding creation and continue the chain.
3298 expr = binding_expr;
3300 if let hir::Node::Param(param) = parent {
3301 // ...and it is a an fn argument.
3302 let prev_ty = self.resolve_vars_if_possible(
3303 typeck_results.node_type_opt(param.hir_id).unwrap_or(tcx.ty_error()),
3305 let assocs_in_this_method = self.probe_assoc_types_at_expr(&type_diffs, param.ty_span, prev_ty, param.hir_id, param_env);
3306 if assocs_in_this_method.iter().any(|a| a.is_some()) {
3307 assocs.push(assocs_in_this_method);
3308 print_root_expr = false;
3314 // We want the type before deref coercions, otherwise we talk about `&[_]`
3315 // instead of `Vec<_>`.
3316 if let Some(ty) = typeck_results.expr_ty_opt(expr) && print_root_expr {
3317 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3318 // Point at the root expression
3319 // vec![1, 2, 3].iter().map(mapper).sum<i32>()
3321 span_labels.push((expr.span, format!("this expression has type `{ty}`")));
3323 // Only show this if it is not a "trivial" expression (not a method
3324 // chain) and there are associated types to talk about.
3325 let mut assocs = assocs.into_iter().peekable();
3326 while let Some(assocs_in_method) = assocs.next() {
3327 let Some(prev_assoc_in_method) = assocs.peek() else {
3328 for entry in assocs_in_method {
3329 let Some((span, (assoc, ty))) = entry else { continue; };
3330 if primary_spans.is_empty() || type_diffs.iter().any(|diff| {
3331 let Sorts(expected_found) = diff else { return false; };
3332 self.can_eq(param_env, expected_found.found, ty).is_ok()
3334 // FIXME: this doesn't quite work for `Iterator::collect`
3335 // because we have `Vec<i32>` and `()`, but we'd want `i32`
3336 // to point at the `.into_iter()` call, but as long as we
3337 // still point at the other method calls that might have
3338 // introduced the issue, this is fine for now.
3339 primary_spans.push(span);
3343 with_forced_trimmed_paths!(format!(
3344 "`{}` is `{ty}` here",
3345 self.tcx.def_path_str(assoc),
3351 for (entry, prev_entry) in
3352 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
3354 match (entry, prev_entry) {
3355 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
3356 let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
3358 let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
3359 if self.can_eq(param_env, ty, *prev_ty).is_err() {
3360 if type_diffs.iter().any(|diff| {
3361 let Sorts(expected_found) = diff else { return false; };
3362 self.can_eq(param_env, expected_found.found, ty).is_ok()
3364 primary_spans.push(span);
3367 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
3369 span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
3372 (Some((span, (assoc, ty))), None) => {
3375 with_forced_trimmed_paths!(format!(
3376 "`{}` is `{}` here",
3377 self.tcx.def_path_str(assoc),
3378 self.ty_to_string(ty),
3382 (None, Some(_)) | (None, None) => {}
3386 if !primary_spans.is_empty() {
3387 let mut multi_span: MultiSpan = primary_spans.into();
3388 for (span, label) in span_labels {
3389 multi_span.push_span_label(span, label);
3393 "the method call chain might not have had the expected associated types",
3398 fn probe_assoc_types_at_expr(
3400 type_diffs: &[TypeError<'tcx>],
3403 body_id: hir::HirId,
3404 param_env: ty::ParamEnv<'tcx>,
3405 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
3406 let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
3407 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
3408 for diff in type_diffs {
3409 let Sorts(expected_found) = diff else { continue; };
3410 let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; };
3412 let origin = TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span };
3413 let trait_def_id = proj.trait_def_id(self.tcx);
3414 // Make `Self` be equivalent to the type of the call chain
3415 // expression we're looking at now, so that we can tell what
3416 // for example `Iterator::Item` is at this point in the chain.
3417 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
3419 ty::GenericParamDefKind::Type { .. } => {
3420 if param.index == 0 {
3421 return prev_ty.into();
3424 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Const { .. } => {}
3426 self.var_for_def(span, param)
3428 // This will hold the resolved type of the associated type, if the
3429 // current expression implements the trait that associated type is
3430 // in. For example, this would be what `Iterator::Item` is here.
3431 let ty_var = self.infcx.next_ty_var(origin);
3432 // This corresponds to `<ExprTy as Iterator>::Item = _`.
3433 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::Projection(
3434 ty::ProjectionPredicate {
3435 projection_ty: self.tcx.mk_alias_ty(proj.def_id, substs),
3436 term: ty_var.into(),
3439 // Add `<ExprTy as Iterator>::Item = _` obligation.
3440 ocx.register_obligation(Obligation::misc(
3441 self.tcx, span, body_id, param_env, projection,
3443 if ocx.select_where_possible().is_empty() {
3444 // `ty_var` now holds the type that `Item` is for `ExprTy`.
3445 let ty_var = self.resolve_vars_if_possible(ty_var);
3446 assocs_in_this_method.push(Some((span, (proj.def_id, ty_var))));
3448 // `<ExprTy as Iterator>` didn't select, so likely we've
3449 // reached the end of the iterator chain, like the originating
3451 // Keep the space consistent for later zipping.
3452 assocs_in_this_method.push(None);
3455 assocs_in_this_method
3459 /// Add a hint to add a missing borrow or remove an unnecessary one.
3460 fn hint_missing_borrow<'tcx>(
3464 found_node: Node<'_>,
3465 err: &mut Diagnostic,
3467 let found_args = match found.kind() {
3468 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3470 span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
3473 let expected_args = match expected.kind() {
3474 ty::FnPtr(f) => f.inputs().skip_binder().iter(),
3476 span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
3480 // This could be a variant constructor, for example.
3481 let Some(fn_decl) = found_node.fn_decl() else { return; };
3483 let arg_spans = fn_decl.inputs.iter().map(|ty| ty.span);
3485 fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, usize) {
3488 while let ty::Ref(_, new_ty, _) = ty.kind() {
3496 let mut to_borrow = Vec::new();
3497 let mut remove_borrow = Vec::new();
3499 for ((found_arg, expected_arg), arg_span) in found_args.zip(expected_args).zip(arg_spans) {
3500 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
3501 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
3503 if found_ty == expected_ty {
3504 if found_refs < expected_refs {
3505 to_borrow.push((arg_span, expected_arg.to_string()));
3506 } else if found_refs > expected_refs {
3507 remove_borrow.push((arg_span, expected_arg.to_string()));
3512 if !to_borrow.is_empty() {
3513 err.multipart_suggestion(
3514 "consider borrowing the argument",
3516 Applicability::MaybeIncorrect,
3520 if !remove_borrow.is_empty() {
3521 err.multipart_suggestion(
3522 "do not borrow the argument",
3524 Applicability::MaybeIncorrect,
3529 /// Collect all the returned expressions within the input expression.
3530 /// Used to point at the return spans when we want to suggest some change to them.
3532 pub struct ReturnsVisitor<'v> {
3533 pub returns: Vec<&'v hir::Expr<'v>>,
3534 in_block_tail: bool,
3537 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
3538 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3539 // Visit every expression to detect `return` paths, either through the function's tail
3540 // expression or `return` statements. We walk all nodes to find `return` statements, but
3541 // we only care about tail expressions when `in_block_tail` is `true`, which means that
3542 // they're in the return path of the function body.
3544 hir::ExprKind::Ret(Some(ex)) => {
3545 self.returns.push(ex);
3547 hir::ExprKind::Block(block, _) if self.in_block_tail => {
3548 self.in_block_tail = false;
3549 for stmt in block.stmts {
3550 hir::intravisit::walk_stmt(self, stmt);
3552 self.in_block_tail = true;
3553 if let Some(expr) = block.expr {
3554 self.visit_expr(expr);
3557 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
3558 self.visit_expr(then);
3559 if let Some(el) = else_opt {
3560 self.visit_expr(el);
3563 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
3565 self.visit_expr(arm.body);
3568 // We need to walk to find `return`s in the entire body.
3569 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
3570 _ => self.returns.push(ex),
3574 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
3575 assert!(!self.in_block_tail);
3576 if body.generator_kind().is_none() {
3577 if let hir::ExprKind::Block(block, None) = body.value.kind {
3578 if block.expr.is_some() {
3579 self.in_block_tail = true;
3583 hir::intravisit::walk_body(self, body);
3587 /// Collect all the awaited expressions within the input expression.
3589 struct AwaitsVisitor {
3590 awaits: Vec<hir::HirId>,
3593 impl<'v> Visitor<'v> for AwaitsVisitor {
3594 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
3595 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
3596 self.awaits.push(id)
3598 hir::intravisit::walk_expr(self, ex)
3602 pub trait NextTypeParamName {
3603 fn next_type_param_name(&self, name: Option<&str>) -> String;
3606 impl NextTypeParamName for &[hir::GenericParam<'_>] {
3607 fn next_type_param_name(&self, name: Option<&str>) -> String {
3608 // This is the list of possible parameter names that we might suggest.
3609 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
3610 let name = name.as_deref();
3611 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
3612 let used_names = self
3614 .filter_map(|p| match p.name {
3615 hir::ParamName::Plain(ident) => Some(ident.name),
3618 .collect::<Vec<_>>();
3622 .find(|n| !used_names.contains(&Symbol::intern(n)))
3623 .unwrap_or(&"ParamName")
3628 fn suggest_trait_object_return_type_alternatives(
3629 err: &mut Diagnostic,
3632 is_object_safe: bool,
3634 err.span_suggestion(
3637 "use `impl {}` as the return type if all return paths have the same type but you \
3638 want to expose only the trait in the signature",
3641 format!("impl {}", trait_obj),
3642 Applicability::MaybeIncorrect,
3645 err.multipart_suggestion(
3647 "use a boxed trait object if all return paths implement trait `{}`",
3651 (ret_ty.shrink_to_lo(), "Box<".to_string()),
3652 (ret_ty.shrink_to_hi(), ">".to_string()),
3654 Applicability::MaybeIncorrect,
3659 /// Collect the spans that we see the generic param `param_did`
3660 struct ReplaceImplTraitVisitor<'a> {
3661 ty_spans: &'a mut Vec<Span>,
3665 impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
3666 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir>) {
3667 if let hir::TyKind::Path(hir::QPath::Resolved(
3669 hir::Path { res: hir::def::Res::Def(_, segment_did), .. },
3672 if self.param_did == *segment_did {
3673 // `fn foo(t: impl Trait)`
3674 // ^^^^^^^^^^ get this to suggest `T` instead
3676 // There might be more than one `impl Trait`.
3677 self.ty_spans.push(t.span);
3682 hir::intravisit::walk_ty(self, t);
3686 // Replace `param` with `replace_ty`
3687 struct ReplaceImplTraitFolder<'tcx> {
3689 param: &'tcx ty::GenericParamDef,
3690 replace_ty: Ty<'tcx>,
3693 impl<'tcx> TypeFolder<'tcx> for ReplaceImplTraitFolder<'tcx> {
3694 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3695 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
3696 if self.param.index == *index {
3697 return self.replace_ty;
3700 t.super_fold_with(self)
3703 fn tcx(&self) -> TyCtxt<'tcx> {