Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checker: disallow $for i in struct.values and $for i in enum.fields #19845

Merged
merged 7 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions vlib/v/checker/comptime.v
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
struct Foo{}

fn (_ Foo) hello() {}

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