]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/internal_lints.rs
Auto merge of #3646 - matthiaskrgr:travis, 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
103 impl EarlyLintPass for Clippy {
104     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
105         if let Some(utils) = krate.module.items.iter().find(|item| item.ident.name == "utils") {
106             if let ItemKind::Mod(ref utils_mod) = utils.node {
107                 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name == "paths") {
108                     if let ItemKind::Mod(ref paths_mod) = paths.node {
109                         let mut last_name: Option<LocalInternedString> = None;
110                         for item in &paths_mod.items {
111                             let name = item.ident.as_str();
112                             if let Some(ref last_name) = last_name {
113                                 if **last_name > *name {
114                                     span_lint(
115                                         cx,
116                                         CLIPPY_LINTS_INTERNAL,
117                                         item.span,
118                                         "this constant should be before the previous constant due to lexical \
119                                          ordering",
120                                     );
121                                 }
122                             }
123                             last_name = Some(name);
124                         }
125                     }
126                 }
127             }
128         }
129     }
130 }
131
132 #[derive(Clone, Debug, Default)]
133 pub struct LintWithoutLintPass {
134     declared_lints: FxHashMap<Name, Span>,
135     registered_lints: FxHashSet<Name>,
136 }
137
138 impl LintPass for LintWithoutLintPass {
139     fn get_lints(&self) -> LintArray {
140         lint_array!(LINT_WITHOUT_LINT_PASS)
141     }
142 }
143
144 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
145     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
146         if let hir::ItemKind::Static(ref ty, MutImmutable, _) = item.node {
147             if is_lint_ref_type(cx, ty) {
148                 self.declared_lints.insert(item.ident.name, item.span);
149             }
150         } else if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.node {
151             if_chain! {
152                 if let hir::TraitRef{path, ..} = trait_ref;
153                 if let Def::Trait(def_id) = path.def;
154                 if match_def_path(cx.tcx, def_id, &paths::LINT_PASS);
155                 then {
156                     let mut collector = LintCollector {
157                         output: &mut self.registered_lints,
158                         cx,
159                     };
160                     let body_id = cx.tcx.hir().body_owned_by(impl_item_refs[0].id.node_id);
161                     collector.visit_expr(&cx.tcx.hir().body(body_id).value);
162                 }
163             }
164         }
165     }
166
167     fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
168         for (lint_name, &lint_span) in &self.declared_lints {
169             // When using the `declare_tool_lint!` macro, the original `lint_span`'s
170             // file points to "<rustc macros>".
171             // `compiletest-rs` thinks that's an error in a different file and
172             // just ignores it. This causes the test in compile-fail/lint_pass
173             // not able to capture the error.
174             // Therefore, we need to climb the macro expansion tree and find the
175             // actual span that invoked `declare_tool_lint!`:
176             let lint_span = lint_span
177                 .ctxt()
178                 .outer()
179                 .expn_info()
180                 .map(|ei| ei.call_site)
181                 .expect("unable to get call_site");
182
183             if !self.registered_lints.contains(lint_name) {
184                 span_lint(
185                     cx,
186                     LINT_WITHOUT_LINT_PASS,
187                     lint_span,
188                     &format!("the lint `{}` is not added to any `LintPass`", lint_name),
189                 );
190             }
191         }
192     }
193 }
194
195 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty) -> bool {
196     if let TyKind::Rptr(
197         _,
198         MutTy {
199             ty: ref inner,
200             mutbl: MutImmutable,
201         },
202     ) = ty.node
203     {
204         if let TyKind::Path(ref path) = inner.node {
205             if let Def::Struct(def_id) = cx.tables.qpath_def(path, inner.hir_id) {
206                 return match_def_path(cx.tcx, def_id, &paths::LINT);
207             }
208         }
209     }
210
211     false
212 }
213
214 struct LintCollector<'a, 'tcx: 'a> {
215     output: &'a mut FxHashSet<Name>,
216     cx: &'a LateContext<'a, 'tcx>,
217 }
218
219 impl<'a, 'tcx: 'a> Visitor<'tcx> for LintCollector<'a, 'tcx> {
220     fn visit_expr(&mut self, expr: &'tcx Expr) {
221         walk_expr(self, expr);
222     }
223
224     fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
225         if path.segments.len() == 1 {
226             self.output.insert(path.segments[0].ident.name);
227         }
228     }
229     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
230         NestedVisitorMap::All(&self.cx.tcx.hir())
231     }
232 }
233
234 pub struct DefaultHashTypes {
235     map: FxHashMap<String, String>,
236 }
237
238 impl DefaultHashTypes {
239     pub fn default() -> Self {
240         let mut map = FxHashMap::default();
241         map.insert("HashMap".to_string(), "FxHashMap".to_string());
242         map.insert("HashSet".to_string(), "FxHashSet".to_string());
243         Self { map }
244     }
245 }
246
247 impl LintPass for DefaultHashTypes {
248     fn get_lints(&self) -> LintArray {
249         lint_array!(DEFAULT_HASH_TYPES)
250     }
251 }
252
253 impl EarlyLintPass for DefaultHashTypes {
254     fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
255         let ident_string = ident.to_string();
256         if let Some(replace) = self.map.get(&ident_string) {
257             let msg = format!(
258                 "Prefer {} over {}, it has better performance \
259                  and we don't need any collision prevention in clippy",
260                 replace, ident_string
261             );
262             span_lint_and_sugg(
263                 cx,
264                 DEFAULT_HASH_TYPES,
265                 ident.span,
266                 &msg,
267                 "use",
268                 replace.to_string(),
269                 Applicability::MaybeIncorrect, // FxHashMap, ... needs another import
270             );
271         }
272     }
273 }
274
275 #[derive(Clone, Default)]
276 pub struct CompilerLintFunctions {
277     map: FxHashMap<String, String>,
278 }
279
280 impl CompilerLintFunctions {
281     pub fn new() -> Self {
282         let mut map = FxHashMap::default();
283         map.insert("span_lint".to_string(), "utils::span_lint".to_string());
284         map.insert("struct_span_lint".to_string(), "utils::span_lint".to_string());
285         map.insert("lint".to_string(), "utils::span_lint".to_string());
286         map.insert("span_lint_note".to_string(), "utils::span_note_and_lint".to_string());
287         map.insert("span_lint_help".to_string(), "utils::span_help_and_lint".to_string());
288         Self { map }
289     }
290 }
291
292 impl LintPass for CompilerLintFunctions {
293     fn get_lints(&self) -> LintArray {
294         lint_array!(COMPILER_LINT_FUNCTIONS)
295     }
296 }
297
298 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
299     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
300         if_chain! {
301             if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
302             let fn_name = path.ident.as_str().to_string();
303             if let Some(sugg) = self.map.get(&fn_name);
304             let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
305             if match_type(cx, ty, &paths::EARLY_CONTEXT)
306                 || match_type(cx, ty, &paths::LATE_CONTEXT);
307             then {
308                 span_help_and_lint(
309                     cx,
310                     COMPILER_LINT_FUNCTIONS,
311                     path.ident.span,
312                     "usage of a compiler lint function",
313                     &format!("Please use the Clippy variant of this function: `{}`", sugg),
314                 );
315             }
316         }
317     }
318 }