translate-c: better handling of int -> enum casts

In std.meta.cast when casting to an enum type from an integer type, first
do a C-style cast from the source value to the tag type of the enum.
This ensures that we don't get an error due to the source value not being
representable by the enum.

In transCCast() use std.meta.cast instead of directly emitting the cast
operation since the enum's underlying type may not be known at translation
time due to an MSVC bug, see https://github.com/ziglang/zig/issues/8003

Fixes #6011
This commit is contained in:
Evan Haas
2021-04-13 20:57:50 -07:00
committed by Andrew Kelley
parent ccdf55310b
commit d4d21dd46d
4 changed files with 35 additions and 9 deletions

View File

@@ -1453,4 +1453,18 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {
\\ return 0;
\\}
, "");
cases.add("Cast to enum from larger integral type. Issue #6011",
\\#include <stdint.h>
\\#include <stdlib.h>
\\enum Foo { A, B, C };
\\static inline enum Foo do_stuff(void) {
\\ int64_t i = 1;
\\ return (enum Foo)i;
\\}
\\int main(void) {
\\ if (do_stuff() != B) abort();
\\ return 0;
\\}
, "");
}