]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/internal_lints.rs
lint all guard types, not just lock functions
[rust.git] / clippy_lints / src / utils / internal_lints.rs
1 use crate::utils::{
2     is_expn_of, match_def_path, match_type, method_calls, paths, span_lint, span_lint_and_help, span_lint_and_sugg,
3     walk_ptrs_ty,
4 };
5 use if_chain::if_chain;
6 use rustc::hir::map::Map;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_errors::Applicability;
9 use rustc_hir as hir;
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
12 use rustc_hir::*;
13 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
14 use rustc_session::declare_tool_lint;
15 use rustc_session::{declare_lint_pass, impl_lint_pass};
16 use rustc_span::source_map::{Span, Spanned};
17 use rustc_span::symbol::SymbolStr;
18 use syntax::ast;
19 use syntax::ast::{Crate as AstCrate, ItemKind, LitKind, Name};
20 use syntax::visit::FnKind;
21
22 declare_clippy_lint! {
23     /// **What it does:** Checks for various things we like to keep tidy in clippy.
24     ///
25     /// **Why is this bad?** We like to pretend we're an example of tidy code.
26     ///
27     /// **Known problems:** None.
28     ///
29     /// **Example:** Wrong ordering of the util::paths constants.
30     pub CLIPPY_LINTS_INTERNAL,
31     internal,
32     "various things that will negatively affect your clippy experience"
33 }
34
35 declare_clippy_lint! {
36     /// **What it does:** Ensures every lint is associated to a `LintPass`.
37     ///
38     /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
39     /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
40     /// know the name of the lint.
41     ///
42     /// **Known problems:** Only checks for lints associated using the
43     /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
44     ///
45     /// **Example:**
46     /// ```rust,ignore
47     /// declare_lint! { pub LINT_1, ... }
48     /// declare_lint! { pub LINT_2, ... }
49     /// declare_lint! { pub FORGOTTEN_LINT, ... }
50     /// // ...
51     /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
52     /// // missing FORGOTTEN_LINT
53     /// ```
54     pub LINT_WITHOUT_LINT_PASS,
55     internal,
56     "declaring a lint without associating it in a LintPass"
57 }
58
59 declare_clippy_lint! {
60     /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
61     /// variant of the function.
62     ///
63     /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
64     /// warning/error messages.
65     ///
66     /// **Known problems:** None.
67     ///
68     /// **Example:**
69     /// Bad:
70     /// ```rust,ignore
71     /// cx.span_lint(LINT_NAME, "message");
72     /// ```
73     ///
74     /// Good:
75     /// ```rust,ignore
76     /// utils::span_lint(cx, LINT_NAME, "message");
77     /// ```
78     pub COMPILER_LINT_FUNCTIONS,
79     internal,
80     "usage of the lint functions of the compiler instead of the utils::* variant"
81 }
82
83 declare_clippy_lint! {
84     /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
85     /// the `cx.outer_expn_data()`
86     ///
87     /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
88     ///
89     /// **Known problems:** None.
90     ///
91     /// **Example:**
92     /// Bad:
93     /// ```rust,ignore
94     /// expr.span.ctxt().outer().expn_data()
95     /// ```
96     ///
97     /// Good:
98     /// ```rust,ignore
99     /// expr.span.ctxt().outer_expn_data()
100     /// ```
101     pub OUTER_EXPN_EXPN_DATA,
102     internal,
103     "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
104 }
105
106 declare_clippy_lint! {
107     /// **What it does:** Not an actual lint. This lint is only meant for testing our customized internal compiler
108     /// error message by calling `panic`.
109     ///
110     /// **Why is this bad?** ICE in large quantities can damage your teeth
111     ///
112     /// **Known problems:** None
113     ///
114     /// **Example:**
115     /// Bad:
116     /// ```rust,ignore
117     /// 🍦🍦🍦🍦🍦
118     /// ```
119     pub PRODUCE_ICE,
120     internal,
121     "this message should not appear anywhere as we ICE before and don't emit the lint"
122 }
123
124 declare_clippy_lint! {
125     /// **What it does:** Checks for cases of an auto-generated lint without an updated description,
126     /// i.e. `default lint description`.
127     ///
128     /// **Why is this bad?** Indicates that the lint is not finished.
129     ///
130     /// **Known problems:** None
131     ///
132     /// **Example:**
133     /// Bad:
134     /// ```rust,ignore
135     /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
136     /// ```
137     ///
138     /// Good:
139     /// ```rust,ignore
140     /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
141     /// ```
142     pub DEFAULT_LINT,
143     internal,
144     "found 'default lint description' in a lint declaration"
145 }
146
147 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
148
149 impl EarlyLintPass for ClippyLintsInternal {
150     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
151         if let Some(utils) = krate
152             .module
153             .items
154             .iter()
155             .find(|item| item.ident.name.as_str() == "utils")
156         {
157             if let ItemKind::Mod(ref utils_mod) = utils.kind {
158                 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
159                     if let ItemKind::Mod(ref paths_mod) = paths.kind {
160                         let mut last_name: Option<SymbolStr> = None;
161                         for item in &*paths_mod.items {
162                             let name = item.ident.as_str();
163                             if let Some(ref last_name) = last_name {
164                                 if **last_name > *name {
165                                     span_lint(
166                                         cx,
167                                         CLIPPY_LINTS_INTERNAL,
168                                         item.span,
169                                         "this constant should be before the previous constant due to lexical \
170                                          ordering",
171                                     );
172                                 }
173                             }
174                             last_name = Some(name);
175                         }
176                     }
177                 }
178             }
179         }
180     }
181 }
182
183 #[derive(Clone, Debug, Default)]
184 pub struct LintWithoutLintPass {
185     declared_lints: FxHashMap<Name, Span>,
186     registered_lints: FxHashSet<Name>,
187 }
188
189 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
190
191 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
192     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
193         if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind {
194             if is_lint_ref_type(cx, ty) {
195                 let expr = &cx.tcx.hir().body(body_id).value;
196                 if_chain! {
197                     if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
198                     if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
199                     let field = fields.iter()
200                                       .find(|f| f.ident.as_str() == "desc")
201                                       .expect("lints must have a description field");
202                     if let ExprKind::Lit(Spanned {
203                         node: LitKind::Str(ref sym, _),
204                         ..
205                     }) = field.expr.kind;
206                     if sym.as_str() == "default lint description";
207
208                     then {
209                         span_lint(
210                             cx,
211                             DEFAULT_LINT,
212                             item.span,
213                             &format!("the lint `{}` has the default lint description", item.ident.name),
214                         );
215                     }
216                 }
217                 self.declared_lints.insert(item.ident.name, item.span);
218             }
219         } else if is_expn_of(item.span, "impl_lint_pass").is_some()
220             || is_expn_of(item.span, "declare_lint_pass").is_some()
221         {
222             if let hir::ItemKind::Impl {
223                 of_trait: None,
224                 items: ref impl_item_refs,
225                 ..
226             } = item.kind
227             {
228                 let mut collector = LintCollector {
229                     output: &mut self.registered_lints,
230                     cx,
231                 };
232                 let body_id = cx.tcx.hir().body_owned_by(
233                     impl_item_refs
234                         .iter()
235                         .find(|iiref| iiref.ident.as_str() == "get_lints")
236                         .expect("LintPass needs to implement get_lints")
237                         .id
238                         .hir_id,
239                 );
240                 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
241             }
242         }
243     }
244
245     fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate<'_>) {
246         for (lint_name, &lint_span) in &self.declared_lints {
247             // When using the `declare_tool_lint!` macro, the original `lint_span`'s
248             // file points to "<rustc macros>".
249             // `compiletest-rs` thinks that's an error in a different file and
250             // just ignores it. This causes the test in compile-fail/lint_pass
251             // not able to capture the error.
252             // Therefore, we need to climb the macro expansion tree and find the
253             // actual span that invoked `declare_tool_lint!`:
254             let lint_span = lint_span.ctxt().outer_expn_data().call_site;
255
256             if !self.registered_lints.contains(lint_name) {
257                 span_lint(
258                     cx,
259                     LINT_WITHOUT_LINT_PASS,
260                     lint_span,
261                     &format!("the lint `{}` is not added to any `LintPass`", lint_name),
262                 );
263             }
264         }
265     }
266 }
267
268 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty<'_>) -> bool {
269     if let TyKind::Rptr(
270         _,
271         MutTy {
272             ty: ref inner,
273             mutbl: Mutability::Not,
274         },
275     ) = ty.kind
276     {
277         if let TyKind::Path(ref path) = inner.kind {
278             if let Res::Def(DefKind::Struct, def_id) = cx.tables.qpath_res(path, inner.hir_id) {
279                 return match_def_path(cx, def_id, &paths::LINT);
280             }
281         }
282     }
283
284     false
285 }
286
287 struct LintCollector<'a, 'tcx> {
288     output: &'a mut FxHashSet<Name>,
289     cx: &'a LateContext<'a, 'tcx>,
290 }
291
292 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
293     type Map = Map<'tcx>;
294
295     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
296         walk_expr(self, expr);
297     }
298
299     fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
300         if path.segments.len() == 1 {
301             self.output.insert(path.segments[0].ident.name);
302         }
303     }
304     fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
305         NestedVisitorMap::All(&self.cx.tcx.hir())
306     }
307 }
308
309 #[derive(Clone, Default)]
310 pub struct CompilerLintFunctions {
311     map: FxHashMap<&'static str, &'static str>,
312 }
313
314 impl CompilerLintFunctions {
315     #[must_use]
316     pub fn new() -> Self {
317         let mut map = FxHashMap::default();
318         map.insert("span_lint", "utils::span_lint");
319         map.insert("struct_span_lint", "utils::span_lint");
320         map.insert("lint", "utils::span_lint");
321         map.insert("span_lint_note", "utils::span_lint_and_note");
322         map.insert("span_lint_help", "utils::span_lint_and_help");
323         Self { map }
324     }
325 }
326
327 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
328
329 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
330     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
331         if_chain! {
332             if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind;
333             let fn_name = path.ident;
334             if let Some(sugg) = self.map.get(&*fn_name.as_str());
335             let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
336             if match_type(cx, ty, &paths::EARLY_CONTEXT)
337                 || match_type(cx, ty, &paths::LATE_CONTEXT);
338             then {
339                 span_lint_and_help(
340                     cx,
341                     COMPILER_LINT_FUNCTIONS,
342                     path.ident.span,
343                     "usage of a compiler lint function",
344                     &format!("please use the Clippy variant of this function: `{}`", sugg),
345                 );
346             }
347         }
348     }
349 }
350
351 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
352
353 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OuterExpnDataPass {
354     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
355         let (method_names, arg_lists, spans) = method_calls(expr, 2);
356         let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
357         let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
358         if_chain! {
359             if let ["expn_data", "outer_expn"] = method_names.as_slice();
360             let args = arg_lists[1];
361             if args.len() == 1;
362             let self_arg = &args[0];
363             let self_ty = walk_ptrs_ty(cx.tables.expr_ty(self_arg));
364             if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
365             then {
366                 span_lint_and_sugg(
367                     cx,
368                     OUTER_EXPN_EXPN_DATA,
369                     spans[1].with_hi(expr.span.hi()),
370                     "usage of `outer_expn().expn_data()`",
371                     "try",
372                     "outer_expn_data()".to_string(),
373                     Applicability::MachineApplicable,
374                 );
375             }
376         }
377     }
378 }
379
380 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
381
382 impl EarlyLintPass for ProduceIce {
383     fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &ast::FnDecl, _: Span, _: ast::NodeId) {
384         if is_trigger_fn(fn_kind) {
385             panic!("Testing the ICE message");
386         }
387     }
388 }
389
390 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
391     match fn_kind {
392         FnKind::ItemFn(ident, ..) | FnKind::Method(ident, ..) => {
393             ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy"
394         },
395         FnKind::Closure(..) => false,
396     }
397 }