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,
86 let sp = self_expr.span;
88 let mut lint = lint.build(&format!(
89 "trait method `{}` will become ambiguous in Rust 2021",
93 let derefs = "*".repeat(pick.autoderefs);
95 let autoref = match pick.autoref_or_ptr_adjustment {
96 Some(probe::AutorefOrPtrAdjustment::Autoref {
97 mutbl: Mutability::Mut,
100 Some(probe::AutorefOrPtrAdjustment::Autoref {
101 mutbl: Mutability::Not,
104 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
106 if let Ok(self_expr) = self.sess().source_map().span_to_snippet(self_expr.span)
108 let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
109 pick.autoref_or_ptr_adjustment
111 format!("{}{} as *const _", derefs, self_expr)
113 format!("{}{}{}", autoref, derefs, self_expr)
116 lint.span_suggestion(
118 "disambiguate the method call",
119 format!("({})", self_adjusted),
120 Applicability::MachineApplicable,
123 let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
124 pick.autoref_or_ptr_adjustment
126 format!("{}(...) as *const _", derefs)
128 format!("{}{}...", autoref, derefs)
132 &format!("disambiguate the method call with `({})`", self_adjusted,),
140 // trait implementations require full disambiguation to not clash with the new prelude
141 // additions (i.e. convert from dot-call to fully-qualified call)
142 self.tcx.struct_span_lint_hir(
143 prelude_or_array_lint,
147 let sp = call_expr.span;
148 let trait_name = self.trait_path_or_bare_name(
151 pick.item.container_id(self.tcx),
154 let mut lint = lint.build(&format!(
155 "trait method `{}` will become ambiguous in Rust 2021",
159 let (self_adjusted, precise) = self.adjust_expr(pick, self_expr, sp);
164 let span = arg.span.find_ancestor_inside(sp).unwrap_or_default();
167 self.sess().source_map().span_to_snippet(span).unwrap()
170 .collect::<String>();
172 lint.span_suggestion(
174 "disambiguate the associated function",
179 if let Some(args) = segment.args.as_ref().and_then(|args| self
182 .span_to_snippet(args.span_ext)
186 format!("::{}", args)
193 Applicability::MachineApplicable,
199 "disambiguate the associated function with `{}::{}(...)`",
200 trait_name, segment.ident,
211 pub(super) fn lint_fully_qualified_call_from_2018(
220 // Rust 2021 and later is already using the new prelude
221 if span.rust_2021() {
225 // These are the fully qualified methods added to prelude in Rust 2021
226 if !matches!(method_name.name, sym::try_into | sym::try_from | sym::from_iter) {
230 // No need to lint if method came from std/core, as that will now be in the prelude
231 if matches!(self.tcx.crate_name(pick.item.def_id.krate), sym::std | sym::core) {
235 // For from_iter, check if the type actually implements FromIterator.
236 // If we know it does not, we don't need to warn.
237 if method_name.name == sym::from_iter {
238 if let Some(trait_def_id) = self.tcx.get_diagnostic_item(sym::FromIterator) {
241 .type_implements_trait(
244 InternalSubsts::empty(),
254 // No need to lint if this is an inherent method called on a specific type, like `Vec::foo(...)`,
255 // since such methods take precedence over trait methods.
256 if matches!(pick.kind, probe::PickKind::InherentImplPick) {
260 self.tcx.struct_span_lint_hir(RUST_2021_PRELUDE_COLLISIONS, expr_id, span, |lint| {
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);
268 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 lint = lint.build(&format!(
286 "trait-associated function `{}` will become ambiguous in Rust 2021",
290 let mut self_ty_name = self_ty_span
291 .find_ancestor_inside(span)
292 .and_then(|span| self.sess().source_map().span_to_snippet(span).ok())
293 .unwrap_or_else(|| self_ty.to_string());
295 // Get the number of generics the self type has (if an Adt) unless we can determine that
296 // the user has written the self type with generics already which we (naively) do by looking
297 // for a "<" in `self_ty_name`.
298 if !self_ty_name.contains('<') {
299 if let Adt(def, _) = self_ty.kind() {
300 let generics = self.tcx.generics_of(def.did());
301 if !generics.params.is_empty() {
302 let counts = generics.own_counts();
303 self_ty_name += &format!(
305 std::iter::repeat("'_")
306 .take(counts.lifetimes)
307 .chain(std::iter::repeat("_").take(counts.types + counts.consts))
314 lint.span_suggestion(
316 "disambiguate the associated function",
317 format!("<{} as {}>::{}", self_ty_name, trait_name, method_name.name,),
318 Applicability::MachineApplicable,
325 fn trait_path_or_bare_name(
331 self.trait_path(span, expr_hir_id, trait_def_id).unwrap_or_else(|| {
332 let key = self.tcx.def_key(trait_def_id);
333 format!("{}", key.disambiguated_data.data)
337 fn trait_path(&self, span: Span, expr_hir_id: HirId, trait_def_id: DefId) -> Option<String> {
338 let applicable_traits = self.tcx.in_scope_traits(expr_hir_id)?;
339 let applicable_trait = applicable_traits.iter().find(|t| t.def_id == trait_def_id)?;
340 if applicable_trait.import_ids.is_empty() {
341 // The trait was declared within the module, we only need to use its name.
345 let import_items: Vec<_> = applicable_trait
348 .map(|&import_id| self.tcx.hir().expect_item(import_id))
351 // Find an identifier with which this trait was imported (note that `_` doesn't count).
352 let any_id = import_items
354 .filter_map(|item| if item.ident.name != Underscore { Some(item.ident) } else { None })
356 if let Some(any_id) = any_id {
357 if any_id.name == Empty {
358 // Glob import, so just use its name.
361 return Some(format!("{}", any_id));
365 // All that is left is `_`! We need to use the full path. It doesn't matter which one we pick,
366 // so just take the first one.
367 match import_items[0].kind {
368 ItemKind::Use(path, _) => Some(
371 .map(|segment| segment.ident.to_string())
376 span_bug!(span, "unexpected item kind, expected a use: {:?}", import_items[0].kind);
381 /// Creates a string version of the `expr` that includes explicit adjustments.
382 /// Returns the string and also a bool indicating whether this is a *precise*
387 expr: &hir::Expr<'tcx>,
389 ) -> (String, bool) {
390 let derefs = "*".repeat(pick.autoderefs);
392 let autoref = match pick.autoref_or_ptr_adjustment {
393 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl: Mutability::Mut, .. }) => "&mut ",
394 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl: Mutability::Not, .. }) => "&",
395 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
398 let (expr_text, precise) = if let Some(expr_text) = expr
400 .find_ancestor_inside(outer)
401 .and_then(|span| self.sess().source_map().span_to_snippet(span).ok())
405 ("(..)".to_string(), false)
408 let adjusted_text = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
409 pick.autoref_or_ptr_adjustment
411 format!("{}{} as *const _", derefs, expr_text)
413 format!("{}{}{}", autoref, derefs, expr_text)
416 (adjusted_text, precise)