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