Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Macros

Annotations and Compile-Time Flags in Crystal

Learn Crystal annotations (@[Deprecated], @[AlwaysInline], custom annotations), compile flags with flag?, platform checks and compile-time constants, with Ruby stand-ins.

Macros are not only about generating methods. Crystal also lets you attach metadata to code with annotations, and choose code paths with compile-time flags such as "this is a release build" or "this is Linux". Both ideas are resolved before the program runs, so the unused branch never reaches the final binary.

The compiler is not available on this site, so the Crystal listings are read-only. The Ruby stand-ins imitate the same decisions with run-time registries and constants; they say clearly where Ruby differs.

Built-in annotations

An annotation is written @[Name] or @[Name(arguments)] right before a definition. The compiler and the standard library give some of them special meaning:

CRYSTAL
@[Deprecated("Use new_total instead")]
def total(items)
  new_total(items)
end

@[AlwaysInline]
def square(x : Int32) : Int32
  x * x
end

@[NoInline]
def rarely_used
end

@[Link("m")]
lib LibM
  fun cos(x : Float64) : Float64
end

@[Packed]
struct Header
  @tag : UInt8
  @size : UInt32
end
  • @[Deprecated] makes the compiler print a warning whenever the method is called.
  • @[AlwaysInline] and @[NoInline] give the optimizer a hint.
  • @[Link] tells the linker which C library to use for a lib binding.
  • @[Packed] removes padding from a struct for binary layouts.
  • @[Extern], @[Raises], @[ThreadLocal] and @[Flags] (for enums) also exist.

@[Flags] is a nice example: it turns an enum into a bit set.

CRYSTAL
@[Flags]
enum Permission
  Read
  Write
  Execute
end

mode = Permission::Read | Permission::Write
mode.write?                  # true
mode.execute?                # false
mode.to_s                    # "Read | Write"
Ruby Ruby stand-in: bit flags like @[Flags]

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.

Your own annotations

You declare an annotation type with annotation and read it with a macro. This lets you tag fields and let a macro treat them differently:

CRYSTAL
annotation Secret
end

class Account
  def initialize(@name : String, @password : String, @balance : Int32)
  end

  @[Secret]
  @password : String
end

class Account
  def to_log : String
    String.build do |io|
      {% for ivar in @type.instance_vars %}
        {% if ivar.annotation(Secret) %}
          io << {{ivar.name.stringify}} << "=*** "
        {% else %}
          io << {{ivar.name.stringify}} << "=" << @{{ivar.name.id}} << " "
        {% end %}
      {% end %}
    end
  end
end

Account.new("ada", "hunter2", 100).to_log
# "name=ada password=*** balance=100 "

Annotations can carry data: @[Column(name: "user_id", primary: true)], and the macro reads ivar.annotation(Column)[:name]. This is the technique behind @[JSON::Field(key: "id")] and ORM libraries.

Ruby Ruby stand-in: a field registry

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.

Compile-time flags

The compiler defines flags from the target and the options you pass. Test them in a macro with flag?:

CRYSTAL
{% if flag?(:linux) %}
  puts "Running on Linux"
{% elsif flag?(:darwin) %}
  puts "Running on macOS"
{% elsif flag?(:win32) %}
  puts "Running on Windows"
{% end %}

{% if flag?(:release) %}
  def log(msg); end
{% else %}
  def log(msg)
    STDERR.puts "[debug] #{msg}"
  end
{% end %}

Flags you can rely on: :linux, :darwin, :win32, :unix, :x86_64, :aarch64, :release (set by crystal build --release), :debug, :preview_mt (multithreading) and any custom flag you add with crystal build -Dmy_flag. Because the else branch is simply not compiled, a release build has no logging code at all.

You can also query the host environment at compile time:

CRYSTAL
VERSION = {{ `git describe --tags 2>/dev/null || echo dev`.stringify.chomp }}
BUILD_TIME = {{ system("date -u +%FT%TZ").stringify }}
API_URL = {{ env("API_URL") || "http://localhost:3000" }}

A backtick command inside {{ }} runs a shell command while compiling and pastes its output as a string. env("NAME") reads an environment variable of the compiling machine. Never paste secrets this way: they end up inside the binary.

Ruby Ruby stand-in: choose code by a flag

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.

run: compile-time computation

{{ run("file.cr") }} compiles and executes another Crystal program at compile time and pastes what it prints. It is used to embed generated tables, such as a lookup table of sine values, directly in the binary. Macro code can also compute with numbers and arrays: {{ [1, 2, 3].map { |n| n * 2 } }} produces the literal [2, 4, 6] in your code.

CRYSTAL
POWERS = {{ (0..5).map { |n| 2 ** n } }}   # [1, 2, 4, 8, 16, 32]

Compile-time computation is limited to what the macro interpreter can do, and it slows compilation, so keep it for small tables.

flowchart TD
  A["crystal build app.cr -Drelease"] --> B["Flags: linux, release, ..."]
  B --> C["Macros choose branches with flag?"]
  C --> D["Only the chosen code is compiled"]
  D --> E["Smaller, faster binary"]

Flags let one source file produce different programs for different targets.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @[Deprecated("Use x")] do?

    The annotation is only a marker: the compiler warns about each use.
  2. 2. How do you test whether the program is compiled for Linux?

    flag?(:linux) is a macro-time check, so the other branches are never compiled.
  3. 3. What does the @[Flags] annotation on an enum give you?

    Members become powers of two, can be combined with | and print as Read | Write.
  4. 4. Why should you not paste env("API_KEY") into a constant at compile time?

    Compile-time values are literals in the executable; anyone with the binary can read them.

Summary

  • Annotations like @[Deprecated], @[AlwaysInline], @[Packed] and @[Flags] attach meaning to code.
  • Declare your own with annotation Name; end and read them in macros with .annotation(Name).
  • flag? selects code by platform or build option; the unused branch is not compiled.
  • Backticks, system, env and run work at compile time; avoid embedding secrets.

Next: Fibers and spawn