Also detect mutable assignment, not just initialization

pull/13813/head
Nick Treleaven 2022-03-23 12:28:57 +00:00
parent d9394b5041
commit 45a556ab34
3 changed files with 28 additions and 13 deletions

View File

@ -338,7 +338,7 @@ pub fn (mut c Checker) assign_stmt(mut node ast.AssignStmt) {
if left_sym.kind == .array && mut left is ast.Ident && mut right is ast.IndexExpr { if left_sym.kind == .array && mut left is ast.Ident && mut right is ast.IndexExpr {
sym := c.table.sym(right.left_type) sym := c.table.sym(right.left_type)
if sym.kind == .array && mut right.left is ast.Ident { if sym.kind == .array && mut right.left is ast.Ident {
if left.is_mut && !right.left.is_mut() { if left.is_mut() && !right.left.is_mut() {
if right.index is ast.RangeExpr { if right.index is ast.RangeExpr {
c.error('cannot mutate immutable slice', right.left.pos) c.error('cannot mutate immutable slice', right.left.pos)
} else { } else {

View File

@ -1,14 +1,28 @@
vlib/v/checker/tests/index_expr_mutation.vv:3:11: error: cannot mutate immutable slice vlib/v/checker/tests/index_expr_mutation.vv:5:11: error: cannot mutate immutable slice
1 | fn test_immutable_slice() { 3 | fn test_immutable_slice() {
2 | arr := [1, 2, 3, 4, 5] 4 | arr := [1, 2, 3, 4, 5]
3 | mut s := arr[1..2] 5 | mut s := arr[1..2]
| ~~~ | ~~~
4 | s[0] = 0 6 | s[0] = 0
5 | } 7 | s = arr[1..2]
vlib/v/checker/tests/index_expr_mutation.vv:9:11: error: cannot mutate immutable element vlib/v/checker/tests/index_expr_mutation.vv:7:6: error: cannot mutate immutable slice
7 | fn test_immutable_element() { 5 | mut s := arr[1..2]
8 | a := [[1]] 6 | s[0] = 0
9 | mut b := a[0] 7 | s = arr[1..2]
| ~~~
8 | mut s2 := imm_arr[..]
9 | s2[0] = 0
vlib/v/checker/tests/index_expr_mutation.vv:8:12: error: cannot mutate immutable slice
6 | s[0] = 0
7 | s = arr[1..2]
8 | mut s2 := imm_arr[..]
| ~~~~~~~
9 | s2[0] = 0
10 | }
vlib/v/checker/tests/index_expr_mutation.vv:14:11: error: cannot mutate immutable element
12 | fn test_immutable_element() {
13 | a := [[1]]
14 | mut b := a[0]
| ^ | ^
10 | b[0] = 0 15 | b[0] = 0
11 | } 16 | }

View File

@ -4,6 +4,7 @@ fn test_immutable_slice() {
arr := [1, 2, 3, 4, 5] arr := [1, 2, 3, 4, 5]
mut s := arr[1..2] mut s := arr[1..2]
s[0] = 0 s[0] = 0
s = arr[1..2]
mut s2 := imm_arr[..] mut s2 := imm_arr[..]
s2[0] = 0 s2[0] = 0
} }