Eiji

Eiji

Is evaluating a quoted expressions of nested DSL calls also considered as a bad practice?

Warning: Calling this function inside a macro is considered bad practice as it will attempt to evaluate runtime values at compile time. Macro arguments are typically transformed by unquoting them into the returned quoted expressions (instead of evaluated).

Source: Code.eval_quoted/3

I’m not sure if I understand it fully. Is it only about “runtime values” (like variables)? Does it apply also to do: block last argument for nested DSL?

For simplicity let’s assume that you start with a simplest DSL, but with 1 extra nested DSL. You prefer do … end way because it’s more flexible, so for example you can use a for … do … end special form to generate nested DSL calls based on some input. Consider below example:

defmodule MyLib do
  defmacro first_case_root(do: block) do
    quote do
      unquote(block)
    end
  end

  defmacro second_case_root(do: block) do
    Code.eval_quoted(block, [], __CALLER__)
  end

  defmacro nested do
    nil
  end
end

defmodule MyApp do
  import MyLib

  first_case_root do
    nested()
  end

  second_case_root do
    nested()
  end
end

In first case the nested macro is called when unquoting a result of the parent macro. For simplicity let’s say it’s called between first_case_root and second_case_root. This way looks a bit complicated as to store accumulated arguments we have to work in inner macro (inside quote) and/or on @before_compile.

However I found something obvious … I can just evaluate quoted block (as shown in second case). This way the nested DSL is evaluated inside a parent macro which in fact flattens nested DSL calls. This allows to work on the parent macro logic inside … a parent macro.

Now let’s go back to the quote. I understand why AST of stuff like variables should not be evaluated especially because in many macros it’s completely not important. However in this case “flattening” nested DSL calls allows to simplify code a lot:

  1. Even in simplest example it’s 1 LOC vs 3 LOC where one line have extra indention.

  2. There is no need to work on module attributes to store compile-time data. Instead we can use many if not all in-memory solutions. The simplest one is most probably Process.put/2

  3. Depending on use case the nested DSL macros does not have to return any quoted expressions and the root DSL macro returns a minimal quoted expression without storing and manipulating data

{nil, []} = Code.eval_quoted(block_with_nested_dsl_calls, [], __CALLER__)

Both macro code and the code returned by macro are much simpler. Simply imagine that a root macro with dozens or even more nested macro calls returns a minimal code which you print like tap(& &1 |> Macro.to_string() |> IO.puts()) and the output contains only desired generated code (generated functions) without lots of other lines you have to scroll in console.

Does described case is also seen as a bad practice? Or as written above the warning was intended only for “runtime values” like variables? If this is bad idea could you please explain why? Are there any side-effects of doing so?

Marked As Solved

D4no0

D4no0

I mean that is just a generic warning, you can do whatever you want in your macros.

I personally would say that using Code.eval_quoted/3 inside of your macros is an imperative way of doing things and composing the AST is the declarative way, as you are composing a data structure that is later evaluated.

I don’t have experience doing this kind of shenanigans, however I would suspect you running into trouble with evaluation contexts sooner or later when you are doing this kind of intermediary evaluations of code.

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
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
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
gazoon
I want to know absolute current module path. In python i could do that: os.path.abspath(__file__) Does elixir have anything similar?
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
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
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
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
Tee
can someone please explain to me how Enum.reduce works with maps
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
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New

We're in Beta

About us Mission Statement