a-maze-d

a-maze-d

Hi,

I’m trying to create some syntactic sugar through a macro. The basic function should look like the following:

f :name do
  data.something + 10
end

The macro will transform the body to an anonymous function. Yes the somewhat undefined data is intentional, it will be used to capture the argument that will be passed to the function.

I didn’t manage to create a macro that resolves the data correctly. I found now a solution that works by using the anonymous function of the capture operator. The downside is that I need to capture the argument through &1.something which does not look nice :frowning: (note the real code looks more complicated since it uses a compile hook, but the following is working)

defmodule F do
  defmacro f(name, options, do: block) do
    func = quote do
      &(unquote(block))
    end
    quote do
      register(unquote(name), unquote(options), unquote(func))
    end
  end

  def register(name, options, func) do
    result = func.(%{something: 10})
    IO.puts("#{inspect name}, #{inspect options}, #{inspect func}, #{inspect result}")
  end
end

defmodule G do
  def run() do
    import F
    F.f :name, [] do
      &1.something-10
    end
  end
end

And call it with:

import G
G.run

If I convert the capturing operator to an anonymous function it should work just fine. The doc does state:

In other words, &(&1 * 2) is equivalent to fn x -> x * 2 end.

But, whenI change my macro to look like this:

defmacro f(name, options, do: block) do
    func = quote do
      fn(data) -> unquote(block) end
    end
    quote do
      register(unquote(name), unquote(options), unquote(func))
    end
  end

I get the error:

warning: variable "data" does not exist and is being expanded to "data()", please use parentheses to remove the ambiguity or change the variable name
  lib/f.ex:21: G.run/0


== Compilation error in file lib/f.ex ==
** (CompileError) lib/f.ex:21: undefined function data/0 (expected G to define such a function or for it to be imported, but none are available)

Why is this? Can someone please help me to understand this?

Showing Posts 1 to 2

christhekeele

christhekeele

What you’re struggling with is called macro hygiene.

This macro would indeed expand this call:

f(:name, [option: :option]) do
  data.something + 10
end

into this code:

register(:name, [option: :option], fn(data) -> data.something + 10 end)

However, the compiler recognizes that the variable data has two different providences, and treats them as different variables; it sees things more like this:

register(:name, [option: :option], fn(data1) -> data2.something + 10 end)
#                                     ▲         ▲
# your macro's `data` ────────────────┘         │
# your user code's `data` ──────────────────────┘

Macro hygiene allows macro authors to not worry about their generated code stepping on other variables in scope, but requires more work when injecting user-provided code with your own variables.

You should be able to follow the guide linked above to decorate your macro’s data with a call to var! to escape hygiene.

Alternatively, and perhaps more idiomatically, you could allow the user code to dictate the variable name by having your macro expect clauses, similar to a case statement. Untested code snippet, that I’ve gotten to work with macros before; IIRC you have to build the AST for the fn by hand instead of using quote/unquote as there is no analog to unquote_splicing that works for clauses:

defmacro f(name, options, do: clauses) do
    func_ast = {:fn, [], clauses}
    quote do
      register(unquote(name), unquote(options), unquote(func_ast))
    end
  end
end

Then in user-code:

f(:name, [option: :option]) do
  data -> data.something + 10
end

This has the added benefit of letting users pattern-match and provide multiple clauses to handle different cases.

At this point though, you may well want them to just pass in a function–depending on your use-case.

a-maze-d

a-maze-d OP

Thanks for your swift help. It is indeed what you are stating. Thus the use of Kernel.var! solves that problem.

The reason why I didn’t manage to resolve it myself, because I didn’t realize the difference between Macro.var and Kernel.var!.

Thanks again for your help.

Ps: Your suggestion to allow the user to select the binding, is definitely something I wanted to allow, in a later version.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews