Skip to content

Commit 504d34a

Browse files
committed
checker: fix mutable const bug (fix #14916)
1 parent 03e93b3 commit 504d34a

4 files changed

Lines changed: 20 additions & 5 deletions

File tree

‎vlib/v/checker/assign.v‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ module checker
44

55
import v.ast
66

7-
// TODO: 600 line function
7+
// TODO: 980 line function
88
fn (mut c Checker) assign_stmt(mut node ast.AssignStmt) {
99
prev_inside_assign := c.inside_assign
1010
c.inside_assign = true

‎vlib/v/checker/containers.v‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -795,6 +795,16 @@ fn (mut c Checker) check_append(mut node ast.InfixExpr, left_type ast.Type, righ
795795
if !left_value_type.has_flag(.option) && right_type.has_flag(.option) {
796796
c.error('unwrapped Option cannot be used in an infix expression', node.pos)
797797
}
798+
799+
right := node.right
800+
if right is ast.PrefixExpr && right.op == .amp {
801+
mut expr2 := right.right
802+
if mut expr2 is ast.Ident {
803+
if !node.left.is_blank_ident() && expr2.obj is ast.ConstField {
804+
c.error('cannot have mutable reference to const `${expr2.name}`', expr2.pos)
805+
}
806+
}
807+
}
798808
if left_value_sym.kind == .interface {
799809
if right_final_sym.kind != .array {
800810
// []Animal << Cat
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
vlib/v/checker/tests/ban_const_ref_mutation.vv:11:14: error: cannot have mutable reference to const `foobar_const`
2+
9 | println('foobar_const.foo: ${foobar_const.foo}') // foobar_const.foo: 123
3+
10 | mut foobars := []&Foobar{}
4+
11 | foobars << &foobar_const
5+
| ~~~~~~~~~~~~
6+
12 | foobars[0].foo = 456
7+
13 | println('foobar_const.foo: ${foobar_const.foo}') // foobar_const.foo: 456
Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
/*
21
struct Foobar {
32
mut:
43
foo int
@@ -7,10 +6,9 @@ mut:
76
const foobar_const = Foobar{123}
87

98
fn main() {
10-
println("foobar_const.foo: ${foobar_const.foo}") // foobar_const.foo: 123
9+
println('foobar_const.foo: ${foobar_const.foo}') // foobar_const.foo: 123
1110
mut foobars := []&Foobar{}
1211
foobars << &foobar_const
1312
foobars[0].foo = 456
14-
println("foobar_const.foo: ${foobar_const.foo}") // foobar_const.foo: 456
13+
println('foobar_const.foo: ${foobar_const.foo}') // foobar_const.foo: 456
1514
}
16-
*/

0 commit comments

Comments
 (0)