Skip to content

Proposal: remove implicit @intCast behavior from @enumFromInt #22712

Open
@mlugg

Description

@mlugg

Background

The @enumToInt builtin does not currently require its operand to be of the enum's integer tag type. Rather, it can be of any integer type, and the value is first converted to the tag type with the same semantics as @intCast. The casted integer is then converted to the enum type.

This behavior was implemented in Zig 0.9.0 by bb38931, and the release notes give a hint as to why:

In summary, you can change this:

return @intToEnum(Tag, @intCast(@typeInfo(Tag).Enum.tag_type, number));

...into this:

return @intToEnum(Tag, number);

That definitely looks like it used to be quite annoying! I can see why the unnecessary friction in the first snippet would have motivated this change.

However, that isn't how casting works anymore! Because casting builtins use RLS, the first snippet would actually now look like this if @enumFromInt did not include an implicit @intCast:

return @enumFromInt(@intCast(number));

This seems like the best of both worlds: it's nice and concise, but it makes it clear what's going on. It also makes it easy to do other operations, such as truncation or bitcast:

return @enumFromInt(@truncate(number));
// or
return @enumFromInt(@bitCast(number));

That is, this proposal is equivalent to #20375.

Proposal

Revert the change implemented by bb38931, and bring @enumFromInt in line with modern casting semantics: the operand is given a result type of the enum's integer tag type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    breakingImplementing this issue could cause existing code to no longer compile or have different behavior.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions