2021-03-25 13:29:11 -05:00
|
|
|
use clippy_utils::diagnostics::span_lint_and_help;
|
|
|
|
use clippy_utils::source::snippet;
|
|
|
|
use clippy_utils::{is_entrypoint_fn, is_no_std_crate};
|
2021-09-12 04:58:27 -05:00
|
|
|
use rustc_hir::{Expr, ExprKind, QPath};
|
2020-01-12 00:08:41 -06:00
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
2023-12-01 11:21:58 -06:00
|
|
|
use rustc_session::impl_lint_pass;
|
2019-06-13 03:58:35 -05:00
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for recursion using the entrypoint.
|
2019-06-17 10:36:42 -05:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Apart from special setups (which we could detect following attributes like #![no_std]),
|
2022-05-21 06:24:00 -05:00
|
|
|
/// recursing into main() seems like an unintuitive anti-pattern we should be able to detect.
|
2019-06-17 10:36:42 -05:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2019-06-17 10:36:42 -05:00
|
|
|
/// ```no_run
|
|
|
|
/// fn main() {
|
|
|
|
/// main();
|
|
|
|
/// }
|
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "1.38.0"]
|
2019-06-13 03:58:35 -05:00
|
|
|
pub MAIN_RECURSION,
|
2019-06-17 10:36:42 -05:00
|
|
|
style,
|
|
|
|
"recursion using the entrypoint"
|
2019-06-13 03:58:35 -05:00
|
|
|
}
|
|
|
|
|
2019-06-17 10:36:42 -05:00
|
|
|
#[derive(Default)]
|
2019-06-13 03:58:35 -05:00
|
|
|
pub struct MainRecursion {
|
2019-06-17 10:36:42 -05:00
|
|
|
has_no_std_attr: bool,
|
2019-06-13 03:58:35 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl_lint_pass!(MainRecursion => [MAIN_RECURSION]);
|
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
impl LateLintPass<'_> for MainRecursion {
|
2021-09-12 04:58:27 -05:00
|
|
|
fn check_crate(&mut self, cx: &LateContext<'_>) {
|
2020-11-26 16:38:53 -06:00
|
|
|
self.has_no_std_attr = is_no_std_crate(cx);
|
2019-06-13 03:58:35 -05:00
|
|
|
}
|
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
fn check_expr_post(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
|
2019-06-13 03:58:35 -05:00
|
|
|
if self.has_no_std_attr {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-11-16 12:13:24 -06:00
|
|
|
if let ExprKind::Call(func, _) = &expr.kind
|
|
|
|
&& let ExprKind::Path(QPath::Resolved(_, path)) = &func.kind
|
|
|
|
&& let Some(def_id) = path.res.opt_def_id()
|
|
|
|
&& is_entrypoint_fn(cx, def_id)
|
|
|
|
{
|
|
|
|
span_lint_and_help(
|
|
|
|
cx,
|
|
|
|
MAIN_RECURSION,
|
|
|
|
func.span,
|
|
|
|
&format!("recursing into entrypoint `{}`", snippet(cx, func.span, "main")),
|
|
|
|
None,
|
|
|
|
"consider using another function for this recursion",
|
|
|
|
);
|
2019-06-13 03:58:35 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|