1 use hir::def_id::DefId;
4 use rustc_ast::Mutability;
5 use rustc_errors::Applicability;
7 use rustc_middle::ty::subst::InternalSubsts;
8 use rustc_middle::ty::{Adt, Array, Ref, Ty};
9 use rustc_session::lint::builtin::RUST_2021_PRELUDE_COLLISIONS;
10 use rustc_span::symbol::kw::{Empty, Underscore};
11 use rustc_span::symbol::{sym, Ident};
13 use rustc_trait_selection::infer::InferCtxtExt;
16 method::probe::{self, Pick},
20 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
21 pub(super) fn lint_dot_call_from_2018(
24 segment: &hir::PathSegment<'_>,
26 call_expr: &'tcx hir::Expr<'tcx>,
27 self_expr: &'tcx hir::Expr<'tcx>,
29 args: &'tcx [hir::Expr<'tcx>],
32 "lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
33 segment.ident, self_ty, call_expr, self_expr
36 // Rust 2021 and later is already using the new prelude
41 let prelude_or_array_lint = match segment.ident.name {
42 // `try_into` was added to the prelude in Rust 2021.
43 sym::try_into => RUST_2021_PRELUDE_COLLISIONS,
44 // `into_iter` wasn't added to the prelude,
45 // but `[T; N].into_iter()` doesn't resolve to IntoIterator::into_iter
46 // before Rust 2021, which results in the same problem.
47 // It is only a problem for arrays.
48 sym::into_iter if let Array(..) = self_ty.kind() => {
49 // In this case, it wasn't really a prelude addition that was the problem.
50 // Instead, the problem is that the array-into_iter hack will no longer apply in Rust 2021.
51 rustc_lint::ARRAY_INTO_ITER
56 // No need to lint if method came from std/core, as that will now be in the prelude
57 if matches!(self.tcx.crate_name(pick.item.def_id.krate), sym::std | sym::core) {
61 if matches!(pick.kind, probe::PickKind::InherentImplPick | probe::PickKind::ObjectPick) {
62 // avoid repeatedly adding unneeded `&*`s
63 if pick.autoderefs == 1
65 pick.autoref_or_ptr_adjustment,
66 Some(probe::AutorefOrPtrAdjustment::Autoref { .. })
68 && matches!(self_ty.kind(), Ref(..))
73 // if it's an inherent `self` method (not `&self` or `&mut self`), it will take
74 // precedence over the `TryInto` impl, and thus won't break in 2021 edition
75 if pick.autoderefs == 0 && pick.autoref_or_ptr_adjustment.is_none() {
79 // Inherent impls only require not relying on autoref and autoderef in order to
80 // ensure that the trait implementation won't be used
81 self.tcx.struct_span_lint_hir(
82 prelude_or_array_lint,
85 format!("trait method `{}` will become ambiguous in Rust 2021", segment.ident.name),
87 let sp = self_expr.span;
89 let derefs = "*".repeat(pick.autoderefs);
91 let autoref = match pick.autoref_or_ptr_adjustment {
92 Some(probe::AutorefOrPtrAdjustment::Autoref {
93 mutbl: Mutability::Mut,
96 Some(probe::AutorefOrPtrAdjustment::Autoref {
97 mutbl: Mutability::Not,
100 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
102 if let Ok(self_expr) = self.sess().source_map().span_to_snippet(self_expr.span)
104 let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
105 pick.autoref_or_ptr_adjustment
107 format!("{}{} as *const _", derefs, self_expr)
109 format!("{}{}{}", autoref, derefs, self_expr)
112 lint.span_suggestion(
114 "disambiguate the method call",
115 format!("({})", self_adjusted),
116 Applicability::MachineApplicable,
119 let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
120 pick.autoref_or_ptr_adjustment
122 format!("{}(...) as *const _", derefs)
124 format!("{}{}...", autoref, derefs)
128 &format!("disambiguate the method call with `({})`", self_adjusted,),
136 // trait implementations require full disambiguation to not clash with the new prelude
137 // additions (i.e. convert from dot-call to fully-qualified call)
138 self.tcx.struct_span_lint_hir(
139 prelude_or_array_lint,
142 format!("trait method `{}` will become ambiguous in Rust 2021", segment.ident.name),
144 let sp = call_expr.span;
145 let trait_name = self.trait_path_or_bare_name(
148 pick.item.container_id(self.tcx),
151 let (self_adjusted, precise) = self.adjust_expr(pick, self_expr, sp);
156 let span = arg.span.find_ancestor_inside(sp).unwrap_or_default();
159 self.sess().source_map().span_to_snippet(span).unwrap()
162 .collect::<String>();
164 lint.span_suggestion(
166 "disambiguate the associated function",
171 if let Some(args) = segment.args.as_ref().and_then(|args| self
174 .span_to_snippet(args.span_ext)
178 format!("::{}", args)
185 Applicability::MachineApplicable,
191 "disambiguate the associated function with `{}::{}(...)`",
192 trait_name, segment.ident,
203 pub(super) fn lint_fully_qualified_call_from_2018(
212 // Rust 2021 and later is already using the new prelude
213 if span.rust_2021() {
217 // These are the fully qualified methods added to prelude in Rust 2021
218 if !matches!(method_name.name, sym::try_into | sym::try_from | sym::from_iter) {
222 // No need to lint if method came from std/core, as that will now be in the prelude
223 if matches!(self.tcx.crate_name(pick.item.def_id.krate), sym::std | sym::core) {
227 // For from_iter, check if the type actually implements FromIterator.
228 // If we know it does not, we don't need to warn.
229 if method_name.name == sym::from_iter {
230 if let Some(trait_def_id) = self.tcx.get_diagnostic_item(sym::FromIterator) {
233 .type_implements_trait(
236 InternalSubsts::empty(),
246 // No need to lint if this is an inherent method called on a specific type, like `Vec::foo(...)`,
247 // since such methods take precedence over trait methods.
248 if matches!(pick.kind, probe::PickKind::InherentImplPick) {
252 self.tcx.struct_span_lint_hir(
253 RUST_2021_PRELUDE_COLLISIONS,
257 "trait-associated function `{}` will become ambiguous in Rust 2021",
261 // "type" refers to either a type or, more likely, a trait from which
262 // the associated function or method is from.
263 let container_id = pick.item.container_id(self.tcx);
264 let trait_path = self.trait_path_or_bare_name(span, expr_id, container_id);
265 let trait_generics = self.tcx.generics_of(container_id);
267 let trait_name = if trait_generics.params.len() <= trait_generics.has_self as usize
271 let counts = trait_generics.own_counts();
275 std::iter::repeat("'_")
276 .take(counts.lifetimes)
277 .chain(std::iter::repeat("_").take(
278 counts.types + counts.consts - trait_generics.has_self as usize
285 let mut self_ty_name = self_ty_span
286 .find_ancestor_inside(span)
287 .and_then(|span| self.sess().source_map().span_to_snippet(span).ok())
288 .unwrap_or_else(|| self_ty.to_string());
290 // Get the number of generics the self type has (if an Adt) unless we can determine that
291 // the user has written the self type with generics already which we (naively) do by looking
292 // for a "<" in `self_ty_name`.
293 if !self_ty_name.contains('<') {
294 if let Adt(def, _) = self_ty.kind() {
295 let generics = self.tcx.generics_of(def.did());
296 if !generics.params.is_empty() {
297 let counts = generics.own_counts();
298 self_ty_name += &format!(
300 std::iter::repeat("'_")
301 .take(counts.lifetimes)
303 std::iter::repeat("_").take(counts.types + counts.consts)
311 lint.span_suggestion(
313 "disambiguate the associated function",
314 format!("<{} as {}>::{}", self_ty_name, trait_name, method_name.name,),
315 Applicability::MachineApplicable,
323 fn trait_path_or_bare_name(
329 self.trait_path(span, expr_hir_id, trait_def_id).unwrap_or_else(|| {
330 let key = self.tcx.def_key(trait_def_id);
331 format!("{}", key.disambiguated_data.data)
335 fn trait_path(&self, span: Span, expr_hir_id: HirId, trait_def_id: DefId) -> Option<String> {
336 let applicable_traits = self.tcx.in_scope_traits(expr_hir_id)?;
337 let applicable_trait = applicable_traits.iter().find(|t| t.def_id == trait_def_id)?;
338 if applicable_trait.import_ids.is_empty() {
339 // The trait was declared within the module, we only need to use its name.
343 let import_items: Vec<_> = applicable_trait
346 .map(|&import_id| self.tcx.hir().expect_item(import_id))
349 // Find an identifier with which this trait was imported (note that `_` doesn't count).
350 let any_id = import_items
352 .filter_map(|item| if item.ident.name != Underscore { Some(item.ident) } else { None })
354 if let Some(any_id) = any_id {
355 if any_id.name == Empty {
356 // Glob import, so just use its name.
359 return Some(format!("{}", any_id));
363 // All that is left is `_`! We need to use the full path. It doesn't matter which one we pick,
364 // so just take the first one.
365 match import_items[0].kind {
366 ItemKind::Use(path, _) => Some(
369 .map(|segment| segment.ident.to_string())
374 span_bug!(span, "unexpected item kind, expected a use: {:?}", import_items[0].kind);
379 /// Creates a string version of the `expr` that includes explicit adjustments.
380 /// Returns the string and also a bool indicating whether this is a *precise*
385 expr: &hir::Expr<'tcx>,
387 ) -> (String, bool) {
388 let derefs = "*".repeat(pick.autoderefs);
390 let autoref = match pick.autoref_or_ptr_adjustment {
391 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl: Mutability::Mut, .. }) => "&mut ",
392 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl: Mutability::Not, .. }) => "&",
393 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
396 let (expr_text, precise) = if let Some(expr_text) = expr
398 .find_ancestor_inside(outer)
399 .and_then(|span| self.sess().source_map().span_to_snippet(span).ok())
403 ("(..)".to_string(), false)
406 let adjusted_text = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
407 pick.autoref_or_ptr_adjustment
409 format!("{}{} as *const _", derefs, expr_text)
411 format!("{}{}{}", autoref, derefs, expr_text)
414 (adjusted_text, precise)