checker: fix sumtype variant option type mismatch (#23659)

This commit is contained in:
Felipe Pena 2025-02-07 11:48:22 -03:00 committed by GitHub
parent c01855c588
commit a4541c2351
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 30 additions and 3 deletions

View File

@ -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)

View File

@ -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')
| ~~~~~~~~~~~

View File

@ -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')

View File

@ -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()) }