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

checker: add mutability check for comptime assignments (#18354)

This commit is contained in:
Turiiya 2023-06-06 18:58:30 +02:00 committed by GitHub
parent 125921db66
commit c06fd556e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 0 deletions

View File

@ -642,6 +642,13 @@ fn (mut c Checker) fail_if_immutable(expr_ ast.Expr) (string, token.Pos) {
return '', expr.pos
}
ast.ComptimeSelector {
if mut expr.left is ast.Ident {
if mut expr.left.obj is ast.Var {
if expr.left.obj.ct_type_var != .generic_param {
c.fail_if_immutable(expr.left)
}
}
}
return '', expr.pos
}
ast.Ident {

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/comptime_assign_missing_mut_err.vv:13:4: error: `res` is immutable, declare it with `mut` to make it mutable
11 | val := doc.value(field.name)
12 | $if field.typ is string {
13 | res.$(field.name) = val.string()
| ~~~
14 | }
15 | }

View File

@ -0,0 +1,21 @@
import toml
struct Person {
name string
}
fn decode[T](toml_str string) !T {
res := T{}
doc := toml.parse_text(toml_str)!.to_any()
$for field in T.fields {
val := doc.value(field.name)
$if field.typ is string {
res.$(field.name) = val.string()
}
}
return res
}
p_str := 'name = "John"'
decode[Person](p_str)!