Simplify option_env_unwrap.

This commit is contained in:
Jason Newcomb 2024-06-15 17:32:04 -04:00
parent ff28de20b4
commit 15eac5abd6

View File

@ -3,7 +3,7 @@
use rustc_ast::ast::{Expr, ExprKind, MethodCall};
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::{sym, Span};
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
@ -35,30 +35,18 @@
impl EarlyLintPass for OptionEnvUnwrap {
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
fn lint(cx: &EarlyContext<'_>, span: Span) {
if let ExprKind::MethodCall(box MethodCall { seg, receiver, .. }) = &expr.kind
&& matches!(seg.ident.name, sym::expect | sym::unwrap)
&& is_direct_expn_of(receiver.span, "option_env").is_some()
{
span_lint_and_help(
cx,
OPTION_ENV_UNWRAP,
span,
expr.span,
"this will panic at run-time if the environment variable doesn't exist at compile-time",
None,
"consider using the `env!` macro instead",
);
}
if let ExprKind::MethodCall(box MethodCall { seg, receiver, .. }) = &expr.kind
&& matches!(seg.ident.name, sym::expect | sym::unwrap)
{
if let ExprKind::Call(caller, _) = &receiver.kind &&
// If it exists, it will be ::core::option::Option::Some("<env var>").unwrap() (A method call in the HIR)
is_direct_expn_of(caller.span, "option_env").is_some()
{
lint(cx, expr.span);
} else if let ExprKind::Path(_, caller) = &receiver.kind && // If it doesn't exist, it will be ::core::option::Option::None::<&'static str>.unwrap() (A path in the HIR)
is_direct_expn_of(caller.span, "option_env").is_some()
{
lint(cx, expr.span);
}
}
}
}