1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::is_direct_expn_of;
3 use if_chain::if_chain;
4 use rustc_ast::ast::{Expr, ExprKind};
5 use rustc_lint::{EarlyContext, EarlyLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 /// **What it does:** Checks for usage of `option_env!(...).unwrap()` and
10 /// suggests usage of the `env!` macro.
12 /// **Why is this bad?** Unwrapping the result of `option_env!` will panic
13 /// at run-time if the environment variable doesn't exist, whereas `env!`
14 /// catches it at compile-time.
16 /// **Known problems:** None.
21 /// let _ = option_env!("HOME").unwrap();
24 /// Is better expressed as:
27 /// let _ = env!("HOME");
29 pub OPTION_ENV_UNWRAP,
31 "using `option_env!(...).unwrap()` to get environment variable"
34 declare_lint_pass!(OptionEnvUnwrap => [OPTION_ENV_UNWRAP]);
36 impl EarlyLintPass for OptionEnvUnwrap {
37 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
39 if let ExprKind::MethodCall(path_segment, args, _) = &expr.kind;
40 let method_name = path_segment.ident.as_str();
41 if method_name == "expect" || method_name == "unwrap";
42 if let ExprKind::Call(caller, _) = &args[0].kind;
43 if is_direct_expn_of(caller.span, "option_env").is_some();
49 "this will panic at run-time if the environment variable doesn't exist at compile-time",
51 "consider using the `env!` macro instead"