checker: prevent C error on const mutation

pull/4840/head
Kris Cherven 2020-05-11 04:09:58 -04:00 committed by GitHub
parent 38277d1dac
commit 3a3d00ac72
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 54 additions and 0 deletions

View File

@ -502,6 +502,8 @@ fn (mut c Checker) fail_if_immutable(expr ast.Expr) {
c.error('`$it.name` is immutable, declare it with `mut` to make it mutable',
it.pos)
}
} else if it.name in c.const_names {
c.error('cannot assign to constant `$it.name`', it.pos)
}
}
ast.IndexExpr {

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/const_field_add_err.v:6:2: error: cannot assign to constant `a`
4 |
5 | fn main() {
6 | a += 1
| ^
7 | }

View File

@ -0,0 +1,7 @@
const (
a = 1
)
fn main() {
a += 1
}

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/const_field_dec_err.v:6:2: error: cannot assign to constant `a`
4 |
5 | fn main() {
6 | a--
| ^
7 | }

View File

@ -0,0 +1,7 @@
const (
a = 1
)
fn main() {
a--
}

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/const_field_inc_err.v:6:2: error: cannot assign to constant `a`
4 |
5 | fn main() {
6 | a++
| ^
7 | }

View File

@ -0,0 +1,7 @@
const (
a = 1
)
fn main() {
a++
}

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/const_field_sub_err.v:6:2: error: cannot assign to constant `a`
4 |
5 | fn main() {
6 | a -= 1
| ^
7 | }

View File

@ -0,0 +1,7 @@
const (
a = 1
)
fn main() {
a -= 1
}