Implement the lint

This commit is contained in:
Pavan Kumar Sunkara 2023-02-16 13:36:51 +00:00
parent 2902359b3c
commit 0b1bb5fbf3
3 changed files with 21 additions and 15 deletions

View File

@ -3866,11 +3866,11 @@ impl Methods {
Some(("or", recv, [or_arg], or_span, _)) => {
or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
},
Some((constructor @ "Some", _, _, _, _)) => {
unnecessary_literal_unwrap::check(cx, expr, recv, constructor);
}
_ => {},
}
if let ExprKind::Call(recv, _) = recv.kind {
unnecessary_literal_unwrap::check(cx, expr, recv, name);
}
unwrap_used::check(cx, expr, recv, false, self.allow_unwrap_in_tests);
},
("unwrap_err", []) => unwrap_used::check(cx, expr, recv, true, self.allow_unwrap_in_tests),

View File

@ -1,28 +1,23 @@
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{diagnostics::span_lint_and_help, is_res_lang_ctor, path_res};
use rustc_hir as hir;
use rustc_lint::LateContext;
use rustc_span::sym;
use super::UNNECESSARY_LITERAL_UNWRAP;
pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>, constructor: &str) {
let obj_ty = cx.typeck_results().expr_ty(recv).peel_refs();
let mess = if is_type_diagnostic_item(cx, obj_ty, sym::Option) {
Some((UNNECESSARY_LITERAL_UNWRAP, "an `Option`", "None", ""))
pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>, name: &str) {
let mess = if is_res_lang_ctor(cx, path_res(cx, recv), hir::LangItem::OptionSome) {
Some((UNNECESSARY_LITERAL_UNWRAP, "Some"))
} else {
None
};
if let Some((lint, kind, none_value, none_prefix)) = mess {
let help = format!("if this value is {none_prefix}`{none_value}`, it will panic");
if let Some((lint, constructor)) = mess {
let help = String::new();
span_lint_and_help(
cx,
lint,
expr.span,
&format!("used `unwrap()` on {kind} value"),
&format!("used `{name}()` on `{constructor}` value"),
None,
&help,
);

View File

@ -0,0 +1,11 @@
error: used `unwrap()` on `Some` value
--> $DIR/unnecessary_literal_unwrap.rs:4:15
|
LL | let val = Some(1).unwrap();
| ^^^^^^^^^^^^^^^^
|
= help:
= note: `-D clippy::unnecessary-literal-unwrap` implied by `-D warnings`
error: aborting due to previous error