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};
8 /// **What it does:** Checks for usage of `option_env!(...).unwrap()` and
9 /// suggests usage of the `env!` macro.
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.
15 /// **Known problems:** None.
20 /// let _ = option_env!("HOME").unwrap();
23 /// Is better expressed as:
26 /// let _ = env!("HOME");
28 pub OPTION_ENV_UNWRAP,
30 "using `option_env!(...).unwrap()` to get environment variable"
33 declare_lint_pass!(OptionEnvUnwrap => [OPTION_ENV_UNWRAP]);
35 impl EarlyLintPass for OptionEnvUnwrap {
36 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
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();
48 "this will panic at run-time if the environment variable doesn't exist at compile-time",
50 "consider using the `env!` macro instead"