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