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