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((
1907 cause_span,
1908 cause_msg,
1909 ));
1910 entry.2.push(p);
1911 skip_list.insert(p);
1912 manually_impl = true;
1913 }
1914
1915 Some(Node::Item(hir::Item {
1917 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
1918 span: item_span,
1919 ..
1920 })) => {
1921 let sized_pred =
1922 unsatisfied_predicates.iter().any(|(pred, _, _)| {
1923 match pred.kind().skip_binder() {
1924 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
1925 self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
1926 && pred.polarity == ty::PredicatePolarity::Positive
1927 }
1928 _ => false,
1929 }
1930 });
1931 for param in generics.params {
1932 if param.span == cause_span && sized_pred {
1933 let (sp, sugg) = match param.colon_span {
1934 Some(sp) => (sp.shrink_to_hi(), " ?Sized +"),
1935 None => (param.span.shrink_to_hi(), ": ?Sized"),
1936 };
1937 err.span_suggestion_verbose(
1938 sp,
1939 "consider relaxing the type parameter's implicit `Sized` bound",
1940 sugg,
1941 Applicability::MachineApplicable,
1942 );
1943 }
1944 }
1945 if let Some(pred) = parent_p {
1946 let _ = format_pred(*pred);
1948 }
1949 skip_list.insert(p);
1950 let entry = spanned_predicates.entry(self_ty.span);
1951 let entry = entry.or_insert_with(|| {
1952 (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
1953 });
1954 entry.2.push(p);
1955 if cause_span != *item_span {
1956 entry.0.insert(cause_span);
1957 entry.1.insert((cause_span, "unsatisfied trait bound introduced here".to_string()));
1958 } else {
1959 if let Some(of_trait) = of_trait {
1960 entry.0.insert(of_trait.trait_ref.path.span);
1961 }
1962 entry.0.insert(self_ty.span);
1963 };
1964 if let Some(of_trait) = of_trait {
1965 entry.1.insert((of_trait.trait_ref.path.span, String::new()));
1966 }
1967 entry.1.insert((self_ty.span, String::new()));
1968 }
1969 Some(Node::Item(hir::Item {
1970 kind: hir::ItemKind::Trait { is_auto: rustc_ast::ast::IsAuto::Yes, .. },
1971 span: item_span,
1972 ..
1973 })) => {
1974 self.dcx().span_delayed_bug(
1975 *item_span,
1976 "auto trait is invoked with no method error, but no error reported?",
1977 );
1978 }
1979 Some(
1980 Node::Item(hir::Item {
1981 kind:
1982 hir::ItemKind::Trait { ident, .. }
1983 | hir::ItemKind::TraitAlias(_, ident, ..),
1984 ..
1985 })
1986 | Node::TraitItem(hir::TraitItem { ident, .. })
1988 | Node::ImplItem(hir::ImplItem { ident, .. })
1989 ) => {
1990 skip_list.insert(p);
1991 let entry = spanned_predicates.entry(ident.span);
1992 let entry = entry.or_insert_with(|| {
1993 (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
1994 });
1995 entry.0.insert(cause_span);
1996 entry.1.insert((ident.span, String::new()));
1997 entry.1.insert((cause_span, "unsatisfied trait bound introduced here".to_string()));
1998 entry.2.push(p);
1999 }
2000 _ => {
2001 }
2006 }
2007 }
2008 let mut spanned_predicates: Vec<_> = spanned_predicates.into_iter().collect();
2009 spanned_predicates.sort_by_key(|(span, _)| *span);
2010 for (_, (primary_spans, span_labels, predicates)) in spanned_predicates {
2011 let mut tracker = TraitBoundDuplicateTracker::new();
2012 let mut all_trait_bounds_for_rcvr = true;
2013 for pred in &predicates {
2014 match pred.kind().skip_binder() {
2015 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
2016 let self_ty = pred.trait_ref.self_ty();
2017 if self_ty.peel_refs() != rcvr_ty {
2018 all_trait_bounds_for_rcvr = false;
2019 break;
2020 }
2021 let is_ref = #[allow(non_exhaustive_omitted_patterns)] match self_ty.kind() {
ty::Ref(..) => true,
_ => false,
}matches!(self_ty.kind(), ty::Ref(..));
2022 tracker.track(pred.trait_ref.def_id, is_ref);
2023 }
2024 _ => {
2025 all_trait_bounds_for_rcvr = false;
2026 break;
2027 }
2028 }
2029 }
2030 let has_ref_dupes = tracker.has_ref_dupes();
2031 let trait_def_ids = tracker.into_trait_def_ids();
2032 let mut preds: Vec<_> = predicates
2033 .iter()
2034 .filter_map(|pred| format_pred(**pred))
2035 .map(|(p, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", p))
})format!("`{p}`"))
2036 .collect();
2037 preds.sort();
2038 preds.dedup();
2039 let availability_note = if all_trait_bounds_for_rcvr
2040 && has_ref_dupes
2041 && trait_def_ids.len() > 1
2042 && #[allow(non_exhaustive_omitted_patterns)] match rcvr_ty.kind() {
ty::Adt(..) => true,
_ => false,
}matches!(rcvr_ty.kind(), ty::Adt(..))
2043 {
2044 let mut trait_names = trait_def_ids
2045 .into_iter()
2046 .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)))
2047 .collect::<Vec<_>>();
2048 trait_names.sort();
2049 listify(&trait_names, |name| name.to_string()).map(|traits| {
2050 ::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!(
2051 "for `{item_ident}` to be available, `{rcvr_ty_str}` must implement {traits}"
2052 )
2053 })
2054 } else {
2055 None
2056 };
2057 let msg = if let Some(availability_note) = availability_note {
2058 availability_note
2059 } else if let [pred] = &preds[..] {
2060 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait bound {0} was not satisfied",
pred))
})format!("trait bound {pred} was not satisfied")
2061 } else {
2062 ::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"),)
2063 };
2064 let mut span: MultiSpan = primary_spans.into_iter().collect::<Vec<_>>().into();
2065 for (sp, label) in span_labels {
2066 span.push_span_label(sp, label);
2067 }
2068 err.span_note(span, msg);
2069 *unsatisfied_bounds = true;
2070 }
2071
2072 let mut suggested_bounds = UnordSet::default();
2073 let mut bound_list = unsatisfied_predicates
2075 .iter()
2076 .filter_map(|(pred, parent_pred, _cause)| {
2077 let mut suggested = false;
2078 format_pred(*pred).map(|(p, self_ty)| {
2079 if let Some(parent) = parent_pred
2080 && suggested_bounds.contains(parent)
2081 {
2082 } else if !suggested_bounds.contains(pred)
2084 && collect_type_param_suggestions(self_ty, *pred, &p)
2085 {
2086 suggested = true;
2087 suggested_bounds.insert(pred);
2088 }
2089 (
2090 match parent_pred {
2091 None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", p))
})format!("`{p}`"),
2092 Some(parent_pred) => match format_pred(*parent_pred) {
2093 None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", p))
})format!("`{p}`"),
2094 Some((parent_p, _)) => {
2095 if !suggested
2096 && !suggested_bounds.contains(pred)
2097 && !suggested_bounds.contains(parent_pred)
2098 && collect_type_param_suggestions(self_ty, *parent_pred, &p)
2099 {
2100 suggested_bounds.insert(pred);
2101 }
2102 ::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}`")
2103 }
2104 },
2105 },
2106 *pred,
2107 )
2108 })
2109 })
2110 .filter(|(_, pred)| !skip_list.contains(&pred))
2111 .map(|(t, _)| t)
2112 .enumerate()
2113 .collect::<Vec<(usize, String)>>();
2114
2115 if !#[allow(non_exhaustive_omitted_patterns)] match rcvr_ty.peel_refs().kind() {
ty::Param(_) => true,
_ => false,
}matches!(rcvr_ty.peel_refs().kind(), ty::Param(_)) {
2116 for ((span, add_where_or_comma), obligations) in type_params.into_iter() {
2117 *restrict_type_params = true;
2118 let obligations = obligations.into_sorted_stable_ord();
2120 err.span_suggestion_verbose(
2121 span,
2122 ::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!(
2123 "consider restricting the type parameter{s} to satisfy the trait \
2124 bound{s}",
2125 s = pluralize!(obligations.len())
2126 ),
2127 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", add_where_or_comma,
obligations.join(", ")))
})format!("{} {}", add_where_or_comma, obligations.join(", ")),
2128 Applicability::MaybeIncorrect,
2129 );
2130 }
2131 }
2132
2133 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() {
2138 let bound_list =
2139 bound_list.into_iter().map(|(_, path)| path).collect::<Vec<_>>().join("\n");
2140 let actual_prefix = rcvr_ty.prefix_string(self.tcx);
2141 {
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:2141",
"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(2141u32),
::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());
2142 let (primary_message, label, notes) = if unimplemented_traits.len() == 1
2143 && unimplemented_traits_only
2144 {
2145 unimplemented_traits
2146 .into_iter()
2147 .next()
2148 .map(|(_, (trait_ref, obligation))| {
2149 if trait_ref.self_ty().references_error() || rcvr_ty.references_error() {
2150 return (None, None, Vec::new());
2152 }
2153 let CustomDiagnostic { message, label, notes, .. } = self
2154 .err_ctxt()
2155 .on_unimplemented_note(trait_ref, &obligation, err.long_ty_path());
2156 (message, label, notes)
2157 })
2158 .unwrap()
2159 } else {
2160 (None, None, Vec::new())
2161 };
2162 let primary_message = primary_message.unwrap_or_else(|| {
2163 let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
2164 ::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!(
2165 "the {item_kind} `{item_ident}` exists for {actual_prefix} `{ty_str}`, \
2166 but its trait bounds were not satisfied"
2167 )
2168 });
2169 err.primary_message(primary_message);
2170 if let Some(label) = label {
2171 *custom_span_label = true;
2172 err.span_label(span, label);
2173 }
2174 if !bound_list.is_empty() {
2175 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}"));
2176 }
2177 for note in notes {
2178 err.note(note);
2179 }
2180
2181 if let ty::Adt(adt_def, _) = rcvr_ty.kind() {
2182 unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
2183 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2184 pred.kind().skip_binder()
2185 {
2186 self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
2187 err, &pred, *adt_def,
2188 )
2189 } else {
2190 false
2191 }
2192 });
2193 }
2194
2195 *suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
2196 *unsatisfied_bounds = true;
2197 }
2198 if manually_impl {
2199 err.help("consider manually implementing the trait to avoid undesired bounds");
2200 }
2201 }
2202
2203 fn lookup_segments_chain_for_no_match_method(
2205 &self,
2206 err: &mut Diag<'_>,
2207 item_name: Ident,
2208 item_kind: &str,
2209 source: SelfSource<'tcx>,
2210 no_match_data: &NoMatchData<'tcx>,
2211 ) {
2212 if no_match_data.unsatisfied_predicates.is_empty()
2213 && let Mode::MethodCall = no_match_data.mode
2214 && let SelfSource::MethodCall(mut source_expr) = source
2215 {
2216 let mut stack_methods = ::alloc::vec::Vec::new()vec![];
2217 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, method_span) =
2218 source_expr.kind
2219 {
2220 if let Some(prev_match) = stack_methods.pop() {
2222 err.span_label(
2223 method_span,
2224 ::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}`"),
2225 );
2226 }
2227 let rcvr_ty = self.resolve_vars_if_possible(
2228 self.typeck_results
2229 .borrow()
2230 .expr_ty_adjusted_opt(rcvr_expr)
2231 .unwrap_or(Ty::new_misc_error(self.tcx)),
2232 );
2233
2234 let Ok(candidates) = self.probe_for_name_many(
2235 Mode::MethodCall,
2236 item_name,
2237 None,
2238 IsSuggestion(true),
2239 rcvr_ty,
2240 source_expr.hir_id,
2241 ProbeScope::TraitsInScope,
2242 ) else {
2243 return;
2244 };
2245
2246 for _matched_method in candidates {
2250 stack_methods.push(rcvr_ty);
2252 }
2253 source_expr = rcvr_expr;
2254 }
2255 if let Some(prev_match) = stack_methods.pop() {
2257 err.span_label(
2258 source_expr.span,
2259 ::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}`"),
2260 );
2261 }
2262 }
2263 }
2264
2265 fn find_likely_intended_associated_item(
2266 &self,
2267 err: &mut Diag<'_>,
2268 similar_candidate: ty::AssocItem,
2269 span: Span,
2270 args: Option<&'tcx [hir::Expr<'tcx>]>,
2271 mode: Mode,
2272 ) {
2273 let tcx = self.tcx;
2274 let def_kind = similar_candidate.as_def_kind();
2275 let an = self.tcx.def_kind_descr_article(def_kind, similar_candidate.def_id);
2276 let similar_candidate_name = similar_candidate.name();
2277 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!(
2278 "there is {an} {} `{}` with a similar name",
2279 self.tcx.def_kind_descr(def_kind, similar_candidate.def_id),
2280 similar_candidate_name,
2281 );
2282 if def_kind == DefKind::AssocFn {
2287 let ty_args = self.infcx.fresh_args_for_item(span, similar_candidate.def_id);
2288 let fn_sig =
2289 tcx.fn_sig(similar_candidate.def_id).instantiate(tcx, ty_args).skip_norm_wip();
2290 let fn_sig = self.instantiate_binder_with_fresh_vars(
2291 span,
2292 BoundRegionConversionTime::FnCall,
2293 fn_sig,
2294 );
2295 if similar_candidate.is_method() {
2296 if let Some(args) = args
2297 && fn_sig.inputs()[1..].len() == args.len()
2298 {
2299 err.span_suggestion_verbose(
2302 span,
2303 msg,
2304 similar_candidate_name,
2305 Applicability::MaybeIncorrect,
2306 );
2307 } else {
2308 err.span_help(
2311 tcx.def_span(similar_candidate.def_id),
2312 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}",
if let None = args {
""
} else { ", but with different arguments" }, msg))
})format!(
2313 "{msg}{}",
2314 if let None = args { "" } else { ", but with different arguments" },
2315 ),
2316 );
2317 }
2318 } else if let Some(args) = args
2319 && fn_sig.inputs().len() == args.len()
2320 {
2321 err.span_suggestion_verbose(
2324 span,
2325 msg,
2326 similar_candidate_name,
2327 Applicability::MaybeIncorrect,
2328 );
2329 } else {
2330 err.span_help(tcx.def_span(similar_candidate.def_id), msg);
2331 }
2332 } else if let Mode::Path = mode
2333 && args.unwrap_or(&[]).is_empty()
2334 {
2335 err.span_suggestion_verbose(
2337 span,
2338 msg,
2339 similar_candidate_name,
2340 Applicability::MaybeIncorrect,
2341 );
2342 } else {
2343 err.span_help(tcx.def_span(similar_candidate.def_id), msg);
2346 }
2347 }
2348
2349 pub(crate) fn confusable_method_name(
2350 &self,
2351 err: &mut Diag<'_>,
2352 rcvr_ty: Ty<'tcx>,
2353 item_name: Ident,
2354 call_args: Option<Vec<Ty<'tcx>>>,
2355 ) -> Option<Symbol> {
2356 if let ty::Adt(adt, adt_args) = rcvr_ty.kind() {
2357 for &inherent_impl_did in self.tcx.inherent_impls(adt.did()).into_iter() {
2358 for inherent_method in
2359 self.tcx.associated_items(inherent_impl_did).in_definition_order()
2360 {
2361 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)
2362 && confusables.contains(&item_name.name)
2363 && inherent_method.is_fn()
2364 {
2365 let args =
2366 ty::GenericArgs::identity_for_item(self.tcx, inherent_method.def_id)
2367 .rebase_onto(
2368 self.tcx,
2369 inherent_method.container_id(self.tcx),
2370 adt_args,
2371 );
2372 let fn_sig = self
2373 .tcx
2374 .fn_sig(inherent_method.def_id)
2375 .instantiate(self.tcx, args)
2376 .skip_norm_wip();
2377 let fn_sig = self.instantiate_binder_with_fresh_vars(
2378 item_name.span,
2379 BoundRegionConversionTime::FnCall,
2380 fn_sig,
2381 );
2382 let name = inherent_method.name();
2383 let inputs = fn_sig.inputs();
2384 let expected_inputs =
2385 if inherent_method.is_method() { &inputs[1..] } else { inputs };
2386 if let Some(ref args) = call_args
2387 && expected_inputs
2388 .iter()
2389 .eq_by(args, |expected, found| self.may_coerce(*expected, *found))
2390 {
2391 err.span_suggestion_verbose(
2392 item_name.span,
2393 ::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),
2394 name,
2395 Applicability::MaybeIncorrect,
2396 );
2397 return Some(name);
2398 } else if let None = call_args {
2399 err.span_note(
2400 self.tcx.def_span(inherent_method.def_id),
2401 ::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),
2402 );
2403 return Some(name);
2404 }
2405 }
2406 }
2407 }
2408 }
2409 None
2410 }
2411 fn note_candidates_on_method_error(
2412 &self,
2413 rcvr_ty: Ty<'tcx>,
2414 item_name: Ident,
2415 self_source: SelfSource<'tcx>,
2416 args: Option<&'tcx [hir::Expr<'tcx>]>,
2417 span: Span,
2418 err: &mut Diag<'_>,
2419 sources: &mut Vec<CandidateSource>,
2420 sugg_span: Option<Span>,
2421 ) {
2422 sources.sort_by_key(|source| match *source {
2423 CandidateSource::Trait(id) => (0, self.tcx.def_path_str(id)),
2424 CandidateSource::Impl(id) => (1, self.tcx.def_path_str(id)),
2425 });
2426 sources.dedup();
2427 let limit = if sources.len() == 5 { 5 } else { 4 };
2429
2430 let mut suggs = ::alloc::vec::Vec::new()vec![];
2431 for (idx, source) in sources.iter().take(limit).enumerate() {
2432 match *source {
2433 CandidateSource::Impl(impl_did) => {
2434 let Some(item) = self.associated_value(impl_did, item_name).or_else(|| {
2437 let impl_trait_id = self.tcx.impl_opt_trait_id(impl_did)?;
2438 self.associated_value(impl_trait_id, item_name)
2439 }) else {
2440 continue;
2441 };
2442
2443 let note_span = if item.def_id.is_local() {
2444 Some(self.tcx.def_span(item.def_id))
2445 } else if impl_did.is_local() {
2446 Some(self.tcx.def_span(impl_did))
2447 } else {
2448 None
2449 };
2450
2451 let impl_ty =
2452 self.tcx.at(span).type_of(impl_did).instantiate_identity().skip_norm_wip();
2453
2454 let insertion = match self.tcx.impl_opt_trait_ref(impl_did) {
2455 None => String::new(),
2456 Some(trait_ref) => {
2457 ::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!(
2458 " of the trait `{}`",
2459 self.tcx.def_path_str(trait_ref.skip_binder().def_id)
2460 )
2461 }
2462 };
2463
2464 let (note_str, idx) = if sources.len() > 1 {
2465 (
2466 ::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!(
2467 "candidate #{} is defined in an impl{} for the type `{}`",
2468 idx + 1,
2469 insertion,
2470 impl_ty,
2471 ),
2472 Some(idx + 1),
2473 )
2474 } else {
2475 (
2476 ::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!(
2477 "the candidate is defined in an impl{insertion} for the type `{impl_ty}`",
2478 ),
2479 None,
2480 )
2481 };
2482 if let Some(note_span) = note_span {
2483 err.span_note(note_span, note_str);
2485 } else {
2486 err.note(note_str);
2487 }
2488 if let Some(sugg_span) = sugg_span
2489 && let Some(trait_ref) = self.tcx.impl_opt_trait_ref(impl_did)
2490 && let Some(sugg) = print_disambiguation_help(
2491 self.tcx,
2492 err,
2493 self_source,
2494 args,
2495 trait_ref
2496 .instantiate(
2497 self.tcx,
2498 self.fresh_args_for_item(sugg_span, impl_did),
2499 )
2500 .skip_norm_wip()
2501 .with_replaced_self_ty(self.tcx, rcvr_ty),
2502 idx,
2503 sugg_span,
2504 item,
2505 )
2506 {
2507 suggs.push(sugg);
2508 }
2509 }
2510 CandidateSource::Trait(trait_did) => {
2511 let Some(item) = self.associated_value(trait_did, item_name) else { continue };
2512 let item_span = self.tcx.def_span(item.def_id);
2513 let idx = if sources.len() > 1 {
2514 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!(
2515 "candidate #{} is defined in the trait `{}`",
2516 idx + 1,
2517 self.tcx.def_path_str(trait_did)
2518 );
2519 err.span_note(item_span, msg);
2520 Some(idx + 1)
2521 } else {
2522 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!(
2523 "the candidate is defined in the trait `{}`",
2524 self.tcx.def_path_str(trait_did)
2525 );
2526 err.span_note(item_span, msg);
2527 None
2528 };
2529 if let Some(sugg_span) = sugg_span
2530 && let Some(sugg) = print_disambiguation_help(
2531 self.tcx,
2532 err,
2533 self_source,
2534 args,
2535 ty::TraitRef::new_from_args(
2536 self.tcx,
2537 trait_did,
2538 self.fresh_args_for_item(sugg_span, trait_did),
2539 )
2540 .with_replaced_self_ty(self.tcx, rcvr_ty),
2541 idx,
2542 sugg_span,
2543 item,
2544 )
2545 {
2546 suggs.push(sugg);
2547 }
2548 }
2549 }
2550 }
2551 if !suggs.is_empty()
2552 && let Some(span) = sugg_span
2553 {
2554 suggs.sort();
2555 err.span_suggestions(
2556 span.with_hi(item_name.span.lo()),
2557 "use fully-qualified syntax to disambiguate",
2558 suggs,
2559 Applicability::MachineApplicable,
2560 );
2561 }
2562 if sources.len() > limit {
2563 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("and {0} others",
sources.len() - limit))
})format!("and {} others", sources.len() - limit));
2564 }
2565 }
2566
2567 fn find_builder_fn(&self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>, expr_id: hir::HirId) {
2570 let ty::Adt(adt_def, _) = rcvr_ty.kind() else {
2571 return;
2572 };
2573 let mut items = self
2574 .tcx
2575 .inherent_impls(adt_def.did())
2576 .iter()
2577 .flat_map(|&i| self.tcx.associated_items(i).in_definition_order())
2578 .filter(|item| {
2581 #[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, .. })
2582 && self
2583 .probe_for_name(
2584 Mode::Path,
2585 item.ident(self.tcx),
2586 None,
2587 IsSuggestion(true),
2588 rcvr_ty,
2589 expr_id,
2590 ProbeScope::TraitsInScope,
2591 )
2592 .is_ok()
2593 })
2594 .filter_map(|item| {
2595 let ret_ty = self
2597 .tcx
2598 .fn_sig(item.def_id)
2599 .instantiate(self.tcx, self.fresh_args_for_item(DUMMY_SP, item.def_id))
2600 .skip_norm_wip()
2601 .output();
2602 let ret_ty = self.tcx.instantiate_bound_regions_with_erased(ret_ty);
2603 let ty::Adt(def, args) = ret_ty.kind() else {
2604 return None;
2605 };
2606 if self.can_eq(self.param_env, ret_ty, rcvr_ty) {
2608 return Some((item.def_id, ret_ty));
2609 }
2610 if ![self.tcx.lang_items().option_type(), self.tcx.get_diagnostic_item(sym::Result)]
2612 .contains(&Some(def.did()))
2613 {
2614 return None;
2615 }
2616 let arg = args.get(0)?.expect_ty();
2617 if self.can_eq(self.param_env, rcvr_ty, arg) {
2618 Some((item.def_id, ret_ty))
2619 } else {
2620 None
2621 }
2622 })
2623 .collect::<Vec<_>>();
2624 let post = if items.len() > 5 {
2625 let items_len = items.len();
2626 items.truncate(4);
2627 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} others", items_len - 4))
})format!("\nand {} others", items_len - 4)
2628 } else {
2629 String::new()
2630 };
2631 match items[..] {
2632 [] => {}
2633 [(def_id, ret_ty)] => {
2634 err.span_note(
2635 self.tcx.def_span(def_id),
2636 ::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!(
2637 "if you're trying to build a new `{rcvr_ty}`, consider using `{}` which \
2638 returns `{ret_ty}`",
2639 self.tcx.def_path_str(def_id),
2640 ),
2641 );
2642 }
2643 _ => {
2644 let span: MultiSpan = items
2645 .iter()
2646 .map(|&(def_id, _)| self.tcx.def_span(def_id))
2647 .collect::<Vec<Span>>()
2648 .into();
2649 err.span_note(
2650 span,
2651 ::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!(
2652 "if you're trying to build a new `{rcvr_ty}` consider using one of the \
2653 following associated functions:\n{}{post}",
2654 items
2655 .iter()
2656 .map(|&(def_id, _ret_ty)| self.tcx.def_path_str(def_id))
2657 .collect::<Vec<String>>()
2658 .join("\n")
2659 ),
2660 );
2661 }
2662 }
2663 }
2664
2665 fn suggest_associated_call_syntax(
2668 &self,
2669 err: &mut Diag<'_>,
2670 static_candidates: &[CandidateSource],
2671 rcvr_ty: Ty<'tcx>,
2672 source: SelfSource<'tcx>,
2673 item_name: Ident,
2674 args: Option<&'tcx [hir::Expr<'tcx>]>,
2675 sugg_span: Span,
2676 ) {
2677 let mut has_unsuggestable_args = false;
2678 let ty_str = if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0) {
2679 let impl_ty = self.tcx.type_of(*impl_did).instantiate_identity().skip_norm_wip();
2683 let target_ty = self
2684 .autoderef(sugg_span, rcvr_ty)
2685 .silence_errors()
2686 .find(|(rcvr_ty, _)| {
2687 DeepRejectCtxt::relate_rigid_infer(self.tcx).types_may_unify(*rcvr_ty, impl_ty)
2688 })
2689 .map_or(impl_ty, |(ty, _)| ty)
2690 .peel_refs();
2691 if let ty::Adt(def, args) = target_ty.kind() {
2692 let infer_args = self.tcx.mk_args_from_iter(args.into_iter().map(|arg| {
2695 if !arg.is_suggestable(self.tcx, true) {
2696 has_unsuggestable_args = true;
2697 match arg.kind() {
2698 GenericArgKind::Lifetime(_) => {
2699 self.next_region_var(RegionVariableOrigin::Misc(DUMMY_SP)).into()
2700 }
2701 GenericArgKind::Type(_) => self.next_ty_var(DUMMY_SP).into(),
2702 GenericArgKind::Const(_) => self.next_const_var(DUMMY_SP).into(),
2703 }
2704 } else {
2705 arg
2706 }
2707 }));
2708
2709 self.tcx.value_path_str_with_args(def.did(), infer_args)
2710 } else {
2711 self.ty_to_value_string(target_ty)
2712 }
2713 } else {
2714 self.ty_to_value_string(rcvr_ty.peel_refs())
2715 };
2716 if let SelfSource::MethodCall(_) = source {
2717 let first_arg = static_candidates.get(0).and_then(|candidate_source| {
2718 let (assoc_did, self_ty) = match candidate_source {
2719 CandidateSource::Impl(impl_did) => (
2720 *impl_did,
2721 self.tcx.type_of(*impl_did).instantiate_identity().skip_norm_wip(),
2722 ),
2723 CandidateSource::Trait(trait_did) => (*trait_did, rcvr_ty),
2724 };
2725
2726 let assoc = self.associated_value(assoc_did, item_name)?;
2727 if !assoc.is_fn() {
2728 return None;
2729 }
2730
2731 let sig = self.tcx.fn_sig(assoc.def_id).instantiate_identity().skip_norm_wip();
2734 sig.inputs().skip_binder().get(0).and_then(|first| {
2735 let first_ty = first.peel_refs();
2737 if first_ty == self_ty || first_ty == self.tcx.types.self_param {
2738 Some(first.ref_mutability().map_or("", |mutbl| mutbl.ref_prefix_str()))
2739 } else {
2740 None
2741 }
2742 })
2743 });
2744
2745 let mut applicability = Applicability::MachineApplicable;
2746 let args = if let SelfSource::MethodCall(receiver) = source
2747 && let Some(args) = args
2748 {
2749 let explicit_args = if first_arg.is_some() {
2751 std::iter::once(receiver).chain(args.iter()).collect::<Vec<_>>()
2752 } else {
2753 if has_unsuggestable_args {
2755 applicability = Applicability::HasPlaceholders;
2756 }
2757 args.iter().collect()
2758 };
2759 ::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!(
2760 "({}{})",
2761 first_arg.unwrap_or(""),
2762 explicit_args
2763 .iter()
2764 .map(|arg| self
2765 .tcx
2766 .sess
2767 .source_map()
2768 .span_to_snippet(arg.span)
2769 .unwrap_or_else(|_| {
2770 applicability = Applicability::HasPlaceholders;
2771 "_".to_owned()
2772 }))
2773 .collect::<Vec<_>>()
2774 .join(", "),
2775 )
2776 } else {
2777 applicability = Applicability::HasPlaceholders;
2778 "(...)".to_owned()
2779 };
2780 err.span_suggestion_verbose(
2781 sugg_span,
2782 "use associated function syntax instead",
2783 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}{2}", ty_str, item_name,
args))
})format!("{ty_str}::{item_name}{args}"),
2784 applicability,
2785 );
2786 } else {
2787 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}`",));
2788 }
2789 }
2790
2791 fn suggest_calling_field_as_fn(
2794 &self,
2795 span: Span,
2796 rcvr_ty: Ty<'tcx>,
2797 expr: &hir::Expr<'_>,
2798 item_name: Ident,
2799 err: &mut Diag<'_>,
2800 ) -> bool {
2801 let tcx = self.tcx;
2802 let field_receiver =
2803 self.autoderef(span, rcvr_ty).silence_errors().find_map(|(ty, _)| match ty.kind() {
2804 ty::Adt(def, args) if !def.is_enum() => {
2805 let variant = &def.non_enum_variant();
2806 tcx.find_field_index(item_name, variant).map(|index| {
2807 let field = &variant.fields[index];
2808 let field_ty = field.ty(tcx, args);
2809 (field, field_ty)
2810 })
2811 }
2812 _ => None,
2813 });
2814 if let Some((field, field_ty)) = field_receiver {
2815 let scope = tcx.parent_module_from_def_id(self.body_id);
2816 let is_accessible = field.vis.is_accessible_from(scope, tcx);
2817
2818 if is_accessible {
2819 if let Some((what, _, _)) = self.extract_callable_info(field_ty) {
2820 let what = match what {
2821 DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
2822 DefIdOrName::Name(what) => what,
2823 };
2824 let expr_span = expr.span.to(item_name.span);
2825 err.multipart_suggestion(
2826 ::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!(
2827 "to call the {what} stored in `{item_name}`, \
2828 surround the field access with parentheses",
2829 ),
2830 ::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![
2831 (expr_span.shrink_to_lo(), '('.to_string()),
2832 (expr_span.shrink_to_hi(), ')'.to_string()),
2833 ],
2834 Applicability::MachineApplicable,
2835 );
2836 } else {
2837 let call_expr = tcx.hir_expect_expr(tcx.parent_hir_id(expr.hir_id));
2838
2839 if let Some(span) = call_expr.span.trim_start(item_name.span) {
2840 err.span_suggestion(
2841 span,
2842 "remove the arguments",
2843 "",
2844 Applicability::MaybeIncorrect,
2845 );
2846 }
2847 }
2848 }
2849
2850 let field_kind = if is_accessible { "field" } else { "private field" };
2851 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"));
2852 return true;
2853 }
2854 false
2855 }
2856
2857 fn report_failed_method_call_on_range_end(
2860 &self,
2861 tcx: TyCtxt<'tcx>,
2862 actual: Ty<'tcx>,
2863 source: SelfSource<'tcx>,
2864 span: Span,
2865 item_name: Ident,
2866 ) -> Result<(), ErrorGuaranteed> {
2867 if let SelfSource::MethodCall(expr) = source {
2868 for (_, parent) in tcx.hir_parent_iter(expr.hir_id).take(5) {
2869 if let Node::Expr(parent_expr) = parent {
2870 if !is_range_literal(parent_expr) {
2871 continue;
2872 }
2873 let lang_item = match parent_expr.kind {
2874 ExprKind::Struct(qpath, _, _) => match tcx.qpath_lang_item(*qpath) {
2875 Some(
2876 lang_item @ (LangItem::Range
2877 | LangItem::RangeCopy
2878 | LangItem::RangeInclusiveCopy
2879 | LangItem::RangeTo
2880 | LangItem::RangeToInclusive),
2881 ) => Some(lang_item),
2882 _ => None,
2883 },
2884 ExprKind::Call(func, _) => match func.kind {
2885 ExprKind::Path(qpath)
2887 if tcx.qpath_is_lang_item(qpath, LangItem::RangeInclusiveNew) =>
2888 {
2889 Some(LangItem::RangeInclusiveStruct)
2890 }
2891 _ => None,
2892 },
2893 _ => None,
2894 };
2895
2896 if lang_item.is_none() {
2897 continue;
2898 }
2899
2900 let span_included = match parent_expr.kind {
2901 hir::ExprKind::Struct(_, eps, _) => {
2902 eps.last().is_some_and(|ep| ep.span.contains(span))
2903 }
2904 hir::ExprKind::Call(func, ..) => func.span.contains(span),
2906 _ => false,
2907 };
2908
2909 if !span_included {
2910 continue;
2911 }
2912
2913 let Some(range_def_id) =
2914 lang_item.and_then(|lang_item| self.tcx.lang_items().get(lang_item))
2915 else {
2916 continue;
2917 };
2918 let range_ty = self
2919 .tcx
2920 .type_of(range_def_id)
2921 .instantiate(self.tcx, &[actual.into()])
2922 .skip_norm_wip();
2923
2924 let pick = self.lookup_probe_for_diagnostic(
2925 item_name,
2926 range_ty,
2927 expr,
2928 ProbeScope::AllTraits,
2929 None,
2930 );
2931 if pick.is_ok() {
2932 let range_span = parent_expr.span.with_hi(expr.span.hi());
2933 return Err(self.dcx().emit_err(errors::MissingParenthesesInRange {
2934 span,
2935 ty: actual,
2936 method_name: item_name.as_str().to_string(),
2937 add_missing_parentheses: Some(errors::AddMissingParenthesesInRange {
2938 func_name: item_name.name.as_str().to_string(),
2939 left: range_span.shrink_to_lo(),
2940 right: range_span.shrink_to_hi(),
2941 }),
2942 }));
2943 }
2944 }
2945 }
2946 }
2947 Ok(())
2948 }
2949
2950 fn report_failed_method_call_on_numerical_infer_var(
2951 &self,
2952 tcx: TyCtxt<'tcx>,
2953 actual: Ty<'tcx>,
2954 source: SelfSource<'_>,
2955 span: Span,
2956 item_kind: &str,
2957 item_name: Ident,
2958 long_ty_path: &mut Option<PathBuf>,
2959 ) -> Result<(), ErrorGuaranteed> {
2960 let found_candidate = all_traits(self.tcx)
2961 .into_iter()
2962 .any(|info| self.associated_value(info.def_id, item_name).is_some());
2963 let found_assoc = |ty: Ty<'tcx>| {
2964 simplify_type(tcx, ty, TreatParams::InstantiateWithInfer)
2965 .and_then(|simp| {
2966 tcx.incoherent_impls(simp)
2967 .iter()
2968 .find_map(|&id| self.associated_value(id, item_name))
2969 })
2970 .is_some()
2971 };
2972 let found_candidate = found_candidate
2973 || found_assoc(tcx.types.i8)
2974 || found_assoc(tcx.types.i16)
2975 || found_assoc(tcx.types.i32)
2976 || found_assoc(tcx.types.i64)
2977 || found_assoc(tcx.types.i128)
2978 || found_assoc(tcx.types.u8)
2979 || found_assoc(tcx.types.u16)
2980 || found_assoc(tcx.types.u32)
2981 || found_assoc(tcx.types.u64)
2982 || found_assoc(tcx.types.u128)
2983 || found_assoc(tcx.types.f32)
2984 || found_assoc(tcx.types.f64);
2985 if found_candidate
2986 && actual.is_numeric()
2987 && !actual.has_concrete_skeleton()
2988 && let SelfSource::MethodCall(expr) = source
2989 {
2990 let ty_str = self.tcx.short_string(actual, long_ty_path);
2991 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!(
2992 self.dcx(),
2993 span,
2994 E0689,
2995 "can't call {item_kind} `{item_name}` on ambiguous numeric type `{ty_str}`"
2996 );
2997 *err.long_ty_path() = long_ty_path.take();
2998 let concrete_type = if actual.is_integral() { "i32" } else { "f32" };
2999 match expr.kind {
3000 ExprKind::Lit(lit) => {
3001 let snippet = tcx
3003 .sess
3004 .source_map()
3005 .span_to_snippet(lit.span)
3006 .unwrap_or_else(|_| "<numeric literal>".to_owned());
3007
3008 let snippet = snippet.trim_suffix('.');
3011 err.span_suggestion(
3012 lit.span,
3013 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you must specify a concrete type for this numeric value, like `{0}`",
concrete_type))
})format!(
3014 "you must specify a concrete type for this numeric value, \
3015 like `{concrete_type}`"
3016 ),
3017 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_{1}", snippet, concrete_type))
})format!("{snippet}_{concrete_type}"),
3018 Applicability::MaybeIncorrect,
3019 );
3020 }
3021 ExprKind::Path(QPath::Resolved(_, path)) => {
3022 if let hir::def::Res::Local(hir_id) = path.res {
3024 let span = tcx.hir_span(hir_id);
3025 let filename = tcx.sess.source_map().span_to_filename(span);
3026
3027 let parent_node = self.tcx.parent_hir_node(hir_id);
3028 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you must specify a type for this binding, like `{0}`",
concrete_type))
})format!(
3029 "you must specify a type for this binding, like `{concrete_type}`",
3030 );
3031
3032 match (filename, parent_node) {
3035 (
3036 FileName::Real(_),
3037 Node::LetStmt(hir::LetStmt {
3038 source: hir::LocalSource::Normal,
3039 ty,
3040 ..
3041 }),
3042 ) => {
3043 let type_span = ty
3044 .map(|ty| ty.span.with_lo(span.hi()))
3045 .unwrap_or(span.shrink_to_hi());
3046 err.span_suggestion(
3047 type_span,
3050 msg,
3051 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}", concrete_type))
})format!(": {concrete_type}"),
3052 Applicability::MaybeIncorrect,
3053 );
3054 }
3055 (FileName::Real(_), Node::Pat(pat))
3058 if let Node::Pat(binding_pat) = self.tcx.hir_node(hir_id)
3059 && let hir::PatKind::Binding(..) = binding_pat.kind
3060 && let Node::Pat(parent_pat) = parent_node
3061 && #[allow(non_exhaustive_omitted_patterns)] match parent_pat.kind {
hir::PatKind::Ref(..) => true,
_ => false,
}matches!(parent_pat.kind, hir::PatKind::Ref(..)) =>
3062 {
3063 err.span_label(span, "you must specify a type for this binding");
3064
3065 let mut ref_muts = Vec::new();
3066 let mut current_node = parent_node;
3067
3068 while let Node::Pat(parent_pat) = current_node {
3069 if let hir::PatKind::Ref(_, _, mutability) = parent_pat.kind {
3070 ref_muts.push(mutability);
3071 current_node = self.tcx.parent_hir_node(parent_pat.hir_id);
3072 } else {
3073 break;
3074 }
3075 }
3076
3077 let mut type_annotation = String::new();
3078 for mutability in ref_muts.iter().rev() {
3079 match mutability {
3080 hir::Mutability::Mut => type_annotation.push_str("&mut "),
3081 hir::Mutability::Not => type_annotation.push('&'),
3082 }
3083 }
3084 type_annotation.push_str(&concrete_type);
3085
3086 err.span_suggestion_verbose(
3087 pat.span.shrink_to_hi(),
3088 "specify the type in the closure argument list",
3089 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}", type_annotation))
})format!(": {type_annotation}"),
3090 Applicability::MaybeIncorrect,
3091 );
3092 }
3093 _ => {
3094 err.span_label(span, msg);
3095 }
3096 }
3097 }
3098 }
3099 _ => {}
3100 }
3101 return Err(err.emit());
3102 }
3103 Ok(())
3104 }
3105
3106 pub(crate) fn suggest_assoc_method_call(&self, segs: &[PathSegment<'_>]) {
3110 {
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:3110",
"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(3110u32),
::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);
3111 let [seg1, seg2] = segs else {
3112 return;
3113 };
3114 self.dcx().try_steal_modify_and_emit_err(
3115 seg1.ident.span,
3116 StashKey::CallAssocMethod,
3117 |err| {
3118 let body = self.tcx.hir_body_owned_by(self.body_id);
3119 struct LetVisitor {
3120 ident_name: Symbol,
3121 }
3122
3123 impl<'v> Visitor<'v> for LetVisitor {
3125 type Result = ControlFlow<Option<&'v hir::Expr<'v>>>;
3126 fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) -> Self::Result {
3127 if let hir::StmtKind::Let(&hir::LetStmt { pat, init, .. }) = ex.kind
3128 && let hir::PatKind::Binding(_, _, ident, ..) = pat.kind
3129 && ident.name == self.ident_name
3130 {
3131 ControlFlow::Break(init)
3132 } else {
3133 hir::intravisit::walk_stmt(self, ex)
3134 }
3135 }
3136 }
3137
3138 if let Node::Expr(call_expr) = self.tcx.parent_hir_node(seg1.hir_id)
3139 && let ControlFlow::Break(Some(expr)) =
3140 (LetVisitor { ident_name: seg1.ident.name }).visit_body(body)
3141 && let Some(self_ty) = self.node_ty_opt(expr.hir_id)
3142 {
3143 let probe = self.lookup_probe_for_diagnostic(
3144 seg2.ident,
3145 self_ty,
3146 call_expr,
3147 ProbeScope::TraitsInScope,
3148 None,
3149 );
3150 if probe.is_ok() {
3151 let sm = self.infcx.tcx.sess.source_map();
3152 err.span_suggestion_verbose(
3153 sm.span_extend_while(seg1.ident.span.shrink_to_hi(), |c| c == ':')
3154 .unwrap(),
3155 "you may have meant to call an instance method",
3156 ".",
3157 Applicability::MaybeIncorrect,
3158 );
3159 }
3160 }
3161 },
3162 );
3163 }
3164
3165 fn suggest_calling_method_on_field(
3167 &self,
3168 err: &mut Diag<'_>,
3169 source: SelfSource<'tcx>,
3170 span: Span,
3171 actual: Ty<'tcx>,
3172 item_name: Ident,
3173 return_type: Option<Ty<'tcx>>,
3174 ) {
3175 if let SelfSource::MethodCall(expr) = source {
3176 let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id();
3177 for fields in self.get_field_candidates_considering_privacy_for_diag(
3178 span,
3179 actual,
3180 mod_id,
3181 expr.hir_id,
3182 ) {
3183 let call_expr = self.tcx.hir_expect_expr(self.tcx.parent_hir_id(expr.hir_id));
3184
3185 let lang_items = self.tcx.lang_items();
3186 let never_mention_traits = [
3187 lang_items.clone_trait(),
3188 lang_items.deref_trait(),
3189 lang_items.deref_mut_trait(),
3190 self.tcx.get_diagnostic_item(sym::AsRef),
3191 self.tcx.get_diagnostic_item(sym::AsMut),
3192 self.tcx.get_diagnostic_item(sym::Borrow),
3193 self.tcx.get_diagnostic_item(sym::BorrowMut),
3194 ];
3195 let mut candidate_fields: Vec<_> = fields
3196 .into_iter()
3197 .filter_map(|candidate_field| {
3198 self.check_for_nested_field_satisfying_condition_for_diag(
3199 span,
3200 &|_, field_ty| {
3201 self.lookup_probe_for_diagnostic(
3202 item_name,
3203 field_ty,
3204 call_expr,
3205 ProbeScope::TraitsInScope,
3206 return_type,
3207 )
3208 .is_ok_and(|pick| {
3209 !never_mention_traits
3210 .iter()
3211 .flatten()
3212 .any(|def_id| self.tcx.parent(pick.item.def_id) == *def_id)
3213 })
3214 },
3215 candidate_field,
3216 ::alloc::vec::Vec::new()vec![],
3217 mod_id,
3218 expr.hir_id,
3219 )
3220 })
3221 .map(|field_path| {
3222 field_path
3223 .iter()
3224 .map(|id| id.to_string())
3225 .collect::<Vec<String>>()
3226 .join(".")
3227 })
3228 .collect();
3229 candidate_fields.sort();
3230
3231 let len = candidate_fields.len();
3232 if len > 0 {
3233 err.span_suggestions(
3234 item_name.span.shrink_to_lo(),
3235 ::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!(
3236 "{} of the expressions' fields {} a method of the same name",
3237 if len > 1 { "some" } else { "one" },
3238 if len > 1 { "have" } else { "has" },
3239 ),
3240 candidate_fields.iter().map(|path| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.", path))
})format!("{path}.")),
3241 Applicability::MaybeIncorrect,
3242 );
3243 }
3244 }
3245 }
3246 }
3247
3248 fn suggest_unwrapping_inner_self(
3249 &self,
3250 err: &mut Diag<'_>,
3251 source: SelfSource<'tcx>,
3252 actual: Ty<'tcx>,
3253 item_name: Ident,
3254 ) {
3255 let tcx = self.tcx;
3256 let SelfSource::MethodCall(expr) = source else {
3257 return;
3258 };
3259 let call_expr = tcx.hir_expect_expr(tcx.parent_hir_id(expr.hir_id));
3260
3261 let ty::Adt(kind, args) = actual.kind() else {
3262 return;
3263 };
3264 match kind.adt_kind() {
3265 ty::AdtKind::Enum => {
3266 let matching_variants: Vec<_> = kind
3267 .variants()
3268 .iter()
3269 .flat_map(|variant| {
3270 let [field] = &variant.fields.raw[..] else {
3271 return None;
3272 };
3273 let field_ty = field.ty(tcx, args);
3274
3275 if self.resolve_vars_if_possible(field_ty).is_ty_var() {
3277 return None;
3278 }
3279
3280 self.lookup_probe_for_diagnostic(
3281 item_name,
3282 field_ty,
3283 call_expr,
3284 ProbeScope::TraitsInScope,
3285 None,
3286 )
3287 .ok()
3288 .map(|pick| (variant, field, pick))
3289 })
3290 .collect();
3291
3292 let ret_ty_matches = |diagnostic_item| {
3293 if let Some(ret_ty) = self
3294 .ret_coercion
3295 .as_ref()
3296 .map(|c| self.resolve_vars_if_possible(c.borrow().expected_ty()))
3297 && let ty::Adt(kind, _) = ret_ty.kind()
3298 && tcx.get_diagnostic_item(diagnostic_item) == Some(kind.did())
3299 {
3300 true
3301 } else {
3302 false
3303 }
3304 };
3305
3306 match &matching_variants[..] {
3307 [(_, field, pick)] => {
3308 let self_ty = field.ty(tcx, args);
3309 err.span_note(
3310 tcx.def_span(pick.item.def_id),
3311 ::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}`"),
3312 );
3313 let (article, kind, variant, question) = if tcx.is_diagnostic_item(sym::Result, kind.did())
3314 && !tcx.hir_is_inside_const_context(expr.hir_id)
3316 {
3317 ("a", "Result", "Err", ret_ty_matches(sym::Result))
3318 } else if tcx.is_diagnostic_item(sym::Option, kind.did()) {
3319 ("an", "Option", "None", ret_ty_matches(sym::Option))
3320 } else {
3321 return;
3322 };
3323 if question {
3324 err.span_suggestion_verbose(
3325 expr.span.shrink_to_hi(),
3326 ::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!(
3327 "use the `?` operator to extract the `{self_ty}` value, propagating \
3328 {article} `{kind}::{variant}` value to the caller"
3329 ),
3330 "?",
3331 Applicability::MachineApplicable,
3332 );
3333 } else {
3334 err.span_suggestion_verbose(
3335 expr.span.shrink_to_hi(),
3336 ::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!(
3337 "consider using `{kind}::expect` to unwrap the `{self_ty}` value, \
3338 panicking if the value is {article} `{kind}::{variant}`"
3339 ),
3340 ".expect(\"REASON\")",
3341 Applicability::HasPlaceholders,
3342 );
3343 }
3344 }
3345 _ => {}
3347 }
3348 }
3349 ty::AdtKind::Struct | ty::AdtKind::Union => {
3352 let [first] = ***args else {
3353 return;
3354 };
3355 let ty::GenericArgKind::Type(ty) = first.kind() else {
3356 return;
3357 };
3358 let Ok(pick) = self.lookup_probe_for_diagnostic(
3359 item_name,
3360 ty,
3361 call_expr,
3362 ProbeScope::TraitsInScope,
3363 None,
3364 ) else {
3365 return;
3366 };
3367
3368 let name = self.ty_to_value_string(actual);
3369 let inner_id = kind.did();
3370 let mutable = if let Some(AutorefOrPtrAdjustment::Autoref { mutbl, .. }) =
3371 pick.autoref_or_ptr_adjustment
3372 {
3373 Some(mutbl)
3374 } else {
3375 None
3376 };
3377
3378 if tcx.is_diagnostic_item(sym::LocalKey, inner_id) {
3379 err.help("use `with` or `try_with` to access thread local storage");
3380 } else if tcx.is_lang_item(kind.did(), LangItem::MaybeUninit) {
3381 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!(
3382 "if this `{name}` has been initialized, \
3383 use one of the `assume_init` methods to access the inner value"
3384 ));
3385 } else if tcx.is_diagnostic_item(sym::RefCell, inner_id) {
3386 let (suggestion, borrow_kind, panic_if) = match mutable {
3387 Some(Mutability::Not) => (".borrow()", "borrow", "a mutable borrow exists"),
3388 Some(Mutability::Mut) => {
3389 (".borrow_mut()", "mutably borrow", "any borrows exist")
3390 }
3391 None => return,
3392 };
3393 err.span_suggestion_verbose(
3394 expr.span.shrink_to_hi(),
3395 ::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!(
3396 "use `{suggestion}` to {borrow_kind} the `{ty}`, \
3397 panicking if {panic_if}"
3398 ),
3399 suggestion,
3400 Applicability::MaybeIncorrect,
3401 );
3402 } else if tcx.is_diagnostic_item(sym::Mutex, inner_id) {
3403 err.span_suggestion_verbose(
3404 expr.span.shrink_to_hi(),
3405 ::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!(
3406 "use `.lock().unwrap()` to borrow the `{ty}`, \
3407 blocking the current thread until it can be acquired"
3408 ),
3409 ".lock().unwrap()",
3410 Applicability::MaybeIncorrect,
3411 );
3412 } else if tcx.is_diagnostic_item(sym::RwLock, inner_id) {
3413 let (suggestion, borrow_kind) = match mutable {
3414 Some(Mutability::Not) => (".read().unwrap()", "borrow"),
3415 Some(Mutability::Mut) => (".write().unwrap()", "mutably borrow"),
3416 None => return,
3417 };
3418 err.span_suggestion_verbose(
3419 expr.span.shrink_to_hi(),
3420 ::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!(
3421 "use `{suggestion}` to {borrow_kind} the `{ty}`, \
3422 blocking the current thread until it can be acquired"
3423 ),
3424 suggestion,
3425 Applicability::MaybeIncorrect,
3426 );
3427 } else {
3428 return;
3429 };
3430
3431 err.span_note(
3432 tcx.def_span(pick.item.def_id),
3433 ::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}`"),
3434 );
3435 }
3436 }
3437 }
3438
3439 pub(crate) fn note_unmet_impls_on_type(
3440 &self,
3441 err: &mut Diag<'_>,
3442 errors: &[FulfillmentError<'tcx>],
3443 suggest_derive: bool,
3444 ) {
3445 let preds: Vec<_> = errors
3446 .iter()
3447 .filter_map(|e| match e.obligation.predicate.kind().skip_binder() {
3448 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
3449 match pred.self_ty().kind() {
3450 ty::Adt(_, _) => Some((e.root_obligation.predicate, pred)),
3451 _ => None,
3452 }
3453 }
3454 _ => None,
3455 })
3456 .collect();
3457
3458 let (mut local_preds, mut foreign_preds): (Vec<_>, Vec<_>) =
3460 preds.iter().partition(|&(_, pred)| {
3461 if let ty::Adt(def, _) = pred.self_ty().kind() {
3462 def.did().is_local()
3463 } else {
3464 false
3465 }
3466 });
3467
3468 local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
3469 let local_def_ids = local_preds
3470 .iter()
3471 .filter_map(|(_, pred)| match pred.self_ty().kind() {
3472 ty::Adt(def, _) => Some(def.did()),
3473 _ => None,
3474 })
3475 .collect::<FxIndexSet<_>>();
3476 let mut local_spans: MultiSpan = local_def_ids
3477 .iter()
3478 .filter_map(|def_id| {
3479 let span = self.tcx.def_span(*def_id);
3480 if span.is_dummy() { None } else { Some(span) }
3481 })
3482 .collect::<Vec<_>>()
3483 .into();
3484 for (_, pred) in &local_preds {
3485 if let ty::Adt(def, _) = pred.self_ty().kind() {
3486 local_spans.push_span_label(
3487 self.tcx.def_span(def.did()),
3488 ::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()),
3489 );
3490 }
3491 }
3492 if local_spans.primary_span().is_some() {
3493 let msg = if let [(_, local_pred)] = local_preds.as_slice() {
3494 ::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!(
3495 "an implementation of `{}` might be missing for `{}`",
3496 local_pred.trait_ref.print_trait_sugared(),
3497 local_pred.self_ty()
3498 )
3499 } else {
3500 ::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!(
3501 "the following type{} would have to `impl` {} required trait{} for this \
3502 operation to be valid",
3503 pluralize!(local_def_ids.len()),
3504 if local_def_ids.len() == 1 { "its" } else { "their" },
3505 pluralize!(local_preds.len()),
3506 )
3507 };
3508 err.span_note(local_spans, msg);
3509 }
3510
3511 foreign_preds
3512 .sort_by_key(|(_, pred): &(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
3513
3514 for (_, pred) in &foreign_preds {
3515 let ty = pred.self_ty();
3516 let ty::Adt(def, _) = ty.kind() else { continue };
3517 let span = self.tcx.def_span(def.did());
3518 if span.is_dummy() {
3519 continue;
3520 }
3521 let mut mspan: MultiSpan = span.into();
3522 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"));
3523 err.span_note(
3524 mspan,
3525 ::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()),
3526 );
3527
3528 foreign_preds.iter().find(|&(root_pred, pred)| {
3529 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3530 root_pred.kind().skip_binder()
3531 && let Some(root_adt) = root_pred.self_ty().ty_adt_def()
3532 {
3533 self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3534 } else {
3535 false
3536 }
3537 });
3538 }
3539
3540 let preds: Vec<_> = errors
3541 .iter()
3542 .map(|e| (e.obligation.predicate, None, Some(e.obligation.cause.clone())))
3543 .collect();
3544 if suggest_derive {
3545 self.suggest_derive(err, &preds);
3546 } else {
3547 let _ = self.note_predicate_source_and_get_derives(err, &preds);
3549 }
3550 }
3551
3552 fn consider_suggesting_derives_for_ty(
3555 &self,
3556 trait_pred: ty::TraitPredicate<'tcx>,
3557 adt: ty::AdtDef<'tcx>,
3558 ) -> Option<Vec<(String, Span, Symbol)>> {
3559 let diagnostic_name = self.tcx.get_diagnostic_name(trait_pred.def_id())?;
3560
3561 let can_derive = match diagnostic_name {
3562 sym::Copy | sym::Clone => true,
3563 _ if adt.is_union() => false,
3564 sym::Default
3565 | sym::Eq
3566 | sym::PartialEq
3567 | sym::Ord
3568 | sym::PartialOrd
3569 | sym::Hash
3570 | sym::Debug => true,
3571 _ => false,
3572 };
3573
3574 if !can_derive {
3575 return None;
3576 }
3577
3578 let trait_def_id = trait_pred.def_id();
3579 let self_ty = trait_pred.self_ty();
3580
3581 if self.tcx.non_blanket_impls_for_ty(trait_def_id, self_ty).any(|impl_def_id| {
3584 self.tcx
3585 .type_of(impl_def_id)
3586 .instantiate_identity()
3587 .skip_norm_wip()
3588 .ty_adt_def()
3589 .is_some_and(|def| def.did() == adt.did())
3590 }) {
3591 return None;
3592 }
3593
3594 let mut derives = Vec::new();
3595 let self_name = self_ty.to_string();
3596 let self_span = self.tcx.def_span(adt.did());
3597
3598 for super_trait in supertraits(self.tcx, ty::Binder::dummy(trait_pred.trait_ref)) {
3599 if let Some(parent_diagnostic_name) = self.tcx.get_diagnostic_name(super_trait.def_id())
3600 {
3601 derives.push((self_name.clone(), self_span, parent_diagnostic_name));
3602 }
3603 }
3604
3605 derives.push((self_name, self_span, diagnostic_name));
3606
3607 Some(derives)
3608 }
3609
3610 fn note_predicate_source_and_get_derives(
3611 &self,
3612 err: &mut Diag<'_>,
3613 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
3614 ) -> Vec<(String, Span, Symbol)> {
3615 let mut derives = Vec::new();
3616 let mut traits = Vec::new();
3617 for (pred, _, _) in unsatisfied_predicates {
3618 let Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred))) =
3619 pred.kind().no_bound_vars()
3620 else {
3621 continue;
3622 };
3623 let adt = match trait_pred.self_ty().ty_adt_def() {
3624 Some(adt) if adt.did().is_local() => adt,
3625 _ => continue,
3626 };
3627 if let Some(new_derives) = self.consider_suggesting_derives_for_ty(trait_pred, adt) {
3628 derives.extend(new_derives);
3629 } else {
3630 traits.push(trait_pred.def_id());
3631 }
3632 }
3633 traits.sort_by_key(|&id| self.tcx.def_path_str(id));
3634 traits.dedup();
3635
3636 let len = traits.len();
3637 if len > 0 {
3638 let span =
3639 MultiSpan::from_spans(traits.iter().map(|&did| self.tcx.def_span(did)).collect());
3640 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]));
3641 for (i, &did) in traits.iter().enumerate().skip(1) {
3642 if len > 2 {
3643 names.push_str(", ");
3644 }
3645 if i == len - 1 {
3646 names.push_str(" and ");
3647 }
3648 names.push('`');
3649 names.push_str(&self.tcx.def_path_str(did));
3650 names.push('`');
3651 }
3652 err.span_note(
3653 span,
3654 ::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),
3655 );
3656 }
3657
3658 derives
3659 }
3660
3661 pub(crate) fn suggest_derive(
3662 &self,
3663 err: &mut Diag<'_>,
3664 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
3665 ) -> bool {
3666 let mut derives = self.note_predicate_source_and_get_derives(err, unsatisfied_predicates);
3667 derives.sort();
3668 derives.dedup();
3669
3670 let mut derives_grouped = Vec::<(String, Span, String)>::new();
3671 for (self_name, self_span, trait_name) in derives.into_iter() {
3672 if let Some((last_self_name, _, last_trait_names)) = derives_grouped.last_mut() {
3673 if last_self_name == &self_name {
3674 last_trait_names.push_str(::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", trait_name))
})format!(", {trait_name}").as_str());
3675 continue;
3676 }
3677 }
3678 derives_grouped.push((self_name, self_span, trait_name.to_string()));
3679 }
3680
3681 for (self_name, self_span, traits) in &derives_grouped {
3682 err.span_suggestion_verbose(
3683 self_span.shrink_to_lo(),
3684 ::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})]`"),
3685 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n", traits))
})format!("#[derive({traits})]\n"),
3686 Applicability::MaybeIncorrect,
3687 );
3688 }
3689 !derives_grouped.is_empty()
3690 }
3691
3692 fn note_derefed_ty_has_method(
3693 &self,
3694 err: &mut Diag<'_>,
3695 self_source: SelfSource<'tcx>,
3696 rcvr_ty: Ty<'tcx>,
3697 item_name: Ident,
3698 expected: Expectation<'tcx>,
3699 ) {
3700 let SelfSource::QPath(ty) = self_source else {
3701 return;
3702 };
3703 for (deref_ty, _) in self.autoderef(DUMMY_SP, rcvr_ty).silence_errors().skip(1) {
3704 if let Ok(pick) = self.probe_for_name(
3705 Mode::Path,
3706 item_name,
3707 expected.only_has_type(self),
3708 IsSuggestion(true),
3709 deref_ty,
3710 ty.hir_id,
3711 ProbeScope::TraitsInScope,
3712 ) {
3713 if deref_ty.is_suggestable(self.tcx, true)
3714 && pick.item.is_method()
3718 && let Some(self_ty) =
3719 self.tcx.fn_sig(pick.item.def_id).instantiate_identity().skip_norm_wip().inputs().skip_binder().get(0)
3720 && self_ty.is_ref()
3721 {
3722 let suggested_path = match deref_ty.kind() {
3723 ty::Bool
3724 | ty::Char
3725 | ty::Int(_)
3726 | ty::Uint(_)
3727 | ty::Float(_)
3728 | ty::Adt(_, _)
3729 | ty::Str
3730 | ty::Alias(ty::AliasTy {
3731 kind: ty::Projection { .. } | ty::Inherent { .. },
3732 ..
3733 })
3734 | ty::Param(_) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", deref_ty))
})format!("{deref_ty}"),
3735 _ if self
3741 .tcx
3742 .sess
3743 .source_map()
3744 .span_wrapped_by_angle_or_parentheses(ty.span) =>
3745 {
3746 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", deref_ty))
})format!("{deref_ty}")
3747 }
3748 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", deref_ty))
})format!("<{deref_ty}>"),
3749 };
3750 err.span_suggestion_verbose(
3751 ty.span,
3752 ::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}`"),
3753 suggested_path,
3754 Applicability::MaybeIncorrect,
3755 );
3756 } else {
3757 err.span_note(
3758 ty.span,
3759 ::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}`"),
3760 );
3761 }
3762 return;
3763 }
3764 }
3765 }
3766
3767 fn suggest_bounds_for_range_to_method(
3768 &self,
3769 err: &mut Diag<'_>,
3770 source: SelfSource<'tcx>,
3771 item_ident: Ident,
3772 ) {
3773 let SelfSource::MethodCall(rcvr_expr) = source else { return };
3774 let hir::ExprKind::Struct(qpath, fields, _) = rcvr_expr.kind else { return };
3775 let Some(lang_item) = self.tcx.qpath_lang_item(*qpath) else {
3776 return;
3777 };
3778 let is_inclusive = match lang_item {
3779 hir::LangItem::RangeTo => false,
3780 hir::LangItem::RangeToInclusive | hir::LangItem::RangeInclusiveCopy => true,
3781 _ => return,
3782 };
3783
3784 let Some(iterator_trait) = self.tcx.get_diagnostic_item(sym::Iterator) else { return };
3785 let Some(_) = self
3786 .tcx
3787 .associated_items(iterator_trait)
3788 .filter_by_name_unhygienic(item_ident.name)
3789 .next()
3790 else {
3791 return;
3792 };
3793
3794 let source_map = self.tcx.sess.source_map();
3795 let range_type = if is_inclusive { "RangeInclusive" } else { "Range" };
3796 let Some(end_field) = fields.iter().find(|f| f.ident.name == rustc_span::sym::end) else {
3797 return;
3798 };
3799
3800 let element_ty = self.typeck_results.borrow().expr_ty_opt(end_field.expr);
3801 let is_integral = element_ty.is_some_and(|ty| ty.is_integral());
3802 let end_is_negative = is_integral
3803 && #[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, _));
3804
3805 let Ok(snippet) = source_map.span_to_snippet(rcvr_expr.span) else { return };
3806
3807 let offset = snippet
3808 .chars()
3809 .take_while(|&c| c == '(' || c.is_whitespace())
3810 .map(|c| c.len_utf8())
3811 .sum::<usize>();
3812
3813 let insert_span = rcvr_expr
3814 .span
3815 .with_lo(rcvr_expr.span.lo() + rustc_span::BytePos(offset as u32))
3816 .shrink_to_lo();
3817
3818 let (value, appl) = if is_integral && !end_is_negative {
3819 ("0", Applicability::MachineApplicable)
3820 } else {
3821 ("/* start */", Applicability::HasPlaceholders)
3822 };
3823
3824 err.span_suggestion_verbose(
3825 insert_span,
3826 ::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"),
3827 value,
3828 appl,
3829 );
3830 }
3831
3832 fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String {
3834 match ty.kind() {
3835 ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), args),
3836 _ => self.ty_to_string(ty),
3837 }
3838 }
3839
3840 fn suggest_await_before_method(
3841 &self,
3842 err: &mut Diag<'_>,
3843 item_name: Ident,
3844 ty: Ty<'tcx>,
3845 call: &hir::Expr<'_>,
3846 span: Span,
3847 return_type: Option<Ty<'tcx>>,
3848 ) {
3849 let Some(output_ty) = self.err_ctxt().get_impl_future_output_ty(ty) else { return };
3850 let output_ty = self.resolve_vars_if_possible(output_ty);
3851 let method_exists =
3852 self.method_exists_for_diagnostic(item_name, output_ty, call.hir_id, return_type);
3853 {
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:3853",
"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(3853u32),
::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);
3854 if method_exists {
3855 err.span_suggestion_verbose(
3856 span.shrink_to_lo(),
3857 "consider `await`ing on the `Future` and calling the method on its `Output`",
3858 "await.",
3859 Applicability::MaybeIncorrect,
3860 );
3861 }
3862 }
3863
3864 fn set_label_for_method_error(
3865 &self,
3866 err: &mut Diag<'_>,
3867 source: SelfSource<'tcx>,
3868 rcvr_ty: Ty<'tcx>,
3869 item_ident: Ident,
3870 expr_id: hir::HirId,
3871 span: Span,
3872 sugg_span: Span,
3873 within_macro_span: Option<Span>,
3874 args: Option<&'tcx [hir::Expr<'tcx>]>,
3875 ) {
3876 let tcx = self.tcx;
3877 if tcx.sess.source_map().is_multiline(sugg_span) {
3878 err.span_label(sugg_span.with_hi(span.lo()), "");
3879 }
3880 if let Some(within_macro_span) = within_macro_span {
3881 err.span_label(within_macro_span, "due to this macro variable");
3882 }
3883
3884 if #[allow(non_exhaustive_omitted_patterns)] match source {
SelfSource::QPath(_) => true,
_ => false,
}matches!(source, SelfSource::QPath(_)) && args.is_some() {
3885 self.find_builder_fn(err, rcvr_ty, expr_id);
3886 }
3887
3888 if tcx.ty_is_opaque_future(rcvr_ty) && item_ident.name == sym::poll {
3889 let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
3890 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!(
3891 "method `poll` found on `Pin<&mut {ty_str}>`, \
3892 see documentation for `std::pin::Pin`"
3893 ));
3894 err.help(
3895 "self type must be pinned to call `Future::poll`, \
3896 see https://rust-lang.github.io/async-book/part-reference/pinning.html",
3897 );
3898 }
3899
3900 if let Some(span) =
3901 tcx.resolutions(()).confused_type_with_std_module.get(&span.with_parent(None))
3902 {
3903 err.span_suggestion(
3904 span.shrink_to_lo(),
3905 "you are looking for the module in `std`, not the primitive type",
3906 "std::",
3907 Applicability::MachineApplicable,
3908 );
3909 }
3910 }
3911
3912 fn suggest_on_pointer_type(
3913 &self,
3914 err: &mut Diag<'_>,
3915 source: SelfSource<'tcx>,
3916 rcvr_ty: Ty<'tcx>,
3917 item_ident: Ident,
3918 ) {
3919 let tcx = self.tcx;
3920 if let SelfSource::MethodCall(rcvr_expr) = source
3922 && let ty::RawPtr(ty, ptr_mutbl) = *rcvr_ty.kind()
3923 && let Ok(pick) = self.lookup_probe_for_diagnostic(
3924 item_ident,
3925 Ty::new_ref(tcx, ty::Region::new_error_misc(tcx), ty, ptr_mutbl),
3926 self.tcx.hir_expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id)),
3927 ProbeScope::TraitsInScope,
3928 None,
3929 )
3930 && let ty::Ref(_, _, sugg_mutbl) = *pick.self_ty.kind()
3931 && (sugg_mutbl.is_not() || ptr_mutbl.is_mut())
3932 {
3933 let (method, method_anchor) = match sugg_mutbl {
3934 Mutability::Not => {
3935 let method_anchor = match ptr_mutbl {
3936 Mutability::Not => "as_ref",
3937 Mutability::Mut => "as_ref-1",
3938 };
3939 ("as_ref", method_anchor)
3940 }
3941 Mutability::Mut => ("as_mut", "as_mut"),
3942 };
3943 err.span_note(
3944 tcx.def_span(pick.item.def_id),
3945 ::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),
3946 );
3947 let mut_str = ptr_mutbl.ptr_str();
3948 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!(
3949 "you might want to use the unsafe method `<*{mut_str} T>::{method}` to get \
3950 an optional reference to the value behind the pointer"
3951 ));
3952 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!(
3953 "read the documentation for `<*{mut_str} T>::{method}` and ensure you satisfy its \
3954 safety preconditions before calling it to avoid undefined behavior: \
3955 https://doc.rust-lang.org/std/primitive.pointer.html#method.{method_anchor}"
3956 ));
3957 }
3958 }
3959
3960 fn suggest_use_candidates<F>(&self, candidates: Vec<DefId>, handle_candidates: F)
3961 where
3962 F: FnOnce(Vec<String>, Vec<String>, Span),
3963 {
3964 let parent_map = self.tcx.visible_parent_map(());
3965
3966 let scope = self.tcx.parent_module_from_def_id(self.body_id);
3967 let (accessible_candidates, inaccessible_candidates): (Vec<_>, Vec<_>) =
3968 candidates.into_iter().partition(|id| {
3969 let vis = self.tcx.visibility(*id);
3970 vis.is_accessible_from(scope, self.tcx)
3971 });
3972
3973 let sugg = |candidates: Vec<_>, visible| {
3974 let (candidates, globs): (Vec<_>, Vec<_>) =
3977 candidates.into_iter().partition(|trait_did| {
3978 if let Some(parent_did) = parent_map.get(trait_did) {
3979 if *parent_did != self.tcx.parent(*trait_did)
3981 && self
3982 .tcx
3983 .module_children(*parent_did)
3984 .iter()
3985 .filter(|child| child.res.opt_def_id() == Some(*trait_did))
3986 .all(|child| child.ident.name == kw::Underscore)
3987 {
3988 return false;
3989 }
3990 }
3991
3992 true
3993 });
3994
3995 let prefix = if visible { "use " } else { "" };
3996 let postfix = if visible { ";" } else { "" };
3997 let path_strings = candidates.iter().map(|trait_did| {
3998 ::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!(
3999 "{prefix}{}{postfix}\n",
4000 with_no_visible_paths_if_doc_hidden!(with_crate_prefix!(
4001 self.tcx.def_path_str(*trait_did)
4002 )),
4003 )
4004 });
4005
4006 let glob_path_strings = globs.iter().map(|trait_did| {
4007 let parent_did = parent_map.get(trait_did).unwrap();
4008 ::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!(
4009 "{prefix}{}::*{postfix} // trait {}\n",
4010 with_no_visible_paths_if_doc_hidden!(with_crate_prefix!(
4011 self.tcx.def_path_str(*parent_did)
4012 )),
4013 self.tcx.item_name(*trait_did),
4014 )
4015 });
4016 let mut sugg: Vec<_> = path_strings.chain(glob_path_strings).collect();
4017 sugg.sort();
4018 sugg
4019 };
4020
4021 let accessible_sugg = sugg(accessible_candidates, true);
4022 let inaccessible_sugg = sugg(inaccessible_candidates, false);
4023
4024 let (module, _, _) = self.tcx.hir_get_module(scope);
4025 let span = module.spans.inject_use_span;
4026 handle_candidates(accessible_sugg, inaccessible_sugg, span);
4027 }
4028
4029 fn suggest_valid_traits(
4030 &self,
4031 err: &mut Diag<'_>,
4032 item_name: Ident,
4033 mut valid_out_of_scope_traits: Vec<DefId>,
4034 explain: bool,
4035 ) -> bool {
4036 valid_out_of_scope_traits.retain(|id| self.tcx.is_user_visible_dep(id.krate));
4037 if !valid_out_of_scope_traits.is_empty() {
4038 let mut candidates = valid_out_of_scope_traits;
4039 candidates.sort_by_key(|&id| self.tcx.def_path_str(id));
4040 candidates.dedup();
4041
4042 let edition_fix = candidates
4044 .iter()
4045 .find(|did| self.tcx.is_diagnostic_item(sym::TryInto, **did))
4046 .copied();
4047
4048 if explain {
4049 err.help("items from traits can only be used if the trait is in scope");
4050 }
4051
4052 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!(
4053 "{this_trait_is} implemented but not in scope",
4054 this_trait_is = if candidates.len() == 1 {
4055 format!(
4056 "trait `{}` which provides `{item_name}` is",
4057 self.tcx.item_name(candidates[0]),
4058 )
4059 } else {
4060 format!("the following traits which provide `{item_name}` are")
4061 }
4062 );
4063
4064 self.suggest_use_candidates(candidates, |accessible_sugg, inaccessible_sugg, span| {
4065 let suggest_for_access = |err: &mut Diag<'_>, mut msg: String, suggs: Vec<_>| {
4066 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!(
4067 "; perhaps you want to import {one_of}",
4068 one_of = if suggs.len() == 1 { "it" } else { "one of them" },
4069 );
4070 err.span_suggestions(span, msg, suggs, Applicability::MaybeIncorrect);
4071 };
4072 let suggest_for_privacy = |err: &mut Diag<'_>, suggs: Vec<String>| {
4073 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!(
4074 "{this_trait_is} implemented but not reachable",
4075 this_trait_is = if let [sugg] = suggs.as_slice() {
4076 format!("trait `{}` which provides `{item_name}` is", sugg.trim())
4077 } else {
4078 format!("the following traits which provide `{item_name}` are")
4079 }
4080 );
4081 if suggs.len() == 1 {
4082 err.help(msg);
4083 } else {
4084 err.span_suggestions(span, msg, suggs, Applicability::MaybeIncorrect);
4085 }
4086 };
4087 if accessible_sugg.is_empty() {
4088 suggest_for_privacy(err, inaccessible_sugg);
4090 } else if inaccessible_sugg.is_empty() {
4091 suggest_for_access(err, msg, accessible_sugg);
4092 } else {
4093 suggest_for_access(err, msg, accessible_sugg);
4094 suggest_for_privacy(err, inaccessible_sugg);
4095 }
4096 });
4097
4098 if let Some(did) = edition_fix {
4099 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!(
4100 "'{}' is included in the prelude starting in Edition 2021",
4101 with_crate_prefix!(self.tcx.def_path_str(did))
4102 ));
4103 }
4104
4105 true
4106 } else {
4107 false
4108 }
4109 }
4110
4111 fn suggest_traits_to_import(
4112 &self,
4113 err: &mut Diag<'_>,
4114 span: Span,
4115 rcvr_ty: Ty<'tcx>,
4116 item_name: Ident,
4117 inputs_len: Option<usize>,
4118 source: SelfSource<'tcx>,
4119 valid_out_of_scope_traits: Vec<DefId>,
4120 static_candidates: &[CandidateSource],
4121 unsatisfied_bounds: bool,
4122 return_type: Option<Ty<'tcx>>,
4123 trait_missing_method: bool,
4124 ) {
4125 let mut alt_rcvr_sugg = false;
4126 let mut trait_in_other_version_found = false;
4127 if let (SelfSource::MethodCall(rcvr), false) = (source, unsatisfied_bounds) {
4128 {
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:4128",
"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(4128u32),
::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!(
4129 "suggest_traits_to_import: span={:?}, item_name={:?}, rcvr_ty={:?}, rcvr={:?}",
4130 span, item_name, rcvr_ty, rcvr
4131 );
4132 let skippable = [
4133 self.tcx.lang_items().clone_trait(),
4134 self.tcx.lang_items().deref_trait(),
4135 self.tcx.lang_items().deref_mut_trait(),
4136 self.tcx.lang_items().drop_trait(),
4137 self.tcx.get_diagnostic_item(sym::AsRef),
4138 ];
4139 for (rcvr_ty, post, pin_call) in &[
4143 (rcvr_ty, "", None),
4144 (
4145 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty),
4146 "&mut ",
4147 Some("as_mut"),
4148 ),
4149 (
4150 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty),
4151 "&",
4152 Some("as_ref"),
4153 ),
4154 ] {
4155 match self.lookup_probe_for_diagnostic(
4156 item_name,
4157 *rcvr_ty,
4158 rcvr,
4159 ProbeScope::AllTraits,
4160 return_type,
4161 ) {
4162 Ok(pick) => {
4163 let did = Some(pick.item.container_id(self.tcx));
4168 if skippable.contains(&did) {
4169 continue;
4170 }
4171 trait_in_other_version_found = self
4172 .detect_and_explain_multiple_crate_versions_of_trait_item(
4173 err,
4174 pick.item.def_id,
4175 rcvr.hir_id,
4176 Some(*rcvr_ty),
4177 );
4178 if pick.autoderefs == 0 && !trait_in_other_version_found {
4179 err.span_label(
4180 pick.item.ident(self.tcx).span,
4181 ::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"),
4182 );
4183 }
4184 break;
4185 }
4186 Err(MethodError::Ambiguity(_)) => {
4187 break;
4192 }
4193 Err(_) => (),
4194 }
4195
4196 let Some(unpin_trait) = self.tcx.lang_items().unpin_trait() else {
4197 return;
4198 };
4199 let pred = ty::TraitRef::new(self.tcx, unpin_trait, [*rcvr_ty]);
4200 let unpin = self.predicate_must_hold_considering_regions(&Obligation::new(
4201 self.tcx,
4202 self.misc(rcvr.span),
4203 self.param_env,
4204 pred,
4205 ));
4206 for (rcvr_ty, pre) in &[
4207 (Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::OwnedBox), "Box::new"),
4208 (Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::Pin), "Pin::new"),
4209 (Ty::new_diagnostic_item(self.tcx, *rcvr_ty, sym::Arc), "Arc::new"),
4210 (Ty::new_diagnostic_item(self.tcx, *rcvr_ty, sym::Rc), "Rc::new"),
4211 ] {
4212 if let Some(new_rcvr_t) = *rcvr_ty
4213 && let Ok(pick) = self.lookup_probe_for_diagnostic(
4214 item_name,
4215 new_rcvr_t,
4216 rcvr,
4217 ProbeScope::AllTraits,
4218 return_type,
4219 )
4220 {
4221 {
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:4221",
"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(4221u32),
::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);
4222 let did = pick.item.trait_container(self.tcx);
4223 let skip = skippable.contains(&did)
4229 || (("Pin::new" == *pre)
4230 && ((sym::as_ref == item_name.name) || !unpin))
4231 || inputs_len.is_some_and(|inputs_len| {
4232 pick.item.is_fn()
4233 && self
4234 .tcx
4235 .fn_sig(pick.item.def_id)
4236 .skip_binder()
4237 .skip_binder()
4238 .inputs()
4239 .len()
4240 != inputs_len
4241 });
4242 if pick.autoderefs == 0 && !skip {
4246 err.span_label(
4247 pick.item.ident(self.tcx).span,
4248 ::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"),
4249 );
4250 err.multipart_suggestion(
4251 "consider wrapping the receiver expression with the \
4252 appropriate type",
4253 ::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![
4254 (rcvr.span.shrink_to_lo(), format!("{pre}({post}")),
4255 (rcvr.span.shrink_to_hi(), ")".to_string()),
4256 ],
4257 Applicability::MaybeIncorrect,
4258 );
4259 alt_rcvr_sugg = true;
4261 }
4262 }
4263 }
4264 if let Some(new_rcvr_t) = Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::Pin)
4267 && !alt_rcvr_sugg
4269 && !unpin
4271 && let Some(pin_call) = pin_call
4273 && let Ok(pick) = self.lookup_probe_for_diagnostic(
4275 item_name,
4276 new_rcvr_t,
4277 rcvr,
4278 ProbeScope::AllTraits,
4279 return_type,
4280 )
4281 && !skippable.contains(&Some(pick.item.container_id(self.tcx)))
4284 && pick.item.impl_container(self.tcx).is_none_or(|did| {
4286 match self.tcx.type_of(did).skip_binder().kind() {
4287 ty::Adt(def, _) => Some(def.did()) != self.tcx.lang_items().pin_type(),
4288 _ => true,
4289 }
4290 })
4291 && pick.autoderefs == 0
4293 && 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)
4296 {
4297 let indent = self
4298 .tcx
4299 .sess
4300 .source_map()
4301 .indentation_before(rcvr.span)
4302 .unwrap_or_else(|| " ".to_string());
4303 let mut expr = rcvr;
4304 while let Node::Expr(call_expr) = self.tcx.parent_hir_node(expr.hir_id)
4305 && let hir::ExprKind::MethodCall(hir::PathSegment { .. }, ..) =
4306 call_expr.kind
4307 {
4308 expr = call_expr;
4309 }
4310 match self.tcx.parent_hir_node(expr.hir_id) {
4311 Node::LetStmt(stmt)
4312 if let Some(init) = stmt.init
4313 && let Ok(code) =
4314 self.tcx.sess.source_map().span_to_snippet(rcvr.span) =>
4315 {
4316 err.multipart_suggestion(
4319 "consider pinning the expression",
4320 ::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![
4321 (
4322 stmt.span.shrink_to_lo(),
4323 format!(
4324 "let mut pinned = std::pin::pin!({code});\n{indent}"
4325 ),
4326 ),
4327 (
4328 init.span.until(rcvr.span.shrink_to_hi()),
4329 format!("pinned.{pin_call}()"),
4330 ),
4331 ],
4332 Applicability::MaybeIncorrect,
4333 );
4334 }
4335 Node::Block(_) | Node::Stmt(_) => {
4336 err.multipart_suggestion(
4339 "consider pinning the expression",
4340 ::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![
4341 (
4342 rcvr.span.shrink_to_lo(),
4343 "let mut pinned = std::pin::pin!(".to_string(),
4344 ),
4345 (
4346 rcvr.span.shrink_to_hi(),
4347 format!(");\n{indent}pinned.{pin_call}()"),
4348 ),
4349 ],
4350 Applicability::MaybeIncorrect,
4351 );
4352 }
4353 _ => {
4354 err.span_help(
4357 rcvr.span,
4358 "consider pinning the expression with `std::pin::pin!()` and \
4359 assigning that to a new binding",
4360 );
4361 }
4362 }
4363 alt_rcvr_sugg = true;
4365 }
4366 }
4367 }
4368
4369 if let SelfSource::QPath(ty) = source
4370 && !valid_out_of_scope_traits.is_empty()
4371 && let hir::TyKind::Path(path) = ty.kind
4372 && let hir::QPath::Resolved(..) = path
4373 && let Some(assoc) = self
4374 .tcx
4375 .associated_items(valid_out_of_scope_traits[0])
4376 .filter_by_name_unhygienic(item_name.name)
4377 .next()
4378 {
4379 let rcvr_ty = self.node_ty_opt(ty.hir_id);
4384 trait_in_other_version_found = self
4385 .detect_and_explain_multiple_crate_versions_of_trait_item(
4386 err,
4387 assoc.def_id,
4388 ty.hir_id,
4389 rcvr_ty,
4390 );
4391 }
4392 if !trait_in_other_version_found
4393 && self.suggest_valid_traits(err, item_name, valid_out_of_scope_traits, true)
4394 {
4395 return;
4396 }
4397
4398 let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
4399
4400 let mut arbitrary_rcvr = ::alloc::vec::Vec::new()vec![];
4401 let mut candidates = all_traits(self.tcx)
4405 .into_iter()
4406 .filter(|info| match self.tcx.lookup_stability(info.def_id) {
4409 Some(attr) => attr.level.is_stable(),
4410 None => true,
4411 })
4412 .filter(|info| {
4413 static_candidates.iter().all(|sc| match *sc {
4416 CandidateSource::Trait(def_id) => def_id != info.def_id,
4417 CandidateSource::Impl(def_id) => {
4418 self.tcx.impl_opt_trait_id(def_id) != Some(info.def_id)
4419 }
4420 })
4421 })
4422 .filter(|info| {
4423 (type_is_local || info.def_id.is_local())
4430 && !self.tcx.trait_is_auto(info.def_id)
4431 && self
4432 .associated_value(info.def_id, item_name)
4433 .filter(|item| {
4434 if item.is_fn() {
4435 let id = item
4436 .def_id
4437 .as_local()
4438 .map(|def_id| self.tcx.hir_node_by_def_id(def_id));
4439 if let Some(hir::Node::TraitItem(hir::TraitItem {
4440 kind: hir::TraitItemKind::Fn(fn_sig, method),
4441 ..
4442 })) = id
4443 {
4444 let self_first_arg = match method {
4445 hir::TraitFn::Required([ident, ..]) => {
4446 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
4447 }
4448 hir::TraitFn::Provided(body_id) => {
4449 self.tcx.hir_body(*body_id).params.first().is_some_and(
4450 |param| {
4451 #[allow(non_exhaustive_omitted_patterns)] match param.pat.kind {
hir::PatKind::Binding(_, _, ident, _) if ident.name == kw::SelfLower =>
true,
_ => false,
}matches!(
4452 param.pat.kind,
4453 hir::PatKind::Binding(_, _, ident, _)
4454 if ident.name == kw::SelfLower
4455 )
4456 },
4457 )
4458 }
4459 _ => false,
4460 };
4461
4462 if !fn_sig.decl.implicit_self().has_implicit_self()
4463 && self_first_arg
4464 {
4465 if let Some(ty) = fn_sig.decl.inputs.get(0) {
4466 arbitrary_rcvr.push(ty.span);
4467 }
4468 return false;
4469 }
4470 }
4471 }
4472 item.visibility(self.tcx).is_public() || info.def_id.is_local()
4474 })
4475 .is_some()
4476 })
4477 .collect::<Vec<_>>();
4478 for span in &arbitrary_rcvr {
4479 err.span_label(
4480 *span,
4481 "the method might not be found because of this arbitrary self type",
4482 );
4483 }
4484 if alt_rcvr_sugg {
4485 return;
4486 }
4487
4488 if !candidates.is_empty() {
4489 candidates
4491 .sort_by_key(|&info| (!info.def_id.is_local(), self.tcx.def_path_str(info.def_id)));
4492 candidates.dedup();
4493
4494 let param_type = match *rcvr_ty.kind() {
4495 ty::Param(param) => Some(param),
4496 ty::Ref(_, ty, _) => match *ty.kind() {
4497 ty::Param(param) => Some(param),
4498 _ => None,
4499 },
4500 _ => None,
4501 };
4502 if !trait_missing_method {
4503 err.help(if param_type.is_some() {
4504 "items from traits can only be used if the type parameter is bounded by the trait"
4505 } else {
4506 "items from traits can only be used if the trait is implemented and in scope"
4507 });
4508 }
4509
4510 let candidates_len = candidates.len();
4511 let message = |action| {
4512 ::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!(
4513 "the following {traits_define} an item `{name}`, perhaps you need to {action} \
4514 {one_of_them}:",
4515 traits_define =
4516 if candidates_len == 1 { "trait defines" } else { "traits define" },
4517 action = action,
4518 one_of_them = if candidates_len == 1 { "it" } else { "one of them" },
4519 name = item_name,
4520 )
4521 };
4522 if let Some(param) = param_type {
4524 let generics = self.tcx.generics_of(self.body_id.to_def_id());
4525 let type_param = generics.type_param(param, self.tcx);
4526 let tcx = self.tcx;
4527 if let Some(def_id) = type_param.def_id.as_local() {
4528 let id = tcx.local_def_id_to_hir_id(def_id);
4529 match tcx.hir_node(id) {
4533 Node::GenericParam(param) => {
4534 enum Introducer {
4535 Plus,
4536 Colon,
4537 Nothing,
4538 }
4539 let hir_generics = tcx.hir_get_generics(id.owner.def_id).unwrap();
4540 let trait_def_ids: DefIdSet = hir_generics
4541 .bounds_for_param(def_id)
4542 .flat_map(|bp| bp.bounds.iter())
4543 .filter_map(|bound| bound.trait_ref()?.trait_def_id())
4544 .collect();
4545 if candidates.iter().any(|t| trait_def_ids.contains(&t.def_id)) {
4546 return;
4547 }
4548 let msg = message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("restrict type parameter `{0}` with",
param.name.ident()))
})format!(
4549 "restrict type parameter `{}` with",
4550 param.name.ident(),
4551 ));
4552 let bounds_span = hir_generics.bounds_span_for_suggestions(def_id);
4553 let mut applicability = Applicability::MaybeIncorrect;
4554 let candidate_strs: Vec<_> = candidates
4557 .iter()
4558 .map(|cand| {
4559 let cand_path = tcx.def_path_str(cand.def_id);
4560 let cand_params = &tcx.generics_of(cand.def_id).own_params;
4561 let cand_args: String = cand_params
4562 .iter()
4563 .skip(1)
4564 .filter_map(|param| match param.kind {
4565 ty::GenericParamDefKind::Type {
4566 has_default: true,
4567 ..
4568 }
4569 | ty::GenericParamDefKind::Const {
4570 has_default: true,
4571 ..
4572 } => None,
4573 _ => Some(param.name.as_str()),
4574 })
4575 .intersperse(", ")
4576 .collect();
4577 if cand_args.is_empty() {
4578 cand_path
4579 } else {
4580 applicability = Applicability::HasPlaceholders;
4581 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}</* {1} */>", cand_path,
cand_args))
})format!("{cand_path}</* {cand_args} */>")
4582 }
4583 })
4584 .collect();
4585
4586 if rcvr_ty.is_ref()
4587 && param.is_impl_trait()
4588 && let Some((bounds_span, _)) = bounds_span
4589 {
4590 err.multipart_suggestions(
4591 msg,
4592 candidate_strs.iter().map(|cand| {
4593 ::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![
4594 (param.span.shrink_to_lo(), "(".to_string()),
4595 (bounds_span, format!(" + {cand})")),
4596 ]
4597 }),
4598 applicability,
4599 );
4600 return;
4601 }
4602
4603 let (sp, introducer, open_paren_sp) =
4604 if let Some((span, open_paren_sp)) = bounds_span {
4605 (span, Introducer::Plus, open_paren_sp)
4606 } else if let Some(colon_span) = param.colon_span {
4607 (colon_span.shrink_to_hi(), Introducer::Nothing, None)
4608 } else if param.is_impl_trait() {
4609 (param.span.shrink_to_hi(), Introducer::Plus, None)
4610 } else {
4611 (param.span.shrink_to_hi(), Introducer::Colon, None)
4612 };
4613
4614 let all_suggs = candidate_strs.iter().map(|cand| {
4615 let suggestion = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}",
match introducer {
Introducer::Plus => " +",
Introducer::Colon => ":",
Introducer::Nothing => "",
}, cand))
})format!(
4616 "{} {cand}",
4617 match introducer {
4618 Introducer::Plus => " +",
4619 Introducer::Colon => ":",
4620 Introducer::Nothing => "",
4621 },
4622 );
4623
4624 let mut suggs = ::alloc::vec::Vec::new()vec![];
4625
4626 if let Some(open_paren_sp) = open_paren_sp {
4627 suggs.push((open_paren_sp, "(".to_string()));
4628 suggs.push((sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("){0}", suggestion))
})format!("){suggestion}")));
4629 } else {
4630 suggs.push((sp, suggestion));
4631 }
4632
4633 suggs
4634 });
4635
4636 err.multipart_suggestions(msg, all_suggs, applicability);
4637
4638 return;
4639 }
4640 Node::Item(hir::Item {
4641 kind: hir::ItemKind::Trait { ident, bounds, .. },
4642 ..
4643 }) => {
4644 let (sp, sep, article) = if bounds.is_empty() {
4645 (ident.span.shrink_to_hi(), ":", "a")
4646 } else {
4647 (bounds.last().unwrap().span().shrink_to_hi(), " +", "another")
4648 };
4649 err.span_suggestions(
4650 sp,
4651 message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add {0} supertrait for", article))
})format!("add {article} supertrait for")),
4652 candidates
4653 .iter()
4654 .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),)),
4655 Applicability::MaybeIncorrect,
4656 );
4657 return;
4658 }
4659 _ => {}
4660 }
4661 }
4662 }
4663
4664 let (potential_candidates, explicitly_negative) = if param_type.is_some() {
4665 (candidates, Vec::new())
4668 } else if let Some(simp_rcvr_ty) =
4669 simplify_type(self.tcx, rcvr_ty, TreatParams::AsRigid)
4670 {
4671 let mut potential_candidates = Vec::new();
4672 let mut explicitly_negative = Vec::new();
4673 for candidate in candidates {
4674 if self
4676 .tcx
4677 .all_impls(candidate.def_id)
4678 .map(|imp_did| self.tcx.impl_trait_header(imp_did))
4679 .filter(|header| header.polarity != ty::ImplPolarity::Positive)
4680 .any(|header| {
4681 let imp = header.trait_ref.instantiate_identity().skip_norm_wip();
4682 let imp_simp =
4683 simplify_type(self.tcx, imp.self_ty(), TreatParams::AsRigid);
4684 imp_simp.is_some_and(|s| s == simp_rcvr_ty)
4685 })
4686 {
4687 explicitly_negative.push(candidate);
4688 } else {
4689 potential_candidates.push(candidate);
4690 }
4691 }
4692 (potential_candidates, explicitly_negative)
4693 } else {
4694 (candidates, Vec::new())
4696 };
4697
4698 let impls_trait = |def_id: DefId| {
4699 let args = ty::GenericArgs::for_item(self.tcx, def_id, |param, _| {
4700 if param.index == 0 {
4701 rcvr_ty.into()
4702 } else {
4703 self.infcx.var_for_def(span, param)
4704 }
4705 });
4706 self.infcx
4707 .type_implements_trait(def_id, args, self.param_env)
4708 .must_apply_modulo_regions()
4709 && param_type.is_none()
4710 };
4711 match &potential_candidates[..] {
4712 [] => {}
4713 [trait_info] if trait_info.def_id.is_local() => {
4714 if impls_trait(trait_info.def_id) {
4715 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);
4716 } else {
4717 err.subdiagnostic(CandidateTraitNote {
4718 span: self.tcx.def_span(trait_info.def_id),
4719 trait_name: self.tcx.def_path_str(trait_info.def_id),
4720 item_name,
4721 action_or_ty: if trait_missing_method {
4722 "NONE".to_string()
4723 } else {
4724 param_type.map_or_else(
4725 || "implement".to_string(), |p| p.to_string(),
4727 )
4728 },
4729 });
4730 }
4731 }
4732 trait_infos => {
4733 let mut msg = message(param_type.map_or_else(
4734 || "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"),
4736 ));
4737 for (i, trait_info) in trait_infos.iter().enumerate() {
4738 if impls_trait(trait_info.def_id) {
4739 self.suggest_valid_traits(
4740 err,
4741 item_name,
4742 ::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],
4743 false,
4744 );
4745 }
4746 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!(
4747 "\ncandidate #{}: `{}`",
4748 i + 1,
4749 self.tcx.def_path_str(trait_info.def_id),
4750 ));
4751 }
4752 err.note(msg);
4753 }
4754 }
4755 match &explicitly_negative[..] {
4756 [] => {}
4757 [trait_info] => {
4758 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!(
4759 "the trait `{}` defines an item `{}`, but is explicitly unimplemented",
4760 self.tcx.def_path_str(trait_info.def_id),
4761 item_name
4762 );
4763 err.note(msg);
4764 }
4765 trait_infos => {
4766 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!(
4767 "the following traits define an item `{item_name}`, but are explicitly unimplemented:"
4768 );
4769 for trait_info in trait_infos {
4770 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)));
4771 }
4772 err.note(msg);
4773 }
4774 }
4775 }
4776 }
4777
4778 fn detect_and_explain_multiple_crate_versions_of_trait_item(
4779 &self,
4780 err: &mut Diag<'_>,
4781 item_def_id: DefId,
4782 hir_id: hir::HirId,
4783 rcvr_ty: Option<Ty<'tcx>>,
4784 ) -> bool {
4785 let hir_id = self.tcx.parent_hir_id(hir_id);
4786 let Some(traits) = self.tcx.in_scope_traits(hir_id) else { return false };
4787 if traits.is_empty() {
4788 return false;
4789 }
4790 let trait_def_id = self.tcx.parent(item_def_id);
4791 if !self.tcx.is_trait(trait_def_id) {
4792 return false;
4793 }
4794 let hir::Node::Expr(rcvr) = self.tcx.hir_node(hir_id) else {
4795 return false;
4796 };
4797 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, rcvr_ty.into_iter());
4798 let trait_pred = ty::Binder::dummy(ty::TraitPredicate {
4799 trait_ref,
4800 polarity: ty::PredicatePolarity::Positive,
4801 });
4802 let obligation = Obligation::new(self.tcx, self.misc(rcvr.span), self.param_env, trait_ref);
4803 self.err_ctxt().note_different_trait_with_same_name(err, &obligation, trait_pred)
4804 }
4805
4806 pub(crate) fn suggest_else_fn_with_closure(
4809 &self,
4810 err: &mut Diag<'_>,
4811 expr: &hir::Expr<'_>,
4812 found: Ty<'tcx>,
4813 expected: Ty<'tcx>,
4814 ) -> bool {
4815 let Some((_def_id_or_name, output, _inputs)) = self.extract_callable_info(found) else {
4816 return false;
4817 };
4818
4819 if !self.may_coerce(output, expected) {
4820 return false;
4821 }
4822
4823 if let Node::Expr(call_expr) = self.tcx.parent_hir_node(expr.hir_id)
4824 && let hir::ExprKind::MethodCall(
4825 hir::PathSegment { ident: method_name, .. },
4826 self_expr,
4827 args,
4828 ..,
4829 ) = call_expr.kind
4830 && let Some(self_ty) = self.typeck_results.borrow().expr_ty_opt(self_expr)
4831 {
4832 let new_name = Ident {
4833 name: Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_else", method_name.as_str()))
})format!("{}_else", method_name.as_str())),
4834 span: method_name.span,
4835 };
4836 let probe = self.lookup_probe_for_diagnostic(
4837 new_name,
4838 self_ty,
4839 self_expr,
4840 ProbeScope::TraitsInScope,
4841 Some(expected),
4842 );
4843
4844 if let Ok(pick) = probe
4846 && let fn_sig = self.tcx.fn_sig(pick.item.def_id)
4847 && let fn_args = fn_sig.skip_binder().skip_binder().inputs()
4848 && fn_args.len() == args.len() + 1
4849 {
4850 err.span_suggestion_verbose(
4851 method_name.span.shrink_to_hi(),
4852 ::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()),
4853 "_else",
4854 Applicability::MaybeIncorrect,
4855 );
4856 return true;
4857 }
4858 }
4859 false
4860 }
4861
4862 fn type_derefs_to_local(
4865 &self,
4866 span: Span,
4867 rcvr_ty: Ty<'tcx>,
4868 source: SelfSource<'tcx>,
4869 ) -> bool {
4870 fn is_local(ty: Ty<'_>) -> bool {
4871 match ty.kind() {
4872 ty::Adt(def, _) => def.did().is_local(),
4873 ty::Foreign(did) => did.is_local(),
4874 ty::Dynamic(tr, ..) => tr.principal().is_some_and(|d| d.def_id().is_local()),
4875 ty::Param(_) => true,
4876
4877 _ => false,
4882 }
4883 }
4884
4885 if let SelfSource::QPath(_) = source {
4888 return is_local(rcvr_ty);
4889 }
4890
4891 self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
4892 }
4893
4894 fn suggest_hashmap_on_unsatisfied_hashset_buildhasher(
4895 &self,
4896 err: &mut Diag<'_>,
4897 pred: &ty::TraitPredicate<'_>,
4898 adt: ty::AdtDef<'_>,
4899 ) -> bool {
4900 if self.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4901 && self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4902 {
4903 err.help("you might have intended to use a HashMap instead");
4904 true
4905 } else {
4906 false
4907 }
4908 }
4909}
4910
4911#[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)]
4912enum SelfSource<'a> {
4913 QPath(&'a hir::Ty<'a>),
4914 MethodCall(&'a hir::Expr<'a> ),
4915}
4916
4917#[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)]
4918pub(crate) struct TraitInfo {
4919 pub def_id: DefId,
4920}
4921
4922pub(crate) fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
4925 tcx.all_traits_including_private().map(|def_id| TraitInfo { def_id }).collect()
4926}
4927
4928fn print_disambiguation_help<'tcx>(
4929 tcx: TyCtxt<'tcx>,
4930 err: &mut Diag<'_>,
4931 source: SelfSource<'tcx>,
4932 args: Option<&'tcx [hir::Expr<'tcx>]>,
4933 trait_ref: ty::TraitRef<'tcx>,
4934 candidate_idx: Option<usize>,
4935 span: Span,
4936 item: ty::AssocItem,
4937) -> Option<String> {
4938 let trait_impl_type = trait_ref.self_ty().peel_refs();
4939 let trait_ref = if item.is_method() {
4940 trait_ref.print_only_trait_name().to_string()
4941 } else {
4942 ::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())
4943 };
4944 Some(
4945 if item.is_fn()
4946 && let SelfSource::MethodCall(receiver) = source
4947 && let Some(args) = args
4948 {
4949 let def_kind_descr = tcx.def_kind_descr(item.as_def_kind(), item.def_id);
4950 let item_name = item.ident(tcx);
4951 let first_input =
4952 tcx.fn_sig(item.def_id).instantiate_identity().skip_binder().inputs().get(0);
4953 let (first_arg_type, rcvr_ref) = (
4954 first_input.map(|first| first.peel_refs()),
4955 first_input
4956 .and_then(|ty| ty.ref_mutability())
4957 .map_or("", |mutbl| mutbl.ref_prefix_str()),
4958 );
4959
4960 let args = if let Some(first_arg_type) = first_arg_type
4962 && (first_arg_type == tcx.types.self_param
4963 || first_arg_type == trait_impl_type
4964 || item.is_method())
4965 {
4966 Some(receiver)
4967 } else {
4968 None
4969 }
4970 .into_iter()
4971 .chain(args)
4972 .map(|arg| {
4973 tcx.sess.source_map().span_to_snippet(arg.span).unwrap_or_else(|_| "_".to_owned())
4974 })
4975 .collect::<Vec<_>>()
4976 .join(", ");
4977
4978 let args = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}{1})", rcvr_ref, args))
})format!("({}{})", rcvr_ref, args);
4979 err.span_suggestion_verbose(
4980 span,
4981 ::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!(
4982 "disambiguate the {def_kind_descr} for {}",
4983 if let Some(candidate) = candidate_idx {
4984 format!("candidate #{candidate}")
4985 } else {
4986 "the candidate".to_string()
4987 },
4988 ),
4989 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}{2}", trait_ref, item_name,
args))
})format!("{trait_ref}::{item_name}{args}"),
4990 Applicability::HasPlaceholders,
4991 );
4992 return None;
4993 } else {
4994 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::", trait_ref))
})format!("{trait_ref}::")
4995 },
4996 )
4997}