Skip to content

Commit 1cce047

Browse files
committed
Auto merge of rust-lang#9225 - tabokie:assert_ok, r=Jarcho
add `[assertions_on_result_states]` lint Close rust-lang#9162 changelog: add `[assertions_on_result_states]` lint Signed-off-by: tabokie <[email protected]>
2 parents a14edd5 + 8454602 commit 1cce047

9 files changed

+282
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -3440,6 +3440,7 @@ Released 2018-09-13
34403440
[`as_conversions`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_conversions
34413441
[`as_underscore`]: https://rust-lang.github.io/rust-clippy/master/index.html#as_underscore
34423442
[`assertions_on_constants`]: https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_constants
3443+
[`assertions_on_result_states`]: https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_result_states
34433444
[`assign_op_pattern`]: https://rust-lang.github.io/rust-clippy/master/index.html#assign_op_pattern
34443445
[`assign_ops`]: https://rust-lang.github.io/rust-clippy/master/index.html#assign_ops
34453446
[`async_yields_async`]: https://rust-lang.github.io/rust-clippy/master/index.html#async_yields_async
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::macros::{find_assert_args, root_macro_call_first_node, PanicExpn};
3+
use clippy_utils::path_res;
4+
use clippy_utils::source::snippet_with_context;
5+
use clippy_utils::ty::{implements_trait, is_copy, is_type_diagnostic_item};
6+
use clippy_utils::usage::local_used_after_expr;
7+
use rustc_errors::Applicability;
8+
use rustc_hir::def::Res;
9+
use rustc_hir::{Expr, ExprKind};
10+
use rustc_lint::{LateContext, LateLintPass};
11+
use rustc_middle::ty::{self, Ty};
12+
use rustc_session::{declare_lint_pass, declare_tool_lint};
13+
use rustc_span::sym;
14+
15+
declare_clippy_lint! {
16+
/// ### What it does
17+
/// Checks for `assert!(r.is_ok())` or `assert!(r.is_err())` calls.
18+
///
19+
/// ### Why is this bad?
20+
/// An assertion failure cannot output an useful message of the error.
21+
///
22+
/// ### Example
23+
/// ```rust,ignore
24+
/// # let r = Ok::<_, ()>(());
25+
/// assert!(r.is_ok());
26+
/// # let r = Err::<_, ()>(());
27+
/// assert!(r.is_err());
28+
/// ```
29+
#[clippy::version = "1.64.0"]
30+
pub ASSERTIONS_ON_RESULT_STATES,
31+
style,
32+
"`assert!(r.is_ok())`/`assert!(r.is_err())` gives worse error message than directly calling `r.unwrap()`/`r.unwrap_err()`"
33+
}
34+
35+
declare_lint_pass!(AssertionsOnResultStates => [ASSERTIONS_ON_RESULT_STATES]);
36+
37+
impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates {
38+
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
39+
if let Some(macro_call) = root_macro_call_first_node(cx, e)
40+
&& matches!(cx.tcx.get_diagnostic_name(macro_call.def_id), Some(sym::assert_macro))
41+
&& let Some((condition, panic_expn)) = find_assert_args(cx, e, macro_call.expn)
42+
&& matches!(panic_expn, PanicExpn::Empty)
43+
&& let ExprKind::MethodCall(method_segment, [recv], _) = condition.kind
44+
&& let result_type_with_refs = cx.typeck_results().expr_ty(recv)
45+
&& let result_type = result_type_with_refs.peel_refs()
46+
&& is_type_diagnostic_item(cx, result_type, sym::Result)
47+
&& let ty::Adt(_, substs) = result_type.kind()
48+
{
49+
if !is_copy(cx, result_type) {
50+
if result_type_with_refs != result_type {
51+
return;
52+
} else if let Res::Local(binding_id) = path_res(cx, recv)
53+
&& local_used_after_expr(cx, binding_id, recv) {
54+
return;
55+
}
56+
}
57+
let mut app = Applicability::MachineApplicable;
58+
match method_segment.ident.as_str() {
59+
"is_ok" if has_debug_impl(cx, substs.type_at(1)) => {
60+
span_lint_and_sugg(
61+
cx,
62+
ASSERTIONS_ON_RESULT_STATES,
63+
macro_call.span,
64+
"called `assert!` with `Result::is_ok`",
65+
"replace with",
66+
format!(
67+
"{}.unwrap()",
68+
snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
69+
),
70+
app,
71+
);
72+
}
73+
"is_err" if has_debug_impl(cx, substs.type_at(0)) => {
74+
span_lint_and_sugg(
75+
cx,
76+
ASSERTIONS_ON_RESULT_STATES,
77+
macro_call.span,
78+
"called `assert!` with `Result::is_err`",
79+
"replace with",
80+
format!(
81+
"{}.unwrap_err()",
82+
snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
83+
),
84+
app,
85+
);
86+
}
87+
_ => (),
88+
};
89+
}
90+
}
91+
}
92+
93+
/// This checks whether a given type is known to implement Debug.
94+
fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
95+
cx.tcx
96+
.get_diagnostic_item(sym::Debug)
97+
.map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
98+
}

