Skip to content

Commit

Permalink
fmt: add single-line ternary expr support for constants (#19681)
Browse files Browse the repository at this point in the history
  • Loading branch information
ttytm committed Oct 28, 2023
1 parent d74b07d commit 2cf024b
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 1 deletion.
3 changes: 2 additions & 1 deletion vlib/v/fmt/fmt.v
Expand Up @@ -2225,7 +2225,8 @@ pub fn (mut f Fmt) if_expr(node ast.IfExpr) {
f.inside_comptime_if = node.is_comptime
mut is_ternary := 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.is_struct_init || f.single_line_fields)
&& (node.is_expr || f.is_assign || f.inside_const || f.is_struct_init
|| f.single_line_fields)
f.single_line_if = is_ternary
start_pos := f.out.len
start_len := f.line_len
Expand Down
2 changes: 2 additions & 0 deletions vlib/v/fmt/tests/comptime_if_expr_script_keep.vv
@@ -1,3 +1,5 @@
const enable_debug = $if debug { true } $else { false }

mut pre_built_str := ''
$if prebuilt ? {
the_date := if $env('DATE') != '' { $env('DATE') } else { '##DATE##' }
Expand Down
16 changes: 16 additions & 0 deletions vlib/v/fmt/tests/if_ternary_expected.vv
@@ -1,3 +1,19 @@
const (
spacing_error = if true { true } else { false }
too_long_line = if b.no_cstep {
'TMP1/${b.nexpected_steps:1d}'
} else {
'${b.cstep:1d}/${b.nexpected_steps:1d}'
}
too_many_branches = if true {
true
} else if true {
true
} else {
false
}
)

fn main() {
// This line is too long
sprogress := if b.no_cstep {
Expand Down
6 changes: 6 additions & 0 deletions vlib/v/fmt/tests/if_ternary_input.vv
@@ -1,3 +1,9 @@
const (
spacing_error = if true {true}else{ false}
too_long_line = if b.no_cstep { 'TMP1/${b.nexpected_steps:1d}' } else { '${b.cstep:1d}/${b.nexpected_steps:1d}' }
too_many_branches = if true { true } else if true { true } else { false }
)

fn main() {
// This line is too long
sprogress := if b.no_cstep { 'TMP1/${b.nexpected_steps:1d}' } else { '${b.cstep:1d}/${b.nexpected_steps:1d}' }
Expand Down
4 changes: 4 additions & 0 deletions vlib/v/fmt/tests/if_ternary_keep.vv
@@ -1,3 +1,7 @@
import os

const exe_extension = if os.user_os() == 'windows' { '.exe' } else { '' }

struct Foo {
n int
s string
Expand Down

0 comments on commit 2cf024b

Please sign in to comment.