Skip to content

Commit

Permalink
checker: disallow $for i in struct.values and `$for i in enum.fiel…
Browse files Browse the repository at this point in the history
…ds` (#19845)
  • Loading branch information
Delta456 committed Nov 13, 2023
1 parent b119941 commit 55cac88
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 0 deletions.
8 changes: 8 additions & 0 deletions vlib/v/checker/comptime.v
Expand Up @@ -287,6 +287,10 @@ fn (mut c Checker) comptime_for(mut node ast.ComptimeFor) {
}
c.comptime_for_field_var = ''
c.inside_comptime_for_field = false
} else if c.table.generic_type_names(node.typ).len == 0 && sym.kind != .placeholder {
c.error('iterating over .fields is supported only for structs and interfaces, and ${sym.name} is neither',
node.typ_pos)
return
}
} else if node.kind == .values {
if sym.kind == .enum_ {
Expand All @@ -301,6 +305,10 @@ fn (mut c Checker) comptime_for(mut node ast.ComptimeFor) {
c.comptime_fields_type[node.val_var] = node.typ
c.stmts(mut node.stmts)
}
} else {
c.error('iterating over .values is supported only for enums, and ${sym.name} is not an enum',
node.typ_pos)
return
}
} else {
c.stmts(mut node.stmts)
Expand Down
7 changes: 7 additions & 0 deletions vlib/v/checker/tests/for_comptime_enum_fields_err.out
@@ -0,0 +1,7 @@
vlib/v/checker/tests/for_comptime_enum_fields_err.vv:6:11: error: iterating over .fields is supported only for structs and interfaces, and Test is neither
4 | }
5 |
6 | $for i in Test.fields {
| ~~~~
7 | println(i)
8 | }
8 changes: 8 additions & 0 deletions vlib/v/checker/tests/for_comptime_enum_fields_err.vv
@@ -0,0 +1,8 @@
enum Test {
one
two
}

$for i in Test.fields {
println(i)
}
7 changes: 7 additions & 0 deletions vlib/v/checker/tests/for_comptime_struct_values_err.out
@@ -0,0 +1,7 @@
vlib/v/checker/tests/for_comptime_struct_values_err.vv:5:11: error: iterating over .values is supported only for enums, and Foo is not an enum
3 | fn (_ Foo) hello() {}
4 |
5 | $for i in Foo.values {
| ~~~
6 | println(i)
7 | }
7 changes: 7 additions & 0 deletions vlib/v/checker/tests/for_comptime_struct_values_err.vv
@@ -0,0 +1,7 @@
struct Foo{}

fn (_ Foo) hello() {}

$for i in Foo.values {
println(i)
}

0 comments on commit 55cac88

Please sign in to comment.