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