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

compiler: implement direct cast for sum type

This commit is contained in:
joe-conigliaro 2020-01-04 00:42:48 +11:00 committed by Alexander Medvednikov
parent 520ec0f53a
commit 43895269ff
2 changed files with 19 additions and 4 deletions

View File

@ -70,8 +70,17 @@ fn (p mut Parser) bool_expression() string {
if typ == cast_typ { if typ == cast_typ {
p.warn('casting `$typ` to `$cast_typ` is not needed') p.warn('casting `$typ` to `$cast_typ` is not needed')
} }
p.cgen.set_placeholder(start_ph, '($cast_typ)(') if typ in p.table.sum_types {
p.gen(')') T := p.table.find_type(cast_typ)
if T.parent != typ {
p.error('cannot cast `$typ` to `$cast_typ`. `$cast_typ` is not a variant of `$typ`')
}
p.cgen.set_placeholder(start_ph, '*($cast_typ*)')
p.gen('.obj')
} else {
p.cgen.set_placeholder(start_ph, '($cast_typ)(')
p.gen(')')
}
return cast_typ return cast_typ
} }
return typ return typ

View File

@ -28,12 +28,12 @@ struct BoolExpr {
} }
struct BinExpr { struct BinExpr {
name string
} }
fn expr1() Expr { fn expr1() Expr {
mut e := Expr{} mut e := Expr{}
e = BinExpr{} e = BinExpr{'binexpr'}
return e return e
//return BinExpr{} //return BinExpr{}
} }
@ -55,6 +55,12 @@ fn parse_bool() BoolExpr {
return BoolExpr{} return BoolExpr{}
} }
fn test_sum_type_cast() {
a := expr1()
b := a as BinExpr
assert b.name == 'binexpr'
}
fn test_sum_types() { fn test_sum_types() {
b := parse_bool() b := parse_bool()
handle_expr(b) handle_expr(b)