2 EvaluationResult, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation,
6 use crate::autoderef::Autoderef;
7 use crate::infer::InferCtxt;
8 use crate::traits::normalize_projection_type;
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_data_structures::stack::ensure_sufficient_stack;
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.tail_span_for_predicate_suggestion(),
323 format!("{} {}", if generics.has_where_clause { "," } else { " where" }, pred,),
327 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
328 /// it can also be an `impl Trait` param that needs to be decomposed to a type
329 /// param for cleaner code.
330 fn suggest_restriction<'tcx>(
332 generics: &hir::Generics<'tcx>,
334 err: &mut Diagnostic,
335 fn_sig: Option<&hir::FnSig<'_>>,
336 projection: Option<&ty::ProjectionTy<'_>>,
337 trait_pred: ty::PolyTraitPredicate<'tcx>,
338 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
340 // When we are dealing with a trait, `super_traits` will be `Some`:
341 // Given `trait T: A + B + C {}`
342 // - ^^^^^^^^^ GenericBounds
345 let span = generics.span_for_predicates_or_empty_place();
346 if span.from_expansion() || span.desugaring_kind().is_some() {
349 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
350 if let Some((bound_str, fn_sig)) =
351 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind() {
352 // Shenanigans to get the `Trait` from the `impl Trait`.
353 ty::Param(param) => {
354 // `fn foo(t: impl Trait)`
355 // ^^^^^ get this string
356 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
361 // We know we have an `impl Trait` that doesn't satisfy a required projection.
363 // Find all of the occurrences of `impl Trait` for `Trait` in the function arguments'
364 // types. There should be at least one, but there might be *more* than one. In that
365 // case we could just ignore it and try to identify which one needs the restriction,
366 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
368 let mut ty_spans = vec![];
369 let impl_trait_str = format!("impl {}", bound_str);
370 for input in fn_sig.decl.inputs {
371 if let hir::TyKind::Path(hir::QPath::Resolved(
373 hir::Path { segments: [segment], .. },
376 if segment.ident.as_str() == impl_trait_str.as_str() {
377 // `fn foo(t: impl Trait)`
378 // ^^^^^^^^^^ get this to suggest `T` instead
380 // There might be more than one `impl Trait`.
381 ty_spans.push(input.span);
386 let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
387 // The type param `T: Trait` we will suggest to introduce.
388 let type_param = format!("{}: {}", type_param_name, bound_str);
390 // FIXME: modify the `trait_pred` instead of string shenanigans.
391 // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
392 let pred = trait_pred.to_predicate(tcx).to_string();
393 let pred = pred.replace(&impl_trait_str, &type_param_name);
395 if let Some(span) = generics.span_for_param_suggestion() {
396 (span, format!(", {}", type_param))
398 (generics.span, format!("<{}>", type_param))
400 // `fn foo(t: impl Trait)`
401 // ^ suggest `where <T as Trait>::A: Bound`
402 predicate_constraint(generics, pred),
404 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
406 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
407 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
408 // `fn foo(t: impl Trait<A: Bound>)` instead.
409 err.multipart_suggestion(
410 "introduce a type parameter with a trait bound instead of using `impl Trait`",
412 Applicability::MaybeIncorrect,
415 // Trivial case: `T` needs an extra bound: `T: Bound`.
416 let (sp, suggestion) = match (
420 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
423 (_, None) => predicate_constraint(generics, trait_pred.to_predicate(tcx).to_string()),
424 (None, Some((ident, []))) => (
425 ident.span.shrink_to_hi(),
426 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
428 (_, Some((_, [.., bounds]))) => (
429 bounds.span().shrink_to_hi(),
430 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
432 (Some(_), Some((_, []))) => (
433 generics.span.shrink_to_hi(),
434 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
438 err.span_suggestion_verbose(
440 &format!("consider further restricting {}", msg),
442 Applicability::MachineApplicable,
447 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
448 fn suggest_restricting_param_bound(
450 mut err: &mut Diagnostic,
451 trait_pred: ty::PolyTraitPredicate<'tcx>,
454 let self_ty = trait_pred.skip_binder().self_ty();
455 let (param_ty, projection) = match self_ty.kind() {
456 ty::Param(_) => (true, None),
457 ty::Projection(projection) => (false, Some(projection)),
461 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
462 // don't suggest `T: Sized + ?Sized`.
463 let mut hir_id = body_id;
464 while let Some(node) = self.tcx.hir().find(hir_id) {
466 hir::Node::Item(hir::Item {
468 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
470 }) if self_ty == self.tcx.types.self_param => {
472 // Restricting `Self` for a single method.
481 Some((ident, bounds)),
486 hir::Node::TraitItem(hir::TraitItem {
488 kind: hir::TraitItemKind::Fn(..),
490 }) if self_ty == self.tcx.types.self_param => {
492 // Restricting `Self` for a single method.
494 self.tcx, &generics, "`Self`", err, None, projection, trait_pred, None,
499 hir::Node::TraitItem(hir::TraitItem {
501 kind: hir::TraitItemKind::Fn(fn_sig, ..),
504 | hir::Node::ImplItem(hir::ImplItem {
506 kind: hir::ImplItemKind::Fn(fn_sig, ..),
509 | hir::Node::Item(hir::Item {
510 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
511 }) if projection.is_some() => {
512 // Missing restriction on associated type of type parameter (unmet projection).
516 "the associated type",
525 hir::Node::Item(hir::Item {
527 hir::ItemKind::Trait(_, _, generics, ..)
528 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
530 }) if projection.is_some() => {
531 // Missing restriction on associated type of type parameter (unmet projection).
535 "the associated type",
545 hir::Node::Item(hir::Item {
547 hir::ItemKind::Struct(_, generics)
548 | hir::ItemKind::Enum(_, generics)
549 | hir::ItemKind::Union(_, generics)
550 | hir::ItemKind::Trait(_, _, generics, ..)
551 | hir::ItemKind::Impl(hir::Impl { generics, .. })
552 | hir::ItemKind::Fn(_, generics, _)
553 | hir::ItemKind::TyAlias(_, generics)
554 | hir::ItemKind::TraitAlias(generics, _)
555 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
558 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
559 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
562 // Missing generic type parameter bound.
563 let param_name = self_ty.to_string();
564 let constraint = with_no_trimmed_paths!(
565 trait_pred.print_modifiers_and_trait_path().to_string()
567 if suggest_constraining_type_param(
573 Some(trait_pred.def_id()),
579 hir::Node::Item(hir::Item {
581 hir::ItemKind::Struct(_, generics)
582 | hir::ItemKind::Enum(_, generics)
583 | hir::ItemKind::Union(_, generics)
584 | hir::ItemKind::Trait(_, _, generics, ..)
585 | hir::ItemKind::Impl(hir::Impl { generics, .. })
586 | hir::ItemKind::Fn(_, generics, _)
587 | hir::ItemKind::TyAlias(_, generics)
588 | hir::ItemKind::TraitAlias(generics, _)
589 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
592 // Missing generic type parameter bound.
593 let param_name = self_ty.to_string();
594 let constraint = trait_pred.print_modifiers_and_trait_path().to_string();
595 if suggest_arbitrary_trait_bound(generics, &mut err, ¶m_name, &constraint) {
599 hir::Node::Crate(..) => return,
604 hir_id = self.tcx.hir().local_def_id_to_hir_id(self.tcx.hir().get_parent_item(hir_id));
608 /// When after several dereferencing, the reference satisfies the trait
609 /// binding. This function provides dereference suggestion for this
610 /// specific situation.
611 fn suggest_dereferences(
613 obligation: &PredicateObligation<'tcx>,
614 err: &mut Diagnostic,
615 trait_pred: ty::PolyTraitPredicate<'tcx>,
617 // It only make sense when suggesting dereferences for arguments
618 let ObligationCauseCode::FunctionArgumentObligation { .. } = obligation.cause.code() else {
621 let param_env = obligation.param_env;
622 let body_id = obligation.cause.body_id;
623 let span = obligation.cause.span;
624 let mut real_trait_pred = trait_pred;
625 let mut code = obligation.cause.code();
626 while let Some((parent_code, parent_trait_pred)) = code.parent() {
628 if let Some(parent_trait_pred) = parent_trait_pred {
629 real_trait_pred = parent_trait_pred;
631 let Some(real_ty) = real_trait_pred.self_ty().no_bound_vars() else {
635 if let ty::Ref(region, base_ty, mutbl) = *real_ty.kind() {
636 let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty, span);
637 if let Some(steps) = autoderef.find_map(|(ty, steps)| {
639 let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
640 let real_trait_pred_and_ty =
641 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
642 let obligation = self
643 .mk_trait_obligation_with_new_self_ty(param_env, real_trait_pred_and_ty);
644 Some(steps).filter(|_| self.predicate_may_hold(&obligation))
647 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
648 // Don't care about `&mut` because `DerefMut` is used less
649 // often and user will not expect autoderef happens.
650 if src.starts_with('&') && !src.starts_with("&mut ") {
651 let derefs = "*".repeat(steps);
654 "consider dereferencing here",
655 format!("&{}{}", derefs, &src[1..]),
656 Applicability::MachineApplicable,
662 } else if real_trait_pred != trait_pred {
663 // This branch addresses #87437.
664 let real_trait_pred_and_base_ty =
665 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, base_ty));
666 let obligation = self.mk_trait_obligation_with_new_self_ty(
668 real_trait_pred_and_base_ty,
670 if self.predicate_may_hold(&obligation) {
671 err.span_suggestion_verbose(
673 "consider dereferencing here",
675 Applicability::MachineApplicable,
685 /// Given a closure's `DefId`, return the given name of the closure.
687 /// This doesn't account for reassignments, but it's only used for suggestions.
688 fn get_closure_name(&self, def_id: DefId, err: &mut Diagnostic, msg: &str) -> Option<String> {
689 let get_name = |err: &mut Diagnostic, kind: &hir::PatKind<'_>| -> Option<String> {
690 // Get the local name of this closure. This can be inaccurate because
691 // of the possibility of reassignment, but this should be good enough.
693 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
694 Some(format!("{}", name))
703 let hir = self.tcx.hir();
704 let hir_id = hir.local_def_id_to_hir_id(def_id.as_local()?);
705 let parent_node = hir.get_parent_node(hir_id);
706 match hir.find(parent_node) {
707 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
708 get_name(err, &local.pat.kind)
710 // Different to previous arm because one is `&hir::Local` and the other
711 // is `P<hir::Local>`.
712 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
717 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
718 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
719 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
722 obligation: &PredicateObligation<'tcx>,
723 err: &mut Diagnostic,
724 trait_pred: ty::PolyTraitPredicate<'tcx>,
726 let self_ty = trait_pred.self_ty().skip_binder();
728 let (def_id, output_ty, callable) = match *self_ty.kind() {
729 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
730 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
733 let msg = format!("use parentheses to call the {}", callable);
735 let output_ty = self.tcx.liberate_late_bound_regions(def_id, output_ty);
737 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output_ty));
740 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
742 match self.evaluate_obligation(&new_obligation) {
744 EvaluationResult::EvaluatedToOk
745 | EvaluationResult::EvaluatedToOkModuloRegions
746 | EvaluationResult::EvaluatedToAmbig,
750 let hir = self.tcx.hir();
751 // Get the name of the callable and the arguments to be used in the suggestion.
752 let (snippet, sugg) = match hir.get_if_local(def_id) {
753 Some(hir::Node::Expr(hir::Expr {
754 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
757 err.span_label(*span, "consider calling this closure");
758 let Some(name) = self.get_closure_name(def_id, err, &msg) else {
761 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
762 let sugg = format!("({})", args);
763 (format!("{}{}", name, sugg), sugg)
765 Some(hir::Node::Item(hir::Item {
767 kind: hir::ItemKind::Fn(.., body_id),
770 err.span_label(ident.span, "consider calling this function");
771 let body = hir.body(*body_id);
775 .map(|arg| match &arg.pat.kind {
776 hir::PatKind::Binding(_, _, ident, None)
777 // FIXME: provide a better suggestion when encountering `SelfLower`, it
778 // should suggest a method call.
779 if ident.name != kw::SelfLower => ident.to_string(),
780 _ => "_".to_string(),
784 let sugg = format!("({})", args);
785 (format!("{}{}", ident, sugg), sugg)
789 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArgumentObligation { .. })
791 // When the obligation error has been ensured to have been caused by
792 // an argument, the `obligation.cause.span` points at the expression
793 // of the argument, so we can provide a suggestion. Otherwise, we give
794 // a more general note.
795 err.span_suggestion_verbose(
796 obligation.cause.span.shrink_to_hi(),
799 Applicability::HasPlaceholders,
802 err.help(&format!("{}: `{}`", msg, snippet));
807 fn suggest_add_reference_to_arg(
809 obligation: &PredicateObligation<'tcx>,
810 err: &mut Diagnostic,
811 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
812 has_custom_message: bool,
814 let span = obligation.cause.span;
816 let code = if let ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } =
817 obligation.cause.code()
820 } else if let ExpnKind::Desugaring(DesugaringKind::ForLoop) =
821 span.ctxt().outer_expn_data().kind
823 obligation.cause.code()
828 // List of traits for which it would be nonsensical to suggest borrowing.
829 // For instance, immutable references are always Copy, so suggesting to
830 // borrow would always succeed, but it's probably not what the user wanted.
831 let mut never_suggest_borrow: Vec<_> =
832 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
834 .filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
837 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
838 never_suggest_borrow.push(def_id);
841 let param_env = obligation.param_env;
843 // Try to apply the original trait binding obligation by borrowing.
844 let mut try_borrowing =
845 |old_pred: ty::PolyTraitPredicate<'tcx>, blacklist: &[DefId]| -> bool {
846 if blacklist.contains(&old_pred.def_id()) {
849 // We map bounds to `&T` and `&mut T`
850 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
853 self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
856 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
859 self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, trait_pred.self_ty()),
863 let mk_result = |trait_pred_and_new_ty| {
865 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
866 self.predicate_must_hold_modulo_regions(&obligation)
868 let imm_result = mk_result(trait_pred_and_imm_ref);
869 let mut_result = mk_result(trait_pred_and_mut_ref);
871 if imm_result || mut_result {
872 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
873 // We have a very specific type of error, where just borrowing this argument
874 // might solve the problem. In cases like this, the important part is the
875 // original type obligation, not the last one that failed, which is arbitrary.
876 // Because of this, we modify the error to refer to the original obligation and
877 // return early in the caller.
880 "the trait bound `{}: {}` is not satisfied",
881 // Safe to skip binder here
882 old_pred.self_ty().skip_binder(),
883 old_pred.print_modifiers_and_trait_path(),
885 if has_custom_message {
889 vec![(rustc_errors::DiagnosticMessage::Str(msg), Style::NoStyle)];
891 if snippet.starts_with('&') {
892 // This is already a literal borrow and the obligation is failing
893 // somewhere else in the obligation chain. Do not suggest non-sense.
899 "expected an implementor of trait `{}`",
900 old_pred.print_modifiers_and_trait_path(),
904 // This if is to prevent a special edge-case
906 span.ctxt().outer_expn_data().kind,
907 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
909 // We don't want a borrowing suggestion on the fields in structs,
912 // the_foos: Vec<Foo>
916 if imm_result && mut_result {
917 err.span_suggestions(
919 "consider borrowing here",
920 ["&".to_string(), "&mut ".to_string()].into_iter(),
921 Applicability::MaybeIncorrect,
924 err.span_suggestion_verbose(
927 "consider{} borrowing here",
928 if mut_result { " mutably" } else { "" }
930 format!("&{}", if mut_result { "mut " } else { "" }),
931 Applicability::MaybeIncorrect,
941 if let ObligationCauseCode::ImplDerivedObligation(cause) = &*code {
942 try_borrowing(cause.derived.parent_trait_pred, &[])
943 } else if let ObligationCauseCode::BindingObligation(_, _)
944 | ObligationCauseCode::ItemObligation(_) = code
946 try_borrowing(poly_trait_pred, &never_suggest_borrow)
952 // Suggest borrowing the type
953 fn suggest_borrowing_for_object_cast(
955 err: &mut Diagnostic,
956 obligation: &PredicateObligation<'tcx>,
960 let ty::Dynamic(predicates, _) = object_ty.kind() else { return; };
961 let self_ref_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, self_ty);
963 for predicate in predicates.iter() {
964 if !self.predicate_must_hold_modulo_regions(
965 &obligation.with(predicate.with_self_ty(self.tcx, self_ref_ty)),
972 obligation.cause.span.shrink_to_lo(),
974 "consider borrowing the value, since `&{self_ty}` can be coerced into `{object_ty}`"
977 Applicability::MaybeIncorrect,
981 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
982 /// suggest removing these references until we reach a type that implements the trait.
983 fn suggest_remove_reference(
985 obligation: &PredicateObligation<'tcx>,
986 err: &mut Diagnostic,
987 trait_pred: ty::PolyTraitPredicate<'tcx>,
989 let span = obligation.cause.span;
991 let mut suggested = false;
992 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
994 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
995 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
996 // Do not suggest removal of borrow from type arguments.
1000 // We skip binder here
1001 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1003 for refs_remaining in 0..refs_number {
1004 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1007 suggested_ty = *inner_ty;
1009 // We remap bounds here
1010 let trait_pred_and_suggested_ty =
1011 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1013 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1014 obligation.param_env,
1015 trait_pred_and_suggested_ty,
1018 if self.predicate_may_hold(&new_obligation) {
1023 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1025 let remove_refs = refs_remaining + 1;
1027 let msg = if remove_refs == 1 {
1028 "consider removing the leading `&`-reference".to_string()
1030 format!("consider removing {} leading `&`-references", remove_refs)
1033 err.span_suggestion_short(
1037 Applicability::MachineApplicable,
1047 fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) {
1048 let span = obligation.cause.span;
1050 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() {
1051 let hir = self.tcx.hir();
1052 if let Some(node) = hir_id.and_then(|hir_id| hir.find(hir_id)) {
1053 if let hir::Node::Expr(expr) = node {
1054 // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()`
1055 // and if not maybe suggest doing something else? If we kept the expression around we
1056 // could also check if it is an fn call (very likely) and suggest changing *that*, if
1057 // it is from the local crate.
1058 err.span_suggestion_verbose(
1059 expr.span.shrink_to_hi().with_hi(span.hi()),
1060 "remove the `.await`",
1062 Applicability::MachineApplicable,
1064 // FIXME: account for associated `async fn`s.
1065 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1066 if let ty::PredicateKind::Trait(pred) =
1067 obligation.predicate.kind().skip_binder()
1071 &format!("this call returns `{}`", pred.self_ty()),
1074 if let Some(typeck_results) =
1075 self.in_progress_typeck_results.map(|t| t.borrow())
1076 && let ty = typeck_results.expr_ty_adjusted(base)
1077 && let ty::FnDef(def_id, _substs) = ty.kind()
1078 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1079 hir.get_if_local(*def_id)
1082 "alternatively, consider making `fn {}` asynchronous",
1085 if vis_span.is_empty() {
1086 err.span_suggestion_verbose(
1087 span.shrink_to_lo(),
1089 "async ".to_string(),
1090 Applicability::MaybeIncorrect,
1093 err.span_suggestion_verbose(
1094 vis_span.shrink_to_hi(),
1096 " async".to_string(),
1097 Applicability::MaybeIncorrect,
1107 /// Check if the trait bound is implemented for a different mutability and note it in the
1109 fn suggest_change_mut(
1111 obligation: &PredicateObligation<'tcx>,
1112 err: &mut Diagnostic,
1113 trait_pred: ty::PolyTraitPredicate<'tcx>,
1115 let points_at_arg = matches!(
1116 obligation.cause.code(),
1117 ObligationCauseCode::FunctionArgumentObligation { .. },
1120 let span = obligation.cause.span;
1121 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1123 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1124 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1125 // Do not suggest removal of borrow from type arguments.
1128 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1129 if trait_pred.has_infer_types_or_consts() {
1130 // Do not ICE while trying to find if a reborrow would succeed on a trait with
1131 // unresolved bindings.
1135 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1137 if region.is_late_bound() || t_type.has_escaping_bound_vars() {
1138 // Avoid debug assertion in `mk_obligation_for_def_id`.
1140 // If the self type has escaping bound vars then it's not
1141 // going to be the type of an expression, so the suggestion
1142 // probably won't apply anyway.
1146 let suggested_ty = match mutability {
1147 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
1148 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
1151 let trait_pred_and_suggested_ty =
1152 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1154 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1155 obligation.param_env,
1156 trait_pred_and_suggested_ty,
1158 let suggested_ty_would_satisfy_obligation = self
1159 .evaluate_obligation_no_overflow(&new_obligation)
1160 .must_apply_modulo_regions();
1161 if suggested_ty_would_satisfy_obligation {
1166 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1167 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
1168 err.span_suggestion_verbose(
1170 "consider changing this borrow's mutability",
1171 "&mut ".to_string(),
1172 Applicability::MachineApplicable,
1176 "`{}` is implemented for `{:?}`, but not for `{:?}`",
1177 trait_pred.print_modifiers_and_trait_path(),
1179 trait_pred.skip_binder().self_ty(),
1187 fn suggest_semicolon_removal(
1189 obligation: &PredicateObligation<'tcx>,
1190 err: &mut Diagnostic,
1192 trait_pred: ty::PolyTraitPredicate<'tcx>,
1194 let hir = self.tcx.hir();
1195 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1196 let node = hir.find(parent_node);
1197 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node
1198 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1199 && sig.decl.output.span().overlaps(span)
1200 && blk.expr.is_none()
1201 && trait_pred.self_ty().skip_binder().is_unit()
1202 && let Some(stmt) = blk.stmts.last()
1203 && let hir::StmtKind::Semi(expr) = stmt.kind
1204 // Only suggest this if the expression behind the semicolon implements the predicate
1205 && let Some(typeck_results) = self.in_progress_typeck_results
1206 && let Some(ty) = typeck_results.borrow().expr_ty_opt(expr)
1207 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1208 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1214 "this expression has type `{}`, which implements `{}`",
1216 trait_pred.print_modifiers_and_trait_path()
1219 err.span_suggestion(
1220 self.tcx.sess.source_map().end_point(stmt.span),
1221 "remove this semicolon",
1223 Applicability::MachineApplicable
1230 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1231 let hir = self.tcx.hir();
1232 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1233 let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find(parent_node) else {
1237 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1240 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
1241 /// applicable and signal that the error has been expanded appropriately and needs to be
1243 fn suggest_impl_trait(
1245 err: &mut Diagnostic,
1247 obligation: &PredicateObligation<'tcx>,
1248 trait_pred: ty::PolyTraitPredicate<'tcx>,
1250 match obligation.cause.code().peel_derives() {
1251 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
1252 ObligationCauseCode::SizedReturnType => {}
1256 let hir = self.tcx.hir();
1257 let fn_hir_id = hir.get_parent_node(obligation.cause.body_id);
1258 let node = hir.find(fn_hir_id);
1259 let Some(hir::Node::Item(hir::Item {
1260 kind: hir::ItemKind::Fn(sig, _, body_id),
1266 let body = hir.body(*body_id);
1267 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1268 let ty = trait_pred.skip_binder().self_ty();
1269 let is_object_safe = match ty.kind() {
1270 ty::Dynamic(predicates, _) => {
1271 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
1274 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
1276 // We only want to suggest `impl Trait` to `dyn Trait`s.
1277 // For example, `fn foo() -> str` needs to be filtered out.
1281 let hir::FnRetTy::Return(ret_ty) = sig.decl.output else {
1285 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
1286 // cases like `fn foo() -> (dyn Trait, i32) {}`.
1287 // Recursively look for `TraitObject` types and if there's only one, use that span to
1288 // suggest `impl Trait`.
1290 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
1291 // otherwise suggest using `Box<dyn Trait>` or an enum.
1292 let mut visitor = ReturnsVisitor::default();
1293 visitor.visit_body(&body);
1295 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1296 let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id) else { return false; };
1298 let ret_types = visitor
1301 .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?)))
1302 .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty)));
1303 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
1305 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
1307 let ty = self.resolve_vars_if_possible(ty);
1309 !matches!(ty.kind(), ty::Error(_))
1310 && last_ty.map_or(true, |last_ty| {
1311 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
1312 // *after* in the dependency graph.
1313 match (ty.kind(), last_ty.kind()) {
1314 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
1315 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
1316 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
1318 Infer(InferTy::FreshFloatTy(_)),
1319 Infer(InferTy::FreshFloatTy(_)),
1324 (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never))
1327 let mut spans_and_needs_box = vec![];
1329 match liberated_sig.output().kind() {
1330 ty::Dynamic(predicates, _) => {
1331 let cause = ObligationCause::misc(ret_ty.span, fn_hir_id);
1332 let param_env = ty::ParamEnv::empty();
1334 if !only_never_return {
1335 for (expr_span, return_ty) in ret_types {
1336 let self_ty_satisfies_dyn_predicates = |self_ty| {
1337 predicates.iter().all(|predicate| {
1338 let pred = predicate.with_self_ty(self.tcx, self_ty);
1339 let obl = Obligation::new(cause.clone(), param_env, pred);
1340 self.predicate_may_hold(&obl)
1344 if let ty::Adt(def, substs) = return_ty.kind()
1346 && self_ty_satisfies_dyn_predicates(substs.type_at(0))
1348 spans_and_needs_box.push((expr_span, false));
1349 } else if self_ty_satisfies_dyn_predicates(return_ty) {
1350 spans_and_needs_box.push((expr_span, true));
1360 let sm = self.tcx.sess.source_map();
1361 if !ret_ty.span.overlaps(span) {
1364 let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind {
1365 if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) {
1371 // Substitute the type, so we can print a fixup given `type Alias = dyn Trait`
1372 let name = liberated_sig.output().to_string();
1374 name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name);
1375 if !name.starts_with("dyn ") {
1381 err.code(error_code!(E0746));
1382 err.set_primary_message("return type cannot have an unboxed trait object");
1383 err.children.clear();
1384 let impl_trait_msg = "for information on `impl Trait`, see \
1385 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1386 #returning-types-that-implement-traits>";
1387 let trait_obj_msg = "for information on trait objects, see \
1388 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1389 #using-trait-objects-that-allow-for-values-of-different-types>";
1391 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
1392 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet };
1393 if only_never_return {
1394 // No return paths, probably using `panic!()` or similar.
1395 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
1396 suggest_trait_object_return_type_alternatives(
1402 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
1403 // Suggest `-> impl Trait`.
1404 err.span_suggestion(
1407 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
1408 which implements `{1}`",
1411 format!("impl {}", trait_obj),
1412 Applicability::MachineApplicable,
1414 err.note(impl_trait_msg);
1417 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
1418 err.multipart_suggestion(
1419 "return a boxed trait object instead",
1421 (ret_ty.span.shrink_to_lo(), "Box<".to_string()),
1422 (span.shrink_to_hi(), ">".to_string()),
1424 Applicability::MaybeIncorrect,
1426 for (span, needs_box) in spans_and_needs_box {
1428 err.multipart_suggestion(
1429 "... and box this value",
1431 (span.shrink_to_lo(), "Box::new(".to_string()),
1432 (span.shrink_to_hi(), ")".to_string()),
1434 Applicability::MaybeIncorrect,
1439 // This is currently not possible to trigger because E0038 takes precedence, but
1440 // leave it in for completeness in case anything changes in an earlier stage.
1442 "if trait `{}` were object-safe, you could return a trait object",
1446 err.note(trait_obj_msg);
1448 "if all the returned values were of the same type you could use `impl {}` as the \
1452 err.note(impl_trait_msg);
1453 err.note("you can create a new `enum` with a variant for each returned type");
1458 fn point_at_returns_when_relevant(
1460 err: &mut Diagnostic,
1461 obligation: &PredicateObligation<'tcx>,
1463 match obligation.cause.code().peel_derives() {
1464 ObligationCauseCode::SizedReturnType => {}
1468 let hir = self.tcx.hir();
1469 let parent_node = hir.get_parent_node(obligation.cause.body_id);
1470 let node = hir.find(parent_node);
1471 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
1474 let body = hir.body(*body_id);
1475 // Point at all the `return`s in the function as they have failed trait bounds.
1476 let mut visitor = ReturnsVisitor::default();
1477 visitor.visit_body(&body);
1478 let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap();
1479 for expr in &visitor.returns {
1480 if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) {
1481 let ty = self.resolve_vars_if_possible(returned_ty);
1482 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1488 fn report_closure_arg_mismatch(
1491 found_span: Option<Span>,
1492 expected_ref: ty::PolyTraitRef<'tcx>,
1493 found: ty::PolyTraitRef<'tcx>,
1494 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1495 crate fn build_fn_sig_string<'tcx>(
1497 trait_ref: ty::PolyTraitRef<'tcx>,
1499 let inputs = trait_ref.skip_binder().substs.type_at(1);
1500 let sig = match inputs.kind() {
1502 if tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some() =>
1506 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1508 hir::Unsafety::Normal,
1513 std::iter::once(inputs),
1514 tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0))),
1516 hir::Unsafety::Normal,
1520 trait_ref.rebind(sig).to_string()
1523 let argument_kind = match expected_ref.skip_binder().self_ty().kind() {
1524 ty::Closure(..) => "closure",
1525 ty::Generator(..) => "generator",
1528 let span = self.tcx.sess.source_map().guess_head_span(span);
1529 let mut err = struct_span_err!(
1533 "type mismatch in {} arguments",
1537 let found_str = format!("expected signature of `{}`", build_fn_sig_string(self.tcx, found));
1538 err.span_label(span, found_str);
1540 let found_span = found_span.unwrap_or(span);
1542 format!("found signature of `{}`", build_fn_sig_string(self.tcx, expected_ref));
1543 err.span_label(found_span, expected_str);
1548 fn suggest_fully_qualified_path(
1550 err: &mut Diagnostic,
1555 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
1556 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1558 "{}s cannot be accessed directly on a `trait`, they can only be \
1559 accessed through a specific `impl`",
1560 assoc_item.kind.as_def_kind().descr(item_def_id)
1562 err.span_suggestion(
1564 "use the fully qualified path to an implementation",
1565 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
1566 Applicability::HasPlaceholders,
1572 /// Adds an async-await specific note to the diagnostic when the future does not implement
1573 /// an auto trait because of a captured type.
1576 /// note: future does not implement `Qux` as this value is used across an await
1577 /// --> $DIR/issue-64130-3-other.rs:17:5
1579 /// LL | let x = Foo;
1580 /// | - has type `Foo`
1581 /// LL | baz().await;
1582 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1584 /// | - `x` is later dropped here
1587 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1588 /// is "replaced" with a different message and a more specific error.
1591 /// error: future cannot be sent between threads safely
1592 /// --> $DIR/issue-64130-2-send.rs:21:5
1594 /// LL | fn is_send<T: Send>(t: T) { }
1595 /// | ---- required by this bound in `is_send`
1597 /// LL | is_send(bar());
1598 /// | ^^^^^^^ future returned by `bar` is not send
1600 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1601 /// implemented for `Foo`
1602 /// note: future is not send as this value is used across an await
1603 /// --> $DIR/issue-64130-2-send.rs:15:5
1605 /// LL | let x = Foo;
1606 /// | - has type `Foo`
1607 /// LL | baz().await;
1608 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1610 /// | - `x` is later dropped here
1613 /// Returns `true` if an async-await specific note was added to the diagnostic.
1614 fn maybe_note_obligation_cause_for_async_await(
1616 err: &mut Diagnostic,
1617 obligation: &PredicateObligation<'tcx>,
1620 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1621 obligation.cause.span={:?}",
1622 obligation.predicate, obligation.cause.span
1624 let hir = self.tcx.hir();
1626 // Attempt to detect an async-await error by looking at the obligation causes, looking
1627 // for a generator to be present.
1629 // When a future does not implement a trait because of a captured type in one of the
1630 // generators somewhere in the call stack, then the result is a chain of obligations.
1632 // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that
1633 // future is passed as an argument to a function C which requires a `Send` type, then the
1634 // chain looks something like this:
1636 // - `BuiltinDerivedObligation` with a generator witness (B)
1637 // - `BuiltinDerivedObligation` with a generator (B)
1638 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1639 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1640 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1641 // - `BuiltinDerivedObligation` with a generator witness (A)
1642 // - `BuiltinDerivedObligation` with a generator (A)
1643 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1644 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1645 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1646 // - `BindingObligation` with `impl_send (Send requirement)
1648 // The first obligation in the chain is the most useful and has the generator that captured
1649 // the type. The last generator (`outer_generator` below) has information about where the
1650 // bound was introduced. At least one generator should be present for this diagnostic to be
1652 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
1653 ty::PredicateKind::Trait(p) => (Some(p), Some(p.self_ty())),
1656 let mut generator = None;
1657 let mut outer_generator = None;
1658 let mut next_code = Some(obligation.cause.code());
1660 let mut seen_upvar_tys_infer_tuple = false;
1662 while let Some(code) = next_code {
1663 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1665 ObligationCauseCode::FunctionArgumentObligation { parent_code, .. } => {
1666 next_code = Some(parent_code);
1668 ObligationCauseCode::ImplDerivedObligation(cause) => {
1669 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
1671 "maybe_note_obligation_cause_for_async_await: ImplDerived \
1672 parent_trait_ref={:?} self_ty.kind={:?}",
1673 cause.derived.parent_trait_pred,
1678 ty::Generator(did, ..) => {
1679 generator = generator.or(Some(did));
1680 outer_generator = Some(did);
1682 ty::GeneratorWitness(..) => {}
1683 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1684 // By introducing a tuple of upvar types into the chain of obligations
1685 // of a generator, the first non-generator item is now the tuple itself,
1686 // we shall ignore this.
1688 seen_upvar_tys_infer_tuple = true;
1690 _ if generator.is_none() => {
1691 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
1692 target_ty = Some(ty);
1697 next_code = Some(&cause.derived.parent_code);
1699 ObligationCauseCode::DerivedObligation(derived_obligation)
1700 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation) => {
1701 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
1703 "maybe_note_obligation_cause_for_async_await: \
1704 parent_trait_ref={:?} self_ty.kind={:?}",
1705 derived_obligation.parent_trait_pred,
1710 ty::Generator(did, ..) => {
1711 generator = generator.or(Some(did));
1712 outer_generator = Some(did);
1714 ty::GeneratorWitness(..) => {}
1715 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
1716 // By introducing a tuple of upvar types into the chain of obligations
1717 // of a generator, the first non-generator item is now the tuple itself,
1718 // we shall ignore this.
1720 seen_upvar_tys_infer_tuple = true;
1722 _ if generator.is_none() => {
1723 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
1724 target_ty = Some(ty);
1729 next_code = Some(&derived_obligation.parent_code);
1735 // Only continue if a generator was found.
1736 debug!(?generator, ?trait_ref, ?target_ty, "maybe_note_obligation_cause_for_async_await");
1737 let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else {
1741 let span = self.tcx.def_span(generator_did);
1743 let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow());
1744 let generator_did_root = self.tcx.typeck_root_def_id(generator_did);
1746 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1747 generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}",
1750 in_progress_typeck_results.as_ref().map(|t| t.hir_owner),
1754 let generator_body = generator_did
1756 .map(|def_id| hir.local_def_id_to_hir_id(def_id))
1757 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1758 .map(|body_id| hir.body(body_id));
1759 let is_async = match generator_did.as_local() {
1760 Some(_) => generator_body
1761 .and_then(|body| body.generator_kind())
1762 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1766 .generator_kind(generator_did)
1767 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1770 let mut visitor = AwaitsVisitor::default();
1771 if let Some(body) = generator_body {
1772 visitor.visit_body(body);
1774 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1776 // Look for a type inside the generator interior that matches the target type to get
1778 let target_ty_erased = self.tcx.erase_regions(target_ty);
1779 let ty_matches = |ty| -> bool {
1780 // Careful: the regions for types that appear in the
1781 // generator interior are not generally known, so we
1782 // want to erase them when comparing (and anyway,
1783 // `Send` and other bounds are generally unaffected by
1784 // the choice of region). When erasing regions, we
1785 // also have to erase late-bound regions. This is
1786 // because the types that appear in the generator
1787 // interior generally contain "bound regions" to
1788 // represent regions that are part of the suspended
1789 // generator frame. Bound regions are preserved by
1790 // `erase_regions` and so we must also call
1791 // `erase_late_bound_regions`.
1792 let ty_erased = self.tcx.erase_late_bound_regions(ty);
1793 let ty_erased = self.tcx.erase_regions(ty_erased);
1794 let eq = ty_erased == target_ty_erased;
1796 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1797 target_ty_erased={:?} eq={:?}",
1798 ty_erased, target_ty_erased, eq
1803 let mut interior_or_upvar_span = None;
1804 let mut interior_extra_info = None;
1806 // Get the typeck results from the infcx if the generator is the function we are currently
1807 // type-checking; otherwise, get them by performing a query. This is needed to avoid
1808 // cycles. If we can't use resolved types because the generator comes from another crate,
1809 // we still provide a targeted error but without all the relevant spans.
1810 let generator_data: Option<GeneratorData<'tcx, '_>> = match &in_progress_typeck_results {
1811 Some(t) if t.hir_owner.to_def_id() == generator_did_root => {
1812 Some(GeneratorData::Local(&t))
1814 _ if generator_did.is_local() => {
1815 Some(GeneratorData::Local(self.tcx.typeck(generator_did.expect_local())))
1819 .generator_diagnostic_data(generator_did)
1821 .map(|generator_diag_data| GeneratorData::Foreign(generator_diag_data)),
1824 if let Some(generator_data) = generator_data.as_ref() {
1825 interior_or_upvar_span =
1826 generator_data.try_get_upvar_span(&self, generator_did, ty_matches);
1828 // The generator interior types share the same binders
1829 if let Some(cause) =
1830 generator_data.get_generator_interior_types().skip_binder().iter().find(
1831 |ty::GeneratorInteriorTypeCause { ty, .. }| {
1832 ty_matches(generator_data.get_generator_interior_types().rebind(*ty))
1836 let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches);
1837 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1840 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(*span));
1841 interior_extra_info = Some((*scope_span, *yield_span, *expr, from_awaited_ty));
1844 if interior_or_upvar_span.is_none() && generator_data.is_foreign() {
1845 interior_or_upvar_span = Some(GeneratorInteriorOrUpvar::Interior(span));
1849 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
1850 let typeck_results = generator_data.and_then(|generator_data| match generator_data {
1851 GeneratorData::Local(typeck_results) => Some(typeck_results),
1852 GeneratorData::Foreign(_) => None,
1854 self.note_obligation_cause_for_async_await(
1856 interior_or_upvar_span,
1857 interior_extra_info,
1872 /// Unconditionally adds the diagnostic note described in
1873 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1874 fn note_obligation_cause_for_async_await(
1876 err: &mut Diagnostic,
1877 interior_or_upvar_span: GeneratorInteriorOrUpvar,
1878 interior_extra_info: Option<(Option<Span>, Span, Option<hir::HirId>, Option<Span>)>,
1880 outer_generator: Option<DefId>,
1881 trait_pred: ty::TraitPredicate<'tcx>,
1882 target_ty: Ty<'tcx>,
1883 typeck_results: Option<&ty::TypeckResults<'tcx>>,
1884 obligation: &PredicateObligation<'tcx>,
1885 next_code: Option<&ObligationCauseCode<'tcx>>,
1887 let source_map = self.tcx.sess.source_map();
1889 let (await_or_yield, an_await_or_yield) =
1890 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1891 let future_or_generator = if is_async { "future" } else { "generator" };
1893 // Special case the primary error message when send or sync is the trait that was
1895 let hir = self.tcx.hir();
1896 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
1897 self.tcx.get_diagnostic_name(trait_pred.def_id())
1899 let (trait_name, trait_verb) =
1900 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1903 err.set_primary_message(format!(
1904 "{} cannot be {} between threads safely",
1905 future_or_generator, trait_verb
1908 let original_span = err.span.primary_span().unwrap();
1909 let original_span = self.tcx.sess.source_map().guess_head_span(original_span);
1910 let mut span = MultiSpan::from_span(original_span);
1912 let message = outer_generator
1913 .and_then(|generator_did| {
1914 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1915 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1916 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1918 .parent(generator_did)
1920 .map(|parent_did| hir.local_def_id_to_hir_id(parent_did))
1921 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1923 format!("future returned by `{}` is not {}", name, trait_name)
1925 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1926 format!("future created by async block is not {}", trait_name)
1928 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1929 format!("future created by async closure is not {}", trait_name)
1933 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1935 span.push_span_label(original_span, message);
1938 format!("is not {}", trait_name)
1940 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
1943 let mut explain_yield = |interior_span: Span,
1945 scope_span: Option<Span>| {
1946 let mut span = MultiSpan::from_span(yield_span);
1947 if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
1948 // #70935: If snippet contains newlines, display "the value" instead
1949 // so that we do not emit complex diagnostics.
1950 let snippet = &format!("`{}`", snippet);
1951 let snippet = if snippet.contains('\n') { "the value" } else { snippet };
1952 // note: future is not `Send` as this value is used across an await
1953 // --> $DIR/issue-70935-complex-spans.rs:13:9
1955 // LL | baz(|| async {
1956 // | ______________-
1959 // LL | | foo(tx.clone());
1961 // | | - ^^^^^^ await occurs here, with value maybe used later
1963 // | has type `closure` which is not `Send`
1964 // note: value is later dropped here
1968 span.push_span_label(
1970 format!("{} occurs here, with {} maybe used later", await_or_yield, snippet),
1972 span.push_span_label(
1974 format!("has type `{}` which {}", target_ty, trait_explanation),
1976 // If available, use the scope span to annotate the drop location.
1977 let mut scope_note = None;
1978 if let Some(scope_span) = scope_span {
1979 let scope_span = source_map.end_point(scope_span);
1981 let msg = format!("{} is later dropped here", snippet);
1982 if source_map.is_multiline(yield_span.between(scope_span)) {
1983 span.push_span_label(scope_span, msg);
1985 scope_note = Some((scope_span, msg));
1991 "{} {} as this value is used across {}",
1992 future_or_generator, trait_explanation, an_await_or_yield
1995 if let Some((span, msg)) = scope_note {
1996 err.span_note(span, &msg);
2000 match interior_or_upvar_span {
2001 GeneratorInteriorOrUpvar::Interior(interior_span) => {
2002 if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {
2003 if let Some(await_span) = from_awaited_ty {
2004 // The type causing this obligation is one being awaited at await_span.
2005 let mut span = MultiSpan::from_span(await_span);
2006 span.push_span_label(
2009 "await occurs here on type `{}`, which {}",
2010 target_ty, trait_explanation
2016 "future {not_trait} as it awaits another future which {not_trait}",
2017 not_trait = trait_explanation
2021 // Look at the last interior type to get a span for the `.await`.
2023 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
2024 typeck_results.as_ref().map(|t| &t.generator_interior_types)
2026 explain_yield(interior_span, yield_span, scope_span);
2029 if let Some(expr_id) = expr {
2030 let expr = hir.expect_expr(expr_id);
2031 debug!("target_ty evaluated from {:?}", expr);
2033 let parent = hir.get_parent_node(expr_id);
2034 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
2035 let parent_span = hir.span(parent);
2036 let parent_did = parent.owner.to_def_id();
2039 // fn foo(&self) -> i32 {}
2042 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
2045 let is_region_borrow = if let Some(typeck_results) = typeck_results {
2047 .expr_adjustments(expr)
2049 .any(|adj| adj.is_region_borrow())
2055 // struct Foo(*const u8);
2056 // bar(Foo(std::ptr::null())).await;
2057 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
2059 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
2060 let is_raw_borrow_inside_fn_like_call =
2061 match self.tcx.def_kind(parent_did) {
2062 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
2065 if let Some(typeck_results) = typeck_results {
2066 if (typeck_results.is_method_call(e) && is_region_borrow)
2067 || is_raw_borrow_inside_fn_like_call
2071 "consider moving this into a `let` \
2072 binding to create a shorter lived borrow",
2080 GeneratorInteriorOrUpvar::Upvar(upvar_span) => {
2081 // `Some(ref_ty)` if `target_ty` is `&T` and `T` fails to impl `Sync`
2082 let refers_to_non_sync = match target_ty.kind() {
2083 ty::Ref(_, ref_ty, _) => match self.evaluate_obligation(&obligation) {
2084 Ok(eval) if !eval.may_apply() => Some(ref_ty),
2090 let (span_label, span_note) = match refers_to_non_sync {
2091 // if `target_ty` is `&T` and `T` fails to impl `Sync`,
2092 // include suggestions to make `T: Sync` so that `&T: Send`
2095 "has type `{}` which {}, because `{}` is not `Sync`",
2096 target_ty, trait_explanation, ref_ty
2099 "captured value {} because `&` references cannot be sent unless their referent is `Sync`",
2104 format!("has type `{}` which {}", target_ty, trait_explanation),
2105 format!("captured value {}", trait_explanation),
2109 let mut span = MultiSpan::from_span(upvar_span);
2110 span.push_span_label(upvar_span, span_label);
2111 err.span_note(span, &span_note);
2115 // Add a note for the item obligation that remains - normally a note pointing to the
2116 // bound that introduced the obligation (e.g. `T: Send`).
2117 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
2118 self.note_obligation_cause_code(
2120 &obligation.predicate,
2121 obligation.param_env,
2124 &mut Default::default(),
2128 fn note_obligation_cause_code<T>(
2130 err: &mut Diagnostic,
2132 param_env: ty::ParamEnv<'tcx>,
2133 cause_code: &ObligationCauseCode<'tcx>,
2134 obligated_types: &mut Vec<Ty<'tcx>>,
2135 seen_requirements: &mut FxHashSet<DefId>,
2141 ObligationCauseCode::ExprAssignable
2142 | ObligationCauseCode::MatchExpressionArm { .. }
2143 | ObligationCauseCode::Pattern { .. }
2144 | ObligationCauseCode::IfExpression { .. }
2145 | ObligationCauseCode::IfExpressionWithNoElse
2146 | ObligationCauseCode::MainFunctionType
2147 | ObligationCauseCode::StartFunctionType
2148 | ObligationCauseCode::IntrinsicType
2149 | ObligationCauseCode::MethodReceiver
2150 | ObligationCauseCode::ReturnNoExpression
2151 | ObligationCauseCode::UnifyReceiver(..)
2152 | ObligationCauseCode::OpaqueType
2153 | ObligationCauseCode::MiscObligation
2154 | ObligationCauseCode::WellFormed(..)
2155 | ObligationCauseCode::MatchImpl(..)
2156 | ObligationCauseCode::ReturnType
2157 | ObligationCauseCode::ReturnValue(_)
2158 | ObligationCauseCode::BlockTailExpression(_)
2159 | ObligationCauseCode::AwaitableExpr(_)
2160 | ObligationCauseCode::ForLoopIterator
2161 | ObligationCauseCode::QuestionMark
2162 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2163 | ObligationCauseCode::LetElse
2164 | ObligationCauseCode::BinOp { .. } => {}
2165 ObligationCauseCode::SliceOrArrayElem => {
2166 err.note("slice and array elements must have `Sized` type");
2168 ObligationCauseCode::TupleElem => {
2169 err.note("only the last element of a tuple may have a dynamically sized type");
2171 ObligationCauseCode::ProjectionWf(data) => {
2172 err.note(&format!("required so that the projection `{}` is well-formed", data,));
2174 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
2176 "required so that reference `{}` does not outlive its referent",
2180 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
2182 "required so that the lifetime bound of `{}` for `{}` is satisfied",
2186 ObligationCauseCode::ItemObligation(_item_def_id) => {
2187 // We hold the `DefId` of the item introducing the obligation, but displaying it
2188 // doesn't add user usable information. It always point at an associated item.
2190 ObligationCauseCode::BindingObligation(item_def_id, span) => {
2191 let item_name = tcx.def_path_str(item_def_id);
2192 let mut multispan = MultiSpan::from(span);
2193 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2194 let sm = tcx.sess.source_map();
2196 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2197 (Ok(l), Ok(r)) => l.line == r.line,
2200 if !ident.span.overlaps(span) && !same_line {
2202 .push_span_label(ident.span, "required by a bound in this".to_string());
2205 let descr = format!("required by a bound in `{}`", item_name);
2206 if span != DUMMY_SP {
2207 let msg = format!("required by this bound in `{}`", item_name);
2208 multispan.push_span_label(span, msg);
2209 err.span_note(multispan, &descr);
2211 err.span_note(tcx.def_span(item_def_id), &descr);
2214 ObligationCauseCode::ObjectCastObligation(object_ty) => {
2216 "required for the cast to the object type `{}`",
2217 self.ty_to_string(object_ty)
2220 ObligationCauseCode::Coercion { source: _, target } => {
2221 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
2223 ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2225 "the `Copy` trait is required because this value will be copied for each element of the array",
2230 "consider creating a new `const` item and initializing it with the result \
2231 of the function call to be used in the repeat position, like \
2232 `const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2236 if self.tcx.sess.is_nightly_build() && is_const_fn {
2238 "create an inline `const` block, see RFC #2920 \
2239 <https://github.com/rust-lang/rfcs/pull/2920> for more information",
2243 ObligationCauseCode::VariableType(hir_id) => {
2244 let parent_node = self.tcx.hir().get_parent_node(hir_id);
2245 match self.tcx.hir().find(parent_node) {
2246 Some(Node::Local(hir::Local {
2247 init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }),
2250 // When encountering an assignment of an unsized trait, like
2251 // `let x = ""[..];`, provide a suggestion to borrow the initializer in
2252 // order to use have a slice instead.
2253 err.span_suggestion_verbose(
2254 span.shrink_to_lo(),
2255 "consider borrowing here",
2257 Applicability::MachineApplicable,
2259 err.note("all local variables must have a statically known size");
2261 Some(Node::Param(param)) => {
2262 err.span_suggestion_verbose(
2263 param.ty_span.shrink_to_lo(),
2264 "function arguments must have a statically known size, borrowed types \
2265 always have a known size",
2267 Applicability::MachineApplicable,
2271 err.note("all local variables must have a statically known size");
2274 if !self.tcx.features().unsized_locals {
2275 err.help("unsized locals are gated as an unstable feature");
2278 ObligationCauseCode::SizedArgumentType(sp) => {
2279 if let Some(span) = sp {
2280 err.span_suggestion_verbose(
2281 span.shrink_to_lo(),
2282 "function arguments must have a statically known size, borrowed types \
2283 always have a known size",
2285 Applicability::MachineApplicable,
2288 err.note("all function arguments must have a statically known size");
2290 if tcx.sess.opts.unstable_features.is_nightly_build()
2291 && !self.tcx.features().unsized_fn_params
2293 err.help("unsized fn params are gated as an unstable feature");
2296 ObligationCauseCode::SizedReturnType => {
2297 err.note("the return type of a function must have a statically known size");
2299 ObligationCauseCode::SizedYieldType => {
2300 err.note("the yield type of a generator must have a statically known size");
2302 ObligationCauseCode::SizedBoxType => {
2303 err.note("the type of a box expression must have a statically known size");
2305 ObligationCauseCode::AssignmentLhsSized => {
2306 err.note("the left-hand-side of an assignment must have a statically known size");
2308 ObligationCauseCode::TupleInitializerSized => {
2309 err.note("tuples must have a statically known size to be initialized");
2311 ObligationCauseCode::StructInitializerSized => {
2312 err.note("structs must have a statically known size to be initialized");
2314 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
2316 AdtKind::Struct => {
2319 "the last field of a packed struct may only have a \
2320 dynamically sized type if it does not need drop to be run",
2324 "only the last field of a struct may have a dynamically sized type",
2329 err.note("no field of a union may have a dynamically sized type");
2332 err.note("no field of an enum variant may have a dynamically sized type");
2335 err.help("change the field's type to have a statically known size");
2336 err.span_suggestion(
2337 span.shrink_to_lo(),
2338 "borrowed types always have a statically known size",
2340 Applicability::MachineApplicable,
2342 err.multipart_suggestion(
2343 "the `Box` type always has a statically known size and allocates its contents \
2346 (span.shrink_to_lo(), "Box<".to_string()),
2347 (span.shrink_to_hi(), ">".to_string()),
2349 Applicability::MachineApplicable,
2352 ObligationCauseCode::ConstSized => {
2353 err.note("constant expressions must have a statically known size");
2355 ObligationCauseCode::InlineAsmSized => {
2356 err.note("all inline asm arguments must have a statically known size");
2358 ObligationCauseCode::ConstPatternStructural => {
2359 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
2361 ObligationCauseCode::SharedStatic => {
2362 err.note("shared static variables must have a type that implements `Sync`");
2364 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
2365 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2366 let ty = parent_trait_ref.skip_binder().self_ty();
2367 if parent_trait_ref.references_error() {
2368 // NOTE(eddyb) this was `.cancel()`, but `err`
2369 // is borrowed, so we can't fully defuse it.
2370 err.downgrade_to_delayed_bug();
2374 // If the obligation for a tuple is set directly by a Generator or Closure,
2375 // then the tuple must be the one containing capture types.
2376 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
2379 if let ObligationCauseCode::BuiltinDerivedObligation(data) = &*data.parent_code
2381 let parent_trait_ref =
2382 self.resolve_vars_if_possible(data.parent_trait_pred);
2383 let ty = parent_trait_ref.skip_binder().self_ty();
2384 matches!(ty.kind(), ty::Generator(..))
2385 || matches!(ty.kind(), ty::Closure(..))
2391 // Don't print the tuple of capture types
2392 if !is_upvar_tys_infer_tuple {
2393 let msg = format!("required because it appears within the type `{}`", ty);
2395 ty::Adt(def, _) => match self.tcx.opt_item_ident(def.did()) {
2396 Some(ident) => err.span_note(ident.span, &msg),
2397 None => err.note(&msg),
2399 _ => err.note(&msg),
2403 obligated_types.push(ty);
2405 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2406 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
2407 // #74711: avoid a stack overflow
2408 ensure_sufficient_stack(|| {
2409 self.note_obligation_cause_code(
2419 ensure_sufficient_stack(|| {
2420 self.note_obligation_cause_code(
2424 cause_code.peel_derives(),
2431 ObligationCauseCode::ImplDerivedObligation(ref data) => {
2432 let mut parent_trait_pred =
2433 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
2434 parent_trait_pred.remap_constness_diag(param_env);
2435 let parent_def_id = parent_trait_pred.def_id();
2437 "required because of the requirements on the impl of `{}` for `{}`",
2438 parent_trait_pred.print_modifiers_and_trait_path(),
2439 parent_trait_pred.skip_binder().self_ty()
2441 let mut is_auto_trait = false;
2442 match self.tcx.hir().get_if_local(data.impl_def_id) {
2443 Some(Node::Item(hir::Item {
2444 kind: hir::ItemKind::Trait(is_auto, ..),
2448 // FIXME: we should do something else so that it works even on crate foreign
2450 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
2451 err.span_note(ident.span, &msg)
2453 Some(Node::Item(hir::Item {
2454 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
2457 let mut spans = Vec::with_capacity(2);
2458 if let Some(trait_ref) = of_trait {
2459 spans.push(trait_ref.path.span);
2461 spans.push(self_ty.span);
2462 err.span_note(spans, &msg)
2464 _ => err.note(&msg),
2467 let mut parent_predicate = parent_trait_pred.to_predicate(tcx);
2468 let mut data = &data.derived;
2470 seen_requirements.insert(parent_def_id);
2472 // We don't want to point at the ADT saying "required because it appears within
2473 // the type `X`", like we would otherwise do in test `supertrait-auto-trait.rs`.
2474 while let ObligationCauseCode::BuiltinDerivedObligation(derived) =
2477 let child_trait_ref =
2478 self.resolve_vars_if_possible(derived.parent_trait_pred);
2479 let child_def_id = child_trait_ref.def_id();
2480 if seen_requirements.insert(child_def_id) {
2484 parent_predicate = child_trait_ref.to_predicate(tcx);
2485 parent_trait_pred = child_trait_ref;
2488 while let ObligationCauseCode::ImplDerivedObligation(child) = &*data.parent_code {
2489 // Skip redundant recursive obligation notes. See `ui/issue-20413.rs`.
2490 let child_trait_pred =
2491 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
2492 let child_def_id = child_trait_pred.def_id();
2493 if seen_requirements.insert(child_def_id) {
2497 data = &child.derived;
2498 parent_predicate = child_trait_pred.to_predicate(tcx);
2499 parent_trait_pred = child_trait_pred;
2503 "{} redundant requirement{} hidden",
2508 "required because of the requirements on the impl of `{}` for `{}`",
2509 parent_trait_pred.print_modifiers_and_trait_path(),
2510 parent_trait_pred.skip_binder().self_ty()
2513 // #74711: avoid a stack overflow
2514 ensure_sufficient_stack(|| {
2515 self.note_obligation_cause_code(
2525 ObligationCauseCode::DerivedObligation(ref data) => {
2526 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2527 let parent_predicate = parent_trait_ref.to_predicate(tcx);
2528 // #74711: avoid a stack overflow
2529 ensure_sufficient_stack(|| {
2530 self.note_obligation_cause_code(
2540 ObligationCauseCode::FunctionArgumentObligation {
2545 let hir = self.tcx.hir();
2546 if let Some(Node::Expr(expr @ hir::Expr { kind: hir::ExprKind::Block(..), .. })) =
2547 hir.find(arg_hir_id)
2549 let in_progress_typeck_results =
2550 self.in_progress_typeck_results.map(|t| t.borrow());
2551 let parent_id = hir.get_parent_item(arg_hir_id);
2552 let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results {
2553 Some(t) if t.hir_owner == parent_id => t,
2554 _ => self.tcx.typeck(parent_id),
2556 let ty = typeck_results.expr_ty_adjusted(expr);
2557 let span = expr.peel_blocks().span;
2558 if Some(span) != err.span.primary_span() {
2561 &if ty.references_error() {
2564 format!("this tail expression is of type `{:?}`", ty)
2569 if let Some(Node::Expr(hir::Expr {
2571 hir::ExprKind::Call(hir::Expr { span, .. }, _)
2572 | hir::ExprKind::MethodCall(
2573 hir::PathSegment { ident: Ident { span, .. }, .. },
2577 })) = hir.find(call_hir_id)
2579 if Some(*span) != err.span.primary_span() {
2580 err.span_label(*span, "required by a bound introduced by this call");
2583 ensure_sufficient_stack(|| {
2584 self.note_obligation_cause_code(
2594 ObligationCauseCode::CompareImplMethodObligation { trait_item_def_id, .. } => {
2595 let item_name = self.tcx.item_name(trait_item_def_id);
2597 "the requirement `{}` appears on the impl method `{}` but not on the \
2598 corresponding trait method",
2599 predicate, item_name,
2603 .opt_item_ident(trait_item_def_id)
2605 .unwrap_or_else(|| self.tcx.def_span(trait_item_def_id));
2606 let mut assoc_span: MultiSpan = sp.into();
2607 assoc_span.push_span_label(
2609 format!("this trait method doesn't have the requirement `{}`", predicate),
2611 if let Some(ident) = self
2613 .opt_associated_item(trait_item_def_id)
2614 .and_then(|i| self.tcx.opt_item_ident(i.container.id()))
2616 assoc_span.push_span_label(ident.span, "in this trait");
2618 err.span_note(assoc_span, &msg);
2620 ObligationCauseCode::CompareImplTypeObligation { trait_item_def_id, .. } => {
2621 let item_name = self.tcx.item_name(trait_item_def_id);
2623 "the requirement `{}` appears on the associated impl type `{}` but not on the \
2624 corresponding associated trait type",
2625 predicate, item_name,
2627 let sp = self.tcx.def_span(trait_item_def_id);
2628 let mut assoc_span: MultiSpan = sp.into();
2629 assoc_span.push_span_label(
2632 "this trait associated type doesn't have the requirement `{}`",
2636 if let Some(ident) = self
2638 .opt_associated_item(trait_item_def_id)
2639 .and_then(|i| self.tcx.opt_item_ident(i.container.id()))
2641 assoc_span.push_span_label(ident.span, "in this trait");
2643 err.span_note(assoc_span, &msg);
2645 ObligationCauseCode::CompareImplConstObligation => {
2647 "the requirement `{}` appears on the associated impl constant \
2648 but not on the corresponding associated trait constant",
2652 ObligationCauseCode::TrivialBound => {
2653 err.help("see issue #48214");
2654 if tcx.sess.opts.unstable_features.is_nightly_build() {
2655 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
2661 fn suggest_new_overflow_limit(&self, err: &mut Diagnostic) {
2662 let suggested_limit = match self.tcx.recursion_limit() {
2663 Limit(0) => Limit(2),
2667 "consider increasing the recursion limit by adding a \
2668 `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
2670 self.tcx.crate_name(LOCAL_CRATE),
2674 fn suggest_await_before_try(
2676 err: &mut Diagnostic,
2677 obligation: &PredicateObligation<'tcx>,
2678 trait_pred: ty::PolyTraitPredicate<'tcx>,
2682 "suggest_await_before_try: obligation={:?}, span={:?}, trait_pred={:?}, trait_pred_self_ty={:?}",
2686 trait_pred.self_ty()
2688 let body_hir_id = obligation.cause.body_id;
2689 let item_id = self.tcx.hir().get_parent_node(body_hir_id);
2691 if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
2692 let body = self.tcx.hir().body(body_id);
2693 if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
2694 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
2696 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
2698 // Do not check on infer_types to avoid panic in evaluate_obligation.
2699 if self_ty.has_infer_types() {
2702 let self_ty = self.tcx.erase_regions(self_ty);
2704 let impls_future = self.type_implements_trait(
2706 self_ty.skip_binder(),
2708 obligation.param_env,
2711 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
2712 // `<T as Future>::Output`
2713 let projection_ty = ty::ProjectionTy {
2715 substs: self.tcx.mk_substs_trait(
2716 trait_pred.self_ty().skip_binder(),
2717 &self.fresh_substs_for_item(span, item_def_id)[1..],
2723 let mut selcx = SelectionContext::new(self);
2725 let mut obligations = vec![];
2726 let normalized_ty = normalize_projection_type(
2728 obligation.param_env,
2730 obligation.cause.clone(),
2736 "suggest_await_before_try: normalized_projection_type {:?}",
2737 self.resolve_vars_if_possible(normalized_ty)
2739 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
2740 obligation.param_env,
2741 trait_pred.map_bound(|trait_pred| (trait_pred, normalized_ty.ty().unwrap())),
2743 debug!("suggest_await_before_try: try_trait_obligation {:?}", try_obligation);
2744 if self.predicate_may_hold(&try_obligation)
2745 && impls_future.must_apply_modulo_regions()
2746 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
2747 && snippet.ends_with('?')
2749 err.span_suggestion_verbose(
2750 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
2751 "consider `await`ing on the `Future`",
2752 ".await".to_string(),
2753 Applicability::MaybeIncorrect,
2760 fn suggest_floating_point_literal(
2762 obligation: &PredicateObligation<'tcx>,
2763 err: &mut Diagnostic,
2764 trait_ref: &ty::PolyTraitRef<'tcx>,
2766 let rhs_span = match obligation.cause.code() {
2767 ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit } if *is_lit => span,
2771 trait_ref.skip_binder().self_ty().kind(),
2772 trait_ref.skip_binder().substs.type_at(1).kind(),
2774 (ty::Float(_), ty::Infer(InferTy::IntVar(_))) => {
2775 err.span_suggestion_verbose(
2776 rhs_span.shrink_to_hi(),
2777 "consider using a floating-point literal by writing it with `.0`",
2779 Applicability::MaybeIncorrect,
2788 obligation: &PredicateObligation<'tcx>,
2789 err: &mut Diagnostic,
2790 trait_pred: ty::PolyTraitPredicate<'tcx>,
2792 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
2795 let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() {
2796 ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs),
2800 let is_derivable_trait = match diagnostic_name {
2801 sym::Default => !adt.is_enum(),
2802 sym::PartialEq | sym::PartialOrd => {
2803 let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1);
2804 trait_pred.skip_binder().self_ty() == rhs_ty
2806 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
2809 is_derivable_trait &&
2810 // Ensure all fields impl the trait.
2811 adt.all_fields().all(|field| {
2812 let field_ty = field.ty(self.tcx, substs);
2813 let trait_substs = match diagnostic_name {
2814 sym::PartialEq | sym::PartialOrd => {
2815 self.tcx.mk_substs_trait(field_ty, &[field_ty.into()])
2817 _ => self.tcx.mk_substs_trait(field_ty, &[]),
2819 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
2820 trait_ref: ty::TraitRef {
2821 substs: trait_substs,
2822 ..trait_pred.skip_binder().trait_ref
2826 let field_obl = Obligation::new(
2827 obligation.cause.clone(),
2828 obligation.param_env,
2829 trait_pred.to_predicate(self.tcx),
2831 self.predicate_must_hold_modulo_regions(&field_obl)
2835 err.span_suggestion_verbose(
2836 self.tcx.def_span(adt.did()).shrink_to_lo(),
2838 "consider annotating `{}` with `#[derive({})]`",
2839 trait_pred.skip_binder().self_ty(),
2842 format!("#[derive({})]\n", diagnostic_name),
2843 Applicability::MaybeIncorrect,
2849 /// Collect all the returned expressions within the input expression.
2850 /// Used to point at the return spans when we want to suggest some change to them.
2852 pub struct ReturnsVisitor<'v> {
2853 pub returns: Vec<&'v hir::Expr<'v>>,
2854 in_block_tail: bool,
2857 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
2858 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2859 // Visit every expression to detect `return` paths, either through the function's tail
2860 // expression or `return` statements. We walk all nodes to find `return` statements, but
2861 // we only care about tail expressions when `in_block_tail` is `true`, which means that
2862 // they're in the return path of the function body.
2864 hir::ExprKind::Ret(Some(ex)) => {
2865 self.returns.push(ex);
2867 hir::ExprKind::Block(block, _) if self.in_block_tail => {
2868 self.in_block_tail = false;
2869 for stmt in block.stmts {
2870 hir::intravisit::walk_stmt(self, stmt);
2872 self.in_block_tail = true;
2873 if let Some(expr) = block.expr {
2874 self.visit_expr(expr);
2877 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
2878 self.visit_expr(then);
2879 if let Some(el) = else_opt {
2880 self.visit_expr(el);
2883 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
2885 self.visit_expr(arm.body);
2888 // We need to walk to find `return`s in the entire body.
2889 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
2890 _ => self.returns.push(ex),
2894 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
2895 assert!(!self.in_block_tail);
2896 if body.generator_kind().is_none() {
2897 if let hir::ExprKind::Block(block, None) = body.value.kind {
2898 if block.expr.is_some() {
2899 self.in_block_tail = true;
2903 hir::intravisit::walk_body(self, body);
2907 /// Collect all the awaited expressions within the input expression.
2909 struct AwaitsVisitor {
2910 awaits: Vec<hir::HirId>,
2913 impl<'v> Visitor<'v> for AwaitsVisitor {
2914 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2915 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
2916 self.awaits.push(id)
2918 hir::intravisit::walk_expr(self, ex)
2922 pub trait NextTypeParamName {
2923 fn next_type_param_name(&self, name: Option<&str>) -> String;
2926 impl NextTypeParamName for &[hir::GenericParam<'_>] {
2927 fn next_type_param_name(&self, name: Option<&str>) -> String {
2928 // This is the list of possible parameter names that we might suggest.
2929 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
2930 let name = name.as_deref();
2931 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
2932 let used_names = self
2934 .filter_map(|p| match p.name {
2935 hir::ParamName::Plain(ident) => Some(ident.name),
2938 .collect::<Vec<_>>();
2942 .find(|n| !used_names.contains(&Symbol::intern(n)))
2943 .unwrap_or(&"ParamName")
2948 fn suggest_trait_object_return_type_alternatives(
2949 err: &mut Diagnostic,
2952 is_object_safe: bool,
2954 err.span_suggestion(
2956 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
2959 Applicability::MaybeIncorrect,
2961 err.span_suggestion(
2964 "use `impl {}` as the return type if all return paths have the same type but you \
2965 want to expose only the trait in the signature",
2968 format!("impl {}", trait_obj),
2969 Applicability::MaybeIncorrect,
2972 err.multipart_suggestion(
2974 "use a boxed trait object if all return paths implement trait `{}`",
2978 (ret_ty.shrink_to_lo(), "Box<".to_string()),
2979 (ret_ty.shrink_to_hi(), ">".to_string()),
2981 Applicability::MaybeIncorrect,