cgen: add missing clear method for generic maps (#20340)

This commit is contained in:
Felipe Pena 2024-01-02 05:07:25 -03:00 committed by GitHub
parent 6ed864d114
commit 8cef744b0d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 55 additions and 0 deletions

View File

@ -879,6 +879,12 @@ fn (mut g Gen) gen_arg_from_type(node_type ast.Type, node ast.Expr) {
fn (mut g Gen) gen_map_method_call(node ast.CallExpr, left_type ast.Type, left_sym ast.TypeSymbol) bool { fn (mut g Gen) gen_map_method_call(node ast.CallExpr, left_type ast.Type, left_sym ast.TypeSymbol) bool {
match node.name { match node.name {
'clear' {
g.write('map_clear(')
g.gen_arg_from_type(left_type, node.left)
g.write(')')
return true
}
'delete' { 'delete' {
left_info := left_sym.info as ast.Map left_info := left_sym.info as ast.Map
elem_type_str := g.typ(left_info.key_type) elem_type_str := g.typ(left_info.key_type)

View File

@ -0,0 +1,49 @@
pub type EventListener[T] = fn (T) !
pub struct EventController[T] {
mut:
id int
listeners map[int]EventListener[T]
}
fn (mut ec EventController[T]) generate_id() int {
return ec.id++
}
pub fn (mut ec EventController[T]) override(listener EventListener[T]) EventController[T] {
ec.listeners.clear()
return ec.listen(listener)
}
pub fn (mut ec EventController[T]) listen(listener EventListener[T]) EventController[T] {
ec.listeners[ec.generate_id()] = listener
return ec
}
struct Foo {}
struct Bar {}
fn make[T](i int) EventController[T] {
return EventController[T]{
id: i
}
}
fn test_main() {
mut a := EventController[Foo]{
id: 1
listeners: {
1: fn (a Foo) ! {
dump(1)
}
}
}
assert dump(a).id == 1
assert dump(a).listeners.len == 1
a.override(fn (a Foo) ! {
dump(2)
})
assert dump(a).id == 2
assert dump(a).listeners.len == 1
}