Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 · Macros

Macro Reflection in Crystal – Inspecting Types at Compile Time

Learn how Crystal macros look inside types with @type, instance_vars, methods and annotations to generate to_h, equality and JSON-like code, with Ruby stand-ins.

A macro becomes really powerful when it can look at the program itself. Inside a macro, the special variable @type stands for the class or struct being compiled, and it comes with methods to list its instance variables, methods, ancestors and more. That is reflection at compile time: the macro asks questions about the type and writes code based on the answers. This is how Crystal's standard library builds JSON::Serializable, YAML::Serializable, record and property.

All Crystal listings are read-only. The Ruby stand-ins use run-time reflection (instance_variables, instance_variable_get), which is similar in spirit but happens while the program runs.

The finished-type hooks

Macros can run when something happens in the program. The most used hooks:

  • macro inherited runs each time a subclass is defined.
  • macro included runs when a module is included.
  • macro method_added runs after each method definition.
  • macro finished runs once the whole program has been read, so every class has all of its instance variables by then.
CRYSTAL
module Describable
  macro included
    def describe : String
      {% verbatim do %}
        # code pasted into the including class
      {% end %}
    end
  end
end

The simplest and most useful pattern is macro finished, or a macro that is called inside a class body after the instance variables have been declared.

Walking instance variables

@type.instance_vars is an array of MetaVar nodes. Each has a name and a type:

CRYSTAL
class User
  def initialize(@name : String, @age : Int32, @admin : Bool)
  end

  def to_h
    {
      {% for ivar in @type.instance_vars %}
        {{ivar.name.stringify}} => @{{ivar.name.id}},
      {% end %}
    }
  end
end

User.new("Ada", 36, true).to_h
# {"name" => "Ada", "age" => 36, "admin" => true}

Here the loop runs at compile time. For User the compiler expands the macro to:

CRYSTAL
def to_h
  {
    "name" => @name,
    "age" => @age,
    "admin" => @admin,
  }
end

Adding a new instance variable to the class automatically adds it to to_h, with no run-time reflection and no slowdown. Because the generated code is typed, the hash's value type is String | Int32 | Bool.

Ruby Ruby stand-in: to_h from instance variables

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Branching on the type

Inside the loop you can check each variable's type and decide what code to write. ivar.type is a TypeNode, with methods such as ==, < (is a subtype of), union? and nilable?:

CRYSTAL
class Report
  def initialize(@title : String, @count : Int32, @note : String?)
  end

  def summary
    String.build do |io|
      {% for ivar in @type.instance_vars %}
        {% if ivar.type.nilable? %}
          if value = @{{ivar.name.id}}
            io << {{ivar.name.stringify}} << "=" << value << " "
          end
        {% else %}
          io << {{ivar.name.stringify}} << "=" << @{{ivar.name.id}} << " "
        {% end %}
      {% end %}
    end
  end
end

Report.new("Q1", 7, nil).summary   # "title=Q1 count=7 "

The nilable? branch is decided at compile time; only the code that applies to each variable ends up in the program.

Ruby Ruby stand-in: branching on nil

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Reflection on methods and other types

Other things a macro can ask about a type:

CRYSTAL
{{ User.name }}                  # "User" (a string literal)
{{ User.instance_vars.size }}    # compile-time number
{{ User.methods.map(&.name) }}   # names of the defined methods
{{ User.ancestors }}             # superclasses and included modules
{{ User.has_method?(:to_h) }}    # true or false
{{ User.annotation(Deprecated) }} # see the lesson on annotations

Use {% debug %} to print the expanded code while compiling, and crystal tool expand file.cr to see what the macros produce. When a macro generates an error you cannot understand, expanding it is the quickest way to find the typo.

Building a mini-serializer

JSON::Serializable works just like the examples above: for each instance variable it generates the code that reads the field from JSON and writes it back. A sketch of the idea:

CRYSTAL
module Printable
  macro included
    def print_fields
      {% for ivar in @type.instance_vars %}
        puts "#{{{ivar.name.stringify}}}: #{@{{ivar.name.id}}.inspect}"
      {% end %}
    end
  end
end

class Point
  include Printable
  def initialize(@x : Int32, @y : Int32)
  end
end

Point.new(1, 2).print_fields
# x: 1
# y: 2

Notice the generated code is as fast as hand-written lines of puts, because that is exactly what it is.

Ruby Ruby stand-in: a Printable module

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Rules of thumb

  • Macros see only what is known at compile time: types and literals, never run-time values.
  • Reflection that depends on all instance variables must run after they are declared, such as inside macro finished or macro included called after the declarations.
  • Use @type only inside a method or macro body that belongs to a type.
  • Test the generated behavior with specs, not the expansion text.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does @type.instance_vars give you inside a macro?

    It is an array of MetaVar nodes describing the declared instance variables of the current type.
  2. 2. Why is reflection in Crystal macros faster than Ruby's instance_variables?

    The macro writes normal code per field; the program just runs that code.
  3. 3. Which tool shows what a macro expanded to?

    crystal tool expand prints the source after macro expansion, which is the fastest way to debug generated code.
  4. 4. Which hook runs after the whole program has been read?

    macro finished runs once everything is defined, so it sees all instance variables.

Summary

  • @type represents the current class or struct inside a macro.
  • instance_vars, methods, ancestors and has_method? describe the type at compile time.
  • Hooks like included, inherited and finished trigger macro code at the right moment.
  • Generated code is typed and fast: JSON::Serializable is built this way.
  • Use crystal tool expand to see the result.

Next: Annotations and Compile-Time Flags