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

RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
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
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
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 131117 1222
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
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

We're in Beta

About us Mission Statement