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 indent int
empty_line bool empty_line bool
line_len int line_len int
single_line_if bool
} }
pub fn fmt(file ast.File, table &table.Table) string { pub fn fmt(file ast.File, table &table.Table) string {
@ -130,8 +131,10 @@ fn (f mut Fmt) stmt(node ast.Stmt) {
} }
ast.ExprStmt { ast.ExprStmt {
f.expr(it.expr) f.expr(it.expr)
if !f.single_line_if {
f.writeln('') f.writeln('')
} }
}
ast.FnDecl { ast.FnDecl {
f.write(it.str(f.table)) f.write(it.str(f.table))
f.writeln(' {') f.writeln(' {')
@ -241,16 +244,36 @@ fn (f mut Fmt) expr(node ast.Expr) {
f.write(it.val) f.write(it.val)
} }
ast.IfExpr { 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.write('if ')
f.expr(it.cond) f.expr(it.cond)
if single_line {
f.write(' { ')
}
else {
f.writeln(' {') f.writeln(' {')
}
f.stmts(it.stmts) f.stmts(it.stmts)
if single_line {
f.write(' ')
}
f.write('}') f.write('}')
if it.else_stmts.len > 0 { 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) f.stmts(it.else_stmts)
if single_line {
f.write(' ')
}
f.write('}') f.write('}')
} }
f.single_line_if = false
} }
ast.Ident { ast.Ident {
f.write('$it.name') 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() { fn (this User) fn_with_receiver() {
x := if true { 1 } else { 2 }
println('') println('')
} }

View File

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