Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Macros

Macro Basics in Crystal

Learn Crystal macros: what compile-time code generation is, macro definitions, {{ }} output, {% %} control, macro arguments as AST nodes, and Ruby stand-ins.

A macro is code that writes code. In Crystal, macros run while the compiler is working, long before your program starts, and they produce ordinary Crystal source that is then compiled together with everything else. Macros let you remove repetition (generating getters, comparisons or serializers), build small domain-specific languages, and do it all without any run-time cost, because the generated code is just normal code.

This is one of Crystal's most powerful and most unusual features. In Ruby, you do similar things at run time with define_method and eval. Crystal does it at compile time, so mistakes are reported as compile errors.

The Crystal listings are read-only. Ruby has no compile step, so our stand-ins generate Ruby source text with string templates and class_eval. This shows the "write code, then run it" idea honestly, but remember the real thing happens before the program starts.

Your first macro

CRYSTAL
macro say_hello(name)
  puts "Hello, {{name}}!"
end

say_hello "Ada"

The compiler replaces say_hello "Ada" with puts "Hello, Ada!". Two kinds of delimiters appear inside a macro:

  • {{ ... }} evaluates an expression and pastes the result into the generated code.
  • {% ... %} runs compile-time logic (if, for, variable assignment) and pastes nothing by itself.

The argument is not a value but a piece of syntax, an AST node (abstract syntax tree). When you wrote say_hello "Ada", name was a StringLiteral node. When you pass 1 + 2, name is a Call node for +, not 3: the macro sees the code, not its result.

Ruby Ruby stand-in: generating source text

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.

Generating methods

The classic use is cutting out boilerplate. Here a macro defines three predicate methods:

CRYSTAL
class Light
  def initialize(@state : Symbol)
  end

  {% for name in %w(red yellow green) %}
    def {{name.id}}?
      @state == :{{name.id}}
    end
  {% end %}
end

light = Light.new(:red)
light.red?     # true
light.green?   # false

{% for ... %} loops at compile time over the array literal. For each name, the body is pasted once, with {{name.id}} turned into red, yellow, green. The .id method turns a string into a bare identifier (without it you would paste "red" with quotes, which is a string, not a method name). After expansion the compiler sees three ordinary methods, red?, yellow? and green?.

Ruby Ruby stand-in: define predicate methods

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.

Writing a macro definition with logic

Macros can include {% if %}, so one macro can generate different code. A {% else %} or {% elsif %} works as in ordinary code:

CRYSTAL
macro define_getter(name, default)
  def {{name.id}}
    @{{name.id}} ||= {{default}}
  end
end

class Config
  define_getter timeout, 30
  define_getter host, "localhost"
end

Config.new.timeout   # 30
Config.new.host      # "localhost"

Here {{default}} pastes 30 or "localhost" exactly as written. The generated method is def timeout; @timeout ||= 30; end. If you pass something that would produce invalid code, the error message points at the expansion, and the compiler can show it with crystal build --error-trace.

Ruby Ruby stand-in: define_getter with class_eval

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.

Macros versus methods

Why not use a method? Because a method works with values at run time. A macro works with code at compile time, which gives it two abilities no method has:

  1. It can create new definitions: methods, classes, constants, instance variables.
  2. It can look at the structure of the program, such as the names and types of instance variables (see Macro Reflection).

If you can do it with a normal method, a block or a generic, prefer that. Macros are harder to read and debug. A good rule is to reach for a macro only when you are generating definitions or need to inspect types.

flowchart LR
  S["Your source with macros"] --> E["Macro expansion"]
  E --> P["Plain Crystal source"]
  P --> T["Type checking"]
  T --> C["Machine code"]

Macros expand early; the rest of the compiler only ever sees ordinary code.

Hygiene and fresh variables

Names you create inside a macro can collide with the caller's names. Crystal's macros are partly hygienic: a variable assigned in a macro is local to the macro's expansion, and you can ask for a unique name with %name:

CRYSTAL
macro twice_timed
  %start = Time.utc
  {{yield}}
  {{yield}}
  puts "took #{Time.utc - %start}"
end

%start is rewritten to a name like __temp_17, so it cannot clash with a start variable in the user's code. The {{yield}} pastes the block given to the macro (see Macro Reflection for more AST work).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a Crystal macro run?

    Macros expand during compilation; the output is ordinary code that the compiler type-checks and compiles.
  2. 2. What is the difference between {{ }} and {% %}?

    {{ expr }} outputs the expression into the generated code; {% ... %} executes compile-time control flow.
  3. 3. If you call say_hello 1 + 2, what does the macro parameter hold?

    Macros receive syntax trees, not evaluated values.
  4. 4. Why is .id used in def {{name.id}}?

    Without .id a string literal would be pasted with its quotes.

Summary

  • A macro is code that writes code, executed at compile time.
  • {{ }} pastes values into the output; {% %} runs if and for without pasting.
  • Macro arguments are AST nodes, not evaluated values.
  • Use .id to turn a name into an identifier and %var for hygienic temporary variables.
  • Prefer methods, blocks and generics; use macros for generating definitions.

Next: Macro Reflection: Looking Inside Types