Annotations

Annotations can be used to add metadata to certain features in the source code. Types, methods, instance variables, and method/macro parameters may be annotated. User-defined annotations, such as the standard library’s JSON::Field, are defined using the annotation keyword. A number of built-in annotations are provided by the compiler.

Users can define their own annotations using the annotation keyword, which works similarly to defining a class or struct.

  1. annotation MyAnnotation
  2. end

The annotation can then be applied to various items, including:

  • Instance and class methods
  • Instance variables
  • Classes, structs, enums, and modules
  • Method and macro parameters (though the latter are currently unaccessable)
  1. annotation MyAnnotation
  2. end
  3. @[MyAnnotation]
  4. def foo
  5. "foo"
  6. end
  7. @[MyAnnotation]
  8. class Klass
  9. end
  10. @[MyAnnotation]
  11. module MyModule
  12. end
  13. def method1(@[MyAnnotation] foo)
  14. end
  15. def method2(
  16. @[MyAnnotation]
  17. bar
  18. )
  19. end
  20. def method3(@[MyAnnotation] & : String ->)
  21. end

Applications

Annotations are best used to store metadata about a given instance variable, type, or method so that it can be read at compile time using macros. One of the main benefits of annotations is that they are applied directly to instance variables/methods, which causes classes to look more natural since a standard macro is not needed to create these properties/methods.

A few applications for annotations:

Object Serialization

Have an annotation that when applied to an instance variable determines if that instance variable should be serialized, or with what key. Crystal’s JSON::Serializable and YAML::Serializable are examples of this.

ORMs

An annotation could be used to designate a property as an ORM column. The name and type of the instance variable can be read off the TypeNode in addition to the annotation; removing the need for any ORM specific macro. The annotation itself could also be used to store metadata about the column, such as if it is nullable, the name of the column, or if it is the primary key.

Fields

Data can be stored within an annotation.

  1. annotation MyAnnotaion
  2. end
  3. # The fields can either be a key/value pair
  4. @[MyAnnotation(key: "value", value: 123)]
  5. # Or positional
  6. @[MyAnnotation("foo", 123, false)]

Key/value

The values of annotation key/value pairs can be accessed at compile time via the [] method.

  1. annotation MyAnnotation
  2. end
  3. @[MyAnnotation(value: 2)]
  4. def annotation_value
  5. # The name can be a `String`, `Symbol`, or `MacroId`
  6. {{ @def.annotation(MyAnnotation)[:value] }}
  7. end
  8. annotation_value # => 2

The named_args method can be used to read all key/value pairs on an annotation as a NamedTupleLiteral. This method is defined on all annotations by default, and is unique to each applied annotation.

  1. annotation MyAnnotation
  2. end
  3. @[MyAnnotation(value: 2, name: "Jim")]
  4. def annotation_named_args
  5. {{ @def.annotation(MyAnnotation).named_args }}
  6. end
  7. annotation_named_args # => {value: 2, name: "Jim"}

Since this method returns a NamedTupleLiteral, all of the methods on that type are available for use. Especially #double_splat which makes it easy to pass annotation arguments to methods.

  1. annotation MyAnnotation
  2. end
  3. class SomeClass
  4. def initialize(@value : Int32, @name : String); end
  5. end
  6. @[MyAnnotation(value: 2, name: "Jim")]
  7. def new_test
  8. {% begin %}
  9. SomeClass.new {{ @def.annotation(MyAnnotation).named_args.double_splat }}
  10. {% end %}
  11. end
  12. new_test # => #<SomeClass:0x5621a19ddf00 @name="Jim", @value=2>

Positional

Positional values can be accessed at compile time via the [] method; however, only one index can be accessed at a time.

  1. annotation MyAnnotation
  2. end
  3. @[MyAnnotation(1, 2, 3, 4)]
  4. def annotation_read
  5. {% for idx in [0, 1, 2, 3, 4] %}
  6. {% value = @def.annotation(MyAnnotation)[idx] %}
  7. pp "{{ idx }} = {{ value }}"
  8. {% end %}
  9. end
  10. annotation_read
  11. # Which would print
  12. "0 = 1"
  13. "1 = 2"
  14. "2 = 3"
  15. "3 = 4"
  16. "4 = nil"

The args method can be used to read all positional arguments on an annotation as a TupleLiteral. This method is defined on all annotations by default, and is unique to each applied annotation.

  1. annotation MyAnnotation
  2. end
  3. @[MyAnnotation(1, 2, 3, 4)]
  4. def annotation_args
  5. {{ @def.annotation(MyAnnotation).args }}
  6. end
  7. annotation_args # => {1, 2, 3, 4}

