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;
12 use rustc_data_structures::sync::Lrc;
14 error_code, pluralize, struct_span_err, Applicability, DiagnosticBuilder, 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::ty::{
23 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
24 Infer, InferTy, ToPredicate, Ty, TyCtxt, TypeFoldable,
26 use rustc_middle::ty::{TypeAndMut, TypeckResults};
27 use rustc_session::Limit;
28 use rustc_span::def_id::LOCAL_CRATE;
29 use rustc_span::symbol::{kw, sym, Ident, Symbol};
30 use rustc_span::{BytePos, DesugaringKind, ExpnKind, MultiSpan, Span, DUMMY_SP};
31 use rustc_target::spec::abi;
34 use super::InferCtxtPrivExt;
35 use crate::infer::InferCtxtExt as _;
36 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
37 use rustc_middle::ty::print::with_no_trimmed_paths;
40 pub enum GeneratorInteriorOrUpvar {
41 // span of interior type
47 // This trait is public to expose the diagnostics methods to clippy.
48 pub trait InferCtxtExt<'tcx> {
49 fn suggest_restricting_param_bound(
51 err: &mut DiagnosticBuilder<'_>,
52 trait_ref: ty::PolyTraitRef<'tcx>,
56 fn suggest_dereferences(
58 obligation: &PredicateObligation<'tcx>,
59 err: &mut DiagnosticBuilder<'tcx>,
60 trait_ref: ty::PolyTraitRef<'tcx>,
66 err: &mut DiagnosticBuilder<'_>,
72 obligation: &PredicateObligation<'tcx>,
73 err: &mut DiagnosticBuilder<'_>,
74 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
77 fn suggest_add_reference_to_arg(
79 obligation: &PredicateObligation<'tcx>,
80 err: &mut DiagnosticBuilder<'_>,
81 trait_ref: &ty::Binder<'tcx, ty::TraitRef<'tcx>>,
82 has_custom_message: bool,
85 fn suggest_remove_reference(
87 obligation: &PredicateObligation<'tcx>,
88 err: &mut DiagnosticBuilder<'_>,
89 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
92 fn suggest_remove_await(
94 obligation: &PredicateObligation<'tcx>,
95 err: &mut DiagnosticBuilder<'_>,
98 fn suggest_change_mut(
100 obligation: &PredicateObligation<'tcx>,
101 err: &mut DiagnosticBuilder<'_>,
102 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
105 fn suggest_semicolon_removal(
107 obligation: &PredicateObligation<'tcx>,
108 err: &mut DiagnosticBuilder<'_>,
110 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
113 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
115 fn suggest_impl_trait(
117 err: &mut DiagnosticBuilder<'_>,
119 obligation: &PredicateObligation<'tcx>,
120 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
123 fn point_at_returns_when_relevant(
125 err: &mut DiagnosticBuilder<'_>,
126 obligation: &PredicateObligation<'tcx>,
129 fn report_closure_arg_mismatch(
132 found_span: Option<Span>,
133 expected_ref: ty::PolyTraitRef<'tcx>,
134 found: ty::PolyTraitRef<'tcx>,
135 ) -> DiagnosticBuilder<'tcx>;
137 fn suggest_fully_qualified_path(
139 err: &mut DiagnosticBuilder<'_>,
145 fn maybe_note_obligation_cause_for_async_await(
147 err: &mut DiagnosticBuilder<'_>,
148 obligation: &PredicateObligation<'tcx>,
151 fn note_obligation_cause_for_async_await(
153 err: &mut DiagnosticBuilder<'_>,
154 interior_or_upvar_span: GeneratorInteriorOrUpvar,
155 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
156 inner_generator_body: Option<&hir::Body<'tcx>>,
157 outer_generator: Option<DefId>,
158 trait_ref: ty::TraitRef<'tcx>,
160 typeck_results: Option<&ty::TypeckResults<'tcx>>,
161 obligation: &PredicateObligation<'tcx>,
162 next_code: Option<&ObligationCauseCode<'tcx>>,
165 fn note_obligation_cause_code<T>(
167 err: &mut DiagnosticBuilder<'_>,
169 cause_code: &ObligationCauseCode<'tcx>,
170 obligated_types: &mut Vec<&ty::TyS<'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_ref: ty::Binder<'tcx, ty::TraitRef<'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(
203 generics: &hir::Generics<'tcx>,
205 err: &mut DiagnosticBuilder<'_>,
206 fn_sig: Option<&hir::FnSig<'_>>,
207 projection: Option<&ty::ProjectionTy<'_>>,
208 trait_ref: ty::PolyTraitRef<'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_ref` instead of string shenanigans.
262 // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
263 let pred = trait_ref.without_const().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(
307 trait_ref.without_const().to_predicate(tcx).to_string(),
309 (None, Some((ident, []))) => {
310 (ident.span.shrink_to_hi(), format!(": {}", trait_ref.print_only_trait_path()))
312 (_, Some((_, [.., bounds]))) => {
313 (bounds.span().shrink_to_hi(), format!(" + {}", trait_ref.print_only_trait_path()))
315 (Some(_), Some((_, []))) => {
316 (generics.span.shrink_to_hi(), format!(": {}", trait_ref.print_only_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_ref: ty::PolyTraitRef<'tcx>,
336 let self_ty = trait_ref.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_ref, 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();
447 with_no_trimmed_paths(|| trait_ref.print_only_trait_path().to_string());
448 if suggest_constraining_type_param(
454 Some(trait_ref.def_id()),
460 hir::Node::Item(hir::Item {
462 hir::ItemKind::Struct(_, generics)
463 | hir::ItemKind::Enum(_, generics)
464 | hir::ItemKind::Union(_, generics)
465 | hir::ItemKind::Trait(_, _, generics, ..)
466 | hir::ItemKind::Impl(hir::Impl { generics, .. })
467 | hir::ItemKind::Fn(_, generics, _)
468 | hir::ItemKind::TyAlias(_, generics)
469 | hir::ItemKind::TraitAlias(generics, _)
470 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
473 // Missing generic type parameter bound.
474 let param_name = self_ty.to_string();
475 let constraint = trait_ref.print_only_trait_path().to_string();
476 if suggest_arbitrary_trait_bound(generics, &mut err, ¶m_name, &constraint) {
480 hir::Node::Crate(..) => return,
485 hir_id = self.tcx.hir().get_parent_item(hir_id);
489 /// When after several dereferencing, the reference satisfies the trait
490 /// binding. This function provides dereference suggestion for this
491 /// specific situation.
492 fn suggest_dereferences(
494 obligation: &PredicateObligation<'tcx>,
495 err: &mut DiagnosticBuilder<'tcx>,
496 trait_ref: ty::PolyTraitRef<'tcx>,
498 // It only make sense when suggesting dereferences for arguments
499 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
500 &obligation.cause.code
506 let param_env = obligation.param_env;
507 let body_id = obligation.cause.body_id;
508 let span = obligation.cause.span;
509 let real_trait_ref = match &*code {
510 ObligationCauseCode::ImplDerivedObligation(cause)
511 | ObligationCauseCode::DerivedObligation(cause)
512 | ObligationCauseCode::BuiltinDerivedObligation(cause) => cause.parent_trait_ref,
515 let real_ty = match real_trait_ref.self_ty().no_bound_vars() {
520 if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
521 let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
522 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
524 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
526 self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_ref, ty);
527 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
530 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
531 // Don't care about `&mut` because `DerefMut` is used less
532 // often and user will not expect autoderef happens.
533 if src.starts_with('&') && !src.starts_with("&mut ") {
534 let derefs = "*".repeat(steps);
537 "consider adding dereference here",
538 format!("&{}{}", derefs, &src[1..]),
539 Applicability::MachineApplicable,
548 /// Given a closure's `DefId`, return the given name of the closure.
550 /// This doesn't account for reassignments, but it's only used for suggestions.
554 err: &mut DiagnosticBuilder<'_>,
556 ) -> Option<String> {
558 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
559 // Get the local name of this closure. This can be inaccurate because
560 // of the possibility of reassignment, but this should be good enough.
562 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
563 Some(format!("{}", name))
572 let hir = self.tcx.hir();
573 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
574 let parent_node = hir.get_parent_node(hir_id);
575 match hir.find(parent_node) {
576 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
577 get_name(err, &local.pat.kind)
579 // Different to previous arm because one is `&hir::Local` and the other
580 // is `P<hir::Local>`.
581 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
586 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
587 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
588 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
591 obligation: &PredicateObligation<'tcx>,
592 err: &mut DiagnosticBuilder<'_>,
593 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
595 let self_ty = match trait_ref.self_ty().no_bound_vars() {
600 let (def_id, output_ty, callable) = match *self_ty.kind() {
601 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
602 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
605 let msg = format!("use parentheses to call the {}", callable);
607 // `mk_trait_obligation_with_new_self_ty` only works for types with no escaping bound
608 // variables, so bail out if we have any.
609 let output_ty = match output_ty.no_bound_vars() {
615 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_ref, output_ty);
617 match self.evaluate_obligation(&new_obligation) {
619 EvaluationResult::EvaluatedToOk
620 | EvaluationResult::EvaluatedToOkModuloRegions
621 | EvaluationResult::EvaluatedToAmbig,
625 let hir = self.tcx.hir();
626 // Get the name of the callable and the arguments to be used in the suggestion.
627 let (snippet, sugg) = match hir.get_if_local(def_id) {
628 Some(hir::Node::Expr(hir::Expr {
629 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
632 err.span_label(*span, "consider calling this closure");
633 let name = match self.get_closure_name(def_id, err, &msg) {
637 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
638 let sugg = format!("({})", args);
639 (format!("{}{}", name, sugg), sugg)
641 Some(hir::Node::Item(hir::Item {
643 kind: hir::ItemKind::Fn(.., body_id),
646 err.span_label(ident.span, "consider calling this function");
647 let body = hir.body(*body_id);
651 .map(|arg| match &arg.pat.kind {
652 hir::PatKind::Binding(_, _, ident, None)
653 // FIXME: provide a better suggestion when encountering `SelfLower`, it
654 // should suggest a method call.
655 if ident.name != kw::SelfLower => ident.to_string(),
656 _ => "_".to_string(),
660 let sugg = format!("({})", args);
661 (format!("{}{}", ident, sugg), sugg)
665 if matches!(obligation.cause.code, ObligationCauseCode::FunctionArgumentObligation { .. }) {
666 // When the obligation error has been ensured to have been caused by
667 // an argument, the `obligation.cause.span` points at the expression
668 // of the argument, so we can provide a suggestion. Otherwise, we give
669 // a more general note.
670 err.span_suggestion_verbose(
671 obligation.cause.span.shrink_to_hi(),
674 Applicability::HasPlaceholders,
677 err.help(&format!("{}: `{}`", msg, snippet));
681 fn suggest_add_reference_to_arg(
683 obligation: &PredicateObligation<'tcx>,
684 err: &mut DiagnosticBuilder<'_>,
685 poly_trait_ref: &ty::Binder<'tcx, ty::TraitRef<'tcx>>,
686 has_custom_message: bool,
688 let span = obligation.cause.span;
690 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
691 &obligation.cause.code
694 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
695 span.ctxt().outer_expn_data().kind
697 Lrc::new(obligation.cause.code.clone())
702 // List of traits for which it would be nonsensical to suggest borrowing.
703 // For instance, immutable references are always Copy, so suggesting to
704 // borrow would always succeed, but it's probably not what the user wanted.
705 let mut never_suggest_borrow: Vec<_> =
706 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
708 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
711 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
712 never_suggest_borrow.push(def_id);
715 let param_env = obligation.param_env;
717 // Try to apply the original trait binding obligation by borrowing.
718 let mut try_borrowing = |old_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
721 if blacklist.contains(&old_ref.def_id()) {
725 let orig_ty = old_ref.self_ty().skip_binder();
726 let mk_result = |new_ty| {
727 let new_ref = old_ref.rebind(ty::TraitRef::new(
729 self.tcx.mk_substs_trait(new_ty, &old_ref.skip_binder().substs[1..]),
731 self.predicate_must_hold_modulo_regions(&Obligation::new(
732 ObligationCause::dummy(),
734 new_ref.without_const().to_predicate(self.tcx),
737 let imm_result = mk_result(self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, orig_ty));
738 let mut_result = mk_result(self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, orig_ty));
740 if imm_result || mut_result {
741 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
742 // We have a very specific type of error, where just borrowing this argument
743 // might solve the problem. In cases like this, the important part is the
744 // original type obligation, not the last one that failed, which is arbitrary.
745 // Because of this, we modify the error to refer to the original obligation and
746 // return early in the caller.
749 "the trait bound `{}: {}` is not satisfied",
751 old_ref.print_only_trait_path(),
753 if has_custom_message {
756 err.message = vec![(msg, Style::NoStyle)];
758 if snippet.starts_with('&') {
759 // This is already a literal borrow and the obligation is failing
760 // somewhere else in the obligation chain. Do not suggest non-sense.
766 "expected an implementor of trait `{}`",
767 old_ref.print_only_trait_path(),
771 // This if is to prevent a special edge-case
773 span.ctxt().outer_expn_data().kind,
774 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
776 // We don't want a borrowing suggestion on the fields in structs,
779 // the_foos: Vec<Foo>
783 if imm_result && mut_result {
784 err.span_suggestions(
786 "consider borrowing here",
787 ["&".to_string(), "&mut ".to_string()].into_iter(),
788 Applicability::MaybeIncorrect,
791 err.span_suggestion_verbose(
794 "consider{} borrowing here",
795 if mut_result { " mutably" } else { "" }
797 format!("&{}", if mut_result { "mut " } else { "" }),
798 Applicability::MaybeIncorrect,
808 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &*code {
809 try_borrowing(obligation.parent_trait_ref, &[])
810 } else if let ObligationCauseCode::BindingObligation(_, _)
811 | ObligationCauseCode::ItemObligation(_) = &*code
813 try_borrowing(*poly_trait_ref, &never_suggest_borrow)
819 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
820 /// suggest removing these references until we reach a type that implements the trait.
821 fn suggest_remove_reference(
823 obligation: &PredicateObligation<'tcx>,
824 err: &mut DiagnosticBuilder<'_>,
825 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
827 let span = obligation.cause.span;
829 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
831 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
832 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
833 // Do not suggest removal of borrow from type arguments.
837 let mut suggested_ty = match trait_ref.self_ty().no_bound_vars() {
842 for refs_remaining in 0..refs_number {
843 if let ty::Ref(_, inner_ty, _) = suggested_ty.kind() {
844 suggested_ty = inner_ty;
846 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
847 obligation.param_env,
852 if self.predicate_may_hold(&new_obligation) {
857 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
859 let remove_refs = refs_remaining + 1;
861 let msg = if remove_refs == 1 {
862 "consider removing the leading `&`-reference".to_string()
864 format!("consider removing {} leading `&`-references", remove_refs)
867 err.span_suggestion_short(
871 Applicability::MachineApplicable,
882 fn suggest_remove_await(
884 obligation: &PredicateObligation<'tcx>,
885 err: &mut DiagnosticBuilder<'_>,
887 let span = obligation.cause.span;
889 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code.peel_derives() {
890 let hir = self.tcx.hir();
891 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
892 if let hir::Node::Expr(expr) = node {
893 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
894 // and if not maybe suggest doing something else? If we kept the expression around we
895 // could also check if it is an fn call (very likely) and suggest changing *that*, if
896 // it is from the local crate.
897 err.span_suggestion_verbose(
898 expr.span.shrink_to_hi().with_hi(span.hi()),
899 "remove the `.await`",
901 Applicability::MachineApplicable,
903 // FIXME: account for associated `async fn`s.
904 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
905 if let ty::PredicateKind::Trait(pred) =
906 obligation.predicate.kind().skip_binder()
910 &format!("this call returns `{}`", pred.self_ty()),
913 if let Some(typeck_results) =
914 self.in_progress_typeck_results.map(|t| t.borrow())
916 let ty = typeck_results.expr_ty_adjusted(base);
917 if let ty::FnDef(def_id, _substs) = ty.kind() {
918 if let Some(hir::Node::Item(hir::Item { span, ident, .. })) =
919 hir.get_if_local(*def_id)
921 err.span_suggestion_verbose(
924 "alternatively, consider making `fn {}` asynchronous",
927 "async ".to_string(),
928 Applicability::MaybeIncorrect,
939 /// Check if the trait bound is implemented for a different mutability and note it in the
941 fn suggest_change_mut(
943 obligation: &PredicateObligation<'tcx>,
944 err: &mut DiagnosticBuilder<'_>,
945 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
947 let points_at_arg = matches!(
948 obligation.cause.code,
949 ObligationCauseCode::FunctionArgumentObligation { .. },
952 let span = obligation.cause.span;
953 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
955 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
956 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
957 // Do not suggest removal of borrow from type arguments.
960 let trait_ref = self.resolve_vars_if_possible(trait_ref);
961 if trait_ref.has_infer_types_or_consts() {
962 // Do not ICE while trying to find if a reborrow would succeed on a trait with
963 // unresolved bindings.
967 if let ty::Ref(region, t_type, mutability) = *trait_ref.skip_binder().self_ty().kind() {
968 if region.is_late_bound() || t_type.has_escaping_bound_vars() {
969 // Avoid debug assertion in `mk_obligation_for_def_id`.
971 // If the self type has escaping bound vars then it's not
972 // going to be the type of an expression, so the suggestion
973 // probably won't apply anyway.
977 let suggested_ty = match mutability {
978 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
979 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
982 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
983 obligation.param_env,
987 let suggested_ty_would_satisfy_obligation = self
988 .evaluate_obligation_no_overflow(&new_obligation)
989 .must_apply_modulo_regions();
990 if suggested_ty_would_satisfy_obligation {
995 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
996 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
997 err.span_suggestion_verbose(
999 "consider changing this borrow's mutability",
1000 "&mut ".to_string(),
1001 Applicability::MachineApplicable,
1005 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1006 trait_ref.print_only_trait_path(),
1008 trait_ref.skip_binder().self_ty(),
1016 fn suggest_semicolon_removal(
1018 obligation: &PredicateObligation<'tcx>,
1019 err: &mut DiagnosticBuilder<'_>,
1021 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
1023 let is_empty_tuple =
1024 |ty: ty::Binder<'tcx, Ty<'_>>| *ty.skip_binder().kind() == ty::Tuple(ty::List::empty());
1026 let hir = self.tcx.hir();
1027 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1028 let node = hir.find(parent_node);
1029 if let Some(hir::Node::Item(hir::Item {
1030 kind: hir::ItemKind::Fn(sig, _, body_id), ..
1033 let body = hir.body(*body_id);
1034 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
1035 if sig.decl.output.span().overlaps(span)
1036 && blk.expr.is_none()
1037 && is_empty_tuple(trait_ref.self_ty())
1039 // FIXME(estebank): When encountering a method with a trait
1040 // bound not satisfied in the return type with a body that has
1041 // no return, suggest removal of semicolon on last statement.
1042 // Once that is added, close #54771.
1043 if let Some(ref stmt) = blk.stmts.last() {
1044 if let hir::StmtKind::Semi(_) = stmt.kind {
1045 let sp = self.tcx.sess.source_map().end_point(stmt.span);
1046 err.span_label(sp, "consider removing this semicolon");
1054 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1055 let hir = self.tcx.hir();
1056 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1057 let sig = match hir.find(parent_node) {
1058 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) => sig,
1062 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1065 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1066 /// applicable and signal that the error has been expanded appropriately and needs to be
1068 fn suggest_impl_trait(
1070 err: &mut DiagnosticBuilder<'_>,
1072 obligation: &PredicateObligation<'tcx>,
1073 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
1075 match obligation.cause.code.peel_derives() {
1076 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1077 ObligationCauseCode::SizedReturnType => {}
1081 let hir = self.tcx.hir();
1082 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1083 let node = hir.find(parent_node);
1084 let Some(hir::Node::Item(hir::Item {
1085 kind: hir::ItemKind::Fn(sig, _, body_id),
1091 let body = hir.body(*body_id);
1092 let trait_ref = self.resolve_vars_if_possible(trait_ref);
1093 let ty = trait_ref.skip_binder().self_ty();
1094 let is_object_safe = match ty.kind() {
1095 ty::Dynamic(predicates, _) => {
1096 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1099 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1101 // We only want to suggest `impl Trait` to `dyn Trait`s.
1102 // For example, `fn foo() -> str` needs to be filtered out.
1106 let ret_ty = if let hir::FnRetTy::Return(ret_ty) = sig.decl.output {
1112 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1113 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1114 // Recursively look for `TraitObject` types and if there's only one, use that span to
1115 // suggest `impl Trait`.
1117 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1118 // otherwise suggest using `Box<dyn Trait>` or an enum.
1119 let mut visitor = ReturnsVisitor::default();
1120 visitor.visit_body(&body);
1122 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1124 let mut ret_types = visitor
1127 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1128 .map(|ty| self.resolve_vars_if_possible(ty));
1129 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1131 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1133 let ty = self.resolve_vars_if_possible(ty);
1135 !matches!(ty.kind(), ty::Error(_))
1136 && last_ty.map_or(true, |last_ty| {
1137 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1138 // *after* in the dependency graph.
1139 match (ty.kind(), last_ty.kind()) {
1140 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1141 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1142 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1144 Infer(InferTy::FreshFloatTy(_)),
1145 Infer(InferTy::FreshFloatTy(_)),
1150 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1153 let all_returns_conform_to_trait =
1154 if let Some(ty_ret_ty) = typeck_results.node_type_opt(ret_ty.hir_id) {
1155 match ty_ret_ty.kind() {
1156 ty::Dynamic(predicates, _) => {
1157 let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
1158 let param_env = ty::ParamEnv::empty();
1160 || ret_types.all(|returned_ty| {
1161 predicates.iter().all(|predicate| {
1162 let pred = predicate.with_self_ty(self.tcx, returned_ty);
1163 let obl = Obligation::new(cause.clone(), param_env, pred);
1164 self.predicate_may_hold(&obl)
1174 let sm = self.tcx.sess.source_map();
1175 let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
1176 // Verify that we're dealing with a return `dyn Trait`
1177 ret_ty.span.overlaps(span),
1179 sm.span_to_snippet(ret_ty.span),
1180 // If any of the return types does not conform to the trait, then we can't
1181 // suggest `impl Trait` nor trait objects: it is a type mismatch error.
1182 all_returns_conform_to_trait,
1188 err.code(error_code!(E0746));
1189 err.set_primary_message("return type cannot have an unboxed trait object");
1190 err.children.clear();
1191 let impl_trait_msg = "for information on `impl Trait`, see \
1192 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1193 #returning-types-that-implement-traits>";
1194 let trait_obj_msg = "for information on trait objects, see \
1195 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1196 #using-trait-objects-that-allow-for-values-of-different-types>";
1197 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1198 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1199 if only_never_return {
1200 // No return paths, probably using `panic!()` or similar.
1201 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1202 suggest_trait_object_return_type_alternatives(
1208 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1209 // Suggest `-> impl Trait`.
1210 err.span_suggestion(
1213 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1214 which implements `{1}`",
1217 format!("impl {}", trait_obj),
1218 Applicability::MachineApplicable,
1220 err.note(impl_trait_msg);
1223 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1224 // Get all the return values and collect their span and suggestion.
1225 let mut suggestions: Vec<_> = visitor
1230 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
1231 (expr.span.shrink_to_hi(), ")".to_string()),
1236 if !suggestions.is_empty() {
1237 // Add the suggestion for the return type.
1238 suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
1239 err.multipart_suggestion(
1240 "return a boxed trait object instead",
1242 Applicability::MaybeIncorrect,
1246 // This is currently not possible to trigger because E0038 takes precedence, but
1247 // leave it in for completeness in case anything changes in an earlier stage.
1249 "if trait `{}` were object-safe, you could return a trait object",
1253 err.note(trait_obj_msg);
1255 "if all the returned values were of the same type you could use `impl {}` as the \
1259 err.note(impl_trait_msg);
1260 err.note("you can create a new `enum` with a variant for each returned type");
1265 fn point_at_returns_when_relevant(
1267 err: &mut DiagnosticBuilder<'_>,
1268 obligation: &PredicateObligation<'tcx>,
1270 match obligation.cause.code.peel_derives() {
1271 ObligationCauseCode::SizedReturnType => {}
1275 let hir = self.tcx.hir();
1276 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1277 let node = hir.find(parent_node);
1278 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1281 let body = hir.body(*body_id);
1282 // Point at all the `return`s in the function as they have failed trait bounds.
1283 let mut visitor = ReturnsVisitor::default();
1284 visitor.visit_body(&body);
1285 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1286 for expr in &visitor.returns {
1287 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1288 let ty = self.resolve_vars_if_possible(returned_ty);
1289 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1295 fn report_closure_arg_mismatch(
1298 found_span: Option<Span>,
1299 expected_ref: ty::PolyTraitRef<'tcx>,
1300 found: ty::PolyTraitRef<'tcx>,
1301 ) -> DiagnosticBuilder<'tcx> {
1302 crate fn build_fn_sig_string<'tcx>(
1304 trait_ref: ty::PolyTraitRef<'tcx>,
1306 let inputs = trait_ref.skip_binder().substs.type_at(1);
1307 let sig = match inputs.kind() {
1309 if tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1312 inputs.iter().map(|k| k.expect_ty()),
1313 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1315 hir::Unsafety::Normal,
1320 std::iter::once(inputs),
1321 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1323 hir::Unsafety::Normal,
1327 trait_ref.rebind(sig).to_string()
1330 let argument_kind = match expected_ref.skip_binder().substs.type_at(0) {
1331 t if t.is_closure() => "closure",
1332 t if t.is_generator() => "generator",
1335 let mut err = struct_span_err!(
1339 "type mismatch in {} arguments",
1343 let found_str = format!("expected signature of `{}`", build_fn_sig_string(self.tcx, found));
1344 err.span_label(span, found_str);
1346 let found_span = found_span.unwrap_or(span);
1348 format!("found signature of `{}`", build_fn_sig_string(self.tcx, expected_ref));
1349 err.span_label(found_span, expected_str);
1354 fn suggest_fully_qualified_path(
1356 err: &mut DiagnosticBuilder<'_>,
1361 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1362 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1364 "{}s cannot be accessed directly on a `trait`, they can only be \
1365 accessed through a specific `impl`",
1366 assoc_item.kind.as_def_kind().descr(def_id)
1368 err.span_suggestion(
1370 "use the fully qualified path to an implementation",
1371 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1372 Applicability::HasPlaceholders,
1378 /// Adds an async-await specific note to the diagnostic when the future does not implement
1379 /// an auto trait because of a captured type.
1382 /// note: future does not implement `Qux` as this value is used across an await
1383 /// --> $DIR/issue-64130-3-other.rs:17:5
1385 /// LL | let x = Foo;
1386 /// | - has type `Foo`
1387 /// LL | baz().await;
1388 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1390 /// | - `x` is later dropped here
1393 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1394 /// is "replaced" with a different message and a more specific error.
1397 /// error: future cannot be sent between threads safely
1398 /// --> $DIR/issue-64130-2-send.rs:21:5
1400 /// LL | fn is_send<T: Send>(t: T) { }
1401 /// | ---- required by this bound in `is_send`
1403 /// LL | is_send(bar());
1404 /// | ^^^^^^^ future returned by `bar` is not send
1406 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1407 /// implemented for `Foo`
1408 /// note: future is not send as this value is used across an await
1409 /// --> $DIR/issue-64130-2-send.rs:15:5
1411 /// LL | let x = Foo;
1412 /// | - has type `Foo`
1413 /// LL | baz().await;
1414 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1416 /// | - `x` is later dropped here
1419 /// Returns `true` if an async-await specific note was added to the diagnostic.
1420 fn maybe_note_obligation_cause_for_async_await(
1422 err: &mut DiagnosticBuilder<'_>,
1423 obligation: &PredicateObligation<'tcx>,
1426 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1427 obligation.cause.span={:?}",
1428 obligation.predicate, obligation.cause.span
1430 let hir = self.tcx.hir();
1432 // Attempt to detect an async-await error by looking at the obligation causes, looking
1433 // for a generator to be present.
1435 // When a future does not implement a trait because of a captured type in one of the
1436 // generators somewhere in the call stack, then the result is a chain of obligations.
1438 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1439 // future is passed as an argument to a function C which requires a `Send` type, then the
1440 // chain looks something like this:
1442 // - `BuiltinDerivedObligation` with a generator witness (B)
1443 // - `BuiltinDerivedObligation` with a generator (B)
1444 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1445 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1446 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1447 // - `BuiltinDerivedObligation` with a generator witness (A)
1448 // - `BuiltinDerivedObligation` with a generator (A)
1449 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1450 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1451 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1452 // - `BindingObligation` with `impl_send (Send requirement)
1454 // The first obligation in the chain is the most useful and has the generator that captured
1455 // the type. The last generator (`outer_generator` below) has information about where the
1456 // bound was introduced. At least one generator should be present for this diagnostic to be
1458 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1459 ty::PredicateKind::Trait(p) => (Some(p.trait_ref), Some(p.self_ty())),
1462 let mut generator = None;
1463 let mut outer_generator = None;
1464 let mut next_code = Some(&obligation.cause.code);
1466 let mut seen_upvar_tys_infer_tuple = false;
1468 while let Some(code) = next_code {
1469 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1471 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1472 next_code = Some(parent_code.as_ref());
1474 ObligationCauseCode::DerivedObligation(derived_obligation)
1475 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1476 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1477 let ty = derived_obligation.parent_trait_ref.skip_binder().self_ty();
1479 "maybe_note_obligation_cause_for_async_await: \
1480 parent_trait_ref={:?} self_ty.kind={:?}",
1481 derived_obligation.parent_trait_ref,
1486 ty::Generator(did, ..) => {
1487 generator = generator.or(Some(did));
1488 outer_generator = Some(did);
1490 ty::GeneratorWitness(..) => {}
1491 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1492 // By introducing a tuple of upvar types into the chain of obligations
1493 // of a generator, the first non-generator item is now the tuple itself,
1494 // we shall ignore this.
1496 seen_upvar_tys_infer_tuple = true;
1498 _ if generator.is_none() => {
1499 trait_ref = Some(derived_obligation.parent_trait_ref.skip_binder());
1500 target_ty = Some(ty);
1505 next_code = Some(derived_obligation.parent_code.as_ref());
1511 // Only continue if a generator was found.
1512 debug!(?generator, ?trait_ref, ?target_ty, "maybe_note_obligation_cause_for_async_await");
1513 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1514 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1515 (generator_did, trait_ref, target_ty)
1520 let span = self.tcx.def_span(generator_did);
1522 let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1523 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1525 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1526 generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
1529 in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1533 let generator_body = generator_did
1535 .map(|def_id| hir.local_def_id_to_hir_id(def_id))
1536 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1537 .map(|body_id| hir.body(body_id));
1538 let mut visitor = AwaitsVisitor::default();
1539 if let Some(body) = generator_body {
1540 visitor.visit_body(body);
1542 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1544 // Look for a type inside the generator interior that matches the target type to get
1546 let target_ty_erased = self.tcx.erase_regions(target_ty);
1547 let ty_matches = |ty| -> bool {
1548 // Careful: the regions for types that appear in the
1549 // generator interior are not generally known, so we
1550 // want to erase them when comparing (and anyway,
1551 // `Send` and other bounds are generally unaffected by
1552 // the choice of region). When erasing regions, we
1553 // also have to erase late-bound regions. This is
1554 // because the types that appear in the generator
1555 // interior generally contain "bound regions" to
1556 // represent regions that are part of the suspended
1557 // generator frame. Bound regions are preserved by
1558 // `erase_regions` and so we must also call
1559 // `erase_late_bound_regions`.
1560 let ty_erased = self.tcx.erase_late_bound_regions(ty);
1561 let ty_erased = self.tcx.erase_regions(ty_erased);
1562 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1564 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1565 target_ty_erased={:?} eq={:?}",
1566 ty_erased, target_ty_erased, eq
1571 let mut interior_or_upvar_span = None;
1572 let mut interior_extra_info = None;
1574 // Get the typeck results from the infcx if the generator is the function we are currently
1575 // type-checking; otherwise, get them by performing a query. This is needed to avoid
1576 // cycles. If we can't use resolved types because the generator comes from another crate,
1577 // we still provide a targeted error but without all the relevant spans.
1578 let query_typeck_results;
1579 let typeck_results: Option<&TypeckResults<'tcx>> = match &in_progress_typeck_results {
1580 Some(t) if t.hir_owner.to_def_id() == generator_did_root => Some(&t),
1581 _ if generator_did.is_local() => {
1582 query_typeck_results = self.tcx.typeck(generator_did.expect_local());
1583 Some(&query_typeck_results)
1585 _ => None, // Do not ICE on closure typeck (#66868).
1587 if let Some(typeck_results) = typeck_results {
1588 if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) {
1589 interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| {
1590 let upvar_ty = typeck_results.node_type(*upvar_id);
1591 let upvar_ty = self.resolve_vars_if_possible(upvar_ty);
1592 if ty_matches(ty::Binder::dummy(upvar_ty)) {
1593 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
1600 // The generator interior types share the same binders
1601 if let Some(cause) =
1602 typeck_results.generator_interior_types.as_ref().skip_binder().iter().find(
1603 |ty::GeneratorInteriorTypeCause { ty, .. }| {
1604 ty_matches(typeck_results.generator_interior_types.rebind(ty))
1608 // Check to see if any awaited expressions have the target type.
1609 let from_awaited_ty = visitor
1612 .map(|id| hir.expect_expr(id))
1613 .find(|await_expr| {
1614 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
1616 .map(|expr| expr.span);
1617 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1620 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1621 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1624 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span));
1627 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1628 self.note_obligation_cause_for_async_await(
1630 interior_or_upvar_span,
1631 interior_extra_info,
1646 /// Unconditionally adds the diagnostic note described in
1647 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1648 fn note_obligation_cause_for_async_await(
1650 err: &mut DiagnosticBuilder<'_>,
1651 interior_or_upvar_span: GeneratorInteriorOrUpvar,
1652 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1653 inner_generator_body: Option<&hir::Body<'tcx>>,
1654 outer_generator: Option<DefId>,
1655 trait_ref: ty::TraitRef<'tcx>,
1656 target_ty: Ty<'tcx>,
1657 typeck_results: Option<&ty::TypeckResults<'tcx>>,
1658 obligation: &PredicateObligation<'tcx>,
1659 next_code: Option<&ObligationCauseCode<'tcx>>,
1661 let source_map = self.tcx.sess.source_map();
1663 let is_async = inner_generator_body
1664 .and_then(|body| body.generator_kind())
1665 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1667 let (await_or_yield, an_await_or_yield) =
1668 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1669 let future_or_generator = if is_async { "future" } else { "generator" };
1671 // Special case the primary error message when send or sync is the trait that was
1673 let hir = self.tcx.hir();
1674 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
1675 self.tcx.get_diagnostic_name(trait_ref.def_id)
1677 let (trait_name, trait_verb) =
1678 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1681 err.set_primary_message(format!(
1682 "{} cannot be {} between threads safely",
1683 future_or_generator, trait_verb
1686 let original_span = err.span.primary_span().unwrap();
1687 let mut span = MultiSpan::from_span(original_span);
1689 let message = outer_generator
1690 .and_then(|generator_did| {
1691 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1692 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1693 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1695 .parent(generator_did)
1696 .and_then(|parent_did| parent_did.as_local())
1697 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
1698 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1700 format!("future returned by `{}` is not {}", name, trait_name)
1702 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1703 format!("future created by async block is not {}", trait_name)
1705 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1706 format!("future created by async closure is not {}", trait_name)
1710 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1712 span.push_span_label(original_span, message);
1715 format!("is not {}", trait_name)
1717 format!("does not implement `{}`", trait_ref.print_only_trait_path())
1720 let mut explain_yield = |interior_span: Span,
1722 scope_span: Option<Span>| {
1723 let mut span = MultiSpan::from_span(yield_span);
1724 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1725 // #70935: If snippet contains newlines, display "the value" instead
1726 // so that we do not emit complex diagnostics.
1727 let snippet = &format!("`{}`", snippet);
1728 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
1729 // note: future is not `Send` as this value is used across an await
1730 // --> $DIR/issue-70935-complex-spans.rs:13:9
1732 // LL | baz(|| async {
1733 // | ______________-
1736 // LL | | foo(tx.clone());
1738 // | | - ^^^^^^ await occurs here, with value maybe used later
1740 // | has type `closure` which is not `Send`
1741 // note: value is later dropped here
1745 span.push_span_label(
1747 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
1749 span.push_span_label(
1751 format!("has type `{}` which {}", target_ty, trait_explanation),
1753 // If available, use the scope span to annotate the drop location.
1754 let mut scope_note = None;
1755 if let Some(scope_span) = scope_span {
1756 let scope_span = source_map.end_point(scope_span);
1758 let msg = format!("{} is later dropped here", snippet);
1759 if source_map.is_multiline(yield_span.between(scope_span)) {
1760 span.push_span_label(scope_span, msg);
1762 scope_note = Some((scope_span, msg));
1768 "{} {} as this value is used across {}",
1769 future_or_generator, trait_explanation, an_await_or_yield
1772 if let Some((span, msg)) = scope_note {
1773 err.span_note(span, &msg);
1777 match interior_or_upvar_span {
1778 GeneratorInteriorOrUpvar::Interior(interior_span) => {
1779 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
1780 if let Some(await_span) = from_awaited_ty {
1781 // The type causing this obligation is one being awaited at await_span.
1782 let mut span = MultiSpan::from_span(await_span);
1783 span.push_span_label(
1786 "await occurs here on type `{}`, which {}",
1787 target_ty, trait_explanation
1793 "future {not_trait} as it awaits another future which {not_trait}",
1794 not_trait = trait_explanation
1798 // Look at the last interior type to get a span for the `.await`.
1800 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1801 typeck_results.as_ref().map(|t| &t.generator_interior_types)
1803 explain_yield(interior_span, yield_span, scope_span);
1806 if let Some(expr_id) = expr {
1807 let expr = hir.expect_expr(expr_id);
1808 debug!("target_ty evaluated from {:?}", expr);
1810 let parent = hir.get_parent_node(expr_id);
1811 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1812 let parent_span = hir.span(parent);
1813 let parent_did = parent.owner.to_def_id();
1816 // fn foo(&self) -> i32 {}
1819 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1822 let is_region_borrow = if let Some(typeck_results) = typeck_results {
1824 .expr_adjustments(expr)
1826 .any(|adj| adj.is_region_borrow())
1832 // struct Foo(*const u8);
1833 // bar(Foo(std::ptr::null())).await;
1834 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1836 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1837 let is_raw_borrow_inside_fn_like_call =
1838 match self.tcx.def_kind(parent_did) {
1839 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
1842 if let Some(typeck_results) = typeck_results {
1843 if (typeck_results.is_method_call(e) && is_region_borrow)
1844 || is_raw_borrow_inside_fn_like_call
1848 "consider moving this into a `let` \
1849 binding to create a shorter lived borrow",
1857 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
1858 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
1859 let refers_to_non_sync = match target_ty.kind() {
1860 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
1861 Ok(eval) if !eval.may_apply() => Some(ref_ty),
1867 let (span_label, span_note) = match refers_to_non_sync {
1868 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
1869 // include suggestions to make `T: Sync` so that `&T: Send`
1872 "has type `{}` which {}, because `{}` is not `Sync`",
1873 target_ty, trait_explanation, ref_ty
1876 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
1881 format!("has type `{}` which {}", target_ty, trait_explanation),
1882 format!("captured value {}", trait_explanation),
1886 let mut span = MultiSpan::from_span(upvar_span);
1887 span.push_span_label(upvar_span, span_label);
1888 err.span_note(span, &span_note);
1892 // Add a note for the item obligation that remains - normally a note pointing to the
1893 // bound that introduced the obligation (e.g. `T: Send`).
1894 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1895 self.note_obligation_cause_code(
1897 &obligation.predicate,
1900 &mut Default::default(),
1904 fn note_obligation_cause_code<T>(
1906 err: &mut DiagnosticBuilder<'_>,
1908 cause_code: &ObligationCauseCode<'tcx>,
1909 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1910 seen_requirements: &mut FxHashSet<DefId>,
1916 ObligationCauseCode::ExprAssignable
1917 | ObligationCauseCode::MatchExpressionArm { .. }
1918 | ObligationCauseCode::Pattern { .. }
1919 | ObligationCauseCode::IfExpression { .. }
1920 | ObligationCauseCode::IfExpressionWithNoElse
1921 | ObligationCauseCode::MainFunctionType
1922 | ObligationCauseCode::StartFunctionType
1923 | ObligationCauseCode::IntrinsicType
1924 | ObligationCauseCode::MethodReceiver
1925 | ObligationCauseCode::ReturnNoExpression
1926 | ObligationCauseCode::UnifyReceiver(..)
1927 | ObligationCauseCode::OpaqueType
1928 | ObligationCauseCode::MiscObligation
1929 | ObligationCauseCode::WellFormed(..)
1930 | ObligationCauseCode::MatchImpl(..)
1931 | ObligationCauseCode::ReturnType
1932 | ObligationCauseCode::ReturnValue(_)
1933 | ObligationCauseCode::BlockTailExpression(_)
1934 | ObligationCauseCode::AwaitableExpr(_)
1935 | ObligationCauseCode::ForLoopIterator
1936 | ObligationCauseCode::QuestionMark
1937 | ObligationCauseCode::LetElse => {}
1938 ObligationCauseCode::SliceOrArrayElem => {
1939 err.note("slice and array elements must have `Sized` type");
1941 ObligationCauseCode::TupleElem => {
1942 err.note("only the last element of a tuple may have a dynamically sized type");
1944 ObligationCauseCode::ProjectionWf(data) => {
1945 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1947 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1949 "required so that reference `{}` does not outlive its referent",
1953 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1955 "required so that the lifetime bound of `{}` for `{}` is satisfied",
1959 ObligationCauseCode::ItemObligation(_item_def_id) => {
1960 // We hold the `DefId` of the item introducing the obligation, but displaying it
1961 // doesn't add user usable information. It always point at an associated item.
1963 ObligationCauseCode::BindingObligation(item_def_id, span) => {
1964 let item_name = tcx.def_path_str(item_def_id);
1965 let mut multispan = MultiSpan::from(span);
1966 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1967 let sm = tcx.sess.source_map();
1969 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
1970 (Ok(l), Ok(r)) => l.line == r.line,
1973 if !ident.span.overlaps(span) && !same_line {
1975 .push_span_label(ident.span, "required by a bound in this".to_string());
1978 let descr = format!("required by a bound in `{}`", item_name);
1979 if span != DUMMY_SP {
1980 let msg = format!("required by this bound in `{}`", item_name);
1981 multispan.push_span_label(span, msg);
1982 err.span_note(multispan, &descr);
1984 err.span_note(tcx.def_span(item_def_id), &descr);
1987 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1989 "required for the cast to the object type `{}`",
1990 self.ty_to_string(object_ty)
1993 ObligationCauseCode::Coercion { source: _, target } => {
1994 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1996 ObligationCauseCode::RepeatVec(is_const_fn) => {
1998 "the `Copy` trait is required because the repeated element will be copied",
2003 "consider creating a new `const` item and initializing it with the result \
2004 of the function call to be used in the repeat position, like \
2005 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2009 if self.tcx.sess.is_nightly_build() && is_const_fn {
2011 "create an inline `const` block, see RFC #2920 \
2012 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2016 ObligationCauseCode::VariableType(hir_id) => {
2017 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2018 match self.tcx.hir().find(parent_node) {
2019 Some(Node::Local(hir::Local {
2020 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2023 // When encountering an assignment of an unsized trait, like
2024 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2025 // order to use have a slice instead.
2026 err.span_suggestion_verbose(
2027 span.shrink_to_lo(),
2028 "consider borrowing here",
2030 Applicability::MachineApplicable,
2032 err.note("all local variables must have a statically known size");
2034 Some(Node::Param(param)) => {
2035 err.span_suggestion_verbose(
2036 param.ty_span.shrink_to_lo(),
2037 "function arguments must have a statically known size, borrowed types \
2038 always have a known size",
2040 Applicability::MachineApplicable,
2044 err.note("all local variables must have a statically known size");
2047 if !self.tcx.features().unsized_locals {
2048 err.help("unsized locals are gated as an unstable feature");
2051 ObligationCauseCode::SizedArgumentType(sp) => {
2052 if let Some(span) = sp {
2053 err.span_suggestion_verbose(
2054 span.shrink_to_lo(),
2055 "function arguments must have a statically known size, borrowed types \
2056 always have a known size",
2058 Applicability::MachineApplicable,
2061 err.note("all function arguments must have a statically known size");
2063 if tcx.sess.opts.unstable_features.is_nightly_build()
2064 && !self.tcx.features().unsized_fn_params
2066 err.help("unsized fn params are gated as an unstable feature");
2069 ObligationCauseCode::SizedReturnType => {
2070 err.note("the return type of a function must have a statically known size");
2072 ObligationCauseCode::SizedYieldType => {
2073 err.note("the yield type of a generator must have a statically known size");
2075 ObligationCauseCode::SizedBoxType => {
2076 err.note("the type of a box expression must have a statically known size");
2078 ObligationCauseCode::AssignmentLhsSized => {
2079 err.note("the left-hand-side of an assignment must have a statically known size");
2081 ObligationCauseCode::TupleInitializerSized => {
2082 err.note("tuples must have a statically known size to be initialized");
2084 ObligationCauseCode::StructInitializerSized => {
2085 err.note("structs must have a statically known size to be initialized");
2087 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2089 AdtKind::Struct => {
2092 "the last field of a packed struct may only have a \
2093 dynamically sized type if it does not need drop to be run",
2097 "only the last field of a struct may have a dynamically sized type",
2102 err.note("no field of a union may have a dynamically sized type");
2105 err.note("no field of an enum variant may have a dynamically sized type");
2108 err.help("change the field's type to have a statically known size");
2109 err.span_suggestion(
2110 span.shrink_to_lo(),
2111 "borrowed types always have a statically known size",
2113 Applicability::MachineApplicable,
2115 err.multipart_suggestion(
2116 "the `Box` type always has a statically known size and allocates its contents \
2119 (span.shrink_to_lo(), "Box<".to_string()),
2120 (span.shrink_to_hi(), ">".to_string()),
2122 Applicability::MachineApplicable,
2125 ObligationCauseCode::ConstSized => {
2126 err.note("constant expressions must have a statically known size");
2128 ObligationCauseCode::InlineAsmSized => {
2129 err.note("all inline asm arguments must have a statically known size");
2131 ObligationCauseCode::ConstPatternStructural => {
2132 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2134 ObligationCauseCode::SharedStatic => {
2135 err.note("shared static variables must have a type that implements `Sync`");
2137 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2138 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2139 let ty = parent_trait_ref.skip_binder().self_ty();
2140 if parent_trait_ref.references_error() {
2145 // If the obligation for a tuple is set directly by a Generator or Closure,
2146 // then the tuple must be the one containing capture types.
2147 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2150 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) =
2153 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2154 let ty = parent_trait_ref.skip_binder().self_ty();
2155 matches!(ty.kind(), ty::Generator(..))
2156 || matches!(ty.kind(), ty::Closure(..))
2162 // Don't print the tuple of capture types
2163 if !is_upvar_tys_infer_tuple {
2164 let msg = format!("required because it appears within the type `{}`", ty);
2166 ty::Adt(def, _) => match self.tcx.opt_item_name(def.did) {
2167 Some(ident) => err.span_note(ident.span, &msg),
2168 None => err.note(&msg),
2170 _ => err.note(&msg),
2174 obligated_types.push(ty);
2176 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2177 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2178 // #74711: avoid a stack overflow
2179 ensure_sufficient_stack(|| {
2180 self.note_obligation_cause_code(
2189 ensure_sufficient_stack(|| {
2190 self.note_obligation_cause_code(
2193 &cause_code.peel_derives(),
2200 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2201 let mut parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2202 let parent_def_id = parent_trait_ref.def_id();
2204 "required because of the requirements on the impl of `{}` for `{}`",
2205 parent_trait_ref.print_only_trait_path(),
2206 parent_trait_ref.skip_binder().self_ty()
2208 let mut candidates = vec![];
2209 self.tcx.for_each_relevant_impl(
2211 parent_trait_ref.self_ty().skip_binder(),
2212 |impl_def_id| match self.tcx.hir().get_if_local(impl_def_id) {
2213 Some(Node::Item(hir::Item {
2214 kind: hir::ItemKind::Impl(hir::Impl { .. }),
2217 candidates.push(impl_def_id);
2222 match &candidates[..] {
2223 [def_id] => match self.tcx.hir().get_if_local(*def_id) {
2224 Some(Node::Item(hir::Item {
2225 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2228 let mut spans = Vec::with_capacity(2);
2229 if let Some(trait_ref) = of_trait {
2230 spans.push(trait_ref.path.span);
2232 spans.push(self_ty.span);
2233 err.span_note(spans, &msg)
2235 _ => err.note(&msg),
2237 _ => err.note(&msg),
2240 let mut parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2241 let mut data = data;
2243 seen_requirements.insert(parent_def_id);
2244 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2245 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2246 let child_trait_ref = self.resolve_vars_if_possible(child.parent_trait_ref);
2247 let child_def_id = child_trait_ref.def_id();
2248 if seen_requirements.insert(child_def_id) {
2253 parent_predicate = child_trait_ref.without_const().to_predicate(tcx);
2254 parent_trait_ref = child_trait_ref;
2258 "{} redundant requirement{} hidden",
2263 "required because of the requirements on the impl of `{}` for `{}`",
2264 parent_trait_ref.print_only_trait_path(),
2265 parent_trait_ref.skip_binder().self_ty()
2268 // #74711: avoid a stack overflow
2269 ensure_sufficient_stack(|| {
2270 self.note_obligation_cause_code(
2279 ObligationCauseCode::DerivedObligation(ref data) => {
2280 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2281 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2282 // #74711: avoid a stack overflow
2283 ensure_sufficient_stack(|| {
2284 self.note_obligation_cause_code(
2293 ObligationCauseCode::FunctionArgumentObligation {
2298 let hir = self.tcx.hir();
2299 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2300 hir.find(arg_hir_id)
2302 let in_progress_typeck_results =
2303 self.in_progress_typeck_results.map(|t| t.borrow());
2304 let parent_id = hir.local_def_id(hir.get_parent_item(arg_hir_id));
2305 let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
2306 Some(t) if t.hir_owner == parent_id => t,
2307 _ => self.tcx.typeck(parent_id),
2309 let ty = typeck_results.expr_ty_adjusted(expr);
2310 let span = expr.peel_blocks().span;
2311 if Some(span) != err.span.primary_span() {
2314 &if ty.references_error() {
2317 format!("this tail expression is of type `{:?}`", ty)
2322 if let Some(Node::Expr(hir::Expr {
2324 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2325 | hir::ExprKind::MethodCall(_, span, ..),
2327 })) = hir.find(call_hir_id)
2329 if Some(*span) != err.span.primary_span() {
2330 err.span_label(*span, "required by a bound introduced by this call");
2333 ensure_sufficient_stack(|| {
2334 self.note_obligation_cause_code(
2343 ObligationCauseCode::CompareImplMethodObligation { trait_item_def_id, .. } => {
2344 let item_name = self.tcx.item_name(trait_item_def_id);
2346 "the requirement `{}` appears on the impl method `{}` but not on the \
2347 corresponding trait method",
2348 predicate, item_name,
2352 .opt_item_name(trait_item_def_id)
2354 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2355 let mut assoc_span: MultiSpan = sp.into();
2356 assoc_span.push_span_label(
2358 format!("this trait method doesn't have the requirement `{}`", predicate),
2360 if let Some(ident) = self
2362 .opt_associated_item(trait_item_def_id)
2363 .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2365 assoc_span.push_span_label(ident.span, "in this trait".into());
2367 err.span_note(assoc_span, &msg);
2369 ObligationCauseCode::CompareImplTypeObligation { trait_item_def_id, .. } => {
2370 let item_name = self.tcx.item_name(trait_item_def_id);
2372 "the requirement `{}` appears on the associated impl type `{}` but not on the \
2373 corresponding associated trait type",
2374 predicate, item_name,
2376 let sp = self.tcx.def_span(trait_item_def_id);
2377 let mut assoc_span: MultiSpan = sp.into();
2378 assoc_span.push_span_label(
2381 "this trait associated type doesn't have the requirement `{}`",
2385 if let Some(ident) = self
2387 .opt_associated_item(trait_item_def_id)
2388 .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2390 assoc_span.push_span_label(ident.span, "in this trait".into());
2392 err.span_note(assoc_span, &msg);
2394 ObligationCauseCode::CompareImplConstObligation => {
2396 "the requirement `{}` appears on the associated impl constant \
2397 but not on the corresponding associated trait constant",
2401 ObligationCauseCode::TrivialBound => {
2402 err.help("see issue #48214");
2403 if tcx.sess.opts.unstable_features.is_nightly_build() {
2404 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2410 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2411 let suggested_limit = match self.tcx.recursion_limit() {
2412 Limit(0) => Limit(2),
2416 "consider increasing the recursion limit by adding a \
2417 `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
2419 self.tcx.crate_name(LOCAL_CRATE),
2423 fn suggest_await_before_try(
2425 err: &mut DiagnosticBuilder<'_>,
2426 obligation: &PredicateObligation<'tcx>,
2427 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2431 "suggest_await_before_try: obligation={:?}, span={:?}, trait_ref={:?}, trait_ref_self_ty={:?}",
2437 let body_hir_id = obligation.cause.body_id;
2438 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2440 if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
2441 let body = self.tcx.hir().body(body_id);
2442 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2443 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2445 let self_ty = self.resolve_vars_if_possible(trait_ref.self_ty());
2447 // Do not check on infer_types to avoid panic in evaluate_obligation.
2448 if self_ty.has_infer_types() {
2451 let self_ty = self.tcx.erase_regions(self_ty);
2453 let impls_future = self.type_implements_trait(
2455 self_ty.skip_binder(),
2457 obligation.param_env,
2460 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2461 // `<T as Future>::Output`
2462 let projection_ty = ty::ProjectionTy {
2464 substs: self.tcx.mk_substs_trait(
2465 trait_ref.self_ty().skip_binder(),
2466 self.fresh_substs_for_item(span, item_def_id),
2472 let mut selcx = SelectionContext::new(self);
2474 let mut obligations = vec![];
2475 let normalized_ty = normalize_projection_type(
2477 obligation.param_env,
2479 obligation.cause.clone(),
2485 "suggest_await_before_try: normalized_projection_type {:?}",
2486 self.resolve_vars_if_possible(normalized_ty)
2488 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2489 obligation.param_env,
2493 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2494 if self.predicate_may_hold(&try_obligation)
2495 && impls_future.must_apply_modulo_regions()
2497 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2498 if snippet.ends_with('?') {
2499 err.span_suggestion_verbose(
2500 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2501 "consider `await`ing on the `Future`",
2502 ".await".to_string(),
2503 Applicability::MaybeIncorrect,
2513 /// Collect all the returned expressions within the input expression.
2514 /// Used to point at the return spans when we want to suggest some change to them.
2516 pub struct ReturnsVisitor<'v> {
2517 pub returns: Vec<&'v hir::Expr<'v>>,
2518 in_block_tail: bool,
2521 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2522 type Map = hir::intravisit::ErasedMap<'v>;
2524 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2525 hir::intravisit::NestedVisitorMap::None
2528 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2529 // Visit every expression to detect `return` paths, either through the function's tail
2530 // expression or `return` statements. We walk all nodes to find `return` statements, but
2531 // we only care about tail expressions when `in_block_tail` is `true`, which means that
2532 // they're in the return path of the function body.
2534 hir::ExprKind::Ret(Some(ex)) => {
2535 self.returns.push(ex);
2537 hir::ExprKind::Block(block, _) if self.in_block_tail => {
2538 self.in_block_tail = false;
2539 for stmt in block.stmts {
2540 hir::intravisit::walk_stmt(self, stmt);
2542 self.in_block_tail = true;
2543 if let Some(expr) = block.expr {
2544 self.visit_expr(expr);
2547 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
2548 self.visit_expr(then);
2549 if let Some(el) = else_opt {
2550 self.visit_expr(el);
2553 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2555 self.visit_expr(arm.body);
2558 // We need to walk to find `return`s in the entire body.
2559 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2560 _ => self.returns.push(ex),
2564 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2565 assert!(!self.in_block_tail);
2566 if body.generator_kind().is_none() {
2567 if let hir::ExprKind::Block(block, None) = body.value.kind {
2568 if block.expr.is_some() {
2569 self.in_block_tail = true;
2573 hir::intravisit::walk_body(self, body);
2577 /// Collect all the awaited expressions within the input expression.
2579 struct AwaitsVisitor {
2580 awaits: Vec<hir::HirId>,
2583 impl<'v> Visitor<'v> for AwaitsVisitor {
2584 type Map = hir::intravisit::ErasedMap<'v>;
2586 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2587 hir::intravisit::NestedVisitorMap::None
2590 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2591 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2592 self.awaits.push(id)
2594 hir::intravisit::walk_expr(self, ex)
2598 pub trait NextTypeParamName {
2599 fn next_type_param_name(&self, name: Option<&str>) -> String;
2602 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2603 fn next_type_param_name(&self, name: Option<&str>) -> String {
2604 // This is the list of possible parameter names that we might suggest.
2605 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2606 let name = name.as_deref();
2607 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2608 let used_names = self
2610 .filter_map(|p| match p.name {
2611 hir::ParamName::Plain(ident) => Some(ident.name),
2614 .collect::<Vec<_>>();
2618 .find(|n| !used_names.contains(&Symbol::intern(n)))
2619 .unwrap_or(&"ParamName")
2624 fn suggest_trait_object_return_type_alternatives(
2625 err: &mut DiagnosticBuilder<'_>,
2628 is_object_safe: bool,
2630 err.span_suggestion(
2632 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2635 Applicability::MaybeIncorrect,
2637 err.span_suggestion(
2640 "use `impl {}` as the return type if all return paths have the same type but you \
2641 want to expose only the trait in the signature",
2644 format!("impl {}", trait_obj),
2645 Applicability::MaybeIncorrect,
2648 err.span_suggestion(
2651 "use a boxed trait object if all return paths implement trait `{}`",
2654 format!("Box<dyn {}>", trait_obj),
2655 Applicability::MaybeIncorrect,