]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/internal_lints.rs
Auto merge of #5373 - flip1995:doc_release_backport, 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_lint, span_lint_and_help, span_lint_and_sugg,
3     walk_ptrs_ty,
4 };
5 use if_chain::if_chain;
6 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, Name, NodeId};
7 use rustc_ast::visit::FnKind;
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_errors::Applicability;
10 use rustc_hir as hir;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
13 use rustc_hir::{Crate, Expr, ExprKind, HirId, Item, MutTy, Mutability, Path, Ty, TyKind};
14 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
15 use rustc_middle::hir::map::Map;
16 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
17 use rustc_span::source_map::{Span, Spanned};
18 use rustc_span::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_clippy_lint! {
123     /// **What it does:** Checks for cases of an auto-generated lint without an updated description,
124     /// i.e. `default lint description`.
125     ///
126     /// **Why is this bad?** Indicates that the lint is not finished.
127     ///
128     /// **Known problems:** None
129     ///
130     /// **Example:**
131     /// Bad:
132     /// ```rust,ignore
133     /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
134     /// ```
135     ///
136     /// Good:
137     /// ```rust,ignore
138     /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
139     /// ```
140     pub DEFAULT_LINT,
141     internal,
142     "found 'default lint description' in a lint declaration"
143 }
144
145 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
146
147 impl EarlyLintPass for ClippyLintsInternal {
148     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
149         if let Some(utils) = krate
150             .module
151             .items
152             .iter()
153             .find(|item| item.ident.name.as_str() == "utils")
154         {
155             if let ItemKind::Mod(ref utils_mod) = utils.kind {
156                 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
157                     if let ItemKind::Mod(ref paths_mod) = paths.kind {
158                         let mut last_name: Option<SymbolStr> = None;
159                         for item in &*paths_mod.items {
160                             let name = item.ident.as_str();
161                             if let Some(ref last_name) = last_name {
162                                 if **last_name > *name {
163                                     span_lint(
164                                         cx,
165                                         CLIPPY_LINTS_INTERNAL,
166                                         item.span,
167                                         "this constant should be before the previous constant due to lexical \
168                                          ordering",
169                                     );
170                                 }
171                             }
172                             last_name = Some(name);
173                         }
174                     }
175                 }
176             }
177         }
178     }
179 }
180
181 #[derive(Clone, Debug, Default)]
182 pub struct LintWithoutLintPass {
183     declared_lints: FxHashMap<Name, Span>,
184     registered_lints: FxHashSet<Name>,
185 }
186
187 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
188
189 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
190     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
191         if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind {
192             if is_lint_ref_type(cx, ty) {
193                 let expr = &cx.tcx.hir().body(body_id).value;
194                 if_chain! {
195                     if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
196                     if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
197                     let field = fields.iter()
198                                       .find(|f| f.ident.as_str() == "desc")
199                                       .expect("lints must have a description field");
200                     if let ExprKind::Lit(Spanned {
201                         node: LitKind::Str(ref sym, _),
202                         ..
203                     }) = field.expr.kind;
204                     if sym.as_str() == "default lint description";
205
206                     then {
207                         span_lint(
208                             cx,
209                             DEFAULT_LINT,
210                             item.span,
211                             &format!("the lint `{}` has the default lint description", item.ident.name),
212                         );
213                     }
214                 }
215                 self.declared_lints.insert(item.ident.name, item.span);
216             }
217         } else if is_expn_of(item.span, "impl_lint_pass").is_some()
218             || is_expn_of(item.span, "declare_lint_pass").is_some()
219         {
220             if let hir::ItemKind::Impl {
221                 of_trait: None,
222                 items: ref impl_item_refs,
223                 ..
224             } = item.kind
225             {
226                 let mut collector = LintCollector {
227                     output: &mut self.registered_lints,
228                     cx,
229                 };
230                 let body_id = cx.tcx.hir().body_owned_by(
231                     impl_item_refs
232                         .iter()
233                         .find(|iiref| iiref.ident.as_str() == "get_lints")
234                         .expect("LintPass needs to implement get_lints")
235                         .id
236                         .hir_id,
237                 );
238                 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
239             }
240         }
241     }
242
243     fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate<'_>) {
244         for (lint_name, &lint_span) in &self.declared_lints {
245             // When using the `declare_tool_lint!` macro, the original `lint_span`'s
246             // file points to "<rustc macros>".
247             // `compiletest-rs` thinks that's an error in a different file and
248             // just ignores it. This causes the test in compile-fail/lint_pass
249             // not able to capture the error.
250             // Therefore, we need to climb the macro expansion tree and find the
251             // actual span that invoked `declare_tool_lint!`:
252             let lint_span = lint_span.ctxt().outer_expn_data().call_site;
253
254             if !self.registered_lints.contains(lint_name) {
255                 span_lint(
256                     cx,
257                     LINT_WITHOUT_LINT_PASS,
258                     lint_span,
259                     &format!("the lint `{}` is not added to any `LintPass`", lint_name),
260                 );
261             }
262         }
263     }
264 }
265
266 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty<'_>) -> bool {
267     if let TyKind::Rptr(
268         _,
269         MutTy {
270             ty: ref inner,
271             mutbl: Mutability::Not,
272         },
273     ) = ty.kind
274     {
275         if let TyKind::Path(ref path) = inner.kind {
276             if let Res::Def(DefKind::Struct, def_id) = cx.tables.qpath_res(path, inner.hir_id) {
277                 return match_def_path(cx, def_id, &paths::LINT);
278             }
279         }
280     }
281
282     false
283 }
284
285 struct LintCollector<'a, 'tcx> {
286     output: &'a mut FxHashSet<Name>,
287     cx: &'a LateContext<'a, 'tcx>,
288 }
289
290 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
291     type Map = Map<'tcx>;
292
293     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
294         walk_expr(self, expr);
295     }
296
297     fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
298         if path.segments.len() == 1 {
299             self.output.insert(path.segments[0].ident.name);
300         }
301     }
302     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
303         NestedVisitorMap::All(self.cx.tcx.hir())
304     }
305 }
306
307 #[derive(Clone, Default)]
308 pub struct CompilerLintFunctions {
309     map: FxHashMap<&'static str, &'static str>,
310 }
311
312 impl CompilerLintFunctions {
313     #[must_use]
314     pub fn new() -> Self {
315         let mut map = FxHashMap::default();
316         map.insert("span_lint", "utils::span_lint");
317         map.insert("struct_span_lint", "utils::span_lint");
318         map.insert("lint", "utils::span_lint");
319         map.insert("span_lint_note", "utils::span_lint_and_note");
320         map.insert("span_lint_help", "utils::span_lint_and_help");
321         Self { map }
322     }
323 }
324
325 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
326
327 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
328     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
329         if_chain! {
330             if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind;
331             let fn_name = path.ident;
332             if let Some(sugg) = self.map.get(&*fn_name.as_str());
333             let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
334             if match_type(cx, ty, &paths::EARLY_CONTEXT)
335                 || match_type(cx, ty, &paths::LATE_CONTEXT);
336             then {
337                 span_lint_and_help(
338                     cx,
339                     COMPILER_LINT_FUNCTIONS,
340                     path.ident.span,
341                     "usage of a compiler lint function",
342                     &format!("please use the Clippy variant of this function: `{}`", sugg),
343                 );
344             }
345         }
346     }
347 }
348
349 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
350
351 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OuterExpnDataPass {
352     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
353         let (method_names, arg_lists, spans) = method_calls(expr, 2);
354         let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
355         let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
356         if_chain! {
357             if let ["expn_data", "outer_expn"] = method_names.as_slice();
358             let args = arg_lists[1];
359             if args.len() == 1;
360             let self_arg = &args[0];
361             let self_ty = walk_ptrs_ty(cx.tables.expr_ty(self_arg));
362             if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
363             then {
364                 span_lint_and_sugg(
365                     cx,
366                     OUTER_EXPN_EXPN_DATA,
367                     spans[1].with_hi(expr.span.hi()),
368                     "usage of `outer_expn().expn_data()`",
369                     "try",
370                     "outer_expn_data()".to_string(),
371                     Applicability::MachineApplicable,
372                 );
373             }
374         }
375     }
376 }
377
378 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
379
380 impl EarlyLintPass for ProduceIce {
381     fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
382         if is_trigger_fn(fn_kind) {
383             panic!("Would you like some help with that?");
384         }
385     }
386 }
387
388 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
389     match fn_kind {
390         FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
391         FnKind::Closure(..) => false,
392     }
393 }