cgen: simplify if guard else clause

pull/4885/head
Enzo Baldisserri 2020-05-13 18:38:00 +02:00 committed by GitHub
parent 33a9822548
commit 172e4ff853
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 8 deletions

View File

@ -1810,18 +1810,16 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
g.write(')') g.write(')')
g.inside_ternary-- g.inside_ternary--
} else { } else {
guard_ok := g.new_tmp_var()
mut is_guard := false mut is_guard := false
for i, branch in node.branches { for i, branch in node.branches {
if i == 0 { if i == 0 {
match branch.cond { match branch.cond {
ast.IfGuardExpr { ast.IfGuardExpr {
is_guard = true is_guard = true
g.writeln('bool $guard_ok;')
g.write('{ /* if guard */ ${g.typ(it.expr_type)} $it.var_name = ') g.write('{ /* if guard */ ${g.typ(it.expr_type)} $it.var_name = ')
g.expr(it.expr) g.expr(it.expr)
g.writeln(';') g.writeln(';')
g.writeln('if (($guard_ok = ${it.var_name}.ok)) {') g.writeln('if (${it.var_name}.ok) {')
} }
else { else {
g.write('if (') g.write('if (')
@ -1834,12 +1832,8 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
g.expr(branch.cond) g.expr(branch.cond)
g.writeln(') {') g.writeln(') {')
} else if i == node.branches.len - 1 && node.has_else { } else if i == node.branches.len - 1 && node.has_else {
if is_guard {
g.writeln('} if (!$guard_ok) { /* else */')
} else {
g.writeln('} else {') g.writeln('} else {')
} }
}
// Assign ret value // Assign ret value
// if i == node.stmts.len - 1 && type_sym.kind != .void {} // if i == node.stmts.len - 1 && type_sym.kind != .void {}
// g.writeln('$tmp =') // g.writeln('$tmp =')

View File

@ -60,6 +60,19 @@ fn test_if_opt() {
assert 1 == 1 assert 1 == 1
} }
fn test_if_else_opt() {
if val := err_call(true) {
assert val == 42
} else {
assert false
}
if _ := err_call(false) {
assert false
} else {
assert true
}
}
fn for_opt_default() ?string { fn for_opt_default() ?string {
return error('awww') return error('awww')
} }