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;
11 use rustc_hir::{Expr, ExprKind, ItemKind, Node, Path, QPath, Stmt, StmtKind, TyKind};
12 use rustc_infer::infer;
13 use rustc_middle::lint::in_external_macro;
14 use rustc_middle::ty::{self, Binder, Ty};
15 use rustc_span::symbol::{kw, sym};
19 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
20 pub(in super::super) fn suggest_semicolon_at_end(
23 err: &mut DiagnosticBuilder<'_>,
25 err.span_suggestion_short(
27 "consider using a semicolon here",
29 Applicability::MachineApplicable,
33 /// On implicit return expressions with mismatched types, provides the following suggestions:
35 /// - Points out the method's return type as the reason for the expected type.
36 /// - Possible missing semicolon.
37 /// - Possible missing return type if the return type is the default, and not `fn main()`.
38 pub fn suggest_mismatched_types_on_tail(
40 err: &mut DiagnosticBuilder<'_>,
41 expr: &'tcx hir::Expr<'tcx>,
46 let expr = expr.peel_drop_temps();
47 // If the expression is from an external macro, then do not suggest
48 // adding a semicolon, because there's nowhere to put it.
50 if expr.can_have_side_effects() && !in_external_macro(self.tcx.sess, expr.span) {
51 self.suggest_missing_semicolon(err, expr, expected);
53 let mut pointing_at_return_type = false;
54 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
55 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
56 pointing_at_return_type = self.suggest_missing_return_type(
64 self.suggest_missing_break_or_return_expr(
65 err, expr, &fn_decl, expected, found, blk_id, fn_id,
68 pointing_at_return_type
71 /// When encountering an fn-like ctor that needs to unify with a value, check whether calling
72 /// the ctor would successfully solve the type mismatch and if so, suggest it:
74 /// fn foo(x: usize) -> usize { x }
75 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
79 err: &mut DiagnosticBuilder<'_>,
84 let hir = self.tcx.hir();
85 let (def_id, sig) = match *found.kind() {
86 ty::FnDef(def_id, _) => (def_id, found.fn_sig(self.tcx)),
87 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig()),
91 let sig = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, sig).0;
92 let sig = self.normalize_associated_types_in(expr.span, sig);
93 if self.can_coerce(sig.output(), expected) {
94 let (mut sugg_call, applicability) = if sig.inputs().is_empty() {
95 (String::new(), Applicability::MachineApplicable)
97 ("...".to_string(), Applicability::HasPlaceholders)
99 let mut msg = "call this function";
100 match hir.get_if_local(def_id) {
102 Node::Item(hir::Item { kind: ItemKind::Fn(.., body_id), .. })
103 | Node::ImplItem(hir::ImplItem {
104 kind: hir::ImplItemKind::Fn(_, body_id), ..
106 | Node::TraitItem(hir::TraitItem {
107 kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Provided(body_id)),
111 let body = hir.body(*body_id);
115 .map(|param| match ¶m.pat.kind {
116 hir::PatKind::Binding(_, _, ident, None)
117 if ident.name != kw::SelfLower =>
121 _ => "_".to_string(),
126 Some(Node::Expr(hir::Expr {
127 kind: ExprKind::Closure(_, _, body_id, _, _),
128 span: full_closure_span,
131 if *full_closure_span == expr.span {
134 msg = "call this closure";
135 let body = hir.body(*body_id);
139 .map(|param| match ¶m.pat.kind {
140 hir::PatKind::Binding(_, _, ident, None)
141 if ident.name != kw::SelfLower =>
145 _ => "_".to_string(),
150 Some(Node::Ctor(hir::VariantData::Tuple(fields, _))) => {
151 sugg_call = fields.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
152 match def_id.as_local().map(|def_id| hir.def_kind(def_id)) {
153 Some(DefKind::Ctor(hir::def::CtorOf::Variant, _)) => {
154 msg = "instantiate this tuple variant";
156 Some(DefKind::Ctor(CtorOf::Struct, _)) => {
157 msg = "instantiate this tuple struct";
162 Some(Node::ForeignItem(hir::ForeignItem {
163 kind: hir::ForeignItemKind::Fn(_, idents, _),
169 if ident.name != kw::SelfLower {
178 Some(Node::TraitItem(hir::TraitItem {
179 kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Required(idents)),
185 if ident.name != kw::SelfLower {
196 err.span_suggestion_verbose(
197 expr.span.shrink_to_hi(),
198 &format!("use parentheses to {}", msg),
199 format!("({})", sugg_call),
207 pub fn suggest_deref_ref_or_into(
209 err: &mut DiagnosticBuilder<'_>,
210 expr: &hir::Expr<'_>,
213 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
215 let expr = expr.peel_blocks();
216 if let Some((sp, msg, suggestion, applicability, verbose)) =
217 self.check_ref(expr, found, expected)
220 err.span_suggestion_verbose(sp, msg, suggestion, applicability);
222 err.span_suggestion(sp, msg, suggestion, applicability);
224 } else if let (ty::FnDef(def_id, ..), true) =
225 (&found.kind(), self.suggest_fn_call(err, expr, expected, found))
227 if let Some(sp) = self.tcx.hir().span_if_local(*def_id) {
228 let sp = self.sess().source_map().guess_head_span(sp);
229 err.span_label(sp, &format!("{} defined here", found));
231 } else if !self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
232 let is_struct_pat_shorthand_field =
233 self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, expr.span);
234 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
235 if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) {
236 let mut suggestions = iter::zip(iter::repeat(&expr_text), &methods)
237 .filter_map(|(receiver, method)| {
238 let method_call = format!(".{}()", method.ident);
239 if receiver.ends_with(&method_call) {
240 None // do not suggest code that is already there (#53348)
242 let method_call_list = [".to_vec()", ".to_string()"];
243 let mut sugg = if receiver.ends_with(".clone()")
244 && method_call_list.contains(&method_call.as_str())
246 let max_len = receiver.rfind('.').unwrap();
249 format!("{}{}", &receiver[..max_len], method_call),
252 if expr.precedence().order() < ExprPrecedence::MethodCall.order() {
254 (expr.span.shrink_to_lo(), "(".to_string()),
255 (expr.span.shrink_to_hi(), format!("){}", method_call)),
258 vec![(expr.span.shrink_to_hi(), method_call)]
261 if is_struct_pat_shorthand_field {
264 (expr.span.shrink_to_lo(), format!("{}: ", receiver)),
271 if suggestions.peek().is_some() {
272 err.multipart_suggestions(
273 "try using a conversion method",
275 Applicability::MaybeIncorrect,
282 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
283 /// in the heap by calling `Box::new()`.
284 pub(in super::super) fn suggest_boxing_when_appropriate(
286 err: &mut DiagnosticBuilder<'_>,
287 expr: &hir::Expr<'_>,
291 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
292 // Do not suggest `Box::new` in const context.
295 if !expected.is_box() || found.is_box() {
298 let boxed_found = self.tcx.mk_box(found);
299 if self.can_coerce(boxed_found, expected) {
300 err.multipart_suggestion(
301 "store this in the heap by calling `Box::new`",
303 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
304 (expr.span.shrink_to_hi(), ")".to_string()),
306 Applicability::MachineApplicable,
309 "for more on the distinction between the stack and the heap, read \
310 https://doc.rust-lang.org/book/ch15-01-box.html, \
311 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
312 https://doc.rust-lang.org/std/boxed/index.html",
317 /// When encountering a closure that captures variables, where a FnPtr is expected,
318 /// suggest a non-capturing closure
319 pub(in super::super) fn suggest_no_capture_closure(
321 err: &mut DiagnosticBuilder<'_>,
325 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
326 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
327 // Report upto four upvars being captured to reduce the amount error messages
328 // reported back to the user.
329 let spans_and_labels = upvars
332 .map(|(var_hir_id, upvar)| {
333 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
334 let msg = format!("`{}` captured here", var_name);
337 .collect::<Vec<_>>();
339 let mut multi_span: MultiSpan =
340 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
341 for (sp, label) in spans_and_labels {
342 multi_span.push_span_label(sp, label);
346 "closures can only be coerced to `fn` types if they do not capture any variables"
352 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
353 #[instrument(skip(self, err))]
354 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
356 err: &mut DiagnosticBuilder<'_>,
357 expr: &hir::Expr<'_>,
363 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
364 // Do not suggest `Box::new` in const context.
367 let pin_did = self.tcx.lang_items().pin_type();
368 // This guards the `unwrap` and `mk_box` below.
369 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
372 let box_found = self.tcx.mk_box(found);
373 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
374 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
375 match expected.kind() {
376 ty::Adt(def, _) if Some(def.did) == pin_did => {
377 if self.can_coerce(pin_box_found, expected) {
378 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
380 ty::Adt(def, _) if def.is_box() => {
381 err.help("use `Box::pin`");
384 err.multipart_suggestion(
385 "you need to pin and box this expression",
387 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
388 (expr.span.shrink_to_hi(), ")".to_string()),
390 Applicability::MaybeIncorrect,
395 } else if self.can_coerce(pin_found, expected) {
397 ty::Adt(def, _) if def.is_box() => {
398 err.help("use `Box::pin`");
407 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
408 // Check if the parent expression is a call to Pin::new. If it
409 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
410 // can suggest Box::pin.
411 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
412 let fn_name = match self.tcx.hir().find(parent) {
413 Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) => fn_name,
417 ExprKind::Path(QPath::TypeRelative(
419 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
423 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
426 "use `Box::pin` to pin and box this expression",
427 "Box::pin".to_string(),
428 Applicability::MachineApplicable,
439 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
443 /// bar_that_returns_u32()
447 /// This routine checks if the return expression in a block would make sense on its own as a
448 /// statement and the return type has been left as default or has been specified as `()`. If so,
449 /// it suggests adding a semicolon.
450 fn suggest_missing_semicolon(
452 err: &mut DiagnosticBuilder<'_>,
453 expression: &'tcx hir::Expr<'tcx>,
456 if expected.is_unit() {
457 // `BlockTailExpression` only relevant if the tail expr would be
458 // useful on its own.
459 match expression.kind {
461 | ExprKind::MethodCall(..)
464 | ExprKind::Match(..)
465 | ExprKind::Block(..)
466 if expression.can_have_side_effects() =>
469 expression.span.shrink_to_hi(),
470 "consider using a semicolon here",
472 Applicability::MachineApplicable,
480 /// A possible error is to forget to add a return type that is needed:
484 /// bar_that_returns_u32()
488 /// This routine checks if the return type is left as default, the method is not part of an
489 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
491 pub(in super::super) fn suggest_missing_return_type(
493 err: &mut DiagnosticBuilder<'_>,
494 fn_decl: &hir::FnDecl<'_>,
500 // Only suggest changing the return type for methods that
501 // haven't set a return type at all (and aren't `fn main()` or an impl).
502 match (&fn_decl.output, found.is_suggestable(), can_suggest, expected.is_unit()) {
503 (&hir::FnRetTy::DefaultReturn(span), true, true, true) => {
506 "try adding a return type",
507 format!("-> {} ", self.resolve_vars_with_obligations(found)),
508 Applicability::MachineApplicable,
512 (&hir::FnRetTy::DefaultReturn(span), false, true, true) => {
513 err.span_label(span, "possibly return type missing here?");
516 (&hir::FnRetTy::DefaultReturn(span), _, false, true) => {
517 // `fn main()` must return `()`, do not suggest changing return type
518 err.span_label(span, "expected `()` because of default return type");
521 // expectation was caused by something else, not the default return
522 (&hir::FnRetTy::DefaultReturn(_), _, _, false) => false,
523 (&hir::FnRetTy::Return(ref ty), _, _, _) => {
524 // Only point to return type if the expected type is the return type, as if they
525 // are not, the expectation must have been caused by something else.
526 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
528 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
529 debug!("suggest_missing_return_type: return type {:?}", ty);
530 debug!("suggest_missing_return_type: expected type {:?}", ty);
531 let bound_vars = self.tcx.late_bound_vars(fn_id);
532 let ty = Binder::bind_with_vars(ty, bound_vars);
533 let ty = self.normalize_associated_types_in(sp, ty);
534 let ty = self.tcx.erase_late_bound_regions(ty);
535 if self.can_coerce(expected, ty) {
536 err.span_label(sp, format!("expected `{}` because of return type", expected));
544 pub(in super::super) fn suggest_missing_break_or_return_expr(
546 err: &mut DiagnosticBuilder<'_>,
547 expr: &'tcx hir::Expr<'tcx>,
548 fn_decl: &hir::FnDecl<'_>,
554 if !expected.is_unit() {
557 let found = self.resolve_vars_with_obligations(found);
559 let in_loop = self.is_loop(id)
560 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
562 let in_local_statement = self.is_local_statement(id)
567 .any(|(parent_id, _)| self.is_local_statement(parent_id));
569 if in_loop && in_local_statement {
570 err.multipart_suggestion(
571 "you might have meant to break the loop with this value",
573 (expr.span.shrink_to_lo(), "break ".to_string()),
574 (expr.span.shrink_to_hi(), ";".to_string()),
576 Applicability::MaybeIncorrect,
581 if let hir::FnRetTy::Return(ty) = fn_decl.output {
582 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
583 let bound_vars = self.tcx.late_bound_vars(fn_id);
584 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
585 let ty = self.normalize_associated_types_in(expr.span, ty);
586 if self.can_coerce(found, ty) {
587 err.multipart_suggestion(
588 "you might have meant to return this value",
590 (expr.span.shrink_to_lo(), "return ".to_string()),
591 (expr.span.shrink_to_hi(), ";".to_string()),
593 Applicability::MaybeIncorrect,
599 pub(in super::super) fn suggest_missing_parentheses(
601 err: &mut DiagnosticBuilder<'_>,
602 expr: &hir::Expr<'_>,
604 let sp = self.tcx.sess.source_map().start_point(expr.span);
605 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
606 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
607 self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp);
611 fn is_loop(&self, id: hir::HirId) -> bool {
612 let node = self.tcx.hir().get(id);
613 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
616 fn is_local_statement(&self, id: hir::HirId) -> bool {
617 let node = self.tcx.hir().get(id);
618 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))