Skip to content

Commit

Permalink
fmt: respect range index expressions in match branches (#19684)
Browse files Browse the repository at this point in the history
  • Loading branch information
ttytm committed Oct 29, 2023
1 parent 5c2eafc commit 52a556c
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 3 deletions.
10 changes: 7 additions & 3 deletions vlib/v/fmt/fmt.v
Expand Up @@ -33,8 +33,6 @@ pub mut:
single_line_if bool
cur_mod string
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
Expand All @@ -48,7 +46,10 @@ pub mut:
inside_const bool
inside_unsafe bool
inside_comptime_if bool
is_assign bool
is_index_expr bool
is_mbranch_expr bool // match a { x...y { } }
is_struct_init bool
fn_scope &ast.Scope = unsafe { nil }
wsinfix_depth int
format_state FormatState
Expand Down Expand Up @@ -2336,9 +2337,12 @@ pub fn (mut f Fmt) index_expr(node ast.IndexExpr) {
f.write('#')
}
}
last_index_expr_state := f.is_index_expr
f.is_index_expr = true
f.write('[')
f.expr(node.index)
f.write(']')
f.is_index_expr = last_index_expr_state
if node.or_expr.kind != .absent {
f.or_expr(node.or_expr)
}
Expand Down Expand Up @@ -2804,7 +2808,7 @@ pub fn (mut f Fmt) prefix_expr(node ast.PrefixExpr) {

pub fn (mut f Fmt) range_expr(node ast.RangeExpr) {
f.expr(node.low)
if f.is_mbranch_expr {
if f.is_mbranch_expr && !f.is_index_expr {
f.write('...')
} else {
f.write('..')
Expand Down
8 changes: 8 additions & 0 deletions vlib/v/fmt/tests/match_expected.vv
Expand Up @@ -48,3 +48,11 @@ fn match_branch_extra_comma() {
else {}
}
}

fn match_index_range_expr(var string) string {
return match true {
var.len < 3 { 'i#' + var }
var[1..2].contains('#') { var }
else { 'i#' + var }
}
}
8 changes: 8 additions & 0 deletions vlib/v/fmt/tests/match_input.vv
Expand Up @@ -46,3 +46,11 @@ fn match_branch_extra_comma() {
else {}
}
}

fn match_index_range_expr(var string) string{
return match true {
var.len< 3{ 'i#' + var }
var[1..2].contains('#') { var }
else { 'i#' + var }
}
}
8 changes: 8 additions & 0 deletions vlib/v/fmt/tests/match_range_expression_branches_keep.vv
Expand Up @@ -13,3 +13,11 @@ pub fn str_escaped(b u8) string {
}
return str
}

fn match_index_range_expr(var string) {
println(match true {
var.len < 3 { 'i#' + var }
var[1..2].contains('#') { var }
else { 'i#' + var }
})
}

0 comments on commit 52a556c

Please sign in to comment.