budgie

budgie

Defining nested macros for a DSL? How can you share state?

I’m trying to build a macro for edge definitions in a graph. How can I access parameters from the outer macro inside the inner macro?

  1. The direction macro must define a module with the block passed into schema.
  2. The schema macro must implicitly be able to access the “accesses” string passed into the top-level edge macro.

How can I define complex multi-level macros like this for building DSLs but have the state be shared like I described?

This is the edge module:

defmodule App.Edge.Accesses do
  import App.Edge.EdgeType

  alias App.Users.User
  alias App.Invitations.Invitation
  alias App.Tenants.Tenant

  edge "accesses" do
    direction from: User, to: Invitation
    direction from: Invitation, to: Tenant

    schema do
    end
  end
end

This is the EdgeType module with all of the macros:

defmodule Quota.Edge.EdgeType do
  defmacro edge(collection_name, do: do_block) do
    quote do
    end
  end

  defmacro direction(from: from, to: to) do
    quote do
    end
  end

  defmacro schema(do: do_block) do
    quote do
    end
  end
end

Most Liked

zachdaniel

zachdaniel

Creator of Ash

In spark, this DSL would look something like this:

defmodule App.Edge.EdgeType.Dsl do
  @schema ... (left out for brevity)

  @direction %Spark.Dsl.Entity{
    name: :direction,
    schema: [
      from: [type: :module, required: true],
      to: [type: :module, required: true]
    ]
  }
  
  defmodule Edge do
    defstruct [:name, :directions]
  end

  @edge %Spark.Dsl.Entity{
    name: :edge,
    target: Edge,
    schema: [
      name: [
        type: :atom,
        required: true
      ],
      entities: [
        directions: [@direction],
        schema: [@schema]
      ],
     singleton_entity_keys: [:schema]
    ]
  }

  @edges %Spark.Dsl.Section{
    name: :edges,
    top_level?: true,
    entities: [
      @edge
    ]
  }
  
  use Spark.Dsl.Extension, sections: [@edge]
end

defmodule App.Edge.EdgeType do
  use Spark.Dsl,
    default_extensions: [extensions: [App.Edge.EdgeType,Dsl]]
end

defmodule EdgeType.Info do
  use Spark.InfoGenerator, extension: App.Edge.EdgeType.Dsl, sections: [:edge]
end

With the above (I left some stuff out, and probably got a few things wrong since I typed this all in a forum window and didn’t test it), the syntax you’ve laid out should work as it is.

defmodule App.Edge.Accesses do
  use App.Edge.EdgeType # but you'd need to `use` instead of `import`

  alias App.Users.User
  alias App.Invitations.Invitation
  alias App.Tenants.Tenant

  edge "accesses" do
    direction from: User, to: Invitation
    direction from: Invitation, to: Tenant

    schema do
    end
  end
end
zachallaun

zachallaun

A somewhat common option often used for “contexts” like this is to use module attributes, where each macro would push their context into the attribute prior to injecting the body block and then pop it out after. Each inner macro can access the current context through that attribute.

I’m on my phone so can’t easily provide a more complete example, but basically the idea is to inject a call to Module.put_attribute at the beginning of the quote block, and then

Here’s an example (untested):

@edge_context :"#{__MODULE__}.edge"

defmacro edge(collection, do: quoted) do
  quote do
    prev = Module.get_attribute(__MODULE__, unquote(@edge_context), [])

    Module.put_attribute(__MODULE__, unquote(@edge_context), [unquote(collection) | prev])

    result = unquote(quoted)

    Module.put_attribute(__MODULE__, unquote(@edge_context), prev)

    result
  end
end

defmacro schema(do: quoted) do
  context = Module.get_attribute(__CALLER__.module, @edge_context)
  
  ...
end
zimt28

zimt28

Where Next?

Popular in Questions 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
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
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
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
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
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

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
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
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
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
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
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
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

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement