Skip to content

Commit ad20b38

Browse files
author
Lukas Neubert
authored
fmt: fix possible code corruption by unwrapped single line if (#8780)
1 parent 230372d commit ad20b38

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

vlib/v/fmt/fmt.v

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1639,7 +1639,8 @@ pub fn (mut f Fmt) if_expr(node ast.IfExpr) {
16391639
&& branch_is_single_line(node.branches[0]) && branch_is_single_line(node.branches[1])
16401640
&& (node.is_expr || f.is_assign || f.is_struct_init || f.single_line_fields)
16411641
f.single_line_if = single_line
1642-
if_start := f.line_len
1642+
start_pos := f.out.len
1643+
start_len := f.line_len
16431644
for {
16441645
for i, branch in node.branches {
16451646
if i == 0 {
@@ -1685,8 +1686,9 @@ pub fn (mut f Fmt) if_expr(node ast.IfExpr) {
16851686
if single_line && f.line_len > fmt.max_len.last() && !f.buffering {
16861687
single_line = false
16871688
f.single_line_if = false
1688-
f.out.go_back(f.line_len - if_start)
1689-
f.line_len = if_start
1689+
f.out.go_back_to(start_pos)
1690+
f.line_len = start_len
1691+
f.empty_line = start_len == 0
16901692
continue
16911693
}
16921694
break

vlib/v/fmt/tests/or_keep.vv

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,14 @@ fn (f Foo) method_with_or() int {
77
f.fn_with_optional() or { return 10 }
88
return 20
99
}
10+
11+
fn unwrapped_single_line_if() {
12+
namefound := publisher.name_fix_check(name_to_find, state.site.id, ispage) or {
13+
if err.contains('Could not find') {
14+
state.error('cannot find link: $name_to_find')
15+
} else {
16+
state.error('cannot find link: $name_to_find\n$err')
17+
}
18+
println('Another stmt')
19+
}
20+
}

0 commit comments

Comments
 (0)