]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/exit.rs
Auto merge of #82864 - jyn514:short-circuit, r=GuillaumeGomez
[rust.git] / src / tools / clippy / clippy_lints / src / exit.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::{is_entrypoint_fn, match_def_path, paths};
3 use if_chain::if_chain;
4 use rustc_hir::{Expr, ExprKind, Item, ItemKind, Node};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 declare_clippy_lint! {
9     /// **What it does:** `exit()`  terminates the program and doesn't provide a
10     /// stack trace.
11     ///
12     /// **Why is this bad?** Ideally a program is terminated by finishing
13     /// the main function.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     /// ```ignore
19     /// std::process::exit(0)
20     /// ```
21     pub EXIT,
22     restriction,
23     "`std::process::exit` is called, terminating the program"
24 }
25
26 declare_lint_pass!(Exit => [EXIT]);
27
28 impl<'tcx> LateLintPass<'tcx> for Exit {
29     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
30         if_chain! {
31             if let ExprKind::Call(ref path_expr, ref _args) = e.kind;
32             if let ExprKind::Path(ref path) = path_expr.kind;
33             if let Some(def_id) = cx.qpath_res(path, path_expr.hir_id).opt_def_id();
34             if match_def_path(cx, def_id, &paths::EXIT);
35             then {
36                 let parent = cx.tcx.hir().get_parent_item(e.hir_id);
37                 if let Some(Node::Item(Item{kind: ItemKind::Fn(..), ..})) = cx.tcx.hir().find(parent) {
38                     // If the next item up is a function we check if it is an entry point
39                     // and only then emit a linter warning
40                     let def_id = cx.tcx.hir().local_def_id(parent);
41                     if !is_entrypoint_fn(cx, def_id.to_def_id()) {
42                         span_lint(cx, EXIT, e.span, "usage of `process::exit`");
43                     }
44                 }
45             }
46         }
47     }
48 }