janp

janp

Keyword.put in macro results in AST instead of keyword list

I am currently stuck in implementing a macro :thinking: Here’s the code I currently have (without unnecessary code):

defmacro request(opts \\ [], do: expr) do
  quote
    typedstruct unquote(opts) do
      unquote(expr)
    end
  end
end

That macro works fine, but I would like to add some options that cannot be overwritten, so I tried this:

defmacro request(opts \\ [], do: expr) do
  quote
    typedstruct Keyword.put(unquote(opts), :module, Req) do
      unquote(expr)
    end
  end
end

Sadly, this fails with a compilation error:

** (FunctionClauseError) no function clause matching in Access.get/3    
    
    The following arguments were given to Access.get/3:
    
        # 1
        {{:., [line: 6], [{:__aliases__, [line: 6, counter: {ChangeUser, 8}, alias: false], [:Keyword]}, :put]}, [line: 6], [[], :module, {:__aliases__, [line: 6, counter: {ChangeUser, 8}, alias: false], [:Req]}]}
    
        # 2
        :enforce
    
        # 3
        nil
    
    Attempted function clauses (showing 6 out of 6):
    
        def get(%module{} = container, key, default)
        def get(map, key, default) when is_map(map)
        def get(list, key, default) when is_list(list) and is_atom(key)
        def get(list, key, _default) when is_list(list) and is_integer(key)
        def get(list, key, _default) when is_list(list)
        def get(nil, _key, default)

That error occurs, because an AST is passed to the typedstruct-macro instead of a keyword list and typed_struct then tries to call opts[:enforce] (tuples do not implement the Access-behaviour).

Is there anyone who can help me figure out what is happening and how to solve this issue? :slight_smile:

Marked As Solved

sodapopcan

sodapopcan

Ah yes, that changes things!

So first thing, the way you’re doing use TypedStruct isn’t going to work. You actually want ChangeUser (or whatever module is useing Operation) to be using it. Perhaps you’ve left out some code, but basically you want something like this:

defmodule Operation do
  defmacro __using__(_) do
    quote do
      use TypedStruct
      import Operation
    end
  end

  defmacro request(opts \\ [], do: expr) do
    opts = Keyword.put(opts, :module, Module.concat([__CALLER__.module, Req]))
  
    quote do
      typedstruct unquote(opts) do
        unquote(expr)
      end
    end
  end
end

Also Liked

sodapopcan

sodapopcan

Move it outside of the quote:

defmacro request(opts \\ [], do: expr) do
  opts = Keyword.put(opts, :module, Req)

  quote do
    typedstruct unquote(opts) do
      unquote(expr)
    end
  end
end

Otherwise, as you pointed out, the code you end up with will literally be the same as typing out:

typedstruct Keyword.put([some: :user, provided: :opts], :module, Req) do
  # unquoted_expr
end

The reason you don’t have to do anything special with opts in the macro body is that lists are one of the constructs that return themselves when quoted.

EDIT: Just re-reading my answer after getting pinged about it:

For good measure you should call Macro.escape on the value you put in the keyword list:

opts = Keyword.put(opts, :module, Macro.escape(Req))

It won’t make any difference in this case (Macro.escape(Req) #=> Req) but if you put other values (like maps, for example) as value, you’ll need to do this so that you get the proper ast representation to be later unquoted.

janp

janp

Great :partying_face: It works!

A few minutes ago, I found some code using __CALLER__, but I was unsure about it. Now I know it better.

Thank you!

sodapopcan

sodapopcan

No prob!

You often don’t need to use __CALLER__ but in this case typedstruct is a macro itself, so of course its arguments get quoted so you need to grab the caller’s module name outside the quote block. But most of the time you can just use __MODULE__ inside the quote block:

defmodule Bar do
  defmarco __using__(_) do
    quote do
      dbg(__MODULE__)
    end
  end
end

defmodule Foo do
  use Bar
end

dbg here will be Foo.

Last Post!

sodapopcan

sodapopcan

No prob!

You often don’t need to use __CALLER__ but in this case typedstruct is a macro itself, so of course its arguments get quoted so you need to grab the caller’s module name outside the quote block. But most of the time you can just use __MODULE__ inside the quote block:

defmodule Bar do
  defmarco __using__(_) do
    quote do
      dbg(__MODULE__)
    end
  end
end

defmodule Foo do
  use Bar
end

dbg here will be Foo.

Where Next?

Popular in Questions Top

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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
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
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
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
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
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New

We're in Beta

About us Mission Statement