From d075be73e8eba7bc6cae4c4ad53d609aa7ca40f8 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Fri, 21 Feb 2020 16:48:37 +0100 Subject: [PATCH] fmt: single line if --- vlib/v/fmt/fmt.v | 39 +++++++++++++++++++++++------ vlib/v/fmt/tests/simple_expected.vv | 1 + vlib/v/fmt/tests/simple_input.vv | 1 + 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index cc1de83ab8..bd083a13ea 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -16,12 +16,13 @@ const ( ) struct Fmt { - out strings.Builder - table &table.Table + out strings.Builder + table &table.Table mut: - indent int - empty_line bool - line_len int + indent int + empty_line bool + line_len int + single_line_if bool } pub fn fmt(file ast.File, table &table.Table) string { @@ -130,7 +131,9 @@ fn (f mut Fmt) stmt(node ast.Stmt) { } ast.ExprStmt { f.expr(it.expr) - f.writeln('') + if !f.single_line_if { + f.writeln('') + } } ast.FnDecl { f.write(it.str(f.table)) @@ -241,16 +244,36 @@ fn (f mut Fmt) expr(node ast.Expr) { f.write(it.val) } ast.IfExpr { + single_line := it.stmts.len == 1 && it.else_stmts.len == 1 && it.typ != table.void_type + f.single_line_if = single_line f.write('if ') f.expr(it.cond) - f.writeln(' {') + if single_line { + f.write(' { ') + } + else { + f.writeln(' {') + } f.stmts(it.stmts) + if single_line { + f.write(' ') + } f.write('}') if it.else_stmts.len > 0 { - f.writeln(' else {') + f.write(' else {') + if single_line { + f.write(' ') + } + else { + f.writeln('') + } f.stmts(it.else_stmts) + if single_line { + f.write(' ') + } f.write('}') } + f.single_line_if = false } ast.Ident { f.write('$it.name') diff --git a/vlib/v/fmt/tests/simple_expected.vv b/vlib/v/fmt/tests/simple_expected.vv index dd710b6b6d..e49b28a192 100644 --- a/vlib/v/fmt/tests/simple_expected.vv +++ b/vlib/v/fmt/tests/simple_expected.vv @@ -66,5 +66,6 @@ fn fn_with_3_args(arg1 string, arg2 int, arg3 User) int { } fn (this User) fn_with_receiver() { + x := if true { 1 } else { 2 } println('') } diff --git a/vlib/v/fmt/tests/simple_input.vv b/vlib/v/fmt/tests/simple_input.vv index 228f634983..6c5600253b 100644 --- a/vlib/v/fmt/tests/simple_input.vv +++ b/vlib/v/fmt/tests/simple_input.vv @@ -70,6 +70,7 @@ return 0 } fn (this User) fn_with_receiver() { + x := if true {1} else {2} println('') }