zoten

zoten

Credo and specs for macro-generated functions

Hi everyone!
I’m searching for a hint for a problem I cannot understand if it is in my code or a third party misbehaviour.
I’m currently working on a project linted by wonderful credo where I have enabled Credo.Check.Readability.Specs to enforce specs on public functions.

Now, I’m creating with a macro a bunch of functions with the same /arity but different matches based on a couple of parameters, e.g.

# example.exs
defmodule SpecMe do
  defmacro __using__(attrs) do
    for attr <- attrs do
      quote do
        def unquote(attr)(attr = unquote(attr)), do: Atom.to_string(attr)
        def unquote(attr)(attr), do: attr |> Atom.to_string() |> String.reverse()
      end
    end
  end
end

# usage
defmodule UseSpec do
  use SpecMe, [:ab, :bc, :cd]
end

UseSpec.ab(:ab) |> IO.inspect()
UseSpec.ab(:bc) |> IO.inspect()

UseSpec.bc(:bc) |> IO.inspect()
UseSpec.bc(:cd) |> IO.inspect()

You can run the example to see it compiles and work with elixir example.exs
You can trigger the check on a credo-enabled project (configured with the check enabled) with mix credo example.exs
You should see a Functions should have a @spec type specification
( code also available via gist, but you’ll still need a credo-enabled project to run mix against it )

Things I tried:

  • putting @spec unquote(attr)(...) wrapping a generic definition e.g.
@spec unquote(attr)(...) :: ...
def unquote(attr)(params)
  • putting @spec unquote(attr)(...) before the first def
  • since my practical example is slightly more complex, putting it in a different quote/do block before the cycle, since I know the name before it, and returning the corresponding ast

Please note that also the name is dynamic, and more clauses are defined for the same name. If I refactor everything to have a static name and put a normal spec on it, it does not complain.
I’m therefore stuck in not understanding a couple of things:

  • it seems to me I’m failing in setting @spec. I know @ is a macro that wraps Module.get_attribute but since it is in fact setting spec during compilation I imagine it has a special treatment, but I’m probably doing things wrong while trying to set it
  • I don’t fully understand why credo is pointing directly at my code inside __using__ and not against the real module using the macro. It seems it is really pointing to those def , but I may be missing a lot of things that happen during compilation

Anyone has any hint regarding this issue? Thanks in advance!

L

Marked As Solved

zoten

zoten

For whoever it may concern, I ended up writing directly on a similar issue in credo’s repo and it seems it is a current (and maybe not solvable :smiling_face_with_tear:) limitation in credo being a static analyzer

Thanks for the hints and kindness, as always <3

Also Liked

LostKobrakai

LostKobrakai

Instead of trying to build the spec dynamically I’d probably build the AST of the spec in the macro body and unquote the complete AST as the value for @spec.

You can use quote to figure out how the AST of a spec needs to look like:

iex(3)> quote do: @spec some_function(map()) :: term()
{:@, [context: Elixir, import: Kernel],
 [
   {:spec, [context: Elixir],
    [{:"::", [], [{:some_function, [], [{:map, [], []}]}, {:term, [], []}]}]}
 ]}

So your macro could look something like this:

defmacro __using__(attrs) do
  for attr <- attrs do
    spec_params = …
    spec_return = …
    spec = {:"::", [], [{attr, [], spec_params}, spec_return]}
    quote do
      @spec unquote(spec)
      def unquote(attr)(attr = unquote(attr)), do: Atom.to_string(attr)
      def unquote(attr)(attr), do: attr |> Atom.to_string() |> String.reverse()
    end
  end
end

Where Next?

Popular in Questions Top

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
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
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
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
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New

We're in Beta

About us Mission Statement