Skip to content

Commit

Permalink
Fix enum flags assigned values when a member has value 0 (#5954)
Browse files Browse the repository at this point in the history
  • Loading branch information
bew authored and RX14 committed Apr 28, 2018
1 parent 319a3c5 commit 346e591
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
15 changes: 15 additions & 0 deletions spec/compiler/semantic/enum_spec.cr
Expand Up @@ -183,6 +183,21 @@ describe "Semantic: enum" do
)) { int32 }
end

it "doesn't break assigned values in enum flags when a member has value 0 (#5767)" do
result = semantic(%(
@[Flags]
enum Foo
OtherNone = 0
Bar
Baz
end
))
enum_type = result.program.types["Foo"].as(EnumType)
enum_type.types["OtherNone"].as(Const).value.should eq(NumberLiteral.new(0, :i32))
enum_type.types["Bar"].as(Const).value.should eq(NumberLiteral.new(1, :i32))
enum_type.types["Baz"].as(Const).value.should eq(NumberLiteral.new(2, :i32))
end

it "disallows None value when defined with @[Flags]" do
assert_error %(
@[Flags]
Expand Down
13 changes: 11 additions & 2 deletions src/compiler/crystal/semantic/top_level_visitor.cr
Expand Up @@ -603,8 +603,17 @@ class Crystal::TopLevelVisitor < Crystal::SemanticVisitor
end

const_value.type = enum_type
counter = is_flags ? counter * 2 : counter + 1
{counter, all_value}
new_counter =
if is_flags
if counter == 0 # In case the member is set to 0
1
else
counter * 2
end
else
counter + 1
end
{new_counter, all_value}
else
member.accept self
{counter, all_value}
Expand Down

0 comments on commit 346e591

Please sign in to comment.