]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs
rustc_hir_typeck: move whole files
[rust.git] / compiler / rustc_hir_typeck / src / fn_ctxt / suggestions.rs
1 use super::FnCtxt;
2 use crate::astconv::AstConv;
3 use crate::errors::{AddReturnTypeSuggestion, ExpectedReturnTypeLabel};
4
5 use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX};
6 use rustc_errors::{Applicability, Diagnostic, MultiSpan};
7 use rustc_hir as hir;
8 use rustc_hir::def::{CtorOf, DefKind};
9 use rustc_hir::lang_items::LangItem;
10 use rustc_hir::{
11     Expr, ExprKind, GenericBound, Node, Path, QPath, Stmt, StmtKind, TyKind, WherePredicate,
12 };
13 use rustc_infer::infer::{self, TyCtxtInferExt};
14 use rustc_infer::traits::{self, StatementAsExpression};
15 use rustc_middle::lint::in_external_macro;
16 use rustc_middle::ty::{self, Binder, IsSuggestable, ToPredicate, Ty};
17 use rustc_session::errors::ExprParenthesesNeeded;
18 use rustc_span::symbol::sym;
19 use rustc_span::Span;
20 use rustc_trait_selection::infer::InferCtxtExt;
21 use rustc_trait_selection::traits::error_reporting::DefIdOrName;
22 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
23
24 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25     pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
26         err.span_suggestion_short(
27             span.shrink_to_hi(),
28             "consider using a semicolon here",
29             ";",
30             Applicability::MachineApplicable,
31         );
32     }
33
34     /// On implicit return expressions with mismatched types, provides the following suggestions:
35     ///
36     /// - Points out the method's return type as the reason for the expected type.
37     /// - Possible missing semicolon.
38     /// - Possible missing return type if the return type is the default, and not `fn main()`.
39     pub fn suggest_mismatched_types_on_tail(
40         &self,
41         err: &mut Diagnostic,
42         expr: &'tcx hir::Expr<'tcx>,
43         expected: Ty<'tcx>,
44         found: Ty<'tcx>,
45         blk_id: hir::HirId,
46     ) -> bool {
47         let expr = expr.peel_drop_temps();
48         self.suggest_missing_semicolon(err, expr, expected, false);
49         let mut pointing_at_return_type = false;
50         if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
51             let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
52             pointing_at_return_type = self.suggest_missing_return_type(
53                 err,
54                 &fn_decl,
55                 expected,
56                 found,
57                 can_suggest,
58                 fn_id,
59             );
60             self.suggest_missing_break_or_return_expr(
61                 err, expr, &fn_decl, expected, found, blk_id, fn_id,
62             );
63         }
64         pointing_at_return_type
65     }
66
67     /// When encountering an fn-like type, try accessing the output of the type
68     /// and suggesting calling it if it satisfies a predicate (i.e. if the
69     /// output has a method or a field):
70     /// ```compile_fail,E0308
71     /// fn foo(x: usize) -> usize { x }
72     /// let x: usize = foo;  // suggest calling the `foo` function: `foo(42)`
73     /// ```
74     pub(crate) fn suggest_fn_call(
75         &self,
76         err: &mut Diagnostic,
77         expr: &hir::Expr<'_>,
78         found: Ty<'tcx>,
79         can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
80     ) -> bool {
81         let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(expr, found)
82             else { return false; };
83         if can_satisfy(output) {
84             let (sugg_call, mut applicability) = match inputs.len() {
85                 0 => ("".to_string(), Applicability::MachineApplicable),
86                 1..=4 => (
87                     inputs
88                         .iter()
89                         .map(|ty| {
90                             if ty.is_suggestable(self.tcx, false) {
91                                 format!("/* {ty} */")
92                             } else {
93                                 "/* value */".to_string()
94                             }
95                         })
96                         .collect::<Vec<_>>()
97                         .join(", "),
98                     Applicability::HasPlaceholders,
99                 ),
100                 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
101             };
102
103             let msg = match def_id_or_name {
104                 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
105                     DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
106                     DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
107                     kind => format!("call this {}", kind.descr(def_id)),
108                 },
109                 DefIdOrName::Name(name) => format!("call this {name}"),
110             };
111
112             let sugg = match expr.kind {
113                 hir::ExprKind::Call(..)
114                 | hir::ExprKind::Path(..)
115                 | hir::ExprKind::Index(..)
116                 | hir::ExprKind::Lit(..) => {
117                     vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
118                 }
119                 hir::ExprKind::Closure { .. } => {
120                     // Might be `{ expr } || { bool }`
121                     applicability = Applicability::MaybeIncorrect;
122                     vec![
123                         (expr.span.shrink_to_lo(), "(".to_string()),
124                         (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
125                     ]
126                 }
127                 _ => {
128                     vec![
129                         (expr.span.shrink_to_lo(), "(".to_string()),
130                         (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
131                     ]
132                 }
133             };
134
135             err.multipart_suggestion_verbose(
136                 format!("use parentheses to {msg}"),
137                 sugg,
138                 applicability,
139             );
140             return true;
141         }
142         false
143     }
144
145     /// Extracts information about a callable type for diagnostics. This is a
146     /// heuristic -- it doesn't necessarily mean that a type is always callable,
147     /// because the callable type must also be well-formed to be called.
148     pub(in super::super) fn extract_callable_info(
149         &self,
150         expr: &Expr<'_>,
151         found: Ty<'tcx>,
152     ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
153         // Autoderef is useful here because sometimes we box callables, etc.
154         let Some((def_id_or_name, output, inputs)) = self.autoderef(expr.span, found).silence_errors().find_map(|(found, _)| {
155             match *found.kind() {
156                 ty::FnPtr(fn_sig) =>
157                     Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
158                 ty::FnDef(def_id, _) => {
159                     let fn_sig = found.fn_sig(self.tcx);
160                     Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
161                 }
162                 ty::Closure(def_id, substs) => {
163                     let fn_sig = substs.as_closure().sig();
164                     Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
165                 }
166                 ty::Opaque(def_id, substs) => {
167                     self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
168                         if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
169                         && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
170                         // args tuple will always be substs[1]
171                         && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
172                         {
173                             Some((
174                                 DefIdOrName::DefId(def_id),
175                                 pred.kind().rebind(proj.term.ty().unwrap()),
176                                 pred.kind().rebind(args.as_slice()),
177                             ))
178                         } else {
179                             None
180                         }
181                     })
182                 }
183                 ty::Dynamic(data, _, ty::Dyn) => {
184                     data.iter().find_map(|pred| {
185                         if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
186                         && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
187                         // for existential projection, substs are shifted over by 1
188                         && let ty::Tuple(args) = proj.substs.type_at(0).kind()
189                         {
190                             Some((
191                                 DefIdOrName::Name("trait object"),
192                                 pred.rebind(proj.term.ty().unwrap()),
193                                 pred.rebind(args.as_slice()),
194                             ))
195                         } else {
196                             None
197                         }
198                     })
199                 }
200                 ty::Param(param) => {
201                     let def_id = self.tcx.generics_of(self.body_id.owner).type_param(&param, self.tcx).def_id;
202                     self.tcx.predicates_of(self.body_id.owner).predicates.iter().find_map(|(pred, _)| {
203                         if let ty::PredicateKind::Projection(proj) = pred.kind().skip_binder()
204                         && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
205                         && proj.projection_ty.self_ty() == found
206                         // args tuple will always be substs[1]
207                         && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
208                         {
209                             Some((
210                                 DefIdOrName::DefId(def_id),
211                                 pred.kind().rebind(proj.term.ty().unwrap()),
212                                 pred.kind().rebind(args.as_slice()),
213                             ))
214                         } else {
215                             None
216                         }
217                     })
218                 }
219                 _ => None,
220             }
221         }) else { return None; };
222
223         let output = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, output);
224         let inputs = inputs
225             .skip_binder()
226             .iter()
227             .map(|ty| {
228                 self.replace_bound_vars_with_fresh_vars(
229                     expr.span,
230                     infer::FnCall,
231                     inputs.rebind(*ty),
232                 )
233             })
234             .collect();
235
236         // We don't want to register any extra obligations, which should be
237         // implied by wf, but also because that would possibly result in
238         // erroneous errors later on.
239         let infer::InferOk { value: output, obligations: _ } =
240             self.normalize_associated_types_in_as_infer_ok(expr.span, output);
241
242         if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
243     }
244
245     pub fn suggest_two_fn_call(
246         &self,
247         err: &mut Diagnostic,
248         lhs_expr: &'tcx hir::Expr<'tcx>,
249         lhs_ty: Ty<'tcx>,
250         rhs_expr: &'tcx hir::Expr<'tcx>,
251         rhs_ty: Ty<'tcx>,
252         can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
253     ) -> bool {
254         let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_expr, lhs_ty)
255             else { return false; };
256         let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_expr, rhs_ty)
257             else { return false; };
258
259         if can_satisfy(lhs_output_ty, rhs_output_ty) {
260             let mut sugg = vec![];
261             let mut applicability = Applicability::MachineApplicable;
262
263             for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
264                 let (sugg_call, this_applicability) = match inputs.len() {
265                     0 => ("".to_string(), Applicability::MachineApplicable),
266                     1..=4 => (
267                         inputs
268                             .iter()
269                             .map(|ty| {
270                                 if ty.is_suggestable(self.tcx, false) {
271                                     format!("/* {ty} */")
272                                 } else {
273                                     "/* value */".to_string()
274                                 }
275                             })
276                             .collect::<Vec<_>>()
277                             .join(", "),
278                         Applicability::HasPlaceholders,
279                     ),
280                     _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
281                 };
282
283                 applicability = applicability.max(this_applicability);
284
285                 match expr.kind {
286                     hir::ExprKind::Call(..)
287                     | hir::ExprKind::Path(..)
288                     | hir::ExprKind::Index(..)
289                     | hir::ExprKind::Lit(..) => {
290                         sugg.extend([(expr.span.shrink_to_hi(), format!("({sugg_call})"))]);
291                     }
292                     hir::ExprKind::Closure { .. } => {
293                         // Might be `{ expr } || { bool }`
294                         applicability = Applicability::MaybeIncorrect;
295                         sugg.extend([
296                             (expr.span.shrink_to_lo(), "(".to_string()),
297                             (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
298                         ]);
299                     }
300                     _ => {
301                         sugg.extend([
302                             (expr.span.shrink_to_lo(), "(".to_string()),
303                             (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
304                         ]);
305                     }
306                 }
307             }
308
309             err.multipart_suggestion_verbose(
310                 format!("use parentheses to call these"),
311                 sugg,
312                 applicability,
313             );
314
315             true
316         } else {
317             false
318         }
319     }
320
321     pub fn suggest_deref_ref_or_into(
322         &self,
323         err: &mut Diagnostic,
324         expr: &hir::Expr<'tcx>,
325         expected: Ty<'tcx>,
326         found: Ty<'tcx>,
327         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
328     ) -> bool {
329         let expr = expr.peel_blocks();
330         if let Some((sp, msg, suggestion, applicability, verbose)) =
331             self.check_ref(expr, found, expected)
332         {
333             if verbose {
334                 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
335             } else {
336                 err.span_suggestion(sp, &msg, suggestion, applicability);
337             }
338             return true;
339         } else if self.suggest_else_fn_with_closure(err, expr, found, expected)
340         {
341             return true;
342         } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected))
343             && let ty::FnDef(def_id, ..) = &found.kind()
344             && let Some(sp) = self.tcx.hir().span_if_local(*def_id)
345         {
346             err.span_label(sp, format!("{found} defined here"));
347             return true;
348         } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
349             return true;
350         } else {
351             let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
352             if !methods.is_empty() {
353                 let mut suggestions = methods.iter()
354                     .filter_map(|conversion_method| {
355                         let receiver_method_ident = expr.method_ident();
356                         if let Some(method_ident) = receiver_method_ident
357                             && method_ident.name == conversion_method.name
358                         {
359                             return None // do not suggest code that is already there (#53348)
360                         }
361
362                         let method_call_list = [sym::to_vec, sym::to_string];
363                         let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
364                             && receiver_method.ident.name == sym::clone
365                             && method_call_list.contains(&conversion_method.name)
366                             // If receiver is `.clone()` and found type has one of those methods,
367                             // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
368                             // to an owned type (`Vec` or `String`).  These conversions clone internally,
369                             // so we remove the user's `clone` call.
370                         {
371                             vec![(
372                                 receiver_method.ident.span,
373                                 conversion_method.name.to_string()
374                             )]
375                         } else if expr.precedence().order()
376                             < ExprPrecedence::MethodCall.order()
377                         {
378                             vec![
379                                 (expr.span.shrink_to_lo(), "(".to_string()),
380                                 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
381                             ]
382                         } else {
383                             vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
384                         };
385                         let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
386                         if let Some(name) = struct_pat_shorthand_field {
387                             sugg.insert(
388                                 0,
389                                 (expr.span.shrink_to_lo(), format!("{}: ", name)),
390                             );
391                         }
392                         Some(sugg)
393                     })
394                     .peekable();
395                 if suggestions.peek().is_some() {
396                     err.multipart_suggestions(
397                         "try using a conversion method",
398                         suggestions,
399                         Applicability::MaybeIncorrect,
400                     );
401                     return true;
402                 }
403             } else if let ty::Adt(found_adt, found_substs) = found.kind()
404                 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
405                 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
406                 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
407                 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
408                 && inner_ty.is_str()
409             {
410                 let ty = found_substs.type_at(0);
411                 let mut peeled = ty;
412                 let mut ref_cnt = 0;
413                 while let ty::Ref(_, inner, _) = peeled.kind() {
414                     peeled = *inner;
415                     ref_cnt += 1;
416                 }
417                 if let ty::Adt(adt, _) = peeled.kind()
418                     && self.tcx.is_diagnostic_item(sym::String, adt.did())
419                 {
420                     err.span_suggestion_verbose(
421                         expr.span.shrink_to_hi(),
422                         "try converting the passed type into a `&str`",
423                         format!(".map(|x| &*{}x)", "*".repeat(ref_cnt)),
424                         Applicability::MaybeIncorrect,
425                     );
426                     return true;
427                 }
428             }
429         }
430
431         false
432     }
433
434     /// When encountering the expected boxed value allocated in the stack, suggest allocating it
435     /// in the heap by calling `Box::new()`.
436     pub(in super::super) fn suggest_boxing_when_appropriate(
437         &self,
438         err: &mut Diagnostic,
439         expr: &hir::Expr<'_>,
440         expected: Ty<'tcx>,
441         found: Ty<'tcx>,
442     ) -> bool {
443         if self.tcx.hir().is_inside_const_context(expr.hir_id) {
444             // Do not suggest `Box::new` in const context.
445             return false;
446         }
447         if !expected.is_box() || found.is_box() {
448             return false;
449         }
450         let boxed_found = self.tcx.mk_box(found);
451         if self.can_coerce(boxed_found, expected) {
452             err.multipart_suggestion(
453                 "store this in the heap by calling `Box::new`",
454                 vec![
455                     (expr.span.shrink_to_lo(), "Box::new(".to_string()),
456                     (expr.span.shrink_to_hi(), ")".to_string()),
457                 ],
458                 Applicability::MachineApplicable,
459             );
460             err.note(
461                 "for more on the distinction between the stack and the heap, read \
462                  https://doc.rust-lang.org/book/ch15-01-box.html, \
463                  https://doc.rust-lang.org/rust-by-example/std/box.html, and \
464                  https://doc.rust-lang.org/std/boxed/index.html",
465             );
466             true
467         } else {
468             false
469         }
470     }
471
472     /// When encountering a closure that captures variables, where a FnPtr is expected,
473     /// suggest a non-capturing closure
474     pub(in super::super) fn suggest_no_capture_closure(
475         &self,
476         err: &mut Diagnostic,
477         expected: Ty<'tcx>,
478         found: Ty<'tcx>,
479     ) -> bool {
480         if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
481             if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
482                 // Report upto four upvars being captured to reduce the amount error messages
483                 // reported back to the user.
484                 let spans_and_labels = upvars
485                     .iter()
486                     .take(4)
487                     .map(|(var_hir_id, upvar)| {
488                         let var_name = self.tcx.hir().name(*var_hir_id).to_string();
489                         let msg = format!("`{}` captured here", var_name);
490                         (upvar.span, msg)
491                     })
492                     .collect::<Vec<_>>();
493
494                 let mut multi_span: MultiSpan =
495                     spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
496                 for (sp, label) in spans_and_labels {
497                     multi_span.push_span_label(sp, label);
498                 }
499                 err.span_note(
500                     multi_span,
501                     "closures can only be coerced to `fn` types if they do not capture any variables"
502                 );
503                 return true;
504             }
505         }
506         false
507     }
508
509     /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
510     #[instrument(skip(self, err))]
511     pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
512         &self,
513         err: &mut Diagnostic,
514         expr: &hir::Expr<'_>,
515         expected: Ty<'tcx>,
516         found: Ty<'tcx>,
517     ) -> bool {
518         // Handle #68197.
519
520         if self.tcx.hir().is_inside_const_context(expr.hir_id) {
521             // Do not suggest `Box::new` in const context.
522             return false;
523         }
524         let pin_did = self.tcx.lang_items().pin_type();
525         // This guards the `unwrap` and `mk_box` below.
526         if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
527             return false;
528         }
529         let box_found = self.tcx.mk_box(found);
530         let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
531         let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
532         match expected.kind() {
533             ty::Adt(def, _) if Some(def.did()) == pin_did => {
534                 if self.can_coerce(pin_box_found, expected) {
535                     debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
536                     match found.kind() {
537                         ty::Adt(def, _) if def.is_box() => {
538                             err.help("use `Box::pin`");
539                         }
540                         _ => {
541                             err.multipart_suggestion(
542                                 "you need to pin and box this expression",
543                                 vec![
544                                     (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
545                                     (expr.span.shrink_to_hi(), ")".to_string()),
546                                 ],
547                                 Applicability::MaybeIncorrect,
548                             );
549                         }
550                     }
551                     true
552                 } else if self.can_coerce(pin_found, expected) {
553                     match found.kind() {
554                         ty::Adt(def, _) if def.is_box() => {
555                             err.help("use `Box::pin`");
556                             true
557                         }
558                         _ => false,
559                     }
560                 } else {
561                     false
562                 }
563             }
564             ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
565                 // Check if the parent expression is a call to Pin::new.  If it
566                 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
567                 // can suggest Box::pin.
568                 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
569                 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
570                     return false;
571                 };
572                 match fn_name.kind {
573                     ExprKind::Path(QPath::TypeRelative(
574                         hir::Ty {
575                             kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
576                             ..
577                         },
578                         method,
579                     )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
580                         err.span_suggestion(
581                             fn_name.span,
582                             "use `Box::pin` to pin and box this expression",
583                             "Box::pin",
584                             Applicability::MachineApplicable,
585                         );
586                         true
587                     }
588                     _ => false,
589                 }
590             }
591             _ => false,
592         }
593     }
594
595     /// A common error is to forget to add a semicolon at the end of a block, e.g.,
596     ///
597     /// ```compile_fail,E0308
598     /// # fn bar_that_returns_u32() -> u32 { 4 }
599     /// fn foo() {
600     ///     bar_that_returns_u32()
601     /// }
602     /// ```
603     ///
604     /// This routine checks if the return expression in a block would make sense on its own as a
605     /// statement and the return type has been left as default or has been specified as `()`. If so,
606     /// it suggests adding a semicolon.
607     ///
608     /// If the expression is the expression of a closure without block (`|| expr`), a
609     /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
610     pub fn suggest_missing_semicolon(
611         &self,
612         err: &mut Diagnostic,
613         expression: &'tcx hir::Expr<'tcx>,
614         expected: Ty<'tcx>,
615         needs_block: bool,
616     ) {
617         if expected.is_unit() {
618             // `BlockTailExpression` only relevant if the tail expr would be
619             // useful on its own.
620             match expression.kind {
621                 ExprKind::Call(..)
622                 | ExprKind::MethodCall(..)
623                 | ExprKind::Loop(..)
624                 | ExprKind::If(..)
625                 | ExprKind::Match(..)
626                 | ExprKind::Block(..)
627                     if expression.can_have_side_effects()
628                         // If the expression is from an external macro, then do not suggest
629                         // adding a semicolon, because there's nowhere to put it.
630                         // See issue #81943.
631                         && !in_external_macro(self.tcx.sess, expression.span) =>
632                 {
633                     if needs_block {
634                         err.multipart_suggestion(
635                             "consider using a semicolon here",
636                             vec![
637                                 (expression.span.shrink_to_lo(), "{ ".to_owned()),
638                                 (expression.span.shrink_to_hi(), "; }".to_owned()),
639                             ],
640                             Applicability::MachineApplicable,
641                         );
642                     } else {
643                         err.span_suggestion(
644                             expression.span.shrink_to_hi(),
645                             "consider using a semicolon here",
646                             ";",
647                             Applicability::MachineApplicable,
648                         );
649                     }
650                 }
651                 _ => (),
652             }
653         }
654     }
655
656     /// A possible error is to forget to add a return type that is needed:
657     ///
658     /// ```compile_fail,E0308
659     /// # fn bar_that_returns_u32() -> u32 { 4 }
660     /// fn foo() {
661     ///     bar_that_returns_u32()
662     /// }
663     /// ```
664     ///
665     /// This routine checks if the return type is left as default, the method is not part of an
666     /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
667     /// type.
668     pub(in super::super) fn suggest_missing_return_type(
669         &self,
670         err: &mut Diagnostic,
671         fn_decl: &hir::FnDecl<'_>,
672         expected: Ty<'tcx>,
673         found: Ty<'tcx>,
674         can_suggest: bool,
675         fn_id: hir::HirId,
676     ) -> bool {
677         let found =
678             self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
679         // Only suggest changing the return type for methods that
680         // haven't set a return type at all (and aren't `fn main()` or an impl).
681         match &fn_decl.output {
682             &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
683                 // `fn main()` must return `()`, do not suggest changing return type
684                 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
685                 return true;
686             }
687             &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
688                 if found.is_suggestable(self.tcx, false) {
689                     err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
690                     return true;
691                 } else if let ty::Closure(_, substs) = found.kind()
692                     // FIXME(compiler-errors): Get better at printing binders...
693                     && let closure = substs.as_closure()
694                     && closure.sig().is_suggestable(self.tcx, false)
695                 {
696                     err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
697                     return true;
698                 } else {
699                     // FIXME: if `found` could be `impl Iterator` we should suggest that.
700                     err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
701                     return true
702                 }
703             }
704             &hir::FnRetTy::Return(ref ty) => {
705                 // Only point to return type if the expected type is the return type, as if they
706                 // are not, the expectation must have been caused by something else.
707                 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
708                 let span = ty.span;
709                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
710                 debug!("suggest_missing_return_type: return type {:?}", ty);
711                 debug!("suggest_missing_return_type: expected type {:?}", ty);
712                 let bound_vars = self.tcx.late_bound_vars(fn_id);
713                 let ty = Binder::bind_with_vars(ty, bound_vars);
714                 let ty = self.normalize_associated_types_in(span, ty);
715                 let ty = self.tcx.erase_late_bound_regions(ty);
716                 if self.can_coerce(expected, ty) {
717                     err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
718                     self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
719                     return true;
720                 }
721             }
722             _ => {}
723         }
724         false
725     }
726
727     /// check whether the return type is a generic type with a trait bound
728     /// only suggest this if the generic param is not present in the arguments
729     /// if this is true, hint them towards changing the return type to `impl Trait`
730     /// ```compile_fail,E0308
731     /// fn cant_name_it<T: Fn() -> u32>() -> T {
732     ///     || 3
733     /// }
734     /// ```
735     fn try_suggest_return_impl_trait(
736         &self,
737         err: &mut Diagnostic,
738         expected: Ty<'tcx>,
739         found: Ty<'tcx>,
740         fn_id: hir::HirId,
741     ) {
742         // Only apply the suggestion if:
743         //  - the return type is a generic parameter
744         //  - the generic param is not used as a fn param
745         //  - the generic param has at least one bound
746         //  - the generic param doesn't appear in any other bounds where it's not the Self type
747         // Suggest:
748         //  - Changing the return type to be `impl <all bounds>`
749
750         debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
751
752         let ty::Param(expected_ty_as_param) = expected.kind() else { return };
753
754         let fn_node = self.tcx.hir().find(fn_id);
755
756         let Some(hir::Node::Item(hir::Item {
757             kind:
758                 hir::ItemKind::Fn(
759                     hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
760                     hir::Generics { params, predicates, .. },
761                     _body_id,
762                 ),
763             ..
764         })) = fn_node else { return };
765
766         if params.get(expected_ty_as_param.index as usize).is_none() {
767             return;
768         };
769
770         // get all where BoundPredicates here, because they are used in to cases below
771         let where_predicates = predicates
772             .iter()
773             .filter_map(|p| match p {
774                 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
775                     bounds,
776                     bounded_ty,
777                     ..
778                 }) => {
779                     // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
780                     let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
781                     Some((ty, bounds))
782                 }
783                 _ => None,
784             })
785             .map(|(ty, bounds)| match ty.kind() {
786                 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
787                 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
788                 _ => match ty.contains(expected) {
789                     true => Err(()),
790                     false => Ok(None),
791                 },
792             })
793             .collect::<Result<Vec<_>, _>>();
794
795         let Ok(where_predicates) = where_predicates else { return };
796
797         // now get all predicates in the same types as the where bounds, so we can chain them
798         let predicates_from_where =
799             where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
800
801         // extract all bounds from the source code using their spans
802         let all_matching_bounds_strs = predicates_from_where
803             .filter_map(|bound| match bound {
804                 GenericBound::Trait(_, _) => {
805                     self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
806                 }
807                 _ => None,
808             })
809             .collect::<Vec<String>>();
810
811         if all_matching_bounds_strs.len() == 0 {
812             return;
813         }
814
815         let all_bounds_str = all_matching_bounds_strs.join(" + ");
816
817         let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
818                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
819                 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
820             });
821
822         if ty_param_used_in_fn_params {
823             return;
824         }
825
826         err.span_suggestion(
827             fn_return.span(),
828             "consider using an impl return type",
829             format!("impl {}", all_bounds_str),
830             Applicability::MaybeIncorrect,
831         );
832     }
833
834     pub(in super::super) fn suggest_missing_break_or_return_expr(
835         &self,
836         err: &mut Diagnostic,
837         expr: &'tcx hir::Expr<'tcx>,
838         fn_decl: &hir::FnDecl<'_>,
839         expected: Ty<'tcx>,
840         found: Ty<'tcx>,
841         id: hir::HirId,
842         fn_id: hir::HirId,
843     ) {
844         if !expected.is_unit() {
845             return;
846         }
847         let found = self.resolve_vars_with_obligations(found);
848
849         let in_loop = self.is_loop(id)
850             || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
851
852         let in_local_statement = self.is_local_statement(id)
853             || self
854                 .tcx
855                 .hir()
856                 .parent_iter(id)
857                 .any(|(parent_id, _)| self.is_local_statement(parent_id));
858
859         if in_loop && in_local_statement {
860             err.multipart_suggestion(
861                 "you might have meant to break the loop with this value",
862                 vec![
863                     (expr.span.shrink_to_lo(), "break ".to_string()),
864                     (expr.span.shrink_to_hi(), ";".to_string()),
865                 ],
866                 Applicability::MaybeIncorrect,
867             );
868             return;
869         }
870
871         if let hir::FnRetTy::Return(ty) = fn_decl.output {
872             let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
873             let bound_vars = self.tcx.late_bound_vars(fn_id);
874             let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
875             let ty = self.normalize_associated_types_in(expr.span, ty);
876             let ty = match self.tcx.asyncness(fn_id.owner) {
877                 hir::IsAsync::Async => {
878                     let infcx = self.tcx.infer_ctxt().build();
879                     infcx
880                         .get_impl_future_output_ty(ty)
881                         .unwrap_or_else(|| {
882                             span_bug!(
883                                 fn_decl.output.span(),
884                                 "failed to get output type of async function"
885                             )
886                         })
887                         .skip_binder()
888                 }
889                 hir::IsAsync::NotAsync => ty,
890             };
891             if self.can_coerce(found, ty) {
892                 err.multipart_suggestion(
893                     "you might have meant to return this value",
894                     vec![
895                         (expr.span.shrink_to_lo(), "return ".to_string()),
896                         (expr.span.shrink_to_hi(), ";".to_string()),
897                     ],
898                     Applicability::MaybeIncorrect,
899                 );
900             }
901         }
902     }
903
904     pub(in super::super) fn suggest_missing_parentheses(
905         &self,
906         err: &mut Diagnostic,
907         expr: &hir::Expr<'_>,
908     ) -> bool {
909         let sp = self.tcx.sess.source_map().start_point(expr.span);
910         if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
911             // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
912             err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
913             true
914         } else {
915             false
916         }
917     }
918
919     /// Given an expression type mismatch, peel any `&` expressions until we get to
920     /// a block expression, and then suggest replacing the braces with square braces
921     /// if it was possibly mistaken array syntax.
922     pub(crate) fn suggest_block_to_brackets_peeling_refs(
923         &self,
924         diag: &mut Diagnostic,
925         mut expr: &hir::Expr<'_>,
926         mut expr_ty: Ty<'tcx>,
927         mut expected_ty: Ty<'tcx>,
928     ) -> bool {
929         loop {
930             match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
931                 (
932                     hir::ExprKind::AddrOf(_, _, inner_expr),
933                     ty::Ref(_, inner_expr_ty, _),
934                     ty::Ref(_, inner_expected_ty, _),
935                 ) => {
936                     expr = *inner_expr;
937                     expr_ty = *inner_expr_ty;
938                     expected_ty = *inner_expected_ty;
939                 }
940                 (hir::ExprKind::Block(blk, _), _, _) => {
941                     self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
942                     break true;
943                 }
944                 _ => break false,
945             }
946         }
947     }
948
949     pub(crate) fn suggest_copied_or_cloned(
950         &self,
951         diag: &mut Diagnostic,
952         expr: &hir::Expr<'_>,
953         expr_ty: Ty<'tcx>,
954         expected_ty: Ty<'tcx>,
955     ) -> bool {
956         let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
957         let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
958         if adt_def != expected_adt_def {
959             return false;
960         }
961
962         let mut suggest_copied_or_cloned = || {
963             let expr_inner_ty = substs.type_at(0);
964             let expected_inner_ty = expected_substs.type_at(0);
965             if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
966                 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
967             {
968                 let def_path = self.tcx.def_path_str(adt_def.did());
969                 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
970                     diag.span_suggestion_verbose(
971                         expr.span.shrink_to_hi(),
972                         format!(
973                             "use `{def_path}::copied` to copy the value inside the `{def_path}`"
974                         ),
975                         ".copied()",
976                         Applicability::MachineApplicable,
977                     );
978                     return true;
979                 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
980                     && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
981                         self,
982                         self.param_env,
983                         *ty,
984                         clone_did,
985                         expr.span
986                     )
987                 {
988                     diag.span_suggestion_verbose(
989                         expr.span.shrink_to_hi(),
990                         format!(
991                             "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
992                         ),
993                         ".cloned()",
994                         Applicability::MachineApplicable,
995                     );
996                     return true;
997                 }
998             }
999             false
1000         };
1001
1002         if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1003             && adt_def.did() == result_did
1004             // Check that the error types are equal
1005             && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1006         {
1007             return suggest_copied_or_cloned();
1008         } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1009             && adt_def.did() == option_did
1010         {
1011             return suggest_copied_or_cloned();
1012         }
1013
1014         false
1015     }
1016
1017     pub(crate) fn suggest_into(
1018         &self,
1019         diag: &mut Diagnostic,
1020         expr: &hir::Expr<'_>,
1021         expr_ty: Ty<'tcx>,
1022         expected_ty: Ty<'tcx>,
1023     ) -> bool {
1024         let expr = expr.peel_blocks();
1025
1026         // We have better suggestions for scalar interconversions...
1027         if expr_ty.is_scalar() && expected_ty.is_scalar() {
1028             return false;
1029         }
1030
1031         // Don't suggest turning a block into another type (e.g. `{}.into()`)
1032         if matches!(expr.kind, hir::ExprKind::Block(..)) {
1033             return false;
1034         }
1035
1036         // We'll later suggest `.as_ref` when noting the type error,
1037         // so skip if we will suggest that instead.
1038         if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1039             return false;
1040         }
1041
1042         if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1043             && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1044                 self.misc(expr.span),
1045                 self.param_env,
1046                 ty::Binder::dummy(ty::TraitRef {
1047                     def_id: into_def_id,
1048                     substs: self.tcx.mk_substs_trait(expr_ty, &[expected_ty.into()]),
1049                 })
1050                 .to_poly_trait_predicate()
1051                 .to_predicate(self.tcx),
1052             ))
1053         {
1054             let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1055                 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1056             } else {
1057                 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1058             };
1059             diag.multipart_suggestion(
1060                 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1061                 sugg,
1062                 Applicability::MaybeIncorrect
1063             );
1064             return true;
1065         }
1066
1067         false
1068     }
1069
1070     /// Suggest wrapping the block in square brackets instead of curly braces
1071     /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1072     pub(crate) fn suggest_block_to_brackets(
1073         &self,
1074         diag: &mut Diagnostic,
1075         blk: &hir::Block<'_>,
1076         blk_ty: Ty<'tcx>,
1077         expected_ty: Ty<'tcx>,
1078     ) {
1079         if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1080             if self.can_coerce(blk_ty, *elem_ty)
1081                 && blk.stmts.is_empty()
1082                 && blk.rules == hir::BlockCheckMode::DefaultBlock
1083             {
1084                 let source_map = self.tcx.sess.source_map();
1085                 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1086                     if snippet.starts_with('{') && snippet.ends_with('}') {
1087                         diag.multipart_suggestion_verbose(
1088                             "to create an array, use square brackets instead of curly braces",
1089                             vec![
1090                                 (
1091                                     blk.span
1092                                         .shrink_to_lo()
1093                                         .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1094                                     "[".to_string(),
1095                                 ),
1096                                 (
1097                                     blk.span
1098                                         .shrink_to_hi()
1099                                         .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1100                                     "]".to_string(),
1101                                 ),
1102                             ],
1103                             Applicability::MachineApplicable,
1104                         );
1105                     }
1106                 }
1107             }
1108         }
1109     }
1110
1111     fn is_loop(&self, id: hir::HirId) -> bool {
1112         let node = self.tcx.hir().get(id);
1113         matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1114     }
1115
1116     fn is_local_statement(&self, id: hir::HirId) -> bool {
1117         let node = self.tcx.hir().get(id);
1118         matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1119     }
1120
1121     /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1122     /// which is a side-effect of autoref.
1123     pub(crate) fn note_type_is_not_clone(
1124         &self,
1125         diag: &mut Diagnostic,
1126         expected_ty: Ty<'tcx>,
1127         found_ty: Ty<'tcx>,
1128         expr: &hir::Expr<'_>,
1129     ) {
1130         let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1131         let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1132         let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1133         let results = self.typeck_results.borrow();
1134         // First, look for a `Clone::clone` call
1135         if segment.ident.name == sym::clone
1136             && results.type_dependent_def_id(expr.hir_id).map_or(
1137                 false,
1138                 |did| {
1139                     let assoc_item = self.tcx.associated_item(did);
1140                     assoc_item.container == ty::AssocItemContainer::TraitContainer
1141                         && assoc_item.container_id(self.tcx) == clone_trait_did
1142                 },
1143             )
1144             // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1145             // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1146             && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1147             // Check that we're in fact trying to clone into the expected type
1148             && self.can_coerce(*pointee_ty, expected_ty)
1149             // And the expected type doesn't implement `Clone`
1150             && !self.predicate_must_hold_considering_regions(&traits::Obligation {
1151                 cause: traits::ObligationCause::dummy(),
1152                 param_env: self.param_env,
1153                 recursion_depth: 0,
1154                 predicate: ty::Binder::dummy(ty::TraitRef {
1155                     def_id: clone_trait_did,
1156                     substs: self.tcx.mk_substs([expected_ty.into()].iter()),
1157                 })
1158                 .without_const()
1159                 .to_predicate(self.tcx),
1160             })
1161         {
1162             diag.span_note(
1163                 callee_expr.span,
1164                 &format!(
1165                     "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1166                 ),
1167             );
1168         }
1169     }
1170
1171     /// A common error is to add an extra semicolon:
1172     ///
1173     /// ```compile_fail,E0308
1174     /// fn foo() -> usize {
1175     ///     22;
1176     /// }
1177     /// ```
1178     ///
1179     /// This routine checks if the final statement in a block is an
1180     /// expression with an explicit semicolon whose type is compatible
1181     /// with `expected_ty`. If so, it suggests removing the semicolon.
1182     pub(crate) fn consider_removing_semicolon(
1183         &self,
1184         blk: &'tcx hir::Block<'tcx>,
1185         expected_ty: Ty<'tcx>,
1186         err: &mut Diagnostic,
1187     ) -> bool {
1188         if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1189             if let StatementAsExpression::NeedsBoxing = boxed {
1190                 err.span_suggestion_verbose(
1191                     span_semi,
1192                     "consider removing this semicolon and boxing the expression",
1193                     "",
1194                     Applicability::HasPlaceholders,
1195                 );
1196             } else {
1197                 err.span_suggestion_short(
1198                     span_semi,
1199                     "remove this semicolon to return this value",
1200                     "",
1201                     Applicability::MachineApplicable,
1202                 );
1203             }
1204             true
1205         } else {
1206             false
1207         }
1208     }
1209 }