cgen: fix code generation wrong, when '?foo.array or {}' as a 'for-in' condition (fix #20528) (#20542)

This commit is contained in:
shove 2024-01-15 21:04:30 +08:00 committed by GitHub
parent f5db8f710b
commit d783cda671
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 1 deletions

View File

@ -235,7 +235,7 @@ fn (mut g Gen) for_in_stmt(node_ ast.ForInStmt) {
} }
mut cond_var := '' mut cond_var := ''
if (node.cond is ast.Ident && !node.cond_type.has_flag(.option)) if (node.cond is ast.Ident && !node.cond_type.has_flag(.option))
|| node.cond is ast.SelectorExpr { || (node.cond is ast.SelectorExpr && node.cond.or_block.kind == .absent) {
cond_var = g.expr_string(node.cond) cond_var = g.expr_string(node.cond)
} else { } else {
cond_var = g.new_tmp_var() cond_var = g.new_tmp_var()

View File

@ -6,3 +6,23 @@ fn test_for_in_option() {
} }
assert true assert true
} }
// for issue 20528
// phenomenon: when the cond expr is SelectorExpr and the type is an array, cgen fails.
struct Foo {
data ?[]int
}
fn (f Foo) get_first() ?int {
for d in f.data or { return none } {
return d
}
return none
}
fn test_cond_is_selector_array_and_with_or_block() {
foo := Foo{
data: [1, 2, 3]
}
assert foo.get_first()? == 1
}