checker, cgen: fix generic map with generic type key (#12859)

pull/12865/head
yuyi 2021-12-16 15:53:05 +08:00 committed by GitHub
parent 1261468d8e
commit d8a333058d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 42 additions and 6 deletions

View File

@ -4593,8 +4593,8 @@ pub fn (mut c Checker) map_init(mut node ast.MapInit) ast.Type {
info := c.table.get_type_symbol(node.typ).map_info() info := c.table.get_type_symbol(node.typ).map_info()
c.ensure_type_exists(info.key_type, node.pos) or {} c.ensure_type_exists(info.key_type, node.pos) or {}
c.ensure_type_exists(info.value_type, node.pos) or {} c.ensure_type_exists(info.value_type, node.pos) or {}
node.key_type = c.unwrap_generic(info.key_type) node.key_type = info.key_type
node.value_type = c.unwrap_generic(info.value_type) node.value_type = info.value_type
return node.typ return node.typ
} }
if node.keys.len > 0 && node.vals.len > 0 { if node.keys.len > 0 && node.vals.len > 0 {

View File

@ -4794,10 +4794,12 @@ fn (mut g Gen) match_expr_classic(node ast.MatchExpr, is_expr bool, cond_var str
} }
fn (mut g Gen) map_init(node ast.MapInit) { fn (mut g Gen) map_init(node ast.MapInit) {
key_typ_str := g.typ(node.key_type) unwrap_key_typ := g.unwrap_generic(node.key_type)
value_typ_str := g.typ(node.value_type) unwrap_val_typ := g.unwrap_generic(node.value_type)
value_typ := g.table.get_type_symbol(node.value_type) key_typ_str := g.typ(unwrap_key_typ)
key_typ := g.table.get_final_type_symbol(node.key_type) value_typ_str := g.typ(unwrap_val_typ)
value_typ := g.table.get_type_symbol(unwrap_val_typ)
key_typ := g.table.get_final_type_symbol(unwrap_key_typ)
hash_fn, key_eq_fn, clone_fn, free_fn := g.map_fn_ptrs(key_typ) hash_fn, key_eq_fn, clone_fn, free_fn := g.map_fn_ptrs(key_typ)
size := node.vals.len size := node.vals.len
mut shared_styp := '' // only needed for shared &[]{...} mut shared_styp := '' // only needed for shared &[]{...}

View File

@ -0,0 +1,34 @@
fn counts<T>(variables []T) map[T]int {
mut tally := map[T]int{}
for var in variables {
tally[var]++
}
return tally
}
fn str_fn() {
a2 := ['1', '2', '3', '4', '5', '3', '1']
ret := counts(a2)
println(ret)
assert ret.len == 5
}
fn int_fn() {
a1 := [1, 2, 3, 4, 5, 2, 3]
ret := counts(a1)
println(ret)
assert ret.len == 5
}
fn float_fn() {
a3 := [0.1, 0.02, 0.3, 4.0, 0.3]
ret := counts(a3)
println(ret)
assert ret.len == 4
}
fn test_generic_map_with_generic_type_key() {
str_fn()
float_fn()
int_fn()
}