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, I have made an issue for this as it is related to decoding negative discriminant enum types from an allocation.

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
Copy link
Member

@jberthold jberthold left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-approving, but please change the description text

Comment on lines +6 to +9
│ (100 steps)
└─ 3 (stuck, leaf)
#traverseProjection ( toLocal ( 2 ) , thunk ( #decodeConstant ( constantKindAllo
span: 153
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should look into why this is failing. My guess is that the decoding code is not ready for signed discriminants.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did a bit of minimised testing and wrote issue #848

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants