2 DerivedObligationCause, EvaluationResult, ImplDerivedObligationCause, Obligation,
3 ObligationCause, ObligationCauseCode, PredicateObligation, SelectionContext,
6 use crate::autoderef::Autoderef;
7 use crate::infer::InferCtxt;
8 use crate::traits::normalize_projection_type;
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_data_structures::stack::ensure_sufficient_stack;
13 error_code, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
14 ErrorGuaranteed, MultiSpan, 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::hir::map;
23 use rustc_middle::ty::{
24 self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, DefIdTree,
25 GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, ToPredicate, Ty, TyCtxt,
28 use rustc_middle::ty::{TypeAndMut, TypeckResults};
29 use rustc_session::Limit;
30 use rustc_span::def_id::LOCAL_CRATE;
31 use rustc_span::symbol::{kw, sym, Ident, Symbol};
32 use rustc_span::{BytePos, DesugaringKind, ExpnKind, Span, DUMMY_SP};
33 use rustc_target::spec::abi;
36 use super::InferCtxtPrivExt;
37 use crate::infer::InferCtxtExt as _;
38 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
39 use rustc_middle::ty::print::with_no_trimmed_paths;
42 pub enum GeneratorInteriorOrUpvar {
43 // span of interior type
49 // This type provides a uniform interface to retrieve data on generators, whether it originated from
50 // the local crate being compiled or from a foreign crate.
52 pub enum GeneratorData<'tcx, 'a> {
53 Local(&'a TypeckResults<'tcx>),
54 Foreign(&'tcx GeneratorDiagnosticData<'tcx>),
57 impl<'tcx, 'a> GeneratorData<'tcx, 'a> {
58 // Try to get information about variables captured by the generator that matches a type we are
59 // looking for with `ty_matches` function. We uses it to find upvar which causes a failure to
61 fn try_get_upvar_span<F>(
63 infer_context: &InferCtxt<'a, 'tcx>,
66 ) -> Option<GeneratorInteriorOrUpvar>
68 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
71 GeneratorData::Local(typeck_results) => {
72 infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| {
73 upvars.iter().find_map(|(upvar_id, upvar)| {
74 let upvar_ty = typeck_results.node_type(*upvar_id);
75 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
76 if ty_matches(ty::Binder::dummy(upvar_ty)) {
77 Some(GeneratorInteriorOrUpvar::Upvar(upvar.span))
84 GeneratorData::Foreign(_) => None,
88 // Try to get the span of a type being awaited on that matches the type we are looking with the
89 // `ty_matches` function. We uses it to find awaited type which causes a failure to meet an
91 fn get_from_await_ty<F>(
93 visitor: AwaitsVisitor,
98 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
101 GeneratorData::Local(typeck_results) => visitor
104 .map(|id| hir.expect_expr(id))
106 ty_matches(ty::Binder::dummy(typeck_results.expr_ty_adjusted(&await_expr)))
108 .map(|expr| expr.span),
109 GeneratorData::Foreign(generator_diagnostic_data) => visitor
112 .map(|id| hir.expect_expr(id))
114 ty_matches(ty::Binder::dummy(
115 generator_diagnostic_data
117 .get(&await_expr.hir_id.local_id)
118 .map_or::<&[ty::adjustment::Adjustment<'tcx>], _>(&[], |a| &a[..])
120 .map_or_else::<Ty<'tcx>, _, _>(
122 generator_diagnostic_data
124 .get(&await_expr.hir_id.local_id)
128 "node_type: no type for node `{}`",
129 ty::tls::with(|tcx| tcx
131 .node_to_string(await_expr.hir_id))
139 .map(|expr| expr.span),
143 /// Get the type, expression, span and optional scope span of all types
144 /// that are live across the yield of this generator
145 fn get_generator_interior_types(
147 ) -> ty::Binder<'tcx, &Vec<GeneratorInteriorTypeCause<'tcx>>> {
149 GeneratorData::Local(typeck_result) => typeck_result.generator_interior_types.as_ref(),
150 GeneratorData::Foreign(generator_diagnostic_data) => {
151 generator_diagnostic_data.generator_interior_types.as_ref()
156 // Used to get the source of the data, note we don't have as much information for generators
157 // originated from foreign crates
158 fn is_foreign(&self) -> bool {
160 GeneratorData::Local(_) => false,
161 GeneratorData::Foreign(_) => true,
166 // This trait is public to expose the diagnostics methods to clippy.
167 pub trait InferCtxtExt<'tcx> {
168 fn suggest_restricting_param_bound(
170 err: &mut Diagnostic,
171 trait_pred: ty::PolyTraitPredicate<'tcx>,
175 fn suggest_dereferences(
177 obligation: &PredicateObligation<'tcx>,
178 err: &mut Diagnostic,
179 trait_pred: ty::PolyTraitPredicate<'tcx>,
182 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<String>;
186 obligation: &PredicateObligation<'tcx>,
187 err: &mut Diagnostic,
188 trait_pred: ty::PolyTraitPredicate<'tcx>,
191 fn suggest_add_reference_to_arg(
193 obligation: &PredicateObligation<'tcx>,
194 err: &mut Diagnostic,
195 trait_pred: ty::PolyTraitPredicate<'tcx>,
196 has_custom_message: bool,
199 fn suggest_borrowing_for_object_cast(
201 err: &mut Diagnostic,
202 obligation: &PredicateObligation<'tcx>,
207 fn suggest_remove_reference(
209 obligation: &PredicateObligation<'tcx>,
210 err: &mut Diagnostic,
211 trait_pred: ty::PolyTraitPredicate<'tcx>,
214 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic);
216 fn suggest_change_mut(
218 obligation: &PredicateObligation<'tcx>,
219 err: &mut Diagnostic,
220 trait_pred: ty::PolyTraitPredicate<'tcx>,
223 fn suggest_semicolon_removal(
225 obligation: &PredicateObligation<'tcx>,
226 err: &mut Diagnostic,
228 trait_pred: ty::PolyTraitPredicate<'tcx>,
231 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
233 fn suggest_impl_trait(
235 err: &mut Diagnostic,
237 obligation: &PredicateObligation<'tcx>,
238 trait_pred: ty::PolyTraitPredicate<'tcx>,
241 fn point_at_returns_when_relevant(
243 err: &mut Diagnostic,
244 obligation: &PredicateObligation<'tcx>,
247 fn report_closure_arg_mismatch(
250 found_span: Option<Span>,
251 expected_ref: ty::PolyTraitRef<'tcx>,
252 found: ty::PolyTraitRef<'tcx>,
253 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;
255 fn suggest_fully_qualified_path(
257 err: &mut Diagnostic,
263 fn maybe_note_obligation_cause_for_async_await(
265 err: &mut Diagnostic,
266 obligation: &PredicateObligation<'tcx>,
269 fn note_obligation_cause_for_async_await(
271 err: &mut Diagnostic,
272 interior_or_upvar_span: GeneratorInteriorOrUpvar,
273 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
275 outer_generator: Option<DefId>,
276 trait_pred: ty::TraitPredicate<'tcx>,
278 typeck_results: Option<&ty::TypeckResults<'tcx>>,
279 obligation: &PredicateObligation<'tcx>,
280 next_code: Option<&ObligationCauseCode<'tcx>>,
283 fn note_obligation_cause_code<T>(
285 err: &mut Diagnostic,
287 param_env: ty::ParamEnv<'tcx>,
288 cause_code: &ObligationCauseCode<'tcx>,
289 obligated_types: &mut Vec<Ty<'tcx>>,
290 seen_requirements: &mut FxHashSet<DefId>,
294 fn suggest_new_overflow_limit(&self, err: &mut Diagnostic);
296 /// Suggest to await before try: future? => future.await?
297 fn suggest_await_before_try(
299 err: &mut Diagnostic,
300 obligation: &PredicateObligation<'tcx>,
301 trait_pred: ty::PolyTraitPredicate<'tcx>,
305 fn suggest_floating_point_literal(
307 obligation: &PredicateObligation<'tcx>,
308 err: &mut Diagnostic,
309 trait_ref: &ty::PolyTraitRef<'tcx>,
314 obligation: &PredicateObligation<'tcx>,
315 err: &mut Diagnostic,
316 trait_pred: ty::PolyTraitPredicate<'tcx>,
320 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
322 generics.where_clause.tail_span_for_suggestion(),
325 if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
331 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
332 /// it can also be an `impl Trait` param that needs to be decomposed to a type
333 /// param for cleaner code.
334 fn suggest_restriction<'tcx>(
336 generics: &hir::Generics<'tcx>,
338 err: &mut Diagnostic,
339 fn_sig: Option<&hir::FnSig<'_>>,
340 projection: Option<&ty::ProjectionTy<'_>>,
341 trait_pred: ty::PolyTraitPredicate<'tcx>,
342 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
344 // When we are dealing with a trait, `super_traits` will be `Some`:
345 // Given `trait T: A + B + C {}`
346 // - ^^^^^^^^^ GenericBounds
349 let span = generics.where_clause.span_for_predicates_or_empty_place();
350 if span.from_expansion() || span.desugaring_kind().is_some() {
353 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
354 if let Some((bound_str, fn_sig)) =
355 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
356 // Shenanigans to get the `Trait` from the `impl Trait`.
357 ty::Param(param) => {
358 // `fn foo(t: impl Trait)`
359 // ^^^^^ get this string
360 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
365 // We know we have an `impl Trait` that doesn't satisfy a required projection.
367 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
368 // types. There should be at least one, but there might be *more* than one. In that
369 // case we could just ignore it and try to identify which one needs the restriction,
370 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
372 let mut ty_spans = vec![];
373 let impl_trait_str = format!("impl {}", bound_str);
374 for input in fn_sig.decl.inputs {
375 if let hir::TyKind::Path(hir::QPath::Resolved(
377 hir::Path { segments: [segment], .. },
380 if segment.ident.as_str() == impl_trait_str.as_str() {
381 // `fn foo(t: impl Trait)`
382 // ^^^^^^^^^^ get this to suggest `T` instead
384 // There might be more than one `impl Trait`.
385 ty_spans.push(input.span);
390 let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
391 // The type param `T: Trait` we will suggest to introduce.
392 let type_param = format!("{}: {}", type_param_name, bound_str);
394 // FIXME: modify the `trait_pred` instead of string shenanigans.
395 // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
396 let pred = trait_pred.to_predicate(tcx).to_string();
397 let pred = pred.replace(&impl_trait_str, &type_param_name);
399 // Find the last of the generic parameters contained within the span of
404 .map(|p| p.bounds_span_for_suggestions().unwrap_or(p.span.shrink_to_hi()))
405 .filter(|&span| generics.span.contains(span) && span.can_be_used_for_suggestions())
406 .max_by_key(|span| span.hi())
408 // `fn foo(t: impl Trait)`
409 // ^ suggest `<T: Trait>` here
410 None => (generics.span, format!("<{}>", type_param)),
411 // `fn foo<A>(t: impl Trait)`
412 // ^^^ suggest `<A, T: Trait>` here
413 Some(span) => (span, format!(", {}", type_param)),
415 // `fn foo(t: impl Trait)`
416 // ^ suggest `where <T as Trait>::A: Bound`
417 predicate_constraint(generics, pred),
419 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
421 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
422 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
423 // `fn foo(t: impl Trait<A: Bound>)` instead.
424 err.multipart_suggestion(
425 "introduce a type parameter with a trait bound instead of using `impl Trait`",
427 Applicability::MaybeIncorrect,
430 // Trivial case: `T` needs an extra bound: `T: Bound`.
431 let (sp, suggestion) = match (
435 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
438 (_, None) => predicate_constraint(generics, trait_pred.to_predicate(tcx).to_string()),
439 (None, Some((ident, []))) => (
440 ident.span.shrink_to_hi(),
441 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
443 (_, Some((_, [.., bounds]))) => (
444 bounds.span().shrink_to_hi(),
445 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
447 (Some(_), Some((_, []))) => (
448 generics.span.shrink_to_hi(),
449 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
453 err.span_suggestion_verbose(
455 &format!("consider further restricting {}", msg),
457 Applicability::MachineApplicable,
462 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
463 fn suggest_restricting_param_bound(
465 mut err: &mut Diagnostic,
466 trait_pred: ty::PolyTraitPredicate<'tcx>,
469 let self_ty = trait_pred.skip_binder().self_ty();
470 let (param_ty, projection) = match self_ty.kind() {
471 ty::Param(_) => (true, None),
472 ty::Projection(projection) => (false, Some(projection)),
476 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
477 // don't suggest `T: Sized + ?Sized`.
478 let mut hir_id = body_id;
479 while let Some(node) = self.tcx.hir().find(hir_id) {
481 hir::Node::Item(hir::Item {
483 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
485 }) if self_ty == self.tcx.types.self_param => {
487 // Restricting `Self` for a single method.
496 Some((ident, bounds)),
501 hir::Node::TraitItem(hir::TraitItem {
503 kind: hir::TraitItemKind::Fn(..),
505 }) if self_ty == self.tcx.types.self_param => {
507 // Restricting `Self` for a single method.
509 self.tcx, &generics, "`Self`", err, None, projection, trait_pred, None,
514 hir::Node::TraitItem(hir::TraitItem {
516 kind: hir::TraitItemKind::Fn(fn_sig, ..),
519 | hir::Node::ImplItem(hir::ImplItem {
521 kind: hir::ImplItemKind::Fn(fn_sig, ..),
524 | hir::Node::Item(hir::Item {
525 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
526 }) if projection.is_some() => {
527 // Missing restriction on associated type of type parameter (unmet projection).
531 "the associated type",
540 hir::Node::Item(hir::Item {
542 hir::ItemKind::Trait(_, _, generics, ..)
543 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
545 }) if projection.is_some() => {
546 // Missing restriction on associated type of type parameter (unmet projection).
550 "the associated type",
560 hir::Node::Item(hir::Item {
562 hir::ItemKind::Struct(_, generics)
563 | hir::ItemKind::Enum(_, generics)
564 | hir::ItemKind::Union(_, generics)
565 | hir::ItemKind::Trait(_, _, generics, ..)
566 | hir::ItemKind::Impl(hir::Impl { generics, .. })
567 | hir::ItemKind::Fn(_, generics, _)
568 | hir::ItemKind::TyAlias(_, generics)
569 | hir::ItemKind::TraitAlias(generics, _)
570 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
573 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
574 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
577 // Missing generic type parameter bound.
578 let param_name = self_ty.to_string();
579 let constraint = with_no_trimmed_paths!(
580 trait_pred.print_modifiers_and_trait_path().to_string()
582 if suggest_constraining_type_param(
588 Some(trait_pred.def_id()),
594 hir::Node::Item(hir::Item {
596 hir::ItemKind::Struct(_, generics)
597 | hir::ItemKind::Enum(_, generics)
598 | hir::ItemKind::Union(_, generics)
599 | hir::ItemKind::Trait(_, _, generics, ..)
600 | hir::ItemKind::Impl(hir::Impl { generics, .. })
601 | hir::ItemKind::Fn(_, generics, _)
602 | hir::ItemKind::TyAlias(_, generics)
603 | hir::ItemKind::TraitAlias(generics, _)
604 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
607 // Missing generic type parameter bound.
608 let param_name = self_ty.to_string();
609 let constraint = trait_pred.print_modifiers_and_trait_path().to_string();
610 if suggest_arbitrary_trait_bound(generics, &mut err, ¶m_name, &constraint) {
614 hir::Node::Crate(..) => return,
619 hir_id = self.tcx.hir().local_def_id_to_hir_id(self.tcx.hir().get_parent_item(hir_id));
623 /// When after several dereferencing, the reference satisfies the trait
624 /// binding. This function provides dereference suggestion for this
625 /// specific situation.
626 fn suggest_dereferences(
628 obligation: &PredicateObligation<'tcx>,
629 err: &mut Diagnostic,
630 trait_pred: ty::PolyTraitPredicate<'tcx>,
632 // It only make sense when suggesting dereferences for arguments
633 let ObligationCauseCode::FunctionArgumentObligation { .. } = obligation.cause.code() else {
636 let param_env = obligation.param_env;
637 let body_id = obligation.cause.body_id;
638 let span = obligation.cause.span;
639 let mut real_trait_pred = trait_pred;
640 let mut code = obligation.cause.code();
643 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
646 ObligationCauseCode::ImplDerivedObligation(box ImplDerivedObligationCause {
647 derived: DerivedObligationCause { parent_code, parent_trait_pred },
650 | ObligationCauseCode::BuiltinDerivedObligation(DerivedObligationCause {
654 | ObligationCauseCode::DerivedObligation(DerivedObligationCause {
659 real_trait_pred = *parent_trait_pred;
663 let Some(real_ty) = real_trait_pred.self_ty().no_bound_vars() else {
667 if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
668 let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
669 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
671 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
673 self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_pred, ty);
674 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
677 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
678 // Don't care about `&mut` because `DerefMut` is used less
679 // often and user will not expect autoderef happens.
680 if src.starts_with('&') && !src.starts_with("&mut ") {
681 let derefs = "*".repeat(steps);
684 "consider dereferencing here",
685 format!("&{}{}", derefs, &src[1..]),
686 Applicability::MachineApplicable,
692 } else if real_trait_pred != trait_pred {
693 // This branch addresses #87437.
694 let obligation = self.mk_trait_obligation_with_new_self_ty(
699 if self.predicate_may_hold(&obligation) {
700 err.span_suggestion_verbose(
702 "consider dereferencing here",
704 Applicability::MachineApplicable,
714 /// Given a closure's `DefId`, return the given name of the closure.
716 /// This doesn't account for reassignments, but it's only used for suggestions.
717 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<String> {
718 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<String> {
719 // Get the local name of this closure. This can be inaccurate because
720 // of the possibility of reassignment, but this should be good enough.
722 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
723 Some(format!("{}", name))
732 let hir = self.tcx.hir();
733 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
734 let parent_node = hir.get_parent_node(hir_id);
735 match hir.find(parent_node) {
736 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
737 get_name(err, &local.pat.kind)
739 // Different to previous arm because one is `&hir::Local` and the other
740 // is `P<hir::Local>`.
741 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
746 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
747 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
748 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
751 obligation: &PredicateObligation<'tcx>,
752 err: &mut Diagnostic,
753 trait_pred: ty::PolyTraitPredicate<'tcx>,
755 let Some(self_ty) = trait_pred.self_ty().no_bound_vars() else {
759 let (def_id, output_ty, callable) = match *self_ty.kind() {
760 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
761 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
764 let msg = format!("use parentheses to call the {}", callable);
766 // `mk_trait_obligation_with_new_self_ty` only works for types with no escaping bound
767 // variables, so bail out if we have any.
768 let Some(output_ty) = output_ty.no_bound_vars() else {
773 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred, output_ty);
775 match self.evaluate_obligation(&new_obligation) {
777 EvaluationResult::EvaluatedToOk
778 | EvaluationResult::EvaluatedToOkModuloRegions
779 | EvaluationResult::EvaluatedToAmbig,
783 let hir = self.tcx.hir();
784 // Get the name of the callable and the arguments to be used in the suggestion.
785 let (snippet, sugg) = match hir.get_if_local(def_id) {
786 Some(hir::Node::Expr(hir::Expr {
787 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
790 err.span_label(*span, "consider calling this closure");
791 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
794 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
795 let sugg = format!("({})", args);
796 (format!("{}{}", name, sugg), sugg)
798 Some(hir::Node::Item(hir::Item {
800 kind: hir::ItemKind::Fn(.., body_id),
803 err.span_label(ident.span, "consider calling this function");
804 let body = hir.body(*body_id);
808 .map(|arg| match &arg.pat.kind {
809 hir::PatKind::Binding(_, _, ident, None)
810 // FIXME: provide a better suggestion when encountering `SelfLower`, it
811 // should suggest a method call.
812 if ident.name != kw::SelfLower => ident.to_string(),
813 _ => "_".to_string(),
817 let sugg = format!("({})", args);
818 (format!("{}{}", ident, sugg), sugg)
822 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
824 // When the obligation error has been ensured to have been caused by
825 // an argument, the `obligation.cause.span` points at the expression
826 // of the argument, so we can provide a suggestion. Otherwise, we give
827 // a more general note.
828 err.span_suggestion_verbose(
829 obligation.cause.span.shrink_to_hi(),
832 Applicability::HasPlaceholders,
835 err.help(&format!("{}: `{}`", msg, snippet));
840 fn suggest_add_reference_to_arg(
842 obligation: &PredicateObligation<'tcx>,
843 err: &mut Diagnostic,
844 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
845 has_custom_message: bool,
847 let span = obligation.cause.span;
849 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
850 obligation.cause.code()
853 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
854 span.ctxt().outer_expn_data().kind
856 obligation.cause.code()
861 // List of traits for which it would be nonsensical to suggest borrowing.
862 // For instance, immutable references are always Copy, so suggesting to
863 // borrow would always succeed, but it's probably not what the user wanted.
864 let mut never_suggest_borrow: Vec<_> =
865 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
867 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
870 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
871 never_suggest_borrow.push(def_id);
874 let param_env = obligation.param_env;
876 // Try to apply the original trait binding obligation by borrowing.
877 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
880 if blacklist.contains(&old_pred.def_id()) {
884 let orig_ty = old_pred.self_ty().skip_binder();
885 let mk_result = |new_ty| {
887 self.mk_trait_obligation_with_new_self_ty(param_env, old_pred, new_ty);
888 self.predicate_must_hold_modulo_regions(&obligation)
890 let imm_result = mk_result(self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, orig_ty));
891 let mut_result = mk_result(self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, orig_ty));
893 if imm_result || mut_result {
894 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
895 // We have a very specific type of error, where just borrowing this argument
896 // might solve the problem. In cases like this, the important part is the
897 // original type obligation, not the last one that failed, which is arbitrary.
898 // Because of this, we modify the error to refer to the original obligation and
899 // return early in the caller.
902 "the trait bound `{}: {}` is not satisfied",
904 old_pred.print_modifiers_and_trait_path(),
906 if has_custom_message {
910 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
912 if snippet.starts_with('&') {
913 // This is already a literal borrow and the obligation is failing
914 // somewhere else in the obligation chain. Do not suggest non-sense.
920 "expected an implementor of trait `{}`",
921 old_pred.print_modifiers_and_trait_path(),
925 // This if is to prevent a special edge-case
927 span.ctxt().outer_expn_data().kind,
928 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
930 // We don't want a borrowing suggestion on the fields in structs,
933 // the_foos: Vec<Foo>
937 if imm_result && mut_result {
938 err.span_suggestions(
940 "consider borrowing here",
941 ["&".to_string(), "&mut ".to_string()].into_iter(),
942 Applicability::MaybeIncorrect,
945 err.span_suggestion_verbose(
948 "consider{} borrowing here",
949 if mut_result { " mutably" } else { "" }
951 format!("&{}", if mut_result { "mut " } else { "" }),
952 Applicability::MaybeIncorrect,
962 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
963 try_borrowing(cause.derived.parent_trait_pred, &[])
964 } else if let ObligationCauseCode::BindingObligation(_, _)
965 | ObligationCauseCode::ItemObligation(_) = code
967 try_borrowing(poly_trait_pred, &never_suggest_borrow)
973 // Suggest borrowing the type
974 fn suggest_borrowing_for_object_cast(
976 err: &mut Diagnostic,
977 obligation: &PredicateObligation<'tcx>,
981 let ty::Dynamic(predicates, _) = object_ty.kind() else { return; };
982 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
984 for predicate in predicates.iter() {
985 if !self.predicate_must_hold_modulo_regions(
986 &obligation.with(predicate.with_self_ty(self.tcx, self_ref_ty)),
993 obligation.cause.span.shrink_to_lo(),
995 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
998 Applicability::MaybeIncorrect,
1002 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
1003 /// suggest removing these references until we reach a type that implements the trait.
1004 fn suggest_remove_reference(
1006 obligation: &PredicateObligation<'tcx>,
1007 err: &mut Diagnostic,
1008 trait_pred: ty::PolyTraitPredicate<'tcx>,
1010 let span = obligation.cause.span;
1012 let mut suggested = false;
1013 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1015 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1016 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1017 // Do not suggest removal of borrow from type arguments.
1021 let Some(mut suggested_ty) = trait_pred.self_ty().no_bound_vars() else {
1025 for refs_remaining in 0..refs_number {
1026 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1029 suggested_ty = *inner_ty;
1031 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1032 obligation.param_env,
1037 if self.predicate_may_hold(&new_obligation) {
1042 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1044 let remove_refs = refs_remaining + 1;
1046 let msg = if remove_refs == 1 {
1047 "consider removing the leading `&`-reference".to_string()
1049 format!("consider removing {} leading `&`-references", remove_refs)
1052 err.span_suggestion_short(
1056 Applicability::MachineApplicable,
1066 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1067 let span = obligation.cause.span;
1069 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1070 let hir = self.tcx.hir();
1071 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1072 if let hir::Node::Expr(expr) = node {
1073 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1074 // and if not maybe suggest doing something else? If we kept the expression around we
1075 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1076 // it is from the local crate.
1077 err.span_suggestion_verbose(
1078 expr.span.shrink_to_hi().with_hi(span.hi()),
1079 "remove the `.await`",
1081 Applicability::MachineApplicable,
1083 // FIXME: account for associated `async fn`s.
1084 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1085 if let ty::PredicateKind::Trait(pred) =
1086 obligation.predicate.kind().skip_binder()
1090 &format!("this call returns `{}`", pred.self_ty()),
1093 if let Some(typeck_results) =
1094 self.in_progress_typeck_results.map(|t| t.borrow())
1095 && let ty = typeck_results.expr_ty_adjusted(base)
1096 && let ty::FnDef(def_id, _substs) = ty.kind()
1097 && let Some(hir::Node::Item(hir::Item { span, ident, .. })) =
1098 hir.get_if_local(*def_id)
1100 err.span_suggestion_verbose(
1101 span.shrink_to_lo(),
1103 "alternatively, consider making `fn {}` asynchronous",
1106 "async ".to_string(),
1107 Applicability::MaybeIncorrect,
1116 /// Check if the trait bound is implemented for a different mutability and note it in the
1118 fn suggest_change_mut(
1120 obligation: &PredicateObligation<'tcx>,
1121 err: &mut Diagnostic,
1122 trait_pred: ty::PolyTraitPredicate<'tcx>,
1124 let points_at_arg = matches!(
1125 obligation.cause.code(),
1126 ObligationCauseCode::FunctionArgumentObligation { .. },
1129 let span = obligation.cause.span;
1130 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1132 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1133 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1134 // Do not suggest removal of borrow from type arguments.
1137 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1138 if trait_pred.has_infer_types_or_consts() {
1139 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1140 // unresolved bindings.
1144 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1146 if region.is_late_bound() || t_type.has_escaping_bound_vars() {
1147 // Avoid debug assertion in `mk_obligation_for_def_id`.
1149 // If the self type has escaping bound vars then it's not
1150 // going to be the type of an expression, so the suggestion
1151 // probably won't apply anyway.
1155 let suggested_ty = match mutability {
1156 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1157 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1160 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1161 obligation.param_env,
1165 let suggested_ty_would_satisfy_obligation = self
1166 .evaluate_obligation_no_overflow(&new_obligation)
1167 .must_apply_modulo_regions();
1168 if suggested_ty_would_satisfy_obligation {
1173 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1174 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1175 err.span_suggestion_verbose(
1177 "consider changing this borrow's mutability",
1178 "&mut ".to_string(),
1179 Applicability::MachineApplicable,
1183 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1184 trait_pred.print_modifiers_and_trait_path(),
1186 trait_pred.skip_binder().self_ty(),
1194 fn suggest_semicolon_removal(
1196 obligation: &PredicateObligation<'tcx>,
1197 err: &mut Diagnostic,
1199 trait_pred: ty::PolyTraitPredicate<'tcx>,
1201 let hir = self.tcx.hir();
1202 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1203 let node = hir.find(parent_node);
1204 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1205 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1206 && sig.decl.output.span().overlaps(span)
1207 && blk.expr.is_none()
1208 && trait_pred.self_ty().skip_binder().is_unit()
1209 && let Some(stmt) = blk.stmts.last()
1210 && let hir::StmtKind::Semi(expr) = stmt.kind
1211 // Only suggest this if the expression behind the semicolon implements the predicate
1212 && let Some(typeck_results) = self.in_progress_typeck_results
1213 && let Some(ty) = typeck_results.borrow().expr_ty_opt(expr)
1214 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred, ty))
1219 "this expression has type `{}`, which implements `{}`",
1221 trait_pred.print_modifiers_and_trait_path()
1224 err.span_suggestion(
1225 self.tcx.sess.source_map().end_point(stmt.span),
1226 "remove this semicolon",
1228 Applicability::MachineApplicable
1235 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1236 let hir = self.tcx.hir();
1237 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1238 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1242 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1245 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1246 /// applicable and signal that the error has been expanded appropriately and needs to be
1248 fn suggest_impl_trait(
1250 err: &mut Diagnostic,
1252 obligation: &PredicateObligation<'tcx>,
1253 trait_pred: ty::PolyTraitPredicate<'tcx>,
1255 match obligation.cause.code().peel_derives() {
1256 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1257 ObligationCauseCode::SizedReturnType => {}
1261 let hir = self.tcx.hir();
1262 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1263 let node = hir.find(fn_hir_id);
1264 let Some(hir::Node::Item(hir::Item {
1265 kind: hir::ItemKind::Fn(sig, _, body_id),
1271 let body = hir.body(*body_id);
1272 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1273 let ty = trait_pred.skip_binder().self_ty();
1274 let is_object_safe = match ty.kind() {
1275 ty::Dynamic(predicates, _) => {
1276 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1279 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1281 // We only want to suggest `impl Trait` to `dyn Trait`s.
1282 // For example, `fn foo() -> str` needs to be filtered out.
1286 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1290 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1291 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1292 // Recursively look for `TraitObject` types and if there's only one, use that span to
1293 // suggest `impl Trait`.
1295 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1296 // otherwise suggest using `Box<dyn Trait>` or an enum.
1297 let mut visitor = ReturnsVisitor::default();
1298 visitor.visit_body(&body);
1300 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1301 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id) else { return false; };
1303 let ret_types = visitor
1306 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1307 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1308 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1310 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1312 let ty = self.resolve_vars_if_possible(ty);
1314 !matches!(ty.kind(), ty::Error(_))
1315 && last_ty.map_or(true, |last_ty| {
1316 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1317 // *after* in the dependency graph.
1318 match (ty.kind(), last_ty.kind()) {
1319 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1320 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1321 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1323 Infer(InferTy::FreshFloatTy(_)),
1324 Infer(InferTy::FreshFloatTy(_)),
1329 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1332 let mut spans_and_needs_box = vec![];
1334 match liberated_sig.output().kind() {
1335 ty::Dynamic(predicates, _) => {
1336 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1337 let param_env = ty::ParamEnv::empty();
1339 if !only_never_return {
1340 for (expr_span, return_ty) in ret_types {
1341 let self_ty_satisfies_dyn_predicates = |self_ty| {
1342 predicates.iter().all(|predicate| {
1343 let pred = predicate.with_self_ty(self.tcx, self_ty);
1344 let obl = Obligation::new(cause.clone(), param_env, pred);
1345 self.predicate_may_hold(&obl)
1349 if let ty::Adt(def, substs) = return_ty.kind()
1351 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1353 spans_and_needs_box.push((expr_span, false));
1354 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1355 spans_and_needs_box.push((expr_span, true));
1365 let sm = self.tcx.sess.source_map();
1366 if !ret_ty.span.overlaps(span) {
1369 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1370 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1376 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1377 let name = liberated_sig.output().to_string();
1379 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1380 if !name.starts_with("dyn ") {
1386 err.code(error_code!(E0746));
1387 err.set_primary_message("return type cannot have an unboxed trait object");
1388 err.children.clear();
1389 let impl_trait_msg = "for information on `impl Trait`, see \
1390 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1391 #returning-types-that-implement-traits>";
1392 let trait_obj_msg = "for information on trait objects, see \
1393 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1394 #using-trait-objects-that-allow-for-values-of-different-types>";
1396 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1397 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1398 if only_never_return {
1399 // No return paths, probably using `panic!()` or similar.
1400 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1401 suggest_trait_object_return_type_alternatives(
1407 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1408 // Suggest `-> impl Trait`.
1409 err.span_suggestion(
1412 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1413 which implements `{1}`",
1416 format!("impl {}", trait_obj),
1417 Applicability::MachineApplicable,
1419 err.note(impl_trait_msg);
1422 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1423 err.multipart_suggestion(
1424 "return a boxed trait object instead",
1426 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1427 (span.shrink_to_hi(), ">".to_string()),
1429 Applicability::MaybeIncorrect,
1431 for (span, needs_box) in spans_and_needs_box {
1433 err.multipart_suggestion(
1434 "... and box this value",
1436 (span.shrink_to_lo(), "Box::new(".to_string()),
1437 (span.shrink_to_hi(), ")".to_string()),
1439 Applicability::MaybeIncorrect,
1444 // This is currently not possible to trigger because E0038 takes precedence, but
1445 // leave it in for completeness in case anything changes in an earlier stage.
1447 "if trait `{}` were object-safe, you could return a trait object",
1451 err.note(trait_obj_msg);
1453 "if all the returned values were of the same type you could use `impl {}` as the \
1457 err.note(impl_trait_msg);
1458 err.note("you can create a new `enum` with a variant for each returned type");
1463 fn point_at_returns_when_relevant(
1465 err: &mut Diagnostic,
1466 obligation: &PredicateObligation<'tcx>,
1468 match obligation.cause.code().peel_derives() {
1469 ObligationCauseCode::SizedReturnType => {}
1473 let hir = self.tcx.hir();
1474 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1475 let node = hir.find(parent_node);
1476 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1479 let body = hir.body(*body_id);
1480 // Point at all the `return`s in the function as they have failed trait bounds.
1481 let mut visitor = ReturnsVisitor::default();
1482 visitor.visit_body(&body);
1483 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1484 for expr in &visitor.returns {
1485 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1486 let ty = self.resolve_vars_if_possible(returned_ty);
1487 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1493 fn report_closure_arg_mismatch(
1496 found_span: Option<Span>,
1497 expected_ref: ty::PolyTraitRef<'tcx>,
1498 found: ty::PolyTraitRef<'tcx>,
1499 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1500 crate fn build_fn_sig_string<'tcx>(
1502 trait_ref: ty::PolyTraitRef<'tcx>,
1504 let inputs = trait_ref.skip_binder().substs.type_at(1);
1505 let sig = match inputs.kind() {
1507 if tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1511 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1513 hir::Unsafety::Normal,
1518 std::iter::once(inputs),
1519 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1521 hir::Unsafety::Normal,
1525 trait_ref.rebind(sig).to_string()
1528 let argument_kind = match expected_ref.skip_binder().self_ty().kind() {
1529 ty::Closure(..) => "closure",
1530 ty::Generator(..) => "generator",
1533 let span = self.tcx.sess.source_map().guess_head_span(span);
1534 let mut err = struct_span_err!(
1538 "type mismatch in {} arguments",
1542 let found_str = format!("expected signature of `{}`", build_fn_sig_string(self.tcx, found));
1543 err.span_label(span, found_str);
1545 let found_span = found_span.unwrap_or(span);
1547 format!("found signature of `{}`", build_fn_sig_string(self.tcx, expected_ref));
1548 err.span_label(found_span, expected_str);
1553 fn suggest_fully_qualified_path(
1555 err: &mut Diagnostic,
1560 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1561 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1563 "{}s cannot be accessed directly on a `trait`, they can only be \
1564 accessed through a specific `impl`",
1565 assoc_item.kind.as_def_kind().descr(item_def_id)
1567 err.span_suggestion(
1569 "use the fully qualified path to an implementation",
1570 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1571 Applicability::HasPlaceholders,
1577 /// Adds an async-await specific note to the diagnostic when the future does not implement
1578 /// an auto trait because of a captured type.
1581 /// note: future does not implement `Qux` as this value is used across an await
1582 /// --> $DIR/issue-64130-3-other.rs:17:5
1584 /// LL | let x = Foo;
1585 /// | - has type `Foo`
1586 /// LL | baz().await;
1587 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1589 /// | - `x` is later dropped here
1592 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1593 /// is "replaced" with a different message and a more specific error.
1596 /// error: future cannot be sent between threads safely
1597 /// --> $DIR/issue-64130-2-send.rs:21:5
1599 /// LL | fn is_send<T: Send>(t: T) { }
1600 /// | ---- required by this bound in `is_send`
1602 /// LL | is_send(bar());
1603 /// | ^^^^^^^ future returned by `bar` is not send
1605 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1606 /// implemented for `Foo`
1607 /// note: future is not send as this value is used across an await
1608 /// --> $DIR/issue-64130-2-send.rs:15:5
1610 /// LL | let x = Foo;
1611 /// | - has type `Foo`
1612 /// LL | baz().await;
1613 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1615 /// | - `x` is later dropped here
1618 /// Returns `true` if an async-await specific note was added to the diagnostic.
1619 fn maybe_note_obligation_cause_for_async_await(
1621 err: &mut Diagnostic,
1622 obligation: &PredicateObligation<'tcx>,
1625 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1626 obligation.cause.span={:?}",
1627 obligation.predicate, obligation.cause.span
1629 let hir = self.tcx.hir();
1631 // Attempt to detect an async-await error by looking at the obligation causes, looking
1632 // for a generator to be present.
1634 // When a future does not implement a trait because of a captured type in one of the
1635 // generators somewhere in the call stack, then the result is a chain of obligations.
1637 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1638 // future is passed as an argument to a function C which requires a `Send` type, then the
1639 // chain looks something like this:
1641 // - `BuiltinDerivedObligation` with a generator witness (B)
1642 // - `BuiltinDerivedObligation` with a generator (B)
1643 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1644 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1645 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1646 // - `BuiltinDerivedObligation` with a generator witness (A)
1647 // - `BuiltinDerivedObligation` with a generator (A)
1648 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1649 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1650 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1651 // - `BindingObligation` with `impl_send (Send requirement)
1653 // The first obligation in the chain is the most useful and has the generator that captured
1654 // the type. The last generator (`outer_generator` below) has information about where the
1655 // bound was introduced. At least one generator should be present for this diagnostic to be
1657 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1658 ty::PredicateKind::Trait(p) => (Some(p), Some(p.self_ty())),
1661 let mut generator = None;
1662 let mut outer_generator = None;
1663 let mut next_code = Some(obligation.cause.code());
1665 let mut seen_upvar_tys_infer_tuple = false;
1667 while let Some(code) = next_code {
1668 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1670 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1671 next_code = Some(parent_code.as_ref());
1673 ObligationCauseCode::ImplDerivedObligation(cause) => {
1674 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1676 "maybe_note_obligation_cause_for_async_await: ImplDerived \
1677 parent_trait_ref={:?} self_ty.kind={:?}",
1678 cause.derived.parent_trait_pred,
1683 ty::Generator(did, ..) => {
1684 generator = generator.or(Some(did));
1685 outer_generator = Some(did);
1687 ty::GeneratorWitness(..) => {}
1688 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1689 // By introducing a tuple of upvar types into the chain of obligations
1690 // of a generator, the first non-generator item is now the tuple itself,
1691 // we shall ignore this.
1693 seen_upvar_tys_infer_tuple = true;
1695 _ if generator.is_none() => {
1696 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1697 target_ty = Some(ty);
1702 next_code = Some(cause.derived.parent_code.as_ref());
1704 ObligationCauseCode::DerivedObligation(derived_obligation)
1705 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1706 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1708 "maybe_note_obligation_cause_for_async_await: \
1709 parent_trait_ref={:?} self_ty.kind={:?}",
1710 derived_obligation.parent_trait_pred,
1715 ty::Generator(did, ..) => {
1716 generator = generator.or(Some(did));
1717 outer_generator = Some(did);
1719 ty::GeneratorWitness(..) => {}
1720 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1721 // By introducing a tuple of upvar types into the chain of obligations
1722 // of a generator, the first non-generator item is now the tuple itself,
1723 // we shall ignore this.
1725 seen_upvar_tys_infer_tuple = true;
1727 _ if generator.is_none() => {
1728 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1729 target_ty = Some(ty);
1734 next_code = Some(derived_obligation.parent_code.as_ref());
1740 // Only continue if a generator was found.
1741 debug!(?generator, ?trait_ref, ?target_ty, "maybe_note_obligation_cause_for_async_await");
1742 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1746 let span = self.tcx.def_span(generator_did);
1748 let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1749 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1751 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1752 generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
1755 in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1759 let generator_body = generator_did
1761 .map(|def_id| hir.local_def_id_to_hir_id(def_id))
1762 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1763 .map(|body_id| hir.body(body_id));
1764 let is_async = match generator_did.as_local() {
1765 Some(_) => generator_body
1766 .and_then(|body| body.generator_kind())
1767 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1771 .generator_kind(generator_did)
1772 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1775 let mut visitor = AwaitsVisitor::default();
1776 if let Some(body) = generator_body {
1777 visitor.visit_body(body);
1779 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1781 // Look for a type inside the generator interior that matches the target type to get
1783 let target_ty_erased = self.tcx.erase_regions(target_ty);
1784 let ty_matches = |ty| -> bool {
1785 // Careful: the regions for types that appear in the
1786 // generator interior are not generally known, so we
1787 // want to erase them when comparing (and anyway,
1788 // `Send` and other bounds are generally unaffected by
1789 // the choice of region). When erasing regions, we
1790 // also have to erase late-bound regions. This is
1791 // because the types that appear in the generator
1792 // interior generally contain "bound regions" to
1793 // represent regions that are part of the suspended
1794 // generator frame. Bound regions are preserved by
1795 // `erase_regions` and so we must also call
1796 // `erase_late_bound_regions`.
1797 let ty_erased = self.tcx.erase_late_bound_regions(ty);
1798 let ty_erased = self.tcx.erase_regions(ty_erased);
1799 let eq = ty_erased == target_ty_erased;
1801 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1802 target_ty_erased={:?} eq={:?}",
1803 ty_erased, target_ty_erased, eq
1808 let mut interior_or_upvar_span = None;
1809 let mut interior_extra_info = None;
1811 // Get the typeck results from the infcx if the generator is the function we are currently
1812 // type-checking; otherwise, get them by performing a query. This is needed to avoid
1813 // cycles. If we can't use resolved types because the generator comes from another crate,
1814 // we still provide a targeted error but without all the relevant spans.
1815 let generator_data: Option<GeneratorData<'tcx, '_>> = match &in_progress_typeck_results {
1816 Some(t) if t.hir_owner.to_def_id() == generator_did_root => {
1817 Some(GeneratorData::Local(&t))
1819 _ if generator_did.is_local() => {
1820 Some(GeneratorData::Local(self.tcx.typeck(generator_did.expect_local())))
1824 .generator_diagnostic_data(generator_did)
1826 .map(|generator_diag_data| GeneratorData::Foreign(generator_diag_data)),
1829 if let Some(generator_data) = generator_data.as_ref() {
1830 interior_or_upvar_span =
1831 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
1833 // The generator interior types share the same binders
1834 if let Some(cause) =
1835 generator_data.get_generator_interior_types().skip_binder().iter().find(
1836 |ty::GeneratorInteriorTypeCause { ty, .. }| {
1837 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
1841 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
1842 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1845 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1846 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1849 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
1850 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span));
1854 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1855 let typeck_results = generator_data.and_then(|generator_data| match generator_data {
1856 GeneratorData::Local(typeck_results) => Some(typeck_results),
1857 GeneratorData::Foreign(_) => None,
1859 self.note_obligation_cause_for_async_await(
1861 interior_or_upvar_span,
1862 interior_extra_info,
1877 /// Unconditionally adds the diagnostic note described in
1878 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1879 fn note_obligation_cause_for_async_await(
1881 err: &mut Diagnostic,
1882 interior_or_upvar_span: GeneratorInteriorOrUpvar,
1883 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1885 outer_generator: Option<DefId>,
1886 trait_pred: ty::TraitPredicate<'tcx>,
1887 target_ty: Ty<'tcx>,
1888 typeck_results: Option<&ty::TypeckResults<'tcx>>,
1889 obligation: &PredicateObligation<'tcx>,
1890 next_code: Option<&ObligationCauseCode<'tcx>>,
1892 let source_map = self.tcx.sess.source_map();
1894 let (await_or_yield, an_await_or_yield) =
1895 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1896 let future_or_generator = if is_async { "future" } else { "generator" };
1898 // Special case the primary error message when send or sync is the trait that was
1900 let hir = self.tcx.hir();
1901 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
1902 self.tcx.get_diagnostic_name(trait_pred.def_id())
1904 let (trait_name, trait_verb) =
1905 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1908 err.set_primary_message(format!(
1909 "{} cannot be {} between threads safely",
1910 future_or_generator, trait_verb
1913 let original_span = err.span.primary_span().unwrap();
1914 let original_span = self.tcx.sess.source_map().guess_head_span(original_span);
1915 let mut span = MultiSpan::from_span(original_span);
1917 let message = outer_generator
1918 .and_then(|generator_did| {
1919 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1920 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1921 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1923 .parent(generator_did)
1924 .and_then(|parent_did| parent_did.as_local())
1925 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
1926 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1928 format!("future returned by `{}` is not {}", name, trait_name)
1930 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1931 format!("future created by async block is not {}", trait_name)
1933 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1934 format!("future created by async closure is not {}", trait_name)
1938 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1940 span.push_span_label(original_span, message);
1943 format!("is not {}", trait_name)
1945 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
1948 let mut explain_yield = |interior_span: Span,
1950 scope_span: Option<Span>| {
1951 let mut span = MultiSpan::from_span(yield_span);
1952 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1953 // #70935: If snippet contains newlines, display "the value" instead
1954 // so that we do not emit complex diagnostics.
1955 let snippet = &format!("`{}`", snippet);
1956 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
1957 // note: future is not `Send` as this value is used across an await
1958 // --> $DIR/issue-70935-complex-spans.rs:13:9
1960 // LL | baz(|| async {
1961 // | ______________-
1964 // LL | | foo(tx.clone());
1966 // | | - ^^^^^^ await occurs here, with value maybe used later
1968 // | has type `closure` which is not `Send`
1969 // note: value is later dropped here
1973 span.push_span_label(
1975 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
1977 span.push_span_label(
1979 format!("has type `{}` which {}", target_ty, trait_explanation),
1981 // If available, use the scope span to annotate the drop location.
1982 let mut scope_note = None;
1983 if let Some(scope_span) = scope_span {
1984 let scope_span = source_map.end_point(scope_span);
1986 let msg = format!("{} is later dropped here", snippet);
1987 if source_map.is_multiline(yield_span.between(scope_span)) {
1988 span.push_span_label(scope_span, msg);
1990 scope_note = Some((scope_span, msg));
1996 "{} {} as this value is used across {}",
1997 future_or_generator, trait_explanation, an_await_or_yield
2000 if let Some((span, msg)) = scope_note {
2001 err.span_note(span, &msg);
2005 match interior_or_upvar_span {
2006 GeneratorInteriorOrUpvar::Interior(interior_span) => {
2007 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2008 if let Some(await_span) = from_awaited_ty {
2009 // The type causing this obligation is one being awaited at await_span.
2010 let mut span = MultiSpan::from_span(await_span);
2011 span.push_span_label(
2014 "await occurs here on type `{}`, which {}",
2015 target_ty, trait_explanation
2021 "future {not_trait} as it awaits another future which {not_trait}",
2022 not_trait = trait_explanation
2026 // Look at the last interior type to get a span for the `.await`.
2028 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
2029 typeck_results.as_ref().map(|t| &t.generator_interior_types)
2031 explain_yield(interior_span, yield_span, scope_span);
2034 if let Some(expr_id) = expr {
2035 let expr = hir.expect_expr(expr_id);
2036 debug!("target_ty evaluated from {:?}", expr);
2038 let parent = hir.get_parent_node(expr_id);
2039 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2040 let parent_span = hir.span(parent);
2041 let parent_did = parent.owner.to_def_id();
2044 // fn foo(&self) -> i32 {}
2047 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2050 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2052 .expr_adjustments(expr)
2054 .any(|adj| adj.is_region_borrow())
2060 // struct Foo(*const u8);
2061 // bar(Foo(std::ptr::null())).await;
2062 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2064 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
2065 let is_raw_borrow_inside_fn_like_call =
2066 match self.tcx.def_kind(parent_did) {
2067 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2070 if let Some(typeck_results) = typeck_results {
2071 if (typeck_results.is_method_call(e) && is_region_borrow)
2072 || is_raw_borrow_inside_fn_like_call
2076 "consider moving this into a `let` \
2077 binding to create a shorter lived borrow",
2085 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2086 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2087 let refers_to_non_sync = match target_ty.kind() {
2088 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2089 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2095 let (span_label, span_note) = match refers_to_non_sync {
2096 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2097 // include suggestions to make `T: Sync` so that `&T: Send`
2100 "has type `{}` which {}, because `{}` is not `Sync`",
2101 target_ty, trait_explanation, ref_ty
2104 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2109 format!("has type `{}` which {}", target_ty, trait_explanation),
2110 format!("captured value {}", trait_explanation),
2114 let mut span = MultiSpan::from_span(upvar_span);
2115 span.push_span_label(upvar_span, span_label);
2116 err.span_note(span, &span_note);
2120 // Add a note for the item obligation that remains - normally a note pointing to the
2121 // bound that introduced the obligation (e.g. `T: Send`).
2122 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2123 self.note_obligation_cause_code(
2125 &obligation.predicate,
2126 obligation.param_env,
2129 &mut Default::default(),
2133 fn note_obligation_cause_code<T>(
2135 err: &mut Diagnostic,
2137 param_env: ty::ParamEnv<'tcx>,
2138 cause_code: &ObligationCauseCode<'tcx>,
2139 obligated_types: &mut Vec<Ty<'tcx>>,
2140 seen_requirements: &mut FxHashSet<DefId>,
2146 ObligationCauseCode::ExprAssignable
2147 | ObligationCauseCode::MatchExpressionArm { .. }
2148 | ObligationCauseCode::Pattern { .. }
2149 | ObligationCauseCode::IfExpression { .. }
2150 | ObligationCauseCode::IfExpressionWithNoElse
2151 | ObligationCauseCode::MainFunctionType
2152 | ObligationCauseCode::StartFunctionType
2153 | ObligationCauseCode::IntrinsicType
2154 | ObligationCauseCode::MethodReceiver
2155 | ObligationCauseCode::ReturnNoExpression
2156 | ObligationCauseCode::UnifyReceiver(..)
2157 | ObligationCauseCode::OpaqueType
2158 | ObligationCauseCode::MiscObligation
2159 | ObligationCauseCode::WellFormed(..)
2160 | ObligationCauseCode::MatchImpl(..)
2161 | ObligationCauseCode::ReturnType
2162 | ObligationCauseCode::ReturnValue(_)
2163 | ObligationCauseCode::BlockTailExpression(_)
2164 | ObligationCauseCode::AwaitableExpr(_)
2165 | ObligationCauseCode::ForLoopIterator
2166 | ObligationCauseCode::QuestionMark
2167 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2168 | ObligationCauseCode::LetElse
2169 | ObligationCauseCode::BinOp { .. } => {}
2170 ObligationCauseCode::SliceOrArrayElem => {
2171 err.note("slice and array elements must have `Sized` type");
2173 ObligationCauseCode::TupleElem => {
2174 err.note("only the last element of a tuple may have a dynamically sized type");
2176 ObligationCauseCode::ProjectionWf(data) => {
2177 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2179 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2181 "required so that reference `{}` does not outlive its referent",
2185 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2187 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2191 ObligationCauseCode::ItemObligation(_item_def_id) => {
2192 // We hold the `DefId` of the item introducing the obligation, but displaying it
2193 // doesn't add user usable information. It always point at an associated item.
2195 ObligationCauseCode::BindingObligation(item_def_id, span) => {
2196 let item_name = tcx.def_path_str(item_def_id);
2197 let mut multispan = MultiSpan::from(span);
2198 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2199 let sm = tcx.sess.source_map();
2201 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2202 (Ok(l), Ok(r)) => l.line == r.line,
2205 if !ident.span.overlaps(span) && !same_line {
2207 .push_span_label(ident.span, "required by a bound in this".to_string());
2210 let descr = format!("required by a bound in `{}`", item_name);
2211 if span != DUMMY_SP {
2212 let msg = format!("required by this bound in `{}`", item_name);
2213 multispan.push_span_label(span, msg);
2214 err.span_note(multispan, &descr);
2216 err.span_note(tcx.def_span(item_def_id), &descr);
2219 ObligationCauseCode::ObjectCastObligation(object_ty) => {
2221 "required for the cast to the object type `{}`",
2222 self.ty_to_string(object_ty)
2225 ObligationCauseCode::Coercion { source: _, target } => {
2226 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2228 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2230 "the `Copy` trait is required because the repeated element will be copied",
2235 "consider creating a new `const` item and initializing it with the result \
2236 of the function call to be used in the repeat position, like \
2237 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2241 if self.tcx.sess.is_nightly_build() && is_const_fn {
2243 "create an inline `const` block, see RFC #2920 \
2244 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2248 ObligationCauseCode::VariableType(hir_id) => {
2249 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2250 match self.tcx.hir().find(parent_node) {
2251 Some(Node::Local(hir::Local {
2252 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2255 // When encountering an assignment of an unsized trait, like
2256 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2257 // order to use have a slice instead.
2258 err.span_suggestion_verbose(
2259 span.shrink_to_lo(),
2260 "consider borrowing here",
2262 Applicability::MachineApplicable,
2264 err.note("all local variables must have a statically known size");
2266 Some(Node::Param(param)) => {
2267 err.span_suggestion_verbose(
2268 param.ty_span.shrink_to_lo(),
2269 "function arguments must have a statically known size, borrowed types \
2270 always have a known size",
2272 Applicability::MachineApplicable,
2276 err.note("all local variables must have a statically known size");
2279 if !self.tcx.features().unsized_locals {
2280 err.help("unsized locals are gated as an unstable feature");
2283 ObligationCauseCode::SizedArgumentType(sp) => {
2284 if let Some(span) = sp {
2285 err.span_suggestion_verbose(
2286 span.shrink_to_lo(),
2287 "function arguments must have a statically known size, borrowed types \
2288 always have a known size",
2290 Applicability::MachineApplicable,
2293 err.note("all function arguments must have a statically known size");
2295 if tcx.sess.opts.unstable_features.is_nightly_build()
2296 && !self.tcx.features().unsized_fn_params
2298 err.help("unsized fn params are gated as an unstable feature");
2301 ObligationCauseCode::SizedReturnType => {
2302 err.note("the return type of a function must have a statically known size");
2304 ObligationCauseCode::SizedYieldType => {
2305 err.note("the yield type of a generator must have a statically known size");
2307 ObligationCauseCode::SizedBoxType => {
2308 err.note("the type of a box expression must have a statically known size");
2310 ObligationCauseCode::AssignmentLhsSized => {
2311 err.note("the left-hand-side of an assignment must have a statically known size");
2313 ObligationCauseCode::TupleInitializerSized => {
2314 err.note("tuples must have a statically known size to be initialized");
2316 ObligationCauseCode::StructInitializerSized => {
2317 err.note("structs must have a statically known size to be initialized");
2319 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2321 AdtKind::Struct => {
2324 "the last field of a packed struct may only have a \
2325 dynamically sized type if it does not need drop to be run",
2329 "only the last field of a struct may have a dynamically sized type",
2334 err.note("no field of a union may have a dynamically sized type");
2337 err.note("no field of an enum variant may have a dynamically sized type");
2340 err.help("change the field's type to have a statically known size");
2341 err.span_suggestion(
2342 span.shrink_to_lo(),
2343 "borrowed types always have a statically known size",
2345 Applicability::MachineApplicable,
2347 err.multipart_suggestion(
2348 "the `Box` type always has a statically known size and allocates its contents \
2351 (span.shrink_to_lo(), "Box<".to_string()),
2352 (span.shrink_to_hi(), ">".to_string()),
2354 Applicability::MachineApplicable,
2357 ObligationCauseCode::ConstSized => {
2358 err.note("constant expressions must have a statically known size");
2360 ObligationCauseCode::InlineAsmSized => {
2361 err.note("all inline asm arguments must have a statically known size");
2363 ObligationCauseCode::ConstPatternStructural => {
2364 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2366 ObligationCauseCode::SharedStatic => {
2367 err.note("shared static variables must have a type that implements `Sync`");
2369 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2370 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2371 let ty = parent_trait_ref.skip_binder().self_ty();
2372 if parent_trait_ref.references_error() {
2373 // NOTE(eddyb) this was `.cancel()`, but `err`
2374 // is borrowed, so we can't fully defuse it.
2375 err.downgrade_to_delayed_bug();
2379 // If the obligation for a tuple is set directly by a Generator or Closure,
2380 // then the tuple must be the one containing capture types.
2381 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2384 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) =
2387 let parent_trait_ref =
2388 self.resolve_vars_if_possible(data.parent_trait_pred);
2389 let ty = parent_trait_ref.skip_binder().self_ty();
2390 matches!(ty.kind(), ty::Generator(..))
2391 || matches!(ty.kind(), ty::Closure(..))
2397 // Don't print the tuple of capture types
2398 if !is_upvar_tys_infer_tuple {
2399 let msg = format!("required because it appears within the type `{}`", ty);
2401 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2402 Some(ident) => err.span_note(ident.span, &msg),
2403 None => err.note(&msg),
2405 _ => err.note(&msg),
2409 obligated_types.push(ty);
2411 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2412 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2413 // #74711: avoid a stack overflow
2414 ensure_sufficient_stack(|| {
2415 self.note_obligation_cause_code(
2425 ensure_sufficient_stack(|| {
2426 self.note_obligation_cause_code(
2430 &cause_code.peel_derives(),
2437 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2438 let mut parent_trait_pred =
2439 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2440 parent_trait_pred.remap_constness_diag(param_env);
2441 let parent_def_id = parent_trait_pred.def_id();
2443 "required because of the requirements on the impl of `{}` for `{}`",
2444 parent_trait_pred.print_modifiers_and_trait_path(),
2445 parent_trait_pred.skip_binder().self_ty()
2447 let mut is_auto_trait = false;
2448 match self.tcx.hir().get_if_local(data.impl_def_id) {
2449 Some(Node::Item(hir::Item {
2450 kind: hir::ItemKind::Trait(is_auto, ..),
2454 // FIXME: we should do something else so that it works even on crate foreign
2456 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2457 err.span_note(ident.span, &msg)
2459 Some(Node::Item(hir::Item {
2460 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2463 let mut spans = Vec::with_capacity(2);
2464 if let Some(trait_ref) = of_trait {
2465 spans.push(trait_ref.path.span);
2467 spans.push(self_ty.span);
2468 err.span_note(spans, &msg)
2470 _ => err.note(&msg),
2473 let mut parent_predicate = parent_trait_pred.to_predicate(tcx);
2474 let mut data = &data.derived;
2476 seen_requirements.insert(parent_def_id);
2478 // We don't want to point at the ADT saying "required because it appears within
2479 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2480 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2483 let child_trait_ref =
2484 self.resolve_vars_if_possible(derived.parent_trait_pred);
2485 let child_def_id = child_trait_ref.def_id();
2486 if seen_requirements.insert(child_def_id) {
2490 parent_predicate = child_trait_ref.to_predicate(tcx);
2491 parent_trait_pred = child_trait_ref;
2494 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2495 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2496 let child_trait_pred =
2497 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2498 let child_def_id = child_trait_pred.def_id();
2499 if seen_requirements.insert(child_def_id) {
2503 data = &child.derived;
2504 parent_predicate = child_trait_pred.to_predicate(tcx);
2505 parent_trait_pred = child_trait_pred;
2509 "{} redundant requirement{} hidden",
2514 "required because of the requirements on the impl of `{}` for `{}`",
2515 parent_trait_pred.print_modifiers_and_trait_path(),
2516 parent_trait_pred.skip_binder().self_ty()
2519 // #74711: avoid a stack overflow
2520 ensure_sufficient_stack(|| {
2521 self.note_obligation_cause_code(
2531 ObligationCauseCode::DerivedObligation(ref data) => {
2532 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2533 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2534 // #74711: avoid a stack overflow
2535 ensure_sufficient_stack(|| {
2536 self.note_obligation_cause_code(
2546 ObligationCauseCode::FunctionArgumentObligation {
2551 let hir = self.tcx.hir();
2552 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2553 hir.find(arg_hir_id)
2555 let in_progress_typeck_results =
2556 self.in_progress_typeck_results.map(|t| t.borrow());
2557 let parent_id = hir.get_parent_item(arg_hir_id);
2558 let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
2559 Some(t) if t.hir_owner == parent_id => t,
2560 _ => self.tcx.typeck(parent_id),
2562 let ty = typeck_results.expr_ty_adjusted(expr);
2563 let span = expr.peel_blocks().span;
2564 if Some(span) != err.span.primary_span() {
2567 &if ty.references_error() {
2570 format!("this tail expression is of type `{:?}`", ty)
2575 if let Some(Node::Expr(hir::Expr {
2577 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2578 | hir::ExprKind::MethodCall(
2579 hir::PathSegment { ident: Ident { span, .. }, .. },
2583 })) = hir.find(call_hir_id)
2585 if Some(*span) != err.span.primary_span() {
2586 err.span_label(*span, "required by a bound introduced by this call");
2589 ensure_sufficient_stack(|| {
2590 self.note_obligation_cause_code(
2600 ObligationCauseCode::CompareImplMethodObligation { trait_item_def_id, .. } => {
2601 let item_name = self.tcx.item_name(trait_item_def_id);
2603 "the requirement `{}` appears on the impl method `{}` but not on the \
2604 corresponding trait method",
2605 predicate, item_name,
2609 .opt_item_ident(trait_item_def_id)
2611 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2612 let mut assoc_span: MultiSpan = sp.into();
2613 assoc_span.push_span_label(
2615 format!("this trait method doesn't have the requirement `{}`", predicate),
2617 if let Some(ident) = self
2619 .opt_associated_item(trait_item_def_id)
2620 .and_then(|i| self.tcx.opt_item_ident(i.container.id()))
2622 assoc_span.push_span_label(ident.span, "in this trait");
2624 err.span_note(assoc_span, &msg);
2626 ObligationCauseCode::CompareImplTypeObligation { trait_item_def_id, .. } => {
2627 let item_name = self.tcx.item_name(trait_item_def_id);
2629 "the requirement `{}` appears on the associated impl type `{}` but not on the \
2630 corresponding associated trait type",
2631 predicate, item_name,
2633 let sp = self.tcx.def_span(trait_item_def_id);
2634 let mut assoc_span: MultiSpan = sp.into();
2635 assoc_span.push_span_label(
2638 "this trait associated type doesn't have the requirement `{}`",
2642 if let Some(ident) = self
2644 .opt_associated_item(trait_item_def_id)
2645 .and_then(|i| self.tcx.opt_item_ident(i.container.id()))
2647 assoc_span.push_span_label(ident.span, "in this trait");
2649 err.span_note(assoc_span, &msg);
2651 ObligationCauseCode::CompareImplConstObligation => {
2653 "the requirement `{}` appears on the associated impl constant \
2654 but not on the corresponding associated trait constant",
2658 ObligationCauseCode::TrivialBound => {
2659 err.help("see issue #48214");
2660 if tcx.sess.opts.unstable_features.is_nightly_build() {
2661 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2667 fn suggest_new_overflow_limit(&self, err: &mut Diagnostic) {
2668 let suggested_limit = match self.tcx.recursion_limit() {
2669 Limit(0) => Limit(2),
2673 "consider increasing the recursion limit by adding a \
2674 `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
2676 self.tcx.crate_name(LOCAL_CRATE),
2680 fn suggest_await_before_try(
2682 err: &mut Diagnostic,
2683 obligation: &PredicateObligation<'tcx>,
2684 trait_pred: ty::PolyTraitPredicate<'tcx>,
2688 "suggest_await_before_try: obligation={:?}, span={:?}, trait_pred={:?}, trait_pred_self_ty={:?}",
2692 trait_pred.self_ty()
2694 let body_hir_id = obligation.cause.body_id;
2695 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2697 if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
2698 let body = self.tcx.hir().body(body_id);
2699 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2700 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2702 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2704 // Do not check on infer_types to avoid panic in evaluate_obligation.
2705 if self_ty.has_infer_types() {
2708 let self_ty = self.tcx.erase_regions(self_ty);
2710 let impls_future = self.type_implements_trait(
2712 self_ty.skip_binder(),
2714 obligation.param_env,
2717 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2718 // `<T as Future>::Output`
2719 let projection_ty = ty::ProjectionTy {
2721 substs: self.tcx.mk_substs_trait(
2722 trait_pred.self_ty().skip_binder(),
2723 &self.fresh_substs_for_item(span, item_def_id)[1..],
2729 let mut selcx = SelectionContext::new(self);
2731 let mut obligations = vec![];
2732 let normalized_ty = normalize_projection_type(
2734 obligation.param_env,
2736 obligation.cause.clone(),
2742 "suggest_await_before_try: normalized_projection_type {:?}",
2743 self.resolve_vars_if_possible(normalized_ty)
2745 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2746 obligation.param_env,
2748 normalized_ty.ty().unwrap(),
2750 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2751 if self.predicate_may_hold(&try_obligation)
2752 && impls_future.must_apply_modulo_regions()
2753 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2754 && snippet.ends_with('?')
2756 err.span_suggestion_verbose(
2757 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2758 "consider `await`ing on the `Future`",
2759 ".await".to_string(),
2760 Applicability::MaybeIncorrect,
2767 fn suggest_floating_point_literal(
2769 obligation: &PredicateObligation<'tcx>,
2770 err: &mut Diagnostic,
2771 trait_ref: &ty::PolyTraitRef<'tcx>,
2773 let rhs_span = match obligation.cause.code() {
2774 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit } if *is_lit => span,
2778 trait_ref.skip_binder().self_ty().kind(),
2779 trait_ref.skip_binder().substs.type_at(1).kind(),
2781 (ty::Float(_), ty::Infer(InferTy::IntVar(_))) => {
2782 err.span_suggestion_verbose(
2783 rhs_span.shrink_to_hi(),
2784 "consider using a floating-point literal by writing it with `.0`",
2786 Applicability::MaybeIncorrect,
2795 obligation: &PredicateObligation<'tcx>,
2796 err: &mut Diagnostic,
2797 trait_pred: ty::PolyTraitPredicate<'tcx>,
2799 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
2802 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
2803 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
2807 let is_derivable_trait = match diagnostic_name {
2808 sym::Default => !adt.is_enum(),
2809 sym::PartialEq | sym::PartialOrd => {
2810 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
2811 trait_pred.skip_binder().self_ty() == rhs_ty
2813 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
2816 is_derivable_trait &&
2817 // Ensure all fields impl the trait.
2818 adt.all_fields().all(|field| {
2819 let field_ty = field.ty(self.tcx, substs);
2820 let trait_substs = match diagnostic_name {
2821 sym::PartialEq | sym::PartialOrd => {
2822 self.tcx.mk_substs_trait(field_ty, &[field_ty.into()])
2824 _ => self.tcx.mk_substs_trait(field_ty, &[]),
2826 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
2827 trait_ref: ty::TraitRef {
2828 substs: trait_substs,
2829 ..trait_pred.skip_binder().trait_ref
2833 let field_obl = Obligation::new(
2834 obligation.cause.clone(),
2835 obligation.param_env,
2836 trait_pred.to_predicate(self.tcx),
2838 self.predicate_must_hold_modulo_regions(&field_obl)
2842 err.span_suggestion_verbose(
2843 self.tcx.def_span(adt.did()).shrink_to_lo(),
2845 "consider annotating `{}` with `#[derive({})]`",
2846 trait_pred.skip_binder().self_ty(),
2847 diagnostic_name.to_string(),
2849 format!("#[derive({})]\n", diagnostic_name.to_string()),
2850 Applicability::MaybeIncorrect,
2856 /// Collect all the returned expressions within the input expression.
2857 /// Used to point at the return spans when we want to suggest some change to them.
2859 pub struct ReturnsVisitor<'v> {
2860 pub returns: Vec<&'v hir::Expr<'v>>,
2861 in_block_tail: bool,
2864 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2865 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2866 // Visit every expression to detect `return` paths, either through the function's tail
2867 // expression or `return` statements. We walk all nodes to find `return` statements, but
2868 // we only care about tail expressions when `in_block_tail` is `true`, which means that
2869 // they're in the return path of the function body.
2871 hir::ExprKind::Ret(Some(ex)) => {
2872 self.returns.push(ex);
2874 hir::ExprKind::Block(block, _) if self.in_block_tail => {
2875 self.in_block_tail = false;
2876 for stmt in block.stmts {
2877 hir::intravisit::walk_stmt(self, stmt);
2879 self.in_block_tail = true;
2880 if let Some(expr) = block.expr {
2881 self.visit_expr(expr);
2884 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
2885 self.visit_expr(then);
2886 if let Some(el) = else_opt {
2887 self.visit_expr(el);
2890 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2892 self.visit_expr(arm.body);
2895 // We need to walk to find `return`s in the entire body.
2896 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2897 _ => self.returns.push(ex),
2901 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2902 assert!(!self.in_block_tail);
2903 if body.generator_kind().is_none() {
2904 if let hir::ExprKind::Block(block, None) = body.value.kind {
2905 if block.expr.is_some() {
2906 self.in_block_tail = true;
2910 hir::intravisit::walk_body(self, body);
2914 /// Collect all the awaited expressions within the input expression.
2916 struct AwaitsVisitor {
2917 awaits: Vec<hir::HirId>,
2920 impl<'v> Visitor<'v> for AwaitsVisitor {
2921 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2922 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2923 self.awaits.push(id)
2925 hir::intravisit::walk_expr(self, ex)
2929 pub trait NextTypeParamName {
2930 fn next_type_param_name(&self, name: Option<&str>) -> String;
2933 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2934 fn next_type_param_name(&self, name: Option<&str>) -> String {
2935 // This is the list of possible parameter names that we might suggest.
2936 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2937 let name = name.as_deref();
2938 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2939 let used_names = self
2941 .filter_map(|p| match p.name {
2942 hir::ParamName::Plain(ident) => Some(ident.name),
2945 .collect::<Vec<_>>();
2949 .find(|n| !used_names.contains(&Symbol::intern(n)))
2950 .unwrap_or(&"ParamName")
2955 fn suggest_trait_object_return_type_alternatives(
2956 err: &mut Diagnostic,
2959 is_object_safe: bool,
2961 err.span_suggestion(
2963 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2966 Applicability::MaybeIncorrect,
2968 err.span_suggestion(
2971 "use `impl {}` as the return type if all return paths have the same type but you \
2972 want to expose only the trait in the signature",
2975 format!("impl {}", trait_obj),
2976 Applicability::MaybeIncorrect,
2979 err.multipart_suggestion(
2981 "use a boxed trait object if all return paths implement trait `{}`",
2985 (ret_ty.shrink_to_lo(), "Box<".to_string()),
2986 (ret_ty.shrink_to_hi(), ">".to_string()),
2988 Applicability::MaybeIncorrect,