1use rustc_errors::{Applicability, Diag, MultiSpan, listify};
2use rustc_hir::def::Res;
3use rustc_hir::intravisit::Visitor;
4use rustc_hir::{self as hir, find_attr};
5use rustc_infer::infer::DefineOpaqueTypes;
6use rustc_middle::ty::adjustment::AllowTwoPhase;
7use rustc_middle::ty::error::{ExpectedFound, TypeError};
8use rustc_middle::ty::print::with_no_trimmed_paths;
9use rustc_middle::ty::{self, AssocItem, BottomUpFolder, Ty, TypeFoldable, TypeVisitableExt};
10use rustc_middle::{bug, span_bug};
11use rustc_span::{DUMMY_SP, Ident, Span, sym};
12use rustc_trait_selection::infer::InferCtxtExt;
13use rustc_trait_selection::traits::ObligationCause;
14use tracing::instrument;
15
16use super::method::probe;
17use crate::FnCtxt;
18
19impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
20 pub(crate) fn emit_type_mismatch_suggestions(
21 &self,
22 err: &mut Diag<'_>,
23 expr: &hir::Expr<'tcx>,
24 expr_ty: Ty<'tcx>,
25 expected: Ty<'tcx>,
26 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
27 error: Option<TypeError<'tcx>>,
28 ) {
29 if expr_ty == expected {
30 return;
31 }
32 self.annotate_alternative_method_deref(err, expr, error);
33 self.explain_self_literal(err, expr, expected, expr_ty);
34
35 let suggested = self.suggest_missing_parentheses(err, expr)
37 || self.suggest_missing_unwrap_expect(err, expr, expected, expr_ty)
38 || self.suggest_remove_last_method_call(err, expr, expected)
39 || self.suggest_associated_const(err, expr, expected)
40 || self.suggest_semicolon_in_repeat_expr(err, expr, expr_ty)
41 || self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr)
42 || self.suggest_option_to_bool(err, expr, expr_ty, expected)
43 || self.suggest_collect(err, expr, expected, expr_ty)
44 || self.suggest_compatible_variants(err, expr, expected, expr_ty)
45 || self.suggest_non_zero_new_unwrap(err, expr, expected, expr_ty)
46 || self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty)
47 || self.suggest_closure_to_fn_ptr_coercion(err, expr, expected, expr_ty)
48 || self.suggest_boxing_when_appropriate(
49 err,
50 expr.peel_blocks().span,
51 expr.hir_id,
52 expected,
53 expr_ty,
54 )
55 || self.suggest_block_to_brackets_peeling_refs(err, expr, expr_ty, expected)
56 || self.suggest_copied_cloned_or_as_ref(err, expr, expr_ty, expected)
57 || self.suggest_clone_for_ref(err, expr, expr_ty, expected)
58 || self.suggest_into(err, expr, expr_ty, expected)
59 || self.suggest_floating_point_literal(err, expr, expected)
60 || self.suggest_null_ptr_for_literal_zero_given_to_ptr_arg(err, expr, expected)
61 || self.suggest_coercing_result_via_try_operator(err, expr, expected, expr_ty)
62 || self.suggest_returning_value_after_loop(err, expr, expected);
63
64 if !suggested {
65 self.note_source_of_type_mismatch_constraint(
66 err,
67 expr,
68 TypeMismatchSource::Ty(expected),
69 );
70 }
71 }
72
73 pub(crate) fn emit_coerce_suggestions(
74 &self,
75 err: &mut Diag<'_>,
76 expr: &hir::Expr<'tcx>,
77 expr_ty: Ty<'tcx>,
78 expected: Ty<'tcx>,
79 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
80 error: Option<TypeError<'tcx>>,
81 ) {
82 if expr_ty == expected {
83 return;
84 }
85
86 self.annotate_expected_due_to_let_ty(err, expr, error);
87 self.annotate_loop_expected_due_to_inference(err, expr, error);
88 if self.annotate_mut_binding_to_immutable_binding(err, expr, expr_ty, expected, error) {
89 return;
90 }
91
92 if #[allow(non_exhaustive_omitted_patterns)] match error {
Some(TypeError::RegionsInsufficientlyPolymorphic(..)) => true,
_ => false,
}matches!(error, Some(TypeError::RegionsInsufficientlyPolymorphic(..))) {
96 return;
97 }
98
99 if self.is_destruct_assignment_desugaring(expr) {
100 return;
101 }
102 self.emit_type_mismatch_suggestions(err, expr, expr_ty, expected, expected_ty_expr, error);
103 self.note_type_is_not_clone(err, expected, expr_ty, expr);
104 self.note_internal_mutation_in_method(err, expr, Some(expected), expr_ty);
105 self.suggest_method_call_on_range_literal(err, expr, expr_ty, expected);
106 self.suggest_return_binding_for_missing_tail_expr(err, expr, expr_ty, expected);
107 self.note_wrong_return_ty_due_to_generic_arg(err, expr, expr_ty);
108 }
109
110 fn adjust_expr_for_assert_eq_macro(
113 &self,
114 found_expr: &mut &'tcx hir::Expr<'tcx>,
115 expected_expr: &mut Option<&'tcx hir::Expr<'tcx>>,
116 ) {
117 let Some(expected_expr) = expected_expr else {
118 return;
119 };
120
121 if !found_expr.span.eq_ctxt(expected_expr.span) {
122 return;
123 }
124
125 if !found_expr
126 .span
127 .ctxt()
128 .outer_expn_data()
129 .macro_def_id
130 .is_some_and(|def_id| self.tcx.is_diagnostic_item(sym::assert_eq_macro, def_id))
131 {
132 return;
133 }
134
135 let hir::ExprKind::Unary(
136 hir::UnOp::Deref,
137 hir::Expr { kind: hir::ExprKind::Path(found_path), .. },
138 ) = found_expr.kind
139 else {
140 return;
141 };
142 let hir::ExprKind::Unary(
143 hir::UnOp::Deref,
144 hir::Expr { kind: hir::ExprKind::Path(expected_path), .. },
145 ) = expected_expr.kind
146 else {
147 return;
148 };
149
150 for (path, name, idx, var) in [
151 (expected_path, "left_val", 0, expected_expr),
152 (found_path, "right_val", 1, found_expr),
153 ] {
154 if let hir::QPath::Resolved(_, path) = path
155 && let [segment] = path.segments
156 && segment.ident.name.as_str() == name
157 && let Res::Local(hir_id) = path.res
158 && let Some((_, hir::Node::Expr(match_expr))) =
159 self.tcx.hir_parent_iter(hir_id).nth(2)
160 && let hir::ExprKind::Match(scrutinee, _, _) = match_expr.kind
161 && let hir::ExprKind::Tup(exprs) = scrutinee.kind
162 && let hir::ExprKind::AddrOf(_, _, macro_arg) = exprs[idx].kind
163 {
164 *var = macro_arg;
165 }
166 }
167 }
168
169 pub(crate) fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
172 if let Err(e) = self.demand_suptype_diag(sp, expected, actual) {
173 e.emit();
174 }
175 }
176
177 pub(crate) fn demand_suptype_diag(
178 &'a self,
179 sp: Span,
180 expected: Ty<'tcx>,
181 actual: Ty<'tcx>,
182 ) -> Result<(), Diag<'a>> {
183 self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
184 }
185
186 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::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("demand_suptype_with_origin",
"rustc_hir_typeck::demand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/demand.rs"),
::tracing_core::__macro_support::Option::Some(186u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::demand"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cause")
}> =
::tracing::__macro_support::FieldName::new("cause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected")
}> =
::tracing::__macro_support::FieldName::new("expected");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("actual")
}> =
::tracing::__macro_support::FieldName::new("actual");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&actual)
as &dyn ::tracing::field::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: Result<(), Diag<'a>> = loop {};
return __tracing_attr_fake_return;
}
{
self.at(cause,
self.param_env).sup(DefineOpaqueTypes::Yes, expected,
actual).map(|infer_ok|
self.register_infer_ok_obligations(infer_ok)).map_err(|e|
{
self.err_ctxt().report_mismatched_types(cause,
self.param_env, expected, actual, e)
})
}
}
}#[instrument(skip(self), level = "debug")]
187 pub(crate) fn demand_suptype_with_origin(
188 &'a self,
189 cause: &ObligationCause<'tcx>,
190 expected: Ty<'tcx>,
191 actual: Ty<'tcx>,
192 ) -> Result<(), Diag<'a>> {
193 self.at(cause, self.param_env)
194 .sup(DefineOpaqueTypes::Yes, expected, actual)
195 .map(|infer_ok| self.register_infer_ok_obligations(infer_ok))
196 .map_err(|e| {
197 self.err_ctxt().report_mismatched_types(cause, self.param_env, expected, actual, e)
198 })
199 }
200
201 pub(crate) fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
202 if let Err(err) = self.demand_eqtype_diag(sp, expected, actual) {
203 err.emit();
204 }
205 }
206
207 pub(crate) fn demand_eqtype_diag(
208 &'a self,
209 sp: Span,
210 expected: Ty<'tcx>,
211 actual: Ty<'tcx>,
212 ) -> Result<(), Diag<'a>> {
213 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
214 }
215
216 pub(crate) fn demand_eqtype_with_origin(
217 &'a self,
218 cause: &ObligationCause<'tcx>,
219 expected: Ty<'tcx>,
220 actual: Ty<'tcx>,
221 ) -> Result<(), Diag<'a>> {
222 self.at(cause, self.param_env)
223 .eq(DefineOpaqueTypes::Yes, expected, actual)
224 .map(|infer_ok| self.register_infer_ok_obligations(infer_ok))
225 .map_err(|e| {
226 self.err_ctxt().report_mismatched_types(cause, self.param_env, expected, actual, e)
227 })
228 }
229
230 pub(crate) fn demand_coerce(
231 &self,
232 expr: &'tcx hir::Expr<'tcx>,
233 checked_ty: Ty<'tcx>,
234 expected: Ty<'tcx>,
235 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
236 allow_two_phase: AllowTwoPhase,
237 ) -> Ty<'tcx> {
238 match self.demand_coerce_diag(expr, checked_ty, expected, expected_ty_expr, allow_two_phase)
239 {
240 Ok(ty) => ty,
241 Err(err) => {
242 err.emit();
243 expected
247 }
248 }
249 }
250
251 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::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("demand_coerce_diag",
"rustc_hir_typeck::demand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_hir_typeck/src/demand.rs"),
::tracing_core::__macro_support::Option::Some(255u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::demand"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("checked_ty")
}> =
::tracing::__macro_support::FieldName::new("checked_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected")
}> =
::tracing::__macro_support::FieldName::new("expected");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&checked_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn ::tracing::field::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: Result<Ty<'tcx>, Diag<'a>> =
loop {};
return __tracing_attr_fake_return;
}
{
let expected =
self.deeply_resolve_ignoring_regions_with_obligations(expected);
let e =
match self.coerce(expr, checked_ty, expected, allow_two_phase,
None) {
Ok(ty) => return Ok(ty),
Err(e) => e,
};
self.adjust_expr_for_assert_eq_macro(&mut expr,
&mut expected_ty_expr);
self.set_tainted_by_errors(self.dcx().span_delayed_bug(expr.span,
"`TypeError` when attempting coercion but no error emitted"));
let expr = expr.peel_drop_temps();
let cause = self.misc(expr.span);
let expr_ty = self.deeply_resolve_ignoring_regions(checked_ty);
let mut err =
self.err_ctxt().report_mismatched_types(&cause,
self.param_env, expected, expr_ty, e);
self.emit_coerce_suggestions(&mut err, expr, expr_ty, expected,
expected_ty_expr, Some(e));
Err(err)
}
}
}#[instrument(level = "debug", skip(self, expr, expected_ty_expr, allow_two_phase))]
256 pub(crate) fn demand_coerce_diag(
257 &'a self,
258 mut expr: &'tcx hir::Expr<'tcx>,
259 checked_ty: Ty<'tcx>,
260 expected: Ty<'tcx>,
261 mut expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
262 allow_two_phase: AllowTwoPhase,
263 ) -> Result<Ty<'tcx>, Diag<'a>> {
264 let expected = self.deeply_resolve_ignoring_regions_with_obligations(expected);
265
266 let e = match self.coerce(expr, checked_ty, expected, allow_two_phase, None) {
267 Ok(ty) => return Ok(ty),
268 Err(e) => e,
269 };
270
271 self.adjust_expr_for_assert_eq_macro(&mut expr, &mut expected_ty_expr);
272
273 self.set_tainted_by_errors(self.dcx().span_delayed_bug(
274 expr.span,
275 "`TypeError` when attempting coercion but no error emitted",
276 ));
277 let expr = expr.peel_drop_temps();
278 let cause = self.misc(expr.span);
279 let expr_ty = self.deeply_resolve_ignoring_regions(checked_ty);
280 let mut err =
281 self.err_ctxt().report_mismatched_types(&cause, self.param_env, expected, expr_ty, e);
282
283 self.emit_coerce_suggestions(&mut err, expr, expr_ty, expected, expected_ty_expr, Some(e));
284
285 Err(err)
286 }
287
288 pub(crate) fn note_source_of_type_mismatch_constraint(
291 &self,
292 err: &mut Diag<'_>,
293 expr: &hir::Expr<'_>,
294 source: TypeMismatchSource<'tcx>,
295 ) -> bool {
296 let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind else {
297 return false;
298 };
299 let [hir::PathSegment { ident, args: None, .. }] = p.segments else {
300 return false;
301 };
302 let hir::def::Res::Local(local_hir_id) = p.res else {
303 return false;
304 };
305 let hir::Node::Pat(pat) = self.tcx.hir_node(local_hir_id) else {
306 return false;
307 };
308 let (init_ty_hir_id, init) = match self.tcx.parent_hir_node(pat.hir_id) {
309 hir::Node::LetStmt(hir::LetStmt { ty: Some(ty), init, .. }) => (ty.hir_id, *init),
310 hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) => (init.hir_id, Some(*init)),
311 _ => return false,
312 };
313 let Some(init_ty) = self.node_ty_opt(init_ty_hir_id) else {
314 return false;
315 };
316
317 struct FindExprs<'tcx> {
319 hir_id: hir::HirId,
320 uses: Vec<&'tcx hir::Expr<'tcx>>,
321 }
322 impl<'tcx> Visitor<'tcx> for FindExprs<'tcx> {
323 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
324 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = ex.kind
325 && let hir::def::Res::Local(hir_id) = path.res
326 && hir_id == self.hir_id
327 {
328 self.uses.push(ex);
329 }
330 hir::intravisit::walk_expr(self, ex);
331 }
332 }
333
334 let mut expr_finder = FindExprs { hir_id: local_hir_id, uses: init.into_iter().collect() };
335 let body = self.tcx.hir_body_owned_by(self.body_def_id);
336 expr_finder.visit_expr(body.value);
337
338 let mut fudger = BottomUpFolder {
340 tcx: self.tcx,
341 ty_op: |ty| {
342 if let ty::Infer(infer) = ty.kind() {
343 match infer {
344 ty::TyVar(_) => self.next_ty_var(DUMMY_SP),
345 ty::IntVar(_) => self.next_int_var(),
346 ty::FloatVar(_) => self.next_float_var(DUMMY_SP, None),
347 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => {
348 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected fresh ty outside of the trait solver"))bug!("unexpected fresh ty outside of the trait solver")
349 }
350 }
351 } else {
352 ty
353 }
354 },
355 lt_op: |_| self.tcx.lifetimes.re_erased,
356 ct_op: |ct| {
357 if let ty::ConstKind::Infer(_) = ct.kind() {
358 self.next_const_var(DUMMY_SP)
359 } else {
360 ct
361 }
362 },
363 };
364
365 let expected_ty = match source {
366 TypeMismatchSource::Ty(expected_ty) => expected_ty,
367 TypeMismatchSource::Arg { call_expr, incompatible_arg: idx } => {
374 let hir::ExprKind::MethodCall(segment, _, args, _) = call_expr.kind else {
375 return false;
376 };
377 let Some(arg_ty) = self.node_ty_opt(args[idx].hir_id) else {
378 return false;
379 };
380 let possible_rcvr_ty = expr_finder.uses.iter().rev().find_map(|binding| {
381 let possible_rcvr_ty = self.node_ty_opt(binding.hir_id)?;
382 if possible_rcvr_ty.is_ty_var() {
383 return None;
384 }
385 let possible_rcvr_ty = possible_rcvr_ty.fold_with(&mut fudger);
387 let method = self
388 .lookup_method_for_diagnostic(
389 possible_rcvr_ty,
390 segment,
391 DUMMY_SP,
392 call_expr,
393 binding,
394 )
395 .ok()?;
396 if Some(method.def_id)
398 != self.typeck_results.borrow().type_dependent_def_id(call_expr.hir_id)
399 {
400 return None;
401 }
402 let Some(input_arg) = method.sig.inputs().get(idx + 1) else {
406 if method.sig.splatted().is_some() {
407 return None;
409 } else {
410 ::rustc_middle::util::bug::span_bug_fmt(self.tcx.def_span(method.def_id),
format_args!("arg index {0} out of bounds for method with {1} inputs",
idx + 1, method.sig.inputs().len()));span_bug!(
411 self.tcx.def_span(method.def_id),
412 "arg index {} out of bounds for method with {} inputs",
413 idx + 1,
414 method.sig.inputs().len(),
415 );
416 }
417 };
418 let _ = self
419 .at(&ObligationCause::dummy(), self.param_env)
420 .eq(DefineOpaqueTypes::Yes, *input_arg, arg_ty)
421 .ok()?;
422 self.select_obligations_where_possible(|errs| {
423 errs.clear();
425 });
426 Some(self.deeply_resolve_ignoring_regions(possible_rcvr_ty))
427 });
428 let Some(rcvr_ty) = possible_rcvr_ty else { return false };
429 rcvr_ty
430 }
431 };
432
433 if !self.can_eq(self.param_env, expected_ty, init_ty.fold_with(&mut fudger)) {
436 return false;
437 }
438
439 for window in expr_finder.uses.windows(2) {
440 let [binding, next_usage] = *window else {
444 continue;
445 };
446
447 if binding.hir_id == expr.hir_id {
449 break;
450 }
451
452 let Some(next_use_ty) = self.node_ty_opt(next_usage.hir_id) else {
453 continue;
454 };
455
456 if self.can_eq(self.param_env, expected_ty, next_use_ty.fold_with(&mut fudger)) {
459 continue;
460 }
461
462 if let hir::Node::Expr(parent_expr) = self.tcx.parent_hir_node(binding.hir_id)
463 && let hir::ExprKind::MethodCall(segment, rcvr, args, _) = parent_expr.kind
464 && rcvr.hir_id == binding.hir_id
465 {
466 let Some(rcvr_ty) = self.node_ty_opt(rcvr.hir_id) else {
470 continue;
471 };
472 let rcvr_ty = rcvr_ty.fold_with(&mut fudger);
473 let Ok(method) = self.lookup_method_for_diagnostic(
474 rcvr_ty,
475 segment,
476 DUMMY_SP,
477 parent_expr,
478 rcvr,
479 ) else {
480 continue;
481 };
482 if Some(method.def_id)
484 != self.typeck_results.borrow().type_dependent_def_id(parent_expr.hir_id)
485 {
486 continue;
487 }
488
489 let ideal_rcvr_ty = rcvr_ty.fold_with(&mut fudger);
490 let ideal_method = self
491 .lookup_method_for_diagnostic(
492 ideal_rcvr_ty,
493 segment,
494 DUMMY_SP,
495 parent_expr,
496 rcvr,
497 )
498 .ok()
499 .and_then(|method| {
500 let _ = self
501 .at(&ObligationCause::dummy(), self.param_env)
502 .eq(DefineOpaqueTypes::Yes, ideal_rcvr_ty, expected_ty)
503 .ok()?;
504 Some(method)
505 });
506
507 for (idx, (expected_arg_ty, arg_expr)) in
510 std::iter::zip(&method.sig.inputs()[1..], args).enumerate()
511 {
512 let Some(arg_ty) = self.node_ty_opt(arg_expr.hir_id) else {
513 continue;
514 };
515 let arg_ty = arg_ty.fold_with(&mut fudger);
516 let _ =
517 self.coerce(arg_expr, arg_ty, *expected_arg_ty, AllowTwoPhase::No, None);
518 self.select_obligations_where_possible(|errs| {
519 errs.clear();
521 });
522 if self.can_eq(self.param_env, rcvr_ty, expected_ty) {
526 continue;
527 }
528 err.span_label(arg_expr.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this argument has type `{0}`...",
arg_ty))
})format!("this argument has type `{arg_ty}`..."));
529 err.span_label(
530 binding.span,
531 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("... which causes `{0}` to have type `{1}`",
ident, next_use_ty))
})format!("... which causes `{ident}` to have type `{next_use_ty}`"),
532 );
533 if #[allow(non_exhaustive_omitted_patterns)] match source {
TypeMismatchSource::Ty(_) => true,
_ => false,
}matches!(source, TypeMismatchSource::Ty(_))
542 && let Some(ideal_method) = ideal_method
543 && Some(ideal_method.def_id)
544 == self
545 .typeck_results
546 .borrow()
547 .type_dependent_def_id(parent_expr.hir_id)
548 && let ideal_arg_ty =
549 self.deeply_resolve_ignoring_regions(ideal_method.sig.inputs()[idx + 1])
550 && !ideal_arg_ty.has_non_region_infer()
551 {
552 self.emit_type_mismatch_suggestions(
553 err,
554 arg_expr,
555 arg_ty,
556 ideal_arg_ty,
557 None,
558 None,
559 );
560 }
561 return true;
562 }
563 }
564 err.span_label(
565 binding.span,
566 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("here the type of `{0}` is inferred to be `{1}`",
ident, next_use_ty))
})format!("here the type of `{ident}` is inferred to be `{next_use_ty}`"),
567 );
568 return true;
569 }
570
571 false
573 }
574
575 pub(crate) fn annotate_loop_expected_due_to_inference(
578 &self,
579 err: &mut Diag<'_>,
580 expr: &hir::Expr<'_>,
581 error: Option<TypeError<'tcx>>,
582 ) {
583 let Some(TypeError::Sorts(ExpectedFound { expected, .. })) = error else {
584 return;
585 };
586 let mut parent_id = self.tcx.parent_hir_id(expr.hir_id);
587 let mut parent;
588 'outer: loop {
589 let (hir::Node::Stmt(&hir::Stmt { kind: hir::StmtKind::Semi(p), .. })
591 | hir::Node::Block(&hir::Block { expr: Some(p), .. })
592 | hir::Node::Expr(p)) = self.tcx.hir_node(parent_id)
593 else {
594 break;
595 };
596 parent = p;
597 parent_id = self.tcx.parent_hir_id(parent_id);
598 let hir::ExprKind::Break(destination, _) = parent.kind else {
599 continue;
600 };
601 let mut parent_id = parent_id;
602 let mut direct = false;
603 loop {
604 let parent = match self.tcx.hir_node(parent_id) {
606 hir::Node::Expr(parent) => {
607 parent_id = self.tcx.parent_hir_id(parent.hir_id);
608 parent
609 }
610 hir::Node::Stmt(hir::Stmt {
611 hir_id,
612 kind: hir::StmtKind::Semi(parent) | hir::StmtKind::Expr(parent),
613 ..
614 }) => {
615 parent_id = self.tcx.parent_hir_id(*hir_id);
616 parent
617 }
618 hir::Node::Stmt(hir::Stmt { hir_id, kind: hir::StmtKind::Let(_), .. }) => {
619 parent_id = self.tcx.parent_hir_id(*hir_id);
620 parent
621 }
622 hir::Node::LetStmt(hir::LetStmt { hir_id, .. }) => {
623 parent_id = self.tcx.parent_hir_id(*hir_id);
624 parent
625 }
626 hir::Node::Block(_) => {
627 parent_id = self.tcx.parent_hir_id(parent_id);
628 parent
629 }
630 _ => break,
631 };
632 if let hir::ExprKind::Loop(..) = parent.kind {
633 direct = !direct;
636 }
637 if let hir::ExprKind::Loop(block, label, _, span) = parent.kind
638 && (destination.label == label || direct)
639 {
640 if let Some((reason_span, message)) =
641 self.maybe_get_coercion_reason(parent_id, parent.span)
642 {
643 err.span_label(reason_span, message);
644 err.span_label(
645 span,
646 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this loop is expected to be of type `{0}`",
expected))
})format!("this loop is expected to be of type `{expected}`"),
647 );
648 break 'outer;
649 } else {
650 struct FindBreaks<'tcx> {
653 label: Option<rustc_ast::Label>,
654 uses: Vec<&'tcx hir::Expr<'tcx>>,
655 nest_depth: usize,
656 }
657 impl<'tcx> Visitor<'tcx> for FindBreaks<'tcx> {
658 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
659 let nest_depth = self.nest_depth;
660 if let hir::ExprKind::Loop(_, label, _, _) = ex.kind {
661 if label == self.label {
662 return;
664 }
665 self.nest_depth += 1;
666 }
667 if let hir::ExprKind::Break(destination, _) = ex.kind
668 && (self.label == destination.label
669 || destination.label.is_none() && self.nest_depth == 0)
671 {
672 self.uses.push(ex);
673 }
674 hir::intravisit::walk_expr(self, ex);
675 self.nest_depth = nest_depth;
676 }
677 }
678 let mut expr_finder = FindBreaks { label, uses: ::alloc::vec::Vec::new()vec![], nest_depth: 0 };
679 expr_finder.visit_block(block);
680 let mut exit = false;
681 for ex in expr_finder.uses {
682 let hir::ExprKind::Break(_, val) = ex.kind else {
683 continue;
684 };
685 let ty = match val {
686 Some(val) => {
687 match self.typeck_results.borrow().expr_ty_adjusted_opt(val) {
688 None => continue,
689 Some(ty) => ty,
690 }
691 }
692 None => self.tcx.types.unit,
693 };
694 if self.can_eq(self.param_env, ty, expected) {
695 err.span_label(ex.span, "expected because of this `break`");
696 exit = true;
697 }
698 }
699 if exit {
700 break 'outer;
701 }
702 }
703 }
704 }
705 }
706 }
707
708 fn annotate_expected_due_to_let_ty(
709 &self,
710 err: &mut Diag<'_>,
711 expr: &hir::Expr<'_>,
712 error: Option<TypeError<'tcx>>,
713 ) {
714 let mut current_hir_id = expr.hir_id;
716 let parent = self
717 .tcx
718 .hir_parent_iter(expr.hir_id)
719 .find_map(|(parent_hir_id, parent)| match parent {
720 hir::Node::Block(block)
721 if block.expr.is_some_and(|expr| expr.hir_id == current_hir_id) =>
722 {
723 current_hir_id = parent_hir_id;
724 None
725 }
726 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Block(block, _), .. })
727 if block.hir_id == current_hir_id =>
728 {
729 current_hir_id = parent_hir_id;
730 None
731 }
732 parent => Some(parent),
733 })
734 .expect("an expression must have a non-block ancestor");
735
736 match (parent, error) {
737 (hir::Node::LetStmt(hir::LetStmt { ty: Some(ty), init: Some(init), .. }), _)
738 if init.hir_id == current_hir_id && !ty.span.source_equal(init.span) =>
739 {
740 err.span_label(ty.span, "expected due to this");
742 }
743 (
744 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Assign(lhs, rhs, _), .. }),
745 Some(TypeError::Sorts(ExpectedFound { expected, .. })),
746 ) if rhs.hir_id == expr.hir_id && !expected.is_closure() => {
747 let mut primary_span = lhs.span;
750 let mut secondary_span = lhs.span;
751 let mut post_message = "";
752 match lhs.kind {
753 hir::ExprKind::Path(hir::QPath::Resolved(
754 None,
755 hir::Path {
756 res:
757 hir::def::Res::Def(
758 hir::def::DefKind::Static { .. } | hir::def::DefKind::Const,
759 def_id,
760 ),
761 ..
762 },
763 )) => {
764 if let Some(hir::Node::Item(hir::Item {
765 kind:
766 hir::ItemKind::Static(_, ident, ty, _)
767 | hir::ItemKind::Const(ident, _, ty, _),
768 ..
769 })) = self.tcx.hir_get_if_local(*def_id)
770 {
771 primary_span = ty.span;
772 secondary_span = ident.span;
773 post_message = " type";
774 }
775 }
776 hir::ExprKind::Path(hir::QPath::Resolved(
777 None,
778 hir::Path { res: hir::def::Res::Local(hir_id), .. },
779 )) => {
780 if let hir::Node::Pat(pat) = self.tcx.hir_node(*hir_id) {
781 primary_span = pat.span;
782 secondary_span = pat.span;
783 match self.tcx.parent_hir_node(pat.hir_id) {
784 hir::Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
785 primary_span = ty.span;
786 post_message = " type";
787 }
788 hir::Node::LetStmt(hir::LetStmt { init: Some(init), .. }) => {
789 primary_span = init.span;
790 post_message = " value";
791 }
792 hir::Node::Param(hir::Param { ty_span, .. }) => {
793 primary_span = *ty_span;
794 post_message = " parameter type";
795 }
796 _ => {}
797 }
798 }
799 }
800 _ => {}
801 }
802
803 if primary_span != secondary_span
804 && self
805 .tcx
806 .sess
807 .source_map()
808 .is_multiline(secondary_span.shrink_to_hi().until(primary_span))
809 {
810 err.span_label(secondary_span, "expected due to the type of this binding");
813 err.span_label(primary_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected due to this{0}",
post_message))
})format!("expected due to this{post_message}"));
814 } else if post_message.is_empty() {
815 err.span_label(primary_span, "expected due to the type of this binding");
817 } else {
818 err.span_label(primary_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected due to this{0}",
post_message))
})format!("expected due to this{post_message}"));
820 }
821
822 if !lhs.is_syntactic_place_expr() {
823 err.downgrade_to_delayed_bug();
826 }
827 }
828 (
829 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(_, lhs, rhs), .. }),
830 Some(TypeError::Sorts(ExpectedFound { expected, .. })),
831 ) if rhs.hir_id == expr.hir_id
832 && self.typeck_results.borrow().expr_ty_adjusted_opt(lhs) == Some(expected)
833 && !#[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
hir::ExprKind::Let(..) => true,
_ => false,
}matches!(lhs.kind, hir::ExprKind::Let(..)) =>
835 {
836 err.span_label(lhs.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected because this is `{0}`",
expected))
})format!("expected because this is `{expected}`"));
837 }
838 _ => {}
839 }
840 }
841
842 fn annotate_mut_binding_to_immutable_binding(
861 &self,
862 err: &mut Diag<'_>,
863 expr: &hir::Expr<'_>,
864 expr_ty: Ty<'tcx>,
865 expected: Ty<'tcx>,
866 error: Option<TypeError<'tcx>>,
867 ) -> bool {
868 if let Some(TypeError::Sorts(ExpectedFound { .. })) = error
869 && let ty::Ref(_, inner, hir::Mutability::Not) = expected.kind()
870
871 && self.can_eq(self.param_env, *inner, expr_ty)
873
874 && let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Assign(lhs, rhs, _), .. }) =
876 self.tcx.parent_hir_node(expr.hir_id)
877 && rhs.hir_id == expr.hir_id
878
879 && let hir::ExprKind::Path(hir::QPath::Resolved(
881 None,
882 hir::Path { res: hir::def::Res::Local(hir_id), .. },
883 )) = lhs.kind
884 && let hir::Node::Pat(pat) = self.tcx.hir_node(*hir_id)
885
886 && let hir::Node::Param(hir::Param { ty_span, .. }) =
888 self.tcx.parent_hir_node(pat.hir_id)
889 && let item = self.tcx.hir_get_parent_item(pat.hir_id)
890 && let item = self.tcx.hir_owner_node(item)
891 && let Some(fn_decl) = item.fn_decl()
892
893 && let hir::PatKind::Binding(hir::BindingMode::MUT, _hir_id, ident, _) = pat.kind
895
896 && let Some(ty_ref) = fn_decl
898 .inputs
899 .iter()
900 .filter_map(|ty| match ty.kind {
901 hir::TyKind::Ref(lt, mut_ty) if ty.span == *ty_span => Some((lt, mut_ty)),
902 _ => None,
903 })
904 .next()
905 {
906 let mut sugg = if ty_ref.1.mutbl.is_mut() {
907 ::alloc::vec::Vec::new()vec![]
909 } else {
910 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ty_ref.1.ty.span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}mut ",
if ty_ref.0.ident.span.is_empty() { "" } else { " " }))
}))]))vec![(
912 ty_ref.1.ty.span.shrink_to_lo(),
913 format!("{}mut ", if ty_ref.0.ident.span.is_empty() { "" } else { " " },),
914 )]
915 };
916 sugg.extend([
917 (pat.span.until(ident.span), String::new()),
918 (lhs.span.shrink_to_lo(), "*".to_string()),
919 ]);
920 err.multipart_suggestion(
923 "you might have meant to mutate the pointed at value being passed in, instead of \
924 changing the reference in the local binding",
925 sugg,
926 Applicability::MaybeIncorrect,
927 );
928 return true;
929 }
930 false
931 }
932
933 fn annotate_alternative_method_deref(
934 &self,
935 err: &mut Diag<'_>,
936 expr: &hir::Expr<'_>,
937 error: Option<TypeError<'tcx>>,
938 ) {
939 let Some(TypeError::Sorts(ExpectedFound { expected, .. })) = error else {
940 return;
941 };
942 let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Assign(lhs, rhs, _), .. }) =
943 self.tcx.parent_hir_node(expr.hir_id)
944 else {
945 return;
946 };
947 if rhs.hir_id != expr.hir_id || expected.is_closure() {
948 return;
949 }
950 let hir::ExprKind::Unary(hir::UnOp::Deref, deref) = lhs.kind else {
951 return;
952 };
953 let hir::ExprKind::MethodCall(path, base, args, _) = deref.kind else {
954 return;
955 };
956 let Some(self_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(base) else {
957 return;
958 };
959
960 let Ok(pick) = self.lookup_probe_for_diagnostic(
961 path.ident,
962 self_ty,
963 deref,
964 probe::ProbeScope::TraitsInScope,
965 None,
966 ) else {
967 return;
968 };
969
970 let Ok(in_scope_methods) = self.probe_for_name_many(
971 probe::Mode::MethodCall,
972 path.ident,
973 Some(expected),
974 probe::IsSuggestion(true),
975 self_ty,
976 deref.hir_id,
977 probe::ProbeScope::TraitsInScope,
978 ) else {
979 return;
980 };
981
982 let other_methods_in_scope: Vec<_> =
983 in_scope_methods.iter().filter(|c| c.item.def_id != pick.item.def_id).collect();
984
985 let Ok(all_methods) = self.probe_for_name_many(
986 probe::Mode::MethodCall,
987 path.ident,
988 Some(expected),
989 probe::IsSuggestion(true),
990 self_ty,
991 deref.hir_id,
992 probe::ProbeScope::AllTraits,
993 ) else {
994 return;
995 };
996
997 let suggestions: Vec<_> = all_methods
998 .into_iter()
999 .filter(|c| c.item.def_id != pick.item.def_id)
1000 .map(|c| {
1001 let m = c.item;
1002 let generic_args = ty::GenericArgs::for_item(self.tcx, m.def_id, |param, _| {
1003 self.var_for_def(deref.span, param)
1004 });
1005 let mutability =
1006 match self.tcx.fn_sig(m.def_id).skip_binder().input(0).skip_binder().kind() {
1007 ty::Ref(_, _, hir::Mutability::Mut) => "&mut ",
1008 ty::Ref(_, _, _) => "&",
1009 _ => "",
1010 };
1011 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(deref.span.until(base.span),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}({1}",
{
let _guard = NoTrimmedGuard::new();
self.tcx.def_path_str_with_args(m.def_id, generic_args)
}, mutability))
})),
match &args {
[] =>
(base.span.shrink_to_hi().with_hi(deref.span.hi()),
")".to_string()),
[first, ..] =>
(base.span.between(first.span), ", ".to_string()),
}]))vec![
1012 (
1013 deref.span.until(base.span),
1014 format!(
1015 "{}({}",
1016 with_no_trimmed_paths!(
1017 self.tcx.def_path_str_with_args(m.def_id, generic_args,)
1018 ),
1019 mutability,
1020 ),
1021 ),
1022 match &args {
1023 [] => (base.span.shrink_to_hi().with_hi(deref.span.hi()), ")".to_string()),
1024 [first, ..] => (base.span.between(first.span), ", ".to_string()),
1025 },
1026 ]
1027 })
1028 .collect();
1029 if suggestions.is_empty() {
1030 return;
1031 }
1032 let mut path_span: MultiSpan = path.ident.span.into();
1033 path_span.push_span_label(
1034 path.ident.span,
1035 {
let _guard = NoTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("refers to `{0}`",
self.tcx.def_path_str(pick.item.def_id)))
})
}with_no_trimmed_paths!(format!(
1036 "refers to `{}`",
1037 self.tcx.def_path_str(pick.item.def_id),
1038 )),
1039 );
1040 let container_id = pick.item.container_id(self.tcx);
1041 let container = { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(container_id) }with_no_trimmed_paths!(self.tcx.def_path_str(container_id));
1042 for &def_id in pick.import_ids {
1043 let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
1044 path_span
1045 .push_span_label(self.tcx.hir_span(hir_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` imported here", container))
})format!("`{container}` imported here"));
1046 }
1047 let tail = {
let _guard = NoTrimmedGuard::new();
match &other_methods_in_scope[..] {
[] => return,
[candidate] =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the method of the same name on {0} `{1}`",
match candidate.kind {
probe::CandidateKind::InherentImplCandidate { .. } =>
"the inherent impl for",
_ => "trait",
},
self.tcx.def_path_str(candidate.item.container_id(self.tcx))))
}),
_ if other_methods_in_scope.len() < 5 => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the methods of the same name on {0}",
listify(&other_methods_in_scope[..other_methods_in_scope.len()
- 1],
|c|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.def_path_str(c.item.container_id(self.tcx))))
})).unwrap_or_default()))
})
}
_ =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the methods of the same name on {0} other traits",
other_methods_in_scope.len()))
}),
}
}with_no_trimmed_paths!(match &other_methods_in_scope[..] {
1048 [] => return,
1049 [candidate] => format!(
1050 "the method of the same name on {} `{}`",
1051 match candidate.kind {
1052 probe::CandidateKind::InherentImplCandidate { .. } => "the inherent impl for",
1053 _ => "trait",
1054 },
1055 self.tcx.def_path_str(candidate.item.container_id(self.tcx))
1056 ),
1057 _ if other_methods_in_scope.len() < 5 => {
1058 format!(
1059 "the methods of the same name on {}",
1060 listify(
1061 &other_methods_in_scope[..other_methods_in_scope.len() - 1],
1062 |c| format!("`{}`", self.tcx.def_path_str(c.item.container_id(self.tcx)))
1063 )
1064 .unwrap_or_default(),
1065 )
1066 }
1067 _ => format!(
1068 "the methods of the same name on {} other traits",
1069 other_methods_in_scope.len()
1070 ),
1071 });
1072 err.span_note(
1073 path_span,
1074 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the `{0}` call is resolved to the method in `{1}`, shadowing {2}",
path.ident, container, tail))
})format!(
1075 "the `{}` call is resolved to the method in `{container}`, shadowing {tail}",
1076 path.ident,
1077 ),
1078 );
1079 if suggestions.len() > other_methods_in_scope.len() {
1080 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("additionally, there are {0} other available methods that aren\'t in scope",
suggestions.len() - other_methods_in_scope.len()))
})format!(
1081 "additionally, there are {} other available methods that aren't in scope",
1082 suggestions.len() - other_methods_in_scope.len()
1083 ));
1084 }
1085 err.multipart_suggestions(
1086 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to call {0}; you can use the fully-qualified path to call {1} explicitly",
if suggestions.len() == 1 {
"the other method"
} else { "one of the other methods" },
if suggestions.len() == 1 { "it" } else { "one of them" }))
})format!(
1087 "you might have meant to call {}; you can use the fully-qualified path to call {} \
1088 explicitly",
1089 if suggestions.len() == 1 {
1090 "the other method"
1091 } else {
1092 "one of the other methods"
1093 },
1094 if suggestions.len() == 1 { "it" } else { "one of them" },
1095 ),
1096 suggestions,
1097 Applicability::MaybeIncorrect,
1098 );
1099 }
1100
1101 pub(crate) fn get_conversion_methods_for_diagnostic(
1102 &self,
1103 span: Span,
1104 expected: Ty<'tcx>,
1105 checked_ty: Ty<'tcx>,
1106 hir_id: hir::HirId,
1107 ) -> Vec<AssocItem> {
1108 let methods = self.probe_for_return_type_for_diagnostic(
1109 span,
1110 probe::Mode::MethodCall,
1111 expected,
1112 checked_ty,
1113 hir_id,
1114 |m| {
1115 self.has_only_self_parameter(m)
1116 && {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(m.def_id, &self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcConversionSuggestion)
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, m.def_id, RustcConversionSuggestion)
1127 },
1128 );
1129
1130 methods
1131 }
1132
1133 fn has_only_self_parameter(&self, method: &AssocItem) -> bool {
1135 method.is_method()
1136 && self.tcx.fn_sig(method.def_id).skip_binder().inputs().skip_binder().len() == 1
1137 }
1138
1139 pub(crate) fn maybe_get_block_expr(
1141 &self,
1142 expr: &hir::Expr<'tcx>,
1143 ) -> Option<&'tcx hir::Expr<'tcx>> {
1144 match expr {
1145 hir::Expr { kind: hir::ExprKind::Block(block, ..), .. } => block.expr,
1146 _ => None,
1147 }
1148 }
1149
1150 pub(crate) fn is_destruct_assignment_desugaring(&self, expr: &hir::Expr<'_>) -> bool {
1155 if let hir::ExprKind::Path(hir::QPath::Resolved(
1156 _,
1157 hir::Path { res: hir::def::Res::Local(bind_hir_id), .. },
1158 )) = expr.kind
1159 && let bind = self.tcx.hir_node(*bind_hir_id)
1160 && let parent = self.tcx.parent_hir_node(*bind_hir_id)
1161 && let hir::Node::Pat(hir::Pat {
1162 kind: hir::PatKind::Binding(_, _hir_id, _, _), ..
1163 }) = bind
1164 && let hir::Node::Pat(hir::Pat { default_binding_modes: false, .. }) = parent
1165 {
1166 true
1167 } else {
1168 false
1169 }
1170 }
1171
1172 fn explain_self_literal(
1173 &self,
1174 err: &mut Diag<'_>,
1175 expr: &hir::Expr<'tcx>,
1176 expected: Ty<'tcx>,
1177 found: Ty<'tcx>,
1178 ) {
1179 match expr.peel_drop_temps().kind {
1180 hir::ExprKind::Struct(
1181 hir::QPath::Resolved(
1182 None,
1183 hir::Path { res: hir::def::Res::SelfTyAlias { alias_to, .. }, span, .. },
1184 ),
1185 ..,
1186 )
1187 | hir::ExprKind::Call(
1188 hir::Expr {
1189 kind:
1190 hir::ExprKind::Path(hir::QPath::Resolved(
1191 None,
1192 hir::Path {
1193 res: hir::def::Res::SelfTyAlias { alias_to, .. },
1194 span,
1195 ..
1196 },
1197 )),
1198 ..
1199 },
1200 ..,
1201 ) => {
1202 if let Some(hir::Node::Item(hir::Item {
1203 kind: hir::ItemKind::Impl(hir::Impl { self_ty, .. }),
1204 ..
1205 })) = self.tcx.hir_get_if_local(*alias_to)
1206 {
1207 err.span_label(self_ty.span, "this is the type of the `Self` literal");
1208 }
1209 if let ty::Adt(e_def, e_args) = expected.kind()
1210 && let ty::Adt(f_def, _f_args) = found.kind()
1211 && e_def == f_def
1212 {
1213 err.span_suggestion_verbose(
1214 *span,
1215 "use the type name directly",
1216 self.tcx.value_path_str_with_args(e_def.did(), e_args),
1217 Applicability::MaybeIncorrect,
1218 );
1219 }
1220 }
1221 _ => {}
1222 }
1223 }
1224
1225 fn note_wrong_return_ty_due_to_generic_arg(
1226 &self,
1227 err: &mut Diag<'_>,
1228 expr: &hir::Expr<'_>,
1229 checked_ty: Ty<'tcx>,
1230 ) {
1231 let hir::Node::Expr(parent_expr) = self.tcx.parent_hir_node(expr.hir_id) else {
1232 return;
1233 };
1234 if parent_expr.span.desugaring_kind().is_some() {
1235 return;
1236 }
1237 enum CallableKind {
1238 Function,
1239 Method,
1240 Constructor,
1241 }
1242 let mut maybe_emit_help = |def_id: hir::def_id::DefId,
1243 callable: Ident,
1244 args: &[hir::Expr<'_>],
1245 kind: CallableKind| {
1246 let arg_idx = args.iter().position(|a| a.hir_id == expr.hir_id).unwrap();
1247 let fn_ty = self.tcx.type_of(def_id).skip_binder();
1248 if !fn_ty.is_fn() {
1249 return;
1250 }
1251 let fn_sig = fn_ty.fn_sig(self.tcx).skip_binder();
1252 let Some(&arg) = fn_sig
1253 .inputs()
1254 .get(arg_idx + if #[allow(non_exhaustive_omitted_patterns)] match kind {
CallableKind::Method => true,
_ => false,
}matches!(kind, CallableKind::Method) { 1 } else { 0 })
1255 else {
1256 return;
1257 };
1258 if #[allow(non_exhaustive_omitted_patterns)] match arg.kind() {
ty::Param(_) => true,
_ => false,
}matches!(arg.kind(), ty::Param(_))
1259 && fn_sig.output().contains(arg)
1260 && self.node_ty(args[arg_idx].hir_id) == checked_ty
1261 {
1262 let mut multi_span: MultiSpan = parent_expr.span.into();
1263 multi_span.push_span_label(
1264 args[arg_idx].span,
1265 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this argument influences the {0} of `{1}`",
if #[allow(non_exhaustive_omitted_patterns)] match kind {
CallableKind::Constructor => true,
_ => false,
} {
"type"
} else { "return type" }, callable))
})format!(
1266 "this argument influences the {} of `{}`",
1267 if matches!(kind, CallableKind::Constructor) {
1268 "type"
1269 } else {
1270 "return type"
1271 },
1272 callable
1273 ),
1274 );
1275 err.span_help(
1276 multi_span,
1277 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} `{1}` due to the type of the argument passed",
match kind {
CallableKind::Function => "return type of this call is",
CallableKind::Method => "return type of this call is",
CallableKind::Constructor => "type constructed contains",
}, checked_ty))
})format!(
1278 "the {} `{}` due to the type of the argument passed",
1279 match kind {
1280 CallableKind::Function => "return type of this call is",
1281 CallableKind::Method => "return type of this call is",
1282 CallableKind::Constructor => "type constructed contains",
1283 },
1284 checked_ty
1285 ),
1286 );
1287 }
1288 };
1289 match parent_expr.kind {
1290 hir::ExprKind::Call(fun, args) => {
1291 let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = fun.kind else {
1292 return;
1293 };
1294 let hir::def::Res::Def(kind, def_id) = path.res else {
1295 return;
1296 };
1297 let callable_kind = if #[allow(non_exhaustive_omitted_patterns)] match kind {
hir::def::DefKind::Ctor(_, _) => true,
_ => false,
}matches!(kind, hir::def::DefKind::Ctor(_, _)) {
1298 CallableKind::Constructor
1299 } else {
1300 CallableKind::Function
1301 };
1302 maybe_emit_help(def_id, path.segments.last().unwrap().ident, args, callable_kind);
1303 }
1304 hir::ExprKind::MethodCall(method, _receiver, args, _span) => {
1305 let Some(def_id) =
1306 self.typeck_results.borrow().type_dependent_def_id(parent_expr.hir_id)
1307 else {
1308 return;
1309 };
1310 maybe_emit_help(def_id, method.ident, args, CallableKind::Method)
1311 }
1312 _ => return,
1313 }
1314 }
1315}
1316
1317pub(crate) enum TypeMismatchSource<'tcx> {
1318 Ty(Ty<'tcx>),
1321 Arg { call_expr: &'tcx hir::Expr<'tcx>, incompatible_arg: usize },
1325}