diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index 9ea485d9de..f6029387a9 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -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 } } diff --git a/vlib/v/fmt/tests/if_keep.vv b/vlib/v/fmt/tests/if_keep.vv new file mode 100644 index 0000000000..c98977a9f8 --- /dev/null +++ b/vlib/v/fmt/tests/if_keep.vv @@ -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} } +}