cgen: fix optional sum types (#8319)

pull/8321/head^2
Daniel Däschle 2021-01-24 20:56:44 +01:00 committed by GitHub
parent 2e695a8e8f
commit 750738aa12
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 12 deletions

View File

@ -4519,7 +4519,7 @@ fn (mut g Gen) return_statement(node ast.Return) {
}
}
for i, expr in node.exprs {
g.expr(expr)
g.expr_with_cast(expr, node.types[i], g.fn_decl.return_type.clear_flag(.optional))
if i < node.exprs.len - 1 {
g.write(', ')
}
@ -5299,7 +5299,7 @@ fn (mut g Gen) or_block(var_name string, or_block ast.OrExpr, return_type table.
if is_opt_call {
g.write('*($mr_styp*) ')
}
g.expr(expr_stmt.expr)
g.expr_with_cast(expr_stmt.expr, expr_stmt.typ, return_type.clear_flag(.optional))
if is_opt_call {
g.write('.data')
}

View File

@ -323,16 +323,52 @@ fn test_option_void_return_types_of_anon_fn_in_struct() {
}
}
fn get_string(param bool) ?string {
if param {
return 'Hello World'
}
return none
type AA = BB | CC
struct BB {
str string
}
fn test_option_auto_add_return_none() {
r := get_string(false) or {
'test'
}
assert r == 'test'
struct CC {
str string
}
fn optional_sum_type(a int) ?AA {
match a {
1 {
return BB{'Test'}
}
2 {
return CC{'Test'}
}
else {
return error('Wrong number')
}
}
}
fn test_optional_sum_type() {
res1 := optional_sum_type(1) or {
assert false
BB{}
}
res2 := optional_sum_type(2) or {
assert false
CC{}
}
if res1 is BB {
assert res1.str == 'Test'
} else {
assert false
}
if res2 is CC {
assert res2.str == 'Test'
} else {
assert false
}
optional_sum_type(3) or {
assert true
return
}
assert false
}