]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/main_recursion.rs
Auto merge of #4938 - flip1995:rustup, r=flip1995
[rust.git] / clippy_lints / src / main_recursion.rs
1 use rustc::hir::{Crate, Expr, ExprKind, QPath};
2 use rustc::impl_lint_pass;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc_session::declare_tool_lint;
5 use syntax::ast::AttrKind;
6 use syntax::symbol::sym;
7
8 use crate::utils::{is_entrypoint_fn, snippet, span_help_and_lint};
9 use if_chain::if_chain;
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for recursion using the entrypoint.
13     ///
14     /// **Why is this bad?** Apart from special setups (which we could detect following attributes like #![no_std]),
15     /// recursing into main() seems like an unintuitive antipattern we should be able to detect.
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     /// ```no_run
21     /// fn main() {
22     ///     main();
23     /// }
24     /// ```
25     pub MAIN_RECURSION,
26     style,
27     "recursion using the entrypoint"
28 }
29
30 #[derive(Default)]
31 pub struct MainRecursion {
32     has_no_std_attr: bool,
33 }
34
35 impl_lint_pass!(MainRecursion => [MAIN_RECURSION]);
36
37 impl LateLintPass<'_, '_> for MainRecursion {
38     fn check_crate(&mut self, _: &LateContext<'_, '_>, krate: &Crate<'_>) {
39         self.has_no_std_attr = krate.attrs.iter().any(|attr| {
40             if let AttrKind::Normal(ref attr) = attr.kind {
41                 attr.path == sym::no_std
42             } else {
43                 false
44             }
45         });
46     }
47
48     fn check_expr_post(&mut self, cx: &LateContext<'_, '_>, expr: &Expr) {
49         if self.has_no_std_attr {
50             return;
51         }
52
53         if_chain! {
54             if let ExprKind::Call(func, _) = &expr.kind;
55             if let ExprKind::Path(path) = &func.kind;
56             if let QPath::Resolved(_, path) = &path;
57             if let Some(def_id) = path.res.opt_def_id();
58             if is_entrypoint_fn(cx, def_id);
59             then {
60                 span_help_and_lint(
61                     cx,
62                     MAIN_RECURSION,
63                     func.span,
64                     &format!("recursing into entrypoint `{}`", snippet(cx, func.span, "main")),
65                     "consider using another function for this recursion"
66                 )
67             }
68         }
69     }
70 }