Skip to content

Commit

Permalink
checker: fix sumtype variant option type mismatch (#23659)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp authored Feb 7, 2025
1 parent c01855c commit a4541c2
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 3 deletions.
3 changes: 1 addition & 2 deletions vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
Expand Up @@ -3402,8 +3402,7 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
node.expr_type = c.promote_num(node.expr_type, xx)
from_type = node.expr_type
}
if !c.table.sumtype_has_variant(to_type, from_type, false) && !to_type.has_flag(.option)
&& !to_type.has_flag(.result) {
if !c.table.sumtype_has_variant(to_type, from_type, false) {
ft := c.table.type_to_str(from_type)
tt := c.table.type_to_str(to_type)
c.error('cannot cast `${ft}` to `${tt}`', node.pos)
Expand Down
18 changes: 18 additions & 0 deletions vlib/v/checker/tests/sumtype_variant_mismatch.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
vlib/v/checker/tests/sumtype_variant_mismatch.vv:4:7: error: cannot cast `?string` to `?Any`
2 | type Any2 = ?int | ?string
3 |
4 | _ := ?Any(?string('baz'))
| ~~~~~~~~~~~~~~~~~~~
5 | _ := ?Any(string('baz'))
6 | _ := ?Any('baz')
vlib/v/checker/tests/sumtype_variant_mismatch.vv:9:7: error: cannot cast `string` to `?Any2`
7 |
8 | _ := ?Any2(?string('baz'))
9 | _ := ?Any2(string('baz'))
| ~~~~~~~~~~~~~~~~~~~
10 | _ := ?Any2('baz')
vlib/v/checker/tests/sumtype_variant_mismatch.vv:10:7: error: cannot cast `string` to `?Any2`
8 | _ := ?Any2(?string('baz'))
9 | _ := ?Any2(string('baz'))
10 | _ := ?Any2('baz')
| ~~~~~~~~~~~
10 changes: 10 additions & 0 deletions vlib/v/checker/tests/sumtype_variant_mismatch.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
type Any = ?int | string
type Any2 = ?int | ?string

_ := ?Any(?string('baz'))
_ := ?Any(string('baz'))
_ := ?Any('baz')

_ := ?Any2(?string('baz'))
_ := ?Any2(string('baz'))
_ := ?Any2('baz')
2 changes: 1 addition & 1 deletion vlib/x/json2/decoder.v
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ fn decode_array_item[T](mut field T, arr []Any) {
typeof[[]time.Time]().idx { field = arr.map(it.to_time() or { time.Time{} }) }
typeof[[]?time.Time]().idx { field = arr.map(?time.Time(it.to_time() or { time.Time{} })) }
typeof[[]Any]().idx { field = arr.clone() }
typeof[[]?Any]().idx { field = arr.map(?Any(it)) }
typeof[[]?Any]().idx { field = arr.map(it) }
typeof[[]u8]().idx { field = arr.map(it.u64()) }
typeof[[]?u8]().idx { field = arr.map(?u8(it.u64())) }
typeof[[]u16]().idx { field = arr.map(it.u64()) }
Expand Down

0 comments on commit a4541c2

Please sign in to comment.