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, WithConstness,
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_change_mut(
94 obligation: &PredicateObligation<'tcx>,
95 err: &mut DiagnosticBuilder<'_>,
96 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: Option<&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_for_suggestions().unwrap_or(p.span.shrink_to_hi()))
266 .filter(|&span| generics.span.contains(span) && span.can_be_used_for_suggestions())
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, 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 (
296 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
299 (_, None) => predicate_constraint(
301 trait_ref.without_const().to_predicate(tcx).to_string(),
303 (None, Some((ident, []))) => {
304 (ident.span.shrink_to_hi(), format!(": {}", trait_ref.print_only_trait_path()))
306 (_, Some((_, [.., bounds]))) => {
307 (bounds.span().shrink_to_hi(), format!(" + {}", trait_ref.print_only_trait_path()))
309 (Some(_), Some((_, []))) => {
310 (generics.span.shrink_to_hi(), format!(": {}", trait_ref.print_only_trait_path()))
314 err.span_suggestion_verbose(
316 &format!("consider further restricting {}", msg),
318 Applicability::MachineApplicable,
323 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
324 fn suggest_restricting_param_bound(
326 mut err: &mut DiagnosticBuilder<'_>,
327 trait_ref: ty::PolyTraitRef<'tcx>,
330 let self_ty = trait_ref.skip_binder().self_ty();
331 let (param_ty, projection) = match self_ty.kind() {
332 ty::Param(_) => (true, None),
333 ty::Projection(projection) => (false, Some(projection)),
337 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
338 // don't suggest `T: Sized + ?Sized`.
339 let mut hir_id = body_id;
340 while let Some(node) = self.tcx.hir().find(hir_id) {
342 hir::Node::Item(hir::Item {
344 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
346 }) if self_ty == self.tcx.types.self_param => {
348 // Restricting `Self` for a single method.
357 Some((ident, bounds)),
362 hir::Node::TraitItem(hir::TraitItem {
364 kind: hir::TraitItemKind::Fn(..),
366 }) if self_ty == self.tcx.types.self_param => {
368 // Restricting `Self` for a single method.
370 self.tcx, &generics, "`Self`", err, None, projection, trait_ref, None,
375 hir::Node::TraitItem(hir::TraitItem {
377 kind: hir::TraitItemKind::Fn(fn_sig, ..),
380 | hir::Node::ImplItem(hir::ImplItem {
382 kind: hir::ImplItemKind::Fn(fn_sig, ..),
385 | hir::Node::Item(hir::Item {
386 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
387 }) if projection.is_some() => {
388 // Missing restriction on associated type of type parameter (unmet projection).
392 "the associated type",
401 hir::Node::Item(hir::Item {
403 hir::ItemKind::Trait(_, _, generics, _, _)
404 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
406 }) if projection.is_some() => {
407 // Missing restriction on associated type of type parameter (unmet projection).
411 "the associated type",
421 hir::Node::Item(hir::Item {
423 hir::ItemKind::Struct(_, generics)
424 | hir::ItemKind::Enum(_, generics)
425 | hir::ItemKind::Union(_, generics)
426 | hir::ItemKind::Trait(_, _, generics, ..)
427 | hir::ItemKind::Impl(hir::Impl { generics, .. })
428 | hir::ItemKind::Fn(_, generics, _)
429 | hir::ItemKind::TyAlias(_, generics)
430 | hir::ItemKind::TraitAlias(generics, _)
431 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
434 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
435 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
438 // Missing generic type parameter bound.
439 let param_name = self_ty.to_string();
441 with_no_trimmed_paths(|| trait_ref.print_only_trait_path().to_string());
442 if suggest_constraining_type_param(
448 Some(trait_ref.def_id()),
454 hir::Node::Item(hir::Item {
456 hir::ItemKind::Struct(_, generics)
457 | hir::ItemKind::Enum(_, generics)
458 | hir::ItemKind::Union(_, generics)
459 | hir::ItemKind::Trait(_, _, generics, ..)
460 | hir::ItemKind::Impl(hir::Impl { generics, .. })
461 | hir::ItemKind::Fn(_, generics, _)
462 | hir::ItemKind::TyAlias(_, generics)
463 | hir::ItemKind::TraitAlias(generics, _)
464 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
467 // Missing generic type parameter bound.
468 let param_name = self_ty.to_string();
469 let constraint = trait_ref.print_only_trait_path().to_string();
470 if suggest_arbitrary_trait_bound(generics, &mut err, ¶m_name, &constraint) {
474 hir::Node::Crate(..) => return,
479 hir_id = self.tcx.hir().get_parent_item(hir_id);
483 /// When after several dereferencing, the reference satisfies the trait
484 /// binding. This function provides dereference suggestion for this
485 /// specific situation.
486 fn suggest_dereferences(
488 obligation: &PredicateObligation<'tcx>,
489 err: &mut DiagnosticBuilder<'tcx>,
490 trait_ref: ty::PolyTraitRef<'tcx>,
492 // It only make sense when suggesting dereferences for arguments
493 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
494 &obligation.cause.code
500 let param_env = obligation.param_env;
501 let body_id = obligation.cause.body_id;
502 let span = obligation.cause.span;
503 let real_trait_ref = match &*code {
504 ObligationCauseCode::ImplDerivedObligation(cause)
505 | ObligationCauseCode::DerivedObligation(cause)
506 | ObligationCauseCode::BuiltinDerivedObligation(cause) => cause.parent_trait_ref,
509 let real_ty = match real_trait_ref.self_ty().no_bound_vars() {
514 if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
515 let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
516 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
518 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
520 self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_ref, ty);
521 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
524 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
525 // Don't care about `&mut` because `DerefMut` is used less
526 // often and user will not expect autoderef happens.
527 if src.starts_with('&') && !src.starts_with("&mut ") {
528 let derefs = "*".repeat(steps);
531 "consider adding dereference here",
532 format!("&{}{}", derefs, &src[1..]),
533 Applicability::MachineApplicable,
542 /// Given a closure's `DefId`, return the given name of the closure.
544 /// This doesn't account for reassignments, but it's only used for suggestions.
548 err: &mut DiagnosticBuilder<'_>,
550 ) -> Option<String> {
552 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
553 // Get the local name of this closure. This can be inaccurate because
554 // of the possibility of reassignment, but this should be good enough.
556 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
557 Some(format!("{}", name))
566 let hir = self.tcx.hir();
567 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
568 let parent_node = hir.get_parent_node(hir_id);
569 match hir.find(parent_node) {
570 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
571 get_name(err, &local.pat.kind)
573 // Different to previous arm because one is `&hir::Local` and the other
574 // is `P<hir::Local>`.
575 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
580 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
581 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
582 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
585 obligation: &PredicateObligation<'tcx>,
586 err: &mut DiagnosticBuilder<'_>,
587 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
589 let self_ty = match trait_ref.self_ty().no_bound_vars() {
594 let (def_id, output_ty, callable) = match *self_ty.kind() {
595 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
596 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
599 let msg = format!("use parentheses to call the {}", callable);
601 // `mk_trait_obligation_with_new_self_ty` only works for types with no escaping bound
602 // variables, so bail out if we have any.
603 let output_ty = match output_ty.no_bound_vars() {
609 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_ref, output_ty);
611 match self.evaluate_obligation(&new_obligation) {
613 EvaluationResult::EvaluatedToOk
614 | EvaluationResult::EvaluatedToOkModuloRegions
615 | EvaluationResult::EvaluatedToAmbig,
619 let hir = self.tcx.hir();
620 // Get the name of the callable and the arguments to be used in the suggestion.
621 let (snippet, sugg) = match hir.get_if_local(def_id) {
622 Some(hir::Node::Expr(hir::Expr {
623 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
626 err.span_label(*span, "consider calling this closure");
627 let name = match self.get_closure_name(def_id, err, &msg) {
631 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
632 let sugg = format!("({})", args);
633 (format!("{}{}", name, sugg), sugg)
635 Some(hir::Node::Item(hir::Item {
637 kind: hir::ItemKind::Fn(.., body_id),
640 err.span_label(ident.span, "consider calling this function");
641 let body = hir.body(*body_id);
645 .map(|arg| match &arg.pat.kind {
646 hir::PatKind::Binding(_, _, ident, None)
647 // FIXME: provide a better suggestion when encountering `SelfLower`, it
648 // should suggest a method call.
649 if ident.name != kw::SelfLower => ident.to_string(),
650 _ => "_".to_string(),
654 let sugg = format!("({})", args);
655 (format!("{}{}", ident, sugg), sugg)
659 if matches!(obligation.cause.code, ObligationCauseCode::FunctionArgumentObligation { .. }) {
660 // When the obligation error has been ensured to have been caused by
661 // an argument, the `obligation.cause.span` points at the expression
662 // of the argument, so we can provide a suggestion. Otherwise, we give
663 // a more general note.
664 err.span_suggestion_verbose(
665 obligation.cause.span.shrink_to_hi(),
668 Applicability::HasPlaceholders,
671 err.help(&format!("{}: `{}`", msg, snippet));
675 fn suggest_add_reference_to_arg(
677 obligation: &PredicateObligation<'tcx>,
678 err: &mut DiagnosticBuilder<'_>,
679 poly_trait_ref: &ty::Binder<'tcx, ty::TraitRef<'tcx>>,
680 has_custom_message: bool,
682 let span = obligation.cause.span;
684 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
685 &obligation.cause.code
688 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
689 span.ctxt().outer_expn_data().kind
691 Lrc::new(obligation.cause.code.clone())
696 // List of traits for which it would be nonsensical to suggest borrowing.
697 // For instance, immutable references are always Copy, so suggesting to
698 // borrow would always succeed, but it's probably not what the user wanted.
699 let mut never_suggest_borrow: Vec<_> =
700 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
702 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
705 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
706 never_suggest_borrow.push(def_id);
709 let param_env = obligation.param_env;
711 // Try to apply the original trait binding obligation by borrowing.
712 let mut try_borrowing = |old_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
715 if blacklist.contains(&old_ref.def_id()) {
719 let orig_ty = old_ref.self_ty().skip_binder();
720 let mk_result = |new_ty| {
721 let new_ref = old_ref.rebind(ty::TraitRef::new(
723 self.tcx.mk_substs_trait(new_ty, &old_ref.skip_binder().substs[1..]),
725 self.predicate_must_hold_modulo_regions(&Obligation::new(
726 ObligationCause::dummy(),
728 new_ref.without_const().to_predicate(self.tcx),
731 let imm_result = mk_result(self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, orig_ty));
732 let mut_result = mk_result(self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, orig_ty));
734 if imm_result || mut_result {
735 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
736 // We have a very specific type of error, where just borrowing this argument
737 // might solve the problem. In cases like this, the important part is the
738 // original type obligation, not the last one that failed, which is arbitrary.
739 // Because of this, we modify the error to refer to the original obligation and
740 // return early in the caller.
743 "the trait bound `{}: {}` is not satisfied",
745 old_ref.print_only_trait_path(),
747 if has_custom_message {
750 err.message = vec![(msg, Style::NoStyle)];
752 if snippet.starts_with('&') {
753 // This is already a literal borrow and the obligation is failing
754 // somewhere else in the obligation chain. Do not suggest non-sense.
760 "expected an implementor of trait `{}`",
761 old_ref.print_only_trait_path(),
765 // This if is to prevent a special edge-case
767 span.ctxt().outer_expn_data().kind,
768 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
770 // We don't want a borrowing suggestion on the fields in structs,
773 // the_foos: Vec<Foo>
777 if imm_result && mut_result {
778 err.span_suggestions(
780 "consider borrowing here",
781 ["&".to_string(), "&mut ".to_string()].into_iter(),
782 Applicability::MaybeIncorrect,
785 err.span_suggestion_verbose(
788 "consider{} borrowing here",
789 if mut_result { " mutably" } else { "" }
791 format!("&{}", if mut_result { "mut " } else { "" }),
792 Applicability::MaybeIncorrect,
802 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &*code {
803 try_borrowing(obligation.parent_trait_ref, &[])
804 } else if let ObligationCauseCode::BindingObligation(_, _)
805 | ObligationCauseCode::ItemObligation(_) = &*code
807 try_borrowing(*poly_trait_ref, &never_suggest_borrow)
813 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
814 /// suggest removing these references until we reach a type that implements the trait.
815 fn suggest_remove_reference(
817 obligation: &PredicateObligation<'tcx>,
818 err: &mut DiagnosticBuilder<'_>,
819 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
821 let span = obligation.cause.span;
823 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
825 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
826 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
827 // Do not suggest removal of borrow from type arguments.
831 let mut suggested_ty = match trait_ref.self_ty().no_bound_vars() {
836 for refs_remaining in 0..refs_number {
837 if let ty::Ref(_, inner_ty, _) = suggested_ty.kind() {
838 suggested_ty = inner_ty;
840 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
841 obligation.param_env,
846 if self.predicate_may_hold(&new_obligation) {
851 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
853 let remove_refs = refs_remaining + 1;
855 let msg = if remove_refs == 1 {
856 "consider removing the leading `&`-reference".to_string()
858 format!("consider removing {} leading `&`-references", remove_refs)
861 err.span_suggestion_short(
865 Applicability::MachineApplicable,
876 /// Check if the trait bound is implemented for a different mutability and note it in the
878 fn suggest_change_mut(
880 obligation: &PredicateObligation<'tcx>,
881 err: &mut DiagnosticBuilder<'_>,
882 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
884 let points_at_arg = matches!(
885 obligation.cause.code,
886 ObligationCauseCode::FunctionArgumentObligation { .. },
889 let span = obligation.cause.span;
890 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
892 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
893 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
894 // Do not suggest removal of borrow from type arguments.
897 let trait_ref = self.resolve_vars_if_possible(trait_ref);
898 if trait_ref.has_infer_types_or_consts() {
899 // Do not ICE while trying to find if a reborrow would succeed on a trait with
900 // unresolved bindings.
904 if let ty::Ref(region, t_type, mutability) = *trait_ref.skip_binder().self_ty().kind() {
905 if region.is_late_bound() || t_type.has_escaping_bound_vars() {
906 // Avoid debug assertion in `mk_obligation_for_def_id`.
908 // If the self type has escaping bound vars then it's not
909 // going to be the type of an expression, so the suggestion
910 // probably won't apply anyway.
914 let suggested_ty = match mutability {
915 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
916 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
919 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
920 obligation.param_env,
924 let suggested_ty_would_satisfy_obligation = self
925 .evaluate_obligation_no_overflow(&new_obligation)
926 .must_apply_modulo_regions();
927 if suggested_ty_would_satisfy_obligation {
932 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
933 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
934 err.span_suggestion_verbose(
936 "consider changing this borrow's mutability",
938 Applicability::MachineApplicable,
942 "`{}` is implemented for `{:?}`, but not for `{:?}`",
943 trait_ref.print_only_trait_path(),
945 trait_ref.skip_binder().self_ty(),
953 fn suggest_semicolon_removal(
955 obligation: &PredicateObligation<'tcx>,
956 err: &mut DiagnosticBuilder<'_>,
958 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
961 |ty: ty::Binder<'tcx, Ty<'_>>| *ty.skip_binder().kind() == ty::Tuple(ty::List::empty());
963 let hir = self.tcx.hir();
964 let parent_node = hir.get_parent_node(obligation.cause.body_id);
965 let node = hir.find(parent_node);
966 if let Some(hir::Node::Item(hir::Item {
967 kind: hir::ItemKind::Fn(sig, _, body_id), ..
970 let body = hir.body(*body_id);
971 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
972 if sig.decl.output.span().overlaps(span)
973 && blk.expr.is_none()
974 && is_empty_tuple(trait_ref.self_ty())
976 // FIXME(estebank): When encountering a method with a trait
977 // bound not satisfied in the return type with a body that has
978 // no return, suggest removal of semicolon on last statement.
979 // Once that is added, close #54771.
980 if let Some(ref stmt) = blk.stmts.last() {
981 if let hir::StmtKind::Semi(_) = stmt.kind {
982 let sp = self.tcx.sess.source_map().end_point(stmt.span);
983 err.span_label(sp, "consider removing this semicolon");
991 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
992 let hir = self.tcx.hir();
993 let parent_node = hir.get_parent_node(obligation.cause.body_id);
994 let sig = match hir.find(parent_node) {
995 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) => sig,
999 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1002 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1003 /// applicable and signal that the error has been expanded appropriately and needs to be
1005 fn suggest_impl_trait(
1007 err: &mut DiagnosticBuilder<'_>,
1009 obligation: &PredicateObligation<'tcx>,
1010 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
1012 match obligation.cause.code.peel_derives() {
1013 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1014 ObligationCauseCode::SizedReturnType => {}
1018 let hir = self.tcx.hir();
1019 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1020 let node = hir.find(parent_node);
1021 let Some(hir::Node::Item(hir::Item {
1022 kind: hir::ItemKind::Fn(sig, _, body_id),
1028 let body = hir.body(*body_id);
1029 let trait_ref = self.resolve_vars_if_possible(trait_ref);
1030 let ty = trait_ref.skip_binder().self_ty();
1031 let is_object_safe = match ty.kind() {
1032 ty::Dynamic(predicates, _) => {
1033 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1036 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1038 // We only want to suggest `impl Trait` to `dyn Trait`s.
1039 // For example, `fn foo() -> str` needs to be filtered out.
1043 let ret_ty = if let hir::FnRetTy::Return(ret_ty) = sig.decl.output {
1049 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1050 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1051 // Recursively look for `TraitObject` types and if there's only one, use that span to
1052 // suggest `impl Trait`.
1054 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1055 // otherwise suggest using `Box<dyn Trait>` or an enum.
1056 let mut visitor = ReturnsVisitor::default();
1057 visitor.visit_body(&body);
1059 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1061 let mut ret_types = visitor
1064 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1065 .map(|ty| self.resolve_vars_if_possible(ty));
1066 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1068 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1070 let ty = self.resolve_vars_if_possible(ty);
1072 !matches!(ty.kind(), ty::Error(_))
1073 && last_ty.map_or(true, |last_ty| {
1074 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1075 // *after* in the dependency graph.
1076 match (ty.kind(), last_ty.kind()) {
1077 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1078 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1079 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1081 Infer(InferTy::FreshFloatTy(_)),
1082 Infer(InferTy::FreshFloatTy(_)),
1087 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1090 let all_returns_conform_to_trait =
1091 if let Some(ty_ret_ty) = typeck_results.node_type_opt(ret_ty.hir_id) {
1092 match ty_ret_ty.kind() {
1093 ty::Dynamic(predicates, _) => {
1094 let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
1095 let param_env = ty::ParamEnv::empty();
1097 || ret_types.all(|returned_ty| {
1098 predicates.iter().all(|predicate| {
1099 let pred = predicate.with_self_ty(self.tcx, returned_ty);
1100 let obl = Obligation::new(cause.clone(), param_env, pred);
1101 self.predicate_may_hold(&obl)
1111 let sm = self.tcx.sess.source_map();
1112 let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
1113 // Verify that we're dealing with a return `dyn Trait`
1114 ret_ty.span.overlaps(span),
1116 sm.span_to_snippet(ret_ty.span),
1117 // If any of the return types does not conform to the trait, then we can't
1118 // suggest `impl Trait` nor trait objects: it is a type mismatch error.
1119 all_returns_conform_to_trait,
1125 err.code(error_code!(E0746));
1126 err.set_primary_message("return type cannot have an unboxed trait object");
1127 err.children.clear();
1128 let impl_trait_msg = "for information on `impl Trait`, see \
1129 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1130 #returning-types-that-implement-traits>";
1131 let trait_obj_msg = "for information on trait objects, see \
1132 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1133 #using-trait-objects-that-allow-for-values-of-different-types>";
1134 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1135 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1136 if only_never_return {
1137 // No return paths, probably using `panic!()` or similar.
1138 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1139 suggest_trait_object_return_type_alternatives(
1145 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1146 // Suggest `-> impl Trait`.
1147 err.span_suggestion(
1150 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1151 which implements `{1}`",
1154 format!("impl {}", trait_obj),
1155 Applicability::MachineApplicable,
1157 err.note(impl_trait_msg);
1160 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1161 // Get all the return values and collect their span and suggestion.
1162 let mut suggestions: Vec<_> = visitor
1167 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
1168 (expr.span.shrink_to_hi(), ")".to_string()),
1173 if !suggestions.is_empty() {
1174 // Add the suggestion for the return type.
1175 suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
1176 err.multipart_suggestion(
1177 "return a boxed trait object instead",
1179 Applicability::MaybeIncorrect,
1183 // This is currently not possible to trigger because E0038 takes precedence, but
1184 // leave it in for completeness in case anything changes in an earlier stage.
1186 "if trait `{}` were object-safe, you could return a trait object",
1190 err.note(trait_obj_msg);
1192 "if all the returned values were of the same type you could use `impl {}` as the \
1196 err.note(impl_trait_msg);
1197 err.note("you can create a new `enum` with a variant for each returned type");
1202 fn point_at_returns_when_relevant(
1204 err: &mut DiagnosticBuilder<'_>,
1205 obligation: &PredicateObligation<'tcx>,
1207 match obligation.cause.code.peel_derives() {
1208 ObligationCauseCode::SizedReturnType => {}
1212 let hir = self.tcx.hir();
1213 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1214 let node = hir.find(parent_node);
1215 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1218 let body = hir.body(*body_id);
1219 // Point at all the `return`s in the function as they have failed trait bounds.
1220 let mut visitor = ReturnsVisitor::default();
1221 visitor.visit_body(&body);
1222 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1223 for expr in &visitor.returns {
1224 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1225 let ty = self.resolve_vars_if_possible(returned_ty);
1226 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1232 fn report_closure_arg_mismatch(
1235 found_span: Option<Span>,
1236 expected_ref: ty::PolyTraitRef<'tcx>,
1237 found: ty::PolyTraitRef<'tcx>,
1238 ) -> DiagnosticBuilder<'tcx> {
1239 crate fn build_fn_sig_string<'tcx>(
1241 trait_ref: ty::PolyTraitRef<'tcx>,
1243 let inputs = trait_ref.skip_binder().substs.type_at(1);
1244 let sig = match inputs.kind() {
1246 if tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1249 inputs.iter().map(|k| k.expect_ty()),
1250 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1252 hir::Unsafety::Normal,
1257 std::iter::once(inputs),
1258 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1260 hir::Unsafety::Normal,
1264 trait_ref.rebind(sig).to_string()
1267 let argument_kind = match expected_ref.skip_binder().substs.type_at(0) {
1268 t if t.is_closure() => "closure",
1269 t if t.is_generator() => "generator",
1272 let mut err = struct_span_err!(
1276 "type mismatch in {} arguments",
1280 let found_str = format!("expected signature of `{}`", build_fn_sig_string(self.tcx, found));
1281 err.span_label(span, found_str);
1283 let found_span = found_span.unwrap_or(span);
1285 format!("found signature of `{}`", build_fn_sig_string(self.tcx, expected_ref));
1286 err.span_label(found_span, expected_str);
1291 fn suggest_fully_qualified_path(
1293 err: &mut DiagnosticBuilder<'_>,
1298 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1299 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1301 "{}s cannot be accessed directly on a `trait`, they can only be \
1302 accessed through a specific `impl`",
1303 assoc_item.kind.as_def_kind().descr(def_id)
1305 err.span_suggestion(
1307 "use the fully qualified path to an implementation",
1308 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1309 Applicability::HasPlaceholders,
1315 /// Adds an async-await specific note to the diagnostic when the future does not implement
1316 /// an auto trait because of a captured type.
1319 /// note: future does not implement `Qux` as this value is used across an await
1320 /// --> $DIR/issue-64130-3-other.rs:17:5
1322 /// LL | let x = Foo;
1323 /// | - has type `Foo`
1324 /// LL | baz().await;
1325 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1327 /// | - `x` is later dropped here
1330 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1331 /// is "replaced" with a different message and a more specific error.
1334 /// error: future cannot be sent between threads safely
1335 /// --> $DIR/issue-64130-2-send.rs:21:5
1337 /// LL | fn is_send<T: Send>(t: T) { }
1338 /// | ---- required by this bound in `is_send`
1340 /// LL | is_send(bar());
1341 /// | ^^^^^^^ future returned by `bar` is not send
1343 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1344 /// implemented for `Foo`
1345 /// note: future is not send as this value is used across an await
1346 /// --> $DIR/issue-64130-2-send.rs:15:5
1348 /// LL | let x = Foo;
1349 /// | - has type `Foo`
1350 /// LL | baz().await;
1351 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1353 /// | - `x` is later dropped here
1356 /// Returns `true` if an async-await specific note was added to the diagnostic.
1357 fn maybe_note_obligation_cause_for_async_await(
1359 err: &mut DiagnosticBuilder<'_>,
1360 obligation: &PredicateObligation<'tcx>,
1363 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1364 obligation.cause.span={:?}",
1365 obligation.predicate, obligation.cause.span
1367 let hir = self.tcx.hir();
1369 // Attempt to detect an async-await error by looking at the obligation causes, looking
1370 // for a generator to be present.
1372 // When a future does not implement a trait because of a captured type in one of the
1373 // generators somewhere in the call stack, then the result is a chain of obligations.
1375 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1376 // future is passed as an argument to a function C which requires a `Send` type, then the
1377 // chain looks something like this:
1379 // - `BuiltinDerivedObligation` with a generator witness (B)
1380 // - `BuiltinDerivedObligation` with a generator (B)
1381 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1382 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1383 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1384 // - `BuiltinDerivedObligation` with a generator witness (A)
1385 // - `BuiltinDerivedObligation` with a generator (A)
1386 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1387 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1388 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1389 // - `BindingObligation` with `impl_send (Send requirement)
1391 // The first obligation in the chain is the most useful and has the generator that captured
1392 // the type. The last generator (`outer_generator` below) has information about where the
1393 // bound was introduced. At least one generator should be present for this diagnostic to be
1395 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1396 ty::PredicateKind::Trait(p) => (Some(p.trait_ref), Some(p.self_ty())),
1399 let mut generator = None;
1400 let mut outer_generator = None;
1401 let mut next_code = Some(&obligation.cause.code);
1403 let mut seen_upvar_tys_infer_tuple = false;
1405 while let Some(code) = next_code {
1406 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1408 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1409 next_code = Some(parent_code.as_ref());
1411 ObligationCauseCode::DerivedObligation(derived_obligation)
1412 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1413 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1414 let ty = derived_obligation.parent_trait_ref.skip_binder().self_ty();
1416 "maybe_note_obligation_cause_for_async_await: \
1417 parent_trait_ref={:?} self_ty.kind={:?}",
1418 derived_obligation.parent_trait_ref,
1423 ty::Generator(did, ..) => {
1424 generator = generator.or(Some(did));
1425 outer_generator = Some(did);
1427 ty::GeneratorWitness(..) => {}
1428 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1429 // By introducing a tuple of upvar types into the chain of obligations
1430 // of a generator, the first non-generator item is now the tuple itself,
1431 // we shall ignore this.
1433 seen_upvar_tys_infer_tuple = true;
1435 _ if generator.is_none() => {
1436 trait_ref = Some(derived_obligation.parent_trait_ref.skip_binder());
1437 target_ty = Some(ty);
1442 next_code = Some(derived_obligation.parent_code.as_ref());
1448 // Only continue if a generator was found.
1449 debug!(?generator, ?trait_ref, ?target_ty, "maybe_note_obligation_cause_for_async_await");
1450 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1451 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1452 (generator_did, trait_ref, target_ty)
1457 let span = self.tcx.def_span(generator_did);
1459 let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1460 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1462 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1463 generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
1466 in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1470 let generator_body = generator_did
1472 .map(|def_id| hir.local_def_id_to_hir_id(def_id))
1473 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1474 .map(|body_id| hir.body(body_id));
1475 let mut visitor = AwaitsVisitor::default();
1476 if let Some(body) = generator_body {
1477 visitor.visit_body(body);
1479 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1481 // Look for a type inside the generator interior that matches the target type to get
1483 let target_ty_erased = self.tcx.erase_regions(target_ty);
1484 let ty_matches = |ty| -> bool {
1485 // Careful: the regions for types that appear in the
1486 // generator interior are not generally known, so we
1487 // want to erase them when comparing (and anyway,
1488 // `Send` and other bounds are generally unaffected by
1489 // the choice of region). When erasing regions, we
1490 // also have to erase late-bound regions. This is
1491 // because the types that appear in the generator
1492 // interior generally contain "bound regions" to
1493 // represent regions that are part of the suspended
1494 // generator frame. Bound regions are preserved by
1495 // `erase_regions` and so we must also call
1496 // `erase_late_bound_regions`.
1497 let ty_erased = self.tcx.erase_late_bound_regions(ty);
1498 let ty_erased = self.tcx.erase_regions(ty_erased);
1499 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1501 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1502 target_ty_erased={:?} eq={:?}",
1503 ty_erased, target_ty_erased, eq
1508 let mut interior_or_upvar_span = None;
1509 let mut interior_extra_info = None;
1511 // Get the typeck results from the infcx if the generator is the function we are currently
1512 // type-checking; otherwise, get them by performing a query. This is needed to avoid
1513 // cycles. If we can't use resolved types because the generator comes from another crate,
1514 // we still provide a targeted error but without all the relevant spans.
1515 let query_typeck_results;
1516 let typeck_results: Option<&TypeckResults<'tcx>> = match &in_progress_typeck_results {
1517 Some(t) if t.hir_owner.to_def_id() == generator_did_root => Some(&t),
1518 _ if generator_did.is_local() => {
1519 query_typeck_results = self.tcx.typeck(generator_did.expect_local());
1520 Some(&query_typeck_results)
1522 _ => None, // Do not ICE on closure typeck (#66868).
1524 if let Some(typeck_results) = typeck_results {
1525 if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) {
1526 interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| {
1527 let upvar_ty = typeck_results.node_type(*upvar_id);
1528 let upvar_ty = self.resolve_vars_if_possible(upvar_ty);
1529 if ty_matches(ty::Binder::dummy(upvar_ty)) {
1530 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
1537 // The generator interior types share the same binders
1538 if let Some(cause) =
1539 typeck_results.generator_interior_types.as_ref().skip_binder().iter().find(
1540 |ty::GeneratorInteriorTypeCause { ty, .. }| {
1541 ty_matches(typeck_results.generator_interior_types.rebind(ty))
1545 // Check to see if any awaited expressions have the target type.
1546 let from_awaited_ty = visitor
1549 .map(|id| hir.expect_expr(id))
1550 .find(|await_expr| {
1551 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
1553 .map(|expr| expr.span);
1554 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1557 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1558 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1561 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span));
1564 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1565 self.note_obligation_cause_for_async_await(
1567 interior_or_upvar_span,
1568 interior_extra_info,
1583 /// Unconditionally adds the diagnostic note described in
1584 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1585 fn note_obligation_cause_for_async_await(
1587 err: &mut DiagnosticBuilder<'_>,
1588 interior_or_upvar_span: GeneratorInteriorOrUpvar,
1589 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1590 inner_generator_body: Option<&hir::Body<'tcx>>,
1591 outer_generator: Option<DefId>,
1592 trait_ref: ty::TraitRef<'tcx>,
1593 target_ty: Ty<'tcx>,
1594 typeck_results: Option<&ty::TypeckResults<'tcx>>,
1595 obligation: &PredicateObligation<'tcx>,
1596 next_code: Option<&ObligationCauseCode<'tcx>>,
1598 let source_map = self.tcx.sess.source_map();
1600 let is_async = inner_generator_body
1601 .and_then(|body| body.generator_kind())
1602 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1604 let (await_or_yield, an_await_or_yield) =
1605 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1606 let future_or_generator = if is_async { "future" } else { "generator" };
1608 // Special case the primary error message when send or sync is the trait that was
1610 let hir = self.tcx.hir();
1611 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
1612 self.tcx.get_diagnostic_name(trait_ref.def_id)
1614 let (trait_name, trait_verb) =
1615 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1618 err.set_primary_message(format!(
1619 "{} cannot be {} between threads safely",
1620 future_or_generator, trait_verb
1623 let original_span = err.span.primary_span().unwrap();
1624 let mut span = MultiSpan::from_span(original_span);
1626 let message = outer_generator
1627 .and_then(|generator_did| {
1628 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1629 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1630 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1632 .parent(generator_did)
1633 .and_then(|parent_did| parent_did.as_local())
1634 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
1635 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1637 format!("future returned by `{}` is not {}", name, trait_name)
1639 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1640 format!("future created by async block is not {}", trait_name)
1642 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1643 format!("future created by async closure is not {}", trait_name)
1647 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1649 span.push_span_label(original_span, message);
1652 format!("is not {}", trait_name)
1654 format!("does not implement `{}`", trait_ref.print_only_trait_path())
1657 let mut explain_yield =
1658 |interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
1659 let mut span = MultiSpan::from_span(yield_span);
1660 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1661 // #70935: If snippet contains newlines, display "the value" instead
1662 // so that we do not emit complex diagnostics.
1663 let snippet = &format!("`{}`", snippet);
1664 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
1665 // The multispan can be complex here, like:
1666 // note: future is not `Send` as this value is used across an await
1667 // --> $DIR/issue-70935-complex-spans.rs:13:9
1669 // LL | baz(|| async{
1670 // | __________^___-
1673 // LL | || foo(tx.clone());
1674 // LL | || }).await;
1675 // | || - ^- value is later dropped here
1676 // | ||_________|______|
1677 // | |__________| await occurs here, with value maybe used later
1678 // | has type `closure` which is not `Send`
1680 // So, detect it and separate into some notes, like:
1682 // note: future is not `Send` as this value is used across an await
1683 // --> $DIR/issue-70935-complex-spans.rs:13:9
1685 // LL | / baz(|| async{
1686 // LL | | foo(tx.clone());
1688 // | |________________^ first, await occurs here, with the value maybe used later...
1689 // note: the value is later dropped here
1690 // --> $DIR/issue-70935-complex-spans.rs:15:17
1695 // If available, use the scope span to annotate the drop location.
1696 if let Some(scope_span) = scope_span {
1697 let scope_span = source_map.end_point(scope_span);
1699 yield_span.overlaps(scope_span) || yield_span.overlaps(interior_span);
1701 span.push_span_label(
1704 "first, {} occurs here, with {} maybe used later...",
1705 await_or_yield, snippet
1711 "{} {} as this value is used across {}",
1712 future_or_generator, trait_explanation, an_await_or_yield
1715 if source_map.is_multiline(interior_span) {
1718 &format!("{} is later dropped here", snippet),
1723 "this has type `{}` which {}",
1724 target_ty, trait_explanation
1728 let mut span = MultiSpan::from_span(scope_span);
1729 span.push_span_label(
1731 format!("has type `{}` which {}", target_ty, trait_explanation),
1733 err.span_note(span, &format!("{} is later dropped here", snippet));
1736 span.push_span_label(
1739 "{} occurs here, with {} maybe used later",
1740 await_or_yield, snippet
1743 span.push_span_label(
1745 format!("{} is later dropped here", snippet),
1747 span.push_span_label(
1749 format!("has type `{}` which {}", target_ty, trait_explanation),
1754 "{} {} as this value is used across {}",
1755 future_or_generator, trait_explanation, an_await_or_yield
1760 span.push_span_label(
1763 "{} occurs here, with {} maybe used later",
1764 await_or_yield, snippet
1767 span.push_span_label(
1769 format!("has type `{}` which {}", target_ty, trait_explanation),
1774 "{} {} as this value is used across {}",
1775 future_or_generator, trait_explanation, an_await_or_yield
1781 match interior_or_upvar_span {
1782 GeneratorInteriorOrUpvar::Interior(interior_span) => {
1783 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
1784 if let Some(await_span) = from_awaited_ty {
1785 // The type causing this obligation is one being awaited at await_span.
1786 let mut span = MultiSpan::from_span(await_span);
1787 span.push_span_label(
1790 "await occurs here on type `{}`, which {}",
1791 target_ty, trait_explanation
1797 "future {not_trait} as it awaits another future which {not_trait}",
1798 not_trait = trait_explanation
1802 // Look at the last interior type to get a span for the `.await`.
1804 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1805 typeck_results.as_ref().map(|t| &t.generator_interior_types)
1807 explain_yield(interior_span, yield_span, scope_span);
1810 if let Some(expr_id) = expr {
1811 let expr = hir.expect_expr(expr_id);
1812 debug!("target_ty evaluated from {:?}", expr);
1814 let parent = hir.get_parent_node(expr_id);
1815 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1816 let parent_span = hir.span(parent);
1817 let parent_did = parent.owner.to_def_id();
1820 // fn foo(&self) -> i32 {}
1823 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1826 let is_region_borrow = if let Some(typeck_results) = typeck_results {
1828 .expr_adjustments(expr)
1830 .any(|adj| adj.is_region_borrow())
1836 // struct Foo(*const u8);
1837 // bar(Foo(std::ptr::null())).await;
1838 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1840 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1841 let is_raw_borrow_inside_fn_like_call =
1842 match self.tcx.def_kind(parent_did) {
1843 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
1846 if let Some(typeck_results) = typeck_results {
1847 if (typeck_results.is_method_call(e) && is_region_borrow)
1848 || is_raw_borrow_inside_fn_like_call
1852 "consider moving this into a `let` \
1853 binding to create a shorter lived borrow",
1861 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
1862 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
1863 let refers_to_non_sync = match target_ty.kind() {
1864 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
1865 Ok(eval) if !eval.may_apply() => Some(ref_ty),
1871 let (span_label, span_note) = match refers_to_non_sync {
1872 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
1873 // include suggestions to make `T: Sync` so that `&T: Send`
1876 "has type `{}` which {}, because `{}` is not `Sync`",
1877 target_ty, trait_explanation, ref_ty
1880 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
1885 format!("has type `{}` which {}", target_ty, trait_explanation),
1886 format!("captured value {}", trait_explanation),
1890 let mut span = MultiSpan::from_span(upvar_span);
1891 span.push_span_label(upvar_span, span_label);
1892 err.span_note(span, &span_note);
1896 // Add a note for the item obligation that remains - normally a note pointing to the
1897 // bound that introduced the obligation (e.g. `T: Send`).
1898 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1899 self.note_obligation_cause_code(
1901 &obligation.predicate,
1904 &mut Default::default(),
1908 fn note_obligation_cause_code<T>(
1910 err: &mut DiagnosticBuilder<'_>,
1912 cause_code: &ObligationCauseCode<'tcx>,
1913 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1914 seen_requirements: &mut FxHashSet<DefId>,
1920 ObligationCauseCode::ExprAssignable
1921 | ObligationCauseCode::MatchExpressionArm { .. }
1922 | ObligationCauseCode::Pattern { .. }
1923 | ObligationCauseCode::IfExpression { .. }
1924 | ObligationCauseCode::IfExpressionWithNoElse
1925 | ObligationCauseCode::MainFunctionType
1926 | ObligationCauseCode::StartFunctionType
1927 | ObligationCauseCode::IntrinsicType
1928 | ObligationCauseCode::MethodReceiver
1929 | ObligationCauseCode::ReturnNoExpression
1930 | ObligationCauseCode::UnifyReceiver(..)
1931 | ObligationCauseCode::OpaqueType
1932 | ObligationCauseCode::MiscObligation
1933 | ObligationCauseCode::WellFormed(..)
1934 | ObligationCauseCode::MatchImpl(..)
1935 | ObligationCauseCode::ReturnType
1936 | ObligationCauseCode::ReturnValue(_)
1937 | ObligationCauseCode::BlockTailExpression(_)
1938 | ObligationCauseCode::LetElse => {}
1939 ObligationCauseCode::SliceOrArrayElem => {
1940 err.note("slice and array elements must have `Sized` type");
1942 ObligationCauseCode::TupleElem => {
1943 err.note("only the last element of a tuple may have a dynamically sized type");
1945 ObligationCauseCode::ProjectionWf(data) => {
1946 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1948 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1950 "required so that reference `{}` does not outlive its referent",
1954 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1956 "required so that the lifetime bound of `{}` for `{}` is satisfied",
1960 ObligationCauseCode::ItemObligation(_item_def_id) => {
1961 // We hold the `DefId` of the item introducing the obligation, but displaying it
1962 // doesn't add user usable information. It always point at an associated item.
1964 ObligationCauseCode::BindingObligation(item_def_id, span) => {
1965 let item_name = tcx.def_path_str(item_def_id);
1966 let mut multispan = MultiSpan::from(span);
1967 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1968 let sm = tcx.sess.source_map();
1970 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
1971 (Ok(l), Ok(r)) => l.line == r.line,
1974 if !ident.span.overlaps(span) && !same_line {
1976 .push_span_label(ident.span, "required by a bound in this".to_string());
1979 let descr = format!("required by a bound in `{}`", item_name);
1980 if span != DUMMY_SP {
1981 let msg = format!("required by this bound in `{}`", item_name);
1982 multispan.push_span_label(span, msg);
1983 err.span_note(multispan, &descr);
1985 err.span_note(tcx.def_span(item_def_id), &descr);
1988 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1990 "required for the cast to the object type `{}`",
1991 self.ty_to_string(object_ty)
1994 ObligationCauseCode::Coercion { source: _, target } => {
1995 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1997 ObligationCauseCode::RepeatVec(is_const_fn) => {
1999 "the `Copy` trait is required because the repeated element will be copied",
2004 "consider creating a new `const` item and initializing it with the result \
2005 of the function call to be used in the repeat position, like \
2006 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2010 if self.tcx.sess.is_nightly_build() && is_const_fn {
2012 "create an inline `const` block, see RFC #2920 \
2013 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2017 ObligationCauseCode::VariableType(hir_id) => {
2018 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2019 match self.tcx.hir().find(parent_node) {
2020 Some(Node::Local(hir::Local {
2021 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2024 // When encountering an assignment of an unsized trait, like
2025 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2026 // order to use have a slice instead.
2027 err.span_suggestion_verbose(
2028 span.shrink_to_lo(),
2029 "consider borrowing here",
2031 Applicability::MachineApplicable,
2033 err.note("all local variables must have a statically known size");
2035 Some(Node::Param(param)) => {
2036 err.span_suggestion_verbose(
2037 param.ty_span.shrink_to_lo(),
2038 "function arguments must have a statically known size, borrowed types \
2039 always have a known size",
2041 Applicability::MachineApplicable,
2045 err.note("all local variables must have a statically known size");
2048 if !self.tcx.features().unsized_locals {
2049 err.help("unsized locals are gated as an unstable feature");
2052 ObligationCauseCode::SizedArgumentType(sp) => {
2053 if let Some(span) = sp {
2054 err.span_suggestion_verbose(
2055 span.shrink_to_lo(),
2056 "function arguments must have a statically known size, borrowed types \
2057 always have a known size",
2059 Applicability::MachineApplicable,
2062 err.note("all function arguments must have a statically known size");
2064 if tcx.sess.opts.unstable_features.is_nightly_build()
2065 && !self.tcx.features().unsized_fn_params
2067 err.help("unsized fn params are gated as an unstable feature");
2070 ObligationCauseCode::SizedReturnType => {
2071 err.note("the return type of a function must have a statically known size");
2073 ObligationCauseCode::SizedYieldType => {
2074 err.note("the yield type of a generator must have a statically known size");
2076 ObligationCauseCode::SizedBoxType => {
2077 err.note("the type of a box expression must have a statically known size");
2079 ObligationCauseCode::AssignmentLhsSized => {
2080 err.note("the left-hand-side of an assignment must have a statically known size");
2082 ObligationCauseCode::TupleInitializerSized => {
2083 err.note("tuples must have a statically known size to be initialized");
2085 ObligationCauseCode::StructInitializerSized => {
2086 err.note("structs must have a statically known size to be initialized");
2088 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2090 AdtKind::Struct => {
2093 "the last field of a packed struct may only have a \
2094 dynamically sized type if it does not need drop to be run",
2098 "only the last field of a struct may have a dynamically sized type",
2103 err.note("no field of a union may have a dynamically sized type");
2106 err.note("no field of an enum variant may have a dynamically sized type");
2109 err.help("change the field's type to have a statically known size");
2110 err.span_suggestion(
2111 span.shrink_to_lo(),
2112 "borrowed types always have a statically known size",
2114 Applicability::MachineApplicable,
2116 err.multipart_suggestion(
2117 "the `Box` type always has a statically known size and allocates its contents \
2120 (span.shrink_to_lo(), "Box<".to_string()),
2121 (span.shrink_to_hi(), ">".to_string()),
2123 Applicability::MachineApplicable,
2126 ObligationCauseCode::ConstSized => {
2127 err.note("constant expressions must have a statically known size");
2129 ObligationCauseCode::InlineAsmSized => {
2130 err.note("all inline asm arguments must have a statically known size");
2132 ObligationCauseCode::ConstPatternStructural => {
2133 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2135 ObligationCauseCode::SharedStatic => {
2136 err.note("shared static variables must have a type that implements `Sync`");
2138 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2139 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2140 let ty = parent_trait_ref.skip_binder().self_ty();
2141 if parent_trait_ref.references_error() {
2146 // If the obligation for a tuple is set directly by a Generator or Closure,
2147 // then the tuple must be the one containing capture types.
2148 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2151 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) =
2154 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2155 let ty = parent_trait_ref.skip_binder().self_ty();
2156 matches!(ty.kind(), ty::Generator(..))
2157 || matches!(ty.kind(), ty::Closure(..))
2163 // Don't print the tuple of capture types
2164 if !is_upvar_tys_infer_tuple {
2165 let msg = format!("required because it appears within the type `{}`", ty);
2167 ty::Adt(def, _) => match self.tcx.opt_item_name(def.did) {
2168 Some(ident) => err.span_note(ident.span, &msg),
2169 None => err.note(&msg),
2171 _ => err.note(&msg),
2175 obligated_types.push(ty);
2177 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2178 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2179 // #74711: avoid a stack overflow
2180 ensure_sufficient_stack(|| {
2181 self.note_obligation_cause_code(
2191 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2192 let mut parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2193 let parent_def_id = parent_trait_ref.def_id();
2195 "required because of the requirements on the impl of `{}` for `{}`",
2196 parent_trait_ref.print_only_trait_path(),
2197 parent_trait_ref.skip_binder().self_ty()
2199 let mut candidates = vec![];
2200 self.tcx.for_each_relevant_impl(
2202 parent_trait_ref.self_ty().skip_binder(),
2203 |impl_def_id| match self.tcx.hir().get_if_local(impl_def_id) {
2204 Some(Node::Item(hir::Item {
2205 kind: hir::ItemKind::Impl(hir::Impl { .. }),
2208 candidates.push(impl_def_id);
2213 match &candidates[..] {
2214 [def_id] => match self.tcx.hir().get_if_local(*def_id) {
2215 Some(Node::Item(hir::Item {
2216 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2219 let mut spans = Vec::with_capacity(2);
2220 if let Some(trait_ref) = of_trait {
2221 spans.push(trait_ref.path.span);
2223 spans.push(self_ty.span);
2224 err.span_note(spans, &msg)
2226 _ => err.note(&msg),
2228 _ => err.note(&msg),
2231 let mut parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2232 let mut data = data;
2234 seen_requirements.insert(parent_def_id);
2235 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2236 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2237 let child_trait_ref = self.resolve_vars_if_possible(child.parent_trait_ref);
2238 let child_def_id = child_trait_ref.def_id();
2239 if seen_requirements.insert(child_def_id) {
2244 parent_predicate = child_trait_ref.without_const().to_predicate(tcx);
2245 parent_trait_ref = child_trait_ref;
2249 "{} redundant requirement{} hidden",
2254 "required because of the requirements on the impl of `{}` for `{}`",
2255 parent_trait_ref.print_only_trait_path(),
2256 parent_trait_ref.skip_binder().self_ty()
2259 // #74711: avoid a stack overflow
2260 ensure_sufficient_stack(|| {
2261 self.note_obligation_cause_code(
2270 ObligationCauseCode::DerivedObligation(ref data) => {
2271 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
2272 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
2273 // #74711: avoid a stack overflow
2274 ensure_sufficient_stack(|| {
2275 self.note_obligation_cause_code(
2284 ObligationCauseCode::FunctionArgumentObligation {
2289 let hir = self.tcx.hir();
2290 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2291 hir.find(arg_hir_id)
2293 let in_progress_typeck_results =
2294 self.in_progress_typeck_results.map(|t| t.borrow());
2295 let parent_id = hir.local_def_id(hir.get_parent_item(arg_hir_id));
2296 let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
2297 Some(t) if t.hir_owner == parent_id => t,
2298 _ => self.tcx.typeck(parent_id),
2300 let ty = typeck_results.expr_ty_adjusted(expr);
2301 let span = expr.peel_blocks().span;
2302 if Some(span) != err.span.primary_span() {
2305 &if ty.references_error() {
2308 format!("this tail expression is of type `{:?}`", ty)
2313 if let Some(Node::Expr(hir::Expr {
2315 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2316 | hir::ExprKind::MethodCall(_, span, ..),
2318 })) = hir.find(call_hir_id)
2320 if Some(*span) != err.span.primary_span() {
2321 err.span_label(*span, "required by a bound introduced by this call");
2324 ensure_sufficient_stack(|| {
2325 self.note_obligation_cause_code(
2334 ObligationCauseCode::CompareImplMethodObligation { trait_item_def_id, .. } => {
2335 let item_name = self.tcx.item_name(trait_item_def_id);
2337 "the requirement `{}` appears on the impl method `{}` but not on the \
2338 corresponding trait method",
2339 predicate, item_name,
2343 .opt_item_name(trait_item_def_id)
2345 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2346 let mut assoc_span: MultiSpan = sp.into();
2347 assoc_span.push_span_label(
2349 format!("this trait method doesn't have the requirement `{}`", predicate),
2351 if let Some(ident) = self
2353 .opt_associated_item(trait_item_def_id)
2354 .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2356 assoc_span.push_span_label(ident.span, "in this trait".into());
2358 err.span_note(assoc_span, &msg);
2360 ObligationCauseCode::CompareImplTypeObligation { trait_item_def_id, .. } => {
2361 let item_name = self.tcx.item_name(trait_item_def_id);
2363 "the requirement `{}` appears on the associated impl type `{}` but not on the \
2364 corresponding associated trait type",
2365 predicate, item_name,
2367 let sp = self.tcx.def_span(trait_item_def_id);
2368 let mut assoc_span: MultiSpan = sp.into();
2369 assoc_span.push_span_label(
2372 "this trait associated type doesn't have the requirement `{}`",
2376 if let Some(ident) = self
2378 .opt_associated_item(trait_item_def_id)
2379 .and_then(|i| self.tcx.opt_item_name(i.container.id()))
2381 assoc_span.push_span_label(ident.span, "in this trait".into());
2383 err.span_note(assoc_span, &msg);
2385 ObligationCauseCode::CompareImplConstObligation => {
2387 "the requirement `{}` appears on the associated impl constant \
2388 but not on the corresponding associated trait constant",
2392 ObligationCauseCode::TrivialBound => {
2393 err.help("see issue #48214");
2394 if tcx.sess.opts.unstable_features.is_nightly_build() {
2395 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2401 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
2402 let suggested_limit = match self.tcx.recursion_limit() {
2403 Limit(0) => Limit(2),
2407 "consider increasing the recursion limit by adding a \
2408 `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
2410 self.tcx.crate_name(LOCAL_CRATE),
2414 fn suggest_await_before_try(
2416 err: &mut DiagnosticBuilder<'_>,
2417 obligation: &PredicateObligation<'tcx>,
2418 trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2422 "suggest_await_before_try: obligation={:?}, span={:?}, trait_ref={:?}, trait_ref_self_ty={:?}",
2428 let body_hir_id = obligation.cause.body_id;
2429 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2431 if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
2432 let body = self.tcx.hir().body(body_id);
2433 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2434 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2436 let self_ty = self.resolve_vars_if_possible(trait_ref.self_ty());
2438 // Do not check on infer_types to avoid panic in evaluate_obligation.
2439 if self_ty.has_infer_types() {
2442 let self_ty = self.tcx.erase_regions(self_ty);
2444 let impls_future = self.type_implements_trait(
2446 self_ty.skip_binder(),
2448 obligation.param_env,
2451 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2452 // `<T as Future>::Output`
2453 let projection_ty = ty::ProjectionTy {
2455 substs: self.tcx.mk_substs_trait(
2456 trait_ref.self_ty().skip_binder(),
2457 self.fresh_substs_for_item(span, item_def_id),
2463 let mut selcx = SelectionContext::new(self);
2465 let mut obligations = vec![];
2466 let normalized_ty = normalize_projection_type(
2468 obligation.param_env,
2470 obligation.cause.clone(),
2476 "suggest_await_before_try: normalized_projection_type {:?}",
2477 self.resolve_vars_if_possible(normalized_ty)
2479 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2480 obligation.param_env,
2484 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2485 if self.predicate_may_hold(&try_obligation)
2486 && impls_future.must_apply_modulo_regions()
2488 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2489 if snippet.ends_with('?') {
2490 err.span_suggestion_verbose(
2491 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2492 "consider `await`ing on the `Future`",
2493 ".await".to_string(),
2494 Applicability::MaybeIncorrect,
2504 /// Collect all the returned expressions within the input expression.
2505 /// Used to point at the return spans when we want to suggest some change to them.
2507 pub struct ReturnsVisitor<'v> {
2508 pub returns: Vec<&'v hir::Expr<'v>>,
2509 in_block_tail: bool,
2512 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2513 type Map = hir::intravisit::ErasedMap<'v>;
2515 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2516 hir::intravisit::NestedVisitorMap::None
2519 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2520 // Visit every expression to detect `return` paths, either through the function's tail
2521 // expression or `return` statements. We walk all nodes to find `return` statements, but
2522 // we only care about tail expressions when `in_block_tail` is `true`, which means that
2523 // they're in the return path of the function body.
2525 hir::ExprKind::Ret(Some(ex)) => {
2526 self.returns.push(ex);
2528 hir::ExprKind::Block(block, _) if self.in_block_tail => {
2529 self.in_block_tail = false;
2530 for stmt in block.stmts {
2531 hir::intravisit::walk_stmt(self, stmt);
2533 self.in_block_tail = true;
2534 if let Some(expr) = block.expr {
2535 self.visit_expr(expr);
2538 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
2539 self.visit_expr(then);
2540 if let Some(el) = else_opt {
2541 self.visit_expr(el);
2544 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2546 self.visit_expr(arm.body);
2549 // We need to walk to find `return`s in the entire body.
2550 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2551 _ => self.returns.push(ex),
2555 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2556 assert!(!self.in_block_tail);
2557 if body.generator_kind().is_none() {
2558 if let hir::ExprKind::Block(block, None) = body.value.kind {
2559 if block.expr.is_some() {
2560 self.in_block_tail = true;
2564 hir::intravisit::walk_body(self, body);
2568 /// Collect all the awaited expressions within the input expression.
2570 struct AwaitsVisitor {
2571 awaits: Vec<hir::HirId>,
2574 impl<'v> Visitor<'v> for AwaitsVisitor {
2575 type Map = hir::intravisit::ErasedMap<'v>;
2577 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2578 hir::intravisit::NestedVisitorMap::None
2581 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2582 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2583 self.awaits.push(id)
2585 hir::intravisit::walk_expr(self, ex)
2589 pub trait NextTypeParamName {
2590 fn next_type_param_name(&self, name: Option<&str>) -> String;
2593 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2594 fn next_type_param_name(&self, name: Option<&str>) -> String {
2595 // This is the list of possible parameter names that we might suggest.
2596 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2597 let name = name.as_deref();
2598 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2599 let used_names = self
2601 .filter_map(|p| match p.name {
2602 hir::ParamName::Plain(ident) => Some(ident.name),
2605 .collect::<Vec<_>>();
2609 .find(|n| !used_names.contains(&Symbol::intern(n)))
2610 .unwrap_or(&"ParamName")
2615 fn suggest_trait_object_return_type_alternatives(
2616 err: &mut DiagnosticBuilder<'_>,
2619 is_object_safe: bool,
2621 err.span_suggestion(
2623 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2626 Applicability::MaybeIncorrect,
2628 err.span_suggestion(
2631 "use `impl {}` as the return type if all return paths have the same type but you \
2632 want to expose only the trait in the signature",
2635 format!("impl {}", trait_obj),
2636 Applicability::MaybeIncorrect,
2639 err.span_suggestion(
2642 "use a boxed trait object if all return paths implement trait `{}`",
2645 format!("Box<dyn {}>", trait_obj),
2646 Applicability::MaybeIncorrect,