-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Split assert #16677
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
jcarey9149
wants to merge
23
commits into
rust-lang:master
Choose a base branch
from
jcarey9149:split_assert
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+450
−1
Draft
Split assert #16677
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
b8b77e1
checkpoint
jcarey9149 44aecbc
add call
jcarey9149 2578569
checkpoint
jcarey9149 3a377c3
checkpoint
jcarey9149 ad206f7
checkpoint
jcarey9149 1b52792
suggested cleanup
jcarey9149 1412099
handle suggestions
jcarey9149 9628673
handle suggestions
jcarey9149 92210c3
reformat
jcarey9149 d4b6fde
remove binary or
jcarey9149 abc270e
remove debug output
jcarey9149 5eba71d
broken lifetime problem
jcarey9149 a11f426
broken lifetime problem
jcarey9149 c78a952
some lint cleanup
jcarey9149 47aac09
more linting
jcarey9149 02d6097
more lints
jcarey9149 0e6ac65
branch cleanup
jcarey9149 e3ba633
Merge branch 'rust-lang:master' into split_assert
jcarey9149 81ab1cb
cleanup, add exprkind path handling
jcarey9149 9beb635
make sample code compile
jcarey9149 83ea35d
make sample code compile
jcarey9149 2317ddc
fix: `match_same_arms` FP with associated consts
profetia 080748f
more comments, implement UnOp::Not
jcarey9149 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| use clippy_utils::diagnostics::span_lint_and_sugg; | ||
| use clippy_utils::macros::{find_assert_args, root_macro_call_first_node}; | ||
| use clippy_utils::source::snippet; | ||
| use rustc_errors::Applicability; | ||
| use rustc_hir::intravisit::Visitor; | ||
| use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp}; | ||
| use rustc_lint::{LateContext, LateLintPass}; | ||
| use rustc_session::declare_lint_pass; | ||
| use rustc_span::sym; | ||
|
|
||
| declare_clippy_lint! { | ||
| /// ### What it does | ||
| /// Looks for cases of assert!(a==b && c==d) and suggests alternative | ||
| /// | ||
| /// ### Why is this bad? | ||
| /// It's hard to identify which test is failing | ||
| /// ### Example | ||
| /// ```no_run | ||
| /// let a = true; | ||
| /// let b = true; | ||
| /// let c = true; | ||
| /// let d = true; | ||
| /// assert!(a==b && c!=d /* && ... */) | ||
| /// ``` | ||
| /// Use instead: | ||
| /// ```no_run | ||
| /// let a = true; | ||
| /// let b = true; | ||
| /// let c = true; | ||
| /// let d = true; | ||
| /// assert_eq!(a, b); | ||
| /// assert_ne!(c,d); | ||
| /// /* ... */ | ||
| /// ``` | ||
| #[clippy::version = "1.95.0"] | ||
| pub ASSERT_MULTIPLE, | ||
| nursery, | ||
| "Splitting an assert using '&&' into separate asserts makes it clearer which is failing." | ||
| } | ||
|
|
||
| declare_lint_pass!(AssertMultiple => [ASSERT_MULTIPLE]); | ||
|
|
||
| // This visiior is a convenient place to hold the session context, as well as the collection of | ||
| // replacement strings and the type of assert to use. | ||
|
|
||
| struct AssertVisitor<'tcx, 'v> { | ||
| cx: &'v LateContext<'tcx>, | ||
| suggests: Vec<String>, | ||
| assert_string: &'v str, | ||
| } | ||
|
|
||
| impl<'tcx> Visitor<'tcx> for AssertVisitor<'tcx, '_> { | ||
| fn visit_expr(&mut self, e: &'tcx Expr<'_>) { | ||
| match e.kind { | ||
| ExprKind::Binary(op, lhs, rhs) => match op.node { | ||
| BinOpKind::And => { | ||
| // For And, turn each of the rhs and lhs expressions into their own assert. | ||
| rustc_hir::intravisit::walk_expr(self, lhs); | ||
| rustc_hir::intravisit::walk_expr(self, rhs); | ||
| }, | ||
| BinOpKind::Or => { | ||
| // For Or, we cannot break the expression up. | ||
| let tmpstr = format!("{}!{};", self.assert_string, snippet(self.cx, e.span, "..")); | ||
| self.suggests.push(tmpstr); | ||
| }, | ||
| _ => { | ||
| if let Some(x) = assert_from_op(self, op.node, *lhs, *rhs) { | ||
| // handle most of the binary operators here. | ||
| self.suggests.push(x); | ||
| } | ||
| }, | ||
| }, | ||
| ExprKind::Call(_call, _args) => { | ||
| // split function calls into their own assert. | ||
| let tmptxt = snippet(self.cx, e.span, ".."); | ||
| let tmpassrt = format!("{}!({});", self.assert_string, tmptxt); | ||
| self.suggests.push(tmpassrt); | ||
| }, | ||
|
|
||
| ExprKind::MethodCall(_path, expr, _args, span) => { | ||
| // split method calls into their own assert as well. | ||
| let calltext = snippet(self.cx, expr.span, ".."); | ||
| let tmptxt = format!("{}.{};", &*calltext, snippet(self.cx, span, "..")); | ||
| self.suggests.push(tmptxt); | ||
| }, | ||
| ExprKind::Path(qpath) => { | ||
| // this is a statndalone boolean variable, not an expression. | ||
| let name = snippet(self.cx, qpath.span(), "_"); | ||
| let tmptxt = format!("{}!({name});", self.assert_string); | ||
| self.suggests.push(tmptxt); | ||
| }, | ||
| ExprKind::Unary(UnOp::Not, expr) => { | ||
| // A Not operator, just output the | ||
| let exptext = snippet(self.cx, expr.span, "_"); | ||
| let tmptxt = format!("{}!(!{exptext});", self.assert_string); | ||
| self.suggests.push(tmptxt); | ||
| }, | ||
|
|
||
| _ => {}, | ||
jcarey9149 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<'tcx> LateLintPass<'tcx> for AssertMultiple { | ||
| fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) { | ||
| if let Some(macro_call) = root_macro_call_first_node(cx, e) | ||
| && let assert_string = match cx.tcx.get_diagnostic_name(macro_call.def_id) { | ||
| Some(sym::assert_macro) => "assert", | ||
| Some(sym::debug_assert_macro) => "debug_assert", | ||
| _ => return, | ||
| } | ||
| && let Some((condition, _)) = find_assert_args(cx, e, macro_call.expn) | ||
| && matches!(condition.kind, ExprKind::Binary(binop,_lhs,_rhs) if binop.node == BinOpKind::And) | ||
| { | ||
| // We only get here on assert/debug_assert macro calls whose arguments have an And expression | ||
| // on the top of the tree. | ||
| let mut am_visitor = AssertVisitor { | ||
| cx, | ||
| suggests: Vec::new(), | ||
| assert_string, | ||
| }; | ||
| rustc_hir::intravisit::walk_expr(&mut am_visitor, condition); | ||
|
|
||
| if !am_visitor.suggests.is_empty() { | ||
| let suggs = am_visitor.suggests.join("\n ").trim_end_matches(';').to_string(); | ||
| span_lint_and_sugg( | ||
| cx, | ||
| ASSERT_MULTIPLE, | ||
| macro_call.span, | ||
| "multiple asserts combined into one", | ||
| "consider writing", | ||
| suggs, | ||
| Applicability::MaybeIncorrect, | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // This function separates out a binary operation into a separate assert, using ..._eq or ..._ne if | ||
| // applicable. | ||
| fn assert_from_op( | ||
| visitor: &mut AssertVisitor<'_, '_>, | ||
| node: BinOpKind, | ||
| lhs: Expr<'_>, | ||
| rhs: Expr<'_>, | ||
| ) -> Option<String> { | ||
| let cx = visitor.cx; | ||
| let lhs_name = snippet(cx, lhs.span, "_"); | ||
| let rhs_name = snippet(cx, rhs.span, "_"); | ||
| match node { | ||
| BinOpKind::Eq => Some(format!("{}_eq!({lhs_name}, {rhs_name});", visitor.assert_string)), | ||
| BinOpKind::Ne => Some(format!("{}_ne!({lhs_name}, {rhs_name});", visitor.assert_string)), | ||
| BinOpKind::Ge | BinOpKind::Gt | BinOpKind::Le | BinOpKind::Lt => Some(format!( | ||
| "{}!({lhs_name} {} {rhs_name})", | ||
| visitor.assert_string, | ||
| node.as_str() | ||
| )), | ||
| _ => None, | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| #![warn(clippy::assert_multiple)] | ||
| #![allow(unused)] | ||
| use std::thread::sleep; | ||
| use std::time::{Duration, SystemTime}; | ||
|
|
||
| fn myfunc1(_a: u32, _b: String) -> bool { | ||
| let time1 = SystemTime::now(); | ||
| let one_sec = Duration::from_secs(1); | ||
| sleep(one_sec); | ||
|
|
||
| time1.elapsed().unwrap() >= one_sec | ||
| } | ||
|
|
||
| struct MyStruct {} | ||
|
|
||
| impl MyStruct { | ||
| fn myfunc(&self, a: u32, b: String) -> bool { | ||
| myfunc1(a, b) | ||
| } | ||
| } | ||
|
|
||
| fn main() { | ||
| #[derive(PartialEq, Debug)] | ||
| enum Vals { | ||
| Owned, | ||
| Borrowed, | ||
| Other, | ||
| } | ||
| let o = Vals::Owned; | ||
| let b = Vals::Borrowed; | ||
| let other = Vals::Other; | ||
| let time = SystemTime::now(); | ||
| let one_sec = Duration::from_secs(1); | ||
| sleep(one_sec); | ||
| let elp = time.elapsed().unwrap(); | ||
| let is_bool = true; | ||
|
|
||
| assert!(myfunc1(1, "foo".to_string())); | ||
| assert_eq!(b, Vals::Borrowed); | ||
| //~^ assert_multiple | ||
| let ms = MyStruct {}; | ||
| ms.myfunc(1, "foo".to_string()); | ||
| assert!(myfunc1(2, "bar".to_string())); | ||
| //~^ assert_multiple | ||
|
|
||
| assert_eq!(o, Vals::Owned); | ||
| assert_eq!(b, Vals::Other); | ||
| //~^ assert_multiple | ||
|
|
||
| debug_assert_eq!(o, b); | ||
| debug_assert_eq!(other, Vals::Other); | ||
| //~^ assert_multiple | ||
|
|
||
| assert_eq!(o, b); | ||
| assert!(o == Vals::Owned || b == Vals::Other); | ||
| //~^ assert_multiple | ||
| assert_eq!(o, b); | ||
| assert!(is_bool); | ||
| //~^ assert_multiple | ||
| assert!(!is_bool); | ||
| assert_eq!(o, b); | ||
| //~^ assert_multiple | ||
| assert_eq!(o, b); | ||
| assert!(!is_bool); | ||
| //~^ assert_multiple | ||
| assert_eq!(o, b); | ||
| assert!(!(is_bool && o == Vals::Owned)); | ||
| //~^ assert_multiple | ||
|
|
||
| // Next ones we cannot split. | ||
| assert!((o == b && o == Vals::Owned) || b == Vals::Other); | ||
| assert!(o == Vals::Owned || b == Vals::Other); | ||
| debug_assert!(o == b); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| #![warn(clippy::assert_multiple)] | ||
| #![allow(unused)] | ||
| use std::thread::sleep; | ||
| use std::time::{Duration, SystemTime}; | ||
|
|
||
| fn myfunc1(_a: u32, _b: String) -> bool { | ||
| let time1 = SystemTime::now(); | ||
| let one_sec = Duration::from_secs(1); | ||
| sleep(one_sec); | ||
|
|
||
| time1.elapsed().unwrap() >= one_sec | ||
| } | ||
|
|
||
| struct MyStruct {} | ||
|
|
||
| impl MyStruct { | ||
| fn myfunc(&self, a: u32, b: String) -> bool { | ||
| myfunc1(a, b) | ||
| } | ||
| } | ||
|
|
||
| fn main() { | ||
| #[derive(PartialEq, Debug)] | ||
| enum Vals { | ||
| Owned, | ||
| Borrowed, | ||
| Other, | ||
| } | ||
| let o = Vals::Owned; | ||
| let b = Vals::Borrowed; | ||
| let other = Vals::Other; | ||
| let time = SystemTime::now(); | ||
| let one_sec = Duration::from_secs(1); | ||
| sleep(one_sec); | ||
| let elp = time.elapsed().unwrap(); | ||
| let is_bool = true; | ||
|
|
||
| assert!(myfunc1(1, "foo".to_string()) && b == Vals::Borrowed); | ||
| //~^ assert_multiple | ||
| let ms = MyStruct {}; | ||
| assert!(ms.myfunc(1, "foo".to_string()) && myfunc1(2, "bar".to_string())); | ||
| //~^ assert_multiple | ||
|
|
||
| assert!(o == Vals::Owned && b == Vals::Other); | ||
| //~^ assert_multiple | ||
|
|
||
| debug_assert!(o == b && other == Vals::Other); | ||
| //~^ assert_multiple | ||
|
|
||
| assert!(o == b && (o == Vals::Owned || b == Vals::Other)); | ||
| //~^ assert_multiple | ||
| assert!(o == b && is_bool); | ||
| //~^ assert_multiple | ||
| assert!(!is_bool && o == b); | ||
| //~^ assert_multiple | ||
| assert!(o == b && !is_bool); | ||
| //~^ assert_multiple | ||
| assert!(o == b && !(is_bool && o == Vals::Owned)); | ||
| //~^ assert_multiple | ||
|
|
||
| // Next ones we cannot split. | ||
| assert!((o == b && o == Vals::Owned) || b == Vals::Other); | ||
| assert!(o == Vals::Owned || b == Vals::Other); | ||
| debug_assert!(o == b); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.