zig
zig copied to clipboard
Translate-C: Fix division and modulo of >8-bit stdint.h types in macros
@cImport fails to import FreeRTOS headers because they divide a uintXX_t in a macro, translate-c converts the type to uXX and c_translation.zig's PromotedIntType rejects Zig integer types (except [iu]8) since #13329.
test.zig:
const c = @cImport({
// @cDefine("uint32_t", "unsigned long"); workaround
@cInclude("test.h");
});
comptime { _ = c.portTICK_PERIOD_MS; }
test.h:
#include <stdint.h>
#define portTICK_PERIOD_MS ((uint32_t)1000 / 2)
Compilation log (Zig 0.12)
$ zig build-obj -I. test.zig
/usr/lib/zig/std/zig/c_translation.zig:448:13: error: Cannot promote `u32`; a C ABI type is required
@compileError("Cannot promote `" ++ @typeName(T) ++ "`; a C ABI type is required");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/lib/zig/std/zig/c_translation.zig:484:39: note: called from here
const A_Promoted = PromotedIntType(A);
~~~~~~~~~~~~~~~^~~
/usr/lib/zig/std/zig/c_translation.zig:542:60: note: called from here
pub fn div(a: anytype, b: anytype) ArithmeticConversion(@TypeOf(a), @TypeOf(b)) {
~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
firmware/zig-cache/o/204410cc92a2a93776005aa2fe7267a9/cimport.zig:602:84: note: called from here
pub const portTICK_PERIOD_MS = @import("std").zig.c_translation.MacroArithmetic.div(@import("std").zig.c_translation.cast(u32, @as(c_int, 1000)), @as(c_int, 2));
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
referenced by:
comptime_0: test.zig:5:17
remaining reference traces hidden; use '-freference-trace' to see all reference traces
Only the division and modulo operations use that integer promotion check, so they are the only ones affected by the issue.
(Related PRs: #13329 and #13371, commits c616141241047d6d6c811d43f644eb1b7d2b26ce and e64eef366c68592f6daf063a8b8f85b8626a1598)
(Tested using zig test lib/std/zig/c_translation.zig && zig test -Itest/c_import test/c_import/macros.zig on x86_64 Linux).