]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/internal_lints.rs
Auto merge of #3790 - ljedrz:HirIdify_intravisit, r=phansch
[rust.git] / clippy_lints / src / utils / internal_lints.rs
1 use crate::utils::{
2     match_def_path, match_type, paths, span_help_and_lint, span_lint, span_lint_and_sugg, walk_ptrs_ty,
3 };
4 use if_chain::if_chain;
5 use rustc::hir;
6 use rustc::hir::def::Def;
7 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
8 use rustc::hir::*;
9 use rustc::lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::{declare_tool_lint, lint_array};
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_errors::Applicability;
13 use syntax::ast::{Crate as AstCrate, Ident, ItemKind, Name};
14 use syntax::source_map::Span;
15 use syntax::symbol::LocalInternedString;
16
17 /// **What it does:** Checks for various things we like to keep tidy in clippy.
18 ///
19 /// **Why is this bad?** We like to pretend we're an example of tidy code.
20 ///
21 /// **Known problems:** None.
22 ///
23 /// **Example:** Wrong ordering of the util::paths constants.
24 declare_clippy_lint! {
25     pub CLIPPY_LINTS_INTERNAL,
26     internal,
27     "various things that will negatively affect your clippy experience"
28 }
29
30 /// **What it does:** Ensures every lint is associated to a `LintPass`.
31 ///
32 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
33 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
34 /// know the name of the lint.
35 ///
36 /// **Known problems:** Only checks for lints associated using the `lint_array!`
37 /// macro.
38 ///
39 /// **Example:**
40 /// ```rust
41 /// declare_lint! { pub LINT_1, ... }
42 /// declare_lint! { pub LINT_2, ... }
43 /// declare_lint! { pub FORGOTTEN_LINT, ... }
44 /// // ...
45 /// pub struct Pass;
46 /// impl LintPass for Pass {
47 ///     fn get_lints(&self) -> LintArray {
48 ///         lint_array![LINT_1, LINT_2]
49 ///         // missing FORGOTTEN_LINT
50 ///     }
51 /// }
52 /// ```
53 declare_clippy_lint! {
54     pub LINT_WITHOUT_LINT_PASS,
55     internal,
56     "declaring a lint without associating it in a LintPass"
57 }
58
59 /// **What it does:** Checks for the presence of the default hash types "HashMap" or "HashSet"
60 /// and recommends the FxHash* variants.
61 ///
62 /// **Why is this bad?** The FxHash variants have better performance
63 /// and we don't need any collision prevention in clippy.
64 declare_clippy_lint! {
65     pub DEFAULT_HASH_TYPES,
66     internal,
67     "forbid HashMap and HashSet and suggest the FxHash* variants"
68 }
69
70 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
71 /// variant of the function.
72 ///
73 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
74 /// warning/error messages.
75 ///
76 /// **Known problems:** None.
77 ///
78 /// **Example:**
79 /// Bad:
80 /// ```rust
81 /// cx.span_lint(LINT_NAME, "message");
82 /// ```
83 ///
84 /// Good:
85 /// ```rust
86 /// utils::span_lint(cx, LINT_NAME, "message");
87 /// ```
88 declare_clippy_lint! {
89     pub COMPILER_LINT_FUNCTIONS,
90     internal,
91     "usage of the lint functions of the compiler instead of the utils::* variant"
92 }
93
94 #[derive(Copy, Clone)]
95 pub struct Clippy;
96
97 impl LintPass for Clippy {
98     fn get_lints(&self) -> LintArray {
99         lint_array!(CLIPPY_LINTS_INTERNAL)
100     }
101
102     fn name(&self) -> &'static str {
103         "ClippyLintsInternal"
104     }
105 }
106
107 impl EarlyLintPass for Clippy {
108     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
109         if let Some(utils) = krate.module.items.iter().find(|item| item.ident.name == "utils") {
110             if let ItemKind::Mod(ref utils_mod) = utils.node {
111                 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name == "paths") {
112                     if let ItemKind::Mod(ref paths_mod) = paths.node {
113                         let mut last_name: Option<LocalInternedString> = None;
114                         for item in &paths_mod.items {
115                             let name = item.ident.as_str();
116                             if let Some(ref last_name) = last_name {
117                                 if **last_name > *name {
118                                     span_lint(
119                                         cx,
120                                         CLIPPY_LINTS_INTERNAL,
121                                         item.span,
122                                         "this constant should be before the previous constant due to lexical \
123                                          ordering",
124                                     );
125                                 }
126                             }
127                             last_name = Some(name);
128                         }
129                     }
130                 }
131             }
132         }
133     }
134 }
135
136 #[derive(Clone, Debug, Default)]
137 pub struct LintWithoutLintPass {
138     declared_lints: FxHashMap<Name, Span>,
139     registered_lints: FxHashSet<Name>,
140 }
141
142 impl LintPass for LintWithoutLintPass {
143     fn get_lints(&self) -> LintArray {
144         lint_array!(LINT_WITHOUT_LINT_PASS)
145     }
146     fn name(&self) -> &'static str {
147         "LintWithoutLintPass"
148     }
149 }
150
151 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
152     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
153         if let hir::ItemKind::Static(ref ty, MutImmutable, _) = item.node {
154             if is_lint_ref_type(cx, ty) {
155                 self.declared_lints.insert(item.ident.name, item.span);
156             }
157         } else if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.node {
158             if_chain! {
159                 if let hir::TraitRef{path, ..} = trait_ref;
160                 if let Def::Trait(def_id) = path.def;
161                 if match_def_path(cx.tcx, def_id, &paths::LINT_PASS);
162                 then {
163                     let mut collector = LintCollector {
164                         output: &mut self.registered_lints,
165                         cx,
166                     };
167                     let body_id = cx.tcx.hir().body_owned_by(impl_item_refs[0].id.node_id);
168                     collector.visit_expr(&cx.tcx.hir().body(body_id).value);
169                 }
170             }
171         }
172     }
173
174     fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
175         for (lint_name, &lint_span) in &self.declared_lints {
176             // When using the `declare_tool_lint!` macro, the original `lint_span`'s
177             // file points to "<rustc macros>".
178             // `compiletest-rs` thinks that's an error in a different file and
179             // just ignores it. This causes the test in compile-fail/lint_pass
180             // not able to capture the error.
181             // Therefore, we need to climb the macro expansion tree and find the
182             // actual span that invoked `declare_tool_lint!`:
183             let lint_span = lint_span
184                 .ctxt()
185                 .outer()
186                 .expn_info()
187                 .map(|ei| ei.call_site)
188                 .expect("unable to get call_site");
189
190             if !self.registered_lints.contains(lint_name) {
191                 span_lint(
192                     cx,
193                     LINT_WITHOUT_LINT_PASS,
194                     lint_span,
195                     &format!("the lint `{}` is not added to any `LintPass`", lint_name),
196                 );
197             }
198         }
199     }
200 }
201
202 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty) -> bool {
203     if let TyKind::Rptr(
204         _,
205         MutTy {
206             ty: ref inner,
207             mutbl: MutImmutable,
208         },
209     ) = ty.node
210     {
211         if let TyKind::Path(ref path) = inner.node {
212             if let Def::Struct(def_id) = cx.tables.qpath_def(path, inner.hir_id) {
213                 return match_def_path(cx.tcx, def_id, &paths::LINT);
214             }
215         }
216     }
217
218     false
219 }
220
221 struct LintCollector<'a, 'tcx: 'a> {
222     output: &'a mut FxHashSet<Name>,
223     cx: &'a LateContext<'a, 'tcx>,
224 }
225
226 impl<'a, 'tcx: 'a> Visitor<'tcx> for LintCollector<'a, 'tcx> {
227     fn visit_expr(&mut self, expr: &'tcx Expr) {
228         walk_expr(self, expr);
229     }
230
231     fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
232         if path.segments.len() == 1 {
233             self.output.insert(path.segments[0].ident.name);
234         }
235     }
236     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
237         NestedVisitorMap::All(&self.cx.tcx.hir())
238     }
239 }
240
241 pub struct DefaultHashTypes {
242     map: FxHashMap<String, String>,
243 }
244
245 impl DefaultHashTypes {
246     pub fn default() -> Self {
247         let mut map = FxHashMap::default();
248         map.insert("HashMap".to_string(), "FxHashMap".to_string());
249         map.insert("HashSet".to_string(), "FxHashSet".to_string());
250         Self { map }
251     }
252 }
253
254 impl LintPass for DefaultHashTypes {
255     fn get_lints(&self) -> LintArray {
256         lint_array!(DEFAULT_HASH_TYPES)
257     }
258
259     fn name(&self) -> &'static str {
260         "DefaultHashType"
261     }
262 }
263
264 impl EarlyLintPass for DefaultHashTypes {
265     fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
266         let ident_string = ident.to_string();
267         if let Some(replace) = self.map.get(&ident_string) {
268             let msg = format!(
269                 "Prefer {} over {}, it has better performance \
270                  and we don't need any collision prevention in clippy",
271                 replace, ident_string
272             );
273             span_lint_and_sugg(
274                 cx,
275                 DEFAULT_HASH_TYPES,
276                 ident.span,
277                 &msg,
278                 "use",
279                 replace.to_string(),
280                 Applicability::MaybeIncorrect, // FxHashMap, ... needs another import
281             );
282         }
283     }
284 }
285
286 #[derive(Clone, Default)]
287 pub struct CompilerLintFunctions {
288     map: FxHashMap<String, String>,
289 }
290
291 impl CompilerLintFunctions {
292     pub fn new() -> Self {
293         let mut map = FxHashMap::default();
294         map.insert("span_lint".to_string(), "utils::span_lint".to_string());
295         map.insert("struct_span_lint".to_string(), "utils::span_lint".to_string());
296         map.insert("lint".to_string(), "utils::span_lint".to_string());
297         map.insert("span_lint_note".to_string(), "utils::span_note_and_lint".to_string());
298         map.insert("span_lint_help".to_string(), "utils::span_help_and_lint".to_string());
299         Self { map }
300     }
301 }
302
303 impl LintPass for CompilerLintFunctions {
304     fn get_lints(&self) -> LintArray {
305         lint_array!(COMPILER_LINT_FUNCTIONS)
306     }
307
308     fn name(&self) -> &'static str {
309         "CompileLintFunctions"
310     }
311 }
312
313 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
314     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
315         if_chain! {
316             if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
317             let fn_name = path.ident.as_str().to_string();
318             if let Some(sugg) = self.map.get(&fn_name);
319             let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
320             if match_type(cx, ty, &paths::EARLY_CONTEXT)
321                 || match_type(cx, ty, &paths::LATE_CONTEXT);
322             then {
323                 span_help_and_lint(
324                     cx,
325                     COMPILER_LINT_FUNCTIONS,
326                     path.ident.span,
327                     "usage of a compiler lint function",
328                     &format!("Please use the Clippy variant of this function: `{}`", sugg),
329                 );
330             }
331         }
332     }
333 }