Skip to content

Commit

Permalink
cgen: fix assert [1, 2, 3]!.index(2) == 1
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Nov 1, 2024
1 parent fc6e481 commit 6dde0f0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
8 changes: 8 additions & 0 deletions vlib/builtin/fixed_array_index_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,38 @@ fn test_index_of_ints() {
mut ii := ia.index(2)
dump(ii)
assert ii == 1
assert [1, 2, 3]!.index(2) == 1

ii = ia.index(5)
dump(ii)
assert ii == -1
assert [1, 2, 3]!.index(5) == -1
}

fn test_index_of_strings() {
sa := ['a', 'b', 'c']!
mut si := sa.index('b')
dump(si)
assert si == 1
assert ['a', 'b', 'c']!.index('b') == 1

si = sa.index('v')
dump(si)
assert si == -1
assert ['a', 'b', 'c']!.index('v') == -1
}

fn test_index_of_voidptrs() {
pa := [voidptr(123), voidptr(45), voidptr(99)]!
mut pi := pa.index(voidptr(45))
dump(pi)
assert pi == 1
assert [voidptr(123), voidptr(45), voidptr(99)]!.index(voidptr(45)) == 1

pi = pa.index(unsafe { nil })
dump(pi)
assert pi == -1
assert [voidptr(123), voidptr(45), voidptr(99)]!.index(unsafe { nil }) == -1
}

fn a() {}
Expand All @@ -44,8 +50,10 @@ fn test_index_of_fns() {
mut fi := fa.index(b)
dump(fi)
assert fi == 1
assert [a, b, c]!.index(b) == 1

fi = fa.index(v)
dump(fi)
assert fi == -1
assert [a, b, c]!.index(v) == -1
}
8 changes: 6 additions & 2 deletions vlib/v/gen/c/array.v
Original file line number Diff line number Diff line change
Expand Up @@ -1300,14 +1300,18 @@ fn (mut g Gen) gen_array_index_methods() {
// `nums.index(2)`
fn (mut g Gen) gen_array_index(node ast.CallExpr) {
fn_name := g.get_array_index_method(node.left_type)
left_sym := g.table.final_sym(node.left_type)
g.write('${fn_name}(')
if node.left_type.is_ptr() {
g.write('*')
}
g.expr(node.left)
if left_sym.kind == .array_fixed && node.left is ast.ArrayInit {
g.fixed_array_init_with_cast(node.left, node.left_type)
} else {
g.expr(node.left)
}
g.write(', ')

left_sym := g.table.final_sym(node.left_type)
elem_typ := if left_sym.kind == .array {
left_sym.array_info().elem_type
} else {
Expand Down

0 comments on commit 6dde0f0

Please sign in to comment.