Skip to content

Commit

Permalink
cgen, checker: fix comptime enumdata value property access (#19768)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Nov 7, 2023
1 parent 6b2a6b9 commit 60ba140
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
1 change: 1 addition & 0 deletions vlib/v/checker/checker.v
Expand Up @@ -1470,6 +1470,7 @@ fn (mut c Checker) selector_expr(mut node ast.SelectorExpr) ast.Type {
} else if c.inside_comptime_for_field && typ == c.enum_data_type && node.field_name == 'value' {
// for comp-time enum.values
node.expr_type = c.comptime_fields_type[c.comptime_for_field_var]
node.typ = typ
return node.expr_type
}
node.expr_type = typ
Expand Down
6 changes: 5 additions & 1 deletion vlib/v/gen/c/cgen.v
Expand Up @@ -3635,7 +3635,6 @@ fn (mut g Gen) selector_expr(node ast.SelectorExpr) {
if node.expr_type == 0 {
g.checker_bug('unexpected SelectorExpr.expr_type = 0', node.pos)
}

sym := g.table.sym(g.unwrap_generic(node.expr_type))
field_name := if sym.language == .v { c_name(node.field_name) } else { node.field_name }

Expand Down Expand Up @@ -3702,6 +3701,11 @@ fn (mut g Gen) selector_expr(node ast.SelectorExpr) {
g.expr(node.expr)
g.write(')')
return
} else if g.enum_data_type == node.typ {
g.expr(node.expr)
g.write('.')
g.write(node.field_name)
return
}
mut sum_type_deref_field := ''
mut sum_type_dot := '.'
Expand Down
35 changes: 35 additions & 0 deletions vlib/v/tests/comptime_enum_values_test.v
@@ -0,0 +1,35 @@
enum CharacterGroup {
chars
alphanumerics
numeric
special
}

fn (self CharacterGroup) value() string {
return match self {
.chars { 'first' }
.alphanumerics { 'second' }
.numeric { 'third' }
.special { 'fourth' }
}
}

fn CharacterGroup.values() []CharacterGroup {
mut res := []CharacterGroup{}
$for item in CharacterGroup.values {
res << CharacterGroup(item.value)
}
return res
}

fn test_main() {
values := CharacterGroup.values()
println('Char group values: ${values}')
println('For loop over the values')
for entry in CharacterGroup.values() {
println('Value: ${entry} ${entry.value()}')
}

assert values == [CharacterGroup.chars, CharacterGroup.alphanumerics, CharacterGroup.numeric,
CharacterGroup.special]
}

0 comments on commit 60ba140

Please sign in to comment.