From fc7237be7b632c06054f1d18949e59222e6424d9 Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 6 Jul 2020 18:32:59 +0800 Subject: [PATCH] checker: fix cast to sum type (fix #5690) (#5692) --- vlib/v/checker/checker.v | 2 +- vlib/v/checker/tests/match_expr_else.out | 7 ------- vlib/v/tests/sum_type_test.v | 14 ++++++++++++++ 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index bd2a92b605..864d99f6ef 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -2131,7 +2131,7 @@ pub fn (mut c Checker) expr(node ast.Expr) table.Type { } if node.expr_type == table.string_type { cast_to_type_sym := c.table.get_type_symbol(node.typ) - if cast_to_type_sym.kind != .alias { + if cast_to_type_sym.kind !in [.alias, .sum_type] { mut error_msg := 'cannot cast a string' if node.expr is ast.StringLiteral { str_lit := node.expr as ast.StringLiteral diff --git a/vlib/v/checker/tests/match_expr_else.out b/vlib/v/checker/tests/match_expr_else.out index 6e4473eda5..3db68544ef 100644 --- a/vlib/v/checker/tests/match_expr_else.out +++ b/vlib/v/checker/tests/match_expr_else.out @@ -1,10 +1,3 @@ -vlib/v/checker/tests/match_expr_else.v:4:10: error: cannot cast a string - 2 | - 3 | fn main() { - 4 | x := AA('test') - | ~~~~~~ - 5 | _ = match x { - 6 | int { vlib/v/checker/tests/match_expr_else.v:5:6: error: match must be exhaustive (add match branches for: `f64` or `else {}` at the end) 3 | fn main() { 4 | x := AA('test') diff --git a/vlib/v/tests/sum_type_test.v b/vlib/v/tests/sum_type_test.v index f797e38da9..be0b1e8bb6 100644 --- a/vlib/v/tests/sum_type_test.v +++ b/vlib/v/tests/sum_type_test.v @@ -128,3 +128,17 @@ fn test_nested_sumtype() { assert false } } + +type Abc = int | string + +fn test_string_cast_to_sumtype() { + a := Abc('test') + match a { + string { + assert true + } + int { + assert false + } + } +}