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(..))
60 // Inherent impls only require not relying on autoref and autoderef in order to
61 // ensure that the trait implementation won't be used
62 self.tcx.struct_span_lint_hir(
63 FUTURE_PRELUDE_COLLISION,
67 let sp = self_expr.span;
69 let mut lint = lint.build(&format!(
70 "trait method `{}` will become ambiguous in Rust 2021",
74 let derefs = "*".repeat(pick.autoderefs);
76 let autoref = match pick.autoref_or_ptr_adjustment {
77 Some(probe::AutorefOrPtrAdjustment::Autoref {
78 mutbl: Mutability::Mut,
81 Some(probe::AutorefOrPtrAdjustment::Autoref {
82 mutbl: Mutability::Not,
85 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
87 if let Ok(self_expr) = self.sess().source_map().span_to_snippet(self_expr.span)
89 let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
90 pick.autoref_or_ptr_adjustment
92 format!("{}{} as *const _", derefs, self_expr)
94 format!("{}{}{}", autoref, derefs, self_expr)
99 "disambiguate the method call",
100 format!("({})", self_adjusted),
101 Applicability::MachineApplicable,
104 let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
105 pick.autoref_or_ptr_adjustment
107 format!("{}(...) as *const _", derefs)
109 format!("{}{}...", autoref, derefs)
113 &format!("disambiguate the method call with `({})`", self_adjusted,),
121 // trait implementations require full disambiguation to not clash with the new prelude
122 // additions (i.e. convert from dot-call to fully-qualified call)
123 self.tcx.struct_span_lint_hir(
124 FUTURE_PRELUDE_COLLISION,
128 let sp = call_expr.span;
129 let trait_name = self.trait_path_or_bare_name(
132 pick.item.container.id(),
135 let mut lint = lint.build(&format!(
136 "trait method `{}` will become ambiguous in Rust 2021",
140 let (self_adjusted, precise) = self.adjust_expr(pick, self_expr);
148 self.sess().source_map().span_to_snippet(arg.span).unwrap()
151 .collect::<String>();
153 lint.span_suggestion(
155 "disambiguate the associated function",
158 trait_name, segment.ident.name, self_adjusted, args
160 Applicability::MachineApplicable,
166 "disambiguate the associated function with `{}::{}(...)`",
167 trait_name, segment.ident,
178 pub(super) fn lint_fully_qualified_call_from_2018(
187 // Rust 2021 and later is already using the new prelude
188 if span.rust_2021() {
192 // These are the fully qualified methods added to prelude in Rust 2021
193 if !matches!(method_name.name, sym::try_into | sym::try_from | sym::from_iter) {
197 // No need to lint if method came from std/core, as that will now be in the prelude
198 if matches!(self.tcx.crate_name(pick.item.def_id.krate), sym::std | sym::core) {
202 // No need to lint if this is an inherent method called on a specific type, like `Vec::foo(...)`,
203 // since such methods take precedence over trait methods.
204 if matches!(pick.kind, probe::PickKind::InherentImplPick) {
208 self.tcx.struct_span_lint_hir(FUTURE_PRELUDE_COLLISION, expr_id, span, |lint| {
209 // "type" refers to either a type or, more likely, a trait from which
210 // the associated function or method is from.
211 let trait_path = self.trait_path_or_bare_name(span, expr_id, pick.item.container.id());
212 let trait_generics = self.tcx.generics_of(pick.item.container.id());
214 let parameter_count = trait_generics.count() - (trait_generics.has_self as usize);
215 let trait_name = if parameter_count == 0 {
221 std::iter::repeat("_").take(parameter_count).collect::<Vec<_>>().join(", ")
225 let mut lint = lint.build(&format!(
226 "trait-associated function `{}` will become ambiguous in Rust 2021",
233 .span_to_snippet(self_ty_span)
234 .unwrap_or_else(|_| self_ty.to_string());
236 lint.span_suggestion(
238 "disambiguate the associated function",
239 format!("<{} as {}>::{}", self_ty, trait_name, method_name.name,),
240 Applicability::MachineApplicable,
247 fn trait_path_or_bare_name(
253 self.trait_path(span, expr_hir_id, trait_def_id).unwrap_or_else(|| {
254 let key = self.tcx.def_key(trait_def_id);
255 format!("{}", key.disambiguated_data.data)
259 fn trait_path(&self, span: Span, expr_hir_id: HirId, trait_def_id: DefId) -> Option<String> {
260 let applicable_traits = self.tcx.in_scope_traits(expr_hir_id)?;
261 let applicable_trait = applicable_traits.iter().find(|t| t.def_id == trait_def_id)?;
262 if applicable_trait.import_ids.is_empty() {
263 // The trait was declared within the module, we only need to use its name.
267 let import_items: Vec<_> = applicable_trait
271 let hir_id = self.tcx.hir().local_def_id_to_hir_id(import_id);
272 self.tcx.hir().expect_item(hir_id)
276 // Find an identifier with which this trait was imported (note that `_` doesn't count).
277 let any_id = import_items
279 .filter_map(|item| if item.ident.name != Underscore { Some(item.ident) } else { None })
281 if let Some(any_id) = any_id {
282 return Some(format!("{}", any_id));
285 // All that is left is `_`! We need to use the full path. It doesn't matter which one we pick,
286 // so just take the first one.
287 match import_items[0].kind {
288 ItemKind::Use(path, _) => Some(
291 .map(|segment| segment.ident.to_string())
296 span_bug!(span, "unexpected item kind, expected a use: {:?}", import_items[0].kind);
301 /// Creates a string version of the `expr` that includes explicit adjustments.
302 /// Returns the string and also a bool indicating whther this is a *precise*
304 fn adjust_expr(&self, pick: &Pick<'tcx>, expr: &hir::Expr<'tcx>) -> (String, bool) {
305 let derefs = "*".repeat(pick.autoderefs);
307 let autoref = match pick.autoref_or_ptr_adjustment {
308 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl: Mutability::Mut, .. }) => "&mut ",
309 Some(probe::AutorefOrPtrAdjustment::Autoref { mutbl: Mutability::Not, .. }) => "&",
310 Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
313 let (expr_text, precise) =
314 if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) {
317 (format!("(..)"), false)
320 let adjusted_text = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
321 pick.autoref_or_ptr_adjustment
323 format!("{}{} as *const _", derefs, expr_text)
325 format!("{}{}{}", autoref, derefs, expr_text)
328 (adjusted_text, precise)