From 03864e4ab8b41c8ddc934af8c28f0e20800a8dab Mon Sep 17 00:00:00 2001 From: yuyi Date: Sun, 26 Dec 2021 17:34:20 +0800 Subject: [PATCH] checker: fix cast enum to alias (#12968) --- vlib/v/checker/checker.v | 3 ++- vlib/v/tests/cast_to_alias_test.v | 36 +++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/cast_to_alias_test.v diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 1a8dd1dbc3..aa93e94f17 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3483,7 +3483,8 @@ pub fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type { c.error('cannot cast `$from_type_sym.name` to `$to_type_sym.name`', node.pos) } } else if mut to_type_sym.info is ast.Alias { - if !c.check_types(from_type, to_type_sym.info.parent_type) { + if !c.check_types(from_type, to_type_sym.info.parent_type) && !(to_type_sym_final.is_int() + && from_type_sym_final.kind == .enum_) { c.error('cannot convert type `$from_type_sym.name` to `$to_type_sym.name` (alias to `$to_type_sym_final.name`)', node.pos) } diff --git a/vlib/v/tests/cast_to_alias_test.v b/vlib/v/tests/cast_to_alias_test.v new file mode 100644 index 0000000000..b9cf2caf18 --- /dev/null +++ b/vlib/v/tests/cast_to_alias_test.v @@ -0,0 +1,36 @@ +module main + +type CEnum = int + +enum Enum { + value = 1 +} + +fn foo(n int) string { + return '$n' +} + +fn bar(n CEnum) string { + return '$n' +} + +fn test_cast_to_alias() { + e := Enum.value + mut ret_str := '' + + ret_str = foo(int(e)) + println(ret_str) + assert ret_str == '1' + + ret_str = bar(int(e)) + println(ret_str) + assert ret_str == '1' + + ret_str = foo(CEnum(e)) + println(ret_str) + assert ret_str == '1' + + ret_str = bar(CEnum(e)) + println(ret_str) + assert ret_str == '1' +}