-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[bool_assert_comparaison
] improve suggestion
#7612
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
Closed
ABouttefeux
wants to merge
8
commits into
rust-lang:master
from
ABouttefeux:bool_assert_comparison_improvment
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
90117a0
improve suggestion for bool_assert_comparaison
ABouttefeux e696ba2
add extraction of fmt parameter
ABouttefeux 3d17ede
extract the formaing string and the values
ABouttefeux b079660
change to a structure for parsing assert macro
ABouttefeux 5f5ea41
remove the format_string_expr from the FormatArgsExpn
ABouttefeux 256e6c5
change based on review and debug_assert
ABouttefeux 073dd99
add assert to the parsing
ABouttefeux 103ac52
reomove unecessary import
ABouttefeux 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
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
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 |
---|---|---|
|
@@ -3,16 +3,19 @@ | |
#![deny(clippy::missing_docs_in_private_items)] | ||
|
||
use crate::ty::is_type_diagnostic_item; | ||
use crate::{is_expn_of, last_path_segment, match_def_path, paths}; | ||
use crate::{is_expn_of, last_path_segment, match_def_path, paths, source::snippet_with_applicability}; | ||
use if_chain::if_chain; | ||
use rustc_ast::ast::{self, LitKind}; | ||
use rustc_errors::Applicability; | ||
use rustc_hir as hir; | ||
use rustc_hir::{ | ||
Arm, Block, BorrowKind, Expr, ExprKind, HirId, LoopSource, MatchSource, Node, Pat, QPath, StmtKind, UnOp, | ||
}; | ||
use rustc_lint::LateContext; | ||
use rustc_span::{sym, symbol, ExpnKind, Span, Symbol}; | ||
|
||
use std::borrow::Cow; | ||
|
||
/// The essential nodes of a desugared for loop as well as the entire span: | ||
/// `for pat in arg { body }` becomes `(pat, arg, body)`. Return `(pat, arg, body, span)`. | ||
pub struct ForLoop<'tcx> { | ||
|
@@ -418,56 +421,177 @@ pub fn binop(op: hir::BinOpKind) -> ast::BinOpKind { | |
} | ||
} | ||
|
||
/// Extract args from an assert-like macro. | ||
/// Currently working with: | ||
/// - `assert!`, `assert_eq!` and `assert_ne!` | ||
/// - `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!` | ||
/// For example: | ||
/// `assert!(expr)` will return `Some([expr])` | ||
/// `debug_assert_eq!(a, b)` will return `Some([a, b])` | ||
pub fn extract_assert_macro_args<'tcx>(e: &'tcx Expr<'tcx>) -> Option<Vec<&'tcx Expr<'tcx>>> { | ||
/// Try to match the AST for a pattern that contains a match, for example when two args are | ||
/// compared | ||
fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>) -> Option<Vec<&Expr<'_>>> { | ||
if_chain! { | ||
if let ExprKind::Match(headerexpr, _, _) = &matchblock_expr.kind; | ||
if let ExprKind::Tup([lhs, rhs]) = &headerexpr.kind; | ||
if let ExprKind::AddrOf(BorrowKind::Ref, _, lhs) = lhs.kind; | ||
if let ExprKind::AddrOf(BorrowKind::Ref, _, rhs) = rhs.kind; | ||
then { | ||
return Some(vec![lhs, rhs]); | ||
/// Kind of assert macros | ||
pub enum AssertExpnKind<'tcx> { | ||
/// Boolean macro like `assert!` or `debug_assert!` | ||
Bool(&'tcx Expr<'tcx>), | ||
/// Comparaison maacro like `assert_eq!`, `assert_ne!`, `debug_assert_eq!` or `debug_assert_ne!` | ||
Eq(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>), | ||
} | ||
|
||
/// A parsed | ||
/// `assert!`, `assert_eq!` or `assert_ne!`, | ||
/// `debug_assert!`, `debug_assert_eq!` or `debug_assert_ne!` | ||
/// macro. | ||
pub struct AssertExpn<'tcx> { | ||
/// Kind of assert macro | ||
pub kind: AssertExpnKind<'tcx>, | ||
/// The format argument passed at the end of the macro | ||
pub format_arg: Option<FormatArgsExpn<'tcx>>, | ||
/// is a debug macro | ||
pub is_debug: bool, | ||
} | ||
camsteffen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
impl<'tcx> AssertExpn<'tcx> { | ||
/// Extract args from an assert-like macro. | ||
/// Currently working with: | ||
/// - `assert!`, `assert_eq!` and `assert_ne!` | ||
/// - `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!` | ||
/// For example: | ||
/// `assert!(expr)` will return `Some(AssertExpn { first_assert_argument: expr, | ||
/// second_assert_argument: None, format_arg:None })` `debug_assert_eq!(a, b)` will return | ||
/// `Some(AssertExpn { first_assert_argument: a, second_assert_argument: Some(b), | ||
/// format_arg:None })` | ||
pub fn parse(e: &'tcx Expr<'tcx>) -> Option<Self> { | ||
if let ExprKind::Block(block, _) = e.kind { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consider doing something like this as a first step if let ExpnKind::Macro(_, name) = expr.span.ctxt().outer_expn_data().kind;
match *name.as_str() {
"assert" | "debug_assert" => ..,
"assert_eq" | "debug_assert_eq" => ..,
} |
||
if block.stmts.len() == 1 { | ||
if let StmtKind::Semi(matchexpr) = block.stmts.get(0)?.kind { | ||
// debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`) | ||
if_chain! { | ||
if let ExprKind::Block(matchblock,_) = matchexpr.kind; | ||
if let Some(matchblock_expr) = matchblock.expr; | ||
then { | ||
return Self::ast_matchblock(matchblock_expr, true); | ||
} | ||
} | ||
// debug macros with unique arg: `debug_assert!` (e.g., `debug_assert!(some_condition)`) | ||
return Self::ast_ifblock(matchexpr, true); | ||
} | ||
} else if let Some(matchblock_expr) = block.expr { | ||
// macros with two args: `assert_{ne, eq}` (e.g., `assert_ne!(a, b)`) | ||
return Self::ast_matchblock(matchblock_expr, false); | ||
} | ||
} else { | ||
// assert! macro | ||
return Self::ast_ifblock(e, false); | ||
} | ||
None | ||
} | ||
|
||
if let ExprKind::Block(block, _) = e.kind { | ||
if block.stmts.len() == 1 { | ||
if let StmtKind::Semi(matchexpr) = block.stmts.get(0)?.kind { | ||
// macros with unique arg: `{debug_}assert!` (e.g., `debug_assert!(some_condition)`) | ||
/// Try to parse the pattern for an assert macro with a single argument like `{debug_}assert!` | ||
fn ast_ifblock(ifblock_expr: &'tcx Expr<'tcx>, is_debug: bool) -> Option<Self> { | ||
if_chain! { | ||
if let Some(If { cond, then, .. }) = If::hir(ifblock_expr); | ||
if let ExprKind::Unary(UnOp::Not, condition) = cond.kind; | ||
then { | ||
if_chain! { | ||
if let Some(If { cond, .. }) = If::hir(matchexpr); | ||
if let ExprKind::Unary(UnOp::Not, condition) = cond.kind; | ||
if let ExprKind::Block(block, _) = then.kind; | ||
if let Some(begin_panic_fmt_block) = block.expr; | ||
if let ExprKind::Block(block,_) = begin_panic_fmt_block.kind; | ||
if let Some(expr) = block.expr; | ||
if let ExprKind::Call(_, args_begin_panic_fmt) = expr.kind; | ||
if !args_begin_panic_fmt.is_empty(); | ||
if let ExprKind::AddrOf(_, _, arg) = args_begin_panic_fmt[0].kind; | ||
if let Some(format_arg_expn) = FormatArgsExpn::parse(arg); | ||
then { | ||
return Some(vec![condition]); | ||
return Some(Self { | ||
kind: AssertExpnKind::Bool(condition), | ||
format_arg: Some(format_arg_expn), | ||
is_debug | ||
}); | ||
} | ||
} | ||
return Some(Self { | ||
kind: AssertExpnKind::Bool(condition), | ||
format_arg: None, | ||
is_debug | ||
}); | ||
} | ||
} | ||
None | ||
} | ||
|
||
// debug macros with two args: `debug_assert_{ne, eq}` (e.g., `assert_ne!(a, b)`) | ||
/// Try to match the AST for a pattern that contains a match, for example when two args are | ||
/// compared | ||
fn ast_matchblock(matchblock_expr: &'tcx Expr<'tcx>, is_debug: bool) -> Option<Self> { | ||
if_chain! { | ||
if let ExprKind::Match(headerexpr, arms, _) = &matchblock_expr.kind; | ||
if let ExprKind::Tup([lhs, rhs]) = &headerexpr.kind; | ||
if let ExprKind::AddrOf(BorrowKind::Ref, _, lhs) = lhs.kind; | ||
if let ExprKind::AddrOf(BorrowKind::Ref, _, rhs) = rhs.kind; | ||
then { | ||
if_chain! { | ||
if let ExprKind::Block(matchblock,_) = matchexpr.kind; | ||
if let Some(matchblock_expr) = matchblock.expr; | ||
if !arms.is_empty(); | ||
if let ExprKind::Block(Block{expr: Some(if_expr),..},_) = arms[0].body.kind; | ||
if let ExprKind::If(_, if_block, _) = if_expr.kind; | ||
if let ExprKind::Block(Block{stmts: stmts_if_block,..},_) = if_block.kind; | ||
if stmts_if_block.len() >= 2; | ||
if let StmtKind::Expr(call_assert_failed) | ||
| StmtKind::Semi(call_assert_failed) = stmts_if_block[1].kind; | ||
if let ExprKind::Call(_, args_assert_failed) = call_assert_failed.kind; | ||
if args_assert_failed.len() >= 4; | ||
if let ExprKind::Call(_, [arg, ..]) = args_assert_failed[3].kind; | ||
if let Some(format_arg_expn) = FormatArgsExpn::parse(arg); | ||
then { | ||
return ast_matchblock(matchblock_expr); | ||
return Some(AssertExpn { | ||
kind: AssertExpnKind::Eq(lhs,rhs), | ||
format_arg: Some(format_arg_expn), | ||
is_debug, | ||
}); | ||
} | ||
} | ||
return Some(AssertExpn { | ||
kind: AssertExpnKind::Eq(lhs,rhs), | ||
format_arg: None, | ||
is_debug, | ||
}); | ||
} | ||
} else if let Some(matchblock_expr) = block.expr { | ||
// macros with two args: `assert_{ne, eq}` (e.g., `assert_ne!(a, b)`) | ||
return ast_matchblock(matchblock_expr); | ||
} | ||
None | ||
} | ||
|
||
/// Gives the argument in the comparaison as a vector leaving the format | ||
pub fn assert_arguments(&self) -> Vec<&'tcx Expr<'tcx>> { | ||
match self.kind { | ||
AssertExpnKind::Bool(expr) => { | ||
vec![expr] | ||
}, | ||
AssertExpnKind::Eq(lhs, rhs) => { | ||
vec![lhs, rhs] | ||
}, | ||
} | ||
} | ||
|
||
/// Gives the argument passed to the macro as a string | ||
pub fn all_arguments_string( | ||
&self, | ||
cx: &LateContext<'_>, | ||
applicability: &mut Applicability, | ||
) -> Vec<Cow<'static, str>> { | ||
let mut vec_arg = vec![]; | ||
for arg in self.assert_arguments() { | ||
vec_arg.push(snippet_with_applicability(cx, arg.span, "..", applicability)); | ||
} | ||
vec_arg.append(&mut self.format_arguments(cx, applicability)); | ||
vec_arg | ||
} | ||
|
||
/// Returns only the format agruments | ||
pub fn format_arguments(&self, cx: &LateContext<'_>, applicability: &mut Applicability) -> Vec<Cow<'static, str>> { | ||
let mut vec_arg = vec![]; | ||
if let Some(ref fmt_arg) = self.format_arg { | ||
vec_arg.push(snippet_with_applicability( | ||
cx, | ||
fmt_arg.format_string_span, | ||
"..", | ||
applicability, | ||
)); | ||
for arg in &fmt_arg.value_args { | ||
vec_arg.push(snippet_with_applicability(cx, arg.span, "..", applicability)); | ||
} | ||
} | ||
vec_arg | ||
} | ||
None | ||
} | ||
|
||
/// A parsed `format!` expansion | ||
|
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.