cgen: fix assert [1, 2, 3]!.contains(2) (#22725)

This commit is contained in:
yuyi 2024-11-02 16:16:54 +08:00 committed by GitHub
parent fc6e481bc3
commit 3b828f3ca1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 4 deletions

View File

@ -3,10 +3,12 @@ fn test_contains_of_ints() {
mut ii := ia.contains(2)
dump(ii)
assert ii
assert [1, 2, 3]!.contains(2)
ii = ia.contains(5)
dump(ii)
assert !ii
assert ![1, 2, 3]!.contains(5)
}
fn test_contains_of_strings() {
@ -14,10 +16,12 @@ fn test_contains_of_strings() {
mut si := sa.contains('b')
dump(si)
assert si
assert ['a', 'b', 'c']!.contains('b')
si = sa.contains('v')
dump(si)
assert !si
assert !['a', 'b', 'c']!.contains('v')
}
fn test_contains_of_voidptrs() {
@ -25,10 +29,12 @@ fn test_contains_of_voidptrs() {
mut pi := pa.contains(voidptr(45))
dump(pi)
assert pi
assert [voidptr(123), voidptr(45), voidptr(99)]!.contains(voidptr(45))
pi = pa.contains(unsafe { nil })
dump(pi)
assert !pi
assert ![voidptr(123), voidptr(45), voidptr(99)]!.contains(unsafe { nil })
}
fn a() {}
@ -44,8 +50,10 @@ fn test_contains_of_fns() {
mut fi := fa.contains(b)
dump(fi)
assert fi
assert [a, b, c]!.contains(b)
fi = fa.contains(v)
dump(fi)
assert !fi
assert ![a, b, c]!.contains(v)
}

View File

@ -1150,16 +1150,20 @@ fn (mut g Gen) gen_array_contains_methods() {
// `nums.contains(2)`
fn (mut g Gen) gen_array_contains(left_type ast.Type, left ast.Expr, right_type ast.Type, right ast.Expr) {
fn_name := g.get_array_contains_method(left_type)
left_sym := g.table.final_sym(left_type)
g.write2('${fn_name}(', strings.repeat(`*`, left_type.nr_muls()))
if left_type.share() == .shared_t {
g.go_back(1)
}
g.expr(left)
if left_sym.kind == .array_fixed && left is ast.ArrayInit {
g.fixed_array_init_with_cast(left, left_type)
} else {
g.expr(left)
}
if left_type.share() == .shared_t {
g.write('->val')
}
g.write(', ')
left_sym := g.table.final_sym(left_type)
elem_typ := if left_sym.kind == .array {
left_sym.array_info().elem_type
} else {
@ -1173,7 +1177,7 @@ fn (mut g Gen) gen_array_contains(left_type ast.Type, left ast.Expr, right_type
}
if g.table.sym(elem_typ).kind in [.interface, .sum_type] {
g.expr_with_cast(right, right_type, elem_typ)
} else if right is ast.ArrayInit {
} else if right is ast.ArrayInit && g.table.final_sym(right_type).kind == .array_fixed {
g.fixed_array_init_with_cast(right, right_type)
} else {
g.expr(right)
@ -1320,7 +1324,8 @@ fn (mut g Gen) gen_array_index(node ast.CallExpr) {
}
if g.table.sym(elem_typ).kind in [.interface, .sum_type] {
g.expr_with_cast(node.args[0].expr, node.args[0].typ, elem_typ)
} else if node.args[0].expr is ast.ArrayInit {
} else if node.args[0].expr is ast.ArrayInit
&& g.table.final_sym(node.args[0].typ).kind == .array_fixed {
g.fixed_array_init_with_cast(node.args[0].expr, node.args[0].typ)
} else {
g.expr(node.args[0].expr)