6894: Parenthesize composite if condition before inverting in invert-if assist r=matklad a=Jesse-Bakker

Fixes #6867

Co-authored-by: Jesse Bakker <github@jessebakker.com>
This commit is contained in:
bors[bot] 2020-12-16 08:20:11 +00:00 committed by GitHub
commit ece626fe81
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 0 deletions

View file

@ -68,6 +68,15 @@ mod tests {
use crate::tests::{check_assist, check_assist_not_applicable};
#[test]
fn invert_if_composite_condition() {
check_assist(
invert_if,
"fn f() { i<|>f x == 3 || x == 4 || x == 5 { 1 } else { 3 * 2 } }",
"fn f() { if !(x == 3 || x == 4 || x == 5) { 3 * 2 } else { 1 } }",
)
}
#[test]
fn invert_if_remove_inequality() {
check_assist(

View file

@ -212,6 +212,10 @@ fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
ast::Expr::BinExpr(bin) => match bin.op_kind()? {
ast::BinOp::NegatedEqualityTest => bin.replace_op(T![==]).map(|it| it.into()),
ast::BinOp::EqualityTest => bin.replace_op(T![!=]).map(|it| it.into()),
// Parenthesize composite boolean expressions before prefixing `!`
ast::BinOp::BooleanAnd | ast::BinOp::BooleanOr => {
Some(make::expr_prefix(T![!], make::expr_paren(expr.clone())))
}
_ => None,
},
ast::Expr::MethodCallExpr(mce) => {

View file

@ -196,6 +196,9 @@ pub fn expr_method_call(receiver: ast::Expr, method: &str, arg_list: ast::ArgLis
pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
expr_from_text(&if exclusive { format!("&mut {}", expr) } else { format!("&{}", expr) })
}
pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
expr_from_text(&format!("({})", expr))
}
fn expr_from_text(text: &str) -> ast::Expr {
ast_from_text(&format!("const C: () = {};", text))
}