checker: fix a bug in generics array init (#14258)

master
yuyi 2022-05-02 21:18:33 +08:00 committed by GitHub
parent d72a25098a
commit 990afe37e1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 1 deletions

View File

@ -223,7 +223,7 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
} }
fn (mut c Checker) check_array_init_para_type(para string, expr ast.Expr, pos token.Pos) { fn (mut c Checker) check_array_init_para_type(para string, expr ast.Expr, pos token.Pos) {
sym := c.table.sym(c.expr(expr)) sym := c.table.sym(c.unwrap_generic(c.expr(expr)))
if sym.kind !in [.int, .int_literal] { if sym.kind !in [.int, .int_literal] {
c.error('array $para needs to be an int', pos) c.error('array $para needs to be an int', pos)
} }

View File

@ -0,0 +1,44 @@
fn get_arr_v1<N, T>(num N, val T) []T {
return []T{len: num, init: val}
}
fn get_arr_v2<N, T>(num N, val T) []T {
return []T{len: int(num), init: val}
}
fn get_arr_v3<N, T>(num N, val T) []T {
tmp := num
return []T{len: tmp, init: val}
}
fn get_arr_v4<N, T>(num N, val T) []T {
tmp := num + 0
return []T{len: tmp, init: val}
}
fn get_arr_v5<N, T>(num N, val T) []T {
tmp := 0 + num
return []T{len: tmp, init: val}
}
fn test_generic_array_init() {
println(get_arr_v1(2, 'hallo v1'))
a1 := get_arr_v1(2, 'hallo v1')
assert a1 == ['hallo v1', 'hallo v1']
println(get_arr_v2(2, 'hallo v2'))
a2 := get_arr_v2(2, 'hallo v2')
assert a2 == ['hallo v2', 'hallo v2']
println(get_arr_v3(2, 'hallo v3'))
a3 := get_arr_v3(2, 'hallo v3')
assert a3 == ['hallo v3', 'hallo v3']
println(get_arr_v4(2, 'hallo v4'))
a4 := get_arr_v4(2, 'hallo v4')
assert a4 == ['hallo v4', 'hallo v4']
println(get_arr_v5(2, 'hallo v5'))
a5 := get_arr_v5(2, 'hallo v5')
assert a5 == ['hallo v5', 'hallo v5']
}