fmt: improve conditions for single line if

pull/7608/head
Lukas Neubert 2020-12-27 12:59:28 +01:00 committed by GitHub
parent 0210d1bf24
commit c9081a8df8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 3 deletions

View File

@ -1446,8 +1446,8 @@ pub fn (mut f Fmt) infix_expr(node ast.InfixExpr) {
pub fn (mut f Fmt) if_expr(it ast.IfExpr) {
dollar := if it.is_comptime { '$' } else { '' }
single_line := it.branches.len == 2 && it.has_else && it.branches[0].stmts.len == 1 &&
it.branches[1].stmts.len == 1 &&
single_line := it.branches.len == 2 && it.has_else && branch_is_single_line(it.branches[0]) &&
branch_is_single_line(it.branches[1]) &&
(it.is_expr || f.is_assign)
f.single_line_if = single_line
for i, branch in it.branches {
@ -1488,6 +1488,13 @@ pub fn (mut f Fmt) if_expr(it ast.IfExpr) {
}
}
fn branch_is_single_line(b ast.IfBranch) bool {
if b.stmts.len == 1 && b.comments.len == 0 && stmt_is_single_line(b.stmts[0]) {
return true
}
return false
}
pub fn (mut f Fmt) at_expr(node ast.AtExpr) {
f.write(node.name)
}
@ -1713,7 +1720,7 @@ fn expr_is_single_line(expr ast.Expr) bool {
return false
}
ast.StructInit {
if expr.fields.len > 0 || expr.pre_comments.len > 0 {
if !expr.is_short && (expr.fields.len > 0 || expr.pre_comments.len > 0) {
return false
}
}

View File

@ -0,0 +1,17 @@
fn main() {
a := if foo { 'TMP1/${b.nexpected_steps:1d}' } else { '${b.cstep:1d}/${b.nexpected_steps:1d}' }
b := if bar {
// comment
'some str'
} else {
'other str'
}
_ := if true {
Foo{}
} else {
Foo{
x: 5
}
}
_ := if false { Foo{} } else { Foo{5, 6} }
}