Context and macro hygiene
Since macros are about injecting code, special care must be taken for the context, of both the caller and the context of the macro. The injected code of the macro cannot safely assume that certain variables will be available for it to consume. For example, let's look at a macro definition that attempts to access some variables of the caller context:
defmodule ContextInfo do defmacro grab_caller_context do quote do IO.puts x end end end
Load up this module in iex
:
iex(1)> c "context.exs" [ContextInfo] iex(2)> import ContextInfo nil iex(3)> x = 42 42 iex(4)> grab_caller_context ** (CompileError) iex:4: undefined function x/0 expanding macro: ContextInfo.grab_caller_context/0 iex:4: (file)
After importing and binding a variable, invoking the macro yields a compiler error, as we would expect, because the macro cannot implicitly access the caller's context.
Similarly, the macro cannot safely inject code that changes the context or environment...