cgen: fix treating errors as values inside if expressions (#9440)

pull/9447/head
spaceface 2021-03-23 21:45:08 +01:00 committed by GitHub
parent 385cb4dd20
commit 392666e475
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 9 deletions

View File

@ -917,13 +917,11 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) {
g.stmt_path_pos << g.out.len
g.skip_stmt_pos = true
if stmt is ast.ExprStmt {
sym := g.table.get_type_symbol(stmt.typ)
if sym.name in ['Option2', 'Option'] || stmt.expr is ast.None {
tmp := g.new_tmp_var()
g.write('Option $tmp = (Option){.state = 0,.err = ')
if stmt.typ == table.error_type_idx || stmt.expr is ast.None {
g.writeln('${tmp_var}.state = 2;')
g.write('${tmp_var}.err = ')
g.expr(stmt.expr)
g.writeln('};')
g.writeln('memcpy(&$tmp_var, &$tmp, sizeof(Option));')
g.writeln(';')
} else {
mut styp := g.base_type(stmt.typ)
$if tinyc && x32 && windows {

View File

@ -7,6 +7,10 @@ fn foo2() ?int {
}
fn foo3() ?int {
return if false { 1 } else { error('foo3 error') }
}
fn foo4() ?int {
return if true { 2 } else { 0 }
}
@ -19,9 +23,15 @@ fn test_if_expr_of_optional() {
println(a2)
assert a2 == 1
a3 := foo3() or { panic('error') }
println(a3)
assert a3 == 2
if _ := foo3() {
assert false
} else {
assert err.msg == 'foo3 error'
}
a4 := foo4() or { panic('error') }
println(a4)
assert a4 == 2
}
fn foo_complex() ?int {