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

relonger picture relonger  路  3Comments

oprypin picture oprypin  路  3Comments

Sija picture Sija  路  3Comments

pbrusco picture pbrusco  路  3Comments

lgphp picture lgphp  路  3Comments