From 3e3d45b2b137bf8f22893efc9b8ce313ff2e7c02 Mon Sep 17 00:00:00 2001 From: zakuro Date: Wed, 13 Jan 2021 14:03:23 +0900 Subject: [PATCH] parser: improve array init warning (#8024) --- vlib/v/parser/containers.v | 6 ++++-- vlib/v/parser/tests/array_init.out | 12 ++++++++++++ vlib/v/parser/tests/array_init.vv | 4 ++++ 3 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 vlib/v/parser/tests/array_init.out create mode 100644 vlib/v/parser/tests/array_init.vv diff --git a/vlib/v/parser/containers.v b/vlib/v/parser/containers.v index 35d3578d37..eb458f92ce 100644 --- a/vlib/v/parser/containers.v +++ b/vlib/v/parser/containers.v @@ -36,6 +36,7 @@ fn (mut p Parser) array_init() ast.ArrayInit { array_type = table.new_type(idx) has_type = true } + last_pos = p.tok.position() } else { // [1,2,3] or [const]byte for i := 0; p.tok.kind !in [.rsbr, .eof]; i++ { @@ -57,6 +58,7 @@ fn (mut p Parser) array_init() ast.ArrayInit { if exprs.len == 1 && p.tok.kind in [.name, .amp, .lsbr] && p.tok.line_nr == line_nr { // [100]byte elem_type = p.parse_type() + last_pos = p.tok.position() is_fixed = true if p.tok.kind == .lcbr { p.next() @@ -75,7 +77,7 @@ fn (mut p Parser) array_init() ast.ArrayInit { p.check(.rcbr) } else { p.warn_with_pos('use e.g. `x := [1]Type{}` instead of `x := [1]Type`', - last_pos) + first_pos.extend(last_pos)) } } else { if p.tok.kind == .not && p.tok.line_nr == p.prev_tok.line_nr { @@ -92,7 +94,7 @@ fn (mut p Parser) array_init() ast.ArrayInit { } } if exprs.len == 0 && p.tok.kind != .lcbr && has_type { - p.warn_with_pos('use `x := []Type{}` instead of `x := []Type`', last_pos) + p.warn_with_pos('use `x := []Type{}` instead of `x := []Type`', first_pos.extend(last_pos)) } mut has_len := false mut has_cap := false diff --git a/vlib/v/parser/tests/array_init.out b/vlib/v/parser/tests/array_init.out new file mode 100644 index 0000000000..75bdbe31a6 --- /dev/null +++ b/vlib/v/parser/tests/array_init.out @@ -0,0 +1,12 @@ +vlib/v/parser/tests/array_init.vv:2:7: warning: use `x := []Type{}` instead of `x := []Type` + 1 | fn main() { + 2 | _ := []int + | ~~~~~ + 3 | _ := [1]int + 4 | } +vlib/v/parser/tests/array_init.vv:3:7: warning: use e.g. `x := [1]Type{}` instead of `x := [1]Type` + 1 | fn main() { + 2 | _ := []int + 3 | _ := [1]int + | ~~~~~~ + 4 | } diff --git a/vlib/v/parser/tests/array_init.vv b/vlib/v/parser/tests/array_init.vv new file mode 100644 index 0000000000..4bbfb88ed2 --- /dev/null +++ b/vlib/v/parser/tests/array_init.vv @@ -0,0 +1,4 @@ +fn main() { + _ := []int + _ := [1]int +}