2 use crate::astconv::AstConv;
3 use crate::errors::{AddReturnTypeSuggestion, ExpectedReturnTypeLabel};
5 use hir::def_id::DefId;
6 use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX};
7 use rustc_errors::{Applicability, Diagnostic, MultiSpan};
9 use rustc_hir::def::{CtorOf, DefKind};
10 use rustc_hir::lang_items::LangItem;
12 Expr, ExprKind, GenericBound, Node, Path, QPath, Stmt, StmtKind, TyKind, WherePredicate,
14 use rustc_infer::infer::{self, TyCtxtInferExt};
15 use rustc_infer::traits::{self, StatementAsExpression};
16 use rustc_middle::lint::in_external_macro;
17 use rustc_middle::ty::{self, Binder, IsSuggestable, ToPredicate, Ty};
18 use rustc_session::errors::ExprParenthesesNeeded;
19 use rustc_span::symbol::sym;
21 use rustc_trait_selection::infer::InferCtxtExt;
22 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
24 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25 pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
26 err.span_suggestion_short(
28 "consider using a semicolon here",
30 Applicability::MachineApplicable,
34 /// On implicit return expressions with mismatched types, provides the following suggestions:
36 /// - Points out the method's return type as the reason for the expected type.
37 /// - Possible missing semicolon.
38 /// - Possible missing return type if the return type is the default, and not `fn main()`.
39 pub fn suggest_mismatched_types_on_tail(
42 expr: &'tcx hir::Expr<'tcx>,
47 let expr = expr.peel_drop_temps();
48 self.suggest_missing_semicolon(err, expr, expected, false);
49 let mut pointing_at_return_type = false;
50 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
51 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
52 pointing_at_return_type = self.suggest_missing_return_type(
60 self.suggest_missing_break_or_return_expr(
61 err, expr, &fn_decl, expected, found, blk_id, fn_id,
64 pointing_at_return_type
67 /// When encountering an fn-like type, try accessing the output of the type
68 /// and suggesting calling it if it satisfies a predicate (i.e. if the
69 /// output has a method or a field):
70 /// ```compile_fail,E0308
71 /// fn foo(x: usize) -> usize { x }
72 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
74 pub(crate) fn suggest_fn_call(
79 can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
81 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(expr, found)
82 else { return false; };
83 if can_satisfy(output) {
84 let (sugg_call, mut applicability) = match inputs.len() {
85 0 => ("".to_string(), Applicability::MachineApplicable),
90 if ty.is_suggestable(self.tcx, false) {
98 Applicability::HasPlaceholders,
100 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
103 let msg = match def_id_or_name {
104 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
105 DefKind::Ctor(CtorOf::Struct, _) => "instantiate this tuple struct".to_string(),
106 DefKind::Ctor(CtorOf::Variant, _) => {
107 "instantiate this tuple variant".to_string()
109 kind => format!("call this {}", kind.descr(def_id)),
111 DefIdOrName::Name(name) => format!("call this {name}"),
114 let sugg = match expr.kind {
115 hir::ExprKind::Call(..)
116 | hir::ExprKind::Path(..)
117 | hir::ExprKind::Index(..)
118 | hir::ExprKind::Lit(..) => {
119 vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
121 hir::ExprKind::Closure { .. } => {
122 // Might be `{ expr } || { bool }`
123 applicability = Applicability::MaybeIncorrect;
125 (expr.span.shrink_to_lo(), "(".to_string()),
126 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
131 (expr.span.shrink_to_lo(), "(".to_string()),
132 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
137 err.multipart_suggestion_verbose(
138 format!("use parentheses to {msg}"),
147 /// Extracts information about a callable type for diagnostics. This is a
148 /// heuristic -- it doesn't necessarily mean that a type is always callable,
149 /// because the callable type must also be well-formed to be called.
150 pub(in super::super) fn extract_callable_info(
154 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
155 // Autoderef is useful here because sometimes we box callables, etc.
156 let Some((def_id_or_name, output, inputs)) = self.autoderef(expr.span, found).silence_errors().find_map(|(found, _)| {
157 match *found.kind() {
159 Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
160 ty::FnDef(def_id, _) => {
161 let fn_sig = found.fn_sig(self.tcx);
162 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
164 ty::Closure(def_id, substs) => {
165 let fn_sig = substs.as_closure().sig();
166 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
168 ty::Opaque(def_id, substs) => {
169 self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
170 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
171 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
172 // args tuple will always be substs[1]
173 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
176 DefIdOrName::DefId(def_id),
177 pred.kind().rebind(proj.term.ty().unwrap()),
178 pred.kind().rebind(args.as_slice()),
185 ty::Dynamic(data, _, ty::Dyn) => {
186 data.iter().find_map(|pred| {
187 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
188 && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
189 // for existential projection, substs are shifted over by 1
190 && let ty::Tuple(args) = proj.substs.type_at(0).kind()
193 DefIdOrName::Name("trait object"),
194 pred.rebind(proj.term.ty().unwrap()),
195 pred.rebind(args.as_slice()),
202 ty::Param(param) => {
203 let def_id = self.tcx.generics_of(self.body_id.owner).type_param(¶m, self.tcx).def_id;
204 self.tcx.predicates_of(self.body_id.owner).predicates.iter().find_map(|(pred, _)| {
205 if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
206 && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
207 && proj.projection_ty.self_ty() == found
208 // args tuple will always be substs[1]
209 && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
212 DefIdOrName::DefId(def_id),
213 pred.kind().rebind(proj.term.ty().unwrap()),
214 pred.kind().rebind(args.as_slice()),
223 }) else { return None; };
225 let output = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, output);
230 self.replace_bound_vars_with_fresh_vars(
238 // We don't want to register any extra obligations, which should be
239 // implied by wf, but also because that would possibly result in
240 // erroneous errors later on.
241 let infer::InferOk { value: output, obligations: _ } =
242 self.normalize_associated_types_in_as_infer_ok(expr.span, output);
244 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
247 pub fn suggest_two_fn_call(
249 err: &mut Diagnostic,
250 lhs_expr: &'tcx hir::Expr<'tcx>,
252 rhs_expr: &'tcx hir::Expr<'tcx>,
254 can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
256 let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_expr, lhs_ty)
257 else { return false; };
258 let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_expr, rhs_ty)
259 else { return false; };
261 if can_satisfy(lhs_output_ty, rhs_output_ty) {
262 let mut sugg = vec![];
263 let mut applicability = Applicability::MachineApplicable;
265 for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
266 let (sugg_call, this_applicability) = match inputs.len() {
267 0 => ("".to_string(), Applicability::MachineApplicable),
272 if ty.is_suggestable(self.tcx, false) {
273 format!("/* {ty} */")
275 "/* value */".to_string()
280 Applicability::HasPlaceholders,
282 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
285 applicability = applicability.max(this_applicability);
288 hir::ExprKind::Call(..)
289 | hir::ExprKind::Path(..)
290 | hir::ExprKind::Index(..)
291 | hir::ExprKind::Lit(..) => {
292 sugg.extend([(expr.span.shrink_to_hi(), format!("({sugg_call})"))]);
294 hir::ExprKind::Closure { .. } => {
295 // Might be `{ expr } || { bool }`
296 applicability = Applicability::MaybeIncorrect;
298 (expr.span.shrink_to_lo(), "(".to_string()),
299 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
304 (expr.span.shrink_to_lo(), "(".to_string()),
305 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
311 err.multipart_suggestion_verbose(
312 format!("use parentheses to call these"),
323 pub fn suggest_deref_ref_or_into(
325 err: &mut Diagnostic,
326 expr: &hir::Expr<'tcx>,
329 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
331 let expr = expr.peel_blocks();
332 if let Some((sp, msg, suggestion, applicability, verbose)) =
333 self.check_ref(expr, found, expected)
336 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
338 err.span_suggestion(sp, &msg, suggestion, applicability);
341 } else if self.suggest_else_fn_with_closure(err, expr, found, expected)
344 } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected))
345 && let ty::FnDef(def_id, ..) = &found.kind()
346 && let Some(sp) = self.tcx.hir().span_if_local(*def_id)
348 err.span_label(sp, format!("{found} defined here"));
350 } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
353 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
354 if !methods.is_empty() {
355 let mut suggestions = methods.iter()
356 .filter_map(|conversion_method| {
357 let receiver_method_ident = expr.method_ident();
358 if let Some(method_ident) = receiver_method_ident
359 && method_ident.name == conversion_method.name
361 return None // do not suggest code that is already there (#53348)
364 let method_call_list = [sym::to_vec, sym::to_string];
365 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
366 && receiver_method.ident.name == sym::clone
367 && method_call_list.contains(&conversion_method.name)
368 // If receiver is `.clone()` and found type has one of those methods,
369 // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
370 // to an owned type (`Vec` or `String`). These conversions clone internally,
371 // so we remove the user's `clone` call.
374 receiver_method.ident.span,
375 conversion_method.name.to_string()
377 } else if expr.precedence().order()
378 < ExprPrecedence::MethodCall.order()
381 (expr.span.shrink_to_lo(), "(".to_string()),
382 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
385 vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
387 let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
388 if let Some(name) = struct_pat_shorthand_field {
391 (expr.span.shrink_to_lo(), format!("{}: ", name)),
397 if suggestions.peek().is_some() {
398 err.multipart_suggestions(
399 "try using a conversion method",
401 Applicability::MaybeIncorrect,
405 } else if let ty::Adt(found_adt, found_substs) = found.kind()
406 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
407 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
408 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
409 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
412 let ty = found_substs.type_at(0);
415 while let ty::Ref(_, inner, _) = peeled.kind() {
419 if let ty::Adt(adt, _) = peeled.kind()
420 && self.tcx.is_diagnostic_item(sym::String, adt.did())
422 err.span_suggestion_verbose(
423 expr.span.shrink_to_hi(),
424 "try converting the passed type into a `&str`",
425 format!(".map(|x| &*{}x)", "*".repeat(ref_cnt)),
426 Applicability::MaybeIncorrect,
436 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
437 /// in the heap by calling `Box::new()`.
438 pub(in super::super) fn suggest_boxing_when_appropriate(
440 err: &mut Diagnostic,
441 expr: &hir::Expr<'_>,
445 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
446 // Do not suggest `Box::new` in const context.
449 if !expected.is_box() || found.is_box() {
452 let boxed_found = self.tcx.mk_box(found);
453 if self.can_coerce(boxed_found, expected) {
454 err.multipart_suggestion(
455 "store this in the heap by calling `Box::new`",
457 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
458 (expr.span.shrink_to_hi(), ")".to_string()),
460 Applicability::MachineApplicable,
463 "for more on the distinction between the stack and the heap, read \
464 https://doc.rust-lang.org/book/ch15-01-box.html, \
465 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
466 https://doc.rust-lang.org/std/boxed/index.html",
474 /// When encountering a closure that captures variables, where a FnPtr is expected,
475 /// suggest a non-capturing closure
476 pub(in super::super) fn suggest_no_capture_closure(
478 err: &mut Diagnostic,
482 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
483 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
484 // Report upto four upvars being captured to reduce the amount error messages
485 // reported back to the user.
486 let spans_and_labels = upvars
489 .map(|(var_hir_id, upvar)| {
490 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
491 let msg = format!("`{}` captured here", var_name);
494 .collect::<Vec<_>>();
496 let mut multi_span: MultiSpan =
497 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
498 for (sp, label) in spans_and_labels {
499 multi_span.push_span_label(sp, label);
503 "closures can only be coerced to `fn` types if they do not capture any variables"
511 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
512 #[instrument(skip(self, err))]
513 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
515 err: &mut Diagnostic,
516 expr: &hir::Expr<'_>,
522 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
523 // Do not suggest `Box::new` in const context.
526 let pin_did = self.tcx.lang_items().pin_type();
527 // This guards the `unwrap` and `mk_box` below.
528 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
531 let box_found = self.tcx.mk_box(found);
532 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
533 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
534 match expected.kind() {
535 ty::Adt(def, _) if Some(def.did()) == pin_did => {
536 if self.can_coerce(pin_box_found, expected) {
537 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
539 ty::Adt(def, _) if def.is_box() => {
540 err.help("use `Box::pin`");
543 err.multipart_suggestion(
544 "you need to pin and box this expression",
546 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
547 (expr.span.shrink_to_hi(), ")".to_string()),
549 Applicability::MaybeIncorrect,
554 } else if self.can_coerce(pin_found, expected) {
556 ty::Adt(def, _) if def.is_box() => {
557 err.help("use `Box::pin`");
566 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
567 // Check if the parent expression is a call to Pin::new. If it
568 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
569 // can suggest Box::pin.
570 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
571 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
575 ExprKind::Path(QPath::TypeRelative(
577 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
581 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
584 "use `Box::pin` to pin and box this expression",
586 Applicability::MachineApplicable,
597 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
599 /// ```compile_fail,E0308
600 /// # fn bar_that_returns_u32() -> u32 { 4 }
602 /// bar_that_returns_u32()
606 /// This routine checks if the return expression in a block would make sense on its own as a
607 /// statement and the return type has been left as default or has been specified as `()`. If so,
608 /// it suggests adding a semicolon.
610 /// If the expression is the expression of a closure without block (`|| expr`), a
611 /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
612 pub fn suggest_missing_semicolon(
614 err: &mut Diagnostic,
615 expression: &'tcx hir::Expr<'tcx>,
619 if expected.is_unit() {
620 // `BlockTailExpression` only relevant if the tail expr would be
621 // useful on its own.
622 match expression.kind {
624 | ExprKind::MethodCall(..)
627 | ExprKind::Match(..)
628 | ExprKind::Block(..)
629 if expression.can_have_side_effects()
630 // If the expression is from an external macro, then do not suggest
631 // adding a semicolon, because there's nowhere to put it.
633 && !in_external_macro(self.tcx.sess, expression.span) =>
636 err.multipart_suggestion(
637 "consider using a semicolon here",
639 (expression.span.shrink_to_lo(), "{ ".to_owned()),
640 (expression.span.shrink_to_hi(), "; }".to_owned()),
642 Applicability::MachineApplicable,
646 expression.span.shrink_to_hi(),
647 "consider using a semicolon here",
649 Applicability::MachineApplicable,
658 /// A possible error is to forget to add a return type that is needed:
660 /// ```compile_fail,E0308
661 /// # fn bar_that_returns_u32() -> u32 { 4 }
663 /// bar_that_returns_u32()
667 /// This routine checks if the return type is left as default, the method is not part of an
668 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
670 pub(in super::super) fn suggest_missing_return_type(
672 err: &mut Diagnostic,
673 fn_decl: &hir::FnDecl<'_>,
680 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
681 // Only suggest changing the return type for methods that
682 // haven't set a return type at all (and aren't `fn main()` or an impl).
683 match &fn_decl.output {
684 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
685 // `fn main()` must return `()`, do not suggest changing return type
686 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
689 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
690 if found.is_suggestable(self.tcx, false) {
691 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
693 } else if let ty::Closure(_, substs) = found.kind()
694 // FIXME(compiler-errors): Get better at printing binders...
695 && let closure = substs.as_closure()
696 && closure.sig().is_suggestable(self.tcx, false)
698 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
701 // FIXME: if `found` could be `impl Iterator` we should suggest that.
702 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
706 &hir::FnRetTy::Return(ref ty) => {
707 // Only point to return type if the expected type is the return type, as if they
708 // are not, the expectation must have been caused by something else.
709 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
711 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
712 debug!("suggest_missing_return_type: return type {:?}", ty);
713 debug!("suggest_missing_return_type: expected type {:?}", ty);
714 let bound_vars = self.tcx.late_bound_vars(fn_id);
715 let ty = Binder::bind_with_vars(ty, bound_vars);
716 let ty = self.normalize_associated_types_in(span, ty);
717 let ty = self.tcx.erase_late_bound_regions(ty);
718 if self.can_coerce(expected, ty) {
719 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
720 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
729 /// check whether the return type is a generic type with a trait bound
730 /// only suggest this if the generic param is not present in the arguments
731 /// if this is true, hint them towards changing the return type to `impl Trait`
732 /// ```compile_fail,E0308
733 /// fn cant_name_it<T: Fn() -> u32>() -> T {
737 fn try_suggest_return_impl_trait(
739 err: &mut Diagnostic,
744 // Only apply the suggestion if:
745 // - the return type is a generic parameter
746 // - the generic param is not used as a fn param
747 // - the generic param has at least one bound
748 // - the generic param doesn't appear in any other bounds where it's not the Self type
750 // - Changing the return type to be `impl <all bounds>`
752 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
754 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
756 let fn_node = self.tcx.hir().find(fn_id);
758 let Some(hir::Node::Item(hir::Item {
761 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
762 hir::Generics { params, predicates, .. },
766 })) = fn_node else { return };
768 if params.get(expected_ty_as_param.index as usize).is_none() {
772 // get all where BoundPredicates here, because they are used in to cases below
773 let where_predicates = predicates
775 .filter_map(|p| match p {
776 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
781 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
782 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
787 .map(|(ty, bounds)| match ty.kind() {
788 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
789 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
790 _ => match ty.contains(expected) {
795 .collect::<Result<Vec<_>, _>>();
797 let Ok(where_predicates) = where_predicates else { return };
799 // now get all predicates in the same types as the where bounds, so we can chain them
800 let predicates_from_where =
801 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
803 // extract all bounds from the source code using their spans
804 let all_matching_bounds_strs = predicates_from_where
805 .filter_map(|bound| match bound {
806 GenericBound::Trait(_, _) => {
807 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
811 .collect::<Vec<String>>();
813 if all_matching_bounds_strs.len() == 0 {
817 let all_bounds_str = all_matching_bounds_strs.join(" + ");
819 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
820 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
821 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
824 if ty_param_used_in_fn_params {
830 "consider using an impl return type",
831 format!("impl {}", all_bounds_str),
832 Applicability::MaybeIncorrect,
836 pub(in super::super) fn suggest_missing_break_or_return_expr(
838 err: &mut Diagnostic,
839 expr: &'tcx hir::Expr<'tcx>,
840 fn_decl: &hir::FnDecl<'_>,
846 if !expected.is_unit() {
849 let found = self.resolve_vars_with_obligations(found);
851 let in_loop = self.is_loop(id)
852 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
854 let in_local_statement = self.is_local_statement(id)
859 .any(|(parent_id, _)| self.is_local_statement(parent_id));
861 if in_loop && in_local_statement {
862 err.multipart_suggestion(
863 "you might have meant to break the loop with this value",
865 (expr.span.shrink_to_lo(), "break ".to_string()),
866 (expr.span.shrink_to_hi(), ";".to_string()),
868 Applicability::MaybeIncorrect,
873 if let hir::FnRetTy::Return(ty) = fn_decl.output {
874 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
875 let bound_vars = self.tcx.late_bound_vars(fn_id);
876 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
877 let ty = self.normalize_associated_types_in(expr.span, ty);
878 let ty = match self.tcx.asyncness(fn_id.owner) {
879 hir::IsAsync::Async => {
880 let infcx = self.tcx.infer_ctxt().build();
882 .get_impl_future_output_ty(ty)
885 fn_decl.output.span(),
886 "failed to get output type of async function"
891 hir::IsAsync::NotAsync => ty,
893 if self.can_coerce(found, ty) {
894 err.multipart_suggestion(
895 "you might have meant to return this value",
897 (expr.span.shrink_to_lo(), "return ".to_string()),
898 (expr.span.shrink_to_hi(), ";".to_string()),
900 Applicability::MaybeIncorrect,
906 pub(in super::super) fn suggest_missing_parentheses(
908 err: &mut Diagnostic,
909 expr: &hir::Expr<'_>,
911 let sp = self.tcx.sess.source_map().start_point(expr.span);
912 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
913 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
914 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
921 /// Given an expression type mismatch, peel any `&` expressions until we get to
922 /// a block expression, and then suggest replacing the braces with square braces
923 /// if it was possibly mistaken array syntax.
924 pub(crate) fn suggest_block_to_brackets_peeling_refs(
926 diag: &mut Diagnostic,
927 mut expr: &hir::Expr<'_>,
928 mut expr_ty: Ty<'tcx>,
929 mut expected_ty: Ty<'tcx>,
932 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
934 hir::ExprKind::AddrOf(_, _, inner_expr),
935 ty::Ref(_, inner_expr_ty, _),
936 ty::Ref(_, inner_expected_ty, _),
939 expr_ty = *inner_expr_ty;
940 expected_ty = *inner_expected_ty;
942 (hir::ExprKind::Block(blk, _), _, _) => {
943 self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
951 pub(crate) fn suggest_copied_or_cloned(
953 diag: &mut Diagnostic,
954 expr: &hir::Expr<'_>,
956 expected_ty: Ty<'tcx>,
958 let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
959 let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
960 if adt_def != expected_adt_def {
964 let mut suggest_copied_or_cloned = || {
965 let expr_inner_ty = substs.type_at(0);
966 let expected_inner_ty = expected_substs.type_at(0);
967 if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
968 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
970 let def_path = self.tcx.def_path_str(adt_def.did());
971 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
972 diag.span_suggestion_verbose(
973 expr.span.shrink_to_hi(),
975 "use `{def_path}::copied` to copy the value inside the `{def_path}`"
978 Applicability::MachineApplicable,
981 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
982 && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
990 diag.span_suggestion_verbose(
991 expr.span.shrink_to_hi(),
993 "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
996 Applicability::MachineApplicable,
1004 if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1005 && adt_def.did() == result_did
1006 // Check that the error types are equal
1007 && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1009 return suggest_copied_or_cloned();
1010 } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1011 && adt_def.did() == option_did
1013 return suggest_copied_or_cloned();
1019 pub(crate) fn suggest_into(
1021 diag: &mut Diagnostic,
1022 expr: &hir::Expr<'_>,
1024 expected_ty: Ty<'tcx>,
1026 let expr = expr.peel_blocks();
1028 // We have better suggestions for scalar interconversions...
1029 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1033 // Don't suggest turning a block into another type (e.g. `{}.into()`)
1034 if matches!(expr.kind, hir::ExprKind::Block(..)) {
1038 // We'll later suggest `.as_ref` when noting the type error,
1039 // so skip if we will suggest that instead.
1040 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1044 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1045 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1046 self.misc(expr.span),
1048 ty::Binder::dummy(ty::TraitRef {
1049 def_id: into_def_id,
1050 substs: self.tcx.mk_substs_trait(expr_ty, &[expected_ty.into()]),
1052 .to_poly_trait_predicate()
1053 .to_predicate(self.tcx),
1056 let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1057 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1059 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1061 diag.multipart_suggestion(
1062 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1064 Applicability::MaybeIncorrect
1072 /// Suggest wrapping the block in square brackets instead of curly braces
1073 /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1074 pub(crate) fn suggest_block_to_brackets(
1076 diag: &mut Diagnostic,
1077 blk: &hir::Block<'_>,
1079 expected_ty: Ty<'tcx>,
1081 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1082 if self.can_coerce(blk_ty, *elem_ty)
1083 && blk.stmts.is_empty()
1084 && blk.rules == hir::BlockCheckMode::DefaultBlock
1086 let source_map = self.tcx.sess.source_map();
1087 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1088 if snippet.starts_with('{') && snippet.ends_with('}') {
1089 diag.multipart_suggestion_verbose(
1090 "to create an array, use square brackets instead of curly braces",
1095 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1101 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1105 Applicability::MachineApplicable,
1113 fn is_loop(&self, id: hir::HirId) -> bool {
1114 let node = self.tcx.hir().get(id);
1115 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1118 fn is_local_statement(&self, id: hir::HirId) -> bool {
1119 let node = self.tcx.hir().get(id);
1120 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1123 /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1124 /// which is a side-effect of autoref.
1125 pub(crate) fn note_type_is_not_clone(
1127 diag: &mut Diagnostic,
1128 expected_ty: Ty<'tcx>,
1130 expr: &hir::Expr<'_>,
1132 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1133 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1134 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1135 let results = self.typeck_results.borrow();
1136 // First, look for a `Clone::clone` call
1137 if segment.ident.name == sym::clone
1138 && results.type_dependent_def_id(expr.hir_id).map_or(
1141 let assoc_item = self.tcx.associated_item(did);
1142 assoc_item.container == ty::AssocItemContainer::TraitContainer
1143 && assoc_item.container_id(self.tcx) == clone_trait_did
1146 // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1147 // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1148 && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1149 // Check that we're in fact trying to clone into the expected type
1150 && self.can_coerce(*pointee_ty, expected_ty)
1151 // And the expected type doesn't implement `Clone`
1152 && !self.predicate_must_hold_considering_regions(&traits::Obligation {
1153 cause: traits::ObligationCause::dummy(),
1154 param_env: self.param_env,
1156 predicate: ty::Binder::dummy(ty::TraitRef {
1157 def_id: clone_trait_did,
1158 substs: self.tcx.mk_substs([expected_ty.into()].iter()),
1161 .to_predicate(self.tcx),
1167 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1173 /// A common error is to add an extra semicolon:
1175 /// ```compile_fail,E0308
1176 /// fn foo() -> usize {
1181 /// This routine checks if the final statement in a block is an
1182 /// expression with an explicit semicolon whose type is compatible
1183 /// with `expected_ty`. If so, it suggests removing the semicolon.
1184 pub(crate) fn consider_removing_semicolon(
1186 blk: &'tcx hir::Block<'tcx>,
1187 expected_ty: Ty<'tcx>,
1188 err: &mut Diagnostic,
1190 if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1191 if let StatementAsExpression::NeedsBoxing = boxed {
1192 err.span_suggestion_verbose(
1194 "consider removing this semicolon and boxing the expression",
1196 Applicability::HasPlaceholders,
1199 err.span_suggestion_short(
1201 "remove this semicolon to return this value",
1203 Applicability::MachineApplicable,
1213 pub enum DefIdOrName {