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

@ -16,12 +16,13 @@ const (
) )
struct Fmt { struct Fmt {
out strings.Builder out strings.Builder
table &table.Table table &table.Table
mut: 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,7 +131,9 @@ fn (f mut Fmt) stmt(node ast.Stmt) {
} }
ast.ExprStmt { ast.ExprStmt {
f.expr(it.expr) f.expr(it.expr)
f.writeln('') if !f.single_line_if {
f.writeln('')
}
} }
ast.FnDecl { ast.FnDecl {
f.write(it.str(f.table)) f.write(it.str(f.table))
@ -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)
f.writeln(' {') if single_line {
f.write(' { ')
}
else {
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('')
} }