lok0613

lok0613

Weird dialyzer warning: the pattern can never match the type

This dialyzer warning just happened randomly once I apply defmacro in my module.
I got 2 modules, the issues only appear in StoreFront module.

defmodule Store do

  defmacro __using__(_opt) do
    quote do
      import unquote(__MODULE__)
      @before_compile unquote(__MODULE__)
    end
  end

  defmacro fruits(do: block) do
    fn_name = String.to_atom("run_fruits")
    quote do
      @fn_names unquote(fn_name)
      def unquote(fn_name)(), do: unquote(block)
    end
  end

  defmacro apple(clause) do
    quote do
      if unquote(clause) in [true, :ok] do
        :ok
      else
        :failure
      end
    end
  end

  defmacro __before_compile__(_env) do
    quote do
      def run() do
        apply(__MODULE__, :run_fruits, [])
        |> IO.inspect
      end
    end
  end

end
defmodule StoreFront do
  use Store

  fruits do
    apple true # emit warning
    apple :ok # emit warning
    apple false # emit warning
  end

  apple true # no warning

end

The complete dialyzer warning messages:

The pattern 
          'false' can never match the type 
          'true'ElixirLS Dialyzer
The test 
          'ok' =:= 
          'true' can never evaluate to 'true'

Most Liked

Qqwy

Qqwy

TypeCheck Core Team

To check what code you exactly end up with, you might want to use the following incancation by the way:

    f = './_build/dev/lib/your_library_name/ebin/Elixir.YourModuleName.beam'
    result = :beam_lib.chunks(f,[:abstract_code])
    {:ok,{_,[{:abstract_code,{_,ac}}]}} = result
    IO.puts :erl_prettypr.format(:erl_syntax.form_list(ac))

(where your_library_name and YourModuleName are replaced by the mix project and module name you’re working on, respectively)

This will show you the core Erlang that ends up being generated after all macros (both your macros and the built-in ones) are expanded. This is actually what Dialyzer is looking at.

(If someone knows a more concise or clean way to look at the core erlang of a module, I’d love to know, by he way!)

NobbZ

NobbZ

Writing functions which do roughly what your macro does, is not writing the code the way it had been generated by the macro call.

So it becomes this:

defmodule StoreFront do
  use Store  # its okay to leave this as is, as it is not mentioned in the warnings

  @fn_names :run_fruits
  def run_fruits() do
    case true === true or true === :ok do # apple true
      x in [false, nil] -> :failure
      _ -> :ok
    end

    case :ok === true or :ok === :ok do # apple :ok
      x in [false, nil] -> :failure
      _ -> :ok
    end

    case false === true or false === :ok do
      x in [false, nil] -> :failure
      _ -> :ok
    end
  end

  # apple true # no need to expand this, dialyzer won't see it anyway, as it does not expand into a function
end

And dialyzer is wondering why you say or true === :ok, when you already know that true === true statically.
It asks why you have a x in [false, nil] clause when you already know in advance, that the condition will always be true.

mudasobwa

mudasobwa

Creator of Cure

The dialyzer has no clue about elixir macros, it sees the compiled code anyway, meaning it sees somewhat like

case :dev do
  :test -> ...
  ...
end

One should not leak testing abstractions to the code in any case. The proper solution would be to introduce a behaviour and mock it in tests.

defmodule ReqIdGen do
  @callback generate :: binary()
end

defmodule My do
  @behaviour ReqIdGen

  @impl ReqIdGen
  def generate, do: Ecto.UUID.generate()

  @generator Application.compile_env(:my_app, :req_id_gen, __MODULE__)

  defp generate_request_id(generator \\ @generator) do
    generator.generate()
  end
end

And mock it in tests.

NobbZ

NobbZ

“Expand” your macros, as well as elixirs stdlib macros until only defmodule and def are left in your StoreFront module. Then you will roughly see what dialyzer sees. That will help to understand the warnings.

bobkocisko

bobkocisko

Sorry to bump an old topic, but wow, this comment is gold!! It helped me figure out a mind-bending dialyzer issue related to nesting a case statement inside the else of a with. Thanks @Qqwy :+1: I am going to keep this in my toolbelt from now to help understand Elixir’s dark corners and edge cases.

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

We're in Beta

About us Mission Statement