checker - improve error for `as` casting on non-sum type (#6587)

pull/6593/head
Nick Treleaven 2020-10-09 15:12:12 +01:00 committed by GitHub
parent fc375a40f8
commit 36706126fd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 3 deletions

View File

@ -2575,9 +2575,11 @@ pub fn (mut c Checker) expr(node ast.Expr) table.Type {
// c.error('only $info.variants can be casted to `$typ`', node.pos)
}
} else {
//
c.error('cannot cast non sum type `$type_sym.source_name` using `as`',
node.pos)
mut s := 'cannot cast non-sum type `$expr_type_sym.source_name` using `as`'
if type_sym.kind == .sum_type {
s += ' - use e.g. `${type_sym.source_name}(some_expr)` instead.'
}
c.error(s, node.pos)
}
return node.typ.to_ptr()
// return node.typ

View File

@ -0,0 +1,27 @@
vlib/v/checker/tests/sum.vv:5:8: error: cannot cast non-sum type `int` using `as`
3 | fn non_sum() {
4 | v := 4
5 | _ = v as rune
| ~~
6 | _ = v as Var
7 | }
vlib/v/checker/tests/sum.vv:6:8: error: cannot cast non-sum type `int` using `as` - use e.g. `Var(some_expr)` instead.
4 | v := 4
5 | _ = v as rune
6 | _ = v as Var
| ~~
7 | }
8 |
vlib/v/checker/tests/sum.vv:10:11: error: cannot cast `rune` to `Var`
8 |
9 | fn sum() {
10 | _ := Var(`J`)
| ~~~
11 | mut s2 := Var('')
12 | s2 = true
vlib/v/checker/tests/sum.vv:12:7: error: cannot assign `bool` to `s2` of type `Var`
10 | _ := Var(`J`)
11 | mut s2 := Var('')
12 | s2 = true
| ~~~~
13 | }

View File

@ -0,0 +1,13 @@
type Var = int | string
fn non_sum() {
v := 4
_ = v as rune
_ = v as Var
}
fn sum() {
_ := Var(`J`)
mut s2 := Var('')
s2 = true
}