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, DiagnosticBuilder, Style,
16 use rustc_hir::def::DefKind;
17 use rustc_hir::def_id::DefId;
18 use rustc_hir::intravisit::Visitor;
19 use rustc_hir::lang_items::LangItem;
20 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
21 use rustc_middle::ty::{
22 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
23 Infer, InferTy, ToPredicate, Ty, TyCtxt, TypeFoldable,
25 use rustc_middle::ty::{TypeAndMut, TypeckResults};
26 use rustc_session::Limit;
27 use rustc_span::def_id::LOCAL_CRATE;
28 use rustc_span::symbol::{kw, sym, Ident, Symbol};
29 use rustc_span::{BytePos, DesugaringKind, ExpnKind, MultiSpan, Span, DUMMY_SP};
30 use rustc_target::spec::abi;
33 use super::InferCtxtPrivExt;
34 use crate::infer::InferCtxtExt as _;
35 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
36 use rustc_middle::ty::print::with_no_trimmed_paths;
39 pub enum GeneratorInteriorOrUpvar {
40 // span of interior type
46 // This trait is public to expose the diagnostics methods to clippy.
47 pub trait InferCtxtExt<'tcx> {
48 fn suggest_restricting_param_bound(
50 err: &mut DiagnosticBuilder<'_>,
51 trait_pred: ty::PolyTraitPredicate<'tcx>,
55 fn suggest_dereferences(
57 obligation: &PredicateObligation<'tcx>,
58 err: &mut DiagnosticBuilder<'tcx>,
59 trait_pred: ty::PolyTraitPredicate<'tcx>,
65 err: &mut DiagnosticBuilder<'_>,
71 obligation: &PredicateObligation<'tcx>,
72 err: &mut DiagnosticBuilder<'_>,
73 trait_pred: ty::PolyTraitPredicate<'tcx>,
76 fn suggest_add_reference_to_arg(
78 obligation: &PredicateObligation<'tcx>,
79 err: &mut DiagnosticBuilder<'_>,
80 trait_pred: ty::PolyTraitPredicate<'tcx>,
81 has_custom_message: bool,
84 fn suggest_remove_reference(
86 obligation: &PredicateObligation<'tcx>,
87 err: &mut DiagnosticBuilder<'_>,
88 trait_pred: ty::PolyTraitPredicate<'tcx>,
91 fn suggest_remove_await(
93 obligation: &PredicateObligation<'tcx>,
94 err: &mut DiagnosticBuilder<'_>,
97 fn suggest_change_mut(
99 obligation: &PredicateObligation<'tcx>,
100 err: &mut DiagnosticBuilder<'_>,
101 trait_pred: ty::PolyTraitPredicate<'tcx>,
104 fn suggest_semicolon_removal(
106 obligation: &PredicateObligation<'tcx>,
107 err: &mut DiagnosticBuilder<'_>,
109 trait_pred: ty::PolyTraitPredicate<'tcx>,
112 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
114 fn suggest_impl_trait(
116 err: &mut DiagnosticBuilder<'_>,
118 obligation: &PredicateObligation<'tcx>,
119 trait_pred: ty::PolyTraitPredicate<'tcx>,
122 fn point_at_returns_when_relevant(
124 err: &mut DiagnosticBuilder<'_>,
125 obligation: &PredicateObligation<'tcx>,
128 fn report_closure_arg_mismatch(
131 found_span: Option<Span>,
132 expected_ref: ty::PolyTraitRef<'tcx>,
133 found: ty::PolyTraitRef<'tcx>,
134 ) -> DiagnosticBuilder<'tcx>;
136 fn suggest_fully_qualified_path(
138 err: &mut DiagnosticBuilder<'_>,
144 fn maybe_note_obligation_cause_for_async_await(
146 err: &mut DiagnosticBuilder<'_>,
147 obligation: &PredicateObligation<'tcx>,
150 fn note_obligation_cause_for_async_await(
152 err: &mut DiagnosticBuilder<'_>,
153 interior_or_upvar_span: GeneratorInteriorOrUpvar,
154 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
155 inner_generator_body: Option<&hir::Body<'tcx>>,
156 outer_generator: Option<DefId>,
157 trait_pred: ty::TraitPredicate<'tcx>,
159 typeck_results: Option<&ty::TypeckResults<'tcx>>,
160 obligation: &PredicateObligation<'tcx>,
161 next_code: Option<&ObligationCauseCode<'tcx>>,
164 fn note_obligation_cause_code<T>(
166 err: &mut DiagnosticBuilder<'_>,
168 param_env: ty::ParamEnv<'tcx>,
169 cause_code: &ObligationCauseCode<'tcx>,
170 obligated_types: &mut Vec<Ty<'tcx>>,
171 seen_requirements: &mut FxHashSet<DefId>,
175 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>);
177 /// Suggest to await before try: future? => future.await?
178 fn suggest_await_before_try(
180 err: &mut DiagnosticBuilder<'_>,
181 obligation: &PredicateObligation<'tcx>,
182 trait_pred: ty::PolyTraitPredicate<'tcx>,
187 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
189 generics.where_clause.tail_span_for_suggestion(),
192 if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
198 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
199 /// it can also be an `impl Trait` param that needs to be decomposed to a type
200 /// param for cleaner code.
201 fn suggest_restriction<'tcx>(
203 generics: &hir::Generics<'tcx>,
205 err: &mut DiagnosticBuilder<'_>,
206 fn_sig: Option<&hir::FnSig<'_>>,
207 projection: Option<&ty::ProjectionTy<'_>>,
208 trait_pred: ty::PolyTraitPredicate<'tcx>,
209 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
211 // When we are dealing with a trait, `super_traits` will be `Some`:
212 // Given `trait T: A + B + C {}`
213 // - ^^^^^^^^^ GenericBounds
216 let span = generics.where_clause.span_for_predicates_or_empty_place();
217 if span.from_expansion() || span.desugaring_kind().is_some() {
220 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
221 if let Some((bound_str, fn_sig)) =
222 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
223 // Shenanigans to get the `Trait` from the `impl Trait`.
224 ty::Param(param) => {
225 // `fn foo(t: impl Trait)`
226 // ^^^^^ get this string
227 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
232 // We know we have an `impl Trait` that doesn't satisfy a required projection.
234 // Find all of the ocurrences of `impl Trait` for `Trait` in the function arguments'
235 // types. There should be at least one, but there might be *more* than one. In that
236 // case we could just ignore it and try to identify which one needs the restriction,
237 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
239 let mut ty_spans = vec![];
240 let impl_trait_str = format!("impl {}", bound_str);
241 for input in fn_sig.decl.inputs {
242 if let hir::TyKind::Path(hir::QPath::Resolved(
244 hir::Path { segments: [segment], .. },
247 if segment.ident.as_str() == impl_trait_str.as_str() {
248 // `fn foo(t: impl Trait)`
249 // ^^^^^^^^^^ get this to suggest `T` instead
251 // There might be more than one `impl Trait`.
252 ty_spans.push(input.span);
257 let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
258 // The type param `T: Trait` we will suggest to introduce.
259 let type_param = format!("{}: {}", type_param_name, bound_str);
261 // FIXME: modify the `trait_pred` instead of string shenanigans.
262 // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
263 let pred = trait_pred.to_predicate(tcx).to_string();
264 let pred = pred.replace(&impl_trait_str, &type_param_name);
266 // Find the last of the generic parameters contained within the span of
271 .map(|p| p.bounds_span_for_suggestions().unwrap_or(p.span.shrink_to_hi()))
272 .filter(|&span| generics.span.contains(span) && span.can_be_used_for_suggestions())
273 .max_by_key(|span| span.hi())
275 // `fn foo(t: impl Trait)`
276 // ^ suggest `<T: Trait>` here
277 None => (generics.span, format!("<{}>", type_param)),
278 // `fn foo<A>(t: impl Trait)`
279 // ^^^ suggest `<A, T: Trait>` here
280 Some(span) => (span, format!(", {}", type_param)),
282 // `fn foo(t: impl Trait)`
283 // ^ suggest `where <T as Trait>::A: Bound`
284 predicate_constraint(generics, pred),
286 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
288 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
289 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
290 // `fn foo(t: impl Trait<A: Bound>)` instead.
291 err.multipart_suggestion(
292 "introduce a type parameter with a trait bound instead of using `impl Trait`",
294 Applicability::MaybeIncorrect,
297 // Trivial case: `T` needs an extra bound: `T: Bound`.
298 let (sp, suggestion) = match (
302 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
305 (_, None) => predicate_constraint(generics, trait_pred.to_predicate(tcx).to_string()),
306 (None, Some((ident, []))) => (
307 ident.span.shrink_to_hi(),
308 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
310 (_, Some((_, [.., bounds]))) => (
311 bounds.span().shrink_to_hi(),
312 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
314 (Some(_), Some((_, []))) => (
315 generics.span.shrink_to_hi(),
316 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
320 err.span_suggestion_verbose(
322 &format!("consider further restricting {}", msg),
324 Applicability::MachineApplicable,
329 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
330 fn suggest_restricting_param_bound(
332 mut err: &mut DiagnosticBuilder<'_>,
333 trait_pred: ty::PolyTraitPredicate<'tcx>,
336 let self_ty = trait_pred.skip_binder().self_ty();
337 let (param_ty, projection) = match self_ty.kind() {
338 ty::Param(_) => (true, None),
339 ty::Projection(projection) => (false, Some(projection)),
343 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
344 // don't suggest `T: Sized + ?Sized`.
345 let mut hir_id = body_id;
346 while let Some(node) = self.tcx.hir().find(hir_id) {
348 hir::Node::Item(hir::Item {
350 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
352 }) if self_ty == self.tcx.types.self_param => {
354 // Restricting `Self` for a single method.
363 Some((ident, bounds)),
368 hir::Node::TraitItem(hir::TraitItem {
370 kind: hir::TraitItemKind::Fn(..),
372 }) if self_ty == self.tcx.types.self_param => {
374 // Restricting `Self` for a single method.
376 self.tcx, &generics, "`Self`", err, None, projection, trait_pred, None,
381 hir::Node::TraitItem(hir::TraitItem {
383 kind: hir::TraitItemKind::Fn(fn_sig, ..),
386 | hir::Node::ImplItem(hir::ImplItem {
388 kind: hir::ImplItemKind::Fn(fn_sig, ..),
391 | hir::Node::Item(hir::Item {
392 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
393 }) if projection.is_some() => {
394 // Missing restriction on associated type of type parameter (unmet projection).
398 "the associated type",
407 hir::Node::Item(hir::Item {
409 hir::ItemKind::Trait(_, _, generics, _, _)
410 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
412 }) if projection.is_some() => {
413 // Missing restriction on associated type of type parameter (unmet projection).
417 "the associated type",
427 hir::Node::Item(hir::Item {
429 hir::ItemKind::Struct(_, generics)
430 | hir::ItemKind::Enum(_, generics)
431 | hir::ItemKind::Union(_, generics)
432 | hir::ItemKind::Trait(_, _, generics, ..)
433 | hir::ItemKind::Impl(hir::Impl { generics, .. })
434 | hir::ItemKind::Fn(_, generics, _)
435 | hir::ItemKind::TyAlias(_, generics)
436 | hir::ItemKind::TraitAlias(generics, _)
437 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
440 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
441 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
444 // Missing generic type parameter bound.
445 let param_name = self_ty.to_string();
446 let constraint = with_no_trimmed_paths!(
447 trait_pred.print_modifiers_and_trait_path().to_string()
449 if suggest_constraining_type_param(
455 Some(trait_pred.def_id()),
461 hir::Node::Item(hir::Item {
463 hir::ItemKind::Struct(_, generics)
464 | hir::ItemKind::Enum(_, generics)
465 | hir::ItemKind::Union(_, generics)
466 | hir::ItemKind::Trait(_, _, generics, ..)
467 | hir::ItemKind::Impl(hir::Impl { generics, .. })
468 | hir::ItemKind::Fn(_, generics, _)
469 | hir::ItemKind::TyAlias(_, generics)
470 | hir::ItemKind::TraitAlias(generics, _)
471 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
474 // Missing generic type parameter bound.
475 let param_name = self_ty.to_string();
476 let constraint = trait_pred.print_modifiers_and_trait_path().to_string();
477 if suggest_arbitrary_trait_bound(generics, &mut err, ¶m_name, &constraint) {
481 hir::Node::Crate(..) => return,
486 hir_id = self.tcx.hir().local_def_id_to_hir_id(self.tcx.hir().get_parent_item(hir_id));
490 /// When after several dereferencing, the reference satisfies the trait
491 /// binding. This function provides dereference suggestion for this
492 /// specific situation.
493 fn suggest_dereferences(
495 obligation: &PredicateObligation<'tcx>,
496 err: &mut DiagnosticBuilder<'tcx>,
497 trait_pred: ty::PolyTraitPredicate<'tcx>,
499 // It only make sense when suggesting dereferences for arguments
500 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
501 obligation.cause.code()
507 let param_env = obligation.param_env;
508 let body_id = obligation.cause.body_id;
509 let span = obligation.cause.span;
510 let real_trait_pred = match &*code {
511 ObligationCauseCode::ImplDerivedObligation(cause)
512 | ObligationCauseCode::DerivedObligation(cause)
513 | ObligationCauseCode::BuiltinDerivedObligation(cause) => cause.parent_trait_pred,
516 let real_ty = match real_trait_pred.self_ty().no_bound_vars() {
521 if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
522 let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
523 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
525 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
527 self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_pred, ty);
528 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
531 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
532 // Don't care about `&mut` because `DerefMut` is used less
533 // often and user will not expect autoderef happens.
534 if src.starts_with('&') && !src.starts_with("&mut ") {
535 let derefs = "*".repeat(steps);
538 "consider adding dereference here",
539 format!("&{}{}", derefs, &src[1..]),
540 Applicability::MachineApplicable,
549 /// Given a closure's `DefId`, return the given name of the closure.
551 /// This doesn't account for reassignments, but it's only used for suggestions.
555 err: &mut DiagnosticBuilder<'_>,
557 ) -> Option<String> {
559 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
560 // Get the local name of this closure. This can be inaccurate because
561 // of the possibility of reassignment, but this should be good enough.
563 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
564 Some(format!("{}", name))
573 let hir = self.tcx.hir();
574 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
575 let parent_node = hir.get_parent_node(hir_id);
576 match hir.find(parent_node) {
577 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
578 get_name(err, &local.pat.kind)
580 // Different to previous arm because one is `&hir::Local` and the other
581 // is `P<hir::Local>`.
582 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
587 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
588 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
589 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
592 obligation: &PredicateObligation<'tcx>,
593 err: &mut DiagnosticBuilder<'_>,
594 trait_pred: ty::PolyTraitPredicate<'tcx>,
596 let self_ty = match trait_pred.self_ty().no_bound_vars() {
601 let (def_id, output_ty, callable) = match *self_ty.kind() {
602 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
603 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
606 let msg = format!("use parentheses to call the {}", callable);
608 // `mk_trait_obligation_with_new_self_ty` only works for types with no escaping bound
609 // variables, so bail out if we have any.
610 let output_ty = match output_ty.no_bound_vars() {
616 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred, output_ty);
618 match self.evaluate_obligation(&new_obligation) {
620 EvaluationResult::EvaluatedToOk
621 | EvaluationResult::EvaluatedToOkModuloRegions
622 | EvaluationResult::EvaluatedToAmbig,
626 let hir = self.tcx.hir();
627 // Get the name of the callable and the arguments to be used in the suggestion.
628 let (snippet, sugg) = match hir.get_if_local(def_id) {
629 Some(hir::Node::Expr(hir::Expr {
630 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
633 err.span_label(*span, "consider calling this closure");
634 let name = match self.get_closure_name(def_id, err, &msg) {
638 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
639 let sugg = format!("({})", args);
640 (format!("{}{}", name, sugg), sugg)
642 Some(hir::Node::Item(hir::Item {
644 kind: hir::ItemKind::Fn(.., body_id),
647 err.span_label(ident.span, "consider calling this function");
648 let body = hir.body(*body_id);
652 .map(|arg| match &arg.pat.kind {
653 hir::PatKind::Binding(_, _, ident, None)
654 // FIXME: provide a better suggestion when encountering `SelfLower`, it
655 // should suggest a method call.
656 if ident.name != kw::SelfLower => ident.to_string(),
657 _ => "_".to_string(),
661 let sugg = format!("({})", args);
662 (format!("{}{}", ident, sugg), sugg)
666 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
668 // When the obligation error has been ensured to have been caused by
669 // an argument, the `obligation.cause.span` points at the expression
670 // of the argument, so we can provide a suggestion. Otherwise, we give
671 // a more general note.
672 err.span_suggestion_verbose(
673 obligation.cause.span.shrink_to_hi(),
676 Applicability::HasPlaceholders,
679 err.help(&format!("{}: `{}`", msg, snippet));
683 fn suggest_add_reference_to_arg(
685 obligation: &PredicateObligation<'tcx>,
686 err: &mut DiagnosticBuilder<'_>,
687 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
688 has_custom_message: bool,
690 let span = obligation.cause.span;
692 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
693 obligation.cause.code()
696 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
697 span.ctxt().outer_expn_data().kind
699 obligation.cause.code()
704 // List of traits for which it would be nonsensical to suggest borrowing.
705 // For instance, immutable references are always Copy, so suggesting to
706 // borrow would always succeed, but it's probably not what the user wanted.
707 let mut never_suggest_borrow: Vec<_> =
708 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
710 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
713 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
714 never_suggest_borrow.push(def_id);
717 let param_env = obligation.param_env;
719 // Try to apply the original trait binding obligation by borrowing.
720 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
723 if blacklist.contains(&old_pred.def_id()) {
727 let orig_ty = old_pred.self_ty().skip_binder();
728 let mk_result = |new_ty| {
730 self.mk_trait_obligation_with_new_self_ty(param_env, old_pred, new_ty);
731 self.predicate_must_hold_modulo_regions(&obligation)
733 let imm_result = mk_result(self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, orig_ty));
734 let mut_result = mk_result(self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, orig_ty));
736 if imm_result || mut_result {
737 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
738 // We have a very specific type of error, where just borrowing this argument
739 // might solve the problem. In cases like this, the important part is the
740 // original type obligation, not the last one that failed, which is arbitrary.
741 // Because of this, we modify the error to refer to the original obligation and
742 // return early in the caller.
745 "the trait bound `{}: {}` is not satisfied",
747 old_pred.print_modifiers_and_trait_path(),
749 if has_custom_message {
752 err.message = vec![(msg, Style::NoStyle)];
754 if snippet.starts_with('&') {
755 // This is already a literal borrow and the obligation is failing
756 // somewhere else in the obligation chain. Do not suggest non-sense.
762 "expected an implementor of trait `{}`",
763 old_pred.print_modifiers_and_trait_path(),
767 // This if is to prevent a special edge-case
769 span.ctxt().outer_expn_data().kind,
770 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
772 // We don't want a borrowing suggestion on the fields in structs,
775 // the_foos: Vec<Foo>
779 if imm_result && mut_result {
780 err.span_suggestions(
782 "consider borrowing here",
783 ["&".to_string(), "&mut ".to_string()].into_iter(),
784 Applicability::MaybeIncorrect,
787 err.span_suggestion_verbose(
790 "consider{} borrowing here",
791 if mut_result { " mutably" } else { "" }
793 format!("&{}", if mut_result { "mut " } else { "" }),
794 Applicability::MaybeIncorrect,
804 if let ObligationCauseCode::ImplDerivedObligation(obligation) = code {
805 try_borrowing(obligation.parent_trait_pred, &[])
806 } else if let ObligationCauseCode::BindingObligation(_, _)
807 | ObligationCauseCode::ItemObligation(_) = code
809 try_borrowing(poly_trait_pred, &never_suggest_borrow)
815 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
816 /// suggest removing these references until we reach a type that implements the trait.
817 fn suggest_remove_reference(
819 obligation: &PredicateObligation<'tcx>,
820 err: &mut DiagnosticBuilder<'_>,
821 trait_pred: ty::PolyTraitPredicate<'tcx>,
823 let span = obligation.cause.span;
825 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
827 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
828 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
829 // Do not suggest removal of borrow from type arguments.
833 let mut suggested_ty = match trait_pred.self_ty().no_bound_vars() {
838 for refs_remaining in 0..refs_number {
839 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
842 suggested_ty = *inner_ty;
844 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
845 obligation.param_env,
850 if self.predicate_may_hold(&new_obligation) {
855 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
857 let remove_refs = refs_remaining + 1;
859 let msg = if remove_refs == 1 {
860 "consider removing the leading `&`-reference".to_string()
862 format!("consider removing {} leading `&`-references", remove_refs)
865 err.span_suggestion_short(
869 Applicability::MachineApplicable,
877 fn suggest_remove_await(
879 obligation: &PredicateObligation<'tcx>,
880 err: &mut DiagnosticBuilder<'_>,
882 let span = obligation.cause.span;
884 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
885 let hir = self.tcx.hir();
886 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
887 if let hir::Node::Expr(expr) = node {
888 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
889 // and if not maybe suggest doing something else? If we kept the expression around we
890 // could also check if it is an fn call (very likely) and suggest changing *that*, if
891 // it is from the local crate.
892 err.span_suggestion_verbose(
893 expr.span.shrink_to_hi().with_hi(span.hi()),
894 "remove the `.await`",
896 Applicability::MachineApplicable,
898 // FIXME: account for associated `async fn`s.
899 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
900 if let ty::PredicateKind::Trait(pred) =
901 obligation.predicate.kind().skip_binder()
905 &format!("this call returns `{}`", pred.self_ty()),
908 if let Some(typeck_results) =
909 self.in_progress_typeck_results.map(|t| t.borrow())
911 let ty = typeck_results.expr_ty_adjusted(base);
912 if let ty::FnDef(def_id, _substs) = ty.kind() {
913 if let Some(hir::Node::Item(hir::Item { span, ident, .. })) =
914 hir.get_if_local(*def_id)
916 err.span_suggestion_verbose(
919 "alternatively, consider making `fn {}` asynchronous",
922 "async ".to_string(),
923 Applicability::MaybeIncorrect,
934 /// Check if the trait bound is implemented for a different mutability and note it in the
936 fn suggest_change_mut(
938 obligation: &PredicateObligation<'tcx>,
939 err: &mut DiagnosticBuilder<'_>,
940 trait_pred: ty::PolyTraitPredicate<'tcx>,
942 let points_at_arg = matches!(
943 obligation.cause.code(),
944 ObligationCauseCode::FunctionArgumentObligation { .. },
947 let span = obligation.cause.span;
948 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
950 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
951 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
952 // Do not suggest removal of borrow from type arguments.
955 let trait_pred = self.resolve_vars_if_possible(trait_pred);
956 if trait_pred.has_infer_types_or_consts() {
957 // Do not ICE while trying to find if a reborrow would succeed on a trait with
958 // unresolved bindings.
962 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
964 if region.is_late_bound() || t_type.has_escaping_bound_vars() {
965 // Avoid debug assertion in `mk_obligation_for_def_id`.
967 // If the self type has escaping bound vars then it's not
968 // going to be the type of an expression, so the suggestion
969 // probably won't apply anyway.
973 let suggested_ty = match mutability {
974 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
975 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
978 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
979 obligation.param_env,
983 let suggested_ty_would_satisfy_obligation = self
984 .evaluate_obligation_no_overflow(&new_obligation)
985 .must_apply_modulo_regions();
986 if suggested_ty_would_satisfy_obligation {
991 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
992 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
993 err.span_suggestion_verbose(
995 "consider changing this borrow's mutability",
997 Applicability::MachineApplicable,
1001 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1002 trait_pred.print_modifiers_and_trait_path(),
1004 trait_pred.skip_binder().self_ty(),
1012 fn suggest_semicolon_removal(
1014 obligation: &PredicateObligation<'tcx>,
1015 err: &mut DiagnosticBuilder<'_>,
1017 trait_pred: ty::PolyTraitPredicate<'tcx>,
1019 let is_empty_tuple =
1020 |ty: ty::Binder<'tcx, Ty<'_>>| *ty.skip_binder().kind() == ty::Tuple(ty::List::empty());
1022 let hir = self.tcx.hir();
1023 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1024 let node = hir.find(parent_node);
1025 if let Some(hir::Node::Item(hir::Item {
1026 kind: hir::ItemKind::Fn(sig, _, body_id), ..
1029 let body = hir.body(*body_id);
1030 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1031 if sig.decl.output.span().overlaps(span)
1032 && blk.expr.is_none()
1033 && is_empty_tuple(trait_pred.self_ty())
1035 // FIXME(estebank): When encountering a method with a trait
1036 // bound not satisfied in the return type with a body that has
1037 // no return, suggest removal of semicolon on last statement.
1038 // Once that is added, close #54771.
1039 if let Some(ref stmt) = blk.stmts.last() {
1040 if let hir::StmtKind::Semi(_) = stmt.kind {
1041 let sp = self.tcx.sess.source_map().end_point(stmt.span);
1042 err.span_label(sp, "consider removing this semicolon");
1050 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1051 let hir = self.tcx.hir();
1052 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1053 let sig = match hir.find(parent_node) {
1054 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) => sig,
1058 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1061 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1062 /// applicable and signal that the error has been expanded appropriately and needs to be
1064 fn suggest_impl_trait(
1066 err: &mut DiagnosticBuilder<'_>,
1068 obligation: &PredicateObligation<'tcx>,
1069 trait_pred: ty::PolyTraitPredicate<'tcx>,
1071 match obligation.cause.code().peel_derives() {
1072 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1073 ObligationCauseCode::SizedReturnType => {}
1077 let hir = self.tcx.hir();
1078 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1079 let node = hir.find(parent_node);
1080 let Some(hir::Node::Item(hir::Item {
1081 kind: hir::ItemKind::Fn(sig, _, body_id),
1087 let body = hir.body(*body_id);
1088 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1089 let ty = trait_pred.skip_binder().self_ty();
1090 let is_object_safe = match ty.kind() {
1091 ty::Dynamic(predicates, _) => {
1092 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1095 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1097 // We only want to suggest `impl Trait` to `dyn Trait`s.
1098 // For example, `fn foo() -> str` needs to be filtered out.
1102 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1106 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1107 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1108 // Recursively look for `TraitObject` types and if there's only one, use that span to
1109 // suggest `impl Trait`.
1111 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1112 // otherwise suggest using `Box<dyn Trait>` or an enum.
1113 let mut visitor = ReturnsVisitor::default();
1114 visitor.visit_body(&body);
1116 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1118 let mut ret_types = visitor
1121 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1122 .map(|ty| self.resolve_vars_if_possible(ty));
1123 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1125 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1127 let ty = self.resolve_vars_if_possible(ty);
1129 !matches!(ty.kind(), ty::Error(_))
1130 && last_ty.map_or(true, |last_ty| {
1131 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1132 // *after* in the dependency graph.
1133 match (ty.kind(), last_ty.kind()) {
1134 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1135 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1136 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1138 Infer(InferTy::FreshFloatTy(_)),
1139 Infer(InferTy::FreshFloatTy(_)),
1144 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1147 let all_returns_conform_to_trait =
1148 if let Some(ty_ret_ty) = typeck_results.node_type_opt(ret_ty.hir_id) {
1149 match ty_ret_ty.kind() {
1150 ty::Dynamic(predicates, _) => {
1151 let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
1152 let param_env = ty::ParamEnv::empty();
1154 || ret_types.all(|returned_ty| {
1155 predicates.iter().all(|predicate| {
1156 let pred = predicate.with_self_ty(self.tcx, returned_ty);
1157 let obl = Obligation::new(cause.clone(), param_env, pred);
1158 self.predicate_may_hold(&obl)
1168 let sm = self.tcx.sess.source_map();
1169 let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
1170 // Verify that we're dealing with a return `dyn Trait`
1171 ret_ty.span.overlaps(span),
1173 sm.span_to_snippet(ret_ty.span),
1174 // If any of the return types does not conform to the trait, then we can't
1175 // suggest `impl Trait` nor trait objects: it is a type mismatch error.
1176 all_returns_conform_to_trait,
1180 err.code(error_code!(E0746));
1181 err.set_primary_message("return type cannot have an unboxed trait object");
1182 err.children.clear();
1183 let impl_trait_msg = "for information on `impl Trait`, see \
1184 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1185 #returning-types-that-implement-traits>";
1186 let trait_obj_msg = "for information on trait objects, see \
1187 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1188 #using-trait-objects-that-allow-for-values-of-different-types>";
1189 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1190 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1191 if only_never_return {
1192 // No return paths, probably using `panic!()` or similar.
1193 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1194 suggest_trait_object_return_type_alternatives(
1200 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1201 // Suggest `-> impl Trait`.
1202 err.span_suggestion(
1205 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1206 which implements `{1}`",
1209 format!("impl {}", trait_obj),
1210 Applicability::MachineApplicable,
1212 err.note(impl_trait_msg);
1215 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1216 // Get all the return values and collect their span and suggestion.
1217 let mut suggestions: Vec<_> = visitor
1222 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
1223 (expr.span.shrink_to_hi(), ")".to_string()),
1228 if !suggestions.is_empty() {
1229 // Add the suggestion for the return type.
1230 suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
1231 err.multipart_suggestion(
1232 "return a boxed trait object instead",
1234 Applicability::MaybeIncorrect,
1238 // This is currently not possible to trigger because E0038 takes precedence, but
1239 // leave it in for completeness in case anything changes in an earlier stage.
1241 "if trait `{}` were object-safe, you could return a trait object",
1245 err.note(trait_obj_msg);
1247 "if all the returned values were of the same type you could use `impl {}` as the \
1251 err.note(impl_trait_msg);
1252 err.note("you can create a new `enum` with a variant for each returned type");
1257 fn point_at_returns_when_relevant(
1259 err: &mut DiagnosticBuilder<'_>,
1260 obligation: &PredicateObligation<'tcx>,
1262 match obligation.cause.code().peel_derives() {
1263 ObligationCauseCode::SizedReturnType => {}
1267 let hir = self.tcx.hir();
1268 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1269 let node = hir.find(parent_node);
1270 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1273 let body = hir.body(*body_id);
1274 // Point at all the `return`s in the function as they have failed trait bounds.
1275 let mut visitor = ReturnsVisitor::default();
1276 visitor.visit_body(&body);
1277 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1278 for expr in &visitor.returns {
1279 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1280 let ty = self.resolve_vars_if_possible(returned_ty);
1281 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1287 fn report_closure_arg_mismatch(
1290 found_span: Option<Span>,
1291 expected_ref: ty::PolyTraitRef<'tcx>,
1292 found: ty::PolyTraitRef<'tcx>,
1293 ) -> DiagnosticBuilder<'tcx> {
1294 crate fn build_fn_sig_string<'tcx>(
1296 trait_ref: ty::PolyTraitRef<'tcx>,
1298 let inputs = trait_ref.skip_binder().substs.type_at(1);
1299 let sig = match inputs.kind() {
1301 if tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1305 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1307 hir::Unsafety::Normal,
1312 std::iter::once(inputs),
1313 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1315 hir::Unsafety::Normal,
1319 trait_ref.rebind(sig).to_string()
1322 let argument_kind = match expected_ref.skip_binder().self_ty().kind() {
1323 ty::Closure(..) => "closure",
1324 ty::Generator(..) => "generator",
1327 let mut err = struct_span_err!(
1331 "type mismatch in {} arguments",
1335 let found_str = format!("expected signature of `{}`", build_fn_sig_string(self.tcx, found));
1336 err.span_label(span, found_str);
1338 let found_span = found_span.unwrap_or(span);
1340 format!("found signature of `{}`", build_fn_sig_string(self.tcx, expected_ref));
1341 err.span_label(found_span, expected_str);
1346 fn suggest_fully_qualified_path(
1348 err: &mut DiagnosticBuilder<'_>,
1353 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1354 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1356 "{}s cannot be accessed directly on a `trait`, they can only be \
1357 accessed through a specific `impl`",
1358 assoc_item.kind.as_def_kind().descr(def_id)
1360 err.span_suggestion(
1362 "use the fully qualified path to an implementation",
1363 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1364 Applicability::HasPlaceholders,
1370 /// Adds an async-await specific note to the diagnostic when the future does not implement
1371 /// an auto trait because of a captured type.
1374 /// note: future does not implement `Qux` as this value is used across an await
1375 /// --> $DIR/issue-64130-3-other.rs:17:5
1377 /// LL | let x = Foo;
1378 /// | - has type `Foo`
1379 /// LL | baz().await;
1380 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1382 /// | - `x` is later dropped here
1385 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1386 /// is "replaced" with a different message and a more specific error.
1389 /// error: future cannot be sent between threads safely
1390 /// --> $DIR/issue-64130-2-send.rs:21:5
1392 /// LL | fn is_send<T: Send>(t: T) { }
1393 /// | ---- required by this bound in `is_send`
1395 /// LL | is_send(bar());
1396 /// | ^^^^^^^ future returned by `bar` is not send
1398 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1399 /// implemented for `Foo`
1400 /// note: future is not send as this value is used across an await
1401 /// --> $DIR/issue-64130-2-send.rs:15:5
1403 /// LL | let x = Foo;
1404 /// | - has type `Foo`
1405 /// LL | baz().await;
1406 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1408 /// | - `x` is later dropped here
1411 /// Returns `true` if an async-await specific note was added to the diagnostic.
1412 fn maybe_note_obligation_cause_for_async_await(
1414 err: &mut DiagnosticBuilder<'_>,
1415 obligation: &PredicateObligation<'tcx>,
1418 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1419 obligation.cause.span={:?}",
1420 obligation.predicate, obligation.cause.span
1422 let hir = self.tcx.hir();
1424 // Attempt to detect an async-await error by looking at the obligation causes, looking
1425 // for a generator to be present.
1427 // When a future does not implement a trait because of a captured type in one of the
1428 // generators somewhere in the call stack, then the result is a chain of obligations.
1430 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1431 // future is passed as an argument to a function C which requires a `Send` type, then the
1432 // chain looks something like this:
1434 // - `BuiltinDerivedObligation` with a generator witness (B)
1435 // - `BuiltinDerivedObligation` with a generator (B)
1436 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1437 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1438 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1439 // - `BuiltinDerivedObligation` with a generator witness (A)
1440 // - `BuiltinDerivedObligation` with a generator (A)
1441 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1442 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1443 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1444 // - `BindingObligation` with `impl_send (Send requirement)
1446 // The first obligation in the chain is the most useful and has the generator that captured
1447 // the type. The last generator (`outer_generator` below) has information about where the
1448 // bound was introduced. At least one generator should be present for this diagnostic to be
1450 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1451 ty::PredicateKind::Trait(p) => (Some(p), Some(p.self_ty())),
1454 let mut generator = None;
1455 let mut outer_generator = None;
1456 let mut next_code = Some(obligation.cause.code());
1458 let mut seen_upvar_tys_infer_tuple = false;
1460 while let Some(code) = next_code {
1461 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1463 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1464 next_code = Some(parent_code.as_ref());
1466 ObligationCauseCode::DerivedObligation(derived_obligation)
1467 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1468 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1469 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1471 "maybe_note_obligation_cause_for_async_await: \
1472 parent_trait_ref={:?} self_ty.kind={:?}",
1473 derived_obligation.parent_trait_pred,
1478 ty::Generator(did, ..) => {
1479 generator = generator.or(Some(did));
1480 outer_generator = Some(did);
1482 ty::GeneratorWitness(..) => {}
1483 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1484 // By introducing a tuple of upvar types into the chain of obligations
1485 // of a generator, the first non-generator item is now the tuple itself,
1486 // we shall ignore this.
1488 seen_upvar_tys_infer_tuple = true;
1490 _ if generator.is_none() => {
1491 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1492 target_ty = Some(ty);
1497 next_code = Some(derived_obligation.parent_code.as_ref());
1503 // Only continue if a generator was found.
1504 debug!(?generator, ?trait_ref, ?target_ty, "maybe_note_obligation_cause_for_async_await");
1505 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1506 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1507 (generator_did, trait_ref, target_ty)
1512 let span = self.tcx.def_span(generator_did);
1514 let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1515 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1517 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1518 generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
1521 in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1525 let generator_body = generator_did
1527 .map(|def_id| hir.local_def_id_to_hir_id(def_id))
1528 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1529 .map(|body_id| hir.body(body_id));
1530 let mut visitor = AwaitsVisitor::default();
1531 if let Some(body) = generator_body {
1532 visitor.visit_body(body);
1534 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1536 // Look for a type inside the generator interior that matches the target type to get
1538 let target_ty_erased = self.tcx.erase_regions(target_ty);
1539 let ty_matches = |ty| -> bool {
1540 // Careful: the regions for types that appear in the
1541 // generator interior are not generally known, so we
1542 // want to erase them when comparing (and anyway,
1543 // `Send` and other bounds are generally unaffected by
1544 // the choice of region). When erasing regions, we
1545 // also have to erase late-bound regions. This is
1546 // because the types that appear in the generator
1547 // interior generally contain "bound regions" to
1548 // represent regions that are part of the suspended
1549 // generator frame. Bound regions are preserved by
1550 // `erase_regions` and so we must also call
1551 // `erase_late_bound_regions`.
1552 let ty_erased = self.tcx.erase_late_bound_regions(ty);
1553 let ty_erased = self.tcx.erase_regions(ty_erased);
1554 let eq = ty_erased == target_ty_erased;
1556 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1557 target_ty_erased={:?} eq={:?}",
1558 ty_erased, target_ty_erased, eq
1563 let mut interior_or_upvar_span = None;
1564 let mut interior_extra_info = None;
1566 // Get the typeck results from the infcx if the generator is the function we are currently
1567 // type-checking; otherwise, get them by performing a query. This is needed to avoid
1568 // cycles. If we can't use resolved types because the generator comes from another crate,
1569 // we still provide a targeted error but without all the relevant spans.
1570 let query_typeck_results;
1571 let typeck_results: Option<&TypeckResults<'tcx>> = match &in_progress_typeck_results {
1572 Some(t) if t.hir_owner.to_def_id() == generator_did_root => Some(&t),
1573 _ if generator_did.is_local() => {
1574 query_typeck_results = self.tcx.typeck(generator_did.expect_local());
1575 Some(&query_typeck_results)
1577 _ => None, // Do not ICE on closure typeck (#66868).
1579 if let Some(typeck_results) = typeck_results {
1580 if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) {
1581 interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| {
1582 let upvar_ty = typeck_results.node_type(*upvar_id);
1583 let upvar_ty = self.resolve_vars_if_possible(upvar_ty);
1584 if ty_matches(ty::Binder::dummy(upvar_ty)) {
1585 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
1592 // The generator interior types share the same binders
1593 if let Some(cause) =
1594 typeck_results.generator_interior_types.as_ref().skip_binder().iter().find(
1595 |ty::GeneratorInteriorTypeCause { ty, .. }| {
1596 ty_matches(typeck_results.generator_interior_types.rebind(*ty))
1600 // Check to see if any awaited expressions have the target type.
1601 let from_awaited_ty = visitor
1604 .map(|id| hir.expect_expr(id))
1605 .find(|await_expr| {
1606 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
1608 .map(|expr| expr.span);
1609 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1612 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1613 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1616 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span));
1619 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1620 self.note_obligation_cause_for_async_await(
1622 interior_or_upvar_span,
1623 interior_extra_info,
1638 /// Unconditionally adds the diagnostic note described in
1639 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1640 fn note_obligation_cause_for_async_await(
1642 err: &mut DiagnosticBuilder<'_>,
1643 interior_or_upvar_span: GeneratorInteriorOrUpvar,
1644 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1645 inner_generator_body: Option<&hir::Body<'tcx>>,
1646 outer_generator: Option<DefId>,
1647 trait_pred: ty::TraitPredicate<'tcx>,
1648 target_ty: Ty<'tcx>,
1649 typeck_results: Option<&ty::TypeckResults<'tcx>>,
1650 obligation: &PredicateObligation<'tcx>,
1651 next_code: Option<&ObligationCauseCode<'tcx>>,
1653 let source_map = self.tcx.sess.source_map();
1655 let is_async = inner_generator_body
1656 .and_then(|body| body.generator_kind())
1657 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1659 let (await_or_yield, an_await_or_yield) =
1660 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1661 let future_or_generator = if is_async { "future" } else { "generator" };
1663 // Special case the primary error message when send or sync is the trait that was
1665 let hir = self.tcx.hir();
1666 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
1667 self.tcx.get_diagnostic_name(trait_pred.def_id())
1669 let (trait_name, trait_verb) =
1670 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1673 err.set_primary_message(format!(
1674 "{} cannot be {} between threads safely",
1675 future_or_generator, trait_verb
1678 let original_span = err.span.primary_span().unwrap();
1679 let mut span = MultiSpan::from_span(original_span);
1681 let message = outer_generator
1682 .and_then(|generator_did| {
1683 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1684 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1685 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1687 .parent(generator_did)
1688 .and_then(|parent_did| parent_did.as_local())
1689 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
1690 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1692 format!("future returned by `{}` is not {}", name, trait_name)
1694 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1695 format!("future created by async block is not {}", trait_name)
1697 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1698 format!("future created by async closure is not {}", trait_name)
1702 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1704 span.push_span_label(original_span, message);
1707 format!("is not {}", trait_name)
1709 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
1712 let mut explain_yield = |interior_span: Span,
1714 scope_span: Option<Span>| {
1715 let mut span = MultiSpan::from_span(yield_span);
1716 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1717 // #70935: If snippet contains newlines, display "the value" instead
1718 // so that we do not emit complex diagnostics.
1719 let snippet = &format!("`{}`", snippet);
1720 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
1721 // note: future is not `Send` as this value is used across an await
1722 // --> $DIR/issue-70935-complex-spans.rs:13:9
1724 // LL | baz(|| async {
1725 // | ______________-
1728 // LL | | foo(tx.clone());
1730 // | | - ^^^^^^ await occurs here, with value maybe used later
1732 // | has type `closure` which is not `Send`
1733 // note: value is later dropped here
1737 span.push_span_label(
1739 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
1741 span.push_span_label(
1743 format!("has type `{}` which {}", target_ty, trait_explanation),
1745 // If available, use the scope span to annotate the drop location.
1746 let mut scope_note = None;
1747 if let Some(scope_span) = scope_span {
1748 let scope_span = source_map.end_point(scope_span);
1750 let msg = format!("{} is later dropped here", snippet);
1751 if source_map.is_multiline(yield_span.between(scope_span)) {
1752 span.push_span_label(scope_span, msg);
1754 scope_note = Some((scope_span, msg));
1760 "{} {} as this value is used across {}",
1761 future_or_generator, trait_explanation, an_await_or_yield
1764 if let Some((span, msg)) = scope_note {
1765 err.span_note(span, &msg);
1769 match interior_or_upvar_span {
1770 GeneratorInteriorOrUpvar::Interior(interior_span) => {
1771 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
1772 if let Some(await_span) = from_awaited_ty {
1773 // The type causing this obligation is one being awaited at await_span.
1774 let mut span = MultiSpan::from_span(await_span);
1775 span.push_span_label(
1778 "await occurs here on type `{}`, which {}",
1779 target_ty, trait_explanation
1785 "future {not_trait} as it awaits another future which {not_trait}",
1786 not_trait = trait_explanation
1790 // Look at the last interior type to get a span for the `.await`.
1792 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1793 typeck_results.as_ref().map(|t| &t.generator_interior_types)
1795 explain_yield(interior_span, yield_span, scope_span);
1798 if let Some(expr_id) = expr {
1799 let expr = hir.expect_expr(expr_id);
1800 debug!("target_ty evaluated from {:?}", expr);
1802 let parent = hir.get_parent_node(expr_id);
1803 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1804 let parent_span = hir.span(parent);
1805 let parent_did = parent.owner.to_def_id();
1808 // fn foo(&self) -> i32 {}
1811 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1814 let is_region_borrow = if let Some(typeck_results) = typeck_results {
1816 .expr_adjustments(expr)
1818 .any(|adj| adj.is_region_borrow())
1824 // struct Foo(*const u8);
1825 // bar(Foo(std::ptr::null())).await;
1826 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1828 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1829 let is_raw_borrow_inside_fn_like_call =
1830 match self.tcx.def_kind(parent_did) {
1831 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
1834 if let Some(typeck_results) = typeck_results {
1835 if (typeck_results.is_method_call(e) && is_region_borrow)
1836 || is_raw_borrow_inside_fn_like_call
1840 "consider moving this into a `let` \
1841 binding to create a shorter lived borrow",
1849 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
1850 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
1851 let refers_to_non_sync = match target_ty.kind() {
1852 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
1853 Ok(eval) if !eval.may_apply() => Some(ref_ty),
1859 let (span_label, span_note) = match refers_to_non_sync {
1860 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
1861 // include suggestions to make `T: Sync` so that `&T: Send`
1864 "has type `{}` which {}, because `{}` is not `Sync`",
1865 target_ty, trait_explanation, ref_ty
1868 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
1873 format!("has type `{}` which {}", target_ty, trait_explanation),
1874 format!("captured value {}", trait_explanation),
1878 let mut span = MultiSpan::from_span(upvar_span);
1879 span.push_span_label(upvar_span, span_label);
1880 err.span_note(span, &span_note);
1884 // Add a note for the item obligation that remains - normally a note pointing to the
1885 // bound that introduced the obligation (e.g. `T: Send`).
1886 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1887 self.note_obligation_cause_code(
1889 &obligation.predicate,
1890 obligation.param_env,
1893 &mut Default::default(),
1897 fn note_obligation_cause_code<T>(
1899 err: &mut DiagnosticBuilder<'_>,
1901 param_env: ty::ParamEnv<'tcx>,
1902 cause_code: &ObligationCauseCode<'tcx>,
1903 obligated_types: &mut Vec<Ty<'tcx>>,
1904 seen_requirements: &mut FxHashSet<DefId>,
1910 ObligationCauseCode::ExprAssignable
1911 | ObligationCauseCode::MatchExpressionArm { .. }
1912 | ObligationCauseCode::Pattern { .. }
1913 | ObligationCauseCode::IfExpression { .. }
1914 | ObligationCauseCode::IfExpressionWithNoElse
1915 | ObligationCauseCode::MainFunctionType
1916 | ObligationCauseCode::StartFunctionType
1917 | ObligationCauseCode::IntrinsicType
1918 | ObligationCauseCode::MethodReceiver
1919 | ObligationCauseCode::ReturnNoExpression
1920 | ObligationCauseCode::UnifyReceiver(..)
1921 | ObligationCauseCode::OpaqueType
1922 | ObligationCauseCode::MiscObligation
1923 | ObligationCauseCode::WellFormed(..)
1924 | ObligationCauseCode::MatchImpl(..)
1925 | ObligationCauseCode::ReturnType
1926 | ObligationCauseCode::ReturnValue(_)
1927 | ObligationCauseCode::BlockTailExpression(_)
1928 | ObligationCauseCode::AwaitableExpr(_)
1929 | ObligationCauseCode::ForLoopIterator
1930 | ObligationCauseCode::QuestionMark
1931 | ObligationCauseCode::LetElse
1932 | ObligationCauseCode::CheckAssociatedTypeBounds { .. } => {}
1933 ObligationCauseCode::SliceOrArrayElem => {
1934 err.note("slice and array elements must have `Sized` type");
1936 ObligationCauseCode::TupleElem => {
1937 err.note("only the last element of a tuple may have a dynamically sized type");
1939 ObligationCauseCode::ProjectionWf(data) => {
1940 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1942 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1944 "required so that reference `{}` does not outlive its referent",
1948 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1950 "required so that the lifetime bound of `{}` for `{}` is satisfied",
1954 ObligationCauseCode::ItemObligation(_item_def_id) => {
1955 // We hold the `DefId` of the item introducing the obligation, but displaying it
1956 // doesn't add user usable information. It always point at an associated item.
1958 ObligationCauseCode::BindingObligation(item_def_id, span) => {
1959 let item_name = tcx.def_path_str(item_def_id);
1960 let mut multispan = MultiSpan::from(span);
1961 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1962 let sm = tcx.sess.source_map();
1964 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
1965 (Ok(l), Ok(r)) => l.line == r.line,
1968 if !ident.span.overlaps(span) && !same_line {
1970 .push_span_label(ident.span, "required by a bound in this".to_string());
1973 let descr = format!("required by a bound in `{}`", item_name);
1974 if span != DUMMY_SP {
1975 let msg = format!("required by this bound in `{}`", item_name);
1976 multispan.push_span_label(span, msg);
1977 err.span_note(multispan, &descr);
1979 err.span_note(tcx.def_span(item_def_id), &descr);
1982 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1984 "required for the cast to the object type `{}`",
1985 self.ty_to_string(object_ty)
1988 ObligationCauseCode::Coercion { source: _, target } => {
1989 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1991 ObligationCauseCode::RepeatVec(is_const_fn) => {
1993 "the `Copy` trait is required because the repeated element will be copied",
1998 "consider creating a new `const` item and initializing it with the result \
1999 of the function call to be used in the repeat position, like \
2000 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2004 if self.tcx.sess.is_nightly_build() && is_const_fn {
2006 "create an inline `const` block, see RFC #2920 \
2007 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2011 ObligationCauseCode::VariableType(hir_id) => {
2012 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2013 match self.tcx.hir().find(parent_node) {
2014 Some(Node::Local(hir::Local {
2015 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2018 // When encountering an assignment of an unsized trait, like
2019 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2020 // order to use have a slice instead.
2021 err.span_suggestion_verbose(
2022 span.shrink_to_lo(),
2023 "consider borrowing here",
2025 Applicability::MachineApplicable,
2027 err.note("all local variables must have a statically known size");
2029 Some(Node::Param(param)) => {
2030 err.span_suggestion_verbose(
2031 param.ty_span.shrink_to_lo(),
2032 "function arguments must have a statically known size, borrowed types \
2033 always have a known size",
2035 Applicability::MachineApplicable,
2039 err.note("all local variables must have a statically known size");
2042 if !self.tcx.features().unsized_locals {
2043 err.help("unsized locals are gated as an unstable feature");
2046 ObligationCauseCode::SizedArgumentType(sp) => {
2047 if let Some(span) = sp {
2048 err.span_suggestion_verbose(
2049 span.shrink_to_lo(),
2050 "function arguments must have a statically known size, borrowed types \
2051 always have a known size",
2053 Applicability::MachineApplicable,
2056 err.note("all function arguments must have a statically known size");
2058 if tcx.sess.opts.unstable_features.is_nightly_build()
2059 && !self.tcx.features().unsized_fn_params
2061 err.help("unsized fn params are gated as an unstable feature");
2064 ObligationCauseCode::SizedReturnType => {
2065 err.note("the return type of a function must have a statically known size");
2067 ObligationCauseCode::SizedYieldType => {
2068 err.note("the yield type of a generator must have a statically known size");
2070 ObligationCauseCode::SizedBoxType => {
2071 err.note("the type of a box expression must have a statically known size");
2073 ObligationCauseCode::AssignmentLhsSized => {
2074 err.note("the left-hand-side of an assignment must have a statically known size");
2076 ObligationCauseCode::TupleInitializerSized => {
2077 err.note("tuples must have a statically known size to be initialized");
2079 ObligationCauseCode::StructInitializerSized => {
2080 err.note("structs must have a statically known size to be initialized");
2082 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2084 AdtKind::Struct => {
2087 "the last field of a packed struct may only have a \
2088 dynamically sized type if it does not need drop to be run",
2092 "only the last field of a struct may have a dynamically sized type",
2097 err.note("no field of a union may have a dynamically sized type");
2100 err.note("no field of an enum variant may have a dynamically sized type");
2103 err.help("change the field's type to have a statically known size");
2104 err.span_suggestion(
2105 span.shrink_to_lo(),
2106 "borrowed types always have a statically known size",
2108 Applicability::MachineApplicable,
2110 err.multipart_suggestion(
2111 "the `Box` type always has a statically known size and allocates its contents \
2114 (span.shrink_to_lo(), "Box<".to_string()),
2115 (span.shrink_to_hi(), ">".to_string()),
2117 Applicability::MachineApplicable,
2120 ObligationCauseCode::ConstSized => {
2121 err.note("constant expressions must have a statically known size");
2123 ObligationCauseCode::InlineAsmSized => {
2124 err.note("all inline asm arguments must have a statically known size");
2126 ObligationCauseCode::ConstPatternStructural => {
2127 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2129 ObligationCauseCode::SharedStatic => {
2130 err.note("shared static variables must have a type that implements `Sync`");
2132 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2133 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2134 let ty = parent_trait_ref.skip_binder().self_ty();
2135 if parent_trait_ref.references_error() {
2140 // If the obligation for a tuple is set directly by a Generator or Closure,
2141 // then the tuple must be the one containing capture types.
2142 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2145 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) =
2148 let parent_trait_ref =
2149 self.resolve_vars_if_possible(data.parent_trait_pred);
2150 let ty = parent_trait_ref.skip_binder().self_ty();
2151 matches!(ty.kind(), ty::Generator(..))
2152 || matches!(ty.kind(), ty::Closure(..))
2158 // Don't print the tuple of capture types
2159 if !is_upvar_tys_infer_tuple {
2160 let msg = format!("required because it appears within the type `{}`", ty);
2162 ty::Adt(def, _) => match self.tcx.opt_item_name(def.did) {
2163 Some(ident) => err.span_note(ident.span, &msg),
2164 None => err.note(&msg),
2166 _ => err.note(&msg),
2170 obligated_types.push(ty);
2172 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2173 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2174 // #74711: avoid a stack overflow
2175 ensure_sufficient_stack(|| {
2176 self.note_obligation_cause_code(
2186 ensure_sufficient_stack(|| {
2187 self.note_obligation_cause_code(
2191 &cause_code.peel_derives(),
2198 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2199 let mut parent_trait_pred = self.resolve_vars_if_possible(data.parent_trait_pred);
2200 parent_trait_pred.remap_constness_diag(param_env);
2201 let parent_def_id = parent_trait_pred.def_id();
2203 "required because of the requirements on the impl of `{}` for `{}`",
2204 parent_trait_pred.print_modifiers_and_trait_path(),
2205 parent_trait_pred.skip_binder().self_ty()
2207 let mut candidates = vec![];
2208 self.tcx.for_each_relevant_impl(
2210 parent_trait_pred.self_ty().skip_binder(),
2211 |impl_def_id| match self.tcx.hir().get_if_local(impl_def_id) {
2212 Some(Node::Item(hir::Item {
2213 kind: hir::ItemKind::Impl(hir::Impl { .. }),
2216 candidates.push(impl_def_id);
2221 match &candidates[..] {
2222 [def_id] => match self.tcx.hir().get_if_local(*def_id) {
2223 Some(Node::Item(hir::Item {
2224 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2227 let mut spans = Vec::with_capacity(2);
2228 if let Some(trait_ref) = of_trait {
2229 spans.push(trait_ref.path.span);
2231 spans.push(self_ty.span);
2232 err.span_note(spans, &msg)
2234 _ => err.note(&msg),
2236 _ => err.note(&msg),
2239 let mut parent_predicate = parent_trait_pred.to_predicate(tcx);
2240 let mut data = data;
2242 seen_requirements.insert(parent_def_id);
2243 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2244 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2245 let child_trait_pred = self.resolve_vars_if_possible(child.parent_trait_pred);
2246 let child_def_id = child_trait_pred.def_id();
2247 if seen_requirements.insert(child_def_id) {
2252 parent_predicate = child_trait_pred.to_predicate(tcx);
2253 parent_trait_pred = child_trait_pred;
2257 "{} redundant requirement{} hidden",
2262 "required because of the requirements on the impl of `{}` for `{}`",
2263 parent_trait_pred.print_modifiers_and_trait_path(),
2264 parent_trait_pred.skip_binder().self_ty()
2267 // #74711: avoid a stack overflow
2268 ensure_sufficient_stack(|| {
2269 self.note_obligation_cause_code(
2279 ObligationCauseCode::DerivedObligation(ref data) => {
2280 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2281 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2282 // #74711: avoid a stack overflow
2283 ensure_sufficient_stack(|| {
2284 self.note_obligation_cause_code(
2294 ObligationCauseCode::FunctionArgumentObligation {
2299 let hir = self.tcx.hir();
2300 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2301 hir.find(arg_hir_id)
2303 let in_progress_typeck_results =
2304 self.in_progress_typeck_results.map(|t| t.borrow());
2305 let parent_id = hir.get_parent_item(arg_hir_id);
2306 let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
2307 Some(t) if t.hir_owner == parent_id => t,
2308 _ => self.tcx.typeck(parent_id),
2310 let ty = typeck_results.expr_ty_adjusted(expr);
2311 let span = expr.peel_blocks().span;
2312 if Some(span) != err.span.primary_span() {
2315 &if ty.references_error() {
2318 format!("this tail expression is of type `{:?}`", ty)
2323 if let Some(Node::Expr(hir::Expr {
2325 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2326 | hir::ExprKind::MethodCall(
2327 hir::PathSegment { ident: Ident { span, .. }, .. },
2331 })) = hir.find(call_hir_id)
2333 if Some(*span) != err.span.primary_span() {
2334 err.span_label(*span, "required by a bound introduced by this call");
2337 ensure_sufficient_stack(|| {
2338 self.note_obligation_cause_code(
2348 ObligationCauseCode::CompareImplMethodObligation { trait_item_def_id, .. } => {
2349 let item_name = self.tcx.item_name(trait_item_def_id);
2351 "the requirement `{}` appears on the impl method `{}` but not on the \
2352 corresponding trait method",
2353 predicate, item_name,
2357 .opt_item_name(trait_item_def_id)
2359 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2360 let mut assoc_span: MultiSpan = sp.into();
2361 assoc_span.push_span_label(
2363 format!("this trait method doesn't have the requirement `{}`", predicate),
2365 if let Some(ident) = self
2367 .opt_associated_item(trait_item_def_id)
2368 .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2370 assoc_span.push_span_label(ident.span, "in this trait".into());
2372 err.span_note(assoc_span, &msg);
2374 ObligationCauseCode::CompareImplTypeObligation { trait_item_def_id, .. } => {
2375 let item_name = self.tcx.item_name(trait_item_def_id);
2377 "the requirement `{}` appears on the associated impl type `{}` but not on the \
2378 corresponding associated trait type",
2379 predicate, item_name,
2381 let sp = self.tcx.def_span(trait_item_def_id);
2382 let mut assoc_span: MultiSpan = sp.into();
2383 assoc_span.push_span_label(
2386 "this trait associated type doesn't have the requirement `{}`",
2390 if let Some(ident) = self
2392 .opt_associated_item(trait_item_def_id)
2393 .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2395 assoc_span.push_span_label(ident.span, "in this trait".into());
2397 err.span_note(assoc_span, &msg);
2399 ObligationCauseCode::CompareImplConstObligation => {
2401 "the requirement `{}` appears on the associated impl constant \
2402 but not on the corresponding associated trait constant",
2406 ObligationCauseCode::TrivialBound => {
2407 err.help("see issue #48214");
2408 if tcx.sess.opts.unstable_features.is_nightly_build() {
2409 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2415 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2416 let suggested_limit = match self.tcx.recursion_limit() {
2417 Limit(0) => Limit(2),
2421 "consider increasing the recursion limit by adding a \
2422 `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
2424 self.tcx.crate_name(LOCAL_CRATE),
2428 fn suggest_await_before_try(
2430 err: &mut DiagnosticBuilder<'_>,
2431 obligation: &PredicateObligation<'tcx>,
2432 trait_pred: ty::PolyTraitPredicate<'tcx>,
2436 "suggest_await_before_try: obligation={:?}, span={:?}, trait_pred={:?}, trait_pred_self_ty={:?}",
2440 trait_pred.self_ty()
2442 let body_hir_id = obligation.cause.body_id;
2443 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2445 if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
2446 let body = self.tcx.hir().body(body_id);
2447 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2448 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2450 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2452 // Do not check on infer_types to avoid panic in evaluate_obligation.
2453 if self_ty.has_infer_types() {
2456 let self_ty = self.tcx.erase_regions(self_ty);
2458 let impls_future = self.type_implements_trait(
2460 self_ty.skip_binder(),
2462 obligation.param_env,
2465 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2466 // `<T as Future>::Output`
2467 let projection_ty = ty::ProjectionTy {
2469 substs: self.tcx.mk_substs_trait(
2470 trait_pred.self_ty().skip_binder(),
2471 &self.fresh_substs_for_item(span, item_def_id)[1..],
2477 let mut selcx = SelectionContext::new(self);
2479 let mut obligations = vec![];
2480 let normalized_ty = normalize_projection_type(
2482 obligation.param_env,
2484 obligation.cause.clone(),
2490 "suggest_await_before_try: normalized_projection_type {:?}",
2491 self.resolve_vars_if_possible(normalized_ty)
2493 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2494 obligation.param_env,
2496 normalized_ty.ty().unwrap(),
2498 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2499 if self.predicate_may_hold(&try_obligation)
2500 && impls_future.must_apply_modulo_regions()
2502 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2503 if snippet.ends_with('?') {
2504 err.span_suggestion_verbose(
2505 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2506 "consider `await`ing on the `Future`",
2507 ".await".to_string(),
2508 Applicability::MaybeIncorrect,
2518 /// Collect all the returned expressions within the input expression.
2519 /// Used to point at the return spans when we want to suggest some change to them.
2521 pub struct ReturnsVisitor<'v> {
2522 pub returns: Vec<&'v hir::Expr<'v>>,
2523 in_block_tail: bool,
2526 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2527 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2528 // Visit every expression to detect `return` paths, either through the function's tail
2529 // expression or `return` statements. We walk all nodes to find `return` statements, but
2530 // we only care about tail expressions when `in_block_tail` is `true`, which means that
2531 // they're in the return path of the function body.
2533 hir::ExprKind::Ret(Some(ex)) => {
2534 self.returns.push(ex);
2536 hir::ExprKind::Block(block, _) if self.in_block_tail => {
2537 self.in_block_tail = false;
2538 for stmt in block.stmts {
2539 hir::intravisit::walk_stmt(self, stmt);
2541 self.in_block_tail = true;
2542 if let Some(expr) = block.expr {
2543 self.visit_expr(expr);
2546 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
2547 self.visit_expr(then);
2548 if let Some(el) = else_opt {
2549 self.visit_expr(el);
2552 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2554 self.visit_expr(arm.body);
2557 // We need to walk to find `return`s in the entire body.
2558 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2559 _ => self.returns.push(ex),
2563 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2564 assert!(!self.in_block_tail);
2565 if body.generator_kind().is_none() {
2566 if let hir::ExprKind::Block(block, None) = body.value.kind {
2567 if block.expr.is_some() {
2568 self.in_block_tail = true;
2572 hir::intravisit::walk_body(self, body);
2576 /// Collect all the awaited expressions within the input expression.
2578 struct AwaitsVisitor {
2579 awaits: Vec<hir::HirId>,
2582 impl<'v> Visitor<'v> for AwaitsVisitor {
2583 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2584 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2585 self.awaits.push(id)
2587 hir::intravisit::walk_expr(self, ex)
2591 pub trait NextTypeParamName {
2592 fn next_type_param_name(&self, name: Option<&str>) -> String;
2595 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2596 fn next_type_param_name(&self, name: Option<&str>) -> String {
2597 // This is the list of possible parameter names that we might suggest.
2598 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2599 let name = name.as_deref();
2600 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2601 let used_names = self
2603 .filter_map(|p| match p.name {
2604 hir::ParamName::Plain(ident) => Some(ident.name),
2607 .collect::<Vec<_>>();
2611 .find(|n| !used_names.contains(&Symbol::intern(n)))
2612 .unwrap_or(&"ParamName")
2617 fn suggest_trait_object_return_type_alternatives(
2618 err: &mut DiagnosticBuilder<'_>,
2621 is_object_safe: bool,
2623 err.span_suggestion(
2625 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2628 Applicability::MaybeIncorrect,
2630 err.span_suggestion(
2633 "use `impl {}` as the return type if all return paths have the same type but you \
2634 want to expose only the trait in the signature",
2637 format!("impl {}", trait_obj),
2638 Applicability::MaybeIncorrect,
2641 err.span_suggestion(
2644 "use a boxed trait object if all return paths implement trait `{}`",
2647 format!("Box<dyn {}>", trait_obj),
2648 Applicability::MaybeIncorrect,