From eefe067c272524a30481f9271e82b462870a0f4e Mon Sep 17 00:00:00 2001 From: kalapalo Date: Fri, 2 Oct 2020 23:04:15 -0400 Subject: [PATCH] cgen: fix `as` cast when sumtype is the result of a function call (#6537) --- vlib/v/gen/cgen.v | 8 ++++++-- .../as_cast_is_expr_sumtype_fn_result_test.v | 20 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/as_cast_is_expr_sumtype_fn_result_test.v diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 457e704639..7ba796ec41 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -5044,11 +5044,13 @@ fn (mut g Gen) as_cast(node ast.AsCast) { g.write('.obj') */ dot := if node.expr_type.is_ptr() { '->' } else { '.' } - g.write('/* as */ ($styp*)__as_cast(') + g.write('/* as */ ($styp*)__as_cast((') g.expr(node.expr) + g.write(')') g.write(dot) - g.write('_object, ') + g.write('_object, (') g.expr(node.expr) + g.write(')') g.write(dot) g.write('typ, /*expected:*/$node.typ)') } @@ -5056,7 +5058,9 @@ fn (mut g Gen) as_cast(node ast.AsCast) { fn (mut g Gen) is_expr(node ast.InfixExpr) { eq := if node.op == .key_is { '==' } else { '!=' } + g.write('(') g.expr(node.left) + g.write(')') if node.left_type.is_ptr() { g.write('->') } else { diff --git a/vlib/v/tests/as_cast_is_expr_sumtype_fn_result_test.v b/vlib/v/tests/as_cast_is_expr_sumtype_fn_result_test.v new file mode 100644 index 0000000000..03c4b67660 --- /dev/null +++ b/vlib/v/tests/as_cast_is_expr_sumtype_fn_result_test.v @@ -0,0 +1,20 @@ +const( str = 'abcdefghijklmnopqrstuvwxyz' num = 1234567890 ) +struct S1 { s1 string = str } +struct S2 { s2 int = num } +type Sum = S1 | S2 + +fn test_as_cast_with_sumtype_fn_result() { + a := [Sum(S1{}), Sum(S2{})] + v1 := a.first() as S1 + assert v1.s1 == str + assert (a.first() as S1).s1 == str + v2 := a.last() as S2 + assert v2.s2 == num + assert (a.last() as S2).s2 == num +} + +fn test_is_expr_with_sumtype_fn_result() { + a := [Sum(S1{}), Sum(S2{})] + assert a.first() is S1 + assert a.last() is S2 +}