Skip to content

Commit

Permalink
checker: disallow assigning mutable reference to immutable ParExpr (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
ttytm committed Jun 13, 2023
1 parent ada702e commit 2ca3046
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
15 changes: 10 additions & 5 deletions vlib/v/checker/assign.v
Expand Up @@ -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)
}
}
Expand Down
@@ -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 | }
@@ -0,0 +1,12 @@
struct MyChar {
c string
}

const a_char = MyChar{
c: 'a'
}

fn foo() {
mut c := &(a_char)
println(c)
}

0 comments on commit 2ca3046

Please sign in to comment.