SlideShare a Scribd company logo
1 of 37
Download to read offline
Intro to Elixir
metaprogramming
First Kyiv Elixir meetup, June 23, 2016
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
Elixir is Erlang with pretty syntax
and metaprogramming!
What is Elixir?
3
▧ Elixir AST
▧ Quote and unquote
▧ Macroses
▧ DSL
▧ Introspection
What will be about
4
Why metaprogramming
▧ Extending language
▧ Boilerplate removing
▧ Creating DSL
5
Ecto.Schema
Elixir metaprogramming in the wild
Source code
6
Phoenix.Router
Elixir metaprogramming in the wild
Source code
7
ESpec.Let
Elixir metaprogramming in the wild
Source code
8
Initial code parsing
Elixir code
Initial AST
Expansion
Expanded AST
Byte-code generation
Byte-code
Compilation process
Magic is here!
9
Compile-time metaprogramming
▧ Code will not be redefined
▧ Static code analysis still works
▧ No performance penalty
10
Elixir AST. Quoting
‘quote’ macro gets the representation
of any expression.
11
Elixir AST. Quoting
12
▧ 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
Elixir AST string representation
‘Macro.to_string’ converts the given
expression to a binary
14
Elixir AST evaluation
‘Code.eval_string’ and ‘Code.eval_quoted’
15
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
Elixir AST. Unquoting
Trying to evaluate ‘final_expr’
I want to build AST which adds 1 + 2
17
Elixir AST. Unquoting
‘unquote’ helps to inject AST fragment
18
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
▧ ‘defmodule’, ‘defmacro’, ‘def’, defstruct
▧ ‘require’, ‘import’, ‘use’
▧ ‘If’, ‘unless’, ‘cond’
▧ etc, etc
Macros are everywhere
87% of Elixir code written on Elixir
20
Macros. Example
Calculator
21
Macros. Example
The result is expect. Nothing special.
Because we see completely compiled
code in the iex console
22
Macros. Example
Remember, macros receive quoted
expression and return them
Let’s do what compiler did step by step
23
Macros. Dynamic function definition example
24
Macros. ‘require’ and ‘import’
We should tell the compiler which module
should be compiled before we can use it.
25
‘use’ macro
The simplest way to bring external
functionality into the current lexical scope
26
‘Use’ for DSL
‘Use Ecto.Migration’
‘Ecto.Migration.__using__’
27
‘Use’ for DSL
‘use GenServer’
28
‘Use’ for DSL
‘GenServer.__using__’
29
‘Use’ for DSL
‘use ESpec’
30
‘Use’ for DSL
‘ESpec.__using__’
31
OMG! How to handle all the stuff?
▧ What function/macro I can use in
current scope?
▧ Where does this function/macro come
from?
32
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
Elixir introspection
‘__ENV__’ in iex
34
And don’t forget about help
‘h IEx.Helpers.b’
35
What is next?
36
With great power comes
great responsibility!
Thank you!
37

More Related Content

What's hot

Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
gerrell
 

What's hot (19)

Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
 
What's new in c# 5.0 net ponto
What's new in c# 5.0   net pontoWhat's new in c# 5.0   net ponto
What's new in c# 5.0 net ponto
 
Java 8
Java 8Java 8
Java 8
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
C++ Tail Recursion Using 64-bit variables
C++ Tail Recursion Using 64-bit variablesC++ Tail Recursion Using 64-bit variables
C++ Tail Recursion Using 64-bit variables
 
12 Jo P Dec 07
12 Jo P Dec 0712 Jo P Dec 07
12 Jo P Dec 07
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++
 
Lambda expressions java8 - yousry
Lambda expressions java8 - yousryLambda expressions java8 - yousry
Lambda expressions java8 - yousry
 
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
 
Functional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNextFunctional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNext
 
inline function
inline function inline function
inline function
 
Ecma script
Ecma scriptEcma script
Ecma script
 
My final requirement
My final requirementMy final requirement
My final requirement
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
 
Elm: Make Yourself A Happy Front-end Web Developer
Elm: Make Yourself A Happy Front-end Web DeveloperElm: Make Yourself A Happy Front-end Web Developer
Elm: Make Yourself A Happy Front-end Web Developer
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
 
MVVM with Kotlin: Making iOS and Android apps as similar as possible
MVVM with Kotlin: Making iOS and Android apps as similar as possibleMVVM with Kotlin: Making iOS and Android apps as similar as possible
MVVM with Kotlin: Making iOS and Android apps as similar as possible
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
 

Viewers also liked

Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
Elixir Club
 
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton MishchukFlowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Elixir Club
 

Viewers also liked (17)

