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::diagnostics::{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 #[allow(non_exhaustive_omitted_patterns)] match item_ident.name.as_str() {
"cloned" | "copied" => true,
_ => false,
}matches!(item_ident.name.as_str(), "cloned" | "copied")
921 && let ty::Adt(adt_def, args) = rcvr_ty.kind()
922 && tcx.is_diagnostic_item(sym::Option, adt_def.did())
923 && let inner_ty = args.type_at(0)
924 && !#[allow(non_exhaustive_omitted_patterns)] match inner_ty.kind() {
ty::Ref(..) | ty::Param(_) | ty::Infer(_) => true,
_ => false,
}matches!(inner_ty.kind(), ty::Ref(..) | ty::Param(_) | ty::Infer(_))
927 {
928 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this method is only available on `Option<&_>`"))
})format!("this method is only available on `Option<&_>`"));
932 if let SelfSource::MethodCall(rcvr_expr) = source
933 && !span.in_external_macro(tcx.sess.source_map())
934 {
935 let call_expr = self.tcx.hir_expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id));
936 err.span_suggestion(
937 rcvr_expr.span.shrink_to_hi().to(call_expr.span.shrink_to_hi()),
938 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing the `.{0}()` call",
item_ident.name))
})format!("consider removing the `.{}()` call", item_ident.name),
939 "",
940 Applicability::MaybeIncorrect,
941 );
942 }
943 return Err(());
944 } else if self.impl_into_iterator_should_be_iterator(rcvr_ty, span, unsatisfied_predicates)
945 {
946 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"));
947 if !span.in_external_macro(self.tcx.sess.source_map())
948 && let Some(method_name) = self.preferred_iterator_method(source, rcvr_ty)
949 {
950 err.multipart_suggestion(
951 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("call `.{0}()` first", method_name))
})format!("call `.{method_name}()` first"),
952 ::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}()."))],
953 Applicability::MaybeIncorrect,
954 );
955 }
956 return Err(());
958 } else if !unsatisfied_predicates.is_empty() {
959 if #[allow(non_exhaustive_omitted_patterns)] match rcvr_ty.kind() {
ty::Param(_) => true,
_ => false,
}matches!(rcvr_ty.kind(), ty::Param(_)) {
960 } else {
971 self.handle_unsatisfied_predicates(
972 err,
973 rcvr_ty,
974 item_ident,
975 item_kind,
976 span,
977 unsatisfied_predicates,
978 &mut restrict_type_params,
979 &mut suggested_derive,
980 &mut unsatisfied_bounds,
981 &mut custom_span_label,
982 &mut bound_spans,
983 );
984 }
985 } else if let ty::Adt(def, targs) = rcvr_ty.kind()
986 && let SelfSource::MethodCall(rcvr_expr) = source
987 {
988 if targs.len() == 1 {
992 let mut item_segment = hir::PathSegment::invalid();
993 item_segment.ident = item_ident;
994 for t in [Ty::new_mut_ref, Ty::new_imm_ref, |_, _, t| t] {
995 let new_args =
996 tcx.mk_args_from_iter(targs.iter().map(|arg| match arg.as_type() {
997 Some(ty) => ty::GenericArg::from(t(
998 tcx,
999 tcx.lifetimes.re_erased,
1000 ty.peel_refs(),
1001 )),
1002 _ => arg,
1003 }));
1004 let rcvr_ty = Ty::new_adt(tcx, *def, new_args);
1005 if let Ok(method) = self.lookup_method_for_diagnostic(
1006 rcvr_ty,
1007 &item_segment,
1008 span,
1009 tcx.parent_hir_node(rcvr_expr.hir_id).expect_expr(),
1010 rcvr_expr,
1011 ) {
1012 err.span_note(
1013 tcx.def_span(method.def_id),
1014 ::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}`"),
1015 );
1016 }
1017 }
1018 }
1019 }
1020 Ok((
1021 restrict_type_params,
1022 suggested_derive,
1023 unsatisfied_bounds,
1024 custom_span_label,
1025 bound_spans,
1026 ))
1027 }
1028
1029 fn suggest_surround_method_call(
1030 &self,
1031 err: &mut Diag<'_>,
1032 span: Span,
1033 rcvr_ty: Ty<'tcx>,
1034 item_ident: Ident,
1035 source: SelfSource<'tcx>,
1036 similar_candidate: &Option<ty::AssocItem>,
1037 ) -> bool {
1038 match source {
1039 SelfSource::MethodCall(expr) => {
1042 !self.suggest_calling_field_as_fn(span, rcvr_ty, expr, item_ident, err)
1043 && similar_candidate.is_none()
1044 }
1045 _ => true,
1046 }
1047 }
1048
1049 fn find_possible_candidates_for_method(
1050 &self,
1051 err: &mut Diag<'_>,
1052 span: Span,
1053 rcvr_ty: Ty<'tcx>,
1054 item_ident: Ident,
1055 item_kind: &str,
1056 mode: Mode,
1057 source: SelfSource<'tcx>,
1058 no_match_data: &NoMatchData<'tcx>,
1059 expected: Expectation<'tcx>,
1060 should_label_not_found: bool,
1061 custom_span_label: bool,
1062 ) {
1063 let mut find_candidate_for_method = false;
1064 let unsatisfied_predicates = &no_match_data.unsatisfied_predicates;
1065
1066 if should_label_not_found && !custom_span_label {
1067 self.set_not_found_span_label(
1068 err,
1069 rcvr_ty,
1070 item_ident,
1071 item_kind,
1072 mode,
1073 source,
1074 span,
1075 unsatisfied_predicates,
1076 &mut find_candidate_for_method,
1077 );
1078 }
1079 if !find_candidate_for_method {
1080 self.lookup_segments_chain_for_no_match_method(
1081 err,
1082 item_ident,
1083 item_kind,
1084 source,
1085 no_match_data,
1086 );
1087 }
1088
1089 if unsatisfied_predicates.is_empty() {
1092 self.suggest_calling_method_on_field(
1093 err,
1094 source,
1095 span,
1096 rcvr_ty,
1097 item_ident,
1098 expected.only_has_type(self),
1099 );
1100 }
1101 }
1102
1103 fn suggest_confusable_or_similarly_named_method(
1104 &self,
1105 err: &mut Diag<'_>,
1106 span: Span,
1107 rcvr_ty: Ty<'tcx>,
1108 item_ident: Ident,
1109 mode: Mode,
1110 args: Option<&'tcx [hir::Expr<'tcx>]>,
1111 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
1112 similar_candidate: Option<ty::AssocItem>,
1113 ) {
1114 let confusable_suggested = self.confusable_method_name(
1115 err,
1116 rcvr_ty,
1117 item_ident,
1118 args.map(|args| {
1119 args.iter()
1120 .map(|expr| {
1121 self.node_ty_opt(expr.hir_id).unwrap_or_else(|| self.next_ty_var(expr.span))
1122 })
1123 .collect()
1124 }),
1125 );
1126 if let Some(similar_candidate) = similar_candidate {
1127 if unsatisfied_predicates.is_empty()
1130 && Some(similar_candidate.name()) != confusable_suggested
1132 && !span.from_expansion()
1134 {
1135 self.find_likely_intended_associated_item(err, similar_candidate, span, args, mode);
1136 }
1137 }
1138 }
1139
1140 fn suggest_method_not_found_because_of_unsatisfied_bounds(
1141 &self,
1142 err: &mut Diag<'_>,
1143 rcvr_ty: Ty<'tcx>,
1144 item_ident: Ident,
1145 item_kind: &str,
1146 bound_spans: SortedMap<Span, Vec<String>>,
1147 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
1148 ) {
1149 let mut ty_span = match rcvr_ty.kind() {
1150 ty::Param(param_type) => {
1151 Some(param_type.span_from_generics(self.tcx, self.body_id.to_def_id()))
1152 }
1153 ty::Adt(def, _) if def.did().is_local() => Some(self.tcx.def_span(def.did())),
1154 _ => None,
1155 };
1156 let rcvr_ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
1157 let mut tracker = TraitBoundDuplicateTracker::new();
1158 for (predicate, _parent_pred, _cause) in unsatisfied_predicates {
1159 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1160 predicate.kind().skip_binder()
1161 && let self_ty = pred.trait_ref.self_ty()
1162 && self_ty.peel_refs() == rcvr_ty
1163 {
1164 let is_ref = #[allow(non_exhaustive_omitted_patterns)] match self_ty.kind() {
ty::Ref(..) => true,
_ => false,
}matches!(self_ty.kind(), ty::Ref(..));
1165 tracker.track(pred.trait_ref.def_id, is_ref);
1166 }
1167 }
1168 let has_ref_dupes = tracker.has_ref_dupes();
1169 let mut missing_trait_names = tracker
1170 .into_trait_def_ids()
1171 .into_iter()
1172 .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)))
1173 .collect::<Vec<_>>();
1174 missing_trait_names.sort();
1175 let should_condense =
1176 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(..));
1177 let missing_trait_list = if should_condense {
1178 Some(match missing_trait_names.as_slice() {
1179 [only] => only.clone(),
1180 [first, second] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} or {1}", first, second))
})format!("{first} or {second}"),
1181 [rest @ .., last] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} or {1}", rest.join(", "),
last))
})format!("{} or {last}", rest.join(", ")),
1182 [] => String::new(),
1183 })
1184 } else {
1185 None
1186 };
1187 for (span, mut bounds) in bound_spans {
1188 if !self.tcx.sess.source_map().is_span_accessible(span) {
1189 continue;
1190 }
1191 bounds.sort();
1192 bounds.dedup();
1193 let is_ty_span = Some(span) == ty_span;
1194 if is_ty_span && should_condense {
1195 ty_span.take();
1196 let label = if let Some(missing_trait_list) = &missing_trait_list {
1197 ::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!(
1198 "{item_kind} `{item_ident}` not found for this {} because `{rcvr_ty_str}` doesn't implement {missing_trait_list}",
1199 rcvr_ty.prefix_string(self.tcx)
1200 )
1201 } else {
1202 ::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!(
1203 "{item_kind} `{item_ident}` not found for this {}",
1204 rcvr_ty.prefix_string(self.tcx)
1205 )
1206 };
1207 err.span_label(span, label);
1208 continue;
1209 }
1210 let pre = if is_ty_span {
1211 ty_span.take();
1212 ::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!(
1213 "{item_kind} `{item_ident}` not found for this {} because it ",
1214 rcvr_ty.prefix_string(self.tcx)
1215 )
1216 } else {
1217 String::new()
1218 };
1219 let msg = match &bounds[..] {
1220 [bound] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}doesn\'t satisfy {1}", pre,
bound))
})format!("{pre}doesn't satisfy {bound}"),
1221 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()),
1222 [bounds @ .., last] => {
1223 ::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(", "))
1224 }
1225 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1226 };
1227 err.span_label(span, msg);
1228 }
1229 if let Some(span) = ty_span {
1230 err.span_label(
1231 span,
1232 ::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!(
1233 "{item_kind} `{item_ident}` not found for this {}",
1234 rcvr_ty.prefix_string(self.tcx)
1235 ),
1236 );
1237 }
1238 }
1239
1240 fn report_no_match_method_error(
1241 &self,
1242 span: Span,
1243 rcvr_ty: Ty<'tcx>,
1244 item_ident: Ident,
1245 expr_id: hir::HirId,
1246 source: SelfSource<'tcx>,
1247 args: Option<&'tcx [hir::Expr<'tcx>]>,
1248 sugg_span: Span,
1249 no_match_data: &mut NoMatchData<'tcx>,
1250 expected: Expectation<'tcx>,
1251 trait_missing_method: bool,
1252 within_macro_span: Option<Span>,
1253 ) -> ErrorGuaranteed {
1254 let tcx = self.tcx;
1255 let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty);
1256
1257 if let Err(guar) = rcvr_ty.error_reported() {
1258 return guar;
1259 }
1260
1261 if let Err(guar) =
1264 self.report_failed_method_call_on_range_end(tcx, rcvr_ty, source, span, item_ident)
1265 {
1266 return guar;
1267 }
1268
1269 let mut ty_file = None;
1270 let mode = no_match_data.mode;
1271 let is_method = mode == Mode::MethodCall;
1272 let item_kind = if is_method {
1273 "method"
1274 } else if rcvr_ty.is_enum() || rcvr_ty.is_fresh_ty() {
1275 "variant, associated function, or constant"
1276 } else {
1277 "associated function or constant"
1278 };
1279
1280 if let Err(guar) = self.report_failed_method_call_on_numerical_infer_var(
1281 tcx,
1282 rcvr_ty,
1283 source,
1284 span,
1285 item_kind,
1286 item_ident,
1287 &mut ty_file,
1288 ) {
1289 return guar;
1290 }
1291
1292 let unsatisfied_predicates = &no_match_data.unsatisfied_predicates;
1293 let is_write = sugg_span.ctxt().outer_expn_data().macro_def_id.is_some_and(|def_id| {
1294 tcx.is_diagnostic_item(sym::write_macro, def_id)
1295 || tcx.is_diagnostic_item(sym::writeln_macro, def_id)
1296 }) && item_ident.name == sym::write_fmt;
1297 let mut err = if is_write && let SelfSource::MethodCall(rcvr_expr) = source {
1298 self.create_missing_writer_err(rcvr_ty, rcvr_expr, ty_file)
1299 } else {
1300 self.create_no_assoc_err(
1301 rcvr_ty,
1302 item_ident,
1303 item_kind,
1304 trait_missing_method,
1305 source,
1306 is_method,
1307 sugg_span,
1308 unsatisfied_predicates,
1309 )
1310 };
1311 if let SelfSource::MethodCall(rcvr_expr) = source {
1312 self.err_ctxt().note_field_shadowed_by_private_candidate(
1313 &mut err,
1314 rcvr_expr.hir_id,
1315 self.param_env,
1316 );
1317 }
1318
1319 self.set_label_for_method_error(
1320 &mut err,
1321 source,
1322 rcvr_ty,
1323 item_ident,
1324 expr_id,
1325 item_ident.span,
1326 sugg_span,
1327 within_macro_span,
1328 args,
1329 );
1330
1331 self.suggest_method_call_annotation(
1332 &mut err,
1333 item_ident.span,
1334 rcvr_ty,
1335 item_ident,
1336 mode,
1337 source,
1338 expected,
1339 );
1340
1341 let static_candidates = self.suggest_static_method_candidates(
1342 &mut err,
1343 item_ident.span,
1344 rcvr_ty,
1345 item_ident,
1346 source,
1347 args,
1348 sugg_span,
1349 &no_match_data,
1350 );
1351
1352 let Ok((
1353 restrict_type_params,
1354 suggested_derive,
1355 unsatisfied_bounds,
1356 custom_span_label,
1357 bound_spans,
1358 )) = self.suggest_unsatisfied_ty_or_trait(
1359 &mut err,
1360 item_ident.span,
1361 rcvr_ty,
1362 item_ident,
1363 item_kind,
1364 source,
1365 unsatisfied_predicates,
1366 &static_candidates,
1367 )
1368 else {
1369 return err.emit();
1370 };
1371
1372 let similar_candidate = no_match_data.similar_candidate;
1373 let should_label_not_found = self.suggest_surround_method_call(
1374 &mut err,
1375 item_ident.span,
1376 rcvr_ty,
1377 item_ident,
1378 source,
1379 &similar_candidate,
1380 );
1381
1382 self.find_possible_candidates_for_method(
1383 &mut err,
1384 item_ident.span,
1385 rcvr_ty,
1386 item_ident,
1387 item_kind,
1388 mode,
1389 source,
1390 no_match_data,
1391 expected,
1392 should_label_not_found,
1393 custom_span_label,
1394 );
1395
1396 self.suggest_unwrapping_inner_self(&mut err, source, rcvr_ty, item_ident);
1397
1398 if rcvr_ty.is_numeric() && rcvr_ty.is_fresh() || restrict_type_params || suggested_derive {
1399 } else {
1401 self.suggest_traits_to_import(
1402 &mut err,
1403 item_ident.span,
1404 rcvr_ty,
1405 item_ident,
1406 args.map(|args| args.len() + 1),
1407 source,
1408 no_match_data.out_of_scope_traits.clone(),
1409 &static_candidates,
1410 unsatisfied_bounds,
1411 expected.only_has_type(self),
1412 trait_missing_method,
1413 );
1414 }
1415
1416 self.suggest_enum_variant_for_method_call(
1417 &mut err,
1418 rcvr_ty,
1419 item_ident,
1420 item_ident.span,
1421 source,
1422 unsatisfied_predicates,
1423 );
1424
1425 self.suggest_confusable_or_similarly_named_method(
1426 &mut err,
1427 item_ident.span,
1428 rcvr_ty,
1429 item_ident,
1430 mode,
1431 args,
1432 unsatisfied_predicates,
1433 similar_candidate,
1434 );
1435
1436 self.suggest_method_not_found_because_of_unsatisfied_bounds(
1437 &mut err,
1438 rcvr_ty,
1439 item_ident,
1440 item_kind,
1441 bound_spans,
1442 unsatisfied_predicates,
1443 );
1444
1445 self.note_derefed_ty_has_method(&mut err, source, rcvr_ty, item_ident, expected);
1446 self.suggest_bounds_for_range_to_method(&mut err, source, item_ident);
1447 err.emit()
1448 }
1449
1450 fn set_not_found_span_label(
1451 &self,
1452 err: &mut Diag<'_>,
1453 rcvr_ty: Ty<'tcx>,
1454 item_ident: Ident,
1455 item_kind: &str,
1456 mode: Mode,
1457 source: SelfSource<'tcx>,
1458 span: Span,
1459 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
1460 find_candidate_for_method: &mut bool,
1461 ) {
1462 let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
1463 if unsatisfied_predicates.is_empty() {
1464 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}`"));
1465 let is_string_or_ref_str = match rcvr_ty.kind() {
1466 ty::Ref(_, ty, _) => {
1467 ty.is_str()
1468 || #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Adt(adt, _) if self.tcx.is_lang_item(adt.did(), LangItem::String) =>
true,
_ => false,
}matches!(
1469 ty.kind(),
1470 ty::Adt(adt, _) if self.tcx.is_lang_item(adt.did(), LangItem::String)
1471 )
1472 }
1473 ty::Adt(adt, _) => self.tcx.is_lang_item(adt.did(), LangItem::String),
1474 _ => false,
1475 };
1476 if is_string_or_ref_str && item_ident.name == sym::iter {
1477 err.span_suggestion_verbose(
1478 item_ident.span,
1479 "because of the in-memory representation of `&str`, to obtain \
1480 an `Iterator` over each of its codepoint use method `chars`",
1481 "chars",
1482 Applicability::MachineApplicable,
1483 );
1484 }
1485 if let ty::Adt(adt, _) = rcvr_ty.kind() {
1486 let mut inherent_impls_candidate = self
1487 .tcx
1488 .inherent_impls(adt.did())
1489 .into_iter()
1490 .copied()
1491 .filter(|def_id| {
1492 if let Some(assoc) = self.associated_value(*def_id, item_ident) {
1493 match (mode, assoc.is_method(), source) {
1496 (Mode::MethodCall, true, SelfSource::MethodCall(_)) => {
1497 self.tcx
1502 .at(span)
1503 .type_of(*def_id)
1504 .instantiate_identity()
1505 .skip_norm_wip()
1506 != rcvr_ty
1507 }
1508 (Mode::Path, false, _) => true,
1509 _ => false,
1510 }
1511 } else {
1512 false
1513 }
1514 })
1515 .collect::<Vec<_>>();
1516 inherent_impls_candidate.sort_by_key(|&id| self.tcx.def_path_str(id));
1517 inherent_impls_candidate.dedup();
1518 let msg = match &inherent_impls_candidate[..] {
1519 [] => return,
1520 [only] => {
1521 ::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![
1522 StringPart::normal(format!("the {item_kind} was found for `")),
1523 StringPart::highlighted(
1524 self.tcx
1525 .at(span)
1526 .type_of(*only)
1527 .instantiate_identity()
1528 .skip_norm_wip()
1529 .to_string(),
1530 ),
1531 StringPart::normal(format!("`")),
1532 ]
1533 }
1534 candidates => {
1535 let limit = if candidates.len() == 5 { 5 } else { 4 };
1537 let type_candidates = candidates
1538 .iter()
1539 .take(limit)
1540 .map(|impl_item| {
1541 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("- `{0}`",
self.tcx.at(span).type_of(*impl_item).instantiate_identity().skip_norm_wip()))
})format!(
1542 "- `{}`",
1543 self.tcx
1544 .at(span)
1545 .type_of(*impl_item)
1546 .instantiate_identity()
1547 .skip_norm_wip()
1548 )
1549 })
1550 .collect::<Vec<_>>()
1551 .join("\n");
1552 let additional_types = if candidates.len() > limit {
1553 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} more types",
candidates.len() - limit))
})format!("\nand {} more types", candidates.len() - limit)
1554 } else {
1555 "".to_string()
1556 };
1557 ::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!(
1558 "the {item_kind} was found for\n{type_candidates}{additional_types}"
1559 ))]
1560 }
1561 };
1562 err.highlighted_note(msg);
1563 *find_candidate_for_method = mode == Mode::MethodCall;
1564 }
1565 } else {
1566 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}` ") };
1567 err.span_label(
1568 span,
1569 ::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"),
1570 );
1571 }
1572 }
1573
1574 fn suggest_enum_variant_for_method_call(
1576 &self,
1577 err: &mut Diag<'_>,
1578 rcvr_ty: Ty<'tcx>,
1579 item_ident: Ident,
1580 span: Span,
1581 source: SelfSource<'tcx>,
1582 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
1583 ) {
1584 if !unsatisfied_predicates.is_empty() || !rcvr_ty.is_enum() {
1586 return;
1587 }
1588
1589 let tcx = self.tcx;
1590 let adt_def = rcvr_ty.ty_adt_def().expect("enum is not an ADT");
1591 if let Some(var_name) = edit_distance::find_best_match_for_name(
1592 &adt_def.variants().iter().map(|s| s.name).collect::<Vec<_>>(),
1593 item_ident.name,
1594 None,
1595 ) && let Some(variant) = adt_def.variants().iter().find(|s| s.name == var_name)
1596 {
1597 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())];
1598 if let SelfSource::QPath(ty) = source
1599 && let hir::Node::Expr(ref path_expr) = tcx.parent_hir_node(ty.hir_id)
1600 && let hir::ExprKind::Path(_) = path_expr.kind
1601 && let hir::Node::Stmt(&hir::Stmt { kind: hir::StmtKind::Semi(parent), .. })
1602 | hir::Node::Expr(parent) = tcx.parent_hir_node(path_expr.hir_id)
1603 {
1604 let replacement_span = match parent.kind {
1606 hir::ExprKind::Call(callee, _) if callee.hir_id == path_expr.hir_id => {
1607 span.with_hi(parent.span.hi())
1608 }
1609 hir::ExprKind::Struct(..) => span.with_hi(parent.span.hi()),
1610 _ => span,
1611 };
1612 match (variant.ctor, parent.kind) {
1613 (None, hir::ExprKind::Struct(..)) => {
1614 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())];
1617 }
1618 (None, _) => {
1619 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![(
1621 replacement_span,
1622 if variant.fields.is_empty() {
1623 format!("{var_name} {{}}")
1624 } else {
1625 format!(
1626 "{var_name} {{ {} }}",
1627 variant
1628 .fields
1629 .iter()
1630 .map(|f| format!("{}: /* value */", f.name))
1631 .collect::<Vec<_>>()
1632 .join(", ")
1633 )
1634 },
1635 )];
1636 }
1637 (Some((hir::def::CtorKind::Const, _)), _) => {
1638 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())];
1640 }
1641 (Some((hir::def::CtorKind::Fn, def_id)), hir::ExprKind::Call(rcvr, args)) => {
1642 let fn_sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1643 let inputs = fn_sig.inputs().skip_binder();
1644 match (inputs, args) {
1647 (inputs, []) => {
1648 suggestion.push((
1650 rcvr.span.shrink_to_hi().with_hi(parent.span.hi()),
1651 ::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!(
1652 "({})",
1653 inputs
1654 .iter()
1655 .map(|i| format!("/* {i} */"))
1656 .collect::<Vec<String>>()
1657 .join(", ")
1658 ),
1659 ));
1660 }
1661 (_, [arg]) if inputs.len() != args.len() => {
1662 suggestion.push((
1664 arg.span,
1665 inputs
1666 .iter()
1667 .map(|i| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", i))
})format!("/* {i} */"))
1668 .collect::<Vec<String>>()
1669 .join(", "),
1670 ));
1671 }
1672 (_, [arg_start, .., arg_end]) if inputs.len() != args.len() => {
1673 suggestion.push((
1675 arg_start.span.to(arg_end.span),
1676 inputs
1677 .iter()
1678 .map(|i| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", i))
})format!("/* {i} */"))
1679 .collect::<Vec<String>>()
1680 .join(", "),
1681 ));
1682 }
1683 _ => {}
1685 }
1686 }
1687 (Some((hir::def::CtorKind::Fn, def_id)), _) => {
1688 let fn_sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1689 let inputs = fn_sig.inputs().skip_binder();
1690 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![(
1691 replacement_span,
1692 format!(
1693 "{var_name}({})",
1694 inputs
1695 .iter()
1696 .map(|i| format!("/* {i} */"))
1697 .collect::<Vec<String>>()
1698 .join(", ")
1699 ),
1700 )];
1701 }
1702 }
1703 }
1704 err.multipart_suggestion(
1705 "there is a variant with a similar name",
1706 suggestion,
1707 Applicability::HasPlaceholders,
1708 );
1709 }
1710 }
1711
1712 fn handle_unsatisfied_predicates(
1713 &self,
1714 err: &mut Diag<'_>,
1715 rcvr_ty: Ty<'tcx>,
1716 item_ident: Ident,
1717 item_kind: &str,
1718 span: Span,
1719 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
1720 restrict_type_params: &mut bool,
1721 suggested_derive: &mut bool,
1722 unsatisfied_bounds: &mut bool,
1723 custom_span_label: &mut bool,
1724 bound_spans: &mut SortedMap<Span, Vec<String>>,
1725 ) {
1726 let tcx = self.tcx;
1727 let rcvr_ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
1728 let mut type_params = FxIndexMap::default();
1729
1730 let mut unimplemented_traits = FxIndexMap::default();
1733
1734 let mut unimplemented_traits_only = true;
1735 for (predicate, _parent_pred, cause) in unsatisfied_predicates {
1736 if let (ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)), Some(cause)) =
1737 (predicate.kind().skip_binder(), cause.as_ref())
1738 {
1739 if p.trait_ref.self_ty() != rcvr_ty {
1740 continue;
1744 }
1745 unimplemented_traits.entry(p.trait_ref.def_id).or_insert((
1746 predicate.kind().rebind(p),
1747 Obligation {
1748 cause: cause.clone(),
1749 param_env: self.param_env,
1750 predicate: *predicate,
1751 recursion_depth: 0,
1752 },
1753 ));
1754 }
1755 }
1756
1757 for (predicate, _parent_pred, _cause) in unsatisfied_predicates {
1762 match predicate.kind().skip_binder() {
1763 ty::PredicateKind::Clause(ty::ClauseKind::Trait(p))
1764 if unimplemented_traits.contains_key(&p.trait_ref.def_id) => {}
1765 _ => {
1766 unimplemented_traits_only = false;
1767 break;
1768 }
1769 }
1770 }
1771
1772 let mut collect_type_param_suggestions =
1773 |self_ty: Ty<'tcx>, parent_pred: ty::Predicate<'tcx>, obligation: &str| {
1774 if let (ty::Param(_), ty::PredicateKind::Clause(ty::ClauseKind::Trait(p))) =
1776 (self_ty.kind(), parent_pred.kind().skip_binder())
1777 {
1778 let node = match p.trait_ref.self_ty().kind() {
1779 ty::Param(_) => {
1780 Some(self.tcx.hir_node_by_def_id(self.body_id))
1783 }
1784 ty::Adt(def, _) => {
1785 def.did().as_local().map(|def_id| self.tcx.hir_node_by_def_id(def_id))
1786 }
1787 _ => None,
1788 };
1789 if let Some(hir::Node::Item(hir::Item { kind, .. })) = node
1790 && let Some(g) = kind.generics()
1791 {
1792 let key = (
1793 g.tail_span_for_predicate_suggestion(),
1794 g.add_where_or_trailing_comma(),
1795 );
1796 type_params
1797 .entry(key)
1798 .or_insert_with(UnordSet::default)
1799 .insert(obligation.to_owned());
1800 return true;
1801 }
1802 }
1803 false
1804 };
1805 let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
1806 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 });
1807 match self_ty.kind() {
1808 ty::Adt(def, _) => {
1810 bound_spans.get_mut_or_insert_default(tcx.def_span(def.did())).push(msg)
1811 }
1812 ty::Dynamic(preds, _) => {
1814 for pred in preds.iter() {
1815 match pred.skip_binder() {
1816 ty::ExistentialPredicate::Trait(tr) => {
1817 bound_spans
1818 .get_mut_or_insert_default(tcx.def_span(tr.def_id))
1819 .push(msg.clone());
1820 }
1821 ty::ExistentialPredicate::Projection(_)
1822 | ty::ExistentialPredicate::AutoTrait(_) => {}
1823 }
1824 }
1825 }
1826 ty::Closure(def_id, _) => {
1828 bound_spans
1829 .get_mut_or_insert_default(tcx.def_span(*def_id))
1830 .push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", quiet))
})format!("`{quiet}`"));
1831 }
1832 _ => {}
1833 }
1834 };
1835
1836 let mut format_pred = |pred: ty::Predicate<'tcx>| {
1837 let bound_predicate = pred.kind();
1838 match bound_predicate.skip_binder() {
1839 ty::PredicateKind::Clause(ty::ClauseKind::Projection(pred)) => {
1840 let pred = bound_predicate.rebind(pred);
1841 let projection_term = pred.skip_binder().projection_term;
1843 let quiet_projection_term = projection_term
1844 .with_replaced_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO));
1845
1846 let term = pred.skip_binder().term;
1847
1848 let obligation = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} = {1}", projection_term, term))
})format!("{projection_term} = {term}");
1849 let quiet =
1850 {
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));
1851
1852 bound_span_label(projection_term.self_ty(), &obligation, &quiet);
1853 Some((obligation, projection_term.self_ty()))
1854 }
1855 ty::PredicateKind::Clause(ty::ClauseKind::Trait(poly_trait_ref)) => {
1856 let p = poly_trait_ref.trait_ref;
1857 let self_ty = p.self_ty();
1858 let path = p.print_only_trait_path();
1859 let obligation = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", self_ty, path))
})format!("{self_ty}: {path}");
1860 let quiet = {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_: {0}", path))
})
}with_forced_trimmed_paths!(format!("_: {}", path));
1861 bound_span_label(self_ty, &obligation, &quiet);
1862 Some((obligation, self_ty))
1863 }
1864 _ => None,
1865 }
1866 };
1867
1868 let mut skip_list: UnordSet<_> = Default::default();
1870 let mut spanned_predicates = FxIndexMap::default();
1871 let mut manually_impl = false;
1872 for (p, parent_p, cause) in unsatisfied_predicates {
1873 let (item_def_id, cause_span, cause_msg) =
1876 match cause.as_ref().map(|cause| cause.code()) {
1877 Some(ObligationCauseCode::ImplDerived(data)) => {
1878 let msg = if let DefKind::Impl { of_trait: true } =
1879 self.tcx.def_kind(data.impl_or_alias_def_id)
1880 {
1881 ::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!(
1882 "type parameter would need to implement `{}`",
1883 self.tcx
1884 .item_name(self.tcx.impl_trait_id(data.impl_or_alias_def_id))
1885 )
1886 } else {
1887 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied bound `{0}` introduced here",
p))
})format!("unsatisfied bound `{p}` introduced here")
1888 };
1889 (data.impl_or_alias_def_id, data.span, msg)
1890 }
1891 Some(
1892 ObligationCauseCode::WhereClauseInExpr(def_id, span, _, _)
1893 | ObligationCauseCode::WhereClause(def_id, span),
1894 ) if !span.is_dummy() => {
1895 (*def_id, *span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied bound `{0}` introduced here",
p))
})format!("unsatisfied bound `{p}` introduced here"))
1896 }
1897 _ => continue,
1898 };
1899
1900 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind().skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Projection(..) |
ty::ClauseKind::Trait(..)) => true,
_ => false,
}matches!(
1902 p.kind().skip_binder(),
1903 ty::PredicateKind::Clause(
1904 ty::ClauseKind::Projection(..) | ty::ClauseKind::Trait(..)
1905 )
1906 ) {
1907 continue;
1908 }
1909
1910 match self.tcx.hir_get_if_local(item_def_id) {
1911 Some(Node::Item(hir::Item {
1914 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
1915 ..
1916 })) if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
{
ExpnKind::Macro(MacroKind::Derive, _) => true,
_ => false,
}matches!(
1917 self_ty.span.ctxt().outer_expn_data().kind,
1918 ExpnKind::Macro(MacroKind::Derive, _)
1919 ) || #[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!(
1920 of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
1921 Some(ExpnKind::Macro(MacroKind::Derive, _))
1922 ) =>
1923 {
1924 let span = self_ty.span.ctxt().outer_expn_data().call_site;
1925 let entry = spanned_predicates.entry(span);
1926 let entry = entry.or_insert_with(|| {
1927 (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
1928 });
1929 entry.0.insert(cause_span);
1930 entry.1.insert((cause_span, cause_msg));
1931 entry.2.push(p);
1932 skip_list.insert(p);
1933 manually_impl = true;
1934 }
1935
1936 Some(Node::Item(hir::Item {
1938 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
1939 span: item_span,
1940 ..
1941 })) => {
1942 let sized_pred = unsatisfied_predicates.iter().any(|(pred, _, _)| {
1943 match pred.kind().skip_binder() {
1944 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
1945 self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
1946 && pred.polarity == ty::PredicatePolarity::Positive
1947 }
1948 _ => false,
1949 }
1950 });
1951 for param in generics.params {
1952 if param.span == cause_span && sized_pred {
1953 let (sp, sugg) = match param.colon_span {
1954 Some(sp) => (sp.shrink_to_hi(), " ?Sized +"),
1955 None => (param.span.shrink_to_hi(), ": ?Sized"),
1956 };
1957 err.span_suggestion_verbose(
1958 sp,
1959 "consider relaxing the type parameter's implicit `Sized` bound",
1960 sugg,
1961 Applicability::MachineApplicable,
1962 );
1963 }
1964 }
1965 if let Some(pred) = parent_p {
1966 let _ = format_pred(*pred);
1968 }
1969 skip_list.insert(p);
1970 let entry = spanned_predicates.entry(self_ty.span);
1971 let entry = entry.or_insert_with(|| {
1972 (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
1973 });
1974 entry.2.push(p);
1975 if cause_span != *item_span {
1976 entry.0.insert(cause_span);
1977 entry.1.insert((
1978 cause_span,
1979 "unsatisfied trait bound introduced here".to_string(),
1980 ));
1981 } else {
1982 if let Some(of_trait) = of_trait {
1983 entry.0.insert(of_trait.trait_ref.path.span);
1984 }
1985 entry.0.insert(self_ty.span);
1986 };
1987 if let Some(of_trait) = of_trait {
1988 entry.1.insert((of_trait.trait_ref.path.span, String::new()));
1989 }
1990 entry.1.insert((self_ty.span, String::new()));
1991 }
1992 Some(Node::Item(hir::Item {
1993 kind: hir::ItemKind::Trait { is_auto: rustc_ast::ast::IsAuto::Yes, .. },
1994 span: item_span,
1995 ..
1996 })) => {
1997 self.dcx().span_delayed_bug(
1998 *item_span,
1999 "auto trait is invoked with no method error, but no error reported?",
2000 );
2001 }
2002 Some(
2003 Node::Item(hir::Item {
2004 kind:
2005 hir::ItemKind::Trait { ident, .. }
2006 | hir::ItemKind::TraitAlias(_, ident, ..),
2007 ..
2008 })
2009 | Node::TraitItem(hir::TraitItem { ident, .. })
2011 | Node::ImplItem(hir::ImplItem { ident, .. })
2012 ) => {
2013 skip_list.insert(p);
2014 let entry = spanned_predicates.entry(ident.span);
2015 let entry = entry.or_insert_with(|| {
2016 (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
2017 });
2018 entry.0.insert(cause_span);
2019 entry.1.insert((ident.span, String::new()));
2020 entry.1.insert((
2021 cause_span,
2022 "unsatisfied trait bound introduced here".to_string(),
2023 ));
2024 entry.2.push(p);
2025 }
2026 _ => {
2027 }
2032 }
2033 }
2034 let mut spanned_predicates: Vec<_> = spanned_predicates.into_iter().collect();
2035 spanned_predicates.sort_by_key(|(span, _)| *span);
2036 for (_, (primary_spans, span_labels, predicates)) in spanned_predicates {
2037 let mut tracker = TraitBoundDuplicateTracker::new();
2038 let mut all_trait_bounds_for_rcvr = true;
2039 for pred in &predicates {
2040 match pred.kind().skip_binder() {
2041 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
2042 let self_ty = pred.trait_ref.self_ty();
2043 if self_ty.peel_refs() != rcvr_ty {
2044 all_trait_bounds_for_rcvr = false;
2045 break;
2046 }
2047 let is_ref = #[allow(non_exhaustive_omitted_patterns)] match self_ty.kind() {
ty::Ref(..) => true,
_ => false,
}matches!(self_ty.kind(), ty::Ref(..));
2048 tracker.track(pred.trait_ref.def_id, is_ref);
2049 }
2050 _ => {
2051 all_trait_bounds_for_rcvr = false;
2052 break;
2053 }
2054 }
2055 }
2056 let has_ref_dupes = tracker.has_ref_dupes();
2057 let trait_def_ids = tracker.into_trait_def_ids();
2058 let mut preds: Vec<_> = predicates
2059 .iter()
2060 .filter_map(|pred| format_pred(**pred))
2061 .map(|(p, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", p))
})format!("`{p}`"))
2062 .collect();
2063 preds.sort();
2064 preds.dedup();
2065 let availability_note = if all_trait_bounds_for_rcvr
2066 && has_ref_dupes
2067 && trait_def_ids.len() > 1
2068 && #[allow(non_exhaustive_omitted_patterns)] match rcvr_ty.kind() {
ty::Adt(..) => true,
_ => false,
}matches!(rcvr_ty.kind(), ty::Adt(..))
2069 {
2070 let mut trait_names = trait_def_ids
2071 .into_iter()
2072 .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)))
2073 .collect::<Vec<_>>();
2074 trait_names.sort();
2075 listify(&trait_names, |name| name.to_string()).map(|traits| {
2076 ::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!(
2077 "for `{item_ident}` to be available, `{rcvr_ty_str}` must implement {traits}"
2078 )
2079 })
2080 } else {
2081 None
2082 };
2083 let msg = if let Some(availability_note) = availability_note {
2084 availability_note
2085 } else if let [pred] = &preds[..] {
2086 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait bound {0} was not satisfied",
pred))
})format!("trait bound {pred} was not satisfied")
2087 } else {
2088 ::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"),)
2089 };
2090 let mut span: MultiSpan = primary_spans.into_iter().collect::<Vec<_>>().into();
2091 for (sp, label) in span_labels {
2092 span.push_span_label(sp, label);
2093 }
2094 err.span_note(span, msg);
2095 *unsatisfied_bounds = true;
2096 }
2097
2098 let mut suggested_bounds = UnordSet::default();
2099 let mut bound_list = unsatisfied_predicates
2101 .iter()
2102 .filter_map(|(pred, parent_pred, _cause)| {
2103 let mut suggested = false;
2104 format_pred(*pred).map(|(p, self_ty)| {
2105 if let Some(parent) = parent_pred
2106 && suggested_bounds.contains(parent)
2107 {
2108 } else if !suggested_bounds.contains(pred)
2110 && collect_type_param_suggestions(self_ty, *pred, &p)
2111 {
2112 suggested = true;
2113 suggested_bounds.insert(pred);
2114 }
2115 (
2116 match parent_pred {
2117 None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", p))
})format!("`{p}`"),
2118 Some(parent_pred) => match format_pred(*parent_pred) {
2119 None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", p))
})format!("`{p}`"),
2120 Some((parent_p, _)) => {
2121 if !suggested
2122 && !suggested_bounds.contains(pred)
2123 && !suggested_bounds.contains(parent_pred)
2124 && collect_type_param_suggestions(self_ty, *parent_pred, &p)
2125 {
2126 suggested_bounds.insert(pred);
2127 }
2128 ::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}`")
2129 }
2130 },
2131 },
2132 *pred,
2133 )
2134 })
2135 })
2136 .filter(|(_, pred)| !skip_list.contains(&pred))
2137 .map(|(t, _)| t)
2138 .enumerate()
2139 .collect::<Vec<(usize, String)>>();
2140
2141 if !#[allow(non_exhaustive_omitted_patterns)] match rcvr_ty.peel_refs().kind() {
ty::Param(_) => true,
_ => false,
}matches!(rcvr_ty.peel_refs().kind(), ty::Param(_)) {
2142 for ((span, add_where_or_comma), obligations) in type_params.into_iter() {
2143 *restrict_type_params = true;
2144 let obligations = obligations.into_sorted_stable_ord();
2146 err.span_suggestion_verbose(
2147 span,
2148 ::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!(
2149 "consider restricting the type parameter{s} to satisfy the trait \
2150 bound{s}",
2151 s = pluralize!(obligations.len())
2152 ),
2153 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", add_where_or_comma,
obligations.join(", ")))
})format!("{} {}", add_where_or_comma, obligations.join(", ")),
2154 Applicability::MaybeIncorrect,
2155 );
2156 }
2157 }
2158
2159 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() {
2164 let bound_list =
2165 bound_list.into_iter().map(|(_, path)| path).collect::<Vec<_>>().join("\n");
2166 let actual_prefix = rcvr_ty.prefix_string(self.tcx);
2167 {
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:2167",
"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(2167u32),
::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());
2168 let (primary_message, label, notes) = if unimplemented_traits.len() == 1
2169 && unimplemented_traits_only
2170 {
2171 unimplemented_traits
2172 .into_iter()
2173 .next()
2174 .map(|(_, (trait_ref, obligation))| {
2175 if trait_ref.self_ty().references_error() || rcvr_ty.references_error() {
2176 return (None, None, Vec::new());
2178 }
2179 let CustomDiagnostic { message, label, notes, .. } = self
2180 .err_ctxt()
2181 .on_unimplemented_note(trait_ref, &obligation, err.long_ty_path());
2182 (message, label, notes)
2183 })
2184 .unwrap()
2185 } else {
2186 (None, None, Vec::new())
2187 };
2188 let primary_message = primary_message.unwrap_or_else(|| {
2189 let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
2190 ::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!(
2191 "the {item_kind} `{item_ident}` exists for {actual_prefix} `{ty_str}`, \
2192 but its trait bounds were not satisfied"
2193 )
2194 });
2195 err.primary_message(primary_message);
2196 if let Some(label) = label {
2197 *custom_span_label = true;
2198 err.span_label(span, label);
2199 }
2200 if !bound_list.is_empty() {
2201 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}"));
2202 }
2203 for note in notes {
2204 err.note(note);
2205 }
2206
2207 if let ty::Adt(adt_def, _) = rcvr_ty.kind() {
2208 unsatisfied_predicates.iter().find(|(pred, _parent, _cause)| {
2209 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2210 pred.kind().skip_binder()
2211 {
2212 self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(
2213 err, &pred, *adt_def,
2214 )
2215 } else {
2216 false
2217 }
2218 });
2219 }
2220
2221 *suggested_derive = self.suggest_derive(err, unsatisfied_predicates);
2222 *unsatisfied_bounds = true;
2223 }
2224 if manually_impl {
2225 err.help("consider manually implementing the trait to avoid undesired bounds");
2226 }
2227 }
2228
2229 fn lookup_segments_chain_for_no_match_method(
2231 &self,
2232 err: &mut Diag<'_>,
2233 item_name: Ident,
2234 item_kind: &str,
2235 source: SelfSource<'tcx>,
2236 no_match_data: &NoMatchData<'tcx>,
2237 ) {
2238 if no_match_data.unsatisfied_predicates.is_empty()
2239 && let Mode::MethodCall = no_match_data.mode
2240 && let SelfSource::MethodCall(mut source_expr) = source
2241 {
2242 let mut stack_methods = ::alloc::vec::Vec::new()vec![];
2243 while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, method_span) =
2244 source_expr.kind
2245 {
2246 if let Some(prev_match) = stack_methods.pop() {
2248 err.span_label(
2249 method_span,
2250 ::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}`"),
2251 );
2252 }
2253 let rcvr_ty = self.resolve_vars_if_possible(
2254 self.typeck_results
2255 .borrow()
2256 .expr_ty_adjusted_opt(rcvr_expr)
2257 .unwrap_or(Ty::new_misc_error(self.tcx)),
2258 );
2259
2260 let Ok(candidates) = self.probe_for_name_many(
2261 Mode::MethodCall,
2262 item_name,
2263 None,
2264 IsSuggestion(true),
2265 rcvr_ty,
2266 source_expr.hir_id,
2267 ProbeScope::TraitsInScope,
2268 ) else {
2269 return;
2270 };
2271
2272 for _matched_method in candidates {
2276 stack_methods.push(rcvr_ty);
2278 }
2279 source_expr = rcvr_expr;
2280 }
2281 if let Some(prev_match) = stack_methods.pop() {
2283 err.span_label(
2284 source_expr.span,
2285 ::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}`"),
2286 );
2287 }
2288 }
2289 }
2290
2291 fn find_likely_intended_associated_item(
2292 &self,
2293 err: &mut Diag<'_>,
2294 similar_candidate: ty::AssocItem,
2295 span: Span,
2296 args: Option<&'tcx [hir::Expr<'tcx>]>,
2297 mode: Mode,
2298 ) {
2299 let tcx = self.tcx;
2300 let def_kind = similar_candidate.as_def_kind();
2301 let an = self.tcx.def_kind_descr_article(def_kind, similar_candidate.def_id);
2302 let similar_candidate_name = similar_candidate.name();
2303 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!(
2304 "there is {an} {} `{}` with a similar name",
2305 self.tcx.def_kind_descr(def_kind, similar_candidate.def_id),
2306 similar_candidate_name,
2307 );
2308 if def_kind == DefKind::AssocFn {
2313 let ty_args = self.infcx.fresh_args_for_item(span, similar_candidate.def_id);
2314 let fn_sig =
2315 tcx.fn_sig(similar_candidate.def_id).instantiate(tcx, ty_args).skip_norm_wip();
2316 let fn_sig = self.instantiate_binder_with_fresh_vars(
2317 span,
2318 BoundRegionConversionTime::FnCall,
2319 fn_sig,
2320 );
2321 if similar_candidate.is_method() {
2322 if let Some(args) = args
2323 && fn_sig.inputs()[1..].len() == args.len()
2324 {
2325 err.span_suggestion_verbose(
2328 span,
2329 msg,
2330 similar_candidate_name,
2331 Applicability::MaybeIncorrect,
2332 );
2333 } else {
2334 err.span_help(
2337 tcx.def_span(similar_candidate.def_id),
2338 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}",
if let None = args {
""
} else { ", but with different arguments" }, msg))
})format!(
2339 "{msg}{}",
2340 if let None = args { "" } else { ", but with different arguments" },
2341 ),
2342 );
2343 }
2344 } else if let Some(args) = args
2345 && fn_sig.inputs().len() == args.len()
2346 {
2347 err.span_suggestion_verbose(
2350 span,
2351 msg,
2352 similar_candidate_name,
2353 Applicability::MaybeIncorrect,
2354 );
2355 } else {
2356 err.span_help(tcx.def_span(similar_candidate.def_id), msg);
2357 }
2358 } else if let Mode::Path = mode
2359 && args.unwrap_or(&[]).is_empty()
2360 {
2361 err.span_suggestion_verbose(
2363 span,
2364 msg,
2365 similar_candidate_name,
2366 Applicability::MaybeIncorrect,
2367 );
2368 } else {
2369 err.span_help(tcx.def_span(similar_candidate.def_id), msg);
2372 }
2373 }
2374
2375 pub(crate) fn confusable_method_name(
2376 &self,
2377 err: &mut Diag<'_>,
2378 rcvr_ty: Ty<'tcx>,
2379 item_name: Ident,
2380 call_args: Option<Vec<Ty<'tcx>>>,
2381 ) -> Option<Symbol> {
2382 if let ty::Adt(adt, adt_args) = rcvr_ty.kind() {
2383 for &inherent_impl_did in self.tcx.inherent_impls(adt.did()).into_iter() {
2384 for inherent_method in
2385 self.tcx.associated_items(inherent_impl_did).in_definition_order()
2386 {
2387 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)
2388 && confusables.contains(&item_name.name)
2389 && inherent_method.is_fn()
2390 {
2391 let args =
2392 ty::GenericArgs::identity_for_item(self.tcx, inherent_method.def_id)
2393 .rebase_onto(
2394 self.tcx,
2395 inherent_method.container_id(self.tcx),
2396 adt_args,
2397 );
2398 let fn_sig = self
2399 .tcx
2400 .fn_sig(inherent_method.def_id)
2401 .instantiate(self.tcx, args)
2402 .skip_norm_wip();
2403 let fn_sig = self.instantiate_binder_with_fresh_vars(
2404 item_name.span,
2405 BoundRegionConversionTime::FnCall,
2406 fn_sig,
2407 );
2408 let name = inherent_method.name();
2409 let inputs = fn_sig.inputs();
2410 let expected_inputs =
2411 if inherent_method.is_method() { &inputs[1..] } else { inputs };
2412 if let Some(ref args) = call_args
2413 && expected_inputs
2414 .iter()
2415 .eq_by(args, |expected, found| self.may_coerce(*expected, *found))
2416 {
2417 err.span_suggestion_verbose(
2418 item_name.span,
2419 ::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),
2420 name,
2421 Applicability::MaybeIncorrect,
2422 );
2423 return Some(name);
2424 } else if let None = call_args {
2425 err.span_note(
2426 self.tcx.def_span(inherent_method.def_id),
2427 ::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),
2428 );
2429 return Some(name);
2430 }
2431 }
2432 }
2433 }
2434 }
2435 None
2436 }
2437 fn note_candidates_on_method_error(
2438 &self,
2439 rcvr_ty: Ty<'tcx>,
2440 item_name: Ident,
2441 self_source: SelfSource<'tcx>,
2442 args: Option<&'tcx [hir::Expr<'tcx>]>,
2443 span: Span,
2444 err: &mut Diag<'_>,
2445 sources: &mut Vec<CandidateSource>,
2446 sugg_span: Option<Span>,
2447 ) {
2448 sources.sort_by_key(|source| match *source {
2449 CandidateSource::Trait(id) => (0, self.tcx.def_path_str(id)),
2450 CandidateSource::Impl(id) => (1, self.tcx.def_path_str(id)),
2451 });
2452 sources.dedup();
2453 let limit = if sources.len() == 5 { 5 } else { 4 };
2455
2456 let mut suggs = ::alloc::vec::Vec::new()vec![];
2457 for (idx, source) in sources.iter().take(limit).enumerate() {
2458 match *source {
2459 CandidateSource::Impl(impl_did) => {
2460 let Some(item) = self.associated_value(impl_did, item_name).or_else(|| {
2463 let impl_trait_id = self.tcx.impl_opt_trait_id(impl_did)?;
2464 self.associated_value(impl_trait_id, item_name)
2465 }) else {
2466 continue;
2467 };
2468
2469 let note_span = if item.def_id.is_local() {
2470 Some(self.tcx.def_span(item.def_id))
2471 } else if impl_did.is_local() {
2472 Some(self.tcx.def_span(impl_did))
2473 } else {
2474 None
2475 };
2476
2477 let impl_ty =
2478 self.tcx.at(span).type_of(impl_did).instantiate_identity().skip_norm_wip();
2479
2480 let insertion = match self.tcx.impl_opt_trait_ref(impl_did) {
2481 None => String::new(),
2482 Some(trait_ref) => {
2483 ::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!(
2484 " of the trait `{}`",
2485 self.tcx.def_path_str(trait_ref.skip_binder().def_id)
2486 )
2487 }
2488 };
2489
2490 let (note_str, idx) = if sources.len() > 1 {
2491 (
2492 ::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!(
2493 "candidate #{} is defined in an impl{} for the type `{}`",
2494 idx + 1,
2495 insertion,
2496 impl_ty,
2497 ),
2498 Some(idx + 1),
2499 )
2500 } else {
2501 (
2502 ::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!(
2503 "the candidate is defined in an impl{insertion} for the type `{impl_ty}`",
2504 ),
2505 None,
2506 )
2507 };
2508 if let Some(note_span) = note_span {
2509 err.span_note(note_span, note_str);
2511 } else {
2512 err.note(note_str);
2513 }
2514 if let Some(sugg_span) = sugg_span
2515 && let Some(trait_ref) = self.tcx.impl_opt_trait_ref(impl_did)
2516 && let Some(sugg) = print_disambiguation_help(
2517 self.tcx,
2518 err,
2519 self_source,
2520 args,
2521 trait_ref
2522 .instantiate(
2523 self.tcx,
2524 self.fresh_args_for_item(sugg_span, impl_did),
2525 )
2526 .skip_norm_wip()
2527 .with_replaced_self_ty(self.tcx, rcvr_ty),
2528 idx,
2529 sugg_span,
2530 item,
2531 )
2532 {
2533 suggs.push(sugg);
2534 }
2535 }
2536 CandidateSource::Trait(trait_did) => {
2537 let Some(item) = self.associated_value(trait_did, item_name) else { continue };
2538 let item_span = self.tcx.def_span(item.def_id);
2539 let idx = if sources.len() > 1 {
2540 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!(
2541 "candidate #{} is defined in the trait `{}`",
2542 idx + 1,
2543 self.tcx.def_path_str(trait_did)
2544 );
2545 err.span_note(item_span, msg);
2546 Some(idx + 1)
2547 } else {
2548 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!(
2549 "the candidate is defined in the trait `{}`",
2550 self.tcx.def_path_str(trait_did)
2551 );
2552 err.span_note(item_span, msg);
2553 None
2554 };
2555 if let Some(sugg_span) = sugg_span
2556 && let Some(sugg) = print_disambiguation_help(
2557 self.tcx,
2558 err,
2559 self_source,
2560 args,
2561 ty::TraitRef::new_from_args(
2562 self.tcx,
2563 trait_did,
2564 self.fresh_args_for_item(sugg_span, trait_did),
2565 )
2566 .with_replaced_self_ty(self.tcx, rcvr_ty),
2567 idx,
2568 sugg_span,
2569 item,
2570 )
2571 {
2572 suggs.push(sugg);
2573 }
2574 }
2575 }
2576 }
2577 if !suggs.is_empty()
2578 && let Some(span) = sugg_span
2579 {
2580 suggs.sort();
2581 err.span_suggestions(
2582 span.with_hi(item_name.span.lo()),
2583 "use fully-qualified syntax to disambiguate",
2584 suggs,
2585 Applicability::MachineApplicable,
2586 );
2587 }
2588 if sources.len() > limit {
2589 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("and {0} others",
sources.len() - limit))
})format!("and {} others", sources.len() - limit));
2590 }
2591 }
2592
2593 fn find_builder_fn(&self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>, expr_id: hir::HirId) {
2596 let ty::Adt(adt_def, _) = rcvr_ty.kind() else {
2597 return;
2598 };
2599 let mut items = self
2600 .tcx
2601 .inherent_impls(adt_def.did())
2602 .iter()
2603 .flat_map(|&i| self.tcx.associated_items(i).in_definition_order())
2604 .filter(|item| {
2607 #[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, .. })
2608 && self
2609 .probe_for_name(
2610 Mode::Path,
2611 item.ident(self.tcx),
2612 None,
2613 IsSuggestion(true),
2614 rcvr_ty,
2615 expr_id,
2616 ProbeScope::TraitsInScope,
2617 )
2618 .is_ok()
2619 })
2620 .filter_map(|item| {
2621 let ret_ty = self
2623 .tcx
2624 .fn_sig(item.def_id)
2625 .instantiate(self.tcx, self.fresh_args_for_item(DUMMY_SP, item.def_id))
2626 .skip_norm_wip()
2627 .output();
2628 let ret_ty = self.tcx.instantiate_bound_regions_with_erased(ret_ty);
2629 let ty::Adt(def, args) = ret_ty.kind() else {
2630 return None;
2631 };
2632 if self.can_eq(self.param_env, ret_ty, rcvr_ty) {
2634 return Some((item.def_id, ret_ty));
2635 }
2636 if ![self.tcx.lang_items().option_type(), self.tcx.get_diagnostic_item(sym::Result)]
2638 .contains(&Some(def.did()))
2639 {
2640 return None;
2641 }
2642 let arg = args.get(0)?.expect_ty();
2643 if self.can_eq(self.param_env, rcvr_ty, arg) {
2644 Some((item.def_id, ret_ty))
2645 } else {
2646 None
2647 }
2648 })
2649 .collect::<Vec<_>>();
2650 let post = if items.len() > 5 {
2651 let items_len = items.len();
2652 items.truncate(4);
2653 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} others", items_len - 4))
})format!("\nand {} others", items_len - 4)
2654 } else {
2655 String::new()
2656 };
2657 match items[..] {
2658 [] => {}
2659 [(def_id, ret_ty)] => {
2660 err.span_note(
2661 self.tcx.def_span(def_id),
2662 ::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!(
2663 "if you're trying to build a new `{rcvr_ty}`, consider using `{}` which \
2664 returns `{ret_ty}`",
2665 self.tcx.def_path_str(def_id),
2666 ),
2667 );
2668 }
2669 _ => {
2670 let span: MultiSpan = items
2671 .iter()
2672 .map(|&(def_id, _)| self.tcx.def_span(def_id))
2673 .collect::<Vec<Span>>()
2674 .into();
2675 err.span_note(
2676 span,
2677 ::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!(
2678 "if you're trying to build a new `{rcvr_ty}` consider using one of the \
2679 following associated functions:\n{}{post}",
2680 items
2681 .iter()
2682 .map(|&(def_id, _ret_ty)| self.tcx.def_path_str(def_id))
2683 .collect::<Vec<String>>()
2684 .join("\n")
2685 ),
2686 );
2687 }
2688 }
2689 }
2690
2691 fn suggest_associated_call_syntax(
2694 &self,
2695 err: &mut Diag<'_>,
2696 static_candidates: &[CandidateSource],
2697 rcvr_ty: Ty<'tcx>,
2698 source: SelfSource<'tcx>,
2699 item_name: Ident,
2700 args: Option<&'tcx [hir::Expr<'tcx>]>,
2701 sugg_span: Span,
2702 ) {
2703 let mut has_unsuggestable_args = false;
2704 let ty_str = if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0) {
2705 let impl_ty = self.tcx.type_of(*impl_did).instantiate_identity().skip_norm_wip();
2709 let target_ty = self
2710 .autoderef(sugg_span, rcvr_ty)
2711 .silence_errors()
2712 .find(|(rcvr_ty, _)| {
2713 DeepRejectCtxt::relate_rigid_infer(self.tcx).types_may_unify(*rcvr_ty, impl_ty)
2714 })
2715 .map_or(impl_ty, |(ty, _)| ty)
2716 .peel_refs();
2717 if let ty::Adt(def, args) = target_ty.kind() {
2718 let infer_args = self.tcx.mk_args_from_iter(args.into_iter().map(|arg| {
2721 if !arg.is_suggestable(self.tcx, true) {
2722 has_unsuggestable_args = true;
2723 match arg.kind() {
2724 GenericArgKind::Lifetime(_) => {
2725 self.next_region_var(RegionVariableOrigin::Misc(DUMMY_SP)).into()
2726 }
2727 GenericArgKind::Type(_) => self.next_ty_var(DUMMY_SP).into(),
2728 GenericArgKind::Const(_) => self.next_const_var(DUMMY_SP).into(),
2729 }
2730 } else {
2731 arg
2732 }
2733 }));
2734
2735 self.tcx.value_path_str_with_args(def.did(), infer_args)
2736 } else {
2737 self.ty_to_value_string(target_ty)
2738 }
2739 } else {
2740 self.ty_to_value_string(rcvr_ty.peel_refs())
2741 };
2742 if let SelfSource::MethodCall(_) = source {
2743 let first_arg = static_candidates.get(0).and_then(|candidate_source| {
2744 let (assoc_did, self_ty) = match candidate_source {
2745 CandidateSource::Impl(impl_did) => (
2746 *impl_did,
2747 self.tcx.type_of(*impl_did).instantiate_identity().skip_norm_wip(),
2748 ),
2749 CandidateSource::Trait(trait_did) => (*trait_did, rcvr_ty),
2750 };
2751
2752 let assoc = self.associated_value(assoc_did, item_name)?;
2753 if !assoc.is_fn() {
2754 return None;
2755 }
2756
2757 let sig = self.tcx.fn_sig(assoc.def_id).instantiate_identity().skip_norm_wip();
2760 sig.inputs().skip_binder().get(0).and_then(|first| {
2761 let first_ty = first.peel_refs();
2763 if first_ty == self_ty || first_ty == self.tcx.types.self_param {
2764 Some(first.ref_mutability().map_or("", |mutbl| mutbl.ref_prefix_str()))
2765 } else {
2766 None
2767 }
2768 })
2769 });
2770
2771 let mut applicability = Applicability::MachineApplicable;
2772 let args = if let SelfSource::MethodCall(receiver) = source
2773 && let Some(args) = args
2774 {
2775 let explicit_args = if first_arg.is_some() {
2777 std::iter::once(receiver).chain(args.iter()).collect::<Vec<_>>()
2778 } else {
2779 if has_unsuggestable_args {
2781 applicability = Applicability::HasPlaceholders;
2782 }
2783 args.iter().collect()
2784 };
2785 ::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!(
2786 "({}{})",
2787 first_arg.unwrap_or(""),
2788 explicit_args
2789 .iter()
2790 .map(|arg| self
2791 .tcx
2792 .sess
2793 .source_map()
2794 .span_to_snippet(arg.span)
2795 .unwrap_or_else(|_| {
2796 applicability = Applicability::HasPlaceholders;
2797 "_".to_owned()
2798 }))
2799 .collect::<Vec<_>>()
2800 .join(", "),
2801 )
2802 } else {
2803 applicability = Applicability::HasPlaceholders;
2804 "(...)".to_owned()
2805 };
2806 err.span_suggestion_verbose(
2807 sugg_span,
2808 "use associated function syntax instead",
2809 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}{2}", ty_str, item_name,
args))
})format!("{ty_str}::{item_name}{args}"),
2810 applicability,
2811 );
2812 } else {
2813 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}`",));
2814 }
2815 }
2816
2817 fn suggest_calling_field_as_fn(
2820 &self,
2821 span: Span,
2822 rcvr_ty: Ty<'tcx>,
2823 expr: &hir::Expr<'_>,
2824 item_name: Ident,
2825 err: &mut Diag<'_>,
2826 ) -> bool {
2827 let tcx = self.tcx;
2828 let field_receiver =
2829 self.autoderef(span, rcvr_ty).silence_errors().find_map(|(ty, _)| match ty.kind() {
2830 ty::Adt(def, args) if !def.is_enum() => {
2831 let variant = &def.non_enum_variant();
2832 tcx.find_field_index(item_name, variant).map(|index| {
2833 let field = &variant.fields[index];
2834 let field_ty = field.ty(tcx, args).skip_norm_wip();
2835 (field, field_ty)
2836 })
2837 }
2838 _ => None,
2839 });
2840 if let Some((field, field_ty)) = field_receiver {
2841 let scope = tcx.parent_module_from_def_id(self.body_id);
2842 let is_accessible = field.vis.is_accessible_from(scope, tcx);
2843
2844 if is_accessible {
2845 if let Some((what, _, _)) = self.extract_callable_info(field_ty) {
2846 let what = match what {
2847 DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
2848 DefIdOrName::Name(what) => what,
2849 };
2850 let expr_span = expr.span.to(item_name.span);
2851 err.multipart_suggestion(
2852 ::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!(
2853 "to call the {what} stored in `{item_name}`, \
2854 surround the field access with parentheses",
2855 ),
2856 ::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![
2857 (expr_span.shrink_to_lo(), '('.to_string()),
2858 (expr_span.shrink_to_hi(), ')'.to_string()),
2859 ],
2860 Applicability::MachineApplicable,
2861 );
2862 } else {
2863 let call_expr = tcx.hir_expect_expr(tcx.parent_hir_id(expr.hir_id));
2864
2865 if let Some(span) = call_expr.span.trim_start(item_name.span) {
2866 err.span_suggestion(
2867 span,
2868 "remove the arguments",
2869 "",
2870 Applicability::MaybeIncorrect,
2871 );
2872 }
2873 }
2874 }
2875
2876 let field_kind = if is_accessible { "field" } else { "private field" };
2877 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"));
2878 return true;
2879 }
2880 false
2881 }
2882
2883 fn report_failed_method_call_on_range_end(
2886 &self,
2887 tcx: TyCtxt<'tcx>,
2888 actual: Ty<'tcx>,
2889 source: SelfSource<'tcx>,
2890 span: Span,
2891 item_name: Ident,
2892 ) -> Result<(), ErrorGuaranteed> {
2893 if let SelfSource::MethodCall(expr) = source {
2894 for (_, parent) in tcx.hir_parent_iter(expr.hir_id).take(5) {
2895 if let Node::Expr(parent_expr) = parent {
2896 if !is_range_literal(parent_expr) {
2897 continue;
2898 }
2899 let lang_item = match parent_expr.kind {
2900 ExprKind::Struct(qpath, _, _) => match tcx.qpath_lang_item(*qpath) {
2901 Some(
2902 lang_item @ (LangItem::Range
2903 | LangItem::RangeCopy
2904 | LangItem::RangeInclusiveCopy
2905 | LangItem::RangeTo
2906 | LangItem::RangeToInclusive),
2907 ) => Some(lang_item),
2908 _ => None,
2909 },
2910 ExprKind::Call(func, _) => match func.kind {
2911 ExprKind::Path(qpath)
2913 if tcx.qpath_is_lang_item(qpath, LangItem::RangeInclusiveNew) =>
2914 {
2915 Some(LangItem::RangeInclusiveStruct)
2916 }
2917 _ => None,
2918 },
2919 _ => None,
2920 };
2921
2922 if lang_item.is_none() {
2923 continue;
2924 }
2925
2926 let span_included = match parent_expr.kind {
2927 hir::ExprKind::Struct(_, eps, _) => {
2928 eps.last().is_some_and(|ep| ep.span.contains(span))
2929 }
2930 hir::ExprKind::Call(func, ..) => func.span.contains(span),
2932 _ => false,
2933 };
2934
2935 if !span_included {
2936 continue;
2937 }
2938
2939 let Some(range_def_id) =
2940 lang_item.and_then(|lang_item| self.tcx.lang_items().get(lang_item))
2941 else {
2942 continue;
2943 };
2944 let range_ty = self
2945 .tcx
2946 .type_of(range_def_id)
2947 .instantiate(self.tcx, &[actual.into()])
2948 .skip_norm_wip();
2949
2950 let pick = self.lookup_probe_for_diagnostic(
2951 item_name,
2952 range_ty,
2953 expr,
2954 ProbeScope::AllTraits,
2955 None,
2956 );
2957 if pick.is_ok() {
2958 let range_span = parent_expr.span.with_hi(expr.span.hi());
2959 return Err(self.dcx().emit_err(diagnostics::MissingParenthesesInRange {
2960 span,
2961 ty: actual,
2962 method_name: item_name.as_str().to_string(),
2963 add_missing_parentheses: Some(
2964 diagnostics::AddMissingParenthesesInRange {
2965 func_name: item_name.name.as_str().to_string(),
2966 left: range_span.shrink_to_lo(),
2967 right: range_span.shrink_to_hi(),
2968 },
2969 ),
2970 }));
2971 }
2972 }
2973 }
2974 }
2975 Ok(())
2976 }
2977
2978 fn report_failed_method_call_on_numerical_infer_var(
2979 &self,
2980 tcx: TyCtxt<'tcx>,
2981 actual: Ty<'tcx>,
2982 source: SelfSource<'_>,
2983 span: Span,
2984 item_kind: &str,
2985 item_name: Ident,
2986 long_ty_path: &mut Option<PathBuf>,
2987 ) -> Result<(), ErrorGuaranteed> {
2988 let found_candidate = all_traits(self.tcx)
2989 .into_iter()
2990 .any(|info| self.associated_value(info.def_id, item_name).is_some());
2991 let found_assoc = |ty: Ty<'tcx>| {
2992 simplify_type(tcx, ty, TreatParams::InstantiateWithInfer)
2993 .and_then(|simp| {
2994 tcx.incoherent_impls(simp)
2995 .iter()
2996 .find_map(|&id| self.associated_value(id, item_name))
2997 })
2998 .is_some()
2999 };
3000 let found_candidate = found_candidate
3001 || found_assoc(tcx.types.i8)
3002 || found_assoc(tcx.types.i16)
3003 || found_assoc(tcx.types.i32)
3004 || found_assoc(tcx.types.i64)
3005 || found_assoc(tcx.types.i128)
3006 || found_assoc(tcx.types.u8)
3007 || found_assoc(tcx.types.u16)
3008 || found_assoc(tcx.types.u32)
3009 || found_assoc(tcx.types.u64)
3010 || found_assoc(tcx.types.u128)
3011 || found_assoc(tcx.types.f32)
3012 || found_assoc(tcx.types.f64);
3013 if found_candidate
3014 && actual.is_numeric()
3015 && !actual.has_concrete_skeleton()
3016 && let SelfSource::MethodCall(expr) = source
3017 {
3018 let ty_str = self.tcx.short_string(actual, long_ty_path);
3019 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!(
3020 self.dcx(),
3021 span,
3022 E0689,
3023 "can't call {item_kind} `{item_name}` on ambiguous numeric type `{ty_str}`"
3024 );
3025 *err.long_ty_path() = long_ty_path.take();
3026 let concrete_type = if actual.is_integral() { "i32" } else { "f32" };
3027 match expr.kind {
3028 ExprKind::Lit(lit) => {
3029 let snippet = tcx
3031 .sess
3032 .source_map()
3033 .span_to_snippet(lit.span)
3034 .unwrap_or_else(|_| "<numeric literal>".to_owned());
3035
3036 let snippet = snippet.trim_suffix('.');
3039 err.span_suggestion(
3040 lit.span,
3041 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you must specify a concrete type for this numeric value, like `{0}`",
concrete_type))
})format!(
3042 "you must specify a concrete type for this numeric value, \
3043 like `{concrete_type}`"
3044 ),
3045 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_{1}", snippet, concrete_type))
})format!("{snippet}_{concrete_type}"),
3046 Applicability::MaybeIncorrect,
3047 );
3048 }
3049 ExprKind::Path(QPath::Resolved(_, path)) => {
3050 if let hir::def::Res::Local(hir_id) = path.res {
3052 let span = tcx.hir_span(hir_id);
3053 let filename = tcx.sess.source_map().span_to_filename(span);
3054
3055 let parent_node = self.tcx.parent_hir_node(hir_id);
3056 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you must specify a type for this binding, like `{0}`",
concrete_type))
})format!(
3057 "you must specify a type for this binding, like `{concrete_type}`",
3058 );
3059
3060 match (filename, parent_node) {
3063 (
3064 FileName::Real(_),
3065 Node::LetStmt(hir::LetStmt {
3066 source: hir::LocalSource::Normal,
3067 ty,
3068 ..
3069 }),
3070 ) => {
3071 let type_span = ty
3072 .map(|ty| ty.span.with_lo(span.hi()))
3073 .unwrap_or(span.shrink_to_hi());
3074 err.span_suggestion(
3075 type_span,
3078 msg,
3079 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}", concrete_type))
})format!(": {concrete_type}"),
3080 Applicability::MaybeIncorrect,
3081 );
3082 }
3083 (FileName::Real(_), Node::Pat(pat))
3086 if let Node::Pat(binding_pat) = self.tcx.hir_node(hir_id)
3087 && let hir::PatKind::Binding(..) = binding_pat.kind
3088 && let Node::Pat(parent_pat) = parent_node
3089 && #[allow(non_exhaustive_omitted_patterns)] match parent_pat.kind {
hir::PatKind::Ref(..) => true,
_ => false,
}matches!(parent_pat.kind, hir::PatKind::Ref(..)) =>
3090 {
3091 err.span_label(span, "you must specify a type for this binding");
3092
3093 let mut ref_muts = Vec::new();
3094 let mut current_node = parent_node;
3095
3096 while let Node::Pat(parent_pat) = current_node {
3097 if let hir::PatKind::Ref(_, _, mutability) = parent_pat.kind {
3098 ref_muts.push(mutability);
3099 current_node = self.tcx.parent_hir_node(parent_pat.hir_id);
3100 } else {
3101 break;
3102 }
3103 }
3104
3105 let mut type_annotation = String::new();
3106 for mutability in ref_muts.iter().rev() {
3107 match mutability {
3108 hir::Mutability::Mut => type_annotation.push_str("&mut "),
3109 hir::Mutability::Not => type_annotation.push('&'),
3110 }
3111 }
3112 type_annotation.push_str(&concrete_type);
3113
3114 err.span_suggestion_verbose(
3115 pat.span.shrink_to_hi(),
3116 "specify the type in the closure argument list",
3117 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}", type_annotation))
})format!(": {type_annotation}"),
3118 Applicability::MaybeIncorrect,
3119 );
3120 }
3121 _ => {
3122 err.span_label(span, msg);
3123 }
3124 }
3125 }
3126 }
3127 _ => {}
3128 }
3129 return Err(err.emit());
3130 }
3131 Ok(())
3132 }
3133
3134 pub(crate) fn suggest_assoc_method_call(&self, segs: &[PathSegment<'_>]) {
3138 {
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:3138",
"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(3138u32),
::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);
3139 let [seg1, seg2] = segs else {
3140 return;
3141 };
3142 self.dcx().try_steal_modify_and_emit_err(
3143 seg1.ident.span,
3144 StashKey::CallAssocMethod,
3145 |err| {
3146 let body = self.tcx.hir_body_owned_by(self.body_id);
3147 struct LetVisitor {
3148 ident_name: Symbol,
3149 }
3150
3151 impl<'v> Visitor<'v> for LetVisitor {
3153 type Result = ControlFlow<Option<&'v hir::Expr<'v>>>;
3154 fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) -> Self::Result {
3155 if let hir::StmtKind::Let(&hir::LetStmt { pat, init, .. }) = ex.kind
3156 && let hir::PatKind::Binding(_, _, ident, ..) = pat.kind
3157 && ident.name == self.ident_name
3158 {
3159 ControlFlow::Break(init)
3160 } else {
3161 hir::intravisit::walk_stmt(self, ex)
3162 }
3163 }
3164 }
3165
3166 if let Node::Expr(call_expr) = self.tcx.parent_hir_node(seg1.hir_id)
3167 && let ControlFlow::Break(Some(expr)) =
3168 (LetVisitor { ident_name: seg1.ident.name }).visit_body(body)
3169 && let Some(self_ty) = self.node_ty_opt(expr.hir_id)
3170 {
3171 let probe = self.lookup_probe_for_diagnostic(
3172 seg2.ident,
3173 self_ty,
3174 call_expr,
3175 ProbeScope::TraitsInScope,
3176 None,
3177 );
3178 if probe.is_ok() {
3179 let sm = self.infcx.tcx.sess.source_map();
3180 err.span_suggestion_verbose(
3181 sm.span_extend_while(seg1.ident.span.shrink_to_hi(), |c| c == ':')
3182 .unwrap(),
3183 "you may have meant to call an instance method",
3184 ".",
3185 Applicability::MaybeIncorrect,
3186 );
3187 }
3188 }
3189 },
3190 );
3191 }
3192
3193 fn suggest_calling_method_on_field(
3195 &self,
3196 err: &mut Diag<'_>,
3197 source: SelfSource<'tcx>,
3198 span: Span,
3199 actual: Ty<'tcx>,
3200 item_name: Ident,
3201 return_type: Option<Ty<'tcx>>,
3202 ) {
3203 if let SelfSource::MethodCall(expr) = source {
3204 let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id();
3205 for fields in self.get_field_candidates_considering_privacy_for_diag(
3206 span,
3207 actual,
3208 mod_id,
3209 expr.hir_id,
3210 ) {
3211 let call_expr = self.tcx.hir_expect_expr(self.tcx.parent_hir_id(expr.hir_id));
3212
3213 let lang_items = self.tcx.lang_items();
3214 let never_mention_traits = [
3215 lang_items.clone_trait(),
3216 lang_items.deref_trait(),
3217 lang_items.deref_mut_trait(),
3218 self.tcx.get_diagnostic_item(sym::AsRef),
3219 self.tcx.get_diagnostic_item(sym::AsMut),
3220 self.tcx.get_diagnostic_item(sym::Borrow),
3221 self.tcx.get_diagnostic_item(sym::BorrowMut),
3222 ];
3223 let mut candidate_fields: Vec<_> = fields
3224 .into_iter()
3225 .filter_map(|candidate_field| {
3226 self.check_for_nested_field_satisfying_condition_for_diag(
3227 span,
3228 &|_, field_ty| {
3229 self.lookup_probe_for_diagnostic(
3230 item_name,
3231 field_ty,
3232 call_expr,
3233 ProbeScope::TraitsInScope,
3234 return_type,
3235 )
3236 .is_ok_and(|pick| {
3237 !never_mention_traits
3238 .iter()
3239 .flatten()
3240 .any(|def_id| self.tcx.parent(pick.item.def_id) == *def_id)
3241 })
3242 },
3243 candidate_field,
3244 ::alloc::vec::Vec::new()vec![],
3245 mod_id,
3246 expr.hir_id,
3247 )
3248 })
3249 .map(|field_path| {
3250 field_path
3251 .iter()
3252 .map(|id| id.to_string())
3253 .collect::<Vec<String>>()
3254 .join(".")
3255 })
3256 .collect();
3257 candidate_fields.sort();
3258
3259 let len = candidate_fields.len();
3260 if len > 0 {
3261 err.span_suggestions(
3262 item_name.span.shrink_to_lo(),
3263 ::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!(
3264 "{} of the expressions' fields {} a method of the same name",
3265 if len > 1 { "some" } else { "one" },
3266 if len > 1 { "have" } else { "has" },
3267 ),
3268 candidate_fields.iter().map(|path| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.", path))
})format!("{path}.")),
3269 Applicability::MaybeIncorrect,
3270 );
3271 }
3272 }
3273 }
3274 }
3275
3276 fn suggest_unwrapping_inner_self(
3277 &self,
3278 err: &mut Diag<'_>,
3279 source: SelfSource<'tcx>,
3280 actual: Ty<'tcx>,
3281 item_name: Ident,
3282 ) {
3283 let tcx = self.tcx;
3284 let SelfSource::MethodCall(expr) = source else {
3285 return;
3286 };
3287 let call_expr = tcx.hir_expect_expr(tcx.parent_hir_id(expr.hir_id));
3288
3289 let ty::Adt(kind, args) = actual.kind() else {
3290 return;
3291 };
3292 match kind.adt_kind() {
3293 ty::AdtKind::Enum => {
3294 let matching_variants: Vec<_> = kind
3295 .variants()
3296 .iter()
3297 .flat_map(|variant| {
3298 let [field] = &variant.fields.raw[..] else {
3299 return None;
3300 };
3301 let field_ty = field.ty(tcx, args).skip_norm_wip();
3302
3303 if self.resolve_vars_if_possible(field_ty).is_ty_var() {
3305 return None;
3306 }
3307
3308 self.lookup_probe_for_diagnostic(
3309 item_name,
3310 field_ty,
3311 call_expr,
3312 ProbeScope::TraitsInScope,
3313 None,
3314 )
3315 .ok()
3316 .map(|pick| (variant, field, pick))
3317 })
3318 .collect();
3319
3320 let ret_ty_matches = |diagnostic_item| {
3321 if let Some(ret_ty) = self
3322 .ret_coercion
3323 .as_ref()
3324 .map(|c| self.resolve_vars_if_possible(c.borrow().expected_ty()))
3325 && let ty::Adt(kind, _) = ret_ty.kind()
3326 && tcx.get_diagnostic_item(diagnostic_item) == Some(kind.did())
3327 {
3328 true
3329 } else {
3330 false
3331 }
3332 };
3333
3334 match &matching_variants[..] {
3335 [(_, field, pick)] => {
3336 let self_ty = field.ty(tcx, args).skip_norm_wip();
3337 err.span_note(
3338 tcx.def_span(pick.item.def_id),
3339 ::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}`"),
3340 );
3341 let (article, kind, variant, question) = if tcx.is_diagnostic_item(sym::Result, kind.did())
3342 && !tcx.hir_is_inside_const_context(expr.hir_id)
3344 {
3345 ("a", "Result", "Err", ret_ty_matches(sym::Result))
3346 } else if tcx.is_diagnostic_item(sym::Option, kind.did()) {
3347 ("an", "Option", "None", ret_ty_matches(sym::Option))
3348 } else {
3349 return;
3350 };
3351 if question {
3352 err.span_suggestion_verbose(
3353 expr.span.shrink_to_hi(),
3354 ::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!(
3355 "use the `?` operator to extract the `{self_ty}` value, propagating \
3356 {article} `{kind}::{variant}` value to the caller"
3357 ),
3358 "?",
3359 Applicability::MachineApplicable,
3360 );
3361 } else {
3362 err.span_suggestion_verbose(
3363 expr.span.shrink_to_hi(),
3364 ::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!(
3365 "consider using `{kind}::expect` to unwrap the `{self_ty}` value, \
3366 panicking if the value is {article} `{kind}::{variant}`"
3367 ),
3368 ".expect(\"REASON\")",
3369 Applicability::HasPlaceholders,
3370 );
3371 }
3372 }
3373 _ => {}
3375 }
3376 }
3377 ty::AdtKind::Struct | ty::AdtKind::Union => {
3380 let [first] = ***args else {
3381 return;
3382 };
3383 let ty::GenericArgKind::Type(ty) = first.kind() else {
3384 return;
3385 };
3386 let Ok(pick) = self.lookup_probe_for_diagnostic(
3387 item_name,
3388 ty,
3389 call_expr,
3390 ProbeScope::TraitsInScope,
3391 None,
3392 ) else {
3393 return;
3394 };
3395
3396 let name = self.ty_to_value_string(actual);
3397 let inner_id = kind.did();
3398 let mutable = if let Some(AutorefOrPtrAdjustment::Autoref { mutbl, .. }) =
3399 pick.autoref_or_ptr_adjustment
3400 {
3401 Some(mutbl)
3402 } else {
3403 None
3404 };
3405
3406 if tcx.is_diagnostic_item(sym::LocalKey, inner_id) {
3407 err.help("use `with` or `try_with` to access thread local storage");
3408 } else if tcx.is_lang_item(kind.did(), LangItem::MaybeUninit) {
3409 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!(
3410 "if this `{name}` has been initialized, \
3411 use one of the `assume_init` methods to access the inner value"
3412 ));
3413 } else if tcx.is_diagnostic_item(sym::RefCell, inner_id) {
3414 let (suggestion, borrow_kind, panic_if) = match mutable {
3415 Some(Mutability::Not) => (".borrow()", "borrow", "a mutable borrow exists"),
3416 Some(Mutability::Mut) => {
3417 (".borrow_mut()", "mutably borrow", "any borrows exist")
3418 }
3419 None => return,
3420 };
3421 err.span_suggestion_verbose(
3422 expr.span.shrink_to_hi(),
3423 ::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!(
3424 "use `{suggestion}` to {borrow_kind} the `{ty}`, \
3425 panicking if {panic_if}"
3426 ),
3427 suggestion,
3428 Applicability::MaybeIncorrect,
3429 );
3430 } else if tcx.is_diagnostic_item(sym::Mutex, inner_id) {
3431 err.span_suggestion_verbose(
3432 expr.span.shrink_to_hi(),
3433 ::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!(
3434 "use `.lock().unwrap()` to borrow the `{ty}`, \
3435 blocking the current thread until it can be acquired"
3436 ),
3437 ".lock().unwrap()",
3438 Applicability::MaybeIncorrect,
3439 );
3440 } else if tcx.is_diagnostic_item(sym::RwLock, inner_id) {
3441 let (suggestion, borrow_kind) = match mutable {
3442 Some(Mutability::Not) => (".read().unwrap()", "borrow"),
3443 Some(Mutability::Mut) => (".write().unwrap()", "mutably borrow"),
3444 None => return,
3445 };
3446 err.span_suggestion_verbose(
3447 expr.span.shrink_to_hi(),
3448 ::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!(
3449 "use `{suggestion}` to {borrow_kind} the `{ty}`, \
3450 blocking the current thread until it can be acquired"
3451 ),
3452 suggestion,
3453 Applicability::MaybeIncorrect,
3454 );
3455 } else {
3456 return;
3457 };
3458
3459 err.span_note(
3460 tcx.def_span(pick.item.def_id),
3461 ::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}`"),
3462 );
3463 }
3464 }
3465 }
3466
3467 pub(crate) fn note_unmet_impls_on_type(
3468 &self,
3469 err: &mut Diag<'_>,
3470 errors: &[FulfillmentError<'tcx>],
3471 suggest_derive: bool,
3472 ) {
3473 let preds: Vec<_> = errors
3474 .iter()
3475 .filter_map(|e| match e.obligation.predicate.kind().skip_binder() {
3476 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
3477 match pred.self_ty().kind() {
3478 ty::Adt(_, _) => Some((e.root_obligation.predicate, pred)),
3479 _ => None,
3480 }
3481 }
3482 _ => None,
3483 })
3484 .collect();
3485
3486 let (mut local_preds, mut foreign_preds): (Vec<_>, Vec<_>) =
3488 preds.iter().partition(|&(_, pred)| {
3489 if let ty::Adt(def, _) = pred.self_ty().kind() {
3490 def.did().is_local()
3491 } else {
3492 false
3493 }
3494 });
3495
3496 local_preds.sort_by_key(|(_, pred)| pred.trait_ref.to_string());
3497 let local_def_ids = local_preds
3498 .iter()
3499 .filter_map(|(_, pred)| match pred.self_ty().kind() {
3500 ty::Adt(def, _) => Some(def.did()),
3501 _ => None,
3502 })
3503 .collect::<FxIndexSet<_>>();
3504 let mut local_spans: MultiSpan = local_def_ids
3505 .iter()
3506 .filter_map(|def_id| {
3507 let span = self.tcx.def_span(*def_id);
3508 if span.is_dummy() { None } else { Some(span) }
3509 })
3510 .collect::<Vec<_>>()
3511 .into();
3512 for (_, pred) in &local_preds {
3513 if let ty::Adt(def, _) = pred.self_ty().kind() {
3514 local_spans.push_span_label(
3515 self.tcx.def_span(def.did()),
3516 ::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()),
3517 );
3518 }
3519 }
3520 if local_spans.primary_span().is_some() {
3521 let msg = if let [(_, local_pred)] = local_preds.as_slice() {
3522 ::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!(
3523 "an implementation of `{}` might be missing for `{}`",
3524 local_pred.trait_ref.print_trait_sugared(),
3525 local_pred.self_ty()
3526 )
3527 } else {
3528 ::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!(
3529 "the following type{} would have to `impl` {} required trait{} for this \
3530 operation to be valid",
3531 pluralize!(local_def_ids.len()),
3532 if local_def_ids.len() == 1 { "its" } else { "their" },
3533 pluralize!(local_preds.len()),
3534 )
3535 };
3536 err.span_note(local_spans, msg);
3537 }
3538
3539 foreign_preds
3540 .sort_by_key(|(_, pred): &(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string());
3541
3542 for (_, pred) in &foreign_preds {
3543 let ty = pred.self_ty();
3544 let ty::Adt(def, _) = ty.kind() else { continue };
3545 let span = self.tcx.def_span(def.did());
3546 if span.is_dummy() {
3547 continue;
3548 }
3549 let mut mspan: MultiSpan = span.into();
3550 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"));
3551 err.span_note(
3552 mspan,
3553 ::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()),
3554 );
3555
3556 foreign_preds.iter().find(|&(root_pred, pred)| {
3557 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3558 root_pred.kind().skip_binder()
3559 && let Some(root_adt) = root_pred.self_ty().ty_adt_def()
3560 {
3561 self.suggest_hashmap_on_unsatisfied_hashset_buildhasher(err, pred, root_adt)
3562 } else {
3563 false
3564 }
3565 });
3566 }
3567
3568 let preds: Vec<_> = errors
3569 .iter()
3570 .map(|e| (e.obligation.predicate, None, Some(e.obligation.cause.clone())))
3571 .collect();
3572 if suggest_derive {
3573 self.suggest_derive(err, &preds);
3574 } else {
3575 let _ = self.note_predicate_source_and_get_derives(err, &preds);
3577 }
3578 }
3579
3580 fn consider_suggesting_derives_for_ty(
3583 &self,
3584 trait_pred: ty::TraitPredicate<'tcx>,
3585 adt: ty::AdtDef<'tcx>,
3586 ) -> Option<Vec<(String, Span, Symbol)>> {
3587 let diagnostic_name = self.tcx.get_diagnostic_name(trait_pred.def_id())?;
3588
3589 let can_derive = match diagnostic_name {
3590 sym::Copy | sym::Clone => true,
3591 _ if adt.is_union() => false,
3592 sym::Default
3593 | sym::Eq
3594 | sym::PartialEq
3595 | sym::Ord
3596 | sym::PartialOrd
3597 | sym::Hash
3598 | sym::Debug => true,
3599 _ => false,
3600 };
3601
3602 if !can_derive {
3603 return None;
3604 }
3605
3606 let trait_def_id = trait_pred.def_id();
3607 let self_ty = trait_pred.self_ty();
3608
3609 if self.tcx.non_blanket_impls_for_ty(trait_def_id, self_ty).any(|impl_def_id| {
3612 self.tcx
3613 .type_of(impl_def_id)
3614 .instantiate_identity()
3615 .skip_norm_wip()
3616 .ty_adt_def()
3617 .is_some_and(|def| def.did() == adt.did())
3618 }) {
3619 return None;
3620 }
3621
3622 let mut derives = Vec::new();
3623 let self_name = self_ty.to_string();
3624 let self_span = self.tcx.def_span(adt.did());
3625
3626 for super_trait in supertraits(self.tcx, ty::Binder::dummy(trait_pred.trait_ref)) {
3627 if let Some(parent_diagnostic_name) = self.tcx.get_diagnostic_name(super_trait.def_id())
3628 {
3629 derives.push((self_name.clone(), self_span, parent_diagnostic_name));
3630 }
3631 }
3632
3633 derives.push((self_name, self_span, diagnostic_name));
3634
3635 Some(derives)
3636 }
3637
3638 fn note_predicate_source_and_get_derives(
3639 &self,
3640 err: &mut Diag<'_>,
3641 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
3642 ) -> Vec<(String, Span, Symbol)> {
3643 let mut derives = Vec::new();
3644 let mut traits = Vec::new();
3645 for (pred, _, _) in unsatisfied_predicates {
3646 let Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred))) =
3647 pred.kind().no_bound_vars()
3648 else {
3649 continue;
3650 };
3651 let adt = match trait_pred.self_ty().ty_adt_def() {
3652 Some(adt) if adt.did().is_local() => adt,
3653 _ => continue,
3654 };
3655 if let Some(new_derives) = self.consider_suggesting_derives_for_ty(trait_pred, adt) {
3656 derives.extend(new_derives);
3657 } else {
3658 traits.push(trait_pred.def_id());
3659 }
3660 }
3661 traits.sort_by_key(|&id| self.tcx.def_path_str(id));
3662 traits.dedup();
3663
3664 let len = traits.len();
3665 if len > 0 {
3666 let span =
3667 MultiSpan::from_spans(traits.iter().map(|&did| self.tcx.def_span(did)).collect());
3668 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]));
3669 for (i, &did) in traits.iter().enumerate().skip(1) {
3670 if len > 2 {
3671 names.push_str(", ");
3672 }
3673 if i == len - 1 {
3674 names.push_str(" and ");
3675 }
3676 names.push('`');
3677 names.push_str(&self.tcx.def_path_str(did));
3678 names.push('`');
3679 }
3680 err.span_note(
3681 span,
3682 ::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),
3683 );
3684 }
3685
3686 derives
3687 }
3688
3689 pub(crate) fn suggest_derive(
3690 &self,
3691 err: &mut Diag<'_>,
3692 unsatisfied_predicates: &UnsatisfiedPredicates<'tcx>,
3693 ) -> bool {
3694 let mut derives = self.note_predicate_source_and_get_derives(err, unsatisfied_predicates);
3695 derives.sort();
3696 derives.dedup();
3697
3698 let mut derives_grouped = Vec::<(String, Span, String)>::new();
3699 for (self_name, self_span, trait_name) in derives.into_iter() {
3700 if let Some((last_self_name, _, last_trait_names)) = derives_grouped.last_mut() {
3701 if last_self_name == &self_name {
3702 last_trait_names.push_str(::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", trait_name))
})format!(", {trait_name}").as_str());
3703 continue;
3704 }
3705 }
3706 derives_grouped.push((self_name, self_span, trait_name.to_string()));
3707 }
3708
3709 for (self_name, self_span, traits) in &derives_grouped {
3710 err.span_suggestion_verbose(
3711 self_span.shrink_to_lo(),
3712 ::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})]`"),
3713 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n", traits))
})format!("#[derive({traits})]\n"),
3714 Applicability::MaybeIncorrect,
3715 );
3716 }
3717 !derives_grouped.is_empty()
3718 }
3719
3720 fn note_derefed_ty_has_method(
3721 &self,
3722 err: &mut Diag<'_>,
3723 self_source: SelfSource<'tcx>,
3724 rcvr_ty: Ty<'tcx>,
3725 item_name: Ident,
3726 expected: Expectation<'tcx>,
3727 ) {
3728 let SelfSource::QPath(ty) = self_source else {
3729 return;
3730 };
3731 for (deref_ty, _) in self.autoderef(DUMMY_SP, rcvr_ty).silence_errors().skip(1) {
3732 if let Ok(pick) = self.probe_for_name(
3733 Mode::Path,
3734 item_name,
3735 expected.only_has_type(self),
3736 IsSuggestion(true),
3737 deref_ty,
3738 ty.hir_id,
3739 ProbeScope::TraitsInScope,
3740 ) {
3741 if deref_ty.is_suggestable(self.tcx, true)
3742 && pick.item.is_method()
3746 && let Some(self_ty) =
3747 self.tcx.fn_sig(pick.item.def_id).instantiate_identity().skip_norm_wip().inputs().skip_binder().get(0)
3748 && self_ty.is_ref()
3749 {
3750 let suggested_path = match deref_ty.kind() {
3751 ty::Bool
3752 | ty::Char
3753 | ty::Int(_)
3754 | ty::Uint(_)
3755 | ty::Float(_)
3756 | ty::Adt(_, _)
3757 | ty::Str
3758 | ty::Alias(ty::AliasTy {
3759 kind: ty::Projection { .. } | ty::Inherent { .. },
3760 ..
3761 })
3762 | ty::Param(_) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", deref_ty))
})format!("{deref_ty}"),
3763 _ if self
3769 .tcx
3770 .sess
3771 .source_map()
3772 .span_wrapped_by_angle_or_parentheses(ty.span) =>
3773 {
3774 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", deref_ty))
})format!("{deref_ty}")
3775 }
3776 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", deref_ty))
})format!("<{deref_ty}>"),
3777 };
3778 err.span_suggestion_verbose(
3779 ty.span,
3780 ::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}`"),
3781 suggested_path,
3782 Applicability::MaybeIncorrect,
3783 );
3784 } else {
3785 err.span_note(
3786 ty.span,
3787 ::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}`"),
3788 );
3789 }
3790 return;
3791 }
3792 }
3793 }
3794
3795 fn suggest_bounds_for_range_to_method(
3796 &self,
3797 err: &mut Diag<'_>,
3798 source: SelfSource<'tcx>,
3799 item_ident: Ident,
3800 ) {
3801 let SelfSource::MethodCall(rcvr_expr) = source else { return };
3802 let hir::ExprKind::Struct(qpath, fields, _) = rcvr_expr.kind else { return };
3803 let Some(lang_item) = self.tcx.qpath_lang_item(*qpath) else {
3804 return;
3805 };
3806 let is_inclusive = match lang_item {
3807 hir::LangItem::RangeTo => false,
3808 hir::LangItem::RangeToInclusive | hir::LangItem::RangeInclusiveCopy => true,
3809 _ => return,
3810 };
3811
3812 let Some(iterator_trait) = self.tcx.get_diagnostic_item(sym::Iterator) else { return };
3813 let Some(_) = self
3814 .tcx
3815 .associated_items(iterator_trait)
3816 .filter_by_name_unhygienic(item_ident.name)
3817 .next()
3818 else {
3819 return;
3820 };
3821
3822 let source_map = self.tcx.sess.source_map();
3823 let range_type = if is_inclusive { "RangeInclusive" } else { "Range" };
3824 let Some(end_field) = fields.iter().find(|f| f.ident.name == rustc_span::sym::end) else {
3825 return;
3826 };
3827
3828 let element_ty = self.typeck_results.borrow().expr_ty_opt(end_field.expr);
3829 let is_integral = element_ty.is_some_and(|ty| ty.is_integral());
3830 let end_is_negative = is_integral
3831 && #[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, _));
3832
3833 let Ok(snippet) = source_map.span_to_snippet(rcvr_expr.span) else { return };
3834
3835 let offset = snippet
3836 .chars()
3837 .take_while(|&c| c == '(' || c.is_whitespace())
3838 .map(|c| c.len_utf8())
3839 .sum::<usize>();
3840
3841 let insert_span = rcvr_expr
3842 .span
3843 .with_lo(rcvr_expr.span.lo() + rustc_span::BytePos(offset as u32))
3844 .shrink_to_lo();
3845
3846 let (value, appl) = if is_integral && !end_is_negative {
3847 ("0", Applicability::MachineApplicable)
3848 } else {
3849 ("/* start */", Applicability::HasPlaceholders)
3850 };
3851
3852 err.span_suggestion_verbose(
3853 insert_span,
3854 ::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"),
3855 value,
3856 appl,
3857 );
3858 }
3859
3860 fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String {
3862 match ty.kind() {
3863 ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), args),
3864 _ => self.ty_to_string(ty),
3865 }
3866 }
3867
3868 fn suggest_await_before_method(
3869 &self,
3870 err: &mut Diag<'_>,
3871 item_name: Ident,
3872 ty: Ty<'tcx>,
3873 call: &hir::Expr<'_>,
3874 span: Span,
3875 return_type: Option<Ty<'tcx>>,
3876 ) {
3877 let Some(output_ty) = self.err_ctxt().get_impl_future_output_ty(ty) else { return };
3878 let output_ty = self.resolve_vars_if_possible(output_ty);
3879 let method_exists =
3880 self.method_exists_for_diagnostic(item_name, output_ty, call.hir_id, return_type);
3881 {
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:3881",
"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(3881u32),
::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);
3882 if method_exists {
3883 err.span_suggestion_verbose(
3884 span.shrink_to_lo(),
3885 "consider `await`ing on the `Future` and calling the method on its `Output`",
3886 "await.",
3887 Applicability::MaybeIncorrect,
3888 );
3889 }
3890 }
3891
3892 fn set_label_for_method_error(
3893 &self,
3894 err: &mut Diag<'_>,
3895 source: SelfSource<'tcx>,
3896 rcvr_ty: Ty<'tcx>,
3897 item_ident: Ident,
3898 expr_id: hir::HirId,
3899 span: Span,
3900 sugg_span: Span,
3901 within_macro_span: Option<Span>,
3902 args: Option<&'tcx [hir::Expr<'tcx>]>,
3903 ) {
3904 let tcx = self.tcx;
3905 if tcx.sess.source_map().is_multiline(sugg_span) {
3906 err.span_label(sugg_span.with_hi(span.lo()), "");
3907 }
3908 if let Some(within_macro_span) = within_macro_span {
3909 err.span_label(within_macro_span, "due to this macro variable");
3910 }
3911
3912 if #[allow(non_exhaustive_omitted_patterns)] match source {
SelfSource::QPath(_) => true,
_ => false,
}matches!(source, SelfSource::QPath(_)) && args.is_some() {
3913 self.find_builder_fn(err, rcvr_ty, expr_id);
3914 }
3915
3916 if tcx.ty_is_opaque_future(rcvr_ty) && item_ident.name == sym::poll {
3917 let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
3918 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!(
3919 "method `poll` found on `Pin<&mut {ty_str}>`, \
3920 see documentation for `std::pin::Pin`"
3921 ));
3922 err.help(
3923 "self type must be pinned to call `Future::poll`, \
3924 see https://rust-lang.github.io/async-book/part-reference/pinning.html",
3925 );
3926 }
3927
3928 if let Some(span) =
3929 tcx.resolutions(()).confused_type_with_std_module.get(&span.with_parent(None))
3930 {
3931 err.span_suggestion(
3932 span.shrink_to_lo(),
3933 "you are looking for the module in `std`, not the primitive type",
3934 "std::",
3935 Applicability::MachineApplicable,
3936 );
3937 }
3938 }
3939
3940 fn suggest_on_pointer_type(
3941 &self,
3942 err: &mut Diag<'_>,
3943 source: SelfSource<'tcx>,
3944 rcvr_ty: Ty<'tcx>,
3945 item_ident: Ident,
3946 ) {
3947 let tcx = self.tcx;
3948 if let SelfSource::MethodCall(rcvr_expr) = source
3950 && let ty::RawPtr(ty, ptr_mutbl) = *rcvr_ty.kind()
3951 && let Ok(pick) = self.lookup_probe_for_diagnostic(
3952 item_ident,
3953 Ty::new_ref(tcx, ty::Region::new_error_misc(tcx), ty, ptr_mutbl),
3954 self.tcx.hir_expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id)),
3955 ProbeScope::TraitsInScope,
3956 None,
3957 )
3958 && let ty::Ref(_, _, sugg_mutbl) = *pick.self_ty.kind()
3959 && (sugg_mutbl.is_not() || ptr_mutbl.is_mut())
3960 {
3961 let (method, method_anchor) = match sugg_mutbl {
3962 Mutability::Not => {
3963 let method_anchor = match ptr_mutbl {
3964 Mutability::Not => "as_ref",
3965 Mutability::Mut => "as_ref-1",
3966 };
3967 ("as_ref", method_anchor)
3968 }
3969 Mutability::Mut => ("as_mut", "as_mut"),
3970 };
3971 err.span_note(
3972 tcx.def_span(pick.item.def_id),
3973 ::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),
3974 );
3975 let mut_str = ptr_mutbl.ptr_str();
3976 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!(
3977 "you might want to use the unsafe method `<*{mut_str} T>::{method}` to get \
3978 an optional reference to the value behind the pointer"
3979 ));
3980 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!(
3981 "read the documentation for `<*{mut_str} T>::{method}` and ensure you satisfy its \
3982 safety preconditions before calling it to avoid undefined behavior: \
3983 https://doc.rust-lang.org/std/primitive.pointer.html#method.{method_anchor}"
3984 ));
3985 }
3986 }
3987
3988 fn suggest_use_candidates<F>(&self, candidates: Vec<DefId>, handle_candidates: F)
3989 where
3990 F: FnOnce(Vec<String>, Vec<String>, Span),
3991 {
3992 let parent_map = self.tcx.visible_parent_map(());
3993
3994 let scope = self.tcx.parent_module_from_def_id(self.body_id);
3995 let (accessible_candidates, inaccessible_candidates): (Vec<_>, Vec<_>) =
3996 candidates.into_iter().partition(|id| {
3997 let vis = self.tcx.visibility(*id);
3998 vis.is_accessible_from(scope, self.tcx)
3999 });
4000
4001 let sugg = |candidates: Vec<_>, visible| {
4002 let (candidates, globs): (Vec<_>, Vec<_>) =
4005 candidates.into_iter().partition(|trait_did| {
4006 if let Some(parent_did) = parent_map.get(trait_did) {
4007 if *parent_did != self.tcx.parent(*trait_did)
4009 && self
4010 .tcx
4011 .module_children(*parent_did)
4012 .iter()
4013 .filter(|child| child.res.opt_def_id() == Some(*trait_did))
4014 .all(|child| child.ident.name == kw::Underscore)
4015 {
4016 return false;
4017 }
4018 }
4019
4020 true
4021 });
4022
4023 let prefix = if visible { "use " } else { "" };
4024 let postfix = if visible { ";" } else { "" };
4025 let path_strings = candidates.iter().map(|trait_did| {
4026 ::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!(
4027 "{prefix}{}{postfix}\n",
4028 with_no_visible_paths_if_doc_hidden!(with_crate_prefix!(
4029 self.tcx.def_path_str(*trait_did)
4030 )),
4031 )
4032 });
4033
4034 let glob_path_strings = globs.iter().map(|trait_did| {
4035 let parent_did = parent_map.get(trait_did).unwrap();
4036 ::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!(
4037 "{prefix}{}::*{postfix} // trait {}\n",
4038 with_no_visible_paths_if_doc_hidden!(with_crate_prefix!(
4039 self.tcx.def_path_str(*parent_did)
4040 )),
4041 self.tcx.item_name(*trait_did),
4042 )
4043 });
4044 let mut sugg: Vec<_> = path_strings.chain(glob_path_strings).collect();
4045 sugg.sort();
4046 sugg
4047 };
4048
4049 let accessible_sugg = sugg(accessible_candidates, true);
4050 let inaccessible_sugg = sugg(inaccessible_candidates, false);
4051
4052 let (module, _, _) = self.tcx.hir_get_module(scope);
4053 let span = module.spans.inject_use_span;
4054 handle_candidates(accessible_sugg, inaccessible_sugg, span);
4055 }
4056
4057 fn suggest_valid_traits(
4058 &self,
4059 err: &mut Diag<'_>,
4060 item_name: Ident,
4061 mut valid_out_of_scope_traits: Vec<DefId>,
4062 explain: bool,
4063 ) -> bool {
4064 valid_out_of_scope_traits.retain(|id| self.tcx.is_user_visible_dep(id.krate));
4065 if !valid_out_of_scope_traits.is_empty() {
4066 let mut candidates = valid_out_of_scope_traits;
4067 candidates.sort_by_key(|&id| self.tcx.def_path_str(id));
4068 candidates.dedup();
4069
4070 let edition_fix = candidates
4072 .iter()
4073 .find(|did| self.tcx.is_diagnostic_item(sym::TryInto, **did))
4074 .copied();
4075
4076 if explain {
4077 err.help("items from traits can only be used if the trait is in scope");
4078 }
4079
4080 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!(
4081 "{this_trait_is} implemented but not in scope",
4082 this_trait_is = if candidates.len() == 1 {
4083 format!(
4084 "trait `{}` which provides `{item_name}` is",
4085 self.tcx.item_name(candidates[0]),
4086 )
4087 } else {
4088 format!("the following traits which provide `{item_name}` are")
4089 }
4090 );
4091
4092 self.suggest_use_candidates(candidates, |accessible_sugg, inaccessible_sugg, span| {
4093 let suggest_for_access = |err: &mut Diag<'_>, mut msg: String, suggs: Vec<_>| {
4094 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!(
4095 "; perhaps you want to import {one_of}",
4096 one_of = if suggs.len() == 1 { "it" } else { "one of them" },
4097 );
4098 err.span_suggestions(span, msg, suggs, Applicability::MaybeIncorrect);
4099 };
4100 let suggest_for_privacy = |err: &mut Diag<'_>, suggs: Vec<String>| {
4101 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!(
4102 "{this_trait_is} implemented but not reachable",
4103 this_trait_is = if let [sugg] = suggs.as_slice() {
4104 format!("trait `{}` which provides `{item_name}` is", sugg.trim())
4105 } else {
4106 format!("the following traits which provide `{item_name}` are")
4107 }
4108 );
4109 if suggs.len() == 1 {
4110 err.help(msg);
4111 } else {
4112 err.span_suggestions(span, msg, suggs, Applicability::MaybeIncorrect);
4113 }
4114 };
4115 if accessible_sugg.is_empty() {
4116 suggest_for_privacy(err, inaccessible_sugg);
4118 } else if inaccessible_sugg.is_empty() {
4119 suggest_for_access(err, msg, accessible_sugg);
4120 } else {
4121 suggest_for_access(err, msg, accessible_sugg);
4122 suggest_for_privacy(err, inaccessible_sugg);
4123 }
4124 });
4125
4126 if let Some(did) = edition_fix {
4127 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!(
4128 "'{}' is included in the prelude starting in Edition 2021",
4129 with_crate_prefix!(self.tcx.def_path_str(did))
4130 ));
4131 }
4132
4133 true
4134 } else {
4135 false
4136 }
4137 }
4138
4139 fn suggest_traits_to_import(
4140 &self,
4141 err: &mut Diag<'_>,
4142 span: Span,
4143 rcvr_ty: Ty<'tcx>,
4144 item_name: Ident,
4145 inputs_len: Option<usize>,
4146 source: SelfSource<'tcx>,
4147 valid_out_of_scope_traits: Vec<DefId>,
4148 static_candidates: &[CandidateSource],
4149 unsatisfied_bounds: bool,
4150 return_type: Option<Ty<'tcx>>,
4151 trait_missing_method: bool,
4152 ) {
4153 let mut alt_rcvr_sugg = false;
4154 let mut trait_in_other_version_found = false;
4155 if let (SelfSource::MethodCall(rcvr), false) = (source, unsatisfied_bounds) {
4156 {
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:4156",
"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(4156u32),
::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!(
4157 "suggest_traits_to_import: span={:?}, item_name={:?}, rcvr_ty={:?}, rcvr={:?}",
4158 span, item_name, rcvr_ty, rcvr
4159 );
4160 let skippable = [
4161 self.tcx.lang_items().clone_trait(),
4162 self.tcx.lang_items().deref_trait(),
4163 self.tcx.lang_items().deref_mut_trait(),
4164 self.tcx.lang_items().drop_trait(),
4165 self.tcx.get_diagnostic_item(sym::AsRef),
4166 ];
4167 for (rcvr_ty, post, pin_call) in &[
4171 (rcvr_ty, "", None),
4172 (
4173 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty),
4174 "&mut ",
4175 Some("as_mut"),
4176 ),
4177 (
4178 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty),
4179 "&",
4180 Some("as_ref"),
4181 ),
4182 ] {
4183 match self.lookup_probe_for_diagnostic(
4184 item_name,
4185 *rcvr_ty,
4186 rcvr,
4187 ProbeScope::AllTraits,
4188 return_type,
4189 ) {
4190 Ok(pick) => {
4191 let did = Some(pick.item.container_id(self.tcx));
4196 if skippable.contains(&did) {
4197 continue;
4198 }
4199 trait_in_other_version_found = self
4200 .detect_and_explain_multiple_crate_versions_of_trait_item(
4201 err,
4202 pick.item.def_id,
4203 rcvr.hir_id,
4204 Some(*rcvr_ty),
4205 );
4206 if pick.autoderefs == 0 && !trait_in_other_version_found {
4207 err.span_label(
4208 pick.item.ident(self.tcx).span,
4209 ::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"),
4210 );
4211 }
4212 break;
4213 }
4214 Err(MethodError::Ambiguity(_)) => {
4215 break;
4220 }
4221 Err(_) => (),
4222 }
4223
4224 let Some(unpin_trait) = self.tcx.lang_items().unpin_trait() else {
4225 return;
4226 };
4227 let pred = ty::TraitRef::new(self.tcx, unpin_trait, [*rcvr_ty]);
4228 let unpin = self.predicate_must_hold_considering_regions(&Obligation::new(
4229 self.tcx,
4230 self.misc(rcvr.span),
4231 self.param_env,
4232 pred,
4233 ));
4234 for (rcvr_ty, pre) in &[
4235 (Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::OwnedBox), "Box::new"),
4236 (Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::Pin), "Pin::new"),
4237 (Ty::new_diagnostic_item(self.tcx, *rcvr_ty, sym::Arc), "Arc::new"),
4238 (Ty::new_diagnostic_item(self.tcx, *rcvr_ty, sym::Rc), "Rc::new"),
4239 ] {
4240 if let Some(new_rcvr_t) = *rcvr_ty
4241 && let Ok(pick) = self.lookup_probe_for_diagnostic(
4242 item_name,
4243 new_rcvr_t,
4244 rcvr,
4245 ProbeScope::AllTraits,
4246 return_type,
4247 )
4248 {
4249 {
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:4249",
"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(4249u32),
::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);
4250 let did = pick.item.trait_container(self.tcx);
4251 let skip = skippable.contains(&did)
4257 || (("Pin::new" == *pre)
4258 && ((sym::as_ref == item_name.name) || !unpin))
4259 || inputs_len.is_some_and(|inputs_len| {
4260 pick.item.is_fn()
4261 && self
4262 .tcx
4263 .fn_sig(pick.item.def_id)
4264 .skip_binder()
4265 .skip_binder()
4266 .inputs()
4267 .len()
4268 != inputs_len
4269 });
4270 if pick.autoderefs == 0 && !skip {
4274 err.span_label(
4275 pick.item.ident(self.tcx).span,
4276 ::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"),
4277 );
4278 err.multipart_suggestion(
4279 "consider wrapping the receiver expression with the \
4280 appropriate type",
4281 ::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![
4282 (rcvr.span.shrink_to_lo(), format!("{pre}({post}")),
4283 (rcvr.span.shrink_to_hi(), ")".to_string()),
4284 ],
4285 Applicability::MaybeIncorrect,
4286 );
4287 alt_rcvr_sugg = true;
4289 }
4290 }
4291 }
4292 if let Some(new_rcvr_t) = Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::Pin)
4295 && !alt_rcvr_sugg
4297 && !unpin
4299 && let Some(pin_call) = pin_call
4301 && let Ok(pick) = self.lookup_probe_for_diagnostic(
4303 item_name,
4304 new_rcvr_t,
4305 rcvr,
4306 ProbeScope::AllTraits,
4307 return_type,
4308 )
4309 && !skippable.contains(&Some(pick.item.container_id(self.tcx)))
4312 && pick.item.impl_container(self.tcx).is_none_or(|did| {
4314 match self.tcx.type_of(did).skip_binder().kind() {
4315 ty::Adt(def, _) => Some(def.did()) != self.tcx.lang_items().pin_type(),
4316 _ => true,
4317 }
4318 })
4319 && pick.autoderefs == 0
4321 && 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)
4324 {
4325 let indent = self
4326 .tcx
4327 .sess
4328 .source_map()
4329 .indentation_before(rcvr.span)
4330 .unwrap_or_else(|| " ".to_string());
4331 let mut expr = rcvr;
4332 while let Node::Expr(call_expr) = self.tcx.parent_hir_node(expr.hir_id)
4333 && let hir::ExprKind::MethodCall(hir::PathSegment { .. }, ..) =
4334 call_expr.kind
4335 {
4336 expr = call_expr;
4337 }
4338 match self.tcx.parent_hir_node(expr.hir_id) {
4339 Node::LetStmt(stmt)
4340 if let Some(init) = stmt.init
4341 && let Ok(code) =
4342 self.tcx.sess.source_map().span_to_snippet(rcvr.span) =>
4343 {
4344 err.multipart_suggestion(
4347 "consider pinning the expression",
4348 ::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![
4349 (
4350 stmt.span.shrink_to_lo(),
4351 format!(
4352 "let mut pinned = std::pin::pin!({code});\n{indent}"
4353 ),
4354 ),
4355 (
4356 init.span.until(rcvr.span.shrink_to_hi()),
4357 format!("pinned.{pin_call}()"),
4358 ),
4359 ],
4360 Applicability::MaybeIncorrect,
4361 );
4362 }
4363 Node::Block(_) | Node::Stmt(_) => {
4364 err.multipart_suggestion(
4367 "consider pinning the expression",
4368 ::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![
4369 (
4370 rcvr.span.shrink_to_lo(),
4371 "let mut pinned = std::pin::pin!(".to_string(),
4372 ),
4373 (
4374 rcvr.span.shrink_to_hi(),
4375 format!(");\n{indent}pinned.{pin_call}()"),
4376 ),
4377 ],
4378 Applicability::MaybeIncorrect,
4379 );
4380 }
4381 _ => {
4382 err.span_help(
4385 rcvr.span,
4386 "consider pinning the expression with `std::pin::pin!()` and \
4387 assigning that to a new binding",
4388 );
4389 }
4390 }
4391 alt_rcvr_sugg = true;
4393 }
4394 }
4395 }
4396
4397 if let SelfSource::QPath(ty) = source
4398 && !valid_out_of_scope_traits.is_empty()
4399 && let hir::TyKind::Path(path) = ty.kind
4400 && let hir::QPath::Resolved(..) = path
4401 && let Some(assoc) = self
4402 .tcx
4403 .associated_items(valid_out_of_scope_traits[0])
4404 .filter_by_name_unhygienic(item_name.name)
4405 .next()
4406 {
4407 let rcvr_ty = self.node_ty_opt(ty.hir_id);
4412 trait_in_other_version_found = self
4413 .detect_and_explain_multiple_crate_versions_of_trait_item(
4414 err,
4415 assoc.def_id,
4416 ty.hir_id,
4417 rcvr_ty,
4418 );
4419 }
4420 if !trait_in_other_version_found
4421 && self.suggest_valid_traits(err, item_name, valid_out_of_scope_traits, true)
4422 {
4423 return;
4424 }
4425
4426 let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
4427
4428 let mut arbitrary_rcvr = ::alloc::vec::Vec::new()vec![];
4429 let mut candidates = all_traits(self.tcx)
4433 .into_iter()
4434 .filter(|info| match self.tcx.lookup_stability(info.def_id) {
4437 Some(attr) => attr.level.is_stable(),
4438 None => true,
4439 })
4440 .filter(|info| {
4441 static_candidates.iter().all(|sc| match *sc {
4444 CandidateSource::Trait(def_id) => def_id != info.def_id,
4445 CandidateSource::Impl(def_id) => {
4446 self.tcx.impl_opt_trait_id(def_id) != Some(info.def_id)
4447 }
4448 })
4449 })
4450 .filter(|info| {
4451 (type_is_local || info.def_id.is_local())
4458 && !self.tcx.trait_is_auto(info.def_id)
4459 && self
4460 .associated_value(info.def_id, item_name)
4461 .filter(|item| {
4462 if item.is_fn() {
4463 let id = item
4464 .def_id
4465 .as_local()
4466 .map(|def_id| self.tcx.hir_node_by_def_id(def_id));
4467 if let Some(hir::Node::TraitItem(hir::TraitItem {
4468 kind: hir::TraitItemKind::Fn(fn_sig, method),
4469 ..
4470 })) = id
4471 {
4472 let self_first_arg = match method {
4473 hir::TraitFn::Required([ident, ..]) => {
4474 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
4475 }
4476 hir::TraitFn::Provided(body_id) => {
4477 self.tcx.hir_body(*body_id).params.first().is_some_and(
4478 |param| {
4479 #[allow(non_exhaustive_omitted_patterns)] match param.pat.kind {
hir::PatKind::Binding(_, _, ident, _) if ident.name == kw::SelfLower =>
true,
_ => false,
}matches!(
4480 param.pat.kind,
4481 hir::PatKind::Binding(_, _, ident, _)
4482 if ident.name == kw::SelfLower
4483 )
4484 },
4485 )
4486 }
4487 _ => false,
4488 };
4489
4490 if !fn_sig.decl.implicit_self().has_implicit_self()
4491 && self_first_arg
4492 {
4493 if let Some(ty) = fn_sig.decl.inputs.get(0) {
4494 arbitrary_rcvr.push(ty.span);
4495 }
4496 return false;
4497 }
4498 }
4499 }
4500 item.visibility(self.tcx).is_public() || info.def_id.is_local()
4502 })
4503 .is_some()
4504 })
4505 .collect::<Vec<_>>();
4506 for span in &arbitrary_rcvr {
4507 err.span_label(
4508 *span,
4509 "the method might not be found because of this arbitrary self type",
4510 );
4511 }
4512 if alt_rcvr_sugg {
4513 return;
4514 }
4515
4516 if !candidates.is_empty() {
4517 candidates
4519 .sort_by_key(|&info| (!info.def_id.is_local(), self.tcx.def_path_str(info.def_id)));
4520 candidates.dedup();
4521
4522 let param_type = match *rcvr_ty.kind() {
4523 ty::Param(param) => Some(param),
4524 ty::Ref(_, ty, _) => match *ty.kind() {
4525 ty::Param(param) => Some(param),
4526 _ => None,
4527 },
4528 _ => None,
4529 };
4530 if !trait_missing_method {
4531 err.help(if param_type.is_some() {
4532 "items from traits can only be used if the type parameter is bounded by the trait"
4533 } else {
4534 "items from traits can only be used if the trait is implemented and in scope"
4535 });
4536 }
4537
4538 let candidates_len = candidates.len();
4539 let message = |action| {
4540 ::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!(
4541 "the following {traits_define} an item `{name}`, perhaps you need to {action} \
4542 {one_of_them}:",
4543 traits_define =
4544 if candidates_len == 1 { "trait defines" } else { "traits define" },
4545 action = action,
4546 one_of_them = if candidates_len == 1 { "it" } else { "one of them" },
4547 name = item_name,
4548 )
4549 };
4550 if let Some(param) = param_type {
4552 let generics = self.tcx.generics_of(self.body_id.to_def_id());
4553 let type_param = generics.type_param(param, self.tcx);
4554 let tcx = self.tcx;
4555 if let Some(def_id) = type_param.def_id.as_local() {
4556 let id = tcx.local_def_id_to_hir_id(def_id);
4557 match tcx.hir_node(id) {
4561 Node::GenericParam(param) => {
4562 enum Introducer {
4563 Plus,
4564 Colon,
4565 Nothing,
4566 }
4567 let hir_generics = tcx.hir_get_generics(id.owner.def_id).unwrap();
4568 let trait_def_ids: DefIdSet = hir_generics
4569 .bounds_for_param(def_id)
4570 .flat_map(|bp| bp.bounds.iter())
4571 .filter_map(|bound| bound.trait_ref()?.trait_def_id())
4572 .collect();
4573 if candidates.iter().any(|t| trait_def_ids.contains(&t.def_id)) {
4574 return;
4575 }
4576 let msg = message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("restrict type parameter `{0}` with",
param.name.ident()))
})format!(
4577 "restrict type parameter `{}` with",
4578 param.name.ident(),
4579 ));
4580 let bounds_span = hir_generics.bounds_span_for_suggestions(def_id);
4581 let mut applicability = Applicability::MaybeIncorrect;
4582 let candidate_strs: Vec<_> = candidates
4585 .iter()
4586 .map(|cand| {
4587 let cand_path = tcx.def_path_str(cand.def_id);
4588 let cand_params = &tcx.generics_of(cand.def_id).own_params;
4589 let cand_args: String = cand_params
4590 .iter()
4591 .skip(1)
4592 .filter_map(|param| match param.kind {
4593 ty::GenericParamDefKind::Type {
4594 has_default: true,
4595 ..
4596 }
4597 | ty::GenericParamDefKind::Const {
4598 has_default: true,
4599 ..
4600 } => None,
4601 _ => Some(param.name.as_str()),
4602 })
4603 .intersperse(", ")
4604 .collect();
4605 if cand_args.is_empty() {
4606 cand_path
4607 } else {
4608 applicability = Applicability::HasPlaceholders;
4609 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}</* {1} */>", cand_path,
cand_args))
})format!("{cand_path}</* {cand_args} */>")
4610 }
4611 })
4612 .collect();
4613
4614 if rcvr_ty.is_ref()
4615 && param.is_impl_trait()
4616 && let Some((bounds_span, _)) = bounds_span
4617 {
4618 err.multipart_suggestions(
4619 msg,
4620 candidate_strs.iter().map(|cand| {
4621 ::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![
4622 (param.span.shrink_to_lo(), "(".to_string()),
4623 (bounds_span, format!(" + {cand})")),
4624 ]
4625 }),
4626 applicability,
4627 );
4628 return;
4629 }
4630
4631 let (sp, introducer, open_paren_sp) =
4632 if let Some((span, open_paren_sp)) = bounds_span {
4633 (span, Introducer::Plus, open_paren_sp)
4634 } else if let Some(colon_span) = param.colon_span {
4635 (colon_span.shrink_to_hi(), Introducer::Nothing, None)
4636 } else if param.is_impl_trait() {
4637 (param.span.shrink_to_hi(), Introducer::Plus, None)
4638 } else {
4639 (param.span.shrink_to_hi(), Introducer::Colon, None)
4640 };
4641
4642 let all_suggs = candidate_strs.iter().map(|cand| {
4643 let suggestion = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}",
match introducer {
Introducer::Plus => " +",
Introducer::Colon => ":",
Introducer::Nothing => "",
}, cand))
})format!(
4644 "{} {cand}",
4645 match introducer {
4646 Introducer::Plus => " +",
4647 Introducer::Colon => ":",
4648 Introducer::Nothing => "",
4649 },
4650 );
4651
4652 let mut suggs = ::alloc::vec::Vec::new()vec![];
4653
4654 if let Some(open_paren_sp) = open_paren_sp {
4655 suggs.push((open_paren_sp, "(".to_string()));
4656 suggs.push((sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("){0}", suggestion))
})format!("){suggestion}")));
4657 } else {
4658 suggs.push((sp, suggestion));
4659 }
4660
4661 suggs
4662 });
4663
4664 err.multipart_suggestions(msg, all_suggs, applicability);
4665
4666 return;
4667 }
4668 Node::Item(hir::Item {
4669 kind: hir::ItemKind::Trait { ident, bounds, .. },
4670 ..
4671 }) => {
4672 let (sp, sep, article) = if bounds.is_empty() {
4673 (ident.span.shrink_to_hi(), ":", "a")
4674 } else {
4675 (bounds.last().unwrap().span().shrink_to_hi(), " +", "another")
4676 };
4677 err.span_suggestions(
4678 sp,
4679 message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add {0} supertrait for", article))
})format!("add {article} supertrait for")),
4680 candidates
4681 .iter()
4682 .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),)),
4683 Applicability::MaybeIncorrect,
4684 );
4685 return;
4686 }
4687 _ => {}
4688 }
4689 }
4690 }
4691
4692 let (potential_candidates, explicitly_negative) = if param_type.is_some() {
4693 (candidates, Vec::new())
4696 } else if let Some(simp_rcvr_ty) =
4697 simplify_type(self.tcx, rcvr_ty, TreatParams::AsRigid)
4698 {
4699 let mut potential_candidates = Vec::new();
4700 let mut explicitly_negative = Vec::new();
4701 for candidate in candidates {
4702 if self
4704 .tcx
4705 .all_impls(candidate.def_id)
4706 .map(|imp_did| self.tcx.impl_trait_header(imp_did))
4707 .filter(|header| header.polarity != ty::ImplPolarity::Positive)
4708 .any(|header| {
4709 let imp = header.trait_ref.instantiate_identity().skip_norm_wip();
4710 let imp_simp =
4711 simplify_type(self.tcx, imp.self_ty(), TreatParams::AsRigid);
4712 imp_simp.is_some_and(|s| s == simp_rcvr_ty)
4713 })
4714 {
4715 explicitly_negative.push(candidate);
4716 } else {
4717 potential_candidates.push(candidate);
4718 }
4719 }
4720 (potential_candidates, explicitly_negative)
4721 } else {
4722 (candidates, Vec::new())
4724 };
4725
4726 let impls_trait = |def_id: DefId| {
4727 let args = ty::GenericArgs::for_item(self.tcx, def_id, |param, _| {
4728 if param.index == 0 {
4729 rcvr_ty.into()
4730 } else {
4731 self.infcx.var_for_def(span, param)
4732 }
4733 });
4734 self.infcx
4735 .type_implements_trait(def_id, args, self.param_env)
4736 .must_apply_modulo_regions()
4737 && param_type.is_none()
4738 };
4739 match &potential_candidates[..] {
4740 [] => {}
4741 [trait_info] if trait_info.def_id.is_local() => {
4742 if impls_trait(trait_info.def_id) {
4743 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);
4744 } else {
4745 err.subdiagnostic(CandidateTraitNote {
4746 span: self.tcx.def_span(trait_info.def_id),
4747 trait_name: self.tcx.def_path_str(trait_info.def_id),
4748 item_name,
4749 action_or_ty: if trait_missing_method {
4750 "NONE".to_string()
4751 } else {
4752 param_type.map_or_else(
4753 || "implement".to_string(), |p| p.to_string(),
4755 )
4756 },
4757 });
4758 }
4759 }
4760 trait_infos => {
4761 let mut msg = message(param_type.map_or_else(
4762 || "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"),
4764 ));
4765 for (i, trait_info) in trait_infos.iter().enumerate() {
4766 if impls_trait(trait_info.def_id) {
4767 self.suggest_valid_traits(
4768 err,
4769 item_name,
4770 ::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],
4771 false,
4772 );
4773 }
4774 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!(
4775 "\ncandidate #{}: `{}`",
4776 i + 1,
4777 self.tcx.def_path_str(trait_info.def_id),
4778 ));
4779 }
4780 err.note(msg);
4781 }
4782 }
4783 match &explicitly_negative[..] {
4784 [] => {}
4785 [trait_info] => {
4786 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!(
4787 "the trait `{}` defines an item `{}`, but is explicitly unimplemented",
4788 self.tcx.def_path_str(trait_info.def_id),
4789 item_name
4790 );
4791 err.note(msg);
4792 }
4793 trait_infos => {
4794 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!(
4795 "the following traits define an item `{item_name}`, but are explicitly unimplemented:"
4796 );
4797 for trait_info in trait_infos {
4798 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)));
4799 }
4800 err.note(msg);
4801 }
4802 }
4803 }
4804 }
4805
4806 fn detect_and_explain_multiple_crate_versions_of_trait_item(
4807 &self,
4808 err: &mut Diag<'_>,
4809 item_def_id: DefId,
4810 hir_id: hir::HirId,
4811 rcvr_ty: Option<Ty<'tcx>>,
4812 ) -> bool {
4813 let hir_id = self.tcx.parent_hir_id(hir_id);
4814 let Some(traits) = self.tcx.in_scope_traits(hir_id) else { return false };
4815 if traits.is_empty() {
4816 return false;
4817 }
4818 let trait_def_id = self.tcx.parent(item_def_id);
4819 if !self.tcx.is_trait(trait_def_id) {
4820 return false;
4821 }
4822 let hir::Node::Expr(rcvr) = self.tcx.hir_node(hir_id) else {
4823 return false;
4824 };
4825 let trait_ref = ty::TraitRef::new_from_args(
4831 self.tcx,
4832 trait_def_id,
4833 ty::GenericArgs::for_item(self.tcx, trait_def_id, |param, _| {
4834 if param.index == 0
4835 && let Some(rcvr_ty) = rcvr_ty
4836 {
4837 rcvr_ty.into()
4838 } else {
4839 self.var_for_def(rcvr.span, param)
4840 }
4841 }),
4842 );
4843 let trait_pred = ty::Binder::dummy(ty::TraitPredicate {
4844 trait_ref,
4845 polarity: ty::PredicatePolarity::Positive,
4846 });
4847 let obligation = Obligation::new(self.tcx, self.misc(rcvr.span), self.param_env, trait_ref);
4848 self.err_ctxt().note_different_trait_with_same_name(err, &obligation, trait_pred)
4849 }
4850
4851 pub(crate) fn suggest_else_fn_with_closure(
4854 &self,
4855 err: &mut Diag<'_>,
4856 expr: &hir::Expr<'_>,
4857 found: Ty<'tcx>,
4858 expected: Ty<'tcx>,
4859 ) -> bool {
4860 let Some((_def_id_or_name, output, _inputs)) = self.extract_callable_info(found) else {
4861 return false;
4862 };
4863
4864 if !self.may_coerce(output, expected) {
4865 return false;
4866 }
4867
4868 if let Node::Expr(call_expr) = self.tcx.parent_hir_node(expr.hir_id)
4869 && let hir::ExprKind::MethodCall(
4870 hir::PathSegment { ident: method_name, .. },
4871 self_expr,
4872 args,
4873 ..,
4874 ) = call_expr.kind
4875 && let Some(self_ty) = self.typeck_results.borrow().expr_ty_opt(self_expr)
4876 {
4877 let new_name = Ident {
4878 name: Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_else", method_name.as_str()))
})format!("{}_else", method_name.as_str())),
4879 span: method_name.span,
4880 };
4881 let probe = self.lookup_probe_for_diagnostic(
4882 new_name,
4883 self_ty,
4884 self_expr,
4885 ProbeScope::TraitsInScope,
4886 Some(expected),
4887 );
4888
4889 if let Ok(pick) = probe
4891 && let fn_sig = self.tcx.fn_sig(pick.item.def_id)
4892 && let fn_args = fn_sig.skip_binder().skip_binder().inputs()
4893 && fn_args.len() == args.len() + 1
4894 {
4895 err.span_suggestion_verbose(
4896 method_name.span.shrink_to_hi(),
4897 ::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()),
4898 "_else",
4899 Applicability::MaybeIncorrect,
4900 );
4901 return true;
4902 }
4903 }
4904 false
4905 }
4906
4907 fn type_derefs_to_local(
4910 &self,
4911 span: Span,
4912 rcvr_ty: Ty<'tcx>,
4913 source: SelfSource<'tcx>,
4914 ) -> bool {
4915 fn is_local(ty: Ty<'_>) -> bool {
4916 match ty.kind() {
4917 ty::Adt(def, _) => def.did().is_local(),
4918 ty::Foreign(did) => did.is_local(),
4919 ty::Dynamic(tr, ..) => tr.principal().is_some_and(|d| d.def_id().is_local()),
4920 ty::Param(_) => true,
4921
4922 _ => false,
4927 }
4928 }
4929
4930 if let SelfSource::QPath(_) = source {
4933 return is_local(rcvr_ty);
4934 }
4935
4936 self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
4937 }
4938
4939 fn suggest_hashmap_on_unsatisfied_hashset_buildhasher(
4940 &self,
4941 err: &mut Diag<'_>,
4942 pred: &ty::TraitPredicate<'_>,
4943 adt: ty::AdtDef<'_>,
4944 ) -> bool {
4945 if self.tcx.is_diagnostic_item(sym::HashSet, adt.did())
4946 && self.tcx.is_diagnostic_item(sym::BuildHasher, pred.def_id())
4947 {
4948 err.help("you might have intended to use a HashMap instead");
4949 true
4950 } else {
4951 false
4952 }
4953 }
4954}
4955
4956#[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)]
4957enum SelfSource<'a> {
4958 QPath(&'a hir::Ty<'a>),
4959 MethodCall(&'a hir::Expr<'a> ),
4960}
4961
4962#[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)]
4963pub(crate) struct TraitInfo {
4964 pub def_id: DefId,
4965}
4966
4967pub(crate) fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
4970 tcx.all_traits_including_private().map(|def_id| TraitInfo { def_id }).collect()
4971}
4972
4973fn print_disambiguation_help<'tcx>(
4974 tcx: TyCtxt<'tcx>,
4975 err: &mut Diag<'_>,
4976 source: SelfSource<'tcx>,
4977 args: Option<&'tcx [hir::Expr<'tcx>]>,
4978 trait_ref: ty::TraitRef<'tcx>,
4979 candidate_idx: Option<usize>,
4980 span: Span,
4981 item: ty::AssocItem,
4982) -> Option<String> {
4983 let trait_impl_type = trait_ref.self_ty().peel_refs();
4984 let trait_ref = if item.is_method() {
4985 trait_ref.print_only_trait_name().to_string()
4986 } else {
4987 ::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())
4988 };
4989 Some(
4990 if item.is_fn()
4991 && let SelfSource::MethodCall(receiver) = source
4992 && let Some(args) = args
4993 {
4994 let def_kind_descr = tcx.def_kind_descr(item.as_def_kind(), item.def_id);
4995 let item_name = item.ident(tcx);
4996 let first_input =
4997 tcx.fn_sig(item.def_id).instantiate_identity().skip_binder().inputs().get(0);
4998 let (first_arg_type, rcvr_ref) = (
4999 first_input.map(|first| first.peel_refs()),
5000 first_input
5001 .and_then(|ty| ty.ref_mutability())
5002 .map_or("", |mutbl| mutbl.ref_prefix_str()),
5003 );
5004
5005 let args = if let Some(first_arg_type) = first_arg_type
5007 && (first_arg_type == tcx.types.self_param
5008 || first_arg_type == trait_impl_type
5009 || item.is_method())
5010 {
5011 Some(receiver)
5012 } else {
5013 None
5014 }
5015 .into_iter()
5016 .chain(args)
5017 .map(|arg| {
5018 tcx.sess.source_map().span_to_snippet(arg.span).unwrap_or_else(|_| "_".to_owned())
5019 })
5020 .collect::<Vec<_>>()
5021 .join(", ");
5022
5023 let args = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}{1})", rcvr_ref, args))
})format!("({}{})", rcvr_ref, args);
5024 err.span_suggestion_verbose(
5025 span,
5026 ::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!(
5027 "disambiguate the {def_kind_descr} for {}",
5028 if let Some(candidate) = candidate_idx {
5029 format!("candidate #{candidate}")
5030 } else {
5031 "the candidate".to_string()
5032 },
5033 ),
5034 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}{2}", trait_ref, item_name,
args))
})format!("{trait_ref}::{item_name}{args}"),
5035 Applicability::HasPlaceholders,
5036 );
5037 return None;
5038 } else {
5039 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::", trait_ref))
})format!("{trait_ref}::")
5040 },
5041 )
5042}