Skip to content

Commit

Permalink
parser, fmt: fix match with multi-commmented branchs (#19898)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Nov 17, 2023
1 parent b347f54 commit 373da77
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 5 deletions.
8 changes: 5 additions & 3 deletions vlib/v/fmt/fmt.v
Expand Up @@ -2696,13 +2696,13 @@ fn (mut f Fmt) match_branch(branch ast.MatchBranch, single_line bool) {
f.writeln('')
}
f.write(estr)
if j < branch.exprs.len - 1 {
f.write(', ')
}
if j < branch.ecmnts.len && branch.ecmnts[j].len > 0 {
f.write(' ')
f.comments(branch.ecmnts[j])
}
if j < branch.exprs.len - 1 {
f.write(', ')
}
}
f.is_mbranch_expr = false
} else {
Expand All @@ -2714,6 +2714,8 @@ fn (mut f Fmt) match_branch(branch ast.MatchBranch, single_line bool) {
} else {
if single_line {
f.write(' { ')
} else if branch.ecmnts.len > 0 && branch.ecmnts.last().len > 0 {
f.writeln('{')
} else {
f.writeln(' {')
}
Expand Down
40 changes: 40 additions & 0 deletions vlib/v/fmt/tests/match_with_multi_commented_branches_keep.vv
@@ -0,0 +1,40 @@
import strings

fn escape_string(s string) string {
mut res := strings.new_builder(s.len * 2)
for ch in s {
match ch {
0 // NUL (null)
{
res.write_u8(92) // \
res.write_u8(48) // 0
}
10 { // LF (line feed)
res.write_u8(92) // \
res.write_u8(110) // n
}
13 { // CR (carriage return)
res.write_u8(92) // \
res.write_u8(114) // r
}
26 { // SUB (substitute)
res.write_u8(92) // \
res.write_u8(90) // Z
}
34, // "
39, // '
92 // \
{
res.write_u8(92) // \
res.write_u8(ch)
}
else {
res.write_u8(ch)
}
}
}
return res.bytestr()
}

fn main() {
}
6 changes: 4 additions & 2 deletions vlib/v/parser/if_match.v
Expand Up @@ -258,13 +258,13 @@ fn (mut p Parser) match_expr() ast.MatchExpr {
for {
// Sum type match
parsed_type := p.parse_type()
ecmnts << p.eat_comments()
types << parsed_type
exprs << ast.TypeNode{
typ: parsed_type
pos: p.prev_tok.pos()
}
if p.tok.kind != .comma {
ecmnts << p.eat_comments()
break
}
p.check(.comma)
Expand All @@ -275,6 +275,7 @@ fn (mut p Parser) match_expr() ast.MatchExpr {
for p.tok.kind == .comma {
p.next()
}
ecmnts << p.eat_comments()
}
}
is_sum_type = true
Expand All @@ -284,7 +285,6 @@ fn (mut p Parser) match_expr() ast.MatchExpr {
p.inside_match_case = true
mut range_pos := p.tok.pos()
expr := p.expr(0)
ecmnts << p.eat_comments()
p.inside_match_case = false
if p.tok.kind == .dotdot {
p.error_with_pos('match only supports inclusive (`...`) ranges, not exclusive (`..`)',
Expand All @@ -306,6 +306,7 @@ fn (mut p Parser) match_expr() ast.MatchExpr {
exprs << expr
}
if p.tok.kind != .comma {
ecmnts << p.eat_comments()
break
}

Expand All @@ -317,6 +318,7 @@ fn (mut p Parser) match_expr() ast.MatchExpr {
for p.tok.kind == .comma {
p.next()
}
ecmnts << p.eat_comments()
}
}
}
Expand Down

0 comments on commit 373da77

Please sign in to comment.