Massive concurrent modifications in web app. How to manage and test.
Massive concurrent modifications in web app. How to manage and test.Massive concurrent modifications in web app. How to manage and test.
Massive concurrent modifications in web app. How to manage and test.
 
Asynchronous Ruby
Asynchronous RubyAsynchronous Ruby
Asynchronous Ruby
 
Espec - Elixir bdd
Espec  - Elixir bddEspec  - Elixir bdd
Espec - Elixir bdd
 
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
 
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton MishchukFlowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
 
Phoenix: Inflame the Web - Alex Troush
Phoenix: Inflame the Web - Alex TroushPhoenix: Inflame the Web - Alex Troush
Phoenix: Inflame the Web - Alex Troush
 
GenStage and Flow - Jose Valim
GenStage and Flow - Jose Valim GenStage and Flow - Jose Valim
GenStage and Flow - Jose Valim
 
Distributed system in Elixir
Distributed system in ElixirDistributed system in Elixir
Distributed system in Elixir
 
Gluecon keynote
Gluecon keynoteGluecon keynote
Gluecon keynote
 
Bottleneck analysis - Devopsdays Silicon Valley 2013
Bottleneck analysis - Devopsdays Silicon Valley 2013Bottleneck analysis - Devopsdays Silicon Valley 2013
Bottleneck analysis - Devopsdays Silicon Valley 2013
 
CMG2013 Workshop: Netflix Cloud Native, Capacity, Performance and Cost Optimi...
CMG2013 Workshop: Netflix Cloud Native, Capacity, Performance and Cost Optimi...CMG2013 Workshop: Netflix Cloud Native, Capacity, Performance and Cost Optimi...
CMG2013 Workshop: Netflix Cloud Native, Capacity, Performance and Cost Optimi...
 
Cassandra Performance and Scalability on AWS
Cassandra Performance and Scalability on AWSCassandra Performance and Scalability on AWS
Cassandra Performance and Scalability on AWS
 
Elixir intro
Elixir introElixir intro
Elixir intro
 
Netflix Architecture Tutorial at Gluecon
Netflix Architecture Tutorial at GlueconNetflix Architecture Tutorial at Gluecon
Netflix Architecture Tutorial at Gluecon
 
Flowcon (added to for CMG) Keynote talk on how Speed Wins and how Netflix is ...
Flowcon (added to for CMG) Keynote talk on how Speed Wins and how Netflix is ...Flowcon (added to for CMG) Keynote talk on how Speed Wins and how Netflix is ...
Flowcon (added to for CMG) Keynote talk on how Speed Wins and how Netflix is ...
 
Yow Conference Dec 2013 Netflix Workshop Slides with Notes
Yow Conference Dec 2013 Netflix Workshop Slides with NotesYow Conference Dec 2013 Netflix Workshop Slides with Notes
Yow Conference Dec 2013 Netflix Workshop Slides with Notes
 
Microservices Workshop All Topics Deck 2016
Microservices Workshop All Topics Deck 2016Microservices Workshop All Topics Deck 2016
Microservices Workshop All Topics Deck 2016
 

Similar to Intro to elixir metaprogramming

In-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCDIn-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCD
Stop Coding
 

Similar to Intro to elixir metaprogramming (20)

Elixir metaprogramming
Elixir metaprogrammingElixir metaprogramming
Elixir metaprogramming
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
 
Eclipse meets e4
Eclipse meets e4Eclipse meets e4
Eclipse meets e4
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
 
java theory and coding topic power point presentation.pptx
java theory and coding topic power point presentation.pptxjava theory and coding topic power point presentation.pptx
java theory and coding topic power point presentation.pptx
 
In-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCDIn-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCD
 
Creating a Fibonacci Generator in Assembly - by Willem van Ketwich
Creating a Fibonacci Generator in Assembly - by Willem van KetwichCreating a Fibonacci Generator in Assembly - by Willem van Ketwich
Creating a Fibonacci Generator in Assembly - by Willem van Ketwich
 
Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)
 
Kernel Recipes 2018 - 10 years of automated evolution in the Linux kernel - J...
Kernel Recipes 2018 - 10 years of automated evolution in the Linux kernel - J...Kernel Recipes 2018 - 10 years of automated evolution in the Linux kernel - J...
Kernel Recipes 2018 - 10 years of automated evolution in the Linux kernel - J...
 
Learning to Spot and Refactor Inconsistent Method Names
Learning to Spot and Refactor Inconsistent Method NamesLearning to Spot and Refactor Inconsistent Method Names
Learning to Spot and Refactor Inconsistent Method Names
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
64-bit Loki
64-bit Loki64-bit Loki
64-bit Loki
 
