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