cgen: fix `as` cast when sumtype is the result of a function call (#6537)

pull/6474/head
kalapalo 2020-10-02 23:04:15 -04:00 committed by GitHub
parent 259f6ea42c
commit eefe067c27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 2 deletions

View File

@ -5044,11 +5044,13 @@ fn (mut g Gen) as_cast(node ast.AsCast) {
g.write('.obj') g.write('.obj')
*/ */
dot := if node.expr_type.is_ptr() { '->' } else { '.' } 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.expr(node.expr)
g.write(')')
g.write(dot) g.write(dot)
g.write('_object, ') g.write('_object, (')
g.expr(node.expr) g.expr(node.expr)
g.write(')')
g.write(dot) g.write(dot)
g.write('typ, /*expected:*/$node.typ)') 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) { fn (mut g Gen) is_expr(node ast.InfixExpr) {
eq := if node.op == .key_is { '==' } else { '!=' } eq := if node.op == .key_is { '==' } else { '!=' }
g.write('(')
g.expr(node.left) g.expr(node.left)
g.write(')')
if node.left_type.is_ptr() { if node.left_type.is_ptr() {
g.write('->') g.write('->')
} else { } else {

View File

@ -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
}