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.stmt_path_pos << g.out.len
g.skip_stmt_pos = true g.skip_stmt_pos = true
if stmt is ast.ExprStmt { if stmt is ast.ExprStmt {
sym := g.table.get_type_symbol(stmt.typ) if stmt.typ == table.error_type_idx || stmt.expr is ast.None {
if sym.name in ['Option2', 'Option'] || stmt.expr is ast.None { g.writeln('${tmp_var}.state = 2;')
tmp := g.new_tmp_var() g.write('${tmp_var}.err = ')
g.write('Option $tmp = (Option){.state = 0,.err = ')
g.expr(stmt.expr) g.expr(stmt.expr)
g.writeln('};') g.writeln(';')
g.writeln('memcpy(&$tmp_var, &$tmp, sizeof(Option));')
} else { } else {
mut styp := g.base_type(stmt.typ) mut styp := g.base_type(stmt.typ)
$if tinyc && x32 && windows { $if tinyc && x32 && windows {

View File

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