checker: add is_mut check for disallowing taking address of map's key and array's element outside unsafe (#6573)

pull/6585/head
Swastik Baranwal 2020-10-08 12:07:18 +05:30 committed by GitHub
parent 393889afa2
commit aea52af9ae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 34 additions and 38 deletions

View File

@ -2754,13 +2754,20 @@ pub fn (mut c Checker) expr(node ast.Expr) table.Type {
}
if node.right is ast.IndexExpr as index {
typ_sym := c.table.get_type_symbol(index.left_type)
if !c.inside_unsafe {
mut is_mut := false
if index.left is ast.Ident as ident {
if ident.obj is ast.Var {
v := ident.obj as ast.Var
is_mut = v.is_mut
}
}
if !c.inside_unsafe && is_mut {
if typ_sym.kind == .map {
c.error('cannot get address of map values outside unsafe blocks',
c.error('cannot take the address of mutable map values outside unsafe blocks',
index.pos)
}
if typ_sym.kind == .array {
c.error('cannot get address of array elements outside unsafe blocks',
c.error('cannot take the address of mutable array elements outside unsafe blocks',
index.pos)
}
}

View File

@ -1,7 +0,0 @@
vlib/v/checker/tests/array_get_element_address_err.vv:3:20: error: cannot get address of array elements outside unsafe blocks
1 | fn main() {
2 | arr_int := [int(23), 45, 7, 8]
3 | ele := &arr_int[1]
| ~~~
4 | println(ele)
5 | }

View File

@ -1,14 +0,0 @@
vlib/v/checker/tests/map_get_value_address_err.vv:3:12: error: cannot get address of map values outside unsafe blocks
1 | fn main() {
2 | m := {'key' : 3}
3 | a := &m['key']
| ~~~~~~~
4 | b := &{'foo': 4}['foo']
5 | println(a)
vlib/v/checker/tests/map_get_value_address_err.vv:4:21: error: cannot get address of map values outside unsafe blocks
2 | m := {'key' : 3}
3 | a := &m['key']
4 | b := &{'foo': 4}['foo']
| ~~~~~~~
5 | println(a)
6 | println(b)

View File

@ -1,7 +0,0 @@
fn main() {
m := {'key' : 3}
a := &m['key']
b := &{'foo': 4}['foo']
println(a)
println(b)
}

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/mut_array_get_element_address_err.vv:3:20: error: cannot take the address of mutable array elements outside unsafe blocks
1 | fn main() {
2 | mut arr_int := [int(23), 45, 7, 8]
3 | ele := &arr_int[1]
| ~~~
4 | println(ele)
5 | }

View File

@ -1,5 +1,5 @@
fn main() {
arr_int := [int(23), 45, 7, 8]
mut arr_int := [int(23), 45, 7, 8]
ele := &arr_int[1]
println(ele)
}

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/mut_map_get_value_address_err.vv:3:12: error: cannot take the address of mutable map values outside unsafe blocks
1 | fn main() {
2 | mut m := {'key' : 3}
3 | a := &m['key']
| ~~~~~~~
4 | println(a)
5 | }

View File

@ -0,0 +1,5 @@
fn main() {
mut m := {'key' : 3}
a := &m['key']
println(a)
}

View File

@ -51,12 +51,10 @@ fn test_unsafe_if_stmt() int {
}
fn test_map_address_index() {
m := {
mut m := {
'one': 1
}
unsafe {
mut one := &m['one']
one++
println(*one)
}
mut one := unsafe {&m['one']}
(*one)++
println(*one)
}