Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 37 ยท Getting Started

How Crystal Compiles and Infers Types

Understand how the Crystal compiler infers types across your whole program, creates one specialised copy of a method per type, and why this gives both short code and speed.

Crystal looks like a scripting language, yet it compiles to native code. The trick is in what the compiler does between your source file and the executable. Understanding this model once explains most of what is surprising about Crystal: why you can omit types, why some errors are long, why compile times grow, and why programs are fast.

Crystal listings are read-only on this site. The Ruby stand-ins below simulate what the compiler does by hand, so you can see the idea. Real Crystal does this automatically and before the program runs.

The pipeline

flowchart LR
  A["Source .cr"] --> B["Parser: syntax tree"]
  B --> C["Type inference"]
  C --> D["Macro expansion"]
  D --> E["LLVM IR"]
  E --> F["Native executable"]

The compiler turns text into a tree, works out every type, expands macros, then lets LLVM produce machine code.

  1. The parser reads your file and builds a tree of the program.
  2. Type inference works out the type of every variable and expression.
  3. Macros run at compile time and generate more code (see the macros chapter).
  4. The result is handed to LLVM, a mature optimising backend that emits machine code.

Whole-program type inference

In many statically typed languages you write the types, and the compiler checks them. In Crystal you mostly do not write them: the compiler discovers them by following the program from the entry point.

CRYSTAL
x = 10          # Int32
y = x + 5       # Int32, because Int32 + Int32 gives Int32
z = y.to_s      # String

No annotation was needed anywhere. Literals have known types (10 is Int32, "a" is String, 1.5 is Float64), and every method has a return type that the compiler can work out. Method calls flow types forward through the program.

Methods are specialised per type

The most important idea: a method without type annotations is a template. Each time you call it with a new combination of argument types, the compiler creates a separate, fully typed copy.

CRYSTAL
def twice(x)
  x + x
end

twice(2)        # compiles twice(Int32)  -> Int32
twice(2.5)      # compiles twice(Float64) -> Float64
twice("ab")     # compiles twice(String) -> String

After compilation, the executable contains three versions of twice, each with the exact machine instructions for its type. There is no run-time lookup of "what is x?" and no boxing of numbers. That is why Crystal code is fast even though you never wrote a type.

The next Ruby stand-in creates one copy of a method per argument class on purpose, to make this visible. It builds a table of "specialisations" the way the compiler would.

Ruby Stand-in: specialising a method per type

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.

Ruby has one twice that checks the class on every call. Crystal has several twice methods, each already knowing its type. Note that Ruby's single Integer class stands where Crystal has Int8, Int32, Int64 and others.

Why errors can be long

Because inference follows the call chain, a type error might surface deep inside a library method that was called with a value you passed in from far away. The message includes the path the compiler took:

TEXT
Error: undefined method 'length' for Int32

If you see an error that points at library code, run the build with --error-trace to see the whole chain, and find the call from your own code. Adding a type restriction on your own method (next lessons) makes errors appear in the right place:

CRYSTAL
def shout(text : String)
  text.upcase + "!"
end

shout(5)   # Error: expected argument #1 to 'shout' to be String, not Int32

The error now names shout and the argument. Annotating the public entry points of your code is a good habit: the compiler still infers everything inside.

Type annotations: where they are required

You may leave types out most of the time, but a few places need them:

  • Instance variables in classes need a type the compiler can know, either through an annotation or through assignments in initialize.
  • Empty collections need a type: [] of Int32, {} of String => Int32.
  • C bindings and some abstract definitions need explicit types.
CRYSTAL
numbers = [] of Int32    # empty array of Int32
numbers << 1
numbers << 2
puts numbers.sum         # 3

Without of Int32 the compiler cannot know what an empty array may hold.

Compile time versus run time

Anything the compiler can decide, it decides before your program starts. Everything else happens when it runs. A useful mental split:

At compile time At run time
Which method will be called The actual values
The type of each variable Branches that depend on input
Macro expansion File and network input
Missing methods, wrong argument counts Division by zero, index errors

A program that compiles has no "undefined method" errors and no forgotten nil checks. It can still have logic bugs and run-time errors such as an out-of-range index, so tests remain important.

The cost: compile time and binary size

Specialising every method for every type and optimising through LLVM is real work. For large programs a release build can take from tens of seconds to minutes. Practical tips:

  • Use crystal run or a debug build while you develop.
  • Keep release builds for CI and deployment.
  • Avoid pulling huge libraries into small tools.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Crystal usually know the type of a local variable?

    Whole-program type inference discovers types from literals and method return types.
  2. 2. What happens to an unannotated method called with an Int32 and with a String?

    Methods are specialised per combination of argument types, which is why there is no run-time dispatch cost.
  3. 3. Why does numbers = [] need of Int32 in Crystal?

    An empty literal gives no clue about the element type, so you provide it.
  4. 4. Which flag helps you trace a confusing type error back to your own call?

    --error-trace prints the chain of calls the compiler followed.

Summary

  • The compiler parses, infers types for the whole program, expands macros and hands LLVM the result.
  • Untyped methods are templates; each distinct argument-type combination gets its own optimised copy.
  • Add type restrictions to public methods so errors point at your code.
  • Empty collections and instance variables need explicit or inferable types.
  • Compile-time checking removes whole classes of errors but costs compile time.

Next: Variables and Constants