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};
11 /// Checks for usage of `option_env!(...).unwrap()` and
12 /// suggests usage of the `env!` macro.
14 /// ### Why is this bad?
15 /// Unwrapping the result of `option_env!` will panic
16 /// at run-time if the environment variable doesn't exist, whereas `env!`
17 /// catches it at compile-time.
21 /// let _ = option_env!("HOME").unwrap();
24 /// Is better expressed as:
27 /// let _ = env!("HOME");
29 #[clippy::version = "1.43.0"]
30 pub OPTION_ENV_UNWRAP,
32 "using `option_env!(...).unwrap()` to get environment variable"
35 declare_lint_pass!(OptionEnvUnwrap => [OPTION_ENV_UNWRAP]);
37 impl EarlyLintPass for OptionEnvUnwrap {
38 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
40 if let ExprKind::MethodCall(path_segment, args, _) = &expr.kind;
41 if matches!(path_segment.ident.name, sym::expect | sym::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"