]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/main_recursion.rs
Add recursion check on main function
[rust.git] / clippy_lints / src / main_recursion.rs
1
2 use syntax::ast::{Crate, Expr, ExprKind};
3 use syntax::symbol::sym;
4 use rustc::lint::{LintArray, LintPass, EarlyLintPass, EarlyContext};
5 use rustc::{declare_tool_lint, impl_lint_pass};
6
7 use if_chain::if_chain;
8 use crate::utils::span_help_and_lint;
9
10 declare_clippy_lint! {
11     pub MAIN_RECURSION,
12     pedantic,
13     "function named `foo`, which is not a descriptive name"
14 }
15
16 pub struct MainRecursion {
17     has_no_std_attr: bool
18 }
19
20 impl_lint_pass!(MainRecursion => [MAIN_RECURSION]);
21
22 impl MainRecursion {
23     pub fn new() -> MainRecursion {
24         MainRecursion {
25             has_no_std_attr: false
26         }
27     }
28 }
29
30 impl EarlyLintPass for MainRecursion {
31     fn check_crate(&mut self, _: &EarlyContext<'_>, krate: &Crate) {
32         self.has_no_std_attr = krate.attrs.iter().any(|attr| attr.path == sym::no_std);
33     }
34
35     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
36         if self.has_no_std_attr {
37             return;
38         }
39
40         if_chain! {
41             if let ExprKind::Call(func, _) = &expr.node;
42             if let ExprKind::Path(_, path) = &func.node;
43             if *path == sym::main;
44             then {
45                 span_help_and_lint(
46                     cx,
47                     MAIN_RECURSION,
48                     expr.span,
49                     "You are recursing into main()",
50                     "Consider using another function for this recursion"
51                 )
52             }
53         }
54     }
55 }