shahryarjb

shahryarjb

Create @behaviour and @type with macro

Hi, I have Elixir macro that I want to use it as @behaviour in my project. but there is a problem I can not be able to use a @type as a parameters of a macro.

My macro

defmodule MishkaPub.ActivityStream.Validator do
  defmacro __using__(opts) do
    quote(bind_quoted: [opts: opts]) do
      type = Keyword.get(opts, :type)
      module = Keyword.get(opts, :module)

      @type t :: unquote(type)
      @type action() :: :build | :validate

      @callback build(t()) :: {:ok, action(), t()} | {:error, action(), any()}
      @callback build(t(), list(String.t())) ::
                  {:ok, action(), t()} | {:error, action(), any()}

      @callback validate(t()) :: {:ok, action(), t()} | {:error, action(), any()}
      @callback validate(t(), list(String.t())) ::
                  {:ok, action(), t()} | {:error, action(), any()}

      @behaviour unquote(module)
    end
  end
end

And the Elixir file I want to use it

defmodule MishkaPub.ActivityStream.Type.Object do
  alias MishkaPub.ActivityStream.Validator

  @type tt :: %__MODULE__{
          id: String.t(),
          type: String.t(),
          name: String.t(),
          replies: list(String.t())
        }

  defstruct [
    :id,
    :type,
    ..
  ]

  use Validator, module: __MODULE__, type: tt()

  def build(%__MODULE__{} = params) do
    {:ok, :build, Map.merge(%__MODULE__{}, params)}
  rescue
    _e ->
      {:ok, :build, :unexpected}
  end

  ...
end

but I have this error

** (CompileError) lib/activity_stream/validator.ex:3: undefined function type/0 (there is no such import)

How can fix this error?


Another problem if this is fixed! I have 2 duplicated types. (tt(), t()) but I just want to have one type which should be t()

Thank you in advance :rose: :pray:

Marked As Solved

christhekeele

christhekeele

The folk in this thread are providing solid advice to improve your approach, which I would recommend following and would resolve your issues.

However, to address the specific cause of this error the way you are doing things today, for learning about Elixir metaprogramming:

You have an unquoting issue in your macro. Take just the lines here:

You have a variable, opts, inside of your macro’s context, containing a keyword list. To make that available to your generated code, you have to unquote it—which you have implicitly via bind_quoted, no problem!

That means that the variable you next introduce, type, is only available in the generated code. So when you proceed to unquote(type), you are getting the equivalent of variable type does not exists—since it does not exist inside the macro’s context.

You have 3 options:

  1. Unquote opts and extract the type exclusively in the generated code context:

    defmacro(__using__(opts) do
      quote(bind_quoted: [opts: opts]) do
        type = Keyword.get(opts, :type)
        @type t :: type
      end
    end
    
  2. Extract the type exclusively in the macro context and unquote in the generate code:

    defmacro(__using__(opts) do
      type = Keyword.fetch!(opts, :type)
      quote do
        @type t :: unquote(type)
      end
    end
    
    
  3. Extract the type exclusively in the macro context and bind_quoted:

    defmacro(__using__(opts) do
      type = Keyword.fetch!(opts, :type)
      quote [bind_quoted: [type: type]] do
        @type t :: type
      end
    end
    

I believe the 3rd option is popular, although personally I tend to prefer the second, as I like to be explicit about my opts munging and unquote-ing.

Also Liked

hst337

hst337

  1. Please note that @callback attribute is set in the module which defines the interface. While @behaviour is set in the module which implements the interface.

  2. So you’ll actually need something like this

defmodule MishkaPub.ActivityStream.Validator do
  @type action() :: :build | :validate
  @type t :: any() # Or what kind of argument Validator generally wants

  @callback build(t()) :: {:ok, action(), t()} | {:error, action(), any()}
  @callback build(t(), list(String.t())) ::
            {:ok, action(), t()} | {:error, action(), any()}

  @callback validate(t()) :: {:ok, action(), t()} | {:error, action(), any()}
  @callback validate(t(), list(String.t())) ::
            {:ok, action(), t()} | {:error, action(), any()}
end

defmodule MishkaPub.ActivityStream.Type.Object do
  alias MishkaPub.ActivityStream.Validator

  @type t :: %__MODULE__{
          id: String.t(),
          type: String.t(),
          name: String.t(),
          replies: list(String.t())
        }

  defstruct [
    :id,
    :type,
    ..
  ]

  @behaviour Validator

  @impl true
  @spec build(t()) :: {:ok, Validator.action(), t()} | {:error, Validator.action(), any()}
  def build(%__MODULE__{} = params) do
    {:ok, :build, Map.merge(%__MODULE__{}, params)}
  rescue
    _e ->
      {:ok, :build, :unexpected}
  end

  ...
end
al2o3cr

al2o3cr

+1 to what @hst337 said, the behaviour and the implementation need to be separate modules.

Some other thoughts:

  • passing __MODULE__ isn’t required, the module that said use is available as __MODULE__ inside the quote block.

    defmodule MacroDemo do
      defmacro __using__(opts) do
        IO.inspect(__MODULE__, label: "outside")
    
        quote(bind_quoted: [opts: opts]) do
          IO.inspect(__MODULE__, label: "inside")
        end
      end
    end
    
    defmodule Foo do
      use MacroDemo
    end
    
    # prints
    outside: MacroDemo
    inside: Foo
    
  • apart from failing to compile, the only thing that type in Validator does is define t. What about just expecting the user to write @type t :: etc etc etc outside of the use and then using it in the @callbacks?

shahryarjb

shahryarjb

Thank you it is very good to know how to do.

Where Next?

Popular in Questions 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
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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
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
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
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
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
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
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
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
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
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement