1use std::fmt::Write;
2
3use hir::def_id::DefId;
4use hir::{HirId, ItemKind};
5use rustc_ast::join_path_idents;
6use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, Level};
7use rustc_hir as hir;
8use rustc_hir::attrs::lang_items::LangItem;
9use rustc_lint::{ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER};
10use rustc_middle::span_bug;
11use rustc_middle::ty::{self, Ty, TyCtxt};
12use rustc_session::lint::builtin::{RUST_2021_PRELUDE_COLLISIONS, RUST_2024_PRELUDE_COLLISIONS};
13use rustc_span::{Ident, STDLIB_STABLE_CRATES, Span, Symbol, kw, sym};
14use rustc_trait_selection::infer::InferCtxtExt;
15use tracing::debug;
16
17use crate::FnCtxt;
18use crate::method::probe::{self, Pick};
19
20struct AmbiguousTraitMethodCall<'a, 'tcx> {
21 segment_name: Symbol,
22 self_expr_span: Span,
23 pick: &'a Pick<'tcx>,
24 tcx: TyCtxt<'tcx>,
25 edition: &'static str,
26}
27
28impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for AmbiguousTraitMethodCall<'b, 'tcx> {
29 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
30 let Self { segment_name, self_expr_span, pick, tcx, edition } = self;
31 let mut lint = Diag::new(
32 dcx,
33 level,
34 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait method `{0}` will become ambiguous in Rust {1}",
segment_name, edition))
})format!("trait method `{}` will become ambiguous in Rust {edition}", segment_name),
35 );
36 let derefs = "*".repeat(pick.autoderefs);
37
38 let autoref = match pick.autoref_or_ptr_adjustment {
39 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl, .. }) => mutbl.ref_prefix_str(),
40 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
41 Some(probe::AutorefOrPtrAdjustment::ReborrowPin(mutbl)) => match mutbl {
42 hir::Mutability::Mut => "Pin<&mut ",
43 hir::Mutability::Not => "Pin<&",
44 },
45 };
46 if let Ok(self_expr) = tcx.sess.source_map().span_to_snippet(self_expr_span) {
47 let mut self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
48 pick.autoref_or_ptr_adjustment
49 {
50 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1} as *const _", derefs,
self_expr))
})format!("{derefs}{self_expr} as *const _")
51 } else {
52 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", autoref, derefs,
self_expr))
})format!("{autoref}{derefs}{self_expr}")
53 };
54
55 if let Some(probe::AutorefOrPtrAdjustment::ReborrowPin(_)) =
56 pick.autoref_or_ptr_adjustment
57 {
58 self_adjusted.push('>');
59 }
60
61 lint.span_suggestion(
62 self_expr_span,
63 "disambiguate the method call",
64 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", self_adjusted))
})format!("({self_adjusted})"),
65 Applicability::MachineApplicable,
66 );
67 } else {
68 let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
69 pick.autoref_or_ptr_adjustment
70 {
71 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}(...) as *const _", derefs))
})format!("{derefs}(...) as *const _")
72 } else {
73 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}...", autoref, derefs))
})format!("{autoref}{derefs}...")
74 };
75 lint.span_help(
76 self_expr_span,
77 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("disambiguate the method call with `({0})`",
self_adjusted))
})format!("disambiguate the method call with `({self_adjusted})`",),
78 );
79 }
80 lint
81 }
82}
83
84struct AmbiguousTraitMethod<'a, 'tcx, 'fnctx> {
85 segment: &'a hir::PathSegment<'tcx>,
86 call_expr: &'tcx hir::Expr<'tcx>,
87 self_expr: &'tcx hir::Expr<'tcx>,
88 pick: &'a Pick<'tcx>,
89 args: &'tcx [hir::Expr<'tcx>],
90 edition: &'static str,
91 span: Span,
92 this: &'a FnCtxt<'fnctx, 'tcx>,
93}
94
95impl<'a, 'c, 'tcx, 'fnctx> Diagnostic<'a, ()> for AmbiguousTraitMethod<'c, 'tcx, 'fnctx> {
96 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
97 let Self { segment, call_expr, self_expr, pick, args, edition, span, this } = self;
98 let mut lint = Diag::new(
99 dcx,
100 level,
101 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait method `{0}` will become ambiguous in Rust {1}",
segment.ident.name, edition))
})format!(
102 "trait method `{}` will become ambiguous in Rust {edition}",
103 segment.ident.name
104 ),
105 );
106
107 let sp = call_expr.span;
108 let trait_name =
109 this.trait_path_or_bare_name(span, call_expr.hir_id, pick.item.container_id(this.tcx));
110
111 let (self_adjusted, precise) = this.adjust_expr(pick, self_expr, sp);
112 if precise {
113 let args = args.iter().fold(String::new(), |mut string, arg| {
114 let span = arg.span.find_ancestor_inside(sp).unwrap_or_default();
115 string.write_fmt(format_args!(", {0}",
this.sess().source_map().span_to_snippet(span).unwrap()))write!(string, ", {}", this.sess().source_map().span_to_snippet(span).unwrap())
116 .unwrap();
117 string
118 });
119
120 lint.span_suggestion(
121 sp,
122 "disambiguate the associated function",
123 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}{2}({3}{4})", trait_name,
segment.ident.name,
if let Some(args) =
segment.args.as_ref().and_then(|args|
this.sess().source_map().span_to_snippet(args.span_ext).ok())
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}", args))
})
} else { String::new() }, self_adjusted, args))
})format!(
124 "{}::{}{}({}{})",
125 trait_name,
126 segment.ident.name,
127 if let Some(args) = segment.args.as_ref().and_then(|args| this
128 .sess()
129 .source_map()
130 .span_to_snippet(args.span_ext)
131 .ok())
132 {
133 format!("::{args}")
135 } else {
136 String::new()
137 },
138 self_adjusted,
139 args,
140 ),
141 Applicability::MachineApplicable,
142 );
143 } else {
144 lint.span_help(
145 sp,
146 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("disambiguate the associated function with `{0}::{1}(...)`",
trait_name, segment.ident))
})format!(
147 "disambiguate the associated function with `{}::{}(...)`",
148 trait_name, segment.ident,
149 ),
150 );
151 }
152 lint
153 }
154}
155
156impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
157 pub(super) fn lint_edition_dependent_dot_call(
158 &self,
159 self_ty: Ty<'tcx>,
160 segment: &hir::PathSegment<'tcx>,
161 span: Span,
162 call_expr: &'tcx hir::Expr<'tcx>,
163 self_expr: &'tcx hir::Expr<'tcx>,
164 pick: &Pick<'tcx>,
165 args: &'tcx [hir::Expr<'tcx>],
166 ) {
167 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs:167",
"rustc_hir_typeck::method::prelude_edition_lints",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs"),
::tracing_core::__macro_support::Option::Some(167u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::method::prelude_edition_lints"),
::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!("lookup(method_name={0}, self_ty={1:?}, call_expr={2:?}, self_expr={3:?})",
segment.ident, self_ty, call_expr, self_expr) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
168 "lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
169 segment.ident, self_ty, call_expr, self_expr
170 );
171
172 let (prelude_or_array_lint, edition) = match segment.ident.name {
173 sym::try_into if !span.at_least_rust_2021() => (RUST_2021_PRELUDE_COLLISIONS, "2021"),
175 sym::poll
177 if !span.at_least_rust_2024()
179 && let ty::Adt(adt_def, args) = self_ty.kind()
180 && self.tcx.is_lang_item(adt_def.did(), LangItem::Pin)
181 && let ty::Ref(_, _, ty::Mutability::Mut) =
182 args[0].as_type().unwrap().kind() =>
183 {
184 (RUST_2024_PRELUDE_COLLISIONS, "2024")
185 }
186 sym::into_future if !span.at_least_rust_2024() => {
188 (RUST_2024_PRELUDE_COLLISIONS, "2024")
189 }
190 sym::into_iter => {
195 if let ty::Array(..) = self_ty.kind()
196 && !span.at_least_rust_2021()
197 {
198 (ARRAY_INTO_ITER, "2021")
202 } else if self_ty.boxed_ty().is_some_and(Ty::is_slice)
203 && !span.at_least_rust_2024()
204 {
205 (BOXED_SLICE_INTO_ITER, "2024")
209 } else {
210 return;
211 }
212 }
213 _ => return,
214 };
215
216 if STDLIB_STABLE_CRATES.contains(&self.tcx.crate_name(pick.item.def_id.krate)) {
218 return;
219 }
220
221 if #[allow(non_exhaustive_omitted_patterns)] match pick.kind {
probe::PickKind::InherentImplPick | probe::PickKind::ObjectPick => true,
_ => false,
}matches!(pick.kind, probe::PickKind::InherentImplPick | probe::PickKind::ObjectPick) {
222 if pick.autoderefs == 1
224 && #[allow(non_exhaustive_omitted_patterns)] match pick.autoref_or_ptr_adjustment
{
Some(probe::AutorefOrPtrAdjustment::Autoref { .. }) => true,
_ => false,
}matches!(
225 pick.autoref_or_ptr_adjustment,
226 Some(probe::AutorefOrPtrAdjustment::Autoref { .. })
227 )
228 && #[allow(non_exhaustive_omitted_patterns)] match self_ty.kind() {
ty::Ref(..) => true,
_ => false,
}matches!(self_ty.kind(), ty::Ref(..))
229 {
230 return;
231 }
232
233 if pick.autoderefs == 0 && pick.autoref_or_ptr_adjustment.is_none() {
236 return;
237 }
238
239 self.tcx.emit_node_span_lint(
242 prelude_or_array_lint,
243 self_expr.hir_id,
244 self_expr.span,
245 AmbiguousTraitMethodCall {
246 segment_name: segment.ident.name,
247 self_expr_span: self_expr.span,
248 pick,
249 tcx: self.tcx,
250 edition,
251 },
252 );
253 } else {
254 self.tcx.emit_node_span_lint(
257 prelude_or_array_lint,
258 call_expr.hir_id,
259 call_expr.span,
260 AmbiguousTraitMethod {
261 segment,
262 call_expr,
263 self_expr,
264 pick,
265 args,
266 edition,
267 span,
268 this: self,
269 },
270 );
271 }
272 }
273
274 pub(super) fn lint_fully_qualified_call_from_2018(
275 &self,
276 span: Span,
277 method_name: Ident,
278 self_ty: Ty<'tcx>,
279 self_ty_span: Span,
280 expr_id: hir::HirId,
281 pick: &Pick<'tcx>,
282 ) {
283 struct AmbiguousTraitAssocFunc<'a, 'fnctx, 'tcx> {
284 method_name: Symbol,
285 this: &'a FnCtxt<'fnctx, 'tcx>,
286 pick: &'a Pick<'tcx>,
287 span: Span,
288 expr_id: hir::HirId,
289 self_ty_span: Span,
290 self_ty: Ty<'tcx>,
291 }
292
293 impl<'a, 'b, 'fnctx, 'tcx> Diagnostic<'a, ()> for AmbiguousTraitAssocFunc<'b, 'fnctx, 'tcx> {
294 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
295 let Self { method_name, this, pick, span, expr_id, self_ty_span, self_ty } = self;
296 let mut lint = Diag::new(
297 dcx,
298 level,
299 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait-associated function `{0}` will become ambiguous in Rust 2021",
method_name))
})format!(
300 "trait-associated function `{}` will become ambiguous in Rust 2021",
301 method_name
302 ),
303 );
304
305 let container_id = pick.item.container_id(this.tcx);
308 let trait_path = this.trait_path_or_bare_name(span, expr_id, container_id);
309 let trait_generics = this.tcx.generics_of(container_id);
310
311 let trait_name =
312 if trait_generics.own_params.len() <= trait_generics.has_self as usize {
313 trait_path
314 } else {
315 let counts = trait_generics.own_counts();
316 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}<{1}>", trait_path,
std::iter::repeat("'_").take(counts.lifetimes).chain(std::iter::repeat("_").take(counts.types
+ counts.consts -
trait_generics.has_self as
usize)).collect::<Vec<_>>().join(", ")))
})format!(
317 "{}<{}>",
318 trait_path,
319 std::iter::repeat("'_")
320 .take(counts.lifetimes)
321 .chain(std::iter::repeat("_").take(
322 counts.types + counts.consts - trait_generics.has_self as usize
323 ))
324 .collect::<Vec<_>>()
325 .join(", ")
326 )
327 };
328
329 let mut self_ty_name = self_ty_span
330 .find_ancestor_inside(span)
331 .and_then(|span| this.sess().source_map().span_to_snippet(span).ok())
332 .unwrap_or_else(|| self_ty.to_string());
333
334 if !self_ty_name.contains('<') {
338 if let ty::Adt(def, _) = self_ty.kind() {
339 let generics = this.tcx.generics_of(def.did());
340 if !generics.is_own_empty() {
341 let counts = generics.own_counts();
342 self_ty_name += &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>",
std::iter::repeat("'_").take(counts.lifetimes).chain(std::iter::repeat("_").take(counts.types
+ counts.consts)).collect::<Vec<_>>().join(", ")))
})format!(
343 "<{}>",
344 std::iter::repeat("'_")
345 .take(counts.lifetimes)
346 .chain(
347 std::iter::repeat("_").take(counts.types + counts.consts)
348 )
349 .collect::<Vec<_>>()
350 .join(", ")
351 );
352 }
353 }
354 }
355 lint.span_suggestion(
356 span,
357 "disambiguate the associated function",
358 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} as {1}>::{2}", self_ty_name,
trait_name, method_name))
})format!("<{} as {}>::{}", self_ty_name, trait_name, method_name),
359 Applicability::MachineApplicable,
360 );
361 lint
362 }
363 }
364
365 if span.at_least_rust_2021() {
367 return;
368 }
369
370 if !#[allow(non_exhaustive_omitted_patterns)] match method_name.name {
sym::try_into | sym::try_from | sym::from_iter => true,
_ => false,
}matches!(method_name.name, sym::try_into | sym::try_from | sym::from_iter) {
372 return;
373 }
374
375 if STDLIB_STABLE_CRATES.contains(&self.tcx.crate_name(pick.item.def_id.krate)) {
377 return;
378 }
379
380 if method_name.name == sym::from_iter {
383 if let Some(trait_def_id) = self.tcx.get_diagnostic_item(sym::FromIterator) {
384 let any_type = self.infcx.next_ty_var(span);
385 if !self
386 .infcx
387 .type_implements_trait(trait_def_id, [self_ty, any_type], self.param_env)
388 .may_apply()
389 {
390 return;
391 }
392 }
393 }
394
395 if #[allow(non_exhaustive_omitted_patterns)] match pick.kind {
probe::PickKind::InherentImplPick => true,
_ => false,
}matches!(pick.kind, probe::PickKind::InherentImplPick) {
398 return;
399 }
400
401 self.tcx.emit_node_span_lint(
402 RUST_2021_PRELUDE_COLLISIONS,
403 expr_id,
404 span,
405 AmbiguousTraitAssocFunc {
406 method_name: method_name.name,
407 this: self,
408 pick,
409 span,
410 expr_id,
411 self_ty_span,
412 self_ty,
413 },
414 );
415 }
416
417 fn trait_path_or_bare_name(
418 &self,
419 span: Span,
420 expr_hir_id: HirId,
421 trait_def_id: DefId,
422 ) -> String {
423 self.trait_path(span, expr_hir_id, trait_def_id).unwrap_or_else(|| {
424 let key = self.tcx.def_key(trait_def_id);
425 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", key.disambiguated_data.data))
})format!("{}", key.disambiguated_data.data)
426 })
427 }
428
429 fn trait_path(&self, span: Span, expr_hir_id: HirId, trait_def_id: DefId) -> Option<String> {
430 let applicable_traits = self.tcx.in_scope_traits(expr_hir_id)?;
431 let applicable_trait = applicable_traits.iter().find(|t| t.def_id == trait_def_id)?;
432 if applicable_trait.import_ids.is_empty() {
433 return None;
435 }
436
437 let import_items: Vec<_> = applicable_trait
438 .import_ids
439 .iter()
440 .map(|&import_id| self.tcx.hir_expect_item(import_id))
441 .collect();
442
443 for item in import_items.iter() {
445 let (_, kind) = item.expect_use();
446 match kind {
447 hir::UseKind::Single(ident) => {
448 if ident.name != kw::Underscore {
449 return Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", ident.name))
})format!("{}", ident.name));
450 }
451 }
452 hir::UseKind::Glob => return None, hir::UseKind::ListStem => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
454 }
455 }
456
457 match import_items[0].kind {
460 ItemKind::Use(path, _) => {
461 Some(join_path_idents(path.segments.iter().map(|seg| seg.ident)))
462 }
463 _ => {
464 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpected item kind, expected a use: {0:?}",
import_items[0].kind));span_bug!(span, "unexpected item kind, expected a use: {:?}", import_items[0].kind);
465 }
466 }
467 }
468
469 fn adjust_expr(
473 &self,
474 pick: &Pick<'tcx>,
475 expr: &hir::Expr<'tcx>,
476 outer: Span,
477 ) -> (String, bool) {
478 let derefs = "*".repeat(pick.autoderefs);
479
480 let autoref = match pick.autoref_or_ptr_adjustment {
481 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl, .. }) => mutbl.ref_prefix_str(),
482 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
483 Some(probe::AutorefOrPtrAdjustment::ReborrowPin(mutbl)) => match mutbl {
484 hir::Mutability::Mut => "Pin<&mut ",
485 hir::Mutability::Not => "Pin<&",
486 },
487 };
488
489 let (expr_text, precise) = if let Some(expr_text) = expr
490 .span
491 .find_ancestor_inside(outer)
492 .and_then(|span| self.sess().source_map().span_to_snippet(span).ok())
493 {
494 (expr_text, true)
495 } else {
496 ("(..)".to_string(), false)
497 };
498
499 let mut adjusted_text = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
500 pick.autoref_or_ptr_adjustment
501 {
502 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1} as *const _", derefs,
expr_text))
})format!("{derefs}{expr_text} as *const _")
503 } else {
504 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", autoref, derefs,
expr_text))
})format!("{autoref}{derefs}{expr_text}")
505 };
506
507 if let Some(probe::AutorefOrPtrAdjustment::ReborrowPin(_)) = pick.autoref_or_ptr_adjustment
508 {
509 adjusted_text.push('>');
510 }
511
512 (adjusted_text, precise)
513 }
514}