A quick syntax reference for metaprogramming, compile-time AST introspection, and macro authoring in Elixir.
🔗 Related: Elixir Language Cheat Sheet
Special Forms & Pseudo-Variables
Core metaprogramming constructs defined in Kernel.SpecialForms:
__DIR__ # Absolute path to directory of the current file as a string
__MODULE__ # Current module name atom (e.g. MyModule)
__ENV__ # Current compilation environment struct (Macro.Env)
__CALLER__ # Environment struct of the macro caller
Inspecting Execution Environment (__ENV__)
# Inspect fields inside compilation environment
Map.keys(__ENV__)
# => [:__struct__, :aliases, :context, :context_modules, :export_vars, :file,
# :function, :functions, :lexical_tracker, :line, :macro_aliases, :macros,
# :module, :requires, :vars]
# Inspect definitions in caller module
__CALLER__.module |> Module.definitions_in() |> IO.inspect()
Quotes, AST & Dynamic Dispatch
# Generate abstract syntax tree (AST)
quote do: 1 + 2
# => {:+, [context: Elixir, import: Kernel], [1, 2]}
# Unquote inside quotes
number = 10
quote do: 1 + unquote(number)
# Dynamic function invocation
apply(Enum, :reverse, [[1, 2, 3]])
# => [3, 2, 1]