]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/internal_lints.rs
Auto merge of #4458 - flip1995:block_in_if_ext_macro, r=phansch
[rust.git] / clippy_lints / src / utils / internal_lints.rs
1 use crate::utils::{
2     match_def_path, match_type, method_calls, 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::{DefKind, Res};
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_lint_pass, declare_tool_lint, impl_lint_pass};
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_errors::Applicability;
13 use syntax::ast::{Crate as AstCrate, ItemKind, Name};
14 use syntax::source_map::Span;
15 use syntax_pos::symbol::LocalInternedString;
16
17 declare_clippy_lint! {
18     /// **What it does:** Checks for various things we like to keep tidy in clippy.
19     ///
20     /// **Why is this bad?** We like to pretend we're an example of tidy code.
21     ///
22     /// **Known problems:** None.
23     ///
24     /// **Example:** Wrong ordering of the util::paths constants.
25     pub CLIPPY_LINTS_INTERNAL,
26     internal,
27     "various things that will negatively affect your clippy experience"
28 }
29
30 declare_clippy_lint! {
31     /// **What it does:** Ensures every lint is associated to a `LintPass`.
32     ///
33     /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
34     /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
35     /// know the name of the lint.
36     ///
37     /// **Known problems:** Only checks for lints associated using the
38     /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
39     ///
40     /// **Example:**
41     /// ```rust,ignore
42     /// declare_lint! { pub LINT_1, ... }
43     /// declare_lint! { pub LINT_2, ... }
44     /// declare_lint! { pub FORGOTTEN_LINT, ... }
45     /// // ...
46     /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
47     /// // missing FORGOTTEN_LINT
48     /// ```
49     pub LINT_WITHOUT_LINT_PASS,
50     internal,
51     "declaring a lint without associating it in a LintPass"
52 }
53
54 declare_clippy_lint! {
55     /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
56     /// variant of the function.
57     ///
58     /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
59     /// warning/error messages.
60     ///
61     /// **Known problems:** None.
62     ///
63     /// **Example:**
64     /// Bad:
65     /// ```rust,ignore
66     /// cx.span_lint(LINT_NAME, "message");
67     /// ```
68     ///
69     /// Good:
70     /// ```rust,ignore
71     /// utils::span_lint(cx, LINT_NAME, "message");
72     /// ```
73     pub COMPILER_LINT_FUNCTIONS,
74     internal,
75     "usage of the lint functions of the compiler instead of the utils::* variant"
76 }
77
78 declare_clippy_lint! {
79     /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
80     /// the `cx.outer_expn_data()`
81     ///
82     /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
83     ///
84     /// **Known problems:** None.
85     ///
86     /// **Example:**
87     /// Bad:
88     /// ```rust,ignore
89     /// expr.span.ctxt().outer().expn_data()
90     /// ```
91     ///
92     /// Good:
93     /// ```rust,ignore
94     /// expr.span.ctxt().outer_expn_data()
95     /// ```
96     pub OUTER_EXPN_EXPN_DATA,
97     internal,
98     "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
99 }
100
101 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
102
103 impl EarlyLintPass for ClippyLintsInternal {
104     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
105         if let Some(utils) = krate
106             .module
107             .items
108             .iter()
109             .find(|item| item.ident.name.as_str() == "utils")
110         {
111             if let ItemKind::Mod(ref utils_mod) = utils.node {
112                 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
113                     if let ItemKind::Mod(ref paths_mod) = paths.node {
114                         let mut last_name: Option<LocalInternedString> = None;
115                         for item in &*paths_mod.items {
116                             let name = item.ident.as_str();
117                             if let Some(ref last_name) = last_name {
118                                 if **last_name > *name {
119                                     span_lint(
120                                         cx,
121                                         CLIPPY_LINTS_INTERNAL,
122                                         item.span,
123                                         "this constant should be before the previous constant due to lexical \
124                                          ordering",
125                                     );
126                                 }
127                             }
128                             last_name = Some(name);
129                         }
130                     }
131                 }
132             }
133         }
134     }
135 }
136
137 #[derive(Clone, Debug, Default)]
138 pub struct LintWithoutLintPass {
139     declared_lints: FxHashMap<Name, Span>,
140     registered_lints: FxHashSet<Name>,
141 }
142
143 impl_lint_pass!(LintWithoutLintPass => [LINT_WITHOUT_LINT_PASS]);
144
145 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
146     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
147         if let hir::ItemKind::Static(ref ty, MutImmutable, _) = item.node {
148             if is_lint_ref_type(cx, ty) {
149                 self.declared_lints.insert(item.ident.name, item.span);
150             }
151         } else if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.node {
152             if_chain! {
153                 if let hir::TraitRef{path, ..} = trait_ref;
154                 if let Res::Def(DefKind::Trait, def_id) = path.res;
155                 if match_def_path(cx, def_id, &paths::LINT_PASS);
156                 then {
157                     let mut collector = LintCollector {
158                         output: &mut self.registered_lints,
159                         cx,
160                     };
161                     let body_id = cx.tcx.hir().body_owned_by(
162                         impl_item_refs
163                             .iter()
164                             .find(|iiref| iiref.ident.as_str() == "get_lints")
165                             .expect("LintPass needs to implement get_lints")
166                             .id.hir_id
167                     );
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.ctxt().outer_expn_data().call_site;
184
185             if !self.registered_lints.contains(lint_name) {
186                 span_lint(
187                     cx,
188                     LINT_WITHOUT_LINT_PASS,
189                     lint_span,
190                     &format!("the lint `{}` is not added to any `LintPass`", lint_name),
191                 );
192             }
193         }
194     }
195 }
196
197 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty) -> bool {
198     if let TyKind::Rptr(
199         _,
200         MutTy {
201             ty: ref inner,
202             mutbl: MutImmutable,
203         },
204     ) = ty.node
205     {
206         if let TyKind::Path(ref path) = inner.node {
207             if let Res::Def(DefKind::Struct, def_id) = cx.tables.qpath_res(path, inner.hir_id) {
208                 return match_def_path(cx, def_id, &paths::LINT);
209             }
210         }
211     }
212
213     false
214 }
215
216 struct LintCollector<'a, 'tcx> {
217     output: &'a mut FxHashSet<Name>,
218     cx: &'a LateContext<'a, 'tcx>,
219 }
220
221 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
222     fn visit_expr(&mut self, expr: &'tcx Expr) {
223         walk_expr(self, expr);
224     }
225
226     fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
227         if path.segments.len() == 1 {
228             self.output.insert(path.segments[0].ident.name);
229         }
230     }
231     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
232         NestedVisitorMap::All(&self.cx.tcx.hir())
233     }
234 }
235
236 #[derive(Clone, Default)]
237 pub struct CompilerLintFunctions {
238     map: FxHashMap<&'static str, &'static str>,
239 }
240
241 impl CompilerLintFunctions {
242     pub fn new() -> Self {
243         let mut map = FxHashMap::default();
244         map.insert("span_lint", "utils::span_lint");
245         map.insert("struct_span_lint", "utils::span_lint");
246         map.insert("lint", "utils::span_lint");
247         map.insert("span_lint_note", "utils::span_note_and_lint");
248         map.insert("span_lint_help", "utils::span_help_and_lint");
249         Self { map }
250     }
251 }
252
253 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
254
255 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
256     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
257         if_chain! {
258             if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
259             let fn_name = path.ident;
260             if let Some(sugg) = self.map.get(&*fn_name.as_str());
261             let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
262             if match_type(cx, ty, &paths::EARLY_CONTEXT)
263                 || match_type(cx, ty, &paths::LATE_CONTEXT);
264             then {
265                 span_help_and_lint(
266                     cx,
267                     COMPILER_LINT_FUNCTIONS,
268                     path.ident.span,
269                     "usage of a compiler lint function",
270                     &format!("please use the Clippy variant of this function: `{}`", sugg),
271                 );
272             }
273         }
274     }
275 }
276
277 pub struct OuterExpnDataPass;
278
279 impl_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
280
281 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OuterExpnDataPass {
282     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
283         let (method_names, arg_lists, spans) = method_calls(expr, 2);
284         let method_names: Vec<LocalInternedString> = method_names.iter().map(|s| s.as_str()).collect();
285         let method_names: Vec<&str> = method_names.iter().map(std::convert::AsRef::as_ref).collect();
286         if_chain! {
287             if let ["expn_data", "outer_expn"] = method_names.as_slice();
288             let args = arg_lists[1];
289             if args.len() == 1;
290             let self_arg = &args[0];
291             let self_ty = walk_ptrs_ty(cx.tables.expr_ty(self_arg));
292             if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
293             then {
294                 span_lint_and_sugg(
295                     cx,
296                     OUTER_EXPN_EXPN_DATA,
297                     spans[1].with_hi(expr.span.hi()),
298                     "usage of `outer_expn().expn_data()`",
299                     "try",
300                     "outer_expn_data()".to_string(),
301                     Applicability::MachineApplicable,
302                 );
303             }
304         }
305     }
306 }