Crystal Expert · Lesson 1 · On the house

Macro introspection: @type, instance_vars and code generation

Read a type's own structure at compile time with @type and instance_vars, then generate methods from it with {% for %} and {% begin %}. Lesson 1 is free — on the house.

Lessons · Crystal Expert · Lesson 1 of 10 · On the house

Macro introspection: @type, instance_vars and code generation

Read a type's own structure at compile time with @type and instance_vars, then generate methods from it with {% for %} and {% begin %}.

Illustration for Crystal
Lesson 1 is on the house.

Inside a method body, {{ @type.instance_vars }} is the list of the type's instance variables, each with .name and .type. map(&.name.stringify) turns them into string literals, so field_names returns ["name", "age", "admin"].

instance_vars only works where the compiler has finished typing the class, which means inside a def. At the top level it is a compile error, so wrap it in a method such as def self.ivar_count.

{% begin %} ... {% end %} lets a {% for %} loop emit pieces of one expression. Here the loop writes one key => value, pair per instance variable, and the surrounding braces make it a single Hash literal.

Macro values are AST nodes, and three conversions cover most needs: .stringify makes a string literal, .id pastes bare code (a method or variable name), and .symbolize makes a symbol. define_flags verified, banned uses .id for verified? and .symbolize for :verified.

{{ expr }} inside a string literal pastes the source text, and #{{{ expr }}} interpolates its run-time value. That is how show 6 * 7 prints 6 * 7 = 42.

{{ "a,b,c".split(",").size }} runs at compile time, and the program contains only the literal 3. Macro code has its own methods on StringLiteral, ArrayLiteral and NumberLiteral, so constant work costs nothing at run time.

macro introspection

class User
  getter name : String
  getter age : Int32
  getter admin : Bool

  def initialize(@name, @age, @admin = false)
  end

  def field_names
    {{ @type.instance_vars.map(&.name.stringify) }}
  end

  def self.ivar_count
    {{ @type.instance_vars.size }}
  end

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

macro define_flags(*names)
  {% for n in names %}
    def {{ n.id }}?
      @flags.includes?({{ n.symbolize }})
    end
  {% end %}
end

class Account
  def initialize(@flags : Array(Symbol))
  end

  define_flags verified, banned
end

macro show(expr)
  puts "{{ expr }} = #{{{ expr }}}"
end

u = User.new("ana", 31)
p u.field_names
p u.to_h
puts User.ivar_count
a = Account.new([:verified])
puts a.verified?
puts a.banned?
show 6 * 7
show [1, 2, 3].sum
puts {{ "a,b,c".split(",").size }}
Match this when you type.

Quiz

Where can {{ @type.instance_vars }} be used?

Quiz

Which conversion pastes a macro argument as a bare method name?

Quiz

What does {% begin %} ... {% end %} allow?

Quiz

What does the compiled program contain for {{ "a,b,c".split(",").size }}?

Check

Match the still for: Macro introspection: @type, instance_vars and code generation.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.