How to typespec guards in a human friendly way?

Background

I am a fan of dialyzer and friends (looking at Gradient) and I try to have sepcs in my code as much as I can. To this end, I am playing with guards and I want my guard definitions to also have a typespec:

defmodule AuctionHouse.Shared.ExtraGuards do
  @moduledoc """
  Contains additional guards to use in functions.
  """

  defguard is_pos_integer(value) when is_integer(value) and value > 0
end

Problem

So, now that I have this simple guard, I want a spec for it. However, dyalizer’s suggestion doesn’t strike me as exactly human readable.

@spec is_pos_integer(any) ::
          {:__block__ | {:., [], [:andalso | :erlang, ...]}, [],
           [{:= | {any, any, any}, list, [...]}, ...]}
defguard is_pos_integer(value) when is_integer(value) and value > 0

I believe this is likely defined as a function that takes any as an argument but the return type is very difficult for me to understand. I assume it means it creates erlang code, like a macro, but I can’t make sense of it.

Questions

  • What does the return type mean?
  • Is there a way to make this more human readable? If so, how?
1 Like

Corresponding tweet for this thread:

Share link for this tweet.

1 Like

Solution

What’s happening here is that defguard receives code and returns code (to be more specific, it both receives a AST representation of code and then returns that AST modified). As as consequence, this means that the correct typespec would be this:

@spec is_pos_integer(Macro.t()) :: Macro.t()

Which many people in the community defend is not very useful.
I agree with this consensus, so the next best option is to add a @doc to the guard to clearly document it, and is what I suggest as well.

Sources:

1 Like