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 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
24 crate fn suggest_restricting_param_bound(
26 mut err: &mut DiagnosticBuilder<'_>,
27 trait_ref: &ty::PolyTraitRef<'_>,
30 let self_ty = trait_ref.self_ty();
31 let (param_ty, projection) = match &self_ty.kind {
32 ty::Param(_) => (true, None),
33 ty::Projection(projection) => (false, Some(projection)),
37 let suggest_restriction =
38 |generics: &hir::Generics<'_>, msg, err: &mut DiagnosticBuilder<'_>| {
39 let span = generics.where_clause.span_for_predicates_or_empty_place();
40 if !span.from_expansion() && span.desugaring_kind().is_none() {
42 generics.where_clause.span_for_predicates_or_empty_place().shrink_to_hi(),
43 &format!("consider further restricting {}", msg),
46 if !generics.where_clause.predicates.is_empty() {
51 trait_ref.to_predicate(),
53 Applicability::MachineApplicable,
58 // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we
59 // don't suggest `T: Sized + ?Sized`.
60 let mut hir_id = body_id;
61 while let Some(node) = self.tcx.hir().find(hir_id) {
63 hir::Node::TraitItem(hir::TraitItem {
65 kind: hir::TraitItemKind::Method(..),
67 }) if param_ty && self_ty == self.tcx.types.self_param => {
68 // Restricting `Self` for a single method.
69 suggest_restriction(&generics, "`Self`", err);
73 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })
74 | hir::Node::TraitItem(hir::TraitItem {
76 kind: hir::TraitItemKind::Method(..),
79 | hir::Node::ImplItem(hir::ImplItem {
81 kind: hir::ImplItemKind::Method(..),
84 | hir::Node::Item(hir::Item {
85 kind: hir::ItemKind::Trait(_, _, generics, _, _),
88 | hir::Node::Item(hir::Item {
89 kind: hir::ItemKind::Impl { generics, .. }, ..
90 }) if projection.is_some() => {
91 // Missing associated type bound.
92 suggest_restriction(&generics, "the associated type", err);
96 hir::Node::Item(hir::Item {
97 kind: hir::ItemKind::Struct(_, generics),
101 | hir::Node::Item(hir::Item {
102 kind: hir::ItemKind::Enum(_, generics), span, ..
104 | hir::Node::Item(hir::Item {
105 kind: hir::ItemKind::Union(_, generics),
109 | hir::Node::Item(hir::Item {
110 kind: hir::ItemKind::Trait(_, _, generics, ..),
114 | hir::Node::Item(hir::Item {
115 kind: hir::ItemKind::Impl { generics, .. },
119 | hir::Node::Item(hir::Item {
120 kind: hir::ItemKind::Fn(_, generics, _),
124 | hir::Node::Item(hir::Item {
125 kind: hir::ItemKind::TyAlias(_, generics),
129 | hir::Node::Item(hir::Item {
130 kind: hir::ItemKind::TraitAlias(generics, _),
134 | hir::Node::Item(hir::Item {
135 kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. }),
139 | hir::Node::TraitItem(hir::TraitItem { generics, span, .. })
140 | hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
143 // Missing generic type parameter bound.
144 let param_name = self_ty.to_string();
145 let constraint = trait_ref.print_only_trait_path().to_string();
146 if suggest_constraining_type_param(
151 self.tcx.sess.source_map(),
158 hir::Node::Crate => return,
163 hir_id = self.tcx.hir().get_parent_item(hir_id);
167 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
168 /// suggestion to borrow the initializer in order to use have a slice instead.
169 crate fn suggest_borrow_on_unsized_slice(
171 code: &ObligationCauseCode<'tcx>,
172 err: &mut DiagnosticBuilder<'tcx>,
174 if let &ObligationCauseCode::VariableType(hir_id) = code {
175 let parent_node = self.tcx.hir().get_parent_node(hir_id);
176 if let Some(Node::Local(ref local)) = self.tcx.hir().find(parent_node) {
177 if let Some(ref expr) = local.init {
178 if let hir::ExprKind::Index(_, _) = expr.kind {
179 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
182 "consider borrowing here",
183 format!("&{}", snippet),
184 Applicability::MachineApplicable,
193 /// Given a closure's `DefId`, return the given name of the closure.
195 /// This doesn't account for reassignments, but it's only used for suggestions.
196 crate fn get_closure_name(
199 err: &mut DiagnosticBuilder<'_>,
201 ) -> Option<String> {
203 |err: &mut DiagnosticBuilder<'_>, kind: &hir::PatKind<'_>| -> Option<String> {
204 // Get the local name of this closure. This can be inaccurate because
205 // of the possibility of reassignment, but this should be good enough.
207 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
208 Some(format!("{}", name))
217 let hir = self.tcx.hir();
218 let hir_id = hir.as_local_hir_id(def_id)?;
219 let parent_node = hir.get_parent_node(hir_id);
220 match hir.find(parent_node) {
221 Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
222 get_name(err, &local.pat.kind)
224 // Different to previous arm because one is `&hir::Local` and the other
225 // is `P<hir::Local>`.
226 Some(hir::Node::Local(local)) => get_name(err, &local.pat.kind),
231 /// We tried to apply the bound to an `fn` or closure. Check whether calling it would
232 /// evaluate to a type that *would* satisfy the trait binding. If it would, suggest calling
233 /// it: `bar(foo)` → `bar(foo())`. This case is *very* likely to be hit if `foo` is `async`.
234 crate fn suggest_fn_call(
236 obligation: &PredicateObligation<'tcx>,
237 err: &mut DiagnosticBuilder<'_>,
238 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
241 let self_ty = trait_ref.self_ty();
242 let (def_id, output_ty, callable) = match self_ty.kind {
243 ty::Closure(def_id, substs) => {
244 (def_id, self.closure_sig(def_id, substs).output(), "closure")
246 ty::FnDef(def_id, _) => (def_id, self_ty.fn_sig(self.tcx).output(), "function"),
249 let msg = format!("use parentheses to call the {}", callable);
251 let obligation = self.mk_obligation_for_def_id(
253 output_ty.skip_binder(),
254 obligation.cause.clone(),
255 obligation.param_env,
258 match self.evaluate_obligation(&obligation) {
259 Ok(EvaluationResult::EvaluatedToOk)
260 | Ok(EvaluationResult::EvaluatedToOkModuloRegions)
261 | Ok(EvaluationResult::EvaluatedToAmbig) => {}
264 let hir = self.tcx.hir();
265 // Get the name of the callable and the arguments to be used in the suggestion.
266 let snippet = match hir.get_if_local(def_id) {
267 Some(hir::Node::Expr(hir::Expr {
268 kind: hir::ExprKind::Closure(_, decl, _, span, ..),
271 err.span_label(*span, "consider calling this closure");
272 let name = match self.get_closure_name(def_id, err, &msg) {
276 let args = decl.inputs.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
277 format!("{}({})", name, args)
279 Some(hir::Node::Item(hir::Item {
281 kind: hir::ItemKind::Fn(.., body_id),
284 err.span_label(ident.span, "consider calling this function");
285 let body = hir.body(*body_id);
289 .map(|arg| match &arg.pat.kind {
290 hir::PatKind::Binding(_, _, ident, None)
291 // FIXME: provide a better suggestion when encountering `SelfLower`, it
292 // should suggest a method call.
293 if ident.name != kw::SelfLower => ident.to_string(),
294 _ => "_".to_string(),
298 format!("{}({})", ident, args)
303 // When the obligation error has been ensured to have been caused by
304 // an argument, the `obligation.cause.span` points at the expression
305 // of the argument, so we can provide a suggestion. This is signaled
306 // by `points_at_arg`. Otherwise, we give a more general note.
308 obligation.cause.span,
311 Applicability::HasPlaceholders,
314 err.help(&format!("{}: `{}`", msg, snippet));
318 crate fn suggest_add_reference_to_arg(
320 obligation: &PredicateObligation<'tcx>,
321 err: &mut DiagnosticBuilder<'tcx>,
322 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
324 has_custom_message: bool,
330 let span = obligation.cause.span;
331 let param_env = obligation.param_env;
332 let trait_ref = trait_ref.skip_binder();
334 if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
335 // Try to apply the original trait binding obligation by borrowing.
336 let self_ty = trait_ref.self_ty();
337 let found = self_ty.to_string();
338 let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
339 let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
340 let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
342 Obligation::new(ObligationCause::dummy(), param_env, new_trait_ref.to_predicate());
343 if self.predicate_must_hold_modulo_regions(&new_obligation) {
344 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
345 // We have a very specific type of error, where just borrowing this argument
346 // might solve the problem. In cases like this, the important part is the
347 // original type obligation, not the last one that failed, which is arbitrary.
348 // Because of this, we modify the error to refer to the original obligation and
349 // return early in the caller.
351 "the trait bound `{}: {}` is not satisfied",
353 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
355 if has_custom_message {
358 err.message = vec![(msg, Style::NoStyle)];
360 if snippet.starts_with('&') {
361 // This is already a literal borrow and the obligation is failing
362 // somewhere else in the obligation chain. Do not suggest non-sense.
368 "expected an implementor of trait `{}`",
369 obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
374 "consider borrowing here",
375 format!("&{}", snippet),
376 Applicability::MaybeIncorrect,
385 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
386 /// suggest removing these references until we reach a type that implements the trait.
387 crate fn suggest_remove_reference(
389 obligation: &PredicateObligation<'tcx>,
390 err: &mut DiagnosticBuilder<'tcx>,
391 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
393 let trait_ref = trait_ref.skip_binder();
394 let span = obligation.cause.span;
396 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
398 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
400 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
402 // Do not suggest removal of borrow from type arguments.
406 let mut trait_type = trait_ref.self_ty();
408 for refs_remaining in 0..refs_number {
409 if let ty::Ref(_, t_type, _) = trait_type.kind {
412 let new_obligation = self.mk_obligation_for_def_id(
415 ObligationCause::dummy(),
416 obligation.param_env,
419 if self.predicate_may_hold(&new_obligation) {
424 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
426 let remove_refs = refs_remaining + 1;
428 format!("consider removing {} leading `&`-references", remove_refs);
430 err.span_suggestion_short(
434 Applicability::MachineApplicable,
445 /// Check if the trait bound is implemented for a different mutability and note it in the
447 crate fn suggest_change_mut(
449 obligation: &PredicateObligation<'tcx>,
450 err: &mut DiagnosticBuilder<'tcx>,
451 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
454 let span = obligation.cause.span;
455 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
457 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
459 snippet.chars().filter(|c| !c.is_whitespace()).skip(refs_number).next()
461 // Do not suggest removal of borrow from type arguments.
464 let trait_ref = self.resolve_vars_if_possible(trait_ref);
465 if trait_ref.has_infer_types() {
466 // Do not ICE while trying to find if a reborrow would succeed on a trait with
467 // unresolved bindings.
471 if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
472 let trait_type = match mutability {
473 hir::Mutability::Mut => self.tcx.mk_imm_ref(region, t_type),
474 hir::Mutability::Not => self.tcx.mk_mut_ref(region, t_type),
477 let new_obligation = self.mk_obligation_for_def_id(
478 trait_ref.skip_binder().def_id,
480 ObligationCause::dummy(),
481 obligation.param_env,
484 if self.evaluate_obligation_no_overflow(&new_obligation).must_apply_modulo_regions()
490 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
491 if points_at_arg && mutability == hir::Mutability::Not && refs_number > 0 {
494 "consider changing this borrow's mutability",
496 Applicability::MachineApplicable,
500 "`{}` is implemented for `{:?}`, but not for `{:?}`",
501 trait_ref.print_only_trait_path(),
503 trait_ref.skip_binder().self_ty(),
511 crate fn suggest_semicolon_removal(
513 obligation: &PredicateObligation<'tcx>,
514 err: &mut DiagnosticBuilder<'tcx>,
516 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
518 let hir = self.tcx.hir();
519 let parent_node = hir.get_parent_node(obligation.cause.body_id);
520 let node = hir.find(parent_node);
521 if let Some(hir::Node::Item(hir::Item {
522 kind: hir::ItemKind::Fn(sig, _, body_id), ..
525 let body = hir.body(*body_id);
526 if let hir::ExprKind::Block(blk, _) = &body.value.kind {
527 if sig.decl.output.span().overlaps(span)
528 && blk.expr.is_none()
529 && "()" == &trait_ref.self_ty().to_string()
531 // FIXME(estebank): When encountering a method with a trait
532 // bound not satisfied in the return type with a body that has
533 // no return, suggest removal of semicolon on last statement.
534 // Once that is added, close #54771.
535 if let Some(ref stmt) = blk.stmts.last() {
536 let sp = self.tcx.sess.source_map().end_point(stmt.span);
537 err.span_label(sp, "consider removing this semicolon");
544 /// If all conditions are met to identify a returned `dyn Trait`, suggest using `impl Trait` if
545 /// applicable and signal that the error has been expanded appropriately and needs to be
547 crate fn suggest_impl_trait(
549 err: &mut DiagnosticBuilder<'tcx>,
551 obligation: &PredicateObligation<'tcx>,
552 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
554 match obligation.cause.code.peel_derives() {
555 // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`.
556 ObligationCauseCode::SizedReturnType => {}
560 let hir = self.tcx.hir();
561 let parent_node = hir.get_parent_node(obligation.cause.body_id);
562 let node = hir.find(parent_node);
563 let (sig, body_id) = if let Some(hir::Node::Item(hir::Item {
564 kind: hir::ItemKind::Fn(sig, _, body_id),
572 let body = hir.body(*body_id);
573 let trait_ref = self.resolve_vars_if_possible(trait_ref);
574 let ty = trait_ref.skip_binder().self_ty();
575 let is_object_safe = match ty.kind {
576 ty::Dynamic(predicates, _) => {
577 // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
580 .map_or(true, |def_id| object_safety_violations(self.tcx, def_id).is_empty())
582 // We only want to suggest `impl Trait` to `dyn Trait`s.
583 // For example, `fn foo() -> str` needs to be filtered out.
587 let ret_ty = if let hir::FunctionRetTy::Return(ret_ty) = sig.decl.output {
593 // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for
594 // cases like `fn foo() -> (dyn Trait, i32) {}`.
595 // Recursively look for `TraitObject` types and if there's only one, use that span to
596 // suggest `impl Trait`.
598 // Visit to make sure there's a single `return` type to suggest `impl Trait`,
599 // otherwise suggest using `Box<dyn Trait>` or an enum.
600 let mut visitor = ReturnsVisitor(vec![]);
601 visitor.visit_body(&body);
603 let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
605 let mut ret_types = visitor.0.iter().filter_map(|expr| tables.node_type_opt(expr.hir_id));
606 let (last_ty, all_returns_have_same_type) =
607 ret_types.clone().fold((None, true), |(last_ty, mut same), returned_ty| {
608 same &= last_ty.map_or(true, |ty| ty == returned_ty);
609 (Some(returned_ty), same)
611 let all_returns_conform_to_trait =
612 if let Some(ty_ret_ty) = tables.node_type_opt(ret_ty.hir_id) {
613 match ty_ret_ty.kind {
614 ty::Dynamic(predicates, _) => {
615 let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id);
616 let param_env = ty::ParamEnv::empty();
617 ret_types.all(|returned_ty| {
618 predicates.iter().all(|predicate| {
619 let pred = predicate.with_self_ty(self.tcx, returned_ty);
620 let obl = Obligation::new(cause.clone(), param_env, pred);
621 self.predicate_may_hold(&obl)
631 let (snippet, last_ty) =
632 if let (true, hir::TyKind::TraitObject(..), Ok(snippet), true, Some(last_ty)) = (
633 // Verify that we're dealing with a return `dyn Trait`
634 ret_ty.span.overlaps(span),
636 self.tcx.sess.source_map().span_to_snippet(ret_ty.span),
637 // If any of the return types does not conform to the trait, then we can't
638 // suggest `impl Trait` nor trait objects, it is a type mismatch error.
639 all_returns_conform_to_trait,
646 err.code(error_code!(E0746));
647 err.set_primary_message("return type cannot have an unboxed trait object");
648 err.children.clear();
649 let impl_trait_msg = "for information on `impl Trait`, see \
650 <https://doc.rust-lang.org/book/ch10-02-traits.html\
651 #returning-types-that-implement-traits>";
652 let trait_obj_msg = "for information on trait objects, see \
653 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
654 #using-trait-objects-that-allow-for-values-of-different-types>";
655 let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn");
656 let trait_obj = if has_dyn { &snippet[4..] } else { &snippet[..] };
657 if all_returns_have_same_type {
658 // Suggest `-> impl Trait`.
662 "return `impl {1}` instead, as all return paths are of type `{}`, \
663 which implements `{1}`",
666 format!("impl {}", trait_obj),
667 Applicability::MachineApplicable,
669 err.note(impl_trait_msg);
672 // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
673 // Get all the return values and collect their span and suggestion.
674 let mut suggestions = visitor
682 self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap()
686 .collect::<Vec<_>>();
687 // Add the suggestion for the return type.
690 format!("Box<{}{}>", if has_dyn { "" } else { "dyn " }, snippet),
692 err.multipart_suggestion(
693 "return a boxed trait object instead",
695 Applicability::MaybeIncorrect,
698 // This is currently not possible to trigger because E0038 takes precedence, but
699 // leave it in for completeness in case anything changes in an earlier stage.
701 "if trait `{}` was object safe, you could return a trait object",
705 err.note(trait_obj_msg);
707 "if all the returned values were of the same type you could use \
708 `impl {}` as the return type",
711 err.note(impl_trait_msg);
712 err.note("you can create a new `enum` with a variant for each returned type");
717 crate fn point_at_returns_when_relevant(
719 err: &mut DiagnosticBuilder<'tcx>,
720 obligation: &PredicateObligation<'tcx>,
722 match obligation.cause.code.peel_derives() {
723 ObligationCauseCode::SizedReturnType => {}
727 let hir = self.tcx.hir();
728 let parent_node = hir.get_parent_node(obligation.cause.body_id);
729 let node = hir.find(parent_node);
730 if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) =
733 let body = hir.body(*body_id);
734 // Point at all the `return`s in the function as they have failed trait bounds.
735 let mut visitor = ReturnsVisitor(vec![]);
736 visitor.visit_body(&body);
737 let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap();
738 for expr in &visitor.0 {
739 if let Some(returned_ty) = tables.node_type_opt(expr.hir_id) {
740 let ty = self.resolve_vars_if_possible(&returned_ty);
741 err.span_label(expr.span, &format!("this returned value is of type `{}`", ty));
747 /// Given some node representing a fn-like thing in the HIR map,
748 /// returns a span and `ArgKind` information that describes the
749 /// arguments it expects. This can be supplied to
750 /// `report_arg_count_mismatch`.
751 pub fn get_fn_like_arguments(&self, node: Node<'_>) -> (Span, Vec<ArgKind>) {
753 Node::Expr(&hir::Expr {
754 kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
757 self.tcx.sess.source_map().def_span(span),
764 if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
775 .span_to_snippet(pat.span)
777 (snippet, "_".to_owned())
779 .collect::<Vec<_>>(),
783 self.tcx.sess.source_map().span_to_snippet(arg.pat.span).unwrap();
784 ArgKind::Arg(name, "_".to_owned())
787 .collect::<Vec<ArgKind>>(),
789 Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
790 | Node::ImplItem(&hir::ImplItem {
792 kind: hir::ImplItemKind::Method(ref sig, _),
795 | Node::TraitItem(&hir::TraitItem {
797 kind: hir::TraitItemKind::Method(ref sig, _),
800 self.tcx.sess.source_map().def_span(span),
804 .map(|arg| match arg.clone().kind {
805 hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
807 vec![("_".to_owned(), "_".to_owned()); tys.len()],
809 _ => ArgKind::empty(),
811 .collect::<Vec<ArgKind>>(),
813 Node::Ctor(ref variant_data) => {
814 let span = variant_data
816 .map(|hir_id| self.tcx.hir().span(hir_id))
817 .unwrap_or(DUMMY_SP);
818 let span = self.tcx.sess.source_map().def_span(span);
820 (span, vec![ArgKind::empty(); variant_data.fields().len()])
822 _ => panic!("non-FnLike node found: {:?}", node),
826 /// Reports an error when the number of arguments needed by a
827 /// trait match doesn't match the number that the expression
829 pub fn report_arg_count_mismatch(
832 found_span: Option<Span>,
833 expected_args: Vec<ArgKind>,
834 found_args: Vec<ArgKind>,
836 ) -> DiagnosticBuilder<'tcx> {
837 let kind = if is_closure { "closure" } else { "function" };
839 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
840 let arg_length = arguments.len();
841 let distinct = match &other[..] {
842 &[ArgKind::Tuple(..)] => true,
845 match (arg_length, arguments.get(0)) {
846 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
847 format!("a single {}-tuple as argument", fields.len())
852 if distinct && arg_length > 1 { "distinct " } else { "" },
853 pluralize!(arg_length)
858 let expected_str = args_str(&expected_args, &found_args);
859 let found_str = args_str(&found_args, &expected_args);
861 let mut err = struct_span_err!(
865 "{} is expected to take {}, but it takes {}",
871 err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
873 if let Some(found_span) = found_span {
874 err.span_label(found_span, format!("takes {}", found_str));
877 // ^^^^^^^^-- def_span
881 let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
885 if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };
887 // Suggest to take and ignore the arguments with expected_args_length `_`s if
888 // found arguments is empty (assume the user just wants to ignore args in this case).
889 // For example, if `expected_args_length` is 2, suggest `|_, _|`.
890 if found_args.is_empty() && is_closure {
891 let underscores = vec!["_"; expected_args.len()].join(", ");
895 "consider changing the closure to take and ignore the expected argument{}",
896 if expected_args.len() < 2 { "" } else { "s" }
898 format!("|{}|", underscores),
899 Applicability::MachineApplicable,
903 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
904 if fields.len() == expected_args.len() {
907 .map(|(name, _)| name.to_owned())
908 .collect::<Vec<String>>()
912 "change the closure to take multiple arguments instead of a single tuple",
913 format!("|{}|", sugg),
914 Applicability::MachineApplicable,
918 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
919 if fields.len() == found_args.len() && is_closure {
924 .map(|arg| match arg {
925 ArgKind::Arg(name, _) => name.to_owned(),
928 .collect::<Vec<String>>()
930 // add type annotations if available
931 if found_args.iter().any(|arg| match arg {
932 ArgKind::Arg(_, ty) => ty != "_",
939 .map(|(_, ty)| ty.to_owned())
940 .collect::<Vec<String>>()
949 "change the closure to accept a tuple instead of individual arguments",
951 Applicability::MachineApplicable,
960 crate fn report_closure_arg_mismatch(
963 found_span: Option<Span>,
964 expected_ref: ty::PolyTraitRef<'tcx>,
965 found: ty::PolyTraitRef<'tcx>,
966 ) -> DiagnosticBuilder<'tcx> {
967 crate fn build_fn_sig_string<'tcx>(
969 trait_ref: &ty::TraitRef<'tcx>,
971 let inputs = trait_ref.substs.type_at(1);
972 let sig = if let ty::Tuple(inputs) = inputs.kind {
974 inputs.iter().map(|k| k.expect_ty()),
975 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
977 hir::Unsafety::Normal,
978 ::rustc_target::spec::abi::Abi::Rust,
982 ::std::iter::once(inputs),
983 tcx.mk_ty_infer(ty::TyVar(ty::TyVid { index: 0 })),
985 hir::Unsafety::Normal,
986 ::rustc_target::spec::abi::Abi::Rust,
989 ty::Binder::bind(sig).to_string()
992 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
993 let mut err = struct_span_err!(
997 "type mismatch in {} arguments",
998 if argument_is_closure { "closure" } else { "function" }
1001 let found_str = format!(
1002 "expected signature of `{}`",
1003 build_fn_sig_string(self.tcx, found.skip_binder())
1005 err.span_label(span, found_str);
1007 let found_span = found_span.unwrap_or(span);
1008 let expected_str = format!(
1009 "found signature of `{}`",
1010 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1012 err.span_label(found_span, expected_str);
1018 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1019 crate fn suggest_fully_qualified_path(
1021 err: &mut DiagnosticBuilder<'_>,
1026 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
1027 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
1029 "{}s cannot be accessed directly on a `trait`, they can only be \
1030 accessed through a specific `impl`",
1031 assoc_item.kind.suggestion_descr(),
1033 err.span_suggestion(
1035 "use the fully qualified path to an implementation",
1036 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.ident),
1037 Applicability::HasPlaceholders,
1043 /// Adds an async-await specific note to the diagnostic when the future does not implement
1044 /// an auto trait because of a captured type.
1046 /// ```ignore (diagnostic)
1047 /// note: future does not implement `Qux` as this value is used across an await
1048 /// --> $DIR/issue-64130-3-other.rs:17:5
1050 /// LL | let x = Foo;
1051 /// | - has type `Foo`
1052 /// LL | baz().await;
1053 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1055 /// | - `x` is later dropped here
1058 /// When the diagnostic does not implement `Send` or `Sync` specifically, then the diagnostic
1059 /// is "replaced" with a different message and a more specific error.
1061 /// ```ignore (diagnostic)
1062 /// error: future cannot be sent between threads safely
1063 /// --> $DIR/issue-64130-2-send.rs:21:5
1065 /// LL | fn is_send<T: Send>(t: T) { }
1066 /// | ------- ---- required by this bound in `is_send`
1068 /// LL | is_send(bar());
1069 /// | ^^^^^^^ future returned by `bar` is not send
1071 /// = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
1072 /// implemented for `Foo`
1073 /// note: future is not send as this value is used across an await
1074 /// --> $DIR/issue-64130-2-send.rs:15:5
1076 /// LL | let x = Foo;
1077 /// | - has type `Foo`
1078 /// LL | baz().await;
1079 /// | ^^^^^^^^^^^ await occurs here, with `x` maybe used later
1081 /// | - `x` is later dropped here
1084 /// Returns `true` if an async-await specific note was added to the diagnostic.
1085 crate fn maybe_note_obligation_cause_for_async_await(
1087 err: &mut DiagnosticBuilder<'_>,
1088 obligation: &PredicateObligation<'tcx>,
1091 "maybe_note_obligation_cause_for_async_await: obligation.predicate={:?} \
1092 obligation.cause.span={:?}",
1093 obligation.predicate, obligation.cause.span
1095 let source_map = self.tcx.sess.source_map();
1097 // Attempt to detect an async-await error by looking at the obligation causes, looking
1098 // for a generator to be present.
1100 // When a future does not implement a trait because of a captured type in one of the
1101 // generators somewhere in the call stack, then the result is a chain of obligations.
1103 // Given a `async fn` A that calls a `async fn` B which captures a non-send type and that
1104 // future is passed as an argument to a function C which requires a `Send` type, then the
1105 // chain looks something like this:
1107 // - `BuiltinDerivedObligation` with a generator witness (B)
1108 // - `BuiltinDerivedObligation` with a generator (B)
1109 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (B)
1110 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1111 // - `BuiltinDerivedObligation` with `impl std::future::Future` (B)
1112 // - `BuiltinDerivedObligation` with a generator witness (A)
1113 // - `BuiltinDerivedObligation` with a generator (A)
1114 // - `BuiltinDerivedObligation` with `std::future::GenFuture` (A)
1115 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1116 // - `BuiltinDerivedObligation` with `impl std::future::Future` (A)
1117 // - `BindingObligation` with `impl_send (Send requirement)
1119 // The first obligation in the chain is the most useful and has the generator that captured
1120 // the type. The last generator has information about where the bound was introduced. At
1121 // least one generator should be present for this diagnostic to be modified.
1122 let (mut trait_ref, mut target_ty) = match obligation.predicate {
1123 ty::Predicate::Trait(p) => {
1124 (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty()))
1128 let mut generator = None;
1129 let mut last_generator = None;
1130 let mut next_code = Some(&obligation.cause.code);
1131 while let Some(code) = next_code {
1132 debug!("maybe_note_obligation_cause_for_async_await: code={:?}", code);
1134 ObligationCauseCode::BuiltinDerivedObligation(derived_obligation)
1135 | ObligationCauseCode::ImplDerivedObligation(derived_obligation) => {
1136 let ty = derived_obligation.parent_trait_ref.self_ty();
1138 "maybe_note_obligation_cause_for_async_await: \
1139 parent_trait_ref={:?} self_ty.kind={:?}",
1140 derived_obligation.parent_trait_ref, ty.kind
1144 ty::Generator(did, ..) => {
1145 generator = generator.or(Some(did));
1146 last_generator = Some(did);
1148 ty::GeneratorWitness(..) => {}
1149 _ if generator.is_none() => {
1150 trait_ref = Some(*derived_obligation.parent_trait_ref.skip_binder());
1151 target_ty = Some(ty);
1156 next_code = Some(derived_obligation.parent_code.as_ref());
1162 // Only continue if a generator was found.
1164 "maybe_note_obligation_cause_for_async_await: generator={:?} trait_ref={:?} \
1166 generator, trait_ref, target_ty
1168 let (generator_did, trait_ref, target_ty) = match (generator, trait_ref, target_ty) {
1169 (Some(generator_did), Some(trait_ref), Some(target_ty)) => {
1170 (generator_did, trait_ref, target_ty)
1175 let span = self.tcx.def_span(generator_did);
1177 // Do not ICE on closure typeck (#66868).
1178 if self.tcx.hir().as_local_hir_id(generator_did).is_none() {
1182 // Get the tables from the infcx if the generator is the function we are
1183 // currently type-checking; otherwise, get them by performing a query.
1184 // This is needed to avoid cycles.
1185 let in_progress_tables = self.in_progress_tables.map(|t| t.borrow());
1186 let generator_did_root = self.tcx.closure_base_def_id(generator_did);
1188 "maybe_note_obligation_cause_for_async_await: generator_did={:?} \
1189 generator_did_root={:?} in_progress_tables.local_id_root={:?} span={:?}",
1192 in_progress_tables.as_ref().map(|t| t.local_id_root),
1196 let tables: &TypeckTables<'tcx> = match &in_progress_tables {
1197 Some(t) if t.local_id_root == Some(generator_did_root) => t,
1199 query_tables = self.tcx.typeck_tables_of(generator_did);
1204 // Look for a type inside the generator interior that matches the target type to get
1206 let target_ty_erased = self.tcx.erase_regions(&target_ty);
1207 let target_span = tables
1208 .generator_interior_types
1210 .find(|ty::GeneratorInteriorTypeCause { ty, .. }| {
1211 // Careful: the regions for types that appear in the
1212 // generator interior are not generally known, so we
1213 // want to erase them when comparing (and anyway,
1214 // `Send` and other bounds are generally unaffected by
1215 // the choice of region). When erasing regions, we
1216 // also have to erase late-bound regions. This is
1217 // because the types that appear in the generator
1218 // interior generally contain "bound regions" to
1219 // represent regions that are part of the suspended
1220 // generator frame. Bound regions are preserved by
1221 // `erase_regions` and so we must also call
1222 // `erase_late_bound_regions`.
1223 let ty_erased = self.tcx.erase_late_bound_regions(&ty::Binder::bind(*ty));
1224 let ty_erased = self.tcx.erase_regions(&ty_erased);
1225 let eq = ty::TyS::same_type(ty_erased, target_ty_erased);
1227 "maybe_note_obligation_cause_for_async_await: ty_erased={:?} \
1228 target_ty_erased={:?} eq={:?}",
1229 ty_erased, target_ty_erased, eq
1233 .map(|ty::GeneratorInteriorTypeCause { span, scope_span, expr, .. }| {
1234 (span, source_map.span_to_snippet(*span), scope_span, expr)
1238 "maybe_note_obligation_cause_for_async_await: target_ty={:?} \
1239 generator_interior_types={:?} target_span={:?}",
1240 target_ty, tables.generator_interior_types, target_span
1242 if let Some((target_span, Ok(snippet), scope_span, expr)) = target_span {
1243 self.note_obligation_cause_for_async_await(
1263 /// Unconditionally adds the diagnostic note described in
1264 /// `maybe_note_obligation_cause_for_async_await`'s documentation comment.
1265 crate fn note_obligation_cause_for_async_await(
1267 err: &mut DiagnosticBuilder<'_>,
1269 scope_span: &Option<Span>,
1270 expr: Option<hir::HirId>,
1272 first_generator: DefId,
1273 last_generator: Option<DefId>,
1274 trait_ref: ty::TraitRef<'_>,
1275 target_ty: Ty<'tcx>,
1276 tables: &ty::TypeckTables<'_>,
1277 obligation: &PredicateObligation<'tcx>,
1278 next_code: Option<&ObligationCauseCode<'tcx>>,
1280 let source_map = self.tcx.sess.source_map();
1282 let is_async_fn = self
1284 .parent(first_generator)
1285 .map(|parent_did| self.tcx.asyncness(parent_did))
1286 .map(|parent_asyncness| parent_asyncness == hir::IsAsync::Async)
1288 let is_async_move = self
1291 .as_local_hir_id(first_generator)
1292 .and_then(|hir_id| self.tcx.hir().maybe_body_owned_by(hir_id))
1293 .map(|body_id| self.tcx.hir().body(body_id))
1294 .and_then(|body| body.generator_kind())
1295 .map(|generator_kind| match generator_kind {
1296 hir::GeneratorKind::Async(..) => true,
1300 let await_or_yield = if is_async_fn || is_async_move { "await" } else { "yield" };
1302 // Special case the primary error message when send or sync is the trait that was
1304 let is_send = self.tcx.is_diagnostic_item(sym::send_trait, trait_ref.def_id);
1305 let is_sync = self.tcx.is_diagnostic_item(sym::sync_trait, trait_ref.def_id);
1306 let hir = self.tcx.hir();
1307 let trait_explanation = if is_send || is_sync {
1308 let (trait_name, trait_verb) =
1309 if is_send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
1312 err.set_primary_message(format!(
1313 "future cannot be {} between threads safely",
1317 let original_span = err.span.primary_span().unwrap();
1318 let mut span = MultiSpan::from_span(original_span);
1320 let message = if let Some(name) = last_generator
1321 .and_then(|generator_did| self.tcx.parent(generator_did))
1322 .and_then(|parent_did| hir.as_local_hir_id(parent_did))
1323 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
1325 format!("future returned by `{}` is not {}", name, trait_name)
1327 format!("future is not {}", trait_name)
1330 span.push_span_label(original_span, message);
1333 format!("is not {}", trait_name)
1335 format!("does not implement `{}`", trait_ref.print_only_trait_path())
1338 // Look at the last interior type to get a span for the `.await`.
1339 let await_span = tables.generator_interior_types.iter().map(|t| t.span).last().unwrap();
1340 let mut span = MultiSpan::from_span(await_span);
1341 span.push_span_label(
1343 format!("{} occurs here, with `{}` maybe used later", await_or_yield, snippet),
1346 span.push_span_label(target_span, format!("has type `{}`", target_ty));
1348 // If available, use the scope span to annotate the drop location.
1349 if let Some(scope_span) = scope_span {
1350 span.push_span_label(
1351 source_map.end_point(*scope_span),
1352 format!("`{}` is later dropped here", snippet),
1359 "future {} as this value is used across an {}",
1360 trait_explanation, await_or_yield,
1364 if let Some(expr_id) = expr {
1365 let expr = hir.expect_expr(expr_id);
1366 let is_ref = tables.expr_adjustments(expr).iter().any(|adj| adj.is_region_borrow());
1367 let parent = hir.get_parent_node(expr_id);
1368 if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1369 let method_span = hir.span(parent);
1370 if tables.is_method_call(e) && is_ref {
1373 "consider moving this method call into a `let` \
1374 binding to create a shorter lived borrow",
1380 // Add a note for the item obligation that remains - normally a note pointing to the
1381 // bound that introduced the obligation (e.g. `T: Send`).
1382 debug!("note_obligation_cause_for_async_await: next_code={:?}", next_code);
1383 self.note_obligation_cause_code(
1385 &obligation.predicate,
1391 crate fn note_obligation_cause_code<T>(
1393 err: &mut DiagnosticBuilder<'_>,
1395 cause_code: &ObligationCauseCode<'tcx>,
1396 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1402 ObligationCauseCode::ExprAssignable
1403 | ObligationCauseCode::MatchExpressionArm { .. }
1404 | ObligationCauseCode::Pattern { .. }
1405 | ObligationCauseCode::IfExpression { .. }
1406 | ObligationCauseCode::IfExpressionWithNoElse
1407 | ObligationCauseCode::MainFunctionType
1408 | ObligationCauseCode::StartFunctionType
1409 | ObligationCauseCode::IntrinsicType
1410 | ObligationCauseCode::MethodReceiver
1411 | ObligationCauseCode::ReturnNoExpression
1412 | ObligationCauseCode::MiscObligation => {}
1413 ObligationCauseCode::SliceOrArrayElem => {
1414 err.note("slice and array elements must have `Sized` type");
1416 ObligationCauseCode::TupleElem => {
1417 err.note("only the last element of a tuple may have a dynamically sized type");
1419 ObligationCauseCode::ProjectionWf(data) => {
1420 err.note(&format!("required so that the projection `{}` is well-formed", data,));
1422 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1424 "required so that reference `{}` does not outlive its referent",
1428 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1430 "required so that the lifetime bound of `{}` for `{}` is satisfied",
1434 ObligationCauseCode::ItemObligation(item_def_id) => {
1435 let item_name = tcx.def_path_str(item_def_id);
1436 let msg = format!("required by `{}`", item_name);
1438 if let Some(sp) = tcx.hir().span_if_local(item_def_id) {
1439 let sp = tcx.sess.source_map().def_span(sp);
1440 err.span_label(sp, &msg);
1445 ObligationCauseCode::BindingObligation(item_def_id, span) => {
1446 let item_name = tcx.def_path_str(item_def_id);
1447 let msg = format!("required by this bound in `{}`", item_name);
1448 if let Some(ident) = tcx.opt_item_name(item_def_id) {
1449 err.span_label(ident.span, "");
1451 if span != DUMMY_SP {
1452 err.span_label(span, &msg);
1457 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1459 "required for the cast to the object type `{}`",
1460 self.ty_to_string(object_ty)
1463 ObligationCauseCode::Coercion { source: _, target } => {
1464 err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
1466 ObligationCauseCode::RepeatVec(suggest_const_in_array_repeat_expressions) => {
1468 "the `Copy` trait is required because the repeated element will be copied",
1470 if suggest_const_in_array_repeat_expressions {
1472 "this array initializer can be evaluated at compile-time, for more \
1473 information, see issue \
1474 https://github.com/rust-lang/rust/issues/49147",
1476 if tcx.sess.opts.unstable_features.is_nightly_build() {
1478 "add `#![feature(const_in_array_repeat_expressions)]` to the \
1479 crate attributes to enable",
1484 ObligationCauseCode::VariableType(_) => {
1485 err.note("all local variables must have a statically known size");
1486 if !self.tcx.features().unsized_locals {
1487 err.help("unsized locals are gated as an unstable feature");
1490 ObligationCauseCode::SizedArgumentType => {
1491 err.note("all function arguments must have a statically known size");
1492 if !self.tcx.features().unsized_locals {
1493 err.help("unsized locals are gated as an unstable feature");
1496 ObligationCauseCode::SizedReturnType => {
1497 err.note("the return type of a function must have a statically known size");
1499 ObligationCauseCode::SizedYieldType => {
1500 err.note("the yield type of a generator must have a statically known size");
1502 ObligationCauseCode::AssignmentLhsSized => {
1503 err.note("the left-hand-side of an assignment must have a statically known size");
1505 ObligationCauseCode::TupleInitializerSized => {
1506 err.note("tuples must have a statically known size to be initialized");
1508 ObligationCauseCode::StructInitializerSized => {
1509 err.note("structs must have a statically known size to be initialized");
1511 ObligationCauseCode::FieldSized { adt_kind: ref item, last } => match *item {
1512 AdtKind::Struct => {
1515 "the last field of a packed struct may only have a \
1516 dynamically sized type if it does not need drop to be run",
1520 "only the last field of a struct may have a dynamically sized type",
1525 err.note("no field of a union may have a dynamically sized type");
1528 err.note("no field of an enum variant may have a dynamically sized type");
1531 ObligationCauseCode::ConstSized => {
1532 err.note("constant expressions must have a statically known size");
1534 ObligationCauseCode::ConstPatternStructural => {
1535 err.note("constants used for pattern-matching must derive `PartialEq` and `Eq`");
1537 ObligationCauseCode::SharedStatic => {
1538 err.note("shared static variables must have a type that implements `Sync`");
1540 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1541 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1542 let ty = parent_trait_ref.skip_binder().self_ty();
1543 err.note(&format!("required because it appears within the type `{}`", ty));
1544 obligated_types.push(ty);
1546 let parent_predicate = parent_trait_ref.to_predicate();
1547 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1548 self.note_obligation_cause_code(
1556 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1557 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
1559 "required because of the requirements on the impl of `{}` for `{}`",
1560 parent_trait_ref.print_only_trait_path(),
1561 parent_trait_ref.skip_binder().self_ty()
1563 let parent_predicate = parent_trait_ref.to_predicate();
1564 self.note_obligation_cause_code(
1571 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1573 "the requirement `{}` appears on the impl method \
1574 but not on the corresponding trait method",
1578 ObligationCauseCode::CompareImplTypeObligation { .. } => {
1580 "the requirement `{}` appears on the associated impl type \
1581 but not on the corresponding associated trait type",
1585 ObligationCauseCode::ReturnType
1586 | ObligationCauseCode::ReturnValue(_)
1587 | ObligationCauseCode::BlockTailExpression(_) => (),
1588 ObligationCauseCode::TrivialBound => {
1589 err.help("see issue #48214");
1590 if tcx.sess.opts.unstable_features.is_nightly_build() {
1591 err.help("add `#![feature(trivial_bounds)]` to the crate attributes to enable");
1594 ObligationCauseCode::AssocTypeBound(ref data) => {
1595 err.span_label(data.original, "associated type defined here");
1596 if let Some(sp) = data.impl_span {
1597 err.span_label(sp, "in this `impl` item");
1599 for sp in &data.bounds {
1600 err.span_label(*sp, "restricted in this bound");
1606 crate fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder<'_>) {
1607 let current_limit = self.tcx.sess.recursion_limit.get();
1608 let suggested_limit = current_limit * 2;
1610 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1616 /// Suggest restricting a type param with a new bound.
1617 pub fn suggest_constraining_type_param(
1618 generics: &hir::Generics<'_>,
1619 err: &mut DiagnosticBuilder<'_>,
1622 source_map: &SourceMap,
1625 let restrict_msg = "consider further restricting this bound";
1626 if let Some(param) =
1627 generics.params.iter().filter(|p| p.name.ident().as_str() == param_name).next()
1629 if param_name.starts_with("impl ") {
1630 // `impl Trait` in argument:
1631 // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
1632 err.span_suggestion(
1635 // `impl CurrentTrait + MissingTrait`
1636 format!("{} + {}", param_name, constraint),
1637 Applicability::MachineApplicable,
1639 } else if generics.where_clause.predicates.is_empty() && param.bounds.is_empty() {
1640 // If there are no bounds whatsoever, suggest adding a constraint
1641 // to the type parameter:
1642 // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
1643 err.span_suggestion(
1645 "consider restricting this bound",
1646 format!("{}: {}", param_name, constraint),
1647 Applicability::MachineApplicable,
1649 } else if !generics.where_clause.predicates.is_empty() {
1650 // There is a `where` clause, so suggest expanding it:
1651 // `fn foo<T>(t: T) where T: Debug {}` →
1652 // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
1653 err.span_suggestion(
1654 generics.where_clause.span().unwrap().shrink_to_hi(),
1655 &format!("consider further restricting type parameter `{}`", param_name),
1656 format!(", {}: {}", param_name, constraint),
1657 Applicability::MachineApplicable,
1660 // If there is no `where` clause lean towards constraining to the
1662 // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
1663 // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
1664 let sp = param.span.with_hi(span.hi());
1665 let span = source_map.span_through_char(sp, ':');
1666 if sp != param.span && sp != span {
1667 // Only suggest if we have high certainty that the span
1668 // covers the colon in `foo<T: Trait>`.
1669 err.span_suggestion(
1672 format!("{}: {} + ", param_name, constraint),
1673 Applicability::MachineApplicable,
1678 &format!("consider adding a `where {}: {}` bound", param_name, constraint),
1687 /// Collect all the returned expressions within the input expression.
1688 /// Used to point at the return spans when we want to suggest some change to them.
1689 struct ReturnsVisitor<'v>(Vec<&'v hir::Expr<'v>>);
1691 impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
1692 type Map = rustc::hir::map::Map<'v>;
1694 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<'_, Self::Map> {
1695 hir::intravisit::NestedVisitorMap::None
1698 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
1699 if let hir::ExprKind::Ret(Some(ex)) = ex.kind {
1702 hir::intravisit::walk_expr(self, ex);
1705 fn visit_body(&mut self, body: &'v hir::Body<'v>) {
1706 if body.generator_kind().is_none() {
1707 if let hir::ExprKind::Block(block, None) = body.value.kind {
1708 if let Some(expr) = block.expr {
1713 hir::intravisit::walk_body(self, body);