Skip to content

@intToEnum not checking for value out of range of enum tag type #14155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
euclidianAce opened this issue Jan 2, 2023 · 1 comment
Closed
Labels
bug Observed behavior contradicts documented or intended behavior
Milestone

Comments

@euclidianAce
Copy link

Zig Version

0.11.0-dev.1026+4172c2916

Steps to Reproduce and Observed Behavior

// enum.zig
const std = @import("std");
pub fn main() void {
    const E = enum(u3) { a, b, c, _ };
    std.debug.print("{}, {}\n", .{
        @intToEnum(E, 100),
        @intToEnum(E, 101),
    });
}
$ zig run enum.zig 
enum.main.E(4), enum.main.E(5)

It currently seems to just mask off the upper bits without checking that 100 is representable in a u3.

Expected Behavior

A safety check of some kind as documented here

Attempting to convert an integer which represents no value in the chosen enum type invokes safety-checked Undefined Behavior.

Furthermore, @intToEnum should arguably take the tag type of the given enumeration rather than anytype to prevent this at the type level.

@intToEnum(comptime DestType: type, integer: anytype) DestType
// vs.
@intToEnum(comptime DestType: type, integer: std.meta.Tag(DestType)) DestType

Possibly related:

@euclidianAce euclidianAce added the bug Observed behavior contradicts documented or intended behavior label Jan 2, 2023
@Vexu Vexu added this to the 0.10.1 milestone Jan 2, 2023
@Vexu
Copy link
Member

Vexu commented Jan 2, 2023

Furthermore, @intToEnum should arguably take the tag type of the given enumeration rather than anytype to prevent this at the type level.

This was intentionally changed in bb38931

Possibly related:

That is a runtime bug and this is a comptime bug, similar but unrelated.

TUSF pushed a commit to TUSF/zig that referenced this issue May 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Observed behavior contradicts documented or intended behavior
Projects
None yet
Development

No branches or pull requests

2 participants