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 Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
445 ExprKind::Path(QPath::TypeRelative(
447 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
451 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
454 "use `Box::pin` to pin and box this expression",
455 "Box::pin".to_string(),
456 Applicability::MachineApplicable,
467 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
471 /// bar_that_returns_u32()
475 /// This routine checks if the return expression in a block would make sense on its own as a
476 /// statement and the return type has been left as default or has been specified as `()`. If so,
477 /// it suggests adding a semicolon.
478 fn suggest_missing_semicolon(
480 err: &mut DiagnosticBuilder<'_>,
481 expression: &'tcx hir::Expr<'tcx>,
484 if expected.is_unit() {
485 // `BlockTailExpression` only relevant if the tail expr would be
486 // useful on its own.
487 match expression.kind {
489 | ExprKind::MethodCall(..)
492 | ExprKind::Match(..)
493 | ExprKind::Block(..)
494 if expression.can_have_side_effects() =>
497 expression.span.shrink_to_hi(),
498 "consider using a semicolon here",
500 Applicability::MachineApplicable,
508 /// A possible error is to forget to add a return type that is needed:
512 /// bar_that_returns_u32()
516 /// This routine checks if the return type is left as default, the method is not part of an
517 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
519 pub(in super::super) fn suggest_missing_return_type(
521 err: &mut DiagnosticBuilder<'_>,
522 fn_decl: &hir::FnDecl<'_>,
528 // Only suggest changing the return type for methods that
529 // haven't set a return type at all (and aren't `fn main()` or an impl).
530 match (&fn_decl.output, found.is_suggestable(), can_suggest, expected.is_unit()) {
531 (&hir::FnRetTy::DefaultReturn(span), true, true, true) => {
534 "try adding a return type",
535 format!("-> {} ", self.resolve_vars_with_obligations(found)),
536 Applicability::MachineApplicable,
540 (&hir::FnRetTy::DefaultReturn(span), false, true, true) => {
541 err.span_label(span, "possibly return type missing here?");
544 (&hir::FnRetTy::DefaultReturn(span), _, false, true) => {
545 // `fn main()` must return `()`, do not suggest changing return type
546 err.span_label(span, "expected `()` because of default return type");
549 // expectation was caused by something else, not the default return
550 (&hir::FnRetTy::DefaultReturn(_), _, _, false) => false,
551 (&hir::FnRetTy::Return(ref ty), _, _, _) => {
552 // Only point to return type if the expected type is the return type, as if they
553 // are not, the expectation must have been caused by something else.
554 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
556 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
557 debug!("suggest_missing_return_type: return type {:?}", ty);
558 debug!("suggest_missing_return_type: expected type {:?}", ty);
559 let bound_vars = self.tcx.late_bound_vars(fn_id);
560 let ty = Binder::bind_with_vars(ty, bound_vars);
561 let ty = self.normalize_associated_types_in(sp, ty);
562 let ty = self.tcx.erase_late_bound_regions(ty);
563 if self.can_coerce(expected, ty) {
564 err.span_label(sp, format!("expected `{}` because of return type", expected));
565 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
573 /// check whether the return type is a generic type with a trait bound
574 /// only suggest this if the generic param is not present in the arguments
575 /// if this is true, hint them towards changing the return type to `impl Trait`
577 /// fn cant_name_it<T: Fn() -> u32>() -> T {
581 fn try_suggest_return_impl_trait(
583 err: &mut DiagnosticBuilder<'_>,
588 // Only apply the suggestion if:
589 // - the return type is a generic parameter
590 // - the generic param is not used as a fn param
591 // - the generic param has at least one bound
592 // - the generic param doesn't appear in any other bounds where it's not the Self type
594 // - Changing the return type to be `impl <all bounds>`
596 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
598 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
600 let fn_node = self.tcx.hir().find(fn_id);
602 let Some(hir::Node::Item(hir::Item {
605 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
606 hir::Generics { params, where_clause, .. },
610 })) = fn_node else { return };
612 let Some(expected_generic_param) = params.get(expected_ty_as_param.index as usize) else { return };
614 // get all where BoundPredicates here, because they are used in to cases below
615 let where_predicates = where_clause
618 .filter_map(|p| match p {
619 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
624 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
625 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
630 .map(|(ty, bounds)| match ty.kind() {
631 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
632 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
633 _ => match ty.contains(expected) {
638 .collect::<Result<Vec<_>, _>>();
640 let Ok(where_predicates) = where_predicates else { return };
642 // now get all predicates in the same types as the where bounds, so we can chain them
643 let predicates_from_where =
644 where_predicates.iter().flatten().map(|bounds| bounds.iter()).flatten();
646 // extract all bounds from the source code using their spans
647 let all_matching_bounds_strs = expected_generic_param
650 .chain(predicates_from_where)
651 .filter_map(|bound| match bound {
652 GenericBound::Trait(_, _) => {
653 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
657 .collect::<Vec<String>>();
659 if all_matching_bounds_strs.len() == 0 {
663 let all_bounds_str = all_matching_bounds_strs.join(" + ");
665 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
666 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
667 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
670 if ty_param_used_in_fn_params {
676 "consider using an impl return type",
677 format!("impl {}", all_bounds_str),
678 Applicability::MaybeIncorrect,
682 pub(in super::super) fn suggest_missing_break_or_return_expr(
684 err: &mut DiagnosticBuilder<'_>,
685 expr: &'tcx hir::Expr<'tcx>,
686 fn_decl: &hir::FnDecl<'_>,
692 if !expected.is_unit() {
695 let found = self.resolve_vars_with_obligations(found);
697 let in_loop = self.is_loop(id)
698 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
700 let in_local_statement = self.is_local_statement(id)
705 .any(|(parent_id, _)| self.is_local_statement(parent_id));
707 if in_loop && in_local_statement {
708 err.multipart_suggestion(
709 "you might have meant to break the loop with this value",
711 (expr.span.shrink_to_lo(), "break ".to_string()),
712 (expr.span.shrink_to_hi(), ";".to_string()),
714 Applicability::MaybeIncorrect,
719 if let hir::FnRetTy::Return(ty) = fn_decl.output {
720 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
721 let bound_vars = self.tcx.late_bound_vars(fn_id);
722 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
723 let ty = self.normalize_associated_types_in(expr.span, ty);
724 let ty = match self.tcx.asyncness(fn_id.owner) {
725 hir::IsAsync::Async => self
729 infcx.get_impl_future_output_ty(ty).unwrap_or_else(|| {
731 fn_decl.output.span(),
732 "failed to get output type of async function"
737 hir::IsAsync::NotAsync => ty,
739 if self.can_coerce(found, ty) {
740 err.multipart_suggestion(
741 "you might have meant to return this value",
743 (expr.span.shrink_to_lo(), "return ".to_string()),
744 (expr.span.shrink_to_hi(), ";".to_string()),
746 Applicability::MaybeIncorrect,
752 pub(in super::super) fn suggest_missing_parentheses(
754 err: &mut DiagnosticBuilder<'_>,
755 expr: &hir::Expr<'_>,
757 let sp = self.tcx.sess.source_map().start_point(expr.span);
758 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
759 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
760 self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp);
764 fn is_loop(&self, id: hir::HirId) -> bool {
765 let node = self.tcx.hir().get(id);
766 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
769 fn is_local_statement(&self, id: hir::HirId) -> bool {
770 let node = self.tcx.hir().get(id);
771 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))