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

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
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
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New

We're in Beta

About us Mission Statement