]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/internal_lints.rs
Auto merge of #4159 - lzutao:into-outer_expn_info, r=matthiaskrgr
[rust.git] / clippy_lints / src / utils / internal_lints.rs
1 use crate::utils::{match_def_path, 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::{DefKind, Res};
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_lint_pass, declare_tool_lint, impl_lint_pass};
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_pos::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
35     /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
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     /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
44     /// // missing FORGOTTEN_LINT
45     /// ```
46     pub LINT_WITHOUT_LINT_PASS,
47     internal,
48     "declaring a lint without associating it in a LintPass"
49 }
50
51 declare_clippy_lint! {
52     /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
53     /// variant of the function.
54     ///
55     /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
56     /// warning/error messages.
57     ///
58     /// **Known problems:** None.
59     ///
60     /// **Example:**
61     /// Bad:
62     /// ```rust
63     /// cx.span_lint(LINT_NAME, "message");
64     /// ```
65     ///
66     /// Good:
67     /// ```rust
68     /// utils::span_lint(cx, LINT_NAME, "message");
69     /// ```
70     pub COMPILER_LINT_FUNCTIONS,
71     internal,
72     "usage of the lint functions of the compiler instead of the utils::* variant"
73 }
74
75 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
76
77 impl EarlyLintPass for ClippyLintsInternal {
78     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
79         if let Some(utils) = krate
80             .module
81             .items
82             .iter()
83             .find(|item| item.ident.name.as_str() == "utils")
84         {
85             if let ItemKind::Mod(ref utils_mod) = utils.node {
86                 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
87                     if let ItemKind::Mod(ref paths_mod) = paths.node {
88                         let mut last_name: Option<LocalInternedString> = None;
89                         for item in &*paths_mod.items {
90                             let name = item.ident.as_str();
91                             if let Some(ref last_name) = last_name {
92                                 if **last_name > *name {
93                                     span_lint(
94                                         cx,
95                                         CLIPPY_LINTS_INTERNAL,
96                                         item.span,
97                                         "this constant should be before the previous constant due to lexical \
98                                          ordering",
99                                     );
100                                 }
101                             }
102                             last_name = Some(name);
103                         }
104                     }
105                 }
106             }
107         }
108     }
109 }
110
111 #[derive(Clone, Debug, Default)]
112 pub struct LintWithoutLintPass {
113     declared_lints: FxHashMap<Name, Span>,
114     registered_lints: FxHashSet<Name>,
115 }
116
117 impl_lint_pass!(LintWithoutLintPass => [LINT_WITHOUT_LINT_PASS]);
118
119 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
120     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
121         if let hir::ItemKind::Static(ref ty, MutImmutable, _) = item.node {
122             if is_lint_ref_type(cx, ty) {
123                 self.declared_lints.insert(item.ident.name, item.span);
124             }
125         } else if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.node {
126             if_chain! {
127                 if let hir::TraitRef{path, ..} = trait_ref;
128                 if let Res::Def(DefKind::Trait, def_id) = path.res;
129                 if match_def_path(cx, def_id, &paths::LINT_PASS);
130                 then {
131                     let mut collector = LintCollector {
132                         output: &mut self.registered_lints,
133                         cx,
134                     };
135                     let body_id = cx.tcx.hir().body_owned_by(
136                         impl_item_refs
137                             .iter()
138                             .find(|iiref| iiref.ident.as_str() == "get_lints")
139                             .expect("LintPass needs to implement get_lints")
140                             .id.hir_id
141                     );
142                     collector.visit_expr(&cx.tcx.hir().body(body_id).value);
143                 }
144             }
145         }
146     }
147
148     fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
149         for (lint_name, &lint_span) in &self.declared_lints {
150             // When using the `declare_tool_lint!` macro, the original `lint_span`'s
151             // file points to "<rustc macros>".
152             // `compiletest-rs` thinks that's an error in a different file and
153             // just ignores it. This causes the test in compile-fail/lint_pass
154             // not able to capture the error.
155             // Therefore, we need to climb the macro expansion tree and find the
156             // actual span that invoked `declare_tool_lint!`:
157             let lint_span = lint_span
158                 .ctxt()
159                 .outer_expn_info()
160                 .map(|ei| ei.call_site)
161                 .expect("unable to get call_site");
162
163             if !self.registered_lints.contains(lint_name) {
164                 span_lint(
165                     cx,
166                     LINT_WITHOUT_LINT_PASS,
167                     lint_span,
168                     &format!("the lint `{}` is not added to any `LintPass`", lint_name),
169                 );
170             }
171         }
172     }
173 }
174
175 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty) -> bool {
176     if let TyKind::Rptr(
177         _,
178         MutTy {
179             ty: ref inner,
180             mutbl: MutImmutable,
181         },
182     ) = ty.node
183     {
184         if let TyKind::Path(ref path) = inner.node {
185             if let Res::Def(DefKind::Struct, def_id) = cx.tables.qpath_res(path, inner.hir_id) {
186                 return match_def_path(cx, def_id, &paths::LINT);
187             }
188         }
189     }
190
191     false
192 }
193
194 struct LintCollector<'a, 'tcx: 'a> {
195     output: &'a mut FxHashSet<Name>,
196     cx: &'a LateContext<'a, 'tcx>,
197 }
198
199 impl<'a, 'tcx: 'a> Visitor<'tcx> for LintCollector<'a, 'tcx> {
200     fn visit_expr(&mut self, expr: &'tcx Expr) {
201         walk_expr(self, expr);
202     }
203
204     fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
205         if path.segments.len() == 1 {
206             self.output.insert(path.segments[0].ident.name);
207         }
208     }
209     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
210         NestedVisitorMap::All(&self.cx.tcx.hir())
211     }
212 }
213
214 #[derive(Clone, Default)]
215 pub struct CompilerLintFunctions {
216     map: FxHashMap<String, String>,
217 }
218
219 impl CompilerLintFunctions {
220     pub fn new() -> Self {
221         let mut map = FxHashMap::default();
222         map.insert("span_lint".to_string(), "utils::span_lint".to_string());
223         map.insert("struct_span_lint".to_string(), "utils::span_lint".to_string());
224         map.insert("lint".to_string(), "utils::span_lint".to_string());
225         map.insert("span_lint_note".to_string(), "utils::span_note_and_lint".to_string());
226         map.insert("span_lint_help".to_string(), "utils::span_help_and_lint".to_string());
227         Self { map }
228     }
229 }
230
231 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
232
233 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
234     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
235         if_chain! {
236             if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
237             let fn_name = path.ident.as_str().to_string();
238             if let Some(sugg) = self.map.get(&fn_name);
239             let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
240             if match_type(cx, ty, &paths::EARLY_CONTEXT)
241                 || match_type(cx, ty, &paths::LATE_CONTEXT);
242             then {
243                 span_help_and_lint(
244                     cx,
245                     COMPILER_LINT_FUNCTIONS,
246                     path.ident.span,
247                     "usage of a compiler lint function",
248                     &format!("please use the Clippy variant of this function: `{}`", sugg),
249                 );
250             }
251         }
252     }
253 }