1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: fix array_init cast type error

This commit is contained in:
yuyi 2020-05-29 12:39:46 +08:00 committed by GitHub
parent bec3e07635
commit 3a340cbffc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 16 deletions

View File

@ -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)

View File

@ -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]'
}