Skip to content

Commit 0897f92

Browse files
committed
Auto merge of #4406 - lzutao:fix-assert-const, r=phansch
Fix assertions on const lint Replaces #4402 changelog: none
2 parents 49dff2c + 533bdfb commit 0897f92

File tree

1 file changed

+20
-25
lines changed

1 file changed

+20
-25
lines changed

Diff for: clippy_lints/src/assertions_on_constants.rs

+20-25
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
use if_chain::if_chain;
21
use rustc::hir::{Expr, ExprKind};
32
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
43
use rustc::{declare_lint_pass, declare_tool_lint};
5-
use syntax_pos::Span;
64

75
use crate::consts::{constant, Constant};
8-
use crate::utils::{in_macro_or_desugar, is_direct_expn_of, span_help_and_lint};
6+
use crate::utils::{in_macro_or_desugar, is_direct_expn_of, is_expn_of, span_help_and_lint};
97

108
declare_clippy_lint! {
119
/// **What it does:** Checks for `assert!(true)` and `assert!(false)` calls.
@@ -33,42 +31,39 @@ declare_lint_pass!(AssertionsOnConstants => [ASSERTIONS_ON_CONSTANTS]);
3331

3432
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertionsOnConstants {
3533
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
36-
let mut is_debug_assert = false;
37-
let debug_assert_not_in_macro_or_desugar = |span: Span| {
38-
is_debug_assert = true;
39-
// Check that `debug_assert!` itself is not inside a macro
40-
!in_macro_or_desugar(span)
41-
};
42-
if_chain! {
43-
if let Some(assert_span) = is_direct_expn_of(e.span, "assert");
44-
if !in_macro_or_desugar(assert_span)
45-
|| is_direct_expn_of(assert_span, "debug_assert")
46-
.map_or(false, debug_assert_not_in_macro_or_desugar);
47-
if let ExprKind::Unary(_, ref lit) = e.node;
48-
if let Some(bool_const) = constant(cx, cx.tables, lit);
49-
then {
50-
match bool_const.0 {
51-
Constant::Bool(true) => {
34+
let lint_assert_cb = |is_debug_assert: bool| {
35+
if let ExprKind::Unary(_, ref lit) = e.node {
36+
if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables, lit) {
37+
if is_true {
5238
span_help_and_lint(
5339
cx,
5440
ASSERTIONS_ON_CONSTANTS,
5541
e.span,
5642
"`assert!(true)` will be optimized out by the compiler",
57-
"remove it"
43+
"remove it",
5844
);
59-
},
60-
Constant::Bool(false) if !is_debug_assert => {
45+
} else if !is_debug_assert {
6146
span_help_and_lint(
6247
cx,
6348
ASSERTIONS_ON_CONSTANTS,
6449
e.span,
6550
"`assert!(false)` should probably be replaced",
66-
"use `panic!()` or `unreachable!()`"
51+
"use `panic!()` or `unreachable!()`",
6752
);
68-
},
69-
_ => (),
53+
}
7054
}
7155
}
56+
};
57+
if let Some(debug_assert_span) = is_expn_of(e.span, "debug_assert") {
58+
if in_macro_or_desugar(debug_assert_span) {
59+
return;
60+
}
61+
lint_assert_cb(true);
62+
} else if let Some(assert_span) = is_direct_expn_of(e.span, "assert") {
63+
if in_macro_or_desugar(assert_span) {
64+
return;
65+
}
66+
lint_assert_cb(false);
7267
}
7368
}
7469
}

0 commit comments

Comments
 (0)