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

checker: add a separate error msg for fail_if_immutable for anon fns (#18854)

This commit is contained in:
Swastik Baranwal 2023-07-13 19:25:06 +05:30 committed by GitHub
parent aef4367a27
commit a9a94cfd51
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 24 additions and 4 deletions

View File

@ -685,9 +685,14 @@ fn (mut c Checker) fail_if_immutable(mut expr ast.Expr) (string, token.Pos) {
if mut expr.obj is ast.Var {
if !expr.obj.is_mut && !c.pref.translated && !c.file.is_translated
&& !c.inside_unsafe {
if c.inside_anon_fn {
c.error('the closure copy of `${expr.name}` is immutable, declare it with `mut` to make it mutable',
expr.pos)
} else {
c.error('`${expr.name}` is immutable, declare it with `mut` to make it mutable',
expr.pos)
}
}
expr.obj.is_changed = true
if expr.obj.typ.share() == .shared_t {
if expr.name !in c.locked_names {

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/closure_copy_immutable_var_err.vv:5:3: error: the closure copy of `name` is immutable, declare it with `mut` to make it mutable
3 |
4 | fn [name] () {
5 | name = 'Ivan'
| ~~~~
6 | println(name)
7 | }()

View File

@ -0,0 +1,8 @@
fn main() {
mut name := 'John'
fn [name] () {
name = 'Ivan'
println(name)
}()
}

View File

@ -1,4 +1,4 @@
vlib/v/checker/tests/closure_immutable.vv:4:3: error: `a` is immutable, declare it with `mut` to make it mutable
vlib/v/checker/tests/closure_immutable.vv:4:3: error: the closure copy of `a` is immutable, declare it with `mut` to make it mutable
2 | a := 1
3 | f1 := fn [a] () {
4 | a++
@ -12,7 +12,7 @@ vlib/v/checker/tests/closure_immutable.vv:7:16: error: original `a` is immutable
| ^
8 | a++
9 | println(a)
vlib/v/checker/tests/closure_immutable.vv:13:3: error: `b` is immutable, declare it with `mut` to make it mutable
vlib/v/checker/tests/closure_immutable.vv:13:3: error: the closure copy of `b` is immutable, declare it with `mut` to make it mutable
11 | mut b := 2
12 | f3 := fn [b] () {
13 | b++