1 use hir::def_id::DefId;
4 use rustc_ast::Mutability;
5 use rustc_errors::Applicability;
7 use rustc_middle::ty::{Ref, Ty};
8 use rustc_session::lint::builtin::FUTURE_PRELUDE_COLLISION;
9 use rustc_span::symbol::kw::Underscore;
10 use rustc_span::symbol::{sym, Ident};
14 method::probe::{self, Pick},
18 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
19 pub(super) fn lint_dot_call_from_2018(
22 segment: &hir::PathSegment<'_>,
24 call_expr: &'tcx hir::Expr<'tcx>,
25 self_expr: &'tcx hir::Expr<'tcx>,
27 args: &'tcx [hir::Expr<'tcx>],
30 "lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
31 segment.ident, self_ty, call_expr, self_expr
34 // Rust 2021 and later is already using the new prelude
39 // These are the method names that were added to prelude in Rust 2021
40 if !matches!(segment.ident.name, sym::try_into) {
44 // No need to lint if method came from std/core, as that will now be in the prelude
45 if matches!(self.tcx.crate_name(pick.item.def_id.krate), sym::std | sym::core) {
49 if matches!(pick.kind, probe::PickKind::InherentImplPick | probe::PickKind::ObjectPick) {
50 // avoid repeatedly adding unneeded `&*`s
51 if pick.autoderefs == 1
53 pick.autoref_or_ptr_adjustment,
54 Some(probe::AutorefOrPtrAdjustment::Autoref { .. })
56 && matches!(self_ty.kind(), Ref(..))
61 // if it's an inherent `self` method (not `&self` or `&mut self`), it will take
62 // precedence over the `TryInto` impl, and thus won't break in 2021 edition
63 if pick.autoderefs == 0 && pick.autoref_or_ptr_adjustment.is_none() {
67 // Inherent impls only require not relying on autoref and autoderef in order to
68 // ensure that the trait implementation won't be used
69 self.tcx.struct_span_lint_hir(
70 FUTURE_PRELUDE_COLLISION,
74 let sp = self_expr.span;
76 let mut lint = lint.build(&format!(
77 "trait method `{}` will become ambiguous in Rust 2021",
81 let derefs = "*".repeat(pick.autoderefs);
83 let autoref = match pick.autoref_or_ptr_adjustment {
84 Some(probe::AutorefOrPtrAdjustment::Autoref {
85 mutbl: Mutability::Mut,
88 Some(probe::AutorefOrPtrAdjustment::Autoref {
89 mutbl: Mutability::Not,
92 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
94 if let Ok(self_expr) = self.sess().source_map().span_to_snippet(self_expr.span)
96 let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
97 pick.autoref_or_ptr_adjustment
99 format!("{}{} as *const _", derefs, self_expr)
101 format!("{}{}{}", autoref, derefs, self_expr)
104 lint.span_suggestion(
106 "disambiguate the method call",
107 format!("({})", self_adjusted),
108 Applicability::MachineApplicable,
111 let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
112 pick.autoref_or_ptr_adjustment
114 format!("{}(...) as *const _", derefs)
116 format!("{}{}...", autoref, derefs)
120 &format!("disambiguate the method call with `({})`", self_adjusted,),
128 // trait implementations require full disambiguation to not clash with the new prelude
129 // additions (i.e. convert from dot-call to fully-qualified call)
130 self.tcx.struct_span_lint_hir(
131 FUTURE_PRELUDE_COLLISION,
135 let sp = call_expr.span;
136 let trait_name = self.trait_path_or_bare_name(
139 pick.item.container.id(),
142 let mut lint = lint.build(&format!(
143 "trait method `{}` will become ambiguous in Rust 2021",
147 let (self_adjusted, precise) = self.adjust_expr(pick, self_expr);
155 self.sess().source_map().span_to_snippet(arg.span).unwrap()
158 .collect::<String>();
160 lint.span_suggestion(
162 "disambiguate the associated function",
165 trait_name, segment.ident.name, self_adjusted, args
167 Applicability::MachineApplicable,
173 "disambiguate the associated function with `{}::{}(...)`",
174 trait_name, segment.ident,
185 pub(super) fn lint_fully_qualified_call_from_2018(
194 // Rust 2021 and later is already using the new prelude
195 if span.rust_2021() {
199 // These are the fully qualified methods added to prelude in Rust 2021
200 if !matches!(method_name.name, sym::try_into | sym::try_from | sym::from_iter) {
204 // No need to lint if method came from std/core, as that will now be in the prelude
205 if matches!(self.tcx.crate_name(pick.item.def_id.krate), sym::std | sym::core) {
209 // No need to lint if this is an inherent method called on a specific type, like `Vec::foo(...)`,
210 // since such methods take precedence over trait methods.
211 if matches!(pick.kind, probe::PickKind::InherentImplPick) {
215 self.tcx.struct_span_lint_hir(FUTURE_PRELUDE_COLLISION, expr_id, span, |lint| {
216 // "type" refers to either a type or, more likely, a trait from which
217 // the associated function or method is from.
218 let trait_path = self.trait_path_or_bare_name(span, expr_id, pick.item.container.id());
219 let trait_generics = self.tcx.generics_of(pick.item.container.id());
221 let parameter_count = trait_generics.count() - (trait_generics.has_self as usize);
222 let trait_name = if parameter_count == 0 {
228 std::iter::repeat("_").take(parameter_count).collect::<Vec<_>>().join(", ")
232 let mut lint = lint.build(&format!(
233 "trait-associated function `{}` will become ambiguous in Rust 2021",
240 .span_to_snippet(self_ty_span)
241 .unwrap_or_else(|_| self_ty.to_string());
243 lint.span_suggestion(
245 "disambiguate the associated function",
246 format!("<{} as {}>::{}", self_ty, trait_name, method_name.name,),
247 Applicability::MachineApplicable,
254 fn trait_path_or_bare_name(
260 self.trait_path(span, expr_hir_id, trait_def_id).unwrap_or_else(|| {
261 let key = self.tcx.def_key(trait_def_id);
262 format!("{}", key.disambiguated_data.data)
266 fn trait_path(&self, span: Span, expr_hir_id: HirId, trait_def_id: DefId) -> Option<String> {
267 let applicable_traits = self.tcx.in_scope_traits(expr_hir_id)?;
268 let applicable_trait = applicable_traits.iter().find(|t| t.def_id == trait_def_id)?;
269 if applicable_trait.import_ids.is_empty() {
270 // The trait was declared within the module, we only need to use its name.
274 let import_items: Vec<_> = applicable_trait
278 let hir_id = self.tcx.hir().local_def_id_to_hir_id(import_id);
279 self.tcx.hir().expect_item(hir_id)
283 // Find an identifier with which this trait was imported (note that `_` doesn't count).
284 let any_id = import_items
286 .filter_map(|item| if item.ident.name != Underscore { Some(item.ident) } else { None })
288 if let Some(any_id) = any_id {
289 return Some(format!("{}", any_id));
292 // All that is left is `_`! We need to use the full path. It doesn't matter which one we pick,
293 // so just take the first one.
294 match import_items[0].kind {
295 ItemKind::Use(path, _) => Some(
298 .map(|segment| segment.ident.to_string())
303 span_bug!(span, "unexpected item kind, expected a use: {:?}", import_items[0].kind);
308 /// Creates a string version of the `expr` that includes explicit adjustments.
309 /// Returns the string and also a bool indicating whther this is a *precise*
311 fn adjust_expr(&self, pick: &Pick<'tcx>, expr: &hir::Expr<'tcx>) -> (String, bool) {
312 let derefs = "*".repeat(pick.autoderefs);
314 let autoref = match pick.autoref_or_ptr_adjustment {
315 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl: Mutability::Mut, .. }) => "&mut ",
316 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl: Mutability::Not, .. }) => "&",
317 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
320 let (expr_text, precise) =
321 if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) {
324 (format!("(..)"), false)
327 let adjusted_text = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
328 pick.autoref_or_ptr_adjustment
330 format!("{}{} as *const _", derefs, expr_text)
332 format!("{}{}{}", autoref, derefs, expr_text)
335 (adjusted_text, precise)