2 EvaluationResult, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation,
5 use crate::infer::InferCtxt;
6 use crate::traits::error_reporting::suggest_constraining_type_param;
8 use rustc_errors::{error_code, struct_span_err, Applicability, DiagnosticBuilder, Style};
10 use rustc_hir::def::DefKind;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit::Visitor;
13 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
14 use rustc_middle::ty::TypeckTables;
15 use rustc_middle::ty::{
16 self, AdtKind, DefIdTree, Infer, InferTy, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
18 use rustc_span::symbol::{kw, sym, Symbol};
19 use rustc_span::{MultiSpan, Span, DUMMY_SP};
22 use super::InferCtxtPrivExt;
23 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
25 // This trait is public to expose the diagnostics methods to clippy.
26 pub trait InferCtxtExt<'tcx> {
27 fn suggest_restricting_param_bound(
29 err: &mut DiagnosticBuilder<'_>,
30 trait_ref: ty::PolyTraitRef<'_>,
34 fn suggest_borrow_on_unsized_slice(
36 code: &ObligationCauseCode<'tcx>,
37 err: &mut DiagnosticBuilder<'tcx>,
43 err: &mut DiagnosticBuilder<'_>,
49 obligation: &PredicateObligation<'tcx>,
50 err: &mut DiagnosticBuilder<'_>,
51 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
55 fn suggest_add_reference_to_arg(
57 obligation: &PredicateObligation<'tcx>,
58 err: &mut DiagnosticBuilder<'tcx>,
59 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
61 has_custom_message: bool,
64 fn suggest_remove_reference(
66 obligation: &PredicateObligation<'tcx>,
67 err: &mut DiagnosticBuilder<'tcx>,
68 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
71 fn suggest_change_mut(
73 obligation: &PredicateObligation<'tcx>,
74 err: &mut DiagnosticBuilder<'tcx>,
75 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
79 fn suggest_semicolon_removal(
81 obligation: &PredicateObligation<'tcx>,
82 err: &mut DiagnosticBuilder<'tcx>,
84 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
87 fn suggest_impl_trait(
89 err: &mut DiagnosticBuilder<'tcx>,
91 obligation: &PredicateObligation<'tcx>,
92 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
95 fn point_at_returns_when_relevant(
97 err: &mut DiagnosticBuilder<'tcx>,
98 obligation: &PredicateObligation<'tcx>,
101 fn report_closure_arg_mismatch(
104 found_span: Option<Span>,
105 expected_ref: ty::PolyTraitRef<'tcx>,
106 found: ty::PolyTraitRef<'tcx>,
107 ) -> DiagnosticBuilder<'tcx>;
109 fn suggest_fully_qualified_path(
111 err: &mut DiagnosticBuilder<'_>,
117 fn maybe_note_obligation_cause_for_async_await(
119 err: &mut DiagnosticBuilder<'_>,
120 obligation: &PredicateObligation<'tcx>,
123 fn note_obligation_cause_for_async_await(
125 err: &mut DiagnosticBuilder<'_>,
127 scope_span: &Option<Span>,
129 expr: Option<hir::HirId>,
131 inner_generator_body: Option<&hir::Body<'_>>,
132 outer_generator: Option<DefId>,
133 trait_ref: ty::TraitRef<'_>,
135 tables: &ty::TypeckTables<'_>,
136 obligation: &PredicateObligation<'tcx>,
137 next_code: Option<&ObligationCauseCode<'tcx>>,
138 from_awaited_ty: Option<Span>,
141 fn note_obligation_cause_code<T>(
143 err: &mut DiagnosticBuilder<'_>,
145 cause_code: &ObligationCauseCode<'tcx>,
146 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
150 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>);
153 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
155 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
158 if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
164 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
165 /// it can also be an `impl Trait` param that needs to be decomposed to a type
166 /// param for cleaner code.
167 fn suggest_restriction(
168 generics: &hir::Generics<'_>,
170 err: &mut DiagnosticBuilder<'_>,
171 fn_sig: Option<&hir::FnSig<'_>>,
172 projection: Option<&ty::ProjectionTy<'_>>,
173 trait_ref: ty::PolyTraitRef<'_>,
175 let span = generics.where_clause.span_for_predicates_or_empty_place();
176 if span.from_expansion() || span.desugaring_kind().is_some() {
179 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
180 if let Some((bound_str, fn_sig)) =
181 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind {
182 // Shenanigans to get the `Trait` from the `impl Trait`.
183 ty::Param(param) => {
184 // `fn foo(t: impl Trait)`
185 // ^^^^^ get this string
186 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
191 // We know we have an `impl Trait` that doesn't satisfy a required projection.
193 // Find all of the ocurrences of `impl Trait` for `Trait` in the function arguments'
194 // types. There should be at least one, but there might be *more* than one. In that
195 // case we could just ignore it and try to identify which one needs the restriction,
196 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
198 let mut ty_spans = vec![];
199 let impl_trait_str = format!("impl {}", bound_str);
200 for input in fn_sig.decl.inputs {
201 if let hir::TyKind::Path(hir::QPath::Resolved(
203 hir::Path { segments: [segment], .. },
206 if segment.ident.as_str() == impl_trait_str.as_str() {
207 // `fn foo(t: impl Trait)`
208 // ^^^^^^^^^^ get this to suggest `T` instead
210 // There might be more than one `impl Trait`.
211 ty_spans.push(input.span);
216 let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
217 // The type param `T: Trait` we will suggest to introduce.
218 let type_param = format!("{}: {}", type_param_name, bound_str);
220 // FIXME: modify the `trait_ref` instead of string shenanigans.
221 // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
222 let pred = trait_ref.without_const().to_predicate().to_string();
223 let pred = pred.replace(&impl_trait_str, &type_param_name);
228 .filter(|p| match p.kind {
229 hir::GenericParamKind::Type {
230 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
237 // `fn foo(t: impl Trait)`
238 // ^ suggest `<T: Trait>` here
239 None => (generics.span, format!("<{}>", type_param)),
240 // `fn foo<A>(t: impl Trait)`
241 // ^^^ suggest `<A, T: Trait>` here
243 param.bounds_span().unwrap_or(param.span).shrink_to_hi(),
244 format!(", {}", type_param),
247 // `fn foo(t: impl Trait)`
248 // ^ suggest `where <T as Trait>::A: Bound`
249 predicate_constraint(generics, pred),
251 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
253 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
254 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
255 // `fn foo(t: impl Trait<A: Bound>)` instead.
256 err.multipart_suggestion(
257 "introduce a type parameter with a trait bound instead of using `impl Trait`",
259 Applicability::MaybeIncorrect,
262 // Trivial case: `T` needs an extra bound: `T: Bound`.
264 predicate_constraint(generics, trait_ref.without_const().to_predicate().to_string());
265 let appl = Applicability::MachineApplicable;
266 err.span_suggestion(sp, &format!("consider further restricting {}", msg), sugg, appl);
270 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
271 fn suggest_restricting_param_bound(
273 mut err: &mut DiagnosticBuilder<'_>,
274 trait_ref: ty::PolyTraitRef<'_>,
277 let self_ty = trait_ref.self_ty();
278 let (param_ty, projection) = match &self_ty.kind {
279 ty::Param(_) => (true, None),
280 ty::Projection(projection) => (false, Some(projection)),
284 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
285 // don't suggest `T: Sized + ?Sized`.
286 let mut hir_id = body_id;
287 while let Some(node) = self.tcx.hir().find(hir_id) {
289 hir::Node::TraitItem(hir::TraitItem {
291 kind: hir::TraitItemKind::Fn(..),
293 }) if param_ty && self_ty == self.tcx.types.self_param => {
294 // Restricting `Self` for a single method.
295 suggest_restriction(&generics, "`Self`", err, None, projection, trait_ref);
299 hir::Node::TraitItem(hir::TraitItem {
301 kind: hir::TraitItemKind::Fn(fn_sig, ..),
304 | hir::Node::ImplItem(hir::ImplItem {
306 kind: hir::ImplItemKind::Fn(fn_sig, ..),
309 | hir::Node::Item(hir::Item {
310 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
311 }) if projection.is_some() => {
312 // Missing restriction on associated type of type parameter (unmet projection).
315 "the associated type",
323 hir::Node::Item(hir::Item {
325 hir::ItemKind::Trait(_, _, generics, _, _)
326 | hir::ItemKind::Impl { generics, .. },
328 }) if projection.is_some() => {
329 // Missing restriction on associated type of type parameter (unmet projection).
332 "the associated type",
341 hir::Node::Item(hir::Item {
343 hir::ItemKind::Struct(_, generics)
344 | hir::ItemKind::Enum(_, generics)
345 | hir::ItemKind::Union(_, generics)
346 | hir::ItemKind::Trait(_, _, generics, ..)
347 | hir::ItemKind::Impl { generics, .. }
348 | hir::ItemKind::Fn(_, generics, _)
349 | hir::ItemKind::TyAlias(_, generics)
350 | hir::ItemKind::TraitAlias(generics, _)
351 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
354 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
355 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
358 // Missing generic type parameter bound.
359 let param_name = self_ty.to_string();
360 let constraint = trait_ref.print_only_trait_path().to_string();
361 if suggest_constraining_type_param(
367 Some(trait_ref.def_id()),
373 hir::Node::Crate(..) => return,
378 hir_id = self.tcx.hir().get_parent_item(hir_id);
382 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
383 /// suggestion to borrow the initializer in order to use have a slice instead.
384 fn suggest_borrow_on_unsized_slice(
386 code: &ObligationCauseCode<'tcx>,
387 err: &mut DiagnosticBuilder<'tcx>,
389 if let &ObligationCauseCode::VariableType(hir_id) = code {
390 let parent_node = self.tcx.hir().get_parent_node(hir_id);
391 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
392 if let Some(ref expr) = local.init {
393 if let hir::ExprKind::Index(_, _) = expr.kind {
394 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
397 "consider borrowing here",
398 format!("&{}", snippet),
399 Applicability::MachineApplicable,
408 /// Given a closure's `DefId`, return the given name of the closure.
410 /// This doesn't account for reassignments, but it's only used for suggestions.
414 err: &mut DiagnosticBuilder<'_>,
416 ) -> Option<String> {
418 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
419 // Get the local name of this closure. This can be inaccurate because
420 // of the possibility of reassignment, but this should be good enough.
422 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
423 Some(format!("{}", name))
432 let hir = self.tcx.hir();
433 let hir_id = hir.as_local_hir_id(def_id.as_local()?);
434 let parent_node = hir.get_parent_node(hir_id);
435 match hir.find(parent_node) {
436 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
437 get_name(err, &local.pat.kind)
439 // Different to previous arm because one is `&hir::Local` and the other
440 // is `P<hir::Local>`.
441 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
446 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
447 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
448 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
451 obligation: &PredicateObligation<'tcx>,
452 err: &mut DiagnosticBuilder<'_>,
453 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
456 let self_ty = trait_ref.self_ty();
457 let (def_id, output_ty, callable) = match self_ty.kind {
458 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
459 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
462 let msg = format!("use parentheses to call the {}", callable);
464 let obligation = self.mk_obligation_for_def_id(
466 output_ty.skip_binder(),
467 obligation.cause.clone(),
468 obligation.param_env,
471 match self.evaluate_obligation(&obligation) {
473 EvaluationResult::EvaluatedToOk
474 | EvaluationResult::EvaluatedToOkModuloRegions
475 | EvaluationResult::EvaluatedToAmbig,
479 let hir = self.tcx.hir();
480 // Get the name of the callable and the arguments to be used in the suggestion.
481 let (snippet, sugg) = match hir.get_if_local(def_id) {
482 Some(hir::Node::Expr(hir::Expr {
483 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
486 err.span_label(*span, "consider calling this closure");
487 let name = match self.get_closure_name(def_id, err, &msg) {
491 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
492 let sugg = format!("({})", args);
493 (format!("{}{}", name, sugg), sugg)
495 Some(hir::Node::Item(hir::Item {
497 kind: hir::ItemKind::Fn(.., body_id),
500 err.span_label(ident.span, "consider calling this function");
501 let body = hir.body(*body_id);
505 .map(|arg| match &arg.pat.kind {
506 hir::PatKind::Binding(_, _, ident, None)
507 // FIXME: provide a better suggestion when encountering `SelfLower`, it
508 // should suggest a method call.
509 if ident.name != kw::SelfLower => ident.to_string(),
510 _ => "_".to_string(),
514 let sugg = format!("({})", args);
515 (format!("{}{}", ident, sugg), sugg)
520 // When the obligation error has been ensured to have been caused by
521 // an argument, the `obligation.cause.span` points at the expression
522 // of the argument, so we can provide a suggestion. This is signaled
523 // by `points_at_arg`. Otherwise, we give a more general note.
524 err.span_suggestion_verbose(
525 obligation.cause.span.shrink_to_hi(),
528 Applicability::HasPlaceholders,
531 err.help(&format!("{}: `{}`", msg, snippet));
535 fn suggest_add_reference_to_arg(
537 obligation: &PredicateObligation<'tcx>,
538 err: &mut DiagnosticBuilder<'tcx>,
539 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
541 has_custom_message: bool,
547 let span = obligation.cause.span;
548 let param_env = obligation.param_env;
549 let trait_ref = trait_ref.skip_binder();
551 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
552 // Try to apply the original trait binding obligation by borrowing.
553 let self_ty = trait_ref.self_ty();
554 let found = self_ty.to_string();
555 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
556 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
557 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
558 let new_obligation = Obligation::new(
559 ObligationCause::dummy(),
561 new_trait_ref.without_const().to_predicate(),
563 if self.predicate_must_hold_modulo_regions(&new_obligation) {
564 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
565 // We have a very specific type of error, where just borrowing this argument
566 // might solve the problem. In cases like this, the important part is the
567 // original type obligation, not the last one that failed, which is arbitrary.
568 // Because of this, we modify the error to refer to the original obligation and
569 // return early in the caller.
571 "the trait bound `{}: {}` is not satisfied",
573 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
575 if has_custom_message {
578 err.message = vec![(msg, Style::NoStyle)];
580 if snippet.starts_with('&') {
581 // This is already a literal borrow and the obligation is failing
582 // somewhere else in the obligation chain. Do not suggest non-sense.
588 "expected an implementor of trait `{}`",
589 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
594 "consider borrowing here",
595 format!("&{}", snippet),
596 Applicability::MaybeIncorrect,
605 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
606 /// suggest removing these references until we reach a type that implements the trait.
607 fn suggest_remove_reference(
609 obligation: &PredicateObligation<'tcx>,
610 err: &mut DiagnosticBuilder<'tcx>,
611 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
613 let trait_ref = trait_ref.skip_binder();
614 let span = obligation.cause.span;
616 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
618 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
619 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
620 // Do not suggest removal of borrow from type arguments.
624 let mut trait_type = trait_ref.self_ty();
626 for refs_remaining in 0..refs_number {
627 if let ty::Ref(_, t_type, _) = trait_type.kind {
630 let new_obligation = self.mk_obligation_for_def_id(
633 ObligationCause::dummy(),
634 obligation.param_env,
637 if self.predicate_may_hold(&new_obligation) {
642 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
644 let remove_refs = refs_remaining + 1;
646 let msg = if remove_refs == 1 {
647 "consider removing the leading `&`-reference".to_string()
649 format!("consider removing {} leading `&`-references", remove_refs)
652 err.span_suggestion_short(
656 Applicability::MachineApplicable,
667 /// Check if the trait bound is implemented for a different mutability and note it in the
669 fn suggest_change_mut(
671 obligation: &PredicateObligation<'tcx>,
672 err: &mut DiagnosticBuilder<'tcx>,
673 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
676 let span = obligation.cause.span;
677 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
679 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
680 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
681 // Do not suggest removal of borrow from type arguments.
684 let trait_ref = self.resolve_vars_if_possible(trait_ref);
685 if trait_ref.has_infer_types_or_consts() {
686 // Do not ICE while trying to find if a reborrow would succeed on a trait with
687 // unresolved bindings.
691 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
692 let trait_type = match mutability {
693 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
694 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
697 let new_obligation = self.mk_obligation_for_def_id(
698 trait_ref.skip_binder().def_id,
700 ObligationCause::dummy(),
701 obligation.param_env,
704 if self.evaluate_obligation_no_overflow(&new_obligation).must_apply_modulo_regions()
710 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
711 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
712 err.span_suggestion_verbose(
714 "consider changing this borrow's mutability",
716 Applicability::MachineApplicable,
720 "`{}` is implemented for `{:?}`, but not for `{:?}`",
721 trait_ref.print_only_trait_path(),
723 trait_ref.skip_binder().self_ty(),
731 fn suggest_semicolon_removal(
733 obligation: &PredicateObligation<'tcx>,
734 err: &mut DiagnosticBuilder<'tcx>,
736 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
738 let hir = self.tcx.hir();
739 let parent_node = hir.get_parent_node(obligation.cause.body_id);
740 let node = hir.find(parent_node);
741 if let Some(hir::Node::Item(hir::Item {
742 kind: hir::ItemKind::Fn(sig, _, body_id), ..
745 let body = hir.body(*body_id);
746 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
747 if sig.decl.output.span().overlaps(span)
748 && blk.expr.is_none()
749 && "()" == &trait_ref.self_ty().to_string()
751 // FIXME(estebank): When encountering a method with a trait
752 // bound not satisfied in the return type with a body that has
753 // no return, suggest removal of semicolon on last statement.
754 // Once that is added, close #54771.
755 if let Some(ref stmt) = blk.stmts.last() {
756 let sp = self.tcx.sess.source_map().end_point(stmt.span);
757 err.span_label(sp, "consider removing this semicolon");
764 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
765 /// applicable and signal that the error has been expanded appropriately and needs to be
767 fn suggest_impl_trait(
769 err: &mut DiagnosticBuilder<'tcx>,
771 obligation: &PredicateObligation<'tcx>,
772 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
774 match obligation.cause.code.peel_derives() {
775 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
776 ObligationCauseCode::SizedReturnType => {}
780 let hir = self.tcx.hir();
781 let parent_node = hir.get_parent_node(obligation.cause.body_id);
782 let node = hir.find(parent_node);
783 let (sig, body_id) = if let Some(hir::Node::Item(hir::Item {
784 kind: hir::ItemKind::Fn(sig, _, body_id),
792 let body = hir.body(*body_id);
793 let trait_ref = self.resolve_vars_if_possible(trait_ref);
794 let ty = trait_ref.skip_binder().self_ty();
795 let is_object_safe = match ty.kind {
796 ty::Dynamic(predicates, _) => {
797 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
800 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
802 // We only want to suggest `impl Trait` to `dyn Trait`s.
803 // For example, `fn foo() -> str` needs to be filtered out.
807 let ret_ty = if let hir::FnRetTy::Return(ret_ty) = sig.decl.output {
813 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
814 // cases like `fn foo() -> (dyn Trait, i32) {}`.
815 // Recursively look for `TraitObject` types and if there's only one, use that span to
816 // suggest `impl Trait`.
818 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
819 // otherwise suggest using `Box<dyn Trait>` or an enum.
820 let mut visitor = ReturnsVisitor::default();
821 visitor.visit_body(&body);
823 let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
825 let mut ret_types = visitor
828 .filter_map(|expr| tables.node_type_opt(expr.hir_id))
829 .map(|ty| self.resolve_vars_if_possible(&ty));
830 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
832 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
834 let ty = self.resolve_vars_if_possible(&ty);
837 && last_ty.map_or(true, |last_ty| {
838 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
839 // *after* in the dependency graph.
840 match (&ty.kind, &last_ty.kind) {
841 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
842 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
843 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
845 Infer(InferTy::FreshFloatTy(_)),
846 Infer(InferTy::FreshFloatTy(_)),
851 (Some(ty), same, only_never_return && matches!(ty.kind, ty::Never))
854 let all_returns_conform_to_trait =
855 if let Some(ty_ret_ty) = tables.node_type_opt(ret_ty.hir_id) {
856 match ty_ret_ty.kind {
857 ty::Dynamic(predicates, _) => {
858 let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
859 let param_env = ty::ParamEnv::empty();
861 || ret_types.all(|returned_ty| {
862 predicates.iter().all(|predicate| {
863 let pred = predicate.with_self_ty(self.tcx, returned_ty);
864 let obl = Obligation::new(cause.clone(), param_env, pred);
865 self.predicate_may_hold(&obl)
875 let sm = self.tcx.sess.source_map();
876 let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
877 // Verify that we're dealing with a return `dyn Trait`
878 ret_ty.span.overlaps(span),
880 sm.span_to_snippet(ret_ty.span),
881 // If any of the return types does not conform to the trait, then we can't
882 // suggest `impl Trait` nor trait objects: it is a type mismatch error.
883 all_returns_conform_to_trait,
889 err.code(error_code!(E0746));
890 err.set_primary_message("return type cannot have an unboxed trait object");
891 err.children.clear();
892 let impl_trait_msg = "for information on `impl Trait`, see \
893 <https://doc.rust-lang.org/book/ch10-02-traits.html\
894 #returning-types-that-implement-traits>";
895 let trait_obj_msg = "for information on trait objects, see \
896 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
897 #using-trait-objects-that-allow-for-values-of-different-types>";
898 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
899 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet[..] };
900 if only_never_return {
901 // No return paths, probably using `panic!()` or similar.
902 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
903 suggest_trait_object_return_type_alternatives(
909 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
910 // Suggest `-> impl Trait`.
914 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
915 which implements `{1}`",
918 format!("impl {}", trait_obj),
919 Applicability::MachineApplicable,
921 err.note(impl_trait_msg);
924 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
925 // Get all the return values and collect their span and suggestion.
926 if let Some(mut suggestions) = visitor
930 let snip = sm.span_to_snippet(expr.span).ok()?;
931 Some((expr.span, format!("Box::new({})", snip)))
933 .collect::<Option<Vec<_>>>()
935 // Add the suggestion for the return type.
936 suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
937 err.multipart_suggestion(
938 "return a boxed trait object instead",
940 Applicability::MaybeIncorrect,
944 // This is currently not possible to trigger because E0038 takes precedence, but
945 // leave it in for completeness in case anything changes in an earlier stage.
947 "if trait `{}` was object safe, you could return a trait object",
951 err.note(trait_obj_msg);
953 "if all the returned values were of the same type you could use `impl {}` as the \
957 err.note(impl_trait_msg);
958 err.note("you can create a new `enum` with a variant for each returned type");
963 fn point_at_returns_when_relevant(
965 err: &mut DiagnosticBuilder<'tcx>,
966 obligation: &PredicateObligation<'tcx>,
968 match obligation.cause.code.peel_derives() {
969 ObligationCauseCode::SizedReturnType => {}
973 let hir = self.tcx.hir();
974 let parent_node = hir.get_parent_node(obligation.cause.body_id);
975 let node = hir.find(parent_node);
976 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
979 let body = hir.body(*body_id);
980 // Point at all the `return`s in the function as they have failed trait bounds.
981 let mut visitor = ReturnsVisitor::default();
982 visitor.visit_body(&body);
983 let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
984 for expr in &visitor.returns {
985 if let Some(returned_ty) = tables.node_type_opt(expr.hir_id) {
986 let ty = self.resolve_vars_if_possible(&returned_ty);
987 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
993 fn report_closure_arg_mismatch(
996 found_span: Option<Span>,
997 expected_ref: ty::PolyTraitRef<'tcx>,
998 found: ty::PolyTraitRef<'tcx>,
999 ) -> DiagnosticBuilder<'tcx> {
1000 crate fn build_fn_sig_string<'tcx>(
1002 trait_ref: &ty::TraitRef<'tcx>,
1004 let inputs = trait_ref.substs.type_at(1);
1005 let sig = if let ty::Tuple(inputs) = inputs.kind {
1007 inputs.iter().map(|k| k.expect_ty()),
1008 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1010 hir::Unsafety::Normal,
1011 ::rustc_target::spec::abi::Abi::Rust,
1015 ::std::iter::once(inputs),
1016 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1018 hir::Unsafety::Normal,
1019 ::rustc_target::spec::abi::Abi::Rust,
1022 ty::Binder::bind(sig).to_string()
1025 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1026 let mut err = struct_span_err!(
1030 "type mismatch in {} arguments",
1031 if argument_is_closure { "closure" } else { "function" }
1034 let found_str = format!(
1035 "expected signature of `{}`",
1036 build_fn_sig_string(self.tcx, found.skip_binder())
1038 err.span_label(span, found_str);
1040 let found_span = found_span.unwrap_or(span);
1041 let expected_str = format!(
1042 "found signature of `{}`",
1043 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1045 err.span_label(found_span, expected_str);
1050 fn suggest_fully_qualified_path(
1052 err: &mut DiagnosticBuilder<'_>,
1057 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1058 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1060 "{}s cannot be accessed directly on a `trait`, they can only be \
1061 accessed through a specific `impl`",
1062 assoc_item.kind.as_def_kind().descr(def_id)
1064 err.span_suggestion(
1066 "use the fully qualified path to an implementation",
1067 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1068 Applicability::HasPlaceholders,
1074 /// Adds an async-await specific note to the diagnostic when the future does not implement
1075 /// an auto trait because of a captured type.
1078 /// note: future does not implement `Qux` as this value is used across an await
1079 /// --> $DIR/issue-64130-3-other.rs:17:5
1081 /// LL | let x = Foo;
1082 /// | - has type `Foo`
1083 /// LL | baz().await;
1084 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1086 /// | - `x` is later dropped here
1089 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1090 /// is "replaced" with a different message and a more specific error.
1093 /// error: future cannot be sent between threads safely
1094 /// --> $DIR/issue-64130-2-send.rs:21:5
1096 /// LL | fn is_send<T: Send>(t: T) { }
1097 /// | ---- required by this bound in `is_send`
1099 /// LL | is_send(bar());
1100 /// | ^^^^^^^ future returned by `bar` is not send
1102 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1103 /// implemented for `Foo`
1104 /// note: future is not send as this value is used across an await
1105 /// --> $DIR/issue-64130-2-send.rs:15:5
1107 /// LL | let x = Foo;
1108 /// | - has type `Foo`
1109 /// LL | baz().await;
1110 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1112 /// | - `x` is later dropped here
1115 /// Returns `true` if an async-await specific note was added to the diagnostic.
1116 fn maybe_note_obligation_cause_for_async_await(
1118 err: &mut DiagnosticBuilder<'_>,
1119 obligation: &PredicateObligation<'tcx>,
1122 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1123 obligation.cause.span={:?}",
1124 obligation.predicate, obligation.cause.span
1126 let source_map = self.tcx.sess.source_map();
1127 let hir = self.tcx.hir();
1129 // Attempt to detect an async-await error by looking at the obligation causes, looking
1130 // for a generator to be present.
1132 // When a future does not implement a trait because of a captured type in one of the
1133 // generators somewhere in the call stack, then the result is a chain of obligations.
1135 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
1136 // future is passed as an argument to a function C which requires a `Send` type, then the
1137 // chain looks something like this:
1139 // - `BuiltinDerivedObligation` with a generator witness (B)
1140 // - `BuiltinDerivedObligation` with a generator (B)
1141 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1142 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1143 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1144 // - `BuiltinDerivedObligation` with a generator witness (A)
1145 // - `BuiltinDerivedObligation` with a generator (A)
1146 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1147 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1148 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1149 // - `BindingObligation` with `impl_send (Send requirement)
1151 // The first obligation in the chain is the most useful and has the generator that captured
1152 // the type. The last generator (`outer_generator` below) has information about where the
1153 // bound was introduced. At least one generator should be present for this diagnostic to be
1155 let (mut trait_ref, mut target_ty) = match obligation.predicate {
1156 ty::Predicate::Trait(p, _) => {
1157 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty()))
1161 let mut generator = None;
1162 let mut outer_generator = None;
1163 let mut next_code = Some(&obligation.cause.code);
1164 while let Some(code) = next_code {
1165 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1167 ObligationCauseCode::DerivedObligation(derived_obligation)
1168 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1169 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1170 let ty = derived_obligation.parent_trait_ref.self_ty();
1172 "maybe_note_obligation_cause_for_async_await: \
1173 parent_trait_ref={:?} self_ty.kind={:?}",
1174 derived_obligation.parent_trait_ref, ty.kind
1178 ty::Generator(did, ..) => {
1179 generator = generator.or(Some(did));
1180 outer_generator = Some(did);
1182 ty::GeneratorWitness(..) => {}
1183 _ if generator.is_none() => {
1184 trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
1185 target_ty = Some(ty);
1190 next_code = Some(derived_obligation.parent_code.as_ref());
1196 // Only continue if a generator was found.
1198 "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
1200 generator, trait_ref, target_ty
1202 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1203 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1204 (generator_did, trait_ref, target_ty)
1209 let span = self.tcx.def_span(generator_did);
1211 // Do not ICE on closure typeck (#66868).
1212 if !generator_did.is_local() {
1216 // Get the tables from the infcx if the generator is the function we are
1217 // currently type-checking; otherwise, get them by performing a query.
1218 // This is needed to avoid cycles.
1219 let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
1220 let generator_did_root = self.tcx.closure_base_def_id(generator_did);
1222 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1223 generator_did_root={:?} in_progress_tables.hir_owner={:?} span={:?}",
1226 in_progress_tables.as_ref().map(|t| t.hir_owner),
1230 let tables: &TypeckTables<'tcx> = match &in_progress_tables {
1231 Some(t) if t.hir_owner.map(|owner| owner.to_def_id()) == Some(generator_did_root) => t,
1233 query_tables = self.tcx.typeck_tables_of(generator_did);
1238 let generator_body = generator_did
1240 .map(|def_id| hir.as_local_hir_id(def_id))
1241 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1242 .map(|body_id| hir.body(body_id));
1243 let mut visitor = AwaitsVisitor::default();
1244 if let Some(body) = generator_body {
1245 visitor.visit_body(body);
1247 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1249 // Look for a type inside the generator interior that matches the target type to get
1251 let target_ty_erased = self.tcx.erase_regions(&target_ty);
1252 let ty_matches = |ty| -> bool {
1253 // Careful: the regions for types that appear in the
1254 // generator interior are not generally known, so we
1255 // want to erase them when comparing (and anyway,
1256 // `Send` and other bounds are generally unaffected by
1257 // the choice of region). When erasing regions, we
1258 // also have to erase late-bound regions. This is
1259 // because the types that appear in the generator
1260 // interior generally contain "bound regions" to
1261 // represent regions that are part of the suspended
1262 // generator frame. Bound regions are preserved by
1263 // `erase_regions` and so we must also call
1264 // `erase_late_bound_regions`.
1265 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(ty));
1266 let ty_erased = self.tcx.erase_regions(&ty_erased);
1267 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1269 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1270 target_ty_erased={:?} eq={:?}",
1271 ty_erased, target_ty_erased, eq
1275 let target_span = tables
1276 .generator_interior_types
1278 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| ty_matches(ty))
1280 // Check to see if any awaited expressions have the target type.
1281 let from_awaited_ty = visitor
1284 .map(|id| hir.expect_expr(id))
1285 .find(|await_expr| {
1286 let ty = tables.expr_ty_adjusted(&await_expr);
1288 "maybe_note_obligation_cause_for_async_await: await_expr={:?}",
1293 .map(|expr| expr.span);
1294 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1298 source_map.span_to_snippet(*span),
1307 "maybe_note_obligation_cause_for_async_await: target_ty={:?} \
1308 generator_interior_types={:?} target_span={:?}",
1309 target_ty, tables.generator_interior_types, target_span
1311 if let Some((target_span, Ok(snippet), scope_span, yield_span, expr, from_awaited_ty)) =
1314 self.note_obligation_cause_for_async_await(
1336 /// Unconditionally adds the diagnostic note described in
1337 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1338 fn note_obligation_cause_for_async_await(
1340 err: &mut DiagnosticBuilder<'_>,
1342 scope_span: &Option<Span>,
1344 expr: Option<hir::HirId>,
1346 inner_generator_body: Option<&hir::Body<'_>>,
1347 outer_generator: Option<DefId>,
1348 trait_ref: ty::TraitRef<'_>,
1349 target_ty: Ty<'tcx>,
1350 tables: &ty::TypeckTables<'_>,
1351 obligation: &PredicateObligation<'tcx>,
1352 next_code: Option<&ObligationCauseCode<'tcx>>,
1353 from_awaited_ty: Option<Span>,
1355 let source_map = self.tcx.sess.source_map();
1357 let is_async = inner_generator_body
1358 .and_then(|body| body.generator_kind())
1359 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1361 let (await_or_yield, an_await_or_yield) =
1362 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1363 let future_or_generator = if is_async { "future" } else { "generator" };
1365 // Special case the primary error message when send or sync is the trait that was
1367 let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
1368 let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
1369 let hir = self.tcx.hir();
1370 let trait_explanation = if is_send || is_sync {
1371 let (trait_name, trait_verb) =
1372 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1375 err.set_primary_message(format!(
1376 "{} cannot be {} between threads safely",
1377 future_or_generator, trait_verb
1380 let original_span = err.span.primary_span().unwrap();
1381 let mut span = MultiSpan::from_span(original_span);
1383 let message = outer_generator
1384 .and_then(|generator_did| {
1385 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1386 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1387 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1389 .parent(generator_did)
1390 .and_then(|parent_did| parent_did.as_local())
1391 .map(|parent_did| hir.as_local_hir_id(parent_did))
1392 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1394 format!("future returned by `{}` is not {}", name, trait_name)
1396 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1397 format!("future created by async block is not {}", trait_name)
1399 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1400 format!("future created by async closure is not {}", trait_name)
1404 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1406 span.push_span_label(original_span, message);
1409 format!("is not {}", trait_name)
1411 format!("does not implement `{}`", trait_ref.print_only_trait_path())
1414 if let Some(await_span) = from_awaited_ty {
1415 // The type causing this obligation is one being awaited at await_span.
1416 let mut span = MultiSpan::from_span(await_span);
1418 span.push_span_label(
1420 format!("await occurs here on type `{}`, which {}", target_ty, trait_explanation),
1426 "future {not_trait} as it awaits another future which {not_trait}",
1427 not_trait = trait_explanation
1431 // Look at the last interior type to get a span for the `.await`.
1433 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1434 tables.generator_interior_types
1436 let mut span = MultiSpan::from_span(yield_span);
1437 span.push_span_label(
1439 format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
1442 span.push_span_label(
1444 format!("has type `{}` which {}", target_ty, trait_explanation),
1447 // If available, use the scope span to annotate the drop location.
1448 if let Some(scope_span) = scope_span {
1449 span.push_span_label(
1450 source_map.end_point(*scope_span),
1451 format!("`{}` is later dropped here", snippet),
1458 "{} {} as this value is used across {}",
1459 future_or_generator, trait_explanation, an_await_or_yield
1464 if let Some(expr_id) = expr {
1465 let expr = hir.expect_expr(expr_id);
1466 debug!("target_ty evaluated from {:?}", expr);
1468 let parent = hir.get_parent_node(expr_id);
1469 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1470 let parent_span = hir.span(parent);
1471 let parent_did = parent.owner.to_def_id();
1474 // fn foo(&self) -> i32 {}
1477 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1480 let is_region_borrow =
1481 tables.expr_adjustments(expr).iter().any(|adj| adj.is_region_borrow());
1484 // struct Foo(*const u8);
1485 // bar(Foo(std::ptr::null())).await;
1486 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1488 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1489 let is_raw_borrow_inside_fn_like_call = match self.tcx.def_kind(parent_did) {
1490 Some(DefKind::Fn | DefKind::Ctor(..)) => target_ty.is_unsafe_ptr(),
1494 if (tables.is_method_call(e) && is_region_borrow)
1495 || is_raw_borrow_inside_fn_like_call
1499 "consider moving this into a `let` \
1500 binding to create a shorter lived borrow",
1506 // Add a note for the item obligation that remains - normally a note pointing to the
1507 // bound that introduced the obligation (e.g. `T: Send`).
1508 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1509 self.note_obligation_cause_code(
1511 &obligation.predicate,
1517 fn note_obligation_cause_code<T>(
1519 err: &mut DiagnosticBuilder<'_>,
1521 cause_code: &ObligationCauseCode<'tcx>,
1522 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1528 ObligationCauseCode::ExprAssignable
1529 | ObligationCauseCode::MatchExpressionArm { .. }
1530 | ObligationCauseCode::Pattern { .. }
1531 | ObligationCauseCode::IfExpression { .. }
1532 | ObligationCauseCode::IfExpressionWithNoElse
1533 | ObligationCauseCode::MainFunctionType
1534 | ObligationCauseCode::StartFunctionType
1535 | ObligationCauseCode::IntrinsicType
1536 | ObligationCauseCode::MethodReceiver
1537 | ObligationCauseCode::ReturnNoExpression
1538 | ObligationCauseCode::MiscObligation => {}
1539 ObligationCauseCode::SliceOrArrayElem => {
1540 err.note("slice and array elements must have `Sized` type");
1542 ObligationCauseCode::TupleElem => {
1543 err.note("only the last element of a tuple may have a dynamically sized type");
1545 ObligationCauseCode::ProjectionWf(data) => {
1546 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1548 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1550 "required so that reference `{}` does not outlive its referent",
1554 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1556 "required so that the lifetime bound of `{}` for `{}` is satisfied",
1560 ObligationCauseCode::ItemObligation(item_def_id) => {
1561 let item_name = tcx.def_path_str(item_def_id);
1562 let msg = format!("required by `{}`", item_name);
1563 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1564 let sp = tcx.sess.source_map().guess_head_span(sp);
1565 err.span_label(sp, &msg);
1570 ObligationCauseCode::BindingObligation(item_def_id, span) => {
1571 let item_name = tcx.def_path_str(item_def_id);
1572 let msg = format!("required by this bound in `{}`", item_name);
1573 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1574 let sm = tcx.sess.source_map();
1576 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
1577 (Ok(l), Ok(r)) => l.line == r.line,
1580 if !ident.span.overlaps(span) && !same_line {
1581 err.span_label(ident.span, "required by a bound in this");
1584 if span != DUMMY_SP {
1585 err.span_label(span, &msg);
1590 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1592 "required for the cast to the object type `{}`",
1593 self.ty_to_string(object_ty)
1596 ObligationCauseCode::Coercion { source: _, target } => {
1597 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1599 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
1601 "the `Copy` trait is required because the repeated element will be copied",
1603 if suggest_const_in_array_repeat_expressions {
1605 "this array initializer can be evaluated at compile-time, see issue \
1606 #48147 <https://github.com/rust-lang/rust/issues/49147> \
1607 for more information",
1609 if tcx.sess.opts.unstable_features.is_nightly_build() {
1611 "add `#![feature(const_in_array_repeat_expressions)]` to the \
1612 crate attributes to enable",
1617 ObligationCauseCode::VariableType(_) => {
1618 err.note("all local variables must have a statically known size");
1619 if !self.tcx.features().unsized_locals {
1620 err.help("unsized locals are gated as an unstable feature");
1623 ObligationCauseCode::SizedArgumentType => {
1624 err.note("all function arguments must have a statically known size");
1625 if !self.tcx.features().unsized_locals {
1626 err.help("unsized locals are gated as an unstable feature");
1629 ObligationCauseCode::SizedReturnType => {
1630 err.note("the return type of a function must have a statically known size");
1632 ObligationCauseCode::SizedYieldType => {
1633 err.note("the yield type of a generator must have a statically known size");
1635 ObligationCauseCode::AssignmentLhsSized => {
1636 err.note("the left-hand-side of an assignment must have a statically known size");
1638 ObligationCauseCode::TupleInitializerSized => {
1639 err.note("tuples must have a statically known size to be initialized");
1641 ObligationCauseCode::StructInitializerSized => {
1642 err.note("structs must have a statically known size to be initialized");
1644 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => match *item {
1645 AdtKind::Struct => {
1648 "the last field of a packed struct may only have a \
1649 dynamically sized type if it does not need drop to be run",
1653 "only the last field of a struct may have a dynamically sized type",
1658 err.note("no field of a union may have a dynamically sized type");
1661 err.note("no field of an enum variant may have a dynamically sized type");
1664 ObligationCauseCode::ConstSized => {
1665 err.note("constant expressions must have a statically known size");
1667 ObligationCauseCode::ConstPatternStructural => {
1668 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
1670 ObligationCauseCode::SharedStatic => {
1671 err.note("shared static variables must have a type that implements `Sync`");
1673 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1674 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1675 let ty = parent_trait_ref.skip_binder().self_ty();
1676 err.note(&format!("required because it appears within the type `{}`", ty));
1677 obligated_types.push(ty);
1679 let parent_predicate = parent_trait_ref.without_const().to_predicate();
1680 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1681 self.note_obligation_cause_code(
1689 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1690 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1692 "required because of the requirements on the impl of `{}` for `{}`",
1693 parent_trait_ref.print_only_trait_path(),
1694 parent_trait_ref.skip_binder().self_ty()
1696 let parent_predicate = parent_trait_ref.without_const().to_predicate();
1697 self.note_obligation_cause_code(
1704 ObligationCauseCode::DerivedObligation(ref data) => {
1705 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1706 let parent_predicate = parent_trait_ref.without_const().to_predicate();
1707 self.note_obligation_cause_code(
1714 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1716 "the requirement `{}` appears on the impl method \
1717 but not on the corresponding trait method",
1721 ObligationCauseCode::CompareImplTypeObligation { .. } => {
1723 "the requirement `{}` appears on the associated impl type \
1724 but not on the corresponding associated trait type",
1728 ObligationCauseCode::ReturnType
1729 | ObligationCauseCode::ReturnValue(_)
1730 | ObligationCauseCode::BlockTailExpression(_) => (),
1731 ObligationCauseCode::TrivialBound => {
1732 err.help("see issue #48214");
1733 if tcx.sess.opts.unstable_features.is_nightly_build() {
1734 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
1740 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1741 let current_limit = self.tcx.sess.recursion_limit.get();
1742 let suggested_limit = current_limit * 2;
1744 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
1745 suggested_limit, self.tcx.crate_name,
1750 /// Collect all the returned expressions within the input expression.
1751 /// Used to point at the return spans when we want to suggest some change to them.
1753 struct ReturnsVisitor<'v> {
1754 returns: Vec<&'v hir::Expr<'v>>,
1755 in_block_tail: bool,
1758 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
1759 type Map = hir::intravisit::ErasedMap<'v>;
1761 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
1762 hir::intravisit::NestedVisitorMap::None
1765 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
1766 // Visit every expression to detect `return` paths, either through the function's tail
1767 // expression or `return` statements. We walk all nodes to find `return` statements, but
1768 // we only care about tail expressions when `in_block_tail` is `true`, which means that
1769 // they're in the return path of the function body.
1771 hir::ExprKind::Ret(Some(ex)) => {
1772 self.returns.push(ex);
1774 hir::ExprKind::Block(block, _) if self.in_block_tail => {
1775 self.in_block_tail = false;
1776 for stmt in block.stmts {
1777 hir::intravisit::walk_stmt(self, stmt);
1779 self.in_block_tail = true;
1780 if let Some(expr) = block.expr {
1781 self.visit_expr(expr);
1784 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
1786 self.visit_expr(arm.body);
1789 // We need to walk to find `return`s in the entire body.
1790 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
1791 _ => self.returns.push(ex),
1795 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
1796 assert!(!self.in_block_tail);
1797 if body.generator_kind().is_none() {
1798 if let hir::ExprKind::Block(block, None) = body.value.kind {
1799 if block.expr.is_some() {
1800 self.in_block_tail = true;
1804 hir::intravisit::walk_body(self, body);
1808 /// Collect all the awaited expressions within the input expression.
1810 struct AwaitsVisitor {
1811 awaits: Vec<hir::HirId>,
1814 impl<'v> Visitor<'v> for AwaitsVisitor {
1815 type Map = hir::intravisit::ErasedMap<'v>;
1817 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
1818 hir::intravisit::NestedVisitorMap::None
1821 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
1822 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
1823 self.awaits.push(id)
1825 hir::intravisit::walk_expr(self, ex)
1829 pub trait NextTypeParamName {
1830 fn next_type_param_name(&self, name: Option<&str>) -> String;
1833 impl NextTypeParamName for &[hir::GenericParam<'_>] {
1834 fn next_type_param_name(&self, name: Option<&str>) -> String {
1835 // This is the whitelist of possible parameter names that we might suggest.
1836 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
1837 let name = name.as_ref().map(|s| s.as_str());
1838 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
1839 let used_names = self
1841 .filter_map(|p| match p.name {
1842 hir::ParamName::Plain(ident) => Some(ident.name),
1845 .collect::<Vec<_>>();
1849 .find(|n| !used_names.contains(&Symbol::intern(n)))
1850 .unwrap_or(&"ParamName")
1855 fn suggest_trait_object_return_type_alternatives(
1856 err: &mut DiagnosticBuilder<'tcx>,
1859 is_object_safe: bool,
1861 err.span_suggestion(
1863 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
1866 Applicability::MaybeIncorrect,
1868 err.span_suggestion(
1871 "use `impl {}` as the return type if all return paths have the same type but you \
1872 want to expose only the trait in the signature",
1875 format!("impl {}", trait_obj),
1876 Applicability::MaybeIncorrect,
1879 err.span_suggestion(
1882 "use a boxed trait object if all return paths implement trait `{}`",
1885 format!("Box<dyn {}>", trait_obj),
1886 Applicability::MaybeIncorrect,