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

Stricter checks for enum definitions #12945

Merged
merged 1 commit into from
Jan 15, 2023

Conversation

HertzDevil
Copy link
Contributor

This PR makes it an error to reopen an enum with an explicit base type that is different from its original definition:

enum Foo; X; end
enum Foo : UInt8; end # Error: enum Foo's base type is Int32, not UInt8

enum Bar : UInt16; X; end
enum Bar : UInt32; end # Error: enum Bar's base type is UInt16, not UInt32
enum Bar; end          # okay, base type not explicitly specified

It also improves overflow detection so that it works immediately after an enum member with a value is declared: (previously the overflow error would trigger on the subsequent enum member afterwards, or not at all)

enum Foo1
  A = 0x7FFFFFFF
  B # Error: value of enum member B would overflow the base type Int32
end

@[Flags]
enum Foo2
  A = 0x40000000
  B # Error: value of enum member B would overflow the base type Int32
end

@[Flags]
enum Foo3 : UInt32
  A = 0x80000000
  B # Error: value of enum member B would overflow the base type UInt32
end

Note that the overflow criterion for signed flags enums is the same as normal multiplication. And indeed this is the case when the overflowing member is succeeded by a valueless member:

@[Flags]
enum Foo4
  A = 0x20000000
  B
  C # Error: value of enum member C would overflow the base type Int32
end

Some code in the wild might assume it is okay to have Foo2::B == -0x80000000 here. IMO this is a bug rather than a breaking change.

Finally, visit_enum_member's implementation is largely refactored, and there are fewer parameters and return values now. (It also removes one of the compiler's remaining non-forwarding uses of an **options parameter.)

@HertzDevil HertzDevil added kind:bug A bug in the code. Does not apply to documentation, specs, etc. kind:refactor topic:compiler:semantic labels Jan 12, 2023
@straight-shoota straight-shoota added this to the 1.8.0 milestone Jan 13, 2023
@straight-shoota straight-shoota merged commit 440b62d into crystal-lang:master Jan 15, 2023
@HertzDevil HertzDevil deleted the bug/stricter-enums branch January 18, 2023 13:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind:bug A bug in the code. Does not apply to documentation, specs, etc. kind:refactor topic:compiler:semantic
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants