Crystal: Check if type is a Enum in macros

Created on 24 Sep 2017  路  2Comments  路  Source: crystal-lang/crystal

class A
  enum FooBar
    Foo
    Bar
  end

  macro is_enum(_type)
    {% p "#{_type} is enum: #{_type.is_a?(Enum)}" %}
  end

  is_enum(FooBar)
end

Prints "FooBar is enum: false" :cry:

_Already tried _type.resolve.is_a?(Enum), no luck too._

question

Most helpful comment

You can use _type.resolve < Enum.

class A
  enum FooBar
    Foo
    Bar
  end

  macro is_enum(_type)
    {% p "#{_type} is enum: #{_type.resolve < Enum}" %}
  end

  is_enum(FooBar)
end

Prints "FooBar is enum: true"

All 2 comments

You can use _type.resolve < Enum.

class A
  enum FooBar
    Foo
    Bar
  end

  macro is_enum(_type)
    {% p "#{_type} is enum: #{_type.resolve < Enum}" %}
  end

  is_enum(FooBar)
end

Prints "FooBar is enum: true"

is_a? in macros check if a node is of a given AST node type. Use type < ::Enum like @firejox says

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MakeNowJust picture MakeNowJust  路  64Comments

stugol picture stugol  路  70Comments

HCLarsen picture HCLarsen  路  162Comments

asterite picture asterite  路  71Comments

farleyknight picture farleyknight  路  64Comments