Metaprogramming - the process of using code to write code - is a core feature of Elixir. You can easily extend the language and dynamically change the code. Despite knowing the first rule of metaprogramming - "Don't use metaprogramming" - every Elixir developer should have an idea what it is.
This talk will introduce the audience to the main metaprogramming concepts of Elixir. You will know about Elixir abstract syntax tree, 'quoting', macros and compile-time hooks. I'll demonstrate how this stuff works using simple examples as well as cases from popular packages.
First Kyiv Elixir Meetup, June 23
2. Hello!
I am Anton Mishchuk from Lviv
▧ Ruby Dev at Matic (and we are hiring)
▧ Fan of Elixir programming language
▧ ESpec creator & maintainer
▧ GitHub: antonmi
2
3. Elixir is Erlang with pretty syntax
and metaprogramming!
What is Elixir?
3
4. ▧ Elixir AST
▧ Quote and unquote
▧ Macroses
▧ DSL
▧ Introspection
What will be about
4
13. ▧ The first element is an atom identifying
the operation or another tuple in the same
representation
▧ The second element is a keyword list
containing metadata, like numbers and
contexts
▧ The third element is either a list of
arguments for the function call or an
atom. When this element is an atom, it
means the tuple represents a variable
Elixir AST - 3 element tuple
13
14. Elixir AST string representation
‘Macro.to_string’ converts the given
expression to a binary
14
16. Elixir AST. Unquoting
Unquoting is a mechanism to inject code
chunks into quoted expressions.
i.e. inject one AST fragment into another
Let’s try an example:
16
19. Magic functions - Macros
▧ Macro (which stands for "macroinstruction")
is a programmable pattern which translates
a certain sequence of input into a preset
sequence of output
▧ Macros receive the input AST and must
produce the output AST
▧ The compiler will then simply replace the
macro call with the AST returned from that
macro
▧ Works only at compile time
19
20. ▧ ‘defmodule’, ‘defmacro’, ‘def’, defstruct
▧ ‘require’, ‘import’, ‘use’
▧ ‘If’, ‘unless’, ‘cond’
▧ etc, etc
Macros are everywhere
87% of Elixir code written on Elixir
20
32. OMG! How to handle all the stuff?
▧ What function/macro I can use in
current scope?
▧ Where does this function/macro come
from?
32
33. Elixir introspection
▧ __ENV__ : Returns a Macro.ENV struct
containing current environment
information
▧ __MODULE__ : Returns the current
module name as an atom
▧ __DIR__ : Returns the current directory
▧ __CALLER__ : Returns the caller’s
environment information as a Macro.
ENV struct
33