From 576192949dbc185ba478070587a6db6786288ca5 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Sun, 4 Aug 2019 03:59:12 +0200 Subject: [PATCH] fixed size array with const size: `numbers := [N]int` --- compiler/parser.v | 14 +++++++++++++- vlib/builtin/array_test.v | 17 +++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/compiler/parser.v b/compiler/parser.v index a7d2129b8f..c5e686ffb6 100644 --- a/compiler/parser.v +++ b/compiler/parser.v @@ -2482,7 +2482,16 @@ fn (p mut Parser) map_init() string { fn (p mut Parser) array_init() string { p.is_alloc = true p.check(.lsbr) - is_integer := p.tok == .number + mut is_integer := p.tok == .number // for `[10]int` + // fixed length arrays with a const len: `nums := [N]int`, same as `[10]int` basically + mut is_const_len := false + if p.tok == .name { + c := p.table.find_const(p.prepend_pkg(p.lit)) + if c.name != '' && c.typ == 'int' && p.peek() == .rsbr && !p.inside_const { + is_integer = true + is_const_len = true + } + } lit := p.lit mut typ := '' new_arr_ph := p.cgen.add_placeholder() @@ -2504,6 +2513,9 @@ fn (p mut Parser) array_init() string { if p.table.known_type(name) { p.cgen.resetln('') p.gen('STRUCT_DEFAULT_VALUE') + if is_const_len { + return '[${p.mod}__$lit]$name' + } return '[$lit]$name' } else { diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index efa9a6c77f..482e794d90 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -160,3 +160,20 @@ fn test_reverse() { assert d[i] == b[b.len-i-1] } } + +const ( + N = 5 +) + +fn test_fixed() { + mut nums := [4]int + assert nums[0] == 0 + assert nums[1] == 0 + assert nums[2] == 0 + assert nums[3] == 0 + nums[1] = 7 + assert nums[1] == 7 + /////// + nums2 := [N]int + assert nums2[N - 1] == 0 +}