2019-06-17 15:36:42 +00:00
|
|
|
use rustc::hir::{Crate, Expr, ExprKind, QPath};
|
|
|
|
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
|
2019-06-13 08:58:35 +00:00
|
|
|
use rustc::{declare_tool_lint, impl_lint_pass};
|
2019-06-17 15:36:42 +00:00
|
|
|
use syntax::symbol::sym;
|
2019-06-13 08:58:35 +00:00
|
|
|
|
2019-06-17 15:36:42 +00:00
|
|
|
use crate::utils::{is_entrypoint_fn, snippet, span_help_and_lint};
|
2019-06-13 08:58:35 +00:00
|
|
|
use if_chain::if_chain;
|
|
|
|
|
|
|
|
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]);
|
|
|
|
|
2019-06-17 15:36:42 +00:00
|
|
|
impl LateLintPass<'_, '_> for MainRecursion {
|
|
|
|
fn check_crate(&mut self, _: &LateContext<'_, '_>, krate: &Crate) {
|
2019-06-13 08:58:35 +00:00
|
|
|
self.has_no_std_attr = krate.attrs.iter().any(|attr| attr.path == sym::no_std);
|
|
|
|
}
|
|
|
|
|
2019-06-17 15:36:42 +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! {
|
|
|
|
if let ExprKind::Call(func, _) = &expr.node;
|
2019-06-17 15:36:42 +00:00
|
|
|
if let ExprKind::Path(path) = &func.node;
|
|
|
|
if let QPath::Resolved(_, path) = &path;
|
|
|
|
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 {
|
|
|
|
span_help_and_lint(
|
|
|
|
cx,
|
|
|
|
MAIN_RECURSION,
|
2019-06-17 15:36:42 +00:00
|
|
|
func.span,
|
|
|
|
&format!("recursing into entrypoint `{}`", snippet(cx, func.span, "main")),
|
|
|
|
"consider using another function for this recursion"
|
2019-06-13 08:58:35 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|