]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/main_recursion.rs
Rollup merge of #91630 - GuillaumeGomez:missing-whitespace, r=notriddle
[rust.git] / src / tools / clippy / clippy_lints / src / main_recursion.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::source::snippet;
3 use clippy_utils::{is_entrypoint_fn, is_no_std_crate};
4 use if_chain::if_chain;
5 use rustc_hir::{Expr, ExprKind, QPath};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
8
9 declare_clippy_lint! {
10     /// ### What it does
11     /// Checks for recursion using the entrypoint.
12     ///
13     /// ### Why is this bad?
14     /// 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     /// ### Example
18     /// ```no_run
19     /// fn main() {
20     ///     main();
21     /// }
22     /// ```
23     #[clippy::version = "1.38.0"]
24     pub MAIN_RECURSION,
25     style,
26     "recursion using the entrypoint"
27 }
28
29 #[derive(Default)]
30 pub struct MainRecursion {
31     has_no_std_attr: bool,
32 }
33
34 impl_lint_pass!(MainRecursion => [MAIN_RECURSION]);
35
36 impl LateLintPass<'_> for MainRecursion {
37     fn check_crate(&mut self, cx: &LateContext<'_>) {
38         self.has_no_std_attr = is_no_std_crate(cx);
39     }
40
41     fn check_expr_post(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
42         if self.has_no_std_attr {
43             return;
44         }
45
46         if_chain! {
47             if let ExprKind::Call(func, _) = &expr.kind;
48             if let ExprKind::Path(QPath::Resolved(_, path)) = &func.kind;
49             if let Some(def_id) = path.res.opt_def_id();
50             if is_entrypoint_fn(cx, def_id);
51             then {
52                 span_lint_and_help(
53                     cx,
54                     MAIN_RECURSION,
55                     func.span,
56                     &format!("recursing into entrypoint `{}`", snippet(cx, func.span, "main")),
57                     None,
58                     "consider using another function for this recursion"
59                 )
60             }
61         }
62     }
63 }