Skip to content

Conversation

@dkcumming
Copy link
Collaborator

@dkcumming dkcumming commented Nov 13, 2025

This PR implements semantics to cast (transmute) an integer into an enum if that enum is known to have no fields in it's variants. Some things to consider that influence this PR:

  1. Transmute is only possible between the same width bits (e.g. u8 -> i8 fine, u8 -> u16 not fine);
  2. Discriminants are stored as u128 in the type data even if they are unsigned at the source level;
  3. An integer transmuted into an enum is wellformed as long as the bit pattern matches a discriminant;

The combination of these points mean that the approach to soundly casting an integer into an enum is to treat the incoming integer as unsigned (converting if signed), and check if that value is in the discriminants. If yes, follow to the corresponding variant position; if not return #UBErrorInvalidDisciminantsInEnumCast.

The added code has meant a work around with retrieving the discriminant of a thunked cast can be removed.

All added tests that should pass do except for one which is failing, but I am unsure what the reason is. I would like some feedback on that.

This test should fail the test suite as it thunks, but doesn't due to a
hack rule that was introduced. This rule stops the thunk from occurring.
- Corrected rules to check discriminant is valid;
- Aggregate returned uses the discriminant to look up the variant;
- Added error condition to prevent thunk if discriminant is invalid;
- Added fail and passing tests;
- `#cast` uses `truncate` similar to `SwitchInt`;
- Added test cases with negative discriminant;
- Added test cases with positive discriminant and negative value;
- Signed discriminants test fails but for unrelated reason I believe.
@dkcumming dkcumming requested a review from jberthold November 14, 2025 09:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants