Skip to content

Commit 21cc3c3

Browse files
authored
cgen: fix sumtype option unwrapping (fix #24746) (#24770)
1 parent d870931 commit 21cc3c3

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

vlib/v/gen/c/cgen.v

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5287,8 +5287,9 @@ fn (mut g Gen) ident(node ast.Ident) {
52875287
obj_sym := g.table.sym(g.unwrap_generic(node.obj.typ))
52885288
if !prevent_sum_type_unwrapping_once {
52895289
nested_unwrap := node.obj.smartcasts.len > 1
5290-
if is_option && nested_unwrap && obj_sym.kind == .sum_type {
5291-
g.write('*(')
5290+
unwrap_sumtype := is_option && nested_unwrap && obj_sym.kind == .sum_type
5291+
if unwrap_sumtype {
5292+
g.write('(*(')
52925293
}
52935294
for i, typ in node.obj.smartcasts {
52945295
is_option_unwrap := i == 0 && is_option
@@ -5379,6 +5380,9 @@ fn (mut g Gen) ident(node ast.Ident) {
53795380
&& obj_sym.kind in [.sum_type, .interface] {
53805381
g.write('${dot}_${cast_sym.cname}')
53815382
}
5383+
if i != 0 && unwrap_sumtype {
5384+
g.write(')')
5385+
}
53825386
}
53835387
}
53845388
if i == 0 && node.obj.ct_type_var != .smartcast && node.obj.is_unwrapped {
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
type TxPayload = Can | u8
2+
3+
enum Tx {
4+
empty
5+
data
6+
can
7+
}
8+
9+
fn (tx Tx) frame_bytes(payload ?TxPayload) ![]u8 {
10+
match tx {
11+
.empty {
12+
return [u8(tx)]
13+
}
14+
.data {
15+
if payload != none {
16+
if payload is u8 {
17+
return [u8(tx), payload]
18+
}
19+
}
20+
return error('Invalid data')
21+
}
22+
.can {
23+
if payload != none {
24+
if payload is Can {
25+
return [u8(tx), payload.net]
26+
}
27+
}
28+
return error('Invalid can')
29+
}
30+
}
31+
}
32+
33+
struct Can {
34+
net u8
35+
}
36+
37+
fn test_main() {
38+
assert Tx.empty.frame_bytes(none)! == [u8(0)]
39+
assert Tx.data.frame_bytes(u8(123))! == [u8(1), 123]
40+
}

0 commit comments

Comments
 (0)