Using Dialyzer

Learn what Dialyzer is and how it works with typespecs.

Introduction

Dialyzer analyzes code that runs on the Erlang VM, looking for potential errors. To use it with Elixir, we have to compile our source into .beam files and make sure that the debug_info compiler option is set (which it is when running mix in the default development mode). Let’s see how to do that by creating a trivial project with two source files.

$ mix new simple
...
$ cd simple

Inside the project, let’s create a simple function. We haven’t implemented the body yet.

defmodule Simple do
  @type atom_list :: list(atom)
  @spec count_atoms(atom_list) :: non_neg_integer 
  def count_atoms(list) do
    # ...
  end 
end

Let’s run Dialyzer on our code. To make life simple, we’ll use the dialyxir library to add a dialyzer task to mix:

defp deps do 
 [
   { :dialyxir, "~> 0.5", only: [:dev], runtime: false } 
 ]
end

Next, we fetch the library and build our project:

$ mix deps.get
$ mix compile

Now we’re ready to analyze our code. However, the first time we do this, dialyzer needs to construct a massive data structure containing all the types and APIs in both Erlang and Elixir. This lets it check not just our code but also that our code is interacting correctly with the rest of the world. Building this data structure is slow; expect it to take 10 to 20 minutes! But once done, it won’t be repeated.

Get hands-on with 1200+ tech skills courses.