From bc640bb41103ebabf78237eed2a0b92088d1c2c4 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Tue, 21 Apr 2026 05:22:52 +0300 Subject: [PATCH] cgen: fix comptime $for f in t.fields over generic struct with ?[]t / ?[n]t fields (fixes #26903) --- vlib/v/gen/c/assign.v | 6 +++- .../comptime_for_fixed_array_field_test.v | 29 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/vlib/v/gen/c/assign.v b/vlib/v/gen/c/assign.v index 1d6309282..60c974ccf 100644 --- a/vlib/v/gen/c/assign.v +++ b/vlib/v/gen/c/assign.v @@ -1440,7 +1440,11 @@ fn (mut g Gen) assign_stmt(node_ ast.AssignStmt) { } else if g.inside_for_c_stmt { g.expr(val) } else if var_type.has_flag(.option) { - g.expr_with_opt(val, val_type, var_type) + // Blank ident option types can be stale across generic instantiations. + // Use the actual RHS option type when it is available so `_ = val` + // does not rewrap the expression into a mismatched option payload. + blank_option_type := if val_type.has_flag(.option) { val_type } else { var_type } + g.expr_with_opt(val, val_type, blank_option_type) } else { if left_sym.kind == .function { g.write('{void* _ = ') diff --git a/vlib/v/tests/comptime/comptime_for_fixed_array_field_test.v b/vlib/v/tests/comptime/comptime_for_fixed_array_field_test.v index 4c43aca65..440ed435b 100644 --- a/vlib/v/tests/comptime/comptime_for_fixed_array_field_test.v +++ b/vlib/v/tests/comptime/comptime_for_fixed_array_field_test.v @@ -84,3 +84,32 @@ fn test_fixed_array_comptime_iteration() { assert field_values[0].contains('999') assert field_values[3].contains('iteration') } + +struct GenericOptionFilter[T] { +mut: + selector ?T + selector2 ?[]T + selector3 ?[1]T +} + +fn process_generic_option_field[T](val T) { + _ = val +} + +fn count_generic_option_fields[T](val T) int { + mut count := 0 + $for f in T.fields { + process_generic_option_field(val.$(f.name)) + count++ + } + return count +} + +fn test_comptime_for_generic_option_array_fields() { + t := GenericOptionFilter[string]{ + selector: 'aa' + selector2: ['a', 'b'] + selector3: ['z']! + } + assert count_generic_option_fields(t) == 3 +} -- 2.39.5