12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine
 
Auto Generating Code Demo via ASTs
Auto Generating Code Demo via ASTsAuto Generating Code Demo via ASTs
Auto Generating Code Demo via ASTs
 
What's a macro?: Learning by Examples
What's a macro?: Learning by ExamplesWhat's a macro?: Learning by Examples
What's a macro?: Learning by Examples
 
Acceleo Code Generation
Acceleo Code GenerationAcceleo Code Generation
Acceleo Code Generation
 
LANGUAGE TRANSLATOR
LANGUAGE TRANSLATORLANGUAGE TRANSLATOR
LANGUAGE TRANSLATOR
 
Bytecode manipulation with Javassist for fun and profit
Bytecode manipulation with Javassist for fun and profitBytecode manipulation with Javassist for fun and profit
Bytecode manipulation with Javassist for fun and profit
 

Recently uploaded

Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 bAsymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Sérgio Sacani
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
The Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptxThe Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptx
seri bangash
 
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
Scintica Instrumentation
 
Module for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learningModule for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learning
levieagacer
 
POGONATUM : morphology, anatomy, reproduction etc.
POGONATUM : morphology, anatomy, reproduction etc.POGONATUM : morphology, anatomy, reproduction etc.
POGONATUM : morphology, anatomy, reproduction etc.
Silpa
 

Recently uploaded (20)

Velocity and Acceleration PowerPoint.ppt
Velocity and Acceleration PowerPoint.pptVelocity and Acceleration PowerPoint.ppt
Velocity and Acceleration PowerPoint.ppt
 
COMPUTING ANTI-DERIVATIVES (Integration by SUBSTITUTION)
COMPUTING ANTI-DERIVATIVES(Integration by SUBSTITUTION)COMPUTING ANTI-DERIVATIVES(Integration by SUBSTITUTION)
COMPUTING ANTI-DERIVATIVES (Integration by SUBSTITUTION)
 
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 bAsymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
 
Clean In Place(CIP).pptx .
Clean In Place(CIP).pptx                 .Clean In Place(CIP).pptx                 .
Clean In Place(CIP).pptx .
 
GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)
 
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS ESCORT SERVICE In Bhiwan...
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS  ESCORT SERVICE In Bhiwan...Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS  ESCORT SERVICE In Bhiwan...
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS ESCORT SERVICE In Bhiwan...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Site Acceptance Test .
Site Acceptance Test                    .Site Acceptance Test                    .
Site Acceptance Test .
 
pumpkin fruit fly, water melon fruit fly, cucumber fruit fly
pumpkin fruit fly, water melon fruit fly, cucumber fruit flypumpkin fruit fly, water melon fruit fly, cucumber fruit fly
pumpkin fruit fly, water melon fruit fly, cucumber fruit fly
 
300003-World Science Day For Peace And Development.pptx
300003-World Science Day For Peace And Development.pptx300003-World Science Day For Peace And Development.pptx
300003-World Science Day For Peace And Development.pptx
 
Grade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its FunctionsGrade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its Functions
 
PSYCHOSOCIAL NEEDS. in nursing II sem pptx
PSYCHOSOCIAL NEEDS. in nursing II sem pptxPSYCHOSOCIAL NEEDS. in nursing II sem pptx
PSYCHOSOCIAL NEEDS. in nursing II sem pptx
 
Call Girls Ahmedabad +917728919243 call me Independent Escort Service
Call Girls Ahmedabad +917728919243 call me Independent Escort ServiceCall Girls Ahmedabad +917728919243 call me Independent Escort Service
Call Girls Ahmedabad +917728919243 call me Independent Escort Service
 
The Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptxThe Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptx
 
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
 
Module for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learningModule for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learning
 
FAIRSpectra - Enabling the FAIRification of Analytical Science
FAIRSpectra - Enabling the FAIRification of Analytical ScienceFAIRSpectra - Enabling the FAIRification of Analytical Science
FAIRSpectra - Enabling the FAIRification of Analytical Science
 
GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)
 
POGONATUM : morphology, anatomy, reproduction etc.
POGONATUM : morphology, anatomy, reproduction etc.POGONATUM : morphology, anatomy, reproduction etc.
POGONATUM : morphology, anatomy, reproduction etc.
 
Climate Change Impacts on Terrestrial and Aquatic Ecosystems.pptx
Climate Change Impacts on Terrestrial and Aquatic Ecosystems.pptxClimate Change Impacts on Terrestrial and Aquatic Ecosystems.pptx
Climate Change Impacts on Terrestrial and Aquatic Ecosystems.pptx
 

Intro to elixir metaprogramming