1use core::ops::ControlFlow;
7use std::borrow::Cow;
8use std::path::PathBuf;
9
10use hir::Expr;
11use rustc_ast::ast::Mutability;
12use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
13use rustc_data_structures::sorted_map::SortedMap;
14use rustc_data_structures::unord::UnordSet;
15use rustc_errors::codes::*;
16use rustc_errors::{
17 Applicability, Diag, MultiSpan, StashKey, StringPart, listify, pluralize, struct_span_code_err,
18};
19use rustc_hir::attrs::diagnostic::CustomDiagnostic;
20use rustc_hir::def::{CtorKind, DefKind, Res};
21use rustc_hir::def_id::DefId;
22use rustc_hir::intravisit::{self, Visitor};
23use rustc_hir::lang_items::LangItem;
24use rustc_hir::{
25 self as hir, ExprKind, HirId, Node, PathSegment, QPath, find_attr, is_range_literal,
26};
27use rustc_infer::infer::{BoundRegionConversionTime, RegionVariableOrigin};
28use rustc_middle::bug;
29use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams, simplify_type};
30use rustc_middle::ty::print::{
31 PrintTraitRefExt as _, with_crate_prefix, with_forced_trimmed_paths,
32 with_no_visible_paths_if_doc_hidden,
33};
34use rustc_middle::ty::{self, GenericArgKind, IsSuggestable, Ty, TyCtxt, TypeVisitableExt};
35use rustc_span::def_id::DefIdSet;
36use rustc_span::{
37 DUMMY_SP, ErrorGuaranteed, ExpnKind, FileName, Ident, MacroKind, Span, Symbol, edit_distance,
38 kw, sym,
39};
40use rustc_trait_selection::error_reporting::traits::DefIdOrName;
41use rustc_trait_selection::infer::InferCtxtExt;
42use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
43use rustc_trait_selection::traits::{
44 FulfillmentError, Obligation, ObligationCauseCode, supertraits,
45};
46use tracing::{debug, info, instrument};
47
48use super::probe::{AutorefOrPtrAdjustment, IsSuggestion, Mode, ProbeScope};
49use super::{CandidateSource, MethodError, NoMatchData};
50use crate::errors::{self, CandidateTraitNote, NoAssociatedItem};
51use crate::expr_use_visitor::expr_place;
52use crate::method::probe::UnsatisfiedPredicates;
53use crate::{Expectation, FnCtxt};
54
55struct TraitBoundDuplicateTracker {
59 trait_def_ids: FxIndexSet<DefId>,
60 seen_ref: FxIndexSet<DefId>,
61 seen_non_ref: FxIndexSet<DefId>,
62 has_ref_dupes: bool,
63}
64
65impl TraitBoundDuplicateTracker {
66 fn new() -> Self {
67 Self {
68 trait_def_ids: FxIndexSet::default(),
69 seen_ref: FxIndexSet::default(),
70 seen_non_ref: FxIndexSet::default(),
71 has_ref_dupes: false,
72 }
73 }
74
75 fn track(&mut self, def_id: DefId, is_ref: bool) {
77 self.trait_def_ids.insert(def_id);
78 if is_ref {
79 if self.seen_non_ref.contains(&def_id) {
80 self.has_ref_dupes = true;
81 }
82 self.seen_ref.insert(def_id);
83 } else {
84 if self.seen_ref.contains(&def_id) {
85 self.has_ref_dupes = true;
86 }
87 self.seen_non_ref.insert(def_id);
88 }
89 }
90
91 fn has_ref_dupes(&self) -> bool {
92 self.has_ref_dupes
93 }
94
95 fn into_trait_def_ids(self) -> FxIndexSet<DefId> {
96 self.trait_def_ids
97 }
98}
99
100impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
101 fn is_slice_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
102 self.autoderef(span, ty)
103 .silence_errors()
104 .any(|(ty, _)| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Slice(..) | ty::Array(..) => true,
_ => false,
}matches!(ty.kind(), ty::Slice(..) | ty::Array(..)))
105 }
106
107 fn impl_into_iterator_should_be_iterator(
108 &self,
109 ty: Ty<'tcx>,
110 span: Span,
111 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
112 ) -> bool {
113 fn predicate_bounds_generic_param<'tcx>(
114 predicate: ty::Predicate<'_>,
115 generics: &'tcx ty::Generics,
116 generic_param: &ty::GenericParamDef,
117 tcx: TyCtxt<'tcx>,
118 ) -> bool {
119 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
120 predicate.kind().as_ref().skip_binder()
121 {
122 let ty::TraitPredicate { trait_ref: ty::TraitRef { args, .. }, .. } = trait_pred;
123 if args.is_empty() {
124 return false;
125 }
126 let Some(arg_ty) = args[0].as_type() else {
127 return false;
128 };
129 let ty::Param(param) = *arg_ty.kind() else {
130 return false;
131 };
132 generic_param.index == generics.type_param(param, tcx).index
134 } else {
135 false
136 }
137 }
138
139 let is_iterator_predicate = |predicate: ty::Predicate<'tcx>| -> bool {
140 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
141 predicate.kind().as_ref().skip_binder()
142 {
143 self.tcx.is_diagnostic_item(sym::Iterator, trait_pred.trait_ref.def_id)
144 && trait_pred.trait_ref.self_ty() == ty
146 } else {
147 false
148 }
149 };
150
151 let Some(into_iterator_trait) = self.tcx.get_diagnostic_item(sym::IntoIterator) else {
153 return false;
154 };
155 let trait_ref = ty::TraitRef::new(self.tcx, into_iterator_trait, [ty]);
156 let obligation = Obligation::new(self.tcx, self.misc(span), self.param_env, trait_ref);
157 if !self.predicate_must_hold_modulo_regions(&obligation) {
158 return false;
159 }
160
161 match *ty.peel_refs().kind() {
162 ty::Param(param) => {
163 let generics = self.tcx.generics_of(self.body_id);
164 let generic_param = generics.type_param(param, self.tcx);
165 for unsatisfied in unsatisfied_predicates.iter() {
166 if predicate_bounds_generic_param(
169 unsatisfied.0,
170 generics,
171 generic_param,
172 self.tcx,
173 ) && is_iterator_predicate(unsatisfied.0)
174 {
175 return true;
176 }
177 }
178 }
179 ty::Slice(..)
180 | ty::Adt(..)
181 | ty::Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
182 for unsatisfied in unsatisfied_predicates.iter() {
183 if is_iterator_predicate(unsatisfied.0) {
184 return true;
185 }
186 }
187 }
188 _ => return false,
189 }
190 false
191 }
192
193 fn preferred_iterator_method(
196 &self,
197 source: SelfSource<'tcx>,
198 rcvr_ty: Ty<'tcx>,
199 ) -> Option<Symbol> {
200 let SelfSource::MethodCall(rcvr_expr) = source else {
201 return Some(sym::into_iter);
202 };
203
204 let rcvr_expr = rcvr_expr.peel_drop_temps().peel_blocks();
205 let Ok(place_with_id) = expr_place(self, rcvr_expr) else {
206 return None;
207 };
208
209 let mut projection_mutability = None;
210 for pointer_ty in place_with_id.place.deref_tys() {
211 match self.structurally_resolve_type(rcvr_expr.span, pointer_ty).kind() {
212 ty::Ref(.., Mutability::Not) => {
213 projection_mutability = Some(Mutability::Not);
214 break;
215 }
216 ty::Ref(.., Mutability::Mut) => {
217 projection_mutability.get_or_insert(Mutability::Mut);
218 }
219 ty::RawPtr(..) => return None,
220 _ => {}
221 }
222 }
223
224 let Some(projection_mutability) = projection_mutability else {
227 return Some(sym::into_iter);
228 };
229
230 let call_expr = self.tcx.hir_expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id));
231 let has_method = |method_name| {
233 self.lookup_probe_for_diagnostic(
234 Ident::with_dummy_span(method_name),
235 rcvr_ty,
236 call_expr,
237 ProbeScope::TraitsInScope,
238 None,
239 )
240 .is_ok()
241 };
242
243 match projection_mutability {
244 Mutability::Not => has_method(sym::iter).then_some(sym::iter),
245 Mutability::Mut => {
246 if has_method(sym::iter_mut) {
247 Some(sym::iter_mut)
248 } else if has_method(sym::iter) {
249 Some(sym::iter)
250 } else {
251 None
252 }
253 }
254 }
255 }
256
257 #[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("report_method_error",
"rustc_hir_typeck::method::suggest",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/suggest.rs"),
::tracing_core::__macro_support::Option::Some(257u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::suggest"),
::tracing_core::field::FieldSet::new(&["call_id", "rcvr_ty",
"error", "expected", "trait_missing_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::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};
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(&call_id)
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(&rcvr_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(&error)
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(&trait_missing_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: ErrorGuaranteed = loop {};
return __tracing_attr_fake_return;
}
{
for &import_id in
self.tcx.in_scope_traits(call_id).into_iter().flatten().flat_map(|c|
c.import_ids) {
self.typeck_results.borrow_mut().used_trait_imports.insert(import_id);
}
let (span, expr_span, source, item_name, args) =
match self.tcx.hir_node(call_id) {
hir::Node::Expr(&hir::Expr {
kind: hir::ExprKind::MethodCall(segment, rcvr, args, _),
span, .. }) => {
(segment.ident.span, span, SelfSource::MethodCall(rcvr),
segment.ident, Some(args))
}
hir::Node::Expr(&hir::Expr {
kind: hir::ExprKind::Path(QPath::TypeRelative(rcvr,
segment)),
span, .. }) |
hir::Node::PatExpr(&hir::PatExpr {
kind: hir::PatExprKind::Path(QPath::TypeRelative(rcvr,
segment)),
span, .. }) |
hir::Node::Pat(&hir::Pat {
kind: hir::PatKind::Struct(QPath::TypeRelative(rcvr,
segment), ..) |
hir::PatKind::TupleStruct(QPath::TypeRelative(rcvr,
segment), ..),
span, .. }) => {
let args =
match self.tcx.parent_hir_node(call_id) {
hir::Node::Expr(&hir::Expr {
kind: hir::ExprKind::Call(callee, args), .. }) if
callee.hir_id == call_id => Some(args),
_ => None,
};
(segment.ident.span, span, SelfSource::QPath(rcvr),
segment.ident, args)
}
node => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{0:?}", node)));
}
};
let within_macro_span =
span.within_macro(expr_span, self.tcx.sess.source_map());
if let Err(guar) = rcvr_ty.error_reported() { return guar; }
match error {
MethodError::NoMatch(mut no_match_data) =>
self.report_no_match_method_error(span, rcvr_ty, item_name,
call_id, source, args, expr_span, &mut no_match_data,
expected, trait_missing_method, within_macro_span),
MethodError::Ambiguity(mut sources) => {
let mut err =
{
self.dcx().struct_span_err(item_name.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("multiple applicable items in scope"))
})).with_code(E0034)
};
err.span_label(item_name.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("multiple `{0}` found",
item_name))
}));
if let Some(within_macro_span) = within_macro_span {
err.span_label(within_macro_span,
"due to this macro variable");
}
self.note_candidates_on_method_error(rcvr_ty, item_name,
source, args, span, &mut err, &mut sources,
Some(expr_span));
err.emit()
}
MethodError::PrivateMatch(kind, def_id, out_of_scope_traits)
=> {
let kind = self.tcx.def_kind_descr(kind, def_id);
let mut err =
{
self.dcx().struct_span_err(item_name.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` is private",
kind, item_name))
})).with_code(E0624)
};
err.span_label(item_name.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("private {0}", kind))
}));
let sp =
self.tcx.hir_span_if_local(def_id).unwrap_or_else(||
self.tcx.def_span(def_id));
err.span_label(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("private {0} defined here",
kind))
}));
if let Some(within_macro_span) = within_macro_span {
err.span_label(within_macro_span,
"due to this macro variable");
}
self.suggest_valid_traits(&mut err, item_name,
out_of_scope_traits, true);
self.suggest_unwrapping_inner_self(&mut err, source,
rcvr_ty, item_name);
err.emit()
}
MethodError::IllegalSizedBound {
candidates, needs_mut, bound_span, self_expr } => {
let msg =
if needs_mut {
{
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the `{0}` method cannot be invoked on `{1}`",
item_name, rcvr_ty))
})
}
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the `{0}` method cannot be invoked on a trait object",
item_name))
})
};
let mut err = self.dcx().struct_span_err(span, msg);
if !needs_mut {
err.span_label(bound_span,
"this has a `Sized` requirement");
}
if let Some(within_macro_span) = within_macro_span {
err.span_label(within_macro_span,
"due to this macro variable");
}
if !candidates.is_empty() {
let help =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}other candidate{1} {2} found in the following trait{1}",
if candidates.len() == 1 { "an" } else { "" },
if candidates.len() == 1 { "" } else { "s" },
if candidates.len() == 1 { "was" } else { "were" }))
});
self.suggest_use_candidates(candidates,
|accessible_sugg, inaccessible_sugg, span|
{
let suggest_for_access =
|err: &mut Diag<'_>, mut msg: String, sugg: Vec<_>|
{
msg +=
&::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", perhaps add a `use` for {0}:",
if sugg.len() == 1 { "it" } else { "one_of_them" }))
});
err.span_suggestions(span, msg, sugg,
Applicability::MaybeIncorrect);
};
let suggest_for_privacy =
|err: &mut Diag<'_>, mut msg: String, suggs: Vec<String>|
{
if let [sugg] = suggs.as_slice() {
err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait `{0}` provides `{1}` is implemented but not reachable",
sugg.trim(), item_name))
}));
} else {
msg +=
&::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" but {0} not reachable",
if suggs.len() == 1 { "is" } else { "are" }))
});
err.span_suggestions(span, msg, suggs,
Applicability::MaybeIncorrect);
}
};
if accessible_sugg.is_empty() {
suggest_for_privacy(&mut err, help, inaccessible_sugg);
} else if inaccessible_sugg.is_empty() {
suggest_for_access(&mut err, help, accessible_sugg);
} else {
suggest_for_access(&mut err, help.clone(), accessible_sugg);
suggest_for_privacy(&mut err, help, inaccessible_sugg);
}
});
}
if let ty::Ref(region, t_type, mutability) = rcvr_ty.kind()
{
if needs_mut {
let trait_type =
Ty::new_ref(self.tcx, *region, *t_type,
mutability.invert());
let msg =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you need `{0}` instead of `{1}`",
trait_type, rcvr_ty))
});
let mut kind = &self_expr.kind;
while let hir::ExprKind::AddrOf(_, _, expr) |
hir::ExprKind::Unary(hir::UnOp::Deref, expr) = kind {
kind = &expr.kind;
}
if let hir::ExprKind::Path(hir::QPath::Resolved(None, path))
= kind && let hir::def::Res::Local(hir_id) = path.res &&
let hir::Node::Pat(b) = self.tcx.hir_node(hir_id) &&
let hir::Node::Param(p) = self.tcx.parent_hir_node(b.hir_id)
&&
let Some(decl) =
self.tcx.parent_hir_node(p.hir_id).fn_decl() &&
let Some(ty) =
decl.inputs.iter().find(|ty| ty.span == p.ty_span) &&
let hir::TyKind::Ref(_, mut_ty) = &ty.kind &&
let hir::Mutability::Not = mut_ty.mutbl {
err.span_suggestion_verbose(mut_ty.ty.span.shrink_to_lo(),
msg, "mut ", Applicability::MachineApplicable);
} else { err.help(msg); }
}
}
err.emit()
}
MethodError::ErrorReported(guar) => guar,
MethodError::BadReturnType =>
::rustc_middle::util::bug::bug_fmt(format_args!("no return type expectations but got BadReturnType")),
}
}
}
}#[instrument(level = "debug", skip(self))]
258 pub(crate) fn report_method_error(
259 &self,
260 call_id: HirId,
261 rcvr_ty: Ty<'tcx>,
262 error: MethodError<'tcx>,
263 expected: Expectation<'tcx>,
264 trait_missing_method: bool,
265 ) -> ErrorGuaranteed {
266 for &import_id in
269 self.tcx.in_scope_traits(call_id).into_iter().flatten().flat_map(|c| c.import_ids)
270 {
271 self.typeck_results.borrow_mut().used_trait_imports.insert(import_id);
272 }
273
274 let (span, expr_span, source, item_name, args) = match self.tcx.hir_node(call_id) {
275 hir::Node::Expr(&hir::Expr {
276 kind: hir::ExprKind::MethodCall(segment, rcvr, args, _),
277 span,
278 ..
279 }) => {
280 (segment.ident.span, span, SelfSource::MethodCall(rcvr), segment.ident, Some(args))
281 }
282 hir::Node::Expr(&hir::Expr {
283 kind: hir::ExprKind::Path(QPath::TypeRelative(rcvr, segment)),
284 span,
285 ..
286 })
287 | hir::Node::PatExpr(&hir::PatExpr {
288 kind: hir::PatExprKind::Path(QPath::TypeRelative(rcvr, segment)),
289 span,
290 ..
291 })
292 | hir::Node::Pat(&hir::Pat {
293 kind:
294 hir::PatKind::Struct(QPath::TypeRelative(rcvr, segment), ..)
295 | hir::PatKind::TupleStruct(QPath::TypeRelative(rcvr, segment), ..),
296 span,
297 ..
298 }) => {
299 let args = match self.tcx.parent_hir_node(call_id) {
300 hir::Node::Expr(&hir::Expr {
301 kind: hir::ExprKind::Call(callee, args), ..
302 }) if callee.hir_id == call_id => Some(args),
303 _ => None,
304 };
305 (segment.ident.span, span, SelfSource::QPath(rcvr), segment.ident, args)
306 }
307 node => unreachable!("{node:?}"),
308 };
309
310 let within_macro_span = span.within_macro(expr_span, self.tcx.sess.source_map());
313
314 if let Err(guar) = rcvr_ty.error_reported() {
316 return guar;
317 }
318
319 match error {
320 MethodError::NoMatch(mut no_match_data) => self.report_no_match_method_error(
321 span,
322 rcvr_ty,
323 item_name,
324 call_id,
325 source,
326 args,
327 expr_span,
328 &mut no_match_data,
329 expected,
330 trait_missing_method,
331 within_macro_span,
332 ),
333
334 MethodError::Ambiguity(mut sources) => {
335 let mut err = struct_span_code_err!(
336 self.dcx(),
337 item_name.span,
338 E0034,
339 "multiple applicable items in scope"
340 );
341 err.span_label(item_name.span, format!("multiple `{item_name}` found"));
342 if let Some(within_macro_span) = within_macro_span {
343 err.span_label(within_macro_span, "due to this macro variable");
344 }
345
346 self.note_candidates_on_method_error(
347 rcvr_ty,
348 item_name,
349 source,
350 args,
351 span,
352 &mut err,
353 &mut sources,
354 Some(expr_span),
355 );
356 err.emit()
357 }
358
359 MethodError::PrivateMatch(kind, def_id, out_of_scope_traits) => {
360 let kind = self.tcx.def_kind_descr(kind, def_id);
361 let mut err = struct_span_code_err!(
362 self.dcx(),
363 item_name.span,
364 E0624,
365 "{} `{}` is private",
366 kind,
367 item_name
368 );
369 err.span_label(item_name.span, format!("private {kind}"));
370 let sp =
371 self.tcx.hir_span_if_local(def_id).unwrap_or_else(|| self.tcx.def_span(def_id));
372 err.span_label(sp, format!("private {kind} defined here"));
373 if let Some(within_macro_span) = within_macro_span {
374 err.span_label(within_macro_span, "due to this macro variable");
375 }
376 self.suggest_valid_traits(&mut err, item_name, out_of_scope_traits, true);
377 self.suggest_unwrapping_inner_self(&mut err, source, rcvr_ty, item_name);
378 err.emit()
379 }
380
381 MethodError::IllegalSizedBound { candidates, needs_mut, bound_span, self_expr } => {
382 let msg = if needs_mut {
383 with_forced_trimmed_paths!(format!(
384 "the `{item_name}` method cannot be invoked on `{rcvr_ty}`"
385 ))
386 } else {
387 format!("the `{item_name}` method cannot be invoked on a trait object")
388 };
389 let mut err = self.dcx().struct_span_err(span, msg);
390 if !needs_mut {
391 err.span_label(bound_span, "this has a `Sized` requirement");
392 }
393 if let Some(within_macro_span) = within_macro_span {
394 err.span_label(within_macro_span, "due to this macro variable");
395 }
396 if !candidates.is_empty() {
397 let help = format!(
398 "{an}other candidate{s} {were} found in the following trait{s}",
399 an = if candidates.len() == 1 { "an" } else { "" },
400 s = pluralize!(candidates.len()),
401 were = pluralize!("was", candidates.len()),
402 );
403 self.suggest_use_candidates(
404 candidates,
405 |accessible_sugg, inaccessible_sugg, span| {
406 let suggest_for_access =
407 |err: &mut Diag<'_>, mut msg: String, sugg: Vec<_>| {
408 msg += &format!(
409 ", perhaps add a `use` for {one_of_them}:",
410 one_of_them =
411 if sugg.len() == 1 { "it" } else { "one_of_them" },
412 );
413 err.span_suggestions(
414 span,
415 msg,
416 sugg,
417 Applicability::MaybeIncorrect,
418 );
419 };
420 let suggest_for_privacy =
421 |err: &mut Diag<'_>, mut msg: String, suggs: Vec<String>| {
422 if let [sugg] = suggs.as_slice() {
423 err.help(format!("\
424 trait `{}` provides `{item_name}` is implemented but not reachable",
425 sugg.trim(),
426 ));
427 } else {
428 msg += &format!(" but {} not reachable", pluralize!("is", suggs.len()));
429 err.span_suggestions(
430 span,
431 msg,
432 suggs,
433 Applicability::MaybeIncorrect,
434 );
435 }
436 };
437 if accessible_sugg.is_empty() {
438 suggest_for_privacy(&mut err, help, inaccessible_sugg);
440 } else if inaccessible_sugg.is_empty() {
441 suggest_for_access(&mut err, help, accessible_sugg);
442 } else {
443 suggest_for_access(&mut err, help.clone(), accessible_sugg);
444 suggest_for_privacy(&mut err, help, inaccessible_sugg);
445 }
446 },
447 );
448 }
449 if let ty::Ref(region, t_type, mutability) = rcvr_ty.kind() {
450 if needs_mut {
451 let trait_type =
452 Ty::new_ref(self.tcx, *region, *t_type, mutability.invert());
453 let msg = format!("you need `{trait_type}` instead of `{rcvr_ty}`");
454 let mut kind = &self_expr.kind;
455 while let hir::ExprKind::AddrOf(_, _, expr)
456 | hir::ExprKind::Unary(hir::UnOp::Deref, expr) = kind
457 {
458 kind = &expr.kind;
459 }
460 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = kind
461 && let hir::def::Res::Local(hir_id) = path.res
462 && let hir::Node::Pat(b) = self.tcx.hir_node(hir_id)
463 && let hir::Node::Param(p) = self.tcx.parent_hir_node(b.hir_id)
464 && let Some(decl) = self.tcx.parent_hir_node(p.hir_id).fn_decl()
465 && let Some(ty) = decl.inputs.iter().find(|ty| ty.span == p.ty_span)
466 && let hir::TyKind::Ref(_, mut_ty) = &ty.kind
467 && let hir::Mutability::Not = mut_ty.mutbl
468 {
469 err.span_suggestion_verbose(
470 mut_ty.ty.span.shrink_to_lo(),
471 msg,
472 "mut ",
473 Applicability::MachineApplicable,
474 );
475 } else {
476 err.help(msg);
477 }
478 }
479 }
480 err.emit()
481 }
482
483 MethodError::ErrorReported(guar) => guar,
484
485 MethodError::BadReturnType => bug!("no return type expectations but got BadReturnType"),
486 }
487 }
488
489 fn create_missing_writer_err(
490 &self,
491 rcvr_ty: Ty<'tcx>,
492 rcvr_expr: &hir::Expr<'tcx>,
493 mut long_ty_path: Option<PathBuf>,
494 ) -> Diag<'_> {
495 let mut err = {
self.dcx().struct_span_err(rcvr_expr.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot write into `{0}`",
self.tcx.short_string(rcvr_ty, &mut long_ty_path)))
})).with_code(E0599)
}struct_span_code_err!(
496 self.dcx(),
497 rcvr_expr.span,
498 E0599,
499 "cannot write into `{}`",
500 self.tcx.short_string(rcvr_ty, &mut long_ty_path),
501 );
502 *err.long_ty_path() = long_ty_path;
503 err.span_note(
504 rcvr_expr.span,
505 "must implement `io::Write`, `fmt::Write`, or have a `write_fmt` method",
506 );
507 if let ExprKind::Lit(_) = rcvr_expr.kind {
508 err.span_help(
509 rcvr_expr.span.shrink_to_lo(),
510 "a writer is needed before this format string",
511 );
512 };
513 err
514 }
515
516 fn create_no_assoc_err(
517 &self,
518 rcvr_ty: Ty<'tcx>,
519 item_ident: Ident,
520 item_kind: &'static str,
521 trait_missing_method: bool,
522 source: SelfSource<'tcx>,
523 is_method: bool,
524 sugg_span: Span,
525 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
526 ) -> Diag<'_> {
527 let mut ty = rcvr_ty;
530 let span = item_ident.span;
531 if let ty::Adt(def, generics) = rcvr_ty.kind() {
532 if generics.len() > 0 {
533 let mut autoderef = self.autoderef(span, rcvr_ty).silence_errors();
534 let candidate_found = autoderef.any(|(ty, _)| {
535 if let ty::Adt(adt_def, _) = ty.kind() {
536 self.tcx
537 .inherent_impls(adt_def.did())
538 .into_iter()
539 .any(|def_id| self.associated_value(*def_id, item_ident).is_some())
540 } else {
541 false
542 }
543 });
544 let has_deref = autoderef.step_count() > 0;
545 if !candidate_found && !has_deref && unsatisfied_predicates.is_empty() {
546 ty =
547 self.tcx.at(span).type_of(def.did()).instantiate_identity().skip_norm_wip();
548 }
549 }
550 }
551
552 let mut err = self.dcx().create_err(NoAssociatedItem {
553 span,
554 item_kind,
555 item_ident,
556 ty_prefix: if trait_missing_method {
557 Cow::from("trait")
559 } else {
560 rcvr_ty.prefix_string(self.tcx)
561 },
562 ty,
563 trait_missing_method,
564 });
565
566 if is_method {
567 self.suggest_use_shadowed_binding_with_method(source, item_ident, rcvr_ty, &mut err);
568 }
569
570 let tcx = self.tcx;
571 if let SelfSource::QPath(ty) = source
573 && let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind
574 && let Res::SelfTyAlias { alias_to: impl_def_id, .. } = path.res
575 && let DefKind::Impl { .. } = self.tcx.def_kind(impl_def_id)
576 && let Some(candidate) = tcx.associated_items(impl_def_id).find_by_ident_and_kind(
577 self.tcx,
578 item_ident,
579 ty::AssocTag::Type,
580 impl_def_id,
581 )
582 && let Some(adt_def) = tcx.type_of(candidate.def_id).skip_binder().ty_adt_def()
583 && adt_def.is_struct()
584 && adt_def.non_enum_variant().ctor_kind() == Some(CtorKind::Fn)
585 {
586 let def_path = tcx.def_path_str(adt_def.did());
587 err.span_suggestion(
588 sugg_span,
589 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to construct a value of type `{0}`, use the explicit path",
def_path))
})format!("to construct a value of type `{}`, use the explicit path", def_path),
590 def_path,
591 Applicability::MachineApplicable,
592 );
593 }
594
595 err
596 }
597
598 fn suggest_use_shadowed_binding_with_method(
599 &self,
600 self_source: SelfSource<'tcx>,
601 method_name: Ident,
602 ty: Ty<'tcx>,
603 err: &mut Diag<'_>,
604 ) {
605 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for LetStmt {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "LetStmt",
"ty_hir_id_opt", &self.ty_hir_id_opt, "binding_id",
&self.binding_id, "span", &self.span, "init_hir_id",
&&self.init_hir_id)
}
}Debug)]
606 struct LetStmt {
607 ty_hir_id_opt: Option<hir::HirId>,
608 binding_id: hir::HirId,
609 span: Span,
610 init_hir_id: hir::HirId,
611 }
612
613 struct LetVisitor<'a, 'tcx> {
623 binding_name: Symbol,
625 binding_id: hir::HirId,
626 fcx: &'a FnCtxt<'a, 'tcx>,
628 call_expr: &'tcx Expr<'tcx>,
629 method_name: Ident,
630 sugg_let: Option<LetStmt>,
632 }
633
634 impl<'a, 'tcx> LetVisitor<'a, 'tcx> {
635 fn is_sub_scope(&self, sub_id: hir::ItemLocalId, super_id: hir::ItemLocalId) -> bool {
637 let scope_tree = self.fcx.tcx.region_scope_tree(self.fcx.body_id);
638 if let Some(sub_var_scope) = scope_tree.var_scope(sub_id)
639 && let Some(super_var_scope) = scope_tree.var_scope(super_id)
640 && scope_tree.is_subscope_of(sub_var_scope, super_var_scope)
641 {
642 return true;
643 }
644 false
645 }
646
647 fn check_and_add_sugg_binding(&mut self, binding: LetStmt) -> bool {
650 if !self.is_sub_scope(self.binding_id.local_id, binding.binding_id.local_id) {
651 return false;
652 }
653
654 if let Some(ty_hir_id) = binding.ty_hir_id_opt
656 && let Some(tyck_ty) = self.fcx.node_ty_opt(ty_hir_id)
657 {
658 if self
659 .fcx
660 .lookup_probe_for_diagnostic(
661 self.method_name,
662 tyck_ty,
663 self.call_expr,
664 ProbeScope::TraitsInScope,
665 None,
666 )
667 .is_ok()
668 {
669 self.sugg_let = Some(binding);
670 return true;
671 } else {
672 return false;
673 }
674 }
675
676 if let Some(self_ty) = self.fcx.node_ty_opt(binding.init_hir_id)
681 && self
682 .fcx
683 .lookup_probe_for_diagnostic(
684 self.method_name,
685 self_ty,
686 self.call_expr,
687 ProbeScope::TraitsInScope,
688 None,
689 )
690 .is_ok()
691 {
692 self.sugg_let = Some(binding);
693 return true;
694 }
695 return false;
696 }
697 }
698
699 impl<'v> Visitor<'v> for LetVisitor<'_, '_> {
700 type Result = ControlFlow<()>;
701 fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) -> Self::Result {
702 if let hir::StmtKind::Let(&hir::LetStmt { pat, ty, init, .. }) = ex.kind
703 && let hir::PatKind::Binding(_, binding_id, binding_name, ..) = pat.kind
704 && let Some(init) = init
705 && binding_name.name == self.binding_name
706 && binding_id != self.binding_id
707 {
708 if self.check_and_add_sugg_binding(LetStmt {
709 ty_hir_id_opt: ty.map(|ty| ty.hir_id),
710 binding_id,
711 span: pat.span,
712 init_hir_id: init.hir_id,
713 }) {
714 return ControlFlow::Break(());
715 }
716 ControlFlow::Continue(())
717 } else {
718 hir::intravisit::walk_stmt(self, ex)
719 }
720 }
721
722 fn visit_pat(&mut self, p: &'v hir::Pat<'v>) -> Self::Result {
726 match p.kind {
727 hir::PatKind::Binding(_, binding_id, binding_name, _) => {
728 if binding_name.name == self.binding_name && binding_id == self.binding_id {
729 return ControlFlow::Break(());
730 }
731 }
732 _ => {
733 let _ = intravisit::walk_pat(self, p);
734 }
735 }
736 ControlFlow::Continue(())
737 }
738 }
739
740 if let SelfSource::MethodCall(rcvr) = self_source
741 && let hir::ExprKind::Path(QPath::Resolved(_, path)) = rcvr.kind
742 && let hir::def::Res::Local(recv_id) = path.res
743 && let Some(segment) = path.segments.first()
744 {
745 let body = self.tcx.hir_body_owned_by(self.body_id);
746
747 if let Node::Expr(call_expr) = self.tcx.parent_hir_node(rcvr.hir_id) {
748 let mut let_visitor = LetVisitor {
749 fcx: self,
750 call_expr,
751 binding_name: segment.ident.name,
752 binding_id: recv_id,
753 method_name,
754 sugg_let: None,
755 };
756 let _ = let_visitor.visit_body(&body);
757 if let Some(sugg_let) = let_visitor.sugg_let
758 && let Some(self_ty) = self.node_ty_opt(sugg_let.init_hir_id)
759 {
760 let _sm = self.infcx.tcx.sess.source_map();
761 let rcvr_name = segment.ident.name;
762 let mut span = MultiSpan::from_span(sugg_let.span);
763 span.push_span_label(sugg_let.span,
764 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` of type `{1}` that has method `{2}` defined earlier here",
rcvr_name, self_ty, method_name))
})format!("`{rcvr_name}` of type `{self_ty}` that has method `{method_name}` defined earlier here"));
765
766 let ty = self.tcx.short_string(ty, err.long_ty_path());
767 span.push_span_label(
768 self.tcx.hir_span(recv_id),
769 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("earlier `{0}` shadowed here with type `{1}`",
rcvr_name, ty))
})format!("earlier `{rcvr_name}` shadowed here with type `{ty}`"),
770 );
771 err.span_note(
772 span,
773 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("there\'s an earlier shadowed binding `{0}` of type `{1}` that has method `{2}` available",
rcvr_name, self_ty, method_name))
})format!(
774 "there's an earlier shadowed binding `{rcvr_name}` of type `{self_ty}` \
775 that has method `{method_name}` available"
776 ),
777 );
778 }
779 }
780 }
781 }
782
783 fn suggest_method_call_annotation(
784 &self,
785 err: &mut Diag<'_>,
786 span: Span,
787 rcvr_ty: Ty<'tcx>,
788 item_ident: Ident,
789 mode: Mode,
790 source: SelfSource<'tcx>,
791 expected: Expectation<'tcx>,
792 ) {
793 if let Mode::MethodCall = mode
794 && let SelfSource::MethodCall(cal) = source
795 {
796 self.suggest_await_before_method(
797 err,
798 item_ident,
799 rcvr_ty,
800 cal,
801 span,
802 expected.only_has_type(self),
803 );
804 }
805
806 self.suggest_on_pointer_type(err, source, rcvr_ty, item_ident);
807
808 if let SelfSource::MethodCall(rcvr_expr) = source {
809 self.suggest_fn_call(err, rcvr_expr, rcvr_ty, |output_ty| {
810 let call_expr = self.tcx.hir_expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id));
811 let probe = self.lookup_probe_for_diagnostic(
812 item_ident,
813 output_ty,
814 call_expr,
815 ProbeScope::AllTraits,
816 expected.only_has_type(self),
817 );
818 probe.is_ok()
819 });
820 self.note_internal_mutation_in_method(
821 err,
822 rcvr_expr,
823 expected.to_option(self),
824 rcvr_ty,
825 );
826 }
827 }
828
829 fn suggest_static_method_candidates(
830 &self,
831 err: &mut Diag<'_>,
832 span: Span,
833 rcvr_ty: Ty<'tcx>,
834 item_ident: Ident,
835 source: SelfSource<'tcx>,
836 args: Option<&'tcx [hir::Expr<'tcx>]>,
837 sugg_span: Span,
838 no_match_data: &NoMatchData<'tcx>,
839 ) -> Vec<CandidateSource> {
840 let mut static_candidates = no_match_data.static_candidates.clone();
841
842 static_candidates.dedup();
846
847 if !static_candidates.is_empty() {
848 err.note(
849 "found the following associated functions; to be used as methods, \
850 functions must have a `self` parameter",
851 );
852 err.span_label(span, "this is an associated function, not a method");
853 }
854 if static_candidates.len() == 1 {
855 self.suggest_associated_call_syntax(
856 err,
857 &static_candidates,
858 rcvr_ty,
859 source,
860 item_ident,
861 args,
862 sugg_span,
863 );
864 self.note_candidates_on_method_error(
865 rcvr_ty,
866 item_ident,
867 source,
868 args,
869 span,
870 err,
871 &mut static_candidates,
872 None,
873 );
874 } else if static_candidates.len() > 1 {
875 self.note_candidates_on_method_error(
876 rcvr_ty,
877 item_ident,
878 source,
879 args,
880 span,
881 err,
882 &mut static_candidates,
883 Some(sugg_span),
884 );
885 }
886 static_candidates
887 }
888
889 fn suggest_unsatisfied_ty_or_trait(
890 &self,
891 err: &mut Diag<'_>,
892 span: Span,
893 rcvr_ty: Ty<'tcx>,
894 item_ident: Ident,
895 item_kind: &str,
896 source: SelfSource<'tcx>,
897 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
898 static_candidates: &[CandidateSource],
899 ) -> Result<(bool, bool, bool, bool, SortedMap<Span, Vec<String>>), ()> {
900 let mut restrict_type_params = false;
901 let mut suggested_derive = false;
902 let mut unsatisfied_bounds = false;
903 let mut custom_span_label = !static_candidates.is_empty();
904 let mut bound_spans: SortedMap<Span, Vec<String>> = Default::default();
905 let tcx = self.tcx;
906
907 if item_ident.name == sym::count && self.is_slice_ty(rcvr_ty, span) {
908 let msg = "consider using `len` instead";
909 if let SelfSource::MethodCall(_expr) = source {
910 err.span_suggestion_short(span, msg, "len", Applicability::MachineApplicable);
911 } else {
912 err.span_label(span, msg);
913 }
914 if let Some(iterator_trait) = self.tcx.get_diagnostic_item(sym::Iterator) {
915 let iterator_trait = self.tcx.def_path_str(iterator_trait);
916 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`count` is defined on `{0}`, which `{1}` does not implement",
iterator_trait, rcvr_ty))
})format!(
917 "`count` is defined on `{iterator_trait}`, which `{rcvr_ty}` does not implement"
918 ));
919 }
920 } else if self.impl_into_iterator_should_be_iterator(rcvr_ty, span, unsatisfied_predicates)
921 {
922 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is not an iterator",
rcvr_ty))
})format!("`{rcvr_ty}` is not an iterator"));
923 if !span.in_external_macro(self.tcx.sess.source_map())
924 && let Some(method_name) = self.preferred_iterator_method(source, rcvr_ty)
925 {
926 err.multipart_suggestion(
927 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("call `.{0}()` first", method_name))
})format!("call `.{method_name}()` first"),
928 ::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}().", method_name))
}))]))vec![(span.shrink_to_lo(), format!("{method_name}()."))],
929 Applicability::MaybeIncorrect,
930 );
931 }
932 return Err(());
934 } else if !unsatisfied_predicates.is_empty() {
935 if #[allow(non_exhaustive_omitted_patterns)] match rcvr_ty.kind() {
ty::Param(_) => true,
_ => false,
}matches!(rcvr_ty.kind(), ty::Param(_)) {
936 } else {
947 self.handle_unsatisfied_predicates(
948 err,
949 rcvr_ty,
950 item_ident,
951 item_kind,
952 span,
953 unsatisfied_predicates,
954 &mut restrict_type_params,
955 &mut suggested_derive,
956 &mut unsatisfied_bounds,
957 &mut custom_span_label,
958 &mut bound_spans,
959 );
960 }
961 } else if let ty::Adt(def, targs) = rcvr_ty.kind()
962 && let SelfSource::MethodCall(rcvr_expr) = source
963 {
964 if targs.len() == 1 {
968 let mut item_segment = hir::PathSegment::invalid();
969 item_segment.ident = item_ident;
970 for t in [Ty::new_mut_ref, Ty::new_imm_ref, |_, _, t| t] {
971 let new_args =
972 tcx.mk_args_from_iter(targs.iter().map(|arg| match arg.as_type() {
973 Some(ty) => ty::GenericArg::from(t(
974 tcx,
975 tcx.lifetimes.re_erased,
976 ty.peel_refs(),
977 )),
978 _ => arg,
979 }));
980 let rcvr_ty = Ty::new_adt(tcx, *def, new_args);
981 if let Ok(method) = self.lookup_method_for_diagnostic(
982 rcvr_ty,
983 &item_segment,
984 span,
985 tcx.parent_hir_node(rcvr_expr.hir_id).expect_expr(),
986 rcvr_expr,
987 ) {
988 err.span_note(
989 tcx.def_span(method.def_id),
990 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is available for `{1}`",
item_kind, rcvr_ty))
})format!("{item_kind} is available for `{rcvr_ty}`"),
991 );
992 }
993 }
994 }
995 }
996 Ok((
997 restrict_type_params,
998 suggested_derive,
999 unsatisfied_bounds,
1000 custom_span_label,
1001 bound_spans,
1002 ))
1003 }
1004
1005 fn suggest_surround_method_call(
1006 &self,
1007 err: &mut Diag<'_>,
1008 span: Span,
1009 rcvr_ty: Ty<'tcx>,
1010 item_ident: Ident,
1011 source: SelfSource<'tcx>,
1012 similar_candidate: &Option<ty::AssocItem>,
1013 ) -> bool {
1014 match source {
1015 SelfSource::MethodCall(expr) => {
1018 !self.suggest_calling_field_as_fn(span, rcvr_ty, expr, item_ident, err)
1019 && similar_candidate.is_none()
1020 }
1021 _ => true,
1022 }
1023 }
1024
1025 fn find_possible_candidates_for_method(
1026 &self,
1027 err: &mut Diag<'_>,
1028 span: Span,
1029 rcvr_ty: Ty<'tcx>,
1030 item_ident: Ident,
1031 item_kind: &str,
1032 mode: Mode,
1033 source: SelfSource<'tcx>,
1034 no_match_data: &NoMatchData<'tcx>,
1035 expected: Expectation<'tcx>,
1036 should_label_not_found: bool,
1037 custom_span_label: bool,
1038 ) {
1039 let mut find_candidate_for_method = false;
1040 let unsatisfied_predicates = &no_match_data.unsatisfied_predicates;
1041
1042 if should_label_not_found && !custom_span_label {
1043 self.set_not_found_span_label(
1044 err,
1045 rcvr_ty,
1046 item_ident,
1047 item_kind,
1048 mode,
1049 source,
1050 span,
1051 unsatisfied_predicates,
1052 &mut find_candidate_for_method,
1053 );
1054 }
1055 if !find_candidate_for_method {
1056 self.lookup_segments_chain_for_no_match_method(
1057 err,
1058 item_ident,
1059 item_kind,
1060 source,
1061 no_match_data,
1062 );
1063 }
1064
1065 if unsatisfied_predicates.is_empty() {
1068 self.suggest_calling_method_on_field(
1069 err,
1070 source,
1071 span,
1072 rcvr_ty,
1073 item_ident,
1074 expected.only_has_type(self),
1075 );
1076 }
1077 }
1078
1079 fn suggest_confusable_or_similarly_named_method(
1080 &self,
1081 err: &mut Diag<'_>,
1082 span: Span,
1083 rcvr_ty: Ty<'tcx>,
1084 item_ident: Ident,
1085 mode: Mode,
1086 args: Option<&'tcx [hir::Expr<'tcx>]>,
1087 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
1088 similar_candidate: Option<ty::AssocItem>,
1089 ) {
1090 let confusable_suggested = self.confusable_method_name(
1091 err,
1092 rcvr_ty,
1093 item_ident,
1094 args.map(|args| {
1095 args.iter()
1096 .map(|expr| {
1097 self.node_ty_opt(expr.hir_id).unwrap_or_else(|| self.next_ty_var(expr.span))
1098 })
1099 .collect()
1100 }),
1101 );
1102 if let Some(similar_candidate) = similar_candidate {
1103 if unsatisfied_predicates.is_empty()
1106 && Some(similar_candidate.name()) != confusable_suggested
1108 && !span.from_expansion()
1110 {
1111 self.find_likely_intended_associated_item(err, similar_candidate, span, args, mode);
1112 }
1113 }
1114 }
1115
1116 fn suggest_method_not_found_because_of_unsatisfied_bounds(
1117 &self,
1118 err: &mut Diag<'_>,
1119 rcvr_ty: Ty<'tcx>,
1120 item_ident: Ident,
1121 item_kind: &str,
1122 bound_spans: SortedMap<Span, Vec<String>>,
1123 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
1124 ) {
1125 let mut ty_span = match rcvr_ty.kind() {
1126 ty::Param(param_type) => {
1127 Some(param_type.span_from_generics(self.tcx, self.body_id.to_def_id()))
1128 }
1129 ty::Adt(def, _) if def.did().is_local() => Some(self.tcx.def_span(def.did())),
1130 _ => None,
1131 };
1132 let rcvr_ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
1133 let mut tracker = TraitBoundDuplicateTracker::new();
1134 for (predicate, _parent_pred, _cause) in unsatisfied_predicates {
1135 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1136 predicate.kind().skip_binder()
1137 && let self_ty = pred.trait_ref.self_ty()
1138 && self_ty.peel_refs() == rcvr_ty
1139 {
1140 let is_ref = #[allow(non_exhaustive_omitted_patterns)] match self_ty.kind() {
ty::Ref(..) => true,
_ => false,
}matches!(self_ty.kind(), ty::Ref(..));
1141 tracker.track(pred.trait_ref.def_id, is_ref);
1142 }
1143 }
1144 let has_ref_dupes = tracker.has_ref_dupes();
1145 let mut missing_trait_names = tracker
1146 .into_trait_def_ids()
1147 .into_iter()
1148 .map(|def_id| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.def_path_str(def_id)))
})format!("`{}`", self.tcx.def_path_str(def_id)))
1149 .collect::<Vec<_>>();
1150 missing_trait_names.sort();
1151 let should_condense =
1152 has_ref_dupes && missing_trait_names.len() > 1 && #[allow(non_exhaustive_omitted_patterns)] match rcvr_ty.kind() {
ty::Adt(..) => true,
_ => false,
}matches!(rcvr_ty.kind(), ty::Adt(..));
1153 let missing_trait_list = if should_condense {
1154 Some(match missing_trait_names.as_slice() {
1155 [only] => only.clone(),
1156 [first, second] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} or {1}", first, second))
})format!("{first} or {second}"),
1157 [rest @ .., last] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} or {1}", rest.join(", "),
last))
})format!("{} or {last}", rest.join(", ")),
1158 [] => String::new(),
1159 })
1160 } else {
1161 None
1162 };
1163 for (span, mut bounds) in bound_spans {
1164 if !self.tcx.sess.source_map().is_span_accessible(span) {
1165 continue;
1166 }
1167 bounds.sort();
1168 bounds.dedup();
1169 let is_ty_span = Some(span) == ty_span;
1170 if is_ty_span && should_condense {
1171 ty_span.take();
1172 let label = if let Some(missing_trait_list) = &missing_trait_list {
1173 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} `{2}` not found for this {0} because `{3}` doesn\'t implement {4}",
rcvr_ty.prefix_string(self.tcx), item_kind, item_ident,
rcvr_ty_str, missing_trait_list))
})format!(
1174 "{item_kind} `{item_ident}` not found for this {} because `{rcvr_ty_str}` doesn't implement {missing_trait_list}",
1175 rcvr_ty.prefix_string(self.tcx)
1176 )
1177 } else {
1178 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} `{2}` not found for this {0}",
rcvr_ty.prefix_string(self.tcx), item_kind, item_ident))
})format!(
1179 "{item_kind} `{item_ident}` not found for this {}",
1180 rcvr_ty.prefix_string(self.tcx)
1181 )
1182 };
1183 err.span_label(span, label);
1184 continue;
1185 }
1186 let pre = if is_ty_span {
1187 ty_span.take();
1188 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} `{2}` not found for this {0} because it ",
rcvr_ty.prefix_string(self.tcx), item_kind, item_ident))
})format!(
1189 "{item_kind} `{item_ident}` not found for this {} because it ",
1190 rcvr_ty.prefix_string(self.tcx)
1191 )
1192 } else {
1193 String::new()
1194 };
1195 let msg = match &bounds[..] {
1196 [bound] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}doesn\'t satisfy {1}", pre,
bound))
})format!("{pre}doesn't satisfy {bound}"),
1197 bounds if bounds.len() > 4 => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("doesn\'t satisfy {0} bounds",
bounds.len()))
})format!("doesn't satisfy {} bounds", bounds.len()),
1198 [bounds @ .., last] => {
1199 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}doesn\'t satisfy {0} or {2}",
bounds.join(", "), pre, last))
})format!("{pre}doesn't satisfy {} or {last}", bounds.join(", "))
1200 }
1201 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1202 };
1203 err.span_label(span, msg);
1204 }
1205 if let Some(span) = ty_span {
1206 err.span_label(
1207 span,
1208 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} `{2}` not found for this {0}",
rcvr_ty.prefix_string(self.tcx), item_kind, item_ident))
})format!(
1209 "{item_kind} `{item_ident}` not found for this {}",
1210 rcvr_ty.prefix_string(self.tcx)
1211 ),
1212 );
1213 }
1214 }
1215
1216 fn report_no_match_method_error(
1217 &self,
1218 span: Span,
1219 rcvr_ty: Ty<'tcx>,
1220 item_ident: Ident,
1221 expr_id: hir::HirId,
1222 source: SelfSource<'tcx>,
1223 args: Option<&'tcx [hir::Expr<'tcx>]>,
1224 sugg_span: Span,
1225 no_match_data: &mut NoMatchData<'tcx>,
1226 expected: Expectation<'tcx>,
1227 trait_missing_method: bool,
1228 within_macro_span: Option<Span>,
1229 ) -> ErrorGuaranteed {
1230 let tcx = self.tcx;
1231 let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty);
1232
1233 if let Err(guar) = rcvr_ty.error_reported() {
1234 return guar;
1235 }
1236
1237 if let Err(guar) =
1240 self.report_failed_method_call_on_range_end(tcx, rcvr_ty, source, span, item_ident)
1241 {
1242 return guar;
1243 }
1244
1245 let mut ty_file = None;
1246 let mode = no_match_data.mode;
1247 let is_method = mode == Mode::MethodCall;
1248 let item_kind = if is_method {
1249 "method"
1250 } else if rcvr_ty.is_enum() || rcvr_ty.is_fresh_ty() {
1251 "variant, associated function, or constant"
1252 } else {
1253 "associated function or constant"
1254 };
1255
1256 if let Err(guar) = self.report_failed_method_call_on_numerical_infer_var(
1257 tcx,
1258 rcvr_ty,
1259 source,
1260 span,
1261 item_kind,
1262 item_ident,
1263 &mut ty_file,
1264 ) {
1265 return guar;
1266 }
1267
1268 let unsatisfied_predicates = &no_match_data.unsatisfied_predicates;
1269 let is_write = sugg_span.ctxt().outer_expn_data().macro_def_id.is_some_and(|def_id| {
1270 tcx.is_diagnostic_item(sym::write_macro, def_id)
1271 || tcx.is_diagnostic_item(sym::writeln_macro, def_id)
1272 }) && item_ident.name == sym::write_fmt;
1273 let mut err = if is_write && let SelfSource::MethodCall(rcvr_expr) = source {
1274 self.create_missing_writer_err(rcvr_ty, rcvr_expr, ty_file)
1275 } else {
1276 self.create_no_assoc_err(
1277 rcvr_ty,
1278 item_ident,
1279 item_kind,
1280 trait_missing_method,
1281 source,
1282 is_method,
1283 sugg_span,
1284 unsatisfied_predicates,
1285 )
1286 };
1287 if let SelfSource::MethodCall(rcvr_expr) = source {
1288 self.err_ctxt().note_field_shadowed_by_private_candidate(
1289 &mut err,
1290 rcvr_expr.hir_id,
1291 self.param_env,
1292 );
1293 }
1294
1295 self.set_label_for_method_error(
1296 &mut err,
1297 source,
1298 rcvr_ty,
1299 item_ident,
1300 expr_id,
1301 item_ident.span,
1302 sugg_span,
1303 within_macro_span,
1304 args,
1305 );
1306
1307 self.suggest_method_call_annotation(
1308 &mut err,
1309 item_ident.span,
1310 rcvr_ty,
1311 item_ident,
1312 mode,
1313 source,
1314 expected,
1315 );
1316
1317 let static_candidates = self.suggest_static_method_candidates(
1318 &mut err,
1319 item_ident.span,
1320 rcvr_ty,
1321 item_ident,
1322 source,
1323 args,
1324 sugg_span,
1325 &no_match_data,
1326 );
1327
1328 let Ok((
1329 restrict_type_params,
1330 suggested_derive,
1331 unsatisfied_bounds,
1332 custom_span_label,
1333 bound_spans,
1334 )) = self.suggest_unsatisfied_ty_or_trait(
1335 &mut err,
1336 item_ident.span,
1337 rcvr_ty,
1338 item_ident,
1339 item_kind,
1340 source,
1341 unsatisfied_predicates,
1342 &static_candidates,
1343 )
1344 else {
1345 return err.emit();
1346 };
1347
1348 let similar_candidate = no_match_data.similar_candidate;
1349 let should_label_not_found = self.suggest_surround_method_call(
1350 &mut err,
1351 item_ident.span,
1352 rcvr_ty,
1353 item_ident,
1354 source,
1355 &similar_candidate,
1356 );
1357
1358 self.find_possible_candidates_for_method(
1359 &mut err,
1360 item_ident.span,
1361 rcvr_ty,
1362 item_ident,
1363 item_kind,
1364 mode,
1365 source,
1366 no_match_data,
1367 expected,
1368 should_label_not_found,
1369 custom_span_label,
1370 );
1371
1372 self.suggest_unwrapping_inner_self(&mut err, source, rcvr_ty, item_ident);
1373
1374 if rcvr_ty.is_numeric() && rcvr_ty.is_fresh() || restrict_type_params || suggested_derive {
1375 } else {
1377 self.suggest_traits_to_import(
1378 &mut err,
1379 item_ident.span,
1380 rcvr_ty,
1381 item_ident,
1382 args.map(|args| args.len() + 1),
1383 source,
1384 no_match_data.out_of_scope_traits.clone(),
1385 &static_candidates,
1386 unsatisfied_bounds,
1387 expected.only_has_type(self),
1388 trait_missing_method,
1389 );
1390 }
1391
1392 self.suggest_enum_variant_for_method_call(
1393 &mut err,
1394 rcvr_ty,
1395 item_ident,
1396 item_ident.span,
1397 source,
1398 unsatisfied_predicates,
1399 );
1400
1401 self.suggest_confusable_or_similarly_named_method(
1402 &mut err,
1403 item_ident.span,
1404 rcvr_ty,
1405 item_ident,
1406 mode,
1407 args,
1408 unsatisfied_predicates,
1409 similar_candidate,
1410 );
1411
1412 self.suggest_method_not_found_because_of_unsatisfied_bounds(
1413 &mut err,
1414 rcvr_ty,
1415 item_ident,
1416 item_kind,
1417 bound_spans,
1418 unsatisfied_predicates,
1419 );
1420
1421 self.note_derefed_ty_has_method(&mut err, source, rcvr_ty, item_ident, expected);
1422 self.suggest_bounds_for_range_to_method(&mut err, source, item_ident);
1423 err.emit()
1424 }
1425
1426 fn set_not_found_span_label(
1427 &self,
1428 err: &mut Diag<'_>,
1429 rcvr_ty: Ty<'tcx>,
1430 item_ident: Ident,
1431 item_kind: &str,
1432 mode: Mode,
1433 source: SelfSource<'tcx>,
1434 span: Span,
1435 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
1436 find_candidate_for_method: &mut bool,
1437 ) {
1438 let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
1439 if unsatisfied_predicates.is_empty() {
1440 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} not found in `{1}`", item_kind,
ty_str))
})format!("{item_kind} not found in `{ty_str}`"));
1441 let is_string_or_ref_str = match rcvr_ty.kind() {
1442 ty::Ref(_, ty, _) => {
1443 ty.is_str()
1444 || #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Adt(adt, _) if self.tcx.is_lang_item(adt.did(), LangItem::String) =>
true,
_ => false,
}matches!(
1445 ty.kind(),
1446 ty::Adt(adt, _) if self.tcx.is_lang_item(adt.did(), LangItem::String)
1447 )
1448 }
1449 ty::Adt(adt, _) => self.tcx.is_lang_item(adt.did(), LangItem::String),
1450 _ => false,
1451 };
1452 if is_string_or_ref_str && item_ident.name == sym::iter {
1453 err.span_suggestion_verbose(
1454 item_ident.span,
1455 "because of the in-memory representation of `&str`, to obtain \
1456 an `Iterator` over each of its codepoint use method `chars`",
1457 "chars",
1458 Applicability::MachineApplicable,
1459 );
1460 }
1461 if let ty::Adt(adt, _) = rcvr_ty.kind() {
1462 let mut inherent_impls_candidate = self
1463 .tcx
1464 .inherent_impls(adt.did())
1465 .into_iter()
1466 .copied()
1467 .filter(|def_id| {
1468 if let Some(assoc) = self.associated_value(*def_id, item_ident) {
1469 match (mode, assoc.is_method(), source) {
1472 (Mode::MethodCall, true, SelfSource::MethodCall(_)) => {
1473 self.tcx
1478 .at(span)
1479 .type_of(*def_id)
1480 .instantiate_identity()
1481 .skip_norm_wip()
1482 != rcvr_ty
1483 }
1484 (Mode::Path, false, _) => true,
1485 _ => false,
1486 }
1487 } else {
1488 false
1489 }
1490 })
1491 .collect::<Vec<_>>();
1492 inherent_impls_candidate.sort_by_key(|&id| self.tcx.def_path_str(id));
1493 inherent_impls_candidate.dedup();
1494 let msg = match &inherent_impls_candidate[..] {
1495 [] => return,
1496 [only] => {
1497 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} was found for `",
item_kind))
})),
StringPart::highlighted(self.tcx.at(span).type_of(*only).instantiate_identity().skip_norm_wip().to_string()),
StringPart::normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`"))
}))]))vec![
1498 StringPart::normal(format!("the {item_kind} was found for `")),
1499 StringPart::highlighted(
1500 self.tcx
1501 .at(span)
1502 .type_of(*only)
1503 .instantiate_identity()
1504 .skip_norm_wip()
1505 .to_string(),
1506 ),
1507 StringPart::normal(format!("`")),
1508 ]
1509 }
1510 candidates => {
1511 let limit = if candidates.len() == 5 { 5 } else { 4 };
1513 let type_candidates = candidates
1514 .iter()
1515 .take(limit)
1516 .map(|impl_item| {
1517 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("- `{0}`",
self.tcx.at(span).type_of(*impl_item).instantiate_identity().skip_norm_wip()))
})format!(
1518 "- `{}`",
1519 self.tcx
1520 .at(span)
1521 .type_of(*impl_item)
1522 .instantiate_identity()
1523 .skip_norm_wip()
1524 )
1525 })
1526 .collect::<Vec<_>>()
1527 .join("\n");
1528 let additional_types = if candidates.len() > limit {
1529 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} more types",
candidates.len() - limit))
})format!("\nand {} more types", candidates.len() - limit)
1530 } else {
1531 "".to_string()
1532 };
1533 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} was found for\n{1}{2}",
item_kind, type_candidates, additional_types))
}))]))vec![StringPart::normal(format!(
1534 "the {item_kind} was found for\n{type_candidates}{additional_types}"
1535 ))]
1536 }
1537 };
1538 err.highlighted_note(msg);
1539 *find_candidate_for_method = mode == Mode::MethodCall;
1540 }
1541 } else {
1542 let ty_str = if ty_str.len() > 50 { String::new() } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("on `{0}` ", ty_str))
})format!("on `{ty_str}` ") };
1543 err.span_label(
1544 span,
1545 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} cannot be called {1}due to unsatisfied trait bounds",
item_kind, ty_str))
})format!("{item_kind} cannot be called {ty_str}due to unsatisfied trait bounds"),
1546 );
1547 }
1548 }
1549
1550 fn suggest_enum_variant_for_method_call(
1552 &self,
1553 err: &mut Diag<'_>,
1554 rcvr_ty: Ty<'tcx>,
1555 item_ident: Ident,
1556 span: Span,
1557 source: SelfSource<'tcx>,
1558 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
1559 ) {
1560 if !unsatisfied_predicates.is_empty() || !rcvr_ty.is_enum() {
1562 return;
1563 }
1564
1565 let tcx = self.tcx;
1566 let adt_def = rcvr_ty.ty_adt_def().expect("enum is not an ADT");
1567 if let Some(var_name) = edit_distance::find_best_match_for_name(
1568 &adt_def.variants().iter().map(|s| s.name).collect::<Vec<_>>(),
1569 item_ident.name,
1570 None,
1571 ) && let Some(variant) = adt_def.variants().iter().find(|s| s.name == var_name)
1572 {
1573 let mut suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, var_name.to_string())]))vec![(span, var_name.to_string())];
1574 if let SelfSource::QPath(ty) = source
1575 && let hir::Node::Expr(ref path_expr) = tcx.parent_hir_node(ty.hir_id)
1576 && let hir::ExprKind::Path(_) = path_expr.kind
1577 && let hir::Node::Stmt(&hir::Stmt { kind: hir::StmtKind::Semi(parent), .. })
1578 | hir::Node::Expr(parent) = tcx.parent_hir_node(path_expr.hir_id)
1579 {
1580 let replacement_span = match parent.kind {
1582 hir::ExprKind::Call(callee, _) if callee.hir_id == path_expr.hir_id => {
1583 span.with_hi(parent.span.hi())
1584 }
1585 hir::ExprKind::Struct(..) => span.with_hi(parent.span.hi()),
1586 _ => span,
1587 };
1588 match (variant.ctor, parent.kind) {
1589 (None, hir::ExprKind::Struct(..)) => {
1590 suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, var_name.to_string())]))vec![(span, var_name.to_string())];
1593 }
1594 (None, _) => {
1595 suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(replacement_span,
if variant.fields.is_empty() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{}}", var_name))
})
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} {{ {0} }}",
variant.fields.iter().map(|f|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: /* value */",
f.name))
})).collect::<Vec<_>>().join(", "), var_name))
})
})]))vec![(
1597 replacement_span,
1598 if variant.fields.is_empty() {
1599 format!("{var_name} {{}}")
1600 } else {
1601 format!(
1602 "{var_name} {{ {} }}",
1603 variant
1604 .fields
1605 .iter()
1606 .map(|f| format!("{}: /* value */", f.name))
1607 .collect::<Vec<_>>()
1608 .join(", ")
1609 )
1610 },
1611 )];
1612 }
1613 (Some((hir::def::CtorKind::Const, _)), _) => {
1614 suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(replacement_span, var_name.to_string())]))vec![(replacement_span, var_name.to_string())];
1616 }
1617 (Some((hir::def::CtorKind::Fn, def_id)), hir::ExprKind::Call(rcvr, args)) => {
1618 let fn_sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1619 let inputs = fn_sig.inputs().skip_binder();
1620 match (inputs, args) {
1623 (inputs, []) => {
1624 suggestion.push((
1626 rcvr.span.shrink_to_hi().with_hi(parent.span.hi()),
1627 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})",
inputs.iter().map(|i|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", i))
})).collect::<Vec<String>>().join(", ")))
})format!(
1628 "({})",
1629 inputs
1630 .iter()
1631 .map(|i| format!("/* {i} */"))
1632 .collect::<Vec<String>>()
1633 .join(", ")
1634 ),
1635 ));
1636 }
1637 (_, [arg]) if inputs.len() != args.len() => {
1638 suggestion.push((
1640 arg.span,
1641 inputs
1642 .iter()
1643 .map(|i| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", i))
})format!("/* {i} */"))
1644 .collect::<Vec<String>>()
1645 .join(", "),
1646 ));
1647 }
1648 (_, [arg_start, .., arg_end]) if inputs.len() != args.len() => {
1649 suggestion.push((
1651 arg_start.span.to(arg_end.span),
1652 inputs
1653 .iter()
1654 .map(|i| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", i))
})format!("/* {i} */"))
1655 .collect::<Vec<String>>()
1656 .join(", "),
1657 ));
1658 }
1659 _ => {}
1661 }
1662 }
1663 (Some((hir::def::CtorKind::Fn, def_id)), _) => {
1664 let fn_sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1665 let inputs = fn_sig.inputs().skip_binder();
1666 suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(replacement_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}({0})",
inputs.iter().map(|i|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", i))
})).collect::<Vec<String>>().join(", "), var_name))
}))]))vec![(
1667 replacement_span,
1668 format!(
1669 "{var_name}({})",
1670 inputs
1671 .iter()
1672 .map(|i| format!("/* {i} */"))
1673 .collect::<Vec<String>>()
1674 .join(", ")
1675 ),
1676 )];
1677 }
1678 }
1679 }
1680 err.multipart_suggestion(
1681 "there is a variant with a similar name",
1682 suggestion,
1683 Applicability::HasPlaceholders,
1684 );
1685 }
1686 }
1687
1688 fn handle_unsatisfied_predicates(
1689 &self,
1690 err: &mut Diag<'_>,
1691 rcvr_ty: Ty<'tcx>,
1692 item_ident: Ident,
1693 item_kind: &str,
1694 span: Span,
1695 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
1696 restrict_type_params: &mut bool,
1697 suggested_derive: &mut bool,
1698 unsatisfied_bounds: &mut bool,
1699 custom_span_label: &mut bool,
1700 bound_spans: &mut SortedMap<Span, Vec<String>>,
1701 ) {
1702 let tcx = self.tcx;
1703 let rcvr_ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
1704 let mut type_params = FxIndexMap::default();
1705
1706 let mut unimplemented_traits = FxIndexMap::default();
1709
1710 let mut unimplemented_traits_only = true;
1711 for (predicate, _parent_pred, cause) in unsatisfied_predicates {
1712 if let (ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)), Some(cause)) =
1713 (predicate.kind().skip_binder(), cause.as_ref())
1714 {
1715 if p.trait_ref.self_ty() != rcvr_ty {
1716 continue;
1720 }
1721 unimplemented_traits.entry(p.trait_ref.def_id).or_insert((
1722 predicate.kind().rebind(p),
1723 Obligation {
1724 cause: cause.clone(),
1725 param_env: self.param_env,
1726 predicate: *predicate,
1727 recursion_depth: 0,
1728 },
1729 ));
1730 }
1731 }
1732
1733 for (predicate, _parent_pred, _cause) in unsatisfied_predicates {
1738 match predicate.kind().skip_binder() {
1739 ty::PredicateKind::Clause(ty::ClauseKind::Trait(p))
1740 if unimplemented_traits.contains_key(&p.trait_ref.def_id) => {}
1741 _ => {
1742 unimplemented_traits_only = false;
1743 break;
1744 }
1745 }
1746 }
1747
1748 let mut collect_type_param_suggestions =
1749 |self_ty: Ty<'tcx>, parent_pred: ty::Predicate<'tcx>, obligation: &str| {
1750 if let (ty::Param(_), ty::PredicateKind::Clause(ty::ClauseKind::Trait(p))) =
1752 (self_ty.kind(), parent_pred.kind().skip_binder())
1753 {
1754 let node = match p.trait_ref.self_ty().kind() {
1755 ty::Param(_) => {
1756 Some(self.tcx.hir_node_by_def_id(self.body_id))
1759 }
1760 ty::Adt(def, _) => {
1761 def.did().as_local().map(|def_id| self.tcx.hir_node_by_def_id(def_id))
1762 }
1763 _ => None,
1764 };
1765 if let Some(hir::Node::Item(hir::Item { kind, .. })) = node
1766 && let Some(g) = kind.generics()
1767 {
1768 let key = (
1769 g.tail_span_for_predicate_suggestion(),
1770 g.add_where_or_trailing_comma(),
1771 );
1772 type_params
1773 .entry(key)
1774 .or_insert_with(UnordSet::default)
1775 .insert(obligation.to_owned());
1776 return true;
1777 }
1778 }
1779 false
1780 };
1781 let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
1782 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
if obligation.len() > 50 { quiet } else { obligation }))
})format!("`{}`", if obligation.len() > 50 { quiet } else { obligation });
1783 match self_ty.kind() {
1784 ty::Adt(def, _) => {
1786 bound_spans.get_mut_or_insert_default(tcx.def_span(def.did())).push(msg)
1787 }
1788 ty::Dynamic(preds, _) => {
1790 for pred in preds.iter() {
1791 match pred.skip_binder() {
1792 ty::ExistentialPredicate::Trait(tr) => {
1793 bound_spans
1794 .get_mut_or_insert_default(tcx.def_span(tr.def_id))
1795 .push(msg.clone());
1796 }
1797 ty::ExistentialPredicate::Projection(_)
1798 | ty::ExistentialPredicate::AutoTrait(_) => {}
1799 }
1800 }
1801 }
1802 ty::Closure(def_id, _) => {
1804 bound_spans
1805 .get_mut_or_insert_default(tcx.def_span(*def_id))
1806 .push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", quiet))
})format!("`{quiet}`"));
1807 }
1808 _ => {}
1809 }
1810 };
1811
1812 let mut format_pred = |pred: ty::Predicate<'tcx>| {
1813 let bound_predicate = pred.kind();
1814 match bound_predicate.skip_binder() {
1815 ty::PredicateKind::Clause(ty::ClauseKind::Projection(pred)) => {
1816 let pred = bound_predicate.rebind(pred);
1817 let projection_term = pred.skip_binder().projection_term;
1819 let quiet_projection_term = projection_term
1820 .with_replaced_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO));
1821
1822 let term = pred.skip_binder().term;
1823
1824 let obligation = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} = {1}", projection_term, term))
})format!("{projection_term} = {term}");
1825 let quiet =
1826 {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} = {1}",
quiet_projection_term, term))
})
}with_forced_trimmed_paths!(format!("{} = {}", quiet_projection_term, term));
1827
1828 bound_span_label(projection_term.self_ty(), &obligation, &quiet);
1829 Some((obligation, projection_term.self_ty()))
1830 }
1831 ty::PredicateKind::Clause(ty::ClauseKind::Trait(poly_trait_ref)) => {
1832 let p = poly_trait_ref.trait_ref;
1833 let self_ty = p.self_ty();
1834 let path = p.print_only_trait_path();
1835 let obligation = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", self_ty, path))
})format!("{self_ty}: {path}");
1836 let quiet = {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_: {0}", path))
})
}with_forced_trimmed_paths!(format!("_: {}", path));
1837 bound_span_label(self_ty, &obligation, &quiet);
1838 Some((obligation, self_ty))
1839 }
1840 _ => None,
1841 }
1842 };
1843
1844 let mut skip_list: UnordSet<_> = Default::default();
1846 let mut spanned_predicates = FxIndexMap::default();
1847 let mut manually_impl = false;
1848 for (p, parent_p, cause) in unsatisfied_predicates {
1849 let (item_def_id, cause_span, cause_msg) =
1852 match cause.as_ref().map(|cause| cause.code()) {
1853 Some(ObligationCauseCode::ImplDerived(data)) => {
1854 let msg = if let DefKind::Impl { of_trait: true } =
1855 self.tcx.def_kind(data.impl_or_alias_def_id)
1856 {
1857 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter would need to implement `{0}`",
self.tcx.item_name(self.tcx.impl_trait_id(data.impl_or_alias_def_id))))
})format!(
1858 "type parameter would need to implement `{}`",
1859 self.tcx
1860 .item_name(self.tcx.impl_trait_id(data.impl_or_alias_def_id))
1861 )
1862 } else {
1863 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied bound `{0}` introduced here",
p))
})format!("unsatisfied bound `{p}` introduced here")
1864 };
1865 (data.impl_or_alias_def_id, data.span, msg)
1866 }
1867 Some(
1868 ObligationCauseCode::WhereClauseInExpr(def_id, span, _, _)
1869 | ObligationCauseCode::WhereClause(def_id, span),
1870 ) if !span.is_dummy() => {
1871 (*def_id, *span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied bound `{0}` introduced here",
p))
})format!("unsatisfied bound `{p}` introduced here"))
1872 }
1873 _ => continue,
1874 };
1875
1876 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind().skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Projection(..) |
ty::ClauseKind::Trait(..)) => true,
_ => false,
}matches!(
1878 p.kind().skip_binder(),
1879 ty::PredicateKind::Clause(
1880 ty::ClauseKind::Projection(..) | ty::ClauseKind::Trait(..)
1881 )
1882 ) {
1883 continue;
1884 }
1885
1886 match self.tcx.hir_get_if_local(item_def_id) {
1887 Some(Node::Item(hir::Item {
1890 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
1891 ..
1892 })) if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
{
ExpnKind::Macro(MacroKind::Derive, _) => true,
_ => false,
}matches!(
1893 self_ty.span.ctxt().outer_expn_data().kind,
1894 ExpnKind::Macro(MacroKind::Derive, _)
1895 ) || #[allow(non_exhaustive_omitted_patterns)] match of_trait.map(|t|
t.trait_ref.path.span.ctxt().outer_expn_data().kind) {
Some(ExpnKind::Macro(MacroKind::Derive, _)) => true,
_ => false,
}matches!(
1896 of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
1897 Some(ExpnKind::Macro(MacroKind::Derive, _))
1898 ) =>
1899 {
1900 let span = self_ty.span.ctxt().outer_expn_data().call_site;
1901 let entry = spanned_predicates.entry(span);
1902 let entry = entry.or_insert_with(|| {
1903 (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
1904 });
1905 entry.0.insert(cause_span);
1906 entry.1.insert((cause_span, cause_msg));
1907 entry.2.push(p);
1908 skip_list.insert(p);
1909 manually_impl = true;
1910 }
1911
1912 Some(Node::Item(hir::Item {
1914 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
1915 span: item_span,
1916 ..
1917 })) => {
1918 let sized_pred = unsatisfied_predicates.iter().any(|(pred, _, _)| {
1919 match pred.kind().skip_binder() {
1920 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
1921 self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
1922 && pred.polarity == ty::PredicatePolarity::Positive
1923 }
1924 _ => false,
1925 }
1926 });
1927 for param in generics.params {
1928 if param.span == cause_span && sized_pred {
1929 let (sp, sugg) = match param.colon_span {
1930 Some(sp) => (sp.shrink_to_hi(), " ?Sized +"),
1931 None => (param.span.shrink_to_hi(), ": ?Sized"),
1932 };
1933 err.span_suggestion_verbose(
1934 sp,
1935 "consider relaxing the type parameter's implicit `Sized` bound",
1936 sugg,
1937 Applicability::MachineApplicable,
1938 );
1939 }
1940 }
1941 if let Some(pred) = parent_p {
1942 let _ = format_pred(*pred);
1944 }
1945 skip_list.insert(p);
1946 let entry = spanned_predicates.entry(self_ty.span);
1947 let entry = entry.or_insert_with(|| {
1948 (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
1949 });
1950 entry.2.push(p);
1951 if cause_span != *item_span {
1952 entry.0.insert(cause_span);
1953 entry.1.insert((
1954 cause_span,
1955 "unsatisfied trait bound introduced here".to_string(),
1956 ));
1957 } else {
1958 if let Some(of_trait) = of_trait {
1959 entry.0.insert(of_trait.trait_ref.path.span);
1960 }
1961 entry.0.insert(self_ty.span);
1962 };
1963 if let Some(of_trait) = of_trait {
1964 entry.1.insert((of_trait.trait_ref.path.span, String::new()));
1965 }
1966 entry.1.insert((self_ty.span, String::new()));
1967 }
1968 Some(Node::Item(hir::Item {
1969 kind: hir::ItemKind::Trait { is_auto: rustc_ast::ast::IsAuto::Yes, .. },
1970 span: item_span,
1971 ..
1972 })) => {
1973 self.dcx().span_delayed_bug(
1974 *item_span,
1975 "auto trait is invoked with no method error, but no error reported?",
1976 );
1977 }
1978 Some(
1979 Node::Item(hir::Item {
1980 kind:
1981 hir::ItemKind::Trait { ident, .. }
1982 | hir::ItemKind::TraitAlias(_, ident, ..),
1983 ..
1984 })
1985 | Node::TraitItem(hir::TraitItem { ident, .. })
1987 | Node::ImplItem(hir::ImplItem { ident, .. })
1988 ) => {
1989 skip_list.insert(p);
1990 let entry = spanned_predicates.entry(ident.span);
1991 let entry = entry.or_insert_with(|| {
1992 (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
1993 });
1994 entry.0.insert(cause_span);
1995 entry.1.insert((ident.span, String::new()));
1996 entry.1.insert((
1997 cause_span,
1998 "unsatisfied trait bound introduced here".to_string(),
1999 ));
2000 entry.2.push(p);
2001 }
2002 _ => {
2003 }
2008 }
2009 }
2010 let mut spanned_predicates: Vec<_> = spanned_predicates.into_iter().collect();
2011 spanned_predicates.sort_by_key(|(span, _)| *span);
2012 for (_, (primary_spans, span_labels, predicates)) in spanned_predicates {
2013 let mut tracker = TraitBoundDuplicateTracker::new();
2014 let mut all_trait_bounds_for_rcvr = true;
2015 for pred in &predicates {
2016 match pred.kind().skip_binder() {
2017 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
2018 let self_ty = pred.trait_ref.self_ty();
2019 if self_ty.peel_refs() != rcvr_ty {
2020 all_trait_bounds_for_rcvr = false;
2021 break;
2022 }
2023 let is_ref = #[allow(non_exhaustive_omitted_patterns)] match self_ty.kind() {
ty::Ref(..) => true,
_ => false,
}matches!(self_ty.kind(), ty::Ref(..));
2024 tracker.track(pred.trait_ref.def_id, is_ref);
2025 }
2026 _ => {
2027 all_trait_bounds_for_rcvr = false;
2028 break;
2029 }
2030 }
2031 }
2032 let has_ref_dupes = tracker.has_ref_dupes();
2033 let trait_def_ids = tracker.into_trait_def_ids();
2034 let mut preds: Vec<_> = predicates
2035 .iter()
2036 .filter_map(|pred| format_pred(**pred))
2037 .map(|(p, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", p))
})format!("`{p}`"))
2038 .collect();
2039 preds.sort();
2040 preds.dedup();
2041 let availability_note = if all_trait_bounds_for_rcvr
2042 && has_ref_dupes
2043 && trait_def_ids.len() > 1
2044 && #[allow(non_exhaustive_omitted_patterns)] match rcvr_ty.kind() {
ty::Adt(..) => true,
_ => false,
}matches!(rcvr_ty.kind(), ty::Adt(..))
2045 {
2046 let mut trait_names = trait_def_ids
2047 .into_iter()
2048 .map(|def_id| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", tcx.def_path_str(def_id)))
})format!("`{}`", tcx.def_path_str(def_id)))
2049 .collect::<Vec<_>>();
2050 trait_names.sort();
2051 listify(&trait_names, |name| name.to_string()).map(|traits| {
2052 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("for `{0}` to be available, `{1}` must implement {2}",
item_ident, rcvr_ty_str, traits))
})format!(
2053 "for `{item_ident}` to be available, `{rcvr_ty_str}` must implement {traits}"
2054 )
2055 })
2056 } else {
2057 None
2058 };
2059 let msg = if let Some(availability_note) = availability_note {
2060 availability_note
2061 } else if let [pred] = &preds[..] {
2062 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait bound {0} was not satisfied",
pred))
})format!("trait bound {pred} was not satisfied")
2063 } else {
2064 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following trait bounds were not satisfied:\n{0}",
preds.join("\n")))
})format!("the following trait bounds were not satisfied:\n{}", preds.join("\n"),)
2065 };
2066 let mut span: MultiSpan = primary_spans.into_iter().collect::<Vec<_>>().into();
2067 for (sp, label) in span_labels {
2068 span.push_span_label(sp, label);
2069 }
2070 err.span_note(span, msg);
2071 *unsatisfied_bounds = true;
2072 }
2073
2074 let mut suggested_bounds = UnordSet::default();
2075 let mut bound_list = unsatisfied_predicates
2077 .iter()
2078 .filter_map(|(pred, parent_pred, _cause)| {
2079 let mut suggested = false;
2080 format_pred(*pred).map(|(p, self_ty)| {
2081 if let Some(parent) = parent_pred
2082 && suggested_bounds.contains(parent)
2083 {
2084 } else if !suggested_bounds.contains(pred)
2086 && collect_type_param_suggestions(self_ty, *pred, &p)
2087 {
2088 suggested = true;
2089 suggested_bounds.insert(pred);
2090 }
2091 (
2092 match parent_pred {
2093 None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", p))
})format!("`{p}`"),
2094 Some(parent_pred) => match format_pred(*parent_pred) {
2095 None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", p))
})format!("`{p}`"),
2096 Some((parent_p, _)) => {
2097 if !suggested
2098 && !suggested_bounds.contains(pred)
2099 && !suggested_bounds.contains(parent_pred)
2100 && collect_type_param_suggestions(self_ty, *parent_pred, &p)
2101 {
2102 suggested_bounds.insert(pred);
2103 }
2104 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`\nwhich is required by `{1}`",
p, parent_p))
})format!("`{p}`\nwhich is required by `{parent_p}`")
2105 }
2106 },
2107 },
2108 *pred,
2109 )
2110 })
2111 })
2112 .filter(|(_, pred)| !skip_list.contains(&pred))
2113 .map(|(t, _)| t)
2114 .enumerate()
2115 .collect::<Vec<(usize, String)>>();
2116
2117 if !#[allow(non_exhaustive_omitted_patterns)] match rcvr_ty.peel_refs().kind() {
ty::Param(_) => true,
_ => false,
}matches!(rcvr_ty.peel_refs().kind(), ty::Param(_)) {
2118 for ((span, add_where_or_comma), obligations) in type_params.into_iter() {
2119 *restrict_type_params = true;
2120 let obligations = obligations.into_sorted_stable_ord();
2122 err.span_suggestion_verbose(
2123 span,
2124 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider restricting the type parameter{0} to satisfy the trait bound{0}",
if obligations.len() == 1 { "" } else { "s" }))
})format!(
2125 "consider restricting the type parameter{s} to satisfy the trait \
2126 bound{s}",
2127 s = pluralize!(obligations.len())
2128 ),
2129 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", add_where_or_comma,
obligations.join(", ")))
})format!("{} {}", add_where_or_comma, obligations.join(", ")),
2130 Applicability::MaybeIncorrect,
2131 );
2132 }
2133 }
2134
2135 bound_list.sort_by(|(_, a), (_, b)| a.cmp(b)); bound_list.dedup_by(|(_, a), (_, b)| a == b); bound_list.sort_by_key(|(pos, _)| *pos); if !bound_list.is_empty() || !skip_list.is_empty() {
2140 let bound_list =
2141 bound_list.into_iter().map(|(_, path)| path).collect::<Vec<_>>().join("\n");
2142 let actual_prefix = rcvr_ty.prefix_string(self.tcx);
2143 {
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/method/suggest.rs:2143",
"rustc_hir_typeck::method::suggest", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/suggest.rs"),
::tracing_core::__macro_support::Option::Some(2143u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::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::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::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!("unimplemented_traits.len() == {0}",
unimplemented_traits.len()) as &dyn Value))])
});
} else { ; }
};info!("unimplemented_traits.len() == {}", unimplemented_traits.len());
2144 let (primary_message, label, notes) = if unimplemented_traits.len() == 1
2145 && unimplemented_traits_only
2146 {
2147 unimplemented_traits
2148 .into_iter()
2149 .next()
2150 .map(|(_, (trait_ref, obligation))| {
2151 if trait_ref.self_ty().references_error() || rcvr_ty.references_error() {
2152 return (None, None, Vec::new());
2154 }
2155 let CustomDiagnostic { message, label, notes, .. } = self
2156 .err_ctxt()
2157 .on_unimplemented_note(trait_ref, &obligation, err.long_ty_path());
2158 (message, label, notes)
2159 })
2160 .unwrap()
2161 } else {
2162 (None, None, Vec::new())
2163 };
2164 let primary_message = primary_message.unwrap_or_else(|| {
2165 let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
2166 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} `{1}` exists for {2} `{3}`, but its trait bounds were not satisfied",
item_kind, item_ident, actual_prefix, ty_str))
})format!(
2167 "the {item_kind} `{item_ident}` exists for {actual_prefix} `{ty_str}`, \
2168 but its trait bounds were not satisfied"
2169 )
2170 });
2171 err.primary_message(primary_message);
2172 if let Some(label) = label {
2173 *custom_span_label = true;
2174 err.span_label(span, label);
2175 }
2176 if !bound_list.is_empty() {
2177 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following trait bounds were not satisfied:\n{0}",
bound_list))
})format!("the following trait bounds were not satisfied:\n{bound_list}"));
2178 }
2179 for note in notes {
2180 err.note(note);
2181 }
2182
2183 if let ty::Adt(adt_def, _) = rcvr_ty.kind() {
2184 unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
2185 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2186 pred.kind().skip_binder()
2187 {
2188 self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
2189 err, &pred, *adt_def,
2190 )
2191 } else {
2192 false
2193 }
2194 });
2195 }
2196
2197 *suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
2198 *unsatisfied_bounds = true;
2199 }
2200 if manually_impl {
2201 err.help("consider manually implementing the trait to avoid undesired bounds");
2202 }
2203 }
2204
2205 fn lookup_segments_chain_for_no_match_method(
2207 &self,
2208 err: &mut Diag<'_>,
2209 item_name: Ident,
2210 item_kind: &str,
2211 source: SelfSource<'tcx>,
2212 no_match_data: &NoMatchData<'tcx>,
2213 ) {
2214 if no_match_data.unsatisfied_predicates.is_empty()
2215 && let Mode::MethodCall = no_match_data.mode
2216 && let SelfSource::MethodCall(mut source_expr) = source
2217 {
2218 let mut stack_methods = ::alloc::vec::Vec::new()vec![];
2219 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, method_span) =
2220 source_expr.kind
2221 {
2222 if let Some(prev_match) = stack_methods.pop() {
2224 err.span_label(
2225 method_span,
2226 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` is available on `{2}`",
item_kind, item_name, prev_match))
})format!("{item_kind} `{item_name}` is available on `{prev_match}`"),
2227 );
2228 }
2229 let rcvr_ty = self.resolve_vars_if_possible(
2230 self.typeck_results
2231 .borrow()
2232 .expr_ty_adjusted_opt(rcvr_expr)
2233 .unwrap_or(Ty::new_misc_error(self.tcx)),
2234 );
2235
2236 let Ok(candidates) = self.probe_for_name_many(
2237 Mode::MethodCall,
2238 item_name,
2239 None,
2240 IsSuggestion(true),
2241 rcvr_ty,
2242 source_expr.hir_id,
2243 ProbeScope::TraitsInScope,
2244 ) else {
2245 return;
2246 };
2247
2248 for _matched_method in candidates {
2252 stack_methods.push(rcvr_ty);
2254 }
2255 source_expr = rcvr_expr;
2256 }
2257 if let Some(prev_match) = stack_methods.pop() {
2259 err.span_label(
2260 source_expr.span,
2261 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` is available on `{2}`",
item_kind, item_name, prev_match))
})format!("{item_kind} `{item_name}` is available on `{prev_match}`"),
2262 );
2263 }
2264 }
2265 }
2266
2267 fn find_likely_intended_associated_item(
2268 &self,
2269 err: &mut Diag<'_>,
2270 similar_candidate: ty::AssocItem,
2271 span: Span,
2272 args: Option<&'tcx [hir::Expr<'tcx>]>,
2273 mode: Mode,
2274 ) {
2275 let tcx = self.tcx;
2276 let def_kind = similar_candidate.as_def_kind();
2277 let an = self.tcx.def_kind_descr_article(def_kind, similar_candidate.def_id);
2278 let similar_candidate_name = similar_candidate.name();
2279 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("there is {2} {0} `{1}` with a similar name",
self.tcx.def_kind_descr(def_kind, similar_candidate.def_id),
similar_candidate_name, an))
})format!(
2280 "there is {an} {} `{}` with a similar name",
2281 self.tcx.def_kind_descr(def_kind, similar_candidate.def_id),
2282 similar_candidate_name,
2283 );
2284 if def_kind == DefKind::AssocFn {
2289 let ty_args = self.infcx.fresh_args_for_item(span, similar_candidate.def_id);
2290 let fn_sig =
2291 tcx.fn_sig(similar_candidate.def_id).instantiate(tcx, ty_args).skip_norm_wip();
2292 let fn_sig = self.instantiate_binder_with_fresh_vars(
2293 span,
2294 BoundRegionConversionTime::FnCall,
2295 fn_sig,
2296 );
2297 if similar_candidate.is_method() {
2298 if let Some(args) = args
2299 && fn_sig.inputs()[1..].len() == args.len()
2300 {
2301 err.span_suggestion_verbose(
2304 span,
2305 msg,
2306 similar_candidate_name,
2307 Applicability::MaybeIncorrect,
2308 );
2309 } else {
2310 err.span_help(
2313 tcx.def_span(similar_candidate.def_id),
2314 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}",
if let None = args {
""
} else { ", but with different arguments" }, msg))
})format!(
2315 "{msg}{}",
2316 if let None = args { "" } else { ", but with different arguments" },
2317 ),
2318 );
2319 }
2320 } else if let Some(args) = args
2321 && fn_sig.inputs().len() == args.len()
2322 {
2323 err.span_suggestion_verbose(
2326 span,
2327 msg,
2328 similar_candidate_name,
2329 Applicability::MaybeIncorrect,
2330 );
2331 } else {
2332 err.span_help(tcx.def_span(similar_candidate.def_id), msg);
2333 }
2334 } else if let Mode::Path = mode
2335 && args.unwrap_or(&[]).is_empty()
2336 {
2337 err.span_suggestion_verbose(
2339 span,
2340 msg,
2341 similar_candidate_name,
2342 Applicability::MaybeIncorrect,
2343 );
2344 } else {
2345 err.span_help(tcx.def_span(similar_candidate.def_id), msg);
2348 }
2349 }
2350
2351 pub(crate) fn confusable_method_name(
2352 &self,
2353 err: &mut Diag<'_>,
2354 rcvr_ty: Ty<'tcx>,
2355 item_name: Ident,
2356 call_args: Option<Vec<Ty<'tcx>>>,
2357 ) -> Option<Symbol> {
2358 if let ty::Adt(adt, adt_args) = rcvr_ty.kind() {
2359 for &inherent_impl_did in self.tcx.inherent_impls(adt.did()).into_iter() {
2360 for inherent_method in
2361 self.tcx.associated_items(inherent_impl_did).in_definition_order()
2362 {
2363 if let Some(confusables) = {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(inherent_method.def_id,
&self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcConfusables { confusables
}) => {
break 'done Some(confusables);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, inherent_method.def_id, RustcConfusables{confusables} => confusables)
2364 && confusables.contains(&item_name.name)
2365 && inherent_method.is_fn()
2366 {
2367 let args =
2368 ty::GenericArgs::identity_for_item(self.tcx, inherent_method.def_id)
2369 .rebase_onto(
2370 self.tcx,
2371 inherent_method.container_id(self.tcx),
2372 adt_args,
2373 );
2374 let fn_sig = self
2375 .tcx
2376 .fn_sig(inherent_method.def_id)
2377 .instantiate(self.tcx, args)
2378 .skip_norm_wip();
2379 let fn_sig = self.instantiate_binder_with_fresh_vars(
2380 item_name.span,
2381 BoundRegionConversionTime::FnCall,
2382 fn_sig,
2383 );
2384 let name = inherent_method.name();
2385 let inputs = fn_sig.inputs();
2386 let expected_inputs =
2387 if inherent_method.is_method() { &inputs[1..] } else { inputs };
2388 if let Some(ref args) = call_args
2389 && expected_inputs
2390 .iter()
2391 .eq_by(args, |expected, found| self.may_coerce(*expected, *found))
2392 {
2393 err.span_suggestion_verbose(
2394 item_name.span,
2395 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use `{0}`",
name))
})format!("you might have meant to use `{}`", name),
2396 name,
2397 Applicability::MaybeIncorrect,
2398 );
2399 return Some(name);
2400 } else if let None = call_args {
2401 err.span_note(
2402 self.tcx.def_span(inherent_method.def_id),
2403 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use method `{0}`",
name))
})format!("you might have meant to use method `{}`", name),
2404 );
2405 return Some(name);
2406 }
2407 }
2408 }
2409 }
2410 }
2411 None
2412 }
2413 fn note_candidates_on_method_error(
2414 &self,
2415 rcvr_ty: Ty<'tcx>,
2416 item_name: Ident,
2417 self_source: SelfSource<'tcx>,
2418 args: Option<&'tcx [hir::Expr<'tcx>]>,
2419 span: Span,
2420 err: &mut Diag<'_>,
2421 sources: &mut Vec<CandidateSource>,
2422 sugg_span: Option<Span>,
2423 ) {
2424 sources.sort_by_key(|source| match *source {
2425 CandidateSource::Trait(id) => (0, self.tcx.def_path_str(id)),
2426 CandidateSource::Impl(id) => (1, self.tcx.def_path_str(id)),
2427 });
2428 sources.dedup();
2429 let limit = if sources.len() == 5 { 5 } else { 4 };
2431
2432 let mut suggs = ::alloc::vec::Vec::new()vec![];
2433 for (idx, source) in sources.iter().take(limit).enumerate() {
2434 match *source {
2435 CandidateSource::Impl(impl_did) => {
2436 let Some(item) = self.associated_value(impl_did, item_name).or_else(|| {
2439 let impl_trait_id = self.tcx.impl_opt_trait_id(impl_did)?;
2440 self.associated_value(impl_trait_id, item_name)
2441 }) else {
2442 continue;
2443 };
2444
2445 let note_span = if item.def_id.is_local() {
2446 Some(self.tcx.def_span(item.def_id))
2447 } else if impl_did.is_local() {
2448 Some(self.tcx.def_span(impl_did))
2449 } else {
2450 None
2451 };
2452
2453 let impl_ty =
2454 self.tcx.at(span).type_of(impl_did).instantiate_identity().skip_norm_wip();
2455
2456 let insertion = match self.tcx.impl_opt_trait_ref(impl_did) {
2457 None => String::new(),
2458 Some(trait_ref) => {
2459 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" of the trait `{0}`",
self.tcx.def_path_str(trait_ref.skip_binder().def_id)))
})format!(
2460 " of the trait `{}`",
2461 self.tcx.def_path_str(trait_ref.skip_binder().def_id)
2462 )
2463 }
2464 };
2465
2466 let (note_str, idx) = if sources.len() > 1 {
2467 (
2468 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("candidate #{0} is defined in an impl{1} for the type `{2}`",
idx + 1, insertion, impl_ty))
})format!(
2469 "candidate #{} is defined in an impl{} for the type `{}`",
2470 idx + 1,
2471 insertion,
2472 impl_ty,
2473 ),
2474 Some(idx + 1),
2475 )
2476 } else {
2477 (
2478 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the candidate is defined in an impl{0} for the type `{1}`",
insertion, impl_ty))
})format!(
2479 "the candidate is defined in an impl{insertion} for the type `{impl_ty}`",
2480 ),
2481 None,
2482 )
2483 };
2484 if let Some(note_span) = note_span {
2485 err.span_note(note_span, note_str);
2487 } else {
2488 err.note(note_str);
2489 }
2490 if let Some(sugg_span) = sugg_span
2491 && let Some(trait_ref) = self.tcx.impl_opt_trait_ref(impl_did)
2492 && let Some(sugg) = print_disambiguation_help(
2493 self.tcx,
2494 err,
2495 self_source,
2496 args,
2497 trait_ref
2498 .instantiate(
2499 self.tcx,
2500 self.fresh_args_for_item(sugg_span, impl_did),
2501 )
2502 .skip_norm_wip()
2503 .with_replaced_self_ty(self.tcx, rcvr_ty),
2504 idx,
2505 sugg_span,
2506 item,
2507 )
2508 {
2509 suggs.push(sugg);
2510 }
2511 }
2512 CandidateSource::Trait(trait_did) => {
2513 let Some(item) = self.associated_value(trait_did, item_name) else { continue };
2514 let item_span = self.tcx.def_span(item.def_id);
2515 let idx = if sources.len() > 1 {
2516 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("candidate #{0} is defined in the trait `{1}`",
idx + 1, self.tcx.def_path_str(trait_did)))
})format!(
2517 "candidate #{} is defined in the trait `{}`",
2518 idx + 1,
2519 self.tcx.def_path_str(trait_did)
2520 );
2521 err.span_note(item_span, msg);
2522 Some(idx + 1)
2523 } else {
2524 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the candidate is defined in the trait `{0}`",
self.tcx.def_path_str(trait_did)))
})format!(
2525 "the candidate is defined in the trait `{}`",
2526 self.tcx.def_path_str(trait_did)
2527 );
2528 err.span_note(item_span, msg);
2529 None
2530 };
2531 if let Some(sugg_span) = sugg_span
2532 && let Some(sugg) = print_disambiguation_help(
2533 self.tcx,
2534 err,
2535 self_source,
2536 args,
2537 ty::TraitRef::new_from_args(
2538 self.tcx,
2539 trait_did,
2540 self.fresh_args_for_item(sugg_span, trait_did),
2541 )
2542 .with_replaced_self_ty(self.tcx, rcvr_ty),
2543 idx,
2544 sugg_span,
2545 item,
2546 )
2547 {
2548 suggs.push(sugg);
2549 }
2550 }
2551 }
2552 }
2553 if !suggs.is_empty()
2554 && let Some(span) = sugg_span
2555 {
2556 suggs.sort();
2557 err.span_suggestions(
2558 span.with_hi(item_name.span.lo()),
2559 "use fully-qualified syntax to disambiguate",
2560 suggs,
2561 Applicability::MachineApplicable,
2562 );
2563 }
2564 if sources.len() > limit {
2565 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("and {0} others",
sources.len() - limit))
})format!("and {} others", sources.len() - limit));
2566 }
2567 }
2568
2569 fn find_builder_fn(&self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>, expr_id: hir::HirId) {
2572 let ty::Adt(adt_def, _) = rcvr_ty.kind() else {
2573 return;
2574 };
2575 let mut items = self
2576 .tcx
2577 .inherent_impls(adt_def.did())
2578 .iter()
2579 .flat_map(|&i| self.tcx.associated_items(i).in_definition_order())
2580 .filter(|item| {
2583 #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ty::AssocKind::Fn { has_self: false, .. } => true,
_ => false,
}matches!(item.kind, ty::AssocKind::Fn { has_self: false, .. })
2584 && self
2585 .probe_for_name(
2586 Mode::Path,
2587 item.ident(self.tcx),
2588 None,
2589 IsSuggestion(true),
2590 rcvr_ty,
2591 expr_id,
2592 ProbeScope::TraitsInScope,
2593 )
2594 .is_ok()
2595 })
2596 .filter_map(|item| {
2597 let ret_ty = self
2599 .tcx
2600 .fn_sig(item.def_id)
2601 .instantiate(self.tcx, self.fresh_args_for_item(DUMMY_SP, item.def_id))
2602 .skip_norm_wip()
2603 .output();
2604 let ret_ty = self.tcx.instantiate_bound_regions_with_erased(ret_ty);
2605 let ty::Adt(def, args) = ret_ty.kind() else {
2606 return None;
2607 };
2608 if self.can_eq(self.param_env, ret_ty, rcvr_ty) {
2610 return Some((item.def_id, ret_ty));
2611 }
2612 if ![self.tcx.lang_items().option_type(), self.tcx.get_diagnostic_item(sym::Result)]
2614 .contains(&Some(def.did()))
2615 {
2616 return None;
2617 }
2618 let arg = args.get(0)?.expect_ty();
2619 if self.can_eq(self.param_env, rcvr_ty, arg) {
2620 Some((item.def_id, ret_ty))
2621 } else {
2622 None
2623 }
2624 })
2625 .collect::<Vec<_>>();
2626 let post = if items.len() > 5 {
2627 let items_len = items.len();
2628 items.truncate(4);
2629 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} others", items_len - 4))
})format!("\nand {} others", items_len - 4)
2630 } else {
2631 String::new()
2632 };
2633 match items[..] {
2634 [] => {}
2635 [(def_id, ret_ty)] => {
2636 err.span_note(
2637 self.tcx.def_span(def_id),
2638 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you\'re trying to build a new `{1}`, consider using `{0}` which returns `{2}`",
self.tcx.def_path_str(def_id), rcvr_ty, ret_ty))
})format!(
2639 "if you're trying to build a new `{rcvr_ty}`, consider using `{}` which \
2640 returns `{ret_ty}`",
2641 self.tcx.def_path_str(def_id),
2642 ),
2643 );
2644 }
2645 _ => {
2646 let span: MultiSpan = items
2647 .iter()
2648 .map(|&(def_id, _)| self.tcx.def_span(def_id))
2649 .collect::<Vec<Span>>()
2650 .into();
2651 err.span_note(
2652 span,
2653 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you\'re trying to build a new `{1}` consider using one of the following associated functions:\n{0}{2}",
items.iter().map(|&(def_id, _ret_ty)|
self.tcx.def_path_str(def_id)).collect::<Vec<String>>().join("\n"),
rcvr_ty, post))
})format!(
2654 "if you're trying to build a new `{rcvr_ty}` consider using one of the \
2655 following associated functions:\n{}{post}",
2656 items
2657 .iter()
2658 .map(|&(def_id, _ret_ty)| self.tcx.def_path_str(def_id))
2659 .collect::<Vec<String>>()
2660 .join("\n")
2661 ),
2662 );
2663 }
2664 }
2665 }
2666
2667 fn suggest_associated_call_syntax(
2670 &self,
2671 err: &mut Diag<'_>,
2672 static_candidates: &[CandidateSource],
2673 rcvr_ty: Ty<'tcx>,
2674 source: SelfSource<'tcx>,
2675 item_name: Ident,
2676 args: Option<&'tcx [hir::Expr<'tcx>]>,
2677 sugg_span: Span,
2678 ) {
2679 let mut has_unsuggestable_args = false;
2680 let ty_str = if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0) {
2681 let impl_ty = self.tcx.type_of(*impl_did).instantiate_identity().skip_norm_wip();
2685 let target_ty = self
2686 .autoderef(sugg_span, rcvr_ty)
2687 .silence_errors()
2688 .find(|(rcvr_ty, _)| {
2689 DeepRejectCtxt::relate_rigid_infer(self.tcx).types_may_unify(*rcvr_ty, impl_ty)
2690 })
2691 .map_or(impl_ty, |(ty, _)| ty)
2692 .peel_refs();
2693 if let ty::Adt(def, args) = target_ty.kind() {
2694 let infer_args = self.tcx.mk_args_from_iter(args.into_iter().map(|arg| {
2697 if !arg.is_suggestable(self.tcx, true) {
2698 has_unsuggestable_args = true;
2699 match arg.kind() {
2700 GenericArgKind::Lifetime(_) => {
2701 self.next_region_var(RegionVariableOrigin::Misc(DUMMY_SP)).into()
2702 }
2703 GenericArgKind::Type(_) => self.next_ty_var(DUMMY_SP).into(),
2704 GenericArgKind::Const(_) => self.next_const_var(DUMMY_SP).into(),
2705 }
2706 } else {
2707 arg
2708 }
2709 }));
2710
2711 self.tcx.value_path_str_with_args(def.did(), infer_args)
2712 } else {
2713 self.ty_to_value_string(target_ty)
2714 }
2715 } else {
2716 self.ty_to_value_string(rcvr_ty.peel_refs())
2717 };
2718 if let SelfSource::MethodCall(_) = source {
2719 let first_arg = static_candidates.get(0).and_then(|candidate_source| {
2720 let (assoc_did, self_ty) = match candidate_source {
2721 CandidateSource::Impl(impl_did) => (
2722 *impl_did,
2723 self.tcx.type_of(*impl_did).instantiate_identity().skip_norm_wip(),
2724 ),
2725 CandidateSource::Trait(trait_did) => (*trait_did, rcvr_ty),
2726 };
2727
2728 let assoc = self.associated_value(assoc_did, item_name)?;
2729 if !assoc.is_fn() {
2730 return None;
2731 }
2732
2733 let sig = self.tcx.fn_sig(assoc.def_id).instantiate_identity().skip_norm_wip();
2736 sig.inputs().skip_binder().get(0).and_then(|first| {
2737 let first_ty = first.peel_refs();
2739 if first_ty == self_ty || first_ty == self.tcx.types.self_param {
2740 Some(first.ref_mutability().map_or("", |mutbl| mutbl.ref_prefix_str()))
2741 } else {
2742 None
2743 }
2744 })
2745 });
2746
2747 let mut applicability = Applicability::MachineApplicable;
2748 let args = if let SelfSource::MethodCall(receiver) = source
2749 && let Some(args) = args
2750 {
2751 let explicit_args = if first_arg.is_some() {
2753 std::iter::once(receiver).chain(args.iter()).collect::<Vec<_>>()
2754 } else {
2755 if has_unsuggestable_args {
2757 applicability = Applicability::HasPlaceholders;
2758 }
2759 args.iter().collect()
2760 };
2761 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}{1})", first_arg.unwrap_or(""),
explicit_args.iter().map(|arg|
self.tcx.sess.source_map().span_to_snippet(arg.span).unwrap_or_else(|_|
{
applicability = Applicability::HasPlaceholders;
"_".to_owned()
})).collect::<Vec<_>>().join(", ")))
})format!(
2762 "({}{})",
2763 first_arg.unwrap_or(""),
2764 explicit_args
2765 .iter()
2766 .map(|arg| self
2767 .tcx
2768 .sess
2769 .source_map()
2770 .span_to_snippet(arg.span)
2771 .unwrap_or_else(|_| {
2772 applicability = Applicability::HasPlaceholders;
2773 "_".to_owned()
2774 }))
2775 .collect::<Vec<_>>()
2776 .join(", "),
2777 )
2778 } else {
2779 applicability = Applicability::HasPlaceholders;
2780 "(...)".to_owned()
2781 };
2782 err.span_suggestion_verbose(
2783 sugg_span,
2784 "use associated function syntax instead",
2785 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}{2}", ty_str, item_name,
args))
})format!("{ty_str}::{item_name}{args}"),
2786 applicability,
2787 );
2788 } else {
2789 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try with `{0}::{1}`", ty_str,
item_name))
})format!("try with `{ty_str}::{item_name}`",));
2790 }
2791 }
2792
2793 fn suggest_calling_field_as_fn(
2796 &self,
2797 span: Span,
2798 rcvr_ty: Ty<'tcx>,
2799 expr: &hir::Expr<'_>,
2800 item_name: Ident,
2801 err: &mut Diag<'_>,
2802 ) -> bool {
2803 let tcx = self.tcx;
2804 let field_receiver =
2805 self.autoderef(span, rcvr_ty).silence_errors().find_map(|(ty, _)| match ty.kind() {
2806 ty::Adt(def, args) if !def.is_enum() => {
2807 let variant = &def.non_enum_variant();
2808 tcx.find_field_index(item_name, variant).map(|index| {
2809 let field = &variant.fields[index];
2810 let field_ty = field.ty(tcx, args).skip_norm_wip();
2811 (field, field_ty)
2812 })
2813 }
2814 _ => None,
2815 });
2816 if let Some((field, field_ty)) = field_receiver {
2817 let scope = tcx.parent_module_from_def_id(self.body_id);
2818 let is_accessible = field.vis.is_accessible_from(scope, tcx);
2819
2820 if is_accessible {
2821 if let Some((what, _, _)) = self.extract_callable_info(field_ty) {
2822 let what = match what {
2823 DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
2824 DefIdOrName::Name(what) => what,
2825 };
2826 let expr_span = expr.span.to(item_name.span);
2827 err.multipart_suggestion(
2828 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to call the {0} stored in `{1}`, surround the field access with parentheses",
what, item_name))
})format!(
2829 "to call the {what} stored in `{item_name}`, \
2830 surround the field access with parentheses",
2831 ),
2832 ::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(), ')'.to_string())]))vec![
2833 (expr_span.shrink_to_lo(), '('.to_string()),
2834 (expr_span.shrink_to_hi(), ')'.to_string()),
2835 ],
2836 Applicability::MachineApplicable,
2837 );
2838 } else {
2839 let call_expr = tcx.hir_expect_expr(tcx.parent_hir_id(expr.hir_id));
2840
2841 if let Some(span) = call_expr.span.trim_start(item_name.span) {
2842 err.span_suggestion(
2843 span,
2844 "remove the arguments",
2845 "",
2846 Applicability::MaybeIncorrect,
2847 );
2848 }
2849 }
2850 }
2851
2852 let field_kind = if is_accessible { "field" } else { "private field" };
2853 err.span_label(item_name.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, not a method", field_kind))
})format!("{field_kind}, not a method"));
2854 return true;
2855 }
2856 false
2857 }
2858
2859 fn report_failed_method_call_on_range_end(
2862 &self,
2863 tcx: TyCtxt<'tcx>,
2864 actual: Ty<'tcx>,
2865 source: SelfSource<'tcx>,
2866 span: Span,
2867 item_name: Ident,
2868 ) -> Result<(), ErrorGuaranteed> {
2869 if let SelfSource::MethodCall(expr) = source {
2870 for (_, parent) in tcx.hir_parent_iter(expr.hir_id).take(5) {
2871 if let Node::Expr(parent_expr) = parent {
2872 if !is_range_literal(parent_expr) {
2873 continue;
2874 }
2875 let lang_item = match parent_expr.kind {
2876 ExprKind::Struct(qpath, _, _) => match tcx.qpath_lang_item(*qpath) {
2877 Some(
2878 lang_item @ (LangItem::Range
2879 | LangItem::RangeCopy
2880 | LangItem::RangeInclusiveCopy
2881 | LangItem::RangeTo
2882 | LangItem::RangeToInclusive),
2883 ) => Some(lang_item),
2884 _ => None,
2885 },
2886 ExprKind::Call(func, _) => match func.kind {
2887 ExprKind::Path(qpath)
2889 if tcx.qpath_is_lang_item(qpath, LangItem::RangeInclusiveNew) =>
2890 {
2891 Some(LangItem::RangeInclusiveStruct)
2892 }
2893 _ => None,
2894 },
2895 _ => None,
2896 };
2897
2898 if lang_item.is_none() {
2899 continue;
2900 }
2901
2902 let span_included = match parent_expr.kind {
2903 hir::ExprKind::Struct(_, eps, _) => {
2904 eps.last().is_some_and(|ep| ep.span.contains(span))
2905 }
2906 hir::ExprKind::Call(func, ..) => func.span.contains(span),
2908 _ => false,
2909 };
2910
2911 if !span_included {
2912 continue;
2913 }
2914
2915 let Some(range_def_id) =
2916 lang_item.and_then(|lang_item| self.tcx.lang_items().get(lang_item))
2917 else {
2918 continue;
2919 };
2920 let range_ty = self
2921 .tcx
2922 .type_of(range_def_id)
2923 .instantiate(self.tcx, &[actual.into()])
2924 .skip_norm_wip();
2925
2926 let pick = self.lookup_probe_for_diagnostic(
2927 item_name,
2928 range_ty,
2929 expr,
2930 ProbeScope::AllTraits,
2931 None,
2932 );
2933 if pick.is_ok() {
2934 let range_span = parent_expr.span.with_hi(expr.span.hi());
2935 return Err(self.dcx().emit_err(errors::MissingParenthesesInRange {
2936 span,
2937 ty: actual,
2938 method_name: item_name.as_str().to_string(),
2939 add_missing_parentheses: Some(errors::AddMissingParenthesesInRange {
2940 func_name: item_name.name.as_str().to_string(),
2941 left: range_span.shrink_to_lo(),
2942 right: range_span.shrink_to_hi(),
2943 }),
2944 }));
2945 }
2946 }
2947 }
2948 }
2949 Ok(())
2950 }
2951
2952 fn report_failed_method_call_on_numerical_infer_var(
2953 &self,
2954 tcx: TyCtxt<'tcx>,
2955 actual: Ty<'tcx>,
2956 source: SelfSource<'_>,
2957 span: Span,
2958 item_kind: &str,
2959 item_name: Ident,
2960 long_ty_path: &mut Option<PathBuf>,
2961 ) -> Result<(), ErrorGuaranteed> {
2962 let found_candidate = all_traits(self.tcx)
2963 .into_iter()
2964 .any(|info| self.associated_value(info.def_id, item_name).is_some());
2965 let found_assoc = |ty: Ty<'tcx>| {
2966 simplify_type(tcx, ty, TreatParams::InstantiateWithInfer)
2967 .and_then(|simp| {
2968 tcx.incoherent_impls(simp)
2969 .iter()
2970 .find_map(|&id| self.associated_value(id, item_name))
2971 })
2972 .is_some()
2973 };
2974 let found_candidate = found_candidate
2975 || found_assoc(tcx.types.i8)
2976 || found_assoc(tcx.types.i16)
2977 || found_assoc(tcx.types.i32)
2978 || found_assoc(tcx.types.i64)
2979 || found_assoc(tcx.types.i128)
2980 || found_assoc(tcx.types.u8)
2981 || found_assoc(tcx.types.u16)
2982 || found_assoc(tcx.types.u32)
2983 || found_assoc(tcx.types.u64)
2984 || found_assoc(tcx.types.u128)
2985 || found_assoc(tcx.types.f32)
2986 || found_assoc(tcx.types.f64);
2987 if found_candidate
2988 && actual.is_numeric()
2989 && !actual.has_concrete_skeleton()
2990 && let SelfSource::MethodCall(expr) = source
2991 {
2992 let ty_str = self.tcx.short_string(actual, long_ty_path);
2993 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("can\'t call {0} `{1}` on ambiguous numeric type `{2}`",
item_kind, item_name, ty_str))
})).with_code(E0689)
}struct_span_code_err!(
2994 self.dcx(),
2995 span,
2996 E0689,
2997 "can't call {item_kind} `{item_name}` on ambiguous numeric type `{ty_str}`"
2998 );
2999 *err.long_ty_path() = long_ty_path.take();
3000 let concrete_type = if actual.is_integral() { "i32" } else { "f32" };
3001 match expr.kind {
3002 ExprKind::Lit(lit) => {
3003 let snippet = tcx
3005 .sess
3006 .source_map()
3007 .span_to_snippet(lit.span)
3008 .unwrap_or_else(|_| "<numeric literal>".to_owned());
3009
3010 let snippet = snippet.trim_suffix('.');
3013 err.span_suggestion(
3014 lit.span,
3015 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you must specify a concrete type for this numeric value, like `{0}`",
concrete_type))
})format!(
3016 "you must specify a concrete type for this numeric value, \
3017 like `{concrete_type}`"
3018 ),
3019 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_{1}", snippet, concrete_type))
})format!("{snippet}_{concrete_type}"),
3020 Applicability::MaybeIncorrect,
3021 );
3022 }
3023 ExprKind::Path(QPath::Resolved(_, path)) => {
3024 if let hir::def::Res::Local(hir_id) = path.res {
3026 let span = tcx.hir_span(hir_id);
3027 let filename = tcx.sess.source_map().span_to_filename(span);
3028
3029 let parent_node = self.tcx.parent_hir_node(hir_id);
3030 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you must specify a type for this binding, like `{0}`",
concrete_type))
})format!(
3031 "you must specify a type for this binding, like `{concrete_type}`",
3032 );
3033
3034 match (filename, parent_node) {
3037 (
3038 FileName::Real(_),
3039 Node::LetStmt(hir::LetStmt {
3040 source: hir::LocalSource::Normal,
3041 ty,
3042 ..
3043 }),
3044 ) => {
3045 let type_span = ty
3046 .map(|ty| ty.span.with_lo(span.hi()))
3047 .unwrap_or(span.shrink_to_hi());
3048 err.span_suggestion(
3049 type_span,
3052 msg,
3053 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}", concrete_type))
})format!(": {concrete_type}"),
3054 Applicability::MaybeIncorrect,
3055 );
3056 }
3057 (FileName::Real(_), Node::Pat(pat))
3060 if let Node::Pat(binding_pat) = self.tcx.hir_node(hir_id)
3061 && let hir::PatKind::Binding(..) = binding_pat.kind
3062 && let Node::Pat(parent_pat) = parent_node
3063 && #[allow(non_exhaustive_omitted_patterns)] match parent_pat.kind {
hir::PatKind::Ref(..) => true,
_ => false,
}matches!(parent_pat.kind, hir::PatKind::Ref(..)) =>
3064 {
3065 err.span_label(span, "you must specify a type for this binding");
3066
3067 let mut ref_muts = Vec::new();
3068 let mut current_node = parent_node;
3069
3070 while let Node::Pat(parent_pat) = current_node {
3071 if let hir::PatKind::Ref(_, _, mutability) = parent_pat.kind {
3072 ref_muts.push(mutability);
3073 current_node = self.tcx.parent_hir_node(parent_pat.hir_id);
3074 } else {
3075 break;
3076 }
3077 }
3078
3079 let mut type_annotation = String::new();
3080 for mutability in ref_muts.iter().rev() {
3081 match mutability {
3082 hir::Mutability::Mut => type_annotation.push_str("&mut "),
3083 hir::Mutability::Not => type_annotation.push('&'),
3084 }
3085 }
3086 type_annotation.push_str(&concrete_type);
3087
3088 err.span_suggestion_verbose(
3089 pat.span.shrink_to_hi(),
3090 "specify the type in the closure argument list",
3091 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}", type_annotation))
})format!(": {type_annotation}"),
3092 Applicability::MaybeIncorrect,
3093 );
3094 }
3095 _ => {
3096 err.span_label(span, msg);
3097 }
3098 }
3099 }
3100 }
3101 _ => {}
3102 }
3103 return Err(err.emit());
3104 }
3105 Ok(())
3106 }
3107
3108 pub(crate) fn suggest_assoc_method_call(&self, segs: &[PathSegment<'_>]) {
3112 {
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/method/suggest.rs:3112",
"rustc_hir_typeck::method::suggest",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/suggest.rs"),
::tracing_core::__macro_support::Option::Some(3112u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::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};
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!("suggest_assoc_method_call segs: {0:?}",
segs) as &dyn Value))])
});
} else { ; }
};debug!("suggest_assoc_method_call segs: {:?}", segs);
3113 let [seg1, seg2] = segs else {
3114 return;
3115 };
3116 self.dcx().try_steal_modify_and_emit_err(
3117 seg1.ident.span,
3118 StashKey::CallAssocMethod,
3119 |err| {
3120 let body = self.tcx.hir_body_owned_by(self.body_id);
3121 struct LetVisitor {
3122 ident_name: Symbol,
3123 }
3124
3125 impl<'v> Visitor<'v> for LetVisitor {
3127 type Result = ControlFlow<Option<&'v hir::Expr<'v>>>;
3128 fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) -> Self::Result {
3129 if let hir::StmtKind::Let(&hir::LetStmt { pat, init, .. }) = ex.kind
3130 && let hir::PatKind::Binding(_, _, ident, ..) = pat.kind
3131 && ident.name == self.ident_name
3132 {
3133 ControlFlow::Break(init)
3134 } else {
3135 hir::intravisit::walk_stmt(self, ex)
3136 }
3137 }
3138 }
3139
3140 if let Node::Expr(call_expr) = self.tcx.parent_hir_node(seg1.hir_id)
3141 && let ControlFlow::Break(Some(expr)) =
3142 (LetVisitor { ident_name: seg1.ident.name }).visit_body(body)
3143 && let Some(self_ty) = self.node_ty_opt(expr.hir_id)
3144 {
3145 let probe = self.lookup_probe_for_diagnostic(
3146 seg2.ident,
3147 self_ty,
3148 call_expr,
3149 ProbeScope::TraitsInScope,
3150 None,
3151 );
3152 if probe.is_ok() {
3153 let sm = self.infcx.tcx.sess.source_map();
3154 err.span_suggestion_verbose(
3155 sm.span_extend_while(seg1.ident.span.shrink_to_hi(), |c| c == ':')
3156 .unwrap(),
3157 "you may have meant to call an instance method",
3158 ".",
3159 Applicability::MaybeIncorrect,
3160 );
3161 }
3162 }
3163 },
3164 );
3165 }
3166
3167 fn suggest_calling_method_on_field(
3169 &self,
3170 err: &mut Diag<'_>,
3171 source: SelfSource<'tcx>,
3172 span: Span,
3173 actual: Ty<'tcx>,
3174 item_name: Ident,
3175 return_type: Option<Ty<'tcx>>,
3176 ) {
3177 if let SelfSource::MethodCall(expr) = source {
3178 let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id();
3179 for fields in self.get_field_candidates_considering_privacy_for_diag(
3180 span,
3181 actual,
3182 mod_id,
3183 expr.hir_id,
3184 ) {
3185 let call_expr = self.tcx.hir_expect_expr(self.tcx.parent_hir_id(expr.hir_id));
3186
3187 let lang_items = self.tcx.lang_items();
3188 let never_mention_traits = [
3189 lang_items.clone_trait(),
3190 lang_items.deref_trait(),
3191 lang_items.deref_mut_trait(),
3192 self.tcx.get_diagnostic_item(sym::AsRef),
3193 self.tcx.get_diagnostic_item(sym::AsMut),
3194 self.tcx.get_diagnostic_item(sym::Borrow),
3195 self.tcx.get_diagnostic_item(sym::BorrowMut),
3196 ];
3197 let mut candidate_fields: Vec<_> = fields
3198 .into_iter()
3199 .filter_map(|candidate_field| {
3200 self.check_for_nested_field_satisfying_condition_for_diag(
3201 span,
3202 &|_, field_ty| {
3203 self.lookup_probe_for_diagnostic(
3204 item_name,
3205 field_ty,
3206 call_expr,
3207 ProbeScope::TraitsInScope,
3208 return_type,
3209 )
3210 .is_ok_and(|pick| {
3211 !never_mention_traits
3212 .iter()
3213 .flatten()
3214 .any(|def_id| self.tcx.parent(pick.item.def_id) == *def_id)
3215 })
3216 },
3217 candidate_field,
3218 ::alloc::vec::Vec::new()vec![],
3219 mod_id,
3220 expr.hir_id,
3221 )
3222 })
3223 .map(|field_path| {
3224 field_path
3225 .iter()
3226 .map(|id| id.to_string())
3227 .collect::<Vec<String>>()
3228 .join(".")
3229 })
3230 .collect();
3231 candidate_fields.sort();
3232
3233 let len = candidate_fields.len();
3234 if len > 0 {
3235 err.span_suggestions(
3236 item_name.span.shrink_to_lo(),
3237 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} of the expressions\' fields {1} a method of the same name",
if len > 1 { "some" } else { "one" },
if len > 1 { "have" } else { "has" }))
})format!(
3238 "{} of the expressions' fields {} a method of the same name",
3239 if len > 1 { "some" } else { "one" },
3240 if len > 1 { "have" } else { "has" },
3241 ),
3242 candidate_fields.iter().map(|path| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.", path))
})format!("{path}.")),
3243 Applicability::MaybeIncorrect,
3244 );
3245 }
3246 }
3247 }
3248 }
3249
3250 fn suggest_unwrapping_inner_self(
3251 &self,
3252 err: &mut Diag<'_>,
3253 source: SelfSource<'tcx>,
3254 actual: Ty<'tcx>,
3255 item_name: Ident,
3256 ) {
3257 let tcx = self.tcx;
3258 let SelfSource::MethodCall(expr) = source else {
3259 return;
3260 };
3261 let call_expr = tcx.hir_expect_expr(tcx.parent_hir_id(expr.hir_id));
3262
3263 let ty::Adt(kind, args) = actual.kind() else {
3264 return;
3265 };
3266 match kind.adt_kind() {
3267 ty::AdtKind::Enum => {
3268 let matching_variants: Vec<_> = kind
3269 .variants()
3270 .iter()
3271 .flat_map(|variant| {
3272 let [field] = &variant.fields.raw[..] else {
3273 return None;
3274 };
3275 let field_ty = field.ty(tcx, args).skip_norm_wip();
3276
3277 if self.resolve_vars_if_possible(field_ty).is_ty_var() {
3279 return None;
3280 }
3281
3282 self.lookup_probe_for_diagnostic(
3283 item_name,
3284 field_ty,
3285 call_expr,
3286 ProbeScope::TraitsInScope,
3287 None,
3288 )
3289 .ok()
3290 .map(|pick| (variant, field, pick))
3291 })
3292 .collect();
3293
3294 let ret_ty_matches = |diagnostic_item| {
3295 if let Some(ret_ty) = self
3296 .ret_coercion
3297 .as_ref()
3298 .map(|c| self.resolve_vars_if_possible(c.borrow().expected_ty()))
3299 && let ty::Adt(kind, _) = ret_ty.kind()
3300 && tcx.get_diagnostic_item(diagnostic_item) == Some(kind.did())
3301 {
3302 true
3303 } else {
3304 false
3305 }
3306 };
3307
3308 match &matching_variants[..] {
3309 [(_, field, pick)] => {
3310 let self_ty = field.ty(tcx, args).skip_norm_wip();
3311 err.span_note(
3312 tcx.def_span(pick.item.def_id),
3313 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the method `{0}` exists on the type `{1}`",
item_name, self_ty))
})format!("the method `{item_name}` exists on the type `{self_ty}`"),
3314 );
3315 let (article, kind, variant, question) = if tcx.is_diagnostic_item(sym::Result, kind.did())
3316 && !tcx.hir_is_inside_const_context(expr.hir_id)
3318 {
3319 ("a", "Result", "Err", ret_ty_matches(sym::Result))
3320 } else if tcx.is_diagnostic_item(sym::Option, kind.did()) {
3321 ("an", "Option", "None", ret_ty_matches(sym::Option))
3322 } else {
3323 return;
3324 };
3325 if question {
3326 err.span_suggestion_verbose(
3327 expr.span.shrink_to_hi(),
3328 ::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",
self_ty, article, kind, variant))
})format!(
3329 "use the `?` operator to extract the `{self_ty}` value, propagating \
3330 {article} `{kind}::{variant}` value to the caller"
3331 ),
3332 "?",
3333 Applicability::MachineApplicable,
3334 );
3335 } else {
3336 err.span_suggestion_verbose(
3337 expr.span.shrink_to_hi(),
3338 ::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, self_ty, article, variant))
})format!(
3339 "consider using `{kind}::expect` to unwrap the `{self_ty}` value, \
3340 panicking if the value is {article} `{kind}::{variant}`"
3341 ),
3342 ".expect(\"REASON\")",
3343 Applicability::HasPlaceholders,
3344 );
3345 }
3346 }
3347 _ => {}
3349 }
3350 }
3351 ty::AdtKind::Struct | ty::AdtKind::Union => {
3354 let [first] = ***args else {
3355 return;
3356 };
3357 let ty::GenericArgKind::Type(ty) = first.kind() else {
3358 return;
3359 };
3360 let Ok(pick) = self.lookup_probe_for_diagnostic(
3361 item_name,
3362 ty,
3363 call_expr,
3364 ProbeScope::TraitsInScope,
3365 None,
3366 ) else {
3367 return;
3368 };
3369
3370 let name = self.ty_to_value_string(actual);
3371 let inner_id = kind.did();
3372 let mutable = if let Some(AutorefOrPtrAdjustment::Autoref { mutbl, .. }) =
3373 pick.autoref_or_ptr_adjustment
3374 {
3375 Some(mutbl)
3376 } else {
3377 None
3378 };
3379
3380 if tcx.is_diagnostic_item(sym::LocalKey, inner_id) {
3381 err.help("use `with` or `try_with` to access thread local storage");
3382 } else if tcx.is_lang_item(kind.did(), LangItem::MaybeUninit) {
3383 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if this `{0}` has been initialized, use one of the `assume_init` methods to access the inner value",
name))
})format!(
3384 "if this `{name}` has been initialized, \
3385 use one of the `assume_init` methods to access the inner value"
3386 ));
3387 } else if tcx.is_diagnostic_item(sym::RefCell, inner_id) {
3388 let (suggestion, borrow_kind, panic_if) = match mutable {
3389 Some(Mutability::Not) => (".borrow()", "borrow", "a mutable borrow exists"),
3390 Some(Mutability::Mut) => {
3391 (".borrow_mut()", "mutably borrow", "any borrows exist")
3392 }
3393 None => return,
3394 };
3395 err.span_suggestion_verbose(
3396 expr.span.shrink_to_hi(),
3397 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `{0}` to {1} the `{2}`, panicking if {3}",
suggestion, borrow_kind, ty, panic_if))
})format!(
3398 "use `{suggestion}` to {borrow_kind} the `{ty}`, \
3399 panicking if {panic_if}"
3400 ),
3401 suggestion,
3402 Applicability::MaybeIncorrect,
3403 );
3404 } else if tcx.is_diagnostic_item(sym::Mutex, inner_id) {
3405 err.span_suggestion_verbose(
3406 expr.span.shrink_to_hi(),
3407 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `.lock().unwrap()` to borrow the `{0}`, blocking the current thread until it can be acquired",
ty))
})format!(
3408 "use `.lock().unwrap()` to borrow the `{ty}`, \
3409 blocking the current thread until it can be acquired"
3410 ),
3411 ".lock().unwrap()",
3412 Applicability::MaybeIncorrect,
3413 );
3414 } else if tcx.is_diagnostic_item(sym::RwLock, inner_id) {
3415 let (suggestion, borrow_kind) = match mutable {
3416 Some(Mutability::Not) => (".read().unwrap()", "borrow"),
3417 Some(Mutability::Mut) => (".write().unwrap()", "mutably borrow"),
3418 None => return,
3419 };
3420 err.span_suggestion_verbose(
3421 expr.span.shrink_to_hi(),
3422 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `{0}` to {1} the `{2}`, blocking the current thread until it can be acquired",
suggestion, borrow_kind, ty))
})format!(
3423 "use `{suggestion}` to {borrow_kind} the `{ty}`, \
3424 blocking the current thread until it can be acquired"
3425 ),
3426 suggestion,
3427 Applicability::MaybeIncorrect,
3428 );
3429 } else {
3430 return;
3431 };
3432
3433 err.span_note(
3434 tcx.def_span(pick.item.def_id),
3435 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the method `{0}` exists on the type `{1}`",
item_name, ty))
})format!("the method `{item_name}` exists on the type `{ty}`"),
3436 );
3437 }
3438 }
3439 }
3440
3441 pub(crate) fn note_unmet_impls_on_type(
3442 &self,
3443 err: &mut Diag<'_>,
3444 errors: &[FulfillmentError<'tcx>],
3445 suggest_derive: bool,
3446 ) {
3447 let preds: Vec<_> = errors
3448 .iter()
3449 .filter_map(|e| match e.obligation.predicate.kind().skip_binder() {
3450 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
3451 match pred.self_ty().kind() {
3452 ty::Adt(_, _) => Some((e.root_obligation.predicate, pred)),
3453 _ => None,
3454 }
3455 }
3456 _ => None,
3457 })
3458 .collect();
3459
3460 let (mut local_preds, mut foreign_preds): (Vec<_>, Vec<_>) =
3462 preds.iter().partition(|&(_, pred)| {
3463 if let ty::Adt(def, _) = pred.self_ty().kind() {
3464 def.did().is_local()
3465 } else {
3466 false
3467 }
3468 });
3469
3470 local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
3471 let local_def_ids = local_preds
3472 .iter()
3473 .filter_map(|(_, pred)| match pred.self_ty().kind() {
3474 ty::Adt(def, _) => Some(def.did()),
3475 _ => None,
3476 })
3477 .collect::<FxIndexSet<_>>();
3478 let mut local_spans: MultiSpan = local_def_ids
3479 .iter()
3480 .filter_map(|def_id| {
3481 let span = self.tcx.def_span(*def_id);
3482 if span.is_dummy() { None } else { Some(span) }
3483 })
3484 .collect::<Vec<_>>()
3485 .into();
3486 for (_, pred) in &local_preds {
3487 if let ty::Adt(def, _) = pred.self_ty().kind() {
3488 local_spans.push_span_label(
3489 self.tcx.def_span(def.did()),
3490 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("must implement `{0}`",
pred.trait_ref.print_trait_sugared()))
})format!("must implement `{}`", pred.trait_ref.print_trait_sugared()),
3491 );
3492 }
3493 }
3494 if local_spans.primary_span().is_some() {
3495 let msg = if let [(_, local_pred)] = local_preds.as_slice() {
3496 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("an implementation of `{0}` might be missing for `{1}`",
local_pred.trait_ref.print_trait_sugared(),
local_pred.self_ty()))
})format!(
3497 "an implementation of `{}` might be missing for `{}`",
3498 local_pred.trait_ref.print_trait_sugared(),
3499 local_pred.self_ty()
3500 )
3501 } else {
3502 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following type{0} would have to `impl` {1} required trait{2} for this operation to be valid",
if local_def_ids.len() == 1 { "" } else { "s" },
if local_def_ids.len() == 1 { "its" } else { "their" },
if local_preds.len() == 1 { "" } else { "s" }))
})format!(
3503 "the following type{} would have to `impl` {} required trait{} for this \
3504 operation to be valid",
3505 pluralize!(local_def_ids.len()),
3506 if local_def_ids.len() == 1 { "its" } else { "their" },
3507 pluralize!(local_preds.len()),
3508 )
3509 };
3510 err.span_note(local_spans, msg);
3511 }
3512
3513 foreign_preds
3514 .sort_by_key(|(_, pred): &(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
3515
3516 for (_, pred) in &foreign_preds {
3517 let ty = pred.self_ty();
3518 let ty::Adt(def, _) = ty.kind() else { continue };
3519 let span = self.tcx.def_span(def.did());
3520 if span.is_dummy() {
3521 continue;
3522 }
3523 let mut mspan: MultiSpan = span.into();
3524 mspan.push_span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is defined in another crate",
ty))
})format!("`{ty}` is defined in another crate"));
3525 err.span_note(
3526 mspan,
3527 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{1}` does not implement `{0}`",
pred.trait_ref.print_trait_sugared(), ty))
})format!("`{ty}` does not implement `{}`", pred.trait_ref.print_trait_sugared()),
3528 );
3529
3530 foreign_preds.iter().find(|&(root_pred, pred)| {
3531 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3532 root_pred.kind().skip_binder()
3533 && let Some(root_adt) = root_pred.self_ty().ty_adt_def()
3534 {
3535 self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3536 } else {
3537 false
3538 }
3539 });
3540 }
3541
3542 let preds: Vec<_> = errors
3543 .iter()
3544 .map(|e| (e.obligation.predicate, None, Some(e.obligation.cause.clone())))
3545 .collect();
3546 if suggest_derive {
3547 self.suggest_derive(err, &preds);
3548 } else {
3549 let _ = self.note_predicate_source_and_get_derives(err, &preds);
3551 }
3552 }
3553
3554 fn consider_suggesting_derives_for_ty(
3557 &self,
3558 trait_pred: ty::TraitPredicate<'tcx>,
3559 adt: ty::AdtDef<'tcx>,
3560 ) -> Option<Vec<(String, Span, Symbol)>> {
3561 let diagnostic_name = self.tcx.get_diagnostic_name(trait_pred.def_id())?;
3562
3563 let can_derive = match diagnostic_name {
3564 sym::Copy | sym::Clone => true,
3565 _ if adt.is_union() => false,
3566 sym::Default
3567 | sym::Eq
3568 | sym::PartialEq
3569 | sym::Ord
3570 | sym::PartialOrd
3571 | sym::Hash
3572 | sym::Debug => true,
3573 _ => false,
3574 };
3575
3576 if !can_derive {
3577 return None;
3578 }
3579
3580 let trait_def_id = trait_pred.def_id();
3581 let self_ty = trait_pred.self_ty();
3582
3583 if self.tcx.non_blanket_impls_for_ty(trait_def_id, self_ty).any(|impl_def_id| {
3586 self.tcx
3587 .type_of(impl_def_id)
3588 .instantiate_identity()
3589 .skip_norm_wip()
3590 .ty_adt_def()
3591 .is_some_and(|def| def.did() == adt.did())
3592 }) {
3593 return None;
3594 }
3595
3596 let mut derives = Vec::new();
3597 let self_name = self_ty.to_string();
3598 let self_span = self.tcx.def_span(adt.did());
3599
3600 for super_trait in supertraits(self.tcx, ty::Binder::dummy(trait_pred.trait_ref)) {
3601 if let Some(parent_diagnostic_name) = self.tcx.get_diagnostic_name(super_trait.def_id())
3602 {
3603 derives.push((self_name.clone(), self_span, parent_diagnostic_name));
3604 }
3605 }
3606
3607 derives.push((self_name, self_span, diagnostic_name));
3608
3609 Some(derives)
3610 }
3611
3612 fn note_predicate_source_and_get_derives(
3613 &self,
3614 err: &mut Diag<'_>,
3615 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
3616 ) -> Vec<(String, Span, Symbol)> {
3617 let mut derives = Vec::new();
3618 let mut traits = Vec::new();
3619 for (pred, _, _) in unsatisfied_predicates {
3620 let Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred))) =
3621 pred.kind().no_bound_vars()
3622 else {
3623 continue;
3624 };
3625 let adt = match trait_pred.self_ty().ty_adt_def() {
3626 Some(adt) if adt.did().is_local() => adt,
3627 _ => continue,
3628 };
3629 if let Some(new_derives) = self.consider_suggesting_derives_for_ty(trait_pred, adt) {
3630 derives.extend(new_derives);
3631 } else {
3632 traits.push(trait_pred.def_id());
3633 }
3634 }
3635 traits.sort_by_key(|&id| self.tcx.def_path_str(id));
3636 traits.dedup();
3637
3638 let len = traits.len();
3639 if len > 0 {
3640 let span =
3641 MultiSpan::from_spans(traits.iter().map(|&did| self.tcx.def_span(did)).collect());
3642 let mut names = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.def_path_str(traits[0])))
})format!("`{}`", self.tcx.def_path_str(traits[0]));
3643 for (i, &did) in traits.iter().enumerate().skip(1) {
3644 if len > 2 {
3645 names.push_str(", ");
3646 }
3647 if i == len - 1 {
3648 names.push_str(" and ");
3649 }
3650 names.push('`');
3651 names.push_str(&self.tcx.def_path_str(did));
3652 names.push('`');
3653 }
3654 err.span_note(
3655 span,
3656 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait{0} {1} must be implemented",
if len == 1 { "" } else { "s" }, names))
})format!("the trait{} {} must be implemented", pluralize!(len), names),
3657 );
3658 }
3659
3660 derives
3661 }
3662
3663 pub(crate) fn suggest_derive(
3664 &self,
3665 err: &mut Diag<'_>,
3666 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
3667 ) -> bool {
3668 let mut derives = self.note_predicate_source_and_get_derives(err, unsatisfied_predicates);
3669 derives.sort();
3670 derives.dedup();
3671
3672 let mut derives_grouped = Vec::<(String, Span, String)>::new();
3673 for (self_name, self_span, trait_name) in derives.into_iter() {
3674 if let Some((last_self_name, _, last_trait_names)) = derives_grouped.last_mut() {
3675 if last_self_name == &self_name {
3676 last_trait_names.push_str(::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", trait_name))
})format!(", {trait_name}").as_str());
3677 continue;
3678 }
3679 }
3680 derives_grouped.push((self_name, self_span, trait_name.to_string()));
3681 }
3682
3683 for (self_name, self_span, traits) in &derives_grouped {
3684 err.span_suggestion_verbose(
3685 self_span.shrink_to_lo(),
3686 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider annotating `{0}` with `#[derive({1})]`",
self_name, traits))
})format!("consider annotating `{self_name}` with `#[derive({traits})]`"),
3687 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n", traits))
})format!("#[derive({traits})]\n"),
3688 Applicability::MaybeIncorrect,
3689 );
3690 }
3691 !derives_grouped.is_empty()
3692 }
3693
3694 fn note_derefed_ty_has_method(
3695 &self,
3696 err: &mut Diag<'_>,
3697 self_source: SelfSource<'tcx>,
3698 rcvr_ty: Ty<'tcx>,
3699 item_name: Ident,
3700 expected: Expectation<'tcx>,
3701 ) {
3702 let SelfSource::QPath(ty) = self_source else {
3703 return;
3704 };
3705 for (deref_ty, _) in self.autoderef(DUMMY_SP, rcvr_ty).silence_errors().skip(1) {
3706 if let Ok(pick) = self.probe_for_name(
3707 Mode::Path,
3708 item_name,
3709 expected.only_has_type(self),
3710 IsSuggestion(true),
3711 deref_ty,
3712 ty.hir_id,
3713 ProbeScope::TraitsInScope,
3714 ) {
3715 if deref_ty.is_suggestable(self.tcx, true)
3716 && pick.item.is_method()
3720 && let Some(self_ty) =
3721 self.tcx.fn_sig(pick.item.def_id).instantiate_identity().skip_norm_wip().inputs().skip_binder().get(0)
3722 && self_ty.is_ref()
3723 {
3724 let suggested_path = match deref_ty.kind() {
3725 ty::Bool
3726 | ty::Char
3727 | ty::Int(_)
3728 | ty::Uint(_)
3729 | ty::Float(_)
3730 | ty::Adt(_, _)
3731 | ty::Str
3732 | ty::Alias(ty::AliasTy {
3733 kind: ty::Projection { .. } | ty::Inherent { .. },
3734 ..
3735 })
3736 | ty::Param(_) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", deref_ty))
})format!("{deref_ty}"),
3737 _ if self
3743 .tcx
3744 .sess
3745 .source_map()
3746 .span_wrapped_by_angle_or_parentheses(ty.span) =>
3747 {
3748 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", deref_ty))
})format!("{deref_ty}")
3749 }
3750 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", deref_ty))
})format!("<{deref_ty}>"),
3751 };
3752 err.span_suggestion_verbose(
3753 ty.span,
3754 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the function `{0}` is implemented on `{1}`",
item_name, deref_ty))
})format!("the function `{item_name}` is implemented on `{deref_ty}`"),
3755 suggested_path,
3756 Applicability::MaybeIncorrect,
3757 );
3758 } else {
3759 err.span_note(
3760 ty.span,
3761 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the function `{0}` is implemented on `{1}`",
item_name, deref_ty))
})format!("the function `{item_name}` is implemented on `{deref_ty}`"),
3762 );
3763 }
3764 return;
3765 }
3766 }
3767 }
3768
3769 fn suggest_bounds_for_range_to_method(
3770 &self,
3771 err: &mut Diag<'_>,
3772 source: SelfSource<'tcx>,
3773 item_ident: Ident,
3774 ) {
3775 let SelfSource::MethodCall(rcvr_expr) = source else { return };
3776 let hir::ExprKind::Struct(qpath, fields, _) = rcvr_expr.kind else { return };
3777 let Some(lang_item) = self.tcx.qpath_lang_item(*qpath) else {
3778 return;
3779 };
3780 let is_inclusive = match lang_item {
3781 hir::LangItem::RangeTo => false,
3782 hir::LangItem::RangeToInclusive | hir::LangItem::RangeInclusiveCopy => true,
3783 _ => return,
3784 };
3785
3786 let Some(iterator_trait) = self.tcx.get_diagnostic_item(sym::Iterator) else { return };
3787 let Some(_) = self
3788 .tcx
3789 .associated_items(iterator_trait)
3790 .filter_by_name_unhygienic(item_ident.name)
3791 .next()
3792 else {
3793 return;
3794 };
3795
3796 let source_map = self.tcx.sess.source_map();
3797 let range_type = if is_inclusive { "RangeInclusive" } else { "Range" };
3798 let Some(end_field) = fields.iter().find(|f| f.ident.name == rustc_span::sym::end) else {
3799 return;
3800 };
3801
3802 let element_ty = self.typeck_results.borrow().expr_ty_opt(end_field.expr);
3803 let is_integral = element_ty.is_some_and(|ty| ty.is_integral());
3804 let end_is_negative = is_integral
3805 && #[allow(non_exhaustive_omitted_patterns)] match end_field.expr.kind {
hir::ExprKind::Unary(rustc_ast::UnOp::Neg, _) => true,
_ => false,
}matches!(end_field.expr.kind, hir::ExprKind::Unary(rustc_ast::UnOp::Neg, _));
3806
3807 let Ok(snippet) = source_map.span_to_snippet(rcvr_expr.span) else { return };
3808
3809 let offset = snippet
3810 .chars()
3811 .take_while(|&c| c == '(' || c.is_whitespace())
3812 .map(|c| c.len_utf8())
3813 .sum::<usize>();
3814
3815 let insert_span = rcvr_expr
3816 .span
3817 .with_lo(rcvr_expr.span.lo() + rustc_span::BytePos(offset as u32))
3818 .shrink_to_lo();
3819
3820 let (value, appl) = if is_integral && !end_is_negative {
3821 ("0", Applicability::MachineApplicable)
3822 } else {
3823 ("/* start */", Applicability::HasPlaceholders)
3824 };
3825
3826 err.span_suggestion_verbose(
3827 insert_span,
3828 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider using a bounded `{0}` by adding a concrete starting value",
range_type))
})format!("consider using a bounded `{range_type}` by adding a concrete starting value"),
3829 value,
3830 appl,
3831 );
3832 }
3833
3834 fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String {
3836 match ty.kind() {
3837 ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), args),
3838 _ => self.ty_to_string(ty),
3839 }
3840 }
3841
3842 fn suggest_await_before_method(
3843 &self,
3844 err: &mut Diag<'_>,
3845 item_name: Ident,
3846 ty: Ty<'tcx>,
3847 call: &hir::Expr<'_>,
3848 span: Span,
3849 return_type: Option<Ty<'tcx>>,
3850 ) {
3851 let Some(output_ty) = self.err_ctxt().get_impl_future_output_ty(ty) else { return };
3852 let output_ty = self.resolve_vars_if_possible(output_ty);
3853 let method_exists =
3854 self.method_exists_for_diagnostic(item_name, output_ty, call.hir_id, return_type);
3855 {
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/method/suggest.rs:3855",
"rustc_hir_typeck::method::suggest",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/suggest.rs"),
::tracing_core::__macro_support::Option::Some(3855u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::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};
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!("suggest_await_before_method: is_method_exist={0}",
method_exists) as &dyn Value))])
});
} else { ; }
};debug!("suggest_await_before_method: is_method_exist={}", method_exists);
3856 if method_exists {
3857 err.span_suggestion_verbose(
3858 span.shrink_to_lo(),
3859 "consider `await`ing on the `Future` and calling the method on its `Output`",
3860 "await.",
3861 Applicability::MaybeIncorrect,
3862 );
3863 }
3864 }
3865
3866 fn set_label_for_method_error(
3867 &self,
3868 err: &mut Diag<'_>,
3869 source: SelfSource<'tcx>,
3870 rcvr_ty: Ty<'tcx>,
3871 item_ident: Ident,
3872 expr_id: hir::HirId,
3873 span: Span,
3874 sugg_span: Span,
3875 within_macro_span: Option<Span>,
3876 args: Option<&'tcx [hir::Expr<'tcx>]>,
3877 ) {
3878 let tcx = self.tcx;
3879 if tcx.sess.source_map().is_multiline(sugg_span) {
3880 err.span_label(sugg_span.with_hi(span.lo()), "");
3881 }
3882 if let Some(within_macro_span) = within_macro_span {
3883 err.span_label(within_macro_span, "due to this macro variable");
3884 }
3885
3886 if #[allow(non_exhaustive_omitted_patterns)] match source {
SelfSource::QPath(_) => true,
_ => false,
}matches!(source, SelfSource::QPath(_)) && args.is_some() {
3887 self.find_builder_fn(err, rcvr_ty, expr_id);
3888 }
3889
3890 if tcx.ty_is_opaque_future(rcvr_ty) && item_ident.name == sym::poll {
3891 let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
3892 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("method `poll` found on `Pin<&mut {0}>`, see documentation for `std::pin::Pin`",
ty_str))
})format!(
3893 "method `poll` found on `Pin<&mut {ty_str}>`, \
3894 see documentation for `std::pin::Pin`"
3895 ));
3896 err.help(
3897 "self type must be pinned to call `Future::poll`, \
3898 see https://rust-lang.github.io/async-book/part-reference/pinning.html",
3899 );
3900 }
3901
3902 if let Some(span) =
3903 tcx.resolutions(()).confused_type_with_std_module.get(&span.with_parent(None))
3904 {
3905 err.span_suggestion(
3906 span.shrink_to_lo(),
3907 "you are looking for the module in `std`, not the primitive type",
3908 "std::",
3909 Applicability::MachineApplicable,
3910 );
3911 }
3912 }
3913
3914 fn suggest_on_pointer_type(
3915 &self,
3916 err: &mut Diag<'_>,
3917 source: SelfSource<'tcx>,
3918 rcvr_ty: Ty<'tcx>,
3919 item_ident: Ident,
3920 ) {
3921 let tcx = self.tcx;
3922 if let SelfSource::MethodCall(rcvr_expr) = source
3924 && let ty::RawPtr(ty, ptr_mutbl) = *rcvr_ty.kind()
3925 && let Ok(pick) = self.lookup_probe_for_diagnostic(
3926 item_ident,
3927 Ty::new_ref(tcx, ty::Region::new_error_misc(tcx), ty, ptr_mutbl),
3928 self.tcx.hir_expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id)),
3929 ProbeScope::TraitsInScope,
3930 None,
3931 )
3932 && let ty::Ref(_, _, sugg_mutbl) = *pick.self_ty.kind()
3933 && (sugg_mutbl.is_not() || ptr_mutbl.is_mut())
3934 {
3935 let (method, method_anchor) = match sugg_mutbl {
3936 Mutability::Not => {
3937 let method_anchor = match ptr_mutbl {
3938 Mutability::Not => "as_ref",
3939 Mutability::Mut => "as_ref-1",
3940 };
3941 ("as_ref", method_anchor)
3942 }
3943 Mutability::Mut => ("as_mut", "as_mut"),
3944 };
3945 err.span_note(
3946 tcx.def_span(pick.item.def_id),
3947 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the method `{1}` exists on the type `{0}`",
pick.self_ty, item_ident))
})format!("the method `{item_ident}` exists on the type `{ty}`", ty = pick.self_ty),
3948 );
3949 let mut_str = ptr_mutbl.ptr_str();
3950 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might want to use the unsafe method `<*{0} T>::{1}` to get an optional reference to the value behind the pointer",
mut_str, method))
})format!(
3951 "you might want to use the unsafe method `<*{mut_str} T>::{method}` to get \
3952 an optional reference to the value behind the pointer"
3953 ));
3954 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("read the documentation for `<*{0} T>::{1}` and ensure you satisfy its safety preconditions before calling it to avoid undefined behavior: https://doc.rust-lang.org/std/primitive.pointer.html#method.{2}",
mut_str, method, method_anchor))
})format!(
3955 "read the documentation for `<*{mut_str} T>::{method}` and ensure you satisfy its \
3956 safety preconditions before calling it to avoid undefined behavior: \
3957 https://doc.rust-lang.org/std/primitive.pointer.html#method.{method_anchor}"
3958 ));
3959 }
3960 }
3961
3962 fn suggest_use_candidates<F>(&self, candidates: Vec<DefId>, handle_candidates: F)
3963 where
3964 F: FnOnce(Vec<String>, Vec<String>, Span),
3965 {
3966 let parent_map = self.tcx.visible_parent_map(());
3967
3968 let scope = self.tcx.parent_module_from_def_id(self.body_id);
3969 let (accessible_candidates, inaccessible_candidates): (Vec<_>, Vec<_>) =
3970 candidates.into_iter().partition(|id| {
3971 let vis = self.tcx.visibility(*id);
3972 vis.is_accessible_from(scope, self.tcx)
3973 });
3974
3975 let sugg = |candidates: Vec<_>, visible| {
3976 let (candidates, globs): (Vec<_>, Vec<_>) =
3979 candidates.into_iter().partition(|trait_did| {
3980 if let Some(parent_did) = parent_map.get(trait_did) {
3981 if *parent_did != self.tcx.parent(*trait_did)
3983 && self
3984 .tcx
3985 .module_children(*parent_did)
3986 .iter()
3987 .filter(|child| child.res.opt_def_id() == Some(*trait_did))
3988 .all(|child| child.ident.name == kw::Underscore)
3989 {
3990 return false;
3991 }
3992 }
3993
3994 true
3995 });
3996
3997 let prefix = if visible { "use " } else { "" };
3998 let postfix = if visible { ";" } else { "" };
3999 let path_strings = candidates.iter().map(|trait_did| {
4000 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}{2}\n",
{
let _guard = NoVisibleIfDocHiddenGuard::new();
{
let _guard = CratePrefixGuard::new();
self.tcx.def_path_str(*trait_did)
}
}, prefix, postfix))
})format!(
4001 "{prefix}{}{postfix}\n",
4002 with_no_visible_paths_if_doc_hidden!(with_crate_prefix!(
4003 self.tcx.def_path_str(*trait_did)
4004 )),
4005 )
4006 });
4007
4008 let glob_path_strings = globs.iter().map(|trait_did| {
4009 let parent_did = parent_map.get(trait_did).unwrap();
4010 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2}{0}::*{3} // trait {1}\n",
{
let _guard = NoVisibleIfDocHiddenGuard::new();
{
let _guard = CratePrefixGuard::new();
self.tcx.def_path_str(*parent_did)
}
}, self.tcx.item_name(*trait_did), prefix, postfix))
})format!(
4011 "{prefix}{}::*{postfix} // trait {}\n",
4012 with_no_visible_paths_if_doc_hidden!(with_crate_prefix!(
4013 self.tcx.def_path_str(*parent_did)
4014 )),
4015 self.tcx.item_name(*trait_did),
4016 )
4017 });
4018 let mut sugg: Vec<_> = path_strings.chain(glob_path_strings).collect();
4019 sugg.sort();
4020 sugg
4021 };
4022
4023 let accessible_sugg = sugg(accessible_candidates, true);
4024 let inaccessible_sugg = sugg(inaccessible_candidates, false);
4025
4026 let (module, _, _) = self.tcx.hir_get_module(scope);
4027 let span = module.spans.inject_use_span;
4028 handle_candidates(accessible_sugg, inaccessible_sugg, span);
4029 }
4030
4031 fn suggest_valid_traits(
4032 &self,
4033 err: &mut Diag<'_>,
4034 item_name: Ident,
4035 mut valid_out_of_scope_traits: Vec<DefId>,
4036 explain: bool,
4037 ) -> bool {
4038 valid_out_of_scope_traits.retain(|id| self.tcx.is_user_visible_dep(id.krate));
4039 if !valid_out_of_scope_traits.is_empty() {
4040 let mut candidates = valid_out_of_scope_traits;
4041 candidates.sort_by_key(|&id| self.tcx.def_path_str(id));
4042 candidates.dedup();
4043
4044 let edition_fix = candidates
4046 .iter()
4047 .find(|did| self.tcx.is_diagnostic_item(sym::TryInto, **did))
4048 .copied();
4049
4050 if explain {
4051 err.help("items from traits can only be used if the trait is in scope");
4052 }
4053
4054 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} implemented but not in scope",
if candidates.len() == 1 {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait `{0}` which provides `{1}` is",
self.tcx.item_name(candidates[0]), item_name))
})
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following traits which provide `{0}` are",
item_name))
})
}))
})format!(
4055 "{this_trait_is} implemented but not in scope",
4056 this_trait_is = if candidates.len() == 1 {
4057 format!(
4058 "trait `{}` which provides `{item_name}` is",
4059 self.tcx.item_name(candidates[0]),
4060 )
4061 } else {
4062 format!("the following traits which provide `{item_name}` are")
4063 }
4064 );
4065
4066 self.suggest_use_candidates(candidates, |accessible_sugg, inaccessible_sugg, span| {
4067 let suggest_for_access = |err: &mut Diag<'_>, mut msg: String, suggs: Vec<_>| {
4068 msg += &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("; perhaps you want to import {0}",
if suggs.len() == 1 { "it" } else { "one of them" }))
})format!(
4069 "; perhaps you want to import {one_of}",
4070 one_of = if suggs.len() == 1 { "it" } else { "one of them" },
4071 );
4072 err.span_suggestions(span, msg, suggs, Applicability::MaybeIncorrect);
4073 };
4074 let suggest_for_privacy = |err: &mut Diag<'_>, suggs: Vec<String>| {
4075 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} implemented but not reachable",
if let [sugg] = suggs.as_slice() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait `{0}` which provides `{1}` is",
sugg.trim(), item_name))
})
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following traits which provide `{0}` are",
item_name))
})
}))
})format!(
4076 "{this_trait_is} implemented but not reachable",
4077 this_trait_is = if let [sugg] = suggs.as_slice() {
4078 format!("trait `{}` which provides `{item_name}` is", sugg.trim())
4079 } else {
4080 format!("the following traits which provide `{item_name}` are")
4081 }
4082 );
4083 if suggs.len() == 1 {
4084 err.help(msg);
4085 } else {
4086 err.span_suggestions(span, msg, suggs, Applicability::MaybeIncorrect);
4087 }
4088 };
4089 if accessible_sugg.is_empty() {
4090 suggest_for_privacy(err, inaccessible_sugg);
4092 } else if inaccessible_sugg.is_empty() {
4093 suggest_for_access(err, msg, accessible_sugg);
4094 } else {
4095 suggest_for_access(err, msg, accessible_sugg);
4096 suggest_for_privacy(err, inaccessible_sugg);
4097 }
4098 });
4099
4100 if let Some(did) = edition_fix {
4101 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}\' is included in the prelude starting in Edition 2021",
{
let _guard = CratePrefixGuard::new();
self.tcx.def_path_str(did)
}))
})format!(
4102 "'{}' is included in the prelude starting in Edition 2021",
4103 with_crate_prefix!(self.tcx.def_path_str(did))
4104 ));
4105 }
4106
4107 true
4108 } else {
4109 false
4110 }
4111 }
4112
4113 fn suggest_traits_to_import(
4114 &self,
4115 err: &mut Diag<'_>,
4116 span: Span,
4117 rcvr_ty: Ty<'tcx>,
4118 item_name: Ident,
4119 inputs_len: Option<usize>,
4120 source: SelfSource<'tcx>,
4121 valid_out_of_scope_traits: Vec<DefId>,
4122 static_candidates: &[CandidateSource],
4123 unsatisfied_bounds: bool,
4124 return_type: Option<Ty<'tcx>>,
4125 trait_missing_method: bool,
4126 ) {
4127 let mut alt_rcvr_sugg = false;
4128 let mut trait_in_other_version_found = false;
4129 if let (SelfSource::MethodCall(rcvr), false) = (source, unsatisfied_bounds) {
4130 {
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/method/suggest.rs:4130",
"rustc_hir_typeck::method::suggest",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/suggest.rs"),
::tracing_core::__macro_support::Option::Some(4130u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::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};
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!("suggest_traits_to_import: span={0:?}, item_name={1:?}, rcvr_ty={2:?}, rcvr={3:?}",
span, item_name, rcvr_ty, rcvr) as &dyn Value))])
});
} else { ; }
};debug!(
4131 "suggest_traits_to_import: span={:?}, item_name={:?}, rcvr_ty={:?}, rcvr={:?}",
4132 span, item_name, rcvr_ty, rcvr
4133 );
4134 let skippable = [
4135 self.tcx.lang_items().clone_trait(),
4136 self.tcx.lang_items().deref_trait(),
4137 self.tcx.lang_items().deref_mut_trait(),
4138 self.tcx.lang_items().drop_trait(),
4139 self.tcx.get_diagnostic_item(sym::AsRef),
4140 ];
4141 for (rcvr_ty, post, pin_call) in &[
4145 (rcvr_ty, "", None),
4146 (
4147 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty),
4148 "&mut ",
4149 Some("as_mut"),
4150 ),
4151 (
4152 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty),
4153 "&",
4154 Some("as_ref"),
4155 ),
4156 ] {
4157 match self.lookup_probe_for_diagnostic(
4158 item_name,
4159 *rcvr_ty,
4160 rcvr,
4161 ProbeScope::AllTraits,
4162 return_type,
4163 ) {
4164 Ok(pick) => {
4165 let did = Some(pick.item.container_id(self.tcx));
4170 if skippable.contains(&did) {
4171 continue;
4172 }
4173 trait_in_other_version_found = self
4174 .detect_and_explain_multiple_crate_versions_of_trait_item(
4175 err,
4176 pick.item.def_id,
4177 rcvr.hir_id,
4178 Some(*rcvr_ty),
4179 );
4180 if pick.autoderefs == 0 && !trait_in_other_version_found {
4181 err.span_label(
4182 pick.item.ident(self.tcx).span,
4183 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the method is available for `{0}` here",
rcvr_ty))
})format!("the method is available for `{rcvr_ty}` here"),
4184 );
4185 }
4186 break;
4187 }
4188 Err(MethodError::Ambiguity(_)) => {
4189 break;
4194 }
4195 Err(_) => (),
4196 }
4197
4198 let Some(unpin_trait) = self.tcx.lang_items().unpin_trait() else {
4199 return;
4200 };
4201 let pred = ty::TraitRef::new(self.tcx, unpin_trait, [*rcvr_ty]);
4202 let unpin = self.predicate_must_hold_considering_regions(&Obligation::new(
4203 self.tcx,
4204 self.misc(rcvr.span),
4205 self.param_env,
4206 pred,
4207 ));
4208 for (rcvr_ty, pre) in &[
4209 (Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::OwnedBox), "Box::new"),
4210 (Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::Pin), "Pin::new"),
4211 (Ty::new_diagnostic_item(self.tcx, *rcvr_ty, sym::Arc), "Arc::new"),
4212 (Ty::new_diagnostic_item(self.tcx, *rcvr_ty, sym::Rc), "Rc::new"),
4213 ] {
4214 if let Some(new_rcvr_t) = *rcvr_ty
4215 && let Ok(pick) = self.lookup_probe_for_diagnostic(
4216 item_name,
4217 new_rcvr_t,
4218 rcvr,
4219 ProbeScope::AllTraits,
4220 return_type,
4221 )
4222 {
4223 {
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/method/suggest.rs:4223",
"rustc_hir_typeck::method::suggest",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/suggest.rs"),
::tracing_core::__macro_support::Option::Some(4223u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::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};
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_alt_rcvr: pick candidate {0:?}",
pick) as &dyn Value))])
});
} else { ; }
};debug!("try_alt_rcvr: pick candidate {:?}", pick);
4224 let did = pick.item.trait_container(self.tcx);
4225 let skip = skippable.contains(&did)
4231 || (("Pin::new" == *pre)
4232 && ((sym::as_ref == item_name.name) || !unpin))
4233 || inputs_len.is_some_and(|inputs_len| {
4234 pick.item.is_fn()
4235 && self
4236 .tcx
4237 .fn_sig(pick.item.def_id)
4238 .skip_binder()
4239 .skip_binder()
4240 .inputs()
4241 .len()
4242 != inputs_len
4243 });
4244 if pick.autoderefs == 0 && !skip {
4248 err.span_label(
4249 pick.item.ident(self.tcx).span,
4250 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the method is available for `{0}` here",
new_rcvr_t))
})format!("the method is available for `{new_rcvr_t}` here"),
4251 );
4252 err.multipart_suggestion(
4253 "consider wrapping the receiver expression with the \
4254 appropriate type",
4255 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(rcvr.span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}({1}", pre, post))
})), (rcvr.span.shrink_to_hi(), ")".to_string())]))vec![
4256 (rcvr.span.shrink_to_lo(), format!("{pre}({post}")),
4257 (rcvr.span.shrink_to_hi(), ")".to_string()),
4258 ],
4259 Applicability::MaybeIncorrect,
4260 );
4261 alt_rcvr_sugg = true;
4263 }
4264 }
4265 }
4266 if let Some(new_rcvr_t) = Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::Pin)
4269 && !alt_rcvr_sugg
4271 && !unpin
4273 && let Some(pin_call) = pin_call
4275 && let Ok(pick) = self.lookup_probe_for_diagnostic(
4277 item_name,
4278 new_rcvr_t,
4279 rcvr,
4280 ProbeScope::AllTraits,
4281 return_type,
4282 )
4283 && !skippable.contains(&Some(pick.item.container_id(self.tcx)))
4286 && pick.item.impl_container(self.tcx).is_none_or(|did| {
4288 match self.tcx.type_of(did).skip_binder().kind() {
4289 ty::Adt(def, _) => Some(def.did()) != self.tcx.lang_items().pin_type(),
4290 _ => true,
4291 }
4292 })
4293 && pick.autoderefs == 0
4295 && inputs_len.is_some_and(|inputs_len| pick.item.is_fn() && self.tcx.fn_sig(pick.item.def_id).skip_binder().skip_binder().inputs().len() == inputs_len)
4298 {
4299 let indent = self
4300 .tcx
4301 .sess
4302 .source_map()
4303 .indentation_before(rcvr.span)
4304 .unwrap_or_else(|| " ".to_string());
4305 let mut expr = rcvr;
4306 while let Node::Expr(call_expr) = self.tcx.parent_hir_node(expr.hir_id)
4307 && let hir::ExprKind::MethodCall(hir::PathSegment { .. }, ..) =
4308 call_expr.kind
4309 {
4310 expr = call_expr;
4311 }
4312 match self.tcx.parent_hir_node(expr.hir_id) {
4313 Node::LetStmt(stmt)
4314 if let Some(init) = stmt.init
4315 && let Ok(code) =
4316 self.tcx.sess.source_map().span_to_snippet(rcvr.span) =>
4317 {
4318 err.multipart_suggestion(
4321 "consider pinning the expression",
4322 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(stmt.span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let mut pinned = std::pin::pin!({0});\n{1}",
code, indent))
})),
(init.span.until(rcvr.span.shrink_to_hi()),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pinned.{0}()", pin_call))
}))]))vec![
4323 (
4324 stmt.span.shrink_to_lo(),
4325 format!(
4326 "let mut pinned = std::pin::pin!({code});\n{indent}"
4327 ),
4328 ),
4329 (
4330 init.span.until(rcvr.span.shrink_to_hi()),
4331 format!("pinned.{pin_call}()"),
4332 ),
4333 ],
4334 Applicability::MaybeIncorrect,
4335 );
4336 }
4337 Node::Block(_) | Node::Stmt(_) => {
4338 err.multipart_suggestion(
4341 "consider pinning the expression",
4342 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(rcvr.span.shrink_to_lo(),
"let mut pinned = std::pin::pin!(".to_string()),
(rcvr.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(");\n{0}pinned.{1}()",
indent, pin_call))
}))]))vec![
4343 (
4344 rcvr.span.shrink_to_lo(),
4345 "let mut pinned = std::pin::pin!(".to_string(),
4346 ),
4347 (
4348 rcvr.span.shrink_to_hi(),
4349 format!(");\n{indent}pinned.{pin_call}()"),
4350 ),
4351 ],
4352 Applicability::MaybeIncorrect,
4353 );
4354 }
4355 _ => {
4356 err.span_help(
4359 rcvr.span,
4360 "consider pinning the expression with `std::pin::pin!()` and \
4361 assigning that to a new binding",
4362 );
4363 }
4364 }
4365 alt_rcvr_sugg = true;
4367 }
4368 }
4369 }
4370
4371 if let SelfSource::QPath(ty) = source
4372 && !valid_out_of_scope_traits.is_empty()
4373 && let hir::TyKind::Path(path) = ty.kind
4374 && let hir::QPath::Resolved(..) = path
4375 && let Some(assoc) = self
4376 .tcx
4377 .associated_items(valid_out_of_scope_traits[0])
4378 .filter_by_name_unhygienic(item_name.name)
4379 .next()
4380 {
4381 let rcvr_ty = self.node_ty_opt(ty.hir_id);
4386 trait_in_other_version_found = self
4387 .detect_and_explain_multiple_crate_versions_of_trait_item(
4388 err,
4389 assoc.def_id,
4390 ty.hir_id,
4391 rcvr_ty,
4392 );
4393 }
4394 if !trait_in_other_version_found
4395 && self.suggest_valid_traits(err, item_name, valid_out_of_scope_traits, true)
4396 {
4397 return;
4398 }
4399
4400 let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
4401
4402 let mut arbitrary_rcvr = ::alloc::vec::Vec::new()vec![];
4403 let mut candidates = all_traits(self.tcx)
4407 .into_iter()
4408 .filter(|info| match self.tcx.lookup_stability(info.def_id) {
4411 Some(attr) => attr.level.is_stable(),
4412 None => true,
4413 })
4414 .filter(|info| {
4415 static_candidates.iter().all(|sc| match *sc {
4418 CandidateSource::Trait(def_id) => def_id != info.def_id,
4419 CandidateSource::Impl(def_id) => {
4420 self.tcx.impl_opt_trait_id(def_id) != Some(info.def_id)
4421 }
4422 })
4423 })
4424 .filter(|info| {
4425 (type_is_local || info.def_id.is_local())
4432 && !self.tcx.trait_is_auto(info.def_id)
4433 && self
4434 .associated_value(info.def_id, item_name)
4435 .filter(|item| {
4436 if item.is_fn() {
4437 let id = item
4438 .def_id
4439 .as_local()
4440 .map(|def_id| self.tcx.hir_node_by_def_id(def_id));
4441 if let Some(hir::Node::TraitItem(hir::TraitItem {
4442 kind: hir::TraitItemKind::Fn(fn_sig, method),
4443 ..
4444 })) = id
4445 {
4446 let self_first_arg = match method {
4447 hir::TraitFn::Required([ident, ..]) => {
4448 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
4449 }
4450 hir::TraitFn::Provided(body_id) => {
4451 self.tcx.hir_body(*body_id).params.first().is_some_and(
4452 |param| {
4453 #[allow(non_exhaustive_omitted_patterns)] match param.pat.kind {
hir::PatKind::Binding(_, _, ident, _) if ident.name == kw::SelfLower =>
true,
_ => false,
}matches!(
4454 param.pat.kind,
4455 hir::PatKind::Binding(_, _, ident, _)
4456 if ident.name == kw::SelfLower
4457 )
4458 },
4459 )
4460 }
4461 _ => false,
4462 };
4463
4464 if !fn_sig.decl.implicit_self().has_implicit_self()
4465 && self_first_arg
4466 {
4467 if let Some(ty) = fn_sig.decl.inputs.get(0) {
4468 arbitrary_rcvr.push(ty.span);
4469 }
4470 return false;
4471 }
4472 }
4473 }
4474 item.visibility(self.tcx).is_public() || info.def_id.is_local()
4476 })
4477 .is_some()
4478 })
4479 .collect::<Vec<_>>();
4480 for span in &arbitrary_rcvr {
4481 err.span_label(
4482 *span,
4483 "the method might not be found because of this arbitrary self type",
4484 );
4485 }
4486 if alt_rcvr_sugg {
4487 return;
4488 }
4489
4490 if !candidates.is_empty() {
4491 candidates
4493 .sort_by_key(|&info| (!info.def_id.is_local(), self.tcx.def_path_str(info.def_id)));
4494 candidates.dedup();
4495
4496 let param_type = match *rcvr_ty.kind() {
4497 ty::Param(param) => Some(param),
4498 ty::Ref(_, ty, _) => match *ty.kind() {
4499 ty::Param(param) => Some(param),
4500 _ => None,
4501 },
4502 _ => None,
4503 };
4504 if !trait_missing_method {
4505 err.help(if param_type.is_some() {
4506 "items from traits can only be used if the type parameter is bounded by the trait"
4507 } else {
4508 "items from traits can only be used if the trait is implemented and in scope"
4509 });
4510 }
4511
4512 let candidates_len = candidates.len();
4513 let message = |action| {
4514 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following {0} an item `{3}`, perhaps you need to {1} {2}:",
if candidates_len == 1 {
"trait defines"
} else { "traits define" }, action,
if candidates_len == 1 { "it" } else { "one of them" },
item_name))
})format!(
4515 "the following {traits_define} an item `{name}`, perhaps you need to {action} \
4516 {one_of_them}:",
4517 traits_define =
4518 if candidates_len == 1 { "trait defines" } else { "traits define" },
4519 action = action,
4520 one_of_them = if candidates_len == 1 { "it" } else { "one of them" },
4521 name = item_name,
4522 )
4523 };
4524 if let Some(param) = param_type {
4526 let generics = self.tcx.generics_of(self.body_id.to_def_id());
4527 let type_param = generics.type_param(param, self.tcx);
4528 let tcx = self.tcx;
4529 if let Some(def_id) = type_param.def_id.as_local() {
4530 let id = tcx.local_def_id_to_hir_id(def_id);
4531 match tcx.hir_node(id) {
4535 Node::GenericParam(param) => {
4536 enum Introducer {
4537 Plus,
4538 Colon,
4539 Nothing,
4540 }
4541 let hir_generics = tcx.hir_get_generics(id.owner.def_id).unwrap();
4542 let trait_def_ids: DefIdSet = hir_generics
4543 .bounds_for_param(def_id)
4544 .flat_map(|bp| bp.bounds.iter())
4545 .filter_map(|bound| bound.trait_ref()?.trait_def_id())
4546 .collect();
4547 if candidates.iter().any(|t| trait_def_ids.contains(&t.def_id)) {
4548 return;
4549 }
4550 let msg = message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("restrict type parameter `{0}` with",
param.name.ident()))
})format!(
4551 "restrict type parameter `{}` with",
4552 param.name.ident(),
4553 ));
4554 let bounds_span = hir_generics.bounds_span_for_suggestions(def_id);
4555 let mut applicability = Applicability::MaybeIncorrect;
4556 let candidate_strs: Vec<_> = candidates
4559 .iter()
4560 .map(|cand| {
4561 let cand_path = tcx.def_path_str(cand.def_id);
4562 let cand_params = &tcx.generics_of(cand.def_id).own_params;
4563 let cand_args: String = cand_params
4564 .iter()
4565 .skip(1)
4566 .filter_map(|param| match param.kind {
4567 ty::GenericParamDefKind::Type {
4568 has_default: true,
4569 ..
4570 }
4571 | ty::GenericParamDefKind::Const {
4572 has_default: true,
4573 ..
4574 } => None,
4575 _ => Some(param.name.as_str()),
4576 })
4577 .intersperse(", ")
4578 .collect();
4579 if cand_args.is_empty() {
4580 cand_path
4581 } else {
4582 applicability = Applicability::HasPlaceholders;
4583 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}</* {1} */>", cand_path,
cand_args))
})format!("{cand_path}</* {cand_args} */>")
4584 }
4585 })
4586 .collect();
4587
4588 if rcvr_ty.is_ref()
4589 && param.is_impl_trait()
4590 && let Some((bounds_span, _)) = bounds_span
4591 {
4592 err.multipart_suggestions(
4593 msg,
4594 candidate_strs.iter().map(|cand| {
4595 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(param.span.shrink_to_lo(), "(".to_string()),
(bounds_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" + {0})", cand))
}))]))vec![
4596 (param.span.shrink_to_lo(), "(".to_string()),
4597 (bounds_span, format!(" + {cand})")),
4598 ]
4599 }),
4600 applicability,
4601 );
4602 return;
4603 }
4604
4605 let (sp, introducer, open_paren_sp) =
4606 if let Some((span, open_paren_sp)) = bounds_span {
4607 (span, Introducer::Plus, open_paren_sp)
4608 } else if let Some(colon_span) = param.colon_span {
4609 (colon_span.shrink_to_hi(), Introducer::Nothing, None)
4610 } else if param.is_impl_trait() {
4611 (param.span.shrink_to_hi(), Introducer::Plus, None)
4612 } else {
4613 (param.span.shrink_to_hi(), Introducer::Colon, None)
4614 };
4615
4616 let all_suggs = candidate_strs.iter().map(|cand| {
4617 let suggestion = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}",
match introducer {
Introducer::Plus => " +",
Introducer::Colon => ":",
Introducer::Nothing => "",
}, cand))
})format!(
4618 "{} {cand}",
4619 match introducer {
4620 Introducer::Plus => " +",
4621 Introducer::Colon => ":",
4622 Introducer::Nothing => "",
4623 },
4624 );
4625
4626 let mut suggs = ::alloc::vec::Vec::new()vec![];
4627
4628 if let Some(open_paren_sp) = open_paren_sp {
4629 suggs.push((open_paren_sp, "(".to_string()));
4630 suggs.push((sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("){0}", suggestion))
})format!("){suggestion}")));
4631 } else {
4632 suggs.push((sp, suggestion));
4633 }
4634
4635 suggs
4636 });
4637
4638 err.multipart_suggestions(msg, all_suggs, applicability);
4639
4640 return;
4641 }
4642 Node::Item(hir::Item {
4643 kind: hir::ItemKind::Trait { ident, bounds, .. },
4644 ..
4645 }) => {
4646 let (sp, sep, article) = if bounds.is_empty() {
4647 (ident.span.shrink_to_hi(), ":", "a")
4648 } else {
4649 (bounds.last().unwrap().span().shrink_to_hi(), " +", "another")
4650 };
4651 err.span_suggestions(
4652 sp,
4653 message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add {0} supertrait for", article))
})format!("add {article} supertrait for")),
4654 candidates
4655 .iter()
4656 .map(|t| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", sep,
tcx.def_path_str(t.def_id)))
})format!("{} {}", sep, tcx.def_path_str(t.def_id),)),
4657 Applicability::MaybeIncorrect,
4658 );
4659 return;
4660 }
4661 _ => {}
4662 }
4663 }
4664 }
4665
4666 let (potential_candidates, explicitly_negative) = if param_type.is_some() {
4667 (candidates, Vec::new())
4670 } else if let Some(simp_rcvr_ty) =
4671 simplify_type(self.tcx, rcvr_ty, TreatParams::AsRigid)
4672 {
4673 let mut potential_candidates = Vec::new();
4674 let mut explicitly_negative = Vec::new();
4675 for candidate in candidates {
4676 if self
4678 .tcx
4679 .all_impls(candidate.def_id)
4680 .map(|imp_did| self.tcx.impl_trait_header(imp_did))
4681 .filter(|header| header.polarity != ty::ImplPolarity::Positive)
4682 .any(|header| {
4683 let imp = header.trait_ref.instantiate_identity().skip_norm_wip();
4684 let imp_simp =
4685 simplify_type(self.tcx, imp.self_ty(), TreatParams::AsRigid);
4686 imp_simp.is_some_and(|s| s == simp_rcvr_ty)
4687 })
4688 {
4689 explicitly_negative.push(candidate);
4690 } else {
4691 potential_candidates.push(candidate);
4692 }
4693 }
4694 (potential_candidates, explicitly_negative)
4695 } else {
4696 (candidates, Vec::new())
4698 };
4699
4700 let impls_trait = |def_id: DefId| {
4701 let args = ty::GenericArgs::for_item(self.tcx, def_id, |param, _| {
4702 if param.index == 0 {
4703 rcvr_ty.into()
4704 } else {
4705 self.infcx.var_for_def(span, param)
4706 }
4707 });
4708 self.infcx
4709 .type_implements_trait(def_id, args, self.param_env)
4710 .must_apply_modulo_regions()
4711 && param_type.is_none()
4712 };
4713 match &potential_candidates[..] {
4714 [] => {}
4715 [trait_info] if trait_info.def_id.is_local() => {
4716 if impls_trait(trait_info.def_id) {
4717 self.suggest_valid_traits(err, item_name, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[trait_info.def_id]))vec![trait_info.def_id], false);
4718 } else {
4719 err.subdiagnostic(CandidateTraitNote {
4720 span: self.tcx.def_span(trait_info.def_id),
4721 trait_name: self.tcx.def_path_str(trait_info.def_id),
4722 item_name,
4723 action_or_ty: if trait_missing_method {
4724 "NONE".to_string()
4725 } else {
4726 param_type.map_or_else(
4727 || "implement".to_string(), |p| p.to_string(),
4729 )
4730 },
4731 });
4732 }
4733 }
4734 trait_infos => {
4735 let mut msg = message(param_type.map_or_else(
4736 || "implement".to_string(), |param| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("restrict type parameter `{0}` with",
param))
})format!("restrict type parameter `{param}` with"),
4738 ));
4739 for (i, trait_info) in trait_infos.iter().enumerate() {
4740 if impls_trait(trait_info.def_id) {
4741 self.suggest_valid_traits(
4742 err,
4743 item_name,
4744 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[trait_info.def_id]))vec![trait_info.def_id],
4745 false,
4746 );
4747 }
4748 msg.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\ncandidate #{0}: `{1}`", i + 1,
self.tcx.def_path_str(trait_info.def_id)))
})format!(
4749 "\ncandidate #{}: `{}`",
4750 i + 1,
4751 self.tcx.def_path_str(trait_info.def_id),
4752 ));
4753 }
4754 err.note(msg);
4755 }
4756 }
4757 match &explicitly_negative[..] {
4758 [] => {}
4759 [trait_info] => {
4760 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait `{0}` defines an item `{1}`, but is explicitly unimplemented",
self.tcx.def_path_str(trait_info.def_id), item_name))
})format!(
4761 "the trait `{}` defines an item `{}`, but is explicitly unimplemented",
4762 self.tcx.def_path_str(trait_info.def_id),
4763 item_name
4764 );
4765 err.note(msg);
4766 }
4767 trait_infos => {
4768 let mut msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following traits define an item `{0}`, but are explicitly unimplemented:",
item_name))
})format!(
4769 "the following traits define an item `{item_name}`, but are explicitly unimplemented:"
4770 );
4771 for trait_info in trait_infos {
4772 msg.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}",
self.tcx.def_path_str(trait_info.def_id)))
})format!("\n{}", self.tcx.def_path_str(trait_info.def_id)));
4773 }
4774 err.note(msg);
4775 }
4776 }
4777 }
4778 }
4779
4780 fn detect_and_explain_multiple_crate_versions_of_trait_item(
4781 &self,
4782 err: &mut Diag<'_>,
4783 item_def_id: DefId,
4784 hir_id: hir::HirId,
4785 rcvr_ty: Option<Ty<'tcx>>,
4786 ) -> bool {
4787 let hir_id = self.tcx.parent_hir_id(hir_id);
4788 let Some(traits) = self.tcx.in_scope_traits(hir_id) else { return false };
4789 if traits.is_empty() {
4790 return false;
4791 }
4792 let trait_def_id = self.tcx.parent(item_def_id);
4793 if !self.tcx.is_trait(trait_def_id) {
4794 return false;
4795 }
4796 let hir::Node::Expr(rcvr) = self.tcx.hir_node(hir_id) else {
4797 return false;
4798 };
4799 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, rcvr_ty.into_iter());
4800 let trait_pred = ty::Binder::dummy(ty::TraitPredicate {
4801 trait_ref,
4802 polarity: ty::PredicatePolarity::Positive,
4803 });
4804 let obligation = Obligation::new(self.tcx, self.misc(rcvr.span), self.param_env, trait_ref);
4805 self.err_ctxt().note_different_trait_with_same_name(err, &obligation, trait_pred)
4806 }
4807
4808 pub(crate) fn suggest_else_fn_with_closure(
4811 &self,
4812 err: &mut Diag<'_>,
4813 expr: &hir::Expr<'_>,
4814 found: Ty<'tcx>,
4815 expected: Ty<'tcx>,
4816 ) -> bool {
4817 let Some((_def_id_or_name, output, _inputs)) = self.extract_callable_info(found) else {
4818 return false;
4819 };
4820
4821 if !self.may_coerce(output, expected) {
4822 return false;
4823 }
4824
4825 if let Node::Expr(call_expr) = self.tcx.parent_hir_node(expr.hir_id)
4826 && let hir::ExprKind::MethodCall(
4827 hir::PathSegment { ident: method_name, .. },
4828 self_expr,
4829 args,
4830 ..,
4831 ) = call_expr.kind
4832 && let Some(self_ty) = self.typeck_results.borrow().expr_ty_opt(self_expr)
4833 {
4834 let new_name = Ident {
4835 name: Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_else", method_name.as_str()))
})format!("{}_else", method_name.as_str())),
4836 span: method_name.span,
4837 };
4838 let probe = self.lookup_probe_for_diagnostic(
4839 new_name,
4840 self_ty,
4841 self_expr,
4842 ProbeScope::TraitsInScope,
4843 Some(expected),
4844 );
4845
4846 if let Ok(pick) = probe
4848 && let fn_sig = self.tcx.fn_sig(pick.item.def_id)
4849 && let fn_args = fn_sig.skip_binder().skip_binder().inputs()
4850 && fn_args.len() == args.len() + 1
4851 {
4852 err.span_suggestion_verbose(
4853 method_name.span.shrink_to_hi(),
4854 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try calling `{0}` instead",
new_name.name.as_str()))
})format!("try calling `{}` instead", new_name.name.as_str()),
4855 "_else",
4856 Applicability::MaybeIncorrect,
4857 );
4858 return true;
4859 }
4860 }
4861 false
4862 }
4863
4864 fn type_derefs_to_local(
4867 &self,
4868 span: Span,
4869 rcvr_ty: Ty<'tcx>,
4870 source: SelfSource<'tcx>,
4871 ) -> bool {
4872 fn is_local(ty: Ty<'_>) -> bool {
4873 match ty.kind() {
4874 ty::Adt(def, _) => def.did().is_local(),
4875 ty::Foreign(did) => did.is_local(),
4876 ty::Dynamic(tr, ..) => tr.principal().is_some_and(|d| d.def_id().is_local()),
4877 ty::Param(_) => true,
4878
4879 _ => false,
4884 }
4885 }
4886
4887 if let SelfSource::QPath(_) = source {
4890 return is_local(rcvr_ty);
4891 }
4892
4893 self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
4894 }
4895
4896 fn suggest_hashmap_on_unsatisfied_hashset_buildhasher(
4897 &self,
4898 err: &mut Diag<'_>,
4899 pred: &ty::TraitPredicate<'_>,
4900 adt: ty::AdtDef<'_>,
4901 ) -> bool {
4902 if self.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4903 && self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4904 {
4905 err.help("you might have intended to use a HashMap instead");
4906 true
4907 } else {
4908 false
4909 }
4910 }
4911}
4912
4913#[derive(#[automatically_derived]
impl<'a> ::core::marker::Copy for SelfSource<'a> { }Copy, #[automatically_derived]
impl<'a> ::core::clone::Clone for SelfSource<'a> {
#[inline]
fn clone(&self) -> SelfSource<'a> {
let _: ::core::clone::AssertParamIsClone<&'a hir::Ty<'a>>;
let _: ::core::clone::AssertParamIsClone<&'a hir::Expr<'a>>;
*self
}
}Clone, #[automatically_derived]
impl<'a> ::core::fmt::Debug for SelfSource<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
SelfSource::QPath(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "QPath",
&__self_0),
SelfSource::MethodCall(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MethodCall", &__self_0),
}
}
}Debug)]
4914enum SelfSource<'a> {
4915 QPath(&'a hir::Ty<'a>),
4916 MethodCall(&'a hir::Expr<'a> ),
4917}
4918
4919#[derive(#[automatically_derived]
impl ::core::marker::Copy for TraitInfo { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TraitInfo {
#[inline]
fn clone(&self) -> TraitInfo {
let _: ::core::clone::AssertParamIsClone<DefId>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for TraitInfo {
#[inline]
fn eq(&self, other: &TraitInfo) -> bool { self.def_id == other.def_id }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for TraitInfo {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<DefId>;
}
}Eq)]
4920pub(crate) struct TraitInfo {
4921 pub def_id: DefId,
4922}
4923
4924pub(crate) fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
4927 tcx.all_traits_including_private().map(|def_id| TraitInfo { def_id }).collect()
4928}
4929
4930fn print_disambiguation_help<'tcx>(
4931 tcx: TyCtxt<'tcx>,
4932 err: &mut Diag<'_>,
4933 source: SelfSource<'tcx>,
4934 args: Option<&'tcx [hir::Expr<'tcx>]>,
4935 trait_ref: ty::TraitRef<'tcx>,
4936 candidate_idx: Option<usize>,
4937 span: Span,
4938 item: ty::AssocItem,
4939) -> Option<String> {
4940 let trait_impl_type = trait_ref.self_ty().peel_refs();
4941 let trait_ref = if item.is_method() {
4942 trait_ref.print_only_trait_name().to_string()
4943 } else {
4944 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} as {1}>", trait_ref.args[0],
trait_ref.print_only_trait_name()))
})format!("<{} as {}>", trait_ref.args[0], trait_ref.print_only_trait_name())
4945 };
4946 Some(
4947 if item.is_fn()
4948 && let SelfSource::MethodCall(receiver) = source
4949 && let Some(args) = args
4950 {
4951 let def_kind_descr = tcx.def_kind_descr(item.as_def_kind(), item.def_id);
4952 let item_name = item.ident(tcx);
4953 let first_input =
4954 tcx.fn_sig(item.def_id).instantiate_identity().skip_binder().inputs().get(0);
4955 let (first_arg_type, rcvr_ref) = (
4956 first_input.map(|first| first.peel_refs()),
4957 first_input
4958 .and_then(|ty| ty.ref_mutability())
4959 .map_or("", |mutbl| mutbl.ref_prefix_str()),
4960 );
4961
4962 let args = if let Some(first_arg_type) = first_arg_type
4964 && (first_arg_type == tcx.types.self_param
4965 || first_arg_type == trait_impl_type
4966 || item.is_method())
4967 {
4968 Some(receiver)
4969 } else {
4970 None
4971 }
4972 .into_iter()
4973 .chain(args)
4974 .map(|arg| {
4975 tcx.sess.source_map().span_to_snippet(arg.span).unwrap_or_else(|_| "_".to_owned())
4976 })
4977 .collect::<Vec<_>>()
4978 .join(", ");
4979
4980 let args = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}{1})", rcvr_ref, args))
})format!("({}{})", rcvr_ref, args);
4981 err.span_suggestion_verbose(
4982 span,
4983 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("disambiguate the {1} for {0}",
if let Some(candidate) = candidate_idx {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("candidate #{0}",
candidate))
})
} else { "the candidate".to_string() }, def_kind_descr))
})format!(
4984 "disambiguate the {def_kind_descr} for {}",
4985 if let Some(candidate) = candidate_idx {
4986 format!("candidate #{candidate}")
4987 } else {
4988 "the candidate".to_string()
4989 },
4990 ),
4991 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}{2}", trait_ref, item_name,
args))
})format!("{trait_ref}::{item_name}{args}"),
4992 Applicability::HasPlaceholders,
4993 );
4994 return None;
4995 } else {
4996 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::", trait_ref))
})format!("{trait_ref}::")
4997 },
4998 )
4999}