]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/option_env_unwrap.rs
Merge commit '4911ab124c481430672a3833b37075e6435ec34d' into clippyup
[rust.git] / clippy_lints / src / option_env_unwrap.rs
1 use crate::utils::{is_direct_expn_of, span_lint_and_help};
2 use if_chain::if_chain;
3 use rustc_ast::ast::{Expr, ExprKind};
4 use rustc_lint::{EarlyContext, EarlyLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// **What it does:** Checks for usage of `option_env!(...).unwrap()` and
9     /// suggests usage of the `env!` macro.
10     ///
11     /// **Why is this bad?** Unwrapping the result of `option_env!` will panic
12     /// at run-time if the environment variable doesn't exist, whereas `env!`
13     /// catches it at compile-time.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     ///
19     /// ```rust,no_run
20     /// let _ = option_env!("HOME").unwrap();
21     /// ```
22     ///
23     /// Is better expressed as:
24     ///
25     /// ```rust,no_run
26     /// let _ = env!("HOME");
27     /// ```
28     pub OPTION_ENV_UNWRAP,
29     correctness,
30     "using `option_env!(...).unwrap()` to get environment variable"
31 }
32
33 declare_lint_pass!(OptionEnvUnwrap => [OPTION_ENV_UNWRAP]);
34
35 impl EarlyLintPass for OptionEnvUnwrap {
36     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
37         if_chain! {
38             if let ExprKind::MethodCall(path_segment, args, _) = &expr.kind;
39             let method_name = path_segment.ident.as_str();
40             if method_name == "expect" || method_name == "unwrap";
41             if let ExprKind::Call(caller, _) = &args[0].kind;
42             if is_direct_expn_of(caller.span, "option_env").is_some();
43             then {
44                 span_lint_and_help(
45                     cx,
46                     OPTION_ENV_UNWRAP,
47                     expr.span,
48                     "this will panic at run-time if the environment variable doesn't exist at compile-time",
49                     None,
50                     "consider using the `env!` macro instead"
51                 );
52             }
53         }
54     }
55 }