Skip to content

Commit b17ac33

Browse files
authored
checker: allow explicit sumtype to option casts (fix #25796) (#25812)
1 parent b968bf0 commit b17ac33

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

vlib/v/checker/checker.v

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3547,8 +3547,15 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
35473547
if from_type == ast.void_type {
35483548
c.error('expression does not return a value so it cannot be cast', node.expr.pos())
35493549
}
3550+
inner_to_type := if to_type.has_flag(.option) {
3551+
to_type.clear_flag(.option)
3552+
} else {
3553+
ast.void_type
3554+
}
35503555
if to_type.has_flag(.option) && from_type == ast.none_type {
35513556
// allow conversion from none to every option type
3557+
} else if to_type.has_flag(.option) && from_type == inner_to_type {
3558+
return to_type
35523559
} else if to_sym.kind == .sum_type {
35533560
to_sym_info := to_sym.info as ast.SumType
35543561
if c.pref.skip_unused && to_sym_info.concrete_types.len > 0 {
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
type SumType = u16 | u32
2+
3+
fn wrap[T](x T) ?T {
4+
return ?T(x)
5+
}
6+
7+
fn test_sumtype_explicit_to_option_sumtype() {
8+
value := SumType(u16(0))
9+
a := ?SumType(value)
10+
assert a != none
11+
assert a? == SumType(u16(0))
12+
}
13+
14+
fn test_sumtype_explicit_to_option_sumtype_generic() {
15+
value := SumType(u16(1))
16+
a := wrap[SumType](value)
17+
assert a != none
18+
assert a? == SumType(u16(1))
19+
}

0 commit comments

Comments
 (0)