checker, cgen: fix array index optional with if expr (#14575)

master
yuyi 2022-06-01 14:18:59 +08:00 committed by GitHub
parent 846ddfd728
commit fefb9643b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 11 additions and 1 deletions

View File

@ -3403,6 +3403,9 @@ pub fn (mut c Checker) index_expr(mut node ast.IndexExpr) ast.Type {
typ = value_type typ = value_type
} }
} }
if node.or_expr.stmts.len > 0 && node.or_expr.stmts.last() is ast.ExprStmt {
c.expected_or_type = typ
}
c.stmts_ending_with_expression(node.or_expr.stmts) c.stmts_ending_with_expression(node.or_expr.stmts)
c.check_expr_opt_call(node, typ) c.check_expr_opt_call(node, typ)
return typ return typ

View File

@ -85,7 +85,7 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
g.stmts(branch.stmts) g.stmts(branch.stmts)
g.expected_cast_type = prev_expected_cast_type g.expected_cast_type = prev_expected_cast_type
} }
if node.branches.len == 1 { if node.branches.len == 1 && !node.is_expr {
g.write(': 0') g.write(': 0')
} }
g.write(')') g.write(')')

View File

@ -0,0 +1,7 @@
fn test_array_index_optional_with_if_expr() {
ret := []string{}[0] or {
if true { 'a' } else { 'b' }
}
println(ret)
assert ret == 'a'
}