Since the return type of TupleLiteral is iterable, we can rewrite the previous example in a better way. By extension, all of the methods on TupleLiteral are available for use as well.

  1. annotation MyAnnotation
  2. end
  3. @[MyAnnotation(1, "foo", true, 17.0)]
  4. def annotation_read
  5. {% for value, idx in @def.annotation(MyAnnotation).args %}
  6. pp "{{ idx }} = #{{{ value }}}"
  7. {% end %}
  8. end
  9. annotation_read
  10. # Which would print
  11. "0 = 1"
  12. "1 = foo"
  13. "2 = true"
  14. "3 = 17.0"

Reading

Annotations can be read off of a TypeNode, Def, MetaVar, or Arg using the .annotation(type : TypeNode) method. This method return an Annotation object representing the applied annotation of the supplied type.

Note

If multiple annotations of the same type are applied, the .annotation method will return the last one.

The @type and @def variables can be used to get a TypeNode or Def object to use the .annotation method on. However, it is also possible to get TypeNode/Def types using other methods on TypeNode. For example TypeNode.all_subclasses or TypeNode.methods, respectively.

Tip

Checkout the parse_type method for a more advanced way to obtain a TypeNode.

The TypeNode.instance_vars can be used to get an array of instance variable MetaVar objects that would allow reading annotations defined on those instance variables.

Note

TypeNode.instance_vars currently only works in the context of an instance/class method.

  1. annotation MyClass
  2. end
  3. annotation MyMethod
  4. end
  5. annotation MyIvar
  6. end
  7. annotation MyParameter
  8. end
  9. @[MyClass]
  10. class Foo
  11. pp {{ @type.annotation(MyClass).stringify }}
  12. @[MyIvar]
  13. @num : Int32 = 1
  14. @[MyIvar]
  15. property name : String = "jim"
  16. def properties
  17. {% for ivar in @type.instance_vars %}
  18. pp {{ ivar.annotation(MyIvar).stringify }}
  19. {% end %}
  20. end
  21. end
  22. @[MyMethod]
  23. def my_method
  24. pp {{ @def.annotation(MyMethod).stringify }}
  25. end
  26. def method_params(
  27. @[MyParameter(index: 0)]
  28. value : Int32,
  29. @[MyParameter(index: 1)] metadata,
  30. @[MyParameter(index: 2)] & : -> String
  31. )
  32. pp {{ @def.args[0].annotation(MyParameter).stringify }}
  33. pp {{ @def.args[1].annotation(MyParameter).stringify }}
  34. pp {{ @def.block_arg.annotation(MyParameter).stringify }}
  35. end
  36. Foo.new.properties
  37. my_method
  38. method_params 10, false do
  39. "foo"
  40. end
  41. pp {{ Foo.annotation(MyClass).stringify }}
  42. # Which would print
  43. "@[MyClass]"
  44. "@[MyIvar]"
  45. "@[MyIvar]"
  46. "@[MyMethod]"
  47. "@[MyParameter(index: 0)]"
  48. "@[MyParameter(index: 1)]"
  49. "@[MyParameter(index: 2)]"
  50. "@[MyClass]"

Warning

Annotations can only be read off of typed block parameters. See https://github.com/crystal-lang/crystal/issues/5334.

Reading Multiple Annotations

The #annotations method returns an ArrayLiteral of all annotations on a type. Optionally, a TypeNode argument with the #annotations(type : TypeNode) method filters only annotations of the provided type.

  1. annotation MyAnnotation; end
  2. annotation OtherAnnotation; end
  3. @[MyAnnotation("foo")]
  4. @[MyAnnotation(123)]
  5. @[OtherAnnotation(456)]
  6. def annotation_read
  7. {% for ann in @def.annotations(MyAnnotation) %}
  8. pp "{{ann.name}}: {{ ann[0].id }}"
  9. {% end %}
  10. puts
  11. {% for ann in @def.annotations %}
  12. pp "{{ann.name}}: {{ ann[0].id }}"
  13. {% end %}
  14. end
  15. annotation_read
  16. # Which would print:
  17. "MyAnnotation: foo"
  18. "MyAnnotation: 123"
  19. "MyAnnotation: foo"
  20. "MyAnnotation: 123"
  21. "OtherAnnotation: 456"