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_errors::{error_code, struct_span_err, Applicability, DiagnosticBuilder, Style};
14 use rustc_hir::def::DefKind;
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::intravisit::Visitor;
17 use rustc_hir::lang_items::LangItem;
18 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
19 use rustc_middle::ty::{
20 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
21 Infer, InferTy, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
23 use rustc_middle::ty::{TypeAndMut, TypeckResults};
24 use rustc_span::def_id::LOCAL_CRATE;
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
27 use rustc_target::spec::abi;
30 use super::InferCtxtPrivExt;
31 use crate::infer::InferCtxtExt as _;
32 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
33 use rustc_middle::ty::print::with_no_trimmed_paths;
36 pub enum GeneratorInteriorOrUpvar {
37 // span of interior type
43 // This trait is public to expose the diagnostics methods to clippy.
44 pub trait InferCtxtExt<'tcx> {
45 fn suggest_restricting_param_bound(
47 err: &mut DiagnosticBuilder<'_>,
48 trait_ref: ty::PolyTraitRef<'tcx>,
52 fn suggest_dereferences(
54 obligation: &PredicateObligation<'tcx>,
55 err: &mut DiagnosticBuilder<'tcx>,
56 trait_ref: ty::PolyTraitRef<'tcx>,
63 err: &mut DiagnosticBuilder<'_>,
69 obligation: &PredicateObligation<'tcx>,
70 err: &mut DiagnosticBuilder<'_>,
71 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
75 fn suggest_add_reference_to_arg(
77 obligation: &PredicateObligation<'tcx>,
78 err: &mut DiagnosticBuilder<'_>,
79 trait_ref: &ty::Binder<'tcx, ty::TraitRef<'tcx>>,
81 has_custom_message: bool,
84 fn suggest_remove_reference(
86 obligation: &PredicateObligation<'tcx>,
87 err: &mut DiagnosticBuilder<'_>,
88 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
91 fn suggest_change_mut(
93 obligation: &PredicateObligation<'tcx>,
94 err: &mut DiagnosticBuilder<'_>,
95 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
99 fn suggest_semicolon_removal(
101 obligation: &PredicateObligation<'tcx>,
102 err: &mut DiagnosticBuilder<'_>,
104 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
107 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
109 fn suggest_impl_trait(
111 err: &mut DiagnosticBuilder<'_>,
113 obligation: &PredicateObligation<'tcx>,
114 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
117 fn point_at_returns_when_relevant(
119 err: &mut DiagnosticBuilder<'_>,
120 obligation: &PredicateObligation<'tcx>,
123 fn report_closure_arg_mismatch(
126 found_span: Option<Span>,
127 expected_ref: ty::PolyTraitRef<'tcx>,
128 found: ty::PolyTraitRef<'tcx>,
129 ) -> DiagnosticBuilder<'tcx>;
131 fn suggest_fully_qualified_path(
133 err: &mut DiagnosticBuilder<'_>,
139 fn maybe_note_obligation_cause_for_async_await(
141 err: &mut DiagnosticBuilder<'_>,
142 obligation: &PredicateObligation<'tcx>,
145 fn note_obligation_cause_for_async_await(
147 err: &mut DiagnosticBuilder<'_>,
148 interior_or_upvar_span: GeneratorInteriorOrUpvar,
149 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
150 inner_generator_body: Option<&hir::Body<'tcx>>,
151 outer_generator: Option<DefId>,
152 trait_ref: ty::TraitRef<'tcx>,
154 typeck_results: &ty::TypeckResults<'tcx>,
155 obligation: &PredicateObligation<'tcx>,
156 next_code: Option<&ObligationCauseCode<'tcx>>,
159 fn note_obligation_cause_code<T>(
161 err: &mut DiagnosticBuilder<'_>,
163 cause_code: &ObligationCauseCode<'tcx>,
164 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
165 seen_requirements: &mut FxHashSet<DefId>,
169 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>);
171 /// Suggest to await before try: future? => future.await?
172 fn suggest_await_before_try(
174 err: &mut DiagnosticBuilder<'_>,
175 obligation: &PredicateObligation<'tcx>,
176 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
181 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
183 generics.where_clause.tail_span_for_suggestion(),
186 if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
192 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
193 /// it can also be an `impl Trait` param that needs to be decomposed to a type
194 /// param for cleaner code.
195 fn suggest_restriction(
197 generics: &hir::Generics<'tcx>,
199 err: &mut DiagnosticBuilder<'_>,
200 fn_sig: Option<&hir::FnSig<'_>>,
201 projection: Option<&ty::ProjectionTy<'_>>,
202 trait_ref: ty::PolyTraitRef<'tcx>,
203 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
205 // When we are dealing with a trait, `super_traits` will be `Some`:
206 // Given `trait T: A + B + C {}`
207 // - ^^^^^^^^^ GenericBounds
210 let span = generics.where_clause.span_for_predicates_or_empty_place();
211 if span.from_expansion() || span.desugaring_kind().is_some() {
214 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
215 if let Some((bound_str, fn_sig)) =
216 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
217 // Shenanigans to get the `Trait` from the `impl Trait`.
218 ty::Param(param) => {
219 // `fn foo(t: impl Trait)`
220 // ^^^^^ get this string
221 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
226 // We know we have an `impl Trait` that doesn't satisfy a required projection.
228 // Find all of the ocurrences of `impl Trait` for `Trait` in the function arguments'
229 // types. There should be at least one, but there might be *more* than one. In that
230 // case we could just ignore it and try to identify which one needs the restriction,
231 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
233 let mut ty_spans = vec![];
234 let impl_trait_str = format!("impl {}", bound_str);
235 for input in fn_sig.decl.inputs {
236 if let hir::TyKind::Path(hir::QPath::Resolved(
238 hir::Path { segments: [segment], .. },
241 if segment.ident.as_str() == impl_trait_str.as_str() {
242 // `fn foo(t: impl Trait)`
243 // ^^^^^^^^^^ get this to suggest `T` instead
245 // There might be more than one `impl Trait`.
246 ty_spans.push(input.span);
251 let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
252 // The type param `T: Trait` we will suggest to introduce.
253 let type_param = format!("{}: {}", type_param_name, bound_str);
255 // FIXME: modify the `trait_ref` instead of string shenanigans.
256 // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
257 let pred = trait_ref.without_const().to_predicate(tcx).to_string();
258 let pred = pred.replace(&impl_trait_str, &type_param_name);
260 // Find the last of the generic parameters contained within the span of
265 .map(|p| p.bounds_span().unwrap_or(p.span))
266 .filter(|&span| generics.span.contains(span) && span.desugaring_kind().is_none())
267 .max_by_key(|span| span.hi())
269 // `fn foo(t: impl Trait)`
270 // ^ suggest `<T: Trait>` here
271 None => (generics.span, format!("<{}>", type_param)),
272 // `fn foo<A>(t: impl Trait)`
273 // ^^^ suggest `<A, T: Trait>` here
274 Some(span) => (span.shrink_to_hi(), format!(", {}", type_param)),
276 // `fn foo(t: impl Trait)`
277 // ^ suggest `where <T as Trait>::A: Bound`
278 predicate_constraint(generics, pred),
280 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
282 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
283 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
284 // `fn foo(t: impl Trait<A: Bound>)` instead.
285 err.multipart_suggestion(
286 "introduce a type parameter with a trait bound instead of using `impl Trait`",
288 Applicability::MaybeIncorrect,
291 // Trivial case: `T` needs an extra bound: `T: Bound`.
292 let (sp, suggestion) = match (
297 !matches!(p.kind, hir::GenericParamKind::Type { synthetic: Some(_), .. })
302 (_, None) => predicate_constraint(
304 trait_ref.without_const().to_predicate(tcx).to_string(),
306 (None, Some((ident, []))) => (
307 ident.span.shrink_to_hi(),
308 format!(": {}", trait_ref.print_only_trait_path().to_string()),
310 (_, Some((_, [.., bounds]))) => (
311 bounds.span().shrink_to_hi(),
312 format!(" + {}", trait_ref.print_only_trait_path().to_string()),
314 (Some(_), Some((_, []))) => (
315 generics.span.shrink_to_hi(),
316 format!(": {}", trait_ref.print_only_trait_path().to_string()),
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>,
499 // It only make sense when suggesting dereferences for arguments
503 let param_env = obligation.param_env;
504 let body_id = obligation.cause.body_id;
505 let span = obligation.cause.span;
506 let real_trait_ref = match &obligation.cause.code {
507 ObligationCauseCode::ImplDerivedObligation(cause)
508 | ObligationCauseCode::DerivedObligation(cause)
509 | ObligationCauseCode::BuiltinDerivedObligation(cause) => cause.parent_trait_ref,
512 let real_ty = match real_trait_ref.self_ty().no_bound_vars() {
517 if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
518 let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
519 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
521 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
523 self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_ref, ty);
524 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
527 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
528 // Don't care about `&mut` because `DerefMut` is used less
529 // often and user will not expect autoderef happens.
530 if src.starts_with('&') && !src.starts_with("&mut ") {
531 let derefs = "*".repeat(steps);
534 "consider adding dereference here",
535 format!("&{}{}", derefs, &src[1..]),
536 Applicability::MachineApplicable,
545 /// Given a closure's `DefId`, return the given name of the closure.
547 /// This doesn't account for reassignments, but it's only used for suggestions.
551 err: &mut DiagnosticBuilder<'_>,
553 ) -> Option<String> {
555 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
556 // Get the local name of this closure. This can be inaccurate because
557 // of the possibility of reassignment, but this should be good enough.
559 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
560 Some(format!("{}", name))
569 let hir = self.tcx.hir();
570 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
571 let parent_node = hir.get_parent_node(hir_id);
572 match hir.find(parent_node) {
573 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
574 get_name(err, &local.pat.kind)
576 // Different to previous arm because one is `&hir::Local` and the other
577 // is `P<hir::Local>`.
578 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
583 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
584 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
585 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
588 obligation: &PredicateObligation<'tcx>,
589 err: &mut DiagnosticBuilder<'_>,
590 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
593 let self_ty = match trait_ref.self_ty().no_bound_vars() {
598 let (def_id, output_ty, callable) = match *self_ty.kind() {
599 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
600 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
603 let msg = format!("use parentheses to call the {}", callable);
605 // `mk_trait_obligation_with_new_self_ty` only works for types with no escaping bound
606 // variables, so bail out if we have any.
607 let output_ty = match output_ty.no_bound_vars() {
613 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_ref, output_ty);
615 match self.evaluate_obligation(&new_obligation) {
617 EvaluationResult::EvaluatedToOk
618 | EvaluationResult::EvaluatedToOkModuloRegions
619 | EvaluationResult::EvaluatedToAmbig,
623 let hir = self.tcx.hir();
624 // Get the name of the callable and the arguments to be used in the suggestion.
625 let (snippet, sugg) = match hir.get_if_local(def_id) {
626 Some(hir::Node::Expr(hir::Expr {
627 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
630 err.span_label(*span, "consider calling this closure");
631 let name = match self.get_closure_name(def_id, err, &msg) {
635 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
636 let sugg = format!("({})", args);
637 (format!("{}{}", name, sugg), sugg)
639 Some(hir::Node::Item(hir::Item {
641 kind: hir::ItemKind::Fn(.., body_id),
644 err.span_label(ident.span, "consider calling this function");
645 let body = hir.body(*body_id);
649 .map(|arg| match &arg.pat.kind {
650 hir::PatKind::Binding(_, _, ident, None)
651 // FIXME: provide a better suggestion when encountering `SelfLower`, it
652 // should suggest a method call.
653 if ident.name != kw::SelfLower => ident.to_string(),
654 _ => "_".to_string(),
658 let sugg = format!("({})", args);
659 (format!("{}{}", ident, sugg), sugg)
664 // When the obligation error has been ensured to have been caused by
665 // an argument, the `obligation.cause.span` points at the expression
666 // of the argument, so we can provide a suggestion. This is signaled
667 // by `points_at_arg`. Otherwise, we give a more general note.
668 err.span_suggestion_verbose(
669 obligation.cause.span.shrink_to_hi(),
672 Applicability::HasPlaceholders,
675 err.help(&format!("{}: `{}`", msg, snippet));
679 fn suggest_add_reference_to_arg(
681 obligation: &PredicateObligation<'tcx>,
682 err: &mut DiagnosticBuilder<'_>,
683 trait_ref: &ty::Binder<'tcx, ty::TraitRef<'tcx>>,
685 has_custom_message: bool,
691 // List of traits for which it would be nonsensical to suggest borrowing.
692 // For instance, immutable references are always Copy, so suggesting to
693 // borrow would always succeed, but it's probably not what the user wanted.
694 let mut never_suggest_borrow: Vec<_> =
695 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
697 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
700 never_suggest_borrow.push(self.tcx.get_diagnostic_item(sym::send_trait).unwrap());
702 let span = obligation.cause.span;
703 let param_env = obligation.param_env;
704 let trait_ref = trait_ref.skip_binder();
706 let found_ty = trait_ref.self_ty();
707 let found_ty_str = found_ty.to_string();
708 let imm_borrowed_found_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, found_ty);
709 let imm_substs = self.tcx.mk_substs_trait(imm_borrowed_found_ty, &[]);
710 let mut_borrowed_found_ty = self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, found_ty);
711 let mut_substs = self.tcx.mk_substs_trait(mut_borrowed_found_ty, &[]);
713 // Try to apply the original trait binding obligation by borrowing.
714 let mut try_borrowing = |new_trait_ref: ty::TraitRef<'tcx>,
715 expected_trait_ref: ty::TraitRef<'tcx>,
719 if blacklist.contains(&expected_trait_ref.def_id) {
723 let new_obligation = Obligation::new(
724 ObligationCause::dummy(),
726 new_trait_ref.without_const().to_predicate(self.tcx),
729 if self.predicate_must_hold_modulo_regions(&new_obligation) {
730 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
731 // We have a very specific type of error, where just borrowing this argument
732 // might solve the problem. In cases like this, the important part is the
733 // original type obligation, not the last one that failed, which is arbitrary.
734 // Because of this, we modify the error to refer to the original obligation and
735 // return early in the caller.
738 "the trait bound `{}: {}` is not satisfied",
740 expected_trait_ref.print_only_trait_path(),
742 if has_custom_message {
745 err.message = vec![(msg, Style::NoStyle)];
747 if snippet.starts_with('&') {
748 // This is already a literal borrow and the obligation is failing
749 // somewhere else in the obligation chain. Do not suggest non-sense.
755 "expected an implementor of trait `{}`",
756 expected_trait_ref.print_only_trait_path(),
760 // This if is to prevent a special edge-case
761 if !span.from_expansion() {
762 // We don't want a borrowing suggestion on the fields in structs,
765 // the_foos: Vec<Foo>
772 "consider{} borrowing here",
773 if mtbl { " mutably" } else { "" }
775 format!("&{}{}", if mtbl { "mut " } else { "" }, snippet),
776 Applicability::MaybeIncorrect,
785 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
786 let expected_trait_ref = obligation.parent_trait_ref.skip_binder();
787 let new_imm_trait_ref =
788 ty::TraitRef::new(obligation.parent_trait_ref.def_id(), imm_substs);
789 let new_mut_trait_ref =
790 ty::TraitRef::new(obligation.parent_trait_ref.def_id(), mut_substs);
791 if try_borrowing(new_imm_trait_ref, expected_trait_ref, false, &[]) {
794 return try_borrowing(new_mut_trait_ref, expected_trait_ref, true, &[]);
796 } else if let ObligationCauseCode::BindingObligation(_, _)
797 | ObligationCauseCode::ItemObligation(_) = &obligation.cause.code
800 ty::TraitRef::new(trait_ref.def_id, imm_substs),
803 &never_suggest_borrow[..],
807 return try_borrowing(
808 ty::TraitRef::new(trait_ref.def_id, mut_substs),
811 &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 /// Check if the trait bound is implemented for a different mutability and note it in the
884 fn suggest_change_mut(
886 obligation: &PredicateObligation<'tcx>,
887 err: &mut DiagnosticBuilder<'_>,
888 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
891 let span = obligation.cause.span;
892 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
894 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
895 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
896 // Do not suggest removal of borrow from type arguments.
899 let trait_ref = self.resolve_vars_if_possible(trait_ref);
900 if trait_ref.has_infer_types_or_consts() {
901 // Do not ICE while trying to find if a reborrow would succeed on a trait with
902 // unresolved bindings.
906 if let ty::Ref(region, t_type, mutability) = *trait_ref.skip_binder().self_ty().kind() {
907 if region.is_late_bound() || t_type.has_escaping_bound_vars() {
908 // Avoid debug assertion in `mk_obligation_for_def_id`.
910 // If the self type has escaping bound vars then it's not
911 // going to be the type of an expression, so the suggestion
912 // probably won't apply anyway.
916 let suggested_ty = match mutability {
917 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
918 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
921 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
922 obligation.param_env,
926 let suggested_ty_would_satisfy_obligation = self
927 .evaluate_obligation_no_overflow(&new_obligation)
928 .must_apply_modulo_regions();
929 if suggested_ty_would_satisfy_obligation {
934 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
935 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
936 err.span_suggestion_verbose(
938 "consider changing this borrow's mutability",
940 Applicability::MachineApplicable,
944 "`{}` is implemented for `{:?}`, but not for `{:?}`",
945 trait_ref.print_only_trait_path(),
947 trait_ref.skip_binder().self_ty(),
955 fn suggest_semicolon_removal(
957 obligation: &PredicateObligation<'tcx>,
958 err: &mut DiagnosticBuilder<'_>,
960 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
963 |ty: ty::Binder<'tcx, Ty<'_>>| *ty.skip_binder().kind() == ty::Tuple(ty::List::empty());
965 let hir = self.tcx.hir();
966 let parent_node = hir.get_parent_node(obligation.cause.body_id);
967 let node = hir.find(parent_node);
968 if let Some(hir::Node::Item(hir::Item {
969 kind: hir::ItemKind::Fn(sig, _, body_id), ..
972 let body = hir.body(*body_id);
973 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
974 if sig.decl.output.span().overlaps(span)
975 && blk.expr.is_none()
976 && is_empty_tuple(trait_ref.self_ty())
978 // FIXME(estebank): When encountering a method with a trait
979 // bound not satisfied in the return type with a body that has
980 // no return, suggest removal of semicolon on last statement.
981 // Once that is added, close #54771.
982 if let Some(ref stmt) = blk.stmts.last() {
983 if let hir::StmtKind::Semi(_) = stmt.kind {
984 let sp = self.tcx.sess.source_map().end_point(stmt.span);
985 err.span_label(sp, "consider removing this semicolon");
993 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
994 let hir = self.tcx.hir();
995 let parent_node = hir.get_parent_node(obligation.cause.body_id);
996 let sig = match hir.find(parent_node) {
997 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) => sig,
1001 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1004 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1005 /// applicable and signal that the error has been expanded appropriately and needs to be
1007 fn suggest_impl_trait(
1009 err: &mut DiagnosticBuilder<'_>,
1011 obligation: &PredicateObligation<'tcx>,
1012 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
1014 match obligation.cause.code.peel_derives() {
1015 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1016 ObligationCauseCode::SizedReturnType => {}
1020 let hir = self.tcx.hir();
1021 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1022 let node = hir.find(parent_node);
1023 let (sig, body_id) = if let Some(hir::Node::Item(hir::Item {
1024 kind: hir::ItemKind::Fn(sig, _, body_id),
1032 let body = hir.body(*body_id);
1033 let trait_ref = self.resolve_vars_if_possible(trait_ref);
1034 let ty = trait_ref.skip_binder().self_ty();
1035 let is_object_safe = match ty.kind() {
1036 ty::Dynamic(predicates, _) => {
1037 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1040 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1042 // We only want to suggest `impl Trait` to `dyn Trait`s.
1043 // For example, `fn foo() -> str` needs to be filtered out.
1047 let ret_ty = if let hir::FnRetTy::Return(ret_ty) = sig.decl.output {
1053 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1054 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1055 // Recursively look for `TraitObject` types and if there's only one, use that span to
1056 // suggest `impl Trait`.
1058 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1059 // otherwise suggest using `Box<dyn Trait>` or an enum.
1060 let mut visitor = ReturnsVisitor::default();
1061 visitor.visit_body(&body);
1063 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1065 let mut ret_types = visitor
1068 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1069 .map(|ty| self.resolve_vars_if_possible(ty));
1070 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1072 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1074 let ty = self.resolve_vars_if_possible(ty);
1076 !matches!(ty.kind(), ty::Error(_))
1077 && last_ty.map_or(true, |last_ty| {
1078 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1079 // *after* in the dependency graph.
1080 match (ty.kind(), last_ty.kind()) {
1081 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1082 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1083 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1085 Infer(InferTy::FreshFloatTy(_)),
1086 Infer(InferTy::FreshFloatTy(_)),
1091 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1094 let all_returns_conform_to_trait =
1095 if let Some(ty_ret_ty) = typeck_results.node_type_opt(ret_ty.hir_id) {
1096 match ty_ret_ty.kind() {
1097 ty::Dynamic(predicates, _) => {
1098 let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
1099 let param_env = ty::ParamEnv::empty();
1101 || ret_types.all(|returned_ty| {
1102 predicates.iter().all(|predicate| {
1103 let pred = predicate.with_self_ty(self.tcx, returned_ty);
1104 let obl = Obligation::new(cause.clone(), param_env, pred);
1105 self.predicate_may_hold(&obl)
1115 let sm = self.tcx.sess.source_map();
1116 let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
1117 // Verify that we're dealing with a return `dyn Trait`
1118 ret_ty.span.overlaps(span),
1120 sm.span_to_snippet(ret_ty.span),
1121 // If any of the return types does not conform to the trait, then we can't
1122 // suggest `impl Trait` nor trait objects: it is a type mismatch error.
1123 all_returns_conform_to_trait,
1129 err.code(error_code!(E0746));
1130 err.set_primary_message("return type cannot have an unboxed trait object");
1131 err.children.clear();
1132 let impl_trait_msg = "for information on `impl Trait`, see \
1133 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1134 #returning-types-that-implement-traits>";
1135 let trait_obj_msg = "for information on trait objects, see \
1136 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1137 #using-trait-objects-that-allow-for-values-of-different-types>";
1138 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1139 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet[..] };
1140 if only_never_return {
1141 // No return paths, probably using `panic!()` or similar.
1142 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1143 suggest_trait_object_return_type_alternatives(
1149 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1150 // Suggest `-> impl Trait`.
1151 err.span_suggestion(
1154 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1155 which implements `{1}`",
1158 format!("impl {}", trait_obj),
1159 Applicability::MachineApplicable,
1161 err.note(impl_trait_msg);
1164 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1165 // Get all the return values and collect their span and suggestion.
1166 if let Some(mut suggestions) = visitor
1170 let snip = sm.span_to_snippet(expr.span).ok()?;
1171 Some((expr.span, format!("Box::new({})", snip)))
1173 .collect::<Option<Vec<_>>>()
1175 // Add the suggestion for the return type.
1176 suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
1177 err.multipart_suggestion(
1178 "return a boxed trait object instead",
1180 Applicability::MaybeIncorrect,
1184 // This is currently not possible to trigger because E0038 takes precedence, but
1185 // leave it in for completeness in case anything changes in an earlier stage.
1187 "if trait `{}` were object-safe, you could return a trait object",
1191 err.note(trait_obj_msg);
1193 "if all the returned values were of the same type you could use `impl {}` as the \
1197 err.note(impl_trait_msg);
1198 err.note("you can create a new `enum` with a variant for each returned type");
1203 fn point_at_returns_when_relevant(
1205 err: &mut DiagnosticBuilder<'_>,
1206 obligation: &PredicateObligation<'tcx>,
1208 match obligation.cause.code.peel_derives() {
1209 ObligationCauseCode::SizedReturnType => {}
1213 let hir = self.tcx.hir();
1214 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1215 let node = hir.find(parent_node);
1216 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1219 let body = hir.body(*body_id);
1220 // Point at all the `return`s in the function as they have failed trait bounds.
1221 let mut visitor = ReturnsVisitor::default();
1222 visitor.visit_body(&body);
1223 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1224 for expr in &visitor.returns {
1225 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1226 let ty = self.resolve_vars_if_possible(returned_ty);
1227 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1233 fn report_closure_arg_mismatch(
1236 found_span: Option<Span>,
1237 expected_ref: ty::PolyTraitRef<'tcx>,
1238 found: ty::PolyTraitRef<'tcx>,
1239 ) -> DiagnosticBuilder<'tcx> {
1240 crate fn build_fn_sig_string<'tcx>(
1242 trait_ref: ty::PolyTraitRef<'tcx>,
1244 let inputs = trait_ref.skip_binder().substs.type_at(1);
1245 let sig = if let ty::Tuple(inputs) = inputs.kind() {
1247 inputs.iter().map(|k| k.expect_ty()),
1248 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1250 hir::Unsafety::Normal,
1255 std::iter::once(inputs),
1256 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1258 hir::Unsafety::Normal,
1262 trait_ref.rebind(sig).to_string()
1265 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1266 let mut err = struct_span_err!(
1270 "type mismatch in {} arguments",
1271 if argument_is_closure { "closure" } else { "function" }
1274 let found_str = format!("expected signature of `{}`", build_fn_sig_string(self.tcx, found));
1275 err.span_label(span, found_str);
1277 let found_span = found_span.unwrap_or(span);
1279 format!("found signature of `{}`", build_fn_sig_string(self.tcx, expected_ref));
1280 err.span_label(found_span, expected_str);
1285 fn suggest_fully_qualified_path(
1287 err: &mut DiagnosticBuilder<'_>,
1292 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1293 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1295 "{}s cannot be accessed directly on a `trait`, they can only be \
1296 accessed through a specific `impl`",
1297 assoc_item.kind.as_def_kind().descr(def_id)
1299 err.span_suggestion(
1301 "use the fully qualified path to an implementation",
1302 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1303 Applicability::HasPlaceholders,
1309 /// Adds an async-await specific note to the diagnostic when the future does not implement
1310 /// an auto trait because of a captured type.
1313 /// note: future does not implement `Qux` as this value is used across an await
1314 /// --> $DIR/issue-64130-3-other.rs:17:5
1316 /// LL | let x = Foo;
1317 /// | - has type `Foo`
1318 /// LL | baz().await;
1319 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1321 /// | - `x` is later dropped here
1324 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1325 /// is "replaced" with a different message and a more specific error.
1328 /// error: future cannot be sent between threads safely
1329 /// --> $DIR/issue-64130-2-send.rs:21:5
1331 /// LL | fn is_send<T: Send>(t: T) { }
1332 /// | ---- required by this bound in `is_send`
1334 /// LL | is_send(bar());
1335 /// | ^^^^^^^ future returned by `bar` is not send
1337 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1338 /// implemented for `Foo`
1339 /// note: future is not send as this value is used across an await
1340 /// --> $DIR/issue-64130-2-send.rs:15:5
1342 /// LL | let x = Foo;
1343 /// | - has type `Foo`
1344 /// LL | baz().await;
1345 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1347 /// | - `x` is later dropped here
1350 /// Returns `true` if an async-await specific note was added to the diagnostic.
1351 fn maybe_note_obligation_cause_for_async_await(
1353 err: &mut DiagnosticBuilder<'_>,
1354 obligation: &PredicateObligation<'tcx>,
1357 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1358 obligation.cause.span={:?}",
1359 obligation.predicate, obligation.cause.span
1361 let hir = self.tcx.hir();
1363 // Attempt to detect an async-await error by looking at the obligation causes, looking
1364 // for a generator to be present.
1366 // When a future does not implement a trait because of a captured type in one of the
1367 // generators somewhere in the call stack, then the result is a chain of obligations.
1369 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
1370 // future is passed as an argument to a function C which requires a `Send` type, then the
1371 // chain looks something like this:
1373 // - `BuiltinDerivedObligation` with a generator witness (B)
1374 // - `BuiltinDerivedObligation` with a generator (B)
1375 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1376 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1377 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1378 // - `BuiltinDerivedObligation` with a generator witness (A)
1379 // - `BuiltinDerivedObligation` with a generator (A)
1380 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1381 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1382 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1383 // - `BindingObligation` with `impl_send (Send requirement)
1385 // The first obligation in the chain is the most useful and has the generator that captured
1386 // the type. The last generator (`outer_generator` below) has information about where the
1387 // bound was introduced. At least one generator should be present for this diagnostic to be
1389 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1390 ty::PredicateKind::Trait(p, _) => (Some(p.trait_ref), Some(p.self_ty())),
1393 let mut generator = None;
1394 let mut outer_generator = None;
1395 let mut next_code = Some(&obligation.cause.code);
1397 let mut seen_upvar_tys_infer_tuple = false;
1399 while let Some(code) = next_code {
1400 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1402 ObligationCauseCode::DerivedObligation(derived_obligation)
1403 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1404 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1405 let ty = derived_obligation.parent_trait_ref.skip_binder().self_ty();
1407 "maybe_note_obligation_cause_for_async_await: \
1408 parent_trait_ref={:?} self_ty.kind={:?}",
1409 derived_obligation.parent_trait_ref,
1414 ty::Generator(did, ..) => {
1415 generator = generator.or(Some(did));
1416 outer_generator = Some(did);
1418 ty::GeneratorWitness(..) => {}
1419 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1420 // By introducing a tuple of upvar types into the chain of obligations
1421 // of a generator, the first non-generator item is now the tuple itself,
1422 // we shall ignore this.
1424 seen_upvar_tys_infer_tuple = true;
1426 _ if generator.is_none() => {
1427 trait_ref = Some(derived_obligation.parent_trait_ref.skip_binder());
1428 target_ty = Some(ty);
1433 next_code = Some(derived_obligation.parent_code.as_ref());
1439 // Only continue if a generator was found.
1441 "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
1443 generator, trait_ref, target_ty
1445 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1446 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1447 (generator_did, trait_ref, target_ty)
1452 let span = self.tcx.def_span(generator_did);
1454 // Do not ICE on closure typeck (#66868).
1455 if !generator_did.is_local() {
1459 // Get the typeck results from the infcx if the generator is the function we are
1460 // currently type-checking; otherwise, get them by performing a query.
1461 // This is needed to avoid cycles.
1462 let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1463 let generator_did_root = self.tcx.closure_base_def_id(generator_did);
1465 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1466 generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
1469 in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1472 let query_typeck_results;
1473 let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
1474 Some(t) if t.hir_owner.to_def_id() == generator_did_root => t,
1476 query_typeck_results = self.tcx.typeck(generator_did.expect_local());
1477 &query_typeck_results
1481 let generator_body = generator_did
1483 .map(|def_id| hir.local_def_id_to_hir_id(def_id))
1484 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1485 .map(|body_id| hir.body(body_id));
1486 let mut visitor = AwaitsVisitor::default();
1487 if let Some(body) = generator_body {
1488 visitor.visit_body(body);
1490 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1492 // Look for a type inside the generator interior that matches the target type to get
1494 let target_ty_erased = self.tcx.erase_regions(target_ty);
1495 let ty_matches = |ty| -> bool {
1496 // Careful: the regions for types that appear in the
1497 // generator interior are not generally known, so we
1498 // want to erase them when comparing (and anyway,
1499 // `Send` and other bounds are generally unaffected by
1500 // the choice of region). When erasing regions, we
1501 // also have to erase late-bound regions. This is
1502 // because the types that appear in the generator
1503 // interior generally contain "bound regions" to
1504 // represent regions that are part of the suspended
1505 // generator frame. Bound regions are preserved by
1506 // `erase_regions` and so we must also call
1507 // `erase_late_bound_regions`.
1508 let ty_erased = self.tcx.erase_late_bound_regions(ty);
1509 let ty_erased = self.tcx.erase_regions(ty_erased);
1510 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1512 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1513 target_ty_erased={:?} eq={:?}",
1514 ty_erased, target_ty_erased, eq
1519 let mut interior_or_upvar_span = None;
1520 let mut interior_extra_info = None;
1522 if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) {
1523 interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| {
1524 let upvar_ty = typeck_results.node_type(*upvar_id);
1525 let upvar_ty = self.resolve_vars_if_possible(upvar_ty);
1526 if ty_matches(ty::Binder::dummy(upvar_ty)) {
1527 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
1534 // The generator interior types share the same binders
1535 if let Some(cause) =
1536 typeck_results.generator_interior_types.as_ref().skip_binder().iter().find(
1537 |ty::GeneratorInteriorTypeCause { ty, .. }| {
1538 ty_matches(typeck_results.generator_interior_types.rebind(ty))
1542 // Check to see if any awaited expressions have the target type.
1543 let from_awaited_ty = visitor
1546 .map(|id| hir.expect_expr(id))
1547 .find(|await_expr| {
1548 let ty = typeck_results.expr_ty_adjusted(&await_expr);
1550 "maybe_note_obligation_cause_for_async_await: await_expr={:?}",
1553 ty_matches(ty::Binder::dummy(ty))
1555 .map(|expr| expr.span);
1556 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } = cause;
1558 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1559 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1563 "maybe_note_obligation_cause_for_async_await: interior_or_upvar={:?} \
1564 generator_interior_types={:?}",
1565 interior_or_upvar_span, typeck_results.generator_interior_types
1567 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1568 self.note_obligation_cause_for_async_await(
1570 interior_or_upvar_span,
1571 interior_extra_info,
1586 /// Unconditionally adds the diagnostic note described in
1587 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1588 fn note_obligation_cause_for_async_await(
1590 err: &mut DiagnosticBuilder<'_>,
1591 interior_or_upvar_span: GeneratorInteriorOrUpvar,
1592 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1593 inner_generator_body: Option<&hir::Body<'tcx>>,
1594 outer_generator: Option<DefId>,
1595 trait_ref: ty::TraitRef<'tcx>,
1596 target_ty: Ty<'tcx>,
1597 typeck_results: &ty::TypeckResults<'tcx>,
1598 obligation: &PredicateObligation<'tcx>,
1599 next_code: Option<&ObligationCauseCode<'tcx>>,
1601 let source_map = self.tcx.sess.source_map();
1603 let is_async = inner_generator_body
1604 .and_then(|body| body.generator_kind())
1605 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1607 let (await_or_yield, an_await_or_yield) =
1608 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1609 let future_or_generator = if is_async { "future" } else { "generator" };
1611 // Special case the primary error message when send or sync is the trait that was
1613 let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
1614 let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
1615 let hir = self.tcx.hir();
1616 let trait_explanation = if is_send || is_sync {
1617 let (trait_name, trait_verb) =
1618 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1621 err.set_primary_message(format!(
1622 "{} cannot be {} between threads safely",
1623 future_or_generator, trait_verb
1626 let original_span = err.span.primary_span().unwrap();
1627 let mut span = MultiSpan::from_span(original_span);
1629 let message = outer_generator
1630 .and_then(|generator_did| {
1631 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1632 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1633 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1635 .parent(generator_did)
1636 .and_then(|parent_did| parent_did.as_local())
1637 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
1638 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1640 format!("future returned by `{}` is not {}", name, trait_name)
1642 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1643 format!("future created by async block is not {}", trait_name)
1645 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1646 format!("future created by async closure is not {}", trait_name)
1650 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1652 span.push_span_label(original_span, message);
1655 format!("is not {}", trait_name)
1657 format!("does not implement `{}`", trait_ref.print_only_trait_path())
1660 let mut explain_yield =
1661 |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
1662 let mut span = MultiSpan::from_span(yield_span);
1663 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1664 // #70935: If snippet contains newlines, display "the value" instead
1665 // so that we do not emit complex diagnostics.
1666 let snippet = &format!("`{}`", snippet);
1667 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
1668 // The multispan can be complex here, like:
1669 // note: future is not `Send` as this value is used across an await
1670 // --> $DIR/issue-70935-complex-spans.rs:13:9
1672 // LL | baz(|| async{
1673 // | __________^___-
1676 // LL | || foo(tx.clone());
1677 // LL | || }).await;
1678 // | || - ^- value is later dropped here
1679 // | ||_________|______|
1680 // | |__________| await occurs here, with value maybe used later
1681 // | has type `closure` which is not `Send`
1683 // So, detect it and separate into some notes, like:
1685 // note: future is not `Send` as this value is used across an await
1686 // --> $DIR/issue-70935-complex-spans.rs:13:9
1688 // LL | / baz(|| async{
1689 // LL | | foo(tx.clone());
1691 // | |________________^ first, await occurs here, with the value maybe used later...
1692 // note: the value is later dropped here
1693 // --> $DIR/issue-70935-complex-spans.rs:15:17
1698 // If available, use the scope span to annotate the drop location.
1699 if let Some(scope_span) = scope_span {
1700 let scope_span = source_map.end_point(scope_span);
1702 yield_span.overlaps(scope_span) || yield_span.overlaps(interior_span);
1704 span.push_span_label(
1707 "first, {} occurs here, with {} maybe used later...",
1708 await_or_yield, snippet
1714 "{} {} as this value is used across {}",
1715 future_or_generator, trait_explanation, an_await_or_yield
1718 if source_map.is_multiline(interior_span) {
1721 &format!("{} is later dropped here", snippet),
1726 "this has type `{}` which {}",
1727 target_ty, trait_explanation
1731 let mut span = MultiSpan::from_span(scope_span);
1732 span.push_span_label(
1734 format!("has type `{}` which {}", target_ty, trait_explanation),
1736 err.span_note(span, &format!("{} is later dropped here", snippet));
1739 span.push_span_label(
1742 "{} occurs here, with {} maybe used later",
1743 await_or_yield, snippet
1746 span.push_span_label(
1748 format!("{} is later dropped here", snippet),
1750 span.push_span_label(
1752 format!("has type `{}` which {}", target_ty, trait_explanation),
1757 "{} {} as this value is used across {}",
1758 future_or_generator, trait_explanation, an_await_or_yield
1763 span.push_span_label(
1766 "{} occurs here, with {} maybe used later",
1767 await_or_yield, snippet
1770 span.push_span_label(
1772 format!("has type `{}` which {}", target_ty, trait_explanation),
1777 "{} {} as this value is used across {}",
1778 future_or_generator, trait_explanation, an_await_or_yield
1784 match interior_or_upvar_span {
1785 GeneratorInteriorOrUpvar::Interior(interior_span) => {
1786 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
1787 if let Some(await_span) = from_awaited_ty {
1788 // The type causing this obligation is one being awaited at await_span.
1789 let mut span = MultiSpan::from_span(await_span);
1790 span.push_span_label(
1793 "await occurs here on type `{}`, which {}",
1794 target_ty, trait_explanation
1800 "future {not_trait} as it awaits another future which {not_trait}",
1801 not_trait = trait_explanation
1805 // Look at the last interior type to get a span for the `.await`.
1807 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1808 typeck_results.generator_interior_types
1810 explain_yield(interior_span, yield_span, scope_span);
1813 if let Some(expr_id) = expr {
1814 let expr = hir.expect_expr(expr_id);
1815 debug!("target_ty evaluated from {:?}", expr);
1817 let parent = hir.get_parent_node(expr_id);
1818 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1819 let parent_span = hir.span(parent);
1820 let parent_did = parent.owner.to_def_id();
1823 // fn foo(&self) -> i32 {}
1826 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1829 let is_region_borrow = typeck_results
1830 .expr_adjustments(expr)
1832 .any(|adj| adj.is_region_borrow());
1835 // struct Foo(*const u8);
1836 // bar(Foo(std::ptr::null())).await;
1837 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1839 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1840 let is_raw_borrow_inside_fn_like_call =
1841 match self.tcx.def_kind(parent_did) {
1842 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
1846 if (typeck_results.is_method_call(e) && is_region_borrow)
1847 || is_raw_borrow_inside_fn_like_call
1851 "consider moving this into a `let` \
1852 binding to create a shorter lived borrow",
1859 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
1860 let mut span = MultiSpan::from_span(upvar_span);
1861 span.push_span_label(
1863 format!("has type `{}` which {}", target_ty, trait_explanation),
1865 err.span_note(span, &format!("captured value {}", trait_explanation));
1869 // Add a note for the item obligation that remains - normally a note pointing to the
1870 // bound that introduced the obligation (e.g. `T: Send`).
1871 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1872 self.note_obligation_cause_code(
1874 &obligation.predicate,
1877 &mut Default::default(),
1881 fn note_obligation_cause_code<T>(
1883 err: &mut DiagnosticBuilder<'_>,
1885 cause_code: &ObligationCauseCode<'tcx>,
1886 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1887 seen_requirements: &mut FxHashSet<DefId>,
1893 ObligationCauseCode::ExprAssignable
1894 | ObligationCauseCode::MatchExpressionArm { .. }
1895 | ObligationCauseCode::Pattern { .. }
1896 | ObligationCauseCode::IfExpression { .. }
1897 | ObligationCauseCode::IfExpressionWithNoElse
1898 | ObligationCauseCode::MainFunctionType
1899 | ObligationCauseCode::StartFunctionType
1900 | ObligationCauseCode::IntrinsicType
1901 | ObligationCauseCode::MethodReceiver
1902 | ObligationCauseCode::ReturnNoExpression
1903 | ObligationCauseCode::UnifyReceiver(..)
1904 | ObligationCauseCode::OpaqueType
1905 | ObligationCauseCode::MiscObligation
1906 | ObligationCauseCode::WellFormed(..) => {}
1907 ObligationCauseCode::SliceOrArrayElem => {
1908 err.note("slice and array elements must have `Sized` type");
1910 ObligationCauseCode::TupleElem => {
1911 err.note("only the last element of a tuple may have a dynamically sized type");
1913 ObligationCauseCode::ProjectionWf(data) => {
1914 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1916 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1918 "required so that reference `{}` does not outlive its referent",
1922 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1924 "required so that the lifetime bound of `{}` for `{}` is satisfied",
1928 ObligationCauseCode::ItemObligation(item_def_id) => {
1929 let item_name = tcx.def_path_str(item_def_id);
1930 let msg = format!("required by `{}`", item_name);
1933 .span_if_local(item_def_id)
1934 .unwrap_or_else(|| tcx.def_span(item_def_id));
1935 let sp = tcx.sess.source_map().guess_head_span(sp);
1936 err.span_note(sp, &msg);
1938 ObligationCauseCode::BindingObligation(item_def_id, span) => {
1939 let item_name = tcx.def_path_str(item_def_id);
1940 let msg = format!("required by this bound in `{}`", item_name);
1941 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1942 let sm = tcx.sess.source_map();
1944 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
1945 (Ok(l), Ok(r)) => l.line == r.line,
1948 if !ident.span.overlaps(span) && !same_line {
1949 err.span_label(ident.span, "required by a bound in this");
1952 if span != DUMMY_SP {
1953 err.span_label(span, &msg);
1956 tcx.def_span(item_def_id),
1957 &format!("required by a bound in `{}`", item_name),
1961 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1963 "required for the cast to the object type `{}`",
1964 self.ty_to_string(object_ty)
1967 ObligationCauseCode::Coercion { source: _, target } => {
1968 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1970 ObligationCauseCode::RepeatVec(is_const_fn) => {
1972 "the `Copy` trait is required because the repeated element will be copied",
1977 "consider creating a new `const` item and initializing it with the result \
1978 of the function call to be used in the repeat position, like \
1979 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
1983 if self.tcx.sess.is_nightly_build() && is_const_fn {
1985 "create an inline `const` block, see RFC #2920 \
1986 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
1990 ObligationCauseCode::VariableType(hir_id) => {
1991 let parent_node = self.tcx.hir().get_parent_node(hir_id);
1992 match self.tcx.hir().find(parent_node) {
1993 Some(Node::Local(hir::Local {
1994 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
1997 // When encountering an assignment of an unsized trait, like
1998 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
1999 // order to use have a slice instead.
2000 err.span_suggestion_verbose(
2001 span.shrink_to_lo(),
2002 "consider borrowing here",
2004 Applicability::MachineApplicable,
2006 err.note("all local variables must have a statically known size");
2008 Some(Node::Param(param)) => {
2009 err.span_suggestion_verbose(
2010 param.ty_span.shrink_to_lo(),
2011 "function arguments must have a statically known size, borrowed types \
2012 always have a known size",
2014 Applicability::MachineApplicable,
2018 err.note("all local variables must have a statically known size");
2021 if !self.tcx.features().unsized_locals {
2022 err.help("unsized locals are gated as an unstable feature");
2025 ObligationCauseCode::SizedArgumentType(sp) => {
2026 if let Some(span) = sp {
2027 err.span_suggestion_verbose(
2028 span.shrink_to_lo(),
2029 "function arguments must have a statically known size, borrowed types \
2030 always have a known size",
2032 Applicability::MachineApplicable,
2035 err.note("all function arguments must have a statically known size");
2037 if tcx.sess.opts.unstable_features.is_nightly_build()
2038 && !self.tcx.features().unsized_fn_params
2040 err.help("unsized fn params are gated as an unstable feature");
2043 ObligationCauseCode::SizedReturnType => {
2044 err.note("the return type of a function must have a statically known size");
2046 ObligationCauseCode::SizedYieldType => {
2047 err.note("the yield type of a generator must have a statically known size");
2049 ObligationCauseCode::AssignmentLhsSized => {
2050 err.note("the left-hand-side of an assignment must have a statically known size");
2052 ObligationCauseCode::TupleInitializerSized => {
2053 err.note("tuples must have a statically known size to be initialized");
2055 ObligationCauseCode::StructInitializerSized => {
2056 err.note("structs must have a statically known size to be initialized");
2058 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2060 AdtKind::Struct => {
2063 "the last field of a packed struct may only have a \
2064 dynamically sized type if it does not need drop to be run",
2068 "only the last field of a struct may have a dynamically sized type",
2073 err.note("no field of a union may have a dynamically sized type");
2076 err.note("no field of an enum variant may have a dynamically sized type");
2079 err.help("change the field's type to have a statically known size");
2080 err.span_suggestion(
2081 span.shrink_to_lo(),
2082 "borrowed types always have a statically known size",
2084 Applicability::MachineApplicable,
2086 err.multipart_suggestion(
2087 "the `Box` type always has a statically known size and allocates its contents \
2090 (span.shrink_to_lo(), "Box<".to_string()),
2091 (span.shrink_to_hi(), ">".to_string()),
2093 Applicability::MachineApplicable,
2096 ObligationCauseCode::ConstSized => {
2097 err.note("constant expressions must have a statically known size");
2099 ObligationCauseCode::InlineAsmSized => {
2100 err.note("all inline asm arguments must have a statically known size");
2102 ObligationCauseCode::ConstPatternStructural => {
2103 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2105 ObligationCauseCode::SharedStatic => {
2106 err.note("shared static variables must have a type that implements `Sync`");
2108 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2109 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2110 let ty = parent_trait_ref.skip_binder().self_ty();
2111 if parent_trait_ref.references_error() {
2116 // If the obligation for a tuple is set directly by a Generator or Closure,
2117 // then the tuple must be the one containing capture types.
2118 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2121 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) =
2124 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2125 let ty = parent_trait_ref.skip_binder().self_ty();
2126 matches!(ty.kind(), ty::Generator(..))
2127 || matches!(ty.kind(), ty::Closure(..))
2133 // Don't print the tuple of capture types
2134 if !is_upvar_tys_infer_tuple {
2135 let msg = format!("required because it appears within the type `{}`", ty);
2137 ty::Adt(def, _) => match self.tcx.opt_item_name(def.did) {
2138 Some(ident) => err.span_note(ident.span, &msg),
2139 None => err.note(&msg),
2141 _ => err.note(&msg),
2145 obligated_types.push(ty);
2147 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2148 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2149 // #74711: avoid a stack overflow
2150 ensure_sufficient_stack(|| {
2151 self.note_obligation_cause_code(
2161 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2162 let mut parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2163 let parent_def_id = parent_trait_ref.def_id();
2165 "required because of the requirements on the impl of `{}` for `{}`",
2166 parent_trait_ref.print_only_trait_path(),
2167 parent_trait_ref.skip_binder().self_ty()
2169 let mut candidates = vec![];
2170 self.tcx.for_each_relevant_impl(
2172 parent_trait_ref.self_ty().skip_binder(),
2173 |impl_def_id| match self.tcx.hir().get_if_local(impl_def_id) {
2174 Some(Node::Item(hir::Item {
2175 kind: hir::ItemKind::Impl(hir::Impl { .. }),
2178 candidates.push(impl_def_id);
2183 match &candidates[..] {
2184 [def_id] => match self.tcx.hir().get_if_local(*def_id) {
2185 Some(Node::Item(hir::Item {
2186 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2189 let mut spans = Vec::with_capacity(2);
2190 if let Some(trait_ref) = of_trait {
2191 spans.push(trait_ref.path.span);
2193 spans.push(self_ty.span);
2194 err.span_note(spans, &msg)
2196 _ => err.note(&msg),
2198 _ => err.note(&msg),
2201 let mut parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2202 let mut data = data;
2204 seen_requirements.insert(parent_def_id);
2205 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2206 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2207 let child_trait_ref = self.resolve_vars_if_possible(child.parent_trait_ref);
2208 let child_def_id = child_trait_ref.def_id();
2209 if seen_requirements.insert(child_def_id) {
2214 parent_predicate = child_trait_ref.without_const().to_predicate(tcx);
2215 parent_trait_ref = child_trait_ref;
2218 err.note(&format!("{} redundant requirements hidden", count));
2220 "required because of the requirements on the impl of `{}` for `{}`",
2221 parent_trait_ref.print_only_trait_path(),
2222 parent_trait_ref.skip_binder().self_ty()
2225 // #74711: avoid a stack overflow
2226 ensure_sufficient_stack(|| {
2227 self.note_obligation_cause_code(
2236 ObligationCauseCode::DerivedObligation(ref data) => {
2237 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2238 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2239 // #74711: avoid a stack overflow
2240 ensure_sufficient_stack(|| {
2241 self.note_obligation_cause_code(
2250 ObligationCauseCode::CompareImplMethodObligation {
2256 "the requirement `{}` appears on the impl method `{}` but not on the \
2257 corresponding trait method",
2258 predicate, item_name,
2262 .opt_item_name(trait_item_def_id)
2264 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2265 let mut assoc_span: MultiSpan = sp.into();
2266 assoc_span.push_span_label(
2268 format!("this trait method doesn't have the requirement `{}`", predicate),
2270 if let Some(ident) = self
2272 .opt_associated_item(trait_item_def_id)
2273 .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2275 assoc_span.push_span_label(ident.span, "in this trait".into());
2277 err.span_note(assoc_span, &msg);
2279 ObligationCauseCode::CompareImplTypeObligation {
2280 item_name, trait_item_def_id, ..
2283 "the requirement `{}` appears on the associated impl type `{}` but not on the \
2284 corresponding associated trait type",
2285 predicate, item_name,
2287 let sp = self.tcx.def_span(trait_item_def_id);
2288 let mut assoc_span: MultiSpan = sp.into();
2289 assoc_span.push_span_label(
2292 "this trait associated type doesn't have the requirement `{}`",
2296 if let Some(ident) = self
2298 .opt_associated_item(trait_item_def_id)
2299 .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2301 assoc_span.push_span_label(ident.span, "in this trait".into());
2303 err.span_note(assoc_span, &msg);
2305 ObligationCauseCode::CompareImplConstObligation => {
2307 "the requirement `{}` appears on the associated impl constant \
2308 but not on the corresponding associated trait constant",
2312 ObligationCauseCode::ReturnType
2313 | ObligationCauseCode::ReturnValue(_)
2314 | ObligationCauseCode::BlockTailExpression(_) => (),
2315 ObligationCauseCode::TrivialBound => {
2316 err.help("see issue #48214");
2317 if tcx.sess.opts.unstable_features.is_nightly_build() {
2318 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2324 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2325 let current_limit = self.tcx.recursion_limit();
2326 let suggested_limit = current_limit * 2;
2328 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
2330 self.tcx.crate_name(LOCAL_CRATE),
2334 fn suggest_await_before_try(
2336 err: &mut DiagnosticBuilder<'_>,
2337 obligation: &PredicateObligation<'tcx>,
2338 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2342 "suggest_await_before_try: obligation={:?}, span={:?}, trait_ref={:?}, trait_ref_self_ty={:?}",
2348 let body_hir_id = obligation.cause.body_id;
2349 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2351 if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
2352 let body = self.tcx.hir().body(body_id);
2353 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2354 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2356 let self_ty = self.resolve_vars_if_possible(trait_ref.self_ty());
2358 // Do not check on infer_types to avoid panic in evaluate_obligation.
2359 if self_ty.has_infer_types() {
2362 let self_ty = self.tcx.erase_regions(self_ty);
2364 let impls_future = self.type_implements_trait(
2366 self_ty.skip_binder(),
2368 obligation.param_env,
2371 let item_def_id = self
2373 .associated_items(future_trait)
2374 .in_definition_order()
2378 // `<T as Future>::Output`
2379 let projection_ty = ty::ProjectionTy {
2381 substs: self.tcx.mk_substs_trait(
2382 trait_ref.self_ty().skip_binder(),
2383 self.fresh_substs_for_item(span, item_def_id),
2389 let mut selcx = SelectionContext::new(self);
2391 let mut obligations = vec![];
2392 let normalized_ty = normalize_projection_type(
2394 obligation.param_env,
2396 obligation.cause.clone(),
2402 "suggest_await_before_try: normalized_projection_type {:?}",
2403 self.resolve_vars_if_possible(normalized_ty)
2405 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2406 obligation.param_env,
2410 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2411 if self.predicate_may_hold(&try_obligation)
2412 && impls_future.must_apply_modulo_regions()
2414 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2415 if snippet.ends_with('?') {
2416 err.span_suggestion_verbose(
2417 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2418 "consider `await`ing on the `Future`",
2419 ".await".to_string(),
2420 Applicability::MaybeIncorrect,
2430 /// Collect all the returned expressions within the input expression.
2431 /// Used to point at the return spans when we want to suggest some change to them.
2433 pub struct ReturnsVisitor<'v> {
2434 pub returns: Vec<&'v hir::Expr<'v>>,
2435 in_block_tail: bool,
2438 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2439 type Map = hir::intravisit::ErasedMap<'v>;
2441 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2442 hir::intravisit::NestedVisitorMap::None
2445 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2446 // Visit every expression to detect `return` paths, either through the function's tail
2447 // expression or `return` statements. We walk all nodes to find `return` statements, but
2448 // we only care about tail expressions when `in_block_tail` is `true`, which means that
2449 // they're in the return path of the function body.
2451 hir::ExprKind::Ret(Some(ex)) => {
2452 self.returns.push(ex);
2454 hir::ExprKind::Block(block, _) if self.in_block_tail => {
2455 self.in_block_tail = false;
2456 for stmt in block.stmts {
2457 hir::intravisit::walk_stmt(self, stmt);
2459 self.in_block_tail = true;
2460 if let Some(expr) = block.expr {
2461 self.visit_expr(expr);
2464 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
2465 self.visit_expr(then);
2466 if let Some(el) = else_opt {
2467 self.visit_expr(el);
2470 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2472 self.visit_expr(arm.body);
2475 // We need to walk to find `return`s in the entire body.
2476 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2477 _ => self.returns.push(ex),
2481 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2482 assert!(!self.in_block_tail);
2483 if body.generator_kind().is_none() {
2484 if let hir::ExprKind::Block(block, None) = body.value.kind {
2485 if block.expr.is_some() {
2486 self.in_block_tail = true;
2490 hir::intravisit::walk_body(self, body);
2494 /// Collect all the awaited expressions within the input expression.
2496 struct AwaitsVisitor {
2497 awaits: Vec<hir::HirId>,
2500 impl<'v> Visitor<'v> for AwaitsVisitor {
2501 type Map = hir::intravisit::ErasedMap<'v>;
2503 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2504 hir::intravisit::NestedVisitorMap::None
2507 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2508 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2509 self.awaits.push(id)
2511 hir::intravisit::walk_expr(self, ex)
2515 pub trait NextTypeParamName {
2516 fn next_type_param_name(&self, name: Option<&str>) -> String;
2519 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2520 fn next_type_param_name(&self, name: Option<&str>) -> String {
2521 // This is the list of possible parameter names that we might suggest.
2522 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2523 let name = name.as_deref();
2524 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2525 let used_names = self
2527 .filter_map(|p| match p.name {
2528 hir::ParamName::Plain(ident) => Some(ident.name),
2531 .collect::<Vec<_>>();
2535 .find(|n| !used_names.contains(&Symbol::intern(n)))
2536 .unwrap_or(&"ParamName")
2541 fn suggest_trait_object_return_type_alternatives(
2542 err: &mut DiagnosticBuilder<'_>,
2545 is_object_safe: bool,
2547 err.span_suggestion(
2549 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2552 Applicability::MaybeIncorrect,
2554 err.span_suggestion(
2557 "use `impl {}` as the return type if all return paths have the same type but you \
2558 want to expose only the trait in the signature",
2561 format!("impl {}", trait_obj),
2562 Applicability::MaybeIncorrect,
2565 err.span_suggestion(
2568 "use a boxed trait object if all return paths implement trait `{}`",
2571 format!("Box<dyn {}>", trait_obj),
2572 Applicability::MaybeIncorrect,