]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/exit.rs
Exclude main from exit lint
[rust.git] / clippy_lints / src / exit.rs
1 use crate::utils::{match_def_path, paths, qpath_res, span_lint};
2 use if_chain::if_chain;
3 use rustc::hir::{Expr, ExprKind, Item, ItemKind, Node};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// **What it does:** `exit()`  terminates the program and doesn't provide a
9     /// stack trace.
10     ///
11     /// **Why is this bad?** Ideally a program is terminated by finishing
12     /// the main function.
13     ///
14     /// **Known problems:** None.
15     ///
16     /// **Example:**
17     /// ```ignore
18     /// std::process::exit(0)
19     /// ```
20     pub EXIT,
21     restriction,
22     "`std::process::exit` is called, terminating the program"
23 }
24
25 declare_lint_pass!(Exit => [EXIT]);
26
27 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Exit {
28     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
29         if_chain! {
30             if let ExprKind::Call(ref path_expr, ref _args) = e.kind;
31             if let ExprKind::Path(ref path) = path_expr.kind;
32             if let Some(def_id) = qpath_res(cx, path, path_expr.hir_id).opt_def_id();
33             if match_def_path(cx, def_id, &paths::EXIT);
34             then {
35                 let mut parent = cx.tcx.hir().get_parent_item(e.hir_id);
36                 // We have to traverse the parents upwards until we find a function
37                 // otherwise a exit in a let or if in main would still trigger this
38                 loop{
39                     match cx.tcx.hir().find(parent) {
40                         Some(Node::Item(Item{ident, kind: ItemKind::Fn(..), ..})) => {
41                             // If we found a function we check it's name if it is
42                             // `main` we emit a lint.
43                             if ident.name.as_str() != "main" {
44                                 span_lint(cx, EXIT, e.span, "usage of `process::exit`");
45                             }
46                             // We found any kind of function and can end our loop
47                             break;
48                         }
49                         // If we found anything but a funciton we continue with the
50                         // loop and go one parent up
51                         Some(_) => {
52                             cx.tcx.hir().get_parent_item(parent);
53                         },
54                         // If we found nothing we break.
55                         None => break,
56                     }
57                 }
58             }
59
60         }
61     }
62 }