fmt: single line if

pull/3806/head
Alexander Medvednikov 2020-02-21 16:48:37 +01:00
parent 15a2927f09
commit d075be73e8
3 changed files with 33 additions and 8 deletions

View File

@ -22,6 +22,7 @@ mut:
indent int
empty_line bool
line_len int
single_line_if bool
}
pub fn fmt(file ast.File, table &table.Table) string {
@ -130,8 +131,10 @@ fn (f mut Fmt) stmt(node ast.Stmt) {
}
ast.ExprStmt {
f.expr(it.expr)
if !f.single_line_if {
f.writeln('')
}
}
ast.FnDecl {
f.write(it.str(f.table))
f.writeln(' {')
@ -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)
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')

View File

@ -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('')
}

View File

@ -70,6 +70,7 @@ return 0
}
fn (this User) fn_with_receiver() {
x := if true {1} else {2}
println('')
}