2 ArgKind, EvaluationResult, Obligation, ObligationCause, ObligationCauseCode,
6 use crate::infer::InferCtxt;
7 use crate::traits::object_safety::object_safety_violations;
8 use crate::ty::TypeckTables;
9 use crate::ty::{self, AdtKind, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable};
12 error_code, pluralize, struct_span_err, Applicability, DiagnosticBuilder, Style,
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::intravisit::Visitor;
18 use rustc_span::source_map::SourceMap;
19 use rustc_span::symbol::{kw, sym};
20 use rustc_span::{MultiSpan, Span, DUMMY_SP};
23 use rustc_error_codes::*;
25 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
26 crate fn suggest_restricting_param_bound(
28 mut err: &mut DiagnosticBuilder<'_>,
29 trait_ref: &ty::PolyTraitRef<'_>,
32 let self_ty = trait_ref.self_ty();
33 let (param_ty, projection) = match &self_ty.kind {
34 ty::Param(_) => (true, None),
35 ty::Projection(projection) => (false, Some(projection)),
39 let suggest_restriction =
40 |generics: &hir::Generics<'_>, msg, err: &mut DiagnosticBuilder<'_>| {
41 let span = generics.where_clause.span_for_predicates_or_empty_place();
42 if !span.from_expansion() && span.desugaring_kind().is_none() {
44 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
45 &format!("consider further restricting {}", msg),
48 if !generics.where_clause.predicates.is_empty() {
53 trait_ref.to_predicate(),
55 Applicability::MachineApplicable,
60 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
61 // don't suggest `T: Sized + ?Sized`.
62 let mut hir_id = body_id;
63 while let Some(node) = self.tcx.hir().find(hir_id) {
65 hir::Node::TraitItem(hir::TraitItem {
67 kind: hir::TraitItemKind::Method(..),
69 }) if param_ty && self_ty == self.tcx.types.self_param => {
70 // Restricting `Self` for a single method.
71 suggest_restriction(&generics, "`Self`", err);
75 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })
76 | hir::Node::TraitItem(hir::TraitItem {
78 kind: hir::TraitItemKind::Method(..),
81 | hir::Node::ImplItem(hir::ImplItem {
83 kind: hir::ImplItemKind::Method(..),
86 | hir::Node::Item(hir::Item {
87 kind: hir::ItemKind::Trait(_, _, generics, _, _),
90 | hir::Node::Item(hir::Item {
91 kind: hir::ItemKind::Impl(_, _, _, generics, ..),
93 }) if projection.is_some() => {
94 // Missing associated type bound.
95 suggest_restriction(&generics, "the associated type", err);
99 hir::Node::Item(hir::Item {
100 kind: hir::ItemKind::Struct(_, generics),
104 | hir::Node::Item(hir::Item {
105 kind: hir::ItemKind::Enum(_, generics), span, ..
107 | hir::Node::Item(hir::Item {
108 kind: hir::ItemKind::Union(_, generics),
112 | hir::Node::Item(hir::Item {
113 kind: hir::ItemKind::Trait(_, _, generics, ..),
117 | hir::Node::Item(hir::Item {
118 kind: hir::ItemKind::Impl(_, _, _, generics, ..),
122 | hir::Node::Item(hir::Item {
123 kind: hir::ItemKind::Fn(_, generics, _),
127 | hir::Node::Item(hir::Item {
128 kind: hir::ItemKind::TyAlias(_, generics),
132 | hir::Node::Item(hir::Item {
133 kind: hir::ItemKind::TraitAlias(generics, _),
137 | hir::Node::Item(hir::Item {
138 kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
142 | hir::Node::TraitItem(hir::TraitItem { generics, span, .. })
143 | hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
146 // Missing generic type parameter bound.
147 let param_name = self_ty.to_string();
148 let constraint = trait_ref.print_only_trait_path().to_string();
149 if suggest_constraining_type_param(
154 self.tcx.sess.source_map(),
161 hir::Node::Crate => return,
166 hir_id = self.tcx.hir().get_parent_item(hir_id);
170 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
171 /// suggestion to borrow the initializer in order to use have a slice instead.
172 crate fn suggest_borrow_on_unsized_slice(
174 code: &ObligationCauseCode<'tcx>,
175 err: &mut DiagnosticBuilder<'tcx>,
177 if let &ObligationCauseCode::VariableType(hir_id) = code {
178 let parent_node = self.tcx.hir().get_parent_node(hir_id);
179 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
180 if let Some(ref expr) = local.init {
181 if let hir::ExprKind::Index(_, _) = expr.kind {
182 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
185 "consider borrowing here",
186 format!("&{}", snippet),
187 Applicability::MachineApplicable,
196 /// Given a closure's `DefId`, return the given name of the closure.
198 /// This doesn't account for reassignments, but it's only used for suggestions.
199 crate fn get_closure_name(
202 err: &mut DiagnosticBuilder<'_>,
204 ) -> Option<String> {
206 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
207 // Get the local name of this closure. This can be inaccurate because
208 // of the possibility of reassignment, but this should be good enough.
210 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
211 Some(format!("{}", name))
220 let hir = self.tcx.hir();
221 let hir_id = hir.as_local_hir_id(def_id)?;
222 let parent_node = hir.get_parent_node(hir_id);
223 match hir.find(parent_node) {
224 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
225 get_name(err, &local.pat.kind)
227 // Different to previous arm because one is `&hir::Local` and the other
228 // is `P<hir::Local>`.
229 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
234 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
235 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
236 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
237 crate fn suggest_fn_call(
239 obligation: &PredicateObligation<'tcx>,
240 err: &mut DiagnosticBuilder<'_>,
241 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
244 let self_ty = trait_ref.self_ty();
245 let (def_id, output_ty, callable) = match self_ty.kind {
246 ty::Closure(def_id, substs) => {
247 (def_id, self.closure_sig(def_id, substs).output(), "closure")
249 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
252 let msg = format!("use parentheses to call the {}", callable);
254 let obligation = self.mk_obligation_for_def_id(
256 output_ty.skip_binder(),
257 obligation.cause.clone(),
258 obligation.param_env,
261 match self.evaluate_obligation(&obligation) {
262 Ok(EvaluationResult::EvaluatedToOk)
263 | Ok(EvaluationResult::EvaluatedToOkModuloRegions)
264 | Ok(EvaluationResult::EvaluatedToAmbig) => {}
267 let hir = self.tcx.hir();
268 // Get the name of the callable and the arguments to be used in the suggestion.
269 let snippet = match hir.get_if_local(def_id) {
270 Some(hir::Node::Expr(hir::Expr {
271 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
274 err.span_label(*span, "consider calling this closure");
275 let name = match self.get_closure_name(def_id, err, &msg) {
279 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
280 format!("{}({})", name, args)
282 Some(hir::Node::Item(hir::Item {
284 kind: hir::ItemKind::Fn(.., body_id),
287 err.span_label(ident.span, "consider calling this function");
288 let body = hir.body(*body_id);
292 .map(|arg| match &arg.pat.kind {
293 hir::PatKind::Binding(_, _, ident, None)
294 // FIXME: provide a better suggestion when encountering `SelfLower`, it
295 // should suggest a method call.
296 if ident.name != kw::SelfLower => ident.to_string(),
297 _ => "_".to_string(),
301 format!("{}({})", ident, args)
306 // When the obligation error has been ensured to have been caused by
307 // an argument, the `obligation.cause.span` points at the expression
308 // of the argument, so we can provide a suggestion. This is signaled
309 // by `points_at_arg`. Otherwise, we give a more general note.
311 obligation.cause.span,
314 Applicability::HasPlaceholders,
317 err.help(&format!("{}: `{}`", msg, snippet));
321 crate fn suggest_add_reference_to_arg(
323 obligation: &PredicateObligation<'tcx>,
324 err: &mut DiagnosticBuilder<'tcx>,
325 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
327 has_custom_message: bool,
333 let span = obligation.cause.span;
334 let param_env = obligation.param_env;
335 let trait_ref = trait_ref.skip_binder();
337 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
338 // Try to apply the original trait binding obligation by borrowing.
339 let self_ty = trait_ref.self_ty();
340 let found = self_ty.to_string();
341 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
342 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
343 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
345 Obligation::new(ObligationCause::dummy(), param_env, new_trait_ref.to_predicate());
346 if self.predicate_must_hold_modulo_regions(&new_obligation) {
347 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
348 // We have a very specific type of error, where just borrowing this argument
349 // might solve the problem. In cases like this, the important part is the
350 // original type obligation, not the last one that failed, which is arbitrary.
351 // Because of this, we modify the error to refer to the original obligation and
352 // return early in the caller.
354 "the trait bound `{}: {}` is not satisfied",
356 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
358 if has_custom_message {
361 err.message = vec![(msg, Style::NoStyle)];
363 if snippet.starts_with('&') {
364 // This is already a literal borrow and the obligation is failing
365 // somewhere else in the obligation chain. Do not suggest non-sense.
371 "expected an implementor of trait `{}`",
372 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
377 "consider borrowing here",
378 format!("&{}", snippet),
379 Applicability::MaybeIncorrect,
388 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
389 /// suggest removing these references until we reach a type that implements the trait.
390 crate fn suggest_remove_reference(
392 obligation: &PredicateObligation<'tcx>,
393 err: &mut DiagnosticBuilder<'tcx>,
394 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
396 let trait_ref = trait_ref.skip_binder();
397 let span = obligation.cause.span;
399 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
401 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
403 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
405 // Do not suggest removal of borrow from type arguments.
409 let mut trait_type = trait_ref.self_ty();
411 for refs_remaining in 0..refs_number {
412 if let ty::Ref(_, t_type, _) = trait_type.kind {
415 let new_obligation = self.mk_obligation_for_def_id(
418 ObligationCause::dummy(),
419 obligation.param_env,
422 if self.predicate_may_hold(&new_obligation) {
427 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
429 let remove_refs = refs_remaining + 1;
431 format!("consider removing {} leading `&`-references", remove_refs);
433 err.span_suggestion_short(
437 Applicability::MachineApplicable,
448 /// Check if the trait bound is implemented for a different mutability and note it in the
450 crate fn suggest_change_mut(
452 obligation: &PredicateObligation<'tcx>,
453 err: &mut DiagnosticBuilder<'tcx>,
454 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
457 let span = obligation.cause.span;
458 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
460 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
462 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
464 // Do not suggest removal of borrow from type arguments.
467 let trait_ref = self.resolve_vars_if_possible(trait_ref);
468 if trait_ref.has_infer_types() {
469 // Do not ICE while trying to find if a reborrow would succeed on a trait with
470 // unresolved bindings.
474 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
475 let trait_type = match mutability {
476 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
477 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
480 let new_obligation = self.mk_obligation_for_def_id(
481 trait_ref.skip_binder().def_id,
483 ObligationCause::dummy(),
484 obligation.param_env,
487 if self.evaluate_obligation_no_overflow(&new_obligation).must_apply_modulo_regions()
493 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
494 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
497 "consider changing this borrow's mutability",
499 Applicability::MachineApplicable,
503 "`{}` is implemented for `{:?}`, but not for `{:?}`",
504 trait_ref.print_only_trait_path(),
506 trait_ref.skip_binder().self_ty(),
514 crate fn suggest_semicolon_removal(
516 obligation: &PredicateObligation<'tcx>,
517 err: &mut DiagnosticBuilder<'tcx>,
519 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
521 let hir = self.tcx.hir();
522 let parent_node = hir.get_parent_node(obligation.cause.body_id);
523 let node = hir.find(parent_node);
524 if let Some(hir::Node::Item(hir::Item {
525 kind: hir::ItemKind::Fn(sig, _, body_id), ..
528 let body = hir.body(*body_id);
529 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
530 if sig.decl.output.span().overlaps(span)
531 && blk.expr.is_none()
532 && "()" == &trait_ref.self_ty().to_string()
534 // FIXME(estebank): When encountering a method with a trait
535 // bound not satisfied in the return type with a body that has
536 // no return, suggest removal of semicolon on last statement.
537 // Once that is added, close #54771.
538 if let Some(ref stmt) = blk.stmts.last() {
539 let sp = self.tcx.sess.source_map().end_point(stmt.span);
540 err.span_label(sp, "consider removing this semicolon");
547 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
548 /// applicable and signal that the error has been expanded appropriately and needs to be
550 crate fn suggest_impl_trait(
552 err: &mut DiagnosticBuilder<'tcx>,
554 obligation: &PredicateObligation<'tcx>,
555 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
557 match obligation.cause.code.peel_derives() {
558 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
559 ObligationCauseCode::SizedReturnType => {}
563 let hir = self.tcx.hir();
564 let parent_node = hir.get_parent_node(obligation.cause.body_id);
565 let node = hir.find(parent_node);
566 let (sig, body_id) = if let Some(hir::Node::Item(hir::Item {
567 kind: hir::ItemKind::Fn(sig, _, body_id),
575 let body = hir.body(*body_id);
576 let trait_ref = self.resolve_vars_if_possible(trait_ref);
577 let ty = trait_ref.skip_binder().self_ty();
578 let is_object_safe = match ty.kind {
579 ty::Dynamic(predicates, _) => {
580 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
583 .map_or(true, |def_id| object_safety_violations(self.tcx, def_id).is_empty())
585 // We only want to suggest `impl Trait` to `dyn Trait`s.
586 // For example, `fn foo() -> str` needs to be filtered out.
590 let ret_ty = if let hir::FunctionRetTy::Return(ret_ty) = sig.decl.output {
596 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
597 // cases like `fn foo() -> (dyn Trait, i32) {}`.
598 // Recursively look for `TraitObject` types and if there's only one, use that span to
599 // suggest `impl Trait`.
601 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
602 // otherwise suggest using `Box<dyn Trait>` or an enum.
603 let mut visitor = ReturnsVisitor(vec![]);
604 visitor.visit_body(&body);
606 let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
608 let mut ret_types = visitor.0.iter().filter_map(|expr| tables.node_type_opt(expr.hir_id));
609 let (last_ty, all_returns_have_same_type) =
610 ret_types.clone().fold((None, true), |(last_ty, mut same), returned_ty| {
611 same &= last_ty.map_or(true, |ty| ty == returned_ty);
612 (Some(returned_ty), same)
614 let all_returns_conform_to_trait =
615 if let Some(ty_ret_ty) = tables.node_type_opt(ret_ty.hir_id) {
616 match ty_ret_ty.kind {
617 ty::Dynamic(predicates, _) => {
618 let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
619 let param_env = ty::ParamEnv::empty();
620 ret_types.all(|returned_ty| {
621 predicates.iter().all(|predicate| {
622 let pred = predicate.with_self_ty(self.tcx, returned_ty);
623 let obl = Obligation::new(cause.clone(), param_env, pred);
624 self.predicate_may_hold(&obl)
634 let (snippet, last_ty) =
635 if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true, Some(last_ty)) = (
636 // Verify that we're dealing with a return `dyn Trait`
637 ret_ty.span.overlaps(span),
639 self.tcx.sess.source_map().span_to_snippet(ret_ty.span),
640 // If any of the return types does not conform to the trait, then we can't
641 // suggest `impl Trait` nor trait objects, it is a type mismatch error.
642 all_returns_conform_to_trait,
649 err.code(error_code!(E0746));
650 err.set_primary_message("return type cannot have an unboxed trait object");
651 err.children.clear();
652 let impl_trait_msg = "for information on `impl Trait`, see \
653 <https://doc.rust-lang.org/book/ch10-02-traits.html\
654 #returning-types-that-implement-traits>";
655 let trait_obj_msg = "for information on trait objects, see \
656 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
657 #using-trait-objects-that-allow-for-values-of-different-types>";
658 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
659 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet[..] };
660 if all_returns_have_same_type {
661 // Suggest `-> impl Trait`.
665 "return `impl {1}` instead, as all return paths are of type `{}`, \
666 which implements `{1}`",
669 format!("impl {}", trait_obj),
670 Applicability::MachineApplicable,
672 err.note(impl_trait_msg);
675 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
676 // Get all the return values and collect their span and suggestion.
677 let mut suggestions = visitor
685 self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap()
689 .collect::<Vec<_>>();
690 // Add the suggestion for the return type.
693 format!("Box<{}{}>", if has_dyn { "" } else { "dyn " }, snippet),
695 err.multipart_suggestion(
696 "return a boxed trait object instead",
698 Applicability::MaybeIncorrect,
701 // This is currently not possible to trigger because E0038 takes precedence, but
702 // leave it in for completeness in case anything changes in an earlier stage.
704 "if trait `{}` was object safe, you could return a trait object",
708 err.note(trait_obj_msg);
710 "if all the returned values were of the same type you could use \
711 `impl {}` as the return type",
714 err.note(impl_trait_msg);
715 err.note("you can create a new `enum` with a variant for each returned type");
720 crate fn point_at_returns_when_relevant(
722 err: &mut DiagnosticBuilder<'tcx>,
723 obligation: &PredicateObligation<'tcx>,
725 match obligation.cause.code.peel_derives() {
726 ObligationCauseCode::SizedReturnType => {}
730 let hir = self.tcx.hir();
731 let parent_node = hir.get_parent_node(obligation.cause.body_id);
732 let node = hir.find(parent_node);
733 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
736 let body = hir.body(*body_id);
737 // Point at all the `return`s in the function as they have failed trait bounds.
738 let mut visitor = ReturnsVisitor(vec![]);
739 visitor.visit_body(&body);
740 let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
741 for expr in &visitor.0 {
742 if let Some(returned_ty) = tables.node_type_opt(expr.hir_id) {
743 let ty = self.resolve_vars_if_possible(&returned_ty);
744 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
750 /// Given some node representing a fn-like thing in the HIR map,
751 /// returns a span and `ArgKind` information that describes the
752 /// arguments it expects. This can be supplied to
753 /// `report_arg_count_mismatch`.
754 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
756 Node::Expr(&hir::Expr {
757 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
760 self.tcx.sess.source_map().def_span(span),
767 if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
778 .span_to_snippet(pat.span)
780 (snippet, "_".to_owned())
782 .collect::<Vec<_>>(),
786 self.tcx.sess.source_map().span_to_snippet(arg.pat.span).unwrap();
787 ArgKind::Arg(name, "_".to_owned())
790 .collect::<Vec<ArgKind>>(),
792 Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
793 | Node::ImplItem(&hir::ImplItem {
795 kind: hir::ImplItemKind::Method(ref sig, _),
798 | Node::TraitItem(&hir::TraitItem {
800 kind: hir::TraitItemKind::Method(ref sig, _),
803 self.tcx.sess.source_map().def_span(span),
807 .map(|arg| match arg.clone().kind {
808 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
810 vec![("_".to_owned(), "_".to_owned()); tys.len()],
812 _ => ArgKind::empty(),
814 .collect::<Vec<ArgKind>>(),
816 Node::Ctor(ref variant_data) => {
817 let span = variant_data
819 .map(|hir_id| self.tcx.hir().span(hir_id))
820 .unwrap_or(DUMMY_SP);
821 let span = self.tcx.sess.source_map().def_span(span);
823 (span, vec![ArgKind::empty(); variant_data.fields().len()])
825 _ => panic!("non-FnLike node found: {:?}", node),
829 /// Reports an error when the number of arguments needed by a
830 /// trait match doesn't match the number that the expression
832 pub fn report_arg_count_mismatch(
835 found_span: Option<Span>,
836 expected_args: Vec<ArgKind>,
837 found_args: Vec<ArgKind>,
839 ) -> DiagnosticBuilder<'tcx> {
840 let kind = if is_closure { "closure" } else { "function" };
842 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
843 let arg_length = arguments.len();
844 let distinct = match &other[..] {
845 &[ArgKind::Tuple(..)] => true,
848 match (arg_length, arguments.get(0)) {
849 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
850 format!("a single {}-tuple as argument", fields.len())
855 if distinct && arg_length > 1 { "distinct " } else { "" },
856 pluralize!(arg_length)
861 let expected_str = args_str(&expected_args, &found_args);
862 let found_str = args_str(&found_args, &expected_args);
864 let mut err = struct_span_err!(
868 "{} is expected to take {}, but it takes {}",
874 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
876 if let Some(found_span) = found_span {
877 err.span_label(found_span, format!("takes {}", found_str));
880 // ^^^^^^^^-- def_span
884 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
888 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
890 // Suggest to take and ignore the arguments with expected_args_length `_`s if
891 // found arguments is empty (assume the user just wants to ignore args in this case).
892 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
893 if found_args.is_empty() && is_closure {
894 let underscores = vec!["_"; expected_args.len()].join(", ");
898 "consider changing the closure to take and ignore the expected argument{}",
899 if expected_args.len() < 2 { "" } else { "s" }
901 format!("|{}|", underscores),
902 Applicability::MachineApplicable,
906 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
907 if fields.len() == expected_args.len() {
910 .map(|(name, _)| name.to_owned())
911 .collect::<Vec<String>>()
915 "change the closure to take multiple arguments instead of a single tuple",
916 format!("|{}|", sugg),
917 Applicability::MachineApplicable,
921 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
922 if fields.len() == found_args.len() && is_closure {
927 .map(|arg| match arg {
928 ArgKind::Arg(name, _) => name.to_owned(),
931 .collect::<Vec<String>>()
933 // add type annotations if available
934 if found_args.iter().any(|arg| match arg {
935 ArgKind::Arg(_, ty) => ty != "_",
942 .map(|(_, ty)| ty.to_owned())
943 .collect::<Vec<String>>()
952 "change the closure to accept a tuple instead of individual arguments",
954 Applicability::MachineApplicable,
963 crate fn report_closure_arg_mismatch(
966 found_span: Option<Span>,
967 expected_ref: ty::PolyTraitRef<'tcx>,
968 found: ty::PolyTraitRef<'tcx>,
969 ) -> DiagnosticBuilder<'tcx> {
970 crate fn build_fn_sig_string<'tcx>(
972 trait_ref: &ty::TraitRef<'tcx>,
974 let inputs = trait_ref.substs.type_at(1);
975 let sig = if let ty::Tuple(inputs) = inputs.kind {
977 inputs.iter().map(|k| k.expect_ty()),
978 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
980 hir::Unsafety::Normal,
981 ::rustc_target::spec::abi::Abi::Rust,
985 ::std::iter::once(inputs),
986 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
988 hir::Unsafety::Normal,
989 ::rustc_target::spec::abi::Abi::Rust,
992 ty::Binder::bind(sig).to_string()
995 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
996 let mut err = struct_span_err!(
1000 "type mismatch in {} arguments",
1001 if argument_is_closure { "closure" } else { "function" }
1004 let found_str = format!(
1005 "expected signature of `{}`",
1006 build_fn_sig_string(self.tcx, found.skip_binder())
1008 err.span_label(span, found_str);
1010 let found_span = found_span.unwrap_or(span);
1011 let expected_str = format!(
1012 "found signature of `{}`",
1013 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1015 err.span_label(found_span, expected_str);
1021 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1022 crate fn suggest_fully_qualified_path(
1024 err: &mut DiagnosticBuilder<'_>,
1029 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1030 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1032 "{}s cannot be accessed directly on a `trait`, they can only be \
1033 accessed through a specific `impl`",
1034 assoc_item.kind.suggestion_descr(),
1036 err.span_suggestion(
1038 "use the fully qualified path to an implementation",
1039 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1040 Applicability::HasPlaceholders,
1046 /// Adds an async-await specific note to the diagnostic when the future does not implement
1047 /// an auto trait because of a captured type.
1049 /// ```ignore (diagnostic)
1050 /// note: future does not implement `Qux` as this value is used across an await
1051 /// --> $DIR/issue-64130-3-other.rs:17:5
1053 /// LL | let x = Foo;
1054 /// | - has type `Foo`
1055 /// LL | baz().await;
1056 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1058 /// | - `x` is later dropped here
1061 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1062 /// is "replaced" with a different message and a more specific error.
1064 /// ```ignore (diagnostic)
1065 /// error: future cannot be sent between threads safely
1066 /// --> $DIR/issue-64130-2-send.rs:21:5
1068 /// LL | fn is_send<T: Send>(t: T) { }
1069 /// | ------- ---- required by this bound in `is_send`
1071 /// LL | is_send(bar());
1072 /// | ^^^^^^^ future returned by `bar` is not send
1074 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1075 /// implemented for `Foo`
1076 /// note: future is not send as this value is used across an await
1077 /// --> $DIR/issue-64130-2-send.rs:15:5
1079 /// LL | let x = Foo;
1080 /// | - has type `Foo`
1081 /// LL | baz().await;
1082 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1084 /// | - `x` is later dropped here
1087 /// Returns `true` if an async-await specific note was added to the diagnostic.
1088 crate fn maybe_note_obligation_cause_for_async_await(
1090 err: &mut DiagnosticBuilder<'_>,
1091 obligation: &PredicateObligation<'tcx>,
1094 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1095 obligation.cause.span={:?}",
1096 obligation.predicate, obligation.cause.span
1098 let source_map = self.tcx.sess.source_map();
1100 // Attempt to detect an async-await error by looking at the obligation causes, looking
1101 // for a generator to be present.
1103 // When a future does not implement a trait because of a captured type in one of the
1104 // generators somewhere in the call stack, then the result is a chain of obligations.
1106 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
1107 // future is passed as an argument to a function C which requires a `Send` type, then the
1108 // chain looks something like this:
1110 // - `BuiltinDerivedObligation` with a generator witness (B)
1111 // - `BuiltinDerivedObligation` with a generator (B)
1112 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1113 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1114 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1115 // - `BuiltinDerivedObligation` with a generator witness (A)
1116 // - `BuiltinDerivedObligation` with a generator (A)
1117 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1118 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1119 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1120 // - `BindingObligation` with `impl_send (Send requirement)
1122 // The first obligation in the chain is the most useful and has the generator that captured
1123 // the type. The last generator has information about where the bound was introduced. At
1124 // least one generator should be present for this diagnostic to be modified.
1125 let (mut trait_ref, mut target_ty) = match obligation.predicate {
1126 ty::Predicate::Trait(p) => {
1127 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty()))
1131 let mut generator = None;
1132 let mut last_generator = None;
1133 let mut next_code = Some(&obligation.cause.code);
1134 while let Some(code) = next_code {
1135 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1137 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1138 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1139 let ty = derived_obligation.parent_trait_ref.self_ty();
1141 "maybe_note_obligation_cause_for_async_await: \
1142 parent_trait_ref={:?} self_ty.kind={:?}",
1143 derived_obligation.parent_trait_ref, ty.kind
1147 ty::Generator(did, ..) => {
1148 generator = generator.or(Some(did));
1149 last_generator = Some(did);
1151 ty::GeneratorWitness(..) => {}
1152 _ if generator.is_none() => {
1153 trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
1154 target_ty = Some(ty);
1159 next_code = Some(derived_obligation.parent_code.as_ref());
1165 // Only continue if a generator was found.
1167 "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
1169 generator, trait_ref, target_ty
1171 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1172 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1173 (generator_did, trait_ref, target_ty)
1178 let span = self.tcx.def_span(generator_did);
1180 // Do not ICE on closure typeck (#66868).
1181 if self.tcx.hir().as_local_hir_id(generator_did).is_none() {
1185 // Get the tables from the infcx if the generator is the function we are
1186 // currently type-checking; otherwise, get them by performing a query.
1187 // This is needed to avoid cycles.
1188 let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
1189 let generator_did_root = self.tcx.closure_base_def_id(generator_did);
1191 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1192 generator_did_root={:?} in_progress_tables.local_id_root={:?} span={:?}",
1195 in_progress_tables.as_ref().map(|t| t.local_id_root),
1199 let tables: &TypeckTables<'tcx> = match &in_progress_tables {
1200 Some(t) if t.local_id_root == Some(generator_did_root) => t,
1202 query_tables = self.tcx.typeck_tables_of(generator_did);
1207 // Look for a type inside the generator interior that matches the target type to get
1209 let target_ty_erased = self.tcx.erase_regions(&target_ty);
1210 let target_span = tables
1211 .generator_interior_types
1213 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| {
1214 // Careful: the regions for types that appear in the
1215 // generator interior are not generally known, so we
1216 // want to erase them when comparing (and anyway,
1217 // `Send` and other bounds are generally unaffected by
1218 // the choice of region). When erasing regions, we
1219 // also have to erase late-bound regions. This is
1220 // because the types that appear in the generator
1221 // interior generally contain "bound regions" to
1222 // represent regions that are part of the suspended
1223 // generator frame. Bound regions are preserved by
1224 // `erase_regions` and so we must also call
1225 // `erase_late_bound_regions`.
1226 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(*ty));
1227 let ty_erased = self.tcx.erase_regions(&ty_erased);
1228 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1230 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1231 target_ty_erased={:?} eq={:?}",
1232 ty_erased, target_ty_erased, eq
1236 .map(|ty::GeneratorInteriorTypeCause { span, scope_span, expr, .. }| {
1237 (span, source_map.span_to_snippet(*span), scope_span, expr)
1241 "maybe_note_obligation_cause_for_async_await: target_ty={:?} \
1242 generator_interior_types={:?} target_span={:?}",
1243 target_ty, tables.generator_interior_types, target_span
1245 if let Some((target_span, Ok(snippet), scope_span, expr)) = target_span {
1246 self.note_obligation_cause_for_async_await(
1266 /// Unconditionally adds the diagnostic note described in
1267 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1268 crate fn note_obligation_cause_for_async_await(
1270 err: &mut DiagnosticBuilder<'_>,
1272 scope_span: &Option<Span>,
1273 expr: Option<hir::HirId>,
1275 first_generator: DefId,
1276 last_generator: Option<DefId>,
1277 trait_ref: ty::TraitRef<'_>,
1278 target_ty: Ty<'tcx>,
1279 tables: &ty::TypeckTables<'_>,
1280 obligation: &PredicateObligation<'tcx>,
1281 next_code: Option<&ObligationCauseCode<'tcx>>,
1283 let source_map = self.tcx.sess.source_map();
1285 let is_async_fn = self
1287 .parent(first_generator)
1288 .map(|parent_did| self.tcx.asyncness(parent_did))
1289 .map(|parent_asyncness| parent_asyncness == hir::IsAsync::Async)
1291 let is_async_move = self
1294 .as_local_hir_id(first_generator)
1295 .and_then(|hir_id| self.tcx.hir().maybe_body_owned_by(hir_id))
1296 .map(|body_id| self.tcx.hir().body(body_id))
1297 .and_then(|body| body.generator_kind())
1298 .map(|generator_kind| match generator_kind {
1299 hir::GeneratorKind::Async(..) => true,
1303 let await_or_yield = if is_async_fn || is_async_move { "await" } else { "yield" };
1305 // Special case the primary error message when send or sync is the trait that was
1307 let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
1308 let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
1309 let hir = self.tcx.hir();
1310 let trait_explanation = if is_send || is_sync {
1311 let (trait_name, trait_verb) =
1312 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1315 err.set_primary_message(format!(
1316 "future cannot be {} between threads safely",
1320 let original_span = err.span.primary_span().unwrap();
1321 let mut span = MultiSpan::from_span(original_span);
1323 let message = if let Some(name) = last_generator
1324 .and_then(|generator_did| self.tcx.parent(generator_did))
1325 .and_then(|parent_did| hir.as_local_hir_id(parent_did))
1326 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1328 format!("future returned by `{}` is not {}", name, trait_name)
1330 format!("future is not {}", trait_name)
1333 span.push_span_label(original_span, message);
1336 format!("is not {}", trait_name)
1338 format!("does not implement `{}`", trait_ref.print_only_trait_path())
1341 // Look at the last interior type to get a span for the `.await`.
1342 let await_span = tables.generator_interior_types.iter().map(|t| t.span).last().unwrap();
1343 let mut span = MultiSpan::from_span(await_span);
1344 span.push_span_label(
1346 format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
1349 span.push_span_label(target_span, format!("has type `{}`", target_ty));
1351 // If available, use the scope span to annotate the drop location.
1352 if let Some(scope_span) = scope_span {
1353 span.push_span_label(
1354 source_map.end_point(*scope_span),
1355 format!("`{}` is later dropped here", snippet),
1362 "future {} as this value is used across an {}",
1363 trait_explanation, await_or_yield,
1367 if let Some(expr_id) = expr {
1368 let expr = hir.expect_expr(expr_id);
1369 let is_ref = tables.expr_adjustments(expr).iter().any(|adj| adj.is_region_borrow());
1370 let parent = hir.get_parent_node(expr_id);
1371 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1372 let method_span = hir.span(parent);
1373 if tables.is_method_call(e) && is_ref {
1376 "consider moving this method call into a `let` \
1377 binding to create a shorter lived borrow",
1383 // Add a note for the item obligation that remains - normally a note pointing to the
1384 // bound that introduced the obligation (e.g. `T: Send`).
1385 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1386 self.note_obligation_cause_code(
1388 &obligation.predicate,
1394 crate fn note_obligation_cause_code<T>(
1396 err: &mut DiagnosticBuilder<'_>,
1398 cause_code: &ObligationCauseCode<'tcx>,
1399 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1405 ObligationCauseCode::ExprAssignable
1406 | ObligationCauseCode::MatchExpressionArm { .. }
1407 | ObligationCauseCode::Pattern { .. }
1408 | ObligationCauseCode::IfExpression { .. }
1409 | ObligationCauseCode::IfExpressionWithNoElse
1410 | ObligationCauseCode::MainFunctionType
1411 | ObligationCauseCode::StartFunctionType
1412 | ObligationCauseCode::IntrinsicType
1413 | ObligationCauseCode::MethodReceiver
1414 | ObligationCauseCode::ReturnNoExpression
1415 | ObligationCauseCode::MiscObligation => {}
1416 ObligationCauseCode::SliceOrArrayElem => {
1417 err.note("slice and array elements must have `Sized` type");
1419 ObligationCauseCode::TupleElem => {
1420 err.note("only the last element of a tuple may have a dynamically sized type");
1422 ObligationCauseCode::ProjectionWf(data) => {
1423 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1425 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1427 "required so that reference `{}` does not outlive its referent",
1431 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1433 "required so that the lifetime bound of `{}` for `{}` is satisfied",
1437 ObligationCauseCode::ItemObligation(item_def_id) => {
1438 let item_name = tcx.def_path_str(item_def_id);
1439 let msg = format!("required by `{}`", item_name);
1441 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1442 let sp = tcx.sess.source_map().def_span(sp);
1443 err.span_label(sp, &msg);
1448 ObligationCauseCode::BindingObligation(item_def_id, span) => {
1449 let item_name = tcx.def_path_str(item_def_id);
1450 let msg = format!("required by this bound in `{}`", item_name);
1451 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1452 err.span_label(ident.span, "");
1454 if span != DUMMY_SP {
1455 err.span_label(span, &msg);
1460 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1462 "required for the cast to the object type `{}`",
1463 self.ty_to_string(object_ty)
1466 ObligationCauseCode::Coercion { source: _, target } => {
1467 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1469 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
1471 "the `Copy` trait is required because the repeated element will be copied",
1473 if suggest_const_in_array_repeat_expressions {
1475 "this array initializer can be evaluated at compile-time, for more \
1476 information, see issue \
1477 https://github.com/rust-lang/rust/issues/49147",
1479 if tcx.sess.opts.unstable_features.is_nightly_build() {
1481 "add `#![feature(const_in_array_repeat_expressions)]` to the \
1482 crate attributes to enable",
1487 ObligationCauseCode::VariableType(_) => {
1488 err.note("all local variables must have a statically known size");
1489 if !self.tcx.features().unsized_locals {
1490 err.help("unsized locals are gated as an unstable feature");
1493 ObligationCauseCode::SizedArgumentType => {
1494 err.note("all function arguments must have a statically known size");
1495 if !self.tcx.features().unsized_locals {
1496 err.help("unsized locals are gated as an unstable feature");
1499 ObligationCauseCode::SizedReturnType => {
1500 err.note("the return type of a function must have a statically known size");
1502 ObligationCauseCode::SizedYieldType => {
1503 err.note("the yield type of a generator must have a statically known size");
1505 ObligationCauseCode::AssignmentLhsSized => {
1506 err.note("the left-hand-side of an assignment must have a statically known size");
1508 ObligationCauseCode::TupleInitializerSized => {
1509 err.note("tuples must have a statically known size to be initialized");
1511 ObligationCauseCode::StructInitializerSized => {
1512 err.note("structs must have a statically known size to be initialized");
1514 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => match *item {
1515 AdtKind::Struct => {
1518 "the last field of a packed struct may only have a \
1519 dynamically sized type if it does not need drop to be run",
1523 "only the last field of a struct may have a dynamically sized type",
1528 err.note("no field of a union may have a dynamically sized type");
1531 err.note("no field of an enum variant may have a dynamically sized type");
1534 ObligationCauseCode::ConstSized => {
1535 err.note("constant expressions must have a statically known size");
1537 ObligationCauseCode::ConstPatternStructural => {
1538 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
1540 ObligationCauseCode::SharedStatic => {
1541 err.note("shared static variables must have a type that implements `Sync`");
1543 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1544 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1545 let ty = parent_trait_ref.skip_binder().self_ty();
1546 err.note(&format!("required because it appears within the type `{}`", ty));
1547 obligated_types.push(ty);
1549 let parent_predicate = parent_trait_ref.to_predicate();
1550 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1551 self.note_obligation_cause_code(
1559 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1560 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1562 "required because of the requirements on the impl of `{}` for `{}`",
1563 parent_trait_ref.print_only_trait_path(),
1564 parent_trait_ref.skip_binder().self_ty()
1566 let parent_predicate = parent_trait_ref.to_predicate();
1567 self.note_obligation_cause_code(
1574 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1576 "the requirement `{}` appears on the impl method \
1577 but not on the corresponding trait method",
1581 ObligationCauseCode::CompareImplTypeObligation { .. } => {
1583 "the requirement `{}` appears on the associated impl type \
1584 but not on the corresponding associated trait type",
1588 ObligationCauseCode::ReturnType
1589 | ObligationCauseCode::ReturnValue(_)
1590 | ObligationCauseCode::BlockTailExpression(_) => (),
1591 ObligationCauseCode::TrivialBound => {
1592 err.help("see issue #48214");
1593 if tcx.sess.opts.unstable_features.is_nightly_build() {
1594 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
1597 ObligationCauseCode::AssocTypeBound(ref data) => {
1598 err.span_label(data.original, "associated type defined here");
1599 if let Some(sp) = data.impl_span {
1600 err.span_label(sp, "in this `impl` item");
1602 for sp in &data.bounds {
1603 err.span_label(*sp, "restricted in this bound");
1609 crate fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1610 let current_limit = self.tcx.sess.recursion_limit.get();
1611 let suggested_limit = current_limit * 2;
1613 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1619 /// Suggest restricting a type param with a new bound.
1620 pub fn suggest_constraining_type_param(
1621 generics: &hir::Generics<'_>,
1622 err: &mut DiagnosticBuilder<'_>,
1625 source_map: &SourceMap,
1628 let restrict_msg = "consider further restricting this bound";
1629 if let Some(param) =
1630 generics.params.iter().filter(|p| p.name.ident().as_str() == param_name).next()
1632 if param_name.starts_with("impl ") {
1633 // `impl Trait` in argument:
1634 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
1635 err.span_suggestion(
1638 // `impl CurrentTrait + MissingTrait`
1639 format!("{} + {}", param_name, constraint),
1640 Applicability::MachineApplicable,
1642 } else if generics.where_clause.predicates.is_empty() && param.bounds.is_empty() {
1643 // If there are no bounds whatsoever, suggest adding a constraint
1644 // to the type parameter:
1645 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
1646 err.span_suggestion(
1648 "consider restricting this bound",
1649 format!("{}: {}", param_name, constraint),
1650 Applicability::MachineApplicable,
1652 } else if !generics.where_clause.predicates.is_empty() {
1653 // There is a `where` clause, so suggest expanding it:
1654 // `fn foo<T>(t: T) where T: Debug {}` →
1655 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
1656 err.span_suggestion(
1657 generics.where_clause.span().unwrap().shrink_to_hi(),
1658 &format!("consider further restricting type parameter `{}`", param_name),
1659 format!(", {}: {}", param_name, constraint),
1660 Applicability::MachineApplicable,
1663 // If there is no `where` clause lean towards constraining to the
1665 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
1666 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
1667 let sp = param.span.with_hi(span.hi());
1668 let span = source_map.span_through_char(sp, ':');
1669 if sp != param.span && sp != span {
1670 // Only suggest if we have high certainty that the span
1671 // covers the colon in `foo<T: Trait>`.
1672 err.span_suggestion(
1675 format!("{}: {} + ", param_name, constraint),
1676 Applicability::MachineApplicable,
1681 &format!("consider adding a `where {}: {}` bound", param_name, constraint),
1690 /// Collect all the returned expressions within the input expression.
1691 /// Used to point at the return spans when we want to suggest some change to them.
1692 struct ReturnsVisitor<'v>(Vec<&'v hir::Expr<'v>>);
1694 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
1695 type Map = rustc::hir::map::Map<'v>;
1697 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<'_, Self::Map> {
1698 hir::intravisit::NestedVisitorMap::None
1701 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
1702 if let hir::ExprKind::Ret(Some(ex)) = ex.kind {
1705 hir::intravisit::walk_expr(self, ex);
1708 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
1709 if body.generator_kind().is_none() {
1710 if let hir::ExprKind::Block(block, None) = body.value.kind {
1711 if let Some(expr) = block.expr {
1716 hir::intravisit::walk_body(self, body);