ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.62k stars 2.53k forks source link

"type 'usize' has fewer bits than destination type 'u32'" on 16-bit targets #10373

Open silversquirl opened 2 years ago

silversquirl commented 2 years ago

Zig Version

0.9.0-dev.2023+16b753549

Steps to Reproduce

  1. Write a program that calls a std function which truncates usize, eg.
    // test.zig
    const std = @import("std");
    export fn foo() void {
    _ = std.hash.CityHash32.hash("Hello, world!");
    }
  2. Compile this program for a 16-bit target, eg. zig build-obj -target avr-freestanding test.zig

Expected Behavior

The program should compile successfully.

Actual Behavior

$ zig build-obj -target avr-freestanding test.zig
/home/silver/.opt/zig/lib/std/hash/cityhash.zig:98:44: error: type 'usize' has fewer bits than destination type 'u32'
        const len: u32 = @truncate(u32, str.len);
                                           ^
/home/silver/.opt/zig/lib/std/hash/cityhash.zig:98:26: note: referenced here
        const len: u32 = @truncate(u32, str.len);
                         ^
silversquirl commented 2 years ago

I'm not sure whether this should be fixed in std or special-cased in the compiler. Being able to truncate usize unconditionally is useful, so maybe @truncate should just allow up-casting usize and only usize.