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_errors::{error_code, struct_span_err, Applicability, DiagnosticBuilder, Style};
12 use rustc_hir::def::DefKind;
13 use rustc_hir::def_id::DefId;
14 use rustc_hir::intravisit::Visitor;
15 use rustc_hir::lang_items;
16 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
17 use rustc_middle::ty::{
18 self, suggest_constraining_type_param, AdtKind, DefIdTree, Infer, InferTy, ToPredicate, Ty,
19 TyCtxt, TypeFoldable, WithConstness,
21 use rustc_middle::ty::{TypeAndMut, TypeckTables};
22 use rustc_span::symbol::{kw, sym, Ident, Symbol};
23 use rustc_span::{MultiSpan, Span, DUMMY_SP};
26 use super::InferCtxtPrivExt;
27 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
30 pub enum GeneratorInteriorOrUpvar {
31 // span of interior type
37 // This trait is public to expose the diagnostics methods to clippy.
38 pub trait InferCtxtExt<'tcx> {
39 fn suggest_restricting_param_bound(
41 err: &mut DiagnosticBuilder<'_>,
42 trait_ref: ty::PolyTraitRef<'tcx>,
46 fn suggest_borrow_on_unsized_slice(
48 code: &ObligationCauseCode<'tcx>,
49 err: &mut DiagnosticBuilder<'_>,
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<ty::TraitRef<'tcx>>,
75 fn suggest_add_reference_to_arg(
77 obligation: &PredicateObligation<'tcx>,
78 err: &mut DiagnosticBuilder<'_>,
79 trait_ref: &ty::Binder<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<ty::TraitRef<'tcx>>,
91 fn suggest_change_mut(
93 obligation: &PredicateObligation<'tcx>,
94 err: &mut DiagnosticBuilder<'_>,
95 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
99 fn suggest_semicolon_removal(
101 obligation: &PredicateObligation<'tcx>,
102 err: &mut DiagnosticBuilder<'_>,
104 trait_ref: &ty::Binder<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<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 tables: &ty::TypeckTables<'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>>,
168 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>);
170 /// Suggest to await before try: future? => future.await?
171 fn suggest_await_before_try(
173 err: &mut DiagnosticBuilder<'_>,
174 obligation: &PredicateObligation<'tcx>,
175 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
180 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
182 generics.where_clause.tail_span_for_suggestion(),
185 if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
191 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
192 /// it can also be an `impl Trait` param that needs to be decomposed to a type
193 /// param for cleaner code.
194 fn suggest_restriction(
196 generics: &hir::Generics<'tcx>,
198 err: &mut DiagnosticBuilder<'_>,
199 fn_sig: Option<&hir::FnSig<'_>>,
200 projection: Option<&ty::ProjectionTy<'_>>,
201 trait_ref: ty::PolyTraitRef<'tcx>,
202 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
204 // When we are dealing with a trait, `super_traits` will be `Some`:
205 // Given `trait T: A + B + C {}`
206 // - ^^^^^^^^^ GenericBounds
209 let span = generics.where_clause.span_for_predicates_or_empty_place();
210 if span.from_expansion() || span.desugaring_kind().is_some() {
213 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
214 if let Some((bound_str, fn_sig)) =
215 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind {
216 // Shenanigans to get the `Trait` from the `impl Trait`.
217 ty::Param(param) => {
218 // `fn foo(t: impl Trait)`
219 // ^^^^^ get this string
220 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
225 // We know we have an `impl Trait` that doesn't satisfy a required projection.
227 // Find all of the ocurrences of `impl Trait` for `Trait` in the function arguments'
228 // types. There should be at least one, but there might be *more* than one. In that
229 // case we could just ignore it and try to identify which one needs the restriction,
230 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
232 let mut ty_spans = vec![];
233 let impl_trait_str = format!("impl {}", bound_str);
234 for input in fn_sig.decl.inputs {
235 if let hir::TyKind::Path(hir::QPath::Resolved(
237 hir::Path { segments: [segment], .. },
240 if segment.ident.as_str() == impl_trait_str.as_str() {
241 // `fn foo(t: impl Trait)`
242 // ^^^^^^^^^^ get this to suggest `T` instead
244 // There might be more than one `impl Trait`.
245 ty_spans.push(input.span);
250 let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
251 // The type param `T: Trait` we will suggest to introduce.
252 let type_param = format!("{}: {}", type_param_name, bound_str);
254 // FIXME: modify the `trait_ref` instead of string shenanigans.
255 // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
256 let pred = trait_ref.without_const().to_predicate(tcx).to_string();
257 let pred = pred.replace(&impl_trait_str, &type_param_name);
262 .filter(|p| match p.kind {
263 hir::GenericParamKind::Type {
264 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
271 // `fn foo(t: impl Trait)`
272 // ^ suggest `<T: Trait>` here
273 None => (generics.span, format!("<{}>", type_param)),
274 // `fn foo<A>(t: impl Trait)`
275 // ^^^ suggest `<A, T: Trait>` here
277 param.bounds_span().unwrap_or(param.span).shrink_to_hi(),
278 format!(", {}", type_param),
281 // `fn foo(t: impl Trait)`
282 // ^ suggest `where <T as Trait>::A: Bound`
283 predicate_constraint(generics, pred),
285 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
287 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
288 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
289 // `fn foo(t: impl Trait<A: Bound>)` instead.
290 err.multipart_suggestion(
291 "introduce a type parameter with a trait bound instead of using `impl Trait`",
293 Applicability::MaybeIncorrect,
296 // Trivial case: `T` needs an extra bound: `T: Bound`.
297 let (sp, suggestion) = match super_traits {
298 None => predicate_constraint(
300 trait_ref.without_const().to_predicate(tcx).to_string(),
302 Some((ident, bounds)) => match bounds {
304 bound.span().shrink_to_hi(),
305 format!(" + {}", trait_ref.print_only_trait_path().to_string()),
308 ident.span.shrink_to_hi(),
309 format!(": {}", trait_ref.print_only_trait_path().to_string()),
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 { 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 { 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();
440 let constraint = trait_ref.print_only_trait_path().to_string();
441 if suggest_constraining_type_param(
447 Some(trait_ref.def_id()),
453 hir::Node::Crate(..) => return,
458 hir_id = self.tcx.hir().get_parent_item(hir_id);
462 /// When after several dereferencing, the reference satisfies the trait
463 /// binding. This function provides dereference suggestion for this
464 /// specific situation.
465 fn suggest_dereferences(
467 obligation: &PredicateObligation<'tcx>,
468 err: &mut DiagnosticBuilder<'tcx>,
469 trait_ref: &ty::PolyTraitRef<'tcx>,
472 // It only make sense when suggesting dereferences for arguments
476 let param_env = obligation.param_env;
477 let body_id = obligation.cause.body_id;
478 let span = obligation.cause.span;
479 let real_trait_ref = match &obligation.cause.code {
480 ObligationCauseCode::ImplDerivedObligation(cause)
481 | ObligationCauseCode::DerivedObligation(cause)
482 | ObligationCauseCode::BuiltinDerivedObligation(cause) => &cause.parent_trait_ref,
485 let real_ty = match real_trait_ref.self_ty().no_bound_vars() {
490 if let ty::Ref(region, base_ty, mutbl) = real_ty.kind {
491 let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty);
492 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
494 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
496 self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_ref, ty);
497 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
500 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
501 // Don't care about `&mut` because `DerefMut` is used less
502 // often and user will not expect autoderef happens.
503 if src.starts_with("&") && !src.starts_with("&mut ") {
504 let derefs = "*".repeat(steps);
507 "consider adding dereference here",
508 format!("&{}{}", derefs, &src[1..]),
509 Applicability::MachineApplicable,
518 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
519 /// suggestion to borrow the initializer in order to use have a slice instead.
520 fn suggest_borrow_on_unsized_slice(
522 code: &ObligationCauseCode<'tcx>,
523 err: &mut DiagnosticBuilder<'_>,
525 if let &ObligationCauseCode::VariableType(hir_id) = code {
526 let parent_node = self.tcx.hir().get_parent_node(hir_id);
527 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
528 if let Some(ref expr) = local.init {
529 if let hir::ExprKind::Index(_, _) = expr.kind {
530 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
533 "consider borrowing here",
534 format!("&{}", snippet),
535 Applicability::MachineApplicable,
544 /// Given a closure's `DefId`, return the given name of the closure.
546 /// This doesn't account for reassignments, but it's only used for suggestions.
550 err: &mut DiagnosticBuilder<'_>,
552 ) -> Option<String> {
554 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
555 // Get the local name of this closure. This can be inaccurate because
556 // of the possibility of reassignment, but this should be good enough.
558 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
559 Some(format!("{}", name))
568 let hir = self.tcx.hir();
569 let hir_id = hir.as_local_hir_id(def_id.as_local()?);
570 let parent_node = hir.get_parent_node(hir_id);
571 match hir.find(parent_node) {
572 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
573 get_name(err, &local.pat.kind)
575 // Different to previous arm because one is `&hir::Local` and the other
576 // is `P<hir::Local>`.
577 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
582 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
583 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
584 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
587 obligation: &PredicateObligation<'tcx>,
588 err: &mut DiagnosticBuilder<'_>,
589 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
592 let self_ty = match trait_ref.self_ty().no_bound_vars() {
597 let (def_id, output_ty, callable) = match self_ty.kind {
598 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
599 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
602 let msg = format!("use parentheses to call the {}", callable);
604 // `mk_trait_obligation_with_new_self_ty` only works for types with no escaping bound
605 // variables, so bail out if we have any.
606 let output_ty = match output_ty.no_bound_vars() {
612 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_ref, output_ty);
614 match self.evaluate_obligation(&new_obligation) {
616 EvaluationResult::EvaluatedToOk
617 | EvaluationResult::EvaluatedToOkModuloRegions
618 | EvaluationResult::EvaluatedToAmbig,
622 let hir = self.tcx.hir();
623 // Get the name of the callable and the arguments to be used in the suggestion.
624 let (snippet, sugg) = match hir.get_if_local(def_id) {
625 Some(hir::Node::Expr(hir::Expr {
626 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
629 err.span_label(*span, "consider calling this closure");
630 let name = match self.get_closure_name(def_id, err, &msg) {
634 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
635 let sugg = format!("({})", args);
636 (format!("{}{}", name, sugg), sugg)
638 Some(hir::Node::Item(hir::Item {
640 kind: hir::ItemKind::Fn(.., body_id),
643 err.span_label(ident.span, "consider calling this function");
644 let body = hir.body(*body_id);
648 .map(|arg| match &arg.pat.kind {
649 hir::PatKind::Binding(_, _, ident, None)
650 // FIXME: provide a better suggestion when encountering `SelfLower`, it
651 // should suggest a method call.
652 if ident.name != kw::SelfLower => ident.to_string(),
653 _ => "_".to_string(),
657 let sugg = format!("({})", args);
658 (format!("{}{}", ident, sugg), sugg)
663 // When the obligation error has been ensured to have been caused by
664 // an argument, the `obligation.cause.span` points at the expression
665 // of the argument, so we can provide a suggestion. This is signaled
666 // by `points_at_arg`. Otherwise, we give a more general note.
667 err.span_suggestion_verbose(
668 obligation.cause.span.shrink_to_hi(),
671 Applicability::HasPlaceholders,
674 err.help(&format!("{}: `{}`", msg, snippet));
678 fn suggest_add_reference_to_arg(
680 obligation: &PredicateObligation<'tcx>,
681 err: &mut DiagnosticBuilder<'_>,
682 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
684 has_custom_message: bool,
690 let span = obligation.cause.span;
691 let param_env = obligation.param_env;
692 let trait_ref = trait_ref.skip_binder();
694 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
695 // Try to apply the original trait binding obligation by borrowing.
696 let self_ty = trait_ref.self_ty();
697 let found = self_ty.to_string();
698 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
699 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
700 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
701 let new_obligation = Obligation::new(
702 ObligationCause::dummy(),
704 new_trait_ref.without_const().to_predicate(self.tcx),
707 if self.predicate_must_hold_modulo_regions(&new_obligation) {
708 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
709 // We have a very specific type of error, where just borrowing this argument
710 // might solve the problem. In cases like this, the important part is the
711 // original type obligation, not the last one that failed, which is arbitrary.
712 // Because of this, we modify the error to refer to the original obligation and
713 // return early in the caller.
716 "the trait bound `{}: {}` is not satisfied",
718 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
720 if has_custom_message {
723 err.message = vec![(msg, Style::NoStyle)];
725 if snippet.starts_with('&') {
726 // This is already a literal borrow and the obligation is failing
727 // somewhere else in the obligation chain. Do not suggest non-sense.
733 "expected an implementor of trait `{}`",
734 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
738 // This if is to prevent a special edge-case
739 if !span.from_expansion() {
740 // We don't want a borrowing suggestion on the fields in structs,
743 // the_foos: Vec<Foo>
749 "consider borrowing here",
750 format!("&{}", snippet),
751 Applicability::MaybeIncorrect,
761 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
762 /// suggest removing these references until we reach a type that implements the trait.
763 fn suggest_remove_reference(
765 obligation: &PredicateObligation<'tcx>,
766 err: &mut DiagnosticBuilder<'_>,
767 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
769 let span = obligation.cause.span;
771 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
773 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
774 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
775 // Do not suggest removal of borrow from type arguments.
779 let mut suggested_ty = match trait_ref.self_ty().no_bound_vars() {
784 for refs_remaining in 0..refs_number {
785 if let ty::Ref(_, inner_ty, _) = suggested_ty.kind {
786 suggested_ty = inner_ty;
788 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
789 obligation.param_env,
794 if self.predicate_may_hold(&new_obligation) {
799 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
801 let remove_refs = refs_remaining + 1;
803 let msg = if remove_refs == 1 {
804 "consider removing the leading `&`-reference".to_string()
806 format!("consider removing {} leading `&`-references", remove_refs)
809 err.span_suggestion_short(
813 Applicability::MachineApplicable,
824 /// Check if the trait bound is implemented for a different mutability and note it in the
826 fn suggest_change_mut(
828 obligation: &PredicateObligation<'tcx>,
829 err: &mut DiagnosticBuilder<'_>,
830 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
833 let span = obligation.cause.span;
834 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
836 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
837 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
838 // Do not suggest removal of borrow from type arguments.
841 let trait_ref = self.resolve_vars_if_possible(trait_ref);
842 if trait_ref.has_infer_types_or_consts() {
843 // Do not ICE while trying to find if a reborrow would succeed on a trait with
844 // unresolved bindings.
848 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
849 if region.is_late_bound() || t_type.has_escaping_bound_vars() {
850 // Avoid debug assertion in `mk_obligation_for_def_id`.
852 // If the self type has escaping bound vars then it's not
853 // going to be the type of an expression, so the suggestion
854 // probably won't apply anyway.
858 let suggested_ty = match mutability {
859 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
860 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
863 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
864 obligation.param_env,
868 let suggested_ty_would_satisfy_obligation = self
869 .evaluate_obligation_no_overflow(&new_obligation)
870 .must_apply_modulo_regions();
871 if suggested_ty_would_satisfy_obligation {
876 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
877 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
878 err.span_suggestion_verbose(
880 "consider changing this borrow's mutability",
882 Applicability::MachineApplicable,
886 "`{}` is implemented for `{:?}`, but not for `{:?}`",
887 trait_ref.print_only_trait_path(),
889 trait_ref.skip_binder().self_ty(),
897 fn suggest_semicolon_removal(
899 obligation: &PredicateObligation<'tcx>,
900 err: &mut DiagnosticBuilder<'_>,
902 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
905 |ty: ty::Binder<Ty<'_>>| ty.skip_binder().kind == ty::Tuple(ty::List::empty());
907 let hir = self.tcx.hir();
908 let parent_node = hir.get_parent_node(obligation.cause.body_id);
909 let node = hir.find(parent_node);
910 if let Some(hir::Node::Item(hir::Item {
911 kind: hir::ItemKind::Fn(sig, _, body_id), ..
914 let body = hir.body(*body_id);
915 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
916 if sig.decl.output.span().overlaps(span)
917 && blk.expr.is_none()
918 && is_empty_tuple(trait_ref.self_ty())
920 // FIXME(estebank): When encountering a method with a trait
921 // bound not satisfied in the return type with a body that has
922 // no return, suggest removal of semicolon on last statement.
923 // Once that is added, close #54771.
924 if let Some(ref stmt) = blk.stmts.last() {
925 let sp = self.tcx.sess.source_map().end_point(stmt.span);
926 err.span_label(sp, "consider removing this semicolon");
933 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
934 let hir = self.tcx.hir();
935 let parent_node = hir.get_parent_node(obligation.cause.body_id);
936 let sig = match hir.find(parent_node) {
937 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) => sig,
941 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
944 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
945 /// applicable and signal that the error has been expanded appropriately and needs to be
947 fn suggest_impl_trait(
949 err: &mut DiagnosticBuilder<'_>,
951 obligation: &PredicateObligation<'tcx>,
952 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
954 match obligation.cause.code.peel_derives() {
955 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
956 ObligationCauseCode::SizedReturnType => {}
960 let hir = self.tcx.hir();
961 let parent_node = hir.get_parent_node(obligation.cause.body_id);
962 let node = hir.find(parent_node);
963 let (sig, body_id) = if let Some(hir::Node::Item(hir::Item {
964 kind: hir::ItemKind::Fn(sig, _, body_id),
972 let body = hir.body(*body_id);
973 let trait_ref = self.resolve_vars_if_possible(trait_ref);
974 let ty = trait_ref.skip_binder().self_ty();
975 let is_object_safe = match ty.kind {
976 ty::Dynamic(predicates, _) => {
977 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
980 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
982 // We only want to suggest `impl Trait` to `dyn Trait`s.
983 // For example, `fn foo() -> str` needs to be filtered out.
987 let ret_ty = if let hir::FnRetTy::Return(ret_ty) = sig.decl.output {
993 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
994 // cases like `fn foo() -> (dyn Trait, i32) {}`.
995 // Recursively look for `TraitObject` types and if there's only one, use that span to
996 // suggest `impl Trait`.
998 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
999 // otherwise suggest using `Box<dyn Trait>` or an enum.
1000 let mut visitor = ReturnsVisitor::default();
1001 visitor.visit_body(&body);
1003 let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
1005 let mut ret_types = visitor
1008 .filter_map(|expr| tables.node_type_opt(expr.hir_id))
1009 .map(|ty| self.resolve_vars_if_possible(&ty));
1010 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1012 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1014 let ty = self.resolve_vars_if_possible(&ty);
1016 !matches!(ty.kind, ty::Error(_))
1017 && last_ty.map_or(true, |last_ty| {
1018 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1019 // *after* in the dependency graph.
1020 match (&ty.kind, &last_ty.kind) {
1021 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1022 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1023 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1025 Infer(InferTy::FreshFloatTy(_)),
1026 Infer(InferTy::FreshFloatTy(_)),
1031 (Some(ty), same, only_never_return && matches!(ty.kind, ty::Never))
1034 let all_returns_conform_to_trait =
1035 if let Some(ty_ret_ty) = tables.node_type_opt(ret_ty.hir_id) {
1036 match ty_ret_ty.kind {
1037 ty::Dynamic(predicates, _) => {
1038 let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
1039 let param_env = ty::ParamEnv::empty();
1041 || ret_types.all(|returned_ty| {
1042 predicates.iter().all(|predicate| {
1043 let pred = predicate.with_self_ty(self.tcx, returned_ty);
1044 let obl = Obligation::new(cause.clone(), param_env, pred);
1045 self.predicate_may_hold(&obl)
1055 let sm = self.tcx.sess.source_map();
1056 let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
1057 // Verify that we're dealing with a return `dyn Trait`
1058 ret_ty.span.overlaps(span),
1060 sm.span_to_snippet(ret_ty.span),
1061 // If any of the return types does not conform to the trait, then we can't
1062 // suggest `impl Trait` nor trait objects: it is a type mismatch error.
1063 all_returns_conform_to_trait,
1069 err.code(error_code!(E0746));
1070 err.set_primary_message("return type cannot have an unboxed trait object");
1071 err.children.clear();
1072 let impl_trait_msg = "for information on `impl Trait`, see \
1073 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1074 #returning-types-that-implement-traits>";
1075 let trait_obj_msg = "for information on trait objects, see \
1076 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1077 #using-trait-objects-that-allow-for-values-of-different-types>";
1078 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1079 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet[..] };
1080 if only_never_return {
1081 // No return paths, probably using `panic!()` or similar.
1082 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1083 suggest_trait_object_return_type_alternatives(
1089 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1090 // Suggest `-> impl Trait`.
1091 err.span_suggestion(
1094 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1095 which implements `{1}`",
1098 format!("impl {}", trait_obj),
1099 Applicability::MachineApplicable,
1101 err.note(impl_trait_msg);
1104 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1105 // Get all the return values and collect their span and suggestion.
1106 if let Some(mut suggestions) = visitor
1110 let snip = sm.span_to_snippet(expr.span).ok()?;
1111 Some((expr.span, format!("Box::new({})", snip)))
1113 .collect::<Option<Vec<_>>>()
1115 // Add the suggestion for the return type.
1116 suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
1117 err.multipart_suggestion(
1118 "return a boxed trait object instead",
1120 Applicability::MaybeIncorrect,
1124 // This is currently not possible to trigger because E0038 takes precedence, but
1125 // leave it in for completeness in case anything changes in an earlier stage.
1127 "if trait `{}` was object safe, you could return a trait object",
1131 err.note(trait_obj_msg);
1133 "if all the returned values were of the same type you could use `impl {}` as the \
1137 err.note(impl_trait_msg);
1138 err.note("you can create a new `enum` with a variant for each returned type");
1143 fn point_at_returns_when_relevant(
1145 err: &mut DiagnosticBuilder<'_>,
1146 obligation: &PredicateObligation<'tcx>,
1148 match obligation.cause.code.peel_derives() {
1149 ObligationCauseCode::SizedReturnType => {}
1153 let hir = self.tcx.hir();
1154 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1155 let node = hir.find(parent_node);
1156 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1159 let body = hir.body(*body_id);
1160 // Point at all the `return`s in the function as they have failed trait bounds.
1161 let mut visitor = ReturnsVisitor::default();
1162 visitor.visit_body(&body);
1163 let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
1164 for expr in &visitor.returns {
1165 if let Some(returned_ty) = tables.node_type_opt(expr.hir_id) {
1166 let ty = self.resolve_vars_if_possible(&returned_ty);
1167 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1173 fn report_closure_arg_mismatch(
1176 found_span: Option<Span>,
1177 expected_ref: ty::PolyTraitRef<'tcx>,
1178 found: ty::PolyTraitRef<'tcx>,
1179 ) -> DiagnosticBuilder<'tcx> {
1180 crate fn build_fn_sig_string<'tcx>(
1182 trait_ref: ty::TraitRef<'tcx>,
1184 let inputs = trait_ref.substs.type_at(1);
1185 let sig = if let ty::Tuple(inputs) = inputs.kind {
1187 inputs.iter().map(|k| k.expect_ty()),
1188 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1190 hir::Unsafety::Normal,
1191 ::rustc_target::spec::abi::Abi::Rust,
1195 ::std::iter::once(inputs),
1196 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1198 hir::Unsafety::Normal,
1199 ::rustc_target::spec::abi::Abi::Rust,
1202 ty::Binder::bind(sig).to_string()
1205 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1206 let mut err = struct_span_err!(
1210 "type mismatch in {} arguments",
1211 if argument_is_closure { "closure" } else { "function" }
1214 let found_str = format!(
1215 "expected signature of `{}`",
1216 build_fn_sig_string(self.tcx, found.skip_binder())
1218 err.span_label(span, found_str);
1220 let found_span = found_span.unwrap_or(span);
1221 let expected_str = format!(
1222 "found signature of `{}`",
1223 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1225 err.span_label(found_span, expected_str);
1230 fn suggest_fully_qualified_path(
1232 err: &mut DiagnosticBuilder<'_>,
1237 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1238 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1240 "{}s cannot be accessed directly on a `trait`, they can only be \
1241 accessed through a specific `impl`",
1242 assoc_item.kind.as_def_kind().descr(def_id)
1244 err.span_suggestion(
1246 "use the fully qualified path to an implementation",
1247 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1248 Applicability::HasPlaceholders,
1254 /// Adds an async-await specific note to the diagnostic when the future does not implement
1255 /// an auto trait because of a captured type.
1258 /// note: future does not implement `Qux` as this value is used across an await
1259 /// --> $DIR/issue-64130-3-other.rs:17:5
1261 /// LL | let x = Foo;
1262 /// | - has type `Foo`
1263 /// LL | baz().await;
1264 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1266 /// | - `x` is later dropped here
1269 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1270 /// is "replaced" with a different message and a more specific error.
1273 /// error: future cannot be sent between threads safely
1274 /// --> $DIR/issue-64130-2-send.rs:21:5
1276 /// LL | fn is_send<T: Send>(t: T) { }
1277 /// | ---- required by this bound in `is_send`
1279 /// LL | is_send(bar());
1280 /// | ^^^^^^^ future returned by `bar` is not send
1282 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1283 /// implemented for `Foo`
1284 /// note: future is not send as this value is used across an await
1285 /// --> $DIR/issue-64130-2-send.rs:15:5
1287 /// LL | let x = Foo;
1288 /// | - has type `Foo`
1289 /// LL | baz().await;
1290 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1292 /// | - `x` is later dropped here
1295 /// Returns `true` if an async-await specific note was added to the diagnostic.
1296 fn maybe_note_obligation_cause_for_async_await(
1298 err: &mut DiagnosticBuilder<'_>,
1299 obligation: &PredicateObligation<'tcx>,
1302 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1303 obligation.cause.span={:?}",
1304 obligation.predicate, obligation.cause.span
1306 let hir = self.tcx.hir();
1308 // Attempt to detect an async-await error by looking at the obligation causes, looking
1309 // for a generator to be present.
1311 // When a future does not implement a trait because of a captured type in one of the
1312 // generators somewhere in the call stack, then the result is a chain of obligations.
1314 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
1315 // future is passed as an argument to a function C which requires a `Send` type, then the
1316 // chain looks something like this:
1318 // - `BuiltinDerivedObligation` with a generator witness (B)
1319 // - `BuiltinDerivedObligation` with a generator (B)
1320 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1321 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1322 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1323 // - `BuiltinDerivedObligation` with a generator witness (A)
1324 // - `BuiltinDerivedObligation` with a generator (A)
1325 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1326 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1327 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1328 // - `BindingObligation` with `impl_send (Send requirement)
1330 // The first obligation in the chain is the most useful and has the generator that captured
1331 // the type. The last generator (`outer_generator` below) has information about where the
1332 // bound was introduced. At least one generator should be present for this diagnostic to be
1334 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind() {
1335 ty::PredicateKind::Trait(p, _) => {
1336 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty()))
1340 let mut generator = None;
1341 let mut outer_generator = None;
1342 let mut next_code = Some(&obligation.cause.code);
1343 while let Some(code) = next_code {
1344 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1346 ObligationCauseCode::DerivedObligation(derived_obligation)
1347 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1348 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1349 let ty = derived_obligation.parent_trait_ref.skip_binder().self_ty();
1351 "maybe_note_obligation_cause_for_async_await: \
1352 parent_trait_ref={:?} self_ty.kind={:?}",
1353 derived_obligation.parent_trait_ref, ty.kind
1357 ty::Generator(did, ..) => {
1358 generator = generator.or(Some(did));
1359 outer_generator = Some(did);
1361 ty::GeneratorWitness(..) => {}
1362 _ if generator.is_none() => {
1363 trait_ref = Some(derived_obligation.parent_trait_ref.skip_binder());
1364 target_ty = Some(ty);
1369 next_code = Some(derived_obligation.parent_code.as_ref());
1375 // Only continue if a generator was found.
1377 "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
1379 generator, trait_ref, target_ty
1381 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1382 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1383 (generator_did, trait_ref, target_ty)
1388 let span = self.tcx.def_span(generator_did);
1390 // Do not ICE on closure typeck (#66868).
1391 if !generator_did.is_local() {
1395 // Get the tables from the infcx if the generator is the function we are
1396 // currently type-checking; otherwise, get them by performing a query.
1397 // This is needed to avoid cycles.
1398 let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
1399 let generator_did_root = self.tcx.closure_base_def_id(generator_did);
1401 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1402 generator_did_root={:?} in_progress_tables.hir_owner={:?} span={:?}",
1405 in_progress_tables.as_ref().map(|t| t.hir_owner),
1409 let tables: &TypeckTables<'tcx> = match &in_progress_tables {
1410 Some(t) if t.hir_owner.to_def_id() == generator_did_root => t,
1412 query_tables = self.tcx.typeck_tables_of(generator_did.expect_local());
1417 let generator_body = generator_did
1419 .map(|def_id| hir.as_local_hir_id(def_id))
1420 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1421 .map(|body_id| hir.body(body_id));
1422 let mut visitor = AwaitsVisitor::default();
1423 if let Some(body) = generator_body {
1424 visitor.visit_body(body);
1426 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1428 // Look for a type inside the generator interior that matches the target type to get
1430 let target_ty_erased = self.tcx.erase_regions(&target_ty);
1431 let ty_matches = |ty| -> bool {
1432 // Careful: the regions for types that appear in the
1433 // generator interior are not generally known, so we
1434 // want to erase them when comparing (and anyway,
1435 // `Send` and other bounds are generally unaffected by
1436 // the choice of region). When erasing regions, we
1437 // also have to erase late-bound regions. This is
1438 // because the types that appear in the generator
1439 // interior generally contain "bound regions" to
1440 // represent regions that are part of the suspended
1441 // generator frame. Bound regions are preserved by
1442 // `erase_regions` and so we must also call
1443 // `erase_late_bound_regions`.
1444 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(ty));
1445 let ty_erased = self.tcx.erase_regions(&ty_erased);
1446 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1448 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1449 target_ty_erased={:?} eq={:?}",
1450 ty_erased, target_ty_erased, eq
1455 let mut interior_or_upvar_span = None;
1456 let mut interior_extra_info = None;
1458 if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) {
1459 interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| {
1460 let upvar_ty = tables.node_type(*upvar_id);
1461 let upvar_ty = self.resolve_vars_if_possible(&upvar_ty);
1462 if ty_matches(&upvar_ty) {
1463 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
1471 .generator_interior_types
1473 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| ty_matches(ty))
1475 // Check to see if any awaited expressions have the target type.
1476 let from_awaited_ty = visitor
1479 .map(|id| hir.expect_expr(id))
1480 .find(|await_expr| {
1481 let ty = tables.expr_ty_adjusted(&await_expr);
1483 "maybe_note_obligation_cause_for_async_await: await_expr={:?}",
1488 .map(|expr| expr.span);
1489 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1492 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1493 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1497 "maybe_note_obligation_cause_for_async_await: interior_or_upvar={:?} \
1498 generator_interior_types={:?}",
1499 interior_or_upvar_span, tables.generator_interior_types
1501 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1502 self.note_obligation_cause_for_async_await(
1504 interior_or_upvar_span,
1505 interior_extra_info,
1520 /// Unconditionally adds the diagnostic note described in
1521 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1522 fn note_obligation_cause_for_async_await(
1524 err: &mut DiagnosticBuilder<'_>,
1525 interior_or_upvar_span: GeneratorInteriorOrUpvar,
1526 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1527 inner_generator_body: Option<&hir::Body<'tcx>>,
1528 outer_generator: Option<DefId>,
1529 trait_ref: ty::TraitRef<'tcx>,
1530 target_ty: Ty<'tcx>,
1531 tables: &ty::TypeckTables<'tcx>,
1532 obligation: &PredicateObligation<'tcx>,
1533 next_code: Option<&ObligationCauseCode<'tcx>>,
1535 let source_map = self.tcx.sess.source_map();
1537 let is_async = inner_generator_body
1538 .and_then(|body| body.generator_kind())
1539 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1541 let (await_or_yield, an_await_or_yield) =
1542 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1543 let future_or_generator = if is_async { "future" } else { "generator" };
1545 // Special case the primary error message when send or sync is the trait that was
1547 let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
1548 let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
1549 let hir = self.tcx.hir();
1550 let trait_explanation = if is_send || is_sync {
1551 let (trait_name, trait_verb) =
1552 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1555 err.set_primary_message(format!(
1556 "{} cannot be {} between threads safely",
1557 future_or_generator, trait_verb
1560 let original_span = err.span.primary_span().unwrap();
1561 let mut span = MultiSpan::from_span(original_span);
1563 let message = outer_generator
1564 .and_then(|generator_did| {
1565 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1566 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1567 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1569 .parent(generator_did)
1570 .and_then(|parent_did| parent_did.as_local())
1571 .map(|parent_did| hir.as_local_hir_id(parent_did))
1572 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1574 format!("future returned by `{}` is not {}", name, trait_name)
1576 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1577 format!("future created by async block is not {}", trait_name)
1579 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1580 format!("future created by async closure is not {}", trait_name)
1584 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1586 span.push_span_label(original_span, message);
1589 format!("is not {}", trait_name)
1591 format!("does not implement `{}`", trait_ref.print_only_trait_path())
1594 let mut explain_yield = |interior_span: Span,
1596 scope_span: Option<Span>| {
1597 let mut span = MultiSpan::from_span(yield_span);
1598 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1599 span.push_span_label(
1601 format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
1603 // If available, use the scope span to annotate the drop location.
1604 if let Some(scope_span) = scope_span {
1605 span.push_span_label(
1606 source_map.end_point(scope_span),
1607 format!("`{}` is later dropped here", snippet),
1611 span.push_span_label(
1613 format!("has type `{}` which {}", target_ty, trait_explanation),
1619 "{} {} as this value is used across {}",
1620 future_or_generator, trait_explanation, an_await_or_yield
1624 match interior_or_upvar_span {
1625 GeneratorInteriorOrUpvar::Interior(interior_span) => {
1626 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
1627 if let Some(await_span) = from_awaited_ty {
1628 // The type causing this obligation is one being awaited at await_span.
1629 let mut span = MultiSpan::from_span(await_span);
1630 span.push_span_label(
1633 "await occurs here on type `{}`, which {}",
1634 target_ty, trait_explanation
1640 "future {not_trait} as it awaits another future which {not_trait}",
1641 not_trait = trait_explanation
1645 // Look at the last interior type to get a span for the `.await`.
1647 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1648 tables.generator_interior_types
1650 explain_yield(interior_span, yield_span, scope_span);
1653 if let Some(expr_id) = expr {
1654 let expr = hir.expect_expr(expr_id);
1655 debug!("target_ty evaluated from {:?}", expr);
1657 let parent = hir.get_parent_node(expr_id);
1658 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1659 let parent_span = hir.span(parent);
1660 let parent_did = parent.owner.to_def_id();
1663 // fn foo(&self) -> i32 {}
1666 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1669 let is_region_borrow = tables
1670 .expr_adjustments(expr)
1672 .any(|adj| adj.is_region_borrow());
1675 // struct Foo(*const u8);
1676 // bar(Foo(std::ptr::null())).await;
1677 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1679 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1680 let is_raw_borrow_inside_fn_like_call =
1681 match self.tcx.def_kind(parent_did) {
1682 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
1686 if (tables.is_method_call(e) && is_region_borrow)
1687 || is_raw_borrow_inside_fn_like_call
1691 "consider moving this into a `let` \
1692 binding to create a shorter lived borrow",
1699 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
1700 let mut span = MultiSpan::from_span(upvar_span);
1701 span.push_span_label(
1703 format!("has type `{}` which {}", target_ty, trait_explanation),
1705 err.span_note(span, &format!("captured value {}", trait_explanation));
1709 // Add a note for the item obligation that remains - normally a note pointing to the
1710 // bound that introduced the obligation (e.g. `T: Send`).
1711 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1712 self.note_obligation_cause_code(
1714 &obligation.predicate,
1720 fn note_obligation_cause_code<T>(
1722 err: &mut DiagnosticBuilder<'_>,
1724 cause_code: &ObligationCauseCode<'tcx>,
1725 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1731 ObligationCauseCode::ExprAssignable
1732 | ObligationCauseCode::MatchExpressionArm { .. }
1733 | ObligationCauseCode::Pattern { .. }
1734 | ObligationCauseCode::IfExpression { .. }
1735 | ObligationCauseCode::IfExpressionWithNoElse
1736 | ObligationCauseCode::MainFunctionType
1737 | ObligationCauseCode::StartFunctionType
1738 | ObligationCauseCode::IntrinsicType
1739 | ObligationCauseCode::MethodReceiver
1740 | ObligationCauseCode::ReturnNoExpression
1741 | ObligationCauseCode::MiscObligation => {}
1742 ObligationCauseCode::SliceOrArrayElem => {
1743 err.note("slice and array elements must have `Sized` type");
1745 ObligationCauseCode::TupleElem => {
1746 err.note("only the last element of a tuple may have a dynamically sized type");
1748 ObligationCauseCode::ProjectionWf(data) => {
1749 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1751 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1753 "required so that reference `{}` does not outlive its referent",
1757 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1759 "required so that the lifetime bound of `{}` for `{}` is satisfied",
1763 ObligationCauseCode::ItemObligation(item_def_id) => {
1764 let item_name = tcx.def_path_str(item_def_id);
1765 let msg = format!("required by `{}`", item_name);
1766 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1767 let sp = tcx.sess.source_map().guess_head_span(sp);
1768 err.span_label(sp, &msg);
1773 ObligationCauseCode::BindingObligation(item_def_id, span) => {
1774 let item_name = tcx.def_path_str(item_def_id);
1775 let msg = format!("required by this bound in `{}`", item_name);
1776 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1777 let sm = tcx.sess.source_map();
1779 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
1780 (Ok(l), Ok(r)) => l.line == r.line,
1783 if !ident.span.overlaps(span) && !same_line {
1784 err.span_label(ident.span, "required by a bound in this");
1787 if span != DUMMY_SP {
1788 err.span_label(span, &msg);
1793 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1795 "required for the cast to the object type `{}`",
1796 self.ty_to_string(object_ty)
1799 ObligationCauseCode::Coercion { source: _, target } => {
1800 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1802 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
1804 "the `Copy` trait is required because the repeated element will be copied",
1806 if suggest_const_in_array_repeat_expressions {
1808 "this array initializer can be evaluated at compile-time, see issue \
1809 #49147 <https://github.com/rust-lang/rust/issues/49147> \
1810 for more information",
1812 if tcx.sess.opts.unstable_features.is_nightly_build() {
1814 "add `#![feature(const_in_array_repeat_expressions)]` to the \
1815 crate attributes to enable",
1820 ObligationCauseCode::VariableType(_) => {
1821 err.note("all local variables must have a statically known size");
1822 if !self.tcx.features().unsized_locals {
1823 err.help("unsized locals are gated as an unstable feature");
1826 ObligationCauseCode::SizedArgumentType(sp) => {
1827 if let Some(span) = sp {
1828 err.span_suggestion_verbose(
1829 span.shrink_to_lo(),
1830 "function arguments must have a statically known size, borrowed types \
1831 always have a known size",
1833 Applicability::MachineApplicable,
1836 err.note("all function arguments must have a statically known size");
1838 if tcx.sess.opts.unstable_features.is_nightly_build()
1839 && !self.tcx.features().unsized_locals
1841 err.help("unsized locals are gated as an unstable feature");
1844 ObligationCauseCode::SizedReturnType => {
1845 err.note("the return type of a function must have a statically known size");
1847 ObligationCauseCode::SizedYieldType => {
1848 err.note("the yield type of a generator must have a statically known size");
1850 ObligationCauseCode::AssignmentLhsSized => {
1851 err.note("the left-hand-side of an assignment must have a statically known size");
1853 ObligationCauseCode::TupleInitializerSized => {
1854 err.note("tuples must have a statically known size to be initialized");
1856 ObligationCauseCode::StructInitializerSized => {
1857 err.note("structs must have a statically known size to be initialized");
1859 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => match *item {
1860 AdtKind::Struct => {
1863 "the last field of a packed struct may only have a \
1864 dynamically sized type if it does not need drop to be run",
1868 "only the last field of a struct may have a dynamically sized type",
1873 err.note("no field of a union may have a dynamically sized type");
1876 err.note("no field of an enum variant may have a dynamically sized type");
1879 ObligationCauseCode::ConstSized => {
1880 err.note("constant expressions must have a statically known size");
1882 ObligationCauseCode::InlineAsmSized => {
1883 err.note("all inline asm arguments must have a statically known size");
1885 ObligationCauseCode::ConstPatternStructural => {
1886 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
1888 ObligationCauseCode::SharedStatic => {
1889 err.note("shared static variables must have a type that implements `Sync`");
1891 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1892 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1893 let ty = parent_trait_ref.skip_binder().self_ty();
1894 err.note(&format!("required because it appears within the type `{}`", ty));
1895 obligated_types.push(ty);
1897 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
1898 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1899 self.note_obligation_cause_code(
1907 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1908 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1910 "required because of the requirements on the impl of `{}` for `{}`",
1911 parent_trait_ref.print_only_trait_path(),
1912 parent_trait_ref.skip_binder().self_ty()
1914 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
1915 self.note_obligation_cause_code(
1922 ObligationCauseCode::DerivedObligation(ref data) => {
1923 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1924 let parent_predicate = parent_trait_ref.without_const().to_predicate(tcx);
1925 self.note_obligation_cause_code(
1932 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1934 "the requirement `{}` appears on the impl method \
1935 but not on the corresponding trait method",
1939 ObligationCauseCode::CompareImplTypeObligation { .. } => {
1941 "the requirement `{}` appears on the associated impl type \
1942 but not on the corresponding associated trait type",
1946 ObligationCauseCode::CompareImplConstObligation => {
1948 "the requirement `{}` appears on the associated impl constant \
1949 but not on the corresponding associated trait constant",
1953 ObligationCauseCode::ReturnType
1954 | ObligationCauseCode::ReturnValue(_)
1955 | ObligationCauseCode::BlockTailExpression(_) => (),
1956 ObligationCauseCode::TrivialBound => {
1957 err.help("see issue #48214");
1958 if tcx.sess.opts.unstable_features.is_nightly_build() {
1959 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
1965 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1966 let current_limit = self.tcx.sess.recursion_limit();
1967 let suggested_limit = current_limit * 2;
1969 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
1970 suggested_limit, self.tcx.crate_name,
1974 fn suggest_await_before_try(
1976 err: &mut DiagnosticBuilder<'_>,
1977 obligation: &PredicateObligation<'tcx>,
1978 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1982 "suggest_await_before_try: obligation={:?}, span={:?}, trait_ref={:?}, trait_ref_self_ty={:?}",
1988 let body_hir_id = obligation.cause.body_id;
1989 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
1991 if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
1992 let body = self.tcx.hir().body(body_id);
1993 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
1995 self.tcx.require_lang_item(lang_items::FutureTraitLangItem, None);
1997 let self_ty = self.resolve_vars_if_possible(&trait_ref.self_ty());
1999 // Do not check on infer_types to avoid panic in evaluate_obligation.
2000 if self_ty.has_infer_types() {
2003 let self_ty = self.tcx.erase_regions(&self_ty);
2005 let impls_future = self.tcx.type_implements_trait((
2007 self_ty.skip_binder(),
2009 obligation.param_env,
2012 let item_def_id = self
2014 .associated_items(future_trait)
2015 .in_definition_order()
2019 // `<T as Future>::Output`
2020 let projection_ty = ty::ProjectionTy {
2022 substs: self.tcx.mk_substs_trait(
2023 trait_ref.self_ty().skip_binder(),
2024 self.fresh_substs_for_item(span, item_def_id),
2030 let mut selcx = SelectionContext::new(self);
2032 let mut obligations = vec![];
2033 let normalized_ty = normalize_projection_type(
2035 obligation.param_env,
2037 obligation.cause.clone(),
2043 "suggest_await_before_try: normalized_projection_type {:?}",
2044 self.resolve_vars_if_possible(&normalized_ty)
2046 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2047 obligation.param_env,
2051 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2052 if self.predicate_may_hold(&try_obligation) && impls_future {
2053 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2054 if snippet.ends_with('?') {
2055 err.span_suggestion(
2057 "consider using `.await` here",
2058 format!("{}.await?", snippet.trim_end_matches('?')),
2059 Applicability::MaybeIncorrect,
2069 /// Collect all the returned expressions within the input expression.
2070 /// Used to point at the return spans when we want to suggest some change to them.
2072 pub struct ReturnsVisitor<'v> {
2073 pub returns: Vec<&'v hir::Expr<'v>>,
2074 in_block_tail: bool,
2077 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2078 type Map = hir::intravisit::ErasedMap<'v>;
2080 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2081 hir::intravisit::NestedVisitorMap::None
2084 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2085 // Visit every expression to detect `return` paths, either through the function's tail
2086 // expression or `return` statements. We walk all nodes to find `return` statements, but
2087 // we only care about tail expressions when `in_block_tail` is `true`, which means that
2088 // they're in the return path of the function body.
2090 hir::ExprKind::Ret(Some(ex)) => {
2091 self.returns.push(ex);
2093 hir::ExprKind::Block(block, _) if self.in_block_tail => {
2094 self.in_block_tail = false;
2095 for stmt in block.stmts {
2096 hir::intravisit::walk_stmt(self, stmt);
2098 self.in_block_tail = true;
2099 if let Some(expr) = block.expr {
2100 self.visit_expr(expr);
2103 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2105 self.visit_expr(arm.body);
2108 // We need to walk to find `return`s in the entire body.
2109 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2110 _ => self.returns.push(ex),
2114 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2115 assert!(!self.in_block_tail);
2116 if body.generator_kind().is_none() {
2117 if let hir::ExprKind::Block(block, None) = body.value.kind {
2118 if block.expr.is_some() {
2119 self.in_block_tail = true;
2123 hir::intravisit::walk_body(self, body);
2127 /// Collect all the awaited expressions within the input expression.
2129 struct AwaitsVisitor {
2130 awaits: Vec<hir::HirId>,
2133 impl<'v> Visitor<'v> for AwaitsVisitor {
2134 type Map = hir::intravisit::ErasedMap<'v>;
2136 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
2137 hir::intravisit::NestedVisitorMap::None
2140 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2141 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2142 self.awaits.push(id)
2144 hir::intravisit::walk_expr(self, ex)
2148 pub trait NextTypeParamName {
2149 fn next_type_param_name(&self, name: Option<&str>) -> String;
2152 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2153 fn next_type_param_name(&self, name: Option<&str>) -> String {
2154 // This is the list of possible parameter names that we might suggest.
2155 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2156 let name = name.as_deref();
2157 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2158 let used_names = self
2160 .filter_map(|p| match p.name {
2161 hir::ParamName::Plain(ident) => Some(ident.name),
2164 .collect::<Vec<_>>();
2168 .find(|n| !used_names.contains(&Symbol::intern(n)))
2169 .unwrap_or(&"ParamName")
2174 fn suggest_trait_object_return_type_alternatives(
2175 err: &mut DiagnosticBuilder<'_>,
2178 is_object_safe: bool,
2180 err.span_suggestion(
2182 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2185 Applicability::MaybeIncorrect,
2187 err.span_suggestion(
2190 "use `impl {}` as the return type if all return paths have the same type but you \
2191 want to expose only the trait in the signature",
2194 format!("impl {}", trait_obj),
2195 Applicability::MaybeIncorrect,
2198 err.span_suggestion(
2201 "use a boxed trait object if all return paths implement trait `{}`",
2204 format!("Box<dyn {}>", trait_obj),
2205 Applicability::MaybeIncorrect,