Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -11944,7 +11944,16 @@ fn (mut g Gen) check_expr_is_const(expr ast.Expr) bool {
return g.check_expr_is_const(expr.left) && g.check_expr_is_const(expr.right)
}
ast.Ident {
return expr.kind == .function || g.table.final_sym(expr.obj.typ).kind != .array_fixed
if expr.kind == .function {
return true
}
// An ident naming a V const is a valid C constant expression
// only when that const is emitted as a simple #define'd
// literal (char/float/int literals). Struct, string and array
// consts are runtime-initialized globals, and referencing
// them in a static initializer produces
// "initializer element is not constant".
return expr.obj.is_simple_define_const()
}
ast.StructInit {
// String fields expand to the `_S()` compound literal, which strict
Expand Down
43 changes: 43 additions & 0 deletions vlib/v/tests/consts/const_fixed_array_of_struct_const_refs_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Regression test: a fixed-array const whose elements are references to
// other struct consts must compile. Struct consts are runtime-initialized
// C globals, so referencing them in a static C initializer produced
// "initializer element is not constant"; such arrays must be initialized
// in _vinit instead.
struct Info {
code i16
name string
}

const first = Info{1, 'first'}
const second = Info{2, 'second'}
const third = Info{3, 'third'}

const by_ref = [first, second, third]!

// mixing references and literals must also work
const mixed = [first, Info{9, 'literal'}]!

// simple #define'd literal consts must keep working statically
const ia = 5
const ib = 6
const int_refs = [ia, ib]!

fn test_fixed_array_of_struct_const_refs() {
assert by_ref.len == 3
assert by_ref[0].code == 1
assert by_ref[1].name == 'second'
mut total := 0
for e in by_ref {
total += int(e.code)
}
assert total == 6
}

fn test_mixed_refs_and_literals() {
assert mixed[0].name == 'first'
assert mixed[1].code == 9
}

fn test_simple_define_consts_still_static() {
assert int_refs[0] + int_refs[1] == 11
}
Loading