2 use crate::astconv::AstConv;
4 use rustc_ast::util::parser::ExprPrecedence;
5 use rustc_span::{self, MultiSpan, Span};
7 use rustc_errors::{Applicability, DiagnosticBuilder};
9 use rustc_hir::def::{CtorOf, DefKind};
10 use rustc_hir::lang_items::LangItem;
12 Expr, ExprKind, GenericBound, ItemKind, Node, Path, QPath, Stmt, StmtKind, TyKind,
15 use rustc_infer::infer::{self, TyCtxtInferExt};
17 use rustc_middle::lint::in_external_macro;
18 use rustc_middle::ty::{self, Binder, Ty};
19 use rustc_span::symbol::{kw, sym};
21 use rustc_middle::ty::subst::GenericArgKind;
24 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25 pub(in super::super) fn suggest_semicolon_at_end(
28 err: &mut DiagnosticBuilder<'_>,
30 err.span_suggestion_short(
32 "consider using a semicolon here",
34 Applicability::MachineApplicable,
38 /// On implicit return expressions with mismatched types, provides the following suggestions:
40 /// - Points out the method's return type as the reason for the expected type.
41 /// - Possible missing semicolon.
42 /// - Possible missing return type if the return type is the default, and not `fn main()`.
43 pub fn suggest_mismatched_types_on_tail(
45 err: &mut DiagnosticBuilder<'_>,
46 expr: &'tcx hir::Expr<'tcx>,
51 let expr = expr.peel_drop_temps();
52 // If the expression is from an external macro, then do not suggest
53 // adding a semicolon, because there's nowhere to put it.
55 if expr.can_have_side_effects() && !in_external_macro(self.tcx.sess, expr.span) {
56 self.suggest_missing_semicolon(err, expr, expected);
58 let mut pointing_at_return_type = false;
59 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
60 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
61 pointing_at_return_type = self.suggest_missing_return_type(
69 self.suggest_missing_break_or_return_expr(
70 err, expr, &fn_decl, expected, found, blk_id, fn_id,
73 pointing_at_return_type
76 /// When encountering an fn-like ctor that needs to unify with a value, check whether calling
77 /// the ctor would successfully solve the type mismatch and if so, suggest it:
79 /// fn foo(x: usize) -> usize { x }
80 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
84 err: &mut DiagnosticBuilder<'_>,
89 let hir = self.tcx.hir();
90 let (def_id, sig) = match *found.kind() {
91 ty::FnDef(def_id, _) => (def_id, found.fn_sig(self.tcx)),
92 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig()),
96 let sig = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, sig).0;
97 let sig = self.normalize_associated_types_in(expr.span, sig);
98 if self.can_coerce(sig.output(), expected) {
99 let (mut sugg_call, applicability) = if sig.inputs().is_empty() {
100 (String::new(), Applicability::MachineApplicable)
102 ("...".to_string(), Applicability::HasPlaceholders)
104 let mut msg = "call this function";
105 match hir.get_if_local(def_id) {
107 Node::Item(hir::Item { kind: ItemKind::Fn(.., body_id), .. })
108 | Node::ImplItem(hir::ImplItem {
109 kind: hir::ImplItemKind::Fn(_, body_id), ..
111 | Node::TraitItem(hir::TraitItem {
112 kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Provided(body_id)),
116 let body = hir.body(*body_id);
120 .map(|param| match ¶m.pat.kind {
121 hir::PatKind::Binding(_, _, ident, None)
122 if ident.name != kw::SelfLower =>
126 _ => "_".to_string(),
131 Some(Node::Expr(hir::Expr {
132 kind: ExprKind::Closure(_, _, body_id, _, _),
133 span: full_closure_span,
136 if *full_closure_span == expr.span {
139 msg = "call this closure";
140 let body = hir.body(*body_id);
144 .map(|param| match ¶m.pat.kind {
145 hir::PatKind::Binding(_, _, ident, None)
146 if ident.name != kw::SelfLower =>
150 _ => "_".to_string(),
155 Some(Node::Ctor(hir::VariantData::Tuple(fields, _))) => {
156 sugg_call = fields.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
157 match def_id.as_local().map(|def_id| hir.def_kind(def_id)) {
158 Some(DefKind::Ctor(hir::def::CtorOf::Variant, _)) => {
159 msg = "instantiate this tuple variant";
161 Some(DefKind::Ctor(CtorOf::Struct, _)) => {
162 msg = "instantiate this tuple struct";
167 Some(Node::ForeignItem(hir::ForeignItem {
168 kind: hir::ForeignItemKind::Fn(_, idents, _),
174 if ident.name != kw::SelfLower {
183 Some(Node::TraitItem(hir::TraitItem {
184 kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Required(idents)),
190 if ident.name != kw::SelfLower {
201 err.span_suggestion_verbose(
202 expr.span.shrink_to_hi(),
203 &format!("use parentheses to {}", msg),
204 format!("({})", sugg_call),
212 pub fn suggest_deref_ref_or_into(
214 err: &mut DiagnosticBuilder<'_>,
215 expr: &hir::Expr<'tcx>,
218 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
220 let expr = expr.peel_blocks();
221 if let Some((sp, msg, suggestion, applicability, verbose)) =
222 self.check_ref(expr, found, expected)
225 err.span_suggestion_verbose(sp, msg, suggestion, applicability);
227 err.span_suggestion(sp, msg, suggestion, applicability);
229 } else if let (ty::FnDef(def_id, ..), true) =
230 (&found.kind(), self.suggest_fn_call(err, expr, expected, found))
232 if let Some(sp) = self.tcx.hir().span_if_local(*def_id) {
233 let sp = self.sess().source_map().guess_head_span(sp);
234 err.span_label(sp, &format!("{} defined here", found));
236 } else if !self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
237 let is_struct_pat_shorthand_field =
238 self.maybe_get_struct_pattern_shorthand_field(expr).is_some();
239 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
240 if !methods.is_empty() {
241 if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) {
242 let mut suggestions = iter::zip(iter::repeat(&expr_text), &methods)
243 .filter_map(|(receiver, method)| {
244 let method_call = format!(".{}()", method.name);
245 if receiver.ends_with(&method_call) {
246 None // do not suggest code that is already there (#53348)
248 let method_call_list = [".to_vec()", ".to_string()"];
249 let mut sugg = if receiver.ends_with(".clone()")
250 && method_call_list.contains(&method_call.as_str())
252 let max_len = receiver.rfind('.').unwrap();
255 format!("{}{}", &receiver[..max_len], method_call),
258 if expr.precedence().order()
259 < ExprPrecedence::MethodCall.order()
262 (expr.span.shrink_to_lo(), "(".to_string()),
263 (expr.span.shrink_to_hi(), format!("){}", method_call)),
266 vec![(expr.span.shrink_to_hi(), method_call)]
269 if is_struct_pat_shorthand_field {
272 (expr.span.shrink_to_lo(), format!("{}: ", receiver)),
279 if suggestions.peek().is_some() {
280 err.multipart_suggestions(
281 "try using a conversion method",
283 Applicability::MaybeIncorrect,
287 } else if found.to_string().starts_with("Option<")
288 && expected.to_string() == "Option<&str>"
290 if let ty::Adt(_def, subst) = found.kind() {
291 if subst.len() != 0 {
292 if let GenericArgKind::Type(ty) = subst[0].unpack() {
293 let peeled = ty.peel_refs().to_string();
294 if peeled == "String" {
295 let ref_cnt = ty.to_string().len() - peeled.len();
296 let result = format!(".map(|x| &*{}x)", "*".repeat(ref_cnt));
297 err.span_suggestion_verbose(
298 expr.span.shrink_to_hi(),
299 "try converting the passed type into a `&str`",
301 Applicability::MaybeIncorrect,
311 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
312 /// in the heap by calling `Box::new()`.
313 pub(in super::super) fn suggest_boxing_when_appropriate(
315 err: &mut DiagnosticBuilder<'_>,
316 expr: &hir::Expr<'_>,
320 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
321 // Do not suggest `Box::new` in const context.
324 if !expected.is_box() || found.is_box() {
327 let boxed_found = self.tcx.mk_box(found);
328 if self.can_coerce(boxed_found, expected) {
329 err.multipart_suggestion(
330 "store this in the heap by calling `Box::new`",
332 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
333 (expr.span.shrink_to_hi(), ")".to_string()),
335 Applicability::MachineApplicable,
338 "for more on the distinction between the stack and the heap, read \
339 https://doc.rust-lang.org/book/ch15-01-box.html, \
340 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
341 https://doc.rust-lang.org/std/boxed/index.html",
346 /// When encountering a closure that captures variables, where a FnPtr is expected,
347 /// suggest a non-capturing closure
348 pub(in super::super) fn suggest_no_capture_closure(
350 err: &mut DiagnosticBuilder<'_>,
354 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
355 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
356 // Report upto four upvars being captured to reduce the amount error messages
357 // reported back to the user.
358 let spans_and_labels = upvars
361 .map(|(var_hir_id, upvar)| {
362 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
363 let msg = format!("`{}` captured here", var_name);
366 .collect::<Vec<_>>();
368 let mut multi_span: MultiSpan =
369 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
370 for (sp, label) in spans_and_labels {
371 multi_span.push_span_label(sp, label);
375 "closures can only be coerced to `fn` types if they do not capture any variables"
381 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
382 #[instrument(skip(self, err))]
383 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
385 err: &mut DiagnosticBuilder<'_>,
386 expr: &hir::Expr<'_>,
392 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
393 // Do not suggest `Box::new` in const context.
396 let pin_did = self.tcx.lang_items().pin_type();
397 // This guards the `unwrap` and `mk_box` below.
398 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
401 let box_found = self.tcx.mk_box(found);
402 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
403 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
404 match expected.kind() {
405 ty::Adt(def, _) if Some(def.did) == pin_did => {
406 if self.can_coerce(pin_box_found, expected) {
407 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
409 ty::Adt(def, _) if def.is_box() => {
410 err.help("use `Box::pin`");
413 err.multipart_suggestion(
414 "you need to pin and box this expression",
416 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
417 (expr.span.shrink_to_hi(), ")".to_string()),
419 Applicability::MaybeIncorrect,
424 } else if self.can_coerce(pin_found, expected) {
426 ty::Adt(def, _) if def.is_box() => {
427 err.help("use `Box::pin`");
436 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
437 // Check if the parent expression is a call to Pin::new. If it
438 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
439 // can suggest Box::pin.
440 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
441 let fn_name = match self.tcx.hir().find(parent) {
442 Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) => fn_name,
446 ExprKind::Path(QPath::TypeRelative(
448 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
452 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
455 "use `Box::pin` to pin and box this expression",
456 "Box::pin".to_string(),
457 Applicability::MachineApplicable,
468 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
472 /// bar_that_returns_u32()
476 /// This routine checks if the return expression in a block would make sense on its own as a
477 /// statement and the return type has been left as default or has been specified as `()`. If so,
478 /// it suggests adding a semicolon.
479 fn suggest_missing_semicolon(
481 err: &mut DiagnosticBuilder<'_>,
482 expression: &'tcx hir::Expr<'tcx>,
485 if expected.is_unit() {
486 // `BlockTailExpression` only relevant if the tail expr would be
487 // useful on its own.
488 match expression.kind {
490 | ExprKind::MethodCall(..)
493 | ExprKind::Match(..)
494 | ExprKind::Block(..)
495 if expression.can_have_side_effects() =>
498 expression.span.shrink_to_hi(),
499 "consider using a semicolon here",
501 Applicability::MachineApplicable,
509 /// A possible error is to forget to add a return type that is needed:
513 /// bar_that_returns_u32()
517 /// This routine checks if the return type is left as default, the method is not part of an
518 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
520 pub(in super::super) fn suggest_missing_return_type(
522 err: &mut DiagnosticBuilder<'_>,
523 fn_decl: &hir::FnDecl<'_>,
529 // Only suggest changing the return type for methods that
530 // haven't set a return type at all (and aren't `fn main()` or an impl).
531 match (&fn_decl.output, found.is_suggestable(), can_suggest, expected.is_unit()) {
532 (&hir::FnRetTy::DefaultReturn(span), true, true, true) => {
535 "try adding a return type",
536 format!("-> {} ", self.resolve_vars_with_obligations(found)),
537 Applicability::MachineApplicable,
541 (&hir::FnRetTy::DefaultReturn(span), false, true, true) => {
542 err.span_label(span, "possibly return type missing here?");
545 (&hir::FnRetTy::DefaultReturn(span), _, false, true) => {
546 // `fn main()` must return `()`, do not suggest changing return type
547 err.span_label(span, "expected `()` because of default return type");
550 // expectation was caused by something else, not the default return
551 (&hir::FnRetTy::DefaultReturn(_), _, _, false) => false,
552 (&hir::FnRetTy::Return(ref ty), _, _, _) => {
553 // Only point to return type if the expected type is the return type, as if they
554 // are not, the expectation must have been caused by something else.
555 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
557 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
558 debug!("suggest_missing_return_type: return type {:?}", ty);
559 debug!("suggest_missing_return_type: expected type {:?}", ty);
560 let bound_vars = self.tcx.late_bound_vars(fn_id);
561 let ty = Binder::bind_with_vars(ty, bound_vars);
562 let ty = self.normalize_associated_types_in(sp, ty);
563 let ty = self.tcx.erase_late_bound_regions(ty);
564 if self.can_coerce(expected, ty) {
565 err.span_label(sp, format!("expected `{}` because of return type", expected));
566 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
574 /// check whether the return type is a generic type with a trait bound
575 /// only suggest this if the generic param is not present in the arguments
576 /// if this is true, hint them towards changing the return type to `impl Trait`
578 /// fn cant_name_it<T: Fn() -> u32>() -> T {
582 fn try_suggest_return_impl_trait(
584 err: &mut DiagnosticBuilder<'_>,
589 // Only apply the suggestion if:
590 // - the return type is a generic parameter
591 // - the generic param is not used as a fn param
592 // - the generic param has at least one bound
593 // - the generic param doesn't appear in any other bounds where it's not the Self type
595 // - Changing the return type to be `impl <all bounds>`
597 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
599 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
601 let fn_node = self.tcx.hir().find(fn_id);
603 let Some(hir::Node::Item(hir::Item {
606 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
607 hir::Generics { params, where_clause, .. },
611 })) = fn_node else { return };
613 let Some(expected_generic_param) = params.get(expected_ty_as_param.index as usize) else { return };
615 // get all where BoundPredicates here, because they are used in to cases below
616 let where_predicates = where_clause
619 .filter_map(|p| match p {
620 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
625 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
626 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
631 .map(|(ty, bounds)| match ty.kind() {
632 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
633 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
634 _ => match ty.contains(expected) {
639 .collect::<Result<Vec<_>, _>>();
641 let Ok(where_predicates) = where_predicates else { return };
643 // now get all predicates in the same types as the where bounds, so we can chain them
644 let predicates_from_where =
645 where_predicates.iter().flatten().map(|bounds| bounds.iter()).flatten();
647 // extract all bounds from the source code using their spans
648 let all_matching_bounds_strs = expected_generic_param
651 .chain(predicates_from_where)
652 .filter_map(|bound| match bound {
653 GenericBound::Trait(_, _) => {
654 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
658 .collect::<Vec<String>>();
660 if all_matching_bounds_strs.len() == 0 {
664 let all_bounds_str = all_matching_bounds_strs.join(" + ");
666 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
667 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
668 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
671 if ty_param_used_in_fn_params {
677 "consider using an impl return type",
678 format!("impl {}", all_bounds_str),
679 Applicability::MaybeIncorrect,
683 pub(in super::super) fn suggest_missing_break_or_return_expr(
685 err: &mut DiagnosticBuilder<'_>,
686 expr: &'tcx hir::Expr<'tcx>,
687 fn_decl: &hir::FnDecl<'_>,
693 if !expected.is_unit() {
696 let found = self.resolve_vars_with_obligations(found);
698 let in_loop = self.is_loop(id)
699 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
701 let in_local_statement = self.is_local_statement(id)
706 .any(|(parent_id, _)| self.is_local_statement(parent_id));
708 if in_loop && in_local_statement {
709 err.multipart_suggestion(
710 "you might have meant to break the loop with this value",
712 (expr.span.shrink_to_lo(), "break ".to_string()),
713 (expr.span.shrink_to_hi(), ";".to_string()),
715 Applicability::MaybeIncorrect,
720 if let hir::FnRetTy::Return(ty) = fn_decl.output {
721 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
722 let bound_vars = self.tcx.late_bound_vars(fn_id);
723 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
724 let ty = self.normalize_associated_types_in(expr.span, ty);
725 let ty = match self.tcx.asyncness(fn_id.owner) {
726 hir::IsAsync::Async => self
730 infcx.get_impl_future_output_ty(ty).unwrap_or_else(|| {
732 fn_decl.output.span(),
733 "failed to get output type of async function"
738 hir::IsAsync::NotAsync => ty,
740 if self.can_coerce(found, ty) {
741 err.multipart_suggestion(
742 "you might have meant to return this value",
744 (expr.span.shrink_to_lo(), "return ".to_string()),
745 (expr.span.shrink_to_hi(), ";".to_string()),
747 Applicability::MaybeIncorrect,
753 pub(in super::super) fn suggest_missing_parentheses(
755 err: &mut DiagnosticBuilder<'_>,
756 expr: &hir::Expr<'_>,
758 let sp = self.tcx.sess.source_map().start_point(expr.span);
759 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
760 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
761 self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp);
765 fn is_loop(&self, id: hir::HirId) -> bool {
766 let node = self.tcx.hir().get(id);
767 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
770 fn is_local_statement(&self, id: hir::HirId) -> bool {
771 let node = self.tcx.hir().get(id);
772 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))