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