3 use crate::errors::{AddReturnTypeSuggestion, ExpectedReturnTypeLabel};
4 use crate::method::probe::{IsSuggestion, Mode, ProbeScope};
5 use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX};
6 use rustc_errors::{fluent, Applicability, Diagnostic, MultiSpan};
8 use rustc_hir::def::{CtorKind, CtorOf, DefKind};
9 use rustc_hir::lang_items::LangItem;
11 Expr, ExprKind, GenericBound, Node, Path, QPath, Stmt, StmtKind, TyKind, WherePredicate,
13 use rustc_hir_analysis::astconv::AstConv;
14 use rustc_infer::traits::{self, StatementAsExpression};
15 use rustc_middle::lint::in_external_macro;
16 use rustc_middle::ty::print::with_no_trimmed_paths;
17 use rustc_middle::ty::{
18 self, suggest_constraining_type_params, Binder, DefIdTree, IsSuggestable, ToPredicate, Ty,
21 use rustc_session::errors::ExprParenthesesNeeded;
22 use rustc_span::source_map::Spanned;
23 use rustc_span::symbol::{sym, Ident};
24 use rustc_span::{Span, Symbol};
25 use rustc_trait_selection::infer::InferCtxtExt;
26 use rustc_trait_selection::traits::error_reporting::suggestions::TypeErrCtxtExt;
27 use rustc_trait_selection::traits::error_reporting::DefIdOrName;
28 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
30 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
31 pub(crate) fn body_fn_sig(&self) -> Option<ty::FnSig<'tcx>> {
35 .get(self.tcx.hir().local_def_id_to_hir_id(self.body_id))
39 pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
40 // This suggestion is incorrect for
41 // fn foo() -> bool { match () { () => true } || match () { () => true } }
42 err.span_suggestion_short(
44 "consider using a semicolon here",
46 Applicability::MaybeIncorrect,
50 /// On implicit return expressions with mismatched types, provides the following suggestions:
52 /// - Points out the method's return type as the reason for the expected type.
53 /// - Possible missing semicolon.
54 /// - Possible missing return type if the return type is the default, and not `fn main()`.
55 pub fn suggest_mismatched_types_on_tail(
58 expr: &'tcx hir::Expr<'tcx>,
63 let expr = expr.peel_drop_temps();
64 self.suggest_missing_semicolon(err, expr, expected, false);
65 let mut pointing_at_return_type = false;
66 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
67 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
68 pointing_at_return_type = self.suggest_missing_return_type(
76 self.suggest_missing_break_or_return_expr(
77 err, expr, &fn_decl, expected, found, blk_id, fn_id,
80 pointing_at_return_type
83 /// When encountering an fn-like type, try accessing the output of the type
84 /// and suggesting calling it if it satisfies a predicate (i.e. if the
85 /// output has a method or a field):
86 /// ```compile_fail,E0308
87 /// fn foo(x: usize) -> usize { x }
88 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
90 pub(crate) fn suggest_fn_call(
95 can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
97 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(found)
98 else { return false; };
99 if can_satisfy(output) {
100 let (sugg_call, mut applicability) = match inputs.len() {
101 0 => ("".to_string(), Applicability::MachineApplicable),
106 if ty.is_suggestable(self.tcx, false) {
107 format!("/* {ty} */")
109 "/* value */".to_string()
114 Applicability::HasPlaceholders,
116 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
119 let msg = match def_id_or_name {
120 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
121 DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
122 DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
123 kind => format!("call this {}", kind.descr(def_id)),
125 DefIdOrName::Name(name) => format!("call this {name}"),
128 let sugg = match expr.kind {
129 hir::ExprKind::Call(..)
130 | hir::ExprKind::Path(..)
131 | hir::ExprKind::Index(..)
132 | hir::ExprKind::Lit(..) => {
133 vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
135 hir::ExprKind::Closure { .. } => {
136 // Might be `{ expr } || { bool }`
137 applicability = Applicability::MaybeIncorrect;
139 (expr.span.shrink_to_lo(), "(".to_string()),
140 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
145 (expr.span.shrink_to_lo(), "(".to_string()),
146 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
151 err.multipart_suggestion_verbose(
152 format!("use parentheses to {msg}"),
161 /// Extracts information about a callable type for diagnostics. This is a
162 /// heuristic -- it doesn't necessarily mean that a type is always callable,
163 /// because the callable type must also be well-formed to be called.
164 pub(in super::super) fn extract_callable_info(
167 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
168 let body_hir_id = self.tcx.hir().local_def_id_to_hir_id(self.body_id);
169 self.err_ctxt().extract_callable_info(body_hir_id, self.param_env, ty)
172 pub fn suggest_two_fn_call(
174 err: &mut Diagnostic,
175 lhs_expr: &'tcx hir::Expr<'tcx>,
177 rhs_expr: &'tcx hir::Expr<'tcx>,
179 can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
181 let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_ty)
182 else { return false; };
183 let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_ty)
184 else { return false; };
186 if can_satisfy(lhs_output_ty, rhs_output_ty) {
187 let mut sugg = vec![];
188 let mut applicability = Applicability::MachineApplicable;
190 for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
191 let (sugg_call, this_applicability) = match inputs.len() {
192 0 => ("".to_string(), Applicability::MachineApplicable),
197 if ty.is_suggestable(self.tcx, false) {
198 format!("/* {ty} */")
200 "/* value */".to_string()
205 Applicability::HasPlaceholders,
207 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
210 applicability = applicability.max(this_applicability);
213 hir::ExprKind::Call(..)
214 | hir::ExprKind::Path(..)
215 | hir::ExprKind::Index(..)
216 | hir::ExprKind::Lit(..) => {
217 sugg.extend([(expr.span.shrink_to_hi(), format!("({sugg_call})"))]);
219 hir::ExprKind::Closure { .. } => {
220 // Might be `{ expr } || { bool }`
221 applicability = Applicability::MaybeIncorrect;
223 (expr.span.shrink_to_lo(), "(".to_string()),
224 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
229 (expr.span.shrink_to_lo(), "(".to_string()),
230 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
236 err.multipart_suggestion_verbose("use parentheses to call these", sugg, applicability);
244 pub fn suggest_remove_last_method_call(
246 err: &mut Diagnostic,
247 expr: &hir::Expr<'tcx>,
250 if let hir::ExprKind::MethodCall(hir::PathSegment { ident: method, .. }, recv_expr, &[], _) = expr.kind &&
251 let Some(recv_ty) = self.typeck_results.borrow().expr_ty_opt(recv_expr) &&
252 self.can_coerce(recv_ty, expected) {
253 let span = if let Some(recv_span) = recv_expr.span.find_ancestor_inside(expr.span) {
254 expr.span.with_lo(recv_span.hi())
256 expr.span.with_lo(method.span.lo() - rustc_span::BytePos(1))
258 err.span_suggestion_verbose(
260 "try removing the method call",
262 Applicability::MachineApplicable,
269 pub fn suggest_deref_ref_or_into(
271 err: &mut Diagnostic,
272 expr: &hir::Expr<'tcx>,
275 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
277 let expr = expr.peel_blocks();
278 if let Some((sp, msg, suggestion, applicability, verbose, annotation)) =
279 self.check_ref(expr, found, expected)
282 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
284 err.span_suggestion(sp, &msg, suggestion, applicability);
287 let suggest_annotation = match expr.peel_drop_temps().kind {
288 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, _) => mutbl.ref_prefix_str(),
291 let mut tuple_indexes = Vec::new();
292 let mut expr_id = expr.hir_id;
293 for (parent_id, node) in self.tcx.hir().parent_iter(expr.hir_id) {
295 Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
299 .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
305 Node::Local(local) => {
306 if let Some(mut ty) = local.ty {
307 while let Some(index) = tuple_indexes.pop() {
309 TyKind::Tup(tys) => ty = &tys[index],
313 let annotation_span = ty.span;
315 annotation_span.with_hi(annotation_span.lo()),
316 "alternatively, consider changing the type annotation",
318 Applicability::MaybeIncorrect,
328 } else if self.suggest_else_fn_with_closure(err, expr, found, expected) {
330 } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected))
331 && let ty::FnDef(def_id, ..) = *found.kind()
332 && let Some(sp) = self.tcx.hir().span_if_local(def_id)
334 let name = self.tcx.item_name(def_id);
335 let kind = self.tcx.def_kind(def_id);
336 if let DefKind::Ctor(of, CtorKind::Fn) = kind {
337 err.span_label(sp, format!("`{name}` defines {} constructor here, which should be called", match of {
338 CtorOf::Struct => "a struct",
339 CtorOf::Variant => "an enum variant",
342 let descr = kind.descr(def_id);
343 err.span_label(sp, format!("{descr} `{name}` defined here"));
346 } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
349 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
350 if !methods.is_empty() {
351 let mut suggestions = methods.iter()
352 .filter_map(|conversion_method| {
353 let receiver_method_ident = expr.method_ident();
354 if let Some(method_ident) = receiver_method_ident
355 && method_ident.name == conversion_method.name
357 return None // do not suggest code that is already there (#53348)
360 let method_call_list = [sym::to_vec, sym::to_string];
361 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
362 && receiver_method.ident.name == sym::clone
363 && method_call_list.contains(&conversion_method.name)
364 // If receiver is `.clone()` and found type has one of those methods,
365 // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
366 // to an owned type (`Vec` or `String`). These conversions clone internally,
367 // so we remove the user's `clone` call.
370 receiver_method.ident.span,
371 conversion_method.name.to_string()
373 } else if expr.precedence().order()
374 < ExprPrecedence::MethodCall.order()
377 (expr.span.shrink_to_lo(), "(".to_string()),
378 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
381 vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
383 let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
384 if let Some(name) = struct_pat_shorthand_field {
387 (expr.span.shrink_to_lo(), format!("{}: ", name)),
393 if suggestions.peek().is_some() {
394 err.multipart_suggestions(
395 "try using a conversion method",
397 Applicability::MaybeIncorrect,
401 } else if let ty::Adt(found_adt, found_substs) = found.kind()
402 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
403 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
404 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
405 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
408 let ty = found_substs.type_at(0);
411 while let ty::Ref(_, inner, _) = peeled.kind() {
415 if let ty::Adt(adt, _) = peeled.kind()
416 && Some(adt.did()) == self.tcx.lang_items().string()
418 let sugg = if ref_cnt == 0 {
421 ".map(|x| x.as_str())"
423 err.span_suggestion_verbose(
424 expr.span.shrink_to_hi(),
425 fluent::hir_typeck_convert_to_str,
427 Applicability::MachineApplicable,
437 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
438 /// in the heap by calling `Box::new()`.
439 pub(in super::super) fn suggest_boxing_when_appropriate(
441 err: &mut Diagnostic,
442 expr: &hir::Expr<'_>,
446 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
447 // Do not suggest `Box::new` in const context.
450 if !expected.is_box() || found.is_box() {
453 let boxed_found = self.tcx.mk_box(found);
454 if self.can_coerce(boxed_found, expected) {
455 err.multipart_suggestion(
456 "store this in the heap by calling `Box::new`",
458 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
459 (expr.span.shrink_to_hi(), ")".to_string()),
461 Applicability::MachineApplicable,
464 "for more on the distinction between the stack and the heap, read \
465 https://doc.rust-lang.org/book/ch15-01-box.html, \
466 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
467 https://doc.rust-lang.org/std/boxed/index.html",
475 /// When encountering a closure that captures variables, where a FnPtr is expected,
476 /// suggest a non-capturing closure
477 pub(in super::super) fn suggest_no_capture_closure(
479 err: &mut Diagnostic,
483 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
484 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
485 // Report upto four upvars being captured to reduce the amount error messages
486 // reported back to the user.
487 let spans_and_labels = upvars
490 .map(|(var_hir_id, upvar)| {
491 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
492 let msg = format!("`{}` captured here", var_name);
495 .collect::<Vec<_>>();
497 let mut multi_span: MultiSpan =
498 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
499 for (sp, label) in spans_and_labels {
500 multi_span.push_span_label(sp, label);
504 "closures can only be coerced to `fn` types if they do not capture any variables"
512 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
513 #[instrument(skip(self, err))]
514 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
516 err: &mut Diagnostic,
517 expr: &hir::Expr<'_>,
523 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
524 // Do not suggest `Box::new` in const context.
527 let pin_did = self.tcx.lang_items().pin_type();
528 // This guards the `unwrap` and `mk_box` below.
529 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
532 let box_found = self.tcx.mk_box(found);
533 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
534 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
535 match expected.kind() {
536 ty::Adt(def, _) if Some(def.did()) == pin_did => {
537 if self.can_coerce(pin_box_found, expected) {
538 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
540 ty::Adt(def, _) if def.is_box() => {
541 err.help("use `Box::pin`");
544 err.multipart_suggestion(
545 "you need to pin and box this expression",
547 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
548 (expr.span.shrink_to_hi(), ")".to_string()),
550 Applicability::MaybeIncorrect,
555 } else if self.can_coerce(pin_found, expected) {
557 ty::Adt(def, _) if def.is_box() => {
558 err.help("use `Box::pin`");
567 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
568 // Check if the parent expression is a call to Pin::new. If it
569 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
570 // can suggest Box::pin.
571 let parent = self.tcx.hir().parent_id(expr.hir_id);
572 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
576 ExprKind::Path(QPath::TypeRelative(
578 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
582 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
585 "use `Box::pin` to pin and box this expression",
587 Applicability::MachineApplicable,
598 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
600 /// ```compile_fail,E0308
601 /// # fn bar_that_returns_u32() -> u32 { 4 }
603 /// bar_that_returns_u32()
607 /// This routine checks if the return expression in a block would make sense on its own as a
608 /// statement and the return type has been left as default or has been specified as `()`. If so,
609 /// it suggests adding a semicolon.
611 /// If the expression is the expression of a closure without block (`|| expr`), a
612 /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
613 pub fn suggest_missing_semicolon(
615 err: &mut Diagnostic,
616 expression: &'tcx hir::Expr<'tcx>,
620 if expected.is_unit() {
621 // `BlockTailExpression` only relevant if the tail expr would be
622 // useful on its own.
623 match expression.kind {
625 | ExprKind::MethodCall(..)
628 | ExprKind::Match(..)
629 | ExprKind::Block(..)
630 if expression.can_have_side_effects()
631 // If the expression is from an external macro, then do not suggest
632 // adding a semicolon, because there's nowhere to put it.
634 && !in_external_macro(self.tcx.sess, expression.span) =>
637 err.multipart_suggestion(
638 "consider using a semicolon here",
640 (expression.span.shrink_to_lo(), "{ ".to_owned()),
641 (expression.span.shrink_to_hi(), "; }".to_owned()),
643 Applicability::MachineApplicable,
647 expression.span.shrink_to_hi(),
648 "consider using a semicolon here",
650 Applicability::MachineApplicable,
659 /// A possible error is to forget to add a return type that is needed:
661 /// ```compile_fail,E0308
662 /// # fn bar_that_returns_u32() -> u32 { 4 }
664 /// bar_that_returns_u32()
668 /// This routine checks if the return type is left as default, the method is not part of an
669 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
671 pub(in super::super) fn suggest_missing_return_type(
673 err: &mut Diagnostic,
674 fn_decl: &hir::FnDecl<'_>,
681 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
682 // Only suggest changing the return type for methods that
683 // haven't set a return type at all (and aren't `fn main()` or an impl).
684 match &fn_decl.output {
685 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
686 // `fn main()` must return `()`, do not suggest changing return type
687 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
690 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
691 if let Some(found) = found.make_suggestable(self.tcx, false) {
692 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
694 } else if let ty::Closure(_, substs) = found.kind()
695 // FIXME(compiler-errors): Get better at printing binders...
696 && let closure = substs.as_closure()
697 && closure.sig().is_suggestable(self.tcx, false)
699 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
702 // FIXME: if `found` could be `impl Iterator` we should suggest that.
703 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
707 hir::FnRetTy::Return(ty) => {
710 if let hir::TyKind::OpaqueDef(item_id, ..) = ty.kind
711 && let hir::Node::Item(hir::Item {
712 kind: hir::ItemKind::OpaqueTy(op_ty),
714 }) = self.tcx.hir().get(item_id.hir_id())
715 && let hir::OpaqueTy {
718 && let hir::GenericBound::LangItemTrait(
719 hir::LangItem::Future, _, _, generic_args) = bound
720 && let hir::GenericArgs { bindings: [ty_binding], .. } = generic_args
721 && let hir::TypeBinding { kind, .. } = ty_binding
722 && let hir::TypeBindingKind::Equality { term } = kind
723 && let hir::Term::Ty(term_ty) = term {
724 // Check if async function's return type was omitted.
725 // Don't emit suggestions if the found type is `impl Future<...>`.
726 debug!("suggest_missing_return_type: found = {:?}", found);
727 if found.is_suggestable(self.tcx, false) {
728 if term_ty.span.is_empty() {
729 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
732 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
737 // Only point to return type if the expected type is the return type, as if they
738 // are not, the expectation must have been caused by something else.
739 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
740 let ty = self.astconv().ast_ty_to_ty(ty);
741 debug!("suggest_missing_return_type: return type {:?}", ty);
742 debug!("suggest_missing_return_type: expected type {:?}", ty);
743 let bound_vars = self.tcx.late_bound_vars(fn_id);
744 let ty = Binder::bind_with_vars(ty, bound_vars);
745 let ty = self.normalize(span, ty);
746 let ty = self.tcx.erase_late_bound_regions(ty);
747 if self.can_coerce(expected, ty) {
748 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
749 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
758 /// check whether the return type is a generic type with a trait bound
759 /// only suggest this if the generic param is not present in the arguments
760 /// if this is true, hint them towards changing the return type to `impl Trait`
761 /// ```compile_fail,E0308
762 /// fn cant_name_it<T: Fn() -> u32>() -> T {
766 fn try_suggest_return_impl_trait(
768 err: &mut Diagnostic,
773 // Only apply the suggestion if:
774 // - the return type is a generic parameter
775 // - the generic param is not used as a fn param
776 // - the generic param has at least one bound
777 // - the generic param doesn't appear in any other bounds where it's not the Self type
779 // - Changing the return type to be `impl <all bounds>`
781 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
783 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
785 let fn_node = self.tcx.hir().find(fn_id);
787 let Some(hir::Node::Item(hir::Item {
790 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
791 hir::Generics { params, predicates, .. },
795 })) = fn_node else { return };
797 if params.get(expected_ty_as_param.index as usize).is_none() {
801 // get all where BoundPredicates here, because they are used in to cases below
802 let where_predicates = predicates
804 .filter_map(|p| match p {
805 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
810 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
811 let ty = self.astconv().ast_ty_to_ty(bounded_ty);
816 .map(|(ty, bounds)| match ty.kind() {
817 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
818 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
819 _ => match ty.contains(expected) {
824 .collect::<Result<Vec<_>, _>>();
826 let Ok(where_predicates) = where_predicates else { return };
828 // now get all predicates in the same types as the where bounds, so we can chain them
829 let predicates_from_where =
830 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
832 // extract all bounds from the source code using their spans
833 let all_matching_bounds_strs = predicates_from_where
834 .filter_map(|bound| match bound {
835 GenericBound::Trait(_, _) => {
836 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
840 .collect::<Vec<String>>();
842 if all_matching_bounds_strs.len() == 0 {
846 let all_bounds_str = all_matching_bounds_strs.join(" + ");
848 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
849 let ty = self.astconv().ast_ty_to_ty( param);
850 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
853 if ty_param_used_in_fn_params {
859 "consider using an impl return type",
860 format!("impl {}", all_bounds_str),
861 Applicability::MaybeIncorrect,
865 pub(in super::super) fn suggest_missing_break_or_return_expr(
867 err: &mut Diagnostic,
868 expr: &'tcx hir::Expr<'tcx>,
869 fn_decl: &hir::FnDecl<'_>,
875 if !expected.is_unit() {
878 let found = self.resolve_vars_with_obligations(found);
880 let in_loop = self.is_loop(id)
881 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
883 let in_local_statement = self.is_local_statement(id)
888 .any(|(parent_id, _)| self.is_local_statement(parent_id));
890 if in_loop && in_local_statement {
891 err.multipart_suggestion(
892 "you might have meant to break the loop with this value",
894 (expr.span.shrink_to_lo(), "break ".to_string()),
895 (expr.span.shrink_to_hi(), ";".to_string()),
897 Applicability::MaybeIncorrect,
902 if let hir::FnRetTy::Return(ty) = fn_decl.output {
903 let ty = self.astconv().ast_ty_to_ty(ty);
904 let bound_vars = self.tcx.late_bound_vars(fn_id);
905 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
906 let ty = match self.tcx.asyncness(fn_id.owner) {
907 hir::IsAsync::Async => self.get_impl_future_output_ty(ty).unwrap_or_else(|| {
908 span_bug!(fn_decl.output.span(), "failed to get output type of async function")
910 hir::IsAsync::NotAsync => ty,
912 let ty = self.normalize(expr.span, ty);
913 if self.can_coerce(found, ty) {
914 err.multipart_suggestion(
915 "you might have meant to return this value",
917 (expr.span.shrink_to_lo(), "return ".to_string()),
918 (expr.span.shrink_to_hi(), ";".to_string()),
920 Applicability::MaybeIncorrect,
926 pub(in super::super) fn suggest_missing_parentheses(
928 err: &mut Diagnostic,
929 expr: &hir::Expr<'_>,
931 let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
932 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
933 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
934 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
941 /// Given an expression type mismatch, peel any `&` expressions until we get to
942 /// a block expression, and then suggest replacing the braces with square braces
943 /// if it was possibly mistaken array syntax.
944 pub(crate) fn suggest_block_to_brackets_peeling_refs(
946 diag: &mut Diagnostic,
947 mut expr: &hir::Expr<'_>,
948 mut expr_ty: Ty<'tcx>,
949 mut expected_ty: Ty<'tcx>,
952 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
954 hir::ExprKind::AddrOf(_, _, inner_expr),
955 ty::Ref(_, inner_expr_ty, _),
956 ty::Ref(_, inner_expected_ty, _),
959 expr_ty = *inner_expr_ty;
960 expected_ty = *inner_expected_ty;
962 (hir::ExprKind::Block(blk, _), _, _) => {
963 self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
971 pub(crate) fn suggest_clone_for_ref(
973 diag: &mut Diagnostic,
974 expr: &hir::Expr<'_>,
976 expected_ty: Ty<'tcx>,
978 if let ty::Ref(_, inner_ty, hir::Mutability::Not) = expr_ty.kind()
979 && let Some(clone_trait_def) = self.tcx.lang_items().clone_trait()
980 && expected_ty == *inner_ty
983 .type_implements_trait(
985 [self.tcx.erase_regions(expected_ty)],
988 .must_apply_modulo_regions()
990 diag.span_suggestion_verbose(
991 expr.span.shrink_to_hi(),
992 "consider using clone here",
994 Applicability::MachineApplicable,
1001 pub(crate) fn suggest_copied_or_cloned(
1003 diag: &mut Diagnostic,
1004 expr: &hir::Expr<'_>,
1006 expected_ty: Ty<'tcx>,
1008 let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
1009 let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
1010 if adt_def != expected_adt_def {
1014 let mut suggest_copied_or_cloned = || {
1015 let expr_inner_ty = substs.type_at(0);
1016 let expected_inner_ty = expected_substs.type_at(0);
1017 if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
1018 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
1020 let def_path = self.tcx.def_path_str(adt_def.did());
1021 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
1022 diag.span_suggestion_verbose(
1023 expr.span.shrink_to_hi(),
1025 "use `{def_path}::copied` to copy the value inside the `{def_path}`"
1028 Applicability::MachineApplicable,
1031 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
1032 && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1040 diag.span_suggestion_verbose(
1041 expr.span.shrink_to_hi(),
1043 "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
1046 Applicability::MachineApplicable,
1054 if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1055 && adt_def.did() == result_did
1056 // Check that the error types are equal
1057 && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1059 return suggest_copied_or_cloned();
1060 } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1061 && adt_def.did() == option_did
1063 return suggest_copied_or_cloned();
1069 pub(crate) fn suggest_into(
1071 diag: &mut Diagnostic,
1072 expr: &hir::Expr<'_>,
1074 expected_ty: Ty<'tcx>,
1076 let expr = expr.peel_blocks();
1078 // We have better suggestions for scalar interconversions...
1079 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1083 // Don't suggest turning a block into another type (e.g. `{}.into()`)
1084 if matches!(expr.kind, hir::ExprKind::Block(..)) {
1088 // We'll later suggest `.as_ref` when noting the type error,
1089 // so skip if we will suggest that instead.
1090 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1094 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1095 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1097 self.misc(expr.span),
1099 ty::Binder::dummy(self.tcx.mk_trait_ref(
1101 [expr_ty, expected_ty]
1105 let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1106 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1108 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1110 diag.multipart_suggestion(
1111 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1113 Applicability::MaybeIncorrect
1121 /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1122 pub(crate) fn suggest_option_to_bool(
1124 diag: &mut Diagnostic,
1125 expr: &hir::Expr<'_>,
1127 expected_ty: Ty<'tcx>,
1129 if !expected_ty.is_bool() {
1133 let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; };
1134 if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1138 let hir = self.tcx.hir();
1139 let cond_parent = hir.parent_iter(expr.hir_id).find(|(_, node)| {
1140 !matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1143 // `let Some(_) = a.is_some() && b`
1145 // since the user probably just misunderstood how `let else`
1146 // and `&&` work together.
1147 if let Some((_, hir::Node::Local(local))) = cond_parent
1148 && let hir::PatKind::Path(qpath) | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1149 && let hir::QPath::Resolved(None, path) = qpath
1150 && let Some(did) = path.res.opt_def_id()
1151 .and_then(|did| self.tcx.opt_parent(did))
1152 .and_then(|did| self.tcx.opt_parent(did))
1153 && self.tcx.is_diagnostic_item(sym::Option, did)
1158 diag.span_suggestion(
1159 expr.span.shrink_to_hi(),
1160 "use `Option::is_some` to test if the `Option` has a value",
1162 Applicability::MachineApplicable,
1168 /// Suggest wrapping the block in square brackets instead of curly braces
1169 /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1170 pub(crate) fn suggest_block_to_brackets(
1172 diag: &mut Diagnostic,
1173 blk: &hir::Block<'_>,
1175 expected_ty: Ty<'tcx>,
1177 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1178 if self.can_coerce(blk_ty, *elem_ty)
1179 && blk.stmts.is_empty()
1180 && blk.rules == hir::BlockCheckMode::DefaultBlock
1182 let source_map = self.tcx.sess.source_map();
1183 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1184 if snippet.starts_with('{') && snippet.ends_with('}') {
1185 diag.multipart_suggestion_verbose(
1186 "to create an array, use square brackets instead of curly braces",
1191 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1197 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1201 Applicability::MachineApplicable,
1209 #[instrument(skip(self, err))]
1210 pub(crate) fn suggest_floating_point_literal(
1212 err: &mut Diagnostic,
1213 expr: &hir::Expr<'_>,
1214 expected_ty: Ty<'tcx>,
1216 if !expected_ty.is_floating_point() {
1220 ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [start, end], _) => {
1221 err.span_suggestion_verbose(
1222 start.span.shrink_to_hi().with_hi(end.span.lo()),
1223 "remove the unnecessary `.` operator for a floating point literal",
1225 Applicability::MaybeIncorrect,
1229 ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, ..), [start], _) => {
1230 err.span_suggestion_verbose(
1231 expr.span.with_lo(start.span.hi()),
1232 "remove the unnecessary `.` operator for a floating point literal",
1234 Applicability::MaybeIncorrect,
1238 ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, ..), [end], _) => {
1239 err.span_suggestion_verbose(
1240 expr.span.until(end.span),
1241 "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1243 Applicability::MaybeIncorrect,
1247 ExprKind::Lit(Spanned {
1248 node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed),
1251 let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) else { return false; };
1252 if !(snippet.starts_with("0x") || snippet.starts_with("0X")) {
1255 if snippet.len() <= 5 || !snippet.is_char_boundary(snippet.len() - 3) {
1258 let (_, suffix) = snippet.split_at(snippet.len() - 3);
1259 let value = match suffix {
1260 "f32" => (lit - 0xf32) / (16 * 16 * 16),
1261 "f64" => (lit - 0xf64) / (16 * 16 * 16),
1264 err.span_suggestions(
1266 "rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
1267 [format!("0x{value:X} as {suffix}"), format!("{value}_{suffix}")],
1268 Applicability::MaybeIncorrect,
1276 /// Suggest providing `std::ptr::null()` or `std::ptr::null_mut()` if they
1277 /// pass in a literal 0 to an raw pointer.
1278 #[instrument(skip(self, err))]
1279 pub(crate) fn suggest_null_ptr_for_literal_zero_given_to_ptr_arg(
1281 err: &mut Diagnostic,
1282 expr: &hir::Expr<'_>,
1283 expected_ty: Ty<'tcx>,
1285 // Expected type needs to be a raw pointer.
1286 let ty::RawPtr(ty::TypeAndMut { mutbl, .. }) = expected_ty.kind() else {
1290 // Provided expression needs to be a literal `0`.
1291 let ExprKind::Lit(Spanned {
1292 node: rustc_ast::LitKind::Int(0, _),
1294 }) = expr.kind else {
1298 // We need to find a null pointer symbol to suggest
1299 let null_sym = match mutbl {
1300 hir::Mutability::Not => sym::ptr_null,
1301 hir::Mutability::Mut => sym::ptr_null_mut,
1303 let Some(null_did) = self.tcx.get_diagnostic_item(null_sym) else {
1306 let null_path_str = with_no_trimmed_paths!(self.tcx.def_path_str(null_did));
1308 // We have satisfied all requirements to provide a suggestion. Emit it.
1309 err.span_suggestion(
1311 format!("if you meant to create a null pointer, use `{null_path_str}()`"),
1312 null_path_str + "()",
1313 Applicability::MachineApplicable,
1319 pub(crate) fn suggest_associated_const(
1321 err: &mut Diagnostic,
1322 expr: &hir::Expr<'_>,
1323 expected_ty: Ty<'tcx>,
1325 let Some((DefKind::AssocFn, old_def_id)) = self.typeck_results.borrow().type_dependent_def(expr.hir_id) else {
1328 let old_item_name = self.tcx.item_name(old_def_id);
1329 let capitalized_name = Symbol::intern(&old_item_name.as_str().to_uppercase());
1330 if old_item_name == capitalized_name {
1333 let (item, segment) = match expr.kind {
1334 hir::ExprKind::Path(QPath::Resolved(
1336 hir::Path { segments: [segment], .. },
1338 | hir::ExprKind::Path(QPath::TypeRelative(ty, segment)) => {
1339 let self_ty = self.astconv().ast_ty_to_ty(ty);
1340 if let Ok(pick) = self.probe_for_name(
1342 Ident::new(capitalized_name, segment.ident.span),
1347 ProbeScope::TraitsInScope,
1349 (pick.item, segment)
1354 hir::ExprKind::Path(QPath::Resolved(
1356 hir::Path { segments: [.., segment], .. },
1358 // we resolved through some path that doesn't end in the item name,
1359 // better not do a bad suggestion by accident.
1360 if old_item_name != segment.ident.name {
1363 if let Some(item) = self
1365 .associated_items(self.tcx.parent(old_def_id))
1366 .filter_by_name_unhygienic(capitalized_name)
1376 if item.def_id == old_def_id || self.tcx.def_kind(item.def_id) != DefKind::AssocConst {
1380 let item_ty = self.tcx.type_of(item.def_id);
1381 // FIXME(compiler-errors): This check is *so* rudimentary
1382 if item_ty.needs_subst() {
1385 if self.can_coerce(item_ty, expected_ty) {
1386 err.span_suggestion_verbose(
1388 format!("try referring to the associated const `{capitalized_name}` instead",),
1390 Applicability::MachineApplicable,
1398 fn is_loop(&self, id: hir::HirId) -> bool {
1399 let node = self.tcx.hir().get(id);
1400 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1403 fn is_local_statement(&self, id: hir::HirId) -> bool {
1404 let node = self.tcx.hir().get(id);
1405 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1408 /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1409 /// which is a side-effect of autoref.
1410 pub(crate) fn note_type_is_not_clone(
1412 diag: &mut Diagnostic,
1413 expected_ty: Ty<'tcx>,
1415 expr: &hir::Expr<'_>,
1417 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1418 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1419 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1420 let results = self.typeck_results.borrow();
1421 // First, look for a `Clone::clone` call
1422 if segment.ident.name == sym::clone
1423 && results.type_dependent_def_id(expr.hir_id).map_or(
1426 let assoc_item = self.tcx.associated_item(did);
1427 assoc_item.container == ty::AssocItemContainer::TraitContainer
1428 && assoc_item.container_id(self.tcx) == clone_trait_did
1431 // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1432 // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1433 && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1434 // Check that we're in fact trying to clone into the expected type
1435 && self.can_coerce(*pointee_ty, expected_ty)
1436 && let trait_ref = ty::Binder::dummy(self.tcx.mk_trait_ref(clone_trait_did, [expected_ty]))
1437 // And the expected type doesn't implement `Clone`
1438 && !self.predicate_must_hold_considering_regions(&traits::Obligation::new(
1440 traits::ObligationCause::dummy(),
1448 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1451 let owner = self.tcx.hir().enclosing_body_owner(expr.hir_id);
1452 if let ty::Param(param) = expected_ty.kind()
1453 && let Some(generics) = self.tcx.hir().get_generics(owner)
1455 suggest_constraining_type_params(
1459 vec![(param.name.as_str(), "Clone", Some(clone_trait_did))].into_iter(),
1462 self.suggest_derive(diag, &[(trait_ref.to_predicate(self.tcx), None, None)]);
1467 /// A common error is to add an extra semicolon:
1469 /// ```compile_fail,E0308
1470 /// fn foo() -> usize {
1475 /// This routine checks if the final statement in a block is an
1476 /// expression with an explicit semicolon whose type is compatible
1477 /// with `expected_ty`. If so, it suggests removing the semicolon.
1478 pub(crate) fn consider_removing_semicolon(
1480 blk: &'tcx hir::Block<'tcx>,
1481 expected_ty: Ty<'tcx>,
1482 err: &mut Diagnostic,
1484 if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1485 if let StatementAsExpression::NeedsBoxing = boxed {
1486 err.span_suggestion_verbose(
1488 "consider removing this semicolon and boxing the expression",
1490 Applicability::HasPlaceholders,
1493 err.span_suggestion_short(
1495 "remove this semicolon to return this value",
1497 Applicability::MachineApplicable,