diff --git a/vlib/compiler/expression.v b/vlib/compiler/expression.v index 80226e69b1..3f8cfed862 100644 --- a/vlib/compiler/expression.v +++ b/vlib/compiler/expression.v @@ -70,8 +70,17 @@ fn (p mut Parser) bool_expression() string { if typ == cast_typ { p.warn('casting `$typ` to `$cast_typ` is not needed') } - p.cgen.set_placeholder(start_ph, '($cast_typ)(') - p.gen(')') + if typ in p.table.sum_types { + 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 typ diff --git a/vlib/compiler/tests/type_test.v b/vlib/compiler/tests/type_test.v index 08ae3455f5..cb81dda236 100644 --- a/vlib/compiler/tests/type_test.v +++ b/vlib/compiler/tests/type_test.v @@ -28,12 +28,12 @@ struct BoolExpr { } struct BinExpr { - + name string } fn expr1() Expr { mut e := Expr{} - e = BinExpr{} + e = BinExpr{'binexpr'} return e //return BinExpr{} } @@ -55,6 +55,12 @@ fn parse_bool() BoolExpr { return BoolExpr{} } +fn test_sum_type_cast() { + a := expr1() + b := a as BinExpr + assert b.name == 'binexpr' +} + fn test_sum_types() { b := parse_bool() handle_expr(b)