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

checker: optimize casting sumtype error message (fix #14023) (#14877)

This commit is contained in:
yuyi 2022-06-28 22:13:58 +08:00 committed by GitHub
parent b47d35a0bb
commit 3ae59a7837
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 8 deletions

View File

@ -2508,7 +2508,8 @@ pub fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
&& 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`',
kind_name := if from_sym.kind == .sum_type { 'sum type' } else { 'interface' }
c.error('cannot cast `$ft` $kind_name value to `$tt`, use `$node.expr as $tt` instead',
node.pos)
}

View File

@ -1,6 +1,13 @@
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))
vlib/v/checker/tests/cast_sumtype_err.vv:8:11: error: cannot cast `Test` sum type value to `int`, use `data as int` instead
6 | fn main() {
7 | data := Test(12)
8 | eprintln(int(data))
| ~~~~~~~~~
8 | }
9 |
10 | foo := Bar('123.45')
vlib/v/checker/tests/cast_sumtype_err.vv:11:10: error: cannot cast `Bar` sum type value to `f32`, use `foo as f32` instead
9 |
10 | foo := Bar('123.45')
11 | println(f32(foo))
| ~~~~~~~~
12 | }

View File

@ -1,8 +1,12 @@
module main
type Test = int | u32 | f32
type Bar = int | string
fn main() {
data := Test(12)
eprintln(int(data))
data := Test(12)
eprintln(int(data))
foo := Bar('123.45')
println(f32(foo))
}