clippy_lints/src/lib.register_all.rs

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
66
LintId::of(almost_complete_letter_range::ALMOST_COMPLETE_LETTER_RANGE),
77
LintId::of(approx_const::APPROX_CONSTANT),
88
LintId::of(assertions_on_constants::ASSERTIONS_ON_CONSTANTS),
9+
LintId::of(assertions_on_result_states::ASSERTIONS_ON_RESULT_STATES),
910
LintId::of(async_yields_async::ASYNC_YIELDS_ASYNC),
1011
LintId::of(attrs::BLANKET_CLIPPY_RESTRICTION_LINTS),
1112
LintId::of(attrs::DEPRECATED_CFG_ATTR),

clippy_lints/src/lib.register_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ store.register_lints(&[
4242
asm_syntax::INLINE_ASM_X86_ATT_SYNTAX,
4343
asm_syntax::INLINE_ASM_X86_INTEL_SYNTAX,
4444
assertions_on_constants::ASSERTIONS_ON_CONSTANTS,
45+
assertions_on_result_states::ASSERTIONS_ON_RESULT_STATES,
4546
async_yields_async::ASYNC_YIELDS_ASYNC,
4647
attrs::ALLOW_ATTRIBUTES_WITHOUT_REASON,
4748
attrs::BLANKET_CLIPPY_RESTRICTION_LINTS,

clippy_lints/src/lib.register_style.rs

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
store.register_group(true, "clippy::style", Some("clippy_style"), vec![
66
LintId::of(assertions_on_constants::ASSERTIONS_ON_CONSTANTS),
7+
LintId::of(assertions_on_result_states::ASSERTIONS_ON_RESULT_STATES),
78
LintId::of(blacklisted_name::BLACKLISTED_NAME),
89
LintId::of(blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS),
910
LintId::of(bool_assert_comparison::BOOL_ASSERT_COMPARISON),

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ mod as_conversions;
174174
mod as_underscore;
175175
mod asm_syntax;
176176
mod assertions_on_constants;
177+
mod assertions_on_result_states;
177178
mod async_yields_async;
178179
mod attrs;
179180
mod await_holding_invalid;
@@ -727,6 +728,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
727728
store.register_late_pass(|| Box::new(unnecessary_sort_by::UnnecessarySortBy));
728729
store.register_late_pass(move || Box::new(unnecessary_wraps::UnnecessaryWraps::new(avoid_breaking_exported_api)));
729730
store.register_late_pass(|| Box::new(assertions_on_constants::AssertionsOnConstants));
731+
store.register_late_pass(|| Box::new(assertions_on_result_states::AssertionsOnResultStates));
730732
store.register_late_pass(|| Box::new(transmuting_null::TransmutingNull));
731733
store.register_late_pass(|| Box::new(path_buf_push_overwrite::PathBufPushOverwrite));
732734
store.register_late_pass(|| Box::new(inherent_to_string::InherentToString));
+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// run-rustfix
2+
#![warn(clippy::assertions_on_result_states)]
3+
4+
use std::result::Result;
5+
6+
struct Foo;
7+
8+
#[derive(Debug)]
9+
struct DebugFoo;
10+
11+
#[derive(Copy, Clone, Debug)]
12+
struct CopyFoo;
13+
14+
macro_rules! get_ok_macro {
15+
() => {
16+
Ok::<_, DebugFoo>(Foo)
17+
};
18+
}
19+
20+
fn main() {
21+
// test ok
22+
let r: Result<Foo, DebugFoo> = Ok(Foo);
23+
debug_assert!(r.is_ok());
24+
r.unwrap();
25+
26+
// test ok with non-debug error type
27+
let r: Result<Foo, Foo> = Ok(Foo);
28+
assert!(r.is_ok());
29+
30+
// test temporary ok
31+
fn get_ok() -> Result<Foo, DebugFoo> {
32+
Ok(Foo)
33+
}
34+
get_ok().unwrap();
35+
36+
// test macro ok
37+
get_ok_macro!().unwrap();
38+
39+
// test ok that shouldn't be moved
40+
let r: Result<CopyFoo, DebugFoo> = Ok(CopyFoo);
41+
fn test_ref_unmoveable_ok(r: &Result<CopyFoo, DebugFoo>) {
42+
assert!(r.is_ok());
43+
}
44+
test_ref_unmoveable_ok(&r);
45+
assert!(r.is_ok());
46+
r.unwrap();
47+
48+
// test ok that is copied
49+
let r: Result<CopyFoo, CopyFoo> = Ok(CopyFoo);
50+
r.unwrap();
51+
r.unwrap();
52+
53+
// test reference to ok
54+
let r: Result<CopyFoo, CopyFoo> = Ok(CopyFoo);
55+
fn test_ref_copy_ok(r: &Result<CopyFoo, CopyFoo>) {
56+
r.unwrap();
57+
}
58+
test_ref_copy_ok(&r);
59+
r.unwrap();
60+
61+
// test err
62+
let r: Result<DebugFoo, Foo> = Err(Foo);
63+
debug_assert!(r.is_err());
64+
r.unwrap_err();
65+
66+
// test err with non-debug value type
67+
let r: Result<Foo, Foo> = Err(Foo);
68+
assert!(r.is_err());
69+
}
+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// run-rustfix
2+
#![warn(clippy::assertions_on_result_states)]
3+
4+
use std::result::Result;
5+
6+
struct Foo;
7+
8+
#[derive(Debug)]
9+
struct DebugFoo;
10+
11+
#[derive(Copy, Clone, Debug)]
12+
struct CopyFoo;
13+
14+
macro_rules! get_ok_macro {
15+
() => {
16+
Ok::<_, DebugFoo>(Foo)
17+
};
18+
}
19+
20+
fn main() {
21+
// test ok
22+
let r: Result<Foo, DebugFoo> = Ok(Foo);
23+
debug_assert!(r.is_ok());
24+
assert!(r.is_ok());
25+
26+
// test ok with non-debug error type
27+
let r: Result<Foo, Foo> = Ok(Foo);
28+
assert!(r.is_ok());
29+
30+
// test temporary ok
31+
fn get_ok() -> Result<Foo, DebugFoo> {
32+
Ok(Foo)
33+
}
34+
assert!(get_ok().is_ok());
35+
36+
// test macro ok
37+
assert!(get_ok_macro!().is_ok());
38+
39+
// test ok that shouldn't be moved
40+
let r: Result<CopyFoo, DebugFoo> = Ok(CopyFoo);
41+
fn test_ref_unmoveable_ok(r: &Result<CopyFoo, DebugFoo>) {
42+
assert!(r.is_ok());
43+
}
44+
test_ref_unmoveable_ok(&r);
45+
assert!(r.is_ok());
46+
r.unwrap();
47+
48+
// test ok that is copied
49+
let r: Result<CopyFoo, CopyFoo> = Ok(CopyFoo);
50+
assert!(r.is_ok());
51+
r.unwrap();
52+
53+
// test reference to ok
54+
let r: Result<CopyFoo, CopyFoo> = Ok(CopyFoo);
55+
fn test_ref_copy_ok(r: &Result<CopyFoo, CopyFoo>) {
56+
assert!(r.is_ok());
57+
}
58+
test_ref_copy_ok(&r);
59+
r.unwrap();
60+
61+
// test err
62+
let r: Result<DebugFoo, Foo> = Err(Foo);
63+
debug_assert!(r.is_err());
64+
assert!(r.is_err());
65+
66+
// test err with non-debug value type
67+
let r: Result<Foo, Foo> = Err(Foo);
68+
assert!(r.is_err());
69+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
error: called `assert!` with `Result::is_ok`
2+
--> $DIR/assertions_on_result_states.rs:24:5
3+
|
4+
LL | assert!(r.is_ok());
5+
| ^^^^^^^^^^^^^^^^^^ help: replace with: `r.unwrap()`
6+
|
7+
= note: `-D clippy::assertions-on-result-states` implied by `-D warnings`
8+
9+
error: called `assert!` with `Result::is_ok`
10+
--> $DIR/assertions_on_result_states.rs:34:5
11+
|
12+
LL | assert!(get_ok().is_ok());
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `get_ok().unwrap()`
14+
15+
error: called `assert!` with `Result::is_ok`
16+
--> $DIR/assertions_on_result_states.rs:37:5
17+
|
18+
LL | assert!(get_ok_macro!().is_ok());
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `get_ok_macro!().unwrap()`
20+
21+
error: called `assert!` with `Result::is_ok`
22+
--> $DIR/assertions_on_result_states.rs:50:5
23+
|
24+
LL | assert!(r.is_ok());
25+
| ^^^^^^^^^^^^^^^^^^ help: replace with: `r.unwrap()`
26+
27+
error: called `assert!` with `Result::is_ok`
28+
--> $DIR/assertions_on_result_states.rs:56:9
29+
|
30+
LL | assert!(r.is_ok());
31+
| ^^^^^^^^^^^^^^^^^^ help: replace with: `r.unwrap()`
32+
33+
error: called `assert!` with `Result::is_err`
34+
--> $DIR/assertions_on_result_states.rs:64:5
35+
|
36+
LL | assert!(r.is_err());
37+
| ^^^^^^^^^^^^^^^^^^^ help: replace with: `r.unwrap_err()`
38+
39+
error: aborting due to 6 previous errors
40+

0 commit comments

Comments
 (0)