]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/option_env_unwrap.rs
New upstream version 1.59.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / option_env_unwrap.rs
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};
7 use rustc_span::sym;
8
9 declare_clippy_lint! {
10 /// ### What it does
11 /// Checks for usage of `option_env!(...).unwrap()` and
12 /// suggests usage of the `env!` macro.
13 ///
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.
18 ///
19 /// ### Example
20 /// ```rust,no_run
21 /// let _ = option_env!("HOME").unwrap();
22 /// ```
23 ///
24 /// Is better expressed as:
25 ///
26 /// ```rust,no_run
27 /// let _ = env!("HOME");
28 /// ```
29 #[clippy::version = "1.43.0"]
30 pub OPTION_ENV_UNWRAP,
31 correctness,
32 "using `option_env!(...).unwrap()` to get environment variable"
33 }
34
35 declare_lint_pass!(OptionEnvUnwrap => [OPTION_ENV_UNWRAP]);
36
37 impl EarlyLintPass for OptionEnvUnwrap {
38 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
39 if_chain! {
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();
44 then {
45 span_lint_and_help(
46 cx,
47 OPTION_ENV_UNWRAP,
48 expr.span,
49 "this will panic at run-time if the environment variable doesn't exist at compile-time",
50 None,
51 "consider using the `env!` macro instead"
52 );
53 }
54 }
55 }
56 }