1use clippy_utils::diagnostics::span_lint;
2use clippy_utils::is_entrypoint_fn;
3use rustc_hir::{Expr, ExprKind, Item, ItemKind, OwnerNode};
4use rustc_lint::{LateContext, LateLintPass};
5use rustc_session::declare_lint_pass;
6use rustc_span::sym;
7
8declare_clippy_lint! {
9 /// ### What it does
10 /// Detects calls to the `exit()` function which terminates the program.
11 ///
12 /// ### Why restrict this?
13 /// `exit()` immediately terminates the program with no information other than an exit code.
14 /// This provides no means to troubleshoot a problem, and may be an unexpected side effect.
15 ///
16 /// Codebases may use this lint to require that all exits are performed either by panicking
17 /// (which produces a message, a code location, and optionally a backtrace)
18 /// or by returning from `main()` (which is a single place to look).
19 ///
20 /// ### Example
21 /// ```no_run
22 /// std::process::exit(0)
23 /// ```
24 ///
25 /// Use instead:
26 ///
27 /// ```ignore
28 /// // To provide a stacktrace and additional information
29 /// panic!("message");
30 ///
31 /// // or a main method with a return
32 /// fn main() -> Result<(), i32> {
33 /// Ok(())
34 /// }
35 /// ```
36 #[clippy::version = "1.41.0"]
37 pub EXIT,
38 restriction,
39 "detects `std::process::exit` calls"
40}
41
42declare_lint_pass!(Exit => [EXIT]);
43
44impl<'tcx> LateLintPass<'tcx> for Exit {
45 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
46 if let ExprKind::Call(path_expr, [_]) = e.kind
47 && let ExprKind::Path(ref path: &{unknown}) = path_expr.kind
48 && let Some(def_id) = cx.qpath_res(path, path_expr.hir_id).opt_def_id()
49 && cx.tcx.is_diagnostic_item(sym::process_exit, def_id)
50 && let parent = cx.tcx.hir_get_parent_item(e.hir_id)
51 && let OwnerNode::Item(Item{kind: ItemKind::Fn{ .. }, ..}) = cx.tcx.hir_owner_node(parent)
52 // If the next item up is a function we check if it is an entry point
53 // and only then emit a linter warning
54 && !is_entrypoint_fn(cx, parent.to_def_id())
55 {
56 span_lint(cx, lint:EXIT, sp:e.span, msg:"usage of `process::exit`");
57 }
58 }
59}
60