parser: fix fixed array using const size (fix #8144) (#8161)

pull/8178/head
yuyi 2021-01-18 13:03:03 +08:00 committed by GitHub
parent 16c9cbce7c
commit 73fd4396c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 4 deletions

View File

@ -5,13 +5,35 @@ module parser
import v.table
import v.util
import v.ast
pub fn (mut p Parser) parse_array_type() table.Type {
p.check(.lsbr)
// fixed array
if p.tok.kind == .number {
size := p.tok.lit.int()
p.next()
if p.tok.kind in [.number, .name] {
mut fixed_size := 0
size_expr := p.expr(0)
match size_expr {
ast.IntegerLiteral {
fixed_size = size_expr.val.int()
}
ast.Ident {
if const_field := p.global_scope.find_const('${p.mod}.$size_expr.name') {
if const_field.expr is ast.IntegerLiteral {
fixed_size = const_field.expr.val.int()
} else {
p.error_with_pos('non existent integer const $size_expr.name while initializing the size of a static array',
size_expr.pos)
}
} else {
p.error_with_pos('non existent integer const $size_expr.name while initializing the size of a static array',
size_expr.pos)
}
}
else {
p.error('expecting `int` for fixed size')
}
}
p.check(.rsbr)
elem_type := p.parse_type()
if elem_type.idx() == 0 {
@ -19,7 +41,7 @@ pub fn (mut p Parser) parse_array_type() table.Type {
return 0
}
// sym := p.table.get_type_symbol(elem_type)
idx := p.table.find_or_register_array_fixed(elem_type, size)
idx := p.table.find_or_register_array_fixed(elem_type, fixed_size)
return table.new_type(idx)
}
// array

View File

@ -0,0 +1,15 @@
const (
size = 5
)
struct Foo {
bar [size]byte
}
fn test_fixed_array_const_size() {
a := Foo{}
println(a)
assert a == Foo{
bar: [byte(0), 0, 0, 0, 0]!
}
}