Skip to content

Commit

Permalink
Enum: automatically generate a none? method for a Flags enum
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Nov 22, 2016
1 parent eab0094 commit 202e771
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
15 changes: 15 additions & 0 deletions spec/compiler/codegen/enum_spec.cr
Expand Up @@ -303,4 +303,19 @@ describe "Code gen: enum" do
Foo::A.value
)).to_i.should eq(30)
end

it "adds a none? method to flags enum" do
run(%(
@[Flags]
enum Foo
A
B
end
x = 0
x += 1 if Foo::None.none?
x += 2 if Foo::A.none?
x
)).to_i.should eq(1)
end
end
8 changes: 8 additions & 0 deletions src/compiler/crystal/semantic/top_level_visitor.cr
Expand Up @@ -477,6 +477,8 @@ class Crystal::TopLevelVisitor < Crystal::SemanticVisitor
none = NumberLiteral.new(0, enum_base_type.kind)
none.type = enum_type
enum_type.add_constant Arg.new("None", default_value: none)

define_enum_none_question_method(enum_type, node)
end

unless enum_type.types["All"]?
Expand Down Expand Up @@ -567,6 +569,12 @@ class Crystal::TopLevelVisitor < Crystal::SemanticVisitor
enum_type.add_def a_def
end

def define_enum_none_question_method(enum_type, node)
body = Call.new(Call.new(nil, "value").at(node), "==", NumberLiteral.new(0)).at(node)
a_def = Def.new("none?", body: body).at(node)
enum_type.add_def a_def
end

def visit(node : Assign)
type_assign(node.target, node.value, node)
false
Expand Down

0 comments on commit 202e771

Please sign in to comment.