Code Injection and the Caller’s Context

Learn how macros are used for code injection.

Macros don’t just generate code for the caller, they inject it.

The place where code is injected is called a context. A context is the scope of the caller’s bindings, imports, and aliases. To the caller of a macro, the context is precious. It holds the view of the world, and by immutability, we don’t expect our variables, imports, and aliases to change underneath us.

Elixir macros strike an excellent balance to safeguard our context while allowing explicit access where necessary. Let’s see how to inject code safely and the available tools to reach into the caller’s context when necessary.

Get hands-on with 1200+ tech skills courses.