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