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_collect(
258 &self,
259 err: &mut Diag<'_>,
260 expr: &hir::Expr<'_>,
261 expected_type: Ty<'tcx>,
262 found_type: Ty<'tcx>,
263 ) -> bool {
264 let tcx = self.tcx;
265 let expected = self.resolve_vars_if_possible(expected_type);
266 let found = self.resolve_vars_if_possible(found_type);
267
268 if expected.references_error() || found.references_error() || expected.is_unit() {
269 return false;
270 }
271
272 let Some(iterator_trait_id) = tcx.get_diagnostic_item(sym::Iterator) else {
273 return false;
274 };
275
276 if !self
277 .infcx
278 .type_implements_trait(iterator_trait_id, [found], self.param_env)
279 .must_apply_modulo_regions()
280 {
281 return false;
282 }
283
284 let Some(from_iterator_trait_id) = tcx.get_diagnostic_item(sym::FromIterator) else {
285 return false;
286 };
287
288 let Some(iterator_item_id) = tcx
289 .associated_items(iterator_trait_id)
290 .in_definition_order()
291 .find(|item| item.name() == sym::Item)
292 .map(|item| item.def_id)
293 else {
294 return false;
295 };
296
297 let item_type = Ty::new_projection(tcx, iterator_item_id, [found]);
298 let item_type =
299 self.normalize(expr.span, rustc_middle::ty::Unnormalized::new_wip(item_type));
300
301 let can_collect = self
302 .infcx
303 .type_implements_trait(from_iterator_trait_id, [expected, item_type], self.param_env)
304 .may_apply();
305
306 if can_collect {
307 err.span_suggestion_verbose(
308 expr.span.shrink_to_hi(),
309 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider using `.collect()` to convert the `Iterator` into a `{0}`",
expected))
})format!(
310 "consider using `.collect()` to convert the `Iterator` into a `{expected}`"
311 ),
312 ".collect()",
313 rustc_errors::Applicability::MaybeIncorrect,
314 );
315 return true;
316 }
317
318 false
319 }
320
321 pub(crate) fn suggest_remove_last_method_call(
322 &self,
323 err: &mut Diag<'_>,
324 expr: &hir::Expr<'tcx>,
325 expected: Ty<'tcx>,
326 ) -> bool {
327 if let hir::ExprKind::MethodCall(hir::PathSegment { ident: method, .. }, recv_expr, &[], _) =
328 expr.kind
329 && let Some(recv_ty) = self.typeck_results.borrow().expr_ty_opt(recv_expr)
330 && self.may_coerce(recv_ty, expected)
331 && let name = method.name.as_str()
332 && (name.starts_with("to_") || name.starts_with("as_") || name == "into")
333 {
334 let span = if let Some(recv_span) = recv_expr.span.find_ancestor_inside(expr.span) {
335 expr.span.with_lo(recv_span.hi())
336 } else {
337 expr.span.with_lo(method.span.lo() - rustc_span::BytePos(1))
338 };
339 err.span_suggestion_verbose(
340 span,
341 "try removing the method call",
342 "",
343 Applicability::MachineApplicable,
344 );
345 return true;
346 }
347 false
348 }
349
350 pub(crate) fn suggest_deref_ref_or_into(
351 &self,
352 err: &mut Diag<'_>,
353 expr: &hir::Expr<'tcx>,
354 expected: Ty<'tcx>,
355 found: Ty<'tcx>,
356 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
357 ) -> bool {
358 let expr = expr.peel_blocks();
359 let methods =
360 self.get_conversion_methods_for_diagnostic(expr.span, expected, found, expr.hir_id);
361
362 if let Some((suggestion, msg, applicability, verbose, annotation)) =
363 self.suggest_deref_or_ref(expr, found, expected)
364 {
365 if verbose {
366 err.multipart_suggestion(msg, suggestion, applicability);
367 } else {
368 err.multipart_suggestion(msg, suggestion, applicability);
369 }
370 if annotation {
371 let suggest_annotation = match expr.peel_drop_temps().kind {
372 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, _) => mutbl.ref_prefix_str(),
373 _ => return true,
374 };
375 let mut tuple_indexes = Vec::new();
376 let mut expr_id = expr.hir_id;
377 for (parent_id, node) in self.tcx.hir_parent_iter(expr.hir_id) {
378 match node {
379 Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
380 tuple_indexes.push(
381 subs.iter()
382 .enumerate()
383 .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
384 .unwrap()
385 .0,
386 );
387 expr_id = parent_id;
388 }
389 Node::LetStmt(local) => {
390 if let Some(mut ty) = local.ty {
391 while let Some(index) = tuple_indexes.pop() {
392 match ty.kind {
393 TyKind::Tup(tys) => ty = &tys[index],
394 _ => return true,
395 }
396 }
397 let annotation_span = ty.span;
398 err.span_suggestion(
399 annotation_span.with_hi(annotation_span.lo()),
400 "alternatively, consider changing the type annotation",
401 suggest_annotation,
402 Applicability::MaybeIncorrect,
403 );
404 }
405 break;
406 }
407 _ => break,
408 }
409 }
410 }
411 return true;
412 }
413
414 if self.suggest_else_fn_with_closure(err, expr, found, expected) {
415 return true;
416 }
417
418 if self.suggest_fn_call(err, expr, found, |output| self.may_coerce(output, expected))
419 && let ty::FnDef(def_id, ..) = *found.kind()
420 && let Some(sp) = self.tcx.hir_span_if_local(def_id)
421 {
422 let name = self.tcx.item_name(def_id);
423 let kind = self.tcx.def_kind(def_id);
424 if let DefKind::Ctor(of, CtorKind::Fn) = kind {
425 err.span_label(
426 sp,
427 ::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!(
428 "`{name}` defines {} constructor here, which should be called",
429 match of {
430 CtorOf::Struct => "a struct",
431 CtorOf::Variant => "an enum variant",
432 }
433 ),
434 );
435 } else {
436 let descr = self.tcx.def_kind_descr(kind, def_id);
437 err.span_label(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` defined here", descr,
name))
})format!("{descr} `{name}` defined here"));
438 }
439 return true;
440 }
441
442 if self.suggest_cast(err, expr, found, expected, expected_ty_expr) {
443 return true;
444 }
445
446 if !methods.is_empty() {
447 let mut suggestions = methods
448 .iter()
449 .filter_map(|conversion_method| {
450 let conversion_method_name = conversion_method.name();
451 let receiver_method_ident = expr.method_ident();
452 if let Some(method_ident) = receiver_method_ident
453 && method_ident.name == conversion_method_name
454 {
455 return None; }
457
458 let method_call_list = [sym::to_vec, sym::to_string];
459 let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
460 && receiver_method.ident.name == sym::clone
461 && method_call_list.contains(&conversion_method_name)
462 {
467 ::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())]
468 } else if self.precedence(expr) < ExprPrecedence::Unambiguous {
469 ::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![
470 (expr.span.shrink_to_lo(), "(".to_string()),
471 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method_name)),
472 ]
473 } else {
474 ::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))]
475 };
476 let struct_pat_shorthand_field =
477 self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr);
478 if let Some(name) = struct_pat_shorthand_field {
479 sugg.insert(0, (expr.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", name))
})format!("{name}: ")));
480 }
481 Some(sugg)
482 })
483 .peekable();
484 if suggestions.peek().is_some() {
485 err.multipart_suggestions(
486 "try using a conversion method",
487 suggestions,
488 Applicability::MaybeIncorrect,
489 );
490 return true;
491 }
492 }
493
494 if let Some((found_ty_inner, expected_ty_inner, error_tys)) =
495 self.deconstruct_option_or_result(found, expected)
496 && let ty::Ref(_, peeled, hir::Mutability::Not) = *expected_ty_inner.kind()
497 {
498 let inner_expr = expr.peel_borrows();
500 if !inner_expr.span.eq_ctxt(expr.span) {
501 return false;
502 }
503 let borrow_removal_span = if inner_expr.hir_id == expr.hir_id {
504 None
505 } else {
506 Some(expr.span.shrink_to_lo().until(inner_expr.span))
507 };
508 let error_tys_equate_as_ref = error_tys.is_none_or(|(found, expected)| {
511 self.can_eq(
512 self.param_env,
513 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, found),
514 expected,
515 )
516 });
517
518 let prefix_wrap = |sugg: &str| {
519 if let Some(name) = self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
520 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}{1}", name, sugg))
})format!(": {}{}", name, sugg)
521 } else {
522 sugg.to_string()
523 }
524 };
525
526 if self.can_eq(self.param_env, found_ty_inner, peeled) && error_tys_equate_as_ref {
529 let sugg = prefix_wrap(".as_ref()");
530 err.subdiagnostic(errors::SuggestConvertViaMethod {
531 span: expr.span.shrink_to_hi(),
532 sugg,
533 expected,
534 found,
535 borrow_removal_span,
536 });
537 return true;
538 } else if let ty::Ref(_, peeled_found_ty, _) = found_ty_inner.kind()
539 && let ty::Adt(adt, _) = peeled_found_ty.peel_refs().kind()
540 && self.tcx.is_lang_item(adt.did(), LangItem::String)
541 && peeled.is_str()
542 && error_tys.is_none_or(|(found, expected)| {
544 self.can_eq(self.param_env, found, expected)
545 })
546 {
547 let sugg = prefix_wrap(".map(|x| x.as_str())");
548 err.span_suggestion_verbose(
549 expr.span.shrink_to_hi(),
550 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`"),
551 sugg,
552 Applicability::MachineApplicable,
553 );
554 return true;
555 } else {
556 if !error_tys_equate_as_ref {
557 return false;
558 }
559 let mut steps = self.autoderef(expr.span, found_ty_inner).silence_errors();
560 if let Some((deref_ty, _)) = steps.nth(1)
561 && self.can_eq(self.param_env, deref_ty, peeled)
562 {
563 let sugg = prefix_wrap(".as_deref()");
564 err.subdiagnostic(errors::SuggestConvertViaMethod {
565 span: expr.span.shrink_to_hi(),
566 sugg,
567 expected,
568 found,
569 borrow_removal_span,
570 });
571 return true;
572 }
573 for (deref_ty, n_step) in steps {
574 if self.can_eq(self.param_env, deref_ty, peeled) {
575 let explicit_deref = "*".repeat(n_step);
576 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)"));
577 err.subdiagnostic(errors::SuggestConvertViaMethod {
578 span: expr.span.shrink_to_hi(),
579 sugg,
580 expected,
581 found,
582 borrow_removal_span,
583 });
584 return true;
585 }
586 }
587 }
588 }
589
590 false
591 }
592
593 fn deconstruct_option_or_result(
597 &self,
598 found_ty: Ty<'tcx>,
599 expected_ty: Ty<'tcx>,
600 ) -> Option<(Ty<'tcx>, Ty<'tcx>, Option<(Ty<'tcx>, Ty<'tcx>)>)> {
601 let ty::Adt(found_adt, found_args) = found_ty.peel_refs().kind() else {
602 return None;
603 };
604 let ty::Adt(expected_adt, expected_args) = expected_ty.kind() else {
605 return None;
606 };
607 if self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
608 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
609 {
610 Some((found_args.type_at(0), expected_args.type_at(0), None))
611 } else if self.tcx.is_diagnostic_item(sym::Result, found_adt.did())
612 && self.tcx.is_diagnostic_item(sym::Result, expected_adt.did())
613 {
614 Some((
615 found_args.type_at(0),
616 expected_args.type_at(0),
617 Some((found_args.type_at(1), expected_args.type_at(1))),
618 ))
619 } else {
620 None
621 }
622 }
623
624 pub(in super::super) fn suggest_boxing_when_appropriate(
627 &self,
628 err: &mut Diag<'_>,
629 span: Span,
630 hir_id: HirId,
631 expected: Ty<'tcx>,
632 found: Ty<'tcx>,
633 ) -> bool {
634 if self.tcx.hir_is_inside_const_context(hir_id) || !expected.is_box() || found.is_box() {
636 return false;
637 }
638 if self.may_coerce(Ty::new_box(self.tcx, found), expected) {
639 let suggest_boxing = match *found.kind() {
640 ty::Tuple(tuple) if tuple.is_empty() => {
641 errors::SuggestBoxing::Unit { start: span.shrink_to_lo(), end: span }
642 }
643 ty::Coroutine(def_id, ..)
644 if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.coroutine_kind(def_id)
{
Some(CoroutineKind::Desugared(CoroutineDesugaring::Async,
CoroutineSource::Closure)) => true,
_ => false,
}matches!(
645 self.tcx.coroutine_kind(def_id),
646 Some(CoroutineKind::Desugared(
647 CoroutineDesugaring::Async,
648 CoroutineSource::Closure
649 ))
650 ) =>
651 {
652 errors::SuggestBoxing::AsyncBody
653 }
654 _ if let Node::ExprField(expr_field) = self.tcx.parent_hir_node(hir_id)
655 && expr_field.is_shorthand =>
656 {
657 errors::SuggestBoxing::ExprFieldShorthand {
658 start: span.shrink_to_lo(),
659 end: span.shrink_to_hi(),
660 ident: expr_field.ident,
661 }
662 }
663 _ => errors::SuggestBoxing::Other {
664 start: span.shrink_to_lo(),
665 end: span.shrink_to_hi(),
666 },
667 };
668 err.subdiagnostic(suggest_boxing);
669
670 true
671 } else {
672 false
673 }
674 }
675
676 pub(in super::super) fn suggest_no_capture_closure(
679 &self,
680 err: &mut Diag<'_>,
681 expected: Ty<'tcx>,
682 found: Ty<'tcx>,
683 ) -> bool {
684 if let (ty::FnPtr(..), ty::Closure(def_id, _)) = (expected.kind(), found.kind())
685 && let Some(upvars) = self.tcx.upvars_mentioned(*def_id)
686 {
687 let spans_and_labels = upvars
690 .iter()
691 .take(4)
692 .map(|(var_hir_id, upvar)| {
693 let var_name = self.tcx.hir_name(*var_hir_id).to_string();
694 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` captured here", var_name))
})format!("`{var_name}` captured here");
695 (upvar.span, msg)
696 })
697 .collect::<Vec<_>>();
698
699 let mut multi_span: MultiSpan =
700 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
701 for (sp, label) in spans_and_labels {
702 multi_span.push_span_label(sp, label);
703 }
704 err.span_note(
705 multi_span,
706 "closures can only be coerced to `fn` types if they do not capture any variables",
707 );
708 return true;
709 }
710 false
711 }
712
713 #[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(714u32),
::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:743",
"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(743u32),
::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))]
715 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
716 &self,
717 err: &mut Diag<'_>,
718 expr: &hir::Expr<'_>,
719 expected: Ty<'tcx>,
720 found: Ty<'tcx>,
721 ) -> bool {
722 if self.tcx.hir_is_inside_const_context(expr.hir_id) {
725 return false;
727 }
728 let pin_did = self.tcx.lang_items().pin_type();
729 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
731 return false;
732 }
733 let box_found = Ty::new_box(self.tcx, found);
734 let Some(pin_box_found) = Ty::new_lang_item(self.tcx, box_found, LangItem::Pin) else {
735 return false;
736 };
737 let Some(pin_found) = Ty::new_lang_item(self.tcx, found, LangItem::Pin) else {
738 return false;
739 };
740 match expected.kind() {
741 ty::Adt(def, _) if Some(def.did()) == pin_did => {
742 if self.may_coerce(pin_box_found, expected) {
743 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
744 match found.kind() {
745 ty::Adt(def, _) if def.is_box() => {
746 err.help("use `Box::pin`");
747 }
748 _ => {
749 let prefix = if let Some(name) =
750 self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr)
751 {
752 format!("{}: ", name)
753 } else {
754 String::new()
755 };
756 let suggestion = vec![
757 (expr.span.shrink_to_lo(), format!("{prefix}Box::pin(")),
758 (expr.span.shrink_to_hi(), ")".to_string()),
759 ];
760 err.multipart_suggestion(
761 "you need to pin and box this expression",
762 suggestion,
763 Applicability::MaybeIncorrect,
764 );
765 }
766 }
767 true
768 } else if self.may_coerce(pin_found, expected) {
769 match found.kind() {
770 ty::Adt(def, _) if def.is_box() => {
771 err.help("use `Box::pin`");
772 true
773 }
774 _ => false,
775 }
776 } else {
777 false
778 }
779 }
780 ty::Adt(def, _) if def.is_box() && self.may_coerce(box_found, expected) => {
781 let Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. }) =
785 self.tcx.parent_hir_node(expr.hir_id)
786 else {
787 return false;
788 };
789 match fn_name.kind {
790 ExprKind::Path(QPath::TypeRelative(
791 hir::Ty {
792 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
793 ..
794 },
795 method,
796 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
797 err.span_suggestion(
798 fn_name.span,
799 "use `Box::pin` to pin and box this expression",
800 "Box::pin",
801 Applicability::MachineApplicable,
802 );
803 true
804 }
805 _ => false,
806 }
807 }
808 _ => false,
809 }
810 }
811
812 pub(crate) fn suggest_missing_semicolon(
828 &self,
829 err: &mut Diag<'_>,
830 expression: &'tcx hir::Expr<'tcx>,
831 expected: Ty<'tcx>,
832 needs_block: bool,
833 parent_is_closure: bool,
834 ) {
835 if !expected.is_unit() {
836 return;
837 }
838 match expression.kind {
841 ExprKind::Call(..)
842 | ExprKind::MethodCall(..)
843 | ExprKind::Loop(..)
844 | ExprKind::If(..)
845 | ExprKind::Match(..)
846 | ExprKind::Block(..)
847 if expression.can_have_side_effects()
848 && !expression.span.in_external_macro(self.tcx.sess.source_map()) =>
852 {
853 if needs_block {
854 err.multipart_suggestion(
855 "consider using a semicolon here",
856 ::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![
857 (expression.span.shrink_to_lo(), "{ ".to_owned()),
858 (expression.span.shrink_to_hi(), "; }".to_owned()),
859 ],
860 Applicability::MachineApplicable,
861 );
862 } else if let hir::Node::Block(block) = self.tcx.parent_hir_node(expression.hir_id)
863 && let hir::Node::Expr(expr) = self.tcx.parent_hir_node(block.hir_id)
864 && let hir::Node::Expr(if_expr) = self.tcx.parent_hir_node(expr.hir_id)
865 && let hir::ExprKind::If(_cond, _then, Some(_else)) = if_expr.kind
866 && let hir::Node::Stmt(stmt) = self.tcx.parent_hir_node(if_expr.hir_id)
867 && let hir::StmtKind::Expr(_) = stmt.kind
868 && self.is_next_stmt_expr_continuation(stmt.hir_id)
869 {
870 err.subdiagnostic(ExprParenthesesNeeded::surrounding(stmt.span));
871 } else {
872 err.span_suggestion(
873 expression.span.shrink_to_hi(),
874 "consider using a semicolon here",
875 ";",
876 Applicability::MachineApplicable,
877 );
878 }
879 }
880 ExprKind::Path(..) | ExprKind::Lit(_)
881 if parent_is_closure
882 && !expression.span.in_external_macro(self.tcx.sess.source_map()) =>
883 {
884 err.span_suggestion_verbose(
885 expression.span.shrink_to_lo(),
886 "consider ignoring the value",
887 "_ = ",
888 Applicability::MachineApplicable,
889 );
890 }
891 _ => {
892 if let hir::Node::Block(block) = self.tcx.parent_hir_node(expression.hir_id)
893 && let hir::Node::Expr(expr) = self.tcx.parent_hir_node(block.hir_id)
894 && let hir::Node::Expr(if_expr) = self.tcx.parent_hir_node(expr.hir_id)
895 && let hir::ExprKind::If(_cond, _then, Some(_else)) = if_expr.kind
896 && let hir::Node::Stmt(stmt) = self.tcx.parent_hir_node(if_expr.hir_id)
897 && let hir::StmtKind::Expr(_) = stmt.kind
898 && self.is_next_stmt_expr_continuation(stmt.hir_id)
899 {
900 err.subdiagnostic(ExprParenthesesNeeded::surrounding(stmt.span));
908 }
909 }
910 }
911 }
912
913 pub(crate) fn is_next_stmt_expr_continuation(&self, hir_id: HirId) -> bool {
914 if let hir::Node::Block(b) = self.tcx.parent_hir_node(hir_id)
915 && let mut stmts = b.stmts.iter().skip_while(|s| s.hir_id != hir_id)
916 && let Some(_) = stmts.next() && let Some(next) = match (stmts.next(), b.expr) { (Some(next), _) => match next.kind {
919 hir::StmtKind::Expr(next) | hir::StmtKind::Semi(next) => Some(next),
920 _ => None,
921 },
922 (None, Some(next)) => Some(next),
923 _ => None,
924 }
925 && let hir::ExprKind::AddrOf(..) | hir::ExprKind::Unary(..) | hir::ExprKind::Err(_) = next.kind
928 {
930 true
931 } else {
932 false
933 }
934 }
935
936 #[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(948u32),
::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:1069",
"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(1069u32),
::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:1087",
"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(1087u32),
::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:1089",
"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(1089u32),
::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:1090",
"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(1090u32),
::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))]
949 pub(in super::super) fn suggest_missing_return_type(
950 &self,
951 err: &mut Diag<'_>,
952 fn_decl: &hir::FnDecl<'tcx>,
953 expected: Ty<'tcx>,
954 found: Ty<'tcx>,
955 fn_id: LocalDefId,
956 ) -> bool {
957 if let Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Block)) =
959 self.tcx.coroutine_kind(fn_id)
960 {
961 return false;
962 }
963
964 let found =
965 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
966 match &fn_decl.output {
969 &hir::FnRetTy::DefaultReturn(_) if self.tcx.is_closure_like(fn_id.to_def_id()) => {}
971 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
972 if !self.can_add_return_type(fn_id) {
973 err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit { span });
974 } else if let Some(found) = found.make_suggestable(self.tcx, false, None) {
975 err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
976 span,
977 found: found.to_string(),
978 });
979 } else if let Some(sugg) = suggest_impl_trait(self, self.param_env, found) {
980 err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { span, found: sugg });
981 } else {
982 err.subdiagnostic(errors::AddReturnTypeSuggestion::MissingHere { span });
984 }
985
986 return true;
987 }
988 hir::FnRetTy::Return(hir_ty) => {
989 if let hir::TyKind::OpaqueDef(op_ty, ..) = hir_ty.kind
990 && let [hir::GenericBound::Trait(trait_ref)] = op_ty.bounds
991 && !trait_ref
992 .trait_ref
993 .path
994 .segments
995 .last()
996 .and_then(|seg| seg.args)
997 .map_or(false, |args| !args.constraints.is_empty())
998 {
999 let trait_name = trait_ref
1001 .trait_ref
1002 .path
1003 .segments
1004 .iter()
1005 .map(|seg| seg.ident.as_str())
1006 .collect::<Vec<_>>()
1007 .join("::");
1008
1009 err.subdiagnostic(errors::ExpectedReturnTypeLabel::ImplTrait {
1010 span: hir_ty.span,
1011 trait_name,
1012 });
1013
1014 if let Some(ret_coercion_span) = self.ret_coercion_span.get() {
1015 let expected_name = expected.to_string();
1016 err.span_label(
1017 ret_coercion_span,
1018 format!("return type resolved to be `{expected_name}`"),
1019 );
1020 }
1021
1022 let trait_def_id = trait_ref.trait_ref.path.res.def_id();
1023 if self.tcx.is_dyn_compatible(trait_def_id) {
1024 err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1025 start_sp: hir_ty.span.with_hi(hir_ty.span.lo() + BytePos(4)),
1026 end_sp: hir_ty.span.shrink_to_hi(),
1027 });
1028
1029 let body = self.tcx.hir_body_owned_by(fn_id);
1030 let mut visitor = ReturnsVisitor::default();
1031 visitor.visit_body(&body);
1032
1033 if !visitor.returns.is_empty() {
1034 let starts: Vec<Span> = visitor
1035 .returns
1036 .iter()
1037 .filter(|expr| expr.span.can_be_used_for_suggestions())
1038 .map(|expr| expr.span.shrink_to_lo())
1039 .collect();
1040 let ends: Vec<Span> = visitor
1041 .returns
1042 .iter()
1043 .filter(|expr| expr.span.can_be_used_for_suggestions())
1044 .map(|expr| expr.span.shrink_to_hi())
1045 .collect();
1046
1047 if !starts.is_empty() {
1048 err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr {
1049 starts,
1050 ends,
1051 });
1052 }
1053 }
1054 }
1055
1056 self.try_suggest_return_impl_trait(err, expected, found, fn_id);
1057 self.try_note_caller_chooses_ty_for_ty_param(err, expected, found);
1058 return true;
1059 } else if let hir::TyKind::OpaqueDef(op_ty, ..) = hir_ty.kind
1060 && let [hir::GenericBound::Trait(trait_ref)] = op_ty.bounds
1062 && let Some(hir::PathSegment { args: Some(generic_args), .. }) =
1063 trait_ref.trait_ref.path.segments.last()
1064 && let [constraint] = generic_args.constraints
1065 && let Some(ty) = constraint.ty()
1066 {
1067 debug!(?found);
1070 if found.is_suggestable(self.tcx, false) {
1071 if ty.span.is_empty() {
1072 err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
1073 span: ty.span,
1074 found: found.to_string(),
1075 });
1076 return true;
1077 } else {
1078 err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
1079 span: ty.span,
1080 expected,
1081 });
1082 }
1083 }
1084 } else {
1085 debug!(?hir_ty, "return type");
1088 let ty = self.lowerer().lower_ty(hir_ty);
1089 debug!(?ty, "return type (lowered)");
1090 debug!(?expected, "expected type");
1091 let bound_vars =
1092 self.tcx.late_bound_vars(self.tcx.local_def_id_to_hir_id(fn_id));
1093 let ty = Binder::bind_with_vars(ty, bound_vars);
1094 let ty = self.normalize(hir_ty.span, Unnormalized::new_wip(ty));
1095 let ty = self.tcx.instantiate_bound_regions_with_erased(ty);
1096 if self.may_coerce(expected, ty) {
1097 err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
1098 span: hir_ty.span,
1099 expected,
1100 });
1101 self.try_suggest_return_impl_trait(err, expected, found, fn_id);
1102 self.try_note_caller_chooses_ty_for_ty_param(err, expected, found);
1103 return true;
1104 }
1105 }
1106 }
1107 _ => {}
1108 }
1109 false
1110 }
1111
1112 fn can_add_return_type(&self, fn_id: LocalDefId) -> bool {
1115 match self.tcx.hir_node_by_def_id(fn_id) {
1116 Node::Item(item) => {
1117 let (ident, _, _, _) = item.expect_fn();
1118 ident.name != sym::main
1122 }
1123 Node::ImplItem(item) => {
1124 let Node::Item(&hir::Item {
1126 kind: hir::ItemKind::Impl(hir::Impl { of_trait, .. }),
1127 ..
1128 }) = self.tcx.parent_hir_node(item.hir_id())
1129 else {
1130 ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1131 };
1132
1133 of_trait.is_none()
1134 }
1135 _ => true,
1136 }
1137 }
1138
1139 fn try_note_caller_chooses_ty_for_ty_param(
1140 &self,
1141 diag: &mut Diag<'_>,
1142 expected: Ty<'tcx>,
1143 found: Ty<'tcx>,
1144 ) {
1145 let ty::Param(expected_ty_as_param) = expected.kind() else {
1152 return;
1153 };
1154
1155 if found.contains(expected) {
1156 return;
1157 }
1158
1159 diag.subdiagnostic(errors::NoteCallerChoosesTyForTyParam {
1160 ty_param_name: expected_ty_as_param.name,
1161 found_ty: found,
1162 });
1163 }
1164
1165 fn try_suggest_return_impl_trait(
1174 &self,
1175 err: &mut Diag<'_>,
1176 expected: Ty<'tcx>,
1177 found: Ty<'tcx>,
1178 fn_id: LocalDefId,
1179 ) {
1180 {
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:1188",
"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(1188u32),
::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);
1189
1190 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
1191
1192 let fn_node = self.tcx.hir_node_by_def_id(fn_id);
1193
1194 let hir::Node::Item(hir::Item {
1195 kind:
1196 hir::ItemKind::Fn {
1197 sig:
1198 hir::FnSig {
1199 decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. },
1200 ..
1201 },
1202 generics: hir::Generics { params, predicates, .. },
1203 ..
1204 },
1205 ..
1206 }) = fn_node
1207 else {
1208 return;
1209 };
1210
1211 if params.get(expected_ty_as_param.index as usize).is_none() {
1212 return;
1213 };
1214
1215 let where_predicates = predicates
1217 .iter()
1218 .filter_map(|p| match p.kind {
1219 WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1220 bounds,
1221 bounded_ty,
1222 ..
1223 }) => {
1224 let ty = self.lowerer().lower_ty(bounded_ty);
1226 Some((ty, bounds))
1227 }
1228 _ => None,
1229 })
1230 .map(|(ty, bounds)| match ty.kind() {
1231 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
1232 _ => match ty.contains(expected) {
1234 true => Err(()),
1235 false => Ok(None),
1236 },
1237 })
1238 .collect::<Result<Vec<_>, _>>();
1239
1240 let Ok(where_predicates) = where_predicates else { return };
1241
1242 let predicates_from_where =
1244 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
1245
1246 let all_matching_bounds_strs = predicates_from_where
1248 .filter_map(|bound| match bound {
1249 GenericBound::Trait(_) => {
1250 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
1251 }
1252 _ => None,
1253 })
1254 .collect::<Vec<String>>();
1255
1256 if all_matching_bounds_strs.is_empty() {
1257 return;
1258 }
1259
1260 let all_bounds_str = all_matching_bounds_strs.join(" + ");
1261
1262 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
1263 let ty = self.lowerer().lower_ty( param);
1264 #[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)
1265 });
1266
1267 if ty_param_used_in_fn_params {
1268 return;
1269 }
1270
1271 err.span_suggestion(
1272 fn_return.span(),
1273 "consider using an impl return type",
1274 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("impl {0}", all_bounds_str))
})format!("impl {all_bounds_str}"),
1275 Applicability::MaybeIncorrect,
1276 );
1277 }
1278
1279 pub(in super::super) fn suggest_missing_break_or_return_expr(
1280 &self,
1281 err: &mut Diag<'_>,
1282 expr: &'tcx hir::Expr<'tcx>,
1283 fn_decl: &hir::FnDecl<'tcx>,
1284 expected: Ty<'tcx>,
1285 found: Ty<'tcx>,
1286 id: HirId,
1287 fn_id: LocalDefId,
1288 ) {
1289 if !expected.is_unit() {
1290 return;
1291 }
1292 let found = self.resolve_vars_if_possible(found);
1293
1294 let innermost_loop = if self.is_loop(id) {
1295 Some(self.tcx.hir_node(id))
1296 } else {
1297 self.tcx
1298 .hir_parent_iter(id)
1299 .take_while(|(_, node)| {
1300 node.body_id().is_none()
1302 })
1303 .find_map(|(parent_id, node)| self.is_loop(parent_id).then_some(node))
1304 };
1305 let can_break_with_value = innermost_loop.is_some_and(|node| {
1306 #[allow(non_exhaustive_omitted_patterns)] match node {
Node::Expr(Expr { kind: ExprKind::Loop(_, _, LoopSource::Loop, ..), .. })
=> true,
_ => false,
}matches!(
1307 node,
1308 Node::Expr(Expr { kind: ExprKind::Loop(_, _, LoopSource::Loop, ..), .. })
1309 )
1310 });
1311
1312 let in_local_statement = self.is_local_statement(id)
1313 || self
1314 .tcx
1315 .hir_parent_iter(id)
1316 .any(|(parent_id, _)| self.is_local_statement(parent_id));
1317
1318 if can_break_with_value && in_local_statement {
1319 err.multipart_suggestion(
1320 "you might have meant to break the loop with this value",
1321 ::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![
1322 (expr.span.shrink_to_lo(), "break ".to_string()),
1323 (expr.span.shrink_to_hi(), ";".to_string()),
1324 ],
1325 Applicability::MaybeIncorrect,
1326 );
1327 return;
1328 }
1329
1330 let scope = self.tcx.hir_parent_iter(id).find(|(_, node)| {
1331 #[allow(non_exhaustive_omitted_patterns)] match node {
Node::Expr(Expr { kind: ExprKind::Closure(..), .. }) | Node::Item(_) |
Node::TraitItem(_) | Node::ImplItem(_) => true,
_ => false,
}matches!(
1332 node,
1333 Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
1334 | Node::Item(_)
1335 | Node::TraitItem(_)
1336 | Node::ImplItem(_)
1337 )
1338 });
1339 let in_closure =
1340 #[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(..), .. }))));
1341
1342 let can_return = match fn_decl.output {
1343 hir::FnRetTy::Return(ty) => {
1344 let ty = self.lowerer().lower_ty(ty);
1345 let bound_vars = self.tcx.late_bound_vars(self.tcx.local_def_id_to_hir_id(fn_id));
1346 let ty = self
1347 .tcx
1348 .instantiate_bound_regions_with_erased(Binder::bind_with_vars(ty, bound_vars));
1349 let ty = match self.tcx.asyncness(fn_id) {
1350 ty::Asyncness::Yes => {
1351 self.err_ctxt().get_impl_future_output_ty(ty).unwrap_or_else(|| {
1352 ::rustc_middle::util::bug::span_bug_fmt(fn_decl.output.span(),
format_args!("failed to get output type of async function"))span_bug!(
1353 fn_decl.output.span(),
1354 "failed to get output type of async function"
1355 )
1356 })
1357 }
1358 ty::Asyncness::No => ty,
1359 };
1360 let ty = self.normalize(expr.span, Unnormalized::new_wip(ty));
1361 self.may_coerce(found, ty)
1362 }
1363 hir::FnRetTy::DefaultReturn(_) if in_closure => {
1364 self.ret_coercion.as_ref().is_some_and(|ret| {
1365 let ret_ty = ret.borrow().expected_ty();
1366 self.may_coerce(found, ret_ty)
1367 })
1368 }
1369 _ => false,
1370 };
1371 if can_return
1372 && let Some(span) = expr.span.find_ancestor_inside(
1373 self.tcx.hir_span_with_body(self.tcx.local_def_id_to_hir_id(fn_id)),
1374 )
1375 {
1376 fn is_in_arm<'tcx>(expr: &'tcx hir::Expr<'tcx>, tcx: TyCtxt<'tcx>) -> bool {
1387 for (_, node) in tcx.hir_parent_iter(expr.hir_id) {
1388 match node {
1389 hir::Node::Block(block) => {
1390 if let Some(ret) = block.expr
1391 && ret.hir_id == expr.hir_id
1392 {
1393 continue;
1394 }
1395 }
1396 hir::Node::Arm(arm) => {
1397 if let hir::ExprKind::Block(block, _) = arm.body.kind
1398 && let Some(ret) = block.expr
1399 && ret.hir_id == expr.hir_id
1400 {
1401 return true;
1402 }
1403 }
1404 hir::Node::Expr(e) if let hir::ExprKind::Block(block, _) = e.kind => {
1405 if let Some(ret) = block.expr
1406 && ret.hir_id == expr.hir_id
1407 {
1408 continue;
1409 }
1410 }
1411 _ => {
1412 return false;
1413 }
1414 }
1415 }
1416
1417 false
1418 }
1419 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())];
1420 if !is_in_arm(expr, self.tcx) {
1421 suggs.push((span.shrink_to_hi(), ";".to_string()));
1422 }
1423 err.multipart_suggestion(
1424 "you might have meant to return this value",
1425 suggs,
1426 Applicability::MaybeIncorrect,
1427 );
1428 }
1429 }
1430
1431 pub(in super::super) fn suggest_missing_parentheses(
1432 &self,
1433 err: &mut Diag<'_>,
1434 expr: &hir::Expr<'_>,
1435 ) -> bool {
1436 let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
1437 if let Some(sp) = self.tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
1438 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
1440 true
1441 } else {
1442 false
1443 }
1444 }
1445
1446 pub(crate) fn suggest_block_to_brackets_peeling_refs(
1450 &self,
1451 diag: &mut Diag<'_>,
1452 mut expr: &hir::Expr<'_>,
1453 mut expr_ty: Ty<'tcx>,
1454 mut expected_ty: Ty<'tcx>,
1455 ) -> bool {
1456 loop {
1457 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
1458 (
1459 hir::ExprKind::AddrOf(_, _, inner_expr),
1460 ty::Ref(_, inner_expr_ty, _),
1461 ty::Ref(_, inner_expected_ty, _),
1462 ) => {
1463 expr = *inner_expr;
1464 expr_ty = *inner_expr_ty;
1465 expected_ty = *inner_expected_ty;
1466 }
1467 (hir::ExprKind::Block(blk, _), _, _) => {
1468 self.suggest_block_to_brackets(diag, blk, expr_ty, expected_ty);
1469 break true;
1470 }
1471 _ => break false,
1472 }
1473 }
1474 }
1475
1476 pub(crate) fn suggest_clone_for_ref(
1477 &self,
1478 diag: &mut Diag<'_>,
1479 expr: &hir::Expr<'_>,
1480 expr_ty: Ty<'tcx>,
1481 expected_ty: Ty<'tcx>,
1482 ) -> bool {
1483 if let ty::Ref(_, inner_ty, hir::Mutability::Not) = expr_ty.kind()
1484 && let Some(clone_trait_def) = self.tcx.lang_items().clone_trait()
1485 && expected_ty == *inner_ty
1486 && self
1487 .infcx
1488 .type_implements_trait(
1489 clone_trait_def,
1490 [self.tcx.erase_and_anonymize_regions(expected_ty)],
1491 self.param_env,
1492 )
1493 .must_apply_modulo_regions()
1494 {
1495 let suggestion = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1496 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}.clone()", ident))
})format!(": {ident}.clone()"),
1497 None => ".clone()".to_string(),
1498 };
1499
1500 let span = expr.span.find_ancestor_not_from_macro().unwrap_or(expr.span).shrink_to_hi();
1501
1502 diag.span_suggestion_verbose(
1503 span,
1504 "consider using clone here",
1505 suggestion,
1506 Applicability::MachineApplicable,
1507 );
1508 return true;
1509 }
1510 false
1511 }
1512
1513 pub(crate) fn suggest_copied_cloned_or_as_ref(
1514 &self,
1515 diag: &mut Diag<'_>,
1516 expr: &hir::Expr<'_>,
1517 expr_ty: Ty<'tcx>,
1518 expected_ty: Ty<'tcx>,
1519 ) -> bool {
1520 let ty::Adt(adt_def, args) = expr_ty.kind() else {
1521 return false;
1522 };
1523 let ty::Adt(expected_adt_def, expected_args) = expected_ty.kind() else {
1524 return false;
1525 };
1526 if adt_def != expected_adt_def {
1527 return false;
1528 }
1529
1530 if Some(adt_def.did()) == self.tcx.get_diagnostic_item(sym::Result)
1531 && self.can_eq(self.param_env, args.type_at(1), expected_args.type_at(1))
1532 || Some(adt_def.did()) == self.tcx.get_diagnostic_item(sym::Option)
1533 {
1534 let expr_inner_ty = args.type_at(0);
1535 let expected_inner_ty = expected_args.type_at(0);
1536 if let &ty::Ref(_, ty, _mutability) = expr_inner_ty.kind()
1537 && self.can_eq(self.param_env, ty, expected_inner_ty)
1538 {
1539 let def_path = self.tcx.def_path_str(adt_def.did());
1540 let span = expr.span.shrink_to_hi();
1541 let subdiag = if self.type_is_copy_modulo_regions(self.param_env, ty) {
1542 errors::OptionResultRefMismatch::Copied { span, def_path }
1543 } else if self.type_is_clone_modulo_regions(self.param_env, ty) {
1544 errors::OptionResultRefMismatch::Cloned { span, def_path }
1545 } else {
1546 return false;
1547 };
1548 diag.subdiagnostic(subdiag);
1549 return true;
1550 }
1551 }
1552
1553 false
1554 }
1555
1556 pub(crate) fn suggest_into(
1557 &self,
1558 diag: &mut Diag<'_>,
1559 expr: &hir::Expr<'_>,
1560 expr_ty: Ty<'tcx>,
1561 expected_ty: Ty<'tcx>,
1562 ) -> bool {
1563 let expr = expr.peel_blocks();
1564
1565 if expr_ty.is_scalar() && expected_ty.is_scalar() {
1567 return false;
1568 }
1569
1570 if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
hir::ExprKind::Block(..) => true,
_ => false,
}matches!(expr.kind, hir::ExprKind::Block(..)) {
1572 return false;
1573 }
1574
1575 if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1578 return false;
1579 }
1580
1581 if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1582 && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1583 self.tcx,
1584 self.misc(expr.span),
1585 self.param_env,
1586 ty::TraitRef::new(self.tcx, into_def_id, [expr_ty, expected_ty]),
1587 ))
1588 && !expr
1589 .span
1590 .macro_backtrace()
1591 .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, ..)))
1592 {
1593 let span = expr
1594 .span
1595 .find_ancestor_not_from_extern_macro(self.tcx.sess.source_map())
1596 .unwrap_or(expr.span);
1597
1598 let mut sugg = if self.precedence(expr) >= ExprPrecedence::Unambiguous {
1599 ::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())]
1600 } else {
1601 ::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![
1602 (span.shrink_to_lo(), "(".to_owned()),
1603 (span.shrink_to_hi(), ").into()".to_owned()),
1604 ]
1605 };
1606 if let Some(name) = self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1607 sugg.insert(0, (expr.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", name))
})format!("{}: ", name)));
1608 }
1609 diag.multipart_suggestion(
1610 ::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}`"),
1611 sugg,
1612 Applicability::MaybeIncorrect
1613 );
1614 return true;
1615 }
1616
1617 false
1618 }
1619
1620 pub(crate) fn suggest_option_to_bool(
1622 &self,
1623 diag: &mut Diag<'_>,
1624 expr: &hir::Expr<'_>,
1625 expr_ty: Ty<'tcx>,
1626 expected_ty: Ty<'tcx>,
1627 ) -> bool {
1628 if !expected_ty.is_bool() {
1629 return false;
1630 }
1631
1632 let ty::Adt(def, _) = expr_ty.peel_refs().kind() else {
1633 return false;
1634 };
1635 if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1636 return false;
1637 }
1638
1639 let cond_parent = self.tcx.hir_parent_iter(expr.hir_id).find(|(_, node)| {
1640 !#[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)
1641 });
1642 if let Some((_, hir::Node::LetStmt(local))) = cond_parent
1648 && let hir::PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), .. })
1649 | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1650 && let hir::QPath::Resolved(None, path) = qpath
1651 && let Some(did) = path
1652 .res
1653 .opt_def_id()
1654 .and_then(|did| self.tcx.opt_parent(did))
1655 .and_then(|did| self.tcx.opt_parent(did))
1656 && self.tcx.is_diagnostic_item(sym::Option, did)
1657 {
1658 return false;
1659 }
1660
1661 let suggestion = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
1662 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}.is_some()", ident))
})format!(": {ident}.is_some()"),
1663 None => ".is_some()".to_string(),
1664 };
1665
1666 diag.span_suggestion_verbose(
1667 expr.span.shrink_to_hi(),
1668 "use `Option::is_some` to test if the `Option` has a value",
1669 suggestion,
1670 Applicability::MachineApplicable,
1671 );
1672 true
1673 }
1674
1675 #[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(1676u32),
::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))]
1677 pub(crate) fn suggest_deref_unwrap_or(
1678 &self,
1679 err: &mut Diag<'_>,
1680 callee_ty: Option<Ty<'tcx>>,
1681 call_ident: Option<Ident>,
1682 expected_ty: Ty<'tcx>,
1683 provided_ty: Ty<'tcx>,
1684 provided_expr: &Expr<'tcx>,
1685 is_method: bool,
1686 ) {
1687 if !is_method {
1688 return;
1689 }
1690 let Some(callee_ty) = callee_ty else {
1691 return;
1692 };
1693 let ty::Adt(callee_adt, _) = callee_ty.peel_refs().kind() else {
1694 return;
1695 };
1696 let adt_name = if self.tcx.is_diagnostic_item(sym::Option, callee_adt.did()) {
1697 "Option"
1698 } else if self.tcx.is_diagnostic_item(sym::Result, callee_adt.did()) {
1699 "Result"
1700 } else {
1701 return;
1702 };
1703
1704 let Some(call_ident) = call_ident else {
1705 return;
1706 };
1707 if call_ident.name != sym::unwrap_or {
1708 return;
1709 }
1710
1711 let ty::Ref(_, peeled, _mutability) = provided_ty.kind() else {
1712 return;
1713 };
1714
1715 let dummy_ty = if let ty::Array(elem_ty, size) = peeled.kind()
1719 && let ty::Infer(_) = elem_ty.kind()
1720 && self
1721 .try_structurally_resolve_const(provided_expr.span, *size)
1722 .try_to_target_usize(self.tcx)
1723 == Some(0)
1724 {
1725 let slice = Ty::new_slice(self.tcx, *elem_ty);
1726 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, slice)
1727 } else {
1728 provided_ty
1729 };
1730
1731 if !self.may_coerce(expected_ty, dummy_ty) {
1732 return;
1733 }
1734 let msg = format!("use `{adt_name}::map_or` to deref inner value of `{adt_name}`");
1735 err.multipart_suggestion(
1736 msg,
1737 vec![
1738 (call_ident.span, "map_or".to_owned()),
1739 (provided_expr.span.shrink_to_hi(), ", |v| v".to_owned()),
1740 ],
1741 Applicability::MachineApplicable,
1742 );
1743 }
1744
1745 pub(crate) fn suggest_block_to_brackets(
1748 &self,
1749 diag: &mut Diag<'_>,
1750 blk: &hir::Block<'_>,
1751 blk_ty: Ty<'tcx>,
1752 expected_ty: Ty<'tcx>,
1753 ) {
1754 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1755 if self.may_coerce(blk_ty, *elem_ty)
1756 && blk.stmts.is_empty()
1757 && blk.rules == hir::BlockCheckMode::DefaultBlock
1758 && let source_map = self.tcx.sess.source_map()
1759 && let Ok(snippet) = source_map.span_to_snippet(blk.span)
1760 && snippet.starts_with('{')
1761 && snippet.ends_with('}')
1762 {
1763 diag.multipart_suggestion(
1764 "to create an array, use square brackets instead of curly braces",
1765 ::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![
1766 (
1767 blk.span
1768 .shrink_to_lo()
1769 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1770 "[".to_string(),
1771 ),
1772 (
1773 blk.span
1774 .shrink_to_hi()
1775 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1776 "]".to_string(),
1777 ),
1778 ],
1779 Applicability::MachineApplicable,
1780 );
1781 }
1782 }
1783 }
1784
1785 #[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(1785u32),
::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))]
1786 pub(crate) fn suggest_floating_point_literal(
1787 &self,
1788 err: &mut Diag<'_>,
1789 expr: &hir::Expr<'_>,
1790 expected_ty: Ty<'tcx>,
1791 ) -> bool {
1792 if !expected_ty.is_floating_point() {
1793 return false;
1794 }
1795 match expr.kind {
1796 ExprKind::Struct(&qpath, [start, end], _)
1797 if is_range_literal(expr)
1798 && self.tcx.qpath_is_lang_item(qpath, LangItem::Range) =>
1799 {
1800 err.span_suggestion_verbose(
1801 start.expr.span.shrink_to_hi().with_hi(end.expr.span.lo()),
1802 "remove the unnecessary `.` operator for a floating point literal",
1803 '.',
1804 Applicability::MaybeIncorrect,
1805 );
1806 true
1807 }
1808 ExprKind::Struct(&qpath, [arg], _)
1809 if is_range_literal(expr)
1810 && let Some(qpath @ (LangItem::RangeFrom | LangItem::RangeTo)) =
1811 self.tcx.qpath_lang_item(qpath) =>
1812 {
1813 let range_span = expr.span.parent_callsite().unwrap();
1814 match qpath {
1815 LangItem::RangeFrom => {
1816 err.span_suggestion_verbose(
1817 range_span.with_lo(arg.expr.span.hi()),
1818 "remove the unnecessary `.` operator for a floating point literal",
1819 '.',
1820 Applicability::MaybeIncorrect,
1821 );
1822 }
1823 _ => {
1824 err.span_suggestion_verbose(
1825 range_span.until(arg.expr.span),
1826 "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1827 "0.",
1828 Applicability::MaybeIncorrect,
1829 );
1830 }
1831 }
1832 true
1833 }
1834 ExprKind::Lit(Spanned {
1835 node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed),
1836 span,
1837 }) => {
1838 let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1839 return false;
1840 };
1841 if !(snippet.starts_with("0x") || snippet.starts_with("0X")) {
1842 return false;
1843 }
1844 if snippet.len() <= 5 || !snippet.is_char_boundary(snippet.len() - 3) {
1845 return false;
1846 }
1847 let (_, suffix) = snippet.split_at(snippet.len() - 3);
1848 let value = match suffix {
1849 "f32" => (lit.get() - 0xf32) / (16 * 16 * 16),
1850 "f64" => (lit.get() - 0xf64) / (16 * 16 * 16),
1851 _ => return false,
1852 };
1853 err.span_suggestions(
1854 expr.span,
1855 "rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
1856 [format!("0x{value:X} as {suffix}"), format!("{value}_{suffix}")],
1857 Applicability::MaybeIncorrect,
1858 );
1859 true
1860 }
1861 _ => false,
1862 }
1863 }
1864
1865 #[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(1867u32),
::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))]
1868 pub(crate) fn suggest_null_ptr_for_literal_zero_given_to_ptr_arg(
1869 &self,
1870 err: &mut Diag<'_>,
1871 expr: &hir::Expr<'_>,
1872 expected_ty: Ty<'tcx>,
1873 ) -> bool {
1874 let ty::RawPtr(_, mutbl) = expected_ty.kind() else {
1876 return false;
1877 };
1878
1879 let ExprKind::Lit(Spanned { node: rustc_ast::LitKind::Int(Pu128(0), _), span }) = expr.kind
1881 else {
1882 return false;
1883 };
1884
1885 let null_sym = match mutbl {
1887 hir::Mutability::Not => sym::ptr_null,
1888 hir::Mutability::Mut => sym::ptr_null_mut,
1889 };
1890 let Some(null_did) = self.tcx.get_diagnostic_item(null_sym) else {
1891 return false;
1892 };
1893 let null_path_str = with_no_trimmed_paths!(self.tcx.def_path_str(null_did));
1894
1895 err.span_suggestion(
1897 span,
1898 format!("if you meant to create a null pointer, use `{null_path_str}()`"),
1899 null_path_str + "()",
1900 Applicability::MachineApplicable,
1901 );
1902
1903 true
1904 }
1905
1906 pub(crate) fn suggest_associated_const(
1907 &self,
1908 err: &mut Diag<'_>,
1909 expr: &hir::Expr<'tcx>,
1910 expected_ty: Ty<'tcx>,
1911 ) -> bool {
1912 let Some((DefKind::AssocFn, old_def_id)) =
1913 self.typeck_results.borrow().type_dependent_def(expr.hir_id)
1914 else {
1915 return false;
1916 };
1917 let old_item_name = self.tcx.item_name(old_def_id);
1918 let capitalized_name = Symbol::intern(&old_item_name.as_str().to_uppercase());
1919 if old_item_name == capitalized_name {
1920 return false;
1921 }
1922 let (item, segment) = match expr.kind {
1923 hir::ExprKind::Path(QPath::Resolved(
1924 Some(ty),
1925 hir::Path { segments: [segment], .. },
1926 ))
1927 | hir::ExprKind::Path(QPath::TypeRelative(ty, segment))
1928 if let Some(self_ty) = self.typeck_results.borrow().node_type_opt(ty.hir_id)
1929 && let Ok(pick) = self.probe_for_name(
1930 Mode::Path,
1931 Ident::new(capitalized_name, segment.ident.span),
1932 Some(expected_ty),
1933 IsSuggestion(true),
1934 self_ty,
1935 expr.hir_id,
1936 ProbeScope::TraitsInScope,
1937 ) =>
1938 {
1939 (pick.item, segment)
1940 }
1941 hir::ExprKind::Path(QPath::Resolved(
1942 None,
1943 hir::Path { segments: [.., segment], .. },
1944 )) => {
1945 if old_item_name != segment.ident.name {
1948 return false;
1949 }
1950 let Some(item) = self
1951 .tcx
1952 .associated_items(self.tcx.parent(old_def_id))
1953 .filter_by_name_unhygienic(capitalized_name)
1954 .next()
1955 else {
1956 return false;
1957 };
1958 (*item, segment)
1959 }
1960 _ => return false,
1961 };
1962 if item.def_id == old_def_id
1963 || !#[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 { .. })
1964 {
1965 return false;
1967 }
1968 let item_ty = self.tcx.type_of(item.def_id).instantiate_identity().skip_norm_wip();
1969 if item_ty.has_param() {
1971 return false;
1972 }
1973 if self.may_coerce(item_ty, expected_ty) {
1974 err.span_suggestion_verbose(
1975 segment.ident.span,
1976 ::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",),
1977 capitalized_name,
1978 Applicability::MachineApplicable,
1979 );
1980 true
1981 } else {
1982 false
1983 }
1984 }
1985
1986 fn is_loop(&self, id: HirId) -> bool {
1987 let node = self.tcx.hir_node(id);
1988 #[allow(non_exhaustive_omitted_patterns)] match node {
Node::Expr(Expr { kind: ExprKind::Loop(..), .. }) => true,
_ => false,
}matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1989 }
1990
1991 fn is_local_statement(&self, id: HirId) -> bool {
1992 let node = self.tcx.hir_node(id);
1993 #[allow(non_exhaustive_omitted_patterns)] match node {
Node::Stmt(Stmt { kind: StmtKind::Let(..), .. }) => true,
_ => false,
}matches!(node, Node::Stmt(Stmt { kind: StmtKind::Let(..), .. }))
1994 }
1995
1996 pub(crate) fn note_type_is_not_clone(
1999 &self,
2000 diag: &mut Diag<'_>,
2001 expected_ty: Ty<'tcx>,
2002 found_ty: Ty<'tcx>,
2003 expr: &hir::Expr<'_>,
2004 ) {
2005 let expr = self.note_type_is_not_clone_inner_expr(expr);
2008
2009 let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else {
2011 return;
2012 };
2013
2014 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else {
2015 return;
2016 };
2017 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
2018 let results = self.typeck_results.borrow();
2019 if segment.ident.name == sym::clone
2021 && results.type_dependent_def_id(expr.hir_id).is_some_and(|did| {
2022 let assoc_item = self.tcx.associated_item(did);
2023 assoc_item.container == ty::AssocContainer::Trait
2024 && assoc_item.container_id(self.tcx) == clone_trait_did
2025 })
2026 && !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(..)))
2029 && self.may_coerce(*pointee_ty, expected_ty)
2031 && let trait_ref = ty::TraitRef::new(self.tcx, clone_trait_did, [expected_ty])
2032 && !self.predicate_must_hold_considering_regions(&traits::Obligation::new(
2034 self.tcx,
2035 traits::ObligationCause::dummy(),
2036 self.param_env,
2037 trait_ref,
2038 ))
2039 {
2040 diag.span_note(
2041 callee_expr.span,
2042 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` does not implement `Clone`, so `{1}` was cloned instead",
expected_ty, found_ty))
})format!(
2043 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
2044 ),
2045 );
2046 let owner = self.tcx.hir_enclosing_body_owner(expr.hir_id);
2047 if let ty::Param(param) = expected_ty.kind()
2048 && let Some(generics) = self.tcx.hir_get_generics(owner)
2049 {
2050 suggest_constraining_type_params(
2051 self.tcx,
2052 generics,
2053 diag,
2054 ::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(),
2055 None,
2056 );
2057 } else {
2058 let mut suggest_derive = true;
2059 if let Some(errors) =
2060 self.type_implements_trait_shallow(clone_trait_did, expected_ty, self.param_env)
2061 {
2062 let manually_impl = "consider manually implementing `Clone` to avoid the \
2063 implicit type parameter bounds";
2064 match &errors[..] {
2065 [] => {}
2066 [error] => {
2067 let msg = "`Clone` is not implemented because a trait bound is not \
2068 satisfied";
2069 if let traits::ObligationCauseCode::ImplDerived(data) =
2070 error.obligation.cause.code()
2071 {
2072 let mut span: MultiSpan = data.span.into();
2073 if self.tcx.is_automatically_derived(data.impl_or_alias_def_id) {
2074 span.push_span_label(
2075 data.span,
2076 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("derive introduces an implicit `{0}` bound",
error.obligation.predicate))
})format!(
2077 "derive introduces an implicit `{}` bound",
2078 error.obligation.predicate
2079 ),
2080 );
2081 }
2082 diag.span_help(span, msg);
2083 if self.tcx.is_automatically_derived(data.impl_or_alias_def_id)
2084 && data.impl_or_alias_def_id.is_local()
2085 {
2086 diag.help(manually_impl);
2087 suggest_derive = false;
2088 }
2089 } else {
2090 diag.help(msg);
2091 }
2092 }
2093 _ => {
2094 let unsatisfied_bounds: Vec<_> = errors
2095 .iter()
2096 .filter_map(|error| match error.obligation.cause.code() {
2097 traits::ObligationCauseCode::ImplDerived(data) => {
2098 let pre = if self
2099 .tcx
2100 .is_automatically_derived(data.impl_or_alias_def_id)
2101 {
2102 "derive introduces an implicit "
2103 } else {
2104 ""
2105 };
2106 Some((
2107 data.span,
2108 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}unsatisfied trait bound `{0}`",
error.obligation.predicate, pre))
})format!(
2109 "{pre}unsatisfied trait bound `{}`",
2110 error.obligation.predicate
2111 ),
2112 ))
2113 }
2114 _ => None,
2115 })
2116 .collect();
2117 let msg = "`Clone` is not implemented because the some trait bounds \
2118 could not be satisfied";
2119 if errors.len() == unsatisfied_bounds.len() {
2120 let mut unsatisfied_bounds_spans: MultiSpan = unsatisfied_bounds
2121 .iter()
2122 .map(|(span, _)| *span)
2123 .collect::<Vec<Span>>()
2124 .into();
2125 for (span, label) in unsatisfied_bounds {
2126 unsatisfied_bounds_spans.push_span_label(span, label);
2127 }
2128 diag.span_help(unsatisfied_bounds_spans, msg);
2129 if errors.iter().all(|error| match error.obligation.cause.code() {
2130 traits::ObligationCauseCode::ImplDerived(data) => {
2131 self.tcx.is_automatically_derived(data.impl_or_alias_def_id)
2132 && data.impl_or_alias_def_id.is_local()
2133 }
2134 _ => false,
2135 }) {
2136 diag.help(manually_impl);
2137 suggest_derive = false;
2138 }
2139 } else {
2140 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!(
2141 "{msg}: {}",
2142 listify(&errors, |e| format!("`{}`", e.obligation.predicate))
2143 .unwrap(),
2144 ));
2145 }
2146 }
2147 }
2148 for error in errors {
2149 if let traits::FulfillmentErrorCode::Select(
2150 traits::SelectionError::Unimplemented,
2151 ) = error.code
2152 && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2153 error.obligation.predicate.kind().skip_binder()
2154 {
2155 self.infcx.err_ctxt().suggest_derive(
2156 &error.obligation,
2157 diag,
2158 error.obligation.predicate.kind().rebind(pred),
2159 );
2160 }
2161 }
2162 }
2163 if suggest_derive {
2164 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)]);
2165 }
2166 }
2167 }
2168 }
2169
2170 fn note_type_is_not_clone_inner_expr<'b>(
2175 &'b self,
2176 expr: &'b hir::Expr<'b>,
2177 ) -> &'b hir::Expr<'b> {
2178 match expr.peel_blocks().kind {
2179 hir::ExprKind::Path(hir::QPath::Resolved(
2180 None,
2181 hir::Path { segments: [_], res: crate::Res::Local(binding), .. },
2182 )) => {
2183 let hir::Node::Pat(hir::Pat { hir_id, .. }) = self.tcx.hir_node(*binding) else {
2184 return expr;
2185 };
2186
2187 match self.tcx.parent_hir_node(*hir_id) {
2188 hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) => {
2190 self.note_type_is_not_clone_inner_expr(init)
2191 }
2192 hir::Node::Pat(hir::Pat {
2194 hir_id: pat_hir_id,
2195 kind: hir::PatKind::Tuple(pats, ..),
2196 ..
2197 }) => {
2198 let hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) =
2199 self.tcx.parent_hir_node(*pat_hir_id)
2200 else {
2201 return expr;
2202 };
2203
2204 match init.peel_blocks().kind {
2205 ExprKind::Tup(init_tup) => {
2206 if let Some(init) = pats
2207 .iter()
2208 .enumerate()
2209 .filter(|x| x.1.hir_id == *hir_id)
2210 .find_map(|(i, _)| init_tup.get(i))
2211 {
2212 self.note_type_is_not_clone_inner_expr(init)
2213 } else {
2214 expr
2215 }
2216 }
2217 _ => expr,
2218 }
2219 }
2220 _ => expr,
2221 }
2222 }
2223 hir::ExprKind::Call(Expr { kind: call_expr_kind, .. }, _) => {
2227 if let hir::ExprKind::Path(hir::QPath::Resolved(None, call_expr_path)) =
2228 call_expr_kind
2229 && let hir::Path { segments: [_], res: crate::Res::Local(binding), .. } =
2230 call_expr_path
2231 && let hir::Node::Pat(hir::Pat { hir_id, .. }) = self.tcx.hir_node(*binding)
2232 && let hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) =
2233 self.tcx.parent_hir_node(*hir_id)
2234 && let Expr {
2235 kind: hir::ExprKind::Closure(hir::Closure { body: body_id, .. }),
2236 ..
2237 } = init
2238 {
2239 let hir::Body { value: body_expr, .. } = self.tcx.hir_body(*body_id);
2240 self.note_type_is_not_clone_inner_expr(body_expr)
2241 } else {
2242 expr
2243 }
2244 }
2245 _ => expr,
2246 }
2247 }
2248
2249 pub(crate) fn is_field_suggestable(
2250 &self,
2251 field: &ty::FieldDef,
2252 hir_id: HirId,
2253 span: Span,
2254 ) -> bool {
2255 field.vis.is_accessible_from(self.tcx.parent_module(hir_id), self.tcx)
2257 && !#[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!(
2259 self.tcx.eval_stability(field.did, None, rustc_span::DUMMY_SP, None),
2260 rustc_middle::middle::stability::EvalResult::Deny { .. }
2261 )
2262 && (field.did.is_local() || !self.tcx.is_doc_hidden(field.did))
2264 && self.tcx.def_ident_span(field.did).unwrap().normalize_to_macros_2_0().eq_ctxt(span)
2266 }
2267
2268 pub(crate) fn suggest_missing_unwrap_expect(
2269 &self,
2270 err: &mut Diag<'_>,
2271 expr: &hir::Expr<'tcx>,
2272 expected: Ty<'tcx>,
2273 found: Ty<'tcx>,
2274 ) -> bool {
2275 let ty::Adt(adt, args) = found.kind() else {
2276 return false;
2277 };
2278 let ret_ty_matches = |diagnostic_item| {
2279 let Some(sig) = self.body_fn_sig() else {
2280 return false;
2281 };
2282 let ty::Adt(kind, _) = sig.output().kind() else {
2283 return false;
2284 };
2285 self.tcx.is_diagnostic_item(diagnostic_item, kind.did())
2286 };
2287
2288 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!(
2291 expr.kind,
2292 hir::ExprKind::Call(
2293 hir::Expr {
2294 kind: hir::ExprKind::Path(hir::QPath::Resolved(
2295 None,
2296 hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. },
2297 )),
2298 ..
2299 },
2300 ..,
2301 ) | hir::ExprKind::Path(hir::QPath::Resolved(
2302 None,
2303 hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. },
2304 )),
2305 );
2306
2307 let (article, kind, variant, sugg_operator) = if self.tcx.is_diagnostic_item(sym::Result, adt.did())
2308 && !self.tcx.hir_is_inside_const_context(expr.hir_id)
2310 {
2311 ("a", "Result", "Err", ret_ty_matches(sym::Result))
2312 } else if self.tcx.is_diagnostic_item(sym::Option, adt.did()) {
2313 ("an", "Option", "None", ret_ty_matches(sym::Option))
2314 } else {
2315 return false;
2316 };
2317 if is_ctor || !self.may_coerce(args.type_at(0), expected) {
2318 return false;
2319 }
2320
2321 let (msg, sugg) = if sugg_operator {
2322 (
2323 ::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!(
2324 "use the `?` operator to extract the `{found}` value, propagating \
2325 {article} `{kind}::{variant}` value to the caller"
2326 ),
2327 "?",
2328 )
2329 } else {
2330 (
2331 ::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!(
2332 "consider using `{kind}::expect` to unwrap the `{found}` value, \
2333 panicking if the value is {article} `{kind}::{variant}`"
2334 ),
2335 ".expect(\"REASON\")",
2336 )
2337 };
2338
2339 let sugg = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2340 Some(_) if expr.span.from_expansion() => return false,
2341 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}{1}", ident, sugg))
})format!(": {ident}{sugg}"),
2342 None => sugg.to_string(),
2343 };
2344
2345 let span = expr
2346 .span
2347 .find_ancestor_not_from_extern_macro(self.tcx.sess.source_map())
2348 .unwrap_or(expr.span);
2349 err.span_suggestion_verbose(span.shrink_to_hi(), msg, sugg, Applicability::HasPlaceholders);
2350 true
2351 }
2352
2353 pub(crate) fn suggest_coercing_result_via_try_operator(
2354 &self,
2355 err: &mut Diag<'_>,
2356 expr: &hir::Expr<'tcx>,
2357 expected: Ty<'tcx>,
2358 found: Ty<'tcx>,
2359 ) -> bool {
2360 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!(
2361 self.tcx.parent_hir_node(expr.hir_id),
2362 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Ret(_), .. })
2363 ) || self.tcx.hir_get_fn_id_for_return_block(expr.hir_id).is_some();
2364 if returned
2365 && let ty::Adt(e, args_e) = expected.kind()
2366 && let ty::Adt(f, args_f) = found.kind()
2367 && e.did() == f.did()
2368 && Some(e.did()) == self.tcx.get_diagnostic_item(sym::Result)
2369 && let e_ok = args_e.type_at(0)
2370 && let f_ok = args_f.type_at(0)
2371 && self.infcx.can_eq(self.param_env, f_ok, e_ok)
2372 && let e_err = args_e.type_at(1)
2373 && let f_err = args_f.type_at(1)
2374 && self
2375 .infcx
2376 .type_implements_trait(
2377 self.tcx.get_diagnostic_item(sym::Into).unwrap(),
2378 [f_err, e_err],
2379 self.param_env,
2380 )
2381 .must_apply_modulo_regions()
2382 {
2383 err.multipart_suggestion(
2384 "use `?` to coerce and return an appropriate `Err`, and wrap the resulting value \
2385 in `Ok` so the expression remains of type `Result`",
2386 ::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![
2387 (expr.span.shrink_to_lo(), "Ok(".to_string()),
2388 (expr.span.shrink_to_hi(), "?)".to_string()),
2389 ],
2390 Applicability::MaybeIncorrect,
2391 );
2392 return true;
2393 }
2394 false
2395 }
2396
2397 pub(crate) fn suggest_returning_value_after_loop(
2400 &self,
2401 err: &mut Diag<'_>,
2402 expr: &hir::Expr<'tcx>,
2403 expected: Ty<'tcx>,
2404 ) -> bool {
2405 let tcx = self.tcx;
2406 let enclosing_scope =
2407 tcx.hir_get_enclosing_scope(expr.hir_id).map(|hir_id| tcx.hir_node(hir_id));
2408
2409 let tail_expr = if let Some(Node::Block(hir::Block { expr, .. })) = enclosing_scope
2411 && expr.is_some()
2412 {
2413 *expr
2414 } else {
2415 let body_def_id = tcx.hir_enclosing_body_owner(expr.hir_id);
2416 let body = tcx.hir_body_owned_by(body_def_id);
2417
2418 match body.value.kind {
2420 hir::ExprKind::Block(block, _) => block.expr,
2422 hir::ExprKind::DropTemps(expr) => Some(expr),
2424 _ => None,
2425 }
2426 };
2427
2428 let Some(tail_expr) = tail_expr else {
2429 return false; };
2431
2432 let loop_expr_in_tail = match expr.kind {
2434 hir::ExprKind::Loop(_, _, hir::LoopSource::While, _) => tail_expr,
2435 hir::ExprKind::Loop(_, _, hir::LoopSource::ForLoop, _) => {
2436 match tail_expr.peel_drop_temps() {
2437 Expr { kind: ExprKind::Match(_, [Arm { body, .. }], _), .. } => body,
2438 _ => return false, }
2440 }
2441 _ => return false, };
2443
2444 if expr.hir_id == loop_expr_in_tail.hir_id {
2447 let span = expr.span;
2448
2449 let (msg, suggestion) = if expected.is_never() {
2450 (
2451 "consider adding a diverging expression here",
2452 "`loop {}` or `panic!(\"...\")`".to_string(),
2453 )
2454 } else {
2455 ("consider returning a value here", ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` value", expected))
})format!("`{expected}` value"))
2456 };
2457
2458 let src_map = tcx.sess.source_map();
2459 let suggestion = if src_map.is_multiline(expr.span) {
2460 let indentation = src_map.indentation_before(span).unwrap_or_default();
2461 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}/* {1} */", indentation,
suggestion))
})format!("\n{indentation}/* {suggestion} */")
2462 } else {
2463 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" /* {0} */", suggestion))
})format!(" /* {suggestion} */")
2466 };
2467
2468 err.span_suggestion_verbose(
2469 span.shrink_to_hi(),
2470 msg,
2471 suggestion,
2472 Applicability::MaybeIncorrect,
2473 );
2474
2475 true
2476 } else {
2477 false
2478 }
2479 }
2480
2481 pub(crate) fn suggest_semicolon_in_repeat_expr(
2484 &self,
2485 err: &mut Diag<'_>,
2486 expr: &hir::Expr<'_>,
2487 expr_ty: Ty<'tcx>,
2488 ) -> bool {
2489 if let hir::Node::Expr(array_expr) = self.tcx.parent_hir_node(expr.hir_id)
2491 && let hir::ExprKind::Array(elements) = array_expr.kind
2492 && let [first, second] = elements
2493 && second.hir_id == expr.hir_id
2494 {
2495 let comma_span = first.span.between(second.span);
2497
2498 let expr_is_const_usize = expr_ty.is_usize()
2506 && match expr.kind {
2507 ExprKind::Path(QPath::Resolved(
2508 None,
2509 Path { res: Res::Def(DefKind::Const { .. }, _), .. },
2510 )) => true,
2511 ExprKind::Call(
2512 Expr {
2513 kind:
2514 ExprKind::Path(QPath::Resolved(
2515 None,
2516 Path { res: Res::Def(DefKind::Fn, fn_def_id), .. },
2517 )),
2518 ..
2519 },
2520 _,
2521 ) => self.tcx.is_const_fn(*fn_def_id),
2522 _ => false,
2523 };
2524
2525 let first_ty = self.typeck_results.borrow().expr_ty(first);
2530
2531 if self.tcx.sess.source_map().is_imported(array_expr.span)
2536 && self.type_is_clone_modulo_regions(self.param_env, first_ty)
2537 && (expr.is_size_lit() || expr_ty.is_usize_like())
2538 {
2539 err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2540 comma_span,
2541 descr: "a vector",
2542 });
2543 return true;
2544 }
2545
2546 if self.type_is_copy_modulo_regions(self.param_env, first_ty)
2550 && (expr.is_size_lit() || expr_is_const_usize)
2551 {
2552 err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2553 comma_span,
2554 descr: "an array",
2555 });
2556 return true;
2557 }
2558 }
2559 false
2560 }
2561
2562 pub(crate) fn suggest_compatible_variants(
2565 &self,
2566 err: &mut Diag<'_>,
2567 expr: &hir::Expr<'_>,
2568 expected: Ty<'tcx>,
2569 expr_ty: Ty<'tcx>,
2570 ) -> bool {
2571 if expr.span.in_external_macro(self.tcx.sess.source_map()) {
2572 return false;
2573 }
2574 if let ty::Adt(expected_adt, args) = expected.kind() {
2575 if let hir::ExprKind::Field(base, ident) = expr.kind {
2576 let base_ty = self.typeck_results.borrow().expr_ty(base);
2577 if self.can_eq(self.param_env, base_ty, expected)
2578 && let Some(base_span) = base.span.find_ancestor_inside(expr.span)
2579 {
2580 err.span_suggestion_verbose(
2581 expr.span.with_lo(base_span.hi()),
2582 ::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}`"),
2583 "",
2584 Applicability::MaybeIncorrect,
2585 );
2586 return true;
2587 }
2588 }
2589
2590 if expr_ty.is_unit() {
2594 let mut id = expr.hir_id;
2595 let mut parent;
2596
2597 loop {
2599 parent = self.tcx.parent_hir_id(id);
2600 let parent_span = self.tcx.hir_span(parent);
2601 if parent_span.find_ancestor_inside(expr.span).is_some() {
2602 id = parent;
2605 continue;
2606 }
2607 break;
2608 }
2609
2610 if let hir::Node::Block(&hir::Block { span: block_span, expr: Some(e), .. }) =
2611 self.tcx.hir_node(parent)
2612 {
2613 if e.hir_id == id {
2614 if let Some(span) = expr.span.find_ancestor_inside(block_span) {
2615 let return_suggestions = if self
2616 .tcx
2617 .is_diagnostic_item(sym::Result, expected_adt.did())
2618 {
2619 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["Ok(())"]))vec!["Ok(())"]
2620 } else if self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) {
2621 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["None", "Some(())"]))vec!["None", "Some(())"]
2622 } else {
2623 return false;
2624 };
2625 if let Some(indent) =
2626 self.tcx.sess.source_map().indentation_before(span.shrink_to_lo())
2627 {
2628 let semicolon =
2630 match self.tcx.sess.source_map().span_to_snippet(span) {
2631 Ok(s) if s.ends_with('}') => "",
2632 _ => ";",
2633 };
2634 err.span_suggestions(
2635 span.shrink_to_hi(),
2636 "try adding an expression at the end of the block",
2637 return_suggestions
2638 .into_iter()
2639 .map(|r| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}\n{1}{2}", semicolon, indent,
r))
})format!("{semicolon}\n{indent}{r}")),
2640 Applicability::MaybeIncorrect,
2641 );
2642 }
2643 return true;
2644 }
2645 }
2646 }
2647 }
2648
2649 let compatible_variants: Vec<(String, _, _, Option<String>)> = expected_adt
2650 .variants()
2651 .iter()
2652 .filter(|variant| {
2653 variant.fields.len() == 1
2654 })
2655 .filter_map(|variant| {
2656 let sole_field = &variant.single_field();
2657
2658 if let (ty::Adt(exp_adt, _), ty::Adt(act_adt, _)) = (expected.kind(), expr_ty.kind())
2662 && exp_adt.did() == act_adt.did()
2663 && sole_field.ty(self.tcx, args).skip_norm_wip().is_ty_var() {
2664 return None;
2665 }
2666
2667 let field_is_local = sole_field.did.is_local();
2668 let field_is_accessible =
2669 sole_field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
2670 && #[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);
2672
2673 if !field_is_local && !field_is_accessible {
2674 return None;
2675 }
2676
2677 let note_about_variant_field_privacy = (field_is_local && !field_is_accessible)
2678 .then(|| " (its field is private, but it's local to this crate and its privacy can be changed)".to_string());
2679
2680 let sole_field_ty = sole_field.ty(self.tcx, args).skip_norm_wip();
2681 if self.may_coerce(expr_ty, sole_field_ty) {
2682 let variant_path =
2683 { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(variant.def_id) }with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
2684 if let Some(path) = variant_path.strip_prefix("std::prelude::")
2686 && let Some((_, path)) = path.split_once("::")
2687 {
2688 return Some((path.to_string(), variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy));
2689 }
2690 Some((variant_path, variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy))
2691 } else {
2692 None
2693 }
2694 })
2695 .collect();
2696
2697 let suggestions_for = |variant: &_, ctor_kind, field_name| {
2698 let prefix = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
2699 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", ident))
})format!("{ident}: "),
2700 None => String::new(),
2701 };
2702
2703 let (open, close) = match ctor_kind {
2704 Some(CtorKind::Fn) => ("(".to_owned(), ")"),
2705 None => (::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0}: ", field_name))
})format!(" {{ {field_name}: "), " }"),
2706
2707 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"),
2708 };
2709
2710 let mut expr = expr;
2714 while let hir::ExprKind::Block(block, _) = &expr.kind
2715 && let Some(expr_) = &block.expr
2716 {
2717 expr = expr_
2718 }
2719
2720 ::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![
2721 (expr.span.shrink_to_lo(), format!("{prefix}{variant}{open}")),
2722 (expr.span.shrink_to_hi(), close.to_owned()),
2723 ]
2724 };
2725
2726 match &compatible_variants[..] {
2727 [] => { }
2728 [(variant, ctor_kind, field_name, note)] => {
2729 err.multipart_suggestion(
2731 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try wrapping the expression in `{1}`{0}",
note.as_deref().unwrap_or(""), variant))
})format!(
2732 "try wrapping the expression in `{variant}`{note}",
2733 note = note.as_deref().unwrap_or("")
2734 ),
2735 suggestions_for(&**variant, *ctor_kind, *field_name),
2736 Applicability::MaybeIncorrect,
2737 );
2738 return true;
2739 }
2740 _ => {
2741 err.multipart_suggestions(
2743 ::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!(
2744 "try wrapping the expression in a variant of `{}`",
2745 self.tcx.def_path_str(expected_adt.did())
2746 ),
2747 compatible_variants.into_iter().map(
2748 |(variant, ctor_kind, field_name, _)| {
2749 suggestions_for(&variant, ctor_kind, field_name)
2750 },
2751 ),
2752 Applicability::MaybeIncorrect,
2753 );
2754 return true;
2755 }
2756 }
2757 }
2758
2759 false
2760 }
2761
2762 pub(crate) fn suggest_non_zero_new_unwrap(
2763 &self,
2764 err: &mut Diag<'_>,
2765 expr: &hir::Expr<'_>,
2766 expected: Ty<'tcx>,
2767 expr_ty: Ty<'tcx>,
2768 ) -> bool {
2769 let tcx = self.tcx;
2770 let (adt, args, unwrap) = match expected.kind() {
2771 ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Option, adt.did()) => {
2773 let nonzero_type = args.type_at(0); let ty::Adt(adt, args) = nonzero_type.kind() else {
2775 return false;
2776 };
2777 (adt, args, "")
2778 }
2779 ty::Adt(adt, args) => (adt, args, ".unwrap()"),
2781 _ => return false,
2782 };
2783
2784 if !self.tcx.is_diagnostic_item(sym::NonZero, adt.did()) {
2785 return false;
2786 }
2787
2788 let int_type = args.type_at(0);
2789 if !self.may_coerce(expr_ty, int_type) {
2790 return false;
2791 }
2792
2793 err.multipart_suggestion(
2794 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider calling `{0}::new`",
sym::NonZero))
})format!("consider calling `{}::new`", sym::NonZero),
2795 ::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![
2796 (expr.span.shrink_to_lo(), format!("{}::new(", sym::NonZero)),
2797 (expr.span.shrink_to_hi(), format!("){unwrap}")),
2798 ],
2799 Applicability::MaybeIncorrect,
2800 );
2801
2802 true
2803 }
2804
2805 fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Vec<(Span, String)>, &'static str)> {
2822 let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind else {
2823 return None;
2824 };
2825
2826 let hir::def::Res::Local(local_id) = path.res else {
2827 return None;
2828 };
2829
2830 let Node::Param(hir::Param { hir_id: param_hir_id, .. }) =
2831 self.tcx.parent_hir_node(local_id)
2832 else {
2833 return None;
2834 };
2835
2836 let Node::Expr(hir::Expr {
2837 hir_id: expr_hir_id,
2838 kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }),
2839 ..
2840 }) = self.tcx.parent_hir_node(*param_hir_id)
2841 else {
2842 return None;
2843 };
2844
2845 let hir = self.tcx.parent_hir_node(*expr_hir_id);
2846 let closure_params_len = closure_fn_decl.inputs.len();
2847 let (
2848 Node::Expr(hir::Expr {
2849 kind: hir::ExprKind::MethodCall(method_path, receiver, ..),
2850 ..
2851 }),
2852 1,
2853 ) = (hir, closure_params_len)
2854 else {
2855 return None;
2856 };
2857
2858 let self_ty = self.typeck_results.borrow().expr_ty_opt(receiver)?;
2859 let name = method_path.ident.name;
2860 let is_as_ref_able = match self_ty.peel_refs().kind() {
2861 ty::Adt(def, _) => {
2862 (self.tcx.is_diagnostic_item(sym::Option, def.did())
2863 || self.tcx.is_diagnostic_item(sym::Result, def.did()))
2864 && (name == sym::map || name == sym::and_then)
2865 }
2866 _ => false,
2867 };
2868 if is_as_ref_able {
2869 Some((
2870 ::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())],
2871 "consider using `as_ref` instead",
2872 ))
2873 } else {
2874 None
2875 }
2876 }
2877
2878 pub(crate) fn suggest_deref_or_ref(
2895 &self,
2896 expr: &hir::Expr<'tcx>,
2897 checked_ty: Ty<'tcx>,
2898 expected: Ty<'tcx>,
2899 ) -> Option<(
2900 Vec<(Span, String)>,
2901 String,
2902 Applicability,
2903 bool, bool, )> {
2906 let sess = self.sess();
2907 let sp = expr.range_span().unwrap_or(expr.span);
2908 let sm = sess.source_map();
2909
2910 if sp.in_external_macro(sm) {
2912 return None;
2913 }
2914
2915 let replace_prefix = |s: &str, old: &str, new: &str| {
2916 s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
2917 };
2918
2919 let expr = expr.peel_drop_temps();
2921
2922 match (&expr.kind, expected.kind(), checked_ty.kind()) {
2923 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) {
2924 (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
2925 if let hir::ExprKind::Lit(_) = expr.kind
2926 && let Ok(src) = sm.span_to_snippet(sp)
2927 && replace_prefix(&src, "b\"", "\"").is_some()
2928 {
2929 let pos = sp.lo() + BytePos(1);
2930 return Some((
2931 ::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())],
2932 "consider removing the leading `b`".to_string(),
2933 Applicability::MachineApplicable,
2934 true,
2935 false,
2936 ));
2937 }
2938 }
2939 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
2940 if let hir::ExprKind::Lit(_) = expr.kind
2941 && let Ok(src) = sm.span_to_snippet(sp)
2942 && replace_prefix(&src, "\"", "b\"").is_some()
2943 {
2944 return Some((
2945 ::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())],
2946 "consider adding a leading `b`".to_string(),
2947 Applicability::MachineApplicable,
2948 true,
2949 false,
2950 ));
2951 }
2952 }
2953 _ => {}
2954 },
2955 (_, &ty::Ref(_, _, mutability), _) => {
2956 let ref_ty = match mutability {
2965 hir::Mutability::Mut => {
2966 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, checked_ty)
2967 }
2968 hir::Mutability::Not => {
2969 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, checked_ty)
2970 }
2971 };
2972 if self.may_coerce(ref_ty, expected) {
2973 let mut sugg_sp = sp;
2974 if let hir::ExprKind::MethodCall(segment, receiver, args, _) = expr.kind {
2975 let clone_trait =
2976 self.tcx.require_lang_item(LangItem::Clone, segment.ident.span);
2977 if args.is_empty()
2978 && self
2979 .typeck_results
2980 .borrow()
2981 .type_dependent_def_id(expr.hir_id)
2982 .is_some_and(|did| {
2983 let ai = self.tcx.associated_item(did);
2984 ai.trait_container(self.tcx) == Some(clone_trait)
2985 })
2986 && segment.ident.name == sym::clone
2987 {
2988 sugg_sp = receiver.span;
2991 }
2992 }
2993
2994 if let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
2995 && let Some(1) = self.deref_steps_for_suggestion(expected, checked_ty)
2996 && self.typeck_results.borrow().expr_ty(inner).is_ref()
2997 {
2998 sugg_sp = sugg_sp.with_hi(inner.span.lo());
3001 return Some((
3002 ::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())],
3003 "consider removing deref here".to_string(),
3004 Applicability::MachineApplicable,
3005 true,
3006 false,
3007 ));
3008 }
3009
3010 if let hir::ExprKind::If(_c, then, els) = expr.kind {
3016 let ExprKind::Block(then, _) = then.kind else { return None };
3019 let Some(then) = then.expr else { return None };
3020 let (mut suggs, help, app, verbose, mutref) =
3021 self.suggest_deref_or_ref(then, checked_ty, expected)?;
3022
3023 let els_expr = match els?.kind {
3025 ExprKind::Block(block, _) => block.expr?,
3026 _ => els?,
3027 };
3028 let (else_suggs, ..) =
3029 self.suggest_deref_or_ref(els_expr, checked_ty, expected)?;
3030 suggs.extend(else_suggs);
3031
3032 return Some((suggs, help, app, verbose, mutref));
3033 }
3034
3035 if let Some((sugg, msg)) = self.can_use_as_ref(expr) {
3036 return Some((
3037 sugg,
3038 msg.to_string(),
3039 Applicability::MachineApplicable,
3040 true,
3041 false,
3042 ));
3043 }
3044
3045 let prefix = match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
3046 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", ident))
})format!("{ident}: "),
3047 None => String::new(),
3048 };
3049
3050 if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Assign(..), .. }) =
3051 self.tcx.parent_hir_node(expr.hir_id)
3052 {
3053 if mutability.is_mut() {
3054 return None;
3056 }
3057 }
3058
3059 let make_sugg = |expr: &Expr<'_>, span: Span, sugg: &str| {
3060 if expr_needs_parens(expr) {
3061 (
3062 ::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![
3063 (span.shrink_to_lo(), format!("{prefix}{sugg}(")),
3064 (span.shrink_to_hi(), ")".to_string()),
3065 ],
3066 false,
3067 )
3068 } else {
3069 (::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)
3070 }
3071 };
3072
3073 if let hir::Node::Expr(hir::Expr {
3075 kind: hir::ExprKind::Binary(_, lhs, ..),
3076 ..
3077 }) = self.tcx.parent_hir_node(expr.hir_id)
3078 && let &ty::Ref(..) = self.check_expr(lhs).kind()
3079 {
3080 let (sugg, verbose) = make_sugg(lhs, lhs.span, "*");
3081
3082 return Some((
3083 sugg,
3084 "consider dereferencing the borrow".to_string(),
3085 Applicability::MachineApplicable,
3086 verbose,
3087 false,
3088 ));
3089 }
3090
3091 let sugg = mutability.ref_prefix_str();
3092 let (sugg, verbose) = make_sugg(expr, sp, sugg);
3093 return Some((
3094 sugg,
3095 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider {0}borrowing here",
mutability.mutably_str()))
})format!("consider {}borrowing here", mutability.mutably_str()),
3096 Applicability::MachineApplicable,
3097 verbose,
3098 false,
3099 ));
3100 }
3101 }
3102 (hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr), _, &ty::Ref(_, checked, _))
3103 if self.can_eq(self.param_env, checked, expected) =>
3104 {
3105 let make_sugg = |start: Span, end: BytePos| {
3106 let sp = sm
3109 .span_extend_while(start.shrink_to_lo(), |c| c == '(' || c.is_whitespace())
3110 .map_or(start, |s| s.shrink_to_hi());
3111 Some((
3112 ::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())],
3113 "consider removing the borrow".to_string(),
3114 Applicability::MachineApplicable,
3115 true,
3116 true,
3117 ))
3118 };
3119
3120 if sm.is_imported(expr.span) {
3123 if let Some(call_span) =
3129 iter::successors(Some(expr.span), |s| s.parent_callsite())
3130 .find(|&s| sp.contains(s))
3131 && sm.is_span_accessible(call_span)
3132 {
3133 return make_sugg(sp, call_span.lo());
3134 }
3135 return None;
3136 }
3137 if sp.contains(expr.span) && sm.is_span_accessible(expr.span) {
3138 return make_sugg(sp, expr.span.lo());
3139 }
3140 }
3141 (_, &ty::RawPtr(ty_b, mutbl_b), &ty::Ref(_, ty_a, mutbl_a)) => {
3142 if let Some(steps) = self.deref_steps_for_suggestion(ty_a, ty_b)
3143 && steps > 0
3145 && let Ok(src) = sm.span_to_snippet(sp)
3147 {
3148 let derefs = "*".repeat(steps);
3149 let old_prefix = mutbl_a.ref_prefix_str();
3150 let new_prefix = mutbl_b.ref_prefix_str().to_owned() + &derefs;
3151
3152 let suggestion = replace_prefix(&src, old_prefix, &new_prefix).map(|_| {
3153 let lo = sp.lo()
3155 + BytePos(min(old_prefix.len(), mutbl_b.ref_prefix_str().len()) as _);
3156 let hi = sp.lo() + BytePos(old_prefix.len() as _);
3158 let sp = sp.with_lo(lo).with_hi(hi);
3159
3160 (
3161 sp,
3162 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" },
derefs))
})format!(
3163 "{}{derefs}",
3164 if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" }
3165 ),
3166 if mutbl_b <= mutbl_a {
3167 Applicability::MachineApplicable
3168 } else {
3169 Applicability::MaybeIncorrect
3170 },
3171 )
3172 });
3173
3174 if let Some((span, src, applicability)) = suggestion {
3175 return Some((
3176 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, src)]))vec![(span, src)],
3177 "consider dereferencing".to_string(),
3178 applicability,
3179 true,
3180 false,
3181 ));
3182 }
3183 }
3184 }
3185 _ if sp == expr.span => {
3186 if let Some(mut steps) = self.deref_steps_for_suggestion(checked_ty, expected) {
3187 let mut expr = expr.peel_blocks();
3188 let mut prefix_span = expr.span.shrink_to_lo();
3189 let mut remove = String::new();
3190
3191 while steps > 0 {
3193 if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind {
3194 prefix_span = prefix_span.with_hi(inner.span.lo());
3196 expr = inner;
3197 remove.push_str(mutbl.ref_prefix_str());
3198 steps -= 1;
3199 } else {
3200 break;
3201 }
3202 }
3203 if steps == 0 && !remove.trim().is_empty() {
3205 return Some((
3206 ::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())],
3207 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing the `{0}`",
remove.trim()))
})format!("consider removing the `{}`", remove.trim()),
3208 if remove.trim() == "&&" && expected == self.tcx.types.bool {
3212 Applicability::MaybeIncorrect
3213 } else {
3214 Applicability::MachineApplicable
3215 },
3216 true,
3217 false,
3218 ));
3219 }
3220
3221 if self.type_is_copy_modulo_regions(self.param_env, expected)
3224 || (checked_ty.is_box() && steps == 1)
3227 || #[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!(
3229 self.tcx.parent_hir_node(expr.hir_id),
3230 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, ..), .. })
3231 if !op.node.is_by_value()
3232 )
3233 {
3234 let deref_kind = if checked_ty.is_box() {
3235 if let ExprKind::Call(box_new, [_]) = expr.kind
3237 && let ExprKind::Path(qpath) = &box_new.kind
3238 && let Res::Def(DefKind::AssocFn, fn_id) =
3239 self.typeck_results.borrow().qpath_res(qpath, box_new.hir_id)
3240 && self.tcx.is_diagnostic_item(sym::box_new, fn_id)
3241 {
3242 let l_paren = self.tcx.sess.source_map().next_point(box_new.span);
3243 let r_paren = self.tcx.sess.source_map().end_point(expr.span);
3244 return Some((
3245 ::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![
3246 (box_new.span.to(l_paren), String::new()),
3247 (r_paren, String::new()),
3248 ],
3249 "consider removing the Box".to_string(),
3250 Applicability::MachineApplicable,
3251 false,
3252 false,
3253 ));
3254 }
3255 "unboxing the value"
3256 } else if checked_ty.is_ref() {
3257 "dereferencing the borrow"
3258 } else {
3259 "dereferencing the type"
3260 };
3261
3262 let message = if remove.is_empty() {
3265 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider {0}", deref_kind))
})format!("consider {deref_kind}")
3266 } else {
3267 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing the `{0}` and {1} instead",
remove.trim(), deref_kind))
})format!(
3268 "consider removing the `{}` and {} instead",
3269 remove.trim(),
3270 deref_kind
3271 )
3272 };
3273
3274 let prefix =
3275 match self.tcx.hir_maybe_get_struct_pattern_shorthand_field(expr) {
3276 Some(ident) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", ident))
})format!("{ident}: "),
3277 None => String::new(),
3278 };
3279
3280 let (span, suggestion) = if self.is_else_if_block(expr) {
3281 return None;
3283 } else if let Some(expr) = self.maybe_get_block_expr(expr) {
3284 (expr.span.shrink_to_lo(), "*".to_string())
3286 } else {
3287 (prefix_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", prefix,
"*".repeat(steps)))
})format!("{}{}", prefix, "*".repeat(steps)))
3288 };
3289 if suggestion.trim().is_empty() {
3290 return None;
3291 }
3292
3293 if expr_needs_parens(expr) {
3294 return Some((
3295 ::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![
3296 (span, format!("{suggestion}(")),
3297 (expr.span.shrink_to_hi(), ")".to_string()),
3298 ],
3299 message,
3300 Applicability::MachineApplicable,
3301 true,
3302 false,
3303 ));
3304 }
3305
3306 return Some((
3307 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, suggestion)]))vec![(span, suggestion)],
3308 message,
3309 Applicability::MachineApplicable,
3310 true,
3311 false,
3312 ));
3313 }
3314 }
3315 }
3316 _ => {}
3317 }
3318 None
3319 }
3320
3321 fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool {
3323 if let hir::ExprKind::If(..) = expr.kind
3324 && let Node::Expr(hir::Expr { kind: hir::ExprKind::If(_, _, Some(else_expr)), .. }) =
3325 self.tcx.parent_hir_node(expr.hir_id)
3326 {
3327 return else_expr.hir_id == expr.hir_id;
3328 }
3329 false
3330 }
3331
3332 pub(crate) fn suggest_cast(
3333 &self,
3334 err: &mut Diag<'_>,
3335 expr: &hir::Expr<'_>,
3336 checked_ty: Ty<'tcx>,
3337 expected_ty: Ty<'tcx>,
3338 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
3339 ) -> bool {
3340 if self.tcx.sess.source_map().is_imported(expr.span) {
3341 return false;
3343 }
3344
3345 let span = if let hir::ExprKind::Lit(lit) = &expr.kind { lit.span } else { expr.span };
3346 let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) else {
3347 return false;
3348 };
3349
3350 let can_cast = false;
3359
3360 let mut sugg = ::alloc::vec::Vec::new()vec![];
3361
3362 if let hir::Node::ExprField(field) = self.tcx.parent_hir_node(expr.hir_id) {
3363 if field.is_shorthand {
3365 sugg.push((field.ident.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", field.ident))
})format!("{}: ", field.ident)));
3367 } else {
3368 return false;
3370 }
3371 };
3372
3373 if let hir::ExprKind::Call(path, args) = &expr.kind
3374 && let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
3375 (&path.kind, args.len())
3376 && let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
3378 (&base_ty.kind, path_segment.ident.name)
3379 {
3380 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
3381 match ident.name {
3382 sym::i128
3383 | sym::i64
3384 | sym::i32
3385 | sym::i16
3386 | sym::i8
3387 | sym::u128
3388 | sym::u64
3389 | sym::u32
3390 | sym::u16
3391 | sym::u8
3392 | sym::isize
3393 | sym::usize
3394 if base_ty_path.segments.len() == 1 =>
3395 {
3396 return false;
3397 }
3398 _ => {}
3399 }
3400 }
3401 }
3402
3403 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!(
3404 "you can convert {} `{}` to {} `{}`",
3405 checked_ty.kind().article(),
3406 checked_ty,
3407 expected_ty.kind().article(),
3408 expected_ty,
3409 );
3410 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!(
3411 "you can cast {} `{}` to {} `{}`",
3412 checked_ty.kind().article(),
3413 checked_ty,
3414 expected_ty.kind().article(),
3415 expected_ty,
3416 );
3417 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!(
3418 "change the type of the numeric literal from `{checked_ty}` to `{expected_ty}`",
3419 );
3420
3421 let close_paren = if self.precedence(expr) < ExprPrecedence::Unambiguous {
3422 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
3423 ")"
3424 } else {
3425 ""
3426 };
3427
3428 let mut cast_suggestion = sugg.clone();
3429 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}")));
3430 let mut into_suggestion = sugg.clone();
3431 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()")));
3432 let mut suffix_suggestion = sugg.clone();
3433 suffix_suggestion.push((
3434 if #[allow(non_exhaustive_omitted_patterns)] match (expected_ty.kind(),
checked_ty.kind()) {
(ty::Int(_) | ty::Uint(_), ty::Float(_)) => true,
_ => false,
}matches!(
3435 (expected_ty.kind(), checked_ty.kind()),
3436 (ty::Int(_) | ty::Uint(_), ty::Float(_))
3437 ) {
3438 let src = src.trim_end_matches(&checked_ty.to_string());
3440 let len = src.split('.').next().unwrap().len();
3441 span.with_lo(span.lo() + BytePos(len as u32))
3442 } else {
3443 let len = src.trim_end_matches(&checked_ty.to_string()).len();
3444 span.with_lo(span.lo() + BytePos(len as u32))
3445 },
3446 if self.precedence(expr) < ExprPrecedence::Unambiguous {
3447 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0})", expected_ty))
})format!("{expected_ty})")
3449 } else {
3450 expected_ty.to_string()
3451 },
3452 ));
3453 let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
3454 if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
3455 };
3456 let is_negative_int =
3457 |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, ..));
3458 let is_uint = |ty: Ty<'_>| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Uint(..) => true,
_ => false,
}matches!(ty.kind(), ty::Uint(..));
3459
3460 let in_const_context = self.tcx.hir_is_inside_const_context(expr.hir_id);
3461
3462 let suggest_fallible_into_or_lhs_from =
3463 |err: &mut Diag<'_>, exp_to_found_is_fallible: bool| {
3464 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
3471 self.tcx
3472 .sess
3473 .source_map()
3474 .span_to_snippet(expr.span)
3475 .ok()
3476 .map(|src| (expr, src))
3477 });
3478 let (msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
3479 (lhs_expr_and_src, exp_to_found_is_fallible)
3480 {
3481 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!(
3482 "you can convert `{lhs_src}` from `{expected_ty}` to `{checked_ty}`, matching the type of `{src}`",
3483 );
3484 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![
3485 (lhs_expr.span.shrink_to_lo(), format!("{checked_ty}::from(")),
3486 (lhs_expr.span.shrink_to_hi(), ")".to_string()),
3487 ];
3488 (msg, suggestion)
3489 } else {
3490 let msg =
3491 ::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());
3492 let mut suggestion = sugg.clone();
3493 suggestion.push((
3494 expr.span.shrink_to_hi(),
3495 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.try_into().unwrap()",
close_paren))
})format!("{close_paren}.try_into().unwrap()"),
3496 ));
3497 (msg, suggestion)
3498 };
3499 err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
3500 };
3501
3502 let suggest_to_change_suffix_or_into =
3503 |err: &mut Diag<'_>, found_to_exp_is_fallible: bool, exp_to_found_is_fallible: bool| {
3504 let exp_is_lhs = expected_ty_expr.is_some_and(|e| self.tcx.hir_is_lhs(e.hir_id));
3505
3506 if exp_is_lhs {
3507 return;
3508 }
3509
3510 let always_fallible = found_to_exp_is_fallible
3511 && (exp_to_found_is_fallible || expected_ty_expr.is_none());
3512 let msg = if literal_is_ty_suffixed(expr) {
3513 lit_msg.clone()
3514 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
3515 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}`");
3519 err.note(msg);
3520 return;
3521 } else if in_const_context {
3522 return;
3524 } else if found_to_exp_is_fallible {
3525 return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
3526 } else {
3527 msg.clone()
3528 };
3529 let suggestion = if literal_is_ty_suffixed(expr) {
3530 suffix_suggestion.clone()
3531 } else {
3532 into_suggestion.clone()
3533 };
3534 err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
3535 };
3536
3537 match (expected_ty.kind(), checked_ty.kind()) {
3538 (ty::Int(exp), ty::Int(found)) => {
3539 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3540 {
3541 (Some(exp), Some(found)) if exp < found => (true, false),
3542 (Some(exp), Some(found)) if exp > found => (false, true),
3543 (None, Some(8 | 16)) => (false, true),
3544 (Some(8 | 16), None) => (true, false),
3545 (None, _) | (_, None) => (true, true),
3546 _ => (false, false),
3547 };
3548 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3549 true
3550 }
3551 (ty::Uint(exp), ty::Uint(found)) => {
3552 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3553 {
3554 (Some(exp), Some(found)) if exp < found => (true, false),
3555 (Some(exp), Some(found)) if exp > found => (false, true),
3556 (None, Some(8 | 16)) => (false, true),
3557 (Some(8 | 16), None) => (true, false),
3558 (None, _) | (_, None) => (true, true),
3559 _ => (false, false),
3560 };
3561 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3562 true
3563 }
3564 (&ty::Int(exp), &ty::Uint(found)) => {
3565 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3566 {
3567 (Some(exp), Some(found)) if found < exp => (false, true),
3568 (None, Some(8)) => (false, true),
3569 _ => (true, true),
3570 };
3571 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3572 true
3573 }
3574 (&ty::Uint(exp), &ty::Int(found)) => {
3575 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
3576 {
3577 (Some(exp), Some(found)) if found > exp => (true, false),
3578 (Some(8), None) => (true, false),
3579 _ => (true, true),
3580 };
3581 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
3582 true
3583 }
3584 (ty::Float(exp), ty::Float(found)) => {
3585 if found.bit_width() < exp.bit_width() {
3586 suggest_to_change_suffix_or_into(err, false, true);
3587 } else if literal_is_ty_suffixed(expr) {
3588 err.multipart_suggestion(
3589 lit_msg,
3590 suffix_suggestion,
3591 Applicability::MachineApplicable,
3592 );
3593 } else if can_cast {
3594 err.multipart_suggestion(
3596 ::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"),
3597 cast_suggestion,
3598 Applicability::MaybeIncorrect, );
3600 }
3601 true
3602 }
3603 (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
3604 if literal_is_ty_suffixed(expr) {
3605 err.multipart_suggestion(
3606 lit_msg,
3607 suffix_suggestion,
3608 Applicability::MachineApplicable,
3609 );
3610 } else if can_cast {
3611 err.multipart_suggestion(
3613 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, rounding the float towards zero",
msg))
})format!("{msg}, rounding the float towards zero"),
3614 cast_suggestion,
3615 Applicability::MaybeIncorrect, );
3617 }
3618 true
3619 }
3620 (ty::Float(exp), ty::Uint(found)) => {
3621 if exp.bit_width() > found.bit_width().unwrap_or(256) {
3623 err.multipart_suggestion(
3624 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer",
msg))
})format!(
3625 "{msg}, producing the floating point representation of the integer",
3626 ),
3627 into_suggestion,
3628 Applicability::MachineApplicable,
3629 );
3630 } else if literal_is_ty_suffixed(expr) {
3631 err.multipart_suggestion(
3632 lit_msg,
3633 suffix_suggestion,
3634 Applicability::MachineApplicable,
3635 );
3636 } else {
3637 err.multipart_suggestion(
3639 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer, rounded if necessary",
cast_msg))
})format!(
3640 "{cast_msg}, producing the floating point representation of the integer, \
3641 rounded if necessary",
3642 ),
3643 cast_suggestion,
3644 Applicability::MaybeIncorrect, );
3646 }
3647 true
3648 }
3649 (ty::Float(exp), ty::Int(found)) => {
3650 if exp.bit_width() > found.bit_width().unwrap_or(256) {
3652 err.multipart_suggestion(
3653 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer",
msg.clone()))
})format!(
3654 "{}, producing the floating point representation of the integer",
3655 msg.clone(),
3656 ),
3657 into_suggestion,
3658 Applicability::MachineApplicable,
3659 );
3660 } else if literal_is_ty_suffixed(expr) {
3661 err.multipart_suggestion(
3662 lit_msg,
3663 suffix_suggestion,
3664 Applicability::MachineApplicable,
3665 );
3666 } else {
3667 err.multipart_suggestion(
3669 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, producing the floating point representation of the integer, rounded if necessary",
&msg))
})format!(
3670 "{}, producing the floating point representation of the integer, \
3671 rounded if necessary",
3672 &msg,
3673 ),
3674 cast_suggestion,
3675 Applicability::MaybeIncorrect, );
3677 }
3678 true
3679 }
3680 (
3681 &ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128)
3682 | &ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128),
3683 &ty::Char,
3684 ) => {
3685 err.multipart_suggestion(
3686 ::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"),
3687 cast_suggestion,
3688 Applicability::MachineApplicable,
3689 );
3690 true
3691 }
3692 _ => false,
3693 }
3694 }
3695
3696 pub(crate) fn suggest_method_call_on_range_literal(
3698 &self,
3699 err: &mut Diag<'_>,
3700 expr: &hir::Expr<'tcx>,
3701 checked_ty: Ty<'tcx>,
3702 expected_ty: Ty<'tcx>,
3703 ) {
3704 if !hir::is_range_literal(expr) {
3705 return;
3706 }
3707 let hir::ExprKind::Struct(&qpath, [start, end], _) = expr.kind else {
3708 return;
3709 };
3710 if !self.tcx.qpath_is_lang_item(qpath, LangItem::Range) {
3711 return;
3712 }
3713 if let hir::Node::ExprField(_) = self.tcx.parent_hir_node(expr.hir_id) {
3714 return;
3716 }
3717 let mut expr = end.expr;
3718 let mut expectation = Some(expected_ty);
3719 while let hir::ExprKind::MethodCall(_, rcvr, ..) = expr.kind {
3720 expr = rcvr;
3723 expectation = None;
3726 }
3727 let hir::ExprKind::Call(method_name, _) = expr.kind else {
3728 return;
3729 };
3730 let ty::Adt(adt, _) = checked_ty.kind() else {
3731 return;
3732 };
3733 if self.tcx.lang_items().range_struct() != Some(adt.did()) {
3734 return;
3735 }
3736 if let ty::Adt(adt, _) = expected_ty.kind()
3737 && self.tcx.is_lang_item(adt.did(), LangItem::Range)
3738 {
3739 return;
3740 }
3741 let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else {
3743 return;
3744 };
3745 let [hir::PathSegment { ident, .. }] = p.segments else {
3746 return;
3747 };
3748 let self_ty = self.typeck_results.borrow().expr_ty(start.expr);
3749 let Ok(_pick) = self.lookup_probe_for_diagnostic(
3750 *ident,
3751 self_ty,
3752 expr,
3753 probe::ProbeScope::AllTraits,
3754 expectation,
3755 ) else {
3756 return;
3757 };
3758 let mut sugg = ".";
3759 let mut span = start.expr.span.between(end.expr.span);
3760 if span.lo() + BytePos(2) == span.hi() {
3761 span = span.with_lo(span.lo() + BytePos(1));
3764 sugg = "";
3765 }
3766 err.span_suggestion_verbose(
3767 span,
3768 "you likely meant to write a method call instead of a range",
3769 sugg,
3770 Applicability::MachineApplicable,
3771 );
3772 }
3773
3774 pub(crate) fn suggest_return_binding_for_missing_tail_expr(
3777 &self,
3778 err: &mut Diag<'_>,
3779 expr: &hir::Expr<'_>,
3780 checked_ty: Ty<'tcx>,
3781 expected_ty: Ty<'tcx>,
3782 ) {
3783 if !checked_ty.is_unit() {
3784 return;
3785 }
3786 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
3787 return;
3788 };
3789 let hir::def::Res::Local(hir_id) = path.res else {
3790 return;
3791 };
3792 let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
3793 return;
3794 };
3795 let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
3796 self.tcx.parent_hir_node(pat.hir_id)
3797 else {
3798 return;
3799 };
3800 let hir::ExprKind::Block(block, None) = init.kind else {
3801 return;
3802 };
3803 if block.expr.is_some() {
3804 return;
3805 }
3806 let [.., stmt] = block.stmts else {
3807 err.span_label(block.span, "this empty block is missing a tail expression");
3808 return;
3809 };
3810 let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
3811 return;
3812 };
3813 let Some(ty) = self.node_ty_opt(tail_expr.hir_id) else {
3814 return;
3815 };
3816 if self.can_eq(self.param_env, expected_ty, ty)
3817 && stmt.span.hi() != tail_expr.span.hi()
3822 {
3823 err.span_suggestion_short(
3824 stmt.span.with_lo(tail_expr.span.hi()),
3825 "remove this semicolon",
3826 "",
3827 Applicability::MachineApplicable,
3828 );
3829 } else {
3830 err.span_label(block.span, "this block is missing a tail expression");
3831 }
3832 }
3833
3834 pub(crate) fn suggest_swapping_lhs_and_rhs(
3835 &self,
3836 err: &mut Diag<'_>,
3837 rhs_ty: Ty<'tcx>,
3838 lhs_ty: Ty<'tcx>,
3839 rhs_expr: &'tcx hir::Expr<'tcx>,
3840 lhs_expr: &'tcx hir::Expr<'tcx>,
3841 ) {
3842 if let Some(partial_eq_def_id) = self.infcx.tcx.lang_items().eq_trait()
3843 && self
3844 .infcx
3845 .type_implements_trait(partial_eq_def_id, [rhs_ty, lhs_ty], self.param_env)
3846 .must_apply_modulo_regions()
3847 {
3848 let sm = self.tcx.sess.source_map();
3849 if !rhs_expr.span.in_external_macro(sm)
3852 && !lhs_expr.span.in_external_macro(sm)
3853 && let Ok(rhs_snippet) = sm.span_to_snippet(rhs_expr.span)
3854 && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_expr.span)
3855 {
3856 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}>`"));
3857 err.multipart_suggestion(
3858 "consider swapping the equality",
3859 ::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)],
3860 Applicability::MaybeIncorrect,
3861 );
3862 }
3863 }
3864 }
3865}