]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs
Rollup merge of #86763 - JohnTitor:test-63355, r=oli-obk
[rust.git] / compiler / rustc_typeck / src / check / fn_ctxt / suggestions.rs
1 use super::FnCtxt;
2 use crate::astconv::AstConv;
3
4 use rustc_ast::util::parser::ExprPrecedence;
5 use rustc_span::{self, MultiSpan, Span};
6
7 use rustc_errors::{Applicability, DiagnosticBuilder};
8 use rustc_hir as hir;
9 use rustc_hir::def::{CtorOf, DefKind};
10 use rustc_hir::lang_items::LangItem;
11 use rustc_hir::{Expr, ExprKind, ItemKind, Node, Stmt, StmtKind};
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;
16
17 use std::iter;
18
19 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
20     pub(in super::super) fn suggest_semicolon_at_end(
21         &self,
22         span: Span,
23         err: &mut DiagnosticBuilder<'_>,
24     ) {
25         err.span_suggestion_short(
26             span.shrink_to_hi(),
27             "consider using a semicolon here",
28             ";".to_string(),
29             Applicability::MachineApplicable,
30         );
31     }
32
33     /// On implicit return expressions with mismatched types, provides the following suggestions:
34     ///
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(
39         &self,
40         err: &mut DiagnosticBuilder<'_>,
41         expr: &'tcx hir::Expr<'tcx>,
42         expected: Ty<'tcx>,
43         found: Ty<'tcx>,
44         blk_id: hir::HirId,
45     ) -> bool {
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.
49         // See issue #81943.
50         if expr.can_have_side_effects() && !in_external_macro(self.tcx.sess, expr.span) {
51             self.suggest_missing_semicolon(err, expr, expected);
52         }
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(
57                 err,
58                 &fn_decl,
59                 expected,
60                 found,
61                 can_suggest,
62                 fn_id,
63             );
64             self.suggest_missing_break_or_return_expr(
65                 err, expr, &fn_decl, expected, found, blk_id, fn_id,
66             );
67         }
68         pointing_at_return_type
69     }
70
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:
73     /// ```
74     /// fn foo(x: usize) -> usize { x }
75     /// let x: usize = foo;  // suggest calling the `foo` function: `foo(42)`
76     /// ```
77     fn suggest_fn_call(
78         &self,
79         err: &mut DiagnosticBuilder<'_>,
80         expr: &hir::Expr<'_>,
81         expected: Ty<'tcx>,
82         found: Ty<'tcx>,
83     ) -> bool {
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()),
88             _ => return false,
89         };
90
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)
96             } else {
97                 ("...".to_string(), Applicability::HasPlaceholders)
98             };
99             let mut msg = "call this function";
100             match hir.get_if_local(def_id) {
101                 Some(
102                     Node::Item(hir::Item { kind: ItemKind::Fn(.., body_id), .. })
103                     | Node::ImplItem(hir::ImplItem {
104                         kind: hir::ImplItemKind::Fn(_, body_id), ..
105                     })
106                     | Node::TraitItem(hir::TraitItem {
107                         kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Provided(body_id)),
108                         ..
109                     }),
110                 ) => {
111                     let body = hir.body(*body_id);
112                     sugg_call = body
113                         .params
114                         .iter()
115                         .map(|param| match &param.pat.kind {
116                             hir::PatKind::Binding(_, _, ident, None)
117                                 if ident.name != kw::SelfLower =>
118                             {
119                                 ident.to_string()
120                             }
121                             _ => "_".to_string(),
122                         })
123                         .collect::<Vec<_>>()
124                         .join(", ");
125                 }
126                 Some(Node::Expr(hir::Expr {
127                     kind: ExprKind::Closure(_, _, body_id, _, _),
128                     span: full_closure_span,
129                     ..
130                 })) => {
131                     if *full_closure_span == expr.span {
132                         return false;
133                     }
134                     msg = "call this closure";
135                     let body = hir.body(*body_id);
136                     sugg_call = body
137                         .params
138                         .iter()
139                         .map(|param| match &param.pat.kind {
140                             hir::PatKind::Binding(_, _, ident, None)
141                                 if ident.name != kw::SelfLower =>
142                             {
143                                 ident.to_string()
144                             }
145                             _ => "_".to_string(),
146                         })
147                         .collect::<Vec<_>>()
148                         .join(", ");
149                 }
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";
155                         }
156                         Some(DefKind::Ctor(CtorOf::Struct, _)) => {
157                             msg = "instantiate this tuple struct";
158                         }
159                         _ => {}
160                     }
161                 }
162                 Some(Node::ForeignItem(hir::ForeignItem {
163                     kind: hir::ForeignItemKind::Fn(_, idents, _),
164                     ..
165                 })) => {
166                     sugg_call = idents
167                         .iter()
168                         .map(|ident| {
169                             if ident.name != kw::SelfLower {
170                                 ident.to_string()
171                             } else {
172                                 "_".to_string()
173                             }
174                         })
175                         .collect::<Vec<_>>()
176                         .join(", ")
177                 }
178                 Some(Node::TraitItem(hir::TraitItem {
179                     kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Required(idents)),
180                     ..
181                 })) => {
182                     sugg_call = idents
183                         .iter()
184                         .map(|ident| {
185                             if ident.name != kw::SelfLower {
186                                 ident.to_string()
187                             } else {
188                                 "_".to_string()
189                             }
190                         })
191                         .collect::<Vec<_>>()
192                         .join(", ")
193                 }
194                 _ => {}
195             }
196             err.span_suggestion_verbose(
197                 expr.span.shrink_to_hi(),
198                 &format!("use parentheses to {}", msg),
199                 format!("({})", sugg_call),
200                 applicability,
201             );
202             return true;
203         }
204         false
205     }
206
207     pub fn suggest_deref_ref_or_into(
208         &self,
209         err: &mut DiagnosticBuilder<'_>,
210         expr: &hir::Expr<'_>,
211         expected: Ty<'tcx>,
212         found: Ty<'tcx>,
213         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
214     ) {
215         let expr = expr.peel_blocks();
216         if let Some((sp, msg, suggestion, applicability)) = self.check_ref(expr, found, expected) {
217             err.span_suggestion(sp, msg, suggestion, applicability);
218         } else if let (ty::FnDef(def_id, ..), true) =
219             (&found.kind(), self.suggest_fn_call(err, expr, expected, found))
220         {
221             if let Some(sp) = self.tcx.hir().span_if_local(*def_id) {
222                 let sp = self.sess().source_map().guess_head_span(sp);
223                 err.span_label(sp, &format!("{} defined here", found));
224             }
225         } else if !self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
226             let is_struct_pat_shorthand_field =
227                 self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, expr.span);
228             let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
229             if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) {
230                 let mut suggestions = iter::zip(iter::repeat(&expr_text), &methods)
231                     .filter_map(|(receiver, method)| {
232                         let method_call = format!(".{}()", method.ident);
233                         if receiver.ends_with(&method_call) {
234                             None // do not suggest code that is already there (#53348)
235                         } else {
236                             let method_call_list = [".to_vec()", ".to_string()"];
237                             let sugg = if receiver.ends_with(".clone()")
238                                 && method_call_list.contains(&method_call.as_str())
239                             {
240                                 let max_len = receiver.rfind('.').unwrap();
241                                 format!("{}{}", &receiver[..max_len], method_call)
242                             } else {
243                                 if expr.precedence().order() < ExprPrecedence::MethodCall.order() {
244                                     format!("({}){}", receiver, method_call)
245                                 } else {
246                                     format!("{}{}", receiver, method_call)
247                                 }
248                             };
249                             Some(if is_struct_pat_shorthand_field {
250                                 format!("{}: {}", receiver, sugg)
251                             } else {
252                                 sugg
253                             })
254                         }
255                     })
256                     .peekable();
257                 if suggestions.peek().is_some() {
258                     err.span_suggestions(
259                         expr.span,
260                         "try using a conversion method",
261                         suggestions,
262                         Applicability::MaybeIncorrect,
263                     );
264                 }
265             }
266         }
267     }
268
269     /// When encountering the expected boxed value allocated in the stack, suggest allocating it
270     /// in the heap by calling `Box::new()`.
271     pub(in super::super) fn suggest_boxing_when_appropriate(
272         &self,
273         err: &mut DiagnosticBuilder<'_>,
274         expr: &hir::Expr<'_>,
275         expected: Ty<'tcx>,
276         found: Ty<'tcx>,
277     ) {
278         if self.tcx.hir().is_inside_const_context(expr.hir_id) {
279             // Do not suggest `Box::new` in const context.
280             return;
281         }
282         if !expected.is_box() || found.is_box() {
283             return;
284         }
285         let boxed_found = self.tcx.mk_box(found);
286         if let (true, Ok(snippet)) = (
287             self.can_coerce(boxed_found, expected),
288             self.sess().source_map().span_to_snippet(expr.span),
289         ) {
290             err.span_suggestion(
291                 expr.span,
292                 "store this in the heap by calling `Box::new`",
293                 format!("Box::new({})", snippet),
294                 Applicability::MachineApplicable,
295             );
296             err.note(
297                 "for more on the distinction between the stack and the heap, read \
298                  https://doc.rust-lang.org/book/ch15-01-box.html, \
299                  https://doc.rust-lang.org/rust-by-example/std/box.html, and \
300                  https://doc.rust-lang.org/std/boxed/index.html",
301             );
302         }
303     }
304
305     /// When encountering a closure that captures variables, where a FnPtr is expected,
306     /// suggest a non-capturing closure
307     pub(in super::super) fn suggest_no_capture_closure(
308         &self,
309         err: &mut DiagnosticBuilder<'_>,
310         expected: Ty<'tcx>,
311         found: Ty<'tcx>,
312     ) {
313         if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
314             if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
315                 // Report upto four upvars being captured to reduce the amount error messages
316                 // reported back to the user.
317                 let spans_and_labels = upvars
318                     .iter()
319                     .take(4)
320                     .map(|(var_hir_id, upvar)| {
321                         let var_name = self.tcx.hir().name(*var_hir_id).to_string();
322                         let msg = format!("`{}` captured here", var_name);
323                         (upvar.span, msg)
324                     })
325                     .collect::<Vec<_>>();
326
327                 let mut multi_span: MultiSpan =
328                     spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
329                 for (sp, label) in spans_and_labels {
330                     multi_span.push_span_label(sp, label);
331                 }
332                 err.span_note(multi_span, "closures can only be coerced to `fn` types if they do not capture any variables");
333             }
334         }
335     }
336
337     /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
338     pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
339         &self,
340         err: &mut DiagnosticBuilder<'_>,
341         expr: &hir::Expr<'_>,
342         expected: Ty<'tcx>,
343         found: Ty<'tcx>,
344     ) -> bool {
345         // Handle #68197.
346
347         if self.tcx.hir().is_inside_const_context(expr.hir_id) {
348             // Do not suggest `Box::new` in const context.
349             return false;
350         }
351         let pin_did = self.tcx.lang_items().pin_type();
352         match expected.kind() {
353             ty::Adt(def, _) if Some(def.did) != pin_did => return false,
354             // This guards the `unwrap` and `mk_box` below.
355             _ if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() => return false,
356             _ => {}
357         }
358         let boxed_found = self.tcx.mk_box(found);
359         let new_found = self.tcx.mk_lang_item(boxed_found, LangItem::Pin).unwrap();
360         if let (true, Ok(snippet)) = (
361             self.can_coerce(new_found, expected),
362             self.sess().source_map().span_to_snippet(expr.span),
363         ) {
364             match found.kind() {
365                 ty::Adt(def, _) if def.is_box() => {
366                     err.help("use `Box::pin`");
367                 }
368                 _ => {
369                     err.span_suggestion(
370                         expr.span,
371                         "you need to pin and box this expression",
372                         format!("Box::pin({})", snippet),
373                         Applicability::MachineApplicable,
374                     );
375                 }
376             }
377             true
378         } else {
379             false
380         }
381     }
382
383     /// A common error is to forget to add a semicolon at the end of a block, e.g.,
384     ///
385     /// ```
386     /// fn foo() {
387     ///     bar_that_returns_u32()
388     /// }
389     /// ```
390     ///
391     /// This routine checks if the return expression in a block would make sense on its own as a
392     /// statement and the return type has been left as default or has been specified as `()`. If so,
393     /// it suggests adding a semicolon.
394     fn suggest_missing_semicolon(
395         &self,
396         err: &mut DiagnosticBuilder<'_>,
397         expression: &'tcx hir::Expr<'tcx>,
398         expected: Ty<'tcx>,
399     ) {
400         if expected.is_unit() {
401             // `BlockTailExpression` only relevant if the tail expr would be
402             // useful on its own.
403             match expression.kind {
404                 ExprKind::Call(..)
405                 | ExprKind::MethodCall(..)
406                 | ExprKind::Loop(..)
407                 | ExprKind::If(..)
408                 | ExprKind::Match(..)
409                 | ExprKind::Block(..)
410                     if expression.can_have_side_effects() =>
411                 {
412                     err.span_suggestion(
413                         expression.span.shrink_to_hi(),
414                         "consider using a semicolon here",
415                         ";".to_string(),
416                         Applicability::MachineApplicable,
417                     );
418                 }
419                 _ => (),
420             }
421         }
422     }
423
424     /// A possible error is to forget to add a return type that is needed:
425     ///
426     /// ```
427     /// fn foo() {
428     ///     bar_that_returns_u32()
429     /// }
430     /// ```
431     ///
432     /// This routine checks if the return type is left as default, the method is not part of an
433     /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
434     /// type.
435     pub(in super::super) fn suggest_missing_return_type(
436         &self,
437         err: &mut DiagnosticBuilder<'_>,
438         fn_decl: &hir::FnDecl<'_>,
439         expected: Ty<'tcx>,
440         found: Ty<'tcx>,
441         can_suggest: bool,
442         fn_id: hir::HirId,
443     ) -> bool {
444         // Only suggest changing the return type for methods that
445         // haven't set a return type at all (and aren't `fn main()` or an impl).
446         match (&fn_decl.output, found.is_suggestable(), can_suggest, expected.is_unit()) {
447             (&hir::FnRetTy::DefaultReturn(span), true, true, true) => {
448                 err.span_suggestion(
449                     span,
450                     "try adding a return type",
451                     format!("-> {} ", self.resolve_vars_with_obligations(found)),
452                     Applicability::MachineApplicable,
453                 );
454                 true
455             }
456             (&hir::FnRetTy::DefaultReturn(span), false, true, true) => {
457                 err.span_label(span, "possibly return type missing here?");
458                 true
459             }
460             (&hir::FnRetTy::DefaultReturn(span), _, false, true) => {
461                 // `fn main()` must return `()`, do not suggest changing return type
462                 err.span_label(span, "expected `()` because of default return type");
463                 true
464             }
465             // expectation was caused by something else, not the default return
466             (&hir::FnRetTy::DefaultReturn(_), _, _, false) => false,
467             (&hir::FnRetTy::Return(ref ty), _, _, _) => {
468                 // Only point to return type if the expected type is the return type, as if they
469                 // are not, the expectation must have been caused by something else.
470                 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
471                 let sp = ty.span;
472                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
473                 debug!("suggest_missing_return_type: return type {:?}", ty);
474                 debug!("suggest_missing_return_type: expected type {:?}", ty);
475                 let bound_vars = self.tcx.late_bound_vars(fn_id);
476                 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
477                 let ty = self.normalize_associated_types_in(sp, ty);
478                 if self.can_coerce(expected, ty) {
479                     err.span_label(sp, format!("expected `{}` because of return type", expected));
480                     return true;
481                 }
482                 false
483             }
484         }
485     }
486
487     pub(in super::super) fn suggest_missing_break_or_return_expr(
488         &self,
489         err: &mut DiagnosticBuilder<'_>,
490         expr: &'tcx hir::Expr<'tcx>,
491         fn_decl: &hir::FnDecl<'_>,
492         expected: Ty<'tcx>,
493         found: Ty<'tcx>,
494         id: hir::HirId,
495         fn_id: hir::HirId,
496     ) {
497         if !expected.is_unit() {
498             return;
499         }
500         let found = self.resolve_vars_with_obligations(found);
501
502         let in_loop = self.is_loop(id)
503             || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
504
505         let in_local_statement = self.is_local_statement(id)
506             || self
507                 .tcx
508                 .hir()
509                 .parent_iter(id)
510                 .any(|(parent_id, _)| self.is_local_statement(parent_id));
511
512         if in_loop && in_local_statement {
513             err.multipart_suggestion(
514                 "you might have meant to break the loop with this value",
515                 vec![
516                     (expr.span.shrink_to_lo(), "break ".to_string()),
517                     (expr.span.shrink_to_hi(), ";".to_string()),
518                 ],
519                 Applicability::MaybeIncorrect,
520             );
521             return;
522         }
523
524         if let hir::FnRetTy::Return(ty) = fn_decl.output {
525             let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
526             let bound_vars = self.tcx.late_bound_vars(fn_id);
527             let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
528             let ty = self.normalize_associated_types_in(expr.span, ty);
529             if self.can_coerce(found, ty) {
530                 err.multipart_suggestion(
531                     "you might have meant to return this value",
532                     vec![
533                         (expr.span.shrink_to_lo(), "return ".to_string()),
534                         (expr.span.shrink_to_hi(), ";".to_string()),
535                     ],
536                     Applicability::MaybeIncorrect,
537                 );
538             }
539         }
540     }
541
542     pub(in super::super) fn suggest_missing_parentheses(
543         &self,
544         err: &mut DiagnosticBuilder<'_>,
545         expr: &hir::Expr<'_>,
546     ) {
547         let sp = self.tcx.sess.source_map().start_point(expr.span);
548         if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
549             // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
550             self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp, None);
551         }
552     }
553
554     fn is_loop(&self, id: hir::HirId) -> bool {
555         let node = self.tcx.hir().get(id);
556         matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
557     }
558
559     fn is_local_statement(&self, id: hir::HirId) -> bool {
560         let node = self.tcx.hir().get(id);
561         matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
562     }
563 }