From 3a340cbffc2aa5fe2ad29e56110aa0f0381bf7cd Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 29 May 2020 12:39:46 +0800 Subject: [PATCH] checker: fix array_init cast type error --- vlib/v/checker/checker.v | 25 +++++++++---------------- vlib/v/tests/array_init_test.v | 14 ++++++++++++++ 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 8caa823346..40d563b84e 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -1338,6 +1338,13 @@ pub fn (mut c Checker) assign_stmt(mut assign_stmt ast.AssignStmt) { c.expected_type = table.void_type } +fn (mut c Checker) check_array_init_para_type(para string, expr ast.Expr, pos token.Position) { + sym := c.table.get_type_symbol(c.expr(expr)) + if sym.kind !in [.int, .any_int] { + c.error('array $para needs to be an int', pos) + } +} + pub fn (mut c Checker) array_init(mut array_init ast.ArrayInit) table.Type { // println('checker: array init $array_init.pos.line_nr $c.file.path') mut elem_type := table.void_type @@ -1345,14 +1352,10 @@ pub fn (mut c Checker) array_init(mut array_init ast.ArrayInit) table.Type { if array_init.typ != table.void_type { if array_init.exprs.len == 0 { if array_init.has_cap { - if c.expr(array_init.cap_expr) !in [table.int_type, table.any_int_type] { - c.error('array cap needs to be an int', array_init.pos) - } + c.check_array_init_para_type('cap', array_init.cap_expr, array_init.pos) } if array_init.has_len { - if c.expr(array_init.len_expr) !in [table.int_type, table.any_int_type] { - c.error('array len needs to be an int', array_init.pos) - } + c.check_array_init_para_type('len', array_init.len_expr, array_init.pos) } } sym := c.table.get_type_symbol(array_init.elem_type) @@ -1363,16 +1366,6 @@ pub fn (mut c Checker) array_init(mut array_init ast.ArrayInit) table.Type { } // a = [] if array_init.exprs.len == 0 { - if array_init.has_cap { - if c.expr(array_init.cap_expr) !in [table.int_type, table.any_int_type] { - c.error('array cap needs to be an int', array_init.pos) - } - } - if array_init.has_len { - if c.expr(array_init.len_expr) !in [table.int_type, table.any_int_type] { - c.error('array len needs to be an int', array_init.pos) - } - } type_sym := c.table.get_type_symbol(c.expected_type) if type_sym.kind != .array { c.error('array_init: no type specified (maybe: `[]Type{}` instead of `[]`)', array_init.pos) diff --git a/vlib/v/tests/array_init_test.v b/vlib/v/tests/array_init_test.v index 6306bfd40f..6aa0dea616 100644 --- a/vlib/v/tests/array_init_test.v +++ b/vlib/v/tests/array_init_test.v @@ -155,3 +155,17 @@ fn test_array_init_in_struct_field() { println(m) assert m.ar.str() == '[1.2, 1.2, 1.2, 1.2]' } + +struct Aaa { +pub mut: + a []int +} + +fn test_array_init_cast_type_in_struct_field() { + size := u32(5) + st := &Aaa{ + a: []int{len: int(size)} + } + println(st) + assert st.a.str() == '[0, 0, 0, 0, 0]' +}