From 482eecbc13eb815a0f3298ace320ff457a14030b Mon Sep 17 00:00:00 2001 From: Louis Schmieder Date: Mon, 16 Aug 2021 13:58:23 +0200 Subject: [PATCH] cgen: fix comptime selector reserved field names (#11199) --- vlib/v/gen/c/comptime.v | 2 +- ..._struct_with_C_reserved_word_fields_test.v | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/comptime_for_over_struct_with_C_reserved_word_fields_test.v diff --git a/vlib/v/gen/c/comptime.v b/vlib/v/gen/c/comptime.v index ee45f91262..9689a8e8d8 100644 --- a/vlib/v/gen/c/comptime.v +++ b/vlib/v/gen/c/comptime.v @@ -20,7 +20,7 @@ fn (mut g Gen) comptime_selector(node ast.ComptimeSelector) { if node.field_expr.expr is ast.Ident { if node.field_expr.expr.name == g.comp_for_field_var && node.field_expr.field_name == 'name' { - g.write(g.comp_for_field_value.name) + g.write(c_name(g.comp_for_field_value.name)) return } } diff --git a/vlib/v/tests/comptime_for_over_struct_with_C_reserved_word_fields_test.v b/vlib/v/tests/comptime_for_over_struct_with_C_reserved_word_fields_test.v new file mode 100644 index 0000000000..f67039cff4 --- /dev/null +++ b/vlib/v/tests/comptime_for_over_struct_with_C_reserved_word_fields_test.v @@ -0,0 +1,25 @@ +struct StructWithCReservedWord { + error string + while int + extern int + switch bool +} + +fn test_structs_that_have_fields_that_are_reserved_c_words_can_be_iterated() { + foo := StructWithCReservedWord{ + error: 'this is an error message' + while: 123 + extern: 456 + switch: true + } + $for field in StructWithCReservedWord.fields { + $if field.typ is string { + println(foo.$(field.name)) + } + } + assert foo.switch + assert foo.extern == 456 + assert foo.while == 123 + assert foo.error == 'this is an error message' + println(foo) +}