Skip to content

Commit 7ca67e9

Browse files
committed
Clarify unquote(kv)() docs, closes #14422
1 parent c00e6fc commit 7ca67e9

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

Diff for: lib/elixir/lib/kernel/special_forms.ex

+12-7
Original file line numberDiff line numberDiff line change
@@ -1242,8 +1242,11 @@ defmodule Kernel.SpecialForms do
12421242
end)
12431243
12441244
In the example above, we have generated the functions `foo/0` and
1245-
`bar/0` dynamically. Now, imagine that we want to convert this
1246-
functionality into a macro:
1245+
`bar/0` dynamically. Note the parentheses in `unquote(k)()` are important,
1246+
otherwise we would try to define a function as `def :foo` instead of
1247+
`def foo()`.
1248+
1249+
Now, imagine that we want to convert this functionality into a macro:
12471250
12481251
defmacro defkv(kv) do
12491252
Enum.map(kv, fn {k, v} ->
@@ -1268,8 +1271,9 @@ defmodule Kernel.SpecialForms do
12681271
code fails.
12691272
12701273
This is actually a common pitfall when developing macros. We are
1271-
assuming a particular shape in the macro. We can work around it
1272-
by unquoting the variable inside the quoted expression:
1274+
assuming a particular shape at compilation time, within the macro
1275+
implementation. One may try to work around it by unquoting the
1276+
variable inside the quoted expression:
12731277
12741278
defmacro defkv(kv) do
12751279
quote do
@@ -1281,9 +1285,10 @@ defmodule Kernel.SpecialForms do
12811285
12821286
If you try to run our new macro, you will notice it won't
12831287
even compile, complaining that the variables `k` and `v`
1284-
do not exist. This is because of the ambiguity: `unquote(k)`
1285-
can either be an unquote fragment, as previously, or a regular
1286-
unquote as in `unquote(kv)`.
1288+
do not exist. This is because the two `unquote`s in the call
1289+
above are meant to run at distinct moments: `unquote(kv)`
1290+
applies to the immediate quote, `unquote(k)` is an unquote
1291+
fragment.
12871292
12881293
One solution to this problem is to disable unquoting in the
12891294
macro, however, doing that would make it impossible to inject the

0 commit comments

Comments
 (0)