Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cgen: fix array.delete_last call generation #21439

Merged
merged 2 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions vlib/v/gen/c/fn.v
Original file line number Diff line number Diff line change
Expand Up @@ -1055,11 +1055,13 @@ fn (mut g Gen) gen_array_method_call(node ast.CallExpr, left_type ast.Type) bool
g.gen_array_all(node)
return true
}
'delete', 'drop' {
'delete', 'drop', 'delete_last' {
g.write('array_${node.name}(')
g.gen_arg_from_type(left_type, node.left)
g.write(', ')
g.expr(node.args[0].expr)
if node.name != 'delete_last' {
g.write(', ')
g.expr(node.args[0].expr)
}
g.write(')')
return true
}
Expand Down
55 changes: 55 additions & 0 deletions vlib/v/tests/array_delete_last_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
struct ArrayList[T] {
mut:
size usize
items []&T
}

fn new_array_list[T]() ArrayList[T] {
return ArrayList[T]{}
}

fn (li ArrayList[T]) is_empty() bool {
return li.size == 0
}

fn (mut li ArrayList[T]) add(item &T) {
li.items << item
li.size += 1
}

fn (mut li ArrayList[T]) pop() ?&T {
if li.is_empty() {
return none
} else {
item := li.items.last()
li.items.delete_last()
li.size -= 1
return item
}
}

struct Student {
name string
mut:
age u8
}

fn (mut s Student) grow() {
s.age += 1
}

fn test_main() {
mut list := new_array_list[Student]()
assert list.is_empty() && list.size == 0

mut stu := Student{'Tom', 16}
list.add(&stu)
assert !list.is_empty() && list.size == 1
stu.grow()
assert stu.age == 17

tom := list.pop()?
assert list.is_empty() && list.size == 0
assert tom == stu
assert tom.age == 17
}
Loading