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 return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span>;
89 fn suggest_impl_trait(
91 err: &mut DiagnosticBuilder<'tcx>,
93 obligation: &PredicateObligation<'tcx>,
94 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
97 fn point_at_returns_when_relevant(
99 err: &mut DiagnosticBuilder<'tcx>,
100 obligation: &PredicateObligation<'tcx>,
103 fn report_closure_arg_mismatch(
106 found_span: Option<Span>,
107 expected_ref: ty::PolyTraitRef<'tcx>,
108 found: ty::PolyTraitRef<'tcx>,
109 ) -> DiagnosticBuilder<'tcx>;
111 fn suggest_fully_qualified_path(
113 err: &mut DiagnosticBuilder<'_>,
119 fn maybe_note_obligation_cause_for_async_await(
121 err: &mut DiagnosticBuilder<'_>,
122 obligation: &PredicateObligation<'tcx>,
125 fn note_obligation_cause_for_async_await(
127 err: &mut DiagnosticBuilder<'_>,
129 scope_span: &Option<Span>,
131 expr: Option<hir::HirId>,
133 inner_generator_body: Option<&hir::Body<'_>>,
134 outer_generator: Option<DefId>,
135 trait_ref: ty::TraitRef<'_>,
137 tables: &ty::TypeckTables<'_>,
138 obligation: &PredicateObligation<'tcx>,
139 next_code: Option<&ObligationCauseCode<'tcx>>,
140 from_awaited_ty: Option<Span>,
143 fn note_obligation_cause_code<T>(
145 err: &mut DiagnosticBuilder<'_>,
147 cause_code: &ObligationCauseCode<'tcx>,
148 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
152 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>);
155 fn predicate_constraint(generics: &hir::Generics<'_>, pred: String) -> (Span, String) {
157 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
160 if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
166 /// Type parameter needs more bounds. The trivial case is `T` `where T: Bound`, but
167 /// it can also be an `impl Trait` param that needs to be decomposed to a type
168 /// param for cleaner code.
169 fn suggest_restriction(
170 generics: &hir::Generics<'_>,
172 err: &mut DiagnosticBuilder<'_>,
173 fn_sig: Option<&hir::FnSig<'_>>,
174 projection: Option<&ty::ProjectionTy<'_>>,
175 trait_ref: ty::PolyTraitRef<'_>,
177 let span = generics.where_clause.span_for_predicates_or_empty_place();
178 if span.from_expansion() || span.desugaring_kind().is_some() {
181 // Given `fn foo(t: impl Trait)` where `Trait` requires assoc type `A`...
182 if let Some((bound_str, fn_sig)) =
183 fn_sig.zip(projection).and_then(|(sig, p)| match p.self_ty().kind {
184 // Shenanigans to get the `Trait` from the `impl Trait`.
185 ty::Param(param) => {
186 // `fn foo(t: impl Trait)`
187 // ^^^^^ get this string
188 param.name.as_str().strip_prefix("impl").map(|s| (s.trim_start().to_string(), sig))
193 // We know we have an `impl Trait` that doesn't satisfy a required projection.
195 // Find all of the ocurrences of `impl Trait` for `Trait` in the function arguments'
196 // types. There should be at least one, but there might be *more* than one. In that
197 // case we could just ignore it and try to identify which one needs the restriction,
198 // but instead we choose to suggest replacing all instances of `impl Trait` with `T`
200 let mut ty_spans = vec![];
201 let impl_trait_str = format!("impl {}", bound_str);
202 for input in fn_sig.decl.inputs {
203 if let hir::TyKind::Path(hir::QPath::Resolved(
205 hir::Path { segments: [segment], .. },
208 if segment.ident.as_str() == impl_trait_str.as_str() {
209 // `fn foo(t: impl Trait)`
210 // ^^^^^^^^^^ get this to suggest `T` instead
212 // There might be more than one `impl Trait`.
213 ty_spans.push(input.span);
218 let type_param_name = generics.params.next_type_param_name(Some(&bound_str));
219 // The type param `T: Trait` we will suggest to introduce.
220 let type_param = format!("{}: {}", type_param_name, bound_str);
222 // FIXME: modify the `trait_ref` instead of string shenanigans.
223 // Turn `<impl Trait as Foo>::Bar: Qux` into `<T as Foo>::Bar: Qux`.
224 let pred = trait_ref.without_const().to_predicate().to_string();
225 let pred = pred.replace(&impl_trait_str, &type_param_name);
230 .filter(|p| match p.kind {
231 hir::GenericParamKind::Type {
232 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
239 // `fn foo(t: impl Trait)`
240 // ^ suggest `<T: Trait>` here
241 None => (generics.span, format!("<{}>", type_param)),
242 // `fn foo<A>(t: impl Trait)`
243 // ^^^ suggest `<A, T: Trait>` here
245 param.bounds_span().unwrap_or(param.span).shrink_to_hi(),
246 format!(", {}", type_param),
249 // `fn foo(t: impl Trait)`
250 // ^ suggest `where <T as Trait>::A: Bound`
251 predicate_constraint(generics, pred),
253 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
255 // Suggest `fn foo<T: Trait>(t: T) where <T as Trait>::A: Bound`.
256 // FIXME: once `#![feature(associated_type_bounds)]` is stabilized, we should suggest
257 // `fn foo(t: impl Trait<A: Bound>)` instead.
258 err.multipart_suggestion(
259 "introduce a type parameter with a trait bound instead of using `impl Trait`",
261 Applicability::MaybeIncorrect,
264 // Trivial case: `T` needs an extra bound: `T: Bound`.
266 predicate_constraint(generics, trait_ref.without_const().to_predicate().to_string());
267 let appl = Applicability::MachineApplicable;
268 err.span_suggestion(sp, &format!("consider further restricting {}", msg), sugg, appl);
272 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
273 fn suggest_restricting_param_bound(
275 mut err: &mut DiagnosticBuilder<'_>,
276 trait_ref: ty::PolyTraitRef<'_>,
279 let self_ty = trait_ref.self_ty();
280 let (param_ty, projection) = match &self_ty.kind {
281 ty::Param(_) => (true, None),
282 ty::Projection(projection) => (false, Some(projection)),
286 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
287 // don't suggest `T: Sized + ?Sized`.
288 let mut hir_id = body_id;
289 while let Some(node) = self.tcx.hir().find(hir_id) {
291 hir::Node::TraitItem(hir::TraitItem {
293 kind: hir::TraitItemKind::Fn(..),
295 }) if param_ty && self_ty == self.tcx.types.self_param => {
296 // Restricting `Self` for a single method.
297 suggest_restriction(&generics, "`Self`", err, None, projection, trait_ref);
301 hir::Node::TraitItem(hir::TraitItem {
303 kind: hir::TraitItemKind::Fn(fn_sig, ..),
306 | hir::Node::ImplItem(hir::ImplItem {
308 kind: hir::ImplItemKind::Fn(fn_sig, ..),
311 | hir::Node::Item(hir::Item {
312 kind: hir::ItemKind::Fn(fn_sig, generics, _), ..
313 }) if projection.is_some() => {
314 // Missing restriction on associated type of type parameter (unmet projection).
317 "the associated type",
325 hir::Node::Item(hir::Item {
327 hir::ItemKind::Trait(_, _, generics, _, _)
328 | hir::ItemKind::Impl { generics, .. },
330 }) if projection.is_some() => {
331 // Missing restriction on associated type of type parameter (unmet projection).
334 "the associated type",
343 hir::Node::Item(hir::Item {
345 hir::ItemKind::Struct(_, generics)
346 | hir::ItemKind::Enum(_, generics)
347 | hir::ItemKind::Union(_, generics)
348 | hir::ItemKind::Trait(_, _, generics, ..)
349 | hir::ItemKind::Impl { generics, .. }
350 | hir::ItemKind::Fn(_, generics, _)
351 | hir::ItemKind::TyAlias(_, generics)
352 | hir::ItemKind::TraitAlias(generics, _)
353 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
356 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
357 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
360 // Missing generic type parameter bound.
361 let param_name = self_ty.to_string();
362 let constraint = trait_ref.print_only_trait_path().to_string();
363 if suggest_constraining_type_param(
369 Some(trait_ref.def_id()),
375 hir::Node::Crate(..) => return,
380 hir_id = self.tcx.hir().get_parent_item(hir_id);
384 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
385 /// suggestion to borrow the initializer in order to use have a slice instead.
386 fn suggest_borrow_on_unsized_slice(
388 code: &ObligationCauseCode<'tcx>,
389 err: &mut DiagnosticBuilder<'tcx>,
391 if let &ObligationCauseCode::VariableType(hir_id) = code {
392 let parent_node = self.tcx.hir().get_parent_node(hir_id);
393 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
394 if let Some(ref expr) = local.init {
395 if let hir::ExprKind::Index(_, _) = expr.kind {
396 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
399 "consider borrowing here",
400 format!("&{}", snippet),
401 Applicability::MachineApplicable,
410 /// Given a closure's `DefId`, return the given name of the closure.
412 /// This doesn't account for reassignments, but it's only used for suggestions.
416 err: &mut DiagnosticBuilder<'_>,
418 ) -> Option<String> {
420 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
421 // Get the local name of this closure. This can be inaccurate because
422 // of the possibility of reassignment, but this should be good enough.
424 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
425 Some(format!("{}", name))
434 let hir = self.tcx.hir();
435 let hir_id = hir.as_local_hir_id(def_id.as_local()?);
436 let parent_node = hir.get_parent_node(hir_id);
437 match hir.find(parent_node) {
438 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
439 get_name(err, &local.pat.kind)
441 // Different to previous arm because one is `&hir::Local` and the other
442 // is `P<hir::Local>`.
443 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
448 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
449 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
450 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
453 obligation: &PredicateObligation<'tcx>,
454 err: &mut DiagnosticBuilder<'_>,
455 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
458 let self_ty = trait_ref.self_ty();
459 let (def_id, output_ty, callable) = match self_ty.kind {
460 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig().output(), "closure"),
461 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
464 let msg = format!("use parentheses to call the {}", callable);
466 let obligation = self.mk_obligation_for_def_id(
468 output_ty.skip_binder(),
469 obligation.cause.clone(),
470 obligation.param_env,
473 match self.evaluate_obligation(&obligation) {
475 EvaluationResult::EvaluatedToOk
476 | EvaluationResult::EvaluatedToOkModuloRegions
477 | EvaluationResult::EvaluatedToAmbig,
481 let hir = self.tcx.hir();
482 // Get the name of the callable and the arguments to be used in the suggestion.
483 let (snippet, sugg) = match hir.get_if_local(def_id) {
484 Some(hir::Node::Expr(hir::Expr {
485 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
488 err.span_label(*span, "consider calling this closure");
489 let name = match self.get_closure_name(def_id, err, &msg) {
493 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
494 let sugg = format!("({})", args);
495 (format!("{}{}", name, sugg), sugg)
497 Some(hir::Node::Item(hir::Item {
499 kind: hir::ItemKind::Fn(.., body_id),
502 err.span_label(ident.span, "consider calling this function");
503 let body = hir.body(*body_id);
507 .map(|arg| match &arg.pat.kind {
508 hir::PatKind::Binding(_, _, ident, None)
509 // FIXME: provide a better suggestion when encountering `SelfLower`, it
510 // should suggest a method call.
511 if ident.name != kw::SelfLower => ident.to_string(),
512 _ => "_".to_string(),
516 let sugg = format!("({})", args);
517 (format!("{}{}", ident, sugg), sugg)
522 // When the obligation error has been ensured to have been caused by
523 // an argument, the `obligation.cause.span` points at the expression
524 // of the argument, so we can provide a suggestion. This is signaled
525 // by `points_at_arg`. Otherwise, we give a more general note.
526 err.span_suggestion_verbose(
527 obligation.cause.span.shrink_to_hi(),
530 Applicability::HasPlaceholders,
533 err.help(&format!("{}: `{}`", msg, snippet));
537 fn suggest_add_reference_to_arg(
539 obligation: &PredicateObligation<'tcx>,
540 err: &mut DiagnosticBuilder<'tcx>,
541 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
543 has_custom_message: bool,
549 let span = obligation.cause.span;
550 let param_env = obligation.param_env;
551 let trait_ref = trait_ref.skip_binder();
553 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
554 // Try to apply the original trait binding obligation by borrowing.
555 let self_ty = trait_ref.self_ty();
556 let found = self_ty.to_string();
557 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
558 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
559 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
560 let new_obligation = Obligation::new(
561 ObligationCause::dummy(),
563 new_trait_ref.without_const().to_predicate(),
565 if self.predicate_must_hold_modulo_regions(&new_obligation) {
566 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
567 // We have a very specific type of error, where just borrowing this argument
568 // might solve the problem. In cases like this, the important part is the
569 // original type obligation, not the last one that failed, which is arbitrary.
570 // Because of this, we modify the error to refer to the original obligation and
571 // return early in the caller.
573 "the trait bound `{}: {}` is not satisfied",
575 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
577 if has_custom_message {
580 err.message = vec![(msg, Style::NoStyle)];
582 if snippet.starts_with('&') {
583 // This is already a literal borrow and the obligation is failing
584 // somewhere else in the obligation chain. Do not suggest non-sense.
590 "expected an implementor of trait `{}`",
591 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
596 "consider borrowing here",
597 format!("&{}", snippet),
598 Applicability::MaybeIncorrect,
607 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
608 /// suggest removing these references until we reach a type that implements the trait.
609 fn suggest_remove_reference(
611 obligation: &PredicateObligation<'tcx>,
612 err: &mut DiagnosticBuilder<'tcx>,
613 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
615 let trait_ref = trait_ref.skip_binder();
616 let span = obligation.cause.span;
618 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
620 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
621 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
622 // Do not suggest removal of borrow from type arguments.
626 let mut trait_type = trait_ref.self_ty();
628 for refs_remaining in 0..refs_number {
629 if let ty::Ref(_, t_type, _) = trait_type.kind {
632 let new_obligation = self.mk_obligation_for_def_id(
635 ObligationCause::dummy(),
636 obligation.param_env,
639 if self.predicate_may_hold(&new_obligation) {
644 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
646 let remove_refs = refs_remaining + 1;
648 let msg = if remove_refs == 1 {
649 "consider removing the leading `&`-reference".to_string()
651 format!("consider removing {} leading `&`-references", remove_refs)
654 err.span_suggestion_short(
658 Applicability::MachineApplicable,
669 /// Check if the trait bound is implemented for a different mutability and note it in the
671 fn suggest_change_mut(
673 obligation: &PredicateObligation<'tcx>,
674 err: &mut DiagnosticBuilder<'tcx>,
675 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
678 let span = obligation.cause.span;
679 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
681 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
682 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
683 // Do not suggest removal of borrow from type arguments.
686 let trait_ref = self.resolve_vars_if_possible(trait_ref);
687 if trait_ref.has_infer_types_or_consts() {
688 // Do not ICE while trying to find if a reborrow would succeed on a trait with
689 // unresolved bindings.
693 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
694 let trait_type = match mutability {
695 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
696 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
699 let new_obligation = self.mk_obligation_for_def_id(
700 trait_ref.skip_binder().def_id,
702 ObligationCause::dummy(),
703 obligation.param_env,
706 if self.evaluate_obligation_no_overflow(&new_obligation).must_apply_modulo_regions()
712 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
713 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
714 err.span_suggestion_verbose(
716 "consider changing this borrow's mutability",
718 Applicability::MachineApplicable,
722 "`{}` is implemented for `{:?}`, but not for `{:?}`",
723 trait_ref.print_only_trait_path(),
725 trait_ref.skip_binder().self_ty(),
733 fn suggest_semicolon_removal(
735 obligation: &PredicateObligation<'tcx>,
736 err: &mut DiagnosticBuilder<'tcx>,
738 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
740 let hir = self.tcx.hir();
741 let parent_node = hir.get_parent_node(obligation.cause.body_id);
742 let node = hir.find(parent_node);
743 if let Some(hir::Node::Item(hir::Item {
744 kind: hir::ItemKind::Fn(sig, _, body_id), ..
747 let body = hir.body(*body_id);
748 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
749 if sig.decl.output.span().overlaps(span)
750 && blk.expr.is_none()
751 && "()" == &trait_ref.self_ty().to_string()
753 // FIXME(estebank): When encountering a method with a trait
754 // bound not satisfied in the return type with a body that has
755 // no return, suggest removal of semicolon on last statement.
756 // Once that is added, close #54771.
757 if let Some(ref stmt) = blk.stmts.last() {
758 let sp = self.tcx.sess.source_map().end_point(stmt.span);
759 err.span_label(sp, "consider removing this semicolon");
766 fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
767 let hir = self.tcx.hir();
768 let parent_node = hir.get_parent_node(obligation.cause.body_id);
769 let sig = match hir.find(parent_node) {
770 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) => sig,
774 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
777 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
778 /// applicable and signal that the error has been expanded appropriately and needs to be
780 fn suggest_impl_trait(
782 err: &mut DiagnosticBuilder<'tcx>,
784 obligation: &PredicateObligation<'tcx>,
785 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
787 match obligation.cause.code.peel_derives() {
788 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
789 ObligationCauseCode::SizedReturnType => {}
793 let hir = self.tcx.hir();
794 let parent_node = hir.get_parent_node(obligation.cause.body_id);
795 let node = hir.find(parent_node);
796 let (sig, body_id) = if let Some(hir::Node::Item(hir::Item {
797 kind: hir::ItemKind::Fn(sig, _, body_id),
805 let body = hir.body(*body_id);
806 let trait_ref = self.resolve_vars_if_possible(trait_ref);
807 let ty = trait_ref.skip_binder().self_ty();
808 let is_object_safe = match ty.kind {
809 ty::Dynamic(predicates, _) => {
810 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
813 .map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
815 // We only want to suggest `impl Trait` to `dyn Trait`s.
816 // For example, `fn foo() -> str` needs to be filtered out.
820 let ret_ty = if let hir::FnRetTy::Return(ret_ty) = sig.decl.output {
826 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
827 // cases like `fn foo() -> (dyn Trait, i32) {}`.
828 // Recursively look for `TraitObject` types and if there's only one, use that span to
829 // suggest `impl Trait`.
831 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
832 // otherwise suggest using `Box<dyn Trait>` or an enum.
833 let mut visitor = ReturnsVisitor::default();
834 visitor.visit_body(&body);
836 let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
838 let mut ret_types = visitor
841 .filter_map(|expr| tables.node_type_opt(expr.hir_id))
842 .map(|ty| self.resolve_vars_if_possible(&ty));
843 let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold(
845 |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool),
847 let ty = self.resolve_vars_if_possible(&ty);
850 && last_ty.map_or(true, |last_ty| {
851 // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes
852 // *after* in the dependency graph.
853 match (&ty.kind, &last_ty.kind) {
854 (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_)))
855 | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_)))
856 | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_)))
858 Infer(InferTy::FreshFloatTy(_)),
859 Infer(InferTy::FreshFloatTy(_)),
864 (Some(ty), same, only_never_return && matches!(ty.kind, ty::Never))
867 let all_returns_conform_to_trait =
868 if let Some(ty_ret_ty) = tables.node_type_opt(ret_ty.hir_id) {
869 match ty_ret_ty.kind {
870 ty::Dynamic(predicates, _) => {
871 let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
872 let param_env = ty::ParamEnv::empty();
874 || ret_types.all(|returned_ty| {
875 predicates.iter().all(|predicate| {
876 let pred = predicate.with_self_ty(self.tcx, returned_ty);
877 let obl = Obligation::new(cause.clone(), param_env, pred);
878 self.predicate_may_hold(&obl)
888 let sm = self.tcx.sess.source_map();
889 let snippet = if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true) = (
890 // Verify that we're dealing with a return `dyn Trait`
891 ret_ty.span.overlaps(span),
893 sm.span_to_snippet(ret_ty.span),
894 // If any of the return types does not conform to the trait, then we can't
895 // suggest `impl Trait` nor trait objects: it is a type mismatch error.
896 all_returns_conform_to_trait,
902 err.code(error_code!(E0746));
903 err.set_primary_message("return type cannot have an unboxed trait object");
904 err.children.clear();
905 let impl_trait_msg = "for information on `impl Trait`, see \
906 <https://doc.rust-lang.org/book/ch10-02-traits.html\
907 #returning-types-that-implement-traits>";
908 let trait_obj_msg = "for information on trait objects, see \
909 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
910 #using-trait-objects-that-allow-for-values-of-different-types>";
911 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
912 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet[..] };
913 if only_never_return {
914 // No return paths, probably using `panic!()` or similar.
915 // Suggest `-> T`, `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`.
916 suggest_trait_object_return_type_alternatives(
922 } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) {
923 // Suggest `-> impl Trait`.
927 "use `impl {1}` as the return type, as all return paths are of type `{}`, \
928 which implements `{1}`",
931 format!("impl {}", trait_obj),
932 Applicability::MachineApplicable,
934 err.note(impl_trait_msg);
937 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
938 // Get all the return values and collect their span and suggestion.
939 if let Some(mut suggestions) = visitor
943 let snip = sm.span_to_snippet(expr.span).ok()?;
944 Some((expr.span, format!("Box::new({})", snip)))
946 .collect::<Option<Vec<_>>>()
948 // Add the suggestion for the return type.
949 suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
950 err.multipart_suggestion(
951 "return a boxed trait object instead",
953 Applicability::MaybeIncorrect,
957 // This is currently not possible to trigger because E0038 takes precedence, but
958 // leave it in for completeness in case anything changes in an earlier stage.
960 "if trait `{}` was object safe, you could return a trait object",
964 err.note(trait_obj_msg);
966 "if all the returned values were of the same type you could use `impl {}` as the \
970 err.note(impl_trait_msg);
971 err.note("you can create a new `enum` with a variant for each returned type");
976 fn point_at_returns_when_relevant(
978 err: &mut DiagnosticBuilder<'tcx>,
979 obligation: &PredicateObligation<'tcx>,
981 match obligation.cause.code.peel_derives() {
982 ObligationCauseCode::SizedReturnType => {}
986 let hir = self.tcx.hir();
987 let parent_node = hir.get_parent_node(obligation.cause.body_id);
988 let node = hir.find(parent_node);
989 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
992 let body = hir.body(*body_id);
993 // Point at all the `return`s in the function as they have failed trait bounds.
994 let mut visitor = ReturnsVisitor::default();
995 visitor.visit_body(&body);
996 let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
997 for expr in &visitor.returns {
998 if let Some(returned_ty) = tables.node_type_opt(expr.hir_id) {
999 let ty = self.resolve_vars_if_possible(&returned_ty);
1000 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
1006 fn report_closure_arg_mismatch(
1009 found_span: Option<Span>,
1010 expected_ref: ty::PolyTraitRef<'tcx>,
1011 found: ty::PolyTraitRef<'tcx>,
1012 ) -> DiagnosticBuilder<'tcx> {
1013 crate fn build_fn_sig_string<'tcx>(
1015 trait_ref: &ty::TraitRef<'tcx>,
1017 let inputs = trait_ref.substs.type_at(1);
1018 let sig = if let ty::Tuple(inputs) = inputs.kind {
1020 inputs.iter().map(|k| k.expect_ty()),
1021 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1023 hir::Unsafety::Normal,
1024 ::rustc_target::spec::abi::Abi::Rust,
1028 ::std::iter::once(inputs),
1029 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
1031 hir::Unsafety::Normal,
1032 ::rustc_target::spec::abi::Abi::Rust,
1035 ty::Binder::bind(sig).to_string()
1038 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1039 let mut err = struct_span_err!(
1043 "type mismatch in {} arguments",
1044 if argument_is_closure { "closure" } else { "function" }
1047 let found_str = format!(
1048 "expected signature of `{}`",
1049 build_fn_sig_string(self.tcx, found.skip_binder())
1051 err.span_label(span, found_str);
1053 let found_span = found_span.unwrap_or(span);
1054 let expected_str = format!(
1055 "found signature of `{}`",
1056 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1058 err.span_label(found_span, expected_str);
1063 fn suggest_fully_qualified_path(
1065 err: &mut DiagnosticBuilder<'_>,
1070 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1071 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1073 "{}s cannot be accessed directly on a `trait`, they can only be \
1074 accessed through a specific `impl`",
1075 assoc_item.kind.as_def_kind().descr(def_id)
1077 err.span_suggestion(
1079 "use the fully qualified path to an implementation",
1080 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1081 Applicability::HasPlaceholders,
1087 /// Adds an async-await specific note to the diagnostic when the future does not implement
1088 /// an auto trait because of a captured type.
1091 /// note: future does not implement `Qux` as this value is used across an await
1092 /// --> $DIR/issue-64130-3-other.rs:17:5
1094 /// LL | let x = Foo;
1095 /// | - has type `Foo`
1096 /// LL | baz().await;
1097 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1099 /// | - `x` is later dropped here
1102 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1103 /// is "replaced" with a different message and a more specific error.
1106 /// error: future cannot be sent between threads safely
1107 /// --> $DIR/issue-64130-2-send.rs:21:5
1109 /// LL | fn is_send<T: Send>(t: T) { }
1110 /// | ---- required by this bound in `is_send`
1112 /// LL | is_send(bar());
1113 /// | ^^^^^^^ future returned by `bar` is not send
1115 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1116 /// implemented for `Foo`
1117 /// note: future is not send as this value is used across an await
1118 /// --> $DIR/issue-64130-2-send.rs:15:5
1120 /// LL | let x = Foo;
1121 /// | - has type `Foo`
1122 /// LL | baz().await;
1123 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1125 /// | - `x` is later dropped here
1128 /// Returns `true` if an async-await specific note was added to the diagnostic.
1129 fn maybe_note_obligation_cause_for_async_await(
1131 err: &mut DiagnosticBuilder<'_>,
1132 obligation: &PredicateObligation<'tcx>,
1135 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1136 obligation.cause.span={:?}",
1137 obligation.predicate, obligation.cause.span
1139 let source_map = self.tcx.sess.source_map();
1140 let hir = self.tcx.hir();
1142 // Attempt to detect an async-await error by looking at the obligation causes, looking
1143 // for a generator to be present.
1145 // When a future does not implement a trait because of a captured type in one of the
1146 // generators somewhere in the call stack, then the result is a chain of obligations.
1148 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
1149 // future is passed as an argument to a function C which requires a `Send` type, then the
1150 // chain looks something like this:
1152 // - `BuiltinDerivedObligation` with a generator witness (B)
1153 // - `BuiltinDerivedObligation` with a generator (B)
1154 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1155 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1156 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1157 // - `BuiltinDerivedObligation` with a generator witness (A)
1158 // - `BuiltinDerivedObligation` with a generator (A)
1159 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1160 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1161 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1162 // - `BindingObligation` with `impl_send (Send requirement)
1164 // The first obligation in the chain is the most useful and has the generator that captured
1165 // the type. The last generator (`outer_generator` below) has information about where the
1166 // bound was introduced. At least one generator should be present for this diagnostic to be
1168 let (mut trait_ref, mut target_ty) = match obligation.predicate {
1169 ty::Predicate::Trait(p, _) => {
1170 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty()))
1174 let mut generator = None;
1175 let mut outer_generator = None;
1176 let mut next_code = Some(&obligation.cause.code);
1177 while let Some(code) = next_code {
1178 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1180 ObligationCauseCode::DerivedObligation(derived_obligation)
1181 | ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1182 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1183 let ty = derived_obligation.parent_trait_ref.self_ty();
1185 "maybe_note_obligation_cause_for_async_await: \
1186 parent_trait_ref={:?} self_ty.kind={:?}",
1187 derived_obligation.parent_trait_ref, ty.kind
1191 ty::Generator(did, ..) => {
1192 generator = generator.or(Some(did));
1193 outer_generator = Some(did);
1195 ty::GeneratorWitness(..) => {}
1196 _ if generator.is_none() => {
1197 trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
1198 target_ty = Some(ty);
1203 next_code = Some(derived_obligation.parent_code.as_ref());
1209 // Only continue if a generator was found.
1211 "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
1213 generator, trait_ref, target_ty
1215 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1216 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1217 (generator_did, trait_ref, target_ty)
1222 let span = self.tcx.def_span(generator_did);
1224 // Do not ICE on closure typeck (#66868).
1225 if !generator_did.is_local() {
1229 // Get the tables from the infcx if the generator is the function we are
1230 // currently type-checking; otherwise, get them by performing a query.
1231 // This is needed to avoid cycles.
1232 let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
1233 let generator_did_root = self.tcx.closure_base_def_id(generator_did);
1235 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1236 generator_did_root={:?} in_progress_tables.hir_owner={:?} span={:?}",
1239 in_progress_tables.as_ref().map(|t| t.hir_owner),
1243 let tables: &TypeckTables<'tcx> = match &in_progress_tables {
1244 Some(t) if t.hir_owner.map(|owner| owner.to_def_id()) == Some(generator_did_root) => t,
1246 query_tables = self.tcx.typeck_tables_of(generator_did);
1251 let generator_body = generator_did
1253 .map(|def_id| hir.as_local_hir_id(def_id))
1254 .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
1255 .map(|body_id| hir.body(body_id));
1256 let mut visitor = AwaitsVisitor::default();
1257 if let Some(body) = generator_body {
1258 visitor.visit_body(body);
1260 debug!("maybe_note_obligation_cause_for_async_await: awaits = {:?}", visitor.awaits);
1262 // Look for a type inside the generator interior that matches the target type to get
1264 let target_ty_erased = self.tcx.erase_regions(&target_ty);
1265 let ty_matches = |ty| -> bool {
1266 // Careful: the regions for types that appear in the
1267 // generator interior are not generally known, so we
1268 // want to erase them when comparing (and anyway,
1269 // `Send` and other bounds are generally unaffected by
1270 // the choice of region). When erasing regions, we
1271 // also have to erase late-bound regions. This is
1272 // because the types that appear in the generator
1273 // interior generally contain "bound regions" to
1274 // represent regions that are part of the suspended
1275 // generator frame. Bound regions are preserved by
1276 // `erase_regions` and so we must also call
1277 // `erase_late_bound_regions`.
1278 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(ty));
1279 let ty_erased = self.tcx.erase_regions(&ty_erased);
1280 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1282 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1283 target_ty_erased={:?} eq={:?}",
1284 ty_erased, target_ty_erased, eq
1288 let target_span = tables
1289 .generator_interior_types
1291 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| ty_matches(ty))
1293 // Check to see if any awaited expressions have the target type.
1294 let from_awaited_ty = visitor
1297 .map(|id| hir.expect_expr(id))
1298 .find(|await_expr| {
1299 let ty = tables.expr_ty_adjusted(&await_expr);
1301 "maybe_note_obligation_cause_for_async_await: await_expr={:?}",
1306 .map(|expr| expr.span);
1307 let ty::GeneratorInteriorTypeCause { span, scope_span, yield_span, expr, .. } =
1311 source_map.span_to_snippet(*span),
1320 "maybe_note_obligation_cause_for_async_await: target_ty={:?} \
1321 generator_interior_types={:?} target_span={:?}",
1322 target_ty, tables.generator_interior_types, target_span
1324 if let Some((target_span, Ok(snippet), scope_span, yield_span, expr, from_awaited_ty)) =
1327 self.note_obligation_cause_for_async_await(
1349 /// Unconditionally adds the diagnostic note described in
1350 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1351 fn note_obligation_cause_for_async_await(
1353 err: &mut DiagnosticBuilder<'_>,
1355 scope_span: &Option<Span>,
1357 expr: Option<hir::HirId>,
1359 inner_generator_body: Option<&hir::Body<'_>>,
1360 outer_generator: Option<DefId>,
1361 trait_ref: ty::TraitRef<'_>,
1362 target_ty: Ty<'tcx>,
1363 tables: &ty::TypeckTables<'_>,
1364 obligation: &PredicateObligation<'tcx>,
1365 next_code: Option<&ObligationCauseCode<'tcx>>,
1366 from_awaited_ty: Option<Span>,
1368 let source_map = self.tcx.sess.source_map();
1370 let is_async = inner_generator_body
1371 .and_then(|body| body.generator_kind())
1372 .map(|generator_kind| matches!(generator_kind, hir::GeneratorKind::Async(..)))
1374 let (await_or_yield, an_await_or_yield) =
1375 if is_async { ("await", "an await") } else { ("yield", "a yield") };
1376 let future_or_generator = if is_async { "future" } else { "generator" };
1378 // Special case the primary error message when send or sync is the trait that was
1380 let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
1381 let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
1382 let hir = self.tcx.hir();
1383 let trait_explanation = if is_send || is_sync {
1384 let (trait_name, trait_verb) =
1385 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1388 err.set_primary_message(format!(
1389 "{} cannot be {} between threads safely",
1390 future_or_generator, trait_verb
1393 let original_span = err.span.primary_span().unwrap();
1394 let mut span = MultiSpan::from_span(original_span);
1396 let message = outer_generator
1397 .and_then(|generator_did| {
1398 Some(match self.tcx.generator_kind(generator_did).unwrap() {
1399 GeneratorKind::Gen => format!("generator is not {}", trait_name),
1400 GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
1402 .parent(generator_did)
1403 .and_then(|parent_did| parent_did.as_local())
1404 .map(|parent_did| hir.as_local_hir_id(parent_did))
1405 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1407 format!("future returned by `{}` is not {}", name, trait_name)
1409 GeneratorKind::Async(AsyncGeneratorKind::Block) => {
1410 format!("future created by async block is not {}", trait_name)
1412 GeneratorKind::Async(AsyncGeneratorKind::Closure) => {
1413 format!("future created by async closure is not {}", trait_name)
1417 .unwrap_or_else(|| format!("{} is not {}", future_or_generator, trait_name));
1419 span.push_span_label(original_span, message);
1422 format!("is not {}", trait_name)
1424 format!("does not implement `{}`", trait_ref.print_only_trait_path())
1427 if let Some(await_span) = from_awaited_ty {
1428 // The type causing this obligation is one being awaited at await_span.
1429 let mut span = MultiSpan::from_span(await_span);
1431 span.push_span_label(
1433 format!("await occurs here on type `{}`, which {}", target_ty, trait_explanation),
1439 "future {not_trait} as it awaits another future which {not_trait}",
1440 not_trait = trait_explanation
1444 // Look at the last interior type to get a span for the `.await`.
1446 "note_obligation_cause_for_async_await generator_interior_types: {:#?}",
1447 tables.generator_interior_types
1449 let mut span = MultiSpan::from_span(yield_span);
1450 span.push_span_label(
1452 format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
1455 span.push_span_label(
1457 format!("has type `{}` which {}", target_ty, trait_explanation),
1460 // If available, use the scope span to annotate the drop location.
1461 if let Some(scope_span) = scope_span {
1462 span.push_span_label(
1463 source_map.end_point(*scope_span),
1464 format!("`{}` is later dropped here", snippet),
1471 "{} {} as this value is used across {}",
1472 future_or_generator, trait_explanation, an_await_or_yield
1477 if let Some(expr_id) = expr {
1478 let expr = hir.expect_expr(expr_id);
1479 debug!("target_ty evaluated from {:?}", expr);
1481 let parent = hir.get_parent_node(expr_id);
1482 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1483 let parent_span = hir.span(parent);
1484 let parent_did = parent.owner.to_def_id();
1487 // fn foo(&self) -> i32 {}
1490 // ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1493 let is_region_borrow =
1494 tables.expr_adjustments(expr).iter().any(|adj| adj.is_region_borrow());
1497 // struct Foo(*const u8);
1498 // bar(Foo(std::ptr::null())).await;
1499 // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1501 debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1502 let is_raw_borrow_inside_fn_like_call = match self.tcx.def_kind(parent_did) {
1503 DefKind::Fn | DefKind::Ctor(..) => target_ty.is_unsafe_ptr(),
1507 if (tables.is_method_call(e) && is_region_borrow)
1508 || is_raw_borrow_inside_fn_like_call
1512 "consider moving this into a `let` \
1513 binding to create a shorter lived borrow",
1519 // Add a note for the item obligation that remains - normally a note pointing to the
1520 // bound that introduced the obligation (e.g. `T: Send`).
1521 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1522 self.note_obligation_cause_code(
1524 &obligation.predicate,
1530 fn note_obligation_cause_code<T>(
1532 err: &mut DiagnosticBuilder<'_>,
1534 cause_code: &ObligationCauseCode<'tcx>,
1535 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1541 ObligationCauseCode::ExprAssignable
1542 | ObligationCauseCode::MatchExpressionArm { .. }
1543 | ObligationCauseCode::Pattern { .. }
1544 | ObligationCauseCode::IfExpression { .. }
1545 | ObligationCauseCode::IfExpressionWithNoElse
1546 | ObligationCauseCode::MainFunctionType
1547 | ObligationCauseCode::StartFunctionType
1548 | ObligationCauseCode::IntrinsicType
1549 | ObligationCauseCode::MethodReceiver
1550 | ObligationCauseCode::ReturnNoExpression
1551 | ObligationCauseCode::MiscObligation => {}
1552 ObligationCauseCode::SliceOrArrayElem => {
1553 err.note("slice and array elements must have `Sized` type");
1555 ObligationCauseCode::TupleElem => {
1556 err.note("only the last element of a tuple may have a dynamically sized type");
1558 ObligationCauseCode::ProjectionWf(data) => {
1559 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1561 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1563 "required so that reference `{}` does not outlive its referent",
1567 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1569 "required so that the lifetime bound of `{}` for `{}` is satisfied",
1573 ObligationCauseCode::ItemObligation(item_def_id) => {
1574 let item_name = tcx.def_path_str(item_def_id);
1575 let msg = format!("required by `{}`", item_name);
1576 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1577 let sp = tcx.sess.source_map().guess_head_span(sp);
1578 err.span_label(sp, &msg);
1583 ObligationCauseCode::BindingObligation(item_def_id, span) => {
1584 let item_name = tcx.def_path_str(item_def_id);
1585 let msg = format!("required by this bound in `{}`", item_name);
1586 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1587 let sm = tcx.sess.source_map();
1589 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
1590 (Ok(l), Ok(r)) => l.line == r.line,
1593 if !ident.span.overlaps(span) && !same_line {
1594 err.span_label(ident.span, "required by a bound in this");
1597 if span != DUMMY_SP {
1598 err.span_label(span, &msg);
1603 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1605 "required for the cast to the object type `{}`",
1606 self.ty_to_string(object_ty)
1609 ObligationCauseCode::Coercion { source: _, target } => {
1610 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1612 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
1614 "the `Copy` trait is required because the repeated element will be copied",
1616 if suggest_const_in_array_repeat_expressions {
1618 "this array initializer can be evaluated at compile-time, see issue \
1619 #48147 <https://github.com/rust-lang/rust/issues/49147> \
1620 for more information",
1622 if tcx.sess.opts.unstable_features.is_nightly_build() {
1624 "add `#![feature(const_in_array_repeat_expressions)]` to the \
1625 crate attributes to enable",
1630 ObligationCauseCode::VariableType(_) => {
1631 err.note("all local variables must have a statically known size");
1632 if !self.tcx.features().unsized_locals {
1633 err.help("unsized locals are gated as an unstable feature");
1636 ObligationCauseCode::SizedArgumentType => {
1637 err.note("all function arguments must have a statically known size");
1638 if !self.tcx.features().unsized_locals {
1639 err.help("unsized locals are gated as an unstable feature");
1642 ObligationCauseCode::SizedReturnType => {
1643 err.note("the return type of a function must have a statically known size");
1645 ObligationCauseCode::SizedYieldType => {
1646 err.note("the yield type of a generator must have a statically known size");
1648 ObligationCauseCode::AssignmentLhsSized => {
1649 err.note("the left-hand-side of an assignment must have a statically known size");
1651 ObligationCauseCode::TupleInitializerSized => {
1652 err.note("tuples must have a statically known size to be initialized");
1654 ObligationCauseCode::StructInitializerSized => {
1655 err.note("structs must have a statically known size to be initialized");
1657 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => match *item {
1658 AdtKind::Struct => {
1661 "the last field of a packed struct may only have a \
1662 dynamically sized type if it does not need drop to be run",
1666 "only the last field of a struct may have a dynamically sized type",
1671 err.note("no field of a union may have a dynamically sized type");
1674 err.note("no field of an enum variant may have a dynamically sized type");
1677 ObligationCauseCode::ConstSized => {
1678 err.note("constant expressions must have a statically known size");
1680 ObligationCauseCode::ConstPatternStructural => {
1681 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
1683 ObligationCauseCode::SharedStatic => {
1684 err.note("shared static variables must have a type that implements `Sync`");
1686 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1687 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1688 let ty = parent_trait_ref.skip_binder().self_ty();
1689 err.note(&format!("required because it appears within the type `{}`", ty));
1690 obligated_types.push(ty);
1692 let parent_predicate = parent_trait_ref.without_const().to_predicate();
1693 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1694 self.note_obligation_cause_code(
1702 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1703 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1705 "required because of the requirements on the impl of `{}` for `{}`",
1706 parent_trait_ref.print_only_trait_path(),
1707 parent_trait_ref.skip_binder().self_ty()
1709 let parent_predicate = parent_trait_ref.without_const().to_predicate();
1710 self.note_obligation_cause_code(
1717 ObligationCauseCode::DerivedObligation(ref data) => {
1718 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1719 let parent_predicate = parent_trait_ref.without_const().to_predicate();
1720 self.note_obligation_cause_code(
1727 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1729 "the requirement `{}` appears on the impl method \
1730 but not on the corresponding trait method",
1734 ObligationCauseCode::CompareImplTypeObligation { .. } => {
1736 "the requirement `{}` appears on the associated impl type \
1737 but not on the corresponding associated trait type",
1741 ObligationCauseCode::ReturnType
1742 | ObligationCauseCode::ReturnValue(_)
1743 | ObligationCauseCode::BlockTailExpression(_) => (),
1744 ObligationCauseCode::TrivialBound => {
1745 err.help("see issue #48214");
1746 if tcx.sess.opts.unstable_features.is_nightly_build() {
1747 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
1753 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1754 let current_limit = self.tcx.sess.recursion_limit.get();
1755 let suggested_limit = current_limit * 2;
1757 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
1758 suggested_limit, self.tcx.crate_name,
1763 /// Collect all the returned expressions within the input expression.
1764 /// Used to point at the return spans when we want to suggest some change to them.
1766 struct ReturnsVisitor<'v> {
1767 returns: Vec<&'v hir::Expr<'v>>,
1768 in_block_tail: bool,
1771 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
1772 type Map = hir::intravisit::ErasedMap<'v>;
1774 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
1775 hir::intravisit::NestedVisitorMap::None
1778 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
1779 // Visit every expression to detect `return` paths, either through the function's tail
1780 // expression or `return` statements. We walk all nodes to find `return` statements, but
1781 // we only care about tail expressions when `in_block_tail` is `true`, which means that
1782 // they're in the return path of the function body.
1784 hir::ExprKind::Ret(Some(ex)) => {
1785 self.returns.push(ex);
1787 hir::ExprKind::Block(block, _) if self.in_block_tail => {
1788 self.in_block_tail = false;
1789 for stmt in block.stmts {
1790 hir::intravisit::walk_stmt(self, stmt);
1792 self.in_block_tail = true;
1793 if let Some(expr) = block.expr {
1794 self.visit_expr(expr);
1797 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
1799 self.visit_expr(arm.body);
1802 // We need to walk to find `return`s in the entire body.
1803 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
1804 _ => self.returns.push(ex),
1808 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
1809 assert!(!self.in_block_tail);
1810 if body.generator_kind().is_none() {
1811 if let hir::ExprKind::Block(block, None) = body.value.kind {
1812 if block.expr.is_some() {
1813 self.in_block_tail = true;
1817 hir::intravisit::walk_body(self, body);
1821 /// Collect all the awaited expressions within the input expression.
1823 struct AwaitsVisitor {
1824 awaits: Vec<hir::HirId>,
1827 impl<'v> Visitor<'v> for AwaitsVisitor {
1828 type Map = hir::intravisit::ErasedMap<'v>;
1830 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
1831 hir::intravisit::NestedVisitorMap::None
1834 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
1835 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
1836 self.awaits.push(id)
1838 hir::intravisit::walk_expr(self, ex)
1842 pub trait NextTypeParamName {
1843 fn next_type_param_name(&self, name: Option<&str>) -> String;
1846 impl NextTypeParamName for &[hir::GenericParam<'_>] {
1847 fn next_type_param_name(&self, name: Option<&str>) -> String {
1848 // This is the whitelist of possible parameter names that we might suggest.
1849 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase());
1850 let name = name.as_ref().map(|s| s.as_str());
1851 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
1852 let used_names = self
1854 .filter_map(|p| match p.name {
1855 hir::ParamName::Plain(ident) => Some(ident.name),
1858 .collect::<Vec<_>>();
1862 .find(|n| !used_names.contains(&Symbol::intern(n)))
1863 .unwrap_or(&"ParamName")
1868 fn suggest_trait_object_return_type_alternatives(
1869 err: &mut DiagnosticBuilder<'tcx>,
1872 is_object_safe: bool,
1874 err.span_suggestion(
1876 "use some type `T` that is `T: Sized` as the return type if all return paths have the \
1879 Applicability::MaybeIncorrect,
1881 err.span_suggestion(
1884 "use `impl {}` as the return type if all return paths have the same type but you \
1885 want to expose only the trait in the signature",
1888 format!("impl {}", trait_obj),
1889 Applicability::MaybeIncorrect,
1892 err.span_suggestion(
1895 "use a boxed trait object if all return paths implement trait `{}`",
1898 format!("Box<dyn {}>", trait_obj),
1899 Applicability::MaybeIncorrect,