1use core::ops::ControlFlow;
2
3use hir::def::CtorKind;
4use hir::intravisit::{Visitor, walk_expr, walk_stmt};
5use hir::{LetStmt, QPath};
6use rustc_data_structures::fx::FxIndexSet;
7use rustc_errors::{Applicability, Diag};
8use rustc_hir as hir;
9use rustc_hir::def::Res;
10use rustc_hir::{MatchSource, Node};
11use rustc_middle::traits::{MatchExpressionArmCause, ObligationCause, ObligationCauseCode};
12use rustc_middle::ty::error::TypeError;
13use rustc_middle::ty::print::with_no_trimmed_paths;
14use rustc_middle::ty::{
15 self as ty, GenericArgKind, IsSuggestable, Ty, TypeVisitableExt, Unnormalized,
16};
17use rustc_span::{Span, sym};
18use tracing::debug;
19
20use crate::diagnostics::{
21 ConsiderAddingAwait, FnConsiderCasting, FnConsiderCastingBoth, FnItemsAreDistinct, FnUniqTypes,
22 FunctionPointerSuggestion, SuggestAccessingField, SuggestRemoveSemiOrReturnBinding,
23 SuggestTuplePatternMany, SuggestTuplePatternOne, TypeErrorAdditionalDiags,
24};
25use crate::error_reporting::TypeErrCtxt;
26use crate::error_reporting::infer::hir::Path;
27
28#[derive(#[automatically_derived]impl ::core::marker::Copy for StatementAsExpression {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for StatementAsExpression {
}
#[automatically_derived]impl ::core::clone::Clone for StatementAsExpression {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for StatementAsExpression {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
StatementAsExpression::CorrectType => "CorrectType",
StatementAsExpression::NeedsBoxing => "NeedsBoxing",
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
StatementAsExpression {
}
#[automatically_derived]impl ::core::cmp::PartialEq for StatementAsExpression
{
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for StatementAsExpression { }Eq, #[automatically_derived]impl ::core::hash::Hash for StatementAsExpression {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash)]
29enum StatementAsExpression {
30 CorrectType,
31 NeedsBoxing,
32}
33
34#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for SuggestAsRefKind {
}
#[automatically_derived]impl ::core::clone::Clone for SuggestAsRefKind {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for SuggestAsRefKind { }Copy)]
35enum SuggestAsRefKind {
36 Option,
37 Result,
38}
39
40impl<'tcx> TypeErrCtxt<'_, 'tcx> {
41 pub(super) fn suggest_remove_semi_or_return_binding(
42 &self,
43 first_id: Option<hir::HirId>,
44 first_ty: Ty<'tcx>,
45 first_span: Span,
46 second_id: Option<hir::HirId>,
47 second_ty: Ty<'tcx>,
48 second_span: Span,
49 ) -> Option<SuggestRemoveSemiOrReturnBinding> {
50 let remove_semicolon = [
51 (first_id, self.deeply_resolve_ignoring_regions(second_ty)),
52 (second_id, self.deeply_resolve_ignoring_regions(first_ty)),
53 ]
54 .into_iter()
55 .find_map(|(id, ty)| {
56 let hir::Node::Block(blk) = self.tcx.hir_node(id?) else { return None };
57 self.could_remove_semicolon(blk, ty)
58 });
59 match remove_semicolon {
60 Some((sp, StatementAsExpression::NeedsBoxing)) => {
61 Some(SuggestRemoveSemiOrReturnBinding::RemoveAndBox {
62 first_lo: first_span.shrink_to_lo(),
63 first_hi: first_span.shrink_to_hi(),
64 second_lo: second_span.shrink_to_lo(),
65 second_hi: second_span.shrink_to_hi(),
66 sp,
67 })
68 }
69 Some((sp, StatementAsExpression::CorrectType)) => {
70 Some(SuggestRemoveSemiOrReturnBinding::Remove { sp })
71 }
72 None => {
73 let mut ret = None;
74 for (id, ty) in [(first_id, second_ty), (second_id, first_ty)] {
75 if let Some(id) = id
76 && let hir::Node::Block(blk) = self.tcx.hir_node(id)
77 && let Some(diag) = self.consider_returning_binding_diag(blk, ty)
78 {
79 ret = Some(diag);
80 break;
81 }
82 }
83 ret
84 }
85 }
86 }
87
88 pub(super) fn suggest_tuple_pattern(
89 &self,
90 cause: &ObligationCause<'tcx>,
91 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
92 diag: &mut Diag<'_>,
93 ) {
94 if let ObligationCauseCode::Pattern { .. } = cause.code()
97 && let ty::Adt(expected_adt, args) = exp_found.expected.kind()
98 {
99 let compatible_variants: Vec<_> = expected_adt
100 .variants()
101 .iter()
102 .filter(|variant| {
103 variant.fields.len() == 1 && variant.ctor_kind() == Some(CtorKind::Fn)
104 })
105 .filter_map(|variant| {
106 let sole_field = &variant.single_field();
107 let sole_field_ty = sole_field.ty(self.tcx, *args).skip_norm_wip();
108 if self.same_type_modulo_infer(sole_field_ty, exp_found.found) {
109 let variant_path =
110 { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(variant.def_id) }with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
111 if let Some(path) = variant_path
113 .strip_prefix("std::prelude::")
114 .or_else(|| variant_path.strip_prefix("core::prelude::"))
115 && let Some((_, path)) = path.split_once("::")
116 {
117 return Some(path.to_string());
118 }
119 Some(variant_path)
120 } else {
121 None
122 }
123 })
124 .collect();
125 match &compatible_variants[..] {
126 [] => {}
127 [variant] => {
128 let sugg = SuggestTuplePatternOne {
129 variant: variant.to_owned(),
130 span_low: cause.span.shrink_to_lo(),
131 span_high: cause.span.shrink_to_hi(),
132 };
133 diag.subdiagnostic(sugg);
134 }
135 _ => {
136 let sugg = SuggestTuplePatternMany {
138 path: self.tcx.def_path_str(expected_adt.did()),
139 cause_span: cause.span,
140 compatible_variants,
141 };
142 diag.subdiagnostic(sugg);
143 }
144 }
145 }
146 }
147
148 pub(super) fn suggest_await_on_expect_found(
168 &self,
169 cause: &ObligationCause<'tcx>,
170 exp_span: Span,
171 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
172 diag: &mut Diag<'_>,
173 ) {
174 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs:174",
"rustc_trait_selection::error_reporting::infer::suggest",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs"),
::tracing_core::__macro_support::Option::Some(174u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::suggest"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("suggest_await_on_expect_found: exp_span={0:?}, expected_ty={1:?}, found_ty={2:?}",
exp_span, exp_found.expected, exp_found.found) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
175 "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
176 exp_span, exp_found.expected, exp_found.found,
177 );
178
179 match self.tcx.coroutine_kind(cause.body_def_id) {
180 Some(hir::CoroutineKind::Desugared(
181 hir::CoroutineDesugaring::Async | hir::CoroutineDesugaring::AsyncGen,
182 _,
183 )) => (),
184 Some(
185 hir::CoroutineKind::Coroutine(_)
186 | hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _),
187 ) => return,
188 None => {
189 self.suggest_add_async_for_tail_return_expr(cause, exp_span, exp_found, diag);
190 return;
191 }
192 }
193
194 if let ObligationCauseCode::CompareImplItem { .. } = cause.code() {
195 return;
196 }
197
198 let subdiag = match (
199 self.tcx.get_impl_future_output_ty(exp_found.expected),
200 self.tcx.get_impl_future_output_ty(exp_found.found),
201 ) {
202 (Some(exp), Some(found)) if self.same_type_modulo_infer(exp, found) => match cause
203 .code()
204 {
205 ObligationCauseCode::IfExpression { expr_id, .. } => {
206 let hir::Node::Expr(hir::Expr {
207 kind: hir::ExprKind::If(_, then_expr, _), ..
208 }) = self.tcx.hir_node(*expr_id)
209 else {
210 return;
211 };
212 let then_span = self.find_block_span_from_hir_id(then_expr.hir_id);
213 Some(ConsiderAddingAwait::BothFuturesSugg {
214 first: then_span.shrink_to_hi(),
215 second: exp_span.shrink_to_hi(),
216 })
217 }
218 ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
219 prior_non_diverging_arms,
220 ..
221 }) => {
222 if let [.., arm_span] = &prior_non_diverging_arms[..] {
223 Some(ConsiderAddingAwait::BothFuturesSugg {
224 first: arm_span.shrink_to_hi(),
225 second: exp_span.shrink_to_hi(),
226 })
227 } else {
228 Some(ConsiderAddingAwait::BothFuturesHelp)
229 }
230 }
231 _ => Some(ConsiderAddingAwait::BothFuturesHelp),
232 },
233 (_, Some(ty)) if self.same_type_modulo_infer(exp_found.expected, ty) => {
234 diag.subdiagnostic(ConsiderAddingAwait::FutureSugg {
236 span: exp_span.shrink_to_hi(),
237 });
238 Some(ConsiderAddingAwait::FutureSuggNote { span: exp_span })
239 }
240 (Some(ty), _) if self.same_type_modulo_infer(ty, exp_found.found) => match cause.code()
241 {
242 ObligationCauseCode::Pattern { span: Some(then_span), origin_expr, .. } => {
243 origin_expr.is_some().then_some(ConsiderAddingAwait::FutureSugg {
244 span: then_span.shrink_to_hi(),
245 })
246 }
247 ObligationCauseCode::IfExpression { expr_id, .. } => {
248 let hir::Node::Expr(hir::Expr {
249 kind: hir::ExprKind::If(_, then_expr, _), ..
250 }) = self.tcx.hir_node(*expr_id)
251 else {
252 return;
253 };
254 let then_span = self.find_block_span_from_hir_id(then_expr.hir_id);
255 Some(ConsiderAddingAwait::FutureSugg { span: then_span.shrink_to_hi() })
256 }
257 ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
258 prior_non_diverging_arms,
259 ..
260 }) => Some({
261 ConsiderAddingAwait::FutureSuggMultiple {
262 spans: prior_non_diverging_arms
263 .iter()
264 .map(|arm| arm.shrink_to_hi())
265 .collect(),
266 }
267 }),
268 _ => None,
269 },
270 _ => None,
271 };
272 if let Some(subdiag) = subdiag {
273 diag.subdiagnostic(subdiag);
274 }
275 }
276
277 fn suggest_add_async_for_tail_return_expr(
278 &self,
279 cause: &ObligationCause<'tcx>,
280 exp_span: Span,
281 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
282 diag: &mut Diag<'_>,
283 ) {
284 let (ObligationCauseCode::BlockTailExpression(return_hir_id, ..)
285 | ObligationCauseCode::ReturnValue(return_hir_id)) = cause.code()
286 else {
287 return;
288 };
289
290 let body_def_id = cause.body_def_id;
291 if !self.tcx.sess.at_least_rust_2018() || self.tcx.is_entrypoint(body_def_id.to_def_id()) {
292 return;
293 }
294
295 let node = self.tcx.hir_node_by_def_id(body_def_id);
296 let (item_span, vis_span) = match node {
297 Node::Item(item) if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
hir::ItemKind::Fn { .. } => true,
_ => false,
}matches!(item.kind, hir::ItemKind::Fn { .. }) => {
298 (item.span, item.vis_span)
299 }
300 Node::ImplItem(item) if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
hir::ImplItemKind::Fn(..) => true,
_ => false,
}matches!(item.kind, hir::ImplItemKind::Fn(..)) => {
301 let Some(vis_span) = item.vis_span() else { return };
302 (item.span, vis_span)
303 }
304 _ => return,
305 };
306 let Some(sig) = node.fn_sig() else {
307 return;
308 };
309 if sig.header.asyncness.is_async()
310 || sig.header.constness != hir::Constness::NotConst
311 || item_span.from_expansion()
312 {
313 return;
314 }
315
316 let (async_span, async_prefix) = if vis_span.is_empty() {
317 (item_span.shrink_to_lo(), "async ".to_string())
318 } else {
319 (vis_span.shrink_to_hi(), " async".to_string())
320 };
321 let body_hir_id = self.tcx.local_def_id_to_hir_id(body_def_id);
322 if self.tcx.hir_get_fn_id_for_return_block(*return_hir_id) == Some(body_hir_id)
323 && let Some(found) = self.tcx.get_impl_future_output_ty(exp_found.found)
324 && self.same_type_modulo_infer(exp_found.expected, found)
325 && exp_span.can_be_used_for_suggestions()
326 {
327 diag.subdiagnostic(ConsiderAddingAwait::MakeFunctionAsync {
328 async_span,
329 async_prefix,
330 await_span: exp_span.shrink_to_hi(),
331 });
332 }
333 }
334
335 pub(super) fn suggest_accessing_field_where_appropriate(
336 &self,
337 cause: &ObligationCause<'tcx>,
338 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
339 diag: &mut Diag<'_>,
340 ) {
341 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs:341",
"rustc_trait_selection::error_reporting::infer::suggest",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs"),
::tracing_core::__macro_support::Option::Some(341u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::suggest"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("suggest_accessing_field_where_appropriate(cause={0:?}, exp_found={1:?})",
cause, exp_found) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
342 "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
343 cause, exp_found
344 );
345 if let ty::Adt(expected_def, expected_args) = exp_found.expected.kind() {
346 if expected_def.is_enum() {
347 return;
348 }
349
350 if let Some((name, ty)) = expected_def
351 .non_enum_variant()
352 .fields
353 .iter()
354 .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
355 .map(|field| (field.name, field.ty(self.tcx, *expected_args).skip_norm_wip()))
356 .find(|(_, ty)| self.same_type_modulo_infer(*ty, exp_found.found))
357 && let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code()
358 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
359 {
360 let suggestion = if expected_def.is_struct() {
361 SuggestAccessingField::Safe { span, snippet, name, ty }
362 } else if expected_def.is_union() {
363 SuggestAccessingField::Unsafe { span, snippet, name, ty }
364 } else {
365 return;
366 };
367 diag.subdiagnostic(suggestion);
368 }
369 }
370 }
371
372 pub(super) fn suggest_turning_stmt_into_expr(
373 &self,
374 cause: &ObligationCause<'tcx>,
375 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
376 diag: &mut Diag<'_>,
377 ) {
378 let ty::error::ExpectedFound { expected, found } = exp_found;
379 if !found.peel_refs().is_unit() {
380 return;
381 }
382
383 let ObligationCauseCode::BlockTailExpression(hir_id, MatchSource::Normal) = cause.code()
384 else {
385 return;
386 };
387
388 let node = self.tcx.hir_node(*hir_id);
389 let mut blocks = ::alloc::vec::Vec::new()vec![];
390 if let hir::Node::Block(block) = node
391 && let Some(expr) = block.expr
392 && let hir::ExprKind::Path(QPath::Resolved(_, Path { res, .. })) = expr.kind
393 && let Res::Local(local) = res
394 && let Node::LetStmt(LetStmt { init: Some(init), .. }) =
395 self.tcx.parent_hir_node(*local)
396 {
397 fn collect_blocks<'hir>(expr: &hir::Expr<'hir>, blocks: &mut Vec<&hir::Block<'hir>>) {
398 match expr.kind {
399 hir::ExprKind::If(_, blk1, Some(blk2)) => {
401 collect_blocks(blk1, blocks);
402 collect_blocks(blk2, blocks);
403 }
404 hir::ExprKind::Match(_, arms, _) => {
405 for arm in arms.iter() {
407 collect_blocks(arm.body, blocks);
408 }
409 }
410 hir::ExprKind::Block(blk, _) => {
411 blocks.push(blk);
412 }
413 _ => {}
414 }
415 }
416 collect_blocks(init, &mut blocks);
417 }
418
419 let expected_inner: Ty<'_> = expected.peel_refs();
420 for block in blocks.iter() {
421 self.consider_removing_semicolon(block, expected_inner, diag);
422 }
423 }
424
425 pub fn consider_removing_semicolon(
437 &self,
438 blk: &'tcx hir::Block<'tcx>,
439 expected_ty: Ty<'tcx>,
440 diag: &mut Diag<'_>,
441 ) -> bool {
442 if let Some((span_semi, boxed)) = self.could_remove_semicolon(blk, expected_ty) {
443 if let StatementAsExpression::NeedsBoxing = boxed {
444 diag.span_suggestion_verbose(
445 span_semi,
446 "consider removing this semicolon and boxing the expression",
447 "",
448 Applicability::HasPlaceholders,
449 );
450 } else {
451 diag.span_suggestion_short(
452 span_semi,
453 "remove this semicolon to return this value",
454 "",
455 Applicability::MachineApplicable,
456 );
457 }
458 true
459 } else {
460 false
461 }
462 }
463
464 pub(crate) fn suggest_function_pointers_impl(
465 &self,
466 span: Option<Span>,
467 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
468 diag: &mut Diag<'_>,
469 ) {
470 let ty::error::ExpectedFound { expected, found } = exp_found;
471 let expected_inner = expected.peel_refs();
472 let found_inner = found.peel_refs();
473 if !expected_inner.is_fn() || !found_inner.is_fn() {
474 return;
475 }
476 match (expected_inner.kind(), found_inner.kind()) {
477 (ty::FnPtr(sig_tys, hdr), ty::FnDef(did, args)) => {
478 let args = args.no_bound_vars().unwrap();
479
480 let sig = sig_tys.with(*hdr);
481 let expected_sig = self.normalize_fn_sig(Unnormalized::new_wip(sig));
482 let found_sig =
483 self.normalize_fn_sig(self.tcx.fn_sig(*did).instantiate(self.tcx, args));
484
485 let fn_name = self.tcx.def_path_str_with_args(*did, args);
486
487 if !self.same_type_modulo_infer(found_sig, expected_sig)
488 || !sig.is_suggestable(self.tcx, true)
489 || self.tcx.intrinsic(*did).is_some()
490 {
491 return;
492 }
493
494 let Some(span) = span else {
495 let casting = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} as {1}", fn_name, sig))
})format!("{fn_name} as {sig}");
496 diag.subdiagnostic(FnItemsAreDistinct);
497 diag.subdiagnostic(FnConsiderCasting { casting });
498 return;
499 };
500
501 let sugg = match (expected.is_ref(), found.is_ref()) {
502 (true, false) => {
503 FunctionPointerSuggestion::UseRef { span: span.shrink_to_lo() }
504 }
505 (false, true) => FunctionPointerSuggestion::RemoveRef { span, fn_name },
506 (true, true) => {
507 diag.subdiagnostic(FnItemsAreDistinct);
508 FunctionPointerSuggestion::CastRef { span, fn_name, sig }
509 }
510 (false, false) => {
511 diag.subdiagnostic(FnItemsAreDistinct);
512 FunctionPointerSuggestion::Cast { span: span.shrink_to_hi(), sig }
513 }
514 };
515 diag.subdiagnostic(sugg);
516 }
517 (ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => {
518 let args1 = args1.no_bound_vars().unwrap();
519 let args2 = args2.no_bound_vars().unwrap();
520
521 let expected_sig =
522 self.normalize_fn_sig(self.tcx.fn_sig(*did1).instantiate(self.tcx, args1));
523 let found_sig =
524 self.normalize_fn_sig(self.tcx.fn_sig(*did2).instantiate(self.tcx, args2));
525
526 let expected_sig_anon = self.tcx.anonymize_bound_vars(expected_sig);
527 let found_sig_anon = self.tcx.anonymize_bound_vars(found_sig);
528 if self.same_type_modulo_infer(expected_sig_anon, found_sig_anon) {
529 diag.subdiagnostic(FnUniqTypes);
530 }
531
532 if !self.same_type_modulo_infer(found_sig, expected_sig)
533 || !found_sig.is_suggestable(self.tcx, true)
534 || !expected_sig.is_suggestable(self.tcx, true)
535 || self.tcx.intrinsic(*did1).is_some()
536 || self.tcx.intrinsic(*did2).is_some()
537 {
538 return;
539 }
540
541 let fn_name = self.tcx.def_path_str_with_args(*did2, args2);
542
543 let Some(span) = span else {
544 diag.subdiagnostic(FnConsiderCastingBoth { sig: expected_sig });
545 return;
546 };
547
548 let sug = if found.is_ref() {
549 FunctionPointerSuggestion::CastBothRef {
550 span,
551 fn_name,
552 found_sig,
553 expected_sig,
554 }
555 } else {
556 FunctionPointerSuggestion::CastBoth {
557 span: span.shrink_to_hi(),
558 found_sig,
559 expected_sig,
560 }
561 };
562
563 diag.subdiagnostic(sug);
564 }
565 (ty::FnDef(did, args), ty::FnPtr(sig_tys, hdr)) => {
566 let args = args.no_bound_vars().unwrap();
567
568 let expected_sig =
569 self.normalize_fn_sig(self.tcx.fn_sig(*did).instantiate(self.tcx, args));
570 let found_sig = self.normalize_fn_sig(Unnormalized::new_wip(sig_tys.with(*hdr)));
571
572 if !self.same_type_modulo_infer(found_sig, expected_sig) {
573 return;
574 }
575
576 let fn_name = self.tcx.def_path_str_with_args(*did, args);
577
578 let casting = if expected.is_ref() {
579 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&({0} as {1})", fn_name,
found_sig))
})format!("&({fn_name} as {found_sig})")
580 } else {
581 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} as {1}", fn_name, found_sig))
})format!("{fn_name} as {found_sig}")
582 };
583
584 diag.subdiagnostic(FnConsiderCasting { casting });
585 }
586 _ => {
587 return;
588 }
589 };
590 }
591
592 pub(super) fn suggest_function_pointers(
593 &self,
594 cause: &ObligationCause<'tcx>,
595 span: Span,
596 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
597 terr: TypeError<'tcx>,
598 diag: &mut Diag<'_>,
599 ) {
600 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs:600",
"rustc_trait_selection::error_reporting::infer::suggest",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs"),
::tracing_core::__macro_support::Option::Some(600u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::suggest"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("suggest_function_pointers(cause={0:?}, exp_found={1:?})",
cause, exp_found) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("suggest_function_pointers(cause={:?}, exp_found={:?})", cause, exp_found);
601
602 if exp_found.expected.peel_refs().is_fn() && exp_found.found.peel_refs().is_fn() {
603 self.suggest_function_pointers_impl(Some(span), exp_found, diag);
604 } else if let TypeError::Sorts(exp_found) = terr {
605 self.suggest_function_pointers_impl(None, &exp_found, diag);
606 }
607 }
608
609 fn should_suggest_as_ref_kind(
610 &self,
611 expected: Ty<'tcx>,
612 found: Ty<'tcx>,
613 ) -> Option<SuggestAsRefKind> {
614 if let (ty::Adt(exp_def, exp_args), ty::Ref(_, found_ty, _)) =
615 (expected.kind(), found.kind())
616 && let ty::Adt(found_def, found_args) = *found_ty.kind()
617 {
618 if exp_def == &found_def {
619 let have_as_ref = &[
620 (sym::Option, SuggestAsRefKind::Option),
621 (sym::Result, SuggestAsRefKind::Result),
622 ];
623 if let Some(msg) = have_as_ref.iter().find_map(|(name, msg)| {
624 self.tcx.is_diagnostic_item(*name, exp_def.did()).then_some(msg)
625 }) {
626 let mut show_suggestion = true;
627 for (exp_ty, found_ty) in std::iter::zip(exp_args.types(), found_args.types()) {
628 match *exp_ty.kind() {
629 ty::Ref(_, exp_ty, _) => {
630 match (exp_ty.kind(), found_ty.kind()) {
631 (_, ty::Param(_))
632 | (_, ty::Infer(_))
633 | (ty::Param(_), _)
634 | (ty::Infer(_), _) => {}
635 _ if self.same_type_modulo_infer(exp_ty, found_ty) => {}
636 _ => show_suggestion = false,
637 };
638 }
639 ty::Param(_) | ty::Infer(_) => {}
640 _ => show_suggestion = false,
641 }
642 }
643 if show_suggestion {
644 return Some(*msg);
645 }
646 }
647 }
648 }
649 None
650 }
651
652 pub fn should_suggest_as_ref(&self, expected: Ty<'tcx>, found: Ty<'tcx>) -> Option<&str> {
654 match self.should_suggest_as_ref_kind(expected, found) {
655 Some(SuggestAsRefKind::Option) => Some(
656 "you can convert from `&Option<T>` to `Option<&T>` using \
657 `.as_ref()`",
658 ),
659 Some(SuggestAsRefKind::Result) => Some(
660 "you can convert from `&Result<T, E>` to \
661 `Result<&T, &E>` using `.as_ref()`",
662 ),
663 None => None,
664 }
665 }
666 pub(super) fn suggest_let_for_letchains(
670 &self,
671 cause: &ObligationCause<'_>,
672 span: Span,
673 ) -> Option<TypeErrorAdditionalDiags> {
674 struct IfVisitor {
676 found_if: bool,
677 err_span: Span,
678 }
679
680 impl<'v> Visitor<'v> for IfVisitor {
681 type Result = ControlFlow<()>;
682 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
683 match ex.kind {
684 hir::ExprKind::If(cond, _, _) => {
685 self.found_if = true;
686 walk_expr(self, cond)?;
687 self.found_if = false;
688 ControlFlow::Continue(())
689 }
690 _ => walk_expr(self, ex),
691 }
692 }
693
694 fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) -> Self::Result {
695 if let hir::StmtKind::Let(LetStmt {
696 span,
697 pat: hir::Pat { .. },
698 ty: None,
699 init: Some(_),
700 ..
701 }) = &ex.kind
702 && self.found_if
703 && span.eq(&self.err_span)
704 {
705 ControlFlow::Break(())
706 } else {
707 walk_stmt(self, ex)
708 }
709 }
710 }
711
712 self.tcx.hir_maybe_body_owned_by(cause.body_def_id).and_then(|body| {
713 IfVisitor { err_span: span, found_if: false }
714 .visit_body(&body)
715 .is_break()
716 .then(|| TypeErrorAdditionalDiags::AddLetForLetChains { span: span.shrink_to_lo() })
717 })
718 }
719
720 pub(super) fn suggest_for_all_lifetime_closure(
723 &self,
724 span: Span,
725 hir: hir::Node<'_>,
726 exp_found: &ty::error::ExpectedFound<ty::TraitRef<'tcx>>,
727 diag: &mut Diag<'_>,
728 ) {
729 let hir::Node::Expr(hir::Expr {
731 kind: hir::ExprKind::Closure(hir::Closure { body, fn_decl, .. }),
732 ..
733 }) = hir
734 else {
735 return;
736 };
737 let hir::Body { params, .. } = self.tcx.hir_body(*body);
738
739 let Some(expected) = exp_found.expected.args.get(1) else {
742 return;
743 };
744 let Some(found) = exp_found.found.args.get(1) else {
745 return;
746 };
747 let expected = expected.kind();
748 let found = found.kind();
749 if let GenericArgKind::Type(expected) = expected
751 && let GenericArgKind::Type(found) = found
752 && let ty::Tuple(expected) = expected.kind()
753 && let ty::Tuple(found) = found.kind()
754 && expected.len() == found.len()
755 {
756 let mut suggestion = "|".to_string();
757 let mut is_first = true;
758 let mut has_suggestion = false;
759
760 for (((expected, found), param_hir), arg_hir) in
761 expected.iter().zip(found.iter()).zip(params.iter()).zip(fn_decl.inputs.iter())
762 {
763 if is_first {
764 is_first = false;
765 } else {
766 suggestion += ", ";
767 }
768
769 if let ty::Ref(expected_region, _, _) = expected.kind()
770 && let ty::Ref(found_region, _, _) = found.kind()
771 && expected_region.is_bound()
772 && !found_region.is_bound()
773 && let hir::TyKind::Infer(()) = arg_hir.kind
774 {
775 if param_hir.pat.span == param_hir.ty_span {
778 let Ok(pat) =
780 self.tcx.sess.source_map().span_to_snippet(param_hir.pat.span)
781 else {
782 return;
783 };
784 suggestion += &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: &_", pat))
})format!("{pat}: &_");
785 } else {
786 let Ok(pat) =
788 self.tcx.sess.source_map().span_to_snippet(param_hir.pat.span)
789 else {
790 return;
791 };
792 let Ok(ty) = self.tcx.sess.source_map().span_to_snippet(param_hir.ty_span)
793 else {
794 return;
795 };
796 suggestion += &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: &{1}", pat, ty))
})format!("{pat}: &{ty}");
797 }
798 has_suggestion = true;
799 } else {
800 let Ok(arg) = self.tcx.sess.source_map().span_to_snippet(param_hir.span) else {
801 return;
802 };
803 suggestion += &arg;
805 }
806 }
807 suggestion += "|";
808
809 if has_suggestion {
810 diag.span_suggestion_verbose(
811 span,
812 "consider specifying the type of the closure parameters",
813 suggestion,
814 Applicability::MaybeIncorrect,
815 );
816 }
817 }
818 }
819}
820
821impl<'tcx> TypeErrCtxt<'_, 'tcx> {
822 fn could_remove_semicolon(
825 &self,
826 blk: &'tcx hir::Block<'tcx>,
827 expected_ty: Ty<'tcx>,
828 ) -> Option<(Span, StatementAsExpression)> {
829 let blk = blk.innermost_block();
830 if blk.expr.is_some() {
832 return None;
833 }
834 let last_stmt = blk.stmts.last()?;
835 let hir::StmtKind::Semi(last_expr) = last_stmt.kind else {
836 return None;
837 };
838 let last_expr_ty = self.typeck_results.as_ref()?.expr_ty_opt(last_expr)?;
839 let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) {
840 _ if last_expr_ty.references_error() => return None,
841 _ if self.same_type_modulo_infer(last_expr_ty, expected_ty) => {
842 StatementAsExpression::CorrectType
843 }
844 (
845 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: last_def_id }, .. }),
846 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: exp_def_id }, .. }),
847 ) if last_def_id == exp_def_id => StatementAsExpression::CorrectType,
848 (
849 ty::Alias(
850 _,
851 ty::AliasTy {
852 kind: ty::Opaque { def_id: last_def_id }, args: last_bounds, ..
853 },
854 ),
855 ty::Alias(
856 _,
857 ty::AliasTy {
858 kind: ty::Opaque { def_id: exp_def_id }, args: exp_bounds, ..
859 },
860 ),
861 ) => {
862 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs:862",
"rustc_trait_selection::error_reporting::infer::suggest",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs"),
::tracing_core::__macro_support::Option::Some(862u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::suggest"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("both opaque, likely future {0:?} {1:?} {2:?} {3:?}",
last_def_id, last_bounds, exp_def_id, exp_bounds) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
863 "both opaque, likely future {:?} {:?} {:?} {:?}",
864 last_def_id, last_bounds, exp_def_id, exp_bounds
865 );
866
867 let last_local_id = last_def_id.as_local()?;
868 let exp_local_id = exp_def_id.as_local()?;
869
870 match (
871 &self.tcx.hir_expect_opaque_ty(last_local_id),
872 &self.tcx.hir_expect_opaque_ty(exp_local_id),
873 ) {
874 (
875 hir::OpaqueTy { bounds: last_bounds, .. },
876 hir::OpaqueTy { bounds: exp_bounds, .. },
877 ) if std::iter::zip(*last_bounds, *exp_bounds).all(|(left, right)| match (
878 left, right,
879 ) {
880 (hir::GenericBound::Trait(tl), hir::GenericBound::Trait(tr))
882 if tl.trait_ref.trait_def_id() == tr.trait_ref.trait_def_id()
883 && tl.modifiers == tr.modifiers =>
884 {
885 true
886 }
887 _ => false,
888 }) =>
889 {
890 StatementAsExpression::NeedsBoxing
891 }
892 _ => StatementAsExpression::CorrectType,
893 }
894 }
895 _ => return None,
896 };
897 let span = if last_stmt.span.from_expansion() {
898 let mac_call = rustc_span::source_map::original_sp(last_stmt.span, blk.span);
899 self.tcx.sess.source_map().mac_call_stmt_semi_span(mac_call)?
900 } else {
901 self.tcx
902 .sess
903 .source_map()
904 .span_extend_while_whitespace(last_expr.span)
905 .shrink_to_hi()
906 .with_hi(last_stmt.span.hi())
907 };
908
909 Some((span, needs_box))
910 }
911
912 fn consider_returning_binding_diag(
915 &self,
916 blk: &'tcx hir::Block<'tcx>,
917 expected_ty: Ty<'tcx>,
918 ) -> Option<SuggestRemoveSemiOrReturnBinding> {
919 let blk = blk.innermost_block();
920 if blk.expr.is_some() {
922 return None;
923 }
924 let mut shadowed = FxIndexSet::default();
925 let mut candidate_idents = ::alloc::vec::Vec::new()vec![];
926 let mut find_compatible_candidates = |pat: &hir::Pat<'_>| {
927 if let hir::PatKind::Binding(_, hir_id, ident, _) = &pat.kind
928 && let Some(pat_ty) = self
929 .typeck_results
930 .as_ref()
931 .and_then(|typeck_results| typeck_results.node_type_opt(*hir_id))
932 {
933 let pat_ty = self.deeply_resolve_ignoring_regions(pat_ty);
934 if self.same_type_modulo_infer(pat_ty, expected_ty)
935 && !(pat_ty, expected_ty).references_error()
936 && shadowed.insert(ident.name)
937 {
938 candidate_idents.push((*ident, pat_ty));
939 }
940 }
941 true
942 };
943
944 for stmt in blk.stmts.iter().rev() {
945 let hir::StmtKind::Let(local) = &stmt.kind else {
946 continue;
947 };
948 local.pat.walk(&mut find_compatible_candidates);
949 }
950 match self.tcx.parent_hir_node(blk.hir_id) {
951 hir::Node::Expr(hir::Expr { hir_id, .. }) => match self.tcx.parent_hir_node(*hir_id) {
952 hir::Node::Arm(hir::Arm { pat, .. }) => {
953 pat.walk(&mut find_compatible_candidates);
954 }
955
956 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { body, .. }, .. })
957 | hir::Node::ImplItem(hir::ImplItem {
958 kind: hir::ImplItemKind::Fn(_, body), ..
959 })
960 | hir::Node::TraitItem(hir::TraitItem {
961 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body)),
962 ..
963 })
964 | hir::Node::Expr(hir::Expr {
965 kind: hir::ExprKind::Closure(hir::Closure { body, .. }),
966 ..
967 }) => {
968 for param in self.tcx.hir_body(*body).params {
969 param.pat.walk(&mut find_compatible_candidates);
970 }
971 }
972 hir::Node::Expr(hir::Expr {
973 kind:
974 hir::ExprKind::If(
975 hir::Expr { kind: hir::ExprKind::Let(let_), .. },
976 then_block,
977 _,
978 ),
979 ..
980 }) if then_block.hir_id == *hir_id => {
981 let_.pat.walk(&mut find_compatible_candidates);
982 }
983 _ => {}
984 },
985 _ => {}
986 }
987
988 match &candidate_idents[..] {
989 [(ident, _ty)] => {
990 let sm = self.tcx.sess.source_map();
991 let (span, sugg) = if let Some(stmt) = blk.stmts.last() {
992 let stmt_span = sm.stmt_span(stmt.span, blk.span);
993 let sugg = if sm.is_multiline(blk.span)
994 && let Some(spacing) = sm.indentation_before(stmt_span)
995 {
996 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}{1}", spacing, ident))
})format!("\n{spacing}{ident}")
997 } else {
998 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", ident))
})format!(" {ident}")
999 };
1000 (stmt_span.shrink_to_hi(), sugg)
1001 } else {
1002 let sugg = if sm.is_multiline(blk.span)
1003 && let Some(spacing) = sm.indentation_before(blk.span.shrink_to_lo())
1004 {
1005 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0} {1}\n{0}", spacing,
ident))
})format!("\n{spacing} {ident}\n{spacing}")
1006 } else {
1007 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0} ", ident))
})format!(" {ident} ")
1008 };
1009 let left_span = sm.span_through_char(blk.span, '{').shrink_to_hi();
1010 (sm.span_extend_while_whitespace(left_span), sugg)
1011 };
1012 Some(SuggestRemoveSemiOrReturnBinding::Add { sp: span, code: sugg, ident: *ident })
1013 }
1014 values if (1..3).contains(&values.len()) => {
1015 let spans = values.iter().map(|(ident, _)| ident.span).collect::<Vec<_>>();
1016 Some(SuggestRemoveSemiOrReturnBinding::AddOne { spans: spans.into() })
1017 }
1018 _ => None,
1019 }
1020 }
1021
1022 pub fn consider_returning_binding(
1023 &self,
1024 blk: &'tcx hir::Block<'tcx>,
1025 expected_ty: Ty<'tcx>,
1026 err: &mut Diag<'_>,
1027 ) -> bool {
1028 let diag = self.consider_returning_binding_diag(blk, expected_ty);
1029 match diag {
1030 Some(diag) => {
1031 err.subdiagnostic(diag);
1032 true
1033 }
1034 None => false,
1035 }
1036 }
1037}