1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: disallow assigning mutable reference to immutable ParExpr (#18420)

This commit is contained in:
Turiiya 2023-06-13 07:52:37 +02:00 committed by GitHub
parent ada702ec66
commit 2ca3046bf8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 29 additions and 5 deletions

View File

@ -732,13 +732,18 @@ fn (mut c Checker) assign_stmt(mut node ast.AssignStmt) {
c.expr(right_node.right)
c.inside_ref_lit = old_inside_ref_lit
if right_node.op == .amp {
if right_node.right is ast.Ident {
if right_node.right.obj is ast.Var {
v := right_node.right.obj
expr := if right_node.right is ast.ParExpr {
right_node.right.expr
} else {
right_node.right
}
if expr is ast.Ident {
if expr.obj is ast.Var {
v := expr.obj
right_type0 = v.typ
}
if !c.inside_unsafe && assigned_var.is_mut() && !right_node.right.is_mut() {
c.error('`${right_node.right.name}` is immutable, cannot have a mutable reference to it',
if !c.inside_unsafe && assigned_var.is_mut() && !expr.is_mut() {
c.error('`${expr.name}` is immutable, cannot have a mutable reference to it',
right_node.pos)
}
}

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/assign_immutable_reference_var_with_parenthesis_err.vv:10:11: error: `a_char` is immutable, cannot have a mutable reference to it
8 |
9 | fn foo() {
10 | mut c := &(a_char)
| ^
11 | println(c)
12 | }

View File

@ -0,0 +1,12 @@
struct MyChar {
c string
}
const a_char = MyChar{
c: 'a'
}
fn foo() {
mut c := &(a_char)
println(c)
}