2 EvaluationResult, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation,
6 use crate::autoderef::Autoderef;
7 use crate::infer::InferCtxt;
8 use crate::traits::normalize_projection_type;
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_data_structures::stack::ensure_sufficient_stack;
13 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
14 ErrorGuaranteed, MultiSpan, Style,
17 use rustc_hir::def::DefKind;
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::intravisit::Visitor;
20 use rustc_hir::lang_items::LangItem;
21 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
22 use rustc_middle::hir::map;
23 use rustc_middle::ty::{
24 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
25 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, ToPredicate, Ty, TyCtxt,
28 use rustc_middle::ty::{TypeAndMut, TypeckResults};
29 use rustc_session::Limit;
30 use rustc_span::def_id::LOCAL_CRATE;
31 use rustc_span::symbol::{kw, sym, Ident, Symbol};
32 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
33 use rustc_target::spec::abi;
36 use super::InferCtxtPrivExt;
37 use crate::infer::InferCtxtExt as _;
38 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
39 use rustc_middle::ty::print::with_no_trimmed_paths;
42 pub enum GeneratorInteriorOrUpvar {
43 // span of interior type
49 // This type provides a uniform interface to retrieve data on generators, whether it originated from
50 // the local crate being compiled or from a foreign crate.
52 pub enum GeneratorData<'tcx, 'a> {
53 Local(&'a TypeckResults<'tcx>),
54 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
57 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
58 // Try to get information about variables captured by the generator that matches a type we are
59 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
61 fn try_get_upvar_span<F>(
63 infer_context: &InferCtxt<'a, 'tcx>,
66 ) -> Option<GeneratorInteriorOrUpvar>
68 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
71 GeneratorData::Local(typeck_results) => {
72 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
73 upvars.iter().find_map(|(upvar_id, upvar)| {
74 let upvar_ty = typeck_results.node_type(*upvar_id);
75 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
76 if ty_matches(ty::Binder::dummy(upvar_ty)) {
77 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
84 GeneratorData::Foreign(_) => None,
88 // Try to get the span of a type being awaited on that matches the type we are looking with the
89 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
91 fn get_from_await_ty<F>(
93 visitor: AwaitsVisitor,
98 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
101 GeneratorData::Local(typeck_results) => visitor
104 .map(|id| hir.expect_expr(id))
106 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
108 .map(|expr| expr.span),
109 GeneratorData::Foreign(generator_diagnostic_data) => visitor
112 .map(|id| hir.expect_expr(id))
114 ty_matches(ty::Binder::dummy(
115 generator_diagnostic_data
117 .get(&await_expr.hir_id.local_id)
118 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
120 .map_or_else::<Ty<'tcx>, _, _>(
122 generator_diagnostic_data
124 .get(&await_expr.hir_id.local_id)
128 "node_type: no type for node `{}`",
129 ty::tls::with(|tcx| tcx
131 .node_to_string(await_expr.hir_id))
139 .map(|expr| expr.span),
143 /// Get the type, expression, span and optional scope span of all types
144 /// that are live across the yield of this generator
145 fn get_generator_interior_types(
147 ) -> ty::Binder<'tcx, &Vec<GeneratorInteriorTypeCause<'tcx>>> {
149 GeneratorData::Local(typeck_result) => typeck_result.generator_interior_types.as_ref(),
150 GeneratorData::Foreign(generator_diagnostic_data) => {
151 generator_diagnostic_data.generator_interior_types.as_ref()
156 // Used to get the source of the data, note we don't have as much information for generators
157 // originated from foreign crates
158 fn is_foreign(&self) -> bool {
160 GeneratorData::Local(_) => false,
161 GeneratorData::Foreign(_) => true,
166 // This trait is public to expose the diagnostics methods to clippy.
167 pub trait InferCtxtExt<'tcx> {
168 fn suggest_restricting_param_bound(
170 err: &mut Diagnostic,
171 trait_pred: ty::PolyTraitPredicate<'tcx>,
175 fn suggest_dereferences(
177 obligation: &PredicateObligation<'tcx>,
178 err: &mut Diagnostic,
179 trait_pred: ty::PolyTraitPredicate<'tcx>,
182 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<String>;
186 obligation: &PredicateObligation<'tcx>,
187 err: &mut Diagnostic,
188 trait_pred: ty::PolyTraitPredicate<'tcx>,
191 fn suggest_add_reference_to_arg(
193 obligation: &PredicateObligation<'tcx>,
194 err: &mut Diagnostic,
195 trait_pred: ty::PolyTraitPredicate<'tcx>,
196 has_custom_message: bool,
199 fn suggest_borrowing_for_object_cast(
201 err: &mut Diagnostic,
202 obligation: &PredicateObligation<'tcx>,
207 fn suggest_remove_reference(
209 obligation: &PredicateObligation<'tcx>,
210 err: &mut Diagnostic,
211 trait_pred: ty::PolyTraitPredicate<'tcx>,
214 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
216 fn suggest_change_mut(
218 obligation: &PredicateObligation<'tcx>,
219 err: &mut Diagnostic,
220 trait_pred: ty::PolyTraitPredicate<'tcx>,
223 fn suggest_semicolon_removal(
225 obligation: &PredicateObligation<'tcx>,
226 err: &mut Diagnostic,
228 trait_pred: ty::PolyTraitPredicate<'tcx>,
231 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
233 fn suggest_impl_trait(
235 err: &mut Diagnostic,
237 obligation: &PredicateObligation<'tcx>,
238 trait_pred: ty::PolyTraitPredicate<'tcx>,
241 fn point_at_returns_when_relevant(
243 err: &mut Diagnostic,
244 obligation: &PredicateObligation<'tcx>,
247 fn report_closure_arg_mismatch(
250 found_span: Option<Span>,
251 expected_ref: ty::PolyTraitRef<'tcx>,
252 found: ty::PolyTraitRef<'tcx>,
253 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
255 fn suggest_fully_qualified_path(
257 err: &mut Diagnostic,
263 fn maybe_note_obligation_cause_for_async_await(
265 err: &mut Diagnostic,
266 obligation: &PredicateObligation<'tcx>,
269 fn note_obligation_cause_for_async_await(
271 err: &mut Diagnostic,
272 interior_or_upvar_span: GeneratorInteriorOrUpvar,
273 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
275 outer_generator: Option<DefId>,
276 trait_pred: ty::TraitPredicate<'tcx>,
278 typeck_results: Option<&ty::TypeckResults<'tcx>>,
279 obligation: &PredicateObligation<'tcx>,
280 next_code: Option<&ObligationCauseCode<'tcx>>,
283 fn note_obligation_cause_code<T>(
285 err: &mut Diagnostic,
287 param_env: ty::ParamEnv<'tcx>,
288 cause_code: &ObligationCauseCode<'tcx>,
289 obligated_types: &mut Vec<Ty<'tcx>>,
290 seen_requirements: &mut FxHashSet<DefId>,
294 fn suggest_new_overflow_limit(&self, err: &mut Diagnostic);
296 /// Suggest to await before try: future? => future.await?
297 fn suggest_await_before_try(
299 err: &mut Diagnostic,
300 obligation: &PredicateObligation<'tcx>,
301 trait_pred: ty::PolyTraitPredicate<'tcx>,
305 fn suggest_floating_point_literal(
307 obligation: &PredicateObligation<'tcx>,
308 err: &mut Diagnostic,
309 trait_ref: &ty::PolyTraitRef<'tcx>,
314 obligation: &PredicateObligation<'tcx>,
315 err: &mut Diagnostic,
316 trait_pred: ty::PolyTraitPredicate<'tcx>,
320 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
322 generics.tail_span_for_predicate_suggestion(),
323 format!("{} {}", if generics.has_where_clause { "," } else { " where" }, pred,),
327 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
328 /// it can also be an `impl Trait` param that needs to be decomposed to a type
329 /// param for cleaner code.
330 fn suggest_restriction<'tcx>(
332 generics: &hir::Generics<'tcx>,
334 err: &mut Diagnostic,
335 fn_sig: Option<&hir::FnSig<'_>>,
336 projection: Option<&ty::ProjectionTy<'_>>,
337 trait_pred: ty::PolyTraitPredicate<'tcx>,
338 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
340 // When we are dealing with a trait, `super_traits` will be `Some`:
341 // Given `trait T: A + B + C {}`
342 // - ^^^^^^^^^ GenericBounds
345 let span = generics.span_for_predicates_or_empty_place();
346 if span.from_expansion() || span.desugaring_kind().is_some() {
349 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
350 if let Some((bound_str, fn_sig)) =
351 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
352 // Shenanigans to get the `Trait` from the `impl Trait`.
353 ty::Param(param) => {
354 // `fn foo(t: impl Trait)`
355 // ^^^^^ get this string
356 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
361 // We know we have an `impl Trait` that doesn't satisfy a required projection.
363 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
364 // types. There should be at least one, but there might be *more* than one. In that
365 // case we could just ignore it and try to identify which one needs the restriction,
366 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
368 let mut ty_spans = vec![];
369 let impl_trait_str = format!("impl {}", bound_str);
370 for input in fn_sig.decl.inputs {
371 if let hir::TyKind::Path(hir::QPath::Resolved(
373 hir::Path { segments: [segment], .. },
376 if segment.ident.as_str() == impl_trait_str.as_str() {
377 // `fn foo(t: impl Trait)`
378 // ^^^^^^^^^^ get this to suggest `T` instead
380 // There might be more than one `impl Trait`.
381 ty_spans.push(input.span);
386 let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
387 // The type param `T: Trait` we will suggest to introduce.
388 let type_param = format!("{}: {}", type_param_name, bound_str);
390 // FIXME: modify the `trait_pred` instead of string shenanigans.
391 // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
392 let pred = trait_pred.to_predicate(tcx).to_string();
393 let pred = pred.replace(&impl_trait_str, &type_param_name);
395 if let Some(span) = generics.span_for_param_suggestion() {
396 (span, format!(", {}", type_param))
398 (generics.span, format!("<{}>", type_param))
400 // `fn foo(t: impl Trait)`
401 // ^ suggest `where <T as Trait>::A: Bound`
402 predicate_constraint(generics, pred),
404 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
406 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
407 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
408 // `fn foo(t: impl Trait<A: Bound>)` instead.
409 err.multipart_suggestion(
410 "introduce a type parameter with a trait bound instead of using `impl Trait`",
412 Applicability::MaybeIncorrect,
415 // Trivial case: `T` needs an extra bound: `T: Bound`.
416 let (sp, suggestion) = match (
420 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
423 (_, None) => predicate_constraint(generics, trait_pred.to_predicate(tcx).to_string()),
424 (None, Some((ident, []))) => (
425 ident.span.shrink_to_hi(),
426 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
428 (_, Some((_, [.., bounds]))) => (
429 bounds.span().shrink_to_hi(),
430 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
432 (Some(_), Some((_, []))) => (
433 generics.span.shrink_to_hi(),
434 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
438 err.span_suggestion_verbose(
440 &format!("consider further restricting {}", msg),
442 Applicability::MachineApplicable,
447 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
448 fn suggest_restricting_param_bound(
450 mut err: &mut Diagnostic,
451 trait_pred: ty::PolyTraitPredicate<'tcx>,
454 let self_ty = trait_pred.skip_binder().self_ty();
455 let (param_ty, projection) = match self_ty.kind() {
456 ty::Param(_) => (true, None),
457 ty::Projection(projection) => (false, Some(projection)),
461 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
462 // don't suggest `T: Sized + ?Sized`.
463 let mut hir_id = body_id;
464 while let Some(node) = self.tcx.hir().find(hir_id) {
466 hir::Node::Item(hir::Item {
468 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
470 }) if self_ty == self.tcx.types.self_param => {
472 // Restricting `Self` for a single method.
481 Some((ident, bounds)),
486 hir::Node::TraitItem(hir::TraitItem {
488 kind: hir::TraitItemKind::Fn(..),
490 }) if self_ty == self.tcx.types.self_param => {
492 // Restricting `Self` for a single method.
494 self.tcx, &generics, "`Self`", err, None, projection, trait_pred, None,
499 hir::Node::TraitItem(hir::TraitItem {
501 kind: hir::TraitItemKind::Fn(fn_sig, ..),
504 | hir::Node::ImplItem(hir::ImplItem {
506 kind: hir::ImplItemKind::Fn(fn_sig, ..),
509 | hir::Node::Item(hir::Item {
510 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
511 }) if projection.is_some() => {
512 // Missing restriction on associated type of type parameter (unmet projection).
516 "the associated type",
525 hir::Node::Item(hir::Item {
527 hir::ItemKind::Trait(_, _, generics, ..)
528 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
530 }) if projection.is_some() => {
531 // Missing restriction on associated type of type parameter (unmet projection).
535 "the associated type",
545 hir::Node::Item(hir::Item {
547 hir::ItemKind::Struct(_, generics)
548 | hir::ItemKind::Enum(_, generics)
549 | hir::ItemKind::Union(_, generics)
550 | hir::ItemKind::Trait(_, _, generics, ..)
551 | hir::ItemKind::Impl(hir::Impl { generics, .. })
552 | hir::ItemKind::Fn(_, generics, _)
553 | hir::ItemKind::TyAlias(_, generics)
554 | hir::ItemKind::TraitAlias(generics, _)
555 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
558 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
559 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
562 // Missing generic type parameter bound.
563 let param_name = self_ty.to_string();
564 let constraint = with_no_trimmed_paths!(
565 trait_pred.print_modifiers_and_trait_path().to_string()
567 if suggest_constraining_type_param(
573 Some(trait_pred.def_id()),
579 hir::Node::Item(hir::Item {
581 hir::ItemKind::Struct(_, generics)
582 | hir::ItemKind::Enum(_, generics)
583 | hir::ItemKind::Union(_, generics)
584 | hir::ItemKind::Trait(_, _, generics, ..)
585 | hir::ItemKind::Impl(hir::Impl { generics, .. })
586 | hir::ItemKind::Fn(_, generics, _)
587 | hir::ItemKind::TyAlias(_, generics)
588 | hir::ItemKind::TraitAlias(generics, _)
589 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
592 // Missing generic type parameter bound.
593 let param_name = self_ty.to_string();
594 let constraint = trait_pred.print_modifiers_and_trait_path().to_string();
595 if suggest_arbitrary_trait_bound(generics, &mut err, ¶m_name, &constraint) {
599 hir::Node::Crate(..) => return,
604 hir_id = self.tcx.hir().local_def_id_to_hir_id(self.tcx.hir().get_parent_item(hir_id));
608 /// When after several dereferencing, the reference satisfies the trait
609 /// binding. This function provides dereference suggestion for this
610 /// specific situation.
611 fn suggest_dereferences(
613 obligation: &PredicateObligation<'tcx>,
614 err: &mut Diagnostic,
615 trait_pred: ty::PolyTraitPredicate<'tcx>,
617 // It only make sense when suggesting dereferences for arguments
618 let ObligationCauseCode::FunctionArgumentObligation { .. } = obligation.cause.code() else {
621 let param_env = obligation.param_env;
622 let body_id = obligation.cause.body_id;
623 let span = obligation.cause.span;
624 let mut real_trait_pred = trait_pred;
625 let mut code = obligation.cause.code();
626 while let Some((parent_code, parent_trait_pred)) = code.parent() {
628 if let Some(parent_trait_pred) = parent_trait_pred {
629 real_trait_pred = parent_trait_pred;
632 // Skipping binder here, remapping below
633 let real_ty = real_trait_pred.self_ty().skip_binder();
635 if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
636 let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
637 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
639 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
641 // Remapping bound vars here
642 let real_trait_pred_and_ty =
643 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
644 let obligation = self
645 .mk_trait_obligation_with_new_self_ty(param_env, real_trait_pred_and_ty);
646 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
649 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
650 // Don't care about `&mut` because `DerefMut` is used less
651 // often and user will not expect autoderef happens.
652 if src.starts_with('&') && !src.starts_with("&mut ") {
653 let derefs = "*".repeat(steps);
656 "consider dereferencing here",
657 format!("&{}{}", derefs, &src[1..]),
658 Applicability::MachineApplicable,
664 } else if real_trait_pred != trait_pred {
665 // This branch addresses #87437.
667 // Remapping bound vars here
668 let real_trait_pred_and_base_ty =
669 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
670 let obligation = self.mk_trait_obligation_with_new_self_ty(
672 real_trait_pred_and_base_ty,
674 if self.predicate_may_hold(&obligation) {
675 err.span_suggestion_verbose(
677 "consider dereferencing here",
679 Applicability::MachineApplicable,
689 /// Given a closure's `DefId`, return the given name of the closure.
691 /// This doesn't account for reassignments, but it's only used for suggestions.
692 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<String> {
693 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<String> {
694 // Get the local name of this closure. This can be inaccurate because
695 // of the possibility of reassignment, but this should be good enough.
697 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
698 Some(format!("{}", name))
707 let hir = self.tcx.hir();
708 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
709 let parent_node = hir.get_parent_node(hir_id);
710 match hir.find(parent_node) {
711 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
712 get_name(err, &local.pat.kind)
714 // Different to previous arm because one is `&hir::Local` and the other
715 // is `P<hir::Local>`.
716 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
721 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
722 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
723 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
726 obligation: &PredicateObligation<'tcx>,
727 err: &mut Diagnostic,
728 trait_pred: ty::PolyTraitPredicate<'tcx>,
730 // Skipping binder here, remapping below
731 let self_ty = trait_pred.self_ty().skip_binder();
733 let (def_id, output_ty, callable) = match *self_ty.kind() {
734 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
735 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
738 let msg = format!("use parentheses to call the {}", callable);
740 // "We should really create a single list of bound vars from the combined vars
741 // from the predicate and function, but instead we just liberate the function bound vars"
742 let output_ty = self.tcx.liberate_late_bound_regions(def_id, output_ty);
744 // Remapping bound vars here
745 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output_ty));
748 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
750 match self.evaluate_obligation(&new_obligation) {
752 EvaluationResult::EvaluatedToOk
753 | EvaluationResult::EvaluatedToOkModuloRegions
754 | EvaluationResult::EvaluatedToAmbig,
758 let hir = self.tcx.hir();
759 // Get the name of the callable and the arguments to be used in the suggestion.
760 let (snippet, sugg) = match hir.get_if_local(def_id) {
761 Some(hir::Node::Expr(hir::Expr {
762 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
765 err.span_label(*span, "consider calling this closure");
766 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
769 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
770 let sugg = format!("({})", args);
771 (format!("{}{}", name, sugg), sugg)
773 Some(hir::Node::Item(hir::Item {
775 kind: hir::ItemKind::Fn(.., body_id),
778 err.span_label(ident.span, "consider calling this function");
779 let body = hir.body(*body_id);
783 .map(|arg| match &arg.pat.kind {
784 hir::PatKind::Binding(_, _, ident, None)
785 // FIXME: provide a better suggestion when encountering `SelfLower`, it
786 // should suggest a method call.
787 if ident.name != kw::SelfLower => ident.to_string(),
788 _ => "_".to_string(),
792 let sugg = format!("({})", args);
793 (format!("{}{}", ident, sugg), sugg)
797 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
799 // When the obligation error has been ensured to have been caused by
800 // an argument, the `obligation.cause.span` points at the expression
801 // of the argument, so we can provide a suggestion. Otherwise, we give
802 // a more general note.
803 err.span_suggestion_verbose(
804 obligation.cause.span.shrink_to_hi(),
807 Applicability::HasPlaceholders,
810 err.help(&format!("{}: `{}`", msg, snippet));
815 fn suggest_add_reference_to_arg(
817 obligation: &PredicateObligation<'tcx>,
818 err: &mut Diagnostic,
819 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
820 has_custom_message: bool,
822 let span = obligation.cause.span;
824 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
825 obligation.cause.code()
828 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
829 span.ctxt().outer_expn_data().kind
831 obligation.cause.code()
836 // List of traits for which it would be nonsensical to suggest borrowing.
837 // For instance, immutable references are always Copy, so suggesting to
838 // borrow would always succeed, but it's probably not what the user wanted.
839 let mut never_suggest_borrow: Vec<_> =
840 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
842 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
845 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
846 never_suggest_borrow.push(def_id);
849 let param_env = obligation.param_env;
851 // Try to apply the original trait binding obligation by borrowing.
852 let mut try_borrowing =
853 |old_pred: ty::PolyTraitPredicate<'tcx>, blacklist: &[DefId]| -> bool {
854 if blacklist.contains(&old_pred.def_id()) {
857 // We map bounds to `&T` and `&mut T`
858 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
861 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
864 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
867 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
871 let mk_result = |trait_pred_and_new_ty| {
873 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
874 self.predicate_must_hold_modulo_regions(&obligation)
876 let imm_result = mk_result(trait_pred_and_imm_ref);
877 let mut_result = mk_result(trait_pred_and_mut_ref);
879 if imm_result || mut_result {
880 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
881 // We have a very specific type of error, where just borrowing this argument
882 // might solve the problem. In cases like this, the important part is the
883 // original type obligation, not the last one that failed, which is arbitrary.
884 // Because of this, we modify the error to refer to the original obligation and
885 // return early in the caller.
887 let msg = format!("the trait bound `{}` is not satisfied", old_pred);
888 if has_custom_message {
892 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
894 if snippet.starts_with('&') {
895 // This is already a literal borrow and the obligation is failing
896 // somewhere else in the obligation chain. Do not suggest non-sense.
902 "expected an implementor of trait `{}`",
903 old_pred.print_modifiers_and_trait_path(),
907 // This if is to prevent a special edge-case
909 span.ctxt().outer_expn_data().kind,
910 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
912 // We don't want a borrowing suggestion on the fields in structs,
915 // the_foos: Vec<Foo>
919 if imm_result && mut_result {
920 err.span_suggestions(
922 "consider borrowing here",
923 ["&".to_string(), "&mut ".to_string()].into_iter(),
924 Applicability::MaybeIncorrect,
927 err.span_suggestion_verbose(
930 "consider{} borrowing here",
931 if mut_result { " mutably" } else { "" }
933 format!("&{}", if mut_result { "mut " } else { "" }),
934 Applicability::MaybeIncorrect,
944 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
945 try_borrowing(cause.derived.parent_trait_pred, &[])
946 } else if let ObligationCauseCode::BindingObligation(_, _)
947 | ObligationCauseCode::ItemObligation(_) = code
949 try_borrowing(poly_trait_pred, &never_suggest_borrow)
955 // Suggest borrowing the type
956 fn suggest_borrowing_for_object_cast(
958 err: &mut Diagnostic,
959 obligation: &PredicateObligation<'tcx>,
963 let ty::Dynamic(predicates, _) = object_ty.kind() else { return; };
964 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
966 for predicate in predicates.iter() {
967 if !self.predicate_must_hold_modulo_regions(
968 &obligation.with(predicate.with_self_ty(self.tcx, self_ref_ty)),
975 obligation.cause.span.shrink_to_lo(),
977 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
980 Applicability::MaybeIncorrect,
984 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
985 /// suggest removing these references until we reach a type that implements the trait.
986 fn suggest_remove_reference(
988 obligation: &PredicateObligation<'tcx>,
989 err: &mut Diagnostic,
990 trait_pred: ty::PolyTraitPredicate<'tcx>,
992 let span = obligation.cause.span;
994 let mut suggested = false;
995 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
997 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
998 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
999 // Do not suggest removal of borrow from type arguments.
1003 // Skipping binder here, remapping below
1004 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1006 for refs_remaining in 0..refs_number {
1007 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1010 suggested_ty = *inner_ty;
1012 // Remapping bound vars here
1013 let trait_pred_and_suggested_ty =
1014 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1016 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1017 obligation.param_env,
1018 trait_pred_and_suggested_ty,
1021 if self.predicate_may_hold(&new_obligation) {
1026 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1028 let remove_refs = refs_remaining + 1;
1030 let msg = if remove_refs == 1 {
1031 "consider removing the leading `&`-reference".to_string()
1033 format!("consider removing {} leading `&`-references", remove_refs)
1036 err.span_suggestion_short(
1040 Applicability::MachineApplicable,
1050 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1051 let span = obligation.cause.span;
1053 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1054 let hir = self.tcx.hir();
1055 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1056 if let hir::Node::Expr(expr) = node {
1057 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1058 // and if not maybe suggest doing something else? If we kept the expression around we
1059 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1060 // it is from the local crate.
1061 err.span_suggestion_verbose(
1062 expr.span.shrink_to_hi().with_hi(span.hi()),
1063 "remove the `.await`",
1065 Applicability::MachineApplicable,
1067 // FIXME: account for associated `async fn`s.
1068 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1069 if let ty::PredicateKind::Trait(pred) =
1070 obligation.predicate.kind().skip_binder()
1074 &format!("this call returns `{}`", pred.self_ty()),
1077 if let Some(typeck_results) =
1078 self.in_progress_typeck_results.map(|t| t.borrow())
1079 && let ty = typeck_results.expr_ty_adjusted(base)
1080 && let ty::FnDef(def_id, _substs) = ty.kind()
1081 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1082 hir.get_if_local(*def_id)
1085 "alternatively, consider making `fn {}` asynchronous",
1088 if vis_span.is_empty() {
1089 err.span_suggestion_verbose(
1090 span.shrink_to_lo(),
1092 "async ".to_string(),
1093 Applicability::MaybeIncorrect,
1096 err.span_suggestion_verbose(
1097 vis_span.shrink_to_hi(),
1099 " async".to_string(),
1100 Applicability::MaybeIncorrect,
1110 /// Check if the trait bound is implemented for a different mutability and note it in the
1112 fn suggest_change_mut(
1114 obligation: &PredicateObligation<'tcx>,
1115 err: &mut Diagnostic,
1116 trait_pred: ty::PolyTraitPredicate<'tcx>,
1118 let points_at_arg = matches!(
1119 obligation.cause.code(),
1120 ObligationCauseCode::FunctionArgumentObligation { .. },
1123 let span = obligation.cause.span;
1124 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1126 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1127 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1128 // Do not suggest removal of borrow from type arguments.
1131 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1132 if trait_pred.has_infer_types_or_consts() {
1133 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1134 // unresolved bindings.
1138 // Skipping binder here, remapping below
1139 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1141 let suggested_ty = match mutability {
1142 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1143 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1146 // Remapping bound vars here
1147 let trait_pred_and_suggested_ty =
1148 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1150 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1151 obligation.param_env,
1152 trait_pred_and_suggested_ty,
1154 let suggested_ty_would_satisfy_obligation = self
1155 .evaluate_obligation_no_overflow(&new_obligation)
1156 .must_apply_modulo_regions();
1157 if suggested_ty_would_satisfy_obligation {
1162 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1163 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1164 err.span_suggestion_verbose(
1166 "consider changing this borrow's mutability",
1167 "&mut ".to_string(),
1168 Applicability::MachineApplicable,
1172 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1173 trait_pred.print_modifiers_and_trait_path(),
1175 trait_pred.skip_binder().self_ty(),
1183 fn suggest_semicolon_removal(
1185 obligation: &PredicateObligation<'tcx>,
1186 err: &mut Diagnostic,
1188 trait_pred: ty::PolyTraitPredicate<'tcx>,
1190 let hir = self.tcx.hir();
1191 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1192 let node = hir.find(parent_node);
1193 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1194 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1195 && sig.decl.output.span().overlaps(span)
1196 && blk.expr.is_none()
1197 && trait_pred.self_ty().skip_binder().is_unit()
1198 && let Some(stmt) = blk.stmts.last()
1199 && let hir::StmtKind::Semi(expr) = stmt.kind
1200 // Only suggest this if the expression behind the semicolon implements the predicate
1201 && let Some(typeck_results) = self.in_progress_typeck_results
1202 && let Some(ty) = typeck_results.borrow().expr_ty_opt(expr)
1203 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1204 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1210 "this expression has type `{}`, which implements `{}`",
1212 trait_pred.print_modifiers_and_trait_path()
1215 err.span_suggestion(
1216 self.tcx.sess.source_map().end_point(stmt.span),
1217 "remove this semicolon",
1219 Applicability::MachineApplicable
1226 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1227 let hir = self.tcx.hir();
1228 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1229 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1233 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1236 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1237 /// applicable and signal that the error has been expanded appropriately and needs to be
1239 fn suggest_impl_trait(
1241 err: &mut Diagnostic,
1243 obligation: &PredicateObligation<'tcx>,
1244 trait_pred: ty::PolyTraitPredicate<'tcx>,
1246 match obligation.cause.code().peel_derives() {
1247 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1248 ObligationCauseCode::SizedReturnType => {}
1252 let hir = self.tcx.hir();
1253 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1254 let node = hir.find(fn_hir_id);
1255 let Some(hir::Node::Item(hir::Item {
1256 kind: hir::ItemKind::Fn(sig, _, body_id),
1262 let body = hir.body(*body_id);
1263 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1264 let ty = trait_pred.skip_binder().self_ty();
1265 let is_object_safe = match ty.kind() {
1266 ty::Dynamic(predicates, _) => {
1267 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1270 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1272 // We only want to suggest `impl Trait` to `dyn Trait`s.
1273 // For example, `fn foo() -> str` needs to be filtered out.
1277 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1281 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1282 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1283 // Recursively look for `TraitObject` types and if there's only one, use that span to
1284 // suggest `impl Trait`.
1286 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1287 // otherwise suggest using `Box<dyn Trait>` or an enum.
1288 let mut visitor = ReturnsVisitor::default();
1289 visitor.visit_body(&body);
1291 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1292 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id) else { return false; };
1294 let ret_types = visitor
1297 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1298 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1299 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1301 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1303 let ty = self.resolve_vars_if_possible(ty);
1305 !matches!(ty.kind(), ty::Error(_))
1306 && last_ty.map_or(true, |last_ty| {
1307 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1308 // *after* in the dependency graph.
1309 match (ty.kind(), last_ty.kind()) {
1310 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1311 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1312 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1314 Infer(InferTy::FreshFloatTy(_)),
1315 Infer(InferTy::FreshFloatTy(_)),
1320 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1323 let mut spans_and_needs_box = vec![];
1325 match liberated_sig.output().kind() {
1326 ty::Dynamic(predicates, _) => {
1327 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1328 let param_env = ty::ParamEnv::empty();
1330 if !only_never_return {
1331 for (expr_span, return_ty) in ret_types {
1332 let self_ty_satisfies_dyn_predicates = |self_ty| {
1333 predicates.iter().all(|predicate| {
1334 let pred = predicate.with_self_ty(self.tcx, self_ty);
1335 let obl = Obligation::new(cause.clone(), param_env, pred);
1336 self.predicate_may_hold(&obl)
1340 if let ty::Adt(def, substs) = return_ty.kind()
1342 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1344 spans_and_needs_box.push((expr_span, false));
1345 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1346 spans_and_needs_box.push((expr_span, true));
1356 let sm = self.tcx.sess.source_map();
1357 if !ret_ty.span.overlaps(span) {
1360 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1361 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1367 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1368 let name = liberated_sig.output().to_string();
1370 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1371 if !name.starts_with("dyn ") {
1377 err.code(error_code!(E0746));
1378 err.set_primary_message("return type cannot have an unboxed trait object");
1379 err.children.clear();
1380 let impl_trait_msg = "for information on `impl Trait`, see \
1381 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1382 #returning-types-that-implement-traits>";
1383 let trait_obj_msg = "for information on trait objects, see \
1384 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1385 #using-trait-objects-that-allow-for-values-of-different-types>";
1387 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1388 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1389 if only_never_return {
1390 // No return paths, probably using `panic!()` or similar.
1391 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1392 suggest_trait_object_return_type_alternatives(
1398 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1399 // Suggest `-> impl Trait`.
1400 err.span_suggestion(
1403 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1404 which implements `{1}`",
1407 format!("impl {}", trait_obj),
1408 Applicability::MachineApplicable,
1410 err.note(impl_trait_msg);
1413 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1414 err.multipart_suggestion(
1415 "return a boxed trait object instead",
1417 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1418 (span.shrink_to_hi(), ">".to_string()),
1420 Applicability::MaybeIncorrect,
1422 for (span, needs_box) in spans_and_needs_box {
1424 err.multipart_suggestion(
1425 "... and box this value",
1427 (span.shrink_to_lo(), "Box::new(".to_string()),
1428 (span.shrink_to_hi(), ")".to_string()),
1430 Applicability::MaybeIncorrect,
1435 // This is currently not possible to trigger because E0038 takes precedence, but
1436 // leave it in for completeness in case anything changes in an earlier stage.
1438 "if trait `{}` were object-safe, you could return a trait object",
1442 err.note(trait_obj_msg);
1444 "if all the returned values were of the same type you could use `impl {}` as the \
1448 err.note(impl_trait_msg);
1449 err.note("you can create a new `enum` with a variant for each returned type");
1454 fn point_at_returns_when_relevant(
1456 err: &mut Diagnostic,
1457 obligation: &PredicateObligation<'tcx>,
1459 match obligation.cause.code().peel_derives() {
1460 ObligationCauseCode::SizedReturnType => {}
1464 let hir = self.tcx.hir();
1465 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1466 let node = hir.find(parent_node);
1467 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1470 let body = hir.body(*body_id);
1471 // Point at all the `return`s in the function as they have failed trait bounds.
1472 let mut visitor = ReturnsVisitor::default();
1473 visitor.visit_body(&body);
1474 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1475 for expr in &visitor.returns {
1476 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1477 let ty = self.resolve_vars_if_possible(returned_ty);
1478 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1484 fn report_closure_arg_mismatch(
1487 found_span: Option<Span>,
1488 expected_ref: ty::PolyTraitRef<'tcx>,
1489 found: ty::PolyTraitRef<'tcx>,
1490 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1491 crate fn build_fn_sig_string<'tcx>(
1493 trait_ref: ty::PolyTraitRef<'tcx>,
1495 let inputs = trait_ref.skip_binder().substs.type_at(1);
1496 let sig = match inputs.kind() {
1498 if tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1502 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1504 hir::Unsafety::Normal,
1509 std::iter::once(inputs),
1510 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1512 hir::Unsafety::Normal,
1516 trait_ref.rebind(sig).to_string()
1519 let argument_kind = match expected_ref.skip_binder().self_ty().kind() {
1520 ty::Closure(..) => "closure",
1521 ty::Generator(..) => "generator",
1524 let span = self.tcx.sess.source_map().guess_head_span(span);
1525 let mut err = struct_span_err!(
1529 "type mismatch in {} arguments",
1533 let found_str = format!("expected signature of `{}`", build_fn_sig_string(self.tcx, found));
1534 err.span_label(span, found_str);
1536 let found_span = found_span.unwrap_or(span);
1538 format!("found signature of `{}`", build_fn_sig_string(self.tcx, expected_ref));
1539 err.span_label(found_span, expected_str);
1544 fn suggest_fully_qualified_path(
1546 err: &mut Diagnostic,
1551 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1552 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1554 "{}s cannot be accessed directly on a `trait`, they can only be \
1555 accessed through a specific `impl`",
1556 assoc_item.kind.as_def_kind().descr(item_def_id)
1558 err.span_suggestion(
1560 "use the fully qualified path to an implementation",
1561 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1562 Applicability::HasPlaceholders,
1568 /// Adds an async-await specific note to the diagnostic when the future does not implement
1569 /// an auto trait because of a captured type.
1572 /// note: future does not implement `Qux` as this value is used across an await
1573 /// --> $DIR/issue-64130-3-other.rs:17:5
1575 /// LL | let x = Foo;
1576 /// | - has type `Foo`
1577 /// LL | baz().await;
1578 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1580 /// | - `x` is later dropped here
1583 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1584 /// is "replaced" with a different message and a more specific error.
1587 /// error: future cannot be sent between threads safely
1588 /// --> $DIR/issue-64130-2-send.rs:21:5
1590 /// LL | fn is_send<T: Send>(t: T) { }
1591 /// | ---- required by this bound in `is_send`
1593 /// LL | is_send(bar());
1594 /// | ^^^^^^^ future returned by `bar` is not send
1596 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1597 /// implemented for `Foo`
1598 /// note: future is not send as this value is used across an await
1599 /// --> $DIR/issue-64130-2-send.rs:15:5
1601 /// LL | let x = Foo;
1602 /// | - has type `Foo`
1603 /// LL | baz().await;
1604 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1606 /// | - `x` is later dropped here
1609 /// Returns `true` if an async-await specific note was added to the diagnostic.
1610 fn maybe_note_obligation_cause_for_async_await(
1612 err: &mut Diagnostic,
1613 obligation: &PredicateObligation<'tcx>,
1616 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1617 obligation.cause.span={:?}",
1618 obligation.predicate, obligation.cause.span
1620 let hir = self.tcx.hir();
1622 // Attempt to detect an async-await error by looking at the obligation causes, looking
1623 // for a generator to be present.
1625 // When a future does not implement a trait because of a captured type in one of the
1626 // generators somewhere in the call stack, then the result is a chain of obligations.
1628 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1629 // future is passed as an argument to a function C which requires a `Send` type, then the
1630 // chain looks something like this:
1632 // - `BuiltinDerivedObligation` with a generator witness (B)
1633 // - `BuiltinDerivedObligation` with a generator (B)
1634 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1635 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1636 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1637 // - `BuiltinDerivedObligation` with a generator witness (A)
1638 // - `BuiltinDerivedObligation` with a generator (A)
1639 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1640 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1641 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1642 // - `BindingObligation` with `impl_send (Send requirement)
1644 // The first obligation in the chain is the most useful and has the generator that captured
1645 // the type. The last generator (`outer_generator` below) has information about where the
1646 // bound was introduced. At least one generator should be present for this diagnostic to be
1648 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1649 ty::PredicateKind::Trait(p) => (Some(p), Some(p.self_ty())),
1652 let mut generator = None;
1653 let mut outer_generator = None;
1654 let mut next_code = Some(obligation.cause.code());
1656 let mut seen_upvar_tys_infer_tuple = false;
1658 while let Some(code) = next_code {
1659 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1661 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1662 next_code = Some(parent_code);
1664 ObligationCauseCode::ImplDerivedObligation(cause) => {
1665 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1667 "maybe_note_obligation_cause_for_async_await: ImplDerived \
1668 parent_trait_ref={:?} self_ty.kind={:?}",
1669 cause.derived.parent_trait_pred,
1674 ty::Generator(did, ..) => {
1675 generator = generator.or(Some(did));
1676 outer_generator = Some(did);
1678 ty::GeneratorWitness(..) => {}
1679 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1680 // By introducing a tuple of upvar types into the chain of obligations
1681 // of a generator, the first non-generator item is now the tuple itself,
1682 // we shall ignore this.
1684 seen_upvar_tys_infer_tuple = true;
1686 _ if generator.is_none() => {
1687 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1688 target_ty = Some(ty);
1693 next_code = Some(&cause.derived.parent_code);
1695 ObligationCauseCode::DerivedObligation(derived_obligation)
1696 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1697 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1699 "maybe_note_obligation_cause_for_async_await: \
1700 parent_trait_ref={:?} self_ty.kind={:?}",
1701 derived_obligation.parent_trait_pred,
1706 ty::Generator(did, ..) => {
1707 generator = generator.or(Some(did));
1708 outer_generator = Some(did);
1710 ty::GeneratorWitness(..) => {}
1711 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1712 // By introducing a tuple of upvar types into the chain of obligations
1713 // of a generator, the first non-generator item is now the tuple itself,
1714 // we shall ignore this.
1716 seen_upvar_tys_infer_tuple = true;
1718 _ if generator.is_none() => {
1719 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1720 target_ty = Some(ty);
1725 next_code = Some(&derived_obligation.parent_code);
1731 // Only continue if a generator was found.
1732 debug!(?generator, ?trait_ref, ?target_ty, "maybe_note_obligation_cause_for_async_await");
1733 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1737 let span = self.tcx.def_span(generator_did);
1739 let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1740 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1742 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1743 generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
1746 in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1750 let generator_body = generator_did
1752 .map(|def_id| hir.local_def_id_to_hir_id(def_id))
1753 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1754 .map(|body_id| hir.body(body_id));
1755 let is_async = match generator_did.as_local() {
1756 Some(_) => generator_body
1757 .and_then(|body| body.generator_kind())
1758 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1762 .generator_kind(generator_did)
1763 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1766 let mut visitor = AwaitsVisitor::default();
1767 if let Some(body) = generator_body {
1768 visitor.visit_body(body);
1770 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1772 // Look for a type inside the generator interior that matches the target type to get
1774 let target_ty_erased = self.tcx.erase_regions(target_ty);
1775 let ty_matches = |ty| -> bool {
1776 // Careful: the regions for types that appear in the
1777 // generator interior are not generally known, so we
1778 // want to erase them when comparing (and anyway,
1779 // `Send` and other bounds are generally unaffected by
1780 // the choice of region). When erasing regions, we
1781 // also have to erase late-bound regions. This is
1782 // because the types that appear in the generator
1783 // interior generally contain "bound regions" to
1784 // represent regions that are part of the suspended
1785 // generator frame. Bound regions are preserved by
1786 // `erase_regions` and so we must also call
1787 // `erase_late_bound_regions`.
1788 let ty_erased = self.tcx.erase_late_bound_regions(ty);
1789 let ty_erased = self.tcx.erase_regions(ty_erased);
1790 let eq = ty_erased == target_ty_erased;
1792 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1793 target_ty_erased={:?} eq={:?}",
1794 ty_erased, target_ty_erased, eq
1799 let mut interior_or_upvar_span = None;
1800 let mut interior_extra_info = None;
1802 // Get the typeck results from the infcx if the generator is the function we are currently
1803 // type-checking; otherwise, get them by performing a query. This is needed to avoid
1804 // cycles. If we can't use resolved types because the generator comes from another crate,
1805 // we still provide a targeted error but without all the relevant spans.
1806 let generator_data: Option<GeneratorData<'tcx, '_>> = match &in_progress_typeck_results {
1807 Some(t) if t.hir_owner.to_def_id() == generator_did_root => {
1808 Some(GeneratorData::Local(&t))
1810 _ if generator_did.is_local() => {
1811 Some(GeneratorData::Local(self.tcx.typeck(generator_did.expect_local())))
1815 .generator_diagnostic_data(generator_did)
1817 .map(|generator_diag_data| GeneratorData::Foreign(generator_diag_data)),
1820 if let Some(generator_data) = generator_data.as_ref() {
1821 interior_or_upvar_span =
1822 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
1824 // The generator interior types share the same binders
1825 if let Some(cause) =
1826 generator_data.get_generator_interior_types().skip_binder().iter().find(
1827 |ty::GeneratorInteriorTypeCause { ty, .. }| {
1828 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
1832 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
1833 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1836 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1837 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1840 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
1841 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span));
1845 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1846 let typeck_results = generator_data.and_then(|generator_data| match generator_data {
1847 GeneratorData::Local(typeck_results) => Some(typeck_results),
1848 GeneratorData::Foreign(_) => None,
1850 self.note_obligation_cause_for_async_await(
1852 interior_or_upvar_span,
1853 interior_extra_info,
1868 /// Unconditionally adds the diagnostic note described in
1869 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1870 fn note_obligation_cause_for_async_await(
1872 err: &mut Diagnostic,
1873 interior_or_upvar_span: GeneratorInteriorOrUpvar,
1874 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1876 outer_generator: Option<DefId>,
1877 trait_pred: ty::TraitPredicate<'tcx>,
1878 target_ty: Ty<'tcx>,
1879 typeck_results: Option<&ty::TypeckResults<'tcx>>,
1880 obligation: &PredicateObligation<'tcx>,
1881 next_code: Option<&ObligationCauseCode<'tcx>>,
1883 let source_map = self.tcx.sess.source_map();
1885 let (await_or_yield, an_await_or_yield) =
1886 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1887 let future_or_generator = if is_async { "future" } else { "generator" };
1889 // Special case the primary error message when send or sync is the trait that was
1891 let hir = self.tcx.hir();
1892 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
1893 self.tcx.get_diagnostic_name(trait_pred.def_id())
1895 let (trait_name, trait_verb) =
1896 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1899 err.set_primary_message(format!(
1900 "{} cannot be {} between threads safely",
1901 future_or_generator, trait_verb
1904 let original_span = err.span.primary_span().unwrap();
1905 let original_span = self.tcx.sess.source_map().guess_head_span(original_span);
1906 let mut span = MultiSpan::from_span(original_span);
1908 let message = outer_generator
1909 .and_then(|generator_did| {
1910 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1911 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1912 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1914 .parent(generator_did)
1916 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
1917 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1919 format!("future returned by `{}` is not {}", name, trait_name)
1921 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1922 format!("future created by async block is not {}", trait_name)
1924 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1925 format!("future created by async closure is not {}", trait_name)
1929 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1931 span.push_span_label(original_span, message);
1934 format!("is not {}", trait_name)
1936 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
1939 let mut explain_yield = |interior_span: Span,
1941 scope_span: Option<Span>| {
1942 let mut span = MultiSpan::from_span(yield_span);
1943 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1944 // #70935: If snippet contains newlines, display "the value" instead
1945 // so that we do not emit complex diagnostics.
1946 let snippet = &format!("`{}`", snippet);
1947 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
1948 // note: future is not `Send` as this value is used across an await
1949 // --> $DIR/issue-70935-complex-spans.rs:13:9
1951 // LL | baz(|| async {
1952 // | ______________-
1955 // LL | | foo(tx.clone());
1957 // | | - ^^^^^^ await occurs here, with value maybe used later
1959 // | has type `closure` which is not `Send`
1960 // note: value is later dropped here
1964 span.push_span_label(
1966 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
1968 span.push_span_label(
1970 format!("has type `{}` which {}", target_ty, trait_explanation),
1972 // If available, use the scope span to annotate the drop location.
1973 let mut scope_note = None;
1974 if let Some(scope_span) = scope_span {
1975 let scope_span = source_map.end_point(scope_span);
1977 let msg = format!("{} is later dropped here", snippet);
1978 if source_map.is_multiline(yield_span.between(scope_span)) {
1979 span.push_span_label(scope_span, msg);
1981 scope_note = Some((scope_span, msg));
1987 "{} {} as this value is used across {}",
1988 future_or_generator, trait_explanation, an_await_or_yield
1991 if let Some((span, msg)) = scope_note {
1992 err.span_note(span, &msg);
1996 match interior_or_upvar_span {
1997 GeneratorInteriorOrUpvar::Interior(interior_span) => {
1998 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
1999 if let Some(await_span) = from_awaited_ty {
2000 // The type causing this obligation is one being awaited at await_span.
2001 let mut span = MultiSpan::from_span(await_span);
2002 span.push_span_label(
2005 "await occurs here on type `{}`, which {}",
2006 target_ty, trait_explanation
2012 "future {not_trait} as it awaits another future which {not_trait}",
2013 not_trait = trait_explanation
2017 // Look at the last interior type to get a span for the `.await`.
2019 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
2020 typeck_results.as_ref().map(|t| &t.generator_interior_types)
2022 explain_yield(interior_span, yield_span, scope_span);
2025 if let Some(expr_id) = expr {
2026 let expr = hir.expect_expr(expr_id);
2027 debug!("target_ty evaluated from {:?}", expr);
2029 let parent = hir.get_parent_node(expr_id);
2030 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2031 let parent_span = hir.span(parent);
2032 let parent_did = parent.owner.to_def_id();
2035 // fn foo(&self) -> i32 {}
2038 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2041 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2043 .expr_adjustments(expr)
2045 .any(|adj| adj.is_region_borrow())
2051 // struct Foo(*const u8);
2052 // bar(Foo(std::ptr::null())).await;
2053 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2055 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
2056 let is_raw_borrow_inside_fn_like_call =
2057 match self.tcx.def_kind(parent_did) {
2058 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2061 if let Some(typeck_results) = typeck_results {
2062 if (typeck_results.is_method_call(e) && is_region_borrow)
2063 || is_raw_borrow_inside_fn_like_call
2067 "consider moving this into a `let` \
2068 binding to create a shorter lived borrow",
2076 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2077 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2078 let refers_to_non_sync = match target_ty.kind() {
2079 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2080 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2086 let (span_label, span_note) = match refers_to_non_sync {
2087 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2088 // include suggestions to make `T: Sync` so that `&T: Send`
2091 "has type `{}` which {}, because `{}` is not `Sync`",
2092 target_ty, trait_explanation, ref_ty
2095 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2100 format!("has type `{}` which {}", target_ty, trait_explanation),
2101 format!("captured value {}", trait_explanation),
2105 let mut span = MultiSpan::from_span(upvar_span);
2106 span.push_span_label(upvar_span, span_label);
2107 err.span_note(span, &span_note);
2111 // Add a note for the item obligation that remains - normally a note pointing to the
2112 // bound that introduced the obligation (e.g. `T: Send`).
2113 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2114 self.note_obligation_cause_code(
2116 &obligation.predicate,
2117 obligation.param_env,
2120 &mut Default::default(),
2124 fn note_obligation_cause_code<T>(
2126 err: &mut Diagnostic,
2128 param_env: ty::ParamEnv<'tcx>,
2129 cause_code: &ObligationCauseCode<'tcx>,
2130 obligated_types: &mut Vec<Ty<'tcx>>,
2131 seen_requirements: &mut FxHashSet<DefId>,
2137 ObligationCauseCode::ExprAssignable
2138 | ObligationCauseCode::MatchExpressionArm { .. }
2139 | ObligationCauseCode::Pattern { .. }
2140 | ObligationCauseCode::IfExpression { .. }
2141 | ObligationCauseCode::IfExpressionWithNoElse
2142 | ObligationCauseCode::MainFunctionType
2143 | ObligationCauseCode::StartFunctionType
2144 | ObligationCauseCode::IntrinsicType
2145 | ObligationCauseCode::MethodReceiver
2146 | ObligationCauseCode::ReturnNoExpression
2147 | ObligationCauseCode::UnifyReceiver(..)
2148 | ObligationCauseCode::OpaqueType
2149 | ObligationCauseCode::MiscObligation
2150 | ObligationCauseCode::WellFormed(..)
2151 | ObligationCauseCode::MatchImpl(..)
2152 | ObligationCauseCode::ReturnType
2153 | ObligationCauseCode::ReturnValue(_)
2154 | ObligationCauseCode::BlockTailExpression(_)
2155 | ObligationCauseCode::AwaitableExpr(_)
2156 | ObligationCauseCode::ForLoopIterator
2157 | ObligationCauseCode::QuestionMark
2158 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2159 | ObligationCauseCode::LetElse
2160 | ObligationCauseCode::BinOp { .. } => {}
2161 ObligationCauseCode::SliceOrArrayElem => {
2162 err.note("slice and array elements must have `Sized` type");
2164 ObligationCauseCode::TupleElem => {
2165 err.note("only the last element of a tuple may have a dynamically sized type");
2167 ObligationCauseCode::ProjectionWf(data) => {
2168 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2170 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2172 "required so that reference `{}` does not outlive its referent",
2176 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2178 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2182 ObligationCauseCode::ItemObligation(_item_def_id) => {
2183 // We hold the `DefId` of the item introducing the obligation, but displaying it
2184 // doesn't add user usable information. It always point at an associated item.
2186 ObligationCauseCode::BindingObligation(item_def_id, span) => {
2187 let item_name = tcx.def_path_str(item_def_id);
2188 let mut multispan = MultiSpan::from(span);
2189 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2190 let sm = tcx.sess.source_map();
2192 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2193 (Ok(l), Ok(r)) => l.line == r.line,
2196 if !ident.span.overlaps(span) && !same_line {
2198 .push_span_label(ident.span, "required by a bound in this".to_string());
2201 let descr = format!("required by a bound in `{}`", item_name);
2202 if span != DUMMY_SP {
2203 let msg = format!("required by this bound in `{}`", item_name);
2204 multispan.push_span_label(span, msg);
2205 err.span_note(multispan, &descr);
2207 err.span_note(tcx.def_span(item_def_id), &descr);
2210 ObligationCauseCode::ObjectCastObligation(object_ty) => {
2212 "required for the cast to the object type `{}`",
2213 self.ty_to_string(object_ty)
2216 ObligationCauseCode::Coercion { source: _, target } => {
2217 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2219 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2221 "the `Copy` trait is required because this value will be copied for each element of the array",
2226 "consider creating a new `const` item and initializing it with the result \
2227 of the function call to be used in the repeat position, like \
2228 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2232 if self.tcx.sess.is_nightly_build() && is_const_fn {
2234 "create an inline `const` block, see RFC #2920 \
2235 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2239 ObligationCauseCode::VariableType(hir_id) => {
2240 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2241 match self.tcx.hir().find(parent_node) {
2242 Some(Node::Local(hir::Local {
2243 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2246 // When encountering an assignment of an unsized trait, like
2247 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2248 // order to use have a slice instead.
2249 err.span_suggestion_verbose(
2250 span.shrink_to_lo(),
2251 "consider borrowing here",
2253 Applicability::MachineApplicable,
2255 err.note("all local variables must have a statically known size");
2257 Some(Node::Param(param)) => {
2258 err.span_suggestion_verbose(
2259 param.ty_span.shrink_to_lo(),
2260 "function arguments must have a statically known size, borrowed types \
2261 always have a known size",
2263 Applicability::MachineApplicable,
2267 err.note("all local variables must have a statically known size");
2270 if !self.tcx.features().unsized_locals {
2271 err.help("unsized locals are gated as an unstable feature");
2274 ObligationCauseCode::SizedArgumentType(sp) => {
2275 if let Some(span) = sp {
2276 err.span_suggestion_verbose(
2277 span.shrink_to_lo(),
2278 "function arguments must have a statically known size, borrowed types \
2279 always have a known size",
2281 Applicability::MachineApplicable,
2284 err.note("all function arguments must have a statically known size");
2286 if tcx.sess.opts.unstable_features.is_nightly_build()
2287 && !self.tcx.features().unsized_fn_params
2289 err.help("unsized fn params are gated as an unstable feature");
2292 ObligationCauseCode::SizedReturnType => {
2293 err.note("the return type of a function must have a statically known size");
2295 ObligationCauseCode::SizedYieldType => {
2296 err.note("the yield type of a generator must have a statically known size");
2298 ObligationCauseCode::SizedBoxType => {
2299 err.note("the type of a box expression must have a statically known size");
2301 ObligationCauseCode::AssignmentLhsSized => {
2302 err.note("the left-hand-side of an assignment must have a statically known size");
2304 ObligationCauseCode::TupleInitializerSized => {
2305 err.note("tuples must have a statically known size to be initialized");
2307 ObligationCauseCode::StructInitializerSized => {
2308 err.note("structs must have a statically known size to be initialized");
2310 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2312 AdtKind::Struct => {
2315 "the last field of a packed struct may only have a \
2316 dynamically sized type if it does not need drop to be run",
2320 "only the last field of a struct may have a dynamically sized type",
2325 err.note("no field of a union may have a dynamically sized type");
2328 err.note("no field of an enum variant may have a dynamically sized type");
2331 err.help("change the field's type to have a statically known size");
2332 err.span_suggestion(
2333 span.shrink_to_lo(),
2334 "borrowed types always have a statically known size",
2336 Applicability::MachineApplicable,
2338 err.multipart_suggestion(
2339 "the `Box` type always has a statically known size and allocates its contents \
2342 (span.shrink_to_lo(), "Box<".to_string()),
2343 (span.shrink_to_hi(), ">".to_string()),
2345 Applicability::MachineApplicable,
2348 ObligationCauseCode::ConstSized => {
2349 err.note("constant expressions must have a statically known size");
2351 ObligationCauseCode::InlineAsmSized => {
2352 err.note("all inline asm arguments must have a statically known size");
2354 ObligationCauseCode::ConstPatternStructural => {
2355 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2357 ObligationCauseCode::SharedStatic => {
2358 err.note("shared static variables must have a type that implements `Sync`");
2360 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2361 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2362 let ty = parent_trait_ref.skip_binder().self_ty();
2363 if parent_trait_ref.references_error() {
2364 // NOTE(eddyb) this was `.cancel()`, but `err`
2365 // is borrowed, so we can't fully defuse it.
2366 err.downgrade_to_delayed_bug();
2370 // If the obligation for a tuple is set directly by a Generator or Closure,
2371 // then the tuple must be the one containing capture types.
2372 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2375 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2377 let parent_trait_ref =
2378 self.resolve_vars_if_possible(data.parent_trait_pred);
2379 let ty = parent_trait_ref.skip_binder().self_ty();
2380 matches!(ty.kind(), ty::Generator(..))
2381 || matches!(ty.kind(), ty::Closure(..))
2387 // Don't print the tuple of capture types
2388 if !is_upvar_tys_infer_tuple {
2389 let msg = format!("required because it appears within the type `{}`", ty);
2391 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2392 Some(ident) => err.span_note(ident.span, &msg),
2393 None => err.note(&msg),
2395 _ => err.note(&msg),
2399 obligated_types.push(ty);
2401 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2402 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2403 // #74711: avoid a stack overflow
2404 ensure_sufficient_stack(|| {
2405 self.note_obligation_cause_code(
2415 ensure_sufficient_stack(|| {
2416 self.note_obligation_cause_code(
2420 cause_code.peel_derives(),
2427 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2428 let mut parent_trait_pred =
2429 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2430 parent_trait_pred.remap_constness_diag(param_env);
2431 let parent_def_id = parent_trait_pred.def_id();
2433 "required because of the requirements on the impl of `{}` for `{}`",
2434 parent_trait_pred.print_modifiers_and_trait_path(),
2435 parent_trait_pred.skip_binder().self_ty()
2437 let mut is_auto_trait = false;
2438 match self.tcx.hir().get_if_local(data.impl_def_id) {
2439 Some(Node::Item(hir::Item {
2440 kind: hir::ItemKind::Trait(is_auto, ..),
2444 // FIXME: we should do something else so that it works even on crate foreign
2446 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2447 err.span_note(ident.span, &msg)
2449 Some(Node::Item(hir::Item {
2450 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2453 let mut spans = Vec::with_capacity(2);
2454 if let Some(trait_ref) = of_trait {
2455 spans.push(trait_ref.path.span);
2457 spans.push(self_ty.span);
2458 err.span_note(spans, &msg)
2460 _ => err.note(&msg),
2463 let mut parent_predicate = parent_trait_pred.to_predicate(tcx);
2464 let mut data = &data.derived;
2466 seen_requirements.insert(parent_def_id);
2468 // We don't want to point at the ADT saying "required because it appears within
2469 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2470 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2473 let child_trait_ref =
2474 self.resolve_vars_if_possible(derived.parent_trait_pred);
2475 let child_def_id = child_trait_ref.def_id();
2476 if seen_requirements.insert(child_def_id) {
2480 parent_predicate = child_trait_ref.to_predicate(tcx);
2481 parent_trait_pred = child_trait_ref;
2484 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2485 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2486 let child_trait_pred =
2487 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2488 let child_def_id = child_trait_pred.def_id();
2489 if seen_requirements.insert(child_def_id) {
2493 data = &child.derived;
2494 parent_predicate = child_trait_pred.to_predicate(tcx);
2495 parent_trait_pred = child_trait_pred;
2499 "{} redundant requirement{} hidden",
2504 "required because of the requirements on the impl of `{}` for `{}`",
2505 parent_trait_pred.print_modifiers_and_trait_path(),
2506 parent_trait_pred.skip_binder().self_ty()
2509 // #74711: avoid a stack overflow
2510 ensure_sufficient_stack(|| {
2511 self.note_obligation_cause_code(
2521 ObligationCauseCode::DerivedObligation(ref data) => {
2522 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2523 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2524 // #74711: avoid a stack overflow
2525 ensure_sufficient_stack(|| {
2526 self.note_obligation_cause_code(
2536 ObligationCauseCode::FunctionArgumentObligation {
2541 let hir = self.tcx.hir();
2542 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2543 hir.find(arg_hir_id)
2545 let in_progress_typeck_results =
2546 self.in_progress_typeck_results.map(|t| t.borrow());
2547 let parent_id = hir.get_parent_item(arg_hir_id);
2548 let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
2549 Some(t) if t.hir_owner == parent_id => t,
2550 _ => self.tcx.typeck(parent_id),
2552 let ty = typeck_results.expr_ty_adjusted(expr);
2553 let span = expr.peel_blocks().span;
2554 if Some(span) != err.span.primary_span() {
2557 &if ty.references_error() {
2560 format!("this tail expression is of type `{:?}`", ty)
2565 if let Some(Node::Expr(hir::Expr {
2567 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2568 | hir::ExprKind::MethodCall(
2569 hir::PathSegment { ident: Ident { span, .. }, .. },
2573 })) = hir.find(call_hir_id)
2575 if Some(*span) != err.span.primary_span() {
2576 err.span_label(*span, "required by a bound introduced by this call");
2579 ensure_sufficient_stack(|| {
2580 self.note_obligation_cause_code(
2590 ObligationCauseCode::CompareImplMethodObligation { trait_item_def_id, .. } => {
2591 let item_name = self.tcx.item_name(trait_item_def_id);
2593 "the requirement `{}` appears on the impl method `{}` but not on the \
2594 corresponding trait method",
2595 predicate, item_name,
2599 .opt_item_ident(trait_item_def_id)
2601 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2602 let mut assoc_span: MultiSpan = sp.into();
2603 assoc_span.push_span_label(
2605 format!("this trait method doesn't have the requirement `{}`", predicate),
2607 if let Some(ident) = self
2609 .opt_associated_item(trait_item_def_id)
2610 .and_then(|i| self.tcx.opt_item_ident(i.container.id()))
2612 assoc_span.push_span_label(ident.span, "in this trait");
2614 err.span_note(assoc_span, &msg);
2616 ObligationCauseCode::CompareImplTypeObligation { trait_item_def_id, .. } => {
2617 let item_name = self.tcx.item_name(trait_item_def_id);
2619 "the requirement `{}` appears on the associated impl type `{}` but not on the \
2620 corresponding associated trait type",
2621 predicate, item_name,
2623 let sp = self.tcx.def_span(trait_item_def_id);
2624 let mut assoc_span: MultiSpan = sp.into();
2625 assoc_span.push_span_label(
2628 "this trait associated type doesn't have the requirement `{}`",
2632 if let Some(ident) = self
2634 .opt_associated_item(trait_item_def_id)
2635 .and_then(|i| self.tcx.opt_item_ident(i.container.id()))
2637 assoc_span.push_span_label(ident.span, "in this trait");
2639 err.span_note(assoc_span, &msg);
2641 ObligationCauseCode::CompareImplConstObligation => {
2643 "the requirement `{}` appears on the associated impl constant \
2644 but not on the corresponding associated trait constant",
2648 ObligationCauseCode::TrivialBound => {
2649 err.help("see issue #48214");
2650 if tcx.sess.opts.unstable_features.is_nightly_build() {
2651 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2657 fn suggest_new_overflow_limit(&self, err: &mut Diagnostic) {
2658 let suggested_limit = match self.tcx.recursion_limit() {
2659 Limit(0) => Limit(2),
2663 "consider increasing the recursion limit by adding a \
2664 `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
2666 self.tcx.crate_name(LOCAL_CRATE),
2670 fn suggest_await_before_try(
2672 err: &mut Diagnostic,
2673 obligation: &PredicateObligation<'tcx>,
2674 trait_pred: ty::PolyTraitPredicate<'tcx>,
2678 "suggest_await_before_try: obligation={:?}, span={:?}, trait_pred={:?}, trait_pred_self_ty={:?}",
2682 trait_pred.self_ty()
2684 let body_hir_id = obligation.cause.body_id;
2685 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2687 if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
2688 let body = self.tcx.hir().body(body_id);
2689 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2690 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2692 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2694 // Do not check on infer_types to avoid panic in evaluate_obligation.
2695 if self_ty.has_infer_types() {
2698 let self_ty = self.tcx.erase_regions(self_ty);
2700 let impls_future = self.type_implements_trait(
2702 self_ty.skip_binder(),
2704 obligation.param_env,
2707 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2708 // `<T as Future>::Output`
2709 let projection_ty = ty::ProjectionTy {
2711 substs: self.tcx.mk_substs_trait(
2712 trait_pred.self_ty().skip_binder(),
2713 &self.fresh_substs_for_item(span, item_def_id)[1..],
2719 let mut selcx = SelectionContext::new(self);
2721 let mut obligations = vec![];
2722 let normalized_ty = normalize_projection_type(
2724 obligation.param_env,
2726 obligation.cause.clone(),
2732 "suggest_await_before_try: normalized_projection_type {:?}",
2733 self.resolve_vars_if_possible(normalized_ty)
2735 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2736 obligation.param_env,
2737 trait_pred.map_bound(|trait_pred| (trait_pred, normalized_ty.ty().unwrap())),
2739 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2740 if self.predicate_may_hold(&try_obligation)
2741 && impls_future.must_apply_modulo_regions()
2742 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2743 && snippet.ends_with('?')
2745 err.span_suggestion_verbose(
2746 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2747 "consider `await`ing on the `Future`",
2748 ".await".to_string(),
2749 Applicability::MaybeIncorrect,
2756 fn suggest_floating_point_literal(
2758 obligation: &PredicateObligation<'tcx>,
2759 err: &mut Diagnostic,
2760 trait_ref: &ty::PolyTraitRef<'tcx>,
2762 let rhs_span = match obligation.cause.code() {
2763 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit } if *is_lit => span,
2767 trait_ref.skip_binder().self_ty().kind(),
2768 trait_ref.skip_binder().substs.type_at(1).kind(),
2770 (ty::Float(_), ty::Infer(InferTy::IntVar(_))) => {
2771 err.span_suggestion_verbose(
2772 rhs_span.shrink_to_hi(),
2773 "consider using a floating-point literal by writing it with `.0`",
2775 Applicability::MaybeIncorrect,
2784 obligation: &PredicateObligation<'tcx>,
2785 err: &mut Diagnostic,
2786 trait_pred: ty::PolyTraitPredicate<'tcx>,
2788 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
2791 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
2792 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
2796 let is_derivable_trait = match diagnostic_name {
2797 sym::Default => !adt.is_enum(),
2798 sym::PartialEq | sym::PartialOrd => {
2799 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
2800 trait_pred.skip_binder().self_ty() == rhs_ty
2802 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
2805 is_derivable_trait &&
2806 // Ensure all fields impl the trait.
2807 adt.all_fields().all(|field| {
2808 let field_ty = field.ty(self.tcx, substs);
2809 let trait_substs = match diagnostic_name {
2810 sym::PartialEq | sym::PartialOrd => {
2811 self.tcx.mk_substs_trait(field_ty, &[field_ty.into()])
2813 _ => self.tcx.mk_substs_trait(field_ty, &[]),
2815 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
2816 trait_ref: ty::TraitRef {
2817 substs: trait_substs,
2818 ..trait_pred.skip_binder().trait_ref
2822 let field_obl = Obligation::new(
2823 obligation.cause.clone(),
2824 obligation.param_env,
2825 trait_pred.to_predicate(self.tcx),
2827 self.predicate_must_hold_modulo_regions(&field_obl)
2831 err.span_suggestion_verbose(
2832 self.tcx.def_span(adt.did()).shrink_to_lo(),
2834 "consider annotating `{}` with `#[derive({})]`",
2835 trait_pred.skip_binder().self_ty(),
2838 format!("#[derive({})]\n", diagnostic_name),
2839 Applicability::MaybeIncorrect,
2845 /// Collect all the returned expressions within the input expression.
2846 /// Used to point at the return spans when we want to suggest some change to them.
2848 pub struct ReturnsVisitor<'v> {
2849 pub returns: Vec<&'v hir::Expr<'v>>,
2850 in_block_tail: bool,
2853 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2854 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2855 // Visit every expression to detect `return` paths, either through the function's tail
2856 // expression or `return` statements. We walk all nodes to find `return` statements, but
2857 // we only care about tail expressions when `in_block_tail` is `true`, which means that
2858 // they're in the return path of the function body.
2860 hir::ExprKind::Ret(Some(ex)) => {
2861 self.returns.push(ex);
2863 hir::ExprKind::Block(block, _) if self.in_block_tail => {
2864 self.in_block_tail = false;
2865 for stmt in block.stmts {
2866 hir::intravisit::walk_stmt(self, stmt);
2868 self.in_block_tail = true;
2869 if let Some(expr) = block.expr {
2870 self.visit_expr(expr);
2873 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
2874 self.visit_expr(then);
2875 if let Some(el) = else_opt {
2876 self.visit_expr(el);
2879 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2881 self.visit_expr(arm.body);
2884 // We need to walk to find `return`s in the entire body.
2885 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2886 _ => self.returns.push(ex),
2890 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2891 assert!(!self.in_block_tail);
2892 if body.generator_kind().is_none() {
2893 if let hir::ExprKind::Block(block, None) = body.value.kind {
2894 if block.expr.is_some() {
2895 self.in_block_tail = true;
2899 hir::intravisit::walk_body(self, body);
2903 /// Collect all the awaited expressions within the input expression.
2905 struct AwaitsVisitor {
2906 awaits: Vec<hir::HirId>,
2909 impl<'v> Visitor<'v> for AwaitsVisitor {
2910 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2911 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2912 self.awaits.push(id)
2914 hir::intravisit::walk_expr(self, ex)
2918 pub trait NextTypeParamName {
2919 fn next_type_param_name(&self, name: Option<&str>) -> String;
2922 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2923 fn next_type_param_name(&self, name: Option<&str>) -> String {
2924 // This is the list of possible parameter names that we might suggest.
2925 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2926 let name = name.as_deref();
2927 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2928 let used_names = self
2930 .filter_map(|p| match p.name {
2931 hir::ParamName::Plain(ident) => Some(ident.name),
2934 .collect::<Vec<_>>();
2938 .find(|n| !used_names.contains(&Symbol::intern(n)))
2939 .unwrap_or(&"ParamName")
2944 fn suggest_trait_object_return_type_alternatives(
2945 err: &mut Diagnostic,
2948 is_object_safe: bool,
2950 err.span_suggestion(
2952 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2955 Applicability::MaybeIncorrect,
2957 err.span_suggestion(
2960 "use `impl {}` as the return type if all return paths have the same type but you \
2961 want to expose only the trait in the signature",
2964 format!("impl {}", trait_obj),
2965 Applicability::MaybeIncorrect,
2968 err.multipart_suggestion(
2970 "use a boxed trait object if all return paths implement trait `{}`",
2974 (ret_ty.shrink_to_lo(), "Box<".to_string()),
2975 (ret_ty.shrink_to_hi(), ">".to_string()),
2977 Applicability::MaybeIncorrect,