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