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