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

checker,json2: relax checking of x.enum = integer at comptime; refactor json2 to clean it up (#16926)

This commit is contained in:
Hitalo Souza
2023-01-11 05:18:45 -03:00
committed by GitHub
parent 09f48455c5
commit d1306ffcf5
9 changed files with 89 additions and 24 deletions

View File

@@ -593,7 +593,16 @@ fn (mut c Checker) assign_stmt(mut node ast.AssignStmt) {
node.pos)
}
} else {
c.error('cannot assign to `${left}`: ${err.msg()}', right.pos())
// allow `t.$(field.name) = 0` where `t.$(field.name)` is a enum
if c.inside_comptime_for_field && left is ast.ComptimeSelector {
field_sym := c.table.sym(c.unwrap_generic(c.comptime_fields_default_type))
if field_sym.kind == .enum_ && !right_type.is_int() {
c.error('enums can only be assigned `int` values', right.pos())
}
} else {
c.error('cannot assign to `${left}`: ${err.msg()}', right.pos())
}
}
}
}

View File

@@ -0,0 +1,7 @@
vlib/v/checker/tests/assign_enum_at_comptime.vv:13:21: error: enums can only be assigned `int` values
11 |
12 | $for field in TestStruct.fields {
13 | t.$(field.name) = '1'
| ~~~
14 | }
15 | }

View File

@@ -0,0 +1,15 @@
enum TestEnum {
one = 1
}
struct TestStruct {
test TestEnum
}
fn main() {
mut t := TestStruct{}
$for field in TestStruct.fields {
t.$(field.name) = '1'
}
}

View File

@@ -5,6 +5,14 @@ mut:
name string
}
enum TestEnum {
one = 1
}
struct TestStruct {
test TestEnum
}
fn comptime_field_selector_read[T]() []string {
mut t := T{}
t.name = '2'
@@ -42,6 +50,15 @@ fn test_comptime_field_selector_write() {
assert res.name == '1'
}
fn test_comptime_field_selector_write_enum() {
mut t := TestStruct{}
$for field in TestStruct.fields {
t.$(field.name) = 1
}
assert t.test == .one
}
struct Foo2 {
f Foo
}