1use core::cmp::min;
3use core::iter;
4
5use hir::def_id::LocalDefId;
6use rustc_ast::util::parser::ExprPrecedence;
7use rustc_data_structures::packed::Pu128;
8use rustc_errors::{Applicability, Diag, MultiSpan, listify, msg};
9use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
10use rustc_hir::intravisit::Visitor;
11use rustc_hir::lang_items::LangItem;
12use rustc_hir::{
13 self as hir, Arm, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, ExprKind,
14 GenericBound, HirId, LoopSource, Node, PatExpr, PatExprKind, Path, QPath, Stmt, StmtKind,
15 TyKind, WherePredicateKind, expr_needs_parens, is_range_literal,
16};
17use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
18use rustc_hir_analysis::suggest_impl_trait;
19use rustc_middle::middle::stability::EvalResult;
20use rustc_middle::span_bug;
21use rustc_middle::ty::print::with_no_trimmed_paths;
22use rustc_middle::ty::{
23 self, Article, Binder, IsSuggestable, Ty, TyCtxt, TypeVisitableExt, Unnormalized, Upcast,
24 suggest_constraining_type_params,
25};
26use rustc_session::errors::ExprParenthesesNeeded;
27use rustc_span::{ExpnKind, Ident, MacroKind, Span, Spanned, Symbol, sym};
28use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
29use rustc_trait_selection::error_reporting::traits::DefIdOrName;
30use rustc_trait_selection::error_reporting::traits::suggestions::ReturnsVisitor;
31use rustc_trait_selection::infer::InferCtxtExt;
32use rustc_trait_selection::traits;
33use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
34use tracing::{debug, instrument};
35
36use super::FnCtxt;
37use crate::errors::{self, SuggestBoxingForReturnImplTrait};
38use crate::fn_ctxt::rustc_span::BytePos;
39use crate::method::probe;
40use crate::method::probe::{IsSuggestion, Mode, ProbeScope};
41
42impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43 pub(crate) fn body_fn_sig(&self) -> Option<ty::FnSig<'tcx>> {
44 self.typeck_results
45 .borrow()
46 .liberated_fn_sigs()
47 .get(self.tcx.local_def_id_to_hir_id(self.body_id))
48 .copied()
49 }
50
51 pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diag<'_>) {
52 err.span_suggestion_short(
55 span.shrink_to_hi(),
56 "consider using a semicolon here",
57 ";",
58 Applicability::MaybeIncorrect,
59 );
60 }
61
62 pub(crate) fn suggest_mismatched_types_on_tail(
68 &self,
69 err: &mut Diag<'_>,
70 expr: &'tcx hir::Expr<'tcx>,
71 expected: Ty<'tcx>,
72 found: Ty<'tcx>,
73 blk_id: HirId,
74 ) -> bool {
75 let expr = expr.peel_drop_temps();
76 let mut pointing_at_return_type = false;
77 if let hir::ExprKind::Break(..) = expr.kind {
78 return false;
80 }
81 if let Some((fn_id, fn_decl)) = self.get_fn_decl(blk_id) {
82 pointing_at_return_type =
83 self.suggest_missing_return_type(err, fn_decl, expected, found, fn_id);
84 self.suggest_missing_break_or_return_expr(
85 err, expr, fn_decl, expected, found, blk_id, fn_id,
86 );
87 }
88 pointing_at_return_type
89 }
90
91 pub(crate) fn suggest_fn_call(
99 &self,
100 err: &mut Diag<'_>,
101 expr: &hir::Expr<'_>,
102 found: Ty<'tcx>,
103 can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
104 ) -> bool {
105 let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(found) else {
106 return false;
107 };
108 if can_satisfy(output) {
109 let (sugg_call, mut applicability) = match inputs.len() {
110 0 => ("".to_string(), Applicability::MachineApplicable),
111 1..=4 => (
112 inputs
113 .iter()
114 .map(|ty| {
115 if ty.is_suggestable(self.tcx, false) {
116 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", ty))
})format!("/* {ty} */")
117 } else {
118 "/* value */".to_string()
119 }
120 })
121 .collect::<Vec<_>>()
122 .join(", "),
123 Applicability::HasPlaceholders,
124 ),
125 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
126 };
127
128 let msg = match def_id_or_name {
129 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
130 DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
131 DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
132 kind => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("call this {0}",
self.tcx.def_kind_descr(kind, def_id)))
})format!("call this {}", self.tcx.def_kind_descr(kind, def_id)),
133 },
134 DefIdOrName::Name(name) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("call this {0}", name))
})format!("call this {name}"),
135 };
136
137 let sugg = match expr.kind {
138 hir::ExprKind::Call(..)
139 | hir::ExprKind::Path(..)
140 | hir::ExprKind::Index(..)
141 | hir::ExprKind::Lit(..) => {
142 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", sugg_call))
}))]))vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
143 }
144 hir::ExprKind::Closure { .. } => {
145 applicability = Applicability::MaybeIncorrect;
147 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_lo(), "(".to_string()),
(expr.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(")({0})", sugg_call))
}))]))vec![
148 (expr.span.shrink_to_lo(), "(".to_string()),
149 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
150 ]
151 }
152 _ => {
153 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_lo(), "(".to_string()),
(expr.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(")({0})", sugg_call))
}))]))vec![
154 (expr.span.shrink_to_lo(), "(".to_string()),
155 (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
156 ]
157 }
158 };
159
160 err.multipart_suggestion(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use parentheses to {0}", msg))
})format!("use parentheses to {msg}"), sugg, applicability);
161 return true;
162 }
163 false
164 }
165
166 pub(in super::super) fn extract_callable_info(
170 &self,
171 ty: Ty<'tcx>,
172 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
173 self.err_ctxt().extract_callable_info(self.body_id, self.param_env, ty)
174 }
175
176 pub(crate) fn suggest_two_fn_call(
177 &self,
178 err: &mut Diag<'_>,
179 lhs_expr: &'tcx hir::Expr<'tcx>,
180 lhs_ty: Ty<'tcx>,
181 rhs_expr: &'tcx hir::Expr<'tcx>,
182 rhs_ty: Ty<'tcx>,
183 can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
184 ) -> bool {
185 if lhs_expr.span.in_derive_expansion() || rhs_expr.span.in_derive_expansion() {
186 return false;
187 }
188 let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_ty) else {
189 return false;
190 };
191 let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_ty) else {
192 return false;
193 };
194
195 if can_satisfy(lhs_output_ty, rhs_output_ty) {
196 let mut sugg = ::alloc::vec::Vec::new()vec![];
197 let mut applicability = Applicability::MachineApplicable;
198
199 for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
200 let (sugg_call, this_applicability) = match inputs.len() {
201 0 => ("".to_string(), Applicability::MachineApplicable),
202 1..=4 => (
203 inputs
204 .iter()
205 .map(|ty| {
206 if ty.is_suggestable(self.tcx, false) {
207 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", ty))
})format!("/* {ty} */")
208 } else {
209 "/* value */".to_string()
210 }
211 })
212 .collect::<Vec<_>>()
213 .join(", "),
214 Applicability::HasPlaceholders,
215 ),
216 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
217 };
218
219 applicability = applicability.max(this_applicability);
220
221 match expr.kind {
222 hir::ExprKind::Call(..)
223 | hir::ExprKind::Path(..)
224 | hir::ExprKind::Index(..)
225 | hir::ExprKind::Lit(..) => {
226 sugg.extend([(expr.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", sugg_call))
})format!("({sugg_call})"))]);
227 }
228 hir::ExprKind::Closure { .. } => {
229 applicability = Applicability::MaybeIncorrect;
231 sugg.extend([
232 (expr.span.shrink_to_lo(), "(".to_string()),
233 (expr.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(")({0})", sugg_call))
})format!(")({sugg_call})")),
234 ]);
235 }
236 _ => {
237 sugg.extend([
238 (expr.span.shrink_to_lo(), "(".to_string()),
239 (expr.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(")({0})", sugg_call))
})format!(")({sugg_call})")),
240 ]);
241 }
242 }
243 }
244
245 err.multipart_suggestion("use parentheses to call these", sugg, applicability);
246
247 true
248 } else {
249 false
250 }
251 }
252
253 pub(crate) fn suggest_remove_last_method_call(
254 &self,
255 err: &mut Diag<'_>,
256 expr: &hir::Expr<'tcx>,
257 expected: Ty<'tcx>,
258 ) -> bool {
259 if let hir::ExprKind::MethodCall(hir::PathSegment { ident: method, .. }, recv_expr, &[], _) =
260 expr.kind
261 && let Some(recv_ty) = self.typeck_results.borrow().expr_ty_opt(recv_expr)
262 && self.may_coerce(recv_ty, expected)
263 && let name = method.name.as_str()
264 && (name.starts_with("to_") || name.starts_with("as_") || name == "into")
265 {
266 let span = if let Some(recv_span) = recv_expr.span.find_ancestor_inside(expr.span) {
267 expr.span.with_lo(recv_span.hi())
268 } else {
269 expr.span.with_lo(method.span.lo() - rustc_span::BytePos(1))
270 };
271 err.span_suggestion_verbose(
272 span,
273 "try removing the method call",
274 "",
275 Applicability::MachineApplicable,
276 );
277 return true;
278 }
279 false
280 }
281
282 pub(crate) fn suggest_deref_ref_or_into(
283 &self,
284 err: &mut Diag<'_>,
285 expr: &hir::Expr<'tcx>,
286 expected: Ty<'tcx>,
287 found: Ty<'tcx>,
288 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
289 ) -> bool {
290 let expr = expr.peel_blocks();
291 let methods =
292 self.get_conversion_methods_for_diagnostic(expr.span, expected, found, expr.hir_id);
293
294 if let Some((suggestion, msg, applicability, verbose, annotation)) =
295 self.suggest_deref_or_ref(expr, found, expected)
296 {
297 if verbose {
298 err.multipart_suggestion(msg, suggestion, applicability);
299 } else {
300 err.multipart_suggestion(msg, suggestion, applicability);
301 }
302 if annotation {
303 let suggest_annotation = match expr.peel_drop_temps().kind {
304 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, _) => mutbl.ref_prefix_str(),
305 _ => return true,
306 };
307 let mut tuple_indexes = Vec::new();
308 let mut expr_id = expr.hir_id;
309 for (parent_id, node) in self.tcx.hir_parent_iter(expr.hir_id) {
310 match node {
311 Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
312 tuple_indexes.push(
313 subs.iter()
314 .enumerate()
315 .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
316 .unwrap()
317 .0,
318 );
319 expr_id = parent_id;
320 }
321 Node::LetStmt(local) => {
322 if let Some(mut ty) = local.ty {
323 while let Some(index) = tuple_indexes.pop() {
324 match ty.kind {
325 TyKind::Tup(tys) => ty = &tys[index],
326 _ => return true,
327 }
328 }
329 let annotation_span = ty.span;
330 err.span_suggestion(
331 annotation_span.with_hi(annotation_span.lo()),
332 "alternatively, consider changing the type annotation",
333 suggest_annotation,
334 Applicability::MaybeIncorrect,
335 );
336 }
337 break;
338 }
339 _ => break,
340 }
341 }
342 }
343 return true;
344 }
345
346 if self.suggest_else_fn_with_closure(err, expr, found, expected) {
347 return true;
348 }
349
350 if self.suggest_fn_call(err, expr, found, |output| self.may_coerce(output, expected))
351 && let ty::FnDef(def_id, ..) = *found.kind()
352 && let Some(sp) = self.tcx.hir_span_if_local(def_id)
353 {
354 let name = self.tcx.item_name(def_id);
355 let kind = self.tcx.def_kind(def_id);
356 if let DefKind::Ctor(of, CtorKind::Fn) = kind {
357 err.span_label(
358 sp,
359 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{1}` defines {0} constructor here, which should be called",
match of {
CtorOf::Struct => "a struct",
CtorOf::Variant => "an enum variant",
}, name))
})format!(
360 "`{name}` defines {} constructor here, which should be called",
361 match of {
362 CtorOf::Struct => "a struct",
363 CtorOf::Variant => "an enum variant",
364 }
365 ),
366 );
367 } else {
368 let descr = self.tcx.def_kind_descr(kind, def_id);
369 err.span_label(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` defined here", descr,
name))
})format!("{descr} `{name}` defined here"));
370 }
371 return true;
372 }
373
374 if self.suggest_cast(err, expr, found, expected, expected_ty_expr) {
375 return true;
376 }
377
378 if !methods.is_empty() {
379 let mut suggestions = methods
380 .iter()
381 .filter_map(|conversion_method| {
382 let conversion_method_name = conversion_method.name();
383 let receiver_method_ident = expr.method_ident();
384 if let Some(method_ident) = receiver_method_ident
385 && method_ident.name == conversion_method_name
386 {
387 return None; }
389
390 let method_call_list = [sym::to_vec, sym::to_string];
391 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
392 && receiver_method.ident.name == sym::clone
393 && method_call_list.contains(&conversion_method_name)
394 {
399 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(receiver_method.ident.span, conversion_method_name.to_string())]))vec![(receiver_method.ident.span, conversion_method_name.to_string())]
400 } else if self.precedence(expr) < ExprPrecedence::Unambiguous {
401 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_lo(), "(".to_string()),
(expr.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(").{0}()",
conversion_method_name))
}))]))vec![
402 (expr.span.shrink_to_lo(), "(".to_string()),
403 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method_name)),
404 ]
405 } else {
406 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(".{0}()",
conversion_method_name))
}))]))vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method_name))]
407 };
408 let struct_pat_shorthand_field =
409 self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr);
410 if let Some(name) = struct_pat_shorthand_field {
411 sugg.insert(0, (expr.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", name))
})format!("{name}: ")));
412 }
413 Some(sugg)
414 })
415 .peekable();
416 if suggestions.peek().is_some() {
417 err.multipart_suggestions(
418 "try using a conversion method",
419 suggestions,
420 Applicability::MaybeIncorrect,
421 );
422 return true;
423 }
424 }
425
426 if let Some((found_ty_inner, expected_ty_inner, error_tys)) =
427 self.deconstruct_option_or_result(found, expected)
428 && let ty::Ref(_, peeled, hir::Mutability::Not) = *expected_ty_inner.kind()
429 {
430 let inner_expr = expr.peel_borrows();
432 if !inner_expr.span.eq_ctxt(expr.span) {
433 return false;
434 }
435 let borrow_removal_span = if inner_expr.hir_id == expr.hir_id {
436 None
437 } else {
438 Some(expr.span.shrink_to_lo().until(inner_expr.span))
439 };
440 let error_tys_equate_as_ref = error_tys.is_none_or(|(found, expected)| {
443 self.can_eq(
444 self.param_env,
445 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, found),
446 expected,
447 )
448 });
449
450 let prefix_wrap = |sugg: &str| {
451 if let Some(name) = self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
452 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}{1}", name, sugg))
})format!(": {}{}", name, sugg)
453 } else {
454 sugg.to_string()
455 }
456 };
457
458 if self.can_eq(self.param_env, found_ty_inner, peeled) && error_tys_equate_as_ref {
461 let sugg = prefix_wrap(".as_ref()");
462 err.subdiagnostic(errors::SuggestConvertViaMethod {
463 span: expr.span.shrink_to_hi(),
464 sugg,
465 expected,
466 found,
467 borrow_removal_span,
468 });
469 return true;
470 } else if let ty::Ref(_, peeled_found_ty, _) = found_ty_inner.kind()
471 && let ty::Adt(adt, _) = peeled_found_ty.peel_refs().kind()
472 && self.tcx.is_lang_item(adt.did(), LangItem::String)
473 && peeled.is_str()
474 && error_tys.is_none_or(|(found, expected)| {
476 self.can_eq(self.param_env, found, expected)
477 })
478 {
479 let sugg = prefix_wrap(".map(|x| x.as_str())");
480 err.span_suggestion_verbose(
481 expr.span.shrink_to_hi(),
482 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("try converting the passed type into a `&str`"))msg!("try converting the passed type into a `&str`"),
483 sugg,
484 Applicability::MachineApplicable,
485 );
486 return true;
487 } else {
488 if !error_tys_equate_as_ref {
489 return false;
490 }
491 let mut steps = self.autoderef(expr.span, found_ty_inner).silence_errors();
492 if let Some((deref_ty, _)) = steps.nth(1)
493 && self.can_eq(self.param_env, deref_ty, peeled)
494 {
495 let sugg = prefix_wrap(".as_deref()");
496 err.subdiagnostic(errors::SuggestConvertViaMethod {
497 span: expr.span.shrink_to_hi(),
498 sugg,
499 expected,
500 found,
501 borrow_removal_span,
502 });
503 return true;
504 }
505 for (deref_ty, n_step) in steps {
506 if self.can_eq(self.param_env, deref_ty, peeled) {
507 let explicit_deref = "*".repeat(n_step);
508 let sugg = prefix_wrap(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!(".map(|v| &{0}v)", explicit_deref))
})format!(".map(|v| &{explicit_deref}v)"));
509 err.subdiagnostic(errors::SuggestConvertViaMethod {
510 span: expr.span.shrink_to_hi(),
511 sugg,
512 expected,
513 found,
514 borrow_removal_span,
515 });
516 return true;
517 }
518 }
519 }
520 }
521
522 false
523 }
524
525 fn deconstruct_option_or_result(
529 &self,
530 found_ty: Ty<'tcx>,
531 expected_ty: Ty<'tcx>,
532 ) -> Option<(Ty<'tcx>, Ty<'tcx>, Option<(Ty<'tcx>, Ty<'tcx>)>)> {
533 let ty::Adt(found_adt, found_args) = found_ty.peel_refs().kind() else {
534 return None;
535 };
536 let ty::Adt(expected_adt, expected_args) = expected_ty.kind() else {
537 return None;
538 };
539 if self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
540 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
541 {
542 Some((found_args.type_at(0), expected_args.type_at(0), None))
543 } else if self.tcx.is_diagnostic_item(sym::Result, found_adt.did())
544 && self.tcx.is_diagnostic_item(sym::Result, expected_adt.did())
545 {
546 Some((
547 found_args.type_at(0),
548 expected_args.type_at(0),
549 Some((found_args.type_at(1), expected_args.type_at(1))),
550 ))
551 } else {
552 None
553 }
554 }
555
556 pub(in super::super) fn suggest_boxing_when_appropriate(
559 &self,
560 err: &mut Diag<'_>,
561 span: Span,
562 hir_id: HirId,
563 expected: Ty<'tcx>,
564 found: Ty<'tcx>,
565 ) -> bool {
566 if self.tcx.hir_is_inside_const_context(hir_id) || !expected.is_box() || found.is_box() {
568 return false;
569 }
570 if self.may_coerce(Ty::new_box(self.tcx, found), expected) {
571 let suggest_boxing = match *found.kind() {
572 ty::Tuple(tuple) if tuple.is_empty() => {
573 errors::SuggestBoxing::Unit { start: span.shrink_to_lo(), end: span }
574 }
575 ty::Coroutine(def_id, ..)
576 if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.coroutine_kind(def_id)
{
Some(CoroutineKind::Desugared(CoroutineDesugaring::Async,
CoroutineSource::Closure)) => true,
_ => false,
}matches!(
577 self.tcx.coroutine_kind(def_id),
578 Some(CoroutineKind::Desugared(
579 CoroutineDesugaring::Async,
580 CoroutineSource::Closure
581 ))
582 ) =>
583 {
584 errors::SuggestBoxing::AsyncBody
585 }
586 _ if let Node::ExprField(expr_field) = self.tcx.parent_hir_node(hir_id)
587 && expr_field.is_shorthand =>
588 {
589 errors::SuggestBoxing::ExprFieldShorthand {
590 start: span.shrink_to_lo(),
591 end: span.shrink_to_hi(),
592 ident: expr_field.ident,
593 }
594 }
595 _ => errors::SuggestBoxing::Other {
596 start: span.shrink_to_lo(),
597 end: span.shrink_to_hi(),
598 },
599 };
600 err.subdiagnostic(suggest_boxing);
601
602 true
603 } else {
604 false
605 }
606 }
607
608 pub(in super::super) fn suggest_no_capture_closure(
611 &self,
612 err: &mut Diag<'_>,
613 expected: Ty<'tcx>,
614 found: Ty<'tcx>,
615 ) -> bool {
616 if let (ty::FnPtr(..), ty::Closure(def_id, _)) = (expected.kind(), found.kind())
617 && let Some(upvars) = self.tcx.upvars_mentioned(*def_id)
618 {
619 let spans_and_labels = upvars
622 .iter()
623 .take(4)
624 .map(|(var_hir_id, upvar)| {
625 let var_name = self.tcx.hir_name(*var_hir_id).to_string();
626 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` captured here", var_name))
})format!("`{var_name}` captured here");
627 (upvar.span, msg)
628 })
629 .collect::<Vec<_>>();
630
631 let mut multi_span: MultiSpan =
632 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
633 for (sp, label) in spans_and_labels {
634 multi_span.push_span_label(sp, label);
635 }
636 err.span_note(
637 multi_span,
638 "closures can only be coerced to `fn` types if they do not capture any variables",
639 );
640 return true;
641 }
642 false
643 }
644
645 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("suggest_calling_boxed_future_when_appropriate",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(646u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["expr", "expected",
"found"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&found)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
if self.tcx.hir_is_inside_const_context(expr.hir_id) {
return false;
}
let pin_did = self.tcx.lang_items().pin_type();
if pin_did.is_none() ||
self.tcx.lang_items().owned_box().is_none() {
return false;
}
let box_found = Ty::new_box(self.tcx, found);
let Some(pin_box_found) =
Ty::new_lang_item(self.tcx, box_found,
LangItem::Pin) else { return false; };
let Some(pin_found) =
Ty::new_lang_item(self.tcx, found,
LangItem::Pin) else { return false; };
match expected.kind() {
ty::Adt(def, _) if Some(def.did()) == pin_did => {
if self.may_coerce(pin_box_found, expected) {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:675",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(675u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("can coerce {0:?} to {1:?}, suggesting Box::pin",
pin_box_found, expected) as &dyn Value))])
});
} else { ; }
};
match found.kind() {
ty::Adt(def, _) if def.is_box() => {
err.help("use `Box::pin`");
}
_ => {
let prefix =
if let Some(name) =
self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr)
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", name))
})
} else { String::new() };
let suggestion =
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Box::pin(", prefix))
})), (expr.span.shrink_to_hi(), ")".to_string())]));
err.multipart_suggestion("you need to pin and box this expression",
suggestion, Applicability::MaybeIncorrect);
}
}
true
} else if self.may_coerce(pin_found, expected) {
match found.kind() {
ty::Adt(def, _) if def.is_box() => {
err.help("use `Box::pin`");
true
}
_ => false,
}
} else { false }
}
ty::Adt(def, _) if
def.is_box() && self.may_coerce(box_found, expected) => {
let Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), ..
}) =
self.tcx.parent_hir_node(expr.hir_id) else {
return false;
};
match fn_name.kind {
ExprKind::Path(QPath::TypeRelative(hir::Ty {
kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty,
.. })), .. }, method)) if
recv_ty.opt_def_id() == pin_did &&
method.ident.name == sym::new => {
err.span_suggestion(fn_name.span,
"use `Box::pin` to pin and box this expression", "Box::pin",
Applicability::MachineApplicable);
true
}
_ => false,
}
}
_ => false,
}
}
}
}#[instrument(skip(self, err))]
647 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
648 &self,
649 err: &mut Diag<'_>,
650 expr: &hir::Expr<'_>,
651 expected: Ty<'tcx>,
652 found: Ty<'tcx>,
653 ) -> bool {
654 if self.tcx.hir_is_inside_const_context(expr.hir_id) {
657 return false;
659 }
660 let pin_did = self.tcx.lang_items().pin_type();
661 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
663 return false;
664 }
665 let box_found = Ty::new_box(self.tcx, found);
666 let Some(pin_box_found) = Ty::new_lang_item(self.tcx, box_found, LangItem::Pin) else {
667 return false;
668 };
669 let Some(pin_found) = Ty::new_lang_item(self.tcx, found, LangItem::Pin) else {
670 return false;
671 };
672 match expected.kind() {
673 ty::Adt(def, _) if Some(def.did()) == pin_did => {
674 if self.may_coerce(pin_box_found, expected) {
675 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
676 match found.kind() {
677 ty::Adt(def, _) if def.is_box() => {
678 err.help("use `Box::pin`");
679 }
680 _ => {
681 let prefix = if let Some(name) =
682 self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr)
683 {
684 format!("{}: ", name)
685 } else {
686 String::new()
687 };
688 let suggestion = vec![
689 (expr.span.shrink_to_lo(), format!("{prefix}Box::pin(")),
690 (expr.span.shrink_to_hi(), ")".to_string()),
691 ];
692 err.multipart_suggestion(
693 "you need to pin and box this expression",
694 suggestion,
695 Applicability::MaybeIncorrect,
696 );
697 }
698 }
699 true
700 } else if self.may_coerce(pin_found, expected) {
701 match found.kind() {
702 ty::Adt(def, _) if def.is_box() => {
703 err.help("use `Box::pin`");
704 true
705 }
706 _ => false,
707 }
708 } else {
709 false
710 }
711 }
712 ty::Adt(def, _) if def.is_box() && self.may_coerce(box_found, expected) => {
713 let Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. }) =
717 self.tcx.parent_hir_node(expr.hir_id)
718 else {
719 return false;
720 };
721 match fn_name.kind {
722 ExprKind::Path(QPath::TypeRelative(
723 hir::Ty {
724 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
725 ..
726 },
727 method,
728 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
729 err.span_suggestion(
730 fn_name.span,
731 "use `Box::pin` to pin and box this expression",
732 "Box::pin",
733 Applicability::MachineApplicable,
734 );
735 true
736 }
737 _ => false,
738 }
739 }
740 _ => false,
741 }
742 }
743
744 pub(crate) fn suggest_missing_semicolon(
760 &self,
761 err: &mut Diag<'_>,
762 expression: &'tcx hir::Expr<'tcx>,
763 expected: Ty<'tcx>,
764 needs_block: bool,
765 parent_is_closure: bool,
766 ) {
767 if !expected.is_unit() {
768 return;
769 }
770 match expression.kind {
773 ExprKind::Call(..)
774 | ExprKind::MethodCall(..)
775 | ExprKind::Loop(..)
776 | ExprKind::If(..)
777 | ExprKind::Match(..)
778 | ExprKind::Block(..)
779 if expression.can_have_side_effects()
780 && !expression.span.in_external_macro(self.tcx.sess.source_map()) =>
784 {
785 if needs_block {
786 err.multipart_suggestion(
787 "consider using a semicolon here",
788 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expression.span.shrink_to_lo(), "{ ".to_owned()),
(expression.span.shrink_to_hi(), "; }".to_owned())]))vec![
789 (expression.span.shrink_to_lo(), "{ ".to_owned()),
790 (expression.span.shrink_to_hi(), "; }".to_owned()),
791 ],
792 Applicability::MachineApplicable,
793 );
794 } else if let hir::Node::Block(block) = self.tcx.parent_hir_node(expression.hir_id)
795 && let hir::Node::Expr(expr) = self.tcx.parent_hir_node(block.hir_id)
796 && let hir::Node::Expr(if_expr) = self.tcx.parent_hir_node(expr.hir_id)
797 && let hir::ExprKind::If(_cond, _then, Some(_else)) = if_expr.kind
798 && let hir::Node::Stmt(stmt) = self.tcx.parent_hir_node(if_expr.hir_id)
799 && let hir::StmtKind::Expr(_) = stmt.kind
800 && self.is_next_stmt_expr_continuation(stmt.hir_id)
801 {
802 err.subdiagnostic(ExprParenthesesNeeded::surrounding(stmt.span));
803 } else {
804 err.span_suggestion(
805 expression.span.shrink_to_hi(),
806 "consider using a semicolon here",
807 ";",
808 Applicability::MachineApplicable,
809 );
810 }
811 }
812 ExprKind::Path(..) | ExprKind::Lit(_)
813 if parent_is_closure
814 && !expression.span.in_external_macro(self.tcx.sess.source_map()) =>
815 {
816 err.span_suggestion_verbose(
817 expression.span.shrink_to_lo(),
818 "consider ignoring the value",
819 "_ = ",
820 Applicability::MachineApplicable,
821 );
822 }
823 _ => {
824 if let hir::Node::Block(block) = self.tcx.parent_hir_node(expression.hir_id)
825 && let hir::Node::Expr(expr) = self.tcx.parent_hir_node(block.hir_id)
826 && let hir::Node::Expr(if_expr) = self.tcx.parent_hir_node(expr.hir_id)
827 && let hir::ExprKind::If(_cond, _then, Some(_else)) = if_expr.kind
828 && let hir::Node::Stmt(stmt) = self.tcx.parent_hir_node(if_expr.hir_id)
829 && let hir::StmtKind::Expr(_) = stmt.kind
830 && self.is_next_stmt_expr_continuation(stmt.hir_id)
831 {
832 err.subdiagnostic(ExprParenthesesNeeded::surrounding(stmt.span));
840 }
841 }
842 }
843 }
844
845 pub(crate) fn is_next_stmt_expr_continuation(&self, hir_id: HirId) -> bool {
846 if let hir::Node::Block(b) = self.tcx.parent_hir_node(hir_id)
847 && let mut stmts = b.stmts.iter().skip_while(|s| s.hir_id != hir_id)
848 && let Some(_) = stmts.next() && let Some(next) = match (stmts.next(), b.expr) { (Some(next), _) => match next.kind {
851 hir::StmtKind::Expr(next) | hir::StmtKind::Semi(next) => Some(next),
852 _ => None,
853 },
854 (None, Some(next)) => Some(next),
855 _ => None,
856 }
857 && let hir::ExprKind::AddrOf(..) | hir::ExprKind::Unary(..) | hir::ExprKind::Err(_) = next.kind
860 {
862 true
863 } else {
864 false
865 }
866 }
867
868 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("suggest_missing_return_type",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(880u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["fn_decl",
"expected", "found", "fn_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_decl)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&found)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
if let Some(hir::CoroutineKind::Desugared(_,
hir::CoroutineSource::Block)) =
self.tcx.coroutine_kind(fn_id) {
return false;
}
let found =
self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
match &fn_decl.output {
&hir::FnRetTy::DefaultReturn(_) if
self.tcx.is_closure_like(fn_id.to_def_id()) => {}
&hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
if !self.can_add_return_type(fn_id) {
err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit {
span,
});
} else if let Some(found) =
found.make_suggestable(self.tcx, false, None) {
err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
span,
found: found.to_string(),
});
} else if let Some(sugg) =
suggest_impl_trait(self, self.param_env, found) {
err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
span,
found: sugg,
});
} else {
err.subdiagnostic(errors::AddReturnTypeSuggestion::MissingHere {
span,
});
}
return true;
}
hir::FnRetTy::Return(hir_ty) => {
if let hir::TyKind::OpaqueDef(op_ty, ..) = hir_ty.kind &&
let [hir::GenericBound::Trait(trait_ref)] = op_ty.bounds &&
!trait_ref.trait_ref.path.segments.last().and_then(|seg|
seg.args).map_or(false, |args| !args.constraints.is_empty())
{
let trait_name =
trait_ref.trait_ref.path.segments.iter().map(|seg|
seg.ident.as_str()).collect::<Vec<_>>().join("::");
err.subdiagnostic(errors::ExpectedReturnTypeLabel::ImplTrait {
span: hir_ty.span,
trait_name,
});
if let Some(ret_coercion_span) =
self.ret_coercion_span.get() {
let expected_name = expected.to_string();
err.span_label(ret_coercion_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("return type resolved to be `{0}`",
expected_name))
}));
}
let trait_def_id = trait_ref.trait_ref.path.res.def_id();
if self.tcx.is_dyn_compatible(trait_def_id) {
err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
start_sp: hir_ty.span.with_hi(hir_ty.span.lo() +
BytePos(4)),
end_sp: hir_ty.span.shrink_to_hi(),
});
let body = self.tcx.hir_body_owned_by(fn_id);
let mut visitor = ReturnsVisitor::default();
visitor.visit_body(&body);
if !visitor.returns.is_empty() {
let starts: Vec<Span> =
visitor.returns.iter().filter(|expr|
expr.span.can_be_used_for_suggestions()).map(|expr|
expr.span.shrink_to_lo()).collect();
let ends: Vec<Span> =
visitor.returns.iter().filter(|expr|
expr.span.can_be_used_for_suggestions()).map(|expr|
expr.span.shrink_to_hi()).collect();
if !starts.is_empty() {
err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr {
starts,
ends,
});
}
}
}
self.try_suggest_return_impl_trait(err, expected, found,
fn_id);
self.try_note_caller_chooses_ty_for_ty_param(err, expected,
found);
return true;
} else if let hir::TyKind::OpaqueDef(op_ty, ..) =
hir_ty.kind &&
let [hir::GenericBound::Trait(trait_ref)] = op_ty.bounds &&
let Some(hir::PathSegment { args: Some(generic_args), .. })
= trait_ref.trait_ref.path.segments.last() &&
let [constraint] = generic_args.constraints &&
let Some(ty) = constraint.ty() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:1001",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(1001u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["found"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&found) as
&dyn Value))])
});
} else { ; }
};
if found.is_suggestable(self.tcx, false) {
if ty.span.is_empty() {
err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
span: ty.span,
found: found.to_string(),
});
return true;
} else {
err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
span: ty.span,
expected,
});
}
}
} else {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:1019",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(1019u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["message", "hir_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("return type")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&hir_ty) as
&dyn Value))])
});
} else { ; }
};
let ty = self.lowerer().lower_ty(hir_ty);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:1021",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(1021u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["message", "ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("return type (lowered)")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty) as
&dyn Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:1022",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(1022u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["message",
"expected"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("expected type")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&expected)
as &dyn Value))])
});
} else { ; }
};
let bound_vars =
self.tcx.late_bound_vars(self.tcx.local_def_id_to_hir_id(fn_id));
let ty = Binder::bind_with_vars(ty, bound_vars);
let ty =
self.normalize(hir_ty.span, Unnormalized::new_wip(ty));
let ty = self.tcx.instantiate_bound_regions_with_erased(ty);
if self.may_coerce(expected, ty) {
err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
span: hir_ty.span,
expected,
});
self.try_suggest_return_impl_trait(err, expected, found,
fn_id);
self.try_note_caller_chooses_ty_for_ty_param(err, expected,
found);
return true;
}
}
}
_ => {}
}
false
}
}
}#[instrument(level = "trace", skip(self, err))]
881 pub(in super::super) fn suggest_missing_return_type(
882 &self,
883 err: &mut Diag<'_>,
884 fn_decl: &hir::FnDecl<'tcx>,
885 expected: Ty<'tcx>,
886 found: Ty<'tcx>,
887 fn_id: LocalDefId,
888 ) -> bool {
889 if let Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Block)) =
891 self.tcx.coroutine_kind(fn_id)
892 {
893 return false;
894 }
895
896 let found =
897 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
898 match &fn_decl.output {
901 &hir::FnRetTy::DefaultReturn(_) if self.tcx.is_closure_like(fn_id.to_def_id()) => {}
903 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
904 if !self.can_add_return_type(fn_id) {
905 err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit { span });
906 } else if let Some(found) = found.make_suggestable(self.tcx, false, None) {
907 err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
908 span,
909 found: found.to_string(),
910 });
911 } else if let Some(sugg) = suggest_impl_trait(self, self.param_env, found) {
912 err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { span, found: sugg });
913 } else {
914 err.subdiagnostic(errors::AddReturnTypeSuggestion::MissingHere { span });
916 }
917
918 return true;
919 }
920 hir::FnRetTy::Return(hir_ty) => {
921 if let hir::TyKind::OpaqueDef(op_ty, ..) = hir_ty.kind
922 && let [hir::GenericBound::Trait(trait_ref)] = op_ty.bounds
923 && !trait_ref
924 .trait_ref
925 .path
926 .segments
927 .last()
928 .and_then(|seg| seg.args)
929 .map_or(false, |args| !args.constraints.is_empty())
930 {
931 let trait_name = trait_ref
933 .trait_ref
934 .path
935 .segments
936 .iter()
937 .map(|seg| seg.ident.as_str())
938 .collect::<Vec<_>>()
939 .join("::");
940
941 err.subdiagnostic(errors::ExpectedReturnTypeLabel::ImplTrait {
942 span: hir_ty.span,
943 trait_name,
944 });
945
946 if let Some(ret_coercion_span) = self.ret_coercion_span.get() {
947 let expected_name = expected.to_string();
948 err.span_label(
949 ret_coercion_span,
950 format!("return type resolved to be `{expected_name}`"),
951 );
952 }
953
954 let trait_def_id = trait_ref.trait_ref.path.res.def_id();
955 if self.tcx.is_dyn_compatible(trait_def_id) {
956 err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
957 start_sp: hir_ty.span.with_hi(hir_ty.span.lo() + BytePos(4)),
958 end_sp: hir_ty.span.shrink_to_hi(),
959 });
960
961 let body = self.tcx.hir_body_owned_by(fn_id);
962 let mut visitor = ReturnsVisitor::default();
963 visitor.visit_body(&body);
964
965 if !visitor.returns.is_empty() {
966 let starts: Vec<Span> = visitor
967 .returns
968 .iter()
969 .filter(|expr| expr.span.can_be_used_for_suggestions())
970 .map(|expr| expr.span.shrink_to_lo())
971 .collect();
972 let ends: Vec<Span> = visitor
973 .returns
974 .iter()
975 .filter(|expr| expr.span.can_be_used_for_suggestions())
976 .map(|expr| expr.span.shrink_to_hi())
977 .collect();
978
979 if !starts.is_empty() {
980 err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr {
981 starts,
982 ends,
983 });
984 }
985 }
986 }
987
988 self.try_suggest_return_impl_trait(err, expected, found, fn_id);
989 self.try_note_caller_chooses_ty_for_ty_param(err, expected, found);
990 return true;
991 } else if let hir::TyKind::OpaqueDef(op_ty, ..) = hir_ty.kind
992 && let [hir::GenericBound::Trait(trait_ref)] = op_ty.bounds
994 && let Some(hir::PathSegment { args: Some(generic_args), .. }) =
995 trait_ref.trait_ref.path.segments.last()
996 && let [constraint] = generic_args.constraints
997 && let Some(ty) = constraint.ty()
998 {
999 debug!(?found);
1002 if found.is_suggestable(self.tcx, false) {
1003 if ty.span.is_empty() {
1004 err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
1005 span: ty.span,
1006 found: found.to_string(),
1007 });
1008 return true;
1009 } else {
1010 err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
1011 span: ty.span,
1012 expected,
1013 });
1014 }
1015 }
1016 } else {
1017 debug!(?hir_ty, "return type");
1020 let ty = self.lowerer().lower_ty(hir_ty);
1021 debug!(?ty, "return type (lowered)");
1022 debug!(?expected, "expected type");
1023 let bound_vars =
1024 self.tcx.late_bound_vars(self.tcx.local_def_id_to_hir_id(fn_id));
1025 let ty = Binder::bind_with_vars(ty, bound_vars);
1026 let ty = self.normalize(hir_ty.span, Unnormalized::new_wip(ty));
1027 let ty = self.tcx.instantiate_bound_regions_with_erased(ty);
1028 if self.may_coerce(expected, ty) {
1029 err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
1030 span: hir_ty.span,
1031 expected,
1032 });
1033 self.try_suggest_return_impl_trait(err, expected, found, fn_id);
1034 self.try_note_caller_chooses_ty_for_ty_param(err, expected, found);
1035 return true;
1036 }
1037 }
1038 }
1039 _ => {}
1040 }
1041 false
1042 }
1043
1044 fn can_add_return_type(&self, fn_id: LocalDefId) -> bool {
1047 match self.tcx.hir_node_by_def_id(fn_id) {
1048 Node::Item(item) => {
1049 let (ident, _, _, _) = item.expect_fn();
1050 ident.name != sym::main
1054 }
1055 Node::ImplItem(item) => {
1056 let Node::Item(&hir::Item {
1058 kind: hir::ItemKind::Impl(hir::Impl { of_trait, .. }),
1059 ..
1060 }) = self.tcx.parent_hir_node(item.hir_id())
1061 else {
1062 ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1063 };
1064
1065 of_trait.is_none()
1066 }
1067 _ => true,
1068 }
1069 }
1070
1071 fn try_note_caller_chooses_ty_for_ty_param(
1072 &self,
1073 diag: &mut Diag<'_>,
1074 expected: Ty<'tcx>,
1075 found: Ty<'tcx>,
1076 ) {
1077 let ty::Param(expected_ty_as_param) = expected.kind() else {
1084 return;
1085 };
1086
1087 if found.contains(expected) {
1088 return;
1089 }
1090
1091 diag.subdiagnostic(errors::NoteCallerChoosesTyForTyParam {
1092 ty_param_name: expected_ty_as_param.name,
1093 found_ty: found,
1094 });
1095 }
1096
1097 fn try_suggest_return_impl_trait(
1106 &self,
1107 err: &mut Diag<'_>,
1108 expected: Ty<'tcx>,
1109 found: Ty<'tcx>,
1110 fn_id: LocalDefId,
1111 ) {
1112 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs:1120",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(1120u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("try_suggest_return_impl_trait, expected = {0:?}, found = {1:?}",
expected, found) as &dyn Value))])
});
} else { ; }
};debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
1121
1122 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
1123
1124 let fn_node = self.tcx.hir_node_by_def_id(fn_id);
1125
1126 let hir::Node::Item(hir::Item {
1127 kind:
1128 hir::ItemKind::Fn {
1129 sig:
1130 hir::FnSig {
1131 decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. },
1132 ..
1133 },
1134 generics: hir::Generics { params, predicates, .. },
1135 ..
1136 },
1137 ..
1138 }) = fn_node
1139 else {
1140 return;
1141 };
1142
1143 if params.get(expected_ty_as_param.index as usize).is_none() {
1144 return;
1145 };
1146
1147 let where_predicates = predicates
1149 .iter()
1150 .filter_map(|p| match p.kind {
1151 WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1152 bounds,
1153 bounded_ty,
1154 ..
1155 }) => {
1156 let ty = self.lowerer().lower_ty(bounded_ty);
1158 Some((ty, bounds))
1159 }
1160 _ => None,
1161 })
1162 .map(|(ty, bounds)| match ty.kind() {
1163 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
1164 _ => match ty.contains(expected) {
1166 true => Err(()),
1167 false => Ok(None),
1168 },
1169 })
1170 .collect::<Result<Vec<_>, _>>();
1171
1172 let Ok(where_predicates) = where_predicates else { return };
1173
1174 let predicates_from_where =
1176 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
1177
1178 let all_matching_bounds_strs = predicates_from_where
1180 .filter_map(|bound| match bound {
1181 GenericBound::Trait(_) => {
1182 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
1183 }
1184 _ => None,
1185 })
1186 .collect::<Vec<String>>();
1187
1188 if all_matching_bounds_strs.is_empty() {
1189 return;
1190 }
1191
1192 let all_bounds_str = all_matching_bounds_strs.join(" + ");
1193
1194 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
1195 let ty = self.lowerer().lower_ty( param);
1196 #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param
=> true,
_ => false,
}matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
1197 });
1198
1199 if ty_param_used_in_fn_params {
1200 return;
1201 }
1202
1203 err.span_suggestion(
1204 fn_return.span(),
1205 "consider using an impl return type",
1206 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("impl {0}", all_bounds_str))
})format!("impl {all_bounds_str}"),
1207 Applicability::MaybeIncorrect,
1208 );
1209 }
1210
1211 pub(in super::super) fn suggest_missing_break_or_return_expr(
1212 &self,
1213 err: &mut Diag<'_>,
1214 expr: &'tcx hir::Expr<'tcx>,
1215 fn_decl: &hir::FnDecl<'tcx>,
1216 expected: Ty<'tcx>,
1217 found: Ty<'tcx>,
1218 id: HirId,
1219 fn_id: LocalDefId,
1220 ) {
1221 if !expected.is_unit() {
1222 return;
1223 }
1224 let found = self.resolve_vars_if_possible(found);
1225
1226 let innermost_loop = if self.is_loop(id) {
1227 Some(self.tcx.hir_node(id))
1228 } else {
1229 self.tcx
1230 .hir_parent_iter(id)
1231 .take_while(|(_, node)| {
1232 node.body_id().is_none()
1234 })
1235 .find_map(|(parent_id, node)| self.is_loop(parent_id).then_some(node))
1236 };
1237 let can_break_with_value = innermost_loop.is_some_and(|node| {
1238 #[allow(non_exhaustive_omitted_patterns)] match node {
Node::Expr(Expr { kind: ExprKind::Loop(_, _, LoopSource::Loop, ..), .. })
=> true,
_ => false,
}matches!(
1239 node,
1240 Node::Expr(Expr { kind: ExprKind::Loop(_, _, LoopSource::Loop, ..), .. })
1241 )
1242 });
1243
1244 let in_local_statement = self.is_local_statement(id)
1245 || self
1246 .tcx
1247 .hir_parent_iter(id)
1248 .any(|(parent_id, _)| self.is_local_statement(parent_id));
1249
1250 if can_break_with_value && in_local_statement {
1251 err.multipart_suggestion(
1252 "you might have meant to break the loop with this value",
1253 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_lo(), "break ".to_string()),
(expr.span.shrink_to_hi(), ";".to_string())]))vec![
1254 (expr.span.shrink_to_lo(), "break ".to_string()),
1255 (expr.span.shrink_to_hi(), ";".to_string()),
1256 ],
1257 Applicability::MaybeIncorrect,
1258 );
1259 return;
1260 }
1261
1262 let scope = self.tcx.hir_parent_iter(id).find(|(_, node)| {
1263 #[allow(non_exhaustive_omitted_patterns)] match node {
Node::Expr(Expr { kind: ExprKind::Closure(..), .. }) | Node::Item(_) |
Node::TraitItem(_) | Node::ImplItem(_) => true,
_ => false,
}matches!(
1264 node,
1265 Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
1266 | Node::Item(_)
1267 | Node::TraitItem(_)
1268 | Node::ImplItem(_)
1269 )
1270 });
1271 let in_closure =
1272 #[allow(non_exhaustive_omitted_patterns)] match scope {
Some((_, Node::Expr(Expr { kind: ExprKind::Closure(..), .. }))) => true,
_ => false,
}matches!(scope, Some((_, Node::Expr(Expr { kind: ExprKind::Closure(..), .. }))));
1273
1274 let can_return = match fn_decl.output {
1275 hir::FnRetTy::Return(ty) => {
1276 let ty = self.lowerer().lower_ty(ty);
1277 let bound_vars = self.tcx.late_bound_vars(self.tcx.local_def_id_to_hir_id(fn_id));
1278 let ty = self
1279 .tcx
1280 .instantiate_bound_regions_with_erased(Binder::bind_with_vars(ty, bound_vars));
1281 let ty = match self.tcx.asyncness(fn_id) {
1282 ty::Asyncness::Yes => {
1283 self.err_ctxt().get_impl_future_output_ty(ty).unwrap_or_else(|| {
1284 ::rustc_middle::util::bug::span_bug_fmt(fn_decl.output.span(),
format_args!("failed to get output type of async function"))span_bug!(
1285 fn_decl.output.span(),
1286 "failed to get output type of async function"
1287 )
1288 })
1289 }
1290 ty::Asyncness::No => ty,
1291 };
1292 let ty = self.normalize(expr.span, Unnormalized::new_wip(ty));
1293 self.may_coerce(found, ty)
1294 }
1295 hir::FnRetTy::DefaultReturn(_) if in_closure => {
1296 self.ret_coercion.as_ref().is_some_and(|ret| {
1297 let ret_ty = ret.borrow().expected_ty();
1298 self.may_coerce(found, ret_ty)
1299 })
1300 }
1301 _ => false,
1302 };
1303 if can_return
1304 && let Some(span) = expr.span.find_ancestor_inside(
1305 self.tcx.hir_span_with_body(self.tcx.local_def_id_to_hir_id(fn_id)),
1306 )
1307 {
1308 fn is_in_arm<'tcx>(expr: &'tcx hir::Expr<'tcx>, tcx: TyCtxt<'tcx>) -> bool {
1319 for (_, node) in tcx.hir_parent_iter(expr.hir_id) {
1320 match node {
1321 hir::Node::Block(block) => {
1322 if let Some(ret) = block.expr
1323 && ret.hir_id == expr.hir_id
1324 {
1325 continue;
1326 }
1327 }
1328 hir::Node::Arm(arm) => {
1329 if let hir::ExprKind::Block(block, _) = arm.body.kind
1330 && let Some(ret) = block.expr
1331 && ret.hir_id == expr.hir_id
1332 {
1333 return true;
1334 }
1335 }
1336 hir::Node::Expr(e) if let hir::ExprKind::Block(block, _) = e.kind => {
1337 if let Some(ret) = block.expr
1338 && ret.hir_id == expr.hir_id
1339 {
1340 continue;
1341 }
1342 }
1343 _ => {
1344 return false;
1345 }
1346 }
1347 }
1348
1349 false
1350 }
1351 let mut suggs = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "return ".to_string())]))vec![(span.shrink_to_lo(), "return ".to_string())];
1352 if !is_in_arm(expr, self.tcx) {
1353 suggs.push((span.shrink_to_hi(), ";".to_string()));
1354 }
1355 err.multipart_suggestion(
1356 "you might have meant to return this value",
1357 suggs,
1358 Applicability::MaybeIncorrect,
1359 );
1360 }
1361 }
1362
1363 pub(in super::super) fn suggest_missing_parentheses(
1364 &self,
1365 err: &mut Diag<'_>,
1366 expr: &hir::Expr<'_>,
1367 ) -> bool {
1368 let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
1369 if let Some(sp) = self.tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
1370 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
1372 true
1373 } else {
1374 false
1375 }
1376 }
1377
1378 pub(crate) fn suggest_block_to_brackets_peeling_refs(
1382 &self,
1383 diag: &mut Diag<'_>,
1384 mut expr: &hir::Expr<'_>,
1385 mut expr_ty: Ty<'tcx>,
1386 mut expected_ty: Ty<'tcx>,
1387 ) -> bool {
1388 loop {
1389 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
1390 (
1391 hir::ExprKind::AddrOf(_, _, inner_expr),
1392 ty::Ref(_, inner_expr_ty, _),
1393 ty::Ref(_, inner_expected_ty, _),
1394 ) => {
1395 expr = *inner_expr;
1396 expr_ty = *inner_expr_ty;
1397 expected_ty = *inner_expected_ty;
1398 }
1399 (hir::ExprKind::Block(blk, _), _, _) => {
1400 self.suggest_block_to_brackets(diag, blk, expr_ty, expected_ty);
1401 break true;
1402 }
1403 _ => break false,
1404 }
1405 }
1406 }
1407
1408 pub(crate) fn suggest_clone_for_ref(
1409 &self,
1410 diag: &mut Diag<'_>,
1411 expr: &hir::Expr<'_>,
1412 expr_ty: Ty<'tcx>,
1413 expected_ty: Ty<'tcx>,
1414 ) -> bool {
1415 if let ty::Ref(_, inner_ty, hir::Mutability::Not) = expr_ty.kind()
1416 && let Some(clone_trait_def) = self.tcx.lang_items().clone_trait()
1417 && expected_ty == *inner_ty
1418 && self
1419 .infcx
1420 .type_implements_trait(
1421 clone_trait_def,
1422 [self.tcx.erase_and_anonymize_regions(expected_ty)],
1423 self.param_env,
1424 )
1425 .must_apply_modulo_regions()
1426 {
1427 let suggestion = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1428 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}.clone()", ident))
})format!(": {ident}.clone()"),
1429 None => ".clone()".to_string(),
1430 };
1431
1432 let span = expr.span.find_ancestor_not_from_macro().unwrap_or(expr.span).shrink_to_hi();
1433
1434 diag.span_suggestion_verbose(
1435 span,
1436 "consider using clone here",
1437 suggestion,
1438 Applicability::MachineApplicable,
1439 );
1440 return true;
1441 }
1442 false
1443 }
1444
1445 pub(crate) fn suggest_copied_cloned_or_as_ref(
1446 &self,
1447 diag: &mut Diag<'_>,
1448 expr: &hir::Expr<'_>,
1449 expr_ty: Ty<'tcx>,
1450 expected_ty: Ty<'tcx>,
1451 ) -> bool {
1452 let ty::Adt(adt_def, args) = expr_ty.kind() else {
1453 return false;
1454 };
1455 let ty::Adt(expected_adt_def, expected_args) = expected_ty.kind() else {
1456 return false;
1457 };
1458 if adt_def != expected_adt_def {
1459 return false;
1460 }
1461
1462 if Some(adt_def.did()) == self.tcx.get_diagnostic_item(sym::Result)
1463 && self.can_eq(self.param_env, args.type_at(1), expected_args.type_at(1))
1464 || Some(adt_def.did()) == self.tcx.get_diagnostic_item(sym::Option)
1465 {
1466 let expr_inner_ty = args.type_at(0);
1467 let expected_inner_ty = expected_args.type_at(0);
1468 if let &ty::Ref(_, ty, _mutability) = expr_inner_ty.kind()
1469 && self.can_eq(self.param_env, ty, expected_inner_ty)
1470 {
1471 let def_path = self.tcx.def_path_str(adt_def.did());
1472 let span = expr.span.shrink_to_hi();
1473 let subdiag = if self.type_is_copy_modulo_regions(self.param_env, ty) {
1474 errors::OptionResultRefMismatch::Copied { span, def_path }
1475 } else if self.type_is_clone_modulo_regions(self.param_env, ty) {
1476 errors::OptionResultRefMismatch::Cloned { span, def_path }
1477 } else {
1478 return false;
1479 };
1480 diag.subdiagnostic(subdiag);
1481 return true;
1482 }
1483 }
1484
1485 false
1486 }
1487
1488 pub(crate) fn suggest_into(
1489 &self,
1490 diag: &mut Diag<'_>,
1491 expr: &hir::Expr<'_>,
1492 expr_ty: Ty<'tcx>,
1493 expected_ty: Ty<'tcx>,
1494 ) -> bool {
1495 let expr = expr.peel_blocks();
1496
1497 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1499 return false;
1500 }
1501
1502 if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
hir::ExprKind::Block(..) => true,
_ => false,
}matches!(expr.kind, hir::ExprKind::Block(..)) {
1504 return false;
1505 }
1506
1507 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1510 return false;
1511 }
1512
1513 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1514 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1515 self.tcx,
1516 self.misc(expr.span),
1517 self.param_env,
1518 ty::TraitRef::new(self.tcx, into_def_id, [expr_ty, expected_ty]),
1519 ))
1520 && !expr
1521 .span
1522 .macro_backtrace()
1523 .any(|x| #[allow(non_exhaustive_omitted_patterns)] match x.kind {
ExpnKind::Macro(MacroKind::Attr | MacroKind::Derive, ..) => true,
_ => false,
}matches!(x.kind, ExpnKind::Macro(MacroKind::Attr | MacroKind::Derive, ..)))
1524 {
1525 let span = expr
1526 .span
1527 .find_ancestor_not_from_extern_macro(self.tcx.sess.source_map())
1528 .unwrap_or(expr.span);
1529
1530 let mut sugg = if self.precedence(expr) >= ExprPrecedence::Unambiguous {
1531 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_hi(), ".into()".to_owned())]))vec![(span.shrink_to_hi(), ".into()".to_owned())]
1532 } else {
1533 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "(".to_owned()),
(span.shrink_to_hi(), ").into()".to_owned())]))vec![
1534 (span.shrink_to_lo(), "(".to_owned()),
1535 (span.shrink_to_hi(), ").into()".to_owned()),
1536 ]
1537 };
1538 if let Some(name) = self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1539 sugg.insert(0, (expr.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", name))
})format!("{}: ", name)));
1540 }
1541 diag.multipart_suggestion(
1542 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("call `Into::into` on this expression to convert `{0}` into `{1}`",
expr_ty, expected_ty))
})format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1543 sugg,
1544 Applicability::MaybeIncorrect
1545 );
1546 return true;
1547 }
1548
1549 false
1550 }
1551
1552 pub(crate) fn suggest_option_to_bool(
1554 &self,
1555 diag: &mut Diag<'_>,
1556 expr: &hir::Expr<'_>,
1557 expr_ty: Ty<'tcx>,
1558 expected_ty: Ty<'tcx>,
1559 ) -> bool {
1560 if !expected_ty.is_bool() {
1561 return false;
1562 }
1563
1564 let ty::Adt(def, _) = expr_ty.peel_refs().kind() else {
1565 return false;
1566 };
1567 if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1568 return false;
1569 }
1570
1571 let cond_parent = self.tcx.hir_parent_iter(expr.hir_id).find(|(_, node)| {
1572 !#[allow(non_exhaustive_omitted_patterns)] match node {
hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. })
if op.node == hir::BinOpKind::And => true,
_ => false,
}matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1573 });
1574 if let Some((_, hir::Node::LetStmt(local))) = cond_parent
1580 && let hir::PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), .. })
1581 | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1582 && let hir::QPath::Resolved(None, path) = qpath
1583 && let Some(did) = path
1584 .res
1585 .opt_def_id()
1586 .and_then(|did| self.tcx.opt_parent(did))
1587 .and_then(|did| self.tcx.opt_parent(did))
1588 && self.tcx.is_diagnostic_item(sym::Option, did)
1589 {
1590 return false;
1591 }
1592
1593 let suggestion = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1594 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}.is_some()", ident))
})format!(": {ident}.is_some()"),
1595 None => ".is_some()".to_string(),
1596 };
1597
1598 diag.span_suggestion_verbose(
1599 expr.span.shrink_to_hi(),
1600 "use `Option::is_some` to test if the `Option` has a value",
1601 suggestion,
1602 Applicability::MachineApplicable,
1603 );
1604 true
1605 }
1606
1607 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("suggest_deref_unwrap_or",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(1608u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["callee_ty",
"call_ident", "expected_ty", "provided_ty", "is_method"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&call_ident)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&provided_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&is_method as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if !is_method { return; }
let Some(callee_ty) = callee_ty else { return; };
let ty::Adt(callee_adt, _) =
callee_ty.peel_refs().kind() else { return; };
let adt_name =
if self.tcx.is_diagnostic_item(sym::Option, callee_adt.did())
{
"Option"
} else if self.tcx.is_diagnostic_item(sym::Result,
callee_adt.did()) {
"Result"
} else { return; };
let Some(call_ident) = call_ident else { return; };
if call_ident.name != sym::unwrap_or { return; }
let ty::Ref(_, peeled, _mutability) =
provided_ty.kind() else { return; };
let dummy_ty =
if let ty::Array(elem_ty, size) = peeled.kind() &&
let ty::Infer(_) = elem_ty.kind() &&
self.try_structurally_resolve_const(provided_expr.span,
*size).try_to_target_usize(self.tcx) == Some(0) {
let slice = Ty::new_slice(self.tcx, *elem_ty);
Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static,
slice)
} else { provided_ty };
if !self.may_coerce(expected_ty, dummy_ty) { return; }
let msg =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `{0}::map_or` to deref inner value of `{0}`",
adt_name))
});
err.multipart_suggestion(msg,
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(call_ident.span, "map_or".to_owned()),
(provided_expr.span.shrink_to_hi(),
", |v| v".to_owned())])), Applicability::MachineApplicable);
}
}
}#[instrument(level = "trace", skip(self, err, provided_expr))]
1609 pub(crate) fn suggest_deref_unwrap_or(
1610 &self,
1611 err: &mut Diag<'_>,
1612 callee_ty: Option<Ty<'tcx>>,
1613 call_ident: Option<Ident>,
1614 expected_ty: Ty<'tcx>,
1615 provided_ty: Ty<'tcx>,
1616 provided_expr: &Expr<'tcx>,
1617 is_method: bool,
1618 ) {
1619 if !is_method {
1620 return;
1621 }
1622 let Some(callee_ty) = callee_ty else {
1623 return;
1624 };
1625 let ty::Adt(callee_adt, _) = callee_ty.peel_refs().kind() else {
1626 return;
1627 };
1628 let adt_name = if self.tcx.is_diagnostic_item(sym::Option, callee_adt.did()) {
1629 "Option"
1630 } else if self.tcx.is_diagnostic_item(sym::Result, callee_adt.did()) {
1631 "Result"
1632 } else {
1633 return;
1634 };
1635
1636 let Some(call_ident) = call_ident else {
1637 return;
1638 };
1639 if call_ident.name != sym::unwrap_or {
1640 return;
1641 }
1642
1643 let ty::Ref(_, peeled, _mutability) = provided_ty.kind() else {
1644 return;
1645 };
1646
1647 let dummy_ty = if let ty::Array(elem_ty, size) = peeled.kind()
1651 && let ty::Infer(_) = elem_ty.kind()
1652 && self
1653 .try_structurally_resolve_const(provided_expr.span, *size)
1654 .try_to_target_usize(self.tcx)
1655 == Some(0)
1656 {
1657 let slice = Ty::new_slice(self.tcx, *elem_ty);
1658 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, slice)
1659 } else {
1660 provided_ty
1661 };
1662
1663 if !self.may_coerce(expected_ty, dummy_ty) {
1664 return;
1665 }
1666 let msg = format!("use `{adt_name}::map_or` to deref inner value of `{adt_name}`");
1667 err.multipart_suggestion(
1668 msg,
1669 vec![
1670 (call_ident.span, "map_or".to_owned()),
1671 (provided_expr.span.shrink_to_hi(), ", |v| v".to_owned()),
1672 ],
1673 Applicability::MachineApplicable,
1674 );
1675 }
1676
1677 pub(crate) fn suggest_block_to_brackets(
1680 &self,
1681 diag: &mut Diag<'_>,
1682 blk: &hir::Block<'_>,
1683 blk_ty: Ty<'tcx>,
1684 expected_ty: Ty<'tcx>,
1685 ) {
1686 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1687 if self.may_coerce(blk_ty, *elem_ty)
1688 && blk.stmts.is_empty()
1689 && blk.rules == hir::BlockCheckMode::DefaultBlock
1690 && let source_map = self.tcx.sess.source_map()
1691 && let Ok(snippet) = source_map.span_to_snippet(blk.span)
1692 && snippet.starts_with('{')
1693 && snippet.ends_with('}')
1694 {
1695 diag.multipart_suggestion(
1696 "to create an array, use square brackets instead of curly braces",
1697 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(blk.span.shrink_to_lo().with_hi(rustc_span::BytePos(blk.span.lo().0
+ 1)), "[".to_string()),
(blk.span.shrink_to_hi().with_lo(rustc_span::BytePos(blk.span.hi().0
- 1)), "]".to_string())]))vec![
1698 (
1699 blk.span
1700 .shrink_to_lo()
1701 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1702 "[".to_string(),
1703 ),
1704 (
1705 blk.span
1706 .shrink_to_hi()
1707 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1708 "]".to_string(),
1709 ),
1710 ],
1711 Applicability::MachineApplicable,
1712 );
1713 }
1714 }
1715 }
1716
1717 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("suggest_floating_point_literal",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(1717u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["expr",
"expected_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
if !expected_ty.is_floating_point() { return false; }
match expr.kind {
ExprKind::Struct(&qpath, [start, end], _) if
is_range_literal(expr) &&
self.tcx.qpath_is_lang_item(qpath, LangItem::Range) => {
err.span_suggestion_verbose(start.expr.span.shrink_to_hi().with_hi(end.expr.span.lo()),
"remove the unnecessary `.` operator for a floating point literal",
'.', Applicability::MaybeIncorrect);
true
}
ExprKind::Struct(&qpath, [arg], _) if
is_range_literal(expr) &&
let Some(qpath @ (LangItem::RangeFrom | LangItem::RangeTo))
= self.tcx.qpath_lang_item(qpath) => {
let range_span = expr.span.parent_callsite().unwrap();
match qpath {
LangItem::RangeFrom => {
err.span_suggestion_verbose(range_span.with_lo(arg.expr.span.hi()),
"remove the unnecessary `.` operator for a floating point literal",
'.', Applicability::MaybeIncorrect);
}
_ => {
err.span_suggestion_verbose(range_span.until(arg.expr.span),
"remove the unnecessary `.` operator and add an integer part for a floating point literal",
"0.", Applicability::MaybeIncorrect);
}
}
true
}
ExprKind::Lit(Spanned {
node: rustc_ast::LitKind::Int(lit,
rustc_ast::LitIntType::Unsuffixed),
span }) => {
let Ok(snippet) =
self.tcx.sess.source_map().span_to_snippet(span) else {
return false;
};
if !(snippet.starts_with("0x") || snippet.starts_with("0X"))
{
return false;
}
if snippet.len() <= 5 ||
!snippet.is_char_boundary(snippet.len() - 3) {
return false;
}
let (_, suffix) = snippet.split_at(snippet.len() - 3);
let value =
match suffix {
"f32" => (lit.get() - 0xf32) / (16 * 16 * 16),
"f64" => (lit.get() - 0xf64) / (16 * 16 * 16),
_ => return false,
};
err.span_suggestions(expr.span,
"rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
[::alloc::__export::must_use({
::alloc::fmt::format(format_args!("0x{0:X} as {1}", value,
suffix))
}),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_{1}", value, suffix))
})], Applicability::MaybeIncorrect);
true
}
_ => false,
}
}
}
}#[instrument(skip(self, err))]
1718 pub(crate) fn suggest_floating_point_literal(
1719 &self,
1720 err: &mut Diag<'_>,
1721 expr: &hir::Expr<'_>,
1722 expected_ty: Ty<'tcx>,
1723 ) -> bool {
1724 if !expected_ty.is_floating_point() {
1725 return false;
1726 }
1727 match expr.kind {
1728 ExprKind::Struct(&qpath, [start, end], _)
1729 if is_range_literal(expr)
1730 && self.tcx.qpath_is_lang_item(qpath, LangItem::Range) =>
1731 {
1732 err.span_suggestion_verbose(
1733 start.expr.span.shrink_to_hi().with_hi(end.expr.span.lo()),
1734 "remove the unnecessary `.` operator for a floating point literal",
1735 '.',
1736 Applicability::MaybeIncorrect,
1737 );
1738 true
1739 }
1740 ExprKind::Struct(&qpath, [arg], _)
1741 if is_range_literal(expr)
1742 && let Some(qpath @ (LangItem::RangeFrom | LangItem::RangeTo)) =
1743 self.tcx.qpath_lang_item(qpath) =>
1744 {
1745 let range_span = expr.span.parent_callsite().unwrap();
1746 match qpath {
1747 LangItem::RangeFrom => {
1748 err.span_suggestion_verbose(
1749 range_span.with_lo(arg.expr.span.hi()),
1750 "remove the unnecessary `.` operator for a floating point literal",
1751 '.',
1752 Applicability::MaybeIncorrect,
1753 );
1754 }
1755 _ => {
1756 err.span_suggestion_verbose(
1757 range_span.until(arg.expr.span),
1758 "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1759 "0.",
1760 Applicability::MaybeIncorrect,
1761 );
1762 }
1763 }
1764 true
1765 }
1766 ExprKind::Lit(Spanned {
1767 node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed),
1768 span,
1769 }) => {
1770 let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1771 return false;
1772 };
1773 if !(snippet.starts_with("0x") || snippet.starts_with("0X")) {
1774 return false;
1775 }
1776 if snippet.len() <= 5 || !snippet.is_char_boundary(snippet.len() - 3) {
1777 return false;
1778 }
1779 let (_, suffix) = snippet.split_at(snippet.len() - 3);
1780 let value = match suffix {
1781 "f32" => (lit.get() - 0xf32) / (16 * 16 * 16),
1782 "f64" => (lit.get() - 0xf64) / (16 * 16 * 16),
1783 _ => return false,
1784 };
1785 err.span_suggestions(
1786 expr.span,
1787 "rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
1788 [format!("0x{value:X} as {suffix}"), format!("{value}_{suffix}")],
1789 Applicability::MaybeIncorrect,
1790 );
1791 true
1792 }
1793 _ => false,
1794 }
1795 }
1796
1797 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("suggest_null_ptr_for_literal_zero_given_to_ptr_arg",
"rustc_hir_typeck::fn_ctxt::suggestions",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(1799u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::suggestions"),
::tracing_core::field::FieldSet::new(&["expr",
"expected_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
let ty::RawPtr(_, mutbl) =
expected_ty.kind() else { return false; };
let ExprKind::Lit(Spanned {
node: rustc_ast::LitKind::Int(Pu128(0), _), span }) =
expr.kind else { return false; };
let null_sym =
match mutbl {
hir::Mutability::Not => sym::ptr_null,
hir::Mutability::Mut => sym::ptr_null_mut,
};
let Some(null_did) =
self.tcx.get_diagnostic_item(null_sym) else { return false; };
let null_path_str =
{
let _guard = NoTrimmedGuard::new();
self.tcx.def_path_str(null_did)
};
err.span_suggestion(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you meant to create a null pointer, use `{0}()`",
null_path_str))
}), null_path_str + "()", Applicability::MachineApplicable);
true
}
}
}#[instrument(skip(self, err))]
1800 pub(crate) fn suggest_null_ptr_for_literal_zero_given_to_ptr_arg(
1801 &self,
1802 err: &mut Diag<'_>,
1803 expr: &hir::Expr<'_>,
1804 expected_ty: Ty<'tcx>,
1805 ) -> bool {
1806 let ty::RawPtr(_, mutbl) = expected_ty.kind() else {
1808 return false;
1809 };
1810
1811 let ExprKind::Lit(Spanned { node: rustc_ast::LitKind::Int(Pu128(0), _), span }) = expr.kind
1813 else {
1814 return false;
1815 };
1816
1817 let null_sym = match mutbl {
1819 hir::Mutability::Not => sym::ptr_null,
1820 hir::Mutability::Mut => sym::ptr_null_mut,
1821 };
1822 let Some(null_did) = self.tcx.get_diagnostic_item(null_sym) else {
1823 return false;
1824 };
1825 let null_path_str = with_no_trimmed_paths!(self.tcx.def_path_str(null_did));
1826
1827 err.span_suggestion(
1829 span,
1830 format!("if you meant to create a null pointer, use `{null_path_str}()`"),
1831 null_path_str + "()",
1832 Applicability::MachineApplicable,
1833 );
1834
1835 true
1836 }
1837
1838 pub(crate) fn suggest_associated_const(
1839 &self,
1840 err: &mut Diag<'_>,
1841 expr: &hir::Expr<'tcx>,
1842 expected_ty: Ty<'tcx>,
1843 ) -> bool {
1844 let Some((DefKind::AssocFn, old_def_id)) =
1845 self.typeck_results.borrow().type_dependent_def(expr.hir_id)
1846 else {
1847 return false;
1848 };
1849 let old_item_name = self.tcx.item_name(old_def_id);
1850 let capitalized_name = Symbol::intern(&old_item_name.as_str().to_uppercase());
1851 if old_item_name == capitalized_name {
1852 return false;
1853 }
1854 let (item, segment) = match expr.kind {
1855 hir::ExprKind::Path(QPath::Resolved(
1856 Some(ty),
1857 hir::Path { segments: [segment], .. },
1858 ))
1859 | hir::ExprKind::Path(QPath::TypeRelative(ty, segment))
1860 if let Some(self_ty) = self.typeck_results.borrow().node_type_opt(ty.hir_id)
1861 && let Ok(pick) = self.probe_for_name(
1862 Mode::Path,
1863 Ident::new(capitalized_name, segment.ident.span),
1864 Some(expected_ty),
1865 IsSuggestion(true),
1866 self_ty,
1867 expr.hir_id,
1868 ProbeScope::TraitsInScope,
1869 ) =>
1870 {
1871 (pick.item, segment)
1872 }
1873 hir::ExprKind::Path(QPath::Resolved(
1874 None,
1875 hir::Path { segments: [.., segment], .. },
1876 )) => {
1877 if old_item_name != segment.ident.name {
1880 return false;
1881 }
1882 let Some(item) = self
1883 .tcx
1884 .associated_items(self.tcx.parent(old_def_id))
1885 .filter_by_name_unhygienic(capitalized_name)
1886 .next()
1887 else {
1888 return false;
1889 };
1890 (*item, segment)
1891 }
1892 _ => return false,
1893 };
1894 if item.def_id == old_def_id
1895 || !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(item.def_id)
{
DefKind::AssocConst { .. } => true,
_ => false,
}matches!(self.tcx.def_kind(item.def_id), DefKind::AssocConst { .. })
1896 {
1897 return false;
1899 }
1900 let item_ty = self.tcx.type_of(item.def_id).instantiate_identity().skip_norm_wip();
1901 if item_ty.has_param() {
1903 return false;
1904 }
1905 if self.may_coerce(item_ty, expected_ty) {
1906 err.span_suggestion_verbose(
1907 segment.ident.span,
1908 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try referring to the associated const `{0}` instead",
capitalized_name))
})format!("try referring to the associated const `{capitalized_name}` instead",),
1909 capitalized_name,
1910 Applicability::MachineApplicable,
1911 );
1912 true
1913 } else {
1914 false
1915 }
1916 }
1917
1918 fn is_loop(&self, id: HirId) -> bool {
1919 let node = self.tcx.hir_node(id);
1920 #[allow(non_exhaustive_omitted_patterns)] match node {
Node::Expr(Expr { kind: ExprKind::Loop(..), .. }) => true,
_ => false,
}matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1921 }
1922
1923 fn is_local_statement(&self, id: HirId) -> bool {
1924 let node = self.tcx.hir_node(id);
1925 #[allow(non_exhaustive_omitted_patterns)] match node {
Node::Stmt(Stmt { kind: StmtKind::Let(..), .. }) => true,
_ => false,
}matches!(node, Node::Stmt(Stmt { kind: StmtKind::Let(..), .. }))
1926 }
1927
1928 pub(crate) fn note_type_is_not_clone(
1931 &self,
1932 diag: &mut Diag<'_>,
1933 expected_ty: Ty<'tcx>,
1934 found_ty: Ty<'tcx>,
1935 expr: &hir::Expr<'_>,
1936 ) {
1937 let expr = self.note_type_is_not_clone_inner_expr(expr);
1940
1941 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else {
1943 return;
1944 };
1945
1946 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else {
1947 return;
1948 };
1949 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1950 let results = self.typeck_results.borrow();
1951 if segment.ident.name == sym::clone
1953 && results.type_dependent_def_id(expr.hir_id).is_some_and(|did| {
1954 let assoc_item = self.tcx.associated_item(did);
1955 assoc_item.container == ty::AssocContainer::Trait
1956 && assoc_item.container_id(self.tcx) == clone_trait_did
1957 })
1958 && !results.expr_adjustments(callee_expr).iter().any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
ty::adjustment::Adjust::Deref(..) => true,
_ => false,
}matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1961 && self.may_coerce(*pointee_ty, expected_ty)
1963 && let trait_ref = ty::TraitRef::new(self.tcx, clone_trait_did, [expected_ty])
1964 && !self.predicate_must_hold_considering_regions(&traits::Obligation::new(
1966 self.tcx,
1967 traits::ObligationCause::dummy(),
1968 self.param_env,
1969 trait_ref,
1970 ))
1971 {
1972 diag.span_note(
1973 callee_expr.span,
1974 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` does not implement `Clone`, so `{1}` was cloned instead",
expected_ty, found_ty))
})format!(
1975 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1976 ),
1977 );
1978 let owner = self.tcx.hir_enclosing_body_owner(expr.hir_id);
1979 if let ty::Param(param) = expected_ty.kind()
1980 && let Some(generics) = self.tcx.hir_get_generics(owner)
1981 {
1982 suggest_constraining_type_params(
1983 self.tcx,
1984 generics,
1985 diag,
1986 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(param.name.as_str(), "Clone", Some(clone_trait_did))]))vec![(param.name.as_str(), "Clone", Some(clone_trait_did))].into_iter(),
1987 None,
1988 );
1989 } else {
1990 let mut suggest_derive = true;
1991 if let Some(errors) =
1992 self.type_implements_trait_shallow(clone_trait_did, expected_ty, self.param_env)
1993 {
1994 let manually_impl = "consider manually implementing `Clone` to avoid the \
1995 implicit type parameter bounds";
1996 match &errors[..] {
1997 [] => {}
1998 [error] => {
1999 let msg = "`Clone` is not implemented because a trait bound is not \
2000 satisfied";
2001 if let traits::ObligationCauseCode::ImplDerived(data) =
2002 error.obligation.cause.code()
2003 {
2004 let mut span: MultiSpan = data.span.into();
2005 if self.tcx.is_automatically_derived(data.impl_or_alias_def_id) {
2006 span.push_span_label(
2007 data.span,
2008 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("derive introduces an implicit `{0}` bound",
error.obligation.predicate))
})format!(
2009 "derive introduces an implicit `{}` bound",
2010 error.obligation.predicate
2011 ),
2012 );
2013 }
2014 diag.span_help(span, msg);
2015 if self.tcx.is_automatically_derived(data.impl_or_alias_def_id)
2016 && data.impl_or_alias_def_id.is_local()
2017 {
2018 diag.help(manually_impl);
2019 suggest_derive = false;
2020 }
2021 } else {
2022 diag.help(msg);
2023 }
2024 }
2025 _ => {
2026 let unsatisfied_bounds: Vec<_> = errors
2027 .iter()
2028 .filter_map(|error| match error.obligation.cause.code() {
2029 traits::ObligationCauseCode::ImplDerived(data) => {
2030 let pre = if self
2031 .tcx
2032 .is_automatically_derived(data.impl_or_alias_def_id)
2033 {
2034 "derive introduces an implicit "
2035 } else {
2036 ""
2037 };
2038 Some((
2039 data.span,
2040 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}unsatisfied trait bound `{0}`",
error.obligation.predicate, pre))
})format!(
2041 "{pre}unsatisfied trait bound `{}`",
2042 error.obligation.predicate
2043 ),
2044 ))
2045 }
2046 _ => None,
2047 })
2048 .collect();
2049 let msg = "`Clone` is not implemented because the some trait bounds \
2050 could not be satisfied";
2051 if errors.len() == unsatisfied_bounds.len() {
2052 let mut unsatisfied_bounds_spans: MultiSpan = unsatisfied_bounds
2053 .iter()
2054 .map(|(span, _)| *span)
2055 .collect::<Vec<Span>>()
2056 .into();
2057 for (span, label) in unsatisfied_bounds {
2058 unsatisfied_bounds_spans.push_span_label(span, label);
2059 }
2060 diag.span_help(unsatisfied_bounds_spans, msg);
2061 if errors.iter().all(|error| match error.obligation.cause.code() {
2062 traits::ObligationCauseCode::ImplDerived(data) => {
2063 self.tcx.is_automatically_derived(data.impl_or_alias_def_id)
2064 && data.impl_or_alias_def_id.is_local()
2065 }
2066 _ => false,
2067 }) {
2068 diag.help(manually_impl);
2069 suggest_derive = false;
2070 }
2071 } else {
2072 diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}: {0}",
listify(&errors,
|e|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
e.obligation.predicate))
})).unwrap(), msg))
})format!(
2073 "{msg}: {}",
2074 listify(&errors, |e| format!("`{}`", e.obligation.predicate))
2075 .unwrap(),
2076 ));
2077 }
2078 }
2079 }
2080 for error in errors {
2081 if let traits::FulfillmentErrorCode::Select(
2082 traits::SelectionError::Unimplemented,
2083 ) = error.code
2084 && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2085 error.obligation.predicate.kind().skip_binder()
2086 {
2087 self.infcx.err_ctxt().suggest_derive(
2088 &error.obligation,
2089 diag,
2090 error.obligation.predicate.kind().rebind(pred),
2091 );
2092 }
2093 }
2094 }
2095 if suggest_derive {
2096 self.suggest_derive(diag, &::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(trait_ref.upcast(self.tcx), None, None)]))vec![(trait_ref.upcast(self.tcx), None, None)]);
2097 }
2098 }
2099 }
2100 }
2101
2102 fn note_type_is_not_clone_inner_expr<'b>(
2107 &'b self,
2108 expr: &'b hir::Expr<'b>,
2109 ) -> &'b hir::Expr<'b> {
2110 match expr.peel_blocks().kind {
2111 hir::ExprKind::Path(hir::QPath::Resolved(
2112 None,
2113 hir::Path { segments: [_], res: crate::Res::Local(binding), .. },
2114 )) => {
2115 let hir::Node::Pat(hir::Pat { hir_id, .. }) = self.tcx.hir_node(*binding) else {
2116 return expr;
2117 };
2118
2119 match self.tcx.parent_hir_node(*hir_id) {
2120 hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) => {
2122 self.note_type_is_not_clone_inner_expr(init)
2123 }
2124 hir::Node::Pat(hir::Pat {
2126 hir_id: pat_hir_id,
2127 kind: hir::PatKind::Tuple(pats, ..),
2128 ..
2129 }) => {
2130 let hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) =
2131 self.tcx.parent_hir_node(*pat_hir_id)
2132 else {
2133 return expr;
2134 };
2135
2136 match init.peel_blocks().kind {
2137 ExprKind::Tup(init_tup) => {
2138 if let Some(init) = pats
2139 .iter()
2140 .enumerate()
2141 .filter(|x| x.1.hir_id == *hir_id)
2142 .find_map(|(i, _)| init_tup.get(i))
2143 {
2144 self.note_type_is_not_clone_inner_expr(init)
2145 } else {
2146 expr
2147 }
2148 }
2149 _ => expr,
2150 }
2151 }
2152 _ => expr,
2153 }
2154 }
2155 hir::ExprKind::Call(Expr { kind: call_expr_kind, .. }, _) => {
2159 if let hir::ExprKind::Path(hir::QPath::Resolved(None, call_expr_path)) =
2160 call_expr_kind
2161 && let hir::Path { segments: [_], res: crate::Res::Local(binding), .. } =
2162 call_expr_path
2163 && let hir::Node::Pat(hir::Pat { hir_id, .. }) = self.tcx.hir_node(*binding)
2164 && let hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) =
2165 self.tcx.parent_hir_node(*hir_id)
2166 && let Expr {
2167 kind: hir::ExprKind::Closure(hir::Closure { body: body_id, .. }),
2168 ..
2169 } = init
2170 {
2171 let hir::Body { value: body_expr, .. } = self.tcx.hir_body(*body_id);
2172 self.note_type_is_not_clone_inner_expr(body_expr)
2173 } else {
2174 expr
2175 }
2176 }
2177 _ => expr,
2178 }
2179 }
2180
2181 pub(crate) fn is_field_suggestable(
2182 &self,
2183 field: &ty::FieldDef,
2184 hir_id: HirId,
2185 span: Span,
2186 ) -> bool {
2187 field.vis.is_accessible_from(self.tcx.parent_module(hir_id), self.tcx)
2189 && !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.eval_stability(field.did,
None, rustc_span::DUMMY_SP, None) {
rustc_middle::middle::stability::EvalResult::Deny { .. } => true,
_ => false,
}matches!(
2191 self.tcx.eval_stability(field.did, None, rustc_span::DUMMY_SP, None),
2192 rustc_middle::middle::stability::EvalResult::Deny { .. }
2193 )
2194 && (field.did.is_local() || !self.tcx.is_doc_hidden(field.did))
2196 && self.tcx.def_ident_span(field.did).unwrap().normalize_to_macros_2_0().eq_ctxt(span)
2198 }
2199
2200 pub(crate) fn suggest_missing_unwrap_expect(
2201 &self,
2202 err: &mut Diag<'_>,
2203 expr: &hir::Expr<'tcx>,
2204 expected: Ty<'tcx>,
2205 found: Ty<'tcx>,
2206 ) -> bool {
2207 let ty::Adt(adt, args) = found.kind() else {
2208 return false;
2209 };
2210 let ret_ty_matches = |diagnostic_item| {
2211 let Some(sig) = self.body_fn_sig() else {
2212 return false;
2213 };
2214 let ty::Adt(kind, _) = sig.output().kind() else {
2215 return false;
2216 };
2217 self.tcx.is_diagnostic_item(diagnostic_item, kind.did())
2218 };
2219
2220 let is_ctor = #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
hir::ExprKind::Call(hir::Expr {
kind: hir::ExprKind::Path(hir::QPath::Resolved(None, hir::Path {
res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. })), .. }, ..)
|
hir::ExprKind::Path(hir::QPath::Resolved(None, hir::Path {
res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. })) => true,
_ => false,
}matches!(
2223 expr.kind,
2224 hir::ExprKind::Call(
2225 hir::Expr {
2226 kind: hir::ExprKind::Path(hir::QPath::Resolved(
2227 None,
2228 hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. },
2229 )),
2230 ..
2231 },
2232 ..,
2233 ) | hir::ExprKind::Path(hir::QPath::Resolved(
2234 None,
2235 hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. },
2236 )),
2237 );
2238
2239 let (article, kind, variant, sugg_operator) = if self.tcx.is_diagnostic_item(sym::Result, adt.did())
2240 && !self.tcx.hir_is_inside_const_context(expr.hir_id)
2242 {
2243 ("a", "Result", "Err", ret_ty_matches(sym::Result))
2244 } else if self.tcx.is_diagnostic_item(sym::Option, adt.did()) {
2245 ("an", "Option", "None", ret_ty_matches(sym::Option))
2246 } else {
2247 return false;
2248 };
2249 if is_ctor || !self.may_coerce(args.type_at(0), expected) {
2250 return false;
2251 }
2252
2253 let (msg, sugg) = if sugg_operator {
2254 (
2255 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use the `?` operator to extract the `{0}` value, propagating {1} `{2}::{3}` value to the caller",
found, article, kind, variant))
})format!(
2256 "use the `?` operator to extract the `{found}` value, propagating \
2257 {article} `{kind}::{variant}` value to the caller"
2258 ),
2259 "?",
2260 )
2261 } else {
2262 (
2263 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider using `{0}::expect` to unwrap the `{1}` value, panicking if the value is {2} `{0}::{3}`",
kind, found, article, variant))
})format!(
2264 "consider using `{kind}::expect` to unwrap the `{found}` value, \
2265 panicking if the value is {article} `{kind}::{variant}`"
2266 ),
2267 ".expect(\"REASON\")",
2268 )
2269 };
2270
2271 let sugg = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2272 Some(_) if expr.span.from_expansion() => return false,
2273 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}{1}", ident, sugg))
})format!(": {ident}{sugg}"),
2274 None => sugg.to_string(),
2275 };
2276
2277 let span = expr
2278 .span
2279 .find_ancestor_not_from_extern_macro(self.tcx.sess.source_map())
2280 .unwrap_or(expr.span);
2281 err.span_suggestion_verbose(span.shrink_to_hi(), msg, sugg, Applicability::HasPlaceholders);
2282 true
2283 }
2284
2285 pub(crate) fn suggest_coercing_result_via_try_operator(
2286 &self,
2287 err: &mut Diag<'_>,
2288 expr: &hir::Expr<'tcx>,
2289 expected: Ty<'tcx>,
2290 found: Ty<'tcx>,
2291 ) -> bool {
2292 let returned = #[allow(non_exhaustive_omitted_patterns)] match self.tcx.parent_hir_node(expr.hir_id)
{
hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. }) => true,
_ => false,
}matches!(
2293 self.tcx.parent_hir_node(expr.hir_id),
2294 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
2295 ) || self.tcx.hir_get_fn_id_for_return_block(expr.hir_id).is_some();
2296 if returned
2297 && let ty::Adt(e, args_e) = expected.kind()
2298 && let ty::Adt(f, args_f) = found.kind()
2299 && e.did() == f.did()
2300 && Some(e.did()) == self.tcx.get_diagnostic_item(sym::Result)
2301 && let e_ok = args_e.type_at(0)
2302 && let f_ok = args_f.type_at(0)
2303 && self.infcx.can_eq(self.param_env, f_ok, e_ok)
2304 && let e_err = args_e.type_at(1)
2305 && let f_err = args_f.type_at(1)
2306 && self
2307 .infcx
2308 .type_implements_trait(
2309 self.tcx.get_diagnostic_item(sym::Into).unwrap(),
2310 [f_err, e_err],
2311 self.param_env,
2312 )
2313 .must_apply_modulo_regions()
2314 {
2315 err.multipart_suggestion(
2316 "use `?` to coerce and return an appropriate `Err`, and wrap the resulting value \
2317 in `Ok` so the expression remains of type `Result`",
2318 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_lo(), "Ok(".to_string()),
(expr.span.shrink_to_hi(), "?)".to_string())]))vec![
2319 (expr.span.shrink_to_lo(), "Ok(".to_string()),
2320 (expr.span.shrink_to_hi(), "?)".to_string()),
2321 ],
2322 Applicability::MaybeIncorrect,
2323 );
2324 return true;
2325 }
2326 false
2327 }
2328
2329 pub(crate) fn suggest_returning_value_after_loop(
2332 &self,
2333 err: &mut Diag<'_>,
2334 expr: &hir::Expr<'tcx>,
2335 expected: Ty<'tcx>,
2336 ) -> bool {
2337 let tcx = self.tcx;
2338 let enclosing_scope =
2339 tcx.hir_get_enclosing_scope(expr.hir_id).map(|hir_id| tcx.hir_node(hir_id));
2340
2341 let tail_expr = if let Some(Node::Block(hir::Block { expr, .. })) = enclosing_scope
2343 && expr.is_some()
2344 {
2345 *expr
2346 } else {
2347 let body_def_id = tcx.hir_enclosing_body_owner(expr.hir_id);
2348 let body = tcx.hir_body_owned_by(body_def_id);
2349
2350 match body.value.kind {
2352 hir::ExprKind::Block(block, _) => block.expr,
2354 hir::ExprKind::DropTemps(expr) => Some(expr),
2356 _ => None,
2357 }
2358 };
2359
2360 let Some(tail_expr) = tail_expr else {
2361 return false; };
2363
2364 let loop_expr_in_tail = match expr.kind {
2366 hir::ExprKind::Loop(_, _, hir::LoopSource::While, _) => tail_expr,
2367 hir::ExprKind::Loop(_, _, hir::LoopSource::ForLoop, _) => {
2368 match tail_expr.peel_drop_temps() {
2369 Expr { kind: ExprKind::Match(_, [Arm { body, .. }], _), .. } => body,
2370 _ => return false, }
2372 }
2373 _ => return false, };
2375
2376 if expr.hir_id == loop_expr_in_tail.hir_id {
2379 let span = expr.span;
2380
2381 let (msg, suggestion) = if expected.is_never() {
2382 (
2383 "consider adding a diverging expression here",
2384 "`loop {}` or `panic!(\"...\")`".to_string(),
2385 )
2386 } else {
2387 ("consider returning a value here", ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` value", expected))
})format!("`{expected}` value"))
2388 };
2389
2390 let src_map = tcx.sess.source_map();
2391 let suggestion = if src_map.is_multiline(expr.span) {
2392 let indentation = src_map.indentation_before(span).unwrap_or_default();
2393 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}/* {1} */", indentation,
suggestion))
})format!("\n{indentation}/* {suggestion} */")
2394 } else {
2395 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" /* {0} */", suggestion))
})format!(" /* {suggestion} */")
2398 };
2399
2400 err.span_suggestion_verbose(
2401 span.shrink_to_hi(),
2402 msg,
2403 suggestion,
2404 Applicability::MaybeIncorrect,
2405 );
2406
2407 true
2408 } else {
2409 false
2410 }
2411 }
2412
2413 pub(crate) fn suggest_semicolon_in_repeat_expr(
2416 &self,
2417 err: &mut Diag<'_>,
2418 expr: &hir::Expr<'_>,
2419 expr_ty: Ty<'tcx>,
2420 ) -> bool {
2421 if let hir::Node::Expr(array_expr) = self.tcx.parent_hir_node(expr.hir_id)
2423 && let hir::ExprKind::Array(elements) = array_expr.kind
2424 && let [first, second] = elements
2425 && second.hir_id == expr.hir_id
2426 {
2427 let comma_span = first.span.between(second.span);
2429
2430 let expr_is_const_usize = expr_ty.is_usize()
2438 && match expr.kind {
2439 ExprKind::Path(QPath::Resolved(
2440 None,
2441 Path { res: Res::Def(DefKind::Const { .. }, _), .. },
2442 )) => true,
2443 ExprKind::Call(
2444 Expr {
2445 kind:
2446 ExprKind::Path(QPath::Resolved(
2447 None,
2448 Path { res: Res::Def(DefKind::Fn, fn_def_id), .. },
2449 )),
2450 ..
2451 },
2452 _,
2453 ) => self.tcx.is_const_fn(*fn_def_id),
2454 _ => false,
2455 };
2456
2457 let first_ty = self.typeck_results.borrow().expr_ty(first);
2462
2463 if self.tcx.sess.source_map().is_imported(array_expr.span)
2468 && self.type_is_clone_modulo_regions(self.param_env, first_ty)
2469 && (expr.is_size_lit() || expr_ty.is_usize_like())
2470 {
2471 err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2472 comma_span,
2473 descr: "a vector",
2474 });
2475 return true;
2476 }
2477
2478 if self.type_is_copy_modulo_regions(self.param_env, first_ty)
2482 && (expr.is_size_lit() || expr_is_const_usize)
2483 {
2484 err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2485 comma_span,
2486 descr: "an array",
2487 });
2488 return true;
2489 }
2490 }
2491 false
2492 }
2493
2494 pub(crate) fn suggest_compatible_variants(
2497 &self,
2498 err: &mut Diag<'_>,
2499 expr: &hir::Expr<'_>,
2500 expected: Ty<'tcx>,
2501 expr_ty: Ty<'tcx>,
2502 ) -> bool {
2503 if expr.span.in_external_macro(self.tcx.sess.source_map()) {
2504 return false;
2505 }
2506 if let ty::Adt(expected_adt, args) = expected.kind() {
2507 if let hir::ExprKind::Field(base, ident) = expr.kind {
2508 let base_ty = self.typeck_results.borrow().expr_ty(base);
2509 if self.can_eq(self.param_env, base_ty, expected)
2510 && let Some(base_span) = base.span.find_ancestor_inside(expr.span)
2511 {
2512 err.span_suggestion_verbose(
2513 expr.span.with_lo(base_span.hi()),
2514 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing the tuple struct field `{0}`",
ident))
})format!("consider removing the tuple struct field `{ident}`"),
2515 "",
2516 Applicability::MaybeIncorrect,
2517 );
2518 return true;
2519 }
2520 }
2521
2522 if expr_ty.is_unit() {
2526 let mut id = expr.hir_id;
2527 let mut parent;
2528
2529 loop {
2531 parent = self.tcx.parent_hir_id(id);
2532 let parent_span = self.tcx.hir_span(parent);
2533 if parent_span.find_ancestor_inside(expr.span).is_some() {
2534 id = parent;
2537 continue;
2538 }
2539 break;
2540 }
2541
2542 if let hir::Node::Block(&hir::Block { span: block_span, expr: Some(e), .. }) =
2543 self.tcx.hir_node(parent)
2544 {
2545 if e.hir_id == id {
2546 if let Some(span) = expr.span.find_ancestor_inside(block_span) {
2547 let return_suggestions = if self
2548 .tcx
2549 .is_diagnostic_item(sym::Result, expected_adt.did())
2550 {
2551 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["Ok(())"]))vec!["Ok(())"]
2552 } else if self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) {
2553 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["None", "Some(())"]))vec!["None", "Some(())"]
2554 } else {
2555 return false;
2556 };
2557 if let Some(indent) =
2558 self.tcx.sess.source_map().indentation_before(span.shrink_to_lo())
2559 {
2560 let semicolon =
2562 match self.tcx.sess.source_map().span_to_snippet(span) {
2563 Ok(s) if s.ends_with('}') => "",
2564 _ => ";",
2565 };
2566 err.span_suggestions(
2567 span.shrink_to_hi(),
2568 "try adding an expression at the end of the block",
2569 return_suggestions
2570 .into_iter()
2571 .map(|r| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}\n{1}{2}", semicolon, indent,
r))
})format!("{semicolon}\n{indent}{r}")),
2572 Applicability::MaybeIncorrect,
2573 );
2574 }
2575 return true;
2576 }
2577 }
2578 }
2579 }
2580
2581 let compatible_variants: Vec<(String, _, _, Option<String>)> = expected_adt
2582 .variants()
2583 .iter()
2584 .filter(|variant| {
2585 variant.fields.len() == 1
2586 })
2587 .filter_map(|variant| {
2588 let sole_field = &variant.single_field();
2589
2590 if let (ty::Adt(exp_adt, _), ty::Adt(act_adt, _)) = (expected.kind(), expr_ty.kind())
2594 && exp_adt.did() == act_adt.did()
2595 && sole_field.ty(self.tcx, args).is_ty_var() {
2596 return None;
2597 }
2598
2599 let field_is_local = sole_field.did.is_local();
2600 let field_is_accessible =
2601 sole_field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
2602 && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.eval_stability(sole_field.did,
None, expr.span, None) {
EvalResult::Allow | EvalResult::Unmarked => true,
_ => false,
}matches!(self.tcx.eval_stability(sole_field.did, None, expr.span, None), EvalResult::Allow | EvalResult::Unmarked);
2604
2605 if !field_is_local && !field_is_accessible {
2606 return None;
2607 }
2608
2609 let note_about_variant_field_privacy = (field_is_local && !field_is_accessible)
2610 .then(|| " (its field is private, but it's local to this crate and its privacy can be changed)".to_string());
2611
2612 let sole_field_ty = sole_field.ty(self.tcx, args);
2613 if self.may_coerce(expr_ty, sole_field_ty) {
2614 let variant_path =
2615 { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(variant.def_id) }with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
2616 if let Some(path) = variant_path.strip_prefix("std::prelude::")
2618 && let Some((_, path)) = path.split_once("::")
2619 {
2620 return Some((path.to_string(), variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy));
2621 }
2622 Some((variant_path, variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy))
2623 } else {
2624 None
2625 }
2626 })
2627 .collect();
2628
2629 let suggestions_for = |variant: &_, ctor_kind, field_name| {
2630 let prefix = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2631 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", ident))
})format!("{ident}: "),
2632 None => String::new(),
2633 };
2634
2635 let (open, close) = match ctor_kind {
2636 Some(CtorKind::Fn) => ("(".to_owned(), ")"),
2637 None => (::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0}: ", field_name))
})format!(" {{ {field_name}: "), " }"),
2638
2639 Some(CtorKind::Const) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unit variants don\'t have fields")));
}unreachable!("unit variants don't have fields"),
2640 };
2641
2642 let mut expr = expr;
2646 while let hir::ExprKind::Block(block, _) = &expr.kind
2647 && let Some(expr_) = &block.expr
2648 {
2649 expr = expr_
2650 }
2651
2652 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix,
variant, open))
})), (expr.span.shrink_to_hi(), close.to_owned())]))vec![
2653 (expr.span.shrink_to_lo(), format!("{prefix}{variant}{open}")),
2654 (expr.span.shrink_to_hi(), close.to_owned()),
2655 ]
2656 };
2657
2658 match &compatible_variants[..] {
2659 [] => { }
2660 [(variant, ctor_kind, field_name, note)] => {
2661 err.multipart_suggestion(
2663 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try wrapping the expression in `{1}`{0}",
note.as_deref().unwrap_or(""), variant))
})format!(
2664 "try wrapping the expression in `{variant}`{note}",
2665 note = note.as_deref().unwrap_or("")
2666 ),
2667 suggestions_for(&**variant, *ctor_kind, *field_name),
2668 Applicability::MaybeIncorrect,
2669 );
2670 return true;
2671 }
2672 _ => {
2673 err.multipart_suggestions(
2675 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try wrapping the expression in a variant of `{0}`",
self.tcx.def_path_str(expected_adt.did())))
})format!(
2676 "try wrapping the expression in a variant of `{}`",
2677 self.tcx.def_path_str(expected_adt.did())
2678 ),
2679 compatible_variants.into_iter().map(
2680 |(variant, ctor_kind, field_name, _)| {
2681 suggestions_for(&variant, ctor_kind, field_name)
2682 },
2683 ),
2684 Applicability::MaybeIncorrect,
2685 );
2686 return true;
2687 }
2688 }
2689 }
2690
2691 false
2692 }
2693
2694 pub(crate) fn suggest_non_zero_new_unwrap(
2695 &self,
2696 err: &mut Diag<'_>,
2697 expr: &hir::Expr<'_>,
2698 expected: Ty<'tcx>,
2699 expr_ty: Ty<'tcx>,
2700 ) -> bool {
2701 let tcx = self.tcx;
2702 let (adt, args, unwrap) = match expected.kind() {
2703 ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Option, adt.did()) => {
2705 let nonzero_type = args.type_at(0); let ty::Adt(adt, args) = nonzero_type.kind() else {
2707 return false;
2708 };
2709 (adt, args, "")
2710 }
2711 ty::Adt(adt, args) => (adt, args, ".unwrap()"),
2713 _ => return false,
2714 };
2715
2716 if !self.tcx.is_diagnostic_item(sym::NonZero, adt.did()) {
2717 return false;
2718 }
2719
2720 let int_type = args.type_at(0);
2721 if !self.may_coerce(expr_ty, int_type) {
2722 return false;
2723 }
2724
2725 err.multipart_suggestion(
2726 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider calling `{0}::new`",
sym::NonZero))
})format!("consider calling `{}::new`", sym::NonZero),
2727 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::new(",
sym::NonZero))
})),
(expr.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("){0}", unwrap))
}))]))vec![
2728 (expr.span.shrink_to_lo(), format!("{}::new(", sym::NonZero)),
2729 (expr.span.shrink_to_hi(), format!("){unwrap}")),
2730 ],
2731 Applicability::MaybeIncorrect,
2732 );
2733
2734 true
2735 }
2736
2737 fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Vec<(Span, String)>, &'static str)> {
2754 let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind else {
2755 return None;
2756 };
2757
2758 let hir::def::Res::Local(local_id) = path.res else {
2759 return None;
2760 };
2761
2762 let Node::Param(hir::Param { hir_id: param_hir_id, .. }) =
2763 self.tcx.parent_hir_node(local_id)
2764 else {
2765 return None;
2766 };
2767
2768 let Node::Expr(hir::Expr {
2769 hir_id: expr_hir_id,
2770 kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }),
2771 ..
2772 }) = self.tcx.parent_hir_node(*param_hir_id)
2773 else {
2774 return None;
2775 };
2776
2777 let hir = self.tcx.parent_hir_node(*expr_hir_id);
2778 let closure_params_len = closure_fn_decl.inputs.len();
2779 let (
2780 Node::Expr(hir::Expr {
2781 kind: hir::ExprKind::MethodCall(method_path, receiver, ..),
2782 ..
2783 }),
2784 1,
2785 ) = (hir, closure_params_len)
2786 else {
2787 return None;
2788 };
2789
2790 let self_ty = self.typeck_results.borrow().expr_ty(receiver);
2791 let name = method_path.ident.name;
2792 let is_as_ref_able = match self_ty.peel_refs().kind() {
2793 ty::Adt(def, _) => {
2794 (self.tcx.is_diagnostic_item(sym::Option, def.did())
2795 || self.tcx.is_diagnostic_item(sym::Result, def.did()))
2796 && (name == sym::map || name == sym::and_then)
2797 }
2798 _ => false,
2799 };
2800 if is_as_ref_able {
2801 Some((
2802 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(method_path.ident.span.shrink_to_lo(), "as_ref().".to_string())]))vec![(method_path.ident.span.shrink_to_lo(), "as_ref().".to_string())],
2803 "consider using `as_ref` instead",
2804 ))
2805 } else {
2806 None
2807 }
2808 }
2809
2810 pub(crate) fn suggest_deref_or_ref(
2827 &self,
2828 expr: &hir::Expr<'tcx>,
2829 checked_ty: Ty<'tcx>,
2830 expected: Ty<'tcx>,
2831 ) -> Option<(
2832 Vec<(Span, String)>,
2833 String,
2834 Applicability,
2835 bool, bool, )> {
2838 let sess = self.sess();
2839 let sp = expr.range_span().unwrap_or(expr.span);
2840 let sm = sess.source_map();
2841
2842 if sp.in_external_macro(sm) {
2844 return None;
2845 }
2846
2847 let replace_prefix = |s: &str, old: &str, new: &str| {
2848 s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
2849 };
2850
2851 let expr = expr.peel_drop_temps();
2853
2854 match (&expr.kind, expected.kind(), checked_ty.kind()) {
2855 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) {
2856 (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
2857 if let hir::ExprKind::Lit(_) = expr.kind
2858 && let Ok(src) = sm.span_to_snippet(sp)
2859 && replace_prefix(&src, "b\"", "\"").is_some()
2860 {
2861 let pos = sp.lo() + BytePos(1);
2862 return Some((
2863 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(sp.with_hi(pos), String::new())]))vec![(sp.with_hi(pos), String::new())],
2864 "consider removing the leading `b`".to_string(),
2865 Applicability::MachineApplicable,
2866 true,
2867 false,
2868 ));
2869 }
2870 }
2871 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
2872 if let hir::ExprKind::Lit(_) = expr.kind
2873 && let Ok(src) = sm.span_to_snippet(sp)
2874 && replace_prefix(&src, "\"", "b\"").is_some()
2875 {
2876 return Some((
2877 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(sp.shrink_to_lo(), "b".to_string())]))vec![(sp.shrink_to_lo(), "b".to_string())],
2878 "consider adding a leading `b`".to_string(),
2879 Applicability::MachineApplicable,
2880 true,
2881 false,
2882 ));
2883 }
2884 }
2885 _ => {}
2886 },
2887 (_, &ty::Ref(_, _, mutability), _) => {
2888 let ref_ty = match mutability {
2897 hir::Mutability::Mut => {
2898 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, checked_ty)
2899 }
2900 hir::Mutability::Not => {
2901 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, checked_ty)
2902 }
2903 };
2904 if self.may_coerce(ref_ty, expected) {
2905 let mut sugg_sp = sp;
2906 if let hir::ExprKind::MethodCall(segment, receiver, args, _) = expr.kind {
2907 let clone_trait =
2908 self.tcx.require_lang_item(LangItem::Clone, segment.ident.span);
2909 if args.is_empty()
2910 && self
2911 .typeck_results
2912 .borrow()
2913 .type_dependent_def_id(expr.hir_id)
2914 .is_some_and(|did| {
2915 let ai = self.tcx.associated_item(did);
2916 ai.trait_container(self.tcx) == Some(clone_trait)
2917 })
2918 && segment.ident.name == sym::clone
2919 {
2920 sugg_sp = receiver.span;
2923 }
2924 }
2925
2926 if let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
2927 && let Some(1) = self.deref_steps_for_suggestion(expected, checked_ty)
2928 && self.typeck_results.borrow().expr_ty(inner).is_ref()
2929 {
2930 sugg_sp = sugg_sp.with_hi(inner.span.lo());
2933 return Some((
2934 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(sugg_sp, String::new())]))vec![(sugg_sp, String::new())],
2935 "consider removing deref here".to_string(),
2936 Applicability::MachineApplicable,
2937 true,
2938 false,
2939 ));
2940 }
2941
2942 if let hir::ExprKind::If(_c, then, els) = expr.kind {
2948 let ExprKind::Block(then, _) = then.kind else { return None };
2951 let Some(then) = then.expr else { return None };
2952 let (mut suggs, help, app, verbose, mutref) =
2953 self.suggest_deref_or_ref(then, checked_ty, expected)?;
2954
2955 let els_expr = match els?.kind {
2957 ExprKind::Block(block, _) => block.expr?,
2958 _ => els?,
2959 };
2960 let (else_suggs, ..) =
2961 self.suggest_deref_or_ref(els_expr, checked_ty, expected)?;
2962 suggs.extend(else_suggs);
2963
2964 return Some((suggs, help, app, verbose, mutref));
2965 }
2966
2967 if let Some((sugg, msg)) = self.can_use_as_ref(expr) {
2968 return Some((
2969 sugg,
2970 msg.to_string(),
2971 Applicability::MachineApplicable,
2972 true,
2973 false,
2974 ));
2975 }
2976
2977 let prefix = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2978 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", ident))
})format!("{ident}: "),
2979 None => String::new(),
2980 };
2981
2982 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Assign(..), .. }) =
2983 self.tcx.parent_hir_node(expr.hir_id)
2984 {
2985 if mutability.is_mut() {
2986 return None;
2988 }
2989 }
2990
2991 let make_sugg = |expr: &Expr<'_>, span: Span, sugg: &str| {
2992 if expr_needs_parens(expr) {
2993 (
2994 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}(", prefix, sugg))
})), (span.shrink_to_hi(), ")".to_string())]))vec![
2995 (span.shrink_to_lo(), format!("{prefix}{sugg}(")),
2996 (span.shrink_to_hi(), ")".to_string()),
2997 ],
2998 false,
2999 )
3000 } else {
3001 (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", prefix, sugg))
}))]))vec![(span.shrink_to_lo(), format!("{prefix}{sugg}"))], true)
3002 }
3003 };
3004
3005 if let hir::Node::Expr(hir::Expr {
3007 kind: hir::ExprKind::Binary(_, lhs, ..),
3008 ..
3009 }) = self.tcx.parent_hir_node(expr.hir_id)
3010 && let &ty::Ref(..) = self.check_expr(lhs).kind()
3011 {
3012 let (sugg, verbose) = make_sugg(lhs, lhs.span, "*");
3013
3014 return Some((
3015 sugg,
3016 "consider dereferencing the borrow".to_string(),
3017 Applicability::MachineApplicable,
3018 verbose,
3019 false,
3020 ));
3021 }
3022
3023 let sugg = mutability.ref_prefix_str();
3024 let (sugg, verbose) = make_sugg(expr, sp, sugg);
3025 return Some((
3026 sugg,
3027 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider {0}borrowing here",
mutability.mutably_str()))
})format!("consider {}borrowing here", mutability.mutably_str()),
3028 Applicability::MachineApplicable,
3029 verbose,
3030 false,
3031 ));
3032 }
3033 }
3034 (hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr), _, &ty::Ref(_, checked, _))
3035 if self.can_eq(self.param_env, checked, expected) =>
3036 {
3037 let make_sugg = |start: Span, end: BytePos| {
3038 let sp = sm
3041 .span_extend_while(start.shrink_to_lo(), |c| c == '(' || c.is_whitespace())
3042 .map_or(start, |s| s.shrink_to_hi());
3043 Some((
3044 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(sp.with_hi(end), String::new())]))vec![(sp.with_hi(end), String::new())],
3045 "consider removing the borrow".to_string(),
3046 Applicability::MachineApplicable,
3047 true,
3048 true,
3049 ))
3050 };
3051
3052 if sm.is_imported(expr.span) {
3055 if let Some(call_span) =
3061 iter::successors(Some(expr.span), |s| s.parent_callsite())
3062 .find(|&s| sp.contains(s))
3063 && sm.is_span_accessible(call_span)
3064 {
3065 return make_sugg(sp, call_span.lo());
3066 }
3067 return None;
3068 }
3069 if sp.contains(expr.span) && sm.is_span_accessible(expr.span) {
3070 return make_sugg(sp, expr.span.lo());
3071 }
3072 }
3073 (_, &ty::RawPtr(ty_b, mutbl_b), &ty::Ref(_, ty_a, mutbl_a)) => {
3074 if let Some(steps) = self.deref_steps_for_suggestion(ty_a, ty_b)
3075 && steps > 0
3077 && let Ok(src) = sm.span_to_snippet(sp)
3079 {
3080 let derefs = "*".repeat(steps);
3081 let old_prefix = mutbl_a.ref_prefix_str();
3082 let new_prefix = mutbl_b.ref_prefix_str().to_owned() + &derefs;
3083
3084 let suggestion = replace_prefix(&src, old_prefix, &new_prefix).map(|_| {
3085 let lo = sp.lo()
3087 + BytePos(min(old_prefix.len(), mutbl_b.ref_prefix_str().len()) as _);
3088 let hi = sp.lo() + BytePos(old_prefix.len() as _);
3090 let sp = sp.with_lo(lo).with_hi(hi);
3091
3092 (
3093 sp,
3094 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" },
derefs))
})format!(
3095 "{}{derefs}",
3096 if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" }
3097 ),
3098 if mutbl_b <= mutbl_a {
3099 Applicability::MachineApplicable
3100 } else {
3101 Applicability::MaybeIncorrect
3102 },
3103 )
3104 });
3105
3106 if let Some((span, src, applicability)) = suggestion {
3107 return Some((
3108 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, src)]))vec![(span, src)],
3109 "consider dereferencing".to_string(),
3110 applicability,
3111 true,
3112 false,
3113 ));
3114 }
3115 }
3116 }
3117 _ if sp == expr.span => {
3118 if let Some(mut steps) = self.deref_steps_for_suggestion(checked_ty, expected) {
3119 let mut expr = expr.peel_blocks();
3120 let mut prefix_span = expr.span.shrink_to_lo();
3121 let mut remove = String::new();
3122
3123 while steps > 0 {
3125 if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind {
3126 prefix_span = prefix_span.with_hi(inner.span.lo());
3128 expr = inner;
3129 remove.push_str(mutbl.ref_prefix_str());
3130 steps -= 1;
3131 } else {
3132 break;
3133 }
3134 }
3135 if steps == 0 && !remove.trim().is_empty() {
3137 return Some((
3138 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(prefix_span, String::new())]))vec![(prefix_span, String::new())],
3139 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing the `{0}`",
remove.trim()))
})format!("consider removing the `{}`", remove.trim()),
3140 if remove.trim() == "&&" && expected == self.tcx.types.bool {
3144 Applicability::MaybeIncorrect
3145 } else {
3146 Applicability::MachineApplicable
3147 },
3148 true,
3149 false,
3150 ));
3151 }
3152
3153 if self.type_is_copy_modulo_regions(self.param_env, expected)
3156 || (checked_ty.is_box() && steps == 1)
3159 || #[allow(non_exhaustive_omitted_patterns)] match self.tcx.parent_hir_node(expr.hir_id)
{
hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, ..), .. }) if
!op.node.is_by_value() => true,
_ => false,
}matches!(
3161 self.tcx.parent_hir_node(expr.hir_id),
3162 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, ..), .. })
3163 if !op.node.is_by_value()
3164 )
3165 {
3166 let deref_kind = if checked_ty.is_box() {
3167 if let ExprKind::Call(box_new, [_]) = expr.kind
3169 && let ExprKind::Path(qpath) = &box_new.kind
3170 && let Res::Def(DefKind::AssocFn, fn_id) =
3171 self.typeck_results.borrow().qpath_res(qpath, box_new.hir_id)
3172 && self.tcx.is_diagnostic_item(sym::box_new, fn_id)
3173 {
3174 let l_paren = self.tcx.sess.source_map().next_point(box_new.span);
3175 let r_paren = self.tcx.sess.source_map().end_point(expr.span);
3176 return Some((
3177 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(box_new.span.to(l_paren), String::new()),
(r_paren, String::new())]))vec![
3178 (box_new.span.to(l_paren), String::new()),
3179 (r_paren, String::new()),
3180 ],
3181 "consider removing the Box".to_string(),
3182 Applicability::MachineApplicable,
3183 false,
3184 false,
3185 ));
3186 }
3187 "unboxing the value"
3188 } else if checked_ty.is_ref() {
3189 "dereferencing the borrow"
3190 } else {
3191 "dereferencing the type"
3192 };
3193
3194 let message = if remove.is_empty() {
3197 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider {0}", deref_kind))
})format!("consider {deref_kind}")
3198 } else {
3199 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing the `{0}` and {1} instead",
remove.trim(), deref_kind))
})format!(
3200 "consider removing the `{}` and {} instead",
3201 remove.trim(),
3202 deref_kind
3203 )
3204 };
3205
3206 let prefix =
3207 match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
3208 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", ident))
})format!("{ident}: "),
3209 None => String::new(),
3210 };
3211
3212 let (span, suggestion) = if self.is_else_if_block(expr) {
3213 return None;
3215 } else if let Some(expr) = self.maybe_get_block_expr(expr) {
3216 (expr.span.shrink_to_lo(), "*".to_string())
3218 } else {
3219 (prefix_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", prefix,
"*".repeat(steps)))
})format!("{}{}", prefix, "*".repeat(steps)))
3220 };
3221 if suggestion.trim().is_empty() {
3222 return None;
3223 }
3224
3225 if expr_needs_parens(expr) {
3226 return Some((
3227 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}(", suggestion))
})), (expr.span.shrink_to_hi(), ")".to_string())]))vec![
3228 (span, format!("{suggestion}(")),
3229 (expr.span.shrink_to_hi(), ")".to_string()),
3230 ],
3231 message,
3232 Applicability::MachineApplicable,
3233 true,
3234 false,
3235 ));
3236 }
3237
3238 return Some((
3239 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, suggestion)]))vec![(span, suggestion)],
3240 message,
3241 Applicability::MachineApplicable,
3242 true,
3243 false,
3244 ));
3245 }
3246 }
3247 }
3248 _ => {}
3249 }
3250 None
3251 }
3252
3253 fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool {
3255 if let hir::ExprKind::If(..) = expr.kind
3256 && let Node::Expr(hir::Expr { kind: hir::ExprKind::If(_, _, Some(else_expr)), .. }) =
3257 self.tcx.parent_hir_node(expr.hir_id)
3258 {
3259 return else_expr.hir_id == expr.hir_id;
3260 }
3261 false
3262 }
3263
3264 pub(crate) fn suggest_cast(
3265 &self,
3266 err: &mut Diag<'_>,
3267 expr: &hir::Expr<'_>,
3268 checked_ty: Ty<'tcx>,
3269 expected_ty: Ty<'tcx>,
3270 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
3271 ) -> bool {
3272 if self.tcx.sess.source_map().is_imported(expr.span) {
3273 return false;
3275 }
3276
3277 let span = if let hir::ExprKind::Lit(lit) = &expr.kind { lit.span } else { expr.span };
3278 let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) else {
3279 return false;
3280 };
3281
3282 let can_cast = false;
3291
3292 let mut sugg = ::alloc::vec::Vec::new()vec![];
3293
3294 if let hir::Node::ExprField(field) = self.tcx.parent_hir_node(expr.hir_id) {
3295 if field.is_shorthand {
3297 sugg.push((field.ident.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", field.ident))
})format!("{}: ", field.ident)));
3299 } else {
3300 return false;
3302 }
3303 };
3304
3305 if let hir::ExprKind::Call(path, args) = &expr.kind
3306 && let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
3307 (&path.kind, args.len())
3308 && let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
3310 (&base_ty.kind, path_segment.ident.name)
3311 {
3312 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
3313 match ident.name {
3314 sym::i128
3315 | sym::i64
3316 | sym::i32
3317 | sym::i16
3318 | sym::i8
3319 | sym::u128
3320 | sym::u64
3321 | sym::u32
3322 | sym::u16
3323 | sym::u8
3324 | sym::isize
3325 | sym::usize
3326 if base_ty_path.segments.len() == 1 =>
3327 {
3328 return false;
3329 }
3330 _ => {}
3331 }
3332 }
3333 }
3334
3335 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you can convert {0} `{1}` to {2} `{3}`",
checked_ty.kind().article(), checked_ty,
expected_ty.kind().article(), expected_ty))
})format!(
3336 "you can convert {} `{}` to {} `{}`",
3337 checked_ty.kind().article(),
3338 checked_ty,
3339 expected_ty.kind().article(),
3340 expected_ty,
3341 );
3342 let cast_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you can cast {0} `{1}` to {2} `{3}`",
checked_ty.kind().article(), checked_ty,
expected_ty.kind().article(), expected_ty))
})format!(
3343 "you can cast {} `{}` to {} `{}`",
3344 checked_ty.kind().article(),
3345 checked_ty,
3346 expected_ty.kind().article(),
3347 expected_ty,
3348 );
3349 let lit_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("change the type of the numeric literal from `{0}` to `{1}`",
checked_ty, expected_ty))
})format!(
3350 "change the type of the numeric literal from `{checked_ty}` to `{expected_ty}`",
3351 );
3352
3353 let close_paren = if self.precedence(expr) < ExprPrecedence::Unambiguous {
3354 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
3355 ")"
3356 } else {
3357 ""
3358 };
3359
3360 let mut cast_suggestion = sugg.clone();
3361 cast_suggestion.push((expr.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} as {1}", close_paren,
expected_ty))
})format!("{close_paren} as {expected_ty}")));
3362 let mut into_suggestion = sugg.clone();
3363 into_suggestion.push((expr.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.into()", close_paren))
})format!("{close_paren}.into()")));
3364 let mut suffix_suggestion = sugg.clone();
3365 suffix_suggestion.push((
3366 if #[allow(non_exhaustive_omitted_patterns)] match (expected_ty.kind(),
checked_ty.kind()) {
(ty::Int(_) | ty::Uint(_), ty::Float(_)) => true,
_ => false,
}matches!(
3367 (expected_ty.kind(), checked_ty.kind()),
3368 (ty::Int(_) | ty::Uint(_), ty::Float(_))
3369 ) {
3370 let src = src.trim_end_matches(&checked_ty.to_string());
3372 let len = src.split('.').next().unwrap().len();
3373 span.with_lo(span.lo() + BytePos(len as u32))
3374 } else {
3375 let len = src.trim_end_matches(&checked_ty.to_string()).len();
3376 span.with_lo(span.lo() + BytePos(len as u32))
3377 },
3378 if self.precedence(expr) < ExprPrecedence::Unambiguous {
3379 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0})", expected_ty))
})format!("{expected_ty})")
3381 } else {
3382 expected_ty.to_string()
3383 },
3384 ));
3385 let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
3386 if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
3387 };
3388 let is_negative_int =
3389 |expr: &hir::Expr<'_>| #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
hir::ExprKind::Unary(hir::UnOp::Neg, ..) => true,
_ => false,
}matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::Neg, ..));
3390 let is_uint = |ty: Ty<'_>| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Uint(..) => true,
_ => false,
}matches!(ty.kind(), ty::Uint(..));
3391
3392 let in_const_context = self.tcx.hir_is_inside_const_context(expr.hir_id);
3393
3394 let suggest_fallible_into_or_lhs_from =
3395 |err: &mut Diag<'_>, exp_to_found_is_fallible: bool| {
3396 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
3403 self.tcx
3404 .sess
3405 .source_map()
3406 .span_to_snippet(expr.span)
3407 .ok()
3408 .map(|src| (expr, src))
3409 });
3410 let (msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
3411 (lhs_expr_and_src, exp_to_found_is_fallible)
3412 {
3413 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you can convert `{0}` from `{1}` to `{2}`, matching the type of `{3}`",
lhs_src, expected_ty, checked_ty, src))
})format!(
3414 "you can convert `{lhs_src}` from `{expected_ty}` to `{checked_ty}`, matching the type of `{src}`",
3415 );
3416 let suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lhs_expr.span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::from(", checked_ty))
})), (lhs_expr.span.shrink_to_hi(), ")".to_string())]))vec![
3417 (lhs_expr.span.shrink_to_lo(), format!("{checked_ty}::from(")),
3418 (lhs_expr.span.shrink_to_hi(), ")".to_string()),
3419 ];
3420 (msg, suggestion)
3421 } else {
3422 let msg =
3423 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} and panic if the converted value doesn\'t fit",
msg.clone()))
})format!("{} and panic if the converted value doesn't fit", msg.clone());
3424 let mut suggestion = sugg.clone();
3425 suggestion.push((
3426 expr.span.shrink_to_hi(),
3427 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.try_into().unwrap()",
close_paren))
})format!("{close_paren}.try_into().unwrap()"),
3428 ));
3429 (msg, suggestion)
3430 };
3431 err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
3432 };
3433
3434 let suggest_to_change_suffix_or_into =
3435 |err: &mut Diag<'_>, found_to_exp_is_fallible: bool, exp_to_found_is_fallible: bool| {
3436 let exp_is_lhs = expected_ty_expr.is_some_and(|e| self.tcx.hir_is_lhs(e.hir_id));
3437
3438 if exp_is_lhs {
3439 return;
3440 }
3441
3442 let always_fallible = found_to_exp_is_fallible
3443 && (exp_to_found_is_fallible || expected_ty_expr.is_none());
3444 let msg = if literal_is_ty_suffixed(expr) {
3445 lit_msg.clone()
3446 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
3447 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` cannot fit into type `{1}`",
src, expected_ty))
})format!("`{src}` cannot fit into type `{expected_ty}`");
3451 err.note(msg);
3452 return;
3453 } else if in_const_context {
3454 return;
3456 } else if found_to_exp_is_fallible {
3457 return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
3458 } else {
3459 msg.clone()
3460 };
3461 let suggestion = if literal_is_ty_suffixed(expr) {
3462 suffix_suggestion.clone()
3463 } else {
3464 into_suggestion.clone()
3465 };
3466 err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
3467 };
3468
3469 match (expected_ty.kind(), checked_ty.kind()) {
3470 (ty::Int(exp), ty::Int(found)) => {
3471 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3472 {
3473 (Some(exp), Some(found)) if exp < found => (true, false),
3474 (Some(exp), Some(found)) if exp > found => (false, true),
3475 (None, Some(8 | 16)) => (false, true),
3476 (Some(8 | 16), None) => (true, false),
3477 (None, _) | (_, None) => (true, true),
3478 _ => (false, false),
3479 };
3480 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3481 true
3482 }
3483 (ty::Uint(exp), ty::Uint(found)) => {
3484 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3485 {
3486 (Some(exp), Some(found)) if exp < found => (true, false),
3487 (Some(exp), Some(found)) if exp > found => (false, true),
3488 (None, Some(8 | 16)) => (false, true),
3489 (Some(8 | 16), None) => (true, false),
3490 (None, _) | (_, None) => (true, true),
3491 _ => (false, false),
3492 };
3493 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3494 true
3495 }
3496 (&ty::Int(exp), &ty::Uint(found)) => {
3497 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3498 {
3499 (Some(exp), Some(found)) if found < exp => (false, true),
3500 (None, Some(8)) => (false, true),
3501 _ => (true, true),
3502 };
3503 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3504 true
3505 }
3506 (&ty::Uint(exp), &ty::Int(found)) => {
3507 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3508 {
3509 (Some(exp), Some(found)) if found > exp => (true, false),
3510 (Some(8), None) => (true, false),
3511 _ => (true, true),
3512 };
3513 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3514 true
3515 }
3516 (ty::Float(exp), ty::Float(found)) => {
3517 if found.bit_width() < exp.bit_width() {
3518 suggest_to_change_suffix_or_into(err, false, true);
3519 } else if literal_is_ty_suffixed(expr) {
3520 err.multipart_suggestion(
3521 lit_msg,
3522 suffix_suggestion,
3523 Applicability::MachineApplicable,
3524 );
3525 } else if can_cast {
3526 err.multipart_suggestion(
3528 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, producing the closest possible value",
cast_msg))
})format!("{cast_msg}, producing the closest possible value"),
3529 cast_suggestion,
3530 Applicability::MaybeIncorrect, );
3532 }
3533 true
3534 }
3535 (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
3536 if literal_is_ty_suffixed(expr) {
3537 err.multipart_suggestion(
3538 lit_msg,
3539 suffix_suggestion,
3540 Applicability::MachineApplicable,
3541 );
3542 } else if can_cast {
3543 err.multipart_suggestion(
3545 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, rounding the float towards zero",
msg))
})format!("{msg}, rounding the float towards zero"),
3546 cast_suggestion,
3547 Applicability::MaybeIncorrect, );
3549 }
3550 true
3551 }
3552 (ty::Float(exp), ty::Uint(found)) => {
3553 if exp.bit_width() > found.bit_width().unwrap_or(256) {
3555 err.multipart_suggestion(
3556 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer",
msg))
})format!(
3557 "{msg}, producing the floating point representation of the integer",
3558 ),
3559 into_suggestion,
3560 Applicability::MachineApplicable,
3561 );
3562 } else if literal_is_ty_suffixed(expr) {
3563 err.multipart_suggestion(
3564 lit_msg,
3565 suffix_suggestion,
3566 Applicability::MachineApplicable,
3567 );
3568 } else {
3569 err.multipart_suggestion(
3571 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer, rounded if necessary",
cast_msg))
})format!(
3572 "{cast_msg}, producing the floating point representation of the integer, \
3573 rounded if necessary",
3574 ),
3575 cast_suggestion,
3576 Applicability::MaybeIncorrect, );
3578 }
3579 true
3580 }
3581 (ty::Float(exp), ty::Int(found)) => {
3582 if exp.bit_width() > found.bit_width().unwrap_or(256) {
3584 err.multipart_suggestion(
3585 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer",
msg.clone()))
})format!(
3586 "{}, producing the floating point representation of the integer",
3587 msg.clone(),
3588 ),
3589 into_suggestion,
3590 Applicability::MachineApplicable,
3591 );
3592 } else if literal_is_ty_suffixed(expr) {
3593 err.multipart_suggestion(
3594 lit_msg,
3595 suffix_suggestion,
3596 Applicability::MachineApplicable,
3597 );
3598 } else {
3599 err.multipart_suggestion(
3601 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer, rounded if necessary",
&msg))
})format!(
3602 "{}, producing the floating point representation of the integer, \
3603 rounded if necessary",
3604 &msg,
3605 ),
3606 cast_suggestion,
3607 Applicability::MaybeIncorrect, );
3609 }
3610 true
3611 }
3612 (
3613 &ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128)
3614 | &ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128),
3615 &ty::Char,
3616 ) => {
3617 err.multipart_suggestion(
3618 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, since a `char` always occupies 4 bytes",
cast_msg))
})format!("{cast_msg}, since a `char` always occupies 4 bytes"),
3619 cast_suggestion,
3620 Applicability::MachineApplicable,
3621 );
3622 true
3623 }
3624 _ => false,
3625 }
3626 }
3627
3628 pub(crate) fn suggest_method_call_on_range_literal(
3630 &self,
3631 err: &mut Diag<'_>,
3632 expr: &hir::Expr<'tcx>,
3633 checked_ty: Ty<'tcx>,
3634 expected_ty: Ty<'tcx>,
3635 ) {
3636 if !hir::is_range_literal(expr) {
3637 return;
3638 }
3639 let hir::ExprKind::Struct(&qpath, [start, end], _) = expr.kind else {
3640 return;
3641 };
3642 if !self.tcx.qpath_is_lang_item(qpath, LangItem::Range) {
3643 return;
3644 }
3645 if let hir::Node::ExprField(_) = self.tcx.parent_hir_node(expr.hir_id) {
3646 return;
3648 }
3649 let mut expr = end.expr;
3650 let mut expectation = Some(expected_ty);
3651 while let hir::ExprKind::MethodCall(_, rcvr, ..) = expr.kind {
3652 expr = rcvr;
3655 expectation = None;
3658 }
3659 let hir::ExprKind::Call(method_name, _) = expr.kind else {
3660 return;
3661 };
3662 let ty::Adt(adt, _) = checked_ty.kind() else {
3663 return;
3664 };
3665 if self.tcx.lang_items().range_struct() != Some(adt.did()) {
3666 return;
3667 }
3668 if let ty::Adt(adt, _) = expected_ty.kind()
3669 && self.tcx.is_lang_item(adt.did(), LangItem::Range)
3670 {
3671 return;
3672 }
3673 let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else {
3675 return;
3676 };
3677 let [hir::PathSegment { ident, .. }] = p.segments else {
3678 return;
3679 };
3680 let self_ty = self.typeck_results.borrow().expr_ty(start.expr);
3681 let Ok(_pick) = self.lookup_probe_for_diagnostic(
3682 *ident,
3683 self_ty,
3684 expr,
3685 probe::ProbeScope::AllTraits,
3686 expectation,
3687 ) else {
3688 return;
3689 };
3690 let mut sugg = ".";
3691 let mut span = start.expr.span.between(end.expr.span);
3692 if span.lo() + BytePos(2) == span.hi() {
3693 span = span.with_lo(span.lo() + BytePos(1));
3696 sugg = "";
3697 }
3698 err.span_suggestion_verbose(
3699 span,
3700 "you likely meant to write a method call instead of a range",
3701 sugg,
3702 Applicability::MachineApplicable,
3703 );
3704 }
3705
3706 pub(crate) fn suggest_return_binding_for_missing_tail_expr(
3709 &self,
3710 err: &mut Diag<'_>,
3711 expr: &hir::Expr<'_>,
3712 checked_ty: Ty<'tcx>,
3713 expected_ty: Ty<'tcx>,
3714 ) {
3715 if !checked_ty.is_unit() {
3716 return;
3717 }
3718 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
3719 return;
3720 };
3721 let hir::def::Res::Local(hir_id) = path.res else {
3722 return;
3723 };
3724 let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
3725 return;
3726 };
3727 let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
3728 self.tcx.parent_hir_node(pat.hir_id)
3729 else {
3730 return;
3731 };
3732 let hir::ExprKind::Block(block, None) = init.kind else {
3733 return;
3734 };
3735 if block.expr.is_some() {
3736 return;
3737 }
3738 let [.., stmt] = block.stmts else {
3739 err.span_label(block.span, "this empty block is missing a tail expression");
3740 return;
3741 };
3742 let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
3743 return;
3744 };
3745 let Some(ty) = self.node_ty_opt(tail_expr.hir_id) else {
3746 return;
3747 };
3748 if self.can_eq(self.param_env, expected_ty, ty)
3749 && stmt.span.hi() != tail_expr.span.hi()
3754 {
3755 err.span_suggestion_short(
3756 stmt.span.with_lo(tail_expr.span.hi()),
3757 "remove this semicolon",
3758 "",
3759 Applicability::MachineApplicable,
3760 );
3761 } else {
3762 err.span_label(block.span, "this block is missing a tail expression");
3763 }
3764 }
3765
3766 pub(crate) fn suggest_swapping_lhs_and_rhs(
3767 &self,
3768 err: &mut Diag<'_>,
3769 rhs_ty: Ty<'tcx>,
3770 lhs_ty: Ty<'tcx>,
3771 rhs_expr: &'tcx hir::Expr<'tcx>,
3772 lhs_expr: &'tcx hir::Expr<'tcx>,
3773 ) {
3774 if let Some(partial_eq_def_id) = self.infcx.tcx.lang_items().eq_trait()
3775 && self
3776 .infcx
3777 .type_implements_trait(partial_eq_def_id, [rhs_ty, lhs_ty], self.param_env)
3778 .must_apply_modulo_regions()
3779 {
3780 let sm = self.tcx.sess.source_map();
3781 if !rhs_expr.span.in_external_macro(sm)
3784 && !lhs_expr.span.in_external_macro(sm)
3785 && let Ok(rhs_snippet) = sm.span_to_snippet(rhs_expr.span)
3786 && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_expr.span)
3787 {
3788 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `PartialEq<{1}>`",
rhs_ty, lhs_ty))
})format!("`{rhs_ty}` implements `PartialEq<{lhs_ty}>`"));
3789 err.multipart_suggestion(
3790 "consider swapping the equality",
3791 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lhs_expr.span, rhs_snippet), (rhs_expr.span, lhs_snippet)]))vec![(lhs_expr.span, rhs_snippet), (rhs_expr.span, lhs_snippet)],
3792 Applicability::MaybeIncorrect,
3793 );
3794 }
3795 }
3796 }
3797}