Skip to content

Commit

Permalink
parser: add error for array init of Results []!type{} (fix #23360) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
islonely authored Jan 5, 2025
1 parent c77292a commit 66ac23f
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 3 deletions.
1 change: 1 addition & 0 deletions doc/docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -1051,6 +1051,7 @@ An array can be of these types:
| Thread | `[]thread int` |
| Reference | `[]&f64` |
| Shared | `[]shared MyStructType` |
| Option | `[]?f64` |

**Example Code:**

Expand Down
6 changes: 5 additions & 1 deletion vlib/v/parser/containers.v
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,17 @@ fn (mut p Parser) array_init(is_option bool, alias_array_type ast.Type) ast.Arra
line_nr := p.tok.line_nr
p.next()
// []string
if p.tok.kind in [.name, .amp, .lsbr, .question, .key_shared]
if p.tok.kind in [.name, .amp, .lsbr, .question, .key_shared, .not]
&& p.tok.line_nr == line_nr {
elem_type_pos = p.tok.pos()
elem_type = p.parse_type()
// this is set here because it's a known type, others could be the
// result of expr so we do those in checker
if elem_type != 0 {
if elem_type.has_flag(.result) {
p.error_with_pos('arrays do not support storing Result values',
elem_type_pos)
}
idx := p.table.find_or_register_array(elem_type)
if elem_type.has_flag(.generic) {
array_type = ast.new_type(idx).set_flag(.generic)
Expand Down
11 changes: 9 additions & 2 deletions vlib/v/parser/tests/array_init.out
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,17 @@ vlib/v/parser/tests/array_init.vv:2:7: warning: use `x := []Type{}` instead of `
2 | _ := []int
| ~~~~~
3 | _ := [1]int
4 | }
4 | _ := []!int{}
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 | }
4 | _ := []!int{}
5 | }
vlib/v/parser/tests/array_init.vv:4:9: error: arrays do not support storing Result values
2 | _ := []int
3 | _ := [1]int
4 | _ := []!int{}
| ^
5 | }
1 change: 1 addition & 0 deletions vlib/v/parser/tests/array_init.vv
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
fn main() {
_ := []int
_ := [1]int
_ := []!int{}
}

0 comments on commit 66ac23f

Please sign in to comment.