From e19ee071a2776a753e4168a652bc992077ee2f4a Mon Sep 17 00:00:00 2001 From: Steeve Morin Date: Wed, 19 Nov 2025 15:59:40 -0800 Subject: [PATCH] Handle enum types in array accessors Closes #227 --- src/Translator.zig | 3 +- test/cases/translate/array_access_with_enum.c | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 test/cases/translate/array_access_with_enum.c diff --git a/src/Translator.zig b/src/Translator.zig index b693877..de68fea 100644 --- a/src/Translator.zig +++ b/src/Translator.zig @@ -3105,7 +3105,7 @@ fn transArrayAccess(t: *Translator, scope: *Scope, array_access: Node.ArrayAcces const index = index: { const index = try t.transExpr(scope, array_access.index, .used); const index_qt = array_access.index.qt(t.tree); - const maybe_bigger_than_usize = switch (index_qt.base(t.comp).type) { + const maybe_bigger_than_usize = type: switch (index_qt.base(t.comp).type) { .bool => { break :index try ZigTag.int_from_bool.create(t.arena, index); }, @@ -3114,6 +3114,7 @@ fn transArrayAccess(t: *Translator, scope: *Scope, array_access: Node.ArrayAcces else => false, }, .bit_int => |bit_int| bit_int.bits > t.comp.target.ptrBitWidth(), + .@"enum" => |e| if (e.tag) |tag| continue :type tag.base(t.comp).type else false, else => unreachable, }; diff --git a/test/cases/translate/array_access_with_enum.c b/test/cases/translate/array_access_with_enum.c new file mode 100644 index 0000000..6d7cf4a --- /dev/null +++ b/test/cases/translate/array_access_with_enum.c @@ -0,0 +1,29 @@ +typedef enum { + one = 1, + two = 2, +} EnumValues; + +static inline int dynamic_array_access(EnumValues idx) { + static const int values[] = {0, 1, 2}; + return values[idx - 1]; +} + +// translate +// target=native-linux +// +// pub const one: c_int = 1; +// pub const two: c_int = 2; +// pub const EnumValues = c_uint; +// pub fn dynamic_array_access(arg_idx: EnumValues) callconv(.c) c_int { +// var idx = arg_idx; +// _ = &idx; +// const static_local_values = struct { +// const values: [3]c_int = [3]c_int{ +// 0, +// 1, +// 2, +// }; +// }; +// _ = &static_local_values; +// return static_local_values.values[idx -% @as(EnumValues, 1)]; +// }