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