zachdaniel

zachdaniel

Creator of Ash

Dynamically generate typespecs from module attribute list

I was hoping I could get something like this working:

defmodule FooRegistry do
  @foos [
    FirstFoo,
    SecondFoo,
    ThirdFoo
  ]
  
  @foos_by_another_name Enum.into(foos, %{}, fn foo -> {foo.another_name(), foo} end)

  @type foo [Enum.map(@foos, fn foo -> foo.t end)]

  @spec list_foos() :: [foo]
  def list_foos() do
    @foos
  end

  @spec foo_from_another_name(atom) :: foo | nil
  def foo_from_another_name(name) do
    Map.get(@foos_by_another_name, name)
  end
end

I’m not really worried about the exact syntax, but how might I go about dynamically generating a type like this?

Thanks!

Most Liked

evadne

evadne

For posterity:

defmodule Test do
  @keys ~w(a b c)a
  @type key :: unquote(Enum.reduce(@keys, &{:|, [], [&1, &2]}))
end
21
Post #5
axelson

axelson

Scenic Core Team

This is a great snippet! Here’s a function form of this:

defmodule TypeUtils do
  # https://forum.elixirforum.net/t/dynamically-generate-typespecs-from-module-attribute-list/7078/5
  def list_to_typespec(list) when is_list(list) do
    Enum.reduce(list, &{:|, [], [&1, &2]})
  end
end

Usage example:

  @statuses [:not_started, :completed]
  @type status :: unquote(TypeUtils.list_to_typespec(@statuses))
Eiji

Eiji

In both @spec and @type you need to wrap everything in unquote call. Without that instead of calling function/macro the AST of such call would be stored:

iex> quote do
iex>   union_type(@keys)
iex> end
{:union_type, [],
  [{:@, [context: Elixir, import: Kernel], [{:keys, [context: Elixir], Elixir}]}]}

__using__/1 macro is as same as any other macro. use MyModule works like require MyModule + MyModule.__using__([]).

You can also write a macro like this one:

defmodule UnionType do
  defmacro union_type({:"::", _, [{name, _, _}, data]}) do
    quote bind_quoted: [data: data, name: name] do
      @type unquote({name, [], Elixir}) :: unquote(UnionType.union_type_ast(data))
    end
  end

  def union_type_ast([item]), do: item
  def union_type_ast([head | tail]), do: {:|, [], [head, union_type_ast(tail)]}
end

defmodule Example do
  import UnionType
  @keys ~w(a b c)a
  union_type key :: @keys
end

However for this you need to add this option:

[
  # …
  locals_without_parens: [union_type: 1]
]

to .formatter.exs, because otherwise it would format your code to:

defmodule Example do
  import UnionType
  @keys ~w(a b c)a
  union_type(key :: @keys)
end
axelson

axelson

Scenic Core Team

We’ve also now extracted this into a little library:

One of the main reasons to extract it was to avoid extra compile-time dependencies.

Eiji

Eiji

@zachdaniel: You need to write helper module with some macros and then call them to generate ast for special module attributes like @type.
For @type you need to return ast in format:

# root element in case @foos count greater than 2:
{
  :|,
  [],
  children
}
# root element in case @foos count is equal to 2:
{
  :|,
  [],
  [FirstFoo.t, SecondFoo.t]
}
# root element in case @foos count is equal to 1:
FirstFoo.t
# root element in case @foos count is equal to 0:
raise error

Where for children you have same rules as for root element, so for 3 foos:

{
  :|,
  [],
  [
    FirstFoo.t,
    {
      :|,
      [],
      [
        SecondFoo.t,
        ThirdFoo.t
      ]
    }
  ]
}

and this ast for you will look like:
FirstFoo.t | SecondFoo.t | ThirdFoo.t
What you need is to write recursive function that retruns Elixir AST in Tuple notation.

Where Next?

Popular in Questions Top

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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
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
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
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
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
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
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

Other popular topics Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
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
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
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
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
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement