From d3bcd5d305f0c64e7fbeca74608bcf2be39065bc Mon Sep 17 00:00:00 2001 From: zakuro Date: Mon, 15 Feb 2021 03:22:24 +0900 Subject: [PATCH] fmt: keep single line if in struct init (#8734) --- vlib/v/builder/builder.v | 6 +----- vlib/v/fmt/fmt.v | 9 ++++++++- vlib/v/fmt/tests/if_ternary_keep.vv | 10 ++++++++++ 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/vlib/v/builder/builder.v b/vlib/v/builder/builder.v index e8a3919362..c2107e849f 100644 --- a/vlib/v/builder/builder.v +++ b/vlib/v/builder/builder.v @@ -58,11 +58,7 @@ pub fn new_builder(pref &pref.Preferences) Builder { parent: 0 } compiled_dir: compiled_dir - max_nr_errors: if pref.error_limit > 0 { - pref.error_limit - } else { - 100 - } + max_nr_errors: if pref.error_limit > 0 { pref.error_limit } else { 100 } cached_msvc: msvc } // max_nr_errors: pref.error_limit ?? 100 TODO potential syntax? diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index 522e41cd9c..f7b8aa8685 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -36,6 +36,7 @@ pub mut: file ast.File did_imports bool is_assign bool + is_struct_init bool auto_imports []string // automatically inserted imports that the user forgot to specify import_pos int // position of the imports in the resulting string for later autoimports insertion used_imports []string // to remove unused imports @@ -1636,7 +1637,7 @@ pub fn (mut f Fmt) if_expr(node ast.IfExpr) { dollar := if node.is_comptime { '$' } else { '' } mut single_line := node.branches.len == 2 && node.has_else && branch_is_single_line(node.branches[0]) && branch_is_single_line(node.branches[1]) - && (node.is_expr || f.is_assign || f.single_line_fields) + && (node.is_expr || f.is_assign || f.is_struct_init || f.single_line_fields) f.single_line_if = single_line if_start := f.line_len for { @@ -2067,6 +2068,12 @@ pub fn (mut f Fmt) map_init(it ast.MapInit) { } pub fn (mut f Fmt) struct_init(it ast.StructInit) { + struct_init_save := f.is_struct_init + f.is_struct_init = true + defer { + f.is_struct_init = struct_init_save + } + type_sym := f.table.get_type_symbol(it.typ) // f.write('') mut name := type_sym.name diff --git a/vlib/v/fmt/tests/if_ternary_keep.vv b/vlib/v/fmt/tests/if_ternary_keep.vv index 38c8b0cfcf..8352cc52ec 100644 --- a/vlib/v/fmt/tests/if_ternary_keep.vv +++ b/vlib/v/fmt/tests/if_ternary_keep.vv @@ -1,3 +1,8 @@ +struct Foo { + n int + s string +} + fn valid_single_line() { // Variable initialization a, b := if true { 'a', 'b' } else { 'b', 'a' } @@ -10,6 +15,11 @@ fn valid_single_line() { _ := if false { Foo{} } else { Foo{5, 6} } // As argument for a function call some_func(if cond { 'param1' } else { 'param2' }) + // struct init + foo := Foo{ + n: if true { 1 } else { 0 } + s: if false { 'false' } else { 'true' } + } } fn requires_multiple_lines() {