Crystal: Specify annotation targets

Created on 4 Sep 2019  路  4Comments  路  Source: crystal-lang/crystal

Currently when you define an annotation, it is able to be applied to _ANY_ type, such as other annotations, methods, classes, enums, modules etc.

However, in some cases, some annotations are created for specific purposes. I propose there to be some way to specify what types an annotation could be applied to. This would add extra safety to the users of the annotations to make sure they are using them correctly, as well as to possibly prevent unintended effects from applying an annotation on an invalid type.

I could see this working either like

@[Targets("CLASS", "METHOD")]
annotation SomeThing; end

or

annotation SomeThing
  TARGETS = ["CLASS", "METHOD"]
end

Then if this annotation was applied to a property:

class Foo

  @[SomeThing]
  property name : String
end

It would raise a compile time error. Something like: Error: Annotation 'SomeThing' is not allowed to be declared on a property 'Foo@name'. You may only use this annotation on: CLASS, METHOD.

feature compiler

Most helpful comment

Or as an annotation DSL:

annotation SomeThing
  target :class, :method
end

All 4 comments

In other words copy Java's @Target

Or as an annotation DSL:

annotation SomeThing
  target :class, :method
end

Targets would be really nice. Also, this is definitely a separate issue which might already exist, but it would be nice if annotation logic could be put inside of the annotation rather than annotations just being referenced via macro.

Just opened up a forum RFC relating to this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pbrusco picture pbrusco  路  3Comments

relonger picture relonger  路  3Comments

Sija picture Sija  路  3Comments

asterite picture asterite  路  3Comments

RX14 picture RX14  路  3Comments