2021-03-16 00:55:45 +00:00
|
|
|
use clippy_utils::diagnostics::span_lint_and_help;
|
2021-03-14 23:17:44 +00:00
|
|
|
use clippy_utils::source::snippet;
|
2021-03-16 16:06:34 +00:00
|
|
|
use clippy_utils::{is_entrypoint_fn, is_no_std_crate};
|
2021-03-14 23:17:44 +00:00
|
|
|
use if_chain::if_chain;
|
2020-01-06 16:39:50 +00:00
|
|
|
use rustc_hir::{Crate, Expr, ExprKind, QPath};
|
2020-01-12 06:08:41 +00:00
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
2020-01-11 11:37:08 +00:00
|
|
|
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
2019-06-13 08:58:35 +00:00
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2019-06-17 15:36:42 +00:00
|
|
|
/// **What it does:** Checks for recursion using the entrypoint.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** Apart from special setups (which we could detect following attributes like #![no_std]),
|
|
|
|
/// recursing into main() seems like an unintuitive antipattern we should be able to detect.
|
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
/// ```no_run
|
|
|
|
/// fn main() {
|
|
|
|
/// main();
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-06-13 08:58:35 +00:00
|
|
|
pub MAIN_RECURSION,
|
2019-06-17 15:36:42 +00:00
|
|
|
style,
|
|
|
|
"recursion using the entrypoint"
|
2019-06-13 08:58:35 +00:00
|
|
|
}
|
|
|
|
|
2019-06-17 15:36:42 +00:00
|
|
|
#[derive(Default)]
|
2019-06-13 08:58:35 +00:00
|
|
|
pub struct MainRecursion {
|
2019-06-17 15:36:42 +00:00
|
|
|
has_no_std_attr: bool,
|
2019-06-13 08:58:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl_lint_pass!(MainRecursion => [MAIN_RECURSION]);
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
impl LateLintPass<'_> for MainRecursion {
|
2020-11-26 22:38:53 +00:00
|
|
|
fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
|
|
|
|
self.has_no_std_attr = is_no_std_crate(cx);
|
2019-06-13 08:58:35 +00:00
|
|
|
}
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
fn check_expr_post(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
|
2019-06-13 08:58:35 +00:00
|
|
|
if self.has_no_std_attr {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if_chain! {
|
2019-09-27 15:16:06 +00:00
|
|
|
if let ExprKind::Call(func, _) = &expr.kind;
|
2021-01-30 17:06:34 +00:00
|
|
|
if let ExprKind::Path(QPath::Resolved(_, path)) = &func.kind;
|
2019-06-17 15:36:42 +00:00
|
|
|
if let Some(def_id) = path.res.opt_def_id();
|
|
|
|
if is_entrypoint_fn(cx, def_id);
|
2019-06-13 08:58:35 +00:00
|
|
|
then {
|
2020-01-27 01:56:22 +00:00
|
|
|
span_lint_and_help(
|
2019-06-13 08:58:35 +00:00
|
|
|
cx,
|
|
|
|
MAIN_RECURSION,
|
2019-06-17 15:36:42 +00:00
|
|
|
func.span,
|
|
|
|
&format!("recursing into entrypoint `{}`", snippet(cx, func.span, "main")),
|
2020-04-18 10:28:29 +00:00
|
|
|
None,
|
2019-06-17 15:36:42 +00:00
|
|
|
"consider using another function for this recursion"
|
2019-06-13 08:58:35 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|