]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/method/prelude2021.rs
Rollup merge of #86542 - GuillaumeGomez:line-numbers-aligned-with-content, r=jyn514
[rust.git] / compiler / rustc_typeck / src / check / method / prelude2021.rs
1 use hir::def_id::DefId;
2 use hir::HirId;
3 use hir::ItemKind;
4 use rustc_ast::Mutability;
5 use rustc_errors::Applicability;
6 use rustc_hir as hir;
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};
11 use rustc_span::Span;
12
13 use crate::check::{
14     method::probe::{self, Pick},
15     FnCtxt,
16 };
17
18 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
19     pub(super) fn lint_dot_call_from_2018(
20         &self,
21         self_ty: Ty<'tcx>,
22         segment: &hir::PathSegment<'_>,
23         span: Span,
24         call_expr: &'tcx hir::Expr<'tcx>,
25         self_expr: &'tcx hir::Expr<'tcx>,
26         pick: &Pick<'tcx>,
27         args: &'tcx [hir::Expr<'tcx>],
28     ) {
29         debug!(
30             "lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
31             segment.ident, self_ty, call_expr, self_expr
32         );
33
34         // Rust 2021 and later is already using the new prelude
35         if span.rust_2021() {
36             return;
37         }
38
39         // These are the method names that were added to prelude in Rust 2021
40         if !matches!(segment.ident.name, sym::try_into) {
41             return;
42         }
43
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) {
46             return;
47         }
48
49         if matches!(pick.kind, probe::PickKind::InherentImplPick | probe::PickKind::ObjectPick) {
50             // avoid repeatedly adding unneeded `&*`s
51             if pick.autoderefs == 1
52                 && matches!(
53                     pick.autoref_or_ptr_adjustment,
54                     Some(probe::AutorefOrPtrAdjustment::Autoref { .. })
55                 )
56                 && matches!(self_ty.kind(), Ref(..))
57             {
58                 return;
59             }
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,
64                 self_expr.hir_id,
65                 self_expr.span,
66                 |lint| {
67                     let sp = self_expr.span;
68
69                     let mut lint = lint.build(&format!(
70                         "trait method `{}` will become ambiguous in Rust 2021",
71                         segment.ident.name
72                     ));
73
74                     let derefs = "*".repeat(pick.autoderefs);
75
76                     let autoref = match pick.autoref_or_ptr_adjustment {
77                         Some(probe::AutorefOrPtrAdjustment::Autoref {
78                             mutbl: Mutability::Mut,
79                             ..
80                         }) => "&mut ",
81                         Some(probe::AutorefOrPtrAdjustment::Autoref {
82                             mutbl: Mutability::Not,
83                             ..
84                         }) => "&",
85                         Some(probe::AutorefOrPtrAdjustment::ToConstPtr) | None => "",
86                     };
87                     if let Ok(self_expr) = self.sess().source_map().span_to_snippet(self_expr.span)
88                     {
89                         let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
90                             pick.autoref_or_ptr_adjustment
91                         {
92                             format!("{}{} as *const _", derefs, self_expr)
93                         } else {
94                             format!("{}{}{}", autoref, derefs, self_expr)
95                         };
96
97                         lint.span_suggestion(
98                             sp,
99                             "disambiguate the method call",
100                             format!("({})", self_adjusted),
101                             Applicability::MachineApplicable,
102                         );
103                     } else {
104                         let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
105                             pick.autoref_or_ptr_adjustment
106                         {
107                             format!("{}(...) as *const _", derefs)
108                         } else {
109                             format!("{}{}...", autoref, derefs)
110                         };
111                         lint.span_help(
112                             sp,
113                             &format!("disambiguate the method call with `({})`", self_adjusted,),
114                         );
115                     }
116
117                     lint.emit();
118                 },
119             );
120         } else {
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,
125                 call_expr.hir_id,
126                 call_expr.span,
127                 |lint| {
128                     let sp = call_expr.span;
129                     let trait_name = self.trait_path_or_bare_name(
130                         span,
131                         call_expr.hir_id,
132                         pick.item.container.id(),
133                     );
134
135                     let mut lint = lint.build(&format!(
136                         "trait method `{}` will become ambiguous in Rust 2021",
137                         segment.ident.name
138                     ));
139
140                     let (self_adjusted, precise) = self.adjust_expr(pick, self_expr);
141                     if precise {
142                         let args = args
143                             .iter()
144                             .skip(1)
145                             .map(|arg| {
146                                 format!(
147                                     ", {}",
148                                     self.sess().source_map().span_to_snippet(arg.span).unwrap()
149                                 )
150                             })
151                             .collect::<String>();
152
153                         lint.span_suggestion(
154                             sp,
155                             "disambiguate the associated function",
156                             format!(
157                                 "{}::{}({}{})",
158                                 trait_name, segment.ident.name, self_adjusted, args
159                             ),
160                             Applicability::MachineApplicable,
161                         );
162                     } else {
163                         lint.span_help(
164                             sp,
165                             &format!(
166                                 "disambiguate the associated function with `{}::{}(...)`",
167                                 trait_name, segment.ident,
168                             ),
169                         );
170                     }
171
172                     lint.emit();
173                 },
174             );
175         }
176     }
177
178     pub(super) fn lint_fully_qualified_call_from_2018(
179         &self,
180         span: Span,
181         method_name: Ident,
182         self_ty: Ty<'tcx>,
183         self_ty_span: Span,
184         expr_id: hir::HirId,
185         pick: &Pick<'tcx>,
186     ) {
187         // Rust 2021 and later is already using the new prelude
188         if span.rust_2021() {
189             return;
190         }
191
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) {
194             return;
195         }
196
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) {
199             return;
200         }
201
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) {
205             return;
206         }
207
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());
213
214             let parameter_count = trait_generics.count() - (trait_generics.has_self as usize);
215             let trait_name = if parameter_count == 0 {
216                 trait_path
217             } else {
218                 format!(
219                     "{}<{}>",
220                     trait_path,
221                     std::iter::repeat("_").take(parameter_count).collect::<Vec<_>>().join(", ")
222                 )
223             };
224
225             let mut lint = lint.build(&format!(
226                 "trait-associated function `{}` will become ambiguous in Rust 2021",
227                 method_name.name
228             ));
229
230             let self_ty = self
231                 .sess()
232                 .source_map()
233                 .span_to_snippet(self_ty_span)
234                 .unwrap_or_else(|_| self_ty.to_string());
235
236             lint.span_suggestion(
237                 span,
238                 "disambiguate the associated function",
239                 format!("<{} as {}>::{}", self_ty, trait_name, method_name.name,),
240                 Applicability::MachineApplicable,
241             );
242
243             lint.emit();
244         });
245     }
246
247     fn trait_path_or_bare_name(
248         &self,
249         span: Span,
250         expr_hir_id: HirId,
251         trait_def_id: DefId,
252     ) -> String {
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)
256         })
257     }
258
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.
264             return None;
265         }
266
267         let import_items: Vec<_> = applicable_trait
268             .import_ids
269             .iter()
270             .map(|&import_id| {
271                 let hir_id = self.tcx.hir().local_def_id_to_hir_id(import_id);
272                 self.tcx.hir().expect_item(hir_id)
273             })
274             .collect();
275
276         // Find an identifier with which this trait was imported (note that `_` doesn't count).
277         let any_id = import_items
278             .iter()
279             .filter_map(|item| if item.ident.name != Underscore { Some(item.ident) } else { None })
280             .next();
281         if let Some(any_id) = any_id {
282             return Some(format!("{}", any_id));
283         }
284
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(
289                 path.segments
290                     .iter()
291                     .map(|segment| segment.ident.to_string())
292                     .collect::<Vec<_>>()
293                     .join("::"),
294             ),
295             _ => {
296                 span_bug!(span, "unexpected item kind, expected a use: {:?}", import_items[0].kind);
297             }
298         }
299     }
300
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*
303     /// suggestion.
304     fn adjust_expr(&self, pick: &Pick<'tcx>, expr: &hir::Expr<'tcx>) -> (String, bool) {
305         let derefs = "*".repeat(pick.autoderefs);
306
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 => "",
311         };
312
313         let (expr_text, precise) =
314             if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) {
315                 (expr_text, true)
316             } else {
317                 (format!("(..)"), false)
318             };
319
320         let adjusted_text = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
321             pick.autoref_or_ptr_adjustment
322         {
323             format!("{}{} as *const _", derefs, expr_text)
324         } else {
325             format!("{}{}{}", autoref, derefs, expr_text)
326         };
327
328         (adjusted_text, precise)
329     }
330 }