Skip to content
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

Improve type safety of enumerations #778

Closed
whitequark opened this issue May 12, 2023 · 2 comments
Closed

Improve type safety of enumerations #778

whitequark opened this issue May 12, 2023 · 2 comments
Labels
Milestone

Comments

@whitequark
Copy link
Member

whitequark commented May 12, 2023

Now that RFC 8 and RFC 9 are merged, we have two extension points (EnumMeta.__call__ and EnumMeta.const) that can be used to inject a wrapper class checking that the enum-shaped value is used accordingly.

  • For enums that do not inherit from int, the result of Value.cast(E.X) should not be a Value (as it currently is), and the only operations that can be performed directly should be comparisons (==, !=).
  • For flags that do not inherit from int, the result of Value.cast(E.X) should not be a Value (as it currently is), and the only operations that can be performed directly should be comparisons and bitflag set operations (==, !=, |, &, ^).

(This is essentially the same level of type safety as afforded by the Python enum module.)

  • For enums and flags that do inherit from int, the result should be a Value or at least proxying a Value (we don't currently have such a thing but maybe we should? for cases where no semantic change is desired besides some linting). This seems a lot more difficult to support. I think we don't really have to; it's the former case that worries me.

I'm putting this in the 0.4 milestone because for making Value.cast(E.X) return something other than a Value where E is a builtin Enum the ship has long sailed, but we could still return amaranth.lib.enum.EnumView or something where E is an amaranth.lib.enum.Enum since that hasn't appeared in a release yet. It becomes less of a technical drop-in replacement for the builtin Enum then (although arguably more of a conceptual drop-in replacement, since we're replicating builtin behavior), but it's probably OK since the workaround (import enum as py_enum) is trivial.

Someone needs to prototype this before writing an RFC.

@whitequark
Copy link
Member Author

whitequark commented Nov 22, 2023

@wanda-phi has written an RFC for this feature: amaranth-lang/rfcs#31, which comes with an implementation: #957

@whitequark
Copy link
Member Author

The RFC has been merged, and this feature is now tracked in #972.

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

No branches or pull requests

1 participant