Auto merge of #4635 - Lythenas:suggestions-for-assert-false, r=flip1995

Add assert message to suggestion in lint assertions_on_constants

<!--
Thank you for making Clippy better!

We're collecting our changelog from pull request descriptions.
If your PR only updates to the latest nightly, you can leave the
`changelog` entry as `none`. Otherwise, please write a short comment
explaining your change.

If your PR fixes an issue, you can add "fixes #issue_number" into this
PR description. This way the issue will be automatically closed when
your PR is merged.

If you added a new lint, here's a checklist for things that will be
checked during review or continuous integration.

- [x] Followed [lint naming conventions][lint_naming]
- [x] Added passing UI tests (including committed `.stderr` file)
- [ ] `cargo test` passes locally
- [x] Executed `./util/dev update_lints`
- [ ] Added lint documentation
- [ ] Run `./util/dev fmt`

[lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints

Note that you can skip the above if you are just opening a WIP PR in
order to get feedback.

Delete this line and everything above before opening your PR -->

- [x] suggest replacing `assert!(false, "msg")` with `panic!("msg")`
- [x] extend to allow ~~variables~~ any expression for `"msg"`
- ~~suggest replacing `assert!(false, "msg {}", "arg")` with `panic!("msg {}", "arg")`~~

changelog: add assert message to suggestion in lint assertions_on_constants

Work towards fixing: #3575
This commit is contained in:
bors 2019-10-09 08:56:30 +00:00
commit d97fbdbb42
3 changed files with 152 additions and 34 deletions

View File

@ -1,9 +1,11 @@
use rustc::hir::{Expr, ExprKind};
use crate::consts::{constant, Constant};
use crate::utils::paths;
use crate::utils::{is_direct_expn_of, is_expn_of, match_def_path, snippet_opt, span_help_and_lint};
use if_chain::if_chain;
use rustc::hir::*;
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use rustc::{declare_lint_pass, declare_tool_lint};
use crate::consts::{constant, Constant};
use crate::utils::{is_direct_expn_of, is_expn_of, span_help_and_lint};
use syntax::ast::LitKind;
declare_clippy_lint! {
/// **What it does:** Checks for `assert!(true)` and `assert!(false)` calls.
@ -31,39 +33,135 @@ declare_lint_pass!(AssertionsOnConstants => [ASSERTIONS_ON_CONSTANTS]);
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertionsOnConstants {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
let lint_assert_cb = |is_debug_assert: bool| {
if let ExprKind::Unary(_, ref lit) = e.kind {
if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables, lit) {
if is_true {
span_help_and_lint(
cx,
ASSERTIONS_ON_CONSTANTS,
e.span,
"`assert!(true)` will be optimized out by the compiler",
"remove it",
);
} else if !is_debug_assert {
span_help_and_lint(
cx,
ASSERTIONS_ON_CONSTANTS,
e.span,
"`assert!(false)` should probably be replaced",
"use `panic!()` or `unreachable!()`",
);
}
}
}
let lint_true = || {
span_help_and_lint(
cx,
ASSERTIONS_ON_CONSTANTS,
e.span,
"`assert!(true)` will be optimized out by the compiler",
"remove it",
);
};
let lint_false_without_message = || {
span_help_and_lint(
cx,
ASSERTIONS_ON_CONSTANTS,
e.span,
"`assert!(false)` should probably be replaced",
"use `panic!()` or `unreachable!()`",
);
};
let lint_false_with_message = |panic_message: String| {
span_help_and_lint(
cx,
ASSERTIONS_ON_CONSTANTS,
e.span,
&format!("`assert!(false, {})` should probably be replaced", panic_message),
&format!("use `panic!({})` or `unreachable!({})`", panic_message, panic_message),
)
};
if let Some(debug_assert_span) = is_expn_of(e.span, "debug_assert") {
if debug_assert_span.from_expansion() {
return;
}
lint_assert_cb(true);
if_chain! {
if let ExprKind::Unary(_, ref lit) = e.kind;
if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables, lit);
if is_true;
then {
lint_true();
}
};
} else if let Some(assert_span) = is_direct_expn_of(e.span, "assert") {
if assert_span.from_expansion() {
return;
}
lint_assert_cb(false);
if let Some(assert_match) = match_assert_with_message(&cx, e) {
match assert_match {
// matched assert but not message
AssertKind::WithoutMessage(false) => lint_false_without_message(),
AssertKind::WithoutMessage(true) | AssertKind::WithMessage(_, true) => lint_true(),
AssertKind::WithMessage(panic_message, false) => lint_false_with_message(panic_message),
};
}
}
}
}
/// Result of calling `match_assert_with_message`.
enum AssertKind {
WithMessage(String, bool),
WithoutMessage(bool),
}
/// Check if the expression matches
///
/// ```rust,ignore
/// match { let _t = !c; _t } {
/// true => {
/// {
/// ::std::rt::begin_panic(message, _)
/// }
/// }
/// _ => { }
/// };
/// ```
///
/// where `message` is any expression and `c` is a constant bool.
fn match_assert_with_message<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<AssertKind> {
if_chain! {
if let ExprKind::Match(ref expr, ref arms, _) = expr.kind;
// matches { let _t = expr; _t }
if let ExprKind::DropTemps(ref expr) = expr.kind;
if let ExprKind::Unary(UnOp::UnNot, ref expr) = expr.kind;
// bind the first argument of the `assert!` macro
if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables, expr);
// arm 1 pattern
if let PatKind::Lit(ref lit_expr) = arms[0].pat.kind;
if let ExprKind::Lit(ref lit) = lit_expr.kind;
if let LitKind::Bool(true) = lit.node;
// arm 1 block
if let ExprKind::Block(ref block, _) = arms[0].body.kind;
if block.stmts.len() == 0;
if let Some(block_expr) = &block.expr;
if let ExprKind::Block(ref inner_block, _) = block_expr.kind;
if let Some(begin_panic_call) = &inner_block.expr;
// function call
if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
if args.len() == 2;
// bind the second argument of the `assert!` macro if it exists
if let panic_message = snippet_opt(cx, args[0].span);
// second argument of begin_panic is irrelevant
// as is the second match arm
then {
// an empty message occurs when it was generated by the macro
// (and not passed by the user)
return panic_message
.filter(|msg| !msg.is_empty())
.map(|msg| AssertKind::WithMessage(msg, is_true))
.or(Some(AssertKind::WithoutMessage(is_true)));
}
}
None
}
/// Matches a function call with the given path and returns the arguments.
///
/// Usage:
///
/// ```rust,ignore
/// if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
/// ```
fn match_function_call<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, path: &[&str]) -> Option<&'a [Expr]> {
if_chain! {
if let ExprKind::Call(ref fun, ref args) = expr.kind;
if let ExprKind::Path(ref qpath) = fun.kind;
if let Some(fun_def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
if match_def_path(cx, fun_def_id, path);
then {
return Some(&args)
}
};
None
}

View File

@ -11,11 +11,15 @@ fn main() {
assert!(true, "true message");
assert!(false, "false message");
let msg = "panic message";
assert!(false, msg.to_uppercase());
const B: bool = true;
assert!(B);
const C: bool = false;
assert!(C);
assert!(C, "C message");
debug_assert!(true);
// Don't lint this, since there is no better way for expressing "Only panic in debug mode".

View File

@ -23,16 +23,24 @@ LL | assert!(true, "true message");
|
= help: remove it
error: `assert!(false)` should probably be replaced
error: `assert!(false, "false message")` should probably be replaced
--> $DIR/assertions_on_constants.rs:12:5
|
LL | assert!(false, "false message");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: use `panic!()` or `unreachable!()`
= help: use `panic!("false message")` or `unreachable!("false message")`
error: `assert!(false, msg.to_uppercase())` should probably be replaced
--> $DIR/assertions_on_constants.rs:15:5
|
LL | assert!(false, msg.to_uppercase());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: use `panic!(msg.to_uppercase())` or `unreachable!(msg.to_uppercase())`
error: `assert!(true)` will be optimized out by the compiler
--> $DIR/assertions_on_constants.rs:15:5
--> $DIR/assertions_on_constants.rs:18:5
|
LL | assert!(B);
| ^^^^^^^^^^^
@ -40,15 +48,23 @@ LL | assert!(B);
= help: remove it
error: `assert!(false)` should probably be replaced
--> $DIR/assertions_on_constants.rs:18:5
--> $DIR/assertions_on_constants.rs:21:5
|
LL | assert!(C);
| ^^^^^^^^^^^
|
= help: use `panic!()` or `unreachable!()`
error: `assert!(false, "C message")` should probably be replaced
--> $DIR/assertions_on_constants.rs:22:5
|
LL | assert!(C, "C message");
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: use `panic!("C message")` or `unreachable!("C message")`
error: `assert!(true)` will be optimized out by the compiler
--> $DIR/assertions_on_constants.rs:20:5
--> $DIR/assertions_on_constants.rs:24:5
|
LL | debug_assert!(true);
| ^^^^^^^^^^^^^^^^^^^^
@ -56,5 +72,5 @@ LL | debug_assert!(true);
= help: remove it
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
error: aborting due to 7 previous errors
error: aborting due to 9 previous errors