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