From 633e612d62c6c0d54ba1ba918467593f26da7452 Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 2 May 2022 21:18:33 +0800 Subject: [PATCH] checker: fix a bug in generics array init (#14258) --- vlib/v/checker/containers.v | 2 +- vlib/v/tests/generics_array_init_test.v | 44 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/generics_array_init_test.v diff --git a/vlib/v/checker/containers.v b/vlib/v/checker/containers.v index ba8ce66916..16284444db 100644 --- a/vlib/v/checker/containers.v +++ b/vlib/v/checker/containers.v @@ -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) { - sym := c.table.sym(c.expr(expr)) + sym := c.table.sym(c.unwrap_generic(c.expr(expr))) if sym.kind !in [.int, .int_literal] { c.error('array $para needs to be an int', pos) } diff --git a/vlib/v/tests/generics_array_init_test.v b/vlib/v/tests/generics_array_init_test.v new file mode 100644 index 0000000000..f902230a4c --- /dev/null +++ b/vlib/v/tests/generics_array_init_test.v @@ -0,0 +1,44 @@ +fn get_arr_v1(num N, val T) []T { + return []T{len: num, init: val} +} + +fn get_arr_v2(num N, val T) []T { + return []T{len: int(num), init: val} +} + +fn get_arr_v3(num N, val T) []T { + tmp := num + return []T{len: tmp, init: val} +} + +fn get_arr_v4(num N, val T) []T { + tmp := num + 0 + return []T{len: tmp, init: val} +} + +fn get_arr_v5(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'] +}