]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/exit.rs
Rollup merge of #89090 - cjgillot:bare-dyn, r=jackh726
[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
10     /// `exit()`  terminates the program and doesn't provide a
11     /// stack trace.
12     ///
13     /// ### Why is this bad?
14     /// Ideally a program is terminated by finishing
15     /// the main function.
16     ///
17     /// ### Example
18     /// ```ignore
19     /// std::process::exit(0)
20     /// ```
21     #[clippy::version = "1.41.0"]
22     pub EXIT,
23     restriction,
24     "`std::process::exit` is called, terminating the program"
25 }
26
27 declare_lint_pass!(Exit => [EXIT]);
28
29 impl<'tcx> LateLintPass<'tcx> for Exit {
30     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
31         if_chain! {
32             if let ExprKind::Call(path_expr, _args) = e.kind;
33             if let ExprKind::Path(ref path) = path_expr.kind;
34             if let Some(def_id) = cx.qpath_res(path, path_expr.hir_id).opt_def_id();
35             if match_def_path(cx, def_id, &paths::EXIT);
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             then {
43                 span_lint(cx, EXIT, e.span, "usage of `process::exit`");
44             }
45         }
46     }
47 }