1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: check error for cast sumtype (fix #14771) (#14847)

This commit is contained in:
yuyi 2022-06-25 10:19:16 +08:00 committed by GitHub
parent d336b7b877
commit 90287f6aaa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 0 deletions

View File

@ -2500,6 +2500,14 @@ pub fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
c.error(error_msg, node.pos)
}
}
if from_sym.language == .v && !from_type.is_ptr()
&& final_from_sym.kind in [.sum_type, .interface_]
&& final_to_sym.kind !in [.sum_type, .interface_] {
ft := c.table.type_to_str(from_type)
tt := c.table.type_to_str(to_type)
c.error('cannot cast `$ft` to `$tt`, please use `as` instead, e.g. `expr as Ident`',
node.pos)
}
if node.has_arg {
c.expr(node.arg)

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/cast_sumtype_err.vv:7:14: error: cannot cast `Test` to `int`, please use `as` instead, e.g. `expr as Ident`
5 | fn main() {
6 | data := Test(12)
7 | eprintln(int(data))
| ~~~~~~~~~
8 | }

View File

@ -0,0 +1,8 @@
module main
type Test = int | u32 | f32
fn main() {
data := Test(12)
eprintln(int(